File size: 29,700 Bytes
af1bee9
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
"""

Procure-to-Pay (P2P) patch-test loop: LangGraph skeleton, pilot configuration.



Pilot decisions (Chief of Staff, 2026-10-09) implemented here:

  1. The graph owns the single retry. Playwright always runs with --retries=0.

  2. Go/no-go comes from reports/generate_report.py (QA's rule lives there). This graph has NO decision rule.

  3. Match tests keep real amounts. Triage is deterministic + local. Only an allowlisted dict of integer

     counts may ever reach the frontier model (optional summary, off by default).

  4. No cloud GPU with client data (see cost-estimate.md); local model = Ollama on a local/client-hosted GPU.

  5. Scope tiers: P1 always runs, P2 only with include_p2, P3 (and lower) is deferred and listed.

  Accepted simplifications: SQLite checkpoints, client's Git, env vars. Removed/deferred: research swarm,

  LLM test design, script builder, self-heal, Jira ticketing, LLM reporter.



Flow:

  load_cases(priority filter) -> approval_gate[HUMAN interrupt] -> plan_data(deterministic)

    -> execute(Playwright adapter, --retries=0)

         failures and no retry yet -> execute again, failed cases only (exactly one retry)

         otherwise                 -> triage (triage/classifier.py, deterministic)

    -> anything for a human (low-confidence or real-defect verdict, flaky test owner)? -> human_review[HUMAN interrupt] -> report

                      -> report (reports/generate_report.py decides GO/NO-GO)



STUB-ONLY by default: no Oracle Fusion pod exists. PLAYWRIGHT_MODE=live runs the Automation team's

specs against mock-app/ (once they exist). Nothing here is a run against Fusion.

"""
from __future__ import annotations

import argparse
import copy
import importlib
import json
import operator
import os
import re
import sqlite3
import subprocess
import sys
from pathlib import Path
from typing import Annotated, Literal, TypedDict

from langchain_core.runnables import RunnableConfig
from langgraph.checkpoint.memory import InMemorySaver
from langgraph.checkpoint.sqlite import SqliteSaver
from langgraph.graph import END, START, StateGraph
from langgraph.types import Command, interrupt

HERE = Path(__file__).resolve().parent
ROOT = HERE.parent  # /workspace/fusion-patch-testing
RUNS_DIR = Path(os.getenv("P2P_RUNS_DIR", HERE / "out" / "runs"))
MAX_RETRIES = 1  # decision 1: exactly one retry, owned by the graph

# --------------------------------------------------------------------------
# 1. Typed shared state
# --------------------------------------------------------------------------
Priority = Literal["P1", "P2", "P3", "P4"]


class TestCase(TypedDict):
    id: str
    title: str
    process: str          # requisition | po | receipt | invoice | match | payment | supplier | ...
    priority: Priority
    new_or_changed: bool  # only these need human approval
    data_recipe: str


class DeferredCase(TypedDict):
    id: str
    priority: str
    reason: str


class LLMCall(TypedDict):
    node: str
    route: Literal["local", "frontier"]
    model: str
    reason: str


class P2PState(TypedDict, total=False):
    patch_id: str
    include_p2: bool                 # decision 5: P2 only "if time allows"
    test_cases: list[TestCase]       # in scope for this run
    deferred: list[DeferredCase]     # out of scope this run (P2 when excluded, P3+, rejected)
    approvals: dict
    data_refs: dict[str, str]
    attempt_files: list[str]         # one Playwright JSON per attempt
    failures: list[str]              # case ids failing in the latest attempt
    retry_count: int
    triage_path: str
    report_root: str                 # project root generate_report evaluates (ROOT live; stub root in stub mode)
    review_items: list[dict]         # what the human must answer (confirm verdict / flaky owner)
    review: dict                     # generate_report's human-review format: {case_id: {confirmed, waiver, owner}}
    report_path: str
    decision: str                    # copied verbatim from generate_report.summarize()
    counts: dict
    llm_calls: Annotated[list[LLMCall], operator.add]


# --------------------------------------------------------------------------
# 2. Model routing (decision 3)
# --------------------------------------------------------------------------
LOCAL_MODEL = os.getenv("LOCAL_MODEL", "ollama/ministral-3:14b")  # listed on ollama.com/library/ministral-3, checked 2026-10-09
FRONTIER_MODEL = os.getenv("FRONTIER_MODEL", "mistral-large-2512")
# The ONLY payload shape allowed to leave: {count_name: int}. No ids, no amounts, no text.
FRONTIER_COUNT_KEYS = frozenset({
    "total", "executed", "passed", "failed", "flaky", "skipped", "deferred", "needs_review",
    "real_defect", "ui_change", "data", "timing", "unclassified"})


def is_redacted_counts(payload) -> bool:
    return (isinstance(payload, dict) and bool(payload)
            and all(k in FRONTIER_COUNT_KEYS and type(v) is int for k, v in payload.items()))


def route_model(task: str, payload) -> tuple[str, str]:
    """Routing rule (fails closed):

    frontier iff task == "summary" AND payload is a dict of allowlisted count names -> int.

    Everything else is local, including all triage and anything touching match tests or amounts."""
    if task != "summary":
        return "local", f"task '{task}' is local-only (client data, incl. real match amounts)"
    if not is_redacted_counts(payload):
        return "local", "summary payload is not pure allowlisted integer counts; refusing egress"
    return "frontier", "redacted aggregate counts only"


def call_llm(node: str, task: str, payload) -> tuple[str, LLMCall]:
    """Stub. Wire the local branch to Ollama /api/chat, the frontier branch to the provider SDK

    behind the egress module. Live calls are intentionally not implemented."""
    route, reason = route_model(task, payload)
    model = FRONTIER_MODEL if route == "frontier" else LOCAL_MODEL
    if os.getenv("LLM_MODE", "stub") != "stub":
        raise NotImplementedError("Live LLM calls are intentionally not wired in this skeleton.")
    return f"[stub {model}] {task}", LLMCall(node=node, route=route, model=model, reason=reason)


# --------------------------------------------------------------------------
# 3. Adapters to other teams' code
# --------------------------------------------------------------------------
def _team_module(name: str, subdir: str):
    """Import triage/classifier.py or reports/generate_report.py. Raises a clear error if absent."""
    for sub in ("triage", "reports"):
        p = str(ROOT / sub)
        if p not in sys.path:
            sys.path.insert(0, p)
    if not (ROOT / subdir / f"{name}.py").exists():
        raise RuntimeError(f"{subdir}/{name}.py not found: waiting on the Triage and Reporting team")
    return importlib.import_module(name)


def classifier():
    return _team_module("classifier", "triage")


def report_generator():
    return _team_module("generate_report", "reports")


# ---- test cases (Test Designer) ------------------------------------------
SAMPLE_CASES: list[TestCase] = [  # placeholders until tests/cases/*.yaml exists; NOT designed cases
    {"id": "P2P-REQ-001", "title": "Create and submit requisition", "process": "requisition", "priority": "P1", "new_or_changed": False, "data_recipe": ""},
    {"id": "P2P-PO-001", "title": "Approve PO from requisition", "process": "po", "priority": "P1", "new_or_changed": True, "data_recipe": ""},
    {"id": "P2P-RCV-001", "title": "Partial receipt against PO", "process": "receipt", "priority": "P2", "new_or_changed": False, "data_recipe": ""},
    {"id": "P2P-INV-001", "title": "3-way match invoice with real amounts", "process": "match", "priority": "P1", "new_or_changed": True, "data_recipe": ""},
    {"id": "P2P-PAY-001", "title": "Pay validated invoice", "process": "payment", "priority": "P1", "new_or_changed": False, "data_recipe": ""},
    {"id": "P2P-SUP-001", "title": "Edit supplier site description", "process": "supplier", "priority": "P3", "new_or_changed": False, "data_recipe": ""},
]
def normalize_priority(d: dict) -> Priority:
    """Same vocabulary as the go/no-go rule: reports/generate_report.tier() (QA tiers; critical=P1,

    high=P2, medium=P3, low=P4). Field order matches qa/audit.py: priority, then risk.

    Untiered cases default to P1 (run them) so nothing silently drops out of scope; the report lists them as a gap."""
    raw = d.get("priority") or d.get("tier") or d.get("risk")
    if isinstance(raw, dict):
        raw = raw.get("level")
    return report_generator().tier(raw) or "P1"  # type: ignore[return-value]


def _needs_approval(d: dict) -> bool:
    """Explicit new_or_changed wins; else Test Designer's approval_status (anything not 'approved...' needs the gate)."""
    if "new_or_changed" in d:
        return bool(d["new_or_changed"])
    return not str(d.get("approval_status", "")).strip().lower().startswith("approved")


def _recipes(d: dict) -> str:
    r = d.get("data_recipe") or d.get("recipe") or d.get("data_recipes") or ""
    return ",".join(map(str, r)) if isinstance(r, list) else str(r)


def load_cases_from_disk(case_dir: Path | None = None) -> list[TestCase]:
    case_dir = Path(case_dir or os.getenv("P2P_CASES_DIR", ROOT / "tests" / "cases"))
    files = sorted(case_dir.glob("*.y*ml")) if case_dir.exists() else []
    if not files:
        return copy.deepcopy(SAMPLE_CASES)
    import yaml
    out: list[TestCase] = []
    for f in files:
        doc = yaml.safe_load(f.read_text()) or {}
        docs = doc if isinstance(doc, list) else doc.get("cases", [doc])
        for d in docs:
            if isinstance(d, dict) and d.get("id"):
                out.append(TestCase(id=str(d["id"]), title=str(d.get("title", d.get("name", ""))),
                                    process=str(d.get("process", "unknown")), priority=normalize_priority(d),
                                    new_or_changed=_needs_approval(d), data_recipe=_recipes(d)))
    return out or copy.deepcopy(SAMPLE_CASES)


def select_scope(cases: list[TestCase], include_p2: bool) -> tuple[list[TestCase], list[DeferredCase]]:
    """Decision 5: P1 always; P2 only if include_p2; P3/P4 always deferred."""
    keep, deferred = [], []
    for c in cases:
        if c["priority"] == "P1" or (c["priority"] == "P2" and include_p2):
            keep.append(c)
        else:
            why = "P2: excluded this run (time)" if c["priority"] == "P2" else f"{c['priority']}: deferred for pilot"
            deferred.append(DeferredCase(id=c["id"], priority=c["priority"], reason=why))
    return keep, deferred


# ---- Playwright (Automation team) ----------------------------------------
AUTOMATION_DIR = ROOT / "automation"


def playwright_command(case_ids: list[str]) -> list[str]:
    """--retries=0 always: the graph owns the one retry (decision 1)."""
    grep = "|".join(re.escape(i) for i in case_ids)
    return ["npx", "playwright", "test", "--retries=0", "--reporter=json", "--grep", grep]


def run_playwright(case_ids: list[str], attempt: int, out_file: Path) -> Path:
    """Run the given cases once and write a Playwright JSON report to out_file.

    PLAYWRIGHT_MODE=stub (default): synthesize a Playwright-shaped report (no browser).

    PLAYWRIGHT_MODE=live: run automation/ specs against mock-app/ with --retries=0."""
    out_file.parent.mkdir(parents=True, exist_ok=True)
    if os.getenv("PLAYWRIGHT_MODE", "stub") == "live":
        specs = [p for p in (AUTOMATION_DIR / "tests").rglob("*.spec.*")] if (AUTOMATION_DIR / "tests").exists() else []
        if not specs:
            raise RuntimeError("PLAYWRIGHT_MODE=live but automation/tests/**/*.spec.* not found: waiting on Automation")
        env = {**os.environ, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(out_file), "PW_RETRIES": "0"}
        cmd = playwright_command(case_ids)
        if sys.platform == "win32":  # npx is npx.cmd there, and cmd.exe would treat the '|' in --grep as a pipe
            cmd = ["node", str(AUTOMATION_DIR / "node_modules" / "@playwright" / "test" / "cli.js"), *cmd[2:]]
        subprocess.run(cmd, cwd=AUTOMATION_DIR, env=env, check=False)
        if not out_file.exists():
            raise RuntimeError(f"Playwright produced no JSON report at {out_file}")
        return out_file
    out_file.write_text(json.dumps(_stub_report(case_ids, attempt), indent=1))
    return out_file


_STUB_MESSAGES = {
    # strict-mode violation -> classifier: ui_change, high confidence
    "ui": "Error: locator.click: Error: strict mode violation: getByRole('button', { name: 'Submit' }) resolved to 2 elements",
    # unclear locator timeout -> classifier gives low confidence (human review)
    "fail": "Error: locator.click: Timeout 10000ms exceeded.\nwaiting for getByRole('button', { name: 'Submit' })",
    # business-value assertion mismatch -> classifier gives real_defect with high confidence
    "defect": "Error: expect(received).toHaveText(expected)\n\nExpected string: \"Matched\"\nReceived string: \"On hold: price variance\"",
}


def _stub_report(case_ids: list[str], attempt: int) -> dict:
    """Deterministic fake Playwright JSON. Knobs (comma-separated ids):

    STUB_FAIL (always fail, unclear), STUB_DEFECT (always fail, business-value mismatch),

    STUB_UI (always fail, strict-mode locator), STUB_FLAKY (fail attempt 0 only)."""
    ids = lambda k: set(filter(None, os.getenv(k, "").split(",")))  # noqa: E731
    fail, defect, ui, flaky = ids("STUB_FAIL"), ids("STUB_DEFECT"), ids("STUB_UI"), ids("STUB_FLAKY")
    specs = []
    for cid in case_ids:
        kind = ("defect" if cid in defect else "ui" if cid in ui
                else "fail" if cid in fail or (cid in flaky and attempt == 0) else None)
        result = {"status": "failed" if kind else "passed", "retry": 0, "duration": 1000, "attachments": [],
                  "errors": [{"message": _STUB_MESSAGES[kind]}] if kind else []}
        specs.append({"title": f"{cid} (stub)", "tags": [f"@{cid}"], "id": cid, "file": "stub.spec.ts", "line": 1,
                      "tests": [{"projectName": "chromium", "annotations": [{"type": "case", "description": cid}],
                                 "results": [result], "status": "unexpected" if kind else "expected"}]})
    return {"_note": "STUB RUN - synthetic Playwright-shaped report, not a Fusion pod, not a browser run",
            "config": {"version": "stub", "projects": [{"name": "chromium", "use": {"baseURL": "stub://mock"}}]},
            "suites": [{"title": "stub.spec.ts", "file": "stub.spec.ts", "specs": specs, "suites": []}],
            "errors": [], "stats": {}}


def _walk_specs(suites):
    for s in suites or []:
        for spec in s.get("specs", []) or []:
            yield spec
        yield from _walk_specs(s.get("suites", []))


def merge_attempts(files: list[str], out_file: Path) -> Path:
    """Merge per-attempt reports into one Playwright-shaped report so the classifier and the

    report generator see the retry exactly as Playwright would: results=[attempt0, attempt1],

    status expected / unexpected / flaky."""
    base = json.loads(Path(files[0]).read_text())
    index = {(sp.get("file"), sp.get("title")): sp for sp in _walk_specs(base.get("suites"))}
    for attempt, f in enumerate(files[1:], start=1):
        later = json.loads(Path(f).read_text())
        base.setdefault("errors", []).extend(later.get("errors") or [])
        for sp in _walk_specs(later.get("suites")):
            tgt = index.get((sp.get("file"), sp.get("title")))
            if tgt is None:
                continue
            for t_new, t_old in zip(sp.get("tests", []), tgt.get("tests", [])):
                for r in t_new.get("results", []):
                    t_old.setdefault("results", []).append({**r, "retry": attempt})
    for sp in _walk_specs(base.get("suites")):
        for t in sp.get("tests", []):
            st = [r.get("status") for r in t.get("results", [])]
            if not st or all(s == "skipped" for s in st):
                t["status"] = "skipped"
            elif st[-1] == "passed":
                t["status"] = "flaky" if any(s != "passed" for s in st[:-1]) else "expected"
            else:
                t["status"] = "unexpected"
            sp["ok"] = t["status"] in ("expected", "flaky", "skipped")
    out_file.write_text(json.dumps(base, indent=1))
    return out_file


def build_stub_root(run_dir: Path, cases: list[TestCase]) -> Path:
    """Stub mode only. generate_report.py evaluates QA's rule against a project root (tests/cases,

    automation specs, qa/audit.py). The real root has no cases/specs yet, so in stub mode we give it a

    throwaway root holding ONLY the in-scope cases and a placeholder spec listing their ids.

    Every file is labelled STUB. Live mode uses the real project root instead."""
    root = run_dir / "stub-root"
    (root / "tests" / "cases").mkdir(parents=True, exist_ok=True)
    (root / "automation" / "tests").mkdir(parents=True, exist_ok=True)
    import yaml
    (root / "tests" / "cases" / "stub-cases.yaml").write_text(
        "# STUB: in-scope cases for a stub run. Not designed cases, not Fusion data.\n"
        + yaml.safe_dump({"cases": [{"id": c["id"], "title": c["title"], "process": c["process"],
                                     "priority": c["priority"]} for c in cases]}, sort_keys=False))
    (root / "automation" / "tests" / "stub.spec.ts").write_text(
        "// STUB placeholder so qa/audit.py can map case -> script. Never executed.\n"
        + "".join(f"test('{c['id']} {c['title']} (stub)', {{ tag: ['@{c['id']}'] }}, async () => {{}});\n" for c in cases))
    qa_link = root / "qa"
    if not qa_link.exists():
        try:
            qa_link.symlink_to(ROOT / "qa", target_is_directory=True)
        except OSError:  # Windows without admin/Developer Mode cannot symlink: copy instead
            import shutil
            shutil.copytree(ROOT / "qa", qa_link)
    return root


def failing_case_ids(report_file: str) -> list[str]:
    clf = classifier()
    recs = clf.parse_report(clf.load_report(report_file))
    return [r.case_id or r.title for r in recs if r.outcome == "failed"]


# --------------------------------------------------------------------------
# 4. Nodes
# --------------------------------------------------------------------------
def _run_dir(config: RunnableConfig) -> Path:
    d = RUNS_DIR / str(config["configurable"]["thread_id"])
    d.mkdir(parents=True, exist_ok=True)
    return d


def load_cases(state: P2PState, config: RunnableConfig) -> dict:
    run_dir = _run_dir(config)
    for f in run_dir.glob("attempt-*.json"):  # fresh run on this thread
        f.unlink()
    keep, deferred = select_scope(load_cases_from_disk(), bool(state.get("include_p2", False)))
    return {"test_cases": keep, "deferred": deferred, "retry_count": 0, "approvals": {}, "attempt_files": []}


def approval_gate(state: P2PState) -> dict:
    pending = [c["id"] for c in state["test_cases"] if c["new_or_changed"]]
    if not pending:
        return {"approvals": {"cases": {"auto": "no new or changed cases"}}}
    decision = interrupt({"gate": "approve_cases", "pending_case_ids": pending})
    approved = set(decision.get("approved", [])) if isinstance(decision, dict) else set()
    rejected = sorted(set(pending) - approved)
    keep = [c for c in state["test_cases"] if not c["new_or_changed"] or c["id"] in approved]
    deferred = state.get("deferred", []) + [DeferredCase(id=i, priority=next(c["priority"] for c in state["test_cases"] if c["id"] == i),
                                                          reason="rejected at approval gate") for i in rejected]
    return {"test_cases": keep, "deferred": deferred,
            "approvals": {"cases": {"approved": sorted(approved), "rejected": rejected}}}


def plan_data(state: P2PState) -> dict:
    # Deterministic: the case's recipe from tests/data-recipes/, else a per-process default.
    return {"data_refs": {c["id"]: c["data_recipe"] or f"recipe:{c['process']}:default" for c in state["test_cases"]}}


def execute(state: P2PState, config: RunnableConfig) -> dict:
    files = list(state.get("attempt_files", []))
    attempt = len(files)
    ids = [c["id"] for c in state["test_cases"]] if attempt == 0 else list(state["failures"])
    out = run_playwright(ids, attempt, _run_dir(config) / f"attempt-{attempt}.json")
    return {"attempt_files": files + [str(out)], "failures": failing_case_ids(str(out)), "retry_count": attempt}


def triage(state: P2PState, config: RunnableConfig) -> dict:
    """Deterministic triage = triage/classifier.py. No LLM unless LOCAL_TRIAGE_HINTS=1 (then local only)."""
    run_dir = _run_dir(config)
    live = os.getenv("PLAYWRIGHT_MODE", "stub") == "live"
    root = ROOT if live else build_stub_root(run_dir, state["test_cases"])
    merged = merge_attempts(state["attempt_files"], run_dir / "merged-results.json")
    cases_dir = root / "tests" / "cases"
    tri = classifier().triage(merged, cases_dir if cases_dir.exists() else None)  # tri["source"] = results path (QA C5 re-parses it)
    tri["run_mode"] = "live (mock-app)" if live else "STUB RUN - synthetic results, not a browser, not Fusion"
    path = run_dir / "triage.json"
    path.write_text(json.dumps(tri, indent=2, default=str))
    items = []
    for r in tri["records"]:
        cid, cl = r.get("case_id") or r["full_title"], r.get("classification") or {}
        if r["outcome"] == "failed" and (cl.get("needs_review") or cl.get("category") == "real_defect"):
            items.append({"case_id": cid, "ask": "confirm", "category": cl.get("category"),
                          "confidence": cl.get("confidence"), "evidence": cl.get("evidence")})
        elif r["outcome"] == "flaky":
            items.append({"case_id": cid, "ask": "owner"})  # QA C3: every flaky test needs an owner
    calls = []
    if os.getenv("LOCAL_TRIAGE_HINTS") == "1" and any(i["ask"] == "confirm" for i in items):
        _, call = call_llm("triage", "triage", items)  # route_model forces local
        calls.append(call)
    return {"triage_path": str(path), "report_root": str(root), "review_items": items, "review": {}, "llm_calls": calls}


def human_review(state: P2PState) -> dict:
    """Collects answers in generate_report's format: {case_id: {"confirmed": "real_defect"|"not_defect",

    "waiver": str, "owner": str}}. The graph does not interpret them; the report rule does."""
    answer = interrupt({"gate": "human_review", "items": state["review_items"]})
    review = answer.get("review", {}) if isinstance(answer, dict) else {}
    return {"review": review, "approvals": {**state.get("approvals", {}), "review": review}}


def report(state: P2PState, config: RunnableConfig) -> dict:
    """Decision 2: GO/NO-GO is whatever reports/generate_report.py says. No rule here."""
    run_dir = _run_dir(config)
    tri = json.loads(Path(state["triage_path"]).read_text())
    s = report_generator().write_reports(tri, run_dir, root=Path(state["report_root"]), review=state.get("review", {}))
    if not str(tri.get("run_mode", "")).startswith("live"):
        banner = "STUB RUN: synthetic results from p2p_graph.py stubs. No browser, no mock-app, no Fusion. Not evidence of anything."
        md = run_dir / "go-no-go.md"
        md.write_text(f"> **{banner}**\n\n" + md.read_text())
        h = run_dir / "go-no-go.html"
        h.write_text(h.read_text().replace("<body>", f"<body><p style='background:#fdd;padding:8px'><b>{banner}</b></p>", 1))
    c = s["counts"]
    counts = {"total": c["total"], "executed": c["executed"], "passed": c["pass"], "failed": c["fail"],
              "flaky": c["flaky"], "skipped": c["skipped"]}
    counts = {k: int(v) for k, v in counts.items()}
    counts.update({k: int(v) for k, v in s["by_class"].items() if k in FRONTIER_COUNT_KEYS})
    counts["deferred"] = len(state.get("deferred", []))
    calls = []
    if os.getenv("FRONTIER_SUMMARY") == "1":  # optional prose; counts only, enforced by route_model
        _, call = call_llm("report", "summary", counts)
        calls.append(call)
    summary = {"patch_id": state.get("patch_id"), "source": tri.get("source"),
               "run_mode": tri.get("run_mode"), "decision": s["decision"],
               "decision_source": "reports/generate_report.py (QA rule)",
               "criteria": {k: {"ok": ok, "detail": d} for k, (ok, d) in s["criteria"].items()},
               "gaps": s["gaps"], "counts": counts,
               "scope": {"in_scope": [c["id"] for c in state["test_cases"]], "deferred": state.get("deferred", [])},
               "retry_count": state.get("retry_count", 0), "approvals": state.get("approvals", {}),
               "llm_calls": state.get("llm_calls", []) + calls}
    (run_dir / "run-summary.json").write_text(json.dumps(summary, indent=2, default=str))
    return {"report_path": str(run_dir / "go-no-go.md"), "decision": s["decision"], "counts": counts, "llm_calls": calls}


# --------------------------------------------------------------------------
# 5. Edges
# --------------------------------------------------------------------------
def after_execute(state: P2PState) -> str:
    if state["failures"] and len(state["attempt_files"]) <= MAX_RETRIES:
        return "execute"  # the one retry: failed cases only, still --retries=0
    return "triage"


def after_triage(state: P2PState) -> str:
    return "human_review" if state.get("review_items") else "report"


def build_graph(checkpointer=None):
    g = StateGraph(P2PState)
    for name, fn in [("load_cases", load_cases), ("approval_gate", approval_gate), ("plan_data", plan_data),
                     ("execute", execute), ("triage", triage), ("human_review", human_review), ("report", report)]:
        g.add_node(name, fn)
    g.add_edge(START, "load_cases")
    g.add_edge("load_cases", "approval_gate")
    g.add_edge("approval_gate", "plan_data")
    g.add_edge("plan_data", "execute")
    g.add_conditional_edges("execute", after_execute, ["execute", "triage"])
    g.add_conditional_edges("triage", after_triage, ["human_review", "report"])
    g.add_edge("human_review", "report")
    g.add_edge("report", END)
    return g.compile(checkpointer=checkpointer or InMemorySaver())


def sqlite_checkpointer(path: str | Path = HERE / "out" / "checkpoints.sqlite") -> SqliteSaver:
    Path(path).parent.mkdir(parents=True, exist_ok=True)
    return SqliteSaver(sqlite3.connect(str(path), check_same_thread=False))


# --------------------------------------------------------------------------
# 6. CLI
# --------------------------------------------------------------------------
def _print_status(graph, config):
    snap = graph.get_state(config)
    if snap.next:
        for t in snap.tasks:
            for intr in t.interrupts:
                print(f"PAUSED at {t.name}: {json.dumps(intr.value)}")
        return
    v = snap.values
    print(f"DONE. decision={v['decision']} (from reports/generate_report.py, QA rule) counts={json.dumps(v['counts'])}")
    print(f"report: {v['report_path']}")
    print(f"summary: {Path(v['report_path']).parent / 'run-summary.json'}")


def main(argv=None):
    p = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)
    p.add_argument("cmd", choices=["run", "resume", "demo", "status"])
    p.add_argument("--thread", default="demo")
    p.add_argument("--patch-id", default="STUB-26C")
    p.add_argument("--include-p2", action="store_true", help="also run P2 cases (if time allows)")
    p.add_argument("--approve", action="store_true", help="resume: approve all pending items as proposed")
    a = p.parse_args(argv)
    graph = build_graph(sqlite_checkpointer())
    cfg = {"configurable": {"thread_id": a.thread}}

    def answer(payload, approve):
        if payload["gate"] == "approve_cases":
            return {"approved": payload["pending_case_ids"] if approve else []}
        if not approve:
            return {"review": {}}
        # --approve = accept the classifier's verdicts as proposed and assign a placeholder owner to flaky tests
        rv = {}
        for i in payload["items"]:
            rv[i["case_id"]] = ({"owner": "unassigned-demo"} if i["ask"] == "owner" else
                                {"confirmed": "real_defect" if i["category"] == "real_defect" else "not_defect"})
        return {"review": rv}

    if a.cmd == "run":
        graph.invoke({"patch_id": a.patch_id, "include_p2": a.include_p2}, cfg)
    elif a.cmd == "resume":
        snap = graph.get_state(cfg)
        if not (snap.tasks and snap.tasks[0].interrupts):
            print("nothing to resume")
        else:
            graph.invoke(Command(resume=answer(snap.tasks[0].interrupts[0].value, a.approve)), cfg)
    elif a.cmd == "demo":
        graph.invoke({"patch_id": a.patch_id, "include_p2": a.include_p2}, cfg)
        while graph.get_state(cfg).next:
            payload = graph.get_state(cfg).tasks[0].interrupts[0].value
            print(f"auto-approving gate {payload['gate']}")
            graph.invoke(Command(resume=answer(payload, True)), cfg)
    _print_status(graph, cfg)


if __name__ == "__main__":
    main()