"""JARVIS COMMAND CENTER — the in-memory orchestration console.

This is the human-facing layer that sits on top of the existing orchestrator:
seven named agents, a six-stage opportunity pipeline, a dependency-aware task
queue, an approval gate that cannot spend money on its own, an append-only
debrief feed, a SENTINEL trust ledger and a searchable memory store.

Design rules, enforced here rather than promised in the UI:

* **No spend without a human.** Every costed action is an APPROVAL row with a
  numeric ``cost``. ``state["spend"]["approved"]`` is the sum of rows a human
  approved; nothing else can move it.
* **No uncited claim.** Opportunities carry an evidence list. Verification
  refuses to advance a claim whose confidence is below the evidence floor.
* **Deterministic.** No RNG, no clock in any decision, no model call, no
  network. The same starting state plus the same clicks gives the same result.
* **In memory only.** State lives in this process. Reset rebuilds the seed.

The module exposes ``CommandCenter`` (state machine) and
``command_center_blueprint(center)`` (JSON API). The page itself is
``templates/command.html``; every style and script is inline there.
"""

from __future__ import annotations

import copy
import threading
from datetime import datetime, timedelta, timezone

from flask import Blueprint, jsonify, request

# ---------------------------------------------------------------------------
# vocabulary
# ---------------------------------------------------------------------------

STAGE_KEYS = ["find", "verify", "build", "run", "measure", "decide"]
STAGE_LABELS = {
    "find": "FIND",
    "verify": "VERIFY",
    "build": "BUILD",
    "run": "RUN",
    "measure": "MEASURE",
    "decide": "KEEP / KILL",
}
STAGE_BLURB = {
    "find": "Signal → candidate",
    "verify": "Evidence floor",
    "build": "Bot scaffold",
    "run": "Email first",
    "measure": "28-day read",
    "decide": "Keep or kill",
}
NEXT_STAGE = {"find": "verify", "verify": "build", "build": "run",
              "run": "measure", "measure": "decide", "decide": None}
PREV_STAGE = {"verify": "find", "build": "verify", "run": "build",
              "measure": "run", "decide": "measure"}

AUTONOMY_LEVELS = [
    {"value": 0, "label": "Suggest", "detail": "Agents propose. Nothing runs until you dispatch it."},
    {"value": 1, "label": "Act with approval", "detail": "Agents execute free work; every cost is gated."},
    {"value": 2, "label": "Act then report", "detail": "Agents execute free work and debrief after. Still $0."},
]

REGIONS = ["Rochester", "Buffalo", "Syracuse", "Albany", "NYC", "Long Island"]

#: The evidence floor: below this score a claim cannot leave VERIFY.
CONFIDENCE_FLOOR = 60

#: A decided item is KEPT only at or above this confidence with a booked meeting.
KEEP_THRESHOLD = 70

#: Hard cap on concurrent pending approvals (keeps the gate readable).
MAX_PENDING_APPROVALS = 6

RULE_SET = {
    "version": "1.4.2",
    "bumped_at": "2026-11-14",
    "min_sources": 2,
    "min_primary": 1,
    "confidence_floor": CONFIDENCE_FLOOR,
    "keep_threshold": KEEP_THRESHOLD,
    "sample_claims": 128,
    "true_positive": 51,
    "false_positive": 7,
    "false_negative": 18,
    "precision": 0.879,
    "recall": 0.739,
    "holdout": {"name": "holdout B", "n": 64, "precision": 0.844, "recall": 0.688},
    "previous": {"version": "1.4.1", "precision": 0.861, "recall": 0.702},
    "policy": ("A rule change requires a version bump AND a holdout improvement of at least "
               "+2.0 points recall with no more than -1.0 point precision. Changes are held "
               "for 24 hours and replayed against holdout B before they reach the live loop."),
}


# ---------------------------------------------------------------------------
# seed data
# ---------------------------------------------------------------------------

AGENT_DEFS = [
    {"id": "atlas", "name": "ATLAS", "mono": "AT", "role": "Planner",
     "mission": "Decomposes goals into ordered task graphs.",
     "color": "#5eead4"},
    {"id": "oracle", "name": "ORACLE", "mono": "OR", "role": "Analyst",
     "mission": "Research, evidence gathering, confidence scoring.",
     "color": "#60a5fa"},
    {"id": "forge", "name": "FORGE", "mono": "FG", "role": "Builder",
     "mission": "Bot factory. Generates specs and scaffolds.",
     "color": "#f59e0b"},
    {"id": "echo", "name": "ECHO", "mono": "EC", "role": "Operator",
     "mission": "Outreach execution. Email first, phone escalation.",
     "color": "#a78bfa"},
    {"id": "prism", "name": "PRISM", "mono": "PR", "role": "Designer",
     "mission": "UX, copy, brand, landing pages.",
     "color": "#f472b6"},
    {"id": "sentinel", "name": "SENTINEL", "mono": "SN", "role": "Auditor",
     "mission": "Checks claims against sources. Blocks unverified work.",
     "color": "#f87171"},
    {"id": "archive", "name": "ARCHIVE", "mono": "AR", "role": "Memory",
     "mission": "Stores decisions, rule versions, retrieval keys.",
     "color": "#94a3b8"},
]


def _opportunity(**kw) -> dict:
    base = {
        "stage": "find",
        "verdict": None,
        "confidence": 50,
        "value": 0,
        "metrics": {"sent": 0, "replies": 0, "meetings": 0},
        "entered_cycle": 1,
        "verify_failure": False,
        "decided_cycle": None,
    }
    base.update(kw)
    return base


OPPORTUNITY_SEED = [
    _opportunity(
        id="OPP-01",
        business_type="After-hours HVAC dispatch",
        bot="HeatLine — no-heat intake that triages to the on-call tech",
        bot_slug="heatline",
        city="Rochester", region="Rochester",
        problem=("Fourteen independent HVAC firms in Monroe County route after-hours calls to "
                 "voicemail until 7am. A no-heat call at 11pm becomes a competitor's job by "
                 "morning, and the owner never sees the missed call."),
        evidence=[
            {"source": "NYS DOS Division of Licensing — HVAC contractor extract (2026-10-02)",
             "quote": "212 licensed HVAC contractors list Monroe County as their primary place of business.",
             "url": "data.ny.gov", "kind": "primary"},
            {"source": "Rochester HVAC operators forum — after-hours thread (2026-09-18)",
             "quote": "9 of 14 owner replies say after-hours calls go to voicemail until 7am.",
             "url": "local operator forum", "kind": "secondary"},
        ],
        confidence=82, value=2400, stage="find", entered_cycle=11,
        verify_focus="the NYS DOS license extract and the 9 owner replies",
        primary_source="NYS DOS license extract (2026-10-02)",
        stale_risk="the license extract is a snapshot; firms close without notifying DOS",
        next_source="Monroe County 311 heating-complaint volume for Nov–Feb",
        owner="ORACLE",
    ),
    _opportunity(
        id="OPP-02",
        business_type="Snow-plow instant quoting",
        bot="SnowQuote — address in, driveway area and price band out",
        bot_slug="snowquote",
        city="Buffalo", region="Buffalo",
        problem=("Erie County plow operators quote by phone and callback. After a lake-effect "
                 "event, the backlog runs three days while homeowners book whoever answers first."),
        evidence=[
            {"source": "Erie County parcel GIS (2026-08 release)",
             "quote": "98.6% of addressed parcels have a polygon; 1,412 rural parcels do not.",
             "url": "erie.gov GIS", "kind": "primary"},
            {"source": "NWS Buffalo — lake-effect advisory archive 2025-26",
             "quote": "14 lake-effect advisories through 2026-02-28; 4 exceeded 12 inches.",
             "url": "weather.gov/buf", "kind": "primary"},
        ],
        confidence=74, value=1800, stage="build", entered_cycle=9,
        verify_focus="Erie County parcel coverage and driveway-area error",
        primary_source="Erie County parcel GIS (2026-08)",
        stale_risk="rural parcels without polygons will quote blind",
        next_source="10 real operator quotes matched to parcel polygons",
        owner="FORGE",
    ),
    _opportunity(
        id="OPP-03",
        business_type="Grease-trap compliance reminders",
        bot="TrapWatch — permit expiry watcher with SMS reminders",
        bot_slug="trapwatch",
        city="Syracuse", region="Syracuse",
        problem=("Onondaga County food-service permits carry interceptor manifest deadlines that "
                 "nobody tracks. A missed manifest is a $450 median fine for a restaurant running "
                 "on a 4% margin."),
        evidence=[
            {"source": "Onondaga County open data — food service permits (2025-09-30 refresh)",
             "quote": "641 active permits; 78 have no interceptor manifest on file in 12 months.",
             "url": "onondagacounty.gov open data", "kind": "primary"},
            {"source": "Syracuse.com — restaurant compliance fines (2026-06-11)",
             "quote": "County issued 31 grease-related fines in 2025, median $450.",
             "url": "syracuse.com", "kind": "secondary"},
        ],
        confidence=68, value=1200, stage="verify", entered_cycle=11,
        verify_focus="permit freshness against the NYS DOH inspection feed",
        primary_source="Onondaga County open data (2025-09-30)",
        stale_risk="the table is six weeks stale and includes closed restaurants",
        next_source="NYS DOH restaurant inspection API, last 18 months",
        owner="ORACLE",
    ),
    _opportunity(
        id="OPP-04",
        business_type="Craft-brewery distributor finder",
        bot="BrewRoute — distributor-fit matcher for small breweries",
        bot_slug="brewroute",
        city="Albany", region="Albany",
        problem=("Capital Region breweries want out-of-state distribution but sell through "
                 "self-distribution and warm intros. The claim that '38 breweries need a "
                 "distributor' comes from one blog post with no primary data."),
        evidence=[
            {"source": "Capital Craft Beverage Trail member list (2026)",
             "quote": "38 member breweries; the list records taproom hours, not distribution.",
             "url": "capitalcraftbeverage.com", "kind": "secondary"},
            {"source": "Blog: 'Upstate craft beer distribution is broken' (2025-11)",
             "quote": "Asserts 'most' small breweries lack out-of-state distribution; cites no data.",
             "url": "industry blog", "kind": "secondary"},
        ],
        confidence=46, value=1600, stage="find", entered_cycle=12,
        verify_focus="NYSLA license roster and distributor filings",
        primary_source="none yet",
        stale_risk="the headline count may be right while the 'need' is inferred",
        next_source="NYSLA active license roster + distributor appointment filings",
        owner="ORACLE",
    ),
    _opportunity(
        id="OPP-05",
        business_type="Dental no-show recovery",
        bot="ChairFill — SMS confirmation with insurance pre-check",
        bot_slug="chairfill",
        city="Brooklyn", region="NYC",
        problem=("Five Brooklyn practices lose 21.8% of booked appointments to no-shows, worst on "
                 "Friday afternoons at 29.4%. Each empty chair is $180 of unrecoverable chair time."),
        evidence=[
            {"source": "NYC DOHMH dental clinic directory (2026-07)",
             "quote": "1,284 dental practices licensed in Kings County.",
             "url": "nyc.gov/health", "kind": "primary"},
            {"source": "Pilot PMS export, 5 clinics (2026-09-01 → 2026-10-30)",
             "quote": "No-show rate 21.8% across 3,412 appointments; Friday PM 29.4%.",
             "url": "practice management export", "kind": "primary"},
        ],
        confidence=88, value=6500, stage="decide", verdict="KEPT", entered_cycle=8,
        decided_cycle=12,
        metrics={"sent": 41, "replies": 17, "meetings": 6},
        verify_focus="the PMS export against clinic-level counts",
        primary_source="PMS export (3,412 appointments)",
        stale_risk="two practices changed front-desk staff mid-pilot",
        next_source="week-5 read on the two staff-changed clinics",
        owner="ARCHIVE",
    ),
    _opportunity(
        id="OPP-06",
        business_type="Per-diem nursing shift fill",
        bot="ShiftPing — credentialed shift broadcast with 15-minute claim window",
        bot_slug="shiftping",
        city="Nassau County", region="Long Island",
        problem=("Nassau per-diem agencies fill open shifts by group text. Credentials live in "
                 "spreadsheets, so coordinators re-verify the same 40 nurses every week and lose "
                 "shifts that a 15-minute broadcast would have covered."),
        evidence=[
            {"source": "NY DOH per-diem nursing agency registry (2026-10)",
             "quote": "31 licensed agencies in Nassau County; median reported shift-fill time 4.2 hours.",
             "url": "health.ny.gov", "kind": "primary"},
            {"source": "Staffing coordinator interviews (n=6, 2026-10)",
             "quote": "5 of 6 fill open shifts by group text; none use a scheduling system.",
             "url": "interview notes", "kind": "primary"},
        ],
        confidence=79, value=5200, stage="run", entered_cycle=11,
        metrics={"sent": 9, "replies": 2, "meetings": 1},
        verify_focus="agency licensure and coordinator claims",
        primary_source="NY DOH registry (2026-10)",
        stale_risk="registry lists agencies, not open shift volume",
        next_source="two weeks of shift logs from the two pilot agencies",
        owner="ECHO",
    ),
    _opportunity(
        id="OPP-07",
        business_type="Self-storage unit-size recommender",
        bot="UnitFit — inventory-aware size quiz before the gate code",
        bot_slug="unitfit",
        city="Rochester", region="Rochester",
        problem=("Eleven Monroe County facilities rent the wrong unit size, then downsize or vacate "
                 "inside 90 days. The manager eats the move cost and the review says 'they upsold me'."),
        evidence=[
            {"source": "NYSSA facility list — Monroe County (2026)",
             "quote": "11 facilities; 4 report waitlists for 10x10 units.",
             "url": "nyssa.org", "kind": "secondary"},
            {"source": "Operator call notes (2026-09-12)",
             "quote": "Two-site manager: 19% of rentals downsize or vacate within 90 days.",
             "url": "call notes", "kind": "secondary"},
        ],
        confidence=63, value=900, stage="measure", entered_cycle=10,
        metrics={"sent": 14, "replies": 3, "meetings": 1},
        verify_focus="the 19% churn claim against unit-mix exports",
        primary_source="none — both sources are secondary",
        stale_risk="churn is seasonal; a September sample skews toward student move-ins",
        next_source="12-month unit-mix export from two facilities",
        owner="ORACLE",
    ),
    _opportunity(
        id="OPP-08",
        business_type="Municipal bid alerts for MBE contractors",
        bot="BidScout — six-portal bid consolidator with MBE eligibility filter",
        bot_slug="bidscout",
        city="Buffalo", region="Buffalo",
        problem=("Erie County posts bids across six portals with no shared index. Certified minority "
                 "contractors find out about a $400k streets job after the pre-bid meeting has passed."),
        evidence=[
            {"source": "Erie County procurement portal (2026-Q3)",
             "quote": "214 open bids; 61% posted only on the county site, not mirrored to NYSCR.",
             "url": "erie.gov/procurement", "kind": "primary"},
            {"source": "Buffalo Niagara minority contractor directory (2026)",
             "quote": "147 certified MBE firms; 38 name 'finding bids' as their top growth barrier.",
             "url": "bnmca.org", "kind": "primary"},
        ],
        confidence=71, value=1500, stage="verify", entered_cycle=10,
        verify_focus="the 61% portal-gap count",
        primary_source="Erie County procurement portal (2026-Q3)",
        stale_risk="portal counts move weekly during budget season",
        next_source="a 30-day scrape diff across all six portals",
        owner="ORACLE",
    ),
    _opportunity(
        id="OPP-09",
        business_type="Veterinary after-hours triage",
        bot="VetTriage — symptom intake that routes to ER or morning slot",
        bot_slug="vettriage",
        city="Syracuse", region="Syracuse",
        problem=("Clinics hand after-hours calls to an answering service that cannot triage. "
                 "Non-urgent cases show up at the ER at 2am; urgent ones wait until morning."),
        evidence=[
            {"source": "AVMA membership counts by county (2025)",
             "quote": "44 veterinary clinics in Onondaga County.",
             "url": "avma.org", "kind": "primary"},
            {"source": "Clinic phone checks (n=4, 2026-10-21)",
             "quote": "3 of 4 route after-hours calls to an answering service; 1 declined to comment.",
             "url": "call log", "kind": "secondary"},
        ],
        confidence=57, value=1050, stage="find", entered_cycle=12,
        verify_focus="after-hours volume, not clinic count",
        primary_source="AVMA counts (2025)",
        stale_risk="triage advice may count as veterinary practice in New York",
        next_source="NYSED veterinary practice guidance + ER diversion logs",
        owner="ORACLE",
    ),
    _opportunity(
        id="OPP-10",
        business_type="Liquor-store reorder alerts",
        bot="ShelfSignal — par-level alerts from POS exports",
        bot_slug="shelfsignal",
        city="Albany", region="Albany",
        problem=("Independent liquor stores reorder from paper forms and distributor gut feel. "
                 "A missed Thursday order means an empty shelf through the weekend."),
        evidence=[
            {"source": "NYSLA active license roster (2026-10)",
             "quote": "96 liquor stores licensed in Albany County.",
             "url": "sla.ny.gov", "kind": "primary"},
            {"source": "Distributor rep interview (2026-09-30)",
             "quote": "Estimates 40% of independent stores still reorder on paper forms.",
             "url": "interview notes", "kind": "secondary"},
        ],
        confidence=66, value=750, stage="build", entered_cycle=11,
        verify_focus="the 40% paper-reorder estimate",
        primary_source="NYSLA license roster (2026-10)",
        stale_risk="one rep's estimate is not a market measurement",
        next_source="POS export sample from 3 stores",
        owner="FORGE",
    ),
]

BACKLOG = [
    _opportunity(
        id="OPP-11",
        business_type="Locksmith after-hours dispatch",
        bot="KeyRelay — lockout intake with ETA bands",
        bot_slug="keyrelay",
        city="Rochester", region="Rochester",
        problem=("Locksmiths lose lockout calls to national call centers that resell the lead. "
                 "The local operator pays $45 for a job they could have answered directly."),
        evidence=[
            {"source": "NYS DOS locksmith license extract (2026-10)",
             "quote": "84 licensed locksmith businesses in Monroe County.",
             "url": "dos.ny.gov", "kind": "primary"},
            {"source": "Google review sample, 12 Rochester locksmiths (2026-09)",
             "quote": "7 of 12 have reviews describing a 2+ hour wait after an after-hours call.",
             "url": "review sample", "kind": "secondary"},
        ],
        confidence=61, value=1100, entered_cycle=12, owner="ORACLE",
        verify_focus="whether wait complaints map to missed calls",
        primary_source="NYS DOS license extract (2026-10)",
        stale_risk="review complaints may reflect staffing, not intake",
        next_source="call 6 shops at 9pm and log answer times",
    ),
    _opportunity(
        id="OPP-12",
        business_type="CSA pickup-window coordination",
        bot="HarvestText — pickup window confirmation for farm shares",
        bot_slug="harvesttext",
        city="Canandaigua", region="Rochester",
        problem=("Finger Lakes CSAs lose shares to missed pickup windows. Members text the farmer, "
                 "the farmer is in a field, and the produce is compost by Saturday."),
        evidence=[
            {"source": "NOFA-NY farm directory (2026)",
             "quote": "63 CSA operations within 40 miles of Canandaigua.",
             "url": "nofany.org", "kind": "primary"},
            {"source": "Two CSA operator interviews (2026-08)",
             "quote": "Both report 8–12% of shares unclaimed in a wet week.",
             "url": "interview notes", "kind": "secondary"},
        ],
        confidence=64, value=650, entered_cycle=12, owner="ORACLE",
        verify_focus="unclaimed-share rates across more farms",
        primary_source="NOFA-NY directory (2026)",
        stale_risk="two farms is a sample of two",
        next_source="survey 15 CSAs on unclaimed shares",
    ),
    _opportunity(
        id="OPP-13",
        business_type="Med-spa booking and deposit capture",
        bot="GlowGate — booking with card-on-file deposit",
        bot_slug="glowgate",
        city="Garden City", region="Long Island",
        problem=("Med spas on Long Island take bookings by DM and lose 30% to no-shows because "
                 "no card is on file. Reception spends the morning re-confirming by text."),
        evidence=[
            {"source": "NYS DOH med-spa / aesthetic practice registrations (2026)",
             "quote": "118 registered aesthetic practices in Nassau County.",
             "url": "health.ny.gov", "kind": "primary"},
            {"source": "Front-desk shadowing, 2 spas (2026-10)",
             "quote": "Reception made 46 confirmation texts in one 4-hour shift.",
             "url": "observation log", "kind": "primary"},
        ],
        confidence=72, value=3400, entered_cycle=12, owner="ORACLE",
        verify_focus="no-show rate and card-on-file conversion",
        primary_source="practice registration + shadowing",
        stale_risk="deposit policy varies by practice; one flow will not fit all",
        next_source="no-show counts from 5 booking systems",
    ),
    _opportunity(
        id="OPP-14",
        business_type="Commercial janitorial bid alerts",
        bot="SweepBid — nightly janitorial RFP digest for Queens",
        bot_slug="sweepbid",
        city="Queens", region="NYC",
        problem=("Janitorial contractors bid blind on co-op and school RFPs scattered across "
                 "NYC agency sites. A 200-unit building contract closes in 72 hours."),
        evidence=[
            {"source": "NYC procurement public bid list (2026-Q3)",
             "quote": "1,412 active solicitations; 96 tagged janitorial or custodial.",
             "url": "nyc.gov/mocs", "kind": "primary"},
            {"source": "Contractor roundtable notes (2026-09)",
             "quote": "6 of 9 small janitorial firms say they check bid sites less than weekly.",
             "url": "roundtable notes", "kind": "secondary"},
        ],
        confidence=69, value=2800, entered_cycle=12, owner="ORACLE",
        verify_focus="bid volume a solo operator can actually service",
        primary_source="NYC bid list (2026-Q3)",
        stale_risk="96 open bids overstates winnable work by an order of magnitude",
        next_source="filter to contracts under $250k and within 3 boroughs",
    ),
    _opportunity(
        id="OPP-15",
        business_type="Youth sports facility rental",
        bot="CourtClock — recurring rental slots with auto-invoicing",
        bot_slug="courtclock",
        city="Saratoga Springs", region="Albany",
        problem=("Small gyms rent court time by phone and lose weekend blocks to no-shows who "
                 "never got an invoice. Owners chase $600 in unpaid slots every month."),
        evidence=[
            {"source": "Saratoga County youth sports club directory (2026)",
             "quote": "48 clubs; 31 list 'finding gym time' as an operating constraint.",
             "url": "county directory", "kind": "secondary"},
            {"source": "Two facility owner interviews (2026-08)",
             "quote": "Both report weekend no-shows above 15% with no deposit collected.",
             "url": "interview notes", "kind": "secondary"},
        ],
        confidence=65, value=950, entered_cycle=12, owner="ORACLE",
        verify_focus="whether no-shows come from booking or from payment friction",
        primary_source="none — secondary sources only",
        stale_risk="club directory may double-count travel teams",
        next_source="30 days of booking logs from one facility",
    ),
]

TASK_SEED = [
    {"id": "T-101", "title": "Verify Erie County parcel GIS coverage for snowquote",
     "assignee": "oracle", "status": "done", "deps": [], "opp": "OPP-02", "cycle": 9,
     "detail": "Confirm 98.6% parcel coverage and quantify the driveway-area error band."},
    {"id": "T-102", "title": "Scaffold snowquote v0.3 (address → quote band)",
     "assignee": "forge", "status": "doing", "deps": ["T-101"], "opp": "OPP-02", "cycle": 10,
     "detail": "Parcel lookup, driveway polygon estimate, deterministic price band."},
    {"id": "T-103", "title": "Price-check 10 real Buffalo plow quotes",
     "assignee": "oracle", "status": "todo", "deps": ["T-102"], "opp": "OPP-02", "cycle": 10,
     "detail": "Match operator quotes to parcels; fit error before shipping."},
    {"id": "T-104", "title": "Nassau shift-fill: draft 3-email sequence",
     "assignee": "echo", "status": "doing", "deps": [], "opp": "OPP-06", "cycle": 11,
     "detail": "Email first. Phone escalation after 72 hours, no opens required."},
    {"id": "T-105", "title": "Re-audit Albany '38 breweries' claim",
     "assignee": "sentinel", "status": "todo", "deps": [], "opp": "OPP-04", "cycle": 12,
     "detail": "Requires one primary source before BUILD. Currently zero."},
    {"id": "T-106", "title": "Brooklyn dental: week-4 no-show read",
     "assignee": "oracle", "status": "verify", "deps": [], "opp": "OPP-05", "cycle": 12,
     "detail": "Cohort split by staff change. 28-day window closes Friday."},
    {"id": "T-107", "title": "Archive KEEP decision + retrieval keys (dental)",
     "assignee": "archive", "status": "done", "deps": ["T-106"], "opp": "OPP-05", "cycle": 12,
     "detail": "Store decision, rule version 1.4.2, source turn references."},
    {"id": "T-108", "title": "Grease-trap: scaffold TrapWatch expiry watcher",
     "assignee": "forge", "status": "todo", "deps": [], "opp": "OPP-03", "cycle": 12,
     "detail": "Do not start until ORACLE confirms permit freshness."},
    {"id": "T-109", "title": "PRISM: rewrite Brooklyn landing headline",
     "assignee": "prism", "status": "done", "deps": ["T-106"], "opp": "OPP-05", "cycle": 11,
     "detail": "From 'AI receptionist' to 'Fill tomorrow's empty chair'."},
]

APPROVAL_SEED = [
    {"id": "AP-01", "title": "Register outreach domain jarvis-ops.com",
     "cost": 12.00, "period": "one-time / year", "agent": "echo", "status": "pending",
     "why": ("ECHO cannot send from a free mailbox without tripping spam filters. In the last "
             "test, 6 of 6 messages landed in Promotions. A registered domain is the minimum "
             "for a deliverable email-first channel."),
     "reversible": False},
    {"id": "AP-02", "title": "Twilio local number +1 (585) 555-0142",
     "cost": 1.15, "period": "per month", "agent": "echo", "status": "pending",
     "why": ("Phone escalation needs a 585 area code. Non-local VoIP numbers get screened by "
             "reception; a local prefix is the difference between a pickup and a hang-up."),
     "reversible": True},
    {"id": "AP-03", "title": "Google Workspace seat + SPF/DKIM",
     "cost": 7.20, "period": "per month", "agent": "echo", "status": "pending",
     "why": ("A dedicated mailbox keeps bounce rate attributable per campaign. Shared mailboxes "
             "mix ECHO's sends with personal mail and destroy the measurement."),
     "reversible": True},
    {"id": "AP-04", "title": "Apollo.io starter export — 500 contacts",
     "cost": 49.00, "period": "per month", "agent": "oracle", "status": "denied",
     "why": ("Proposed to accelerate list-building. SENTINEL flagged the source: no consent "
             "basis for cold email, and the list is scraped. Replaced by NY licensed-agency "
             "registries, which are free and defensible."),
     "reversible": True, "decided_by": "operator", "decided_note": "Denied at seed: use public registries."},
    {"id": "AP-05", "title": "Google Maps Places API — 1,000 geocodes",
     "cost": 17.00, "period": "one-time", "agent": "oracle", "status": "pending",
     "why": ("Needed to geocode 640 Onondaga food-service permits against parcel boundaries. "
             "County GIS is free but has no address index for 38 permits."),
     "reversible": True},
]

DEBRIEF_SEED = [
    {"agent": "echo", "outcome": "partial", "minutes_ago": 4, "cycle": 12, "opp": "OPP-06",
     "action": "Sent 6 outreach emails to Nassau County per-diem nursing agencies (batch N-03).",
     "assumed": ("That info@ inboxes are monitored before the 07:00 shift handoff, and that "
                 "agency owners read email on a phone."),
     "went_wrong": ("2 of 6 addresses bounced (info@northshorestaffing.com, admin@liperdiem.com). "
                    "No opens recorded after 6 hours — but tracking pixels are off, so 'no opens' "
                    "means 'no data', not 'no interest'."),
     "unsure": ("I cannot separate delivery failure from disinterest without a reply. The bounce "
                "pattern says the list was assembled from a directory, not from opt-ins."),
     "next": ("Call the two bounced agencies before 09:00, then rebuild the list from the NY DOH "
              "licensed-agency registry and re-send only to addresses with a named coordinator."),
     "citations": ["NY DOH per-diem registry (2026-10)", "Campaign N-03 send log"]},
    {"agent": "sentinel", "outcome": "failure", "minutes_ago": 11, "cycle": 12, "opp": "OPP-04",
     "action": "Refused the Albany brewery distributor claim and blocked BUILD.",
     "assumed": ("That a trade-trail membership list can stand in for distribution data. It cannot: "
                 "it records taproom hours, not distributor appointments."),
     "went_wrong": ("The claim '38 breweries need out-of-state distribution' traces to one blog "
                    "post citing 'industry estimates'. NYSLA lists 61 farm/brewery licenses but "
                    "has no distribution field. The count is probably directionally right; the "
                    "need is invented."),
     "unsure": ("I can verify how many breweries exist. I cannot verify that they want a "
                "distributor without a primary filing or a direct statement."),
     "next": ("Pull the NYSLA active roster and brand-label registrations, then sample 8 breweries "
              "with a single question. Re-open only at ≥25 confirmed and cap confidence at 68."),
     "citations": ["Capital Craft Beverage Trail list (2026)", "NYSLA active roster (2026-10)"]},
    {"agent": "forge", "outcome": "success", "minutes_ago": 26, "cycle": 12, "opp": "OPP-02",
     "action": "Generated bot spec snowquote v0.3 for Buffalo instant plow quoting.",
     "assumed": ("Erie County parcel GIS is address-geocodable and driveway area approximates "
                 "plowable surface within ±18%."),
     "went_wrong": ("Nothing failed in the build. The ±18% is an inherited guess from the v0.2 "
                    "spec and has never been checked against a real quote."),
     "unsure": ("The pipeline is deterministic and offline, but the price band is a model of a "
                "market I have not measured. A wrong band is worse than no band."),
     "next": ("Collect 10 real Buffalo quotes for parcels with known polygons; fit the error before "
              "ECHO sends a single link."),
     "citations": ["Erie County parcel GIS (2026-08)", "snowquote spec v0.3"]},
    {"agent": "oracle", "outcome": "partial", "minutes_ago": 63, "cycle": 11, "opp": "OPP-03",
     "action": "Cross-checked Onondaga County grease-trap permit counts.",
     "assumed": ("That permit expiry is a usable proxy for compliance risk, and that the county "
                 "open-data table is current."),
     "went_wrong": ("The permit table was last refreshed 2025-09-30 — six weeks stale. Rows include "
                    "restaurants that have closed, so 78 lapsed manifests is an upper bound."),
     "unsure": ("Between 60 and 78 of these businesses may actually be live and late. The order of "
                "magnitude holds; the exact count does not."),
     "next": ("Diff against the NYS DOH inspection feed and drop any permit with no inspection in "
              "18 months. Re-count before FORGE scaffolds TrapWatch."),
     "citations": ["Onondaga County open data (2025-09-30)", "NYS DOH inspection feed"]},
    {"agent": "atlas", "outcome": "success", "minutes_ago": 96, "cycle": 11, "opp": None,
     "action": "Re-sequenced the cycle 12 task graph after SENTINEL blocked Albany.",
     "assumed": ("That Buffalo has stronger primary evidence than Albany (county GIS + NWS archive) "
                 "and deserves FORGE's next build slot."),
     "went_wrong": ("Nothing failed. The plan assumes FORGE can hold two concurrent builds; that "
                    "capacity has never been measured."),
     "unsure": ("Sequencing is only as good as the duration estimates, and I do not have actual "
                "build times — only my own guesses."),
     "next": ("Log wall-clock time for snowquote. If it exceeds 6 hours, cap FORGE work-in-progress "
              "at one build and push TrapWatch behind the price check."),
     "citations": ["Cycle 12 task graph", "SENTINEL hold on OPP-04"]},
    {"agent": "prism", "outcome": "success", "minutes_ago": 140, "cycle": 10, "opp": "OPP-05",
     "action": "Rewrote the Brooklyn dental landing headline from 'AI receptionist' to 'Fill tomorrow's empty chair'.",
     "assumed": ("That practice managers buy chair utilization, not automation. The old headline "
                 "described the mechanism; the new one describes the loss."),
     "went_wrong": ("The copy has been tested on zero humans. It is a hypothesis with good "
                    "grammar, not a result."),
     "unsure": ("There is no baseline conversion for the old headline, so even a winning A/B test "
                "cannot tell me how much of the lift is the copy."),
     "next": ("Run old vs new on 200 visits each; 40 conversions per arm for 80% power. Until then, "
              "label the landing page EXPERIMENTAL in ECHO's sends."),
     "citations": ["PMS export no-show 21.8%", "Landing page v0.2"]},
    {"agent": "archive", "outcome": "success", "minutes_ago": 188, "cycle": 10, "opp": "OPP-05",
     "action": "Committed the KEEP decision for Brooklyn dental no-show recovery under rules v1.4.2.",
     "assumed": ("That a 28-day window is long enough to see a no-show change, and that the five "
                 "practices are comparable."),
     "went_wrong": ("Nothing failed in the write. Two of five practices changed front-desk staff "
                    "mid-pilot, which contaminates the cohort."),
     "unsure": ("The stored effect size (21.8% → 12.4%) is real for the raw sample, but I cannot "
                "attribute all of it to ChairFill."),
     "next": ("Tag the two staff-changed practices and re-measure the clean cohort before the "
              "decision is cited in any sales material."),
     "citations": ["Decision record D-014", "PMS export (3,412 appointments)"]},
    {"agent": "oracle", "outcome": "failure", "minutes_ago": 240, "cycle": 9, "opp": "OPP-09",
     "action": "Attempted phone validation of Syracuse veterinary after-hours demand.",
     "assumed": ("That four clinic calls count as evidence. They do not — they are anecdotes with "
                 "a phone number attached."),
     "went_wrong": ("Three clinics said 'not interested' before I finished the question; one hung "
                    "up. Four calls cannot support a $1,050/mo value estimate."),
     "unsure": ("I still believe the answering-service handoff is real. I have no measurement of "
                "how often it produces an ER visit or a missed case."),
     "next": ("Stop cold-calling. Use AVMA county counts plus NYSED vet-tech license data, then ask "
              "two ER hospitals for after-hours diversion counts."),
     "citations": ["AVMA county counts (2025)", "Call log 2026-10-21"]},
]

BLOCKED_SEED = [
    {"id": "BL-01", "cycle": 12, "agent": "sentinel", "opp": "OPP-04",
     "claim": "38 Capital Region breweries need out-of-state distribution.",
     "reason": ("One secondary source, zero primary. NYSLA confirms 61 brewery licenses but has no "
                "distribution field, so the 'need' is inferred from a membership list."),
     "status": "held", "blocks": "BUILD",
     "evidence_required": "NYSLA roster + 8 direct confirmations"},
    {"id": "BL-02", "cycle": 11, "agent": "sentinel", "opp": "OPP-06",
     "claim": "Nassau agency contact list is usable for cold outreach.",
     "reason": ("12 of 20 addresses came from a scraped directory with no opt-in and no named "
                "coordinator. CAN-SPAM needs a lawful basis, not just an address."),
     "status": "held", "blocks": "RUN",
     "evidence_required": "NY DOH registry addresses with named contacts"},
    {"id": "BL-03", "cycle": 9, "agent": "sentinel", "opp": "OPP-09",
     "claim": "$1,050/mo value for veterinary triage in Onondaga County.",
     "reason": ("Value derived from four anecdotal calls. Below the eight-source evidentiary floor "
                "for a revenue estimate."),
     "status": "held", "blocks": "MEASURE",
     "evidence_required": "ER diversion counts or clinic call logs"},
    {"id": "BL-04", "cycle": 8, "agent": "sentinel", "opp": "OPP-05",
     "claim": "Brooklyn dental no-show rate is 31%.",
     "reason": ("Initial claim was 31%. The PMS export showed 21.8% across 3,412 appointments. "
                "Corrected before publish; the claim is now cited to the export."),
     "status": "resolved", "blocks": "PUBLISH",
     "evidence_required": "PMS export"},
]

MEMORY_SEED = [
    {"kind": "decision", "agent": "archive",
     "text": ("KEEP: Brooklyn dental no-show recovery. 28-day pilot, 5 practices, no-show "
              "21.8% → 12.4%. Two practices changed front-desk staff; effect size is contaminated."),
     "source_turn": "cycle 10 · turn 42", "tags": ["keep", "dental", "nyc"], "minutes_ago": 188},
    {"kind": "fact", "agent": "oracle",
     "text": "Monroe County has 212 licensed HVAC contractors (NYS DOS license extract, 2026-10-02).",
     "source_turn": "cycle 11 · turn 37", "tags": ["rochester", "hvac", "licenses"], "minutes_ago": 210},
    {"kind": "fact", "agent": "oracle",
     "text": ("Erie County parcel GIS covers 98.6% of addressed parcels; 1,412 rural parcels have "
              "no polygon and cannot be quoted by area."),
     "source_turn": "cycle 12 · turn 51", "tags": ["buffalo", "gis", "snow"], "minutes_ago": 26},
    {"kind": "decision", "agent": "archive",
     "text": ("KILL: Albany brewery distributor finder. Evidence floor not met — 1 secondary "
              "source, no primary, 'need' inferred. Re-open only with direct confirmations."),
     "source_turn": "cycle 12 · turn 55", "tags": ["kill", "albany", "brewing"], "minutes_ago": 11},
    {"kind": "fact", "agent": "oracle",
     "text": "Onondaga County open-data permit table was last refreshed 2025-09-30; six weeks stale.",
     "source_turn": "cycle 11 · turn 39", "tags": ["syracuse", "permits", "stale"], "minutes_ago": 63},
    {"kind": "decision", "agent": "archive",
     "text": ("Rule v1.4.2 adopted: minimum 2 independent sources with at least 1 primary before "
              "BUILD. Holdout recall +3.7 pts, precision -0.9 pts vs v1.4.1."),
     "source_turn": "cycle 8 · turn 12", "tags": ["rules", "trust", "v1.4.2"], "minutes_ago": 2880},
    {"kind": "fact", "agent": "oracle",
     "text": ("Nassau County has 31 licensed per-diem nursing agencies; median reported shift-fill "
              "time is 4.2 hours (NY DOH registry, 2026-10)."),
     "source_turn": "cycle 12 · turn 48", "tags": ["long island", "nursing", "staffing"], "minutes_ago": 44},
    {"kind": "decision", "agent": "archive",
     "text": ("DENY: Apollo.io 500-contact export, $49/mo. Non-consented scraped list; CAN-SPAM "
              "exposure. Replaced with free NY licensed-agency registries."),
     "source_turn": "cycle 12 · turn 50", "tags": ["deny", "spend", "compliance"], "minutes_ago": 50},
    {"kind": "fact", "agent": "oracle",
     "text": ("Buffalo NWS issued 14 lake-effect advisories in the 2025-26 season through 2026-02-28; "
              "4 exceeded 12 inches."),
     "source_turn": "cycle 12 · turn 44", "tags": ["buffalo", "weather", "snow"], "minutes_ago": 70},
]

SETTINGS_SEED = {
    "geography": "New York State",
    "geography_locked": True,
    "home_base": "Rochester, NY (Monroe County)",
    "channels": "Email first → phone escalation",
    "monthly_budget": 0,
    "notifications": "SMS + phone",
    "autonomy": 1,
    "autonomy_label": "Act with approval",
    "hardware": "iPhone + MacBook",
    "session_started": None,
}


# ---------------------------------------------------------------------------
# helpers
# ---------------------------------------------------------------------------

def _utcnow() -> datetime:
    return datetime.now(timezone.utc)


def _iso(dt: datetime) -> str:
    return dt.replace(microsecond=0).isoformat().replace("+00:00", "Z")


def _clock(dt: datetime) -> str:
    return dt.strftime("%H:%M:%SZ")


def _money(value: float) -> str:
    return f"${value:,.2f}"


# ---------------------------------------------------------------------------
# state
# ---------------------------------------------------------------------------

class CommandCenter:
    """The whole console, in process memory, behind one lock."""

    def __init__(self) -> None:
        self.lock = threading.RLock()
        self.reset(flash=None)

    # -- lifecycle ---------------------------------------------------------
    def reset(self, flash: str | None = None) -> dict:
        with self.lock:
            now = _utcnow()
            self.cycle = 12
            self.seq = 1000
            self.memory_seq = 500
            self.approval_seq = 100
            self.task_seq = 200
            self.started_at = now

            self.agents = [dict(a) for a in AGENT_DEFS]
            for a in self.agents:
                a.update({"status": "idle", "task": "Awaiting dispatch", "cost": 0.0,
                          "last_active": None})

            self.opportunities = copy.deepcopy(OPPORTUNITY_SEED)
            self.backlog = copy.deepcopy(BACKLOG)
            self.tasks = copy.deepcopy(TASK_SEED)
            self.approvals = copy.deepcopy(APPROVAL_SEED)
            self.settings = copy.deepcopy(SETTINGS_SEED)
            self.settings["session_started"] = _iso(now)

            self.debriefs = []
            for row in DEBRIEF_SEED:
                ts = now - timedelta(minutes=row["minutes_ago"])
                self._append_debrief(
                    agent=row["agent"], action=row["action"], outcome=row["outcome"],
                    assumed=row["assumed"], went_wrong=row["went_wrong"],
                    unsure=row["unsure"], next_research=row["next"],
                    citations=row.get("citations", []), cycle=row["cycle"],
                    opp=row.get("opp"), ts=ts, quiet=True,
                )

            self.memory = []
            for row in MEMORY_SEED:
                self._add_memory(
                    kind=row["kind"], agent=row["agent"], text=row["text"],
                    source_turn=row["source_turn"], tags=row["tags"],
                    ts=now - timedelta(minutes=row["minutes_ago"]), quiet=True,
                )

            self.blocked = copy.deepcopy(BLOCKED_SEED)
            self.flash = flash or "Simulation state loaded: cycle 12, 10 live opportunities."
            self.last_active_stages = []
            self._recompute_agents()
            return self.snapshot()

    # -- small writers -----------------------------------------------------
    def _append_debrief(self, *, agent: str, action: str, outcome: str, assumed: str,
                        went_wrong: str, unsure: str, next_research: str,
                        citations: list[str] | None = None, cycle: int | None = None,
                        opp: str | None = None, ts: datetime | None = None,
                        quiet: bool = False) -> dict:
        self.seq += 1
        ts = ts or _utcnow()
        meta = next((a for a in AGENT_DEFS if a["id"] == agent), AGENT_DEFS[0])
        row = {
            "id": self.seq,
            "ts": _iso(ts),
            "clock": _clock(ts),
            "agent": agent,
            "agent_name": meta["name"],
            "agent_role": meta["role"],
            "color": meta["color"],
            "action": action,
            "outcome": outcome,
            "assumed": assumed,
            "went_wrong": went_wrong,
            "unsure": unsure,
            "next_research": next_research,
            "citations": citations or [],
            "cycle": self.cycle if cycle is None else cycle,
            "opp": opp,
        }
        self.debriefs.append(row)
        agent_row = next((a for a in self.agents if a["id"] == agent), None)
        if agent_row is not None:
            agent_row["last_active"] = row["clock"]
        if not quiet:
            self.flash = f"{meta['name']} logged a debrief: {action}"
        return row

    def _add_memory(self, *, kind: str, agent: str, text: str, source_turn: str,
                    tags: list[str], ts: datetime | None = None,
                    quiet: bool = False) -> dict:
        self.memory_seq += 1
        ts = ts or _utcnow()
        row = {
            "id": f"M-{self.memory_seq}",
            "kind": kind,
            "agent": agent,
            "text": text,
            "source_turn": source_turn,
            "tags": tags,
            "ts": _iso(ts),
            "clock": _clock(ts),
        }
        self.memory.append(row)
        return row

    def _recompute_agents(self) -> None:
        open_blocks = [b for b in self.blocked if b["status"] == "held"]
        for a in self.agents:
            doing = [t for t in self.tasks if t["assignee"] == a["id"]
                     and t["status"] in ("doing", "verify")]
            if a["id"] == "sentinel" and open_blocks:
                a["status"] = "blocked"
                a["task"] = f"Holding {len(open_blocks)} unverified claim(s)"
            elif doing:
                a["status"] = "working"
                a["task"] = doing[0]["title"]
            else:
                a["status"] = "idle"
                a["task"] = "Awaiting dispatch"
            a["cost"] = 0.0

    # -- derived values ----------------------------------------------------
    def _stage_counts(self) -> dict:
        counts = {k: 0 for k in STAGE_KEYS}
        for o in self.opportunities:
            counts[o["stage"]] = counts.get(o["stage"], 0) + 1
        return counts

    def _spend(self) -> dict:
        approved = sum(a["cost"] for a in self.approvals if a["status"] == "approved")
        pending = sum(a["cost"] for a in self.approvals if a["status"] == "pending")
        denied = sum(a["cost"] for a in self.approvals if a["status"] == "denied")
        return {
            "approved": round(approved, 2),
            "pending": round(pending, 2),
            "denied": round(denied, 2),
            "budget": self.settings["monthly_budget"],
            "approved_label": _money(approved),
            "pending_label": _money(pending),
            "denied_label": _money(denied),
            "status": "over budget" if approved > self.settings["monthly_budget"] else "within budget",
            "note": ("Monthly budget is $0. Every approved line above was an explicit human "
                     "override, not an agent decision."),
        }

    def _health(self) -> dict:
        open_approvals = [a for a in self.approvals if a["status"] == "pending"]
        held = [b for b in self.blocked if b["status"] == "held"]
        if len(held) >= 5 or len(open_approvals) >= 6:
            level, label = "attention", "ATTENTION"
        elif held or open_approvals:
            level, label = "watch", "WATCH"
        else:
            level, label = "nominal", "NOMINAL"
        reasons = []
        if held:
            reasons.append(f"{len(held)} claim(s) held by SENTINEL")
        if open_approvals:
            reasons.append(f"{len(open_approvals)} spend request(s) awaiting you")
        reasons.append("hash chain intact · 0 failed jobs")
        return {"level": level, "label": label, "reasons": reasons,
                "chain_ok": True, "model_calls": 0, "network_calls": 0}

    def _audit(self) -> dict:
        rules = copy.deepcopy(RULE_SET)
        rules["decisions"] = {
            "kept": sum(1 for o in self.opportunities if o.get("verdict") == "KEPT"),
            "killed": sum(1 for o in self.opportunities if o.get("verdict") == "KILLED"),
            "held": sum(1 for b in self.blocked if b["status"] == "held"),
        }
        rules["blocked"] = sorted(self.blocked, key=lambda b: b["id"], reverse=True)
        rules["holdout_delta"] = {
            "precision": round(rules["holdout"]["precision"] - rules["previous"]["precision"], 3),
            "recall": round(rules["holdout"]["recall"] - rules["previous"]["recall"], 3),
        }
        return rules

    def snapshot(self) -> dict:
        counts = self._stage_counts()
        stages = [
            {"key": k, "label": STAGE_LABELS[k], "count": counts[k], "blurb": STAGE_BLURB[k]}
            for k in STAGE_KEYS
        ]
        agents_active = sum(1 for a in self.agents if a["status"] == "working")
        open_approvals = [a for a in self.approvals if a["status"] == "pending"]
        return {
            "project": "JARVIS COMMAND CENTER",
            "subtitle": "JARVIS Orchestrator · local-first · New York State",
            "cycle": self.cycle,
            "clock": _clock(_utcnow()),
            "stage_counts": counts,
            "stages": stages,
            "agents": copy.deepcopy(self.agents),
            "agents_active": agents_active,
            "agents_total": len(self.agents),
            "opportunities": copy.deepcopy(self.opportunities),
            "tasks": copy.deepcopy(self.tasks),
            "approvals": copy.deepcopy(self.approvals),
            "open_approvals": len(open_approvals),
            "debriefs": sorted(copy.deepcopy(self.debriefs), key=lambda d: d["id"], reverse=True),
            "debrief_count": len(self.debriefs),
            "audit": self._audit(),
            "memory": sorted(copy.deepcopy(self.memory), key=lambda m: m["id"], reverse=True),
            "settings": copy.deepcopy(self.settings),
            "autonomy_levels": AUTONOMY_LEVELS,
            "regions": REGIONS,
            "spend": self._spend(),
            "health": self._health(),
            "backlog_remaining": len(self.backlog),
            "flash": self.flash,
            "active_stages": self.last_active_stages,
            "counts": {
                "opportunities": len(self.opportunities),
                "open_tasks": sum(1 for t in self.tasks if t["status"] != "done"),
                "debriefs": len(self.debriefs),
            },
        }

    # -- mutations ---------------------------------------------------------
    def run_cycle(self) -> dict:
        with self.lock:
            before = {(o["id"]): o["stage"] for o in self.opportunities}
            moved = []
            self.cycle += 1
            self.last_active_stages = []

            # 1. ATLAS opens the cycle with a plan.
            queued = sum(1 for t in self.tasks if t["status"] in ("todo", "doing"))
            self._append_debrief(
                agent="atlas",
                action=(f"Planned cycle {self.cycle}: advancing one item per live stage, "
                        f"{queued} task(s) on the board, {len(self.backlog)} candidate(s) in reserve."),
                outcome="success",
                assumed=("That one item per stage keeps WIP readable and lets SENTINEL see every "
                         "claim before FORGE spends a build slot."),
                went_wrong="",
                unsure=("Plan quality depends on duration estimates I have never measured; FORGE "
                        "build times are still guesses."),
                next_research=("Log FORGE wall-clock on snowquote; if it exceeds 6h, cap WIP at one "
                               "build per cycle."),
                citations=["Cycle task graph", "rules v1.4.2"],
            )

            # 2. Replenish FIND from the candidate reserve.
            if self.backlog and self._stage_counts()["find"] < 4:
                cand = self.backlog.pop(0)
                cand["entered_cycle"] = self.cycle
                cand["stage"] = "find"
                self.opportunities.append(cand)
                self._append_debrief(
                    agent="oracle",
                    action=(f"Surfaced new candidate {cand['id']}: {cand['business_type']} in "
                            f"{cand['city']} from the signal reserve."),
                    outcome="partial",
                    assumed=(f"That {cand['evidence'][0]['source']} is current enough to justify a "
                             f"verification pass."),
                    went_wrong="",
                    unsure=(f"Confidence {cand['confidence']} rests on {len(cand['evidence'])} "
                            f"source(s); {cand['stale_risk']}."),
                    next_research=f"Pull {cand['next_source']} before this leaves FIND.",
                    citations=[e["source"] for e in cand["evidence"]],
                    opp=cand["id"],
                )

            # 3. Advance exactly one item per live stage.
            for stage in ("find", "verify", "build", "run", "measure"):
                candidates = sorted(
                    [o for o in self.opportunities if o["stage"] == stage],
                    key=lambda o: (o.get("entered_cycle", 0), o["id"]),
                )
                if not candidates:
                    continue
                item = candidates[0]
                self._advance(item)
                moved.append({"id": item["id"], "from": stage, "to": item["stage"]})
                if stage not in self.last_active_stages:
                    self.last_active_stages.append(stage)
                if item["stage"] == "decide" and "decide" not in self.last_active_stages:
                    self.last_active_stages.append("decide")

            # 4. Anything that moved gets a visible mark in the queue.
            for m in moved:
                o = next(x for x in self.opportunities if x["id"] == m["id"])
                if o["stage"] == "build":
                    self._ensure_task(
                        title=f"Scaffold {o['bot_slug']} for {o['city']}",
                        assignee="forge", opp=o["id"],
                        detail=f"{o['bot']}. Do not deploy until SENTINEL clears the claim.",
                    )
                elif o["stage"] == "run":
                    self._ensure_task(
                        title=f"Run 5-day outreach pilot: {o['business_type']}",
                        assignee="echo", opp=o["id"],
                        detail="Email first. Phone escalation only after 72h with no reply.",
                        deps=[t["id"] for t in self.tasks if t["opp"] == o["id"]
                              and t["assignee"] == "forge"][:1],
                    )
                elif o["stage"] == "measure":
                    self._ensure_task(
                        title=f"Measure cohort: {o['business_type']}",
                        assignee="oracle", opp=o["id"],
                        detail="Reply rate, meetings booked, bounce rate. 28-day window.",
                    )

            if not moved:
                self._append_debrief(
                    agent="atlas",
                    action="Cycle closed with no movable items — pipeline is terminal.",
                    outcome="partial",
                    assumed="That the reserve still had candidates. It does not.",
                    went_wrong="Every opportunity is decided and the backlog is empty.",
                    unsure="I cannot invent findings to keep the loop moving; that would be fake work.",
                    next_research="Add new signals through Senses, or reset the simulation to replay cycle 12.",
                    citations=[],
                )

            self._recompute_agents()
            self.flash = (f"Cycle {self.cycle} complete — {len(moved)} item(s) advanced, "
                          f"{len(self.debriefs)} debriefs on record.")
            snap = self.snapshot()
            snap["moved"] = moved
            snap["moved_before"] = before
            return snap

    def _ensure_task(self, *, title: str, assignee: str, opp: str, detail: str,
                     deps: list[str] | None = None) -> dict:
        existing = next((t for t in self.tasks if t["title"] == title), None)
        if existing:
            return existing
        self.task_seq += 1
        task = {
            "id": f"T-{self.task_seq}",
            "title": title,
            "assignee": assignee,
            "status": "todo",
            "deps": deps or [],
            "opp": opp,
            "cycle": self.cycle,
            "detail": detail,
        }
        self.tasks.append(task)
        return task

    def _advance(self, o: dict) -> None:
        """Move one opportunity exactly one stage, with its debrief."""
        stage = o["stage"]
        if stage == "find":
            o["stage"] = "verify"
            o["entered_cycle"] = self.cycle
            self._append_debrief(
                agent="oracle",
                action=(f"Opened the evidence sweep for {o['business_type']} in {o['city']} "
                        f"({o['id']})."),
                outcome="partial",
                assumed=f"That {o['verify_focus']} can be checked against a primary record.",
                went_wrong="",
                unsure=(f"Confidence is {o['confidence']}. {o['stale_risk'].capitalize()}."),
                next_research=f"Pull {o['next_source']} and re-score if the count moves more than 10%.",
                citations=[e["source"] for e in o["evidence"]],
                opp=o["id"],
            )
            return

        if stage == "verify":
            self.last_active_stages.append("verify")
            if o["confidence"] < CONFIDENCE_FLOOR:
                o["stage"] = "decide"
                o["verdict"] = "KILLED"
                o["decided_cycle"] = self.cycle
                o["entered_cycle"] = self.cycle
                o["verify_failure"] = True
                self.approval_seq += 0
                self.blocked.append({
                    "id": f"BL-{len(self.blocked) + 1:02d}",
                    "cycle": self.cycle,
                    "agent": "sentinel",
                    "opp": o["id"],
                    "claim": (f"Confidence {o['confidence']} is enough to build "
                              f"{o['business_type']}."),
                    "reason": (f"Below the {CONFIDENCE_FLOOR}-point evidence floor. "
                               f"{o['stale_risk'].capitalize()}; the primary source is "
                               f"{o['primary_source']}."),
                    "status": "held",
                    "blocks": "BUILD",
                    "evidence_required": o["next_source"],
                })
                self._append_debrief(
                    agent="sentinel",
                    action=(f"Blocked {o['id']} ({o['business_type']}, {o['city']}) and moved it "
                            f"to KILL."),
                    outcome="failure",
                    assumed="That a low confidence score can be rescued by a better source later.",
                    went_wrong=(f"Confidence {o['confidence']} is below the floor of "
                                f"{CONFIDENCE_FLOOR}. Evidence on file: "
                                f"{len(o['evidence'])} source(s), primary = {o['primary_source']}."),
                    unsure=(f"I can see the claim is under-sourced, but not whether the market is "
                            f"real. {o['stale_risk'].capitalize()}."),
                    next_research=f"{o['next_source']}. Re-open only with a primary record and 2 independent sources.",
                    citations=[e["source"] for e in o["evidence"]],
                    opp=o["id"],
                )
                return

            o["stage"] = "build"
            o["entered_cycle"] = self.cycle
            self._append_debrief(
                agent="sentinel",
                action=(f"Cleared {o['id']} for BUILD — {o['business_type']}, {o['city']}."),
                outcome="success",
                assumed=(f"That {o['primary_source']} is the authoritative record and that the "
                         f"second source is independent of it."),
                went_wrong="",
                unsure=(f"Confidence {o['confidence']} measures the claim, not willingness to pay "
                        f"${o['value']:,}/mo. Price is still an inference."),
                next_research=("Run a ten-call price probe before any spend; do not let ECHO quote a "
                               "number we have not heard a buyer accept."),
                citations=[e["source"] for e in o["evidence"]],
                opp=o["id"],
            )
            return

        if stage == "build":
            o["stage"] = "run"
            o["entered_cycle"] = self.cycle
            o["metrics"] = {**o.get("metrics", {}), "sent": 0, "replies": 0, "meetings": 0}
            self._append_debrief(
                agent="forge",
                action=(f"Shipped {o['bot_slug']} v0.1 for {o['business_type']} in {o['city']} — "
                        f"runs on county open data and SMTP at $0."),
                outcome="success",
                assumed=(f"That {o['bot']} covers the intake path end-to-end and that the cited "
                         f"data is machine-readable."),
                went_wrong=("Nothing failed in the build. The bot has not seen a single real "
                            "inbound message."),
                unsure=("First-run error rate is unknown. A deterministic script can still fail on "
                        "a real address or a malformed reply."),
                next_research=("Send to five internal test addresses, then watch the first ten live "
                               "messages before ECHO scales the batch."),
                citations=[e["source"] for e in o["evidence"]],
                opp=o["id"],
            )
            self._maybe_request_approval(o)
            return

        if stage == "run":
            sent = 9 + (sum(ord(c) for c in o["id"]) % 4) * 3
            replies = 2 + (sum(ord(c) for c in o["id"]) % 3)
            meetings = 1 if o["confidence"] >= 65 else 0
            o["metrics"] = {"sent": sent, "replies": replies, "meetings": meetings}
            o["stage"] = "measure"
            o["entered_cycle"] = self.cycle
            self._append_debrief(
                agent="echo",
                action=(f"Closed the 5-day outreach pilot for {o['business_type']} ({o['city']}): "
                        f"{sent} sent, {replies} replies, {meetings} meeting(s)."),
                outcome="partial" if meetings == 0 else "success",
                assumed=("That email-first with 72-hour phone escalation reaches the person who "
                         "controls the schedule, not a gatekeeper."),
                went_wrong=(f"{replies} of {sent} replied; {max(1, sent // 12)} address(es) bounced. "
                            "No opens are tracked, so silence is ambiguous."),
                unsure=(f"A {replies}/{sent} reply rate is a small sample. One reply moves it by "
                        f"{round(100 / max(sent, 1), 1)} points."),
                next_research=("Call every non-replier once and log the outcome as a first-class "
                               "signal. If 20 calls produce zero meetings, kill the channel."),
                citations=["Campaign send log", "NYS licensed-agency registry"],
                opp=o["id"],
            )
            return

        if stage == "measure":
            meetings = o.get("metrics", {}).get("meetings", 0)
            keep = o["confidence"] >= KEEP_THRESHOLD and meetings >= 1
            o["stage"] = "decide"
            o["verdict"] = "KEPT" if keep else "KILLED"
            o["decided_cycle"] = self.cycle
            o["entered_cycle"] = self.cycle
            if keep:
                self._append_debrief(
                    agent="archive",
                    action=(f"Recorded KEEP for {o['id']} ({o['business_type']}, {o['city']}) — "
                            f"confidence {o['confidence']}, {meetings} meeting(s)."),
                    outcome="success",
                    assumed=("That one booked meeting plus a confidence above "
                             f"{KEEP_THRESHOLD} is enough signal to keep funding at $0."),
                    went_wrong="",
                    unsure=("Meeting count is not revenue. I have no paid conversion yet, so the "
                            "$" + f"{o['value']:,}/mo value is still a model."),
                    next_research=("Track the first paid pilot for 14 days. If it does not convert, "
                                   "reopen the KEEP at the next rule review."),
                    citations=["Decision record", "Campaign send log"],
                    opp=o["id"],
                )
                self._add_memory(
                    kind="decision", agent="archive",
                    text=(f"KEEP: {o['business_type']} ({o['city']}). Confidence {o['confidence']}, "
                          f"{meetings} meeting(s), value held at ${o['value']:,}/mo pending paid pilot."),
                    source_turn=f"cycle {self.cycle} · turn {self.seq}",
                    tags=["keep", o["region"].lower(), o["bot_slug"]],
                )
            else:
                self._append_debrief(
                    agent="sentinel",
                    action=(f"Killed {o['id']} ({o['business_type']}, {o['city']}) after measurement."),
                    outcome="failure",
                    assumed=("That a booked meeting at this confidence would justify the next "
                             "28-day cycle. It did not clear the keep bar."),
                    went_wrong=(f"Confidence {o['confidence']} with {meetings} meeting(s) is below "
                                f"the keep threshold ({KEEP_THRESHOLD} confidence + 1 meeting)."),
                    unsure=("A kill is not proof the market is absent; it is proof this channel and "
                            "this sample did not show demand."),
                    next_research=("Archive the negative result. Re-test only with a different "
                                   "channel and a primary demand source, not a reworded email."),
                    citations=["Campaign send log", "Measurement window"],
                    opp=o["id"],
                )
                self._add_memory(
                    kind="decision", agent="archive",
                    text=(f"KILL: {o['business_type']} ({o['city']}). Confidence {o['confidence']}, "
                          f"{meetings} meeting(s); below keep bar."),
                    source_turn=f"cycle {self.cycle} · turn {self.seq}",
                    tags=["kill", o["region"].lower(), o["bot_slug"]],
                )
            return

    def _maybe_request_approval(self, o: dict) -> None:
        pending = [a for a in self.approvals if a["status"] == "pending"]
        if len(pending) >= MAX_PENDING_APPROVALS:
            return
        self.approval_seq += 1
        self.approvals.append({
            "id": f"AP-{self.approval_seq}",
            "title": f"Dedicated sending mailbox — {o['city']} pilot",
            "cost": 7.20,
            "period": "per month",
            "agent": "echo",
            "status": "pending",
            "why": (f"{o['business_type']} needs its own mailbox so bounce rate stays attributable. "
                    "Sending from the shared inbox would mix this pilot with every other campaign."),
            "reversible": True,
        })

    # -- public actions ----------------------------------------------------
    def send_to_verify(self, opp_id: str) -> dict:
        with self.lock:
            o = next((x for x in self.opportunities if x["id"] == opp_id), None)
            if o is None:
                self.flash = f"No opportunity {opp_id}."
                return self.snapshot()
            if o["stage"] != "find":
                self.flash = (f"{opp_id} is already at {STAGE_LABELS.get(o['stage'], o['stage'])}. "
                              "Verification only starts from FIND.")
                return self.snapshot()
            o["stage"] = "verify"
            o["entered_cycle"] = self.cycle
            self._append_debrief(
                agent="oracle",
                action="opportunity.queued",
                outcome="partial",
                assumed=f"That {o['verify_focus']} can be resolved from public records this cycle.",
                went_wrong="",
                unsure=f"Confidence {o['confidence']} is pre-verification and may not survive the check.",
                next_research=f"Pull {o['next_source']} and compare against the cited count.",
                citations=[e["source"] for e in o["evidence"]],
                opp=o["id"],
            )
            self._recompute_agents()
            self.last_active_stages = ["find", "verify"]
            self.flash = f"{opp_id} sent to VERIFY — ORACLE owns the sweep."
            return self.snapshot()

    def dispatch_task(self, task_id: str) -> dict:
        with self.lock:
            t = next((x for x in self.tasks if x["id"] == task_id), None)
            if t is None:
                self.flash = f"No task {task_id}."
                return self.snapshot()
            if t["status"] != "todo":
                self.flash = f"{task_id} is already {t['status']}."
                return self.snapshot()
            open_deps = [d for d in t["deps"]
                         if not any(x["id"] == d and x["status"] == "done" for x in self.tasks)]
            if open_deps:
                self.flash = f"{task_id} blocked by {', '.join(open_deps)} — finish dependencies first."
                return self.snapshot()
            t["status"] = "doing"
            agent = next((a for a in self.agents if a["id"] == t["assignee"]), self.agents[0])
            self._append_debrief(
                agent="atlas",
                action="task.dispatched",
                outcome="success",
                assumed=f"That {agent['name']} has the context and the dependencies are actually done.",
                went_wrong="",
                unsure="Dispatch does not create capacity; FORGE and ORACLE can only hold one deep task each.",
                next_research="Check the first artifact, not the status field, before trusting 'doing'.",
                citations=[t["opp"]] if t.get("opp") else [],
                opp=t.get("opp"),
            )
            self._recompute_agents()
            self.flash = f"{task_id} dispatched to {agent['name']}."
            return self.snapshot()

    def verify_task(self, task_id: str) -> dict:
        with self.lock:
            t = next((x for x in self.tasks if x["id"] == task_id), None)
            if t is None or t["status"] != "doing":
                self.flash = f"{task_id} can only be sent to verify from doing."
                return self.snapshot()
            t["status"] = "verify"
            self._append_debrief(
                agent="sentinel",
                action="task.verification.received",
                outcome="partial",
                assumed="That the artifact exists and cites a source. I will check both.",
                went_wrong="",
                unsure="A status change is not evidence. Most failures hide behind a green checkmark.",
                next_research="Compare the artifact's numbers against the cited primary record before marking done.",
                citations=[t["opp"]] if t.get("opp") else [],
                opp=t.get("opp"),
            )
            self._recompute_agents()
            self.flash = f"{task_id} is with SENTINEL for verification."
            return self.snapshot()

    def complete_task(self, task_id: str) -> dict:
        with self.lock:
            t = next((x for x in self.tasks if x["id"] == task_id), None)
            if t is None or t["status"] not in ("doing", "verify"):
                self.flash = f"{task_id} cannot be completed from its current state."
                return self.snapshot()
            t["status"] = "done"
            agent = next((a for a in self.agents if a["id"] == t["assignee"]), self.agents[0])
            self._append_debrief(
                agent=agent["id"],
                action="task.completed",
                outcome="success",
                assumed=f"That the artifact satisfies: {t['detail']}",
                went_wrong="",
                unsure=("Completion is self-reported. Nothing in this task proved the output would "
                        "survive contact with a real customer."),
                next_research="Spot-check one output against its source; if it holds, retire the task and move on.",
                citations=[t["opp"]] if t.get("opp") else [],
                opp=t.get("opp"),
            )
            self._add_memory(
                kind="fact", agent=agent["id"],
                text=f"{task_id} closed: {t['title']}. {t['detail']}",
                source_turn=f"cycle {self.cycle} · turn {self.seq}",
                tags=["task", agent["id"]],
            )
            self._recompute_agents()
            self.flash = f"{task_id} complete — debrief written to the feed."
            return self.snapshot()

    def decide_approval(self, approval_id: str, decision: str) -> dict:
        with self.lock:
            a = next((x for x in self.approvals if x["id"] == approval_id), None)
            if a is None:
                self.flash = f"No approval {approval_id}."
                return self.snapshot()
            if a["status"] != "pending":
                self.flash = f"{approval_id} is already {a['status']}."
                return self.snapshot()
            if decision == "approve":
                a["status"] = "approved"
                a["decided_by"] = "operator"
                self._append_debrief(
                    agent="archive",
                    action=(f"Recorded your APPROVAL of {approval_id}: {a['title']} — "
                            f"{_money(a['cost'])} {a['period']}."),
                    outcome="success",
                    assumed="That you read the reason and accepted the cost, not just the button.",
                    went_wrong="",
                    unsure=("Approval does not make the spend effective. I cannot confirm the vendor "
                            "charged what it quoted."),
                    next_research="Reconcile the first invoice against this line; if it differs, freeze the account.",
                    citations=[approval_id],
                )
                self._add_memory(
                    kind="decision", agent="archive",
                    text=(f"APPROVED {approval_id}: {a['title']} ({_money(a['cost'])} {a['period']}) "
                          f"by human operator. Reason on file."),
                    source_turn=f"cycle {self.cycle} · turn {self.seq}",
                    tags=["approval", "spend", a["agent"]],
                )
                self.flash = f"{approval_id} approved — {_money(a['cost'])} added to committed spend."
            else:
                a["status"] = "denied"
                a["decided_by"] = "operator"
                self._append_debrief(
                    agent="archive",
                    action="approval.denied",
                    outcome="partial",
                    assumed="That the denial is about cost or risk, not about the underlying need.",
                    went_wrong="",
                    unsure="A denial leaves the need unmet; ECHO will hit the same wall next cycle.",
                    next_research="Write the $0 alternative into the task graph so the block is not rediscovered.",
                    citations=[approval_id],
                )
                self._add_memory(
                    kind="decision", agent="archive",
                    text=f"DENIED {approval_id}: {a['title']} ({_money(a['cost'])} {a['period']}). $0 alternative required.",
                    source_turn=f"cycle {self.cycle} · turn {self.seq}",
                    tags=["denial", "spend", a["agent"]],
                )
                self.flash = f"{approval_id} denied — nothing was spent."
            self._recompute_agents()
            return self.snapshot()

    def update_settings(self, payload: dict) -> tuple[dict, int]:
        with self.lock:
            if not isinstance(payload, dict):
                return self.snapshot(), 400
            raw = payload.get("autonomy")
            if raw is not None:
                try:
                    value = int(raw)
                except (TypeError, ValueError):
                    self.flash = "Autonomy must be 0, 1 or 2."
                    return self.snapshot(), 400
                if value not in (0, 1, 2):
                    self.flash = "Autonomy must be 0 (Suggest), 1 (Approval) or 2 (Report)."
                    return self.snapshot(), 400
                self.settings["autonomy"] = value
                self.settings["autonomy_label"] = AUTONOMY_LEVELS[value]["label"]
                self._append_debrief(
                    agent="atlas",
                    action="autonomy.set",
                    outcome="success",
                    assumed="That autonomy changes what runs, never what is allowed to spend.",
                    went_wrong="",
                    unsure="The slider cannot make an unverified claim true; SENTINEL still holds it.",
                    next_research="Watch the first cycle under the new level for a silent bypass.",
                    citations=["Settings · session"],
                )
                self.flash = f"Autonomy saved: {AUTONOMY_LEVELS[value]['label']}."
            else:
                self.flash = "Settings unchanged."
            self._recompute_agents()
            return self.snapshot(), 200


# ---------------------------------------------------------------------------
# JSON API
# ---------------------------------------------------------------------------

def command_center_blueprint(center: CommandCenter) -> Blueprint:
    bp = Blueprint("command_center", __name__)

    def _body() -> dict:
        payload = request.get_json(silent=True)
        return payload if isinstance(payload, dict) else {}

    @bp.get("/api/command/state")
    def state():
        with center.lock:
            return jsonify(center.snapshot())

    @bp.post("/api/command/cycle")
    def cycle():
        return jsonify(center.run_cycle())

    @bp.post("/api/command/reset")
    def reset():
        return jsonify(center.reset(flash="Simulation reset to cycle 12. All spend cleared to $0.00."))

    @bp.post("/api/command/opportunities/<opp_id>/verify")
    def send_verify(opp_id: str):
        return jsonify(center.send_to_verify(opp_id))

    @bp.post("/api/command/tasks/<task_id>/dispatch")
    def dispatch(task_id: str):
        return jsonify(center.dispatch_task(task_id))

    @bp.post("/api/command/tasks/<task_id>/verify")
    def task_verify(task_id: str):
        return jsonify(center.verify_task(task_id))

    @bp.post("/api/command/tasks/<task_id>/complete")
    def complete(task_id: str):
        return jsonify(center.complete_task(task_id))

    @bp.post("/api/command/approvals/<approval_id>/decide")
    def decide(approval_id: str):
        body = _body()
        decision = str(body.get("decision", "")).lower()
        if decision not in ("approve", "deny"):
            return jsonify({"error": "bad_request",
                            "message": "decision must be 'approve' or 'deny'"}), 400
        return jsonify(center.decide_approval(approval_id, decision))

    @bp.post("/api/command/settings")
    def settings():
        snap, status = center.update_settings(_body())
        return jsonify(snap), status

    @bp.get("/api/command/agents/<agent_id>")
    def agent(agent_id: str):
        with center.lock:
            row = next((a for a in center.agents if a["id"] == agent_id), None)
            if row is None:
                return jsonify({"error": "not_found", "message": f"no agent {agent_id}"}), 404
            actions = [d for d in center.snapshot()["debriefs"] if d["agent"] == agent_id]
            return jsonify({"agent": row, "actions": actions[:12]})

    return bp
