EnergyVenom commited on
Commit
d7c4fa8
·
verified ·
1 Parent(s): 39bf357

Deploy Patch Testing Co-worker

Browse files
automation/playwright.fusion.config.ts CHANGED
@@ -11,6 +11,7 @@ if (!process.env.PW_RUN_ID) {
11
  process.env.PW_RUN_ID = `fusion-${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}${p2(d.getSeconds())}`;
12
  }
13
  const RUN_DIR = path.join(__dirname, 'results', 'runs', process.env.PW_RUN_ID);
 
14
  const SLOW_MO = process.env.FPT_LIVE_VIEW_DIR ? Math.max(0, Math.min(3000, Number(process.env.FPT_BROWSER_SLOWMO_MS) || 0)) : 0;
15
 
16
  export default defineConfig({
@@ -35,5 +36,10 @@ export default defineConfig({
35
  viewport: { width: 1440, height: 900 },
36
  launchOptions: { slowMo: SLOW_MO },
37
  },
38
- projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }],
 
 
 
 
 
39
  });
 
11
  process.env.PW_RUN_ID = `fusion-${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}${p2(d.getSeconds())}`;
12
  }
13
  const RUN_DIR = path.join(__dirname, 'results', 'runs', process.env.PW_RUN_ID);
14
+ const DRAFTS = process.env.FPT_DRAFTS_DIR;
15
  const SLOW_MO = process.env.FPT_LIVE_VIEW_DIR ? Math.max(0, Math.min(3000, Number(process.env.FPT_BROWSER_SLOWMO_MS) || 0)) : 0;
16
 
17
  export default defineConfig({
 
36
  viewport: { width: 1440, height: 900 },
37
  launchOptions: { slowMo: SLOW_MO },
38
  },
39
+ projects: [
40
+ { name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } },
41
+ // AI-written steps scenarios staged by the co-worker (FPT_DRAFTS_DIR, outside automation/): their dry run before
42
+ // the consultant approves them, and runs from staging. Invisible to `npm test` and to qa/audit.py.
43
+ ...(DRAFTS ? [{ name: 'drafts', testDir: DRAFTS, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []),
44
+ ],
45
  });
automation/scripts/gen-fusion-steps.js CHANGED
@@ -1,11 +1,13 @@
1
  // Gives every steps scenario (tests/cases/*.yaml with `runner: steps`) its Playwright entry point at
2
  // tests/fusion/steps/<ID>.spec.ts. The entry is two lines; the steps live in the YAML. Run: npm run gen:fusion-steps
 
3
  const fs = require('fs');
4
  const path = require('path');
5
  const YAML = require('yaml');
6
 
7
- const CASES = path.join(__dirname, '..', '..', 'tests', 'cases');
8
- const OUT = path.join(__dirname, '..', 'tests', 'fusion', 'steps');
 
9
  fs.mkdirSync(OUT, { recursive: true });
10
  const want = new Set();
11
  for (const f of fs.readdirSync(CASES).filter((x) => x.endsWith('.yaml'))) {
 
1
  // Gives every steps scenario (tests/cases/*.yaml with `runner: steps`) its Playwright entry point at
2
  // tests/fusion/steps/<ID>.spec.ts. The entry is two lines; the steps live in the YAML. Run: npm run gen:fusion-steps
3
+ // Optional: --cases <dir> --out <dir> (the co-worker passes them when it promotes an approved AI scenario).
4
  const fs = require('fs');
5
  const path = require('path');
6
  const YAML = require('yaml');
7
 
8
+ const arg = (name) => { const i = process.argv.indexOf(name); return i > 0 ? process.argv[i + 1] : undefined; };
9
+ const CASES = arg('--cases') || path.join(__dirname, '..', '..', 'tests', 'cases');
10
+ const OUT = arg('--out') || path.join(__dirname, '..', 'tests', 'fusion', 'steps');
11
  fs.mkdirSync(OUT, { recursive: true });
12
  const want = new Set();
13
  for (const f of fs.readdirSync(CASES).filter((x) => x.endsWith('.yaml'))) {
automation/src/fusion/steps.ts CHANGED
@@ -18,8 +18,19 @@ export interface StepCase { id: string; title: string; runner?: string; steps: S
18
 
19
  const CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases');
20
 
21
- export function loadStepCase(id: string): StepCase {
22
- const f = path.join(CASES_DIR, `${id}.yaml`);
 
 
 
 
 
 
 
 
 
 
 
23
  const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase;
24
  if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`);
25
  return c;
@@ -94,9 +105,10 @@ async function runStep(s: Step, ctx: Ctx) {
94
  await (fn as (...a: unknown[]) => Promise<void>).apply(ctx.ui, block.args(s, ctx));
95
  }
96
 
97
- /** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/<ID>.spec.ts. */
98
- export function stepsTest(id: string, tags: string[]) {
99
- const c = loadStepCase(id);
 
100
  test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices }) => {
101
  const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track };
102
  for (const [i, s] of c.steps.entries()) {
 
18
 
19
  const CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases');
20
 
21
+ /**
22
+ * The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds
23
+ * that id (the co-worker's staging folder for drafts), else from the script library tests/cases/.
24
+ */
25
+ export function stepCaseFile(id: string, dir?: string): string {
26
+ for (const d of [dir, process.env.FPT_STEPS_DIR]) {
27
+ if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`);
28
+ }
29
+ return path.join(CASES_DIR, `${id}.yaml`);
30
+ }
31
+
32
+ export function loadStepCase(id: string, dir?: string): StepCase {
33
+ const f = stepCaseFile(id, dir);
34
  const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase;
35
  if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`);
36
  return c;
 
105
  await (fn as (...a: unknown[]) => Promise<void>).apply(ctx.ui, block.args(s, ctx));
106
  }
107
 
108
+ /** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/<ID>.spec.ts, or
109
+ * from a staged draft's entry (opts.dir = the staging folder holding its YAML). */
110
+ export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {
111
+ const c = loadStepCase(id, opts.dir);
112
  test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices }) => {
113
  const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track };
114
  for (const [i, s] of c.steps.entries()) {
coworker/api/routes/consultant.py CHANGED
@@ -69,6 +69,7 @@ def _scenarios_view(svc, runs, run: dict) -> dict:
69
  pending = {p["id"]: p for p in (gate or {}).get("pending", [])} if (gate or {}).get("gate") == "approve_cases" else {}
70
  outcomes = (state.get("run_results") or {}).get("outcomes") or {}
71
  steps_cache: dict[str, list[dict]] = {}
 
72
  out, seen = [], set()
73
  cases = list(state.get("test_cases") or []) + [p for p in pending.values() if p["id"] not in {c["id"] for c in state.get("test_cases") or []}]
74
  for c in cases:
@@ -78,7 +79,11 @@ def _scenarios_view(svc, runs, run: dict) -> dict:
78
  seen.add(cid)
79
  module = c.get("module") or cid.split("-", 1)[0]
80
  steps = steps_cache.setdefault(module, R.module_steps(module))
81
- d = R.scenario_detail(cid, steps, state)
 
 
 
 
82
  if d is None: # a generated draft: no library entry yet, show what the generator proposed
83
  st = R.step_for_case({"id": cid, "map_ids": c.get("map_ids") or [], "process": c.get("process")}, steps)
84
  pr = str(c.get("priority") or "")[:2]
 
69
  pending = {p["id"]: p for p in (gate or {}).get("pending", [])} if (gate or {}).get("gate") == "approve_cases" else {}
70
  outcomes = (state.get("run_results") or {}).get("outcomes") or {}
71
  steps_cache: dict[str, list[dict]] = {}
72
+ ai_by_id = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}
73
  out, seen = [], set()
74
  cases = list(state.get("test_cases") or []) + [p for p in pending.values() if p["id"] not in {c["id"] for c in state.get("test_cases") or []}]
75
  for c in cases:
 
79
  seen.add(cid)
80
  module = c.get("module") or cid.split("-", 1)[0]
81
  steps = steps_cache.setdefault(module, R.module_steps(module))
82
+ ai = ai_by_id.get(cid)
83
+ d = R.scenario_detail(cid, steps, state, path=c.get("yaml_path") if ai else None)
84
+ if d is not None and ai: # written by the AI model: say so, with its dry run on the pod
85
+ d["why"] = [f"Written by the AI model: {ai['why']}" if ai.get("why") else "Written by the AI model"] + d["why"]
86
+ d.update(written_by="AI model", dry_run=ai.get("dry_run"), ai_status=ai.get("status"))
87
  if d is None: # a generated draft: no library entry yet, show what the generator proposed
88
  st = R.step_for_case({"id": cid, "map_ids": c.get("map_ids") or [], "process": c.get("process")}, steps)
89
  pr = str(c.get("priority") or "")[:2]
coworker/api/routes/runs.py CHANGED
@@ -155,7 +155,8 @@ def run_cases(run_id: str, request: Request, user: Principal = Depends(require("
155
  st = runs.state(run_id)
156
  approvals_rows = svc.db.q("SELECT case_id, gate, decision, actor, comment, ts, auto FROM approvals WHERE run_id=? ORDER BY id", (run_id,))
157
  return {"test_cases": st.get("test_cases") or [], "deferred": st.get("deferred") or [],
158
- "proposed_cases": st.get("proposed_cases") or [], "approvals": st.get("approvals") or {}, "approval_log": approvals_rows}
 
159
 
160
 
161
  @router.get("/runs/{run_id}/data-plan")
 
155
  st = runs.state(run_id)
156
  approvals_rows = svc.db.q("SELECT case_id, gate, decision, actor, comment, ts, auto FROM approvals WHERE run_id=? ORDER BY id", (run_id,))
157
  return {"test_cases": st.get("test_cases") or [], "deferred": st.get("deferred") or [],
158
+ "proposed_cases": st.get("proposed_cases") or [], "ai_drafts": st.get("ai_drafts") or [],
159
+ "approvals": st.get("approvals") or {}, "approval_log": approvals_rows}
160
 
161
 
162
  @router.get("/runs/{run_id}/data-plan")
coworker/config.py CHANGED
@@ -110,6 +110,9 @@ class Settings(BaseSettings):
110
  approval_remind_after_s: int = Field(24 * 3600, validation_alias=_alias("approval_remind_after", "approval_remind_after_s"))
111
  approval_escalate_after_s: int = Field(72 * 3600, validation_alias=_alias("approval_escalate_after", "approval_escalate_after_s"))
112
  exec_chunk_size: int = 10
 
 
 
113
 
114
  pod_kind: Literal["mock", "fusion"] = "mock"
115
  pod_base_url: str = "http://127.0.0.1:3100"
 
110
  approval_remind_after_s: int = Field(24 * 3600, validation_alias=_alias("approval_remind_after", "approval_remind_after_s"))
111
  approval_escalate_after_s: int = Field(72 * 3600, validation_alias=_alias("approval_escalate_after", "approval_escalate_after_s"))
112
  exec_chunk_size: int = 10
113
+ # Fusion pods with an AI model on: how many NEW scenarios the model writes per business area in each test run
114
+ # (dry-run on the pod, then offered at the approval gate). 0 turns it off.
115
+ fusion_ai_scenarios: int = Field(2, validation_alias=_alias("fpt_fusion_ai_scenarios", "fusion_ai_scenarios"))
116
 
117
  pod_kind: Literal["mock", "fusion"] = "mock"
118
  pod_base_url: str = "http://127.0.0.1:3100"
coworker/graph/nodes/ai_scenarios.py ADDED
@@ -0,0 +1,275 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI-written scenarios for a real Oracle Fusion pod (part of the design phase).
2
+
3
+ After test_generator has chosen the library cases, and only when the run targets a registered Fusion pod AND an
4
+ external AI model is switched on, the step writer (platform/step_writer.py) designs a few NEW scenarios for each business
5
+ area from the area's captured screens (public labels only; the data rule of the step writer is unchanged), writes their
6
+ steps and checks them. Each accepted draft is staged under FPT_HOME/staging/steps/<run_id>/ with its Playwright entry
7
+ point under FPT_HOME/staging/specs/<run_id>/, then DRY-RUN on the pod with the step runner before the approval gate.
8
+
9
+ - dry run passed -> offered at the approval gate (origin "ai") with its steps in plain language and the dry-run result;
10
+ - dry run failed -> NOT offered as runnable; shown at the gate with the failing step and its message.
11
+ Approving promotes the draft into the script library (tests/cases/<ID>.yaml + its entry spec, committed to library.git);
12
+ rejected drafts stay in staging. Nothing here runs for the practice pod, or when no AI model is configured."""
13
+ from __future__ import annotations
14
+
15
+ import json
16
+ import re
17
+ import subprocess
18
+ from datetime import datetime, timezone
19
+ from pathlib import Path
20
+ from urllib.parse import urlparse
21
+
22
+ import yaml
23
+
24
+ from ...adapters import playwright as pw
25
+ from ...config import ROOT
26
+ from ...llm.base import Route
27
+ from ...platform import procs, step_writer
28
+ from ...platform.rundb import now_iso
29
+
30
+ ANSI = re.compile(r"\x1b\[[0-9;]*m")
31
+ STEP_TITLE = re.compile(r"^\d+\.\s")
32
+ PROMOTE_ROOT = ROOT # where approved drafts go (tests/cases + automation/tests/fusion/steps); tests point it elsewhere
33
+ AI_ORIGIN = "ai"
34
+
35
+
36
+ def _note(svc, run_id: str, message: str, **extra) -> None:
37
+ svc.db.add_event(run_id, "test_generator", "ai_scenarios", {"message": message, **extra})
38
+ svc.audit.append("ai_scenarios.note", actor="system", run_id=run_id, node="test_generator", summary=message[:200])
39
+
40
+
41
+ def _pod_host(svc, pod_id: int) -> str:
42
+ row = svc.db.one("SELECT base_url FROM pods WHERE id=?", (pod_id,))
43
+ return urlparse((row or {}).get("base_url") or "").hostname or "the pod"
44
+
45
+
46
+ def specs_dir(svc, run_id: str) -> Path:
47
+ return svc.cfg.path("staging", "specs", run_id)
48
+
49
+
50
+ # ====================================================================== dry run
51
+ def _failed_step(steps: list[dict]) -> tuple[str | None, str | None]:
52
+ """(title of the first scenario step that failed, its error message) from a Playwright JSON result's steps."""
53
+ for s in steps or []:
54
+ title = str(s.get("title") or "")
55
+ inner_t, inner_m = _failed_step(s.get("steps") or [])
56
+ if s.get("error") or inner_t:
57
+ if STEP_TITLE.match(title):
58
+ msg = (s.get("error") or {}).get("message") or inner_m
59
+ return title, ANSI.sub("", str(msg or ""))[:1200] or None
60
+ if inner_t:
61
+ return inner_t, inner_m
62
+ return None, None
63
+
64
+
65
+ def read_dry_run(report_file: Path, ids: list[str]) -> dict[str, dict]:
66
+ """{id: {status, failed_step, message}} from the dry run's Playwright JSON (stub or live)."""
67
+ data = json.loads(Path(report_file).read_text(encoding="utf-8"))
68
+ out: dict[str, dict] = {}
69
+ for spec in pw._walk_specs(data.get("suites")):
70
+ tags = [t.lstrip("@") for t in spec.get("tags") or []]
71
+ cid = next((i for i in ids if i in tags or spec.get("id") == i or str(spec.get("title", "")).startswith(i + " ")), None)
72
+ if not cid:
73
+ continue
74
+ for t in spec.get("tests") or []:
75
+ res = (t.get("results") or [{}])[-1]
76
+ status = res.get("status") or ("passed" if t.get("status") == "expected" else "failed")
77
+ step, msg = _failed_step(res.get("steps") or [])
78
+ if status != "passed" and not msg:
79
+ msg = ANSI.sub("", "\n".join(e.get("message", "") for e in res.get("errors") or []))[:1200] or None
80
+ out[cid] = {"status": "passed" if status == "passed" else "failed", "failed_step": step, "message": msg}
81
+ for i in ids:
82
+ out.setdefault(i, {"status": "failed", "failed_step": None, "message": "the dry run did not report this scenario"})
83
+ return out
84
+
85
+
86
+ def dry_run(state, svc, pod_id: int, drafts: list[dict]) -> None:
87
+ """Runs the staged drafts once on the pod (step runner, playwright.fusion.config.ts, 'drafts' project) and attaches
88
+ {status, failed_step, message, pod, at, simulated} to each draft. In a quick simulation (stub mode) nothing runs on
89
+ the pod: the result says so and is never presented as a pod result."""
90
+ run_id = state["run_id"]
91
+ mode = state.get("playwright_mode") or svc.cfg.playwright_mode
92
+ ids = [d["id"] for d in drafts]
93
+ host = _pod_host(svc, pod_id)
94
+ at = now_iso()
95
+ run_dir = svc.run_dir(run_id)
96
+ try:
97
+ cred_env: dict = {}
98
+ if mode == "live":
99
+ from ...platform.pods import PodRegistry
100
+ for m in sorted({d["module"] for d in drafts}):
101
+ cred_env.update(svc.vault.executor_env(m))
102
+ cred_env.update(PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).executor_env(pod_id) or {})
103
+ svc.db.add_event(run_id, "test_generator", "ai_scenarios",
104
+ {"message": f"dry run of {len(ids)} AI-written scenario(s) on {host if mode == 'live' else 'the simulation'}",
105
+ "scenarios": ", ".join(ids)})
106
+ res = pw.run_attempt(run_id=run_id, ids=ids, attempt=0, tag="-dryrun", mode=mode, out_file=run_dir / "ai-dry-run.json",
107
+ stub_knobs=state.get("stub_knobs"), drafts_dir=specs_dir(svc, run_id), cred_env=cred_env,
108
+ backend=svc.cfg.executor_backend, log_dir=run_dir, config="playwright.fusion.config.ts")
109
+ results = read_dry_run(Path(res["file"]), ids)
110
+ if res.get("run_dir"):
111
+ try: # the dry run's traces and screenshots go to the encrypted evidence store like any attempt's
112
+ svc.evidence.ingest_dir(run_id, -1, Path(res["run_dir"]), pw.attachments_by_case(Path(res["file"])))
113
+ except Exception as e: # noqa: BLE001
114
+ svc.audit.append("evidence.error", actor="system", run_id=run_id, summary=str(e)[:300])
115
+ except Exception as e: # noqa: BLE001 - a dry run that cannot start fails every draft, never the test run
116
+ results = {i: {"status": "failed", "failed_step": None, "message": f"the dry run could not run: {str(e)[:500]}"} for i in ids}
117
+ for d in drafts:
118
+ d["dry_run"] = {**results[d["id"]], "pod": host if mode == "live" else None, "at": at, "simulated": mode != "live"}
119
+ d["runnable"] = results[d["id"]]["status"] == "passed"
120
+
121
+
122
+ # ====================================================================== writing
123
+ def write_ai_scenarios(state, svc, library: list[dict]) -> dict:
124
+ """{"cases": [test cases for drafts whose dry run passed], "drafts": [every AI draft with its result]}; {} when the
125
+ run is not on a Fusion pod (silently) or no AI model is configured (with a note in the run's events)."""
126
+ run_id = state["run_id"]
127
+ pod_id = svc.fusion_pod_id(run_id)
128
+ if pod_id is None:
129
+ return {}
130
+ count = int(svc.cfg.fusion_ai_scenarios or 0)
131
+ if count <= 0:
132
+ return {}
133
+ if not svc.router.frontier_ready():
134
+ _note(svc, run_id, "No AI model is configured, so no new scenarios were written for this pod (Settings > AI models).")
135
+ return {}
136
+ from .research import scope_modules
137
+ areas = [m for m in scope_modules(state) if m in step_writer.AREA_SCREENS]
138
+ research = {r.get("module"): r for r in state.get("research") or []}
139
+ drafts: list[dict] = []
140
+ taken: set[str] = set()
141
+ example = step_writer.example_yaml()
142
+ for area in areas:
143
+ screens = [inv for inv in (step_writer.load_inventory(t) for t in step_writer.AREA_SCREENS[area]) if inv]
144
+ if not screens:
145
+ _note(svc, run_id, f"{area}: no captured screens, so no new scenarios were written.", module=area)
146
+ continue
147
+ changes = (research.get(area) or {}).get("changes") or step_writer.area_changes(svc, area)
148
+ titles = [c["title"] for c in library if c.get("module") == area and c.get("title")]
149
+ try:
150
+ intents = step_writer.design_scenarios(svc, area, step_writer.area_processes(area), changes, screens, count=count,
151
+ run_id=run_id, existing_titles=titles)
152
+ except Exception as e: # noqa: BLE001
153
+ _note(svc, run_id, f"{area}: the AI model could not design new scenarios ({type(e).__name__}).", module=area)
154
+ continue
155
+ intents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value)]
156
+ if not intents:
157
+ _note(svc, run_id, f"{area}: the AI model gave no new scenario this time.", module=area)
158
+ continue
159
+ by_task = {step_writer.norm_task(s["task"]): s for s in screens}
160
+ for it in intents:
161
+ r = step_writer.write_steps(svc, it, by_task[step_writer.norm_task(it["task"])], example, run_id=run_id)
162
+ base = {"title": it["title"], "module": area, "priority": it.get("priority") or "P2", "type": it.get("type"),
163
+ "why": it.get("why") or "", "task": it["task"], "model": r.get("model") or it.get("model"),
164
+ "written_by": "AI model", "attempts": r.get("attempts")}
165
+ if not r["ok"]:
166
+ drafts.append({**base, "id": None, "status": "not written", "runnable": False, "problems": r["problems"][:10],
167
+ "dry_run": None, "steps": []})
168
+ continue
169
+ cid = step_writer.next_case_id(svc, area, taken)
170
+ taken.add(cid)
171
+ text = step_writer.to_case_yaml(it, r["steps"], cid, "model", area)
172
+ yp = step_writer.save_draft(svc, cid, text, batch=run_id)
173
+ sd = specs_dir(svc, run_id)
174
+ sd.mkdir(parents=True, exist_ok=True)
175
+ spec = sd / f"{cid}.spec.ts"
176
+ spec.write_text(step_writer.staged_entry_spec(cid, base["priority"], yp.parent), encoding="utf-8")
177
+ doc = yaml.safe_load(text)
178
+ drafts.append({**base, "id": cid, "status": "staged", "yaml_path": str(yp), "spec_path": str(spec), "problems": [],
179
+ "process": doc.get("process"), "steps": doc.get("steps") or [],
180
+ "test_values": doc.get("test_values") or {}, "expected_result": doc.get("expected_result")})
181
+ staged = [d for d in drafts if d["id"]]
182
+ if staged:
183
+ dry_run(state, svc, pod_id, staged)
184
+ passed = [d for d in staged if d.get("runnable")]
185
+ if drafts:
186
+ _note(svc, run_id, f"The AI model wrote {len(staged)} new scenario(s); {len(passed)} passed the dry run"
187
+ + (f", {len(staged) - len(passed)} failed it" if len(staged) > len(passed) else "")
188
+ + (f"; {len(drafts) - len(staged)} could not be written correctly" if len(drafts) > len(staged) else "") + ".",
189
+ written=len(staged), passed=len(passed))
190
+ cases = [{"id": d["id"], "title": d["title"], "module": d["module"], "process": d.get("process") or "", "priority": d["priority"],
191
+ "new_or_changed": True, "changed_by_patch": False, "origin": AI_ORIGIN, "yaml_path": d["yaml_path"], "map_ids": [],
192
+ "data_recipes": [], "learned": {"recent_failures": 0, "last_label": None}, "already_approved": False} for d in passed]
193
+ return {"cases": cases, "drafts": drafts}
194
+
195
+
196
+ # ====================================================================== approval gate
197
+ def plain_steps(steps: list[dict], test_values: dict | None = None) -> list[dict]:
198
+ from ...platform.readiness import plain_fusion_step
199
+ return [{"n": s.get("n", i + 1), "action": s.get("action"), "field": s.get("field") or (", ".join(s.get("fields") or []) or None),
200
+ "value": None if s.get("value") is None else str(s.get("value")), "expected": s.get("expected"),
201
+ "text": plain_fusion_step(s, test_values)} for i, s in enumerate(steps or [])]
202
+
203
+
204
+ def gate_view(d: dict) -> dict:
205
+ """What the consultant sees about one AI draft at the approval gate."""
206
+ return {"id": d.get("id"), "title": d["title"], "module": d["module"], "priority": d["priority"], "written_by": "AI model",
207
+ "model": d.get("model"), "why": d.get("why"), "status": d.get("status"), "runnable": bool(d.get("runnable")),
208
+ "dry_run": d.get("dry_run"), "problems": d.get("problems") or [], "steps": plain_steps(d.get("steps") or [], d.get("test_values")),
209
+ "expected_result": d.get("expected_result")}
210
+
211
+
212
+ def _gen_entry_specs(root: Path) -> tuple[bool, str]:
213
+ cmd = ["node", str(ROOT / "automation" / "scripts" / "gen-fusion-steps.js"), "--cases", str(root / "tests" / "cases"),
214
+ "--out", str(root / "automation" / "tests" / "fusion" / "steps")]
215
+ p = subprocess.run(cmd, cwd=str(ROOT / "automation"), capture_output=True, text=True, encoding="utf-8", errors="replace",
216
+ timeout=120, **procs.popen_kwargs())
217
+ return p.returncode == 0, (p.stdout + p.stderr)[-1000:]
218
+
219
+
220
+ def approve_drafts(state, svc, approved: list[str], actor: str) -> dict:
221
+ """Approved AI drafts: approval + verification lines set, then (case write-back on) promoted into the script library
222
+ and committed; with write-back off they stay in staging, approved, and run from there. Returns {ai_drafts, cases}."""
223
+ run_id = state["run_id"]
224
+ drafts = [dict(d) for d in state.get("ai_drafts") or []]
225
+ date = datetime.now(timezone.utc).strftime("%Y-%m-%d")
226
+ root = Path(PROMOTE_ROOT)
227
+ paths_to_commit: list[Path] = []
228
+ moved: dict[str, str] = {}
229
+ for d in drafts:
230
+ if d.get("id") not in approved or not d.get("runnable"):
231
+ continue
232
+ dr = d.get("dry_run") or {}
233
+ verification = (f"dry run passed on {dr.get('pod')} {date}" if not dr.get("simulated")
234
+ else f"dry run simulated (quick simulation, no browser, not on a pod) {date}")
235
+ src = Path(d["yaml_path"])
236
+ text = step_writer.approved_yaml(src.read_text(encoding="utf-8"), f"approved by {actor} on {date}", verification)
237
+ d.update(status="approved", approved_by=actor, approved_at=date, verification=verification)
238
+ if not svc.cfg.case_writeback:
239
+ src.write_text(text, encoding="utf-8")
240
+ continue
241
+ dst = root / "tests" / "cases" / f"{d['id']}.yaml"
242
+ if dst.exists():
243
+ d.update(status="approved (kept in staging)", note=f"{dst.name} already exists in the library")
244
+ src.write_text(text, encoding="utf-8")
245
+ continue
246
+ dst.parent.mkdir(parents=True, exist_ok=True)
247
+ dst.write_text(text, encoding="utf-8", newline="")
248
+ ok, log = _gen_entry_specs(root)
249
+ spec = root / "automation" / "tests" / "fusion" / "steps" / f"{d['id']}.spec.ts"
250
+ if not ok or not spec.exists():
251
+ dst.unlink(missing_ok=True)
252
+ src.write_text(text, encoding="utf-8")
253
+ d.update(status="approved (kept in staging)", note=f"entry spec not generated: {log[-300:]}")
254
+ continue
255
+ Path(d["spec_path"]).unlink(missing_ok=True) # the library entry replaces the staged one (never both)
256
+ d.update(status="promoted", yaml_path=dst.relative_to(root).as_posix() if root == ROOT else str(dst), spec_path=str(spec))
257
+ moved[d["id"]] = d["yaml_path"]
258
+ paths_to_commit += [dst, spec]
259
+ commit = None
260
+ if paths_to_commit and svc.library.exists():
261
+ try:
262
+ commit = svc.library.commit(paths_to_commit, f"add {len(moved)} AI-written scenario(s) approved in run {run_id}: "
263
+ + ", ".join(sorted(moved)), actor)
264
+ except Exception as e: # noqa: BLE001
265
+ svc.audit.append("library.error", actor="system", run_id=run_id, summary=str(e)[:300])
266
+ for d in drafts:
267
+ if d.get("id") in moved:
268
+ d["library_commit"] = commit
269
+ svc.audit.append("ai_scenario.promoted", actor=actor, run_id=run_id, node="approval_gate", summary=d["id"],
270
+ payload={"case_id": d["id"], "yaml": d["yaml_path"], "commit": commit})
271
+ elif d.get("id") and d.get("runnable") and d["id"] not in approved and d.get("status") == "staged":
272
+ d["status"] = "rejected (kept in staging)"
273
+ cases = [{**c, "yaml_path": moved.get(c["id"], c.get("yaml_path")), "already_approved": c["id"] in approved}
274
+ if c.get("origin") == AI_ORIGIN else c for c in state.get("test_cases") or []]
275
+ return {"ai_drafts": drafts, "test_cases": cases, "commit": commit}
coworker/graph/nodes/design.py CHANGED
@@ -19,6 +19,7 @@ from ...llm.base import LLMRequest, Sensitivity
19
  from ...llm.schemas import CaseProposals, ScriptDraft
20
  from ...platform import procs
21
  from ...platform.rundb import now_iso
 
22
  from .research import scope_modules
23
 
24
  AUTOMATION = ROOT / "automation"
@@ -100,14 +101,22 @@ def test_generator(state, config, svc) -> dict:
100
  slim = [{k: c[k] for k in ("id", "title", "module", "process", "priority", "new_or_changed", "changed_by_patch", "origin",
101
  "yaml_path", "map_ids", "data_recipes", "learned")} | {"already_approved": c.get("already_approved", False)}
102
  for c in keep]
103
- return {"test_cases": slim + gen_cases, "deferred": deferred, "proposed_cases": proposals,
104
- "approvals": {"pulled_in_changed_by_patch": pulled}, "llm_calls": [resp.record]}
 
 
 
 
 
105
 
106
 
107
  # ====================================================================== approval_gate
108
  def _diff_for(svc, c: dict, proposals: dict) -> str | None:
109
  if c["origin"] == "generated":
110
  return yaml.safe_dump(proposals.get(c["id"], {}), sort_keys=False)
 
 
 
111
  if c.get("yaml_path"):
112
  try:
113
  d = svc.library.diff_worktree(ROOT / c["yaml_path"]) if svc.library.exists() else ""
@@ -130,10 +139,10 @@ def approval_prepare(state, svc) -> tuple[dict | None, dict | None]:
130
  run_id = state["run_id"]
131
  cases = state.get("test_cases") or []
132
  proposals = {p["id"]: p for p in state.get("proposed_cases") or []}
133
- need = [c for c in cases if c["new_or_changed"] or c["origin"] == "generated" or c.get("changed_by_patch")]
134
  auto: list[str] = []
135
- for m in sorted({c["module"] for c in need}):
136
- auto += svc.autonomy.auto_approvals(m, [c for c in need if c["module"] == m])
137
  pending = [c for c in need if c["id"] not in auto]
138
  levels = {m: svc.autonomy.level(m) for m in sorted({c["module"] for c in cases})}
139
  policy = max(levels.values(), default="L0")
@@ -142,11 +151,17 @@ def approval_prepare(state, svc) -> tuple[dict | None, dict | None]:
142
  svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid, "decision": "approved",
143
  "actor": "autonomy", "ts": now_iso(), "auto": 1}, ('run_id', 'gate', 'case_id'))
144
  return None, {"approvals": {"cases": {"auto": auto or "no new, changed or generated cases", "policy": policy}}}
 
145
  payload = {"gate": "approve_cases", "policy": policy, "levels": levels, "auto_approved": auto,
146
  "pending": [{"id": c["id"], "title": c["title"], "module": c["module"], "priority": c["priority"],
147
  "origin": c["origin"], "changed_by_patch": c.get("changed_by_patch", False),
148
  "new_or_changed": c["new_or_changed"], "yaml_path": c.get("yaml_path") or None,
149
- "diff": _diff_for(svc, c, proposals)} for c in pending]}
 
 
 
 
 
150
  return payload, None
151
 
152
 
@@ -201,18 +216,29 @@ def approval_apply(state, svc, payload: dict, answer) -> dict:
201
  d["approval_status"] = f"approved {date} by {actor} (run {run_id}) - generated draft, not yet promoted"
202
  (pdir / f"{cid}.yaml").write_text("# Generated draft (co-worker). UNVERIFIED. Mock app, not Oracle Fusion.\n"
203
  + yaml.safe_dump(d, sort_keys=False), encoding="utf-8")
 
 
 
 
204
  keep = [c for c in cases if c["id"] not in rejected]
205
  deferred = list(state.get("deferred") or []) + [{"id": i, "priority": by_id[i]["priority"], "reason": "rejected at approval gate"}
206
  for i in rejected]
207
- return {"test_cases": keep, "deferred": deferred,
208
- "approvals": {"cases": {"approved": approved, "rejected": rejected, "auto": auto, "comments": comments,
209
- "actor": actor, "policy": policy, "library_commit": commit}}}
 
 
 
 
210
 
211
 
212
  # ====================================================================== script_builder
213
  def existing_spec(case_id: str) -> Path | None:
 
214
  for p in SPEC_DIR.rglob(f"{case_id}.spec.ts"):
215
  return p
 
 
216
  return None
217
 
218
 
@@ -343,7 +369,14 @@ def script_builder(state, config, svc) -> dict:
343
  proposals = {p["id"]: p for p in state.get("proposed_cases") or []}
344
  scripts: dict = {}
345
  to_build = []
 
346
  for c in state.get("test_cases") or []:
 
 
 
 
 
 
347
  sp = existing_spec(c["id"])
348
  if sp:
349
  scripts[c["id"]] = {"case_id": c["id"], "path": sp.relative_to(ROOT).as_posix(), "status": "existing",
 
19
  from ...llm.schemas import CaseProposals, ScriptDraft
20
  from ...platform import procs
21
  from ...platform.rundb import now_iso
22
+ from . import ai_scenarios
23
  from .research import scope_modules
24
 
25
  AUTOMATION = ROOT / "automation"
 
101
  slim = [{k: c[k] for k in ("id", "title", "module", "process", "priority", "new_or_changed", "changed_by_patch", "origin",
102
  "yaml_path", "map_ids", "data_recipes", "learned")} | {"already_approved": c.get("already_approved", False)}
103
  for c in keep]
104
+ # Fusion pods with an AI model on: new scenarios written by the model, dry-run on the pod before the gate
105
+ ai = ai_scenarios.write_ai_scenarios(state, svc, case_lib.load_cases(mods) if only and mods else library)
106
+ out = {"test_cases": slim + gen_cases + ai.get("cases", []), "deferred": deferred, "proposed_cases": proposals,
107
+ "approvals": {"pulled_in_changed_by_patch": pulled}, "llm_calls": [resp.record]}
108
+ if ai:
109
+ out["ai_drafts"] = ai["drafts"]
110
+ return out
111
 
112
 
113
  # ====================================================================== approval_gate
114
  def _diff_for(svc, c: dict, proposals: dict) -> str | None:
115
  if c["origin"] == "generated":
116
  return yaml.safe_dump(proposals.get(c["id"], {}), sort_keys=False)
117
+ if c["origin"] == ai_scenarios.AI_ORIGIN: # the draft's YAML as the model wrote it
118
+ p = Path(c.get("yaml_path") or "")
119
+ return p.read_text(encoding="utf-8") if p.is_file() else None
120
  if c.get("yaml_path"):
121
  try:
122
  d = svc.library.diff_worktree(ROOT / c["yaml_path"]) if svc.library.exists() else ""
 
139
  run_id = state["run_id"]
140
  cases = state.get("test_cases") or []
141
  proposals = {p["id"]: p for p in state.get("proposed_cases") or []}
142
+ need = [c for c in cases if c["new_or_changed"] or c["origin"] in ("generated", ai_scenarios.AI_ORIGIN) or c.get("changed_by_patch")]
143
  auto: list[str] = []
144
+ for m in sorted({c["module"] for c in need}): # scenarios written by the AI model always wait for a person
145
+ auto += svc.autonomy.auto_approvals(m, [c for c in need if c["module"] == m and c["origin"] != ai_scenarios.AI_ORIGIN])
146
  pending = [c for c in need if c["id"] not in auto]
147
  levels = {m: svc.autonomy.level(m) for m in sorted({c["module"] for c in cases})}
148
  policy = max(levels.values(), default="L0")
 
151
  svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid, "decision": "approved",
152
  "actor": "autonomy", "ts": now_iso(), "auto": 1}, ('run_id', 'gate', 'case_id'))
153
  return None, {"approvals": {"cases": {"auto": auto or "no new, changed or generated cases", "policy": policy}}}
154
+ ai = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}
155
  payload = {"gate": "approve_cases", "policy": policy, "levels": levels, "auto_approved": auto,
156
  "pending": [{"id": c["id"], "title": c["title"], "module": c["module"], "priority": c["priority"],
157
  "origin": c["origin"], "changed_by_patch": c.get("changed_by_patch", False),
158
  "new_or_changed": c["new_or_changed"], "yaml_path": c.get("yaml_path") or None,
159
+ "diff": _diff_for(svc, c, proposals)}
160
+ | ({"ai": ai_scenarios.gate_view(ai[c["id"]])} if c["origin"] == ai_scenarios.AI_ORIGIN and c["id"] in ai else {})
161
+ for c in pending]}
162
+ not_runnable = [ai_scenarios.gate_view(d) for d in state.get("ai_drafts") or [] if not d.get("runnable")]
163
+ if not_runnable: # written by the model but failed the dry run (or the checks): shown with the failure, not offered
164
+ payload["ai_not_runnable"] = not_runnable
165
  return payload, None
166
 
167
 
 
216
  d["approval_status"] = f"approved {date} by {actor} (run {run_id}) - generated draft, not yet promoted"
217
  (pdir / f"{cid}.yaml").write_text("# Generated draft (co-worker). UNVERIFIED. Mock app, not Oracle Fusion.\n"
218
  + yaml.safe_dump(d, sort_keys=False), encoding="utf-8")
219
+ ai_upd: dict = {}
220
+ if state.get("ai_drafts"): # approved AI drafts join the script library; rejected ones stay in staging
221
+ ai_upd = ai_scenarios.approve_drafts(state, svc, [i for i in approved if by_id.get(i, {}).get("origin") == ai_scenarios.AI_ORIGIN], actor)
222
+ cases = ai_upd["test_cases"]
223
  keep = [c for c in cases if c["id"] not in rejected]
224
  deferred = list(state.get("deferred") or []) + [{"id": i, "priority": by_id[i]["priority"], "reason": "rejected at approval gate"}
225
  for i in rejected]
226
+ out = {"test_cases": keep, "deferred": deferred,
227
+ "approvals": {"cases": {"approved": approved, "rejected": rejected, "auto": auto, "comments": comments,
228
+ "actor": actor, "policy": policy, "library_commit": commit}}}
229
+ if ai_upd:
230
+ out["ai_drafts"] = ai_upd["ai_drafts"]
231
+ out["approvals"]["cases"]["ai_library_commit"] = ai_upd["commit"]
232
+ return out
233
 
234
 
235
  # ====================================================================== script_builder
236
  def existing_spec(case_id: str) -> Path | None:
237
+ """The case's spec in the script library: practice cases (tests/cases), smoke, and real-Fusion ones (tests/fusion)."""
238
  for p in SPEC_DIR.rglob(f"{case_id}.spec.ts"):
239
  return p
240
+ for p in (AUTOMATION / "tests" / "fusion").rglob(f"{case_id}.spec.ts"):
241
+ return p
242
  return None
243
 
244
 
 
369
  proposals = {p["id"]: p for p in state.get("proposed_cases") or []}
370
  scripts: dict = {}
371
  to_build = []
372
+ ai = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}
373
  for c in state.get("test_cases") or []:
374
+ if c["origin"] == ai_scenarios.AI_ORIGIN: # written by the model, dry-run on the pod, approved at the gate
375
+ d = ai.get(c["id"], {})
376
+ sp = Path(d.get("spec_path") or "")
377
+ scripts[c["id"]] = {"case_id": c["id"], "path": str(sp), "status": "existing" if d.get("status") == "promoted" else "generated",
378
+ "lint_ok": None, "dry_run_ok": bool(d.get("runnable")) and sp.is_file(), "draft_id": None}
379
+ continue
380
  sp = existing_spec(c["id"])
381
  if sp:
382
  scripts[c["id"]] = {"case_id": c["id"], "path": sp.relative_to(ROOT).as_posix(), "status": "existing",
coworker/llm/prompts/design_scenarios.md CHANGED
@@ -21,4 +21,6 @@ Rules:
21
  - Prefer scenarios that touch what the patch changed; say which change in `why` (one sentence). P1 = core flow a
22
  business cannot work without, P2 = important variant, P3 = edge case.
23
  - Titles are short, specific and in plain business language. No ids, names, amounts or URLs that are not in the input.
 
 
24
  - Return exactly the number of scenarios asked for in `count` (fewer only if the screen does not allow that many distinct ones).
 
21
  - Prefer scenarios that touch what the patch changed; say which change in `why` (one sentence). P1 = core flow a
22
  business cannot work without, P2 = important variant, P3 = edge case.
23
  - Titles are short, specific and in plain business language. No ids, names, amounts or URLs that are not in the input.
24
+ - When the input has `existing_scenarios_do_not_repeat`, those scenarios already exist: every scenario you propose must
25
+ check something DIFFERENT from all of them (not the same flow with other words). Never return one of those titles.
26
  - Return exactly the number of scenarios asked for in `count` (fewer only if the screen does not allow that many distinct ones).
coworker/llm/router.py CHANGED
@@ -67,6 +67,15 @@ class LLMRouter:
67
  def _frontier_on(self) -> bool:
68
  return (self.cfg.llm_frontier != "off" and self.frontier is not None and self.frontier.available())
69
 
 
 
 
 
 
 
 
 
 
70
  def _local_on(self) -> bool:
71
  return self.cfg.llm_local == "ollama" and self.local is not None and self.local.available()
72
 
 
67
  def _frontier_on(self) -> bool:
68
  return (self.cfg.llm_frontier != "off" and self.frontier is not None and self.frontier.available())
69
 
70
+ def frontier_ready(self) -> bool:
71
+ """The external AI model is switched on and configured (after picking up settings saved in the app)."""
72
+ if self.before_call:
73
+ try:
74
+ self.before_call()
75
+ except Exception: # noqa: BLE001
76
+ pass
77
+ return self._frontier_on()
78
+
79
  def _local_on(self) -> bool:
80
  return self.cfg.llm_local == "ollama" and self.local is not None and self.local.available()
81
 
coworker/platform/readiness.py CHANGED
@@ -12,6 +12,7 @@ from __future__ import annotations
12
 
13
  import json
14
  import re
 
15
 
16
  from ..adapters import coverage_maps
17
  from ..adapters.cases import find_yaml, load_cases, load_doc
@@ -207,6 +208,49 @@ def _human(v) -> str:
207
  return _PH.sub(rep, str(v)) if v is not None else ""
208
 
209
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
210
  def plain_step(st: dict) -> str:
211
  act = str(st.get("action", "")).lower()
212
  tgt = st.get("target") or {}
@@ -237,8 +281,10 @@ def _data_values(outputs: dict, limit: int = 8) -> dict[str, str]:
237
  return out
238
 
239
 
240
- def scenario_detail(case_id: str, steps: list[dict] | None = None, state: dict | None = None) -> dict | None:
241
- p = find_yaml(case_id)
 
 
242
  if not p:
243
  return None
244
  d = load_doc(p) or {}
@@ -268,7 +314,9 @@ def scenario_detail(case_id: str, steps: list[dict] | None = None, state: dict |
268
  return {"id": case_id, "title": d.get("title"), "module": module, "process": d.get("process"),
269
  "step": st["name"] if st else None, "priority": pr, "priority_words": PRIORITY_WORDS.get(pr, "Unrated"),
270
  "roles": [str(r) for r in d.get("roles") or []], "preconditions": [str(x) for x in d.get("preconditions") or []],
271
- "steps": [{"n": s.get("n", i + 1), "text": plain_step(s), "expected": _human(s.get("expected"))}
 
 
272
  for i, s in enumerate(d.get("steps") or [])],
273
  "expected_result": _human(d.get("expected_result")), "test_data": data, "why": why,
274
  "verification": d.get("verification") or "UNVERIFIED", "map_ids": case["map_ids"],
 
12
 
13
  import json
14
  import re
15
+ from pathlib import Path
16
 
17
  from ..adapters import coverage_maps
18
  from ..adapters.cases import find_yaml, load_cases, load_doc
 
208
  return _PH.sub(rep, str(v)) if v is not None else ""
209
 
210
 
211
+ _FPH = re.compile(r"\{\{\s*([^{}]+?)\s*\}\}")
212
+
213
+
214
+ def _fusion_value(v, test_values: dict | None = None) -> str:
215
+ """A steps-runner value in words: {{pod.ap.supplier}} -> the pod's test supplier, {{unique:AP}} -> a new number."""
216
+ def rep(m):
217
+ k = m.group(1)
218
+ if k.startswith("pod."):
219
+ return "the pod's test " + k.split(".")[-1].replace("_", " ")
220
+ if k == "today":
221
+ return "today's date"
222
+ if k.startswith("unique:"):
223
+ return "a new unique number"
224
+ if k.startswith("tv."):
225
+ tv = (test_values or {}).get(k[3:])
226
+ return str(tv) if tv is not None else k[3:].replace("_", " ")
227
+ if k.startswith("saved."):
228
+ return "the remembered " + k[6:].replace("_", " ")
229
+ return k
230
+ return _FPH.sub(rep, str(v)) if v is not None else ""
231
+
232
+
233
+ def plain_fusion_step(st: dict, test_values: dict | None = None) -> str:
234
+ """One step of a Fusion steps scenario (runner: steps) as a consultant would say it."""
235
+ a = str(st.get("action", ""))
236
+ f = st.get("field")
237
+ v = _fusion_value(st.get("value"), test_values)
238
+ fields = ", ".join(st.get("fields") or ([f] if f else []))
239
+ return {"sign_in": "Sign in as the test user",
240
+ "open_task": f"Open {v}",
241
+ "enter": f"Enter {v} in {f}",
242
+ "expect_filled": f"Check that Fusion fills in {fields} by itself",
243
+ "expect_value": f"Check that {f} shows {v!r}" if v else f"Check that {f} is empty",
244
+ "remember": f"Note the value of {f}",
245
+ "click": f"Click {v!r}",
246
+ "confirm_if_asked": "Confirm if Fusion asks",
247
+ "cancel_without_saving": "Cancel without saving",
248
+ "add_line": f"Add an invoice line of {v} with the pod's test distribution account",
249
+ "save": "Save",
250
+ "invoice_action": f"Choose {v!r} in Invoice Actions",
251
+ "expect_status": f"Check that the status is {v!r}"}.get(a, f"{a.replace('_', ' ').capitalize()} {f or ''} {v}".strip())
252
+
253
+
254
  def plain_step(st: dict) -> str:
255
  act = str(st.get("action", "")).lower()
256
  tgt = st.get("target") or {}
 
281
  return out
282
 
283
 
284
+ def scenario_detail(case_id: str, steps: list[dict] | None = None, state: dict | None = None,
285
+ path: Path | str | None = None) -> dict | None:
286
+ """`path`: the scenario's YAML when it is not in the library yet (a staged AI draft)."""
287
+ p = Path(path) if path and Path(path).is_file() else find_yaml(case_id)
288
  if not p:
289
  return None
290
  d = load_doc(p) or {}
 
314
  return {"id": case_id, "title": d.get("title"), "module": module, "process": d.get("process"),
315
  "step": st["name"] if st else None, "priority": pr, "priority_words": PRIORITY_WORDS.get(pr, "Unrated"),
316
  "roles": [str(r) for r in d.get("roles") or []], "preconditions": [str(x) for x in d.get("preconditions") or []],
317
+ "steps": [{"n": s.get("n", i + 1),
318
+ "text": plain_fusion_step(s, d.get("test_values")) if d.get("runner") == "steps" else plain_step(s),
319
+ "expected": _human(s.get("expected"))}
320
  for i, s in enumerate(d.get("steps") or [])],
321
  "expected_result": _human(d.get("expected_result")), "test_data": data, "why": why,
322
  "verification": d.get("verification") or "UNVERIFIED", "map_ids": case["map_ids"],
coworker/platform/step_writer.py CHANGED
@@ -227,10 +227,18 @@ def _call(svc, prompt: str, payload: dict, schema, run_id: str | None):
227
  return svc.router.call(req)
228
 
229
 
 
 
 
 
 
 
 
230
  def design_scenarios(svc, area: str, processes: list[str], changes: list, screens: list[dict], count: int = 3,
231
- run_id: str | None = None) -> list[dict]:
232
  """Scenario intents {title, type, priority, why, task} for the given screens. Intents naming a task that is not one of
233
- the screens are dropped. Each intent carries `designed_by` (the route that answered)."""
 
234
  pub = [public_inventory(s) for s in screens]
235
  chg = []
236
  for c in changes or []:
@@ -241,13 +249,25 @@ def design_scenarios(svc, area: str, processes: list[str], changes: list, screen
241
  payload = {"area": area, "processes": [str(p) for p in processes or []], "patch_changes": chg, "count": int(count),
242
  "screens": [{k: s[k] for k in ("task", "fields", "line_fields", "buttons", "menus")} for s in pub],
243
  "allowed_actions": ALLOWED_ACTIONS}
244
- resp = _call(svc, "design_scenarios", payload, ScenarioIntents, run_id)
245
  tasks = {norm_task(s["task"]): s["task"] for s in pub}
246
- out = []
247
- for it in resp.output.scenarios: # type: ignore[attr-defined]
248
- t = tasks.get(norm_task(it.task))
249
- if t:
250
- out.append({**it.model_dump(), "task": t, "designed_by": resp.route.value, "model": resp.model})
 
 
 
 
 
 
 
 
 
 
 
 
251
  return out[: max(1, int(count))]
252
 
253
 
@@ -364,6 +384,42 @@ def save_draft(svc, case_id: str, text: str, batch: str | None = None) -> Path:
364
  return f
365
 
366
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
367
  def area_processes(area: str) -> list[str]:
368
  """Process names of the area's library cases (public names such as 'Invoice entry')."""
369
  out = []
 
227
  return svc.router.call(req)
228
 
229
 
230
+ def same_title(a: str, b: str) -> bool:
231
+ """Two scenario titles that say the same thing (case, punctuation and tiny wording differences ignored)."""
232
+ import difflib
233
+ na, nb = (re.sub(r"[^a-z0-9]+", " ", str(x).lower()).strip() for x in (a, b))
234
+ return na == nb or difflib.SequenceMatcher(None, na, nb).ratio() >= 0.9
235
+
236
+
237
  def design_scenarios(svc, area: str, processes: list[str], changes: list, screens: list[dict], count: int = 3,
238
+ run_id: str | None = None, existing_titles: list[str] | None = None) -> list[dict]:
239
  """Scenario intents {title, type, priority, why, task} for the given screens. Intents naming a task that is not one of
240
+ the screens are dropped. Each intent carries `designed_by` (the route that answered). With `existing_titles` (the
241
+ titles of the library's own scenarios, public), the model is asked for new ones and repeats are dropped."""
242
  pub = [public_inventory(s) for s in screens]
243
  chg = []
244
  for c in changes or []:
 
249
  payload = {"area": area, "processes": [str(p) for p in processes or []], "patch_changes": chg, "count": int(count),
250
  "screens": [{k: s[k] for k in ("task", "fields", "line_fields", "buttons", "menus")} for s in pub],
251
  "allowed_actions": ALLOWED_ACTIONS}
252
+ titles = [str(t) for t in existing_titles or [] if str(t).strip()]
253
  tasks = {norm_task(s["task"]): s["task"] for s in pub}
254
+ out: list[dict] = []
255
+ avoid = list(titles)
256
+ for _ask in range(3 if titles else 1): # models tend to repeat the obvious scenarios: ask again, naming the repeats
257
+ if titles:
258
+ payload["existing_scenarios_do_not_repeat"] = avoid
259
+ payload["count"] = int(count) + 2
260
+ resp = _call(svc, "design_scenarios", payload, ScenarioIntents, run_id)
261
+ for it in resp.output.scenarios: # type: ignore[attr-defined]
262
+ t = tasks.get(norm_task(it.task))
263
+ if not t or any(same_title(it.title, x) for x in avoid + [o["title"] for o in out]):
264
+ if t and it.title not in avoid:
265
+ avoid.append(it.title)
266
+ continue
267
+ out.append({**it.model_dump(), "task": t, "designed_by": resp.route.value, "model": resp.model,
268
+ "fallback_reason": resp.fallback_reason})
269
+ if len(out) >= int(count) or resp.route == Route.STUB:
270
+ break
271
  return out[: max(1, int(count))]
272
 
273
 
 
384
  return f
385
 
386
 
387
+ AUTOMATION = ROOT / "automation"
388
+ # the captured screens (tests/screens/<slug>.json) the model writes new scenarios for, per business area
389
+ AREA_SCREENS: dict[str, list[str]] = {"AP": ["Payables > Invoices > Create Invoice"]}
390
+
391
+
392
+ def entry_tags(case_id: str, priority: str | None) -> list[str]:
393
+ """The literal tags of a steps scenario's entry spec (same as automation/scripts/gen-fusion-steps.js)."""
394
+ return [f"@{case_id}", f"@{case_id.split('-', 1)[0]}", f"@{priority or 'P2'}"]
395
+
396
+
397
+ def staged_entry_spec(case_id: str, priority: str | None, yaml_dir: Path) -> str:
398
+ """Playwright entry point for a STAGED steps draft (dry run / run before promotion): it reads the YAML from the
399
+ staging folder. Promoted scenarios get the normal entry from gen-fusion-steps.js instead."""
400
+ steps_mod = (AUTOMATION / "src" / "fusion" / "steps").as_posix()
401
+ tags = ", ".join(f"'{t}'" for t in entry_tags(case_id, priority))
402
+ return (f"// STAGED AI draft {case_id} (YAML: {Path(yaml_dir).as_posix()}/{case_id}.yaml). Not in the script library until a\n"
403
+ f"// consultant approves it. Written by the co-worker; edit the YAML, not this file.\n"
404
+ f"import {{ stepsTest }} from {json.dumps(steps_mod)};\n\n"
405
+ f"stepsTest('{case_id}', [{tags}], {{ dir: {json.dumps(Path(yaml_dir).as_posix())} }});\n")
406
+
407
+
408
+ def _set_top_line(text: str, key: str, value: str) -> str:
409
+ line = f"{key}: {json.dumps(value, ensure_ascii=False)}"
410
+ pat = re.compile(rf"^{re.escape(key)}:.*$", re.M)
411
+ return pat.sub(lambda _m: line, text, count=1) if pat.search(text) else text.rstrip("\n") + "\n" + line + "\n"
412
+
413
+
414
+ def approved_yaml(text: str, approval: str, verification: str) -> str:
415
+ """The draft YAML with its approval and verification lines set (nothing else changes but the draft header)."""
416
+ out = _set_top_line(_set_top_line(text, "approval_status", approval), "verification", verification)
417
+ out = re.sub(r"^# Draft: .*$", "# Approved by a consultant after its dry run; now part of the script library.", out, count=1, flags=re.M)
418
+ d = yaml.safe_load(out)
419
+ assert d["approval_status"] == approval and d["verification"] == verification
420
+ return out
421
+
422
+
423
  def area_processes(area: str) -> list[str]:
424
  """Process names of the area's library cases (public names such as 'Invoice entry')."""
425
  out = []
coworker/state.py CHANGED
@@ -106,7 +106,7 @@ class TestCase(TypedDict, total=False):
106
  priority: Priority
107
  new_or_changed: bool
108
  changed_by_patch: bool
109
- origin: Literal["library", "generated"]
110
  yaml_path: str
111
  map_ids: list[str]
112
  data_recipes: list[str]
@@ -220,6 +220,7 @@ class CoworkerState(TypedDict, total=False):
220
  test_cases: list[TestCase]
221
  deferred: list[DeferredCase]
222
  proposed_cases: list[dict]
 
223
  approvals: Annotated[dict, merge_dict]
224
  scripts: dict[str, ScriptRef]
225
  # 3 data
 
106
  priority: Priority
107
  new_or_changed: bool
108
  changed_by_patch: bool
109
+ origin: Literal["library", "generated", "ai"]
110
  yaml_path: str
111
  map_ids: list[str]
112
  data_recipes: list[str]
 
220
  test_cases: list[TestCase]
221
  deferred: list[DeferredCase]
222
  proposed_cases: list[dict]
223
+ ai_drafts: list[dict] # Fusion pods: scenarios written by the AI model, with their dry-run result
224
  approvals: Annotated[dict, merge_dict]
225
  scripts: dict[str, ScriptRef]
226
  # 3 data
coworker/tests/test_ai_scenarios.py ADDED
@@ -0,0 +1,167 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """AI-written scenarios on a Fusion pod: with the AI model on, the design phase writes new scenarios from the captured
2
+ screens, dry-runs them (here: the quick simulation, no browser, no network), shows them at the approval gate with their
3
+ steps and dry-run result, and approving promotes them into the script library; failing drafts are shown, not offered.
4
+ Model off, or the practice pod: nothing changes."""
5
+ from __future__ import annotations
6
+
7
+ import json
8
+ import shutil
9
+ import tempfile
10
+ import unittest
11
+ from datetime import datetime, timezone
12
+ from pathlib import Path
13
+ from unittest import mock
14
+
15
+ from coworker.graph.nodes import ai_scenarios
16
+ from coworker.tests.fakes import bearer, make_app
17
+
18
+ POD = {"name": "Client test pod", "kind": "fusion", "base_url": "https://acme-test.fa.ocs.oraclecloud.com", "environment": "test"}
19
+
20
+
21
+ class FakeLibrary:
22
+ def __init__(self):
23
+ self.commits: list[tuple[list[str], str, str]] = []
24
+
25
+ def exists(self) -> bool:
26
+ return True
27
+
28
+ def diff_worktree(self, path) -> str:
29
+ return ""
30
+
31
+ def commit(self, paths, message, author) -> str:
32
+ self.commits.append(([Path(p).as_posix() for p in paths], message, author))
33
+ return "f" * 40
34
+
35
+
36
+ def fusion_app(**over):
37
+ app, c, svc, pod = make_app(**over)
38
+ h = {r: bearer(c, r) for r in ("viewer", "consultant", "admin")}
39
+ p = c.post("/api/pods", json=POD, headers=h["admin"]).json()
40
+ c.post(f"/api/pods/{p['id']}/credentials", json={"module": "AP", "username": "zz.ap", "password": "S3cret-x!"}, headers=h["admin"])
41
+ return app, c, svc, h, p["id"]
42
+
43
+
44
+ def start(c, h, pod_id, **extra) -> str:
45
+ r = c.post("/api/runs", json={"modules": ["AP"], "playwright_mode": "stub", "pod_id": pod_id, **extra}, headers=h["consultant"])
46
+ assert r.status_code == 202, r.text
47
+ return r.json()["run_id"]
48
+
49
+
50
+ def events(svc, rid) -> list[dict]:
51
+ return svc.db.events(rid)
52
+
53
+
54
+ class TestModelOn(unittest.TestCase):
55
+ @classmethod
56
+ def setUpClass(cls):
57
+ cls.root = Path(tempfile.mkdtemp(prefix="fpt-promote-"))
58
+ cls.patch = mock.patch.object(ai_scenarios, "PROMOTE_ROOT", cls.root)
59
+ cls.patch.start()
60
+ cls.app, cls.c, cls.svc, cls.h, cls.pod_id = fusion_app(llm_frontier="stub", case_writeback=True)
61
+ cls.svc.library = FakeLibrary()
62
+ cls.rid = start(cls.c, cls.h, cls.pod_id, stub_knobs={"STUB_FAIL": "AP-FUS-102"})
63
+ cls.app.state.runs.drain()
64
+ cls.gate = cls.c.get(f"/api/runs/{cls.rid}/gate", headers=cls.h["viewer"]).json()
65
+
66
+ @classmethod
67
+ def tearDownClass(cls):
68
+ cls.patch.stop()
69
+ shutil.rmtree(cls.root, ignore_errors=True)
70
+
71
+ def test_1_drafts_written_dry_run_and_shown_at_the_gate(self):
72
+ g = self.gate
73
+ self.assertEqual(g["gate"], "approve_cases")
74
+ ai = [p for p in g["pending"] if p["origin"] == "ai"]
75
+ self.assertEqual([p["id"] for p in ai], ["AP-FUS-101"]) # the failing draft is not offered
76
+ a = ai[0]["ai"]
77
+ self.assertEqual(a["written_by"], "AI model")
78
+ self.assertTrue(a["runnable"])
79
+ self.assertEqual(a["dry_run"]["status"], "passed")
80
+ self.assertTrue(a["dry_run"]["simulated"]) # a simulation never claims a pod result
81
+ self.assertIsNone(a["dry_run"]["pod"])
82
+ self.assertEqual(a["steps"][0]["text"], "Sign in as the test user")
83
+ self.assertTrue(any(s["action"] == "enter" and s["field"] and s["value"] for s in a["steps"]))
84
+ self.assertIn("runner: steps", ai[0]["diff"])
85
+ bad = g["ai_not_runnable"]
86
+ self.assertEqual([b["id"] for b in bad], ["AP-FUS-102"])
87
+ self.assertEqual(bad[0]["dry_run"]["status"], "failed")
88
+ self.assertTrue(bad[0]["dry_run"]["message"])
89
+ self.assertFalse(bad[0]["runnable"])
90
+ staged = self.svc.cfg.path("staging", "steps", self.rid)
91
+ self.assertEqual(sorted(p.name for p in staged.glob("*.yaml")), ["AP-FUS-101.yaml", "AP-FUS-102.yaml"])
92
+ spec = (self.svc.cfg.path("staging", "specs", self.rid) / "AP-FUS-101.spec.ts").read_text(encoding="utf-8")
93
+ self.assertIn("stepsTest('AP-FUS-101', ['@AP-FUS-101', '@AP', ", spec)
94
+ self.assertIn("dir:", spec)
95
+ sc = self.c.get(f"/api/runs/{self.rid}/scenarios", headers=self.h["viewer"]).json()["scenarios"]
96
+ s101 = next(s for s in sc if s["id"] == "AP-FUS-101")
97
+ self.assertEqual(s101["written_by"], "AI model")
98
+ self.assertTrue(s101["steps"] and s101["why"][0].startswith("Written by the AI model"))
99
+ self.assertTrue(any(e["kind"] == "ai_scenarios" for e in events(self.svc, self.rid)))
100
+
101
+ def test_2_approval_promotes_and_the_scenario_runs(self):
102
+ ids = [p["id"] for p in self.gate["pending"]]
103
+ r = self.c.post(f"/api/runs/{self.rid}/gates/approve_cases", json={"approved": ["AP-FUS-101"],
104
+ "rejected": [i for i in ids if i != "AP-FUS-101"]}, headers=self.h["consultant"])
105
+ self.assertEqual(r.status_code, 200, r.text)
106
+ self.app.state.runs.drain()
107
+ y = self.root / "tests" / "cases" / "AP-FUS-101.yaml"
108
+ spec = self.root / "automation" / "tests" / "fusion" / "steps" / "AP-FUS-101.spec.ts"
109
+ today = datetime.now(timezone.utc).strftime("%Y-%m-%d")
110
+ import yaml
111
+ doc = yaml.safe_load(y.read_text(encoding="utf-8"))
112
+ self.assertEqual(doc["approval_status"], f"approved by consultant on {today}")
113
+ self.assertTrue(doc["verification"].startswith("dry run simulated"))
114
+ self.assertIn("stepsTest('AP-FUS-101',['@AP-FUS-101','@AP','@", spec.read_text(encoding="utf-8").replace(" ", ""))
115
+ paths, msg, author = self.svc.library.commits[-1]
116
+ self.assertEqual(author, "consultant")
117
+ self.assertTrue(any(p.endswith("tests/cases/AP-FUS-101.yaml") for p in paths) and any(p.endswith("AP-FUS-101.spec.ts") for p in paths))
118
+ self.assertFalse((self.svc.cfg.path("staging", "specs", self.rid) / "AP-FUS-101.spec.ts").exists()) # never both
119
+ self.assertTrue((self.svc.cfg.path("staging", "steps", self.rid) / "AP-FUS-102.yaml").exists()) # stays in staging
120
+ st = self.app.state.runs.state(self.rid)
121
+ self.assertEqual(st["run_results"]["outcomes"].get("AP-FUS-101"), "passed")
122
+ self.assertNotIn("AP-FUS-102", st["run_results"]["outcomes"])
123
+ self.assertEqual(next(d for d in st["ai_drafts"] if d["id"] == "AP-FUS-101")["status"], "promoted")
124
+ self.assertEqual(self.c.get(f"/api/runs/{self.rid}", headers=self.h["viewer"]).json()["status"], "completed")
125
+
126
+
127
+ class TestModelOffAndPracticePod(unittest.TestCase):
128
+ def test_model_off_fusion_run_unchanged_with_a_note(self):
129
+ app, c, svc, h, pod_id = fusion_app()
130
+ rid = start(c, h, pod_id)
131
+ app.state.runs.drain()
132
+ g = c.get(f"/api/runs/{rid}/gate", headers=h["viewer"]).json()
133
+ self.assertFalse([p for p in g["pending"] if p["origin"] == "ai"])
134
+ self.assertNotIn("ai_not_runnable", g)
135
+ self.assertFalse(app.state.runs.state(rid).get("ai_drafts"))
136
+ notes = [json.dumps(e["summary"]) for e in events(svc, rid) if e["kind"] == "ai_scenarios"]
137
+ self.assertTrue(any("No AI model is configured" in n for n in notes), notes)
138
+ self.assertFalse(svc.cfg.path("staging", "steps").exists() and any(svc.cfg.path("staging", "steps").rglob("*.yaml")))
139
+
140
+ def test_practice_pod_never_writes_ai_scenarios(self):
141
+ app, c, svc, pod = make_app(llm_frontier="stub")
142
+ h = bearer(c, "consultant")
143
+ r = c.post("/api/runs", json={"modules": ["P2P"], "playwright_mode": "stub"}, headers=h)
144
+ rid = r.json()["run_id"]
145
+ app.state.runs.drain()
146
+ self.assertFalse(app.state.runs.state(rid).get("ai_drafts"))
147
+ self.assertFalse([e for e in events(svc, rid) if e["kind"] == "ai_scenarios"])
148
+ app.state.runs.cancel(rid, "test")
149
+
150
+
151
+ class TestDryRunReport(unittest.TestCase):
152
+ def test_failing_step_and_message_from_a_live_report(self):
153
+ rep = {"suites": [{"specs": [{"title": "AP-FUS-103 x", "tags": ["@AP-FUS-103"], "tests": [{"status": "unexpected", "results": [{
154
+ "status": "failed", "errors": [{"message": "Timeout"}],
155
+ "steps": [{"title": "1. sign_in", "steps": []},
156
+ {"title": "2. enter Supplier = X (expect: ok)", "error": {"message": "\x1b[31mlocator not found\x1b[39m"}}]}]}]},
157
+ {"title": "AP-FUS-104 y", "tags": ["@AP-FUS-104"], "tests": [{"status": "expected", "results": [{"status": "passed", "steps": []}]}]}]}]}
158
+ f = Path(tempfile.mkdtemp()) / "r.json"
159
+ f.write_text(json.dumps(rep), encoding="utf-8")
160
+ out = ai_scenarios.read_dry_run(f, ["AP-FUS-103", "AP-FUS-104", "AP-FUS-105"])
161
+ self.assertEqual(out["AP-FUS-103"], {"status": "failed", "failed_step": "2. enter Supplier = X (expect: ok)", "message": "locator not found"})
162
+ self.assertEqual(out["AP-FUS-104"]["status"], "passed")
163
+ self.assertEqual(out["AP-FUS-105"]["status"], "failed")
164
+
165
+
166
+ if __name__ == "__main__":
167
+ unittest.main()
web/src/api/types.ts CHANGED
@@ -16,9 +16,14 @@ export interface ModuleInfo { module: string; pack_id: string; resources: string
16
  export interface PodProfile { about: { release: string; environment: string; is_mock: boolean; source: string } | null; modules: ModuleInfo[]; scanned_at?: string | null }
17
  export interface ResearchView { pod_profile: PodProfile | null; research: ModuleResearch[]; coverage_map: { patch_id: string; rows: CoverageRow[]; gaps: { module: string | null; row_id?: string; reason: string }[]; generated_by: string; note?: string } | null; research_modules: string[] }
18
 
19
- export interface TestCase { id: string; title: string; module: string; process: string; priority: Priority; new_or_changed: boolean; changed_by_patch: boolean; origin: 'library' | 'generated'; yaml_path: string; map_ids: string[]; data_recipes: string[] }
20
- export interface PendingCase { id: string; title: string; module: string; priority: Priority; origin: 'library' | 'generated'; changed_by_patch: boolean; new_or_changed: boolean; yaml_path: string | null; diff: string | null }
21
- export interface ApproveGate { gate: 'approve_cases'; pending: PendingCase[]; auto_approved: string[]; policy: string; levels?: Record<string, string> }
 
 
 
 
 
22
  export interface ReviewItem { case_id: string; ask: 'confirm' | 'owner'; category: string | null; confidence: number | null; evidence: string[] | null; similar: { run_id: string; case_id: string; category: string; human_label: string | null; similarity: number }[]; llm_hint?: { category: string; confidence: number; rationale: string; route: string; model: string } | null }
23
  export interface ReviewGate { gate: 'human_review'; items: ReviewItem[] }
24
  export type GatePayload = ApproveGate | ReviewGate;
@@ -62,7 +67,8 @@ export interface ReadinessView { pod_id?: number | null; patch_id?: string | nul
62
  export interface Scenario { id: string; title: string; module: string; process: string; step: string | null; priority: string;
63
  priority_words: string; roles: string[]; preconditions: string[]; steps: { n: number; text: string; expected: string }[];
64
  expected_result: string; test_data: { id: string; title: string; purpose: string; values: Record<string, string> }[]; why: string[];
65
- verification: string; map_ids: string[]; approval_status: string; origin?: string; pending?: boolean; outcome?: string | null }
 
66
  export interface Failure { case_id: string; title: string | null; step: string | null; outcome: string; priority?: string; priority_words?: string; expected: string | null; actual: string | null;
67
  category: string; suggestion: string; confidence: number; needs_review: boolean; ask: 'confirm' | 'owner' | null; pending: boolean;
68
  answer: Record<string, string> | null; screenshots: Evidence[]; evidence_text: string[] }
 
16
  export interface PodProfile { about: { release: string; environment: string; is_mock: boolean; source: string } | null; modules: ModuleInfo[]; scanned_at?: string | null }
17
  export interface ResearchView { pod_profile: PodProfile | null; research: ModuleResearch[]; coverage_map: { patch_id: string; rows: CoverageRow[]; gaps: { module: string | null; row_id?: string; reason: string }[]; generated_by: string; note?: string } | null; research_modules: string[] }
18
 
19
+ export interface TestCase { id: string; title: string; module: string; process: string; priority: Priority; new_or_changed: boolean; changed_by_patch: boolean; origin: 'library' | 'generated' | 'ai'; yaml_path: string; map_ids: string[]; data_recipes: string[] }
20
+ export interface DryRun { status: 'passed' | 'failed'; failed_step: string | null; message: string | null; pod: string | null; at: string; simulated: boolean }
21
+ /** A scenario written by the AI model for a Fusion pod (approval gate). */
22
+ export interface AiDraft { id: string | null; title: string; module: string; priority: string; written_by: string; model: string | null; why: string | null;
23
+ status: string; runnable: boolean; dry_run: DryRun | null; problems: string[];
24
+ steps: { n: number; action: string; field: string | null; value: string | null; expected: string | null; text: string }[]; expected_result: string | null }
25
+ export interface PendingCase { id: string; title: string; module: string; priority: Priority; origin: 'library' | 'generated' | 'ai'; changed_by_patch: boolean; new_or_changed: boolean; yaml_path: string | null; diff: string | null; ai?: AiDraft }
26
+ export interface ApproveGate { gate: 'approve_cases'; pending: PendingCase[]; auto_approved: string[]; policy: string; levels?: Record<string, string>; ai_not_runnable?: AiDraft[] }
27
  export interface ReviewItem { case_id: string; ask: 'confirm' | 'owner'; category: string | null; confidence: number | null; evidence: string[] | null; similar: { run_id: string; case_id: string; category: string; human_label: string | null; similarity: number }[]; llm_hint?: { category: string; confidence: number; rationale: string; route: string; model: string } | null }
28
  export interface ReviewGate { gate: 'human_review'; items: ReviewItem[] }
29
  export type GatePayload = ApproveGate | ReviewGate;
 
67
  export interface Scenario { id: string; title: string; module: string; process: string; step: string | null; priority: string;
68
  priority_words: string; roles: string[]; preconditions: string[]; steps: { n: number; text: string; expected: string }[];
69
  expected_result: string; test_data: { id: string; title: string; purpose: string; values: Record<string, string> }[]; why: string[];
70
+ verification: string; map_ids: string[]; approval_status: string; origin?: string; pending?: boolean; outcome?: string | null;
71
+ written_by?: string; dry_run?: DryRun | null }
72
  export interface Failure { case_id: string; title: string | null; step: string | null; outcome: string; priority?: string; priority_words?: string; expected: string | null; actual: string | null;
73
  category: string; suggestion: string; confidence: number; needs_review: boolean; ask: 'confirm' | 'owner' | null; pending: boolean;
74
  answer: Record<string, string> | null; screenshots: Evidence[]; evidence_text: string[] }
web/src/pages/RunGuide.tsx CHANGED
@@ -64,6 +64,8 @@ export function Approve({ r }: { r: Run }) {
64
  const g = gate.data?.gate === 'approve_cases' ? (gate.data as ApproveGate) : null;
65
  const ids = (g?.pending ?? []).map((p) => p.id);
66
  const changed = (g?.pending ?? []).filter((p) => p.changed_by_patch).length;
 
 
67
  return (
68
  <Stack gap="sm">
69
  <Text size="lg" fw={500}>{ids.length} scenario{ids.length === 1 ? '' : 's'} {ids.length === 1 ? 'is' : 'are'} ready to test</Text>
@@ -71,6 +73,12 @@ export function Approve({ r }: { r: Run }) {
71
  A scenario is one business check, for example “a requisition below the limit is approved by the first approver”.
72
  {changed > 0 ? ` ${changed} of them cover something this patch changes.` : ''} We recommend testing all of them.
73
  </Text>
 
 
 
 
 
 
74
  <ErrorAlert error={approve.error || gate.error} />
75
  <Can perm="gate.approve_cases" fallback={<Alert color="gray">Approving scenarios needs the consultant or admin role. You can still read them and download the test script.</Alert>}>
76
  <Group gap="sm" wrap="wrap">
 
64
  const g = gate.data?.gate === 'approve_cases' ? (gate.data as ApproveGate) : null;
65
  const ids = (g?.pending ?? []).map((p) => p.id);
66
  const changed = (g?.pending ?? []).filter((p) => p.changed_by_patch).length;
67
+ const byAi = (g?.pending ?? []).filter((p) => p.origin === 'ai').length;
68
+ const aiFailed = (g?.ai_not_runnable ?? []).length;
69
  return (
70
  <Stack gap="sm">
71
  <Text size="lg" fw={500}>{ids.length} scenario{ids.length === 1 ? '' : 's'} {ids.length === 1 ? 'is' : 'are'} ready to test</Text>
 
73
  A scenario is one business check, for example “a requisition below the limit is approved by the first approver”.
74
  {changed > 0 ? ` ${changed} of them cover something this patch changes.` : ''} We recommend testing all of them.
75
  </Text>
76
+ {(byAi > 0 || aiFailed > 0) && (
77
+ <Text size="sm" data-testid="guide-ai-count">
78
+ {byAi > 0 ? `${byAi} ${byAi === 1 ? 'is a new scenario' : 'are new scenarios'} written by the AI model that passed a dry run; read ${byAi === 1 ? 'it' : 'them'} before approving.` : ''}
79
+ {aiFailed > 0 ? ` ${aiFailed} more written by the AI model failed the dry run and ${aiFailed === 1 ? 'is' : 'are'} not offered.` : ''}
80
+ </Text>
81
+ )}
82
  <ErrorAlert error={approve.error || gate.error} />
83
  <Can perm="gate.approve_cases" fallback={<Alert color="gray">Approving scenarios needs the consultant or admin role. You can still read them and download the test script.</Alert>}>
84
  <Group gap="sm" wrap="wrap">
web/src/pages/ScenarioReview.tsx CHANGED
@@ -1,8 +1,8 @@
1
- import { Accordion, Alert, Button, Collapse, Group, Stack, Text, Textarea, UnstyledButton } from '@mantine/core';
2
  import { IconChevronDown, IconChevronRight, IconCode, IconUser } from '@tabler/icons-react';
3
  import { useMemo, useState } from 'react';
4
  import { useApproveCases, useCaseYaml, useGate, useRunScenarios } from '../api/hooks';
5
- import type { ApproveGate, PendingCase, Scenario } from '../api/types';
6
  import { Can, Diff, ErrorAlert, Pill, Pre, Term } from '../components/common';
7
  import { PRIORITY_WORDS } from '../glossary';
8
 
@@ -21,7 +21,7 @@ function TechnicalDetails({ p, id }: { p?: PendingCase; id: string }) {
21
  <Accordion.Item value="tech">
22
  <Accordion.Control icon={<IconCode size={14} />}><Text size="xs">Technical details (scenario file)</Text></Accordion.Control>
23
  <Accordion.Panel>
24
- {p?.diff && (p.origin === 'generated' ? <Pre maxHeight={300}>{p.diff}</Pre> : <Diff text={p.diff} />)}
25
  {yaml.data && <Pre maxHeight={300}>{yaml.data.yaml}</Pre>}
26
  <Text size="xs" c="dimmed" mt={4}>{id}{p ? ` · ${p.origin}` : ''}</Text>
27
  </Accordion.Panel>
@@ -30,6 +30,40 @@ function TechnicalDetails({ p, id }: { p?: PendingCase; id: string }) {
30
  );
31
  }
32
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
33
  /** One business scenario: a one-line row that expands to the plain-language steps. */
34
  export function ScenarioCard({ s, p, decision, onDecision, note, onNote, editable }: {
35
  s: Scenario; p?: PendingCase; decision?: Decision; onDecision?: (d: Decision) => void; note?: string; onNote?: (v: string) => void; editable: boolean;
@@ -46,6 +80,8 @@ export function ScenarioCard({ s, p, decision, onDecision, note, onNote, editabl
46
  <Text size="sm" truncate={open ? undefined : 'end'} style={{ minWidth: 0 }}>{s.title}</Text>
47
  <Pill tone={PRIO_TONE[s.priority_words] ?? 'neutral'}>{s.priority_words}</Pill>
48
  {s.origin === 'generated' && <Pill tone="lav">new</Pill>}
 
 
49
  {out && <Pill tone={out.tone}>{out.label}</Pill>}
50
  </Group>
51
  </UnstyledButton>
@@ -85,7 +121,23 @@ export function ScenarioCard({ s, p, decision, onDecision, note, onNote, editabl
85
  </div>
86
  )}
87
  {s.expected_result && <Text size="sm"><b>Expected result:</b> {s.expected_result}</Text>}
88
- <Text size="xs" c="dimmed">This scenario description is not yet checked on a real Fusion pod.</Text>
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
89
  {editable && onNote && (noteOpen || note
90
  ? <Textarea size="xs" autosize minRows={1} placeholder="Note for this scenario" aria-label={`note for ${s.id}`} value={note ?? ''} onChange={(e) => onNote(e.currentTarget.value)} autoFocus={noteOpen} />
91
  : <Button variant="subtle" size="compact-xs" w="fit-content" onClick={() => setNoteOpen(true)}>Add a note</Button>)}
@@ -160,7 +212,7 @@ export function ScenarioReview({ id, waiting }: { id: string; waiting: boolean }
160
  const all = useMemo(() => sc.data?.scenarios ?? [], [sc.data]);
161
  const known = useMemo(() => new Map(all.map((s) => [s.id, s])), [all]);
162
  const toReview = useMemo(() => [...pending.values()].map((p) => known.get(p.id) ?? stub(p)), [pending, known]);
163
- const isChanged = (s: Scenario) => { const p = pending.get(s.id); return !!p && (p.changed_by_patch || p.new_or_changed || p.origin === 'generated'); };
164
  const changed = toReview.filter(isChanged);
165
  const unchanged = toReview.filter((s) => !isChanged(s));
166
  const others = all.filter((s) => !pending.has(s.id));
@@ -188,6 +240,7 @@ export function ScenarioReview({ id, waiting }: { id: string; waiting: boolean }
188
  {changed.length === 0
189
  ? <Text size="sm" c="dimmed">This patch does not add or change any scenario in this test run.</Text>
190
  : <StepGroups list={changed} kind="changed" {...groupProps} />}
 
191
  {unchanged.length > 0 && (
192
  <>
193
  <Group gap={8} wrap="wrap">
 
1
+ import { Accordion, Alert, Button, Collapse, Group, Stack, Table, Text, Textarea, UnstyledButton } from '@mantine/core';
2
  import { IconChevronDown, IconChevronRight, IconCode, IconUser } from '@tabler/icons-react';
3
  import { useMemo, useState } from 'react';
4
  import { useApproveCases, useCaseYaml, useGate, useRunScenarios } from '../api/hooks';
5
+ import type { AiDraft, ApproveGate, DryRun, PendingCase, Scenario } from '../api/types';
6
  import { Can, Diff, ErrorAlert, Pill, Pre, Term } from '../components/common';
7
  import { PRIORITY_WORDS } from '../glossary';
8
 
 
21
  <Accordion.Item value="tech">
22
  <Accordion.Control icon={<IconCode size={14} />}><Text size="xs">Technical details (scenario file)</Text></Accordion.Control>
23
  <Accordion.Panel>
24
+ {p?.diff && (p.origin === 'generated' || p.origin === 'ai' ? <Pre maxHeight={300}>{p.diff}</Pre> : <Diff text={p.diff} />)}
25
  {yaml.data && <Pre maxHeight={300}>{yaml.data.yaml}</Pre>}
26
  <Text size="xs" c="dimmed" mt={4}>{id}{p ? ` · ${p.origin}` : ''}</Text>
27
  </Accordion.Panel>
 
30
  );
31
  }
32
 
33
+ /** The dry run of an AI-written scenario: on the pod (or a simulation, said plainly), and the failing step if any. */
34
+ export function DryRunLine({ d }: { d: DryRun | null | undefined }) {
35
+ if (!d) return <Text size="sm" c="dimmed">Not dry-run: the model's steps did not pass the checks.</Text>;
36
+ const where = d.simulated ? 'in a quick simulation (no browser, not on a pod)' : `on ${d.pod}`;
37
+ return (
38
+ <div data-testid="dry-run">
39
+ <Text size="sm"><b>Dry run:</b> {d.status === 'passed' ? `passed ${where}` : `failed ${where}`}{d.at ? ` · ${d.at.slice(0, 16).replace('T', ' ')}` : ''}</Text>
40
+ {d.status !== 'passed' && (d.failed_step || d.message) && (
41
+ <Text size="xs" c="red" style={{ whiteSpace: 'pre-wrap' }}>{d.failed_step ? `Step ${d.failed_step}: ` : ''}{(d.message ?? '').slice(0, 400)}</Text>
42
+ )}
43
+ </div>
44
+ );
45
+ }
46
+
47
+ /** AI-written scenarios that are not offered for approval: their dry run failed (or their steps never passed the checks). */
48
+ function NotRunnable({ list }: { list: AiDraft[] }) {
49
+ return (
50
+ <div data-testid="ai-not-runnable" style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
51
+ <Text size="sm" fw={600}>Written by the AI model, not offered ({list.length})</Text>
52
+ <Text size="xs" c="dimmed">These new scenarios failed their dry run, so they are not part of this test run. They stay in staging.</Text>
53
+ {list.map((d, i) => (
54
+ <div key={d.id ?? `x${i}`} className="fpt-srow" data-testid={`ai-failed-${d.id ?? i}`}>
55
+ <Group gap={6} wrap="wrap"><Text size="sm">{d.title}</Text><Pill tone="lav">Written by the AI model</Pill><Pill tone="red">{d.dry_run ? 'dry run failed' : 'not written'}</Pill></Group>
56
+ <DryRunLine d={d.dry_run} />
57
+ {d.problems.length > 0 && <Text size="xs" c="dimmed">{d.problems.slice(0, 3).join(' · ')}</Text>}
58
+ {d.steps.length > 0 && (
59
+ <ol style={{ margin: '4px 0 0', paddingLeft: 20, fontSize: 12 }}>{d.steps.map((st) => <li key={st.n}>{st.text}</li>)}</ol>
60
+ )}
61
+ </div>
62
+ ))}
63
+ </div>
64
+ );
65
+ }
66
+
67
  /** One business scenario: a one-line row that expands to the plain-language steps. */
68
  export function ScenarioCard({ s, p, decision, onDecision, note, onNote, editable }: {
69
  s: Scenario; p?: PendingCase; decision?: Decision; onDecision?: (d: Decision) => void; note?: string; onNote?: (v: string) => void; editable: boolean;
 
80
  <Text size="sm" truncate={open ? undefined : 'end'} style={{ minWidth: 0 }}>{s.title}</Text>
81
  <Pill tone={PRIO_TONE[s.priority_words] ?? 'neutral'}>{s.priority_words}</Pill>
82
  {s.origin === 'generated' && <Pill tone="lav">new</Pill>}
83
+ {(s.origin === 'ai' || p?.origin === 'ai') && <Pill tone="lav">Written by the AI model</Pill>}
84
+ {p?.ai?.dry_run?.status === 'passed' && <Pill tone="green">{p.ai.dry_run.simulated ? 'dry run simulated' : 'dry run passed'}</Pill>}
85
  {out && <Pill tone={out.tone}>{out.label}</Pill>}
86
  </Group>
87
  </UnstyledButton>
 
121
  </div>
122
  )}
123
  {s.expected_result && <Text size="sm"><b>Expected result:</b> {s.expected_result}</Text>}
124
+ {(s.origin === 'ai' || p?.origin === 'ai') && (
125
+ <>
126
+ <Text size="sm"><b>Written by the AI model</b>{p?.ai?.model ? ` (${p.ai.model})` : ''} from Oracle's standard screen labels; no client data was sent to it.</Text>
127
+ <DryRunLine d={p?.ai?.dry_run ?? s.dry_run} />
128
+ {p?.ai && p.ai.steps.length > 0 && (
129
+ <Table.ScrollContainer minWidth={480}>
130
+ <Table fz="xs" striped withTableBorder aria-label={`steps of ${s.id}`}>
131
+ <Table.Thead><Table.Tr><Table.Th>#</Table.Th><Table.Th>Action</Table.Th><Table.Th>Field</Table.Th><Table.Th>Value</Table.Th><Table.Th>Expected</Table.Th></Table.Tr></Table.Thead>
132
+ <Table.Tbody>{p.ai.steps.map((st) => (
133
+ <Table.Tr key={st.n}><Table.Td>{st.n}</Table.Td><Table.Td>{st.action.replace(/_/g, ' ')}</Table.Td><Table.Td>{st.field ?? ''}</Table.Td><Table.Td>{st.value ?? ''}</Table.Td><Table.Td>{st.expected ?? ''}</Table.Td></Table.Tr>
134
+ ))}</Table.Tbody>
135
+ </Table>
136
+ </Table.ScrollContainer>
137
+ )}
138
+ </>
139
+ )}
140
+ {s.origin !== 'ai' && <Text size="xs" c="dimmed">This scenario description is not yet checked on a real Fusion pod.</Text>}
141
  {editable && onNote && (noteOpen || note
142
  ? <Textarea size="xs" autosize minRows={1} placeholder="Note for this scenario" aria-label={`note for ${s.id}`} value={note ?? ''} onChange={(e) => onNote(e.currentTarget.value)} autoFocus={noteOpen} />
143
  : <Button variant="subtle" size="compact-xs" w="fit-content" onClick={() => setNoteOpen(true)}>Add a note</Button>)}
 
212
  const all = useMemo(() => sc.data?.scenarios ?? [], [sc.data]);
213
  const known = useMemo(() => new Map(all.map((s) => [s.id, s])), [all]);
214
  const toReview = useMemo(() => [...pending.values()].map((p) => known.get(p.id) ?? stub(p)), [pending, known]);
215
+ const isChanged = (s: Scenario) => { const p = pending.get(s.id); return !!p && (p.changed_by_patch || p.new_or_changed || p.origin === 'generated' || p.origin === 'ai'); };
216
  const changed = toReview.filter(isChanged);
217
  const unchanged = toReview.filter((s) => !isChanged(s));
218
  const others = all.filter((s) => !pending.has(s.id));
 
240
  {changed.length === 0
241
  ? <Text size="sm" c="dimmed">This patch does not add or change any scenario in this test run.</Text>
242
  : <StepGroups list={changed} kind="changed" {...groupProps} />}
243
+ {(g.ai_not_runnable ?? []).length > 0 && <NotRunnable list={g.ai_not_runnable ?? []} />}
244
  {unchanged.length > 0 && (
245
  <>
246
  <Group gap={8} wrap="wrap">