EnergyVenom commited on
Commit
152e0c1
·
verified ·
1 Parent(s): 0108bcf

Astra: regression catalogue, runner robustness, idempotent Agent Studio contract, key-screen design (2182ef729b22)

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. automation/remote_runner/server.py +89 -14
  2. automation/src/fusion/rest.ts +5 -0
  3. automation/src/fusion/ui.ts +43 -12
  4. coworker/adapters/playwright.py +78 -8
  5. coworker/adapters/remote_runner.py +289 -72
  6. coworker/adapters/screens.py +13 -2
  7. coworker/api/app.py +1 -1
  8. coworker/api/routes/admin.py +1 -1
  9. coworker/api/routes/agent_studio.py +31 -9
  10. coworker/api/runner.py +15 -6
  11. coworker/config.py +34 -0
  12. coworker/graph/nodes/ai_scenarios.py +82 -2
  13. coworker/graph/nodes/execute.py +135 -8
  14. coworker/llm/prompts/design_scenarios.md +6 -0
  15. coworker/llm/prompts/write_steps.md +9 -0
  16. coworker/platform/agent_studio.py +239 -50
  17. coworker/platform/fusion_catalog.py +279 -1
  18. coworker/platform/migrations/026_agent_studio_delivery_contract.sql +9 -0
  19. coworker/platform/notify.py +6 -0
  20. coworker/platform/preflight.py +37 -7
  21. coworker/platform/statesync.py +9 -3
  22. coworker/platform/step_writer.py +4 -0
  23. coworker/tests/test_agent_studio.py +220 -8
  24. coworker/tests/test_area_user_passes.py +5 -1
  25. coworker/tests/test_preflight.py +7 -1
  26. coworker/tests/test_regression_checks.py +155 -0
  27. coworker/tests/test_runner_robust.py +542 -0
  28. coworker/tests/test_step_writer.py +16 -0
  29. coworker/tests/test_supabase.py +13 -0
  30. coworker/workflows/client.py +2 -2
  31. deploy/DEPLOY.md +20 -10
  32. deploy/runner/sync.sh +9 -1
  33. docs/AGENT_STUDIO.md +100 -39
  34. docs/ARCHITECTURE.md +93 -32
  35. docs/AUDIT.md +2 -0
  36. docs/DEPLOYMENT.md +76 -29
  37. docs/FINAL_REPORT.md +2 -0
  38. docs/FRONTEND_AUDIT.md +2 -0
  39. docs/QUALITY.md +21 -2
  40. docs/REMOTE_RUNNER.md +166 -73
  41. docs/RUNBOOK.md +67 -22
  42. docs/SECURITY.md +24 -11
  43. docs/design/BEUI.md +2 -0
  44. docs/design/UI-APPLE.md +2 -0
  45. docs/design/UI-REDESIGN.md +2 -0
  46. docs/design/UI-RESEARCH-RECOVERY.md +2 -0
  47. docs/design/UI-REVIEW-1.md +2 -0
  48. docs/design/UI-REVIEW-2.md +2 -0
  49. docs/design/UI-REVIEW-3.md +2 -0
  50. docs/design/UI-SIMPLIFY.md +2 -0
automation/remote_runner/server.py CHANGED
@@ -5,12 +5,17 @@ The Patchwise server posts an attempt (case ids, config, the run's environment,
5
  polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), the
6
  run directory (screenshots, videos, traces), the pod values tried and the ledger of created test records.
7
 
 
 
 
 
 
8
  Security: every call needs `Authorization: Bearer <RUNNER_TOKEN>` (compared in constant time). Only known environment
9
  keys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password exists
10
  only in the Playwright process's environment, never on disk. Put it behind HTTPS (deploy/remote-runner/Caddyfile).
11
 
12
  Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (default ~/runner-data),
13
- AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24)."""
14
  from __future__ import annotations
15
 
16
  import base64
@@ -34,6 +39,7 @@ PORT = int(os.environ.get("RUNNER_PORT", "8899"))
34
  HOME = Path(os.environ.get("RUNNER_HOME", str(Path.home() / "runner-data")))
35
  AUTOMATION = Path(os.environ.get("AUTOMATION_DIR", str(Path(__file__).resolve().parents[1])))
36
  KEEP_S = float(os.environ.get("RUNNER_KEEP_HOURS", "24")) * 3600
 
37
  # the scenario files the repo's own step specs read (../tests/cases), and the commit deploy/runner/sync.sh installed
38
  CASES = AUTOMATION.parent / "tests" / "cases"
39
  VERSION_FILE = AUTOMATION.parent / "VERSION"
@@ -47,6 +53,40 @@ MAX_BODY = 20_000_000
47
  GROUP = {"start_new_session": True} if os.name == "posix" else {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
48
  LOCK = threading.Lock() # one attempt at a time: the runner is sized for one browser
49
  JOBS: dict[str, dict] = {}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
50
 
51
 
52
  def grep_for(ids: list[str]) -> str:
@@ -144,9 +184,10 @@ def start(body: dict) -> dict:
144
  "--retries=0", "--reporter=json", "--grep", grep_for(ids)]
145
  log = open(jd / "playwright.log", "wb")
146
  p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP)
147
- job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(),
148
  "deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None}
149
  JOBS[jid] = job
 
150
  threading.Thread(target=_watch, args=(job,), daemon=True).start()
151
  return {"id": jid, "state": "running"}
152
  except BaseException:
@@ -192,6 +233,7 @@ def start_screens(body: dict) -> dict:
192
  job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": jid, "started": time.time(), "kind": kind,
193
  "deadline": time.time() + min(float(body.get("timeout_s") or 5400), 4 * 3600), "state": "running", "exit_code": None}
194
  JOBS[jid] = job
 
195
  threading.Thread(target=_watch, args=(job,), daemon=True).start()
196
  return {"id": jid, "state": "running"}
197
  except BaseException:
@@ -241,24 +283,54 @@ def _kill_tree(p: subprocess.Popen) -> None:
241
  pass
242
 
243
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
244
  def _watch(job: dict) -> None:
245
  p = job["proc"]
246
  try:
 
247
  while p.poll() is None:
248
- if time.time() > job["deadline"] or job.get("cancel"):
249
- job["timed_out"] = not job.get("cancel")
250
  _kill_tree(p)
 
 
 
 
 
 
251
  time.sleep(2)
252
  job["exit_code"] = p.returncode
253
  job["log"].close()
254
- run_dir = AUTOMATION / "results" / "runs" / job["pw_run_id"]
255
- report = job["dir"] / "report.json"
256
- if report.exists():
257
- _relativize(report, run_dir)
258
- if run_dir.exists(): # the run's evidence moves into the job (so the automation folder never piles up)
259
- shutil.move(str(run_dir), str(job["dir"] / "run"))
260
  job["state"] = "cancelled" if job.get("cancel") else "done"
 
 
 
261
  finally:
 
262
  LOCK.release()
263
 
264
 
@@ -343,8 +415,9 @@ class H(BaseHTTPRequestHandler):
343
  if job["state"] == "running":
344
  return self._send(409, {"error": "the attempt is still running"})
345
  return self._send(200, raw=bundle(job), ctype="application/zip")
346
- st = {"id": job["id"], "state": job["state"], "exit_code": job["exit_code"], "timed_out": bool(job.get("timed_out")),
347
- "progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists()}
 
348
  if m.group(3) is not None: # a screen read follows its log lines ("[explore] ...") for its progress
349
  st["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3)))
350
  self._send(200, st)
@@ -367,8 +440,9 @@ class H(BaseHTTPRequestHandler):
367
  if m:
368
  job = self._job(m.group(1))
369
  if job:
370
- job["cancel"] = True
371
- self._send(202, {"id": job["id"], "state": "cancelling"})
 
372
  return
373
  self._send(404, {"error": "not found"})
374
 
@@ -377,6 +451,7 @@ if __name__ == "__main__":
377
  if not TOKEN or len(TOKEN) < 24:
378
  raise SystemExit("set RUNNER_TOKEN (at least 24 characters)")
379
  HOME.mkdir(parents=True, exist_ok=True)
 
380
  threading.Thread(target=sweep, daemon=True).start()
381
  print(f"Patchwise remote runner on 127.0.0.1:{PORT}, automation {AUTOMATION}", flush=True)
382
  ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
 
5
  polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), the
6
  run directory (screenshots, videos, traces), the pod values tried and the ledger of created test records.
7
 
8
+ An attempt that reaches its own deadline is first asked to stop (SIGINT: Playwright ends the tests that run and still
9
+ writes its report), and only killed after RUNNER_GRACE_S. Each job's metadata is kept in its folder (job.json), so after a
10
+ runner restart a finished job still answers its status and bundle, and a job that was running is reported "lost" (the
11
+ Patchwise server then fails it at once instead of waiting for its deadline).
12
+
13
  Security: every call needs `Authorization: Bearer <RUNNER_TOKEN>` (compared in constant time). Only known environment
14
  keys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password exists
15
  only in the Playwright process's environment, never on disk. Put it behind HTTPS (deploy/remote-runner/Caddyfile).
16
 
17
  Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (default ~/runner-data),
18
+ AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24), RUNNER_GRACE_S (default 90)."""
19
  from __future__ import annotations
20
 
21
  import base64
 
39
  HOME = Path(os.environ.get("RUNNER_HOME", str(Path.home() / "runner-data")))
40
  AUTOMATION = Path(os.environ.get("AUTOMATION_DIR", str(Path(__file__).resolve().parents[1])))
41
  KEEP_S = float(os.environ.get("RUNNER_KEEP_HOURS", "24")) * 3600
42
+ GRACE_S = float(os.environ.get("RUNNER_GRACE_S", "90")) # an attempt past its deadline gets this long to write its report
43
  # the scenario files the repo's own step specs read (../tests/cases), and the commit deploy/runner/sync.sh installed
44
  CASES = AUTOMATION.parent / "tests" / "cases"
45
  VERSION_FILE = AUTOMATION.parent / "VERSION"
 
53
  GROUP = {"start_new_session": True} if os.name == "posix" else {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP}
54
  LOCK = threading.Lock() # one attempt at a time: the runner is sized for one browser
55
  JOBS: dict[str, dict] = {}
56
+ META = ("id", "kind", "state", "started", "deadline", "pw_run_id", "exit_code", "timed_out", "error")
57
+ ENDED = ("done", "cancelled", "failed")
58
+
59
+
60
+ def save_meta(job: dict) -> None:
61
+ """The job's metadata (never its environment) in its folder, written whole, so a restarted runner can answer for it."""
62
+ try:
63
+ tmp = job["dir"] / ".job.json.tmp"
64
+ tmp.write_text(json.dumps({k: job.get(k) for k in META}), encoding="utf-8")
65
+ tmp.replace(job["dir"] / "job.json")
66
+ except OSError:
67
+ pass
68
+
69
+
70
+ def load_jobs() -> None:
71
+ """After a restart: jobs kept on disk answer again. A finished one as it ended; one that was running is "lost" (its
72
+ processes died with the old runner), and what it left (its ledger of test records, its run folder) still ships."""
73
+ for d in sorted(HOME.glob("job_*")):
74
+ try:
75
+ meta = json.loads((d / "job.json").read_text(encoding="utf-8"))
76
+ except (OSError, ValueError):
77
+ continue
78
+ jid = str(meta.get("id") or "")
79
+ if jid != d.name or jid in JOBS or not re.fullmatch(r"job_[0-9a-f]{12}", jid):
80
+ continue
81
+ job = {**{k: meta.get(k) for k in META}, "dir": d, "started": float(meta.get("started") or d.stat().st_mtime)}
82
+ if job["state"] not in ENDED:
83
+ job["state"] = "lost"
84
+ try:
85
+ _collect(job)
86
+ except OSError:
87
+ pass # what could not be moved stays where it is; the job still answers
88
+ save_meta(job)
89
+ JOBS[jid] = job
90
 
91
 
92
  def grep_for(ids: list[str]) -> str:
 
184
  "--retries=0", "--reporter=json", "--grep", grep_for(ids)]
185
  log = open(jd / "playwright.log", "wb")
186
  p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP)
187
+ job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(), "kind": "attempt",
188
  "deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None}
189
  JOBS[jid] = job
190
+ save_meta(job)
191
  threading.Thread(target=_watch, args=(job,), daemon=True).start()
192
  return {"id": jid, "state": "running"}
193
  except BaseException:
 
233
  job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": jid, "started": time.time(), "kind": kind,
234
  "deadline": time.time() + min(float(body.get("timeout_s") or 5400), 4 * 3600), "state": "running", "exit_code": None}
235
  JOBS[jid] = job
236
+ save_meta(job)
237
  threading.Thread(target=_watch, args=(job,), daemon=True).start()
238
  return {"id": jid, "state": "running"}
239
  except BaseException:
 
283
  pass
284
 
285
 
286
+ def _interrupt(p: subprocess.Popen) -> bool:
287
+ """Ask Playwright to stop as Ctrl+C does: it ends the running tests, marks the rest as not run and still writes its
288
+ JSON report. False where that cannot be asked (Windows: the attempt is killed at once)."""
289
+ if os.name != "posix":
290
+ return False
291
+ try:
292
+ os.kill(p.pid, signal.SIGINT)
293
+ return True
294
+ except OSError:
295
+ return False
296
+
297
+
298
+ def _collect(job: dict) -> None:
299
+ """What the attempt left becomes the job's: the report (attachment paths made relative) and the run folder."""
300
+ run_dir = AUTOMATION / "results" / "runs" / str(job.get("pw_run_id") or "")
301
+ report = job["dir"] / "report.json"
302
+ if report.exists():
303
+ try:
304
+ _relativize(report, run_dir)
305
+ except (OSError, ValueError):
306
+ pass # a report cut off mid-write still ships as it is
307
+ if job.get("pw_run_id") and run_dir.is_dir() and not (job["dir"] / "run").exists():
308
+ shutil.move(str(run_dir), str(job["dir"] / "run")) # the evidence moves into the job (the automation folder never piles up)
309
+
310
+
311
  def _watch(job: dict) -> None:
312
  p = job["proc"]
313
  try:
314
+ stop_at = None
315
  while p.poll() is None:
316
+ if job.get("cancel"):
 
317
  _kill_tree(p)
318
+ elif time.time() > job["deadline"]:
319
+ if stop_at is None: # its own time is up: stopped gently first, so its report is not lost
320
+ job["timed_out"] = True
321
+ stop_at = time.time() + (GRACE_S if _interrupt(p) else 0)
322
+ if time.time() >= stop_at:
323
+ _kill_tree(p)
324
  time.sleep(2)
325
  job["exit_code"] = p.returncode
326
  job["log"].close()
327
+ _collect(job)
 
 
 
 
 
328
  job["state"] = "cancelled" if job.get("cancel") else "done"
329
+ except Exception as e: # noqa: BLE001 - the job ends as failed, never stays "running" once the lock is released
330
+ job["state"], job["error"] = "failed", f"{type(e).__name__}: {e}"[:300]
331
+ _kill_tree(p)
332
  finally:
333
+ save_meta(job)
334
  LOCK.release()
335
 
336
 
 
415
  if job["state"] == "running":
416
  return self._send(409, {"error": "the attempt is still running"})
417
  return self._send(200, raw=bundle(job), ctype="application/zip")
418
+ st = {"id": job["id"], "state": job["state"], "exit_code": job.get("exit_code"), "timed_out": bool(job.get("timed_out")),
419
+ "progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists(),
420
+ "started": job.get("started"), "pw_run_id": job.get("pw_run_id")}
421
  if m.group(3) is not None: # a screen read follows its log lines ("[explore] ...") for its progress
422
  st["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3)))
423
  self._send(200, st)
 
440
  if m:
441
  job = self._job(m.group(1))
442
  if job:
443
+ if job["state"] == "running":
444
+ job["cancel"] = True
445
+ self._send(202, {"id": job["id"], "state": "cancelling" if job["state"] == "running" else job["state"]})
446
  return
447
  self._send(404, {"error": "not found"})
448
 
 
451
  if not TOKEN or len(TOKEN) < 24:
452
  raise SystemExit("set RUNNER_TOKEN (at least 24 characters)")
453
  HOME.mkdir(parents=True, exist_ok=True)
454
+ load_jobs()
455
  threading.Thread(target=sweep, daemon=True).start()
456
  print(f"Patchwise remote runner on 127.0.0.1:{PORT}, automation {AUTOMATION}", flush=True)
457
  ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever()
automation/src/fusion/rest.ts CHANGED
@@ -56,6 +56,11 @@ export class FusionRest {
56
  return (await this.invoices(number, supplier))[0] || null;
57
  }
58
 
 
 
 
 
 
59
  holds(number: string): Promise<InvoiceHold[]> {
60
  return this.get<InvoiceHold>('invoiceHolds', `InvoiceNumber='${q(number)}'`);
61
  }
 
56
  return (await this.invoices(number, supplier))[0] || null;
57
  }
58
 
59
+ /** The invoice with this number, whatever its supplier (test numbers are unique per run). */
60
+ async invoiceByNumber(number: string): Promise<Invoice | null> {
61
+ return (await this.get<Invoice>('invoices', `InvoiceNumber='${q(number)}'`))[0] || null;
62
+ }
63
+
64
  holds(number: string): Promise<InvoiceHold[]> {
65
  return this.get<InvoiceHold>('invoiceHolds', `InvoiceNumber='${q(number)}'`);
66
  }
automation/src/fusion/ui.ts CHANGED
@@ -228,12 +228,18 @@ export class FusionUi {
228
 
229
  /** The task is open: the page title names it ("Create Invoice - Oracle Fusion ...", "Invoice Workbench - Create
230
  * Recurring Invoices - ..."), or a dialog named after it is showing (Create Order opens a dialog over the work area,
231
- * and the page title stays the work area's). */
 
232
  async expectTitle(task: string) {
233
  const title = new RegExp(`(^|[-–:|]\\s*)${esc(task)}\\b`, 'i');
234
  const dialog = this.page.getByRole('dialog').filter({ hasText: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true });
235
- await expect.poll(async () => title.test(await this.page.title()) || (await dialog.count()) > 0,
236
- { message: `"${task}" should open (its page or its dialog)`, timeout: 60_000 }).toBe(true);
 
 
 
 
 
237
  }
238
 
239
  /** The Tasks list of a work area: the panel region whose id ends "_FndTasksList" (its tab: "..._FndTasksList::disAcr").
@@ -481,10 +487,13 @@ export class FusionUi {
481
  }
482
 
483
  /** One row of the invoice Lines table. Up to 26C Fusion names each row "Select Row <n> <n> ..."; from 26D each line
484
- * is a nested table in table "Invoice Lines" whose first cell is the line number. */
 
 
485
  lineRow(n: number): Locator {
486
  const named = this.page.getByRole('row', { name: new RegExp(`^Select Row ${n} ${n} `) });
487
  const nested = this.page.getByRole('table', { name: 'Invoice Lines' }).getByRole('row')
 
488
  .filter({ has: this.page.getByRole('cell', { name: String(n), exact: true }) });
489
  return named.or(nested).first();
490
  }
@@ -513,17 +522,28 @@ export class FusionUi {
513
  * the account is then cleared and the pod's next candidate tried, and the one Fusion takes is remembered. */
514
  private async putLineAccount(account: Locator, first: string) {
515
  const tried: string[] = [];
516
- for (const v of [first, ...podCandidates('AP', 'account')].filter((x, i, all) => x && all.indexOf(x) === i).slice(0, 6)) {
 
 
 
 
 
 
 
 
517
  await account.click(); await account.fill(v); await account.press('Tab'); await this.settle(2500);
518
- const segments = this.page.getByRole('dialog', { name: /Distribution Combination/ }).filter({ visible: true });
519
- const error = this.page.getByText(/You must enter a combination|is not a valid (account|combination)|combination .* (does not exist|is not valid)/i)
520
- .filter({ visible: true });
521
- const refused = (await segments.count()) > 0 || (await error.count()) > 0
522
- || (await account.inputValue().catch(() => '')).trim() !== v.trim();
 
 
523
  if (!refused) { used('AP', 'account', v, true); return; }
524
  used('AP', 'account', v, false);
525
  tried.push(v);
526
  if (await segments.count()) await segments.getByRole('button', { name: 'Cancel', exact: true }).first().click().catch(() => this.page.keyboard.press('Escape'));
 
527
  await this.settle(1000);
528
  await account.fill(''); await account.press('Tab'); await this.settle(1000);
529
  }
@@ -815,10 +835,21 @@ export class FusionUi {
815
  { message: `the page should show the status ${status}` }).toBeVisible({ timeout: 60_000 });
816
  }
817
 
818
- /** The invoice status Fusion shows beside the page title (Not validated, Validated, Needs revalidation, Canceled). */
 
 
819
  async statusOnPage(): Promise<string> {
820
  const link = this.page.getByRole('link', { name: new RegExp(`^(${INVOICE_STATUSES.join('|')})$`) }).first();
821
- return (await link.innerText({ timeout: 5_000 }).catch(() => '')).trim();
 
 
 
 
 
 
 
 
 
822
  }
823
 
824
  async expectStatus(status: (typeof INVOICE_STATUSES)[number]) {
 
228
 
229
  /** The task is open: the page title names it ("Create Invoice - Oracle Fusion ...", "Invoice Workbench - Create
230
  * Recurring Invoices - ..."), or a dialog named after it is showing (Create Order opens a dialog over the work area,
231
+ * and the page title stays the work area's), or a page heading names it (26D opens some tasks in place), or a
232
+ * Create task's document opened for editing ("Create Noncatalog Request" -> "Noncatalog Request - Edit"). */
233
  async expectTitle(task: string) {
234
  const title = new RegExp(`(^|[-–:|]\\s*)${esc(task)}\\b`, 'i');
235
  const dialog = this.page.getByRole('dialog').filter({ hasText: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true });
236
+ const heading = this.page.getByRole('heading', { name: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true });
237
+ const noun = /^create\s+(.+)$/i.exec(task.trim())?.[1];
238
+ const editing = noun ? new RegExp(`(^|[-–:|]\\s*)${esc(noun)}\\s*[-–:]\\s*(Edit|Create)\\b`, 'i') : null;
239
+ await expect.poll(async () => {
240
+ const t = await this.page.title();
241
+ return title.test(t) || (editing?.test(t) ?? false) || (await dialog.count()) > 0 || (await heading.count()) > 0;
242
+ }, { message: `"${task}" should open (its page, its dialog or its heading)`, timeout: 60_000 }).toBe(true);
243
  }
244
 
245
  /** The Tasks list of a work area: the panel region whose id ends "_FndTasksList" (its tab: "..._FndTasksList::disAcr").
 
487
  }
488
 
489
  /** One row of the invoice Lines table. Up to 26C Fusion names each row "Select Row <n> <n> ..."; from 26D each line
490
+ * is a nested table in table "Invoice Lines" whose first cell is the line number. Only the innermost rows count (a
491
+ * row holding no table of its own), so the outer row that wraps a line's table is never taken for it. (Matching the
492
+ * number in the first cell only, by CSS position, found no row at all on the 26D page: the cell name match stays.) */
493
  lineRow(n: number): Locator {
494
  const named = this.page.getByRole('row', { name: new RegExp(`^Select Row ${n} ${n} `) });
495
  const nested = this.page.getByRole('table', { name: 'Invoice Lines' }).getByRole('row')
496
+ .filter({ hasNot: this.page.getByRole('table') }) // data tables only: ADF lays inputs out in presentation tables
497
  .filter({ has: this.page.getByRole('cell', { name: String(n), exact: true }) });
498
  return named.or(nested).first();
499
  }
 
522
  * the account is then cleared and the pod's next candidate tried, and the one Fusion takes is remembered. */
523
  private async putLineAccount(account: Locator, first: string) {
524
  const tried: string[] = [];
525
+ let pod: string[] = [];
526
+ try { pod = podCandidates('AP', 'account'); } catch { /* the step's own account only: a pod without account data */ }
527
+ // an account Fusion took may come back reformatted (separators, spaces): compared without them
528
+ const bare = (s: string) => s.replace(/[\s.\-_]/g, '').toUpperCase();
529
+ const segments = this.page.getByRole('dialog', { name: /Distribution Combination/ }).filter({ visible: true });
530
+ const errorText = /You must enter a combination|is not a valid (account|combination)|combination .* (does not exist|is not valid)/i;
531
+ for (const v of [first, ...pod].filter((x, i, all) => x && all.indexOf(x) === i).slice(0, 6)) {
532
+ // errors already on the page (an earlier line, an earlier candidate) are not this candidate's
533
+ const before = await this.page.getByText(errorText).filter({ visible: true }).count();
534
  await account.click(); await account.fill(v); await account.press('Tab'); await this.settle(2500);
535
+ const message = this.page.getByRole('dialog').filter({ hasText: errorText }).filter({ visible: true });
536
+ let refused = (await segments.count()) > 0 || (await message.count()) > 0
537
+ || (await this.page.getByText(errorText).filter({ visible: true }).count()) > before;
538
+ if (!refused) { // Fusion may redraw the value a moment later: read it until it settles
539
+ refused = !(await expect.poll(async () => bare(await account.inputValue().catch(() => '')), { timeout: 5_000 })
540
+ .toBe(bare(v)).then(() => true, () => false));
541
+ }
542
  if (!refused) { used('AP', 'account', v, true); return; }
543
  used('AP', 'account', v, false);
544
  tried.push(v);
545
  if (await segments.count()) await segments.getByRole('button', { name: 'Cancel', exact: true }).first().click().catch(() => this.page.keyboard.press('Escape'));
546
+ if (await message.count()) await message.getByRole('button', { name: /^(OK|Close)$/ }).first().click().catch(() => this.page.keyboard.press('Escape'));
547
  await this.settle(1000);
548
  await account.fill(''); await account.press('Tab'); await this.settle(1000);
549
  }
 
835
  { message: `the page should show the status ${status}` }).toBeVisible({ timeout: 60_000 });
836
  }
837
 
838
+ /** The invoice status Fusion shows beside the page title (Not validated, Validated, Needs revalidation, Canceled).
839
+ * A page that shows no status link (a layout without it) is answered by Fusion itself: the status of the invoice
840
+ * whose number the page holds, read over REST, so a moved status link never fails a test that worked. */
841
  async statusOnPage(): Promise<string> {
842
  const link = this.page.getByRole('link', { name: new RegExp(`^(${INVOICE_STATUSES.join('|')})$`) }).first();
843
+ const shown = (await link.innerText({ timeout: 5_000 }).catch(() => '')).trim();
844
+ if (shown) return shown;
845
+ const number = await this.field('Number').inputValue({ timeout: 2_000 }).catch(() => '');
846
+ if (!number.trim()) return '';
847
+ const { FusionRest } = await import('./rest');
848
+ const inv = await new FusionRest().invoiceByNumber(number.trim()).catch(() => null);
849
+ if (!inv) return '';
850
+ if (inv.CanceledFlag) return 'Canceled';
851
+ const rest = String(inv.ValidationStatus || '').trim().toLowerCase(); // in the page's own spelling
852
+ return INVOICE_STATUSES.find((s) => s.toLowerCase() === rest) ?? String(inv.ValidationStatus || '');
853
  }
854
 
855
  async expectStatus(status: (typeof INVOICE_STATUSES)[number]) {
coworker/adapters/playwright.py CHANGED
@@ -209,31 +209,101 @@ def merge_chunk_reports(files: list[Path], out_file: Path) -> Path:
209
  return out_file
210
 
211
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
212
  def run_attempt_chunked(*, ids: list[str], out_file: Path, chunk_size: int, done: dict | None = None,
213
- done_dirs: dict | None = None, on_chunk=None, **kw) -> dict:
 
214
  """Resumable attempt: cases run in chunks of chunk_size, each with its own JSON report and Playwright run dir.
215
  `done` / `done_dirs` map chunk index -> report file / run dir from a previous (crashed) try of the same attempt; those
216
  chunks are skipped but their reports AND run dirs are still returned (so their evidence is ingested).
217
- on_chunk(k, file, n_chunks, run_dir) is called after each chunk (the Temporal activity heartbeats it)."""
 
 
 
 
 
218
  chunks = [ids[i:i + chunk_size] for i in range(0, len(ids), max(1, chunk_size))] or [[]]
219
  done = {int(k): v for k, v in (done or {}).items() if Path(v).exists()}
220
  dirs = {int(k): v for k, v in (done_dirs or {}).items() if v}
221
- skipped = []
 
 
222
  for k, chunk in enumerate(chunks):
223
- cf = out_file.with_name(f"{out_file.stem}.c{k}.json")
224
  if k in done:
225
  skipped.append(k)
226
  continue
227
- res = run_attempt(ids=chunk, out_file=cf, tag=f"-c{k}", live_meta={"all_ids": ids, "chunk": k, "chunks": len(chunks)}, **kw)
 
 
 
 
 
 
 
 
 
 
 
 
228
  if res.get("run_dir"):
229
  dirs[k] = res["run_dir"]
230
- done[k] = str(cf)
 
231
  if on_chunk:
232
  on_chunk(k, str(cf), len(chunks), res.get("run_dir"))
233
- merge_chunk_reports([Path(done[k]) for k in range(len(chunks))], out_file)
 
 
234
  run_dirs = [dirs[k] for k in range(len(chunks)) if dirs.get(k)]
235
  return {"file": str(out_file), "run_dirs": run_dirs, "run_dir": run_dirs[-1] if run_dirs else None,
236
- "chunks": len(chunks), "skipped_chunks": skipped, "mode": kw.get("mode")}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
237
 
238
 
239
  def attachments_by_case(report_file: Path) -> dict[str, str]:
 
209
  return out_file
210
 
211
 
212
+ NO_RESULT = "_no_result" # a scenario entry written for a pass that ran out of time before it reported (its case id)
213
+
214
+
215
+ def timed_out_report(ids: list[str], out_file: Path, why: str) -> Path:
216
+ """The report of a pass that ran out of time and wrote none: each of its scenarios is recorded as timed out with the
217
+ reason, so it is counted, shown and retried like any failure instead of vanishing from the run."""
218
+ specs = [{"title": cid, "file": "", NO_RESULT: cid, "tags": [f"@{cid}"], "ok": False,
219
+ "tests": [{"status": "unexpected", "results": [{"status": "timedOut", "duration": 0, "errors": [{"message": why}],
220
+ "attachments": []}]}]} for cid in ids]
221
+ out_file.write_text(json.dumps({"config": {"projects": []}, "suites": [{"title": "no result", "file": "", "specs": specs}],
222
+ "errors": [], "stats": {}}, indent=1), encoding="utf-8")
223
+ return out_file
224
+
225
+
226
  def run_attempt_chunked(*, ids: list[str], out_file: Path, chunk_size: int, done: dict | None = None,
227
+ done_dirs: dict | None = None, on_chunk=None, run=None, tag: str = "", lost_ok: bool = False,
228
+ single_as_attempt: bool = False, **kw) -> dict:
229
  """Resumable attempt: cases run in chunks of chunk_size, each with its own JSON report and Playwright run dir.
230
  `done` / `done_dirs` map chunk index -> report file / run dir from a previous (crashed) try of the same attempt; those
231
  chunks are skipped but their reports AND run dirs are still returned (so their evidence is ingested).
232
+ on_chunk(k, file, n_chunks, run_dir) is called after each chunk (the Temporal activity heartbeats it).
233
+ `run` runs one chunk (default run_attempt; the LangGraph path passes one that may use the remote runner) and `tag`
234
+ prefixes the chunk tags. lost_ok: a chunk that runs out of time with no report is recorded as timed out
235
+ (timed_out_report) and the next chunk runs, unless no chunk of the attempt produced a report. single_as_attempt: an
236
+ attempt that fits in one chunk keeps the attempt's own report file and tag, as an unchunked run would."""
237
+ from ..platform.failures import ExecutionError
238
  chunks = [ids[i:i + chunk_size] for i in range(0, len(ids), max(1, chunk_size))] or [[]]
239
  done = {int(k): v for k, v in (done or {}).items() if Path(v).exists()}
240
  dirs = {int(k): v for k, v in (done_dirs or {}).items() if v}
241
+ files = dict(done)
242
+ skipped, lost, code, timed_out, last_err = [], [], 0, False, None
243
+ whole = single_as_attempt and len(chunks) == 1
244
  for k, chunk in enumerate(chunks):
245
+ cf = out_file if whole else out_file.with_name(f"{out_file.stem}.c{k}.json")
246
  if k in done:
247
  skipped.append(k)
248
  continue
249
+ try:
250
+ res = (run or run_attempt)(ids=chunk, out_file=cf, tag=tag if whole else f"{tag}-c{k}",
251
+ live_meta={"all_ids": ids, "chunk": k, "chunks": len(chunks)}, **kw) or {}
252
+ except ExecutionError as e:
253
+ if not (lost_ok and e.timed_out and len(chunks) > 1):
254
+ raise
255
+ log_.warning("chunk %s of %s ran out of time with no report: its %s scenario(s) are recorded as timed out",
256
+ k + 1, len(chunks), len(chunk))
257
+ files[k] = str(timed_out_report(chunk, cf, f"{e} This pass ({len(chunk)} scenarios) stopped before it reported, "
258
+ "so they have no result of their own; the retry runs them again."))
259
+ lost.append(k)
260
+ last_err, timed_out = e, True
261
+ continue
262
  if res.get("run_dir"):
263
  dirs[k] = res["run_dir"]
264
+ done[k] = files[k] = str(cf)
265
+ code, timed_out = code or res.get("exit_code") or 0, timed_out or bool(res.get("timed_out"))
266
  if on_chunk:
267
  on_chunk(k, str(cf), len(chunks), res.get("run_dir"))
268
+ if last_err is not None and len(lost) == len(chunks): # nothing at all was learned: the attempt fails as one would
269
+ raise last_err
270
+ merge_chunk_reports([Path(files[k]) for k in range(len(chunks))], out_file)
271
  run_dirs = [dirs[k] for k in range(len(chunks)) if dirs.get(k)]
272
  return {"file": str(out_file), "run_dirs": run_dirs, "run_dir": run_dirs[-1] if run_dirs else None,
273
+ "chunks": len(chunks), "skipped_chunks": skipped, "lost_chunks": lost, "exit_code": code, "timed_out": timed_out,
274
+ "mode": kw.get("mode")}
275
+
276
+
277
+ def adopt_no_result(files: list) -> None:
278
+ """A scenario recorded as timed out (timed_out_report) has no spec file or title of its own, so the retry's result
279
+ could not be matched to it when attempts are merged: it takes them from the later attempt that ran it."""
280
+ first = Path(files[0])
281
+ try:
282
+ data = json.loads(first.read_text(encoding="utf-8"))
283
+ except (OSError, ValueError):
284
+ return
285
+ holes = [sp for sp in _walk_specs(data.get("suites")) if sp.get(NO_RESULT)]
286
+ if not holes:
287
+ return
288
+ real: dict[str, dict] = {}
289
+ for f in files[1:]:
290
+ try:
291
+ later = json.loads(Path(f).read_text(encoding="utf-8"))
292
+ except (OSError, ValueError):
293
+ continue
294
+ for sp in _walk_specs(later.get("suites")):
295
+ if not sp.get(NO_RESULT):
296
+ for t in sp.get("tags") or []:
297
+ real.setdefault(str(t).lstrip("@"), sp)
298
+ changed = False
299
+ for sp in holes:
300
+ got = real.get(str(sp[NO_RESULT]))
301
+ if got:
302
+ sp.update({"file": got.get("file", ""), "title": got.get("title", sp["title"]), "tags": got.get("tags") or sp["tags"]})
303
+ sp.pop(NO_RESULT, None)
304
+ changed = True
305
+ if changed:
306
+ first.write_text(json.dumps(data, indent=1), encoding="utf-8")
307
 
308
 
309
  def attachments_by_case(report_file: Path) -> dict[str, str]:
coworker/adapters/remote_runner.py CHANGED
@@ -5,12 +5,18 @@ remote_runner.token, or FPT_SECRET_REMOTE_RUNNER_TOKEN): this host may sit on a
5
  attempt goes out through the egress gate (https, the runner's host only; the audit log never sees the password), is
6
  polled, and its bundle is unpacked where a local attempt would leave its files: the JSON report at out_file
7
  (attachment paths made absolute here), the run directory under automation/results/runs, the pod values tried and the
8
- ledger of created test records. Everything after that (evidence, triage, clean-up, reports) runs unchanged."""
 
 
 
 
 
9
  from __future__ import annotations
10
 
11
  import base64
12
  import io
13
  import json
 
14
  import re
15
  import time
16
  import zipfile
@@ -18,8 +24,17 @@ from pathlib import Path
18
 
19
  from .playwright import AUTOMATION, testdata_used_file
20
 
 
 
21
  ENV_KEYS = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
22
  "FPT_FUSION_WORKERS", "FPT_BROWSER_SLOWMO_MS")
 
 
 
 
 
 
 
23
 
24
 
25
  class RemoteRunnerError(RuntimeError):
@@ -65,6 +80,13 @@ def _absolutize(report: Path, run_dir: Path) -> None:
65
  report.write_text(json.dumps(data), encoding="utf-8")
66
 
67
 
 
 
 
 
 
 
 
68
  def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int | str) -> bool:
69
  with zipfile.ZipFile(io.BytesIO(blob)) as z:
70
  for info in z.infolist():
@@ -81,9 +103,8 @@ def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: s
81
  if dest is None:
82
  continue
83
  dest.parent.mkdir(parents=True, exist_ok=True)
84
- if name == "created.jsonl" and dest.exists(): # records made by an earlier pass stay listed for cleanup
85
- with dest.open("ab") as fh:
86
- fh.write(z.read(info))
87
  else:
88
  dest.write_bytes(z.read(info))
89
  if out_file.exists():
@@ -107,42 +128,111 @@ def runner_for(svc) -> tuple[str, str] | None:
107
  SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")
108
 
109
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
110
  def run_screens_remote(egress, base_url: str, token: str, *, kind: str, env: dict, out_dir: Path, plan: dict | None = None,
111
- task: str | None = None, timeout_s: int = 5400, on_line=None, poll_s: float = 5.0) -> tuple[int | None, list[str]]:
 
112
  """Read the pod's screens on the runner ("explore" with a plan, "capture" of one task). The files it wrote (inventories
113
- and list choices) land in out_dir; returns (exit code, the log's lines). on_line gets each new line as it comes."""
 
114
  base = base_url.rstrip("/")
115
  hdr = {"Authorization": f"Bearer {token}"}
116
  body = {"kind": kind, "env": {k: str(v) for k, v in (env or {}).items() if k in SCREEN_ENV and v}, "timeout_s": timeout_s,
117
  **({"plan": plan} if plan is not None else {}), **({"task": task} if task else {})}
118
- r = egress.service_request("remote_runner", "POST", base + "/v1/screens", allowed_base=base, json_body=body, headers=hdr,
119
- log_body={"kind": kind, "task": task, "areas": [a.get("code") for a in (plan or {}).get("areas") or [] if isinstance(a, dict)]},
120
- timeout=60)
121
- if r.status_code != 202:
122
- raise RemoteRunnerError(f"the remote browser runner refused the screen read (HTTP {r.status_code}: {r.text[:200]})")
123
- jid = r.json()["id"]
124
  deadline = time.time() + timeout_s + 300
125
- seen, st = 0, {}
126
  while True:
127
  time.sleep(poll_s)
128
- try:
129
- st = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}?since={seen}", allowed_base=base, headers=hdr,
130
- log_body=None, timeout=30).json()
131
- except Exception: # noqa: BLE001 - a dropped poll is tried again; the read keeps going on the runner
132
- st = {}
 
 
 
133
  new = st.get("lines") or []
134
  seen += len(new)
135
  if on_line:
136
  for line in new:
137
  on_line(line)
138
- if st.get("state") in ("done", "cancelled"):
 
 
139
  break
140
  if time.time() > deadline:
141
- egress.service_request("remote_runner", "POST", f"{base}/v1/attempts/{jid}/cancel", allowed_base=base, headers=hdr,
142
- log_body={"cancel": jid}, timeout=30)
143
  raise RemoteRunnerError(f"the remote browser runner did not finish reading the screens in {timeout_s // 60} minutes")
144
- z = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/bundle", allowed_base=base, headers=hdr,
145
- log_body=None, timeout=300)
146
  if z.status_code != 200:
147
  raise RemoteRunnerError(f"the remote browser runner did not return the screens (HTTP {z.status_code})")
148
  out = Path(out_dir)
@@ -187,69 +277,196 @@ def _pull_live(egress, base: str, hdr: dict, jid: str, live_dir: Path, seen: dic
187
  _write_atomic(live_dir, "failed.jpg", base64.b64decode(v["failed"]))
188
 
189
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
190
  def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
191
  cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
192
  log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0,
193
- live_dir: Path | None = None, live_meta: dict | None = None, tag: str = "") -> dict:
194
- """One attempt on the remote runner. `tag` names a pass of the attempt (one per test user) so passes keep their own
195
- run folder and log."""
 
 
 
196
  from ..platform.cleanup import LEDGER
197
  from ..platform.failures import ExecutionError
198
  base = base_url.rstrip("/")
199
  hdr = {"Authorization": f"Bearer {token}"}
200
  pw_run_id = f"fpt-{run_id}-a{attempt}{tag}"
201
- env = {k: str(v) for k, v in (cred_env or {}).items() if k in ENV_KEYS}
202
- if overrides_file and Path(overrides_file).exists():
203
- ov = json.loads(Path(overrides_file).read_text(encoding="utf-8") or "{}")
204
- if ov:
205
- env["PW_LOCATOR_OVERRIDES"] = json.dumps(ov)
206
- body = {"ids": ids, "pw_run_id": pw_run_id, "config": config, "env": env, "timeout_s": timeout_s,
207
- "drafts": _specs(drafts_dir), "library": _specs(library_dir)}
208
- body["steps"] = _step_yamls(body["drafts"], body["library"])
209
  if live_dir: # Live panel: the runner's browser hook writes frames there, this side copies them into the run
210
  from ..platform import liveview
211
  meta = {"attempt_key": f"{run_id}-a{attempt}", "attempt": attempt, "ids": ids, "all_ids": ids, "chunk": 0, "chunks": 1,
212
  **(live_meta or {})}
213
  liveview.prepare(Path(live_dir), meta)
214
- body["live"] = {"attempt": meta["attempt_key"]}
215
  poll_s = min(poll_s, 2.0)
216
- seen: dict = {}
217
- r = egress.service_request("remote_runner", "POST", base + "/v1/attempts", allowed_base=base, json_body=body, headers=hdr,
218
- log_body={"ids": ids, "config": config, "pw_run_id": pw_run_id, "specs": len(body["drafts"]) + len(body["library"]),
219
- "steps": len(body["steps"])},
220
- timeout=60)
221
- if r.status_code != 202:
222
- raise RemoteRunnerError(f"the remote browser runner refused the attempt (HTTP {r.status_code}: {r.text[:200]})")
223
- jid = r.json()["id"]
224
- deadline = time.time() + timeout_s + 300
225
- st = {}
226
  while True:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
227
  try:
228
- if kill:
229
- kill()
230
- except BaseException:
231
- egress.service_request("remote_runner", "POST", f"{base}/v1/attempts/{jid}/cancel", allowed_base=base, headers=hdr,
232
- log_body={"cancel": jid}, timeout=30)
233
  raise
234
- time.sleep(poll_s)
235
- try:
236
- st = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}", allowed_base=base, headers=hdr,
237
- log_body=None, timeout=30).json()
238
- except Exception: # noqa: BLE001 - a dropped poll is tried again; the attempt keeps running on the runner
239
- st = {}
240
- if live_dir and st.get("state") == "running":
241
- _pull_live(egress, base, hdr, jid, Path(live_dir), seen)
242
- if st.get("state") in ("done", "cancelled"):
243
- break
244
- if time.time() > deadline:
245
- raise ExecutionError("The remote browser runner did not finish the attempt in time.", timed_out=True, minutes=timeout_s // 60)
246
- z = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/bundle", allowed_base=base, headers=hdr,
247
- log_body=None, timeout=300)
248
- if z.status_code != 200:
249
- raise RemoteRunnerError(f"the remote browser runner did not return the results (HTTP {z.status_code})")
250
- run_dir = AUTOMATION / "results" / "runs" / pw_run_id
251
- if not _unpack(z.content, Path(out_file), run_dir, Path(log_dir), LEDGER, f"{attempt}{tag}"):
252
- raise ExecutionError(f"The remote browser run produced no report (exit {st.get('exit_code')}), so no scenario result was recorded.",
253
- exit_code=st.get("exit_code"), timed_out=bool(st.get("timed_out")), minutes=max(1, timeout_s // 60))
254
- return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(run_dir), "exit_code": st.get("exit_code"),
255
- "mode": "live", "timed_out": bool(st.get("timed_out")), "remote": True}
 
 
 
 
 
 
 
 
 
 
 
5
  attempt goes out through the egress gate (https, the runner's host only; the audit log never sees the password), is
6
  polled, and its bundle is unpacked where a local attempt would leave its files: the JSON report at out_file
7
  (attachment paths made absolute here), the run directory under automation/results/runs, the pod values tried and the
8
+ ledger of created test records. Everything after that (evidence, triage, clean-up, reports) runs unchanged.
9
+
10
+ The runner drives one browser job at a time. A job that finds it busy (HTTP 409) waits for it, for a bounded time. The
11
+ id of the job an attempt follows is kept in the run folder (remote-job.json) until its results are in, so a server that
12
+ restarts mid-attempt and is resumed follows the same job again instead of starting a second one, and a runner that
13
+ restarted (it no longer knows the job, or reports it "lost") fails the attempt in seconds instead of at its deadline."""
14
  from __future__ import annotations
15
 
16
  import base64
17
  import io
18
  import json
19
+ import logging
20
  import re
21
  import time
22
  import zipfile
 
24
 
25
  from .playwright import AUTOMATION, testdata_used_file
26
 
27
+ log = logging.getLogger("fpt.remote_runner")
28
+
29
  ENV_KEYS = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES",
30
  "FPT_FUSION_WORKERS", "FPT_BROWSER_SLOWMO_MS")
31
+ JOB_FILE = "remote-job.json"
32
+ JOB_ID = re.compile(r"job_[0-9a-f]{12}")
33
+ # a job's last states; "failed" (the runner's own error) and "lost" (it restarted mid-job) come from runners that keep
34
+ # their jobs across a restart, older ones only say done or cancelled
35
+ ENDED = ("done", "cancelled", "failed", "lost")
36
+ GONE_AFTER = 2 # consecutive 404s for a job: the runner restarted and no longer knows it
37
+ BUSY_WAIT_S = 900 # how long a job waits for a busy runner when the caller does not say (Settings has the knob)
38
 
39
 
40
  class RemoteRunnerError(RuntimeError):
 
80
  report.write_text(json.dumps(data), encoding="utf-8")
81
 
82
 
83
+ def _append(dest: Path, data: bytes) -> None:
84
+ """JSON lines from one more pass (or job) go after the earlier ones, each pass starting its own line."""
85
+ dest.parent.mkdir(parents=True, exist_ok=True)
86
+ with dest.open("ab") as fh:
87
+ fh.write(data if not data or data.endswith(b"\n") else data + b"\n")
88
+
89
+
90
  def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int | str) -> bool:
91
  with zipfile.ZipFile(io.BytesIO(blob)) as z:
92
  for info in z.infolist():
 
103
  if dest is None:
104
  continue
105
  dest.parent.mkdir(parents=True, exist_ok=True)
106
+ if name in ("created.jsonl", "testdata-used.jsonl"): # an earlier pass's records and values stay listed
107
+ _append(dest, z.read(info))
 
108
  else:
109
  dest.write_bytes(z.read(info))
110
  if out_file.exists():
 
128
  SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")
129
 
130
 
131
+ def _call(egress, base: str, hdr: dict, method: str, path: str, *, log_body=None, json_body=None, timeout: float = 30):
132
+ return egress.service_request("remote_runner", method, base + path, allowed_base=base, json_body=json_body, headers=hdr,
133
+ log_body=log_body, timeout=timeout)
134
+
135
+
136
+ def _cancel(egress, base: str, hdr: dict, jid: str) -> None:
137
+ """Ask the runner to stop a job (it frees the browser for the next one). Never raises: a runner that does not answer
138
+ stops the job at its own deadline."""
139
+ try:
140
+ _call(egress, base, hdr, "POST", f"/v1/attempts/{jid}/cancel", log_body={"cancel": jid})
141
+ except Exception as e: # noqa: BLE001
142
+ log.warning("could not cancel runner job %s: %s", jid, type(e).__name__)
143
+
144
+
145
+ def _pause(seconds: float, kill=None) -> None:
146
+ """Sleep in short steps, so a cancelled run or the kill switch is noticed while it waits."""
147
+ end = time.time() + seconds
148
+ while True:
149
+ if kill:
150
+ kill()
151
+ left = end - time.time()
152
+ if left <= 0:
153
+ return
154
+ time.sleep(min(5.0, left))
155
+
156
+
157
+ def _start_job(egress, base: str, hdr: dict, path: str, body: dict, log_body: dict, *, what: str, busy_wait_s: float,
158
+ on_wait=None, kill=None) -> str:
159
+ """Start a job on the runner and return its id. The runner drives one browser at a time and answers 409 while another
160
+ job runs (another run, a screen read, or a job of this run from before a restart that is ending): that is waited for,
161
+ with growing pauses, for up to busy_wait_s, and only then refused. on_wait(message) hears once that it waits."""
162
+ first, pause, told = time.time(), 10.0, False
163
+ while True:
164
+ r = _call(egress, base, hdr, "POST", path, json_body=body, log_body=log_body, timeout=60)
165
+ if r.status_code == 202:
166
+ if told:
167
+ log.info("the remote browser runner is free: the %s starts", what)
168
+ return r.json()["id"]
169
+ waited = time.time() - first
170
+ if r.status_code != 409:
171
+ raise RemoteRunnerError(f"the remote browser runner refused the {what} (HTTP {r.status_code}: {r.text[:200]})")
172
+ if waited >= busy_wait_s:
173
+ raise RemoteRunnerError(f"the remote browser runner stayed busy with another job for {max(1, round(waited / 60))} "
174
+ f"minutes, so the {what} could not start: try again when it is free")
175
+ if not told:
176
+ told = True
177
+ msg = (f"Waiting for the browser runner: it is busy with another job (the {what} waits up to "
178
+ f"{max(1, round(busy_wait_s / 60))} minutes).")
179
+ log.info(msg)
180
+ if on_wait:
181
+ on_wait(msg)
182
+ _pause(min(pause, max(1.0, busy_wait_s - waited)), kill)
183
+ pause = min(pause * 2, 60.0)
184
+
185
+
186
+ def _status(egress, base: str, hdr: dict, jid: str, query: str = "") -> tuple[int, dict]:
187
+ """(HTTP status, body) of one poll; (0, {}) when the poll itself was dropped (it is tried again)."""
188
+ try:
189
+ r = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}{query}")
190
+ except Exception: # noqa: BLE001 - a dropped poll is tried again; the job keeps running on the runner
191
+ return 0, {}
192
+ try:
193
+ return r.status_code, (r.json() if r.status_code == 200 else {})
194
+ except ValueError:
195
+ return r.status_code, {}
196
+
197
+
198
  def run_screens_remote(egress, base_url: str, token: str, *, kind: str, env: dict, out_dir: Path, plan: dict | None = None,
199
+ task: str | None = None, timeout_s: int = 5400, on_line=None, poll_s: float = 5.0,
200
+ busy_wait_s: float = BUSY_WAIT_S, on_wait=None) -> tuple[int | None, list[str]]:
201
  """Read the pod's screens on the runner ("explore" with a plan, "capture" of one task). The files it wrote (inventories
202
+ and list choices) land in out_dir; returns (exit code, the log's lines). on_line gets each new line as it comes;
203
+ on_wait(message) hears that the read waits for a busy runner."""
204
  base = base_url.rstrip("/")
205
  hdr = {"Authorization": f"Bearer {token}"}
206
  body = {"kind": kind, "env": {k: str(v) for k, v in (env or {}).items() if k in SCREEN_ENV and v}, "timeout_s": timeout_s,
207
  **({"plan": plan} if plan is not None else {}), **({"task": task} if task else {})}
208
+ jid = _start_job(egress, base, hdr, "/v1/screens", body,
209
+ {"kind": kind, "task": task, "areas": [a.get("code") for a in (plan or {}).get("areas") or [] if isinstance(a, dict)]},
210
+ what="screen read", busy_wait_s=busy_wait_s, on_wait=on_wait)
 
 
 
211
  deadline = time.time() + timeout_s + 300
212
+ seen, gone, st = 0, 0, {}
213
  while True:
214
  time.sleep(poll_s)
215
+ code, st = _status(egress, base, hdr, jid, f"?since={seen}")
216
+ if code == 404:
217
+ gone += 1
218
+ if gone >= GONE_AFTER:
219
+ raise RemoteRunnerError("the remote browser runner no longer knows this screen read: it restarted while it ran")
220
+ continue
221
+ if code:
222
+ gone = 0
223
  new = st.get("lines") or []
224
  seen += len(new)
225
  if on_line:
226
  for line in new:
227
  on_line(line)
228
+ if st.get("state") == "lost":
229
+ raise RemoteRunnerError("the remote browser runner restarted while it read the screens, so the read was lost")
230
+ if st.get("state") in ENDED:
231
  break
232
  if time.time() > deadline:
233
+ _cancel(egress, base, hdr, jid)
 
234
  raise RemoteRunnerError(f"the remote browser runner did not finish reading the screens in {timeout_s // 60} minutes")
235
+ z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)
 
236
  if z.status_code != 200:
237
  raise RemoteRunnerError(f"the remote browser runner did not return the screens (HTTP {z.status_code})")
238
  out = Path(out_dir)
 
277
  _write_atomic(live_dir, "failed.jpg", base64.b64decode(v["failed"]))
278
 
279
 
280
+ # ------------------------------------------------------------------ the job an attempt follows, kept in the run folder
281
+ def saved_job(run_dir: Path) -> dict | None:
282
+ """The runner job a run's attempt was following when this server last stopped, or None."""
283
+ try:
284
+ job = json.loads((Path(run_dir) / JOB_FILE).read_text(encoding="utf-8"))
285
+ except (OSError, ValueError):
286
+ return None
287
+ return job if isinstance(job, dict) and JOB_ID.fullmatch(str(job.get("job_id") or "")) else None
288
+
289
+
290
+ def _save_job(run_dir: Path, job: dict) -> None:
291
+ d = Path(run_dir)
292
+ d.mkdir(parents=True, exist_ok=True)
293
+ tmp = d / f".{JOB_FILE}.tmp"
294
+ tmp.write_text(json.dumps(job), encoding="utf-8")
295
+ tmp.replace(d / JOB_FILE)
296
+
297
+
298
+ def _drop_job(run_dir: Path, jid: str) -> None:
299
+ job = saved_job(run_dir)
300
+ if job and job["job_id"] == jid:
301
+ (Path(run_dir) / JOB_FILE).unlink(missing_ok=True)
302
+
303
+
304
+ def _salvage(egress, base: str, hdr: dict, jid: str, log_dir: Path, ledger: str, wait_s: float = 90.0) -> bool:
305
+ """Keep the ledger of test records a job made when its results are not used (it was stopped, overran, or belongs to
306
+ a pass nobody follows any more), so the run's clean-up still finds them. True when the runner answered. Never raises."""
307
+ try:
308
+ end = time.time() + wait_s
309
+ while True:
310
+ code, st = _status(egress, base, hdr, jid)
311
+ if code == 404:
312
+ return True # nothing left to fetch
313
+ if code == 200 and st.get("state") != "running" or time.time() > end:
314
+ break
315
+ time.sleep(3)
316
+ z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)
317
+ if z.status_code != 200:
318
+ return False
319
+ with zipfile.ZipFile(io.BytesIO(z.content)) as zf:
320
+ if "created.jsonl" in zf.namelist():
321
+ _append(Path(log_dir) / ledger, zf.read("created.jsonl"))
322
+ return True
323
+ except Exception as e: # noqa: BLE001 - salvage is best effort
324
+ log.warning("could not fetch the records runner job %s made: %s", jid, type(e).__name__)
325
+ return False
326
+
327
+
328
+ def release_job(svc, run_id: str) -> bool:
329
+ """A run that will not follow its runner job any more (it was cancelled after a restart left the job running): stop
330
+ the job so the runner is free for the next run, and keep the records it made for the clean-up. Never raises."""
331
+ from ..platform.cleanup import LEDGER
332
+ try:
333
+ run_dir = svc.run_dir(run_id)
334
+ job = saved_job(run_dir)
335
+ rt = runner_for(svc) if job else None
336
+ if not job or not rt:
337
+ return False
338
+ base, hdr = rt[0], {"Authorization": f"Bearer {rt[1]}"}
339
+ if job.get("base_url") == base:
340
+ _cancel(svc.egress, base, hdr, job["job_id"])
341
+ _salvage(svc.egress, base, hdr, job["job_id"], run_dir, LEDGER)
342
+ _drop_job(run_dir, job["job_id"])
343
+ return True
344
+ except Exception: # noqa: BLE001
345
+ log.exception("could not release the runner job of run %s", run_id)
346
+ return False
347
+
348
+
349
+ def _follow(egress, base: str, hdr: dict, jid: str, deadline: float, *, kill, poll_s: float, live_dir: Path | None) -> dict | None:
350
+ """Poll a job until it ends: its last status, {"state": "overdue"} past the deadline, or None when the runner no
351
+ longer knows it (GONE_AFTER 404s in a row: it restarted and lost its jobs)."""
352
+ seen: dict = {}
353
+ gone = 0
354
+ while True:
355
+ if kill:
356
+ kill()
357
+ time.sleep(poll_s)
358
+ code, st = _status(egress, base, hdr, jid)
359
+ if code == 404:
360
+ gone += 1
361
+ if gone >= GONE_AFTER:
362
+ return None
363
+ continue
364
+ if code:
365
+ gone = 0
366
+ if live_dir and st.get("state") == "running":
367
+ _pull_live(egress, base, hdr, jid, Path(live_dir), seen)
368
+ if st.get("state") in ENDED:
369
+ return st
370
+ if time.time() > deadline:
371
+ return {"state": "overdue"}
372
+
373
+
374
+ def _resumable(egress, base: str, hdr: dict, log_dir: Path, pw_run_id: str, out_file: Path, ledger: str) -> dict | None:
375
+ """The saved job of this very pass (same runner, same pass id and report file), to be followed again after a
376
+ restart. A saved job of another pass (the plan changed) is not: it is stopped so it frees the runner, its records kept."""
377
+ job = saved_job(log_dir)
378
+ if not job:
379
+ return None
380
+ if job.get("base_url") == base and job.get("pw_run_id") == pw_run_id and job.get("out_file") == str(out_file):
381
+ return job
382
+ if job.get("base_url") == base:
383
+ _cancel(egress, base, hdr, job["job_id"])
384
+ _salvage(egress, base, hdr, job["job_id"], log_dir, ledger)
385
+ _drop_job(log_dir, job["job_id"])
386
+ return None
387
+
388
+
389
  def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path,
390
  cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None,
391
  log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0,
392
+ live_dir: Path | None = None, live_meta: dict | None = None, tag: str = "",
393
+ busy_wait_s: float = BUSY_WAIT_S, on_event=None) -> dict:
394
+ """One attempt on the remote runner. `tag` names a pass of the attempt (one per test user, one per chunk) so passes
395
+ keep their own run folder and log. While the job runs its id is kept in log_dir (the run folder): a resumed run whose
396
+ server restarted mid-pass follows the same job and gets its results; one the runner no longer knows starts again.
397
+ on_event(message) hears what a person watching the run should know (a wait for a busy runner, a re-attach)."""
398
  from ..platform.cleanup import LEDGER
399
  from ..platform.failures import ExecutionError
400
  base = base_url.rstrip("/")
401
  hdr = {"Authorization": f"Bearer {token}"}
402
  pw_run_id = f"fpt-{run_id}-a{attempt}{tag}"
403
+ out_file, log_dir = Path(out_file), Path(log_dir)
404
+ note = on_event or (lambda _msg: None)
405
+ live = None
 
 
 
 
 
406
  if live_dir: # Live panel: the runner's browser hook writes frames there, this side copies them into the run
407
  from ..platform import liveview
408
  meta = {"attempt_key": f"{run_id}-a{attempt}", "attempt": attempt, "ids": ids, "all_ids": ids, "chunk": 0, "chunks": 1,
409
  **(live_meta or {})}
410
  liveview.prepare(Path(live_dir), meta)
411
+ live = {"attempt": meta["attempt_key"]}
412
  poll_s = min(poll_s, 2.0)
413
+ job = _resumable(egress, base, hdr, log_dir, pw_run_id, out_file, LEDGER)
 
 
 
 
 
 
 
 
 
414
  while True:
415
+ if job:
416
+ jid, started, budget = job["job_id"], float(job.get("started") or time.time()), int(job.get("timeout_s") or timeout_s)
417
+ log.info("run %s: following runner job %s again (%s)", run_id, jid, pw_run_id)
418
+ note("Following the browser runner's job for this pass again: it started before the server restarted.")
419
+ else:
420
+ env = {k: str(v) for k, v in (cred_env or {}).items() if k in ENV_KEYS}
421
+ if overrides_file and Path(overrides_file).exists():
422
+ ov = json.loads(Path(overrides_file).read_text(encoding="utf-8") or "{}")
423
+ if ov:
424
+ env["PW_LOCATOR_OVERRIDES"] = json.dumps(ov)
425
+ body = {"ids": ids, "pw_run_id": pw_run_id, "config": config, "env": env, "timeout_s": timeout_s,
426
+ "drafts": _specs(drafts_dir), "library": _specs(library_dir), **({"live": live} if live else {})}
427
+ body["steps"] = _step_yamls(body["drafts"], body["library"])
428
+ jid = _start_job(egress, base, hdr, "/v1/attempts", body,
429
+ {"ids": ids, "config": config, "pw_run_id": pw_run_id, "specs": len(body["drafts"]) + len(body["library"]),
430
+ "steps": len(body["steps"])}, what="attempt", busy_wait_s=busy_wait_s, on_wait=note, kill=kill)
431
+ started, budget = time.time(), timeout_s
432
+ _save_job(log_dir, {"job_id": jid, "base_url": base, "attempt": attempt, "tag": tag, "pw_run_id": pw_run_id,
433
+ "out_file": str(out_file), "started": started, "timeout_s": timeout_s})
434
  try:
435
+ st = _follow(egress, base, hdr, jid, started + budget + 300, kill=kill, poll_s=poll_s, live_dir=live_dir)
436
+ except BaseException: # cancelled or the kill switch: stop the job and keep the records it made; when the
437
+ _cancel(egress, base, hdr, jid) # runner cannot be reached, the saved id lets a resume or a cancel collect them
438
+ if _salvage(egress, base, hdr, jid, log_dir, LEDGER, wait_s=30):
439
+ _drop_job(log_dir, jid)
440
  raise
441
+ if st is None:
442
+ _drop_job(log_dir, jid)
443
+ if job:
444
+ note("The browser runner no longer knows the job from before the restart (it restarted too): starting the pass again.")
445
+ job = None
446
+ continue
447
+ raise RemoteRunnerError("the remote browser runner no longer knows this attempt: it restarted while the attempt ran, "
448
+ "so its results are lost")
449
+ if st.get("state") == "overdue":
450
+ _cancel(egress, base, hdr, jid)
451
+ _salvage(egress, base, hdr, jid, log_dir, LEDGER)
452
+ _drop_job(log_dir, jid)
453
+ raise ExecutionError("The remote browser runner did not finish the attempt in time.", timed_out=True,
454
+ minutes=max(1, budget // 60))
455
+ z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)
456
+ if z.status_code != 200:
457
+ _drop_job(log_dir, jid)
458
+ raise RemoteRunnerError(f"the remote browser runner did not return the results (HTTP {z.status_code})")
459
+ run_dir = AUTOMATION / "results" / "runs" / pw_run_id
460
+ got = _unpack(z.content, out_file, run_dir, log_dir, LEDGER, f"{attempt}{tag}")
461
+ _drop_job(log_dir, jid)
462
+ if not got and job and st.get("state") in ("lost", "cancelled"): # the old job died with no report: run it again
463
+ note("The browser runner's job from before the restart ended without results: starting the pass again.")
464
+ job = None
465
+ continue
466
+ if not got and st.get("state") == "lost":
467
+ raise RemoteRunnerError("the remote browser runner restarted while the attempt ran, so its results are lost")
468
+ if not got:
469
+ raise ExecutionError(f"The remote browser run produced no report (exit {st.get('exit_code')}), so no scenario result was recorded.",
470
+ exit_code=st.get("exit_code"), timed_out=bool(st.get("timed_out")), minutes=max(1, budget // 60))
471
+ return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(run_dir), "exit_code": st.get("exit_code"),
472
+ "mode": "live", "timed_out": bool(st.get("timed_out")), "remote": True}
coworker/adapters/screens.py CHANGED
@@ -97,6 +97,15 @@ def _remote(svc):
97
  return runner_for(svc)
98
 
99
 
 
 
 
 
 
 
 
 
 
100
  def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int = 1200, svc=None) -> dict:
101
  """Run the capture CLI against the pod in `env` (FUSION_BASE_URL/USERNAME/PASSWORD from PodRegistry.executor_env)
102
  and return the stored inventory. Nothing is saved on the pod; the credentials go to the child process only. With a
@@ -113,7 +122,8 @@ def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int
113
  if remote:
114
  from .remote_runner import RemoteRunnerError, run_screens_remote
115
  try:
116
- rc, lines = run_screens_remote(svc.egress, *remote, kind="capture", env=env, out_dir=out, task=task, timeout_s=timeout_s)
 
117
  except RemoteRunnerError as e:
118
  raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed on the remote runner: {e}", 502) from None
119
  text = _scrub("\n".join(lines), env)
@@ -174,7 +184,8 @@ def explore(plan: dict, env: dict, out_dir: Path, *, timeout_s: int = 5400, on_l
174
  on_line(line[len("[explore] "):])
175
  try:
176
  rc, raw_lines = run_screens_remote(svc.egress, *remote, kind="explore", env=env, out_dir=out, plan=plan,
177
- timeout_s=timeout_s, on_line=relay)
 
178
  except RemoteRunnerError as e:
179
  raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed on the remote runner: {e}", 502) from None
180
  lines = [_scrub(line, env).rstrip() for line in raw_lines]
 
97
  return runner_for(svc)
98
 
99
 
100
+ def _busy_wait_s(svc) -> float:
101
+ """How long a screen read waits for a busy remote runner (Settings.remote_runner_busy_wait_minutes)."""
102
+ from .remote_runner import BUSY_WAIT_S
103
+ try:
104
+ return 60.0 * float(svc.cfg.remote_runner_busy_wait_minutes)
105
+ except (AttributeError, TypeError, ValueError):
106
+ return BUSY_WAIT_S
107
+
108
+
109
  def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int = 1200, svc=None) -> dict:
110
  """Run the capture CLI against the pod in `env` (FUSION_BASE_URL/USERNAME/PASSWORD from PodRegistry.executor_env)
111
  and return the stored inventory. Nothing is saved on the pod; the credentials go to the child process only. With a
 
122
  if remote:
123
  from .remote_runner import RemoteRunnerError, run_screens_remote
124
  try:
125
+ rc, lines = run_screens_remote(svc.egress, *remote, kind="capture", env=env, out_dir=out, task=task, timeout_s=timeout_s,
126
+ busy_wait_s=_busy_wait_s(svc))
127
  except RemoteRunnerError as e:
128
  raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed on the remote runner: {e}", 502) from None
129
  text = _scrub("\n".join(lines), env)
 
184
  on_line(line[len("[explore] "):])
185
  try:
186
  rc, raw_lines = run_screens_remote(svc.egress, *remote, kind="explore", env=env, out_dir=out, plan=plan,
187
+ timeout_s=timeout_s, on_line=relay, busy_wait_s=_busy_wait_s(svc),
188
+ on_wait=on_line)
189
  except RemoteRunnerError as e:
190
  raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed on the remote runner: {e}", 502) from None
191
  lines = [_scrub(line, env).rstrip() for line in raw_lines]
coworker/api/app.py CHANGED
@@ -84,7 +84,7 @@ def create_app(svc: Services | None = None, cfg: Settings | None = None, *, back
84
  log.info("state is saved to Supabase Storage every %ss when it changes", syncer.interval)
85
  yield
86
  if syncer: # save first: the host may stop this process before the services below have all stopped
87
- syncer.tick("shutdown")
88
  if getattr(app.state, "courier", None):
89
  app.state.courier.stop()
90
  sched.stop()
 
84
  log.info("state is saved to Supabase Storage every %ss when it changes", syncer.interval)
85
  yield
86
  if syncer: # save first: the host may stop this process before the services below have all stopped
87
+ syncer.tick("shutdown", force=True)
88
  if getattr(app.state, "courier", None):
89
  app.state.courier.stop()
90
  sched.stop()
coworker/api/routes/admin.py CHANGED
@@ -99,7 +99,7 @@ def save_storage_now(request: Request, user: Principal = Depends(require("admin"
99
  syncer = getattr(request.app.state, "syncer", None)
100
  if syncer is None:
101
  raise ApiError(409, "NOT_SAVING", "this server does not save its state (no state store configured)")
102
- saved = syncer.tick("before restart")
103
  svc = request.app.state.svc
104
  svc.audit.append("state.saved_on_request", actor=user.username, summary="saved" if saved else "unchanged")
105
  last = svc.extra.get("state_last") or {}
 
99
  syncer = getattr(request.app.state, "syncer", None)
100
  if syncer is None:
101
  raise ApiError(409, "NOT_SAVING", "this server does not save its state (no state store configured)")
102
+ saved = syncer.tick("before restart", force=True)
103
  svc = request.app.state.svc
104
  svc.audit.append("state.saved_on_request", actor=user.username, summary="saved" if saved else "unchanged")
105
  last = svc.extra.get("state_last") or {}
coworker/api/routes/agent_studio.py CHANGED
@@ -3,20 +3,22 @@
3
  For the Fusion side (OAuth 2.0 client credentials, scope patchwise.invoke):
4
  POST /oauth/token client_credentials -> bearer token (one hour)
5
  POST /api/agent-studio/v1/test-data/check is this test data acceptable (synthetic, well formed)?
6
- POST /api/agent-studio/v1/cycles approved synthetic test data starts a test cycle
 
7
  GET /api/agent-studio/v1/cycles/{cycle_id} where the cycle is
8
  POST /api/agent-studio/v1/cycles/{cycle_id}/approval the person's start-testing decision, made in Fusion
9
  POST /api/agent-studio/v1/events/claim delivery mode pull: pick up waiting events
10
  POST /api/agent-studio/v1/events/ack confirm them
11
 
12
- For Patchwise administrators (signed-in session): clients, cycles, callbacks sent, the release watch, the stand-in."""
 
13
  from __future__ import annotations
14
 
15
  import base64
16
  import json
17
  from typing import Any, Literal
18
 
19
- from fastapi import APIRouter, Depends, Request
20
  from pydantic import BaseModel, Field
21
 
22
  from ...platform.agent_studio import AgentStudio, AgentStudioError, verify_signature
@@ -126,11 +128,18 @@ def check_test_data(body: dict, request: Request, client: dict = Depends(agent_c
126
 
127
 
128
  @router.post("/agent-studio/v1/cycles", status_code=202, summary="Start a test cycle with approved synthetic test data")
129
- def start_cycle(body: CycleIn, request: Request, client: dict = Depends(agent_client)):
 
 
 
130
  try:
131
- return _studio(request).start_cycle(client, body.model_dump(exclude_none=True), request.app.state.runs)
 
132
  except AgentStudioError as e:
133
  _fail(e)
 
 
 
134
 
135
 
136
  @router.get("/agent-studio/v1/cycles/{cycle_id}", summary="Where a test cycle is")
@@ -169,8 +178,9 @@ class AckIn(BaseModel):
169
 
170
  @router.post("/agent-studio/v1/events/claim", summary="Pick up waiting events (delivery mode pull)")
171
  def claim_events(body: ClaimIn, request: Request, client: dict = Depends(agent_client)):
172
- """The events Patchwise would have sent (scripts_ready, failures_need_review, results, stopped, patch_update), oldest
173
- first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again."""
 
174
  return _studio(request).claim(client["client_id"], body.max, body.cycle_id)
175
 
176
 
@@ -264,8 +274,20 @@ def list_cycles(request: Request, user: Principal = Depends(require("read"))):
264
 
265
 
266
  @router.get("/agent-studio/deliveries")
267
- def list_deliveries(request: Request, user: Principal = Depends(require("admin"))):
268
- return {"items": _studio(request).deliveries()}
 
 
 
 
 
 
 
 
 
 
 
 
269
 
270
 
271
  @router.get("/agent-studio/release-watch")
 
3
  For the Fusion side (OAuth 2.0 client credentials, scope patchwise.invoke):
4
  POST /oauth/token client_credentials -> bearer token (one hour)
5
  POST /api/agent-studio/v1/test-data/check is this test data acceptable (synthetic, well formed)?
6
+ POST /api/agent-studio/v1/cycles approved synthetic test data starts a test cycle (a retry with the
7
+ same Idempotency-Key or correlation_id returns that cycle)
8
  GET /api/agent-studio/v1/cycles/{cycle_id} where the cycle is
9
  POST /api/agent-studio/v1/cycles/{cycle_id}/approval the person's start-testing decision, made in Fusion
10
  POST /api/agent-studio/v1/events/claim delivery mode pull: pick up waiting events
11
  POST /api/agent-studio/v1/events/ack confirm them
12
 
13
+ For Astra administrators (signed-in session): clients, cycles, callbacks sent (dead letters sent again), the release
14
+ watch, the stand-in."""
15
  from __future__ import annotations
16
 
17
  import base64
18
  import json
19
  from typing import Any, Literal
20
 
21
+ from fastapi import APIRouter, Depends, Request, Response
22
  from pydantic import BaseModel, Field
23
 
24
  from ...platform.agent_studio import AgentStudio, AgentStudioError, verify_signature
 
128
 
129
 
130
  @router.post("/agent-studio/v1/cycles", status_code=202, summary="Start a test cycle with approved synthetic test data")
131
+ def start_cycle(body: CycleIn, request: Request, response: Response, client: dict = Depends(agent_client)):
132
+ """Safe to send again: with the same Idempotency-Key header (optional), or the same correlation_id while that cycle
133
+ is still going, it starts nothing and answers with the cycle the first call made (202, same body; the header
134
+ Idempotent-Replayed: true says so)."""
135
  try:
136
+ cycle, replayed = _studio(request).start_or_replay(client, body.model_dump(exclude_none=True), request.app.state.runs,
137
+ request.headers.get("idempotency-key"))
138
  except AgentStudioError as e:
139
  _fail(e)
140
+ if replayed:
141
+ response.headers["Idempotent-Replayed"] = "true"
142
+ return cycle
143
 
144
 
145
  @router.get("/agent-studio/v1/cycles/{cycle_id}", summary="Where a test cycle is")
 
178
 
179
  @router.post("/agent-studio/v1/events/claim", summary="Pick up waiting events (delivery mode pull)")
180
  def claim_events(body: ClaimIn, request: Request, client: dict = Depends(agent_client)):
181
+ """The events Astra would have sent (scripts_ready, failures_need_review, results, stopped, paused, patch_update), oldest
182
+ first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again (at least once:
183
+ the same event keeps its delivery_id)."""
184
  return _studio(request).claim(client["client_id"], body.max, body.cycle_id)
185
 
186
 
 
274
 
275
 
276
  @router.get("/agent-studio/deliveries")
277
+ def list_deliveries(request: Request, state: Literal["dead"] | None = None, user: Principal = Depends(require("admin"))):
278
+ """The callbacks, newest first, each with its state (queued, picked_up, retrying, delivered, superseded, dead).
279
+ ?state=dead lists the dead letters only: events that ran out of tries; send one again with .../requeue."""
280
+ studio = _studio(request)
281
+ return {"items": studio.deliveries(state=state), "dead_letters": studio.dead_letters()}
282
+
283
+
284
+ @router.post("/agent-studio/deliveries/{delivery_id}/requeue")
285
+ def requeue_delivery(delivery_id: str, request: Request, user: Principal = Depends(require("admin"))):
286
+ """Send a dead letter (or an event still retrying) again: its tries start over, with the same delivery_id."""
287
+ try:
288
+ return _studio(request).requeue(delivery_id, user.username)
289
+ except AgentStudioError as e:
290
+ _fail(e)
291
 
292
 
293
  @router.get("/agent-studio/release-watch")
coworker/api/runner.py CHANGED
@@ -88,9 +88,11 @@ def _create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod
88
  "inputs": state, "status": "queued", "orchestrator": orchestrator, "pod_id": pod["id"]})
89
 
90
 
91
- def create_run_record(svc, inputs: dict, actor: str, trigger: str = "manual", orchestrator: str = "langgraph") -> tuple[str, dict]:
 
92
  """Validate inputs, create the run row (status queued), the initial shared state, the queued event and the audit entry.
93
- Shared by both orchestrators (LangGraph RunManager and the Temporal one)."""
 
94
  svc.kill.check("run.start")
95
  from ..platform.pods import PodError, PodRegistry
96
  reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)
@@ -110,7 +112,7 @@ def create_run_record(svc, inputs: dict, actor: str, trigger: str = "manual", or
110
  if failed:
111
  svc.db.update("pods", "id", pod["id"], last_check_at=now_iso(), last_check_ok=0, last_check_detail=failed["detail"])
112
  raise RunError(f"{pod['name']}: {failed['detail']}", "POD_CHECK_FAILED", 409)
113
- rid = new_run_id()
114
  mods = [m.upper() for m in inputs.get("modules") or []]
115
  state = {"run_id": rid, "patch_id": inputs.get("patch_id") or "", "trigger": trigger, "modules_requested": mods,
116
  "include_p2": bool(inputs.get("include_p2")), "case_filter": [str(x) for x in inputs.get("case_ids") or []],
@@ -210,8 +212,8 @@ class RunManager:
210
  self._execute(*job)
211
 
212
  # ------------------------------------------------------------ API
213
- def start(self, inputs: dict, actor: str, trigger: str = "manual") -> str:
214
- rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph")
215
  self._enqueue("start", rid, state)
216
  return rid
217
 
@@ -253,7 +255,14 @@ class RunManager:
253
  from ..platform.statesync import save_soon
254
  save_soon("run cancelled")
255
  if self.current != run_id: # a running one is swept by the worker once Playwright is gone
256
- threading.Thread(target=sweep_test_data, args=(self.svc, run_id, "cancelled"), daemon=True).start()
 
 
 
 
 
 
 
257
 
258
  def gate_payload(self, run_id: str) -> dict | None:
259
  snap = self.graph.get_state(run_config(run_id, self.svc.cfg))
 
88
  "inputs": state, "status": "queued", "orchestrator": orchestrator, "pod_id": pod["id"]})
89
 
90
 
91
+ def create_run_record(svc, inputs: dict, actor: str, trigger: str = "manual", orchestrator: str = "langgraph",
92
+ run_id: str | None = None) -> tuple[str, dict]:
93
  """Validate inputs, create the run row (status queued), the initial shared state, the queued event and the audit entry.
94
+ Shared by both orchestrators (LangGraph RunManager and the Temporal one). `run_id`: an id the caller reserved
95
+ beforehand (an Agent Studio cycle records it before the run exists); a new one otherwise."""
96
  svc.kill.check("run.start")
97
  from ..platform.pods import PodError, PodRegistry
98
  reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)
 
112
  if failed:
113
  svc.db.update("pods", "id", pod["id"], last_check_at=now_iso(), last_check_ok=0, last_check_detail=failed["detail"])
114
  raise RunError(f"{pod['name']}: {failed['detail']}", "POD_CHECK_FAILED", 409)
115
+ rid = run_id or new_run_id()
116
  mods = [m.upper() for m in inputs.get("modules") or []]
117
  state = {"run_id": rid, "patch_id": inputs.get("patch_id") or "", "trigger": trigger, "modules_requested": mods,
118
  "include_p2": bool(inputs.get("include_p2")), "case_filter": [str(x) for x in inputs.get("case_ids") or []],
 
212
  self._execute(*job)
213
 
214
  # ------------------------------------------------------------ API
215
+ def start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str:
216
+ rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph", run_id=run_id)
217
  self._enqueue("start", rid, state)
218
  return rid
219
 
 
255
  from ..platform.statesync import save_soon
256
  save_soon("run cancelled")
257
  if self.current != run_id: # a running one is swept by the worker once Playwright is gone
258
+ threading.Thread(target=self._release_and_sweep, args=(run_id,), daemon=True).start()
259
+
260
+ def _release_and_sweep(self, run_id: str) -> None:
261
+ """A cancelled run that is not running here may still own a job on the remote browser runner (a restart left it
262
+ running): stop it, so the runner is free, and fetch the records it made before the clean-up looks for them."""
263
+ from ..adapters.remote_runner import release_job
264
+ release_job(self.svc, run_id)
265
+ sweep_test_data(self.svc, run_id, "cancelled")
266
 
267
  def gate_payload(self, run_id: str) -> dict | None:
268
  snap = self.graph.get_state(run_config(run_id, self.svc.cfg))
coworker/config.py CHANGED
@@ -15,6 +15,25 @@ ROOT = Path(__file__).resolve().parents[1]
15
  CONFIG_YAML = Path(os.getenv("FPT_CONFIG", ROOT / "config" / "coworker.yaml"))
16
  VERSION = "1.0.0-pilot"
17
  MOCK_BANNER = "Mock app, not Oracle Fusion"
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
 
19
 
20
  def _alias(*names: str):
@@ -138,9 +157,24 @@ class Settings(BaseSettings):
138
  fusion_ai_scenarios_max: int = Field(12, validation_alias=_alias("fpt_fusion_ai_scenarios_max", "fusion_ai_scenarios_max"))
139
  # regression (depth full): end-to-end flows per area, one per business process, at most this many (0: none)
140
  fusion_regression_flows: int = Field(3, validation_alias=_alias("fpt_fusion_regression_flows", "fusion_regression_flows"))
 
 
 
141
  # browsers working at once on a Fusion pod (screen reading, dry runs, test runs) and areas the AI designs at once.
142
  # Fusion's own server is the slow part, so a small server still runs about 3 well; 1 = one at a time
143
  fusion_workers: int = Field(3, validation_alias=_alias("fpt_fusion_workers", "fusion_workers"))
 
 
 
 
 
 
 
 
 
 
 
 
144
  # read the screens of a Fusion pod's areas in the background as soon as they are discovered or its release changes,
145
  # so a run finds them ready instead of reading them itself
146
  fusion_screens_on_setup: bool = Field(True, validation_alias=_alias("fpt_fusion_screens_on_setup", "fusion_screens_on_setup"))
 
15
  CONFIG_YAML = Path(os.getenv("FPT_CONFIG", ROOT / "config" / "coworker.yaml"))
16
  VERSION = "1.0.0-pilot"
17
  MOCK_BANNER = "Mock app, not Oracle Fusion"
18
+ # where a deploy may record the commit it installed (deploy/runner/sync.sh writes the same file on a browser runner)
19
+ COMMIT_ENV = ("FPT_COMMIT", "GIT_COMMIT", "SOURCE_COMMIT", "RENDER_GIT_COMMIT")
20
+ COMMIT_FILE = ROOT / "VERSION"
21
+
22
+
23
+ def server_commit() -> str:
24
+ """The commit this server runs, when its deploy recorded one (an environment variable or a VERSION file at the repo
25
+ root); "" when it cannot know, and then nothing compares against it."""
26
+ import re
27
+ vals = [os.getenv(k) or "" for k in COMMIT_ENV]
28
+ try:
29
+ vals.append(COMMIT_FILE.read_text(encoding="utf-8") if COMMIT_FILE.is_file() else "")
30
+ except OSError:
31
+ pass
32
+ for v in vals:
33
+ v = v.strip().lower()
34
+ if re.fullmatch(r"[0-9a-f]{7,40}", v):
35
+ return v
36
+ return ""
37
 
38
 
39
  def _alias(*names: str):
 
157
  fusion_ai_scenarios_max: int = Field(12, validation_alias=_alias("fpt_fusion_ai_scenarios_max", "fusion_ai_scenarios_max"))
158
  # regression (depth full): end-to-end flows per area, one per business process, at most this many (0: none)
159
  fusion_regression_flows: int = Field(3, validation_alias=_alias("fpt_fusion_regression_flows", "fusion_regression_flows"))
160
+ # regression (depth full): the area's standard regression and edge-case checks (fusion_catalog "regression") that no
161
+ # library scenario covers yet, one AI-designed scenario each, at most this many per area (0: none)
162
+ fusion_regression_checks: int = Field(25, validation_alias=_alias("fpt_fusion_regression_checks", "fusion_regression_checks"))
163
  # browsers working at once on a Fusion pod (screen reading, dry runs, test runs) and areas the AI designs at once.
164
  # Fusion's own server is the slow part, so a small server still runs about 3 well; 1 = one at a time
165
  fusion_workers: int = Field(3, validation_alias=_alias("fpt_fusion_workers", "fusion_workers"))
166
+ # a browser pass on a Fusion pod gets this many minutes per scenario each worker runs (Playwright stops one test after
167
+ # 10), plus start-up, kept between the floor and the ceiling below; a pass past its time is stopped and loses its results
168
+ fusion_scenario_minutes: int = Field(12, validation_alias=_alias("fpt_fusion_scenario_minutes", "fusion_scenario_minutes"))
169
+ fusion_attempt_min_minutes: int = Field(30, validation_alias=_alias("fpt_fusion_attempt_min_minutes", "fusion_attempt_min_minutes"))
170
+ # the remote runner stops any job after 4 hours whatever is asked, so a higher ceiling only helps local browsers
171
+ fusion_attempt_max_minutes: int = Field(240, validation_alias=_alias("fpt_fusion_attempt_max_minutes", "fusion_attempt_max_minutes"))
172
+ # a bigger attempt on a Fusion pod runs as passes of this many scenarios, each with its own time budget and report,
173
+ # so a pass that runs out of time loses only its own scenarios and a resumed run keeps the finished passes (0: one pass)
174
+ fusion_chunk_scenarios: int = Field(24, validation_alias=_alias("fpt_fusion_chunk_scenarios", "fusion_chunk_scenarios"))
175
+ # the remote runner drives one browser job at a time: a run or screen read that finds it busy waits this long for it
176
+ remote_runner_busy_wait_minutes: int = Field(15, validation_alias=_alias("fpt_remote_runner_busy_wait_minutes",
177
+ "remote_runner_busy_wait_minutes"))
178
  # read the screens of a Fusion pod's areas in the background as soon as they are discovered or its release changes,
179
  # so a run finds them ready instead of reading them itself
180
  fusion_screens_on_setup: bool = Field(True, validation_alias=_alias("fpt_fusion_screens_on_setup", "fusion_screens_on_setup"))
coworker/graph/nodes/ai_scenarios.py CHANGED
@@ -268,6 +268,80 @@ def _design_area_flows(svc, run_id: str, area: str, processes: list[str], change
268
  module=area)
269
 
270
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
271
  # ====================================================================== writing
272
  def write_ai_scenarios(state, svc, library: list[dict]) -> dict:
273
  """{"cases": [test cases for drafts whose dry run passed], "drafts": [every AI draft with its result]}; {} when the
@@ -317,14 +391,17 @@ def write_ai_scenarios(state, svc, library: list[dict]) -> dict:
317
  auto = sum(1 for c in changes if c.get("on_by_default"))
318
  n = scenario_count(count, auto, int(svc.cfg.fusion_ai_scenarios_max or count), len(screens))
319
  titles = [c["title"] for c in library if c.get("module") == area and c.get("title")]
 
 
 
320
  try:
321
- intents = step_writer.design_scenarios(svc, area, processes, changes, screens, count=n,
322
  run_id=run_id, existing_titles=titles)
323
  except Exception as e: # noqa: BLE001
324
  _note(svc, run_id, f"{area}: the AI model could not design new scenarios ({type(e).__name__}).", module=area)
325
  return
326
  why = next((i.get("fallback_reason") for i in intents if i.get("fallback_reason")), None)
327
- intents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value)]
328
  if not intents: # say why: a model that was not reached is a fault to fix, not an empty answer
329
  _note(svc, run_id, f"{area}: no new scenario was written: "
330
  + (f"the AI model could not be used ({why[:200]})." if why else "the AI model proposed none for these screens."),
@@ -338,6 +415,9 @@ def write_ai_scenarios(state, svc, library: list[dict]) -> dict:
338
  flows = list(dict.fromkeys(list(cat.get("processes") or []) + step_writer.area_processes(area)))
339
  _design_area_flows(svc, run_id, area, flows, changes, screens, titles + [i["title"] for i in intents], example, taken,
340
  drafts, placeholders, lock)
 
 
 
341
 
342
  workers = max(1, min(int(svc.cfg.fusion_workers or 1), len(areas) or 1))
343
  with ThreadPoolExecutor(max_workers=workers, thread_name_prefix=f"design-{run_id[-6:]}") as ex:
 
268
  module=area)
269
 
270
 
271
+ PER_SCREEN = 3 # scenarios one screen may take in an area's general design (flows and regression checks aside)
272
+
273
+
274
+ def key_screens(screens: list[dict], key_tasks: list[str]) -> list[dict]:
275
+ """The screens of the area's key business tasks (catalog key_tasks, matched on the task's last part), in that order;
276
+ empty when none of them was read."""
277
+ last = lambda s: step_writer.norm_task(str(s.get("task") or "").split(">")[-1]) # noqa: E731
278
+ order = [step_writer.norm_task(k) for k in key_tasks]
279
+ return sorted((s for s in screens if last(s) in order), key=lambda s: order.index(last(s)))
280
+
281
+
282
+ def spread(intents) -> list[dict]:
283
+ """At most PER_SCREEN scenarios per screen, in the model's order: coverage across the area, not one screen's corners."""
284
+ out, per = [], {}
285
+ for i in intents:
286
+ k = step_writer.norm_task(str(i.get("task") or ""))
287
+ per[k] = per.get(k, 0) + 1
288
+ if per[k] <= PER_SCREEN:
289
+ out.append(i)
290
+ return out
291
+
292
+
293
+ REGRESSION_BATCH = 8 # regression checks asked of the model in one call (more makes its answers vaguer)
294
+
295
+
296
+ def regression_checks(checks: list, titles: list[str]) -> list[dict]:
297
+ """The area's catalog regression checks that no scenario covers yet (a title that says the same thing), taken one
298
+ process at a time in turn, so a cap still reaches every business process of the area."""
299
+ by_process: dict[str, list[dict]] = {}
300
+ for c in checks or []:
301
+ if not isinstance(c, dict) or not str(c.get("check") or "").strip():
302
+ continue
303
+ if not any(step_writer.same_title(c["check"], t) for t in titles):
304
+ by_process.setdefault(str(c.get("process") or ""), []).append(c)
305
+ out: list[dict] = []
306
+ queues = list(by_process.values())
307
+ while any(queues):
308
+ out += [q.pop(0) for q in queues if q]
309
+ return out
310
+
311
+
312
+ def _design_regression_checks(svc, run_id: str, area: str, checks: list, screens: list[dict], titles: list[str], example: str,
313
+ taken: set[str], drafts: list[dict], placeholders: list[str], lock=None) -> None:
314
+ """Regression (depth full): one scenario for each of the area's standard regression and edge-case checks
315
+ (fusion_catalog "regression") that the library and this run do not cover yet, at most FPT_FUSION_REGRESSION_CHECKS,
316
+ asked in batches. Each draft goes through the same step checks as every AI scenario: one whose steps fail them is
317
+ shown as not written and never offered as runnable."""
318
+ cap = max(0, int(svc.cfg.fusion_regression_checks or 0))
319
+ todo = regression_checks(checks, titles)[:cap]
320
+ if not todo:
321
+ return
322
+ seen, designed = list(titles), []
323
+ for start in range(0, len(todo), REGRESSION_BATCH):
324
+ batch = todo[start:start + REGRESSION_BATCH]
325
+ asks = [f"{c.get('process') or area}: regression check: {c['check']} (one scenario that tests exactly this)" for c in batch]
326
+ try: # no release changes here: those were covered first, these scenarios are the checks themselves
327
+ intents = step_writer.design_scenarios(svc, area, asks, [], screens, count=len(batch), run_id=run_id,
328
+ existing_titles=list(seen))
329
+ except Exception as e: # noqa: BLE001 - the model is down or refused: the next batches would fail the same way
330
+ _note(svc, run_id, f"{area}: the AI model could not design regression checks ({type(e).__name__})"
331
+ + (f"; {len(designed)} were designed before." if designed else "."), module=area)
332
+ return
333
+ intents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value)]
334
+ if intents:
335
+ _write_intents(svc, run_id, area, intents, screens, example, taken, drafts, placeholders, lock)
336
+ seen += [i["title"] for i in intents]
337
+ designed += intents
338
+ if designed:
339
+ _note(svc, run_id, f"{area}: {len(designed)} regression check(s) designed: " + "; ".join(i["title"] for i in designed)[:300] + ".",
340
+ module=area, asked=len(todo))
341
+ else:
342
+ _note(svc, run_id, f"{area}: no regression check was designed this time ({len(todo)} asked).", module=area, asked=len(todo))
343
+
344
+
345
  # ====================================================================== writing
346
  def write_ai_scenarios(state, svc, library: list[dict]) -> dict:
347
  """{"cases": [test cases for drafts whose dry run passed], "drafts": [every AI draft with its result]}; {} when the
 
391
  auto = sum(1 for c in changes if c.get("on_by_default"))
392
  n = scenario_count(count, auto, int(svc.cfg.fusion_ai_scenarios_max or count), len(screens))
393
  titles = [c["title"] for c in library if c.get("module") == area and c.get("title")]
394
+ # the area's main business screens (catalog key_tasks) first: given every screen read, the model once spent most
395
+ # of an AP run on a bank-file screen; flows and regression checks below still see every screen
396
+ key = key_screens(screens, cat.get("key_tasks") or [])
397
  try:
398
+ intents = step_writer.design_scenarios(svc, area, processes, changes, key or screens, count=n,
399
  run_id=run_id, existing_titles=titles)
400
  except Exception as e: # noqa: BLE001
401
  _note(svc, run_id, f"{area}: the AI model could not design new scenarios ({type(e).__name__}).", module=area)
402
  return
403
  why = next((i.get("fallback_reason") for i in intents if i.get("fallback_reason")), None)
404
+ intents = spread(i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value))
405
  if not intents: # say why: a model that was not reached is a fault to fix, not an empty answer
406
  _note(svc, run_id, f"{area}: no new scenario was written: "
407
  + (f"the AI model could not be used ({why[:200]})." if why else "the AI model proposed none for these screens."),
 
415
  flows = list(dict.fromkeys(list(cat.get("processes") or []) + step_writer.area_processes(area)))
416
  _design_area_flows(svc, run_id, area, flows, changes, screens, titles + [i["title"] for i in intents], example, taken,
417
  drafts, placeholders, lock)
418
+ # then every standard regression and edge-case check of the area that nothing above covers
419
+ _design_regression_checks(svc, run_id, area, cat.get("regression") or [], screens, titles + [d["title"] for d in drafts],
420
+ example, taken, drafts, placeholders, lock)
421
 
422
  workers = max(1, min(int(svc.cfg.fusion_workers or 1), len(areas) or 1))
423
  with ThreadPoolExecutor(max_workers=workers, thread_name_prefix=f"design-{run_id[-6:]}") as ex:
coworker/graph/nodes/execute.py CHANGED
@@ -66,14 +66,17 @@ def browser_failure(out_file: str | Path, res: dict | None) -> str | None:
66
  return why + (f": {errs[0]}" if errs and errs[0] else "") + "."
67
 
68
 
69
- def plan_attempt(state, svc, clean: bool = True) -> dict:
70
- """Which cases this attempt runs (attempt 0: in-scope; attempt 1: failed ids only) and the run_attempt arguments."""
 
71
  run_id = state["run_id"]
72
  run_dir = svc.run_dir(run_id)
73
  files = list(state.get("attempt_files") or [])
74
  attempt = len(files)
75
  mode = state.get("playwright_mode") or svc.cfg.playwright_mode
76
  if attempt == 0:
 
 
77
  if clean: # a fresh attempt 0 never reuses old reports (a resumed one keeps its finished chunks)
78
  for f in run_dir.glob("attempt-*.json"):
79
  f.unlink()
@@ -123,22 +126,138 @@ def user_groups(reg, pod_id: int, run_id: str, ids: list[str], module_of: dict[s
123
  return list(groups.values()) if len(groups) > 1 else None
124
 
125
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
126
  def run_planned(plan: dict, svc, **extra) -> dict:
127
- """Default runner: one Playwright invocation for the whole attempt (LangGraph path); one per test user when the
128
- areas sign in as different users (plan["groups"]), merged into the attempt's one report."""
 
129
  if plan.get("groups"):
130
  return run_groups(plan, svc, **extra)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  remote = (svc.cfg.remote_runner_url or "").strip()
132
- if remote and plan["mode"] == "live" and plan.get("config") == "playwright.fusion.config.ts":
133
  from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs there
134
  token = svc.vault.get("remote_runner.token") or ""
135
  if token:
136
  svc.redactor.add_secrets([token])
137
- return run_attempt_remote(svc.egress, remote, token, run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"],
 
 
 
 
 
138
  out_file=Path(plan["out_file"]), cred_env=plan["cred_env"], drafts_dir=Path(plan["drafts_dir"]),
139
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
140
  overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
141
- config=plan["config"], kill=lambda: svc.kill.check("executor.remote"),
 
 
142
  live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, tag=plan.get("tag") or "")
143
  if plan["mode"] == "live" and not plan.get("config"):
144
  pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
@@ -146,6 +265,10 @@ def run_planned(plan: dict, svc, **extra) -> dict:
146
  extra.setdefault("config", plan["config"])
147
  if plan.get("tag"):
148
  extra.setdefault("tag", plan["tag"])
 
 
 
 
149
  return pw.run_attempt(run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"], mode=plan["mode"],
150
  out_file=Path(plan["out_file"]), stub_knobs=plan["stub_knobs"], drafts_dir=Path(plan["drafts_dir"]),
151
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
@@ -199,6 +322,8 @@ def finish_attempt(state, svc, plan: dict, res: dict | None) -> dict:
199
  except Exception as e: # noqa: BLE001
200
  svc.audit.append("evidence.error", actor="system", run_id=run_id, summary=str(e)[:300])
201
  files = plan["files"] + [str(out_file)]
 
 
202
  merged = merge_attempts(files, Path(plan["run_dir"]) / "merged-results.json")
203
  outs, counts = outcomes(str(merged))
204
  fails = failing_ids(str(out_file)) if plan["ids"] else []
@@ -233,6 +358,7 @@ def executor(state, config, svc) -> dict:
233
  raise ExecutionError(f"The browser test run failed twice before any scenario ran. {why}", exit_code=(res or {}).get("exit_code"),
234
  timed_out=bool((res or {}).get("timed_out")))
235
  Path(plan["out_file"]).unlink(missing_ok=True)
 
236
  return finish_attempt(state, svc, plan, res)
237
 
238
 
@@ -243,7 +369,8 @@ def preflight_or_stop(state, svc, plan: dict) -> None:
243
  if pid is None:
244
  return
245
  from ...platform import preflight
246
- areas = sorted({c["module"] for c in state.get("test_cases") or []})
 
247
  results = preflight.check(svc, pid, plan["run_id"], areas)
248
  bad = preflight.problems(results)
249
  svc.db.add_event(plan["run_id"], "executor", "preflight", {"ok": not bad, "checks": results})
 
66
  return why + (f": {errs[0]}" if errs and errs[0] else "") + "."
67
 
68
 
69
+ def plan_attempt(state, svc, clean: bool | None = None) -> dict:
70
+ """Which cases this attempt runs (attempt 0: in-scope; attempt 1: failed ids only) and the run_attempt arguments.
71
+ clean: whether attempt 0 deletes old reports first; None decides it from the run folder (resumed_attempt)."""
72
  run_id = state["run_id"]
73
  run_dir = svc.run_dir(run_id)
74
  files = list(state.get("attempt_files") or [])
75
  attempt = len(files)
76
  mode = state.get("playwright_mode") or svc.cfg.playwright_mode
77
  if attempt == 0:
78
+ if clean is None:
79
+ clean = not resumed_attempt(run_dir)
80
  if clean: # a fresh attempt 0 never reuses old reports (a resumed one keeps its finished chunks)
81
  for f in run_dir.glob("attempt-*.json"):
82
  f.unlink()
 
126
  return list(groups.values()) if len(groups) > 1 else None
127
 
128
 
129
+ FUSION_CONFIG = "playwright.fusion.config.ts"
130
+ STARTUP_MINUTES = 10 # a pass's own start-up: Playwright, the browser and the test user's one sign-in
131
+
132
+
133
+ def attempt_timeout_s(cfg, scenarios: int, workers=None) -> int:
134
+ """How long a browser pass of this many scenarios on a Fusion pod may take: its scenarios shared over the workers that
135
+ run at once (FPT_FUSION_WORKERS), fusion_scenario_minutes each, plus start-up, kept between the floor and the ceiling.
136
+ A fixed hour stopped every big pass at its deadline, and a pass stopped that way loses all its results."""
137
+ w = max(1, min(4, int(workers or cfg.fusion_workers or 1)))
138
+ rounds = -(-max(1, int(scenarios)) // w)
139
+ minutes = STARTUP_MINUTES + rounds * max(1, int(cfg.fusion_scenario_minutes))
140
+ return 60 * max(int(cfg.fusion_attempt_min_minutes), min(int(cfg.fusion_attempt_max_minutes), minutes))
141
+
142
+
143
+ class RunCancelled(RuntimeError):
144
+ pass
145
+
146
+
147
+ def _stop_check(svc, run_id: str) -> None:
148
+ """Called while a remote pass runs: the kill switch, or a person cancelling the run, stops the runner's job too
149
+ (nothing else would: the browser is not a process of this server)."""
150
+ svc.kill.check("executor.remote")
151
+ r = svc.db.get_run(run_id)
152
+ if isinstance(r, dict) and r.get("status") == "cancelled":
153
+ raise RunCancelled(f"run {run_id} was cancelled")
154
+
155
+
156
+ def progress_file(out_file: str | Path) -> Path:
157
+ """Where a Fusion attempt lists its finished passes (next to its report; a fresh attempt 0 deletes it with the reports)."""
158
+ out = Path(out_file)
159
+ return out.with_name(f"{out.stem}.chunks.json")
160
+
161
+
162
+ def _finished_passes(prog: Path, ids: list[str], size: int) -> tuple[dict, dict]:
163
+ """(chunk -> report, chunk -> run dir) of the passes an earlier try of this attempt finished, when it planned the
164
+ same scenarios in the same passes; nothing otherwise."""
165
+ try:
166
+ d = json.loads(prog.read_text(encoding="utf-8"))
167
+ except (OSError, ValueError):
168
+ return {}, {}
169
+ if not isinstance(d, dict) or d.get("ids") != ids or d.get("size") != size:
170
+ return {}, {}
171
+ done = {int(k): v for k, v in (d.get("done") or {}).items() if Path(v).exists()}
172
+ return done, {k: v for k, v in ((int(k), v) for k, v in (d.get("dirs") or {}).items()) if k in done and v}
173
+
174
+
175
+ def forget_passes(out_file: str | Path) -> None:
176
+ """A try of the attempt is thrown away (nothing ran): its pass reports and their list go, so the next try runs all."""
177
+ out = Path(out_file)
178
+ for f in out.parent.glob(f"{out.stem}.*.json"):
179
+ f.unlink(missing_ok=True)
180
+
181
+
182
+ def resumed_attempt(run_dir: str | Path) -> bool:
183
+ """Attempt 0 entered again (the run was resumed after a restart or a failure) keeps its finished passes: a list of
184
+ them, or the runner job it was following, is still in the run folder. A first entry finds neither."""
185
+ from ...adapters.remote_runner import saved_job
186
+ job = saved_job(Path(run_dir))
187
+ return any(Path(run_dir).glob("attempt-0*.chunks.json")) or bool(job and job.get("attempt") == 0)
188
+
189
+
190
  def run_planned(plan: dict, svc, **extra) -> dict:
191
+ """Default runner (LangGraph path): one Playwright invocation for the attempt; one per test user when the areas sign
192
+ in as different users (plan["groups"]), merged into the attempt's one report. On a Fusion pod an attempt runs in
193
+ passes of at most fusion_chunk_scenarios, each with a time budget for its size (run_fusion)."""
194
  if plan.get("groups"):
195
  return run_groups(plan, svc, **extra)
196
+ if plan["mode"] == "live" and plan.get("config") == FUSION_CONFIG and plan["ids"]:
197
+ return run_fusion(plan, svc, **extra)
198
+ return run_pass(plan, svc, **extra)
199
+
200
+
201
+ def run_fusion(plan: dict, svc, **extra) -> dict:
202
+ """A browser attempt on a Fusion pod: passes of at most fusion_chunk_scenarios scenarios (pw.run_attempt_chunked, as
203
+ under Temporal), each with its own time budget and report, merged into the attempt's one report. A pass that runs
204
+ out of time loses only its own scenarios (recorded as timed out, so the retry runs them), and the finished passes are
205
+ listed next to the report so a resumed run skips them. An attempt that fits in one pass keeps its usual names."""
206
+ ids, out = list(plan["ids"]), Path(plan["out_file"])
207
+ size = int(svc.cfg.fusion_chunk_scenarios or 0)
208
+ size = size if 0 < size < len(ids) else len(ids)
209
+ prog = progress_file(out)
210
+ done, dirs = _finished_passes(prog, ids, size)
211
+ workers = (plan.get("cred_env") or {}).get("FPT_FUSION_WORKERS")
212
+ if done:
213
+ svc.db.add_event(plan["run_id"], "executor", "resumed", {"attempt": plan["attempt"], "skipped_chunks": sorted(done),
214
+ "message": f"{len(done)} finished pass(es) of this attempt are kept."})
215
+
216
+ def one(*, ids: list[str], out_file: Path, tag: str, live_meta: dict, **_):
217
+ sub = {**plan, "ids": ids, "out_file": str(out_file), "tag": tag, "live_meta": live_meta, "groups": None,
218
+ "timeout_s": attempt_timeout_s(svc.cfg, len(ids), workers)}
219
+ return run_pass(sub, svc, **extra)
220
+
221
+ def on_chunk(k: int, f: str, total: int, run_dir: str | None) -> None:
222
+ done[k] = f
223
+ if run_dir:
224
+ dirs[k] = run_dir
225
+ tmp = prog.with_name(f".{prog.name}.tmp")
226
+ tmp.write_text(json.dumps({"ids": ids, "size": size, "done": done, "dirs": dirs}), encoding="utf-8")
227
+ tmp.replace(prog)
228
+ if total > 1:
229
+ svc.db.add_event(plan["run_id"], "executor", "progress", {"attempt": plan["attempt"], "chunk": k + 1, "of": total})
230
+
231
+ res = pw.run_attempt_chunked(ids=ids, out_file=out, chunk_size=size, done=done, done_dirs=dirs, on_chunk=on_chunk, run=one,
232
+ tag=plan.get("tag") or "", lost_ok=True, single_as_attempt=True)
233
+ if res.get("lost_chunks"):
234
+ svc.db.add_event(plan["run_id"], "executor", "execution_error", {
235
+ "attempt": plan["attempt"], "lost_chunks": res["lost_chunks"], "retrying": False,
236
+ "error": f"{len(res['lost_chunks'])} of {res['chunks']} passes ran out of time before they reported; their "
237
+ "scenarios are recorded as timed out and tried again in the retry."})
238
+ return {**res, "mode": plan["mode"]}
239
+
240
+
241
+ def run_pass(plan: dict, svc, **extra) -> dict:
242
+ """One Playwright invocation: on the remote runner for a Fusion pod when one is set, else on this server."""
243
  remote = (svc.cfg.remote_runner_url or "").strip()
244
+ if remote and plan["mode"] == "live" and plan.get("config") == FUSION_CONFIG:
245
  from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs there
246
  token = svc.vault.get("remote_runner.token") or ""
247
  if token:
248
  svc.redactor.add_secrets([token])
249
+ rid, attempt = plan["run_id"], plan["attempt"]
250
+
251
+ def note(message: str) -> None:
252
+ svc.db.add_event(rid, "executor", "runner", {"message": message, "attempt": attempt, "pass": plan.get("tag") or None})
253
+
254
+ return run_attempt_remote(svc.egress, remote, token, run_id=rid, ids=plan["ids"], attempt=attempt,
255
  out_file=Path(plan["out_file"]), cred_env=plan["cred_env"], drafts_dir=Path(plan["drafts_dir"]),
256
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
257
  overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]),
258
+ config=plan["config"], kill=lambda: _stop_check(svc, rid),
259
+ timeout_s=int(plan.get("timeout_s") or 3600), live_meta=plan.get("live_meta"),
260
+ busy_wait_s=60 * int(svc.cfg.remote_runner_busy_wait_minutes), on_event=note,
261
  live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, tag=plan.get("tag") or "")
262
  if plan["mode"] == "live" and not plan.get("config"):
263
  pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))
 
265
  extra.setdefault("config", plan["config"])
266
  if plan.get("tag"):
267
  extra.setdefault("tag", plan["tag"])
268
+ if plan.get("timeout_s"):
269
+ extra.setdefault("timeout_s", int(plan["timeout_s"]))
270
+ if plan.get("live_meta"):
271
+ extra.setdefault("live_meta", plan["live_meta"])
272
  return pw.run_attempt(run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"], mode=plan["mode"],
273
  out_file=Path(plan["out_file"]), stub_knobs=plan["stub_knobs"], drafts_dir=Path(plan["drafts_dir"]),
274
  library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None,
 
322
  except Exception as e: # noqa: BLE001
323
  svc.audit.append("evidence.error", actor="system", run_id=run_id, summary=str(e)[:300])
324
  files = plan["files"] + [str(out_file)]
325
+ if len(files) > 1: # a scenario recorded as timed out (its pass overran) is matched to its retry's result
326
+ pw.adopt_no_result(files)
327
  merged = merge_attempts(files, Path(plan["run_dir"]) / "merged-results.json")
328
  outs, counts = outcomes(str(merged))
329
  fails = failing_ids(str(out_file)) if plan["ids"] else []
 
358
  raise ExecutionError(f"The browser test run failed twice before any scenario ran. {why}", exit_code=(res or {}).get("exit_code"),
359
  timed_out=bool((res or {}).get("timed_out")))
360
  Path(plan["out_file"]).unlink(missing_ok=True)
361
+ forget_passes(plan["out_file"]) # the retry runs every pass again: none of them recorded anything
362
  return finish_attempt(state, svc, plan, res)
363
 
364
 
 
369
  if pid is None:
370
  return
371
  from ...platform import preflight
372
+ ids = set(plan["ids"]) # the areas this attempt runs, not every area the run designed for
373
+ areas = sorted({c["module"] for c in state.get("test_cases") or [] if c["id"] in ids})
374
  results = preflight.check(svc, pid, plan["run_id"], areas)
375
  bad = preflight.problems(results)
376
  svc.db.add_event(plan["run_id"], "executor", "preflight", {"ok": not bad, "checks": results})
coworker/llm/prompts/design_scenarios.md CHANGED
@@ -44,6 +44,12 @@ Rules:
44
  the choice changes them;
45
  - search: find the document just created by its number, and a search that should find nothing.
46
  At least half of the scenarios that are not change coverage must be `negative` or edge cases (P3).
 
 
 
 
 
 
47
  - Say in `why` (one sentence) which change it covers, or that it is a regression check, or which edge case it tests.
48
  P1 = core flow a business cannot work without, or a change switched on by the update; P2 = important variant;
49
  P3 = edge case.
 
44
  the choice changes them;
45
  - search: find the document just created by its number, and a search that should find nothing.
46
  At least half of the scenarios that are not change coverage must be `negative` or edge cases (P3).
47
+ Only propose edge cases Fusion refuses on Save, Submit or an action (not a value a field rejects while typing, and
48
+ never an invalid choice in a drop-down list, which offers only its own choices).
49
+ - When the input's processes say "regression check: ...", each is one standard check a senior tester runs every cycle:
50
+ propose exactly one scenario per check that tests exactly what it says, with a title close to the check's words, on
51
+ the input screen (or flow) that shows it. Skip a check none of the input screens can show; the rules above about the
52
+ mix of scenarios do not apply then.
53
  - Say in `why` (one sentence) which change it covers, or that it is a regression check, or which edge case it tests.
54
  P1 = core flow a business cannot work without, or a change switched on by the update; P2 = important variant;
55
  P3 = edge case.
coworker/llm/prompts/write_steps.md CHANGED
@@ -41,6 +41,15 @@ Rules:
41
  - Every scenario proves its title with at least one check step (`expect_filled`, `expect_value`, `expect_status`,
42
  `expect_no_error` after a save or action, `expect_message` for a message the scenario expects, `expect_results`
43
  after a search), and `expected_result` says in one sentence what it proves. Write the WHOLE scenario, to its last check.
 
 
 
 
 
 
 
 
 
44
  - A scenario that does not need to keep anything ends with `cancel_without_saving`.
45
  - `process` is the short business process name, for example "Invoice entry" or "Invoice validation and holds".
46
  - To check that a field is empty, use `expect_value` with value "".
 
41
  - Every scenario proves its title with at least one check step (`expect_filled`, `expect_value`, `expect_status`,
42
  `expect_no_error` after a save or action, `expect_message` for a message the scenario expects, `expect_results`
43
  after a search), and `expected_result` says in one sentence what it proves. Write the WHOLE scenario, to its last check.
44
+ - Negative and edge cases as Fusion really behaves (seen on live pods):
45
+ - a drop-down list (`kind: list`) only offers its own choices: never enter an invalid or made-up choice in it; test a
46
+ list by choosing a valid entry and checking what it changes;
47
+ - a value the field itself refuses while typing (a malformed date, letters in a number) stops the test at that step:
48
+ test refusals that happen on Save, Submit or an action instead (a required field left empty, lines that do not add
49
+ up, a duplicate number, an amount over what is allowed), and check them with `expect_message`;
50
+ - `expect_message` takes one or two words Fusion is sure to use in that message ("required", "duplicate", "hold",
51
+ "exceeds"), never a whole sentence you expect it to say;
52
+ - type dates with the `{{today}}` placeholder or in the pod's own format; never type a date in another format (an ISO year-month-day date is refused by the field).
53
  - A scenario that does not need to keep anything ends with `cancel_without_saving`.
54
  - `process` is the short business process name, for example "Invoice entry" or "Invoice validation and holds".
55
  - To check that a field is empty, use `expect_value` with value "".
coworker/platform/agent_studio.py CHANGED
@@ -1,20 +1,24 @@
1
- """Oracle Fusion AI Agent Studio drives Patchwise (docs/AGENT_STUDIO.md).
2
 
3
  The Fusion side (a weekly scheduler and an AI Agent Studio workflow) reads the module space, generates SYNTHETIC test
4
- data, masks and validates it, and a person approves it in Fusion. It then calls Patchwise with an OAuth 2.0 client
5
  (client credentials, invoke-only):
6
 
7
  POST /oauth/token -> a bearer token (one hour, scope patchwise.invoke)
8
- POST /api/agent-studio/v1/cycles -> the approved test data JSON starts a test cycle (one Patchwise run)
 
9
  callback scripts_ready <- the scenarios and their Excel script, waiting for approval in Fusion
10
  POST /api/agent-studio/v1/cycles/{id}/approval -> the person's "start testing" decision, made in Fusion
11
- callback failures_need_review <- failed tests wait for a person to decide (in Patchwise)
12
  callback results / stopped <- verdicts per area, report and PDF links
 
13
  callback patch_update <- the release watch: new or changed items in Oracle's What's New
14
 
15
  Callbacks are signed (X-Patchwise-Signature: sha256=HMAC of the body with the client's signing key), sent through the
16
- egress gate to the client's own callback address only, and retried. Test data is synthetic by contract and checked:
17
- anything that looks like personal data (an email, a phone or card number, a national id) is refused."""
 
 
18
  from __future__ import annotations
19
 
20
  import base64
@@ -37,10 +41,22 @@ _TOKENS: dict[str, tuple[str, float]] = {} # client_id -> (Oracle access token
37
  SCOPE = "patchwise.invoke"
38
  TOKEN_TTL_S = 3600
39
  TOKEN_PREFIX = "pwa_"
40
- EVENTS = ("scripts_ready", "failures_need_review", "results", "stopped", "patch_update")
 
 
 
 
 
 
41
  DEPTHS = {"regression": "full", "full": "full", "standard": "standard", "smoke": "smoke"}
42
  MAX_ATTEMPTS = 6
43
- STOPPED = ("failed", "killed", "cancelled", "interrupted")
 
 
 
 
 
 
44
 
45
  # test data must be synthetic: values that look like personal or payment data are refused outright
46
  _PII = [
@@ -117,6 +133,49 @@ def _hash(s: str) -> str:
117
  return hashlib.sha256(s.encode()).hexdigest()
118
 
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  def _utc(ts: str) -> datetime:
121
  d = datetime.fromisoformat(ts.replace("Z", "+00:00"))
122
  return d if d.tzinfo else d.replace(tzinfo=timezone.utc)
@@ -199,6 +258,7 @@ class AgentStudio:
199
  "created_by": actor, "created_at": now_iso()})
200
  self.svc.vault.set(f"agent_studio.{cid}.signing", signing)
201
  self.svc.audit.append("agent_studio.client_created", actor=actor, summary=f"{cid} {name}", payload={"client_id": cid, "name": name})
 
202
  return {"client_id": cid, "client_secret": secret, "signing_key": signing, "name": name,
203
  "callback_url": callback_url, "release_watch_url": release_watch_url}
204
 
@@ -258,6 +318,7 @@ class AgentStudio:
258
  self.db.update("agent_clients", "client_id", client_id, revoked_at=now_iso())
259
  self.db.x("DELETE FROM agent_tokens WHERE client_id=?", (client_id,))
260
  self.svc.audit.append("agent_studio.client_revoked", actor=actor, summary=client_id, payload={"client_id": client_id})
 
261
 
262
  def _shown(self, r: dict) -> dict:
263
  out = {k: v for k, v in r.items() if k not in ("secret_hash", "fusion")}
@@ -379,28 +440,61 @@ class AgentStudio:
379
  raise AgentStudioError("invalid_client", "unknown client or wrong secret", 401)
380
  if scope and scope.strip() != SCOPE:
381
  raise AgentStudioError("invalid_scope", f"the only scope is {SCOPE}", 400)
382
- token = TOKEN_PREFIX + secrets.token_urlsafe(32)
 
383
  self.db.x("DELETE FROM agent_tokens WHERE expires_at < ?", (now_iso(),))
384
- self.db.insert("agent_tokens", {"token_hash": _hash(token), "client_id": client_id, "scope": SCOPE,
385
- "created_at": now_iso(), "expires_at": _later(TOKEN_TTL_S)})
386
  self.db.update("agent_clients", "client_id", client_id, last_used_at=now_iso())
387
  return {"access_token": token, "token_type": "Bearer", "expires_in": TOKEN_TTL_S, "scope": SCOPE}
388
 
389
  def client_for_token(self, token: str) -> dict:
 
 
390
  if not token or not token.startswith(TOKEN_PREFIX):
391
  raise AgentStudioError("invalid_token", "a bearer token from /oauth/token is needed", 401)
392
- t = self.db.one("SELECT * FROM agent_tokens WHERE token_hash=?", (_hash(token),))
393
- if not t or _utc(t["expires_at"]) < datetime.now(timezone.utc):
 
 
 
 
394
  raise AgentStudioError("invalid_token", "the token is unknown or expired: ask /oauth/token for a new one", 401)
395
- c = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (t["client_id"],))
396
  if not c or c.get("revoked_at"):
397
  raise AgentStudioError("invalid_token", "this client was revoked", 401)
398
  return {k: v for k, v in c.items() if k != "secret_hash"}
399
 
400
  # ------------------------------------------------------------ test cycles
401
- def start_cycle(self, client: dict, body: dict, runs) -> dict:
402
- """The Fusion workflow's approved test data starts one Patchwise run (a full browser run as the action-only
403
- test user). Returns the cycle; its first callback is scripts_ready."""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
404
  approved_by = str(body.get("data_approved_by") or "").strip()[:120]
405
  if not approved_by:
406
  raise AgentStudioError("NOT_APPROVED", "data_approved_by is required: a person approves the test data in Fusion first")
@@ -443,27 +537,35 @@ class AgentStudio:
443
  reg.update(pod["id"], {"release": str(body["release"]).upper()}, f"agent-studio:{client['client_id']}")
444
  except PodError as e:
445
  raise AgentStudioError(e.code, str(e), e.status) from e
446
- from ..api.runner import RunError
447
- try:
448
- run_id = runs.start(inputs, actor=f"Oracle AI Agent Studio ({client['name']})", trigger="agent_studio")
449
- except RunError as e:
450
- raise AgentStudioError(e.code, str(e), e.status) from e
451
- cycle_id = "cyc_" + secrets.token_hex(6)
452
  meta = {k: body.get(k) for k in ("generated_by", "masked", "validated", "module_space", "correlation_id") if body.get(k) is not None}
453
- self.db.insert("agent_cycles", {"cycle_id": cycle_id, "run_id": run_id, "client_id": client["client_id"],
454
- "correlation_id": str(body.get("correlation_id") or "")[:120] or None, "pod_id": pod["id"],
455
- "release": body.get("release"), "areas": json.dumps(areas), "test_data": json.dumps(td),
456
- "skipped_areas": json.dumps(skipped), "package": package_json,
457
- "package_id": str((package or {}).get("package_id") or "")[:120] or None,
458
- "data_meta": json.dumps(meta), "data_approved_by": approved_by, "callback_url": callback,
459
- "last_status": "queued", "created_at": now_iso(), "updated_at": now_iso()})
 
 
 
 
 
 
 
 
 
 
 
460
  self.db.add_event(run_id, "agent_studio", "message", {"message": f"Started by Oracle AI Agent Studio with synthetic test data "
461
  f"approved in Fusion by {approved_by}."})
462
  self.svc.audit.append("agent_studio.cycle_started", actor=f"agent-studio:{client['client_id']}", run_id=run_id,
463
  summary=f"{cycle_id} {areas} data approved by {approved_by}",
464
  payload={"cycle_id": cycle_id, "areas": areas, "skipped_areas": [x["area"] for x in skipped],
465
  "package_id": (package or {}).get("package_id"), "keys": {a: sorted(k) for a, k in td.items()}})
466
- return self.cycle(cycle_id)
 
467
 
468
  def cycle(self, cycle_id: str, client_id: str | None = None) -> dict:
469
  c = self.db.one("SELECT * FROM agent_cycles WHERE cycle_id=?", (cycle_id,))
@@ -523,6 +625,7 @@ class AgentStudio:
523
  self.db.update("agent_cycles", "cycle_id", cycle_id, scripts_approved_by=who, scripts_approved_at=now_iso(), updated_at=now_iso())
524
  self.svc.audit.append("agent_studio.approval", actor=actor, run_id=c["run_id"], summary=f"{cycle_id} {decision}",
525
  payload={"cycle_id": cycle_id, "decision": decision})
 
526
  return {**self.cycle(cycle_id), "decision": decision}
527
 
528
  def _links(self, run_id: str) -> dict:
@@ -548,24 +651,36 @@ class AgentStudio:
548
 
549
  # ------------------------------------------------------------ callbacks
550
  def queue(self, client_id: str, url: str | None, event: str, payload: dict, cycle_id: str | None = None) -> str | None:
 
 
 
551
  url = self._target(client_id, url)
552
  if not url:
553
  return None
554
- did = "dlv_" + secrets.token_hex(8)
555
- body = {"event": event, "delivery_id": did, "sent_at": now_iso(), **({"cycle_id": cycle_id} if cycle_id else {}), **payload}
556
- self.db.insert("agent_callbacks", {"delivery_id": did, "client_id": client_id, "cycle_id": cycle_id, "event": event, "url": url,
557
- "payload": json.dumps(body), "attempts": 0, "next_at": now_iso(), "created_at": now_iso()})
 
 
 
 
 
 
 
 
 
 
558
  return did
559
 
560
  def deliver_due(self) -> int:
561
- """Send callbacks that are due; a failure is tried again later (1, 2, 4, 8, 16 minutes), six tries in all."""
 
562
  sent = 0
563
- for d in self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND attempts < ? AND next_at <= ? AND url <> ? "
564
- "ORDER BY id LIMIT 20", (MAX_ATTEMPTS, now_iso(), PULL)):
565
- key = self.svc.vault.get(f"agent_studio.{d['client_id']}.signing") or ""
566
  payload = _j(d["payload"])
567
  body = json.dumps(payload).encode()
568
- sig = "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest()
569
  code, err, job = None, None, None
570
  fusion = self._fusion(d["client_id"])
571
  try:
@@ -576,7 +691,12 @@ class AgentStudio:
576
  job = out or None
577
  else:
578
  err = out
 
 
 
 
579
  else:
 
580
  r = self.svc.egress.service_request("agent_callback", "POST", d["url"], allowed_base=d["url"], content=body,
581
  headers={"Content-Type": "application/json", "X-Patchwise-Event": d["event"],
582
  "X-Patchwise-Delivery": d["delivery_id"], "X-Patchwise-Signature": sig},
@@ -592,13 +712,51 @@ class AgentStudio:
592
  sent += 1
593
  else:
594
  self.db.update("agent_callbacks", "id", d["id"], attempts=n, status_code=code, error=err, next_at=_later(60 * 2 ** (n - 1)))
 
595
  return sent
596
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
597
  def claim(self, client_id: str, limit: int = 5, cycle_id: str | None = None) -> dict:
598
  """The pull client's waiting events, oldest first (one cycle's, when cycle_id is given). Each is held for
599
  LEASE_S; one not confirmed with ack() by then is handed out again."""
600
  limit = max(1, min(int(limit or 5), 20))
601
- where, args = "client_id=? AND url=? AND delivered_at IS NULL AND attempts < ? AND next_at <= ?", [client_id, PULL, MAX_PICKUPS, now_iso()]
 
602
  if cycle_id:
603
  where, args = where + " AND cycle_id=?", args + [cycle_id]
604
  rows = self.db.q(f"SELECT * FROM agent_callbacks WHERE {where} ORDER BY id LIMIT ?", (*args, limit + 1))
@@ -611,28 +769,55 @@ class AgentStudio:
611
  return {"events": out, "count": len(out), "more": len(rows) > limit, "confirm_within_s": LEASE_S}
612
 
613
  def ack(self, client_id: str, delivery_ids: list[str]) -> dict:
614
- """Confirms picked-up events: they are not handed out again. Ids of other clients or unknown ids are ignored."""
 
615
  done = []
616
  for did in dict.fromkeys(str(x) for x in delivery_ids or []):
617
  d = self.db.one("SELECT id FROM agent_callbacks WHERE delivery_id=? AND client_id=? AND url=? AND delivered_at IS NULL",
618
  (did, client_id, PULL))
619
  if d:
620
- self.db.update("agent_callbacks", "id", d["id"], delivered_at=now_iso(), status_code=200, error=None)
621
  done.append(did)
622
  return {"confirmed": done, "count": len(done)}
623
 
624
- def deliveries(self, limit: int = 50) -> list[dict]:
625
- return [{k: (_j(v) if k == "payload" else v) for k, v in r.items()}
626
- for r in self.db.q("SELECT * FROM agent_callbacks ORDER BY id DESC LIMIT ?", (limit,))]
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
627
 
628
  def watch_runs(self, runs) -> int:
629
  """Callbacks for each cycle whose run reached a new step: scripts_ready (waiting for approval),
630
- failures_need_review, results, stopped. Idempotent: a step is reported once."""
 
 
631
  queued = 0
632
- for c in self.db.q("SELECT * FROM agent_cycles WHERE last_status NOT IN ('completed','failed','killed','cancelled') OR last_status IS NULL"):
 
 
 
 
633
  run = self.db.get_run(c["run_id"]) or {}
634
  status, gate = run.get("status"), run.get("pending_gate")
635
- if (status, gate) == (c["last_status"], c["last_gate"]):
636
  continue
637
  event, payload = None, {}
638
  if status == "waiting_approval" and gate == "approve_cases":
@@ -651,7 +836,11 @@ class AgentStudio:
651
  elif status == "completed":
652
  event, payload = "results", self._results(c["run_id"], runs)
653
  elif status in STOPPED:
654
- event, payload = "stopped", {"status": status, "reason": run.get("error")}
 
 
 
 
655
  if event:
656
  self.queue(c["client_id"], c["callback_url"], event, {"run_id": c["run_id"], "correlation_id": c["correlation_id"],
657
  "links": self._links(c["run_id"]), **payload}, c["cycle_id"])
 
1
+ """Oracle Fusion AI Agent Studio drives Astra (docs/AGENT_STUDIO.md).
2
 
3
  The Fusion side (a weekly scheduler and an AI Agent Studio workflow) reads the module space, generates SYNTHETIC test
4
+ data, masks and validates it, and a person approves it in Fusion. It then calls Astra with an OAuth 2.0 client
5
  (client credentials, invoke-only):
6
 
7
  POST /oauth/token -> a bearer token (one hour, scope patchwise.invoke)
8
+ POST /api/agent-studio/v1/cycles -> the approved test data JSON starts a test cycle (one Astra run); sent
9
+ again (same correlation_id or Idempotency-Key) it returns that cycle
10
  callback scripts_ready <- the scenarios and their Excel script, waiting for approval in Fusion
11
  POST /api/agent-studio/v1/cycles/{id}/approval -> the person's "start testing" decision, made in Fusion
12
+ callback failures_need_review <- failed tests wait for a person to decide (in Astra)
13
  callback results / stopped <- verdicts per area, report and PDF links
14
+ callback paused <- (optional) the run was interrupted by a restart; it can be resumed
15
  callback patch_update <- the release watch: new or changed items in Oracle's What's New
16
 
17
  Callbacks are signed (X-Patchwise-Signature: sha256=HMAC of the body with the client's signing key), sent through the
18
+ egress gate to the client's own callback address only, and retried: delivery is at least once, and the same logical
19
+ event always has the same delivery_id, so the Fusion side drops repeats by that id. An event that runs out of tries is
20
+ kept as a dead letter an admin can send again. Test data is synthetic by contract and checked: anything that looks like
21
+ personal data (an email, a phone or card number, a national id) is refused."""
22
  from __future__ import annotations
23
 
24
  import base64
 
41
  SCOPE = "patchwise.invoke"
42
  TOKEN_TTL_S = 3600
43
  TOKEN_PREFIX = "pwa_"
44
+ # Access tokens are signed (HMAC-SHA256), not looked up: pwa_2.<client id>.<expires>.<nonce>.<signature>. A restart that
45
+ # restores an older snapshot keeps every token the Fusion side holds valid; the client row (revoked or not) still decides.
46
+ # The key is the vault's agent_studio.token_key (FPT_SECRET_AGENT_STUDIO_TOKEN_KEY), made once when it is missing.
47
+ TOKEN_VERSION = "2"
48
+ TOKEN_KEY = "agent_studio.token_key"
49
+ # "paused" is the one event older Fusion callback workflows do not know: they ignore it (the others never change)
50
+ EVENTS = ("scripts_ready", "failures_need_review", "results", "stopped", "paused", "patch_update")
51
  DEPTHS = {"regression": "full", "full": "full", "standard": "standard", "smoke": "smoke"}
52
  MAX_ATTEMPTS = 6
53
+ STOPPED = ("failed", "killed", "cancelled")
54
+ # a run the backend restart interrupted is not over: it can be resumed, so the cycle is "paused", not "stopped"
55
+ PAUSED = ("interrupted",)
56
+ # a cycle is watched until its run cannot move on any more (failed and interrupted runs can be resumed)
57
+ FINAL = ("completed", "killed", "cancelled")
58
+ # a start sent again with the same correlation_id returns the cycle while its run is still going
59
+ ACTIVE = ("queued", "running", "waiting_approval", "waiting_review")
60
 
61
  # test data must be synthetic: values that look like personal or payment data are refused outright
62
  _PII = [
 
133
  return hashlib.sha256(s.encode()).hexdigest()
134
 
135
 
136
+ def _save_soon(reason: str) -> None:
137
+ """Ask for a state save now: a restart minutes later must not lose a cycle, an approval or a client."""
138
+ from .statesync import save_soon
139
+ save_soon(reason)
140
+
141
+
142
+ def delivery_id_for(scope: str, event: str, seq: int) -> str:
143
+ """The same logical event always gets the same id: (cycle, or client for the release watch; event; how many of
144
+ that event the cycle had before). A snapshot restored after a restart re-creates a lost event with its old id."""
145
+ return "dlv_" + hashlib.sha256(f"{scope}|{event}|{seq}".encode()).hexdigest()[:16]
146
+
147
+
148
+ def _token_key(svc) -> bytes:
149
+ k = svc.vault.get(TOKEN_KEY)
150
+ if not k:
151
+ if not hasattr(svc.vault, "set"):
152
+ raise AgentStudioError("server_error", "the vault cannot keep a token key; set FPT_SECRET_AGENT_STUDIO_TOKEN_KEY", 500)
153
+ k = secrets.token_urlsafe(32)
154
+ svc.vault.set(TOKEN_KEY, k)
155
+ _save_soon("agent studio token key made")
156
+ return k.encode()
157
+
158
+
159
+ def _token_mac(svc, body: str) -> str:
160
+ return base64.urlsafe_b64encode(hmac.new(_token_key(svc), body.encode(), hashlib.sha256).digest()).decode().rstrip("=")
161
+
162
+
163
+ def sign_token(svc, client_id: str, ttl_s: int = TOKEN_TTL_S, now: float | None = None) -> str:
164
+ body = f"{TOKEN_VERSION}.{client_id}.{int((now or time.time()) + ttl_s)}.{secrets.token_hex(8)}"
165
+ return f"{TOKEN_PREFIX}{body}.{_token_mac(svc, body)}"
166
+
167
+
168
+ def token_client_id(svc, token: str, now: float | None = None) -> str | None:
169
+ """The client id of a signed token that is genuine and not expired; None otherwise (no database read)."""
170
+ parts = token[len(TOKEN_PREFIX):].split(".")
171
+ if len(parts) != 5 or parts[0] != TOKEN_VERSION or not parts[2].isdigit():
172
+ return None
173
+ body = ".".join(parts[:4])
174
+ if not hmac.compare_digest(_token_mac(svc, body), parts[4]) or int(parts[2]) < (now or time.time()):
175
+ return None
176
+ return parts[1]
177
+
178
+
179
  def _utc(ts: str) -> datetime:
180
  d = datetime.fromisoformat(ts.replace("Z", "+00:00"))
181
  return d if d.tzinfo else d.replace(tzinfo=timezone.utc)
 
258
  "created_by": actor, "created_at": now_iso()})
259
  self.svc.vault.set(f"agent_studio.{cid}.signing", signing)
260
  self.svc.audit.append("agent_studio.client_created", actor=actor, summary=f"{cid} {name}", payload={"client_id": cid, "name": name})
261
+ _save_soon("agent studio client created") # the secret is shown once: a restart must not forget the client
262
  return {"client_id": cid, "client_secret": secret, "signing_key": signing, "name": name,
263
  "callback_url": callback_url, "release_watch_url": release_watch_url}
264
 
 
318
  self.db.update("agent_clients", "client_id", client_id, revoked_at=now_iso())
319
  self.db.x("DELETE FROM agent_tokens WHERE client_id=?", (client_id,))
320
  self.svc.audit.append("agent_studio.client_revoked", actor=actor, summary=client_id, payload={"client_id": client_id})
321
+ _save_soon("agent studio client revoked") # signed tokens end with the client: the revocation must survive a restart
322
 
323
  def _shown(self, r: dict) -> dict:
324
  out = {k: v for k, v in r.items() if k not in ("secret_hash", "fusion")}
 
440
  raise AgentStudioError("invalid_client", "unknown client or wrong secret", 401)
441
  if scope and scope.strip() != SCOPE:
442
  raise AgentStudioError("invalid_scope", f"the only scope is {SCOPE}", 400)
443
+ # signed, not stored: a restored snapshot cannot forget it (tokens issued before this kept their rows, below)
444
+ token = sign_token(self.svc, client_id)
445
  self.db.x("DELETE FROM agent_tokens WHERE expires_at < ?", (now_iso(),))
 
 
446
  self.db.update("agent_clients", "client_id", client_id, last_used_at=now_iso())
447
  return {"access_token": token, "token_type": "Bearer", "expires_in": TOKEN_TTL_S, "scope": SCOPE}
448
 
449
  def client_for_token(self, token: str) -> dict:
450
+ """The client of a bearer token: a signed one (checked with the token key, no row needed) or one issued before
451
+ tokens were signed (its row, until it expires). Either way the client must exist and not be revoked."""
452
  if not token or not token.startswith(TOKEN_PREFIX):
453
  raise AgentStudioError("invalid_token", "a bearer token from /oauth/token is needed", 401)
454
+ if "." in token:
455
+ cid = token_client_id(self.svc, token)
456
+ else:
457
+ t = self.db.one("SELECT * FROM agent_tokens WHERE token_hash=?", (_hash(token),))
458
+ cid = t["client_id"] if t and _utc(t["expires_at"]) >= datetime.now(timezone.utc) else None
459
+ if not cid:
460
  raise AgentStudioError("invalid_token", "the token is unknown or expired: ask /oauth/token for a new one", 401)
461
+ c = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (cid,))
462
  if not c or c.get("revoked_at"):
463
  raise AgentStudioError("invalid_token", "this client was revoked", 401)
464
  return {k: v for k, v in c.items() if k != "secret_hash"}
465
 
466
  # ------------------------------------------------------------ test cycles
467
+ def start_cycle(self, client: dict, body: dict, runs, idempotency_key: str | None = None) -> dict:
468
+ return self.start_or_replay(client, body, runs, idempotency_key)[0]
469
+
470
+ def _replay(self, client_id: str, correlation_id: str | None, idempotency_key: str | None) -> str | None:
471
+ """The cycle an earlier start with the same Idempotency-Key made (any time), or the same correlation_id while
472
+ that cycle's run is still going (or being created). A finished, failed or interrupted cycle is not replayed:
473
+ a new start with its correlation_id is a new cycle."""
474
+ if idempotency_key:
475
+ r = self.db.one("SELECT cycle_id FROM agent_cycles WHERE client_id=? AND idempotency_key=? ORDER BY created_at DESC LIMIT 1",
476
+ (client_id, idempotency_key))
477
+ if r:
478
+ return r["cycle_id"]
479
+ if correlation_id:
480
+ r = self.db.one("SELECT c.cycle_id, r.status FROM agent_cycles c LEFT JOIN runs r ON r.run_id=c.run_id "
481
+ "WHERE c.client_id=? AND c.correlation_id=? ORDER BY c.created_at DESC, c.rowid DESC LIMIT 1",
482
+ (client_id, correlation_id))
483
+ if r and (r["status"] is None or r["status"] in ACTIVE):
484
+ return r["cycle_id"]
485
+ return None
486
+
487
+ def start_or_replay(self, client: dict, body: dict, runs, idempotency_key: str | None = None) -> tuple[dict, bool]:
488
+ """The Fusion workflow's approved test data starts one Astra run (a full browser run as the action-only test
489
+ user). Returns (the cycle, False); its first callback is scripts_ready. Sent again (a retry: same Idempotency-Key,
490
+ or same correlation_id while that cycle is going) it starts nothing and returns (that cycle, True).
491
+ The cycle row is written before the run starts, so the runner always finds the cycle's test data, and a save is
492
+ asked for at once, so a restart does not forget the cycle."""
493
+ corr = str(body.get("correlation_id") or "")[:120] or None
494
+ key = str(idempotency_key or "").strip()[:200] or None
495
+ again = self._replay(client["client_id"], corr, key)
496
+ if again:
497
+ return self.cycle(again), True
498
  approved_by = str(body.get("data_approved_by") or "").strip()[:120]
499
  if not approved_by:
500
  raise AgentStudioError("NOT_APPROVED", "data_approved_by is required: a person approves the test data in Fusion first")
 
537
  reg.update(pod["id"], {"release": str(body["release"]).upper()}, f"agent-studio:{client['client_id']}")
538
  except PodError as e:
539
  raise AgentStudioError(e.code, str(e), e.status) from e
540
+ from ..api.runner import RunError, new_run_id
541
+ cycle_id, run_id = "cyc_" + secrets.token_hex(6), new_run_id()
 
 
 
 
542
  meta = {k: body.get(k) for k in ("generated_by", "masked", "validated", "module_space", "correlation_id") if body.get(k) is not None}
543
+ with self.db.write_lock: # the retry check and the cycle row are one step: two copies of a start make one cycle
544
+ again = self._replay(client["client_id"], corr, key)
545
+ if again:
546
+ return self.cycle(again), True
547
+ self.db.insert("agent_cycles", {"cycle_id": cycle_id, "run_id": run_id, "client_id": client["client_id"],
548
+ "correlation_id": corr, "idempotency_key": key, "pod_id": pod["id"],
549
+ "release": body.get("release"), "areas": json.dumps(areas), "test_data": json.dumps(td),
550
+ "skipped_areas": json.dumps(skipped), "package": package_json,
551
+ "package_id": str((package or {}).get("package_id") or "")[:120] or None,
552
+ "data_meta": json.dumps(meta), "data_approved_by": approved_by, "callback_url": callback,
553
+ "last_status": "queued", "created_at": now_iso(), "updated_at": now_iso()})
554
+ try: # the run gets the id the cycle row already holds
555
+ runs.start(inputs, actor=f"Oracle AI Agent Studio ({client['name']})", trigger="agent_studio", run_id=run_id)
556
+ except BaseException as e:
557
+ self.db.x("DELETE FROM agent_cycles WHERE cycle_id=?", (cycle_id,))
558
+ if isinstance(e, RunError):
559
+ raise AgentStudioError(e.code, str(e), e.status) from e
560
+ raise
561
  self.db.add_event(run_id, "agent_studio", "message", {"message": f"Started by Oracle AI Agent Studio with synthetic test data "
562
  f"approved in Fusion by {approved_by}."})
563
  self.svc.audit.append("agent_studio.cycle_started", actor=f"agent-studio:{client['client_id']}", run_id=run_id,
564
  summary=f"{cycle_id} {areas} data approved by {approved_by}",
565
  payload={"cycle_id": cycle_id, "areas": areas, "skipped_areas": [x["area"] for x in skipped],
566
  "package_id": (package or {}).get("package_id"), "keys": {a: sorted(k) for a, k in td.items()}})
567
+ _save_soon("agent studio cycle started")
568
+ return self.cycle(cycle_id), False
569
 
570
  def cycle(self, cycle_id: str, client_id: str | None = None) -> dict:
571
  c = self.db.one("SELECT * FROM agent_cycles WHERE cycle_id=?", (cycle_id,))
 
625
  self.db.update("agent_cycles", "cycle_id", cycle_id, scripts_approved_by=who, scripts_approved_at=now_iso(), updated_at=now_iso())
626
  self.svc.audit.append("agent_studio.approval", actor=actor, run_id=c["run_id"], summary=f"{cycle_id} {decision}",
627
  payload={"cycle_id": cycle_id, "decision": decision})
628
+ _save_soon(f"agent studio {decision}") # the decision made in Fusion must survive a restart
629
  return {**self.cycle(cycle_id), "decision": decision}
630
 
631
  def _links(self, run_id: str) -> dict:
 
651
 
652
  # ------------------------------------------------------------ callbacks
653
  def queue(self, client_id: str, url: str | None, event: str, payload: dict, cycle_id: str | None = None) -> str | None:
654
+ """One event for the client, delivered at least once. Its delivery_id is stable (delivery_id_for): queued again
655
+ for the same step (a restored snapshot re-creating a lost event) it keeps the id the Fusion side may have seen.
656
+ A newer event of the cycle drops a "paused" one that was not delivered yet (it would arrive out of date)."""
657
  url = self._target(client_id, url)
658
  if not url:
659
  return None
660
+ scope = cycle_id or f"client:{client_id}"
661
+ with self.db.write_lock: # the count and the insert are one step: two threads never compute the same id
662
+ if cycle_id:
663
+ n = self.db.one("SELECT COUNT(*) AS n FROM agent_callbacks WHERE cycle_id=? AND event=?", (cycle_id, event))["n"]
664
+ else:
665
+ n = self.db.one("SELECT COUNT(*) AS n FROM agent_callbacks WHERE cycle_id IS NULL AND client_id=? AND event=?",
666
+ (client_id, event))["n"]
667
+ did = delivery_id_for(scope, event, int(n))
668
+ body = {"event": event, "delivery_id": did, "sent_at": now_iso(), **({"cycle_id": cycle_id} if cycle_id else {}), **payload}
669
+ self.db.x("INSERT OR IGNORE INTO agent_callbacks (delivery_id, client_id, cycle_id, event, url, payload, attempts, next_at, created_at) "
670
+ "VALUES (?,?,?,?,?,?,0,?,?)", (did, client_id, cycle_id, event, url, json.dumps(body), now_iso(), now_iso()))
671
+ if cycle_id and event != "paused":
672
+ self.db.x("UPDATE agent_callbacks SET superseded_by=? WHERE cycle_id=? AND event='paused' AND delivered_at IS NULL "
673
+ "AND dead_at IS NULL AND superseded_by IS NULL", (did, cycle_id))
674
  return did
675
 
676
  def deliver_due(self) -> int:
677
+ """Send callbacks that are due; a failure is tried again later (1, 2, 4, 8, 16 minutes), six tries in all. One
678
+ that runs out of tries becomes a dead letter (bury_dead)."""
679
  sent = 0
680
+ for d in self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND dead_at IS NULL AND superseded_by IS NULL "
681
+ "AND attempts < ? AND next_at <= ? AND url <> ? ORDER BY id LIMIT 20", (MAX_ATTEMPTS, now_iso(), PULL)):
 
682
  payload = _j(d["payload"])
683
  body = json.dumps(payload).encode()
 
684
  code, err, job = None, None, None
685
  fusion = self._fusion(d["client_id"])
686
  try:
 
691
  job = out or None
692
  else:
693
  err = out
694
+ elif not (key := self.svc.vault.get(f"agent_studio.{d['client_id']}.signing")):
695
+ # never sign with an empty key: the receiver could not tell this callback from a forged one
696
+ err = f"no signing key for client {d['client_id']} in the vault: not sent (unsigned callbacks are never sent)"
697
+ log.error("agent studio: %s (delivery %s)", err, d["delivery_id"])
698
  else:
699
+ sig = "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest()
700
  r = self.svc.egress.service_request("agent_callback", "POST", d["url"], allowed_base=d["url"], content=body,
701
  headers={"Content-Type": "application/json", "X-Patchwise-Event": d["event"],
702
  "X-Patchwise-Delivery": d["delivery_id"], "X-Patchwise-Signature": sig},
 
712
  sent += 1
713
  else:
714
  self.db.update("agent_callbacks", "id", d["id"], attempts=n, status_code=code, error=err, next_at=_later(60 * 2 ** (n - 1)))
715
+ self.bury_dead()
716
  return sent
717
 
718
+ def bury_dead(self) -> list[str]:
719
+ """Events that ran out of tries (six sends, or 20 pickups without a confirmation) become dead letters: kept,
720
+ audited, shown under Callbacks and told to the admins in one notification. An admin sends one again (requeue)."""
721
+ rows = self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND dead_at IS NULL AND superseded_by IS NULL "
722
+ "AND ((url<>? AND attempts>=?) OR (url=? AND attempts>=? AND next_at<=?)) ORDER BY id",
723
+ (PULL, MAX_ATTEMPTS, PULL, MAX_PICKUPS, now_iso()))
724
+ for d in rows:
725
+ why = d.get("error") or (f"not confirmed after {d['attempts']} pickups" if d["url"] == PULL else "no answer")
726
+ self.db.update("agent_callbacks", "id", d["id"], dead_at=now_iso(), error=why)
727
+ self.svc.audit.append("agent_studio.dead_letter", actor="agent-studio", run_id=(self.cycle_for_id(d["cycle_id"]) or {}).get("run_id"),
728
+ summary=f"{d['delivery_id']} {d['event']} not delivered after {d['attempts']} tries: {why}"[:300],
729
+ payload={"delivery_id": d["delivery_id"], "client_id": d["client_id"], "cycle_id": d["cycle_id"],
730
+ "event": d["event"], "attempts": d["attempts"], "error": why[:300]})
731
+ if rows:
732
+ from . import notify
733
+ run_ids = {(self.cycle_for_id(d["cycle_id"]) or {}).get("run_id") for d in rows}
734
+ run = self.db.get_run(next(iter(run_ids))) if len(run_ids) == 1 and None not in run_ids else None
735
+ notify.get(self.svc).emit("agent_studio.dead_letter", run, count=len(rows), events=sorted({d["event"] for d in rows}))
736
+ return [d["delivery_id"] for d in rows]
737
+
738
+ def requeue(self, delivery_id: str, actor: str) -> dict:
739
+ """An admin sends an event again (a dead letter, or one still retrying): its tries start over, same delivery_id."""
740
+ d = self.db.one("SELECT * FROM agent_callbacks WHERE delivery_id=?", (delivery_id,))
741
+ if not d:
742
+ raise AgentStudioError("NO_DELIVERY", f"no callback {delivery_id}", 404)
743
+ if d.get("delivered_at"):
744
+ raise AgentStudioError("ALREADY_DELIVERED", f"{delivery_id} was delivered at {d['delivered_at']}", 409)
745
+ self.db.update("agent_callbacks", "id", d["id"], attempts=0, next_at=now_iso(), dead_at=None, superseded_by=None, error=None)
746
+ self.svc.audit.append("agent_studio.requeued", actor=actor, run_id=(self.cycle_for_id(d["cycle_id"]) or {}).get("run_id"),
747
+ summary=f"{delivery_id} {d['event']}", payload={"delivery_id": delivery_id, "event": d["event"],
748
+ "was_dead": bool(d.get("dead_at"))})
749
+ return self.delivery(delivery_id)
750
+
751
+ def cycle_for_id(self, cycle_id: str | None) -> dict | None:
752
+ return self.db.one("SELECT * FROM agent_cycles WHERE cycle_id=?", (cycle_id,)) if cycle_id else None
753
+
754
  def claim(self, client_id: str, limit: int = 5, cycle_id: str | None = None) -> dict:
755
  """The pull client's waiting events, oldest first (one cycle's, when cycle_id is given). Each is held for
756
  LEASE_S; one not confirmed with ack() by then is handed out again."""
757
  limit = max(1, min(int(limit or 5), 20))
758
+ where, args = ("client_id=? AND url=? AND delivered_at IS NULL AND dead_at IS NULL AND superseded_by IS NULL AND attempts < ? "
759
+ "AND next_at <= ?"), [client_id, PULL, MAX_PICKUPS, now_iso()]
760
  if cycle_id:
761
  where, args = where + " AND cycle_id=?", args + [cycle_id]
762
  rows = self.db.q(f"SELECT * FROM agent_callbacks WHERE {where} ORDER BY id LIMIT ?", (*args, limit + 1))
 
769
  return {"events": out, "count": len(out), "more": len(rows) > limit, "confirm_within_s": LEASE_S}
770
 
771
  def ack(self, client_id: str, delivery_ids: list[str]) -> dict:
772
+ """Confirms picked-up events: they are not handed out again. Ids of other clients or unknown ids are ignored. A
773
+ confirmation that arrives late (the event became a dead letter meanwhile) still counts."""
774
  done = []
775
  for did in dict.fromkeys(str(x) for x in delivery_ids or []):
776
  d = self.db.one("SELECT id FROM agent_callbacks WHERE delivery_id=? AND client_id=? AND url=? AND delivered_at IS NULL",
777
  (did, client_id, PULL))
778
  if d:
779
+ self.db.update("agent_callbacks", "id", d["id"], delivered_at=now_iso(), status_code=200, error=None, dead_at=None)
780
  done.append(did)
781
  return {"confirmed": done, "count": len(done)}
782
 
783
+ @staticmethod
784
+ def _delivery(r: dict) -> dict:
785
+ state = ("delivered" if r.get("delivered_at") else "dead" if r.get("dead_at") else "superseded" if r.get("superseded_by")
786
+ else "retrying" if r.get("attempts") and r.get("url") != PULL else "picked_up" if r.get("attempts") else "queued")
787
+ return {**{k: (_j(v) if k == "payload" else v) for k, v in r.items()}, "state": state}
788
+
789
+ def deliveries(self, limit: int = 50, state: str | None = None) -> list[dict]:
790
+ """The callbacks, newest first; state "dead" lists only the dead letters (up to 500, however old)."""
791
+ if state == "dead":
792
+ rows = self.db.q("SELECT * FROM agent_callbacks WHERE dead_at IS NOT NULL AND delivered_at IS NULL ORDER BY id DESC LIMIT ?",
793
+ (max(limit, 500),))
794
+ else:
795
+ rows = self.db.q("SELECT * FROM agent_callbacks ORDER BY id DESC LIMIT ?", (limit,))
796
+ return [self._delivery(r) for r in rows]
797
+
798
+ def dead_letters(self) -> int:
799
+ return int(self.db.one("SELECT COUNT(*) AS n FROM agent_callbacks WHERE dead_at IS NOT NULL AND delivered_at IS NULL")["n"])
800
+
801
+ def delivery(self, delivery_id: str) -> dict:
802
+ r = self.db.one("SELECT * FROM agent_callbacks WHERE delivery_id=?", (delivery_id,))
803
+ if not r:
804
+ raise AgentStudioError("NO_DELIVERY", f"no callback {delivery_id}", 404)
805
+ return self._delivery(r)
806
 
807
  def watch_runs(self, runs) -> int:
808
  """Callbacks for each cycle whose run reached a new step: scripts_ready (waiting for approval),
809
+ failures_need_review, results, stopped, paused (interrupted by a restart). Idempotent: a step is reported once.
810
+ A cycle is watched until its run cannot move on any more: a failed or interrupted run can be resumed, and the
811
+ cycle reports again when it does. A cycle whose run does not exist (yet) is left alone."""
812
  queued = 0
813
+ final = ",".join("?" * len(FINAL))
814
+ for c in self.db.q(f"SELECT c.* FROM agent_cycles c JOIN runs r ON r.run_id=c.run_id "
815
+ f"WHERE (c.last_status IS NULL OR c.last_status NOT IN ({final})) "
816
+ f"AND (c.last_status IS NULL OR r.status<>c.last_status OR COALESCE(r.pending_gate,'')<>COALESCE(c.last_gate,''))",
817
+ FINAL):
818
  run = self.db.get_run(c["run_id"]) or {}
819
  status, gate = run.get("status"), run.get("pending_gate")
820
+ if not run or (status, gate) == (c["last_status"], c["last_gate"]):
821
  continue
822
  event, payload = None, {}
823
  if status == "waiting_approval" and gate == "approve_cases":
 
836
  elif status == "completed":
837
  event, payload = "results", self._results(c["run_id"], runs)
838
  elif status in STOPPED:
839
+ event, payload = "stopped", {"status": status, "reason": run.get("error"), "resumable": status == "failed"}
840
+ elif status in PAUSED: # not over: Astra restarted mid-run; an admin resumes it and the cycle reports on
841
+ event, payload = "paused", {"status": status, "resumable": True,
842
+ "reason": run.get("error") or "Astra restarted while this cycle's run was going. It continues "
843
+ "from where it stopped once it is resumed in Astra."}
844
  if event:
845
  self.queue(c["client_id"], c["callback_url"], event, {"run_id": c["run_id"], "correlation_id": c["correlation_id"],
846
  "links": self._links(c["run_id"]), **payload}, c["cycle_id"])
coworker/platform/fusion_catalog.py CHANGED
@@ -7,6 +7,13 @@ to sample and the placeholder key each becomes, used as {{pod.<area>.<key>}} in
7
  its quarterly What's New (`readiness`: the guide's family and product on docs.oracle.com/en/cloud/saas/readiness, and the
8
  words that pick the area's rows from a guide shared by several areas; empty `match` = every row of the guide).
9
 
 
 
 
 
 
 
 
10
  Nothing here is pod-specific. A deployment can add or change areas without a code change with FPT_HOME/fusion_areas.json
11
  (a list in the same shape; an entry whose "code" matches replaces the built-in one). Resource names are the standard
12
  Fusion REST resources of /fscmRestApi/resources/11.13.18.05; a resource a pod does not have answers 404 and the area
@@ -21,11 +28,50 @@ log = logging.getLogger("coworker.fusion_catalog")
21
 
22
  FSCM = "/fscmRestApi/resources/11.13.18.05"
23
 
 
 
 
 
 
 
24
  AREAS: list[dict] = [
25
  {"code": "AP", "id": "payables", "name": "Payables", "probes": ["invoices", "suppliers"],
26
  "processes": ["Invoice entry", "Invoice validation and holds", "Invoice matching", "Credit memos", "Prepayments", "Payments"],
27
  "navigator": ["Payables > Invoices", "Payables > Payments"],
28
  "key_tasks": ["Create Invoice", "Manage Invoices", "Create Payment", "Manage Payments", "Submit Payment Process Request"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
  "readiness": {"family": "erp", "product": "fins", "match": ["Payables", "Payment", "Supplier Invoice", "Invoice Imaging", "Withholding"]},
30
  "test_data": [{"resource": "invoices", "order_by": "InvoiceId:desc", "key_field": "InvoiceId", "own_field": "InvoiceNumber",
31
  "fields": {"business_unit": "BusinessUnit", "supplier": "Supplier", "supplier_site": "SupplierSite",
@@ -36,6 +82,36 @@ AREAS: list[dict] = [
36
  "processes": ["Requisition entry", "Requisition approval", "Purchase order creation", "Change orders", "Receiving"],
37
  "navigator": ["Procurement > Purchase Requisitions", "Procurement > Purchase Orders"],
38
  "key_tasks": ["Create Order", "Manage Orders", "Manage Requisitions", "Manage Agreements"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
39
  "readiness": {"family": "scm", "product": "proc", "match": []},
40
  "test_data": [{"resource": "purchaseOrders", "order_by": "POHeaderId:desc",
41
  "fields": {"business_unit": "ProcurementBU", "supplier": "Supplier", "supplier_site": "SupplierSite",
@@ -46,6 +122,36 @@ AREAS: list[dict] = [
46
  "processes": ["Transaction entry", "Credit memos", "Receipts", "Receipt application", "Customer statements"],
47
  "navigator": ["Receivables > Billing", "Receivables > Accounts Receivable"],
48
  "key_tasks": ["Create Transaction", "Manage Transactions", "Create Receipt", "Manage Receipts"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
49
  "readiness": {"family": "erp", "product": "fins", "match": ["Receivables", "Collections", "Collector", "Billing", "Customer Payments", "Receipt"]},
50
  "test_data": [{"resource": "receivablesInvoices", "order_by": "CustomerTransactionId:desc",
51
  "fields": {"business_unit": "BusinessUnit", "customer": "BillToCustomerName", "transaction_type": "TransactionType",
@@ -56,6 +162,32 @@ AREAS: list[dict] = [
56
  "processes": ["Journal entry", "Journal approval and posting", "Period close", "Account inquiry"],
57
  "navigator": ["General Accounting > Journals", "General Accounting > Period Close"],
58
  "key_tasks": ["Create Journal", "Manage Journals", "Manage Accounting Periods"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
  "readiness": {"family": "erp", "product": "fins", "match": ["General Ledger", "Ledger", "Intercompany", "Financial Reporting", "Period Close", "Subledger Accounting", "Budgetary Control", "Journal"]},
60
  "test_data": [{"resource": "ledgersLOV", "fields": {"ledger": "Name"}},
61
  {"resource": "journalBatches", "order_by": "JeBatchId:desc",
@@ -64,29 +196,150 @@ AREAS: list[dict] = [
64
  "processes": ["Expense entry", "Expense report approval", "Expense audit", "Reimbursement"],
65
  "navigator": ["Me > Expenses"],
66
  "key_tasks": ["Create Expense Report", "Create Report", "Manage Expense Reports"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
67
  "readiness": {"family": "erp", "product": "fins", "match": ["Expense"]},
68
  "test_data": [{"resource": "expenseReports", "order_by": "ExpenseReportId:desc", "fields": {"currency": "ReimbursementCurrencyCode"}}]},
69
  {"code": "FA", "id": "assets", "name": "Fixed Assets", "probes": ["fixedAssets"],
70
  "processes": ["Asset additions", "Asset adjustments", "Depreciation", "Retirements"],
71
  "navigator": ["Fixed Assets > Assets"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  "readiness": {"family": "erp", "product": "fins", "match": ["Assets", "Asset "]},
73
  "test_data": [{"resource": "fixedAssets", "order_by": "AssetId:desc", "fields": {"book": "BookTypeCode", "category": "AssetCategory"}}]},
74
  {"code": "CM", "id": "cash-management", "name": "Cash Management", "probes": ["cashBankAccounts", "cashBankStatements"],
75
  "processes": ["Bank statements", "Reconciliation", "Cash positioning"],
76
  "navigator": ["Cash Management > Bank Statements and Reconciliation"],
77
  "key_tasks": ["Create Bank Statement", "Manage Bank Statements", "Manage Reconciliation Exceptions", "Create External Cash Transaction"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
78
  "readiness": {"family": "erp", "product": "fins", "match": ["Cash Management", "Cash Processing", "Bank Statement", "Cash Positioning", "Reconciliation"]},
79
  "test_data": [{"resource": "cashBankAccounts", "fields": {"bank_account": "BankAccountName"}}]},
80
  {"code": "PPM", "id": "projects", "name": "Project Management", "probes": ["projects"],
81
  "processes": ["Project creation", "Project costing", "Project billing"],
82
  "navigator": ["Projects > Project Financial Management"],
83
  "key_tasks": ["Create Project", "Manage Projects", "Manage Project Costs"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
84
  "readiness": {"family": "erp", "product": "ppm", "match": []},
85
  "test_data": [{"resource": "projects", "order_by": "ProjectId:desc", "fields": {"business_unit": "OwningOrganizationName"}}]},
86
  {"code": "OM", "id": "order-management", "name": "Order Management", "probes": ["salesOrdersForOrderHub"],
87
  "processes": ["Sales order entry", "Order fulfilment", "Returns"],
88
  "navigator": ["Order Management > Order Management"],
89
  "key_tasks": ["Create Order", "Manage Orders"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
90
  "readiness": {"family": "scm", "product": "order", "match": []},
91
  "test_data": [{"resource": "salesOrdersForOrderHub", "order_by": "HeaderId:desc",
92
  "fields": {"business_unit": "BusinessUnitName", "customer": "BuyingPartyName"}}]},
@@ -94,11 +347,36 @@ AREAS: list[dict] = [
94
  "processes": ["Item setup", "Transfers", "Cycle counts", "Receipts into stock"],
95
  "navigator": ["Supply Chain Execution > Inventory Management (Classic)", "Supply Chain Execution > Inventory Management"],
96
  "key_tasks": ["Create Miscellaneous Transaction", "Manage Item Quantities", "Create Transfer Order"],
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  "readiness": {"family": "scm", "product": "inv", "match": []},
98
  "test_data": [{"resource": "inventoryOrganizations", "fields": {"organization": "OrganizationCode"}}]},
99
  ]
100
 
101
- KEYS = ("code", "id", "name", "probes", "processes", "navigator", "test_data", "readiness", "words")
102
 
103
  # what people call each area in a request ("start a run of Payables"), besides its name and code
104
  WORDS: dict[str, tuple[str, ...]] = {
 
7
  its quarterly What's New (`readiness`: the guide's family and product on docs.oracle.com/en/cloud/saas/readiness, and the
8
  words that pick the area's rows from a guide shared by several areas; empty `match` = every row of the guide).
9
 
10
+ `regression` lists the standard regression and edge-case checks a senior functional tester runs on the area every
11
+ cycle, in business language, each with the process it belongs to ({"process": one of the area's `processes`, "check":
12
+ "Invoice without a supplier site is refused"}): happy paths, refusals, boundaries, duplicates, state changes, defaults
13
+ and searches. Only checks the area's own screens can show (a status, a field's value, a message, a search result); no
14
+ reports, batch jobs, setup changes or other products. A full regression run asks the AI model for one scenario per
15
+ check that no library scenario covers yet (graph/nodes/ai_scenarios.py).
16
+
17
  Nothing here is pod-specific. A deployment can add or change areas without a code change with FPT_HOME/fusion_areas.json
18
  (a list in the same shape; an entry whose "code" matches replaces the built-in one). Resource names are the standard
19
  Fusion REST resources of /fscmRestApi/resources/11.13.18.05; a resource a pod does not have answers 404 and the area
 
28
 
29
  FSCM = "/fscmRestApi/resources/11.13.18.05"
30
 
31
+
32
+ def _checks(process: str, *checks: str) -> list[dict]:
33
+ """Regression checks of one business process, in the catalog's shape."""
34
+ return [{"process": process, "check": c} for c in checks]
35
+
36
+
37
  AREAS: list[dict] = [
38
  {"code": "AP", "id": "payables", "name": "Payables", "probes": ["invoices", "suppliers"],
39
  "processes": ["Invoice entry", "Invoice validation and holds", "Invoice matching", "Credit memos", "Prepayments", "Payments"],
40
  "navigator": ["Payables > Invoices", "Payables > Payments"],
41
  "key_tasks": ["Create Invoice", "Manage Invoices", "Create Payment", "Manage Payments", "Submit Payment Process Request"],
42
+ "regression": [
43
+ *_checks("Invoice entry",
44
+ "Standard invoice with one item line saves and gets an invoice number",
45
+ "Supplier site, payment terms and currency default from the supplier",
46
+ "Invoice without a supplier site is refused",
47
+ "Invoice without an invoice amount is refused",
48
+ "Duplicate invoice number for the same supplier is refused",
49
+ "Negative amount on a standard invoice is refused",
50
+ "Amount with more decimals than the invoice currency allows is refused or rounded",
51
+ "Accounting date in a closed period is refused",
52
+ "Cancel without saving leaves no invoice behind (a search by its number finds nothing)",
53
+ "Saved invoice is found by its number in Manage Invoices"),
54
+ *_checks("Invoice validation and holds",
55
+ "Invoice whose lines equal the header amount validates with no holds",
56
+ "Lines one cent short of the header amount put the invoice on a line variance hold",
57
+ "Changing the amount of a validated invoice makes it need revalidation",
58
+ "Canceled invoice shows status Canceled and cannot be validated again"),
59
+ *_checks("Invoice matching",
60
+ "Invoice matched to a purchase order takes the order's supplier and lines",
61
+ "Billing more than the ordered quantity puts the matched invoice on a quantity ordered hold",
62
+ "Invoice matched to an unknown or closed purchase order number is refused"),
63
+ *_checks("Credit memos",
64
+ "Credit memo with a negative amount saves and validates",
65
+ "Credit memo with a positive amount is refused"),
66
+ *_checks("Prepayments",
67
+ "Prepayment invoice saves with type Prepayment and validates",
68
+ "Applying more than the prepayment's available amount is refused"),
69
+ *_checks("Payments",
70
+ "Payment of a validated invoice is created and found in Manage Payments",
71
+ "Paying more than the invoice's unpaid amount is refused",
72
+ "Voided payment shows status Voided",
73
+ "Payment process request without a name or pay through date is refused")
74
+ ],
75
  "readiness": {"family": "erp", "product": "fins", "match": ["Payables", "Payment", "Supplier Invoice", "Invoice Imaging", "Withholding"]},
76
  "test_data": [{"resource": "invoices", "order_by": "InvoiceId:desc", "key_field": "InvoiceId", "own_field": "InvoiceNumber",
77
  "fields": {"business_unit": "BusinessUnit", "supplier": "Supplier", "supplier_site": "SupplierSite",
 
82
  "processes": ["Requisition entry", "Requisition approval", "Purchase order creation", "Change orders", "Receiving"],
83
  "navigator": ["Procurement > Purchase Requisitions", "Procurement > Purchase Orders"],
84
  "key_tasks": ["Create Order", "Manage Orders", "Manage Requisitions", "Manage Agreements"],
85
+ "regression": [
86
+ *_checks("Requisition entry",
87
+ "Requisition with one noncatalog line saves with status Incomplete",
88
+ "Requisition line with zero quantity is refused",
89
+ "Requisition line with a negative price is refused",
90
+ "Need-by date in the past is refused or warned",
91
+ "Saved requisition is found by its number in Manage Requisitions"),
92
+ *_checks("Requisition approval",
93
+ "Submitted requisition shows status Pending approval",
94
+ "Requisition line without a charge account cannot be submitted",
95
+ "Withdrawn requisition returns to status Incomplete and can be changed"),
96
+ *_checks("Purchase order creation",
97
+ "Purchase order with one goods line saves; supplier site, currency and payment terms default from the supplier",
98
+ "Order without a supplier is refused",
99
+ "Order line with zero quantity is refused",
100
+ "Order line with a negative price is refused",
101
+ "Price with more decimals than allowed is refused or rounded",
102
+ "Order total equals quantity times price of its lines",
103
+ "Submitted order shows status Pending approval or Open",
104
+ "Cancel without saving leaves no draft order behind (a search finds nothing)",
105
+ "Order is found by its number in Manage Orders and an unknown number finds nothing"),
106
+ *_checks("Change orders",
107
+ "Change order raising a line quantity on an open order shows a new revision",
108
+ "Reducing an order line below the quantity already received is refused",
109
+ "Canceled order shows status Canceled",
110
+ "Canceled order cannot be changed"),
111
+ *_checks("Receiving",
112
+ "Receipt for an open order line shows the received quantity on the order",
113
+ "Receiving more than the ordered quantity plus tolerance is refused")
114
+ ],
115
  "readiness": {"family": "scm", "product": "proc", "match": []},
116
  "test_data": [{"resource": "purchaseOrders", "order_by": "POHeaderId:desc",
117
  "fields": {"business_unit": "ProcurementBU", "supplier": "Supplier", "supplier_site": "SupplierSite",
 
122
  "processes": ["Transaction entry", "Credit memos", "Receipts", "Receipt application", "Customer statements"],
123
  "navigator": ["Receivables > Billing", "Receivables > Accounts Receivable"],
124
  "key_tasks": ["Create Transaction", "Manage Transactions", "Create Receipt", "Manage Receipts"],
125
+ "regression": [
126
+ *_checks("Transaction entry",
127
+ "Invoice with one line completes and shows status Complete",
128
+ "Bill-to site, payment terms and currency default from the customer and transaction type",
129
+ "Transaction without a customer is refused",
130
+ "Transaction without a transaction type is refused",
131
+ "Completing a transaction without lines is refused",
132
+ "Duplicate transaction number for the same transaction source is refused",
133
+ "Line amount equals quantity times unit price",
134
+ "Accounting date in a closed period is refused",
135
+ "Completed transaction must be made incomplete before its lines can change",
136
+ "Saved transaction is found by its number in Manage Transactions"),
137
+ *_checks("Credit memos",
138
+ "Credit memo against a completed invoice reduces its balance due",
139
+ "Crediting more than the invoice's balance due is refused",
140
+ "Credit memo line with a positive amount is refused"),
141
+ *_checks("Receipts",
142
+ "Standard receipt with a receipt method saves and shows status Unapplied",
143
+ "Receipt without a receipt method or amount is refused",
144
+ "Receipt with a zero or negative amount is refused",
145
+ "Reversed receipt shows status Reversed",
146
+ "Duplicate receipt number for the same customer and date is refused or warned"),
147
+ *_checks("Receipt application",
148
+ "Receipt applied in full to an invoice closes the invoice's balance due",
149
+ "Applying more than the receipt's unapplied amount is refused",
150
+ "Partial application leaves the rest of the receipt unapplied",
151
+ "Unapplying a receipt restores the invoice's balance due"),
152
+ *_checks("Customer statements",
153
+ "Search by customer in Manage Transactions lists that customer's open transactions with their balance")
154
+ ],
155
  "readiness": {"family": "erp", "product": "fins", "match": ["Receivables", "Collections", "Collector", "Billing", "Customer Payments", "Receipt"]},
156
  "test_data": [{"resource": "receivablesInvoices", "order_by": "CustomerTransactionId:desc",
157
  "fields": {"business_unit": "BusinessUnit", "customer": "BillToCustomerName", "transaction_type": "TransactionType",
 
162
  "processes": ["Journal entry", "Journal approval and posting", "Period close", "Account inquiry"],
163
  "navigator": ["General Accounting > Journals", "General Accounting > Period Close"],
164
  "key_tasks": ["Create Journal", "Manage Journals", "Manage Accounting Periods"],
165
+ "regression": [
166
+ *_checks("Journal entry",
167
+ "Balanced journal with one debit and one credit line saves",
168
+ "Unbalanced journal (debits not equal to credits) is refused",
169
+ "One-cent difference between debits and credits is refused",
170
+ "Journal without a category is refused",
171
+ "Line with both a debit and a credit amount is refused",
172
+ "Line with an invalid or disabled account combination is refused",
173
+ "Accounting period defaults from the accounting date",
174
+ "Journal with an accounting date in a closed period is refused",
175
+ "Amount with more decimals than the currency allows is refused or rounded",
176
+ "Foreign currency journal defaults a conversion rate type and needs a rate",
177
+ "Journal is found by its batch name in Manage Journals and an unknown name finds nothing"),
178
+ *_checks("Journal approval and posting",
179
+ "Posted journal shows status Posted",
180
+ "Posted journal cannot be edited or deleted",
181
+ "Reversing a posted journal creates its reversal journal",
182
+ "Reversing the same journal twice is refused",
183
+ "Journal that needs approval shows an approval status after Post",
184
+ "Unposted journal can be deleted and is no longer found"),
185
+ *_checks("Period close",
186
+ "Manage Accounting Periods shows the ledger's periods with their statuses",
187
+ "Journal in a period with status Future Entry saves but cannot be posted"),
188
+ *_checks("Account inquiry",
189
+ "Searching journals by account finds the posted journal lines")
190
+ ],
191
  "readiness": {"family": "erp", "product": "fins", "match": ["General Ledger", "Ledger", "Intercompany", "Financial Reporting", "Period Close", "Subledger Accounting", "Budgetary Control", "Journal"]},
192
  "test_data": [{"resource": "ledgersLOV", "fields": {"ledger": "Name"}},
193
  {"resource": "journalBatches", "order_by": "JeBatchId:desc",
 
196
  "processes": ["Expense entry", "Expense report approval", "Expense audit", "Reimbursement"],
197
  "navigator": ["Me > Expenses"],
198
  "key_tasks": ["Create Expense Report", "Create Report", "Manage Expense Reports"],
199
+ "regression": [
200
+ *_checks("Expense entry",
201
+ "Expense report with one expense item saves with status Saved",
202
+ "Expense item without an expense type is refused",
203
+ "Expense item without an amount is refused",
204
+ "Expense item with a zero or negative amount is refused",
205
+ "Expense date in the future is refused",
206
+ "Expense older than the policy allows is flagged as a policy violation",
207
+ "Amount over the expense type's limit shows a policy warning",
208
+ "Expense in a foreign currency gets a conversion rate and reimbursable amount",
209
+ "Reimbursement currency defaults to the person's currency",
210
+ "Itemized expense lines must add up to the expense amount",
211
+ "Itemization one cent off the expense amount is refused",
212
+ "Report total equals the sum of its expense items",
213
+ "The same expense entered twice is flagged as a possible duplicate",
214
+ "Purpose longer than the field allows is refused or cut"),
215
+ *_checks("Expense report approval",
216
+ "Submitted report shows status Pending manager approval",
217
+ "Report without a purpose cannot be submitted",
218
+ "Withdrawn report returns to status Saved and can be changed"),
219
+ *_checks("Expense audit",
220
+ "Policy violation needs a justification before the report can be submitted",
221
+ "Expense that needs a receipt cannot be submitted without one or a missing receipt justification"),
222
+ *_checks("Reimbursement",
223
+ "Report is found by its number in Manage Expense Reports with its reimbursable amount")
224
+ ],
225
  "readiness": {"family": "erp", "product": "fins", "match": ["Expense"]},
226
  "test_data": [{"resource": "expenseReports", "order_by": "ExpenseReportId:desc", "fields": {"currency": "ReimbursementCurrencyCode"}}]},
227
  {"code": "FA", "id": "assets", "name": "Fixed Assets", "probes": ["fixedAssets"],
228
  "processes": ["Asset additions", "Asset adjustments", "Depreciation", "Retirements"],
229
  "navigator": ["Fixed Assets > Assets"],
230
+ "regression": [
231
+ *_checks("Asset additions",
232
+ "Asset added with a category and cost saves and gets an asset number",
233
+ "Book, depreciation method and life default from the asset category",
234
+ "Asset without a category is refused",
235
+ "Asset without a cost is refused",
236
+ "Asset without an assignment (location and expense account) is refused",
237
+ "Date placed in service in the future is refused",
238
+ "Asset with zero units is refused",
239
+ "Duplicate tag number is refused",
240
+ "Asset is found by its number in Manage Assets and an unknown number finds nothing"),
241
+ *_checks("Asset adjustments",
242
+ "Cost adjustment changes the asset's current cost",
243
+ "Transfer to a new location shows the new assignment",
244
+ "Transferring more units than the asset has is refused"),
245
+ *_checks("Depreciation",
246
+ "Salvage value greater than the cost is refused",
247
+ "Asset with Depreciate switched off shows no depreciation"),
248
+ *_checks("Retirements",
249
+ "Full retirement shows the asset as retired",
250
+ "Retiring more than the asset's cost or units is refused",
251
+ "Retirement date before the date placed in service is refused",
252
+ "Adjusting a fully retired asset is refused")
253
+ ],
254
  "readiness": {"family": "erp", "product": "fins", "match": ["Assets", "Asset "]},
255
  "test_data": [{"resource": "fixedAssets", "order_by": "AssetId:desc", "fields": {"book": "BookTypeCode", "category": "AssetCategory"}}]},
256
  {"code": "CM", "id": "cash-management", "name": "Cash Management", "probes": ["cashBankAccounts", "cashBankStatements"],
257
  "processes": ["Bank statements", "Reconciliation", "Cash positioning"],
258
  "navigator": ["Cash Management > Bank Statements and Reconciliation"],
259
  "key_tasks": ["Create Bank Statement", "Manage Bank Statements", "Manage Reconciliation Exceptions", "Create External Cash Transaction"],
260
+ "regression": [
261
+ *_checks("Bank statements",
262
+ "Manual bank statement with one line saves for a bank account",
263
+ "Statement without a bank account is refused",
264
+ "Statement without a statement number or statement date is refused",
265
+ "Duplicate statement number for the same bank account is refused",
266
+ "Closing balance one cent off the opening balance plus lines is refused or flagged",
267
+ "Statement line without an amount or transaction type is refused",
268
+ "Statement line with a zero amount is refused",
269
+ "Statement date in the future is refused",
270
+ "Statement is found by its number in Manage Bank Statements and an unknown number finds nothing"),
271
+ *_checks("Reconciliation",
272
+ "Statement line manually reconciled to a matching transaction shows status Reconciled",
273
+ "Reconciling a line to a transaction of a different amount is refused",
274
+ "Unreconciling a reconciled line returns it to Unreconciled",
275
+ "Reconciliation exceptions search lists the unreconciled lines of a statement",
276
+ "External cash transaction saves with status Unreconciled",
277
+ "External transaction without an amount, date or bank account is refused",
278
+ "External transaction with a negative amount is refused"),
279
+ *_checks("Cash positioning",
280
+ "External transaction takes the bank account's currency",
281
+ "Bank account search finds the account with its currency")
282
+ ],
283
  "readiness": {"family": "erp", "product": "fins", "match": ["Cash Management", "Cash Processing", "Bank Statement", "Cash Positioning", "Reconciliation"]},
284
  "test_data": [{"resource": "cashBankAccounts", "fields": {"bank_account": "BankAccountName"}}]},
285
  {"code": "PPM", "id": "projects", "name": "Project Management", "probes": ["projects"],
286
  "processes": ["Project creation", "Project costing", "Project billing"],
287
  "navigator": ["Projects > Project Financial Management"],
288
  "key_tasks": ["Create Project", "Manage Projects", "Manage Project Costs"],
289
+ "regression": [
290
+ *_checks("Project creation",
291
+ "Project created from a template saves with status Unapproved",
292
+ "Project without a name or number is refused",
293
+ "Duplicate project number or name is refused",
294
+ "Finish date before the start date is refused",
295
+ "Business unit, organization and currency default from the template",
296
+ "Project name longer than the field allows is refused or cut",
297
+ "Task with dates outside the project's dates is refused",
298
+ "Changing the status to Active is saved and shown",
299
+ "Project is found by its number in Manage Projects and an unknown number finds nothing"),
300
+ *_checks("Project costing",
301
+ "Miscellaneous cost on a chargeable task of an active project saves",
302
+ "Cost on a task that is not chargeable is refused",
303
+ "Cost with an expenditure date outside the task's dates is refused",
304
+ "Cost with a zero quantity is refused",
305
+ "Cost on a closed project is refused",
306
+ "Cost without an expenditure type is refused",
307
+ "Search by project in Manage Project Costs lists the project's costs"),
308
+ *_checks("Project billing",
309
+ "Billable flag defaults from the task on a new cost",
310
+ "Cost on a task that is not billable shows as not billable")
311
+ ],
312
  "readiness": {"family": "erp", "product": "ppm", "match": []},
313
  "test_data": [{"resource": "projects", "order_by": "ProjectId:desc", "fields": {"business_unit": "OwningOrganizationName"}}]},
314
  {"code": "OM", "id": "order-management", "name": "Order Management", "probes": ["salesOrdersForOrderHub"],
315
  "processes": ["Sales order entry", "Order fulfilment", "Returns"],
316
  "navigator": ["Order Management > Order Management"],
317
  "key_tasks": ["Create Order", "Manage Orders"],
318
+ "regression": [
319
+ *_checks("Sales order entry",
320
+ "Order with one line submits and shows status Processing",
321
+ "Draft order saves with status Draft",
322
+ "Bill-to, ship-to and payment terms default from the customer",
323
+ "Order without a customer is refused",
324
+ "Submitting an order without lines is refused",
325
+ "Line with a zero or negative quantity is refused",
326
+ "Decimal quantity for an item sold in whole units is refused",
327
+ "Line amount equals quantity times the price list price",
328
+ "Requested ship date in the past is refused or warned",
329
+ "Duplicate customer purchase order number is warned",
330
+ "Order is found by its number in Manage Orders and an unknown number finds nothing",
331
+ "Copying an order creates a new draft with the same lines"),
332
+ *_checks("Order fulfilment",
333
+ "Hold applied to an order shows the hold on the order",
334
+ "Releasing the hold removes it from the order",
335
+ "Canceling a submitted order shows status Canceled",
336
+ "Canceling a shipped line is refused",
337
+ "Revising a submitted order's quantity creates a new order version"),
338
+ *_checks("Returns",
339
+ "Return line referencing an original order line saves",
340
+ "Returning more than the shipped quantity is refused",
341
+ "Return without a return reason is refused")
342
+ ],
343
  "readiness": {"family": "scm", "product": "order", "match": []},
344
  "test_data": [{"resource": "salesOrdersForOrderHub", "order_by": "HeaderId:desc",
345
  "fields": {"business_unit": "BusinessUnitName", "customer": "BuyingPartyName"}}]},
 
347
  "processes": ["Item setup", "Transfers", "Cycle counts", "Receipts into stock"],
348
  "navigator": ["Supply Chain Execution > Inventory Management (Classic)", "Supply Chain Execution > Inventory Management"],
349
  "key_tasks": ["Create Miscellaneous Transaction", "Manage Item Quantities", "Create Transfer Order"],
350
+ "regression": [
351
+ *_checks("Receipts into stock",
352
+ "Miscellaneous receipt into a subinventory increases the on-hand quantity",
353
+ "Miscellaneous transaction without an item, subinventory or quantity is refused",
354
+ "Miscellaneous transaction with a zero quantity is refused",
355
+ "Lot-controlled item without a lot number is refused",
356
+ "Serial-controlled item needs as many serial numbers as the quantity",
357
+ "Transaction date in a closed inventory period is refused",
358
+ "Quantity with more decimals than the unit of measure allows is refused or rounded",
359
+ "Locator-controlled subinventory without a locator is refused"),
360
+ *_checks("Transfers",
361
+ "Miscellaneous issue larger than the on-hand quantity is refused",
362
+ "Subinventory transfer moves the quantity from one subinventory to the other",
363
+ "Transfer to the same subinventory and locator is refused",
364
+ "Transfer order with one line saves and is found again",
365
+ "Transfer order without a destination organization is refused"),
366
+ *_checks("Cycle counts",
367
+ "Manage Item Quantities shows on-hand and available quantity by subinventory",
368
+ "Item quantity search for an unknown item finds nothing",
369
+ "Available quantity is the on-hand quantity less reservations"),
370
+ *_checks("Item setup",
371
+ "Unit of measure defaults from the item on a transaction",
372
+ "Transaction for an item not assigned to the organization is refused",
373
+ "Item is found by its number in Manage Item Quantities")
374
+ ],
375
  "readiness": {"family": "scm", "product": "inv", "match": []},
376
  "test_data": [{"resource": "inventoryOrganizations", "fields": {"organization": "OrganizationCode"}}]},
377
  ]
378
 
379
+ KEYS = ("code", "id", "name", "probes", "processes", "navigator", "key_tasks", "test_data", "readiness", "words", "regression")
380
 
381
  # what people call each area in a request ("start a run of Payables"), besides its name and code
382
  WORDS: dict[str, tuple[str, ...]] = {
coworker/platform/migrations/026_agent_studio_delivery_contract.sql ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ -- 026: the Agent Studio contract made safe to repeat (docs/AGENT_STUDIO.md).
2
+ -- agent_cycles.idempotency_key: a start sent again with the same Idempotency-Key header returns the cycle it made.
3
+ -- agent_callbacks.dead_at: an event that ran out of tries (push or pull) is kept as a dead letter for an admin to send again.
4
+ -- agent_callbacks.superseded_by: a "paused" event not delivered yet is dropped once a newer event of its cycle is queued.
5
+ ALTER TABLE agent_cycles ADD COLUMN idempotency_key TEXT;
6
+ CREATE INDEX IF NOT EXISTS agent_cycles_client_correlation ON agent_cycles (client_id, correlation_id);
7
+ CREATE INDEX IF NOT EXISTS agent_cycles_client_idempotency ON agent_cycles (client_id, idempotency_key);
8
+ ALTER TABLE agent_callbacks ADD COLUMN dead_at TEXT;
9
+ ALTER TABLE agent_callbacks ADD COLUMN superseded_by TEXT;
coworker/platform/notify.py CHANGED
@@ -54,6 +54,7 @@ COWORKER = {
54
  "run.failed": "Astra",
55
  "run.stopped": "Astra",
56
  "defect.created": "Triage",
 
57
  "test": "Astra",
58
  }
59
  DECISION_WORDS = {"GO": "Ready", "NO-GO": "Not ready", "HELD": "Held"}
@@ -367,6 +368,11 @@ class Notifier:
367
  if kind == "run.stopped":
368
  how = "by the emergency stop" if run.get("status") == "killed" else "by a person"
369
  return f"{name} was stopped", f"The test run was stopped {how}. Nothing more runs for it.", f"/runs/{rid}"
 
 
 
 
 
370
  if kind == "defect.created":
371
  tid, case = extra.get("ticket_id") or "", extra.get("case_id") or ""
372
  return (f"Defect {tid} raised", f"A person confirmed a real defect in {case} ({name}).".replace(" ()", ""),
 
54
  "run.failed": "Astra",
55
  "run.stopped": "Astra",
56
  "defect.created": "Triage",
57
+ "agent_studio.dead_letter": "Astra",
58
  "test": "Astra",
59
  }
60
  DECISION_WORDS = {"GO": "Ready", "NO-GO": "Not ready", "HELD": "Held"}
 
368
  if kind == "run.stopped":
369
  how = "by the emergency stop" if run.get("status") == "killed" else "by a person"
370
  return f"{name} was stopped", f"The test run was stopped {how}. Nothing more runs for it.", f"/runs/{rid}"
371
+ if kind == "agent_studio.dead_letter":
372
+ n, events = int(extra.get("count") or 1), ", ".join(str(e).replace("_", " ") for e in extra.get("events") or [])
373
+ return (f"{n} event(s) could not be delivered to Oracle Fusion",
374
+ f"Astra gave up on {events or 'them'} after every retry. Open Agent Studio, Callbacks, to see why and send "
375
+ f"them again.", "/agent-studio")
376
  if kind == "defect.created":
377
  tid, case = extra.get("ticket_id") or "", extra.get("case_id") or ""
378
  return (f"Defect {tid} raised", f"A person confirmed a real defect in {case} ({name}).".replace(" ()", ""),
coworker/platform/preflight.py CHANGED
@@ -1,11 +1,24 @@
1
  """Pre-flight: before a Fusion run starts its browsers, the things it needs are checked in seconds, so a run that
2
  cannot work stops with the reason instead of spending its browser time failing.
3
 
4
- Checks, read-only: the remote browser runner answers and has the scenario files its step specs read (tests/cases); the
5
- pod accepts the test user (the pod's connection test); every area of the run has test data. Each result is
6
- {name, ok, detail}; `problems` lists the failed ones' details."""
 
7
  from __future__ import annotations
8
 
 
 
 
 
 
 
 
 
 
 
 
 
9
 
10
  def runner_check(svc) -> dict | None:
11
  """The remote runner's /healthz, or None when browsers run on this server."""
@@ -25,7 +38,22 @@ def runner_check(svc) -> dict | None:
25
  if h.get("cases") is False:
26
  return {"name": "runner", "ok": False, "detail": f"The browser runner at {base} has no scenario files (tests/cases): "
27
  "update it with deploy/runner/sync.sh."}
28
- return {"name": "runner", "ok": True, "detail": f"Browser runner ready (version {h.get('version') or 'unknown'})."}
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
 
31
  def check(svc, pod_id: int, run_id: str, areas: list[str]) -> list[dict]:
@@ -40,9 +68,11 @@ def check(svc, pod_id: int, run_id: str, areas: list[str]) -> list[dict]:
40
  out.append(failed or {"name": "fusion", "ok": True, "detail": sign_in[-1]["detail"] if sign_in else "Oracle Fusion answers."})
41
  cands = reg.test_data_candidates(pod_id, run_id)
42
  missing = [a for a in areas if not cands.get(a.upper())]
43
- out.append({"name": "test_data", "ok": not missing, "detail":
44
- f"No test data for {', '.join(missing)} on this pod: run Discover on the Test environments page, or set it there."
45
- if missing else f"Test data for {', '.join(areas)}."})
 
 
46
  return out
47
 
48
 
 
1
  """Pre-flight: before a Fusion run starts its browsers, the things it needs are checked in seconds, so a run that
2
  cannot work stops with the reason instead of spending its browser time failing.
3
 
4
+ Checks, read-only: the remote browser runner answers, has the scenario files its step specs read (tests/cases) and runs
5
+ the same commit as this server when both know theirs; the pod accepts the test user (the pod's connection test); every
6
+ area of the run has test data (a warning only). A busy runner is information, not a stop: the run waits for it. Each
7
+ result is {name, ok, detail}; `problems` lists the failed ones' details."""
8
  from __future__ import annotations
9
 
10
+ import re
11
+
12
+ from ..config import server_commit
13
+
14
+ COMMIT = re.compile(r"[0-9a-f]{7,40}")
15
+
16
+
17
+ def _same_commit(a: str, b: str) -> bool:
18
+ """Two commit ids name the same commit: one is a prefix of the other (sync.sh writes a 12-character short id)."""
19
+ n = min(len(a), len(b))
20
+ return n >= 7 and a[:n] == b[:n]
21
+
22
 
23
  def runner_check(svc) -> dict | None:
24
  """The remote runner's /healthz, or None when browsers run on this server."""
 
38
  if h.get("cases") is False:
39
  return {"name": "runner", "ok": False, "detail": f"The browser runner at {base} has no scenario files (tests/cases): "
40
  "update it with deploy/runner/sync.sh."}
41
+ version = str(h.get("version") or "unknown").strip().lower()
42
+ mine = server_commit()
43
+ if mine and COMMIT.fullmatch(version) and not _same_commit(version, mine):
44
+ return {"name": "runner", "ok": False, "detail": f"The browser runner at {base} runs commit {version[:12]} but this server "
45
+ f"runs {mine[:12]}: update it with deploy/runner/sync.sh on {mine[:12]}."}
46
+ out = {"name": "runner", "ok": True, "detail": f"Browser runner ready (version {version})."}
47
+ if mine and not COMMIT.fullmatch(version): # installed some other way: it may run older scenarios or step code
48
+ out.update(warning=True, detail=f"Browser runner ready, but it does not say which commit it runs (this server runs "
49
+ f"{mine[:12]}): update it with deploy/runner/sync.sh.")
50
+ if h.get("busy"): # one browser job at a time: the run waits for it (remote_runner_busy_wait_minutes), not fails
51
+ try:
52
+ wait = f"up to {int(svc.cfg.remote_runner_busy_wait_minutes)} minutes"
53
+ except (TypeError, ValueError):
54
+ wait = "for a while"
55
+ out.update(busy=True, detail=out["detail"] + f" It is busy with another job right now: this run waits for it ({wait}).")
56
+ return out
57
 
58
 
59
  def check(svc, pod_id: int, run_id: str, areas: list[str]) -> list[dict]:
 
68
  out.append(failed or {"name": "fusion", "ok": True, "detail": sign_in[-1]["detail"] if sign_in else "Oracle Fusion answers."})
69
  cands = reg.test_data_candidates(pod_id, run_id)
70
  missing = [a for a in areas if not cands.get(a.upper())]
71
+ # a warning, not a stop: an area with no records yet has no sampled data, and its scenarios that use no pod value
72
+ # can still pass; the ones that need one fail with the same message
73
+ out.append({"name": "test_data", "ok": True, "warning": bool(missing), "detail":
74
+ f"No test data for {', '.join(missing)} on this pod: scenarios that need it will fail. Run Discover on the Test "
75
+ "environments page, or set it there." if missing else f"Test data for {', '.join(areas)}."})
76
  return out
77
 
78
 
coworker/platform/statesync.py CHANGED
@@ -221,20 +221,25 @@ class Syncer:
221
  self._stop = threading.Event()
222
  self._wake = threading.Event() # soon(): save now instead of at the next interval
223
  self._reason = "changed"
 
 
 
224
  self._lock = threading.Lock() # one save at a time (the loop, soon(), an administrator's save, shutdown)
225
  self._thread: threading.Thread | None = None
226
  self.last_error: str | None = None
227
  self.last_error_at: str | None = None
228
 
229
- def tick(self, reason: str = "changed") -> bool:
230
  with self._lock:
 
231
  try:
232
- if signature(self.svc) == self.svc.extra.get("state_signature"):
233
  return False
234
  push(self.svc, reason)
235
  self.last_error = None
236
  return True
237
  except Exception as e: # noqa: BLE001 - never take the application down because a save failed
 
238
  self.last_error = f"{type(e).__name__}: {str(e)[:200]}"
239
  self.last_error_at = now_iso()
240
  log.warning("state save failed: %s", self.last_error)
@@ -244,6 +249,7 @@ class Syncer:
244
  """Save as soon as possible: something a restart must not lose has just finished (a screen read, a run that now
245
  waits for a person or has ended). Only such moments call it, so the bucket's request budget still holds."""
246
  self._reason = reason
 
247
  self._wake.set()
248
 
249
  def start(self) -> None:
@@ -268,7 +274,7 @@ class Syncer:
268
  _RUNNING = None
269
  self._stop.set()
270
  self._wake.set()
271
- self.tick("shutdown") # one last save so a restart continues from here
272
 
273
 
274
  _RUNNING: Syncer | None = None # the API process's saver, once started
 
221
  self._stop = threading.Event()
222
  self._wake = threading.Event() # soon(): save now instead of at the next interval
223
  self._reason = "changed"
224
+ # soon() was asked: push even when the signature looks saved. A save that was uploading while the event wrote
225
+ # records a signature that already includes the write its archive does not hold, so the signature alone would skip it
226
+ self._dirty = False
227
  self._lock = threading.Lock() # one save at a time (the loop, soon(), an administrator's save, shutdown)
228
  self._thread: threading.Thread | None = None
229
  self.last_error: str | None = None
230
  self.last_error_at: str | None = None
231
 
232
+ def tick(self, reason: str = "changed", force: bool = False) -> bool:
233
  with self._lock:
234
+ dirty, self._dirty = self._dirty, False
235
  try:
236
+ if not (force or dirty) and signature(self.svc) == self.svc.extra.get("state_signature"):
237
  return False
238
  push(self.svc, reason)
239
  self.last_error = None
240
  return True
241
  except Exception as e: # noqa: BLE001 - never take the application down because a save failed
242
+ self._dirty = self._dirty or dirty # the asked-for save did not happen: still owed
243
  self.last_error = f"{type(e).__name__}: {str(e)[:200]}"
244
  self.last_error_at = now_iso()
245
  log.warning("state save failed: %s", self.last_error)
 
249
  """Save as soon as possible: something a restart must not lose has just finished (a screen read, a run that now
250
  waits for a person or has ended). Only such moments call it, so the bucket's request budget still holds."""
251
  self._reason = reason
252
+ self._dirty = True
253
  self._wake.set()
254
 
255
  def start(self) -> None:
 
274
  _RUNNING = None
275
  self._stop.set()
276
  self._wake.set()
277
+ self.tick("shutdown", force=True) # one last save so a restart continues from here
278
 
279
 
280
  _RUNNING: Syncer | None = None # the API process's saver, once started
coworker/platform/step_writer.py CHANGED
@@ -71,6 +71,7 @@ def pod_placeholders(home=None) -> set[str]:
71
  AREA_TAGS = {"AP": "payables", "AR": "receivables", "GL": "general-ledger", "PO": "purchasing", "EXP": "expenses"}
72
  NUMBER_RE = re.compile(r"[$€£]?\d[\d,.]*\d|\d") # any figure in public notes: an amount or id to the leak check
73
  PH_RE = re.compile(r"\{\{\s*([^{}]*?)\s*\}\}")
 
74
  SINGLE_BRACE_RE = re.compile(r"(?<!\{)\{\s*(?:pod\.|today|unique:|tv\.|saved\.)[^{}]*\}(?!\})")
75
 
76
 
@@ -284,6 +285,9 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
284
  if a == "save" and sc.has_number and not number_entered:
285
  problems.append(f"step {i}: save comes before Number is entered with {{{{unique:TAG}}}}; the runner needs it to cancel "
286
  "the test document afterwards")
 
 
 
287
  if a == "enter" and s.field and s.value:
288
  for m in PH_RE.finditer(s.value):
289
  want = PLACEHOLDER_FIELDS.get(m.group(1))
 
71
  AREA_TAGS = {"AP": "payables", "AR": "receivables", "GL": "general-ledger", "PO": "purchasing", "EXP": "expenses"}
72
  NUMBER_RE = re.compile(r"[$€£]?\d[\d,.]*\d|\d") # any figure in public notes: an amount or id to the leak check
73
  PH_RE = re.compile(r"\{\{\s*([^{}]*?)\s*\}\}")
74
+ MASK_RE = re.compile(r"<(?:EMAIL|AMOUNT|ID|NAME|SECRET)_\d+>") # the leak mask's placeholders (platform/redaction.py)
75
  SINGLE_BRACE_RE = re.compile(r"(?<!\{)\{\s*(?:pod\.|today|unique:|tv\.|saved\.)[^{}]*\}(?!\})")
76
 
77
 
 
285
  if a == "save" and sc.has_number and not number_entered:
286
  problems.append(f"step {i}: save comes before Number is entered with {{{{unique:TAG}}}}; the runner needs it to cancel "
287
  "the test document afterwards")
288
+ masked = next((m.group(0) for x in (s.value, s.expected) if x for m in [MASK_RE.search(str(x))] if m), None)
289
+ if masked: # a placeholder of the leak mask that was not restored would be typed into Fusion as it is
290
+ problems.append(f"step {i}: '{masked}' is a masked value, not test data: use a placeholder from the list or a plain value")
291
  if a == "enter" and s.field and s.value:
292
  for m in PH_RE.finditer(s.value):
293
  want = PLACEHOLDER_FIELDS.get(m.group(1))
coworker/tests/test_agent_studio.py CHANGED
@@ -1,12 +1,17 @@
1
  """Oracle AI Agent Studio drives a test cycle (docs/AGENT_STUDIO.md): an OAuth client gets an invoke-only token; the
2
  approved synthetic test data starts a run; scripts_ready goes back; the start-testing decision made in Fusion resumes
3
- the run; results go back; the cycle's test data is tried first by the runner; personal data is refused."""
 
 
4
  from __future__ import annotations
5
 
6
  import json
 
7
  import unittest
 
8
 
9
- from coworker.platform.agent_studio import AgentStudio, Courier, validate_test_data, verify_signature, AgentStudioError
 
10
  from coworker.tests.test_ai_scenarios import fusion_app
11
 
12
  TD = {"AP": {"business_unit": "TEST_US_BU", "supplier": ["Test Supplier A", "Test Supplier B"], "currency": "USD"}}
@@ -71,7 +76,7 @@ class TestAgentStudio(unittest.TestCase):
71
  courier = Courier(self.svc, self.app.state.runs, watch_hours=0)
72
  courier.studio.watch_runs(self.app.state.runs)
73
  sent = studio.deliveries()
74
- ready = next(d for d in sent if d["event"] == "scripts_ready")
75
  self.assertEqual(ready["payload"]["cycle_id"], cyc["cycle_id"])
76
  self.assertTrue(any(sc["steps"] and {"n", "action", "expected"} <= set(sc["steps"][0]) for sc in ready["payload"]["scenarios"]))
77
  # the Excel opens from the e-mail without a login: this run only, and not once the link is changed
@@ -91,7 +96,7 @@ class TestAgentStudio(unittest.TestCase):
91
  "approval in Oracle Fusion (start testing)")
92
  # the same step is reported once
93
  courier.studio.watch_runs(self.app.state.runs)
94
- self.assertEqual(sum(1 for d in studio.deliveries() if d["event"] == "scripts_ready"), 1)
95
  # a signed body: what the Fusion side checks
96
  key = self.client["signing_key"]
97
  body = json.dumps(ready["payload"]).encode()
@@ -99,19 +104,21 @@ class TestAgentStudio(unittest.TestCase):
99
  self.assertTrue(verify_signature(key, body, "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest()))
100
  self.assertFalse(verify_signature(key, body, "sha256=00"))
101
 
102
- # the start-testing decision, made in Fusion
103
- r = self.c.post(f"/api/agent-studio/v1/cycles/{cyc['cycle_id']}/approval", json={"decision": "approve", "approved_by": "Priya (Fusion QA)"}, headers=h)
 
 
104
  self.assertEqual(r.status_code, 200, r.text)
105
  self.assertEqual(r.json()["scripts_approved_by"], "Priya (Fusion QA)")
106
  self.app.state.runs.drain()
107
  run = self.svc.db.get_run(cyc["run_id"])
108
  if run["status"] == "waiting_review": # failures wait for a person in Patchwise; the cycle says so
109
  courier.studio.watch_runs(self.app.state.runs)
110
- self.assertTrue(any(d["event"] == "failures_need_review" for d in studio.deliveries()))
111
  else:
112
  self.assertEqual(run["status"], "completed")
113
  courier.studio.watch_runs(self.app.state.runs)
114
- res = next(d for d in studio.deliveries() if d["event"] == "results")
115
  self.assertIn(res["payload"]["verdict"], ("Ready", "Not ready"))
116
  sc = res["payload"]["scenarios"] # each scenario's outcome, for the results e-mail
117
  self.assertTrue(sc and all(s["outcome"] in ("passed", "failed", "flaky", "skipped") for s in sc), sc)
@@ -144,6 +151,211 @@ class TestAgentStudio(unittest.TestCase):
144
  self.assertFalse(links.verify(self.svc, "r1", "report.pdf", int(q["exp"]), q["sig"], now=2000))
145
  self.assertFalse(links.verify(self.svc, "r1", "test-script.xlsx", int(q["exp"]) + 86400, q["sig"], now=2000))
146
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
147
  def test_a_callback_that_fails_is_tried_again_later(self):
148
  studio = AgentStudio(self.svc)
149
  did = studio.queue(self.client["client_id"], "https://fusion.example/cb", "stopped", {"status": "failed"})
 
1
  """Oracle AI Agent Studio drives a test cycle (docs/AGENT_STUDIO.md): an OAuth client gets an invoke-only token; the
2
  approved synthetic test data starts a run; scripts_ready goes back; the start-testing decision made in Fusion resumes
3
+ the run; results go back; the cycle's test data is tried first by the runner; personal data is refused.
4
+ The contract is safe to repeat: a retried start returns its cycle, events keep their delivery id, an interrupted run
5
+ is paused (not stopped), events that run out of tries are dead letters, and tokens are signed (no row needed)."""
6
  from __future__ import annotations
7
 
8
  import json
9
+ import secrets
10
  import unittest
11
+ from unittest import mock
12
 
13
+ from coworker.platform.agent_studio import (AgentStudio, Courier, validate_test_data, verify_signature, AgentStudioError, MAX_ATTEMPTS,
14
+ MAX_PICKUPS, delivery_id_for, sign_token, _hash)
15
  from coworker.tests.test_ai_scenarios import fusion_app
16
 
17
  TD = {"AP": {"business_unit": "TEST_US_BU", "supplier": ["Test Supplier A", "Test Supplier B"], "currency": "USD"}}
 
76
  courier = Courier(self.svc, self.app.state.runs, watch_hours=0)
77
  courier.studio.watch_runs(self.app.state.runs)
78
  sent = studio.deliveries()
79
+ ready = next(d for d in sent if d["event"] == "scripts_ready" and d["cycle_id"] == cyc["cycle_id"])
80
  self.assertEqual(ready["payload"]["cycle_id"], cyc["cycle_id"])
81
  self.assertTrue(any(sc["steps"] and {"n", "action", "expected"} <= set(sc["steps"][0]) for sc in ready["payload"]["scenarios"]))
82
  # the Excel opens from the e-mail without a login: this run only, and not once the link is changed
 
96
  "approval in Oracle Fusion (start testing)")
97
  # the same step is reported once
98
  courier.studio.watch_runs(self.app.state.runs)
99
+ self.assertEqual(sum(1 for d in studio.deliveries() if d["event"] == "scripts_ready" and d["cycle_id"] == cyc["cycle_id"]), 1)
100
  # a signed body: what the Fusion side checks
101
  key = self.client["signing_key"]
102
  body = json.dumps(ready["payload"]).encode()
 
104
  self.assertTrue(verify_signature(key, body, "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest()))
105
  self.assertFalse(verify_signature(key, body, "sha256=00"))
106
 
107
+ # the start-testing decision, made in Fusion (and saved at once: a restart must not lose it)
108
+ with mock.patch("coworker.platform.statesync.save_soon") as save:
109
+ r = self.c.post(f"/api/agent-studio/v1/cycles/{cyc['cycle_id']}/approval", json={"decision": "approve", "approved_by": "Priya (Fusion QA)"}, headers=h)
110
+ self.assertIn("agent studio approve", [c.args[0] for c in save.call_args_list])
111
  self.assertEqual(r.status_code, 200, r.text)
112
  self.assertEqual(r.json()["scripts_approved_by"], "Priya (Fusion QA)")
113
  self.app.state.runs.drain()
114
  run = self.svc.db.get_run(cyc["run_id"])
115
  if run["status"] == "waiting_review": # failures wait for a person in Patchwise; the cycle says so
116
  courier.studio.watch_runs(self.app.state.runs)
117
+ self.assertTrue(any(d["event"] == "failures_need_review" and d["cycle_id"] == cyc["cycle_id"] for d in studio.deliveries()))
118
  else:
119
  self.assertEqual(run["status"], "completed")
120
  courier.studio.watch_runs(self.app.state.runs)
121
+ res = next(d for d in studio.deliveries() if d["event"] == "results" and d["cycle_id"] == cyc["cycle_id"])
122
  self.assertIn(res["payload"]["verdict"], ("Ready", "Not ready"))
123
  sc = res["payload"]["scenarios"] # each scenario's outcome, for the results e-mail
124
  self.assertTrue(sc and all(s["outcome"] in ("passed", "failed", "flaky", "skipped") for s in sc), sc)
 
151
  self.assertFalse(links.verify(self.svc, "r1", "report.pdf", int(q["exp"]), q["sig"], now=2000))
152
  self.assertFalse(links.verify(self.svc, "r1", "test-script.xlsx", int(q["exp"]) + 86400, q["sig"], now=2000))
153
 
154
+ # ------------------------------------------------------------ the contract, safe to repeat
155
+ def _new_client(self, name: str) -> dict:
156
+ r = self.c.post("/api/agent-studio/clients", json={"name": name, "callback_url": "https://fusion.example/cb"}, headers=self.h["admin"])
157
+ self.assertEqual(r.status_code, 201, r.text)
158
+ return r.json()
159
+
160
+ def _row(self, client_id: str) -> dict:
161
+ return AgentStudio(self.svc).client_for_token(sign_token(self.svc, client_id))
162
+
163
+ def _fake_cycle(self, client_id: str, status: str) -> tuple[str, str]:
164
+ """A cycle whose run is a bare row the test moves from status to status (no graph behind it)."""
165
+ rid, cid = "t-" + secrets.token_hex(4), "cyc_" + secrets.token_hex(6)
166
+ self.svc.db.create_run({"run_id": rid, "created_by": "test", "trigger": "agent_studio", "modules": ["AP"], "include_p2": 0,
167
+ "playwright_mode": "stub", "inputs": {}, "status": status, "orchestrator": "langgraph", "pod_id": self.pod_id})
168
+ self.svc.db.insert("agent_cycles", {"cycle_id": cid, "run_id": rid, "client_id": client_id, "test_data": "{}",
169
+ "data_approved_by": "X", "callback_url": "https://fusion.example/cb", "last_status": status,
170
+ "created_at": "2026-01-01T00:00:00+00:00", "updated_at": "2026-01-01T00:00:00+00:00"})
171
+ return cid, rid
172
+
173
+ def test_a_retried_start_returns_the_cycle_it_made(self):
174
+ h = {"Authorization": f"Bearer {self.token()}"}
175
+ body = {"test_data": TD, "data_approved_by": "Priya (Fusion QA)", "areas": ["AP"], "correlation_id": "wf-retry-1"}
176
+ runs = self.app.state.runs
177
+ made = []
178
+ try:
179
+ first = self.c.post("/api/agent-studio/v1/cycles", json=body, headers=h)
180
+ self.assertEqual(first.status_code, 202, first.text)
181
+ made.append(first.json()["run_id"])
182
+ again = self.c.post("/api/agent-studio/v1/cycles", json=body, headers=h) # Fusion retried: no second run
183
+ self.assertEqual(again.status_code, 202, again.text)
184
+ self.assertEqual(again.headers.get("idempotent-replayed"), "true")
185
+ self.assertIsNone(first.headers.get("idempotent-replayed"))
186
+ self.assertEqual(set(again.json()), set(first.json())) # the same shape
187
+ self.assertEqual((again.json()["cycle_id"], again.json()["run_id"]), (first.json()["cycle_id"], first.json()["run_id"]))
188
+ self.assertEqual(self.svc.db.one("SELECT COUNT(*) AS n FROM agent_cycles WHERE correlation_id='wf-retry-1'")["n"], 1)
189
+ runs.cancel(first.json()["run_id"], "test", "done")
190
+ # once that cycle is over, the same correlation_id starts a new one (a later week's workflow)
191
+ later = self.c.post("/api/agent-studio/v1/cycles", json=body, headers=h)
192
+ self.assertEqual(later.status_code, 202, later.text)
193
+ made.append(later.json()["run_id"])
194
+ self.assertNotEqual(later.json()["cycle_id"], first.json()["cycle_id"])
195
+ runs.cancel(later.json()["run_id"], "test", "done")
196
+ # an Idempotency-Key replays whatever became of its cycle
197
+ k = {**h, "Idempotency-Key": "fusion-req-77"}
198
+ nocorr = {x: v for x, v in body.items() if x != "correlation_id"}
199
+ one = self.c.post("/api/agent-studio/v1/cycles", json=nocorr, headers=k)
200
+ self.assertEqual(one.status_code, 202, one.text)
201
+ made.append(one.json()["run_id"])
202
+ runs.cancel(one.json()["run_id"], "test", "done")
203
+ two = self.c.post("/api/agent-studio/v1/cycles", json=nocorr, headers=k)
204
+ self.assertEqual((two.status_code, two.json()["cycle_id"], two.headers.get("idempotent-replayed")), (202, one.json()["cycle_id"], "true"))
205
+ finally:
206
+ for rid in made:
207
+ if (self.svc.db.get_run(rid) or {}).get("status") not in ("cancelled", "completed", "failed"):
208
+ runs.cancel(rid, "test", "done")
209
+
210
+ def test_a_cycle_row_is_written_before_its_run_and_saved_at_once(self):
211
+ studio = AgentStudio(self.svc)
212
+ client = self._row(self.client["client_id"])
213
+ seen = {}
214
+
215
+ class Runs:
216
+ def start(_, inputs, actor, trigger="manual", run_id=None):
217
+ seen["cycle"] = studio.cycle_for_run(run_id) # what the runner reads for the test data
218
+ seen["test_data"] = studio.test_data_for_run(run_id)
219
+ return run_id
220
+
221
+ with mock.patch("coworker.platform.statesync.save_soon") as save:
222
+ cyc = studio.start_cycle(client, {"test_data": TD, "data_approved_by": "X", "areas": ["AP"]}, Runs())
223
+ self.assertEqual(seen["cycle"]["cycle_id"], cyc["cycle_id"])
224
+ self.assertEqual(seen["test_data"]["AP"]["supplier"][0], "Test Supplier A")
225
+ self.assertIn("agent studio cycle started", [c.args[0] for c in save.call_args_list])
226
+ from coworker.api.runner import RunError
227
+
228
+ class Refuses:
229
+ def start(_, inputs, actor, trigger="manual", run_id=None):
230
+ seen["refused"] = run_id
231
+ raise RunError("the pod check failed", "POD_CHECK_FAILED", 409)
232
+
233
+ with self.assertRaises(AgentStudioError) as e:
234
+ studio.start_cycle(client, {"test_data": TD, "data_approved_by": "X", "areas": ["AP"], "correlation_id": "wf-refused"}, Refuses())
235
+ self.assertEqual((e.exception.code, e.exception.status), ("POD_CHECK_FAILED", 409))
236
+ self.assertIsNone(studio.cycle_for_run(seen["refused"])) # no cycle is left without its run
237
+
238
+ def test_an_event_keeps_its_delivery_id(self):
239
+ studio = AgentStudio(self.svc)
240
+ cid = "cyc_" + secrets.token_hex(6)
241
+ first = studio.queue(self.client["client_id"], "https://fusion.example/cb", "scripts_ready", {"n": 1}, cid)
242
+ self.assertEqual(first, delivery_id_for(cid, "scripts_ready", 0))
243
+ # a restart restored a snapshot taken before the event: the same step makes the same event, with the same id
244
+ self.svc.db.x("DELETE FROM agent_callbacks WHERE delivery_id=?", (first,))
245
+ self.assertEqual(studio.queue(self.client["client_id"], "https://fusion.example/cb", "scripts_ready", {"n": 1}, cid), first)
246
+ # a later step of the same kind (the run resumed and asks again) is a new event
247
+ second = studio.queue(self.client["client_id"], "https://fusion.example/cb", "scripts_ready", {"n": 2}, cid)
248
+ self.assertNotEqual(second, first)
249
+ self.assertEqual(studio.delivery(second)["payload"]["delivery_id"], second)
250
+
251
+ def test_an_interrupted_run_is_paused_and_the_cycle_reports_again_after_a_resume(self):
252
+ studio = AgentStudio(self.svc)
253
+
254
+ class Runs:
255
+ def state(_, run_id):
256
+ return {}
257
+
258
+ def gate_payload(_, run_id):
259
+ return {"pending": []}
260
+
261
+ cid, rid = self._fake_cycle(self.client["client_id"], "running")
262
+
263
+ def evs():
264
+ return [d for d in studio.deliveries(500) if d["cycle_id"] == cid][::-1]
265
+
266
+ self.svc.db.update_run(rid, status="interrupted") # recover() after a restart
267
+ studio.watch_runs(Runs())
268
+ self.assertEqual([d["event"] for d in evs()], ["paused"])
269
+ p = evs()[0]["payload"]
270
+ self.assertEqual((p["status"], p["resumable"]), ("interrupted", True))
271
+ self.assertTrue(p["reason"])
272
+ self.svc.db.update_run(rid, status="queued") # resume()
273
+ studio.watch_runs(Runs())
274
+ self.svc.db.update_run(rid, status="failed", error="the browser stopped")
275
+ studio.watch_runs(Runs())
276
+ self.assertEqual([d["event"] for d in evs()], ["paused", "stopped"])
277
+ self.assertEqual(evs()[1]["payload"]["resumable"], True)
278
+ self.assertEqual(evs()[0]["state"], "superseded") # the paused event never arrives after the newer one
279
+ self.svc.db.update_run(rid, status="running", error=None) # a failed run resumed: the cycle is still watched
280
+ studio.watch_runs(Runs())
281
+ self.svc.db.update_run(rid, status="completed")
282
+ studio.watch_runs(Runs())
283
+ self.assertEqual([d["event"] for d in evs()], ["paused", "stopped", "results"])
284
+ studio.watch_runs(Runs())
285
+ self.assertEqual(len(evs()), 3)
286
+
287
+ def test_an_event_that_runs_out_of_tries_is_a_dead_letter_an_admin_sends_again(self):
288
+ studio = AgentStudio(self.svc)
289
+ did = studio.queue(self.client["client_id"], "https://fusion.example/cb", "results", {"verdict": "Ready"}, "cyc_" + secrets.token_hex(6))
290
+ self.svc.db.x("UPDATE agent_callbacks SET attempts=?, next_at='2000-01-01T00:00:00+00:00' WHERE delivery_id=?", (MAX_ATTEMPTS - 1, did))
291
+ studio.deliver_due()
292
+ d = studio.delivery(did)
293
+ self.assertEqual((d["state"], d["attempts"]), ("dead", MAX_ATTEMPTS))
294
+ self.assertTrue(d["dead_at"] and d["error"])
295
+ self.assertTrue(self.svc.db.one("SELECT 1 AS x FROM audit_log WHERE kind='agent_studio.dead_letter' AND summary LIKE ?", (f"{did}%",)))
296
+ self.assertTrue(self.svc.db.one("SELECT 1 AS x FROM notify_events WHERE kind='agent_studio.dead_letter'"))
297
+ studio.deliver_due() # a dead letter is not sent again by itself
298
+ self.assertEqual(studio.delivery(did)["attempts"], MAX_ATTEMPTS)
299
+ listed = self.c.get("/api/agent-studio/deliveries?state=dead", headers=self.h["admin"]).json()
300
+ self.assertIn(did, [x["delivery_id"] for x in listed["items"]])
301
+ self.assertGreaterEqual(listed["dead_letters"], 1)
302
+ self.assertEqual(self.c.get("/api/agent-studio/deliveries", headers=self.h["viewer"]).status_code, 403)
303
+ r = self.c.post(f"/api/agent-studio/deliveries/{did}/requeue", headers=self.h["admin"])
304
+ self.assertEqual(r.status_code, 200, r.text)
305
+ self.assertEqual((r.json()["state"], r.json()["attempts"], r.json()["delivery_id"]), ("queued", 0, did))
306
+ self.assertEqual(self.c.post("/api/agent-studio/deliveries/dlv_none/requeue", headers=self.h["admin"]).status_code, 404)
307
+ self.assertEqual(self.c.post(f"/api/agent-studio/deliveries/{did}/requeue", headers=self.h["consultant"]).status_code, 403)
308
+
309
+ # pull: 20 pickups without a confirmation; a confirmation that comes late still counts
310
+ pull = self._new_client("Fusion pull pod")
311
+ self.c.put(f"/api/agent-studio/clients/{pull['client_id']}/delivery", json={"mode": "pull"}, headers=self.h["admin"])
312
+ pid = studio.queue(pull["client_id"], None, "scripts_ready", {"count": 0}, "cyc_" + secrets.token_hex(6))
313
+ self.svc.db.x("UPDATE agent_callbacks SET attempts=?, next_at='2000-01-01T00:00:00+00:00' WHERE delivery_id=?", (MAX_PICKUPS, pid))
314
+ self.assertIn(pid, studio.bury_dead())
315
+ self.assertEqual(studio.claim(pull["client_id"])["count"], 0)
316
+ self.assertEqual(studio.ack(pull["client_id"], [pid])["confirmed"], [pid])
317
+ self.assertEqual(studio.delivery(pid)["state"], "delivered")
318
+
319
+ def test_a_callback_is_never_signed_with_an_empty_key(self):
320
+ studio = AgentStudio(self.svc)
321
+ cl = self._new_client("Fusion pod without a key")
322
+ self.svc.vault.set(f"agent_studio.{cl['client_id']}.signing", "")
323
+ did = studio.queue(cl["client_id"], "https://fusion.example/cb", "results", {"verdict": "Ready"}, "cyc_" + secrets.token_hex(6))
324
+ with mock.patch.object(self.svc.egress, "service_request", wraps=self.svc.egress.service_request) as sent:
325
+ studio.deliver_due()
326
+ self.assertFalse([c for c in sent.call_args_list if (c.kwargs.get("headers") or {}).get("X-Patchwise-Delivery") == did])
327
+ d = studio.delivery(did)
328
+ self.assertIn("no signing key", d["error"])
329
+ self.assertIsNone(d["delivered_at"])
330
+ self.assertIsNone(d["status_code"])
331
+
332
+ def test_a_token_is_signed_and_needs_no_row(self):
333
+ cl = self._new_client("Fusion pod, tokens")
334
+ r = self.c.post("/oauth/token", data={"grant_type": "client_credentials", "client_id": cl["client_id"], "client_secret": cl["client_secret"]})
335
+ tok = r.json()["access_token"]
336
+ self.assertTrue(tok.startswith("pwa_"))
337
+ self.svc.db.x("DELETE FROM agent_tokens") # a restart restored a snapshot older than the token
338
+
339
+ def status(t):
340
+ return self.c.get("/api/agent-studio/v1/cycles/cyc_none", headers={"Authorization": f"Bearer {t}"}).status_code
341
+
342
+ self.assertEqual(status(tok), 404) # accepted (the cycle does not exist)
343
+ self.assertEqual(status(tok[:-3] + ("AAA" if not tok.endswith("AAA") else "BBB")), 401) # forged
344
+ self.assertEqual(status(tok.replace(cl["client_id"], self.client["client_id"])), 401) # another client's id
345
+ self.assertEqual(status(sign_token(self.svc, cl["client_id"], now=1000)), 401) # expired
346
+ # a token issued before tokens were signed keeps working until it expires
347
+ legacy = "pwa_" + secrets.token_urlsafe(32)
348
+ self.svc.db.insert("agent_tokens", {"token_hash": _hash(legacy), "client_id": cl["client_id"], "scope": "patchwise.invoke",
349
+ "created_at": "2026-01-01T00:00:00+00:00", "expires_at": "2999-01-01T00:00:00+00:00"})
350
+ self.assertEqual(status(legacy), 404)
351
+ old = "pwa_" + secrets.token_urlsafe(32)
352
+ self.svc.db.insert("agent_tokens", {"token_hash": _hash(old), "client_id": cl["client_id"], "scope": "patchwise.invoke",
353
+ "created_at": "2000-01-01T00:00:00+00:00", "expires_at": "2000-01-01T01:00:00+00:00"})
354
+ self.assertEqual(status(old), 401)
355
+ # revoking the client ends its signed tokens at once
356
+ self.assertEqual(self.c.delete(f"/api/agent-studio/clients/{cl['client_id']}", headers=self.h["admin"]).status_code, 204)
357
+ self.assertEqual((status(tok), status(legacy)), (401, 401))
358
+
359
  def test_a_callback_that_fails_is_tried_again_later(self):
360
  studio = AgentStudio(self.svc)
361
  did = studio.queue(self.client["client_id"], "https://fusion.example/cb", "stopped", {"status": "failed"})
coworker/tests/test_area_user_passes.py CHANGED
@@ -49,7 +49,11 @@ class TestAreaUserPasses(unittest.TestCase):
49
  "config": "playwright.fusion.config.ts", "cred_env": {},
50
  "groups": execute.user_groups(Reg(), 1, "r", list(mods), mods, {})}
51
  events = []
52
- svc = SimpleNamespace(cfg=SimpleNamespace(remote_runner_url="", executor_backend="local"),
 
 
 
 
53
  db=SimpleNamespace(add_event=lambda *a: events.append(a[3])))
54
  with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run):
55
  res = execute.run_planned(plan, svc)
 
49
  "config": "playwright.fusion.config.ts", "cred_env": {},
50
  "groups": execute.user_groups(Reg(), 1, "r", list(mods), mods, {})}
51
  events = []
52
+ from coworker.config import Settings
53
+ knobs = {k: getattr(Settings.model_construct(), k) for k in (
54
+ "fusion_chunk_scenarios", "fusion_workers", "fusion_scenario_minutes", "fusion_attempt_min_minutes",
55
+ "fusion_attempt_max_minutes")}
56
+ svc = SimpleNamespace(cfg=SimpleNamespace(remote_runner_url="", executor_backend="local", **knobs),
57
  db=SimpleNamespace(add_event=lambda *a: events.append(a[3])))
58
  with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run):
59
  res = execute.run_planned(plan, svc)
coworker/tests/test_preflight.py CHANGED
@@ -54,11 +54,17 @@ class TestPreflight(unittest.TestCase):
54
  (svc_with(OSError("refused")), reg_with(), "does not answer"),
55
  (svc_with({"ok": False, "automation": True}), reg_with(), "not ready"),
56
  (svc_with(None), reg_with(sign_in_ok=False), "HTTP 401"),
57
- (svc_with(None), reg_with(cands={}), "No test data for AP"),
58
  ]
59
  for svc, reg, needle in cases:
60
  self.assertTrue(any(needle in p for p in preflight.problems(self.run_check(svc, reg))), needle)
61
 
 
 
 
 
 
 
 
62
  def test_a_run_that_cannot_work_stops_before_any_browser(self):
63
  svc = mock.MagicMock()
64
  svc.fusion_pod_id.return_value = 2
 
54
  (svc_with(OSError("refused")), reg_with(), "does not answer"),
55
  (svc_with({"ok": False, "automation": True}), reg_with(), "not ready"),
56
  (svc_with(None), reg_with(sign_in_ok=False), "HTTP 401"),
 
57
  ]
58
  for svc, reg, needle in cases:
59
  self.assertTrue(any(needle in p for p in preflight.problems(self.run_check(svc, reg))), needle)
60
 
61
+ def test_missing_test_data_is_a_warning_not_a_stop(self):
62
+ res = self.run_check(svc_with(None), reg_with(cands={}))
63
+ self.assertEqual(preflight.problems(res), [])
64
+ td = next(r for r in res if r["name"] == "test_data")
65
+ self.assertTrue(td["warning"])
66
+ self.assertIn("No test data for AP", td["detail"])
67
+
68
  def test_a_run_that_cannot_work_stops_before_any_browser(self):
69
  svc = mock.MagicMock()
70
  svc.fusion_pod_id.return_value = 2
coworker/tests/test_regression_checks.py ADDED
@@ -0,0 +1,155 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Regression (depth full): each area's standard regression and edge-case checks (fusion_catalog "regression") are asked
2
+ of the AI model, one scenario per check, in batches; checks a library scenario already covers are skipped, the number is
3
+ capped by FPT_FUSION_REGRESSION_CHECKS (0 = off), and every catalog area with screens has such a list."""
4
+ from __future__ import annotations
5
+
6
+ import unittest
7
+ from types import SimpleNamespace
8
+ from unittest import mock
9
+
10
+ from coworker.config import Settings
11
+ from coworker.graph.nodes import ai_scenarios
12
+ from coworker.llm.base import Route
13
+ from coworker.platform import fusion_catalog
14
+
15
+ SCREENS = [{"task": "Payables > Invoices > Create Invoice"}, {"task": "Payables > Invoices > Manage Invoices"}]
16
+ FR = Route.FRONTIER.value
17
+ WORDS = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet", "kilo", "lima"]
18
+ CHECKS = [{"process": "Invoice entry", "check": f"Entry check {w}"} for w in WORDS] \
19
+ + [{"process": "Payments", "check": f"Payment check {w}"} for w in WORDS[:6]]
20
+
21
+
22
+ def svc(checks=25):
23
+ return SimpleNamespace(cfg=SimpleNamespace(fusion_regression_checks=checks))
24
+
25
+
26
+ def answer(*args, **kw):
27
+ """The fake model: one scenario per regression check asked, titled with the check's words."""
28
+ return [{"title": a.split("regression check: ", 1)[1].split(" (one scenario", 1)[0], "task": SCREENS[0]["task"],
29
+ "designed_by": FR} for a in args[2]]
30
+
31
+
32
+ class TestRegressionChecks(unittest.TestCase):
33
+ def run_checks(self, checks=CHECKS, cap=25, titles=(), side_effect=answer):
34
+ notes, written = [], []
35
+ design = mock.Mock(side_effect=side_effect)
36
+ with mock.patch.object(ai_scenarios.step_writer, "design_scenarios", design), \
37
+ mock.patch.object(ai_scenarios, "_write_intents", lambda *a, **k: written.extend(a[3])), \
38
+ mock.patch.object(ai_scenarios, "_note", lambda s, rid, text, **k: notes.append(text)):
39
+ ai_scenarios._design_regression_checks(svc(cap), "r", "AP", list(checks), SCREENS, list(titles), "", set(), [], [])
40
+ return design, written, notes
41
+
42
+ def test_every_check_is_asked_in_batches(self):
43
+ design, written, notes = self.run_checks()
44
+ self.assertEqual(design.call_count, 3) # 18 checks, at most 8 per call
45
+ self.assertEqual([len(c.args[2]) for c in design.call_args_list], [8, 8, 2])
46
+ self.assertEqual(design.call_args_list[0].kwargs["count"], 8)
47
+ self.assertTrue(design.call_args_list[0].args[2][0].startswith("Invoice entry: regression check: Entry check alpha"))
48
+ self.assertTrue(design.call_args_list[0].args[2][1].startswith("Payments: regression check: Payment check alpha")) # processes in turn
49
+ self.assertEqual(design.call_args_list[0].args[3], []) # the checks themselves, not the release's changes
50
+ self.assertEqual(len(written), 18)
51
+ later = design.call_args_list[1].kwargs["existing_titles"]
52
+ self.assertEqual(len(later), 8) # what was designed is not asked again
53
+ self.assertIn("AP: 18 regression check(s) designed: ", notes[-1])
54
+
55
+ def test_checks_the_library_covers_are_skipped(self):
56
+ design, written, _ = self.run_checks(titles=["Entry check delta", "payment check: foxtrot."])
57
+ asked = [a for c in design.call_args_list for a in c.args[2]]
58
+ self.assertEqual(len(asked), 16)
59
+ self.assertFalse(any("Entry check delta " in a or "Payment check foxtrot " in a for a in asked))
60
+ self.assertEqual(design.call_args_list[0].kwargs["existing_titles"], ["Entry check delta", "payment check: foxtrot."])
61
+
62
+ def test_the_cap_is_respected(self):
63
+ design, written, _ = self.run_checks(cap=5)
64
+ self.assertEqual(design.call_count, 1)
65
+ self.assertEqual(len(design.call_args.args[2]), 5)
66
+ self.assertEqual(len(written), 5)
67
+
68
+ def test_zero_turns_it_off(self):
69
+ design, written, notes = self.run_checks(cap=0)
70
+ design.assert_not_called()
71
+ self.assertEqual((written, notes), ([], []))
72
+ self.assertEqual(Settings().fusion_regression_checks, 25)
73
+
74
+ def test_only_model_answers_are_kept_and_a_failure_is_a_note(self):
75
+ _, written, notes = self.run_checks(side_effect=lambda *a, **k: [{"title": "Fallback", "task": SCREENS[0]["task"], "designed_by": "baseline"}])
76
+ self.assertEqual(written, [])
77
+ self.assertIn("no regression check was designed", notes[-1])
78
+ design, written, notes = self.run_checks(side_effect=RuntimeError("down"))
79
+ self.assertEqual(design.call_count, 1) # stops at the first failure
80
+ self.assertIn("could not design regression checks", notes[-1])
81
+
82
+ def test_asked_only_at_depth_full(self):
83
+ """Through write_ai_scenarios: the catalog's checks are asked in a full run only."""
84
+ def run(depth):
85
+ asks = []
86
+
87
+ def design(s, area, processes, *a, **k):
88
+ asks.extend(processes)
89
+ return [{"title": "First", "task": SCREENS[0]["task"], "designed_by": FR}]
90
+ reg = mock.Mock()
91
+ reg.area_screens.return_value = list(SCREENS)
92
+ reg.test_data_keys.return_value = []
93
+ cfg = SimpleNamespace(fusion_ai_scenarios=4, fusion_ai_scenarios_max=8, fusion_regression_flows=0,
94
+ fusion_regression_checks=25, fusion_workers=1, fusion_ai_dry_run=False, home=None)
95
+ s = SimpleNamespace(cfg=cfg, db=None, vault=None, egress=None, audit=None, fusion_pod_id=lambda rid: 1,
96
+ router=SimpleNamespace(frontier_ready=lambda: True))
97
+ state = {"run_id": "r", "depth": depth, "scope": {"modules": ["AP"]}, "playwright_mode": "stub"}
98
+ with mock.patch("coworker.platform.pods.PodRegistry", return_value=reg), \
99
+ mock.patch("coworker.graph.nodes.research.scope_modules", return_value=["AP"]), \
100
+ mock.patch.object(ai_scenarios.step_writer, "design_scenarios", design), \
101
+ mock.patch.object(ai_scenarios.step_writer, "area_changes", return_value=[]), \
102
+ mock.patch.object(ai_scenarios, "_write_intents", lambda *a, **k: None), \
103
+ mock.patch.object(ai_scenarios, "_note", lambda *a, **k: None):
104
+ ai_scenarios.write_ai_scenarios(state, s, [])
105
+ return [a for a in asks if "regression check: " in a]
106
+ self.assertEqual(run("standard"), [])
107
+ self.assertEqual(len(run("full")), 25)
108
+
109
+
110
+ class TestCatalogRegression(unittest.TestCase):
111
+ def test_every_area_with_screens_has_its_regression_checks(self):
112
+ for a in fusion_catalog.AREAS:
113
+ if not a.get("navigator"):
114
+ continue
115
+ checks = a.get("regression") or []
116
+ self.assertGreaterEqual(len(checks), 15, a["code"])
117
+ self.assertLessEqual(len(checks), 30, a["code"])
118
+ for c in checks:
119
+ self.assertIn(c["process"], a["processes"], f"{a['code']}: {c['check']}")
120
+ self.assertTrue(c["check"].strip(), a["code"])
121
+ names = [c["check"].lower() for c in checks]
122
+ self.assertEqual(len(names), len(set(names)), f"{a['code']}: a check is listed twice")
123
+
124
+ def test_an_override_keeps_the_built_in_checks(self):
125
+ import json
126
+ import tempfile
127
+ from pathlib import Path
128
+ home = Path(tempfile.mkdtemp())
129
+ (home / "fusion_areas.json").write_text(json.dumps([{"code": "AP", "name": "Payables (client)", "probes": ["invoices"]}]),
130
+ encoding="utf-8")
131
+ self.assertEqual(fusion_catalog.by_code("AP", home)["regression"], fusion_catalog.by_code("AP")["regression"])
132
+
133
+
134
+ if __name__ == "__main__":
135
+ unittest.main()
136
+
137
+
138
+ class TestScreenFocus(unittest.TestCase):
139
+ """Seen on a live AP run: given every screen read, the model put 8 of its 11 scenarios on Create Positive Pay File.
140
+ The general design now starts from the area's key screens and no screen takes more than PER_SCREEN scenarios."""
141
+
142
+ def test_key_screens_come_first_in_key_order(self):
143
+ screens = [{"task": t} for t in ("Payables > Payments > Create Positive Pay File", "Payables > Manage Invoices",
144
+ "Payables > Create Invoice", "Payables > Payments > Create Payment")]
145
+ got = ai_scenarios.key_screens(screens, ["Create Invoice", "Manage Invoices", "Create Payment", "Manage Payments"])
146
+ self.assertEqual([s["task"] for s in got], ["Payables > Create Invoice", "Payables > Manage Invoices",
147
+ "Payables > Payments > Create Payment"])
148
+ self.assertEqual(ai_scenarios.key_screens(screens, []), [])
149
+
150
+ def test_no_screen_takes_more_than_its_share(self):
151
+ intents = [{"task": "Payables > Payments > Create Positive Pay File", "title": f"p{i}"} for i in range(8)]
152
+ intents += [{"task": "Payables > Create Invoice", "title": "c1"}]
153
+ got = ai_scenarios.spread(intents)
154
+ self.assertEqual(sum(1 for i in got if "Positive Pay" in i["task"]), ai_scenarios.PER_SCREEN)
155
+ self.assertEqual(got[-1]["title"], "c1")
coworker/tests/test_runner_robust.py ADDED
@@ -0,0 +1,542 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """The browser execution path survives long runs, restarts and a busy runner: a pass's time budget grows with its
2
+ scenarios and a big attempt runs in passes, so one pass that overruns loses only its own scenarios; a restarted server
3
+ follows the runner job it had started instead of starting another; a restarted runner fails the pass in seconds; a pass
4
+ that overruns cancels its job; a busy runner is waited for (and given up on after a bounded time); pre-flight names a
5
+ runner on another commit. The runner keeps its jobs' state on disk and stops an overrunning attempt gently."""
6
+ from __future__ import annotations
7
+
8
+ import io
9
+ import json
10
+ import shutil
11
+ import subprocess
12
+ import sys
13
+ import tempfile
14
+ import time as real_time
15
+ import unittest
16
+ import zipfile
17
+ from pathlib import Path
18
+ from types import SimpleNamespace
19
+ from unittest import mock
20
+
21
+ import httpx
22
+
23
+ from coworker.adapters import playwright as pwa
24
+ from coworker.adapters import remote_runner as R
25
+ from coworker.config import Settings
26
+ from coworker.graph.nodes import execute
27
+ from coworker.platform import preflight
28
+ from coworker.platform.failures import ExecutionError
29
+ from coworker.tests.test_remote_runner import load_server
30
+
31
+ OLD_JOB, NEW_JOB = "job_0000000000aa", "job_0000000000bb"
32
+ TOKEN = "tok-" + "x" * 30
33
+
34
+
35
+ def report(*ids: str) -> dict:
36
+ return {"suites": [{"title": f"{i}.spec.ts", "file": f"{i}.spec.ts", "specs": [
37
+ {"title": f"{i} scenario", "file": f"{i}.spec.ts", "tags": [f"@{i}"],
38
+ "tests": [{"status": "expected", "results": [{"status": "passed", "attachments": []}]}]}]} for i in ids], "errors": []}
39
+
40
+
41
+ def bundle(*ids: str, ledger: str = '{"invoice":"TEST_1"}\n', with_report: bool = True) -> bytes:
42
+ buf = io.BytesIO()
43
+ with zipfile.ZipFile(buf, "w") as z:
44
+ if with_report:
45
+ z.writestr("report.json", json.dumps(report(*(ids or ("AP-FUS-001",)))))
46
+ z.writestr("created.jsonl", ledger)
47
+ z.writestr("playwright.log", "[1/1]\n")
48
+ return buf.getvalue()
49
+
50
+
51
+ class Clock:
52
+ """Virtual time for the adapter: a sleep moves the clock instead of waiting."""
53
+
54
+ def __init__(self):
55
+ self.t = 1_000_000.0
56
+
57
+ def time(self):
58
+ return self.t
59
+
60
+ def sleep(self, s):
61
+ self.t += max(float(s), 0.001)
62
+
63
+
64
+ class Runner:
65
+ """A fake runner behind the egress gate. `starts`: HTTP codes of successive job starts (the last repeats); `polls`:
66
+ successive status answers, a dict or an HTTP code (the last repeats)."""
67
+
68
+ def __init__(self, starts=(202,), polls=({"state": "done", "exit_code": 0},), blob: bytes | None = None, new_id=NEW_JOB):
69
+ self.calls: list[tuple[str, str, dict | None]] = []
70
+ self.starts, self.polls, self.blob, self.new_id = list(starts), list(polls), blob or bundle(), new_id
71
+
72
+ @staticmethod
73
+ def _next(seq):
74
+ return seq.pop(0) if len(seq) > 1 else seq[0]
75
+
76
+ def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None,
77
+ timeout=30.0, log_url=None):
78
+ assert kind == "remote_runner" and url.startswith(allowed_base)
79
+ path = url[len(allowed_base):]
80
+ self.calls.append((method, path, json_body))
81
+ if method == "POST" and path in ("/v1/attempts", "/v1/screens"):
82
+ code = self._next(self.starts)
83
+ return httpx.Response(code, json={"id": self.new_id, "state": "running"} if code == 202 else {"error": "busy"})
84
+ if path.endswith("/cancel"):
85
+ return httpx.Response(202, json={"state": "cancelling"})
86
+ if path.endswith("/bundle"):
87
+ return httpx.Response(200, content=self.blob)
88
+ if path.endswith("/live"):
89
+ return httpx.Response(200, json={})
90
+ ans = self._next(self.polls)
91
+ if isinstance(ans, int):
92
+ return httpx.Response(ans, json={"error": "no such attempt"})
93
+ return httpx.Response(200, json=ans)
94
+
95
+ def posts(self, suffix="/v1/attempts"):
96
+ return [b for m, p, b in self.calls if m == "POST" and p == suffix]
97
+
98
+ def cancels(self):
99
+ return [p for m, p, _ in self.calls if p.endswith("/cancel")]
100
+
101
+
102
+ def cfg(**over):
103
+ base = {k: getattr(Settings.model_construct(), k) for k in (
104
+ "fusion_chunk_scenarios", "fusion_workers", "fusion_scenario_minutes", "fusion_attempt_min_minutes",
105
+ "fusion_attempt_max_minutes", "remote_runner_busy_wait_minutes")}
106
+ return SimpleNamespace(**{"remote_runner_url": "", "executor_backend": "local", **base, **over})
107
+
108
+
109
+ class Base(unittest.TestCase):
110
+ def setUp(self):
111
+ self.tmp = Path(tempfile.mkdtemp())
112
+ self.clock = Clock()
113
+ p = mock.patch.object(R, "time", self.clock)
114
+ p.start()
115
+ self.addCleanup(p.stop)
116
+ self.addCleanup(shutil.rmtree, self.tmp, True)
117
+
118
+ def tearDown(self):
119
+ for d in (R.AUTOMATION / "results" / "runs").glob("fpt-rr-*"):
120
+ shutil.rmtree(d, ignore_errors=True)
121
+
122
+ def remote(self, eg, *, attempt=0, tag="", timeout_s=1800, **kw):
123
+ return R.run_attempt_remote(eg, "https://runner.example", TOKEN, run_id="rr-1", ids=["AP-FUS-001"], attempt=attempt,
124
+ out_file=self.tmp / "attempt-0.json", cred_env={}, drafts_dir=None, library_dir=None,
125
+ overrides_file=None, log_dir=self.tmp, config="playwright.fusion.config.ts", poll_s=5,
126
+ timeout_s=timeout_s, tag=tag, **kw)
127
+
128
+
129
+ # ---------------------------------------------------------------------------------------------------------------- 1
130
+ class TestTimeBudget(unittest.TestCase):
131
+ def test_the_budget_grows_with_the_scenarios_and_shrinks_with_workers(self):
132
+ c = cfg(fusion_workers=3, fusion_scenario_minutes=12, fusion_attempt_min_minutes=30, fusion_attempt_max_minutes=240)
133
+ self.assertEqual(execute.attempt_timeout_s(c, 1), 30 * 60) # the floor
134
+ self.assertEqual(execute.attempt_timeout_s(c, 12), (10 + 4 * 12) * 60) # 12 scenarios over 3 workers: 4 rounds
135
+ self.assertGreater(execute.attempt_timeout_s(c, 24), execute.attempt_timeout_s(c, 12))
136
+ self.assertEqual(execute.attempt_timeout_s(c, 500), 240 * 60) # the ceiling
137
+ self.assertEqual(execute.attempt_timeout_s(c, 12, workers="1"), (10 + 12 * 12) * 60) # the pass's own workers count
138
+ self.assertEqual(execute.attempt_timeout_s(c, 12, workers="9"), (10 + 3 * 12) * 60) # Playwright runs at most 4
139
+
140
+ def test_a_big_attempt_runs_in_passes_each_with_its_own_budget(self):
141
+ calls = []
142
+
143
+ def fake_run(**kw):
144
+ calls.append((kw["ids"], kw["tag"], kw["timeout_s"], Path(kw["out_file"]).name))
145
+ Path(kw["out_file"]).write_text(json.dumps(report(*kw["ids"])), encoding="utf-8")
146
+ return {"run_dir": f"run{kw['tag']}", "exit_code": 0}
147
+
148
+ with tempfile.TemporaryDirectory() as d:
149
+ ids = [f"AP-FUS-{i:03d}" for i in range(1, 6)]
150
+ plan = plan_for(d, ids)
151
+ svc = SimpleNamespace(cfg=cfg(fusion_chunk_scenarios=2), db=SimpleNamespace(add_event=lambda *a: None))
152
+ with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run):
153
+ res = execute.run_planned(plan, svc)
154
+ self.assertEqual([c[0] for c in calls], [ids[0:2], ids[2:4], ids[4:]])
155
+ self.assertEqual([c[1] for c in calls], ["-c0", "-c1", "-c2"])
156
+ self.assertEqual([c[2] for c in calls], [execute.attempt_timeout_s(svc.cfg, n) for n in (2, 2, 1)])
157
+ merged = json.loads((Path(d) / "attempt-0.json").read_text())
158
+ self.assertEqual(len(merged["suites"]), 5)
159
+ self.assertEqual(res["run_dirs"], ["run-c0", "run-c1", "run-c2"])
160
+
161
+ def test_one_overrunning_pass_loses_only_its_own_scenarios(self):
162
+ def fake_run(**kw):
163
+ if kw["tag"] == "-c1":
164
+ raise ExecutionError("The browser tests did not finish.", timed_out=True, minutes=30)
165
+ Path(kw["out_file"]).write_text(json.dumps(report(*kw["ids"])), encoding="utf-8")
166
+ return {"run_dir": f"run{kw['tag']}", "exit_code": 0}
167
+
168
+ with tempfile.TemporaryDirectory() as d:
169
+ ids = ["AP-FUS-001", "AP-FUS-002", "AP-FUS-003", "AP-FUS-004"]
170
+ svc = SimpleNamespace(cfg=cfg(fusion_chunk_scenarios=2), db=SimpleNamespace(add_event=lambda *a: None))
171
+ with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run):
172
+ res = execute.run_planned(plan_for(d, ids), svc)
173
+ self.assertEqual(res["lost_chunks"], [1])
174
+ outs, counts = execute.outcomes(str(Path(d) / "attempt-0.json"))
175
+ self.assertEqual(outs, {"AP-FUS-001": "passed", "AP-FUS-002": "passed", "AP-FUS-003": "failed", "AP-FUS-004": "failed"})
176
+ self.assertEqual(sorted(execute.failing_ids(str(Path(d) / "attempt-0.json"))), ["AP-FUS-003", "AP-FUS-004"])
177
+ # the retry's results land on the timed-out entries when the attempts are merged
178
+ retry = Path(d) / "attempt-1.json"
179
+ retry.write_text(json.dumps(report("AP-FUS-003", "AP-FUS-004")), encoding="utf-8")
180
+ pwa.adopt_no_result([str(Path(d) / "attempt-0.json"), str(retry)])
181
+ merged = execute.merge_attempts([str(Path(d) / "attempt-0.json"), str(retry)], Path(d) / "merged.json")
182
+ self.assertEqual(execute.outcomes(str(merged))[0]["AP-FUS-003"], "flaky")
183
+ # a resumed attempt reruns only the lost pass
184
+ again = []
185
+ with mock.patch.object(execute.pw, "run_attempt", side_effect=lambda **kw: again.append(kw["tag"]) or fake_run(
186
+ **{**kw, "tag": "-ok"})):
187
+ execute.run_planned(plan_for(d, ids), svc)
188
+ self.assertEqual(again, ["-c1"])
189
+
190
+ def test_when_every_pass_overruns_the_attempt_fails_as_before(self):
191
+ def fake_run(**kw):
192
+ raise ExecutionError("did not finish", timed_out=True, minutes=30)
193
+
194
+ with tempfile.TemporaryDirectory() as d:
195
+ svc = SimpleNamespace(cfg=cfg(fusion_chunk_scenarios=1), db=SimpleNamespace(add_event=lambda *a: None))
196
+ with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run), self.assertRaises(ExecutionError):
197
+ execute.run_planned(plan_for(d, ["AP-FUS-001", "AP-FUS-002"]), svc)
198
+
199
+
200
+ def plan_for(d, ids, **over) -> dict:
201
+ return {"run_id": "rr-1", "attempt": 0, "ids": ids, "mode": "live", "out_file": str(Path(d) / "attempt-0.json"),
202
+ "stub_knobs": None, "drafts_dir": str(d), "library_dir": None, "overrides": None, "run_dir": str(d), "live_dir": None,
203
+ "config": "playwright.fusion.config.ts", "cred_env": {}, "groups": None, **over}
204
+
205
+
206
+ # ---------------------------------------------------------------------------------------------------------------- 2
207
+ class TestReattach(Base):
208
+ def save_old(self, **over):
209
+ R._save_job(self.tmp, {"job_id": OLD_JOB, "base_url": "https://runner.example", "attempt": 0, "tag": "",
210
+ "pw_run_id": "fpt-rr-1-a0", "out_file": str(self.tmp / "attempt-0.json"),
211
+ "started": self.clock.t - 600, "timeout_s": 1800, **over})
212
+
213
+ def test_an_accepted_job_is_kept_in_the_run_folder_until_its_results_are_in(self):
214
+ eg = Runner(polls=[{"state": "running"}, {"state": "done", "exit_code": 0}])
215
+ seen = []
216
+ orig = R._follow
217
+
218
+ def spy(*a, **kw):
219
+ seen.append(R.saved_job(self.tmp))
220
+ return orig(*a, **kw)
221
+
222
+ with mock.patch.object(R, "_follow", side_effect=spy):
223
+ self.remote(eg)
224
+ self.assertEqual((seen[0]["job_id"], seen[0]["pw_run_id"], seen[0]["timeout_s"]), (NEW_JOB, "fpt-rr-1-a0", 1800))
225
+ self.assertIsNone(R.saved_job(self.tmp)) # collected: nothing left to follow
226
+
227
+ def test_a_resumed_run_follows_the_job_it_had_started(self):
228
+ self.save_old()
229
+ eg = Runner(polls=[{"state": "running"}, {"state": "done", "exit_code": 0}])
230
+ events = []
231
+ res = self.remote(eg, on_event=events.append)
232
+ self.assertEqual(eg.posts(), []) # no second job on the runner
233
+ self.assertTrue(any(p == f"/v1/attempts/{OLD_JOB}/bundle" for _, p, _ in eg.calls))
234
+ self.assertEqual(res["pw_run_id"], "fpt-rr-1-a0")
235
+ self.assertTrue((self.tmp / "created-test-data.jsonl").read_text().strip()) # its ledger is fetched for clean-up
236
+ self.assertIsNone(R.saved_job(self.tmp))
237
+ self.assertTrue(any("again" in e for e in events))
238
+
239
+ def test_a_job_the_restarted_runner_does_not_know_is_started_again(self):
240
+ self.save_old()
241
+ eg = Runner(polls=[404, 404, {"state": "done", "exit_code": 0}])
242
+ res = self.remote(eg)
243
+ self.assertEqual(len(eg.posts()), 1)
244
+ self.assertEqual(res["exit_code"], 0)
245
+
246
+ def test_a_lost_job_is_started_again_and_its_ledger_kept(self):
247
+ self.save_old()
248
+ eg = Runner(polls=[{"state": "lost"}, {"state": "done", "exit_code": 0}],
249
+ blob=bundle(ledger='{"invoice":"TEST_LOST"}\n', with_report=False))
250
+ real = eg.service_request
251
+
252
+ def answer(*a, **kw): # the lost job's bundle has only its ledger; the new job's has a report
253
+ r = real(*a, **kw)
254
+ if a[2].endswith("/bundle"):
255
+ eg.blob = bundle(ledger='{"invoice":"TEST_NEW"}\n')
256
+ return r
257
+ eg.service_request = answer
258
+ self.remote(eg)
259
+ self.assertEqual(len(eg.posts()), 1)
260
+ ledger = (self.tmp / "created-test-data.jsonl").read_text()
261
+ self.assertIn("TEST_LOST", ledger)
262
+ self.assertIn("TEST_NEW", ledger)
263
+
264
+ def test_a_saved_job_of_another_pass_is_stopped_so_it_frees_the_runner(self):
265
+ self.save_old(pw_run_id="fpt-rr-1-a0-c3", out_file=str(self.tmp / "attempt-0.c3.json"))
266
+ eg = Runner(polls=[{"state": "cancelled"}, {"state": "done", "exit_code": 0}])
267
+ self.remote(eg)
268
+ self.assertEqual(eg.cancels(), [f"/v1/attempts/{OLD_JOB}/cancel"])
269
+ self.assertEqual(len(eg.posts()), 1)
270
+
271
+ def test_a_resumed_attempt_0_keeps_its_finished_passes(self):
272
+ (self.tmp / "attempt-0.c0.json").write_text("{}")
273
+ (self.tmp / "attempt-0.chunks.json").write_text(json.dumps({"ids": ["A"], "size": 1, "done": {}}))
274
+ self.assertTrue(execute.resumed_attempt(self.tmp))
275
+ state = {"run_id": "rr-1", "test_cases": [], "playwright_mode": "stub"}
276
+ svc = mock.MagicMock()
277
+ svc.run_dir.return_value = self.tmp
278
+ svc.fusion_pod_id.return_value = None
279
+ with mock.patch.object(execute.liveview, "availability", return_value=(False, "")), \
280
+ mock.patch.object(execute.ai_scenarios, "library_root", return_value=self.tmp):
281
+ execute.plan_attempt(state, svc)
282
+ self.assertTrue((self.tmp / "attempt-0.c0.json").exists()) # resumed: kept
283
+ (self.tmp / "attempt-0.chunks.json").unlink()
284
+ self.assertFalse(execute.resumed_attempt(self.tmp))
285
+ execute.plan_attempt(state, svc)
286
+ self.assertFalse((self.tmp / "attempt-0.c0.json").exists()) # a fresh attempt 0 starts clean
287
+ self.save_old()
288
+ self.assertTrue(execute.resumed_attempt(self.tmp)) # a job still followed counts as a resume
289
+
290
+ def test_cancelling_an_orphaned_run_stops_its_job_and_keeps_its_records(self):
291
+ self.save_old()
292
+ eg = Runner(polls=[{"state": "cancelled"}])
293
+ svc = SimpleNamespace(cfg=SimpleNamespace(remote_runner_url="https://runner.example"), egress=eg,
294
+ vault=SimpleNamespace(get=lambda k: TOKEN), run_dir=lambda rid: self.tmp)
295
+ self.assertTrue(R.release_job(svc, "rr-1"))
296
+ self.assertEqual(eg.cancels(), [f"/v1/attempts/{OLD_JOB}/cancel"])
297
+ self.assertIn("TEST_1", (self.tmp / "created-test-data.jsonl").read_text())
298
+ self.assertIsNone(R.saved_job(self.tmp))
299
+
300
+
301
+ # ---------------------------------------------------------------------------------------------------------------- 3
302
+ class TestRunnerErrors(Base):
303
+ def test_a_runner_that_forgot_the_job_fails_the_pass_in_seconds(self):
304
+ eg = Runner(polls=[{"state": "running"}, 404, 404, {"state": "done"}])
305
+ start = self.clock.t
306
+ with self.assertRaises(R.RemoteRunnerError) as e:
307
+ self.remote(eg)
308
+ self.assertIn("no longer knows", str(e.exception))
309
+ self.assertLess(self.clock.t - start, 60) # not at the deadline (35 minutes away)
310
+ self.assertIsNone(R.saved_job(self.tmp))
311
+
312
+ def test_one_dropped_404_is_not_a_restart(self):
313
+ eg = Runner(polls=[404, {"state": "running"}, 404, {"state": "done", "exit_code": 0}])
314
+ self.assertEqual(self.remote(eg)["exit_code"], 0)
315
+
316
+ def test_a_lost_job_fails_the_pass_with_a_clear_reason(self):
317
+ eg = Runner(polls=[{"state": "lost"}], blob=bundle(with_report=False))
318
+ with self.assertRaises(R.RemoteRunnerError) as e:
319
+ self.remote(eg)
320
+ self.assertIn("restarted", str(e.exception))
321
+ self.assertIn("TEST_1", (self.tmp / "created-test-data.jsonl").read_text()) # what it made is still cleaned up
322
+
323
+ def test_past_the_deadline_the_job_is_cancelled(self):
324
+ eg = Runner(polls=[{"state": "running"}])
325
+ with self.assertRaises(ExecutionError) as e:
326
+ self.remote(eg, timeout_s=600)
327
+ self.assertTrue(e.exception.timed_out)
328
+ self.assertEqual(eg.cancels(), [f"/v1/attempts/{NEW_JOB}/cancel"])
329
+ self.assertIn("TEST_1", (self.tmp / "created-test-data.jsonl").read_text())
330
+ self.assertIsNone(R.saved_job(self.tmp))
331
+
332
+ def test_a_busy_runner_is_waited_for_then_the_attempt_starts(self):
333
+ eg = Runner(starts=[409, 409, 409, 202])
334
+ events = []
335
+ start = self.clock.t
336
+ res = self.remote(eg, on_event=events.append, busy_wait_s=900)
337
+ self.assertEqual(len(eg.posts()), 4)
338
+ self.assertEqual(res["exit_code"], 0)
339
+ self.assertEqual(len([e for e in events if "Waiting for the browser runner" in e]), 1) # said once, not per try
340
+ self.assertGreater(self.clock.t - start, 60) # it really waited (with backoff)
341
+
342
+ def test_a_runner_busy_for_too_long_is_given_up_on(self):
343
+ eg = Runner(starts=[409])
344
+ start = self.clock.t
345
+ with self.assertRaises(R.RemoteRunnerError) as e:
346
+ self.remote(eg, busy_wait_s=300)
347
+ self.assertIn("busy", str(e.exception))
348
+ self.assertGreaterEqual(self.clock.t - start, 300)
349
+ self.assertLess(self.clock.t - start, 400)
350
+ self.assertIsNone(R.saved_job(self.tmp))
351
+
352
+ def test_another_refusal_is_not_waited_for(self):
353
+ eg = Runner(starts=[400])
354
+ with self.assertRaises(R.RemoteRunnerError) as e:
355
+ self.remote(eg)
356
+ self.assertIn("HTTP 400", str(e.exception))
357
+ self.assertEqual(len(eg.posts()), 1)
358
+
359
+ def test_a_screen_read_waits_for_a_busy_runner_too(self):
360
+ buf = io.BytesIO()
361
+ with zipfile.ZipFile(buf, "w") as z:
362
+ z.writestr("playwright.log", "CAPTURED x\n")
363
+ eg = Runner(starts=[409, 202], polls=[{"state": "done", "exit_code": 0, "lines": []}], blob=buf.getvalue())
364
+ waits = []
365
+ rc, lines = R.run_screens_remote(eg, "https://runner.example", TOKEN, kind="capture", env={}, out_dir=self.tmp / "out",
366
+ task="Payables > Invoices > Create Invoice", on_wait=waits.append, busy_wait_s=600)
367
+ self.assertEqual((rc, lines), (0, ["CAPTURED x"]))
368
+ self.assertEqual(len(eg.posts("/v1/screens")), 2)
369
+ self.assertEqual(len(waits), 1)
370
+ with self.assertRaises(R.RemoteRunnerError):
371
+ R.run_screens_remote(Runner(starts=[409]), "https://runner.example", TOKEN, kind="capture", env={}, out_dir=self.tmp,
372
+ task="Payables > Invoices > Create Invoice", busy_wait_s=60)
373
+
374
+ def test_a_cancelled_run_stops_its_runner_job(self):
375
+ eg = Runner(polls=[{"state": "running"}])
376
+ status = {"status": "running"}
377
+ svc = mock.MagicMock()
378
+ svc.db.get_run.side_effect = lambda rid: dict(status)
379
+ n = {"polls": 0}
380
+
381
+ def kill():
382
+ n["polls"] += 1
383
+ if n["polls"] > 2:
384
+ status["status"] = "cancelled"
385
+ execute._stop_check(svc, "rr-1")
386
+
387
+ with self.assertRaises(execute.RunCancelled):
388
+ self.remote(eg, kill=kill)
389
+ self.assertEqual(eg.cancels(), [f"/v1/attempts/{NEW_JOB}/cancel"])
390
+ self.assertIsNone(R.saved_job(self.tmp)) # stopped and its records fetched
391
+
392
+ def test_the_langgraph_path_sends_each_pass_with_its_budget_and_notes_waits(self):
393
+ eg = Runner(starts=[409, 202, 202], new_id=NEW_JOB)
394
+ svc = mock.MagicMock()
395
+ svc.cfg = cfg(remote_runner_url="https://runner.example", fusion_chunk_scenarios=2)
396
+ svc.egress, svc.vault.get.return_value = eg, TOKEN
397
+ svc.db.get_run.return_value = {"status": "running"}
398
+ ids = ["AP-FUS-001", "AP-FUS-002", "AP-FUS-003"]
399
+ eg.blob = bundle(*ids)
400
+ try:
401
+ res = execute.run_planned(plan_for(self.tmp, ids, run_id="rr-1"), svc)
402
+ finally:
403
+ for d in (R.AUTOMATION / "results" / "runs").glob("fpt-rr-1-a0-c*"):
404
+ shutil.rmtree(d, ignore_errors=True)
405
+ self.assertEqual([b["timeout_s"] for b in eg.posts()][-2:], [execute.attempt_timeout_s(svc.cfg, n) for n in (2, 1)])
406
+ self.assertEqual([b["pw_run_id"] for b in eg.posts()][-2:], ["fpt-rr-1-a0-c0", "fpt-rr-1-a0-c1"])
407
+ self.assertEqual(res["chunks"], 2)
408
+ kinds = [(c.args[2], c.args[3].get("message", "")) for c in svc.db.add_event.call_args_list]
409
+ self.assertTrue(any(k == "runner" and "Waiting for the browser runner" in m for k, m in kinds))
410
+
411
+
412
+ # ---------------------------------------------------------------------------------------------------------------- 4
413
+ class Resp:
414
+ def __init__(self, body):
415
+ self.status_code, self._body = 200, body
416
+
417
+ def json(self):
418
+ return self._body
419
+
420
+
421
+ class TestPreflightVersion(unittest.TestCase):
422
+ def check(self, health: dict, commit: str) -> dict:
423
+ svc = mock.MagicMock()
424
+ svc.cfg.remote_runner_url = "https://runner.example"
425
+ svc.cfg.remote_runner_busy_wait_minutes = 15
426
+ svc.vault.get.return_value = TOKEN
427
+ svc.egress.service_request.return_value = Resp({"ok": True, "automation": True, "cases": True, **health})
428
+ with mock.patch.object(preflight, "server_commit", return_value=commit):
429
+ return preflight.runner_check(svc)
430
+
431
+ def test_a_runner_on_another_commit_fails_pre_flight(self):
432
+ r = self.check({"version": "0123456789ab"}, "fedcba9876543210fedcba9876543210fedcba98")
433
+ self.assertFalse(r["ok"])
434
+ self.assertIn("deploy/runner/sync.sh", r["detail"])
435
+ self.assertEqual(preflight.problems([r]), [r["detail"]])
436
+
437
+ def test_the_same_commit_short_or_long_passes(self):
438
+ self.assertTrue(self.check({"version": "0123456789ab"}, "0123456789abcdef0123456789abcdef01234567")["ok"])
439
+
440
+ def test_without_its_own_commit_the_server_does_not_compare(self):
441
+ r = self.check({"version": "0123456789ab"}, "")
442
+ self.assertTrue(r["ok"])
443
+ self.assertNotIn("warning", r)
444
+
445
+ def test_a_runner_that_does_not_say_its_commit_is_a_warning(self):
446
+ r = self.check({"version": "unknown"}, "0123456789ab")
447
+ self.assertTrue(r["ok"] and r["warning"])
448
+
449
+ def test_a_busy_runner_is_information_not_a_failure(self):
450
+ r = self.check({"version": "0123456789ab", "busy": True}, "")
451
+ self.assertTrue(r["ok"] and r["busy"])
452
+ self.assertIn("waits for it (up to 15 minutes)", r["detail"])
453
+ self.assertEqual(preflight.problems([r]), [])
454
+
455
+ def test_the_server_reads_its_commit_from_its_deploy(self):
456
+ from coworker import config
457
+ with tempfile.TemporaryDirectory() as d:
458
+ f = Path(d) / "VERSION"
459
+ with mock.patch.object(config, "COMMIT_FILE", f), mock.patch.dict("os.environ", {k: "" for k in config.COMMIT_ENV}):
460
+ self.assertEqual(config.server_commit(), "")
461
+ f.write_text("0123456789AB\n")
462
+ self.assertEqual(config.server_commit(), "0123456789ab")
463
+ with mock.patch.dict("os.environ", {"FPT_COMMIT": "not a commit"}):
464
+ self.assertEqual(config.server_commit(), "0123456789ab")
465
+ with mock.patch.dict("os.environ", {"FPT_COMMIT": "abcdef1"}):
466
+ self.assertEqual(config.server_commit(), "abcdef1")
467
+
468
+
469
+ # ---------------------------------------------------------------------------------------------------------------- 5
470
+ class TestRunnerServerJobs(unittest.TestCase):
471
+ def setUp(self):
472
+ self.S = load_server()
473
+ self.home = Path(tempfile.mkdtemp())
474
+ self.addCleanup(shutil.rmtree, self.home, True)
475
+ self.S.HOME = self.home
476
+ self.S.JOBS.clear()
477
+
478
+ def job(self, state: str, jid: str) -> Path:
479
+ d = self.home / jid
480
+ d.mkdir()
481
+ (d / "created.jsonl").write_text('{"invoice":"TEST_1"}\n')
482
+ self.S.save_meta({"id": jid, "dir": d, "kind": "attempt", "state": state, "started": real_time.time(), "pw_run_id": "fpt-x",
483
+ "exit_code": 0 if state == "done" else None, "proc": object(), "log": object()})
484
+ return d
485
+
486
+ def test_a_restarted_runner_answers_for_its_jobs(self):
487
+ self.job("done", "job_0000000000d1")
488
+ self.job("running", "job_0000000000d2")
489
+ meta = json.loads((self.home / "job_0000000000d1" / "job.json").read_text())
490
+ self.assertNotIn("env", meta)
491
+ self.assertEqual(set(meta), set(self.S.META))
492
+ self.S.load_jobs()
493
+ self.assertEqual(self.S.JOBS["job_0000000000d1"]["state"], "done")
494
+ self.assertEqual(self.S.JOBS["job_0000000000d2"]["state"], "lost") # it died with the old runner
495
+ self.assertEqual(json.loads((self.home / "job_0000000000d2" / "job.json").read_text())["state"], "lost")
496
+ names = zipfile.ZipFile(io.BytesIO(self.S.bundle(self.S.JOBS["job_0000000000d2"]))).namelist()
497
+ self.assertIn("created.jsonl", names) # its ledger still ships
498
+
499
+ def test_a_folder_that_is_not_a_job_is_ignored(self):
500
+ d = self.home / "job_0000000000d3"
501
+ d.mkdir()
502
+ (d / "job.json").write_text(json.dumps({"id": "job_0000000000ff", "state": "done"})) # names another job
503
+ self.S.load_jobs()
504
+ self.assertEqual(self.S.JOBS, {})
505
+
506
+ def run_watch(self, deadline_in: float, code: str) -> dict:
507
+ d = self.home / "job_0000000000e1"
508
+ d.mkdir()
509
+ log = open(d / "playwright.log", "wb")
510
+ p = subprocess.Popen([sys.executable, "-c", code], stdout=log, stderr=subprocess.STDOUT, **self.S.GROUP)
511
+ job = {"id": "job_0000000000e1", "dir": d, "proc": p, "log": log, "pw_run_id": "fpt-none", "started": real_time.time(),
512
+ "kind": "attempt", "deadline": real_time.time() + deadline_in, "state": "running", "exit_code": None}
513
+ self.S.LOCK.acquire()
514
+ self.S.GRACE_S = 5
515
+ self.S._watch(job)
516
+ return job
517
+
518
+ def test_a_finished_attempt_is_recorded_and_frees_the_runner(self):
519
+ job = self.run_watch(60, "print('[1/1] ok')")
520
+ self.assertEqual((job["state"], job["exit_code"]), ("done", 0))
521
+ self.assertFalse(self.S.LOCK.locked())
522
+ self.assertEqual(json.loads((self.home / job["id"] / "job.json").read_text())["state"], "done")
523
+
524
+ def test_an_attempt_past_its_deadline_is_stopped_and_still_reports(self):
525
+ # a Playwright stand-in that writes its report when asked to stop (SIGINT), as the JSON reporter does
526
+ code = ("import json, signal, sys, time, pathlib\n"
527
+ "def stop(*a):\n"
528
+ " pathlib.Path(sys.argv[1]).write_text(json.dumps({'suites': [], 'errors': [], 'stats': {'interrupted': True}}))\n"
529
+ " sys.exit(130)\n"
530
+ "signal.signal(signal.SIGINT, stop)\n"
531
+ "time.sleep(60)\n")
532
+ d = self.home / "job_0000000000e1"
533
+ job = self.run_watch(0, code.replace("sys.argv[1]", repr(str(d / "report.json"))))
534
+ self.assertTrue(job["timed_out"])
535
+ self.assertEqual(job["state"], "done")
536
+ self.assertFalse(self.S.LOCK.locked())
537
+ if self.S.os.name == "posix": # Windows has no gentle stop: killed at once
538
+ self.assertTrue((d / "report.json").exists())
539
+
540
+
541
+ if __name__ == "__main__":
542
+ unittest.main()
coworker/tests/test_step_writer.py CHANGED
@@ -116,6 +116,10 @@ class TestChecker(unittest.TestCase):
116
  self.assertIn("{{saved.later}} is used before", p)
117
  self.assertNotIn("{{saved.amt}}", p)
118
 
 
 
 
 
119
  def test_empty_expected_value_is_allowed_but_missing_is_not(self):
120
  base = {**GOOD, "steps": GOOD["steps"][:4]}
121
  ok = {**base, "steps": base["steps"] + [{"action": "expect_value", "field": "Description", "value": ""}]}
@@ -308,3 +312,15 @@ class TestFrontierProvider(unittest.TestCase):
308
 
309
  if __name__ == "__main__":
310
  unittest.main()
 
 
 
 
 
 
 
 
 
 
 
 
 
116
  self.assertIn("{{saved.later}} is used before", p)
117
  self.assertNotIn("{{saved.amt}}", p)
118
 
119
+ def test_a_mask_left_in_a_step_is_refused(self):
120
+ bad = {**GOOD, "steps": GOOD["steps"][:4] + [{"action": "enter", "field": "Description", "value": "Paid to <NAME_3>"}]}
121
+ self.assertIn("'<NAME_3>' is a masked value", "\n".join(sw.check_steps(bad, INV)))
122
+
123
  def test_empty_expected_value_is_allowed_but_missing_is_not(self):
124
  base = {**GOOD, "steps": GOOD["steps"][:4]}
125
  ok = {**base, "steps": base["steps"] + [{"action": "expect_value", "field": "Description", "value": ""}]}
 
312
 
313
  if __name__ == "__main__":
314
  unittest.main()
315
+
316
+
317
+ class TestPromptsPassTheLeakCheck(unittest.TestCase):
318
+ """Every model request carries its system prompt, and the egress leak check reads the whole request: a prompt with
319
+ something that looks like data (an example date, an id, an amount) would refuse every call of that task. Seen before
320
+ deploy: an example date in write_steps.md sent every step-writing call to the built-in rules."""
321
+
322
+ def test_no_prompt_looks_like_client_data(self):
323
+ from ..platform.redaction import Redactor
324
+ red = Redactor([])
325
+ for f in sorted((Path(sw.__file__).parents[1] / "llm" / "prompts").glob("*.md")):
326
+ self.assertEqual(red.find_leaks(f.read_text(encoding="utf-8")), [], f.name)
coworker/tests/test_supabase.py CHANGED
@@ -260,6 +260,19 @@ class TestStateSync(unittest.TestCase):
260
  statesync.restore(cfg2, sb.Supabase(cfg2, svc.egress, None))
261
  self.assertFalse((fresh / "fpt.sqlite").exists())
262
 
 
 
 
 
 
 
 
 
 
 
 
 
 
263
  def test_a_finished_screen_read_or_paused_run_is_saved_at_once_not_at_the_next_interval(self):
264
  """Seen on the live Space: a deploy restarted it minutes after an hour of screen reading had finished, before the
265
  periodic save, and the restore brought back the old screens with the read still 'running'."""
 
260
  statesync.restore(cfg2, sb.Supabase(cfg2, svc.egress, None))
261
  self.assertFalse((fresh / "fpt.sqlite").exists())
262
 
263
+ def test_an_asked_for_save_happens_even_when_the_signature_looks_saved(self):
264
+ """Race found in review: a save uploading while an event writes records a signature that already includes the
265
+ write, though its archive does not; the asked-for save must not be skipped as 'unchanged'."""
266
+ fake = FakeSupabase(confirm=False)
267
+ _, c, svc = make(fake)
268
+ s = statesync.Syncer(svc, 3600)
269
+ self.assertTrue(s.tick())
270
+ self.assertFalse(s.tick()) # nothing changed, nothing asked: skipped
271
+ s.soon("run completed") # the loop is not started: tick by hand
272
+ self.assertTrue(s.tick()) # asked for: saved even though the signature matches
273
+ self.assertFalse(s.tick()) # owed once only
274
+ self.assertTrue(s.tick("before restart", force=True))
275
+
276
  def test_a_finished_screen_read_or_paused_run_is_saved_at_once_not_at_the_next_interval(self):
277
  """Seen on the live Space: a deploy restarted it minutes after an hour of screen reading had finished, before the
278
  periodic save, and the restore brought back the old screens with the read still 'running'."""
coworker/workflows/client.py CHANGED
@@ -79,8 +79,8 @@ class TemporalRunManager:
79
  return self.client.get_workflow_handle(run_id)
80
 
81
  # ---------------------------------------------------------------- API
82
- def start(self, inputs: dict, actor: str, trigger: str = "manual") -> str:
83
- rid, _ = create_run_record(self.svc, inputs, actor, trigger, orchestrator="temporal")
84
  self._loop.run(self.client.start_workflow("PatchCycleWorkflow", workflow_input(self.cfg, rid), id=rid,
85
  task_queue=self.cfg.temporal_task_queue))
86
  return rid
 
79
  return self.client.get_workflow_handle(run_id)
80
 
81
  # ---------------------------------------------------------------- API
82
+ def start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str:
83
+ rid, _ = create_run_record(self.svc, inputs, actor, trigger, orchestrator="temporal", run_id=run_id)
84
  self._loop.run(self.client.start_workflow("PatchCycleWorkflow", workflow_input(self.cfg, rid), id=rid,
85
  task_queue=self.cfg.temporal_task_queue))
86
  return rid
deploy/DEPLOY.md CHANGED
@@ -1,8 +1,14 @@
1
- # Deploying Patchwise in a customer's cloud
2
 
3
  One deployment serves one customer. Everything the product stores stays on the customer's own server, in Docker
4
  volumes: nothing is kept outside their environment.
5
 
 
 
 
 
 
 
6
  > **Status of this package.** The application image is built and checked automatically on every push to `main`
7
  > (`.github/workflows/image.yml`): it starts, serves the web app, the practice pod answers, sign-in works, and the
8
  > self-tests pass inside the container (35 checks offline, 42 with three scenarios in Chromium). Image size: 1.8 GB.
@@ -74,7 +80,7 @@ Live view, and download the report and the Excel test script.
74
  | Logs | `docker compose logs -f app` |
75
  | Backup | `./backup.sh /secure/backups` (the archive includes the secrets vault: keep it encrypted) |
76
  | Upgrade | take a backup, load or build the new image, `docker compose up -d` (database upgrades run on start) |
77
- | Upgrade the browser runner (when Fusion tests run on a separate runner, `FPT_REMOTE_RUNNER_URL`) | right after every upgrade, on the same commit: `deploy/runner/sync.sh ubuntu@<runner> <ssh key> https://<runner>`. It refuses while a test run is using the runner; its `/healthz` then shows the commit as `version` and `cases: true` |
78
  | Temporal UI | `ssh -L 8233:127.0.0.1:8233 <server>` then open `http://127.0.0.1:8233` |
79
  | Emergency stop | in the product: Settings > Emergency stop, or `docker compose exec app python -m coworker kill` |
80
  | Check the audit log | `docker compose exec app python -m coworker verify-audit` |
@@ -92,9 +98,9 @@ Live view, and download the report and the Excel test script.
92
 
93
  These are the limits of the product today, not of the packaging. Say them plainly to a buyer.
94
 
95
- - **Oracle Fusion coverage is Payables only.** Runs on a registered Fusion test pod work end to end for Payables
96
- (verified on a real pod on 31 Oct 2026: 6 of 6 scenarios in the browser). Other business areas run on the
97
- practice pod only until their Fusion scripts are written and verified.
98
  - **Single sign-on** (SAML/OIDC) is not built; accounts are local or come from Supabase.
99
  - **SQLite and a single-node Temporal dev server.** Fine for one customer on one server; not highly available.
100
  - **Jira / ServiceNow**: tickets are written to files; the connectors are stubs.
@@ -104,7 +110,8 @@ These are the limits of the product today, not of the packaging. Say them plainl
104
 
105
  ## Settings that make the demo survive a restart (Hugging Face Space or any host without a disk)
106
 
107
- The app keeps its data in an encrypted snapshot in Supabase Storage and restores it at start. These settings rebuild the
 
108
  essentials from the environment, so a lost or unreadable snapshot never leaves the product without its pod or its AI model.
109
 
110
  | Setting | Kind | Effect |
@@ -112,12 +119,15 @@ essentials from the environment, so a lost or unreadable snapshot never leaves t
112
  | `FPT_FUSION_BASE_URL` (`https://<pod>.fa.ocs.oraclecloud.com`), `FPT_FUSION_NAME`, `FPT_FUSION_ENVIRONMENT`, `FPT_FUSION_MODULES` | variable | The Oracle Fusion test pod exists after every start. Production addresses are refused. |
113
  | `FPT_SECRET_FUSION_USERNAME`, `FPT_SECRET_FUSION_PASSWORD` | secret | The pod's test user. Never written to the vault file or shown. |
114
  | `FRONTIER_BASE_URL` (https), `FRONTIER_MODEL`, `FPT_SECRET_FRONTIER_API_KEY` | variable, variable, secret | The external model is switched on at start when no AI settings are saved in the app. `FPT_FRONTIER_AUTO=0` turns this off. |
115
- | `SUPABASE_BUCKET`, `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `FPT_STATE_KEY` | variable and secrets | One bucket per deployment; never share a bucket between two instances (the last writer wins). |
 
116
 
117
  If the start-up restore fails, the instance starts empty and **stops saving** (`/api/ready` shows `saved_state.paused`, and the app shows a notice) so the good
118
  snapshot is not overwritten; restart to retry. The first save of every start keeps the archive it found as `state/previous.bin`
119
  in the bucket; copy it over `state/latest.bin` to undo a bad save.
120
 
121
- **Before every restart or deploy**, save the state and wait for the answer: `POST /api/storage/save` (administrator).
122
- The app also saves at once when a screen read finishes and when a run waits for a person or ends, and first thing on
123
- shutdown; a screen read cut off by a restart shows as interrupted after it, never as still running.
 
 
 
1
+ # Deploying Astra in a customer's cloud
2
 
3
  One deployment serves one customer. Everything the product stores stays on the customer's own server, in Docker
4
  volumes: nothing is kept outside their environment.
5
 
6
+ > **Oracle Fusion pods do not run in this shape today.** This stack runs the workflow on Temporal, and the Temporal
7
+ > execute activity (`coworker/workflows/activities.py`) supports the practice pod only: it starts the local practice
8
+ > pod and has no remote browser runner, no per-area test users and no pre-flight. Fusion test cycles run on the
9
+ > Hugging Face Space shape with a remote runner ([docs/DEPLOYMENT.md](../docs/DEPLOYMENT.md)). Say this plainly to a
10
+ > buyer.
11
+
12
  > **Status of this package.** The application image is built and checked automatically on every push to `main`
13
  > (`.github/workflows/image.yml`): it starts, serves the web app, the practice pod answers, sign-in works, and the
14
  > self-tests pass inside the container (35 checks offline, 42 with three scenarios in Chromium). Image size: 1.8 GB.
 
80
  | Logs | `docker compose logs -f app` |
81
  | Backup | `./backup.sh /secure/backups` (the archive includes the secrets vault: keep it encrypted) |
82
  | Upgrade | take a backup, load or build the new image, `docker compose up -d` (database upgrades run on start) |
83
+ | Upgrade the browser runner (Space shape only: Fusion tests on a separate runner, `FPT_REMOTE_RUNNER_URL`) | right after every upgrade, on the same commit: `deploy/runner/sync.sh ubuntu@<runner> <ssh key> https://<runner>`. It refuses while a test run is using the runner; its `/healthz` then shows the commit as `version` and `cases: true` |
84
  | Temporal UI | `ssh -L 8233:127.0.0.1:8233 <server>` then open `http://127.0.0.1:8233` |
85
  | Emergency stop | in the product: Settings > Emergency stop, or `docker compose exec app python -m coworker kill` |
86
  | Check the audit log | `docker compose exec app python -m coworker verify-audit` |
 
98
 
99
  These are the limits of the product today, not of the packaging. Say them plainly to a buyer.
100
 
101
+ - **No Oracle Fusion pods in this shape** (see the note at the top). On the Space shape, the committed Fusion
102
+ scenario library is Payables (`AP-FUS-*`); scenarios for the other areas are written by the AI model from the
103
+ pod's screens during a run; approved ones join the library when `FPT_CASE_WRITEBACK=1`.
104
  - **Single sign-on** (SAML/OIDC) is not built; accounts are local or come from Supabase.
105
  - **SQLite and a single-node Temporal dev server.** Fine for one customer on one server; not highly available.
106
  - **Jira / ServiceNow**: tickets are written to files; the connectors are stubs.
 
110
 
111
  ## Settings that make the demo survive a restart (Hugging Face Space or any host without a disk)
112
 
113
+ The app keeps its data in an encrypted snapshot in a bucket (OCI Object Storage when `OCI_STATE_PAR_URL` is set, else
114
+ Supabase Storage) and restores it at start. These settings rebuild the
115
  essentials from the environment, so a lost or unreadable snapshot never leaves the product without its pod or its AI model.
116
 
117
  | Setting | Kind | Effect |
 
119
  | `FPT_FUSION_BASE_URL` (`https://<pod>.fa.ocs.oraclecloud.com`), `FPT_FUSION_NAME`, `FPT_FUSION_ENVIRONMENT`, `FPT_FUSION_MODULES` | variable | The Oracle Fusion test pod exists after every start. Production addresses are refused. |
120
  | `FPT_SECRET_FUSION_USERNAME`, `FPT_SECRET_FUSION_PASSWORD` | secret | The pod's test user. Never written to the vault file or shown. |
121
  | `FRONTIER_BASE_URL` (https), `FRONTIER_MODEL`, `FPT_SECRET_FRONTIER_API_KEY` | variable, variable, secret | The external model is switched on at start when no AI settings are saved in the app. `FPT_FRONTIER_AUTO=0` turns this off. |
122
+ | `OCI_STATE_PAR_URL`, `FPT_STATE_KEY` | secrets | The OCI bucket's pre-authenticated request URL (read and write objects, listing denied) and the snapshot key, which OCI requires. Periodic saves at most every 300 s there; event saves go at once. One bucket per deployment. |
123
+ | `SUPABASE_BUCKET`, `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `FPT_STATE_KEY` | variable and secrets | Supabase Storage instead. One bucket per deployment; never share a bucket between two instances (the last writer wins). |
124
 
125
  If the start-up restore fails, the instance starts empty and **stops saving** (`/api/ready` shows `saved_state.paused`, and the app shows a notice) so the good
126
  snapshot is not overwritten; restart to retry. The first save of every start keeps the archive it found as `state/previous.bin`
127
  in the bucket; copy it over `state/latest.bin` to undo a bad save.
128
 
129
+ **Before every restart or deploy**, check that no run is running or queued and the runner is not busy, then save the
130
+ state and wait for the answer: `POST /api/storage/save` (administrator). After the deploy, run `deploy/runner/sync.sh`
131
+ on the same commit. The app also saves at once when a screen read finishes and when a run waits for a person, ends or
132
+ is cancelled, and first thing on shutdown; a screen read cut off by a restart shows as interrupted after it, never as
133
+ still running. Full steps: docs/RUNBOOK.md "Before every deploy or restart".
deploy/runner/sync.sh CHANGED
@@ -36,12 +36,20 @@ else
36
  npm ci --no-audit --no-fund --loglevel=error
37
  fi
38
  npx playwright install chromium >/dev/null
 
 
 
 
 
 
39
  rm -rf ~/astra.prev
40
  [ -d ~/astra ] && mv ~/astra ~/astra.prev
41
  mv ~/astra.new ~/astra
42
  sudo systemctl restart "$SERVICE"
43
  sleep 3
44
- curl -s http://127.0.0.1:${RUNNER_PORT:-8899}/healthz; echo
 
 
45
  REMOTE
46
 
47
  if [ -n "$URL" ]; then
 
36
  npm ci --no-audit --no-fund --loglevel=error
37
  fi
38
  npx playwright install chromium >/dev/null
39
+ # the install took minutes: a test run may have started meanwhile, and the restart would kill its browsers
40
+ if curl -s --max-time 10 http://127.0.0.1:${RUNNER_PORT:-8899}/healthz | grep -q '"busy": true'; then
41
+ echo "a test run started on the runner during the install: nothing switched; run this again when it ends" >&2
42
+ rm -rf ~/astra.new
43
+ exit 2
44
+ fi
45
  rm -rf ~/astra.prev
46
  [ -d ~/astra ] && mv ~/astra ~/astra.prev
47
  mv ~/astra.new ~/astra
48
  sudo systemctl restart "$SERVICE"
49
  sleep 3
50
+ H=$(curl -s http://127.0.0.1:${RUNNER_PORT:-8899}/healthz); echo "$H"
51
+ # the service must run the copy just installed (its AUTOMATION_DIR is ~/astra/automation) and have its scenario files
52
+ echo "$H" | grep -q "\"version\": \"$REV\"" && echo "$H" | grep -q '"cases": true' || { echo "the runner does not report $REV with its scenario files: check the service's AUTOMATION_DIR" >&2; exit 3; }
53
  REMOTE
54
 
55
  if [ -n "$URL" ]; then
docs/AGENT_STUDIO.md CHANGED
@@ -1,12 +1,15 @@
1
- # Oracle AI Agent Studio → Patchwise
2
 
3
- This guide explains how an Oracle Fusion Cloud AI Agent Studio workflow runs a patch test cycle in Patchwise. Fusion
4
- owns the schedule, the synthetic test data and both human approvals. Patchwise (LangGraph) writes the test scripts,
5
  runs the browser tests and reports back. The OpenAPI spec is `web/src/api/openapi.json` (tag **agent-studio**). The live `/api/docs` page is off on the public Space (`FPT_API_DOCS=0`).
6
 
 
 
 
7
  ```
8
- Oracle Fusion Cloud Patchwise
9
- ─────────────────── ─────────
10
  Scheduler (weekly)
11
  └ AI Agent Studio workflow
12
  1 Read module space
@@ -16,25 +19,26 @@ Scheduler (weekly)
16
  5 Email + notification ◀── callback scripts_ready ──────────────────────┘
17
  6 Human approval (start) ── POST /api/agent-studio/v1/cycles/{id}/approval ▶ Playwright browser runner
18
  (User B, TEST_US_BU)
19
- ◀── callback failures_need_review (if any) ─────── triage (a person, in Patchwise)
20
  7 Email + notification ◀── callback results / stopped ────────────────── reports
 
21
  Release watch agent ◀── callback patch_update ───────────────────── web crawler of Oracle release notes
22
  ```
23
 
24
- **Contract:** test data is **synthetic only**, with no personal data and no real transactions. Patchwise refuses values
25
  that look like an email address, a phone or card number, or a national id (`NOT_SYNTHETIC`). Every approval is made by
26
  a person: the two in Fusion are forwarded with that person's name, and test failures are always decided by a person
27
- in Patchwise, never automatically.
28
 
29
  ## Users and privileges
30
 
31
  | Who | Where | Can |
32
  |---|---|---|
33
- | User A | Fusion only | data roles for the workflow; never given to Patchwise |
34
  | User C | the OAuth client (`patchwise.invoke`) | start cycles, read them, forward approvals. Cannot list runs or touch anything else |
35
- | User B | the Fusion test pod's sign-in, stored in Patchwise | the browser tests: action privileges only, in test business unit `TEST_US_BU` |
36
 
37
- ## 1. Set up (a Patchwise admin)
38
 
39
  1. **Test environments**: register the Fusion test pod with User B's sign-in (it is stored in the vault and never shown).
40
  2. **Agent Studio → Clients → New client**: name it and give the HTTPS **callback address** (step 5/7 in Fusion), and
@@ -58,18 +62,28 @@ grant_type=client_credentials&client_id=…&client_secret=…&scope=patchwise.in
58
  ```
59
 
60
  HTTP Basic or a JSON body also work. The response is `{"access_token":"pwa_…","token_type":"Bearer","expires_in":3600,"scope":"patchwise.invoke"}`.
61
- Send it as `Authorization: Bearer pwa_…` on every call below.
 
 
 
 
 
 
 
 
 
62
 
63
  ### Check test data (optional)
64
 
65
  `POST /test-data/check` with `{"test_data": {...}}` returns `{"ok": true, "areas": {...}, "mapped": {...}, "not_testable": [...]}`
66
- or `{"ok": false, "code", "problem"}`. `mapped` lists the Fusion workflow's own area codes Patchwise renamed (below);
67
- `not_testable` lists areas Patchwise has no Fusion tests for (HCM, PAY, ABS, BEN, IRC today).
68
 
69
  ### Start a cycle (after the person approves the data)
70
 
71
  ```http
72
  POST /cycles
 
73
  {
74
  "test_data": {"AP": {"business_unit": "TEST_US_BU", "supplier": ["Test Supplier A", "Test Supplier B"], "currency": "USD"}},
75
  "data_approved_by": "Priya (Fusion QA)",
@@ -86,17 +100,30 @@ POST /cycles
86
  | `data_approved_by` | required: who approved the data in Fusion |
87
  | `areas` | defaults to the test data's areas. Areas the pod cannot test are skipped and listed in `skipped_areas`; the cycle is refused (`BAD_TEST_DATA`) only when none can be tested |
88
  | `package` | optional: the approved test data package of the V3.6 workflows (up to 2 MB). Kept with the cycle; its `package_id` is in the response and admins read it at `GET /api/agent-studio/cycles/{cycle_id}/package` |
89
- | `depth` | `regression` (default): every approved scenario of each area, every priority, plus one end-to-end flow per business process of the area (at most `FPT_FUSION_REGRESSION_FLOWS`, 3) and the cross-area flows (Procure-to-Pay ...) when all their areas are tested. `standard`: the patch's P1 scenarios and the ones its changes touch. `smoke`: the quickest check. Anything else is refused (`BAD_DEPTH`) |
90
- | `environment` | the Patchwise test environment's name; defaults to the default Fusion pod |
91
  | `callback_url` | defaults to the client's callback address |
92
- | `correlation_id` | your workflow's id, echoed in every callback |
93
 
94
  The response is **202** with `{"cycle_id": "cyc_…", "run_id": "…", "areas", "skipped_areas", "package_id", "status", "waiting_for", "links": {"run", "excel", "report"}}`.
95
  The approval answer has the same shape plus `decision`.
96
 
 
 
 
 
 
 
 
 
 
 
 
 
 
97
  ### Where a cycle is
98
 
99
- `GET /cycles/{cycle_id}` returns the same shape. `waiting_for` is one of:
100
  - `"approval in Oracle Fusion (start testing)"`;
101
  - `"a person to decide the failures (in Patchwise)"`;
102
  - `null`.
@@ -110,7 +137,7 @@ POST /cycles/{cycle_id}/approval
110
 
111
  - Leaving out `scenario_ids` approves every scenario offered.
112
  - `"reject"` cancels the cycle; `comment` is kept.
113
- - Patchwise records the actor as `Priya (Fusion QA) (in Oracle Fusion)`.
114
 
115
  ### Errors
116
 
@@ -124,14 +151,31 @@ The body is `{"code", "detail", "request_id"}`.
124
  | 409 | the run is not waiting for that decision, or no Fusion environment exists |
125
  | 422 | a required field is missing |
126
 
127
- ## 3. Callbacks (Patchwise → Fusion)
128
 
129
  Each OAuth client chooses how its events reach Fusion (**Agent Studio → OAuth clients → Delivery**).
130
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
131
  ### Oracle Fusion directly (recommended; no relay)
132
 
133
- Patchwise signs in to your OCI IAM identity domain with a confidential app (client credentials). The client secret is
134
- write-only and kept in the vault; the token is held in memory only. Patchwise then starts the callback workflow:
135
  `POST {Fusion address}/api/fusion-ai/orchestrator/agent/v2/{workflow code}/invokeAsync`, by default
136
  `PATCH_TEST_CALLBACK_V3_7`.
137
 
@@ -163,33 +207,46 @@ in a **While Loop** with a **Wait** of 2 to 5 minutes after `createCycle`.
163
  optional. The answer is `{events, count, more, confirm_within_s}`. Each event is the callback body below, plus
164
  `delivery_id` and `pickup` (how many times it was handed out).
165
  - **Confirm:** `POST /api/agent-studio/v1/events/ack` with `{"delivery_ids": ["dlv_…"]}`. A confirmed event is not
166
- handed out again.
167
 
168
- An event that isn't confirmed within 5 minutes is handed out again, up to 20 times. A client only sees and confirms
169
- its own events. To keep this mode on a server without saved state, add `"delivery": "pull"` to the client in
170
- `FPT_SECRET_AGENT_STUDIO_BOOTSTRAP_CLIENTS`.
 
 
 
171
 
172
  ### Callback address (a relay or any receiver)
173
 
174
  Callbacks are sent with `POST` to the callback address, as `Content-Type: application/json`, with these headers:
175
 
176
  - `X-Patchwise-Event`: the event's name.
177
- - `X-Patchwise-Delivery`: a unique id; use it to ignore duplicates.
178
  - `X-Patchwise-Signature: sha256=<hex>`: an HMAC-SHA256 of the **raw body** with the client's signing key.
179
 
180
  Answer with any 2xx code. Anything else, or no answer within 20 s, is retried after 1, 2, 4, 8 and 16 minutes (six
181
- tries in all). Delivery state is listed under **Agent Studio → Callbacks**.
 
 
 
182
 
183
  Every body has `event`, `delivery_id`, `sent_at`, `cycle_id`, `run_id`, `correlation_id` and `links`, plus:
184
 
185
  | Event | When | Extra fields |
186
  |---|---|---|
187
- | `scripts_ready` | test scripts written, waiting for step 6 | `scenarios[]` (`id`, `title`, `area`, `priority`, `written_by`, `covers_patch_change`), `count`, `approve_with`. `links.excel` is the test script |
188
- | `failures_need_review` | some tests failed | `note`: a person decides each failure in Patchwise |
189
- | `results` | finished | `verdict` (`Ready` / `Not ready`), `areas[]` (`area`, `verdict`, `rule_result`, `counts`) |
190
- | `stopped` | failed, cancelled, killed or interrupted | `status`, `reason` |
 
191
  | `patch_update` | the release watch found new items (to the release watch address) | `release`, `count`, `changes[]` (`id`, `area`, `title`, `on_by_default`, `impact`, `action_to_enable`, `link`) |
192
 
 
 
 
 
 
 
193
  Verify a callback before using it:
194
 
195
  ```python
@@ -201,7 +258,7 @@ def verify(signing_key: str, raw_body: bytes, header: str) -> bool:
201
 
202
  ## 4. The release watch
203
 
204
- Every 24 hours (setting `agent_studio_watch_hours`; 0 turns it off), Patchwise reads Oracle's What's New for each
205
  Fusion pod's release and for the areas in use. New items go to every client's release watch address as one
206
  `patch_update`. The Fusion release watch agent drafts the impact assessment and emails it. Admins can run a check at
207
  once with **Agent Studio → Release watch → Check now** (`POST /api/agent-studio/release-watch/check`).
@@ -220,20 +277,24 @@ The console only calls what Fusion would call. It cannot skip a human decision.
220
 
221
  ## 6. Where the data lives
222
 
223
- The backend is the same as Patchwise v1. Supabase Auth handles sign-in and registration. An encrypted snapshot of the
224
- app's data (the SQLite database, which holds the `agent_*` tables, plus the vault with the signing keys, reports and
225
- evidence) is saved to a private Supabase Storage bucket whenever the database changes, and restored after a restart.
 
226
  This Space uses **its own bucket, `patchwise-agent-studio`** (set in the Dockerfile), in the same Supabase project, so
227
  it never overwrites v1's saved state. It also has its own `FPT_STATE_KEY`.
228
 
229
  Space secrets to set:
230
  - `SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_KEY` (the same project as v1);
231
  - `FPT_SECRET_FRONTIER_API_KEY`;
232
- - `FPT_SECRET_FUSION_USERNAME` and `FPT_SECRET_FUSION_PASSWORD` (User B).
 
233
 
234
  ## 7. Security notes
235
 
236
- - Client secrets and tokens are stored hashed. Signing keys are kept in the vault.
 
237
  - A token is for this API only: it cannot read runs or call any other `/api` route.
238
- - Callbacks go only to the client's own HTTPS address, through the egress gate, and every one is audited.
 
239
  - Rotate a client's credentials by creating a new client and revoking the old one.
 
1
+ # Oracle AI Agent Studio → Astra
2
 
3
+ This guide explains how an Oracle Fusion Cloud AI Agent Studio workflow runs a patch test cycle in Astra. Fusion
4
+ owns the schedule, the synthetic test data and both human approvals. Astra (LangGraph) writes the test scripts,
5
  runs the browser tests and reports back. The OpenAPI spec is `web/src/api/openapi.json` (tag **agent-studio**). The live `/api/docs` page is off on the public Space (`FPT_API_DOCS=0`).
6
 
7
+ Some names on the wire still say `patchwise` (the scope `patchwise.invoke`, the `X-Patchwise-*` headers, the
8
+ `pwc_`/`pws_`/`pwk_`/`pwa_` prefixes). They are part of the contract the Fusion workflows already use and do not change.
9
+
10
  ```
11
+ Oracle Fusion Cloud Astra
12
+ ─────────────────── ─────
13
  Scheduler (weekly)
14
  └ AI Agent Studio workflow
15
  1 Read module space
 
19
  5 Email + notification ◀── callback scripts_ready ──────────────────────┘
20
  6 Human approval (start) ── POST /api/agent-studio/v1/cycles/{id}/approval ▶ Playwright browser runner
21
  (User B, TEST_US_BU)
22
+ ◀── callback failures_need_review (if any) ─────── triage (a person, in Astra)
23
  7 Email + notification ◀── callback results / stopped ────────────────── reports
24
+ ◀── callback paused (optional, may be ignored) ─── a restart interrupted the run
25
  Release watch agent ◀── callback patch_update ───────────────────── web crawler of Oracle release notes
26
  ```
27
 
28
+ **Contract:** test data is **synthetic only**, with no personal data and no real transactions. Astra refuses values
29
  that look like an email address, a phone or card number, or a national id (`NOT_SYNTHETIC`). Every approval is made by
30
  a person: the two in Fusion are forwarded with that person's name, and test failures are always decided by a person
31
+ in Astra, never automatically.
32
 
33
  ## Users and privileges
34
 
35
  | Who | Where | Can |
36
  |---|---|---|
37
+ | User A | Fusion only | data roles for the workflow; never given to Astra |
38
  | User C | the OAuth client (`patchwise.invoke`) | start cycles, read them, forward approvals. Cannot list runs or touch anything else |
39
+ | User B | the Fusion test pod's sign-in, stored in Astra | the browser tests: action privileges only, in test business unit `TEST_US_BU` |
40
 
41
+ ## 1. Set up (an Astra admin)
42
 
43
  1. **Test environments**: register the Fusion test pod with User B's sign-in (it is stored in the vault and never shown).
44
  2. **Agent Studio → Clients → New client**: name it and give the HTTPS **callback address** (step 5/7 in Fusion), and
 
62
  ```
63
 
64
  HTTP Basic or a JSON body also work. The response is `{"access_token":"pwa_…","token_type":"Bearer","expires_in":3600,"scope":"patchwise.invoke"}`.
65
+ Send it as `Authorization: Bearer pwa_…` on every call below. Treat the token as opaque; only its `pwa_` prefix is
66
+ fixed.
67
+
68
+ **How tokens behave.** A token is signed by Astra (HMAC-SHA256 over the client id and the expiry time), so Astra checks
69
+ it without looking it up. A restart that restores an older saved state therefore does not end a token the Fusion side
70
+ has cached: it stays valid for its hour. The key is the vault secret `agent_studio.token_key`. Set
71
+ `FPT_SECRET_AGENT_STUDIO_TOKEN_KEY` on the server to keep it fixed; otherwise Astra makes one the first time and keeps
72
+ it in the saved state. Changing the key ends every token already issued, and the Fusion side then asks for a new one.
73
+ Every call still checks the client: a revoked client's tokens are refused at once (`401 invalid_token`). Tokens issued
74
+ before tokens were signed keep working until they expire.
75
 
76
  ### Check test data (optional)
77
 
78
  `POST /test-data/check` with `{"test_data": {...}}` returns `{"ok": true, "areas": {...}, "mapped": {...}, "not_testable": [...]}`
79
+ or `{"ok": false, "code", "problem"}`. `mapped` lists the Fusion workflow's own area codes Astra renamed (below);
80
+ `not_testable` lists areas Astra has no Fusion tests for (HCM, PAY, ABS, BEN, IRC today).
81
 
82
  ### Start a cycle (after the person approves the data)
83
 
84
  ```http
85
  POST /cycles
86
+ Idempotency-Key: 6c1f… (optional)
87
  {
88
  "test_data": {"AP": {"business_unit": "TEST_US_BU", "supplier": ["Test Supplier A", "Test Supplier B"], "currency": "USD"}},
89
  "data_approved_by": "Priya (Fusion QA)",
 
100
  | `data_approved_by` | required: who approved the data in Fusion |
101
  | `areas` | defaults to the test data's areas. Areas the pod cannot test are skipped and listed in `skipped_areas`; the cycle is refused (`BAD_TEST_DATA`) only when none can be tested |
102
  | `package` | optional: the approved test data package of the V3.6 workflows (up to 2 MB). Kept with the cycle; its `package_id` is in the response and admins read it at `GET /api/agent-studio/cycles/{cycle_id}/package` |
103
+ | `depth` | `regression` (default): every approved scenario of each area, every priority, plus one end-to-end flow per business process of the area (at most `FPT_FUSION_REGRESSION_FLOWS`, 3) and the cross-area flows (Procure-to-Pay ...) when all their areas are tested. It also asks the AI model for one scenario per standard regression and edge-case check of the area (the `regression` list of `coworker/platform/fusion_catalog.py`: refusals, boundaries, duplicates, state changes, defaults, searches) that no library scenario covers yet, at most `FPT_FUSION_REGRESSION_CHECKS` (25, 0 = off) per area. `standard`: the patch's P1 scenarios and the ones its changes touch. `smoke`: the quickest check. Anything else is refused (`BAD_DEPTH`) |
104
+ | `environment` | the Astra test environment's name; defaults to the default Fusion pod |
105
  | `callback_url` | defaults to the client's callback address |
106
+ | `correlation_id` | your workflow's id, echoed in every callback. Also makes the start safe to retry (below) |
107
 
108
  The response is **202** with `{"cycle_id": "cyc_…", "run_id": "…", "areas", "skipped_areas", "package_id", "status", "waiting_for", "links": {"run", "excel", "report"}}`.
109
  The approval answer has the same shape plus `decision`.
110
 
111
+ **Starting is safe to retry.** A call that timed out or got no answer can be sent again. Astra does not start a second
112
+ cycle or run in these cases:
113
+
114
+ - **Same `Idempotency-Key` header** (optional, up to 200 characters, per client). Astra returns the cycle that key
115
+ made, whatever state it is in now.
116
+ - **Same `correlation_id`** from the same client while that cycle's run is still going (queued, running, or waiting
117
+ for an approval or a decision). Once that cycle has finished, failed, been interrupted or been cancelled, the same
118
+ `correlation_id` starts a new cycle. A workflow that sends the same id every week keeps working.
119
+
120
+ A repeated start gets the same **202** and the same body as the first call, plus the response header
121
+ `Idempotent-Replayed: true`. Astra saves the cycle as soon as it starts, and saves the start-testing decision as soon
122
+ as it is made, so a restart a few minutes later does not lose either one.
123
+
124
  ### Where a cycle is
125
 
126
+ `GET /cycles/{cycle_id}` returns the same shape. `waiting_for` is one of these exact strings (they do not change):
127
  - `"approval in Oracle Fusion (start testing)"`;
128
  - `"a person to decide the failures (in Patchwise)"`;
129
  - `null`.
 
137
 
138
  - Leaving out `scenario_ids` approves every scenario offered.
139
  - `"reject"` cancels the cycle; `comment` is kept.
140
+ - Astra records the actor as `Priya (Fusion QA) (in Oracle Fusion)`.
141
 
142
  ### Errors
143
 
 
151
  | 409 | the run is not waiting for that decision, or no Fusion environment exists |
152
  | 422 | a required field is missing |
153
 
154
+ ## 3. Callbacks (Astra → Fusion)
155
 
156
  Each OAuth client chooses how its events reach Fusion (**Agent Studio → OAuth clients → Delivery**).
157
 
158
+ ### Delivery semantics (all three modes)
159
+
160
+ - **At least once.** An event can arrive more than once: a retry after a lost answer, a pull event handed out again,
161
+ an admin sending a dead letter again, or an event made again after a restart restored an older saved state.
162
+ - **Stable ids.** Every event has a `delivery_id` (in the body, the `X-Patchwise-Delivery` header and the `deliveryId`
163
+ parameter). The same logical event always has the same id. Astra derives it from the cycle, the event type and how
164
+ many events of that type the cycle had before, so a copy made again after a restore keeps its id. Use
165
+ `delivery_id` to drop repeats.
166
+ - **Order.** Events of one cycle are queued in the order they happen. A `paused` event that was not delivered before a
167
+ newer event of its cycle is dropped (listed as `superseded`), so it never arrives after the cycle has moved on.
168
+ - **Dead letters.** An event that runs out of tries is kept as a **dead letter**: 6 sends for the URL and Fusion
169
+ modes, or 20 pickups without a confirmation in pull mode. Astra writes an audit entry
170
+ (`agent_studio.dead_letter`) and sends the admins one notification ("event(s) could not be delivered to Oracle
171
+ Fusion"). The event shows as `dead` under **Agent Studio → Callbacks**. An admin sends it again with **Send again**
172
+ (`POST /api/agent-studio/deliveries/{delivery_id}/requeue`); its tries start over with the same `delivery_id`. A
173
+ pull confirmation that arrives after the event became a dead letter still counts.
174
+
175
  ### Oracle Fusion directly (recommended; no relay)
176
 
177
+ Astra signs in to your OCI IAM identity domain with a confidential app (client credentials). The client secret is
178
+ write-only and kept in the vault; the token is held in memory only. Astra then starts the callback workflow:
179
  `POST {Fusion address}/api/fusion-ai/orchestrator/agent/v2/{workflow code}/invokeAsync`, by default
180
  `PATCH_TEST_CALLBACK_V3_7`.
181
 
 
207
  optional. The answer is `{events, count, more, confirm_within_s}`. Each event is the callback body below, plus
208
  `delivery_id` and `pickup` (how many times it was handed out).
209
  - **Confirm:** `POST /api/agent-studio/v1/events/ack` with `{"delivery_ids": ["dlv_…"]}`. A confirmed event is not
210
+ handed out again. Confirm every event you pick up, including types your workflow ignores (such as `paused`).
211
 
212
+ `POST /test-data/check` with `{"pickup": {"max": 1, "cycle_id": "cyc_…"}}` answers as `/events/claim`, and
213
+ `{"confirm": ["dlv_…"]}` answers as `/events/ack`, so a workflow can use its existing tool function.
214
+
215
+ An event that isn't confirmed within 5 minutes is handed out again, up to 20 times; after that it is a dead letter
216
+ (above). A client only sees and confirms its own events. To keep this mode on a server without saved state, add
217
+ `"delivery": "pull"` to the client in `FPT_SECRET_AGENT_STUDIO_BOOTSTRAP_CLIENTS`.
218
 
219
  ### Callback address (a relay or any receiver)
220
 
221
  Callbacks are sent with `POST` to the callback address, as `Content-Type: application/json`, with these headers:
222
 
223
  - `X-Patchwise-Event`: the event's name.
224
+ - `X-Patchwise-Delivery`: the event's stable id; use it to ignore duplicates.
225
  - `X-Patchwise-Signature: sha256=<hex>`: an HMAC-SHA256 of the **raw body** with the client's signing key.
226
 
227
  Answer with any 2xx code. Anything else, or no answer within 20 s, is retried after 1, 2, 4, 8 and 16 minutes (six
228
+ tries in all). Delivery state is listed under **Agent Studio → Callbacks**. A callback is never sent unsigned: if the
229
+ client's signing key is missing from the vault, Astra logs an error and does not send it. The try counts as failed,
230
+ with the error "no signing key …", so the event ends up as a dead letter an admin can send again once the key is
231
+ back.
232
 
233
  Every body has `event`, `delivery_id`, `sent_at`, `cycle_id`, `run_id`, `correlation_id` and `links`, plus:
234
 
235
  | Event | When | Extra fields |
236
  |---|---|---|
237
+ | `scripts_ready` | test scripts written, waiting for step 6 | `scenarios[]` (`id`, `title`, `area`, `priority`, `written_by`, `covers_patch_change`, `steps`), `count`, `approve_with`. `links.excel` is the test script |
238
+ | `failures_need_review` | some tests failed | `note`: a person decides each failure in Astra; `scenarios[]`, `count` |
239
+ | `results` | finished | `verdict` (`Ready` / `Not ready`), `areas[]` (`area`, `verdict`, `rule_result`, `counts`), `scenarios[]` |
240
+ | `stopped` | failed, cancelled or killed | `status`, `reason`, `resumable` (true for `failed`: an admin can resume the run, and the cycle then reports again) |
241
+ | `paused` | **optional, new.** A backend restart interrupted the run. It is not over: once an admin resumes it, the cycle goes on and sends its next events as usual | `status` (`interrupted`), `reason`, `resumable: true` |
242
  | `patch_update` | the release watch found new items (to the release watch address) | `release`, `count`, `changes[]` (`id`, `area`, `title`, `on_by_default`, `impact`, `action_to_enable`, `link`) |
243
 
244
+ `paused` is the only event type the existing callback workflows (up to V3.11) do not know. They can ignore it. An
245
+ interrupted run used to be reported as `stopped`, but it can be resumed, so it is now `paused`. Astra keeps watching a
246
+ cycle whose run failed or was interrupted, and reports again (`scripts_ready`, `failures_need_review`, `results` or
247
+ `stopped`) when the resumed run moves on. New optional fields such as `resumable` may appear in any event; ignore
248
+ fields you do not know.
249
+
250
  Verify a callback before using it:
251
 
252
  ```python
 
258
 
259
  ## 4. The release watch
260
 
261
+ Every 24 hours (setting `agent_studio_watch_hours`; 0 turns it off), Astra reads Oracle's What's New for each
262
  Fusion pod's release and for the areas in use. New items go to every client's release watch address as one
263
  `patch_update`. The Fusion release watch agent drafts the impact assessment and emails it. Admins can run a check at
264
  once with **Agent Studio → Release watch → Check now** (`POST /api/agent-studio/release-watch/check`).
 
277
 
278
  ## 6. Where the data lives
279
 
280
+ The backend is the same as Astra v1. Supabase Auth handles sign-in and registration. An encrypted snapshot of the
281
+ app's data (the SQLite database, which holds the `agent_*` tables, plus the vault with the signing keys and the token
282
+ key, reports and evidence) is saved to a private Supabase Storage bucket whenever the database changes, and restored
283
+ after a restart. A new client, a revoked client, a new cycle and a start-testing decision ask for a save at once.
284
  This Space uses **its own bucket, `patchwise-agent-studio`** (set in the Dockerfile), in the same Supabase project, so
285
  it never overwrites v1's saved state. It also has its own `FPT_STATE_KEY`.
286
 
287
  Space secrets to set:
288
  - `SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_KEY` (the same project as v1);
289
  - `FPT_SECRET_FRONTIER_API_KEY`;
290
+ - `FPT_SECRET_FUSION_USERNAME` and `FPT_SECRET_FUSION_PASSWORD` (User B);
291
+ - optionally `FPT_SECRET_AGENT_STUDIO_TOKEN_KEY`, so tokens stay valid even if the saved state is lost.
292
 
293
  ## 7. Security notes
294
 
295
+ - Client secrets are stored hashed. Signing keys and the token key are kept in the vault. Access tokens are signed,
296
+ not stored; tokens from before that change are stored hashed until they expire.
297
  - A token is for this API only: it cannot read runs or call any other `/api` route.
298
+ - Callbacks go only to the client's own HTTPS address, through the egress gate, and every one is audited. They are
299
+ never sent without a signature.
300
  - Rotate a client's credentials by creating a new client and revoking the old one.
docs/ARCHITECTURE.md CHANGED
@@ -1,64 +1,125 @@
1
  # Architecture
2
 
 
 
 
3
  ## Components
4
 
5
  ```mermaid
6
  flowchart LR
7
  U[Browser: consultant, QA approver, admin] -->|HTTPS, session cookie + CSRF header| API
8
- subgraph Container [One Docker image, non-root, tini]
 
9
  API[FastAPI app<br/>coworker/api] --> RM[Run manager<br/>api/runner.py, run_jobs queue]
10
  RM --> G[LangGraph workflow<br/>coworker/graph]
11
- G --> PW[Playwright executor<br/>automation/, adapters/playwright.py]
12
  G --> RR[QA rule C1-C6<br/>reports/generate_report.py, qa/audit.py]
13
  G --> TR[Triage<br/>triage/classifier.py]
14
- API --> DB[(SQLite: runs, events, users, sessions,<br/>pods, schedules, audit chain)]
15
- API --> V[(Vault: secrets/vault.json<br/>+ FPT_SECRET_* env)]
16
  SCH[Scheduler<br/>platform/scheduler.py] --> RM
 
17
  SYNC[State sync<br/>platform/statesync.py] --> DB
18
  MOCK[Practice pod<br/>mock-app :3100]
19
  end
20
  G -->|EgressGate| LLM[AI model<br/>llm/router.py]
21
- G -->|EgressGate: REST| FUS[Oracle Fusion test pod]
22
- PW -->|browser| FUS
23
- PW --> MOCK
24
- API -->|EgressGate| SB[Supabase: identity, encrypted backup]
25
- API -->|EgressGate, optional| H[Hermes assistant]
 
 
26
  ```
27
 
28
- ## A test run, step by step
 
 
 
 
 
 
 
 
 
 
 
 
 
29
 
30
- | Step | Node (`coworker/graph/nodes/`) | What happens |
31
  |---|---|---|
32
- | 1 | `research.scout` | Reads the pod; stops on a production pod. On a Fusion pod it first discovers which business areas the pod uses and samples their test data from the pod's own records (`platform/discovery.py`, docs/DISCOVERY.md) |
33
- | 2 | `research.*` | Reads what the patch changes; the AI model summarises (public or redacted data only) |
34
- | 3 | `design.*` | Chooses scenarios from the library (`tests/cases`), coverage maps (`analysis/`); AI may draft extra scenarios, which are dry-run |
35
- | 4 | `design.approval_gate` | Pauses; a consultant approves or skips each scenario (one answer per gate, atomic) |
36
- | 5 | `data.*` | Plans test data |
37
- | 6 | `execute.executor` | Runs Playwright in chunks; live view frames; retries a crashed attempt once |
38
- | 7 | `triage.*` | Classifies failures (UI change, data, timing, real defect) |
39
- | 8 | human review gate | A QA approver confirms real defects or waives |
40
- | 9 | `report.*` | Go / no-go by the QA rule, PDF/HTML/Excel; test data clean-up summary |
41
-
42
- The run manager persists queued jobs (`run_jobs`) so answers survive a restart; LangGraph checkpoints (SQLite) let a
43
- paused run continue. Temporal is an alternative orchestrator (`FPT_ORCHESTRATOR=temporal`) for long runs on a
44
- dedicated server.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
45
 
46
  ## Boundaries that matter
47
 
48
  - **Egress gate** (`platform/egress.py`): the only module that makes HTTP calls. It checks the kill switch, writes an
49
  audit record per call, pins each call to the configured host, and allows writes to Fusion only for seeding test
50
- data (with `SEED_ALLOWED=1`) and cancelling it.
51
- - **Vault** (`platform/vault.py`): secrets live in the environment (`FPT_SECRET_*`) or the encrypted vault file; API
52
- answers never contain them; child processes get a scrubbed environment (`platform/procs.child_env`).
53
- - **LLM router** (`llm/router.py`): client data never goes to an external model; only public or redacted payloads.
 
 
 
 
 
54
  - **QA rule**: the decision is computed by `reports/generate_report.py`, never by the AI.
55
 
56
  ## Data
57
 
58
- SQLite at `$FPT_HOME/fpt.sqlite`, migrations in `coworker/platform/migrations/*.sql` (forward-only, applied by
59
- `python -m coworker setup` at every start). Evidence (screenshots, videos, traces) encrypted under `$FPT_HOME/evidence`
60
- with retention. Without a persistent disk, the whole data folder is saved encrypted to Supabase Storage every 60 s and
61
- restored at boot.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
  ## Web app
64
 
 
1
  # Architecture
2
 
3
+ Astra is an AI QA co-worker that tests Oracle Fusion Cloud TEST pods. The running system is one container (a Hugging
4
+ Face Space), a remote browser runner for Fusion pods, and a storage bucket that holds an encrypted snapshot of the data.
5
+
6
  ## Components
7
 
8
  ```mermaid
9
  flowchart LR
10
  U[Browser: consultant, QA approver, admin] -->|HTTPS, session cookie + CSRF header| API
11
+ AS[Oracle Fusion AI Agent Studio<br/>workflows] -->|OAuth client: cycles, approval,<br/>pull of events| API
12
+ subgraph Container [One Docker image, non-root, tini: the Hugging Face Space]
13
  API[FastAPI app<br/>coworker/api] --> RM[Run manager<br/>api/runner.py, run_jobs queue]
14
  RM --> G[LangGraph workflow<br/>coworker/graph]
15
+ G --> PW[Playwright adapters<br/>adapters/playwright.py, adapters/remote_runner.py]
16
  G --> RR[QA rule C1-C6<br/>reports/generate_report.py, qa/audit.py]
17
  G --> TR[Triage<br/>triage/classifier.py]
18
+ API --> DB[(SQLite: runs, events, users, sessions,<br/>pods, schedules, Agent Studio cycles, audit chain)]
19
+ API --> V[(Vault: FPT_HOME/secrets/vault.json<br/>+ FPT_SECRET_* env)]
20
  SCH[Scheduler<br/>platform/scheduler.py] --> RM
21
+ COU[Courier<br/>platform/agent_studio.py] --> RM
22
  SYNC[State sync<br/>platform/statesync.py] --> DB
23
  MOCK[Practice pod<br/>mock-app :3100]
24
  end
25
  G -->|EgressGate| LLM[AI model<br/>llm/router.py]
26
+ G -->|EgressGate: REST, read-only| FUS[Oracle Fusion test pod]
27
+ PW -->|EgressGate: HTTPS + runner token| RUN[Remote runner<br/>automation/remote_runner/server.py<br/>behind Caddy]
28
+ RUN -->|browser| FUS
29
+ PW -->|local browser| MOCK
30
+ COU -->|EgressGate: signed callbacks, push mode| AS
31
+ SYNC -->|EgressGate: encrypted snapshot| BKT[(Bucket: OCI Object Storage<br/>or Supabase Storage)]
32
+ API -->|EgressGate| SB[Supabase: identity]
33
  ```
34
 
35
+ | Part | What it is | Code |
36
+ |---|---|---|
37
+ | API and web app | FastAPI serving the React app, the REST API, `/mcp`, `/a2a` and `/oauth/token` | `coworker/api` |
38
+ | Run manager | One worker thread; queued jobs are kept in `run_jobs` | `coworker/api/runner.py` |
39
+ | Workflow | LangGraph graph, one checkpoint per step (SQLite) | `coworker/graph` |
40
+ | Remote runner | Runs the browsers of Fusion test attempts and screen reads, one job at a time ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)) | `automation/remote_runner/server.py` |
41
+ | Agent Studio API and courier | Fusion workflows start test cycles and approve them; the courier sends or queues the cycle events and runs the release watch ([AGENT_STUDIO.md](AGENT_STUDIO.md)) | `coworker/platform/agent_studio.py`, `coworker/api/routes/agent_studio.py` |
42
+ | State sync | Saves an encrypted snapshot of `FPT_HOME` to the bucket and restores it at start | `coworker/platform/statesync.py`, `coworker/platform/ocistore.py` |
43
+
44
+ ## A Fusion test cycle, step by step
45
+
46
+ A cycle starts from the web app, a schedule, or Oracle AI Agent Studio (`POST /api/agent-studio/v1/cycles`; there the
47
+ depth defaults to `regression`, which is depth `full`). Nodes are in `coworker/graph/nodes/`; the graph is in
48
+ `coworker/graph/build.py`.
49
 
50
+ | Step | Node | What happens |
51
  |---|---|---|
52
+ | 1 | `scout` | Reads the pod; stops on a production pod. On a Fusion pod it finds which business areas the pod uses and samples their test data from the pod's own records (`platform/discovery.py`, [DISCOVERY.md](DISCOVERY.md)). Invoice lines are read from the business unit the tests use first, so the line account belongs to that unit's chart of accounts. |
53
+ | 2 | `research_module`, `synthesizer` | Reads Oracle's What's New for the pod's release, per area (public data), and ranks the release changes into the coverage view. |
54
+ | 3 | `test_generator` | Picks scenarios from the library (`tests/cases` and the approved ones in `FPT_HOME/library`; at depth `full`, every approved scenario of the areas). With an AI model configured it then designs new ones (`graph/nodes/ai_scenarios.py`), steps 3a to 3e. |
55
+ | 3a | | **Screen reading** of the areas whose screens are missing (never read, read on another release, or files gone), inside the run, on the runner. Each area's key business tasks (`platform/fusion_catalog.py` `key_tasks`) are read first. Live runs only. |
56
+ | 3b | | **AI scenarios** from the area's key screens, at most 3 per screen (`PER_SCREEN`). |
57
+ | 3c | | **End-to-end flows**: at depth `full`, one per business process of each area (at most `FPT_FUSION_REGRESSION_FLOWS`, default 3); and cross-area flows (Procure-to-Pay, Order-to-Cash, Record-to-Report) when the run tests all their areas. |
58
+ | 3d | | **Regression checks**: at depth `full`, one scenario per catalogue check (`fusion_catalog` `regression`) that no scenario covers yet, at most `FPT_FUSION_REGRESSION_CHECKS` (default 25) per area. |
59
+ | 3e | | **Dry run** of the AI scenarios on the pod, only when `FPT_FUSION_AI_DRY_RUN=1` (off by default). With it off, nothing runs on the pod before a person approves. |
60
+ | 4 | `approval_gate` | Pauses. A person approves or skips each scenario: in the app, or in Fusion for an Agent Studio cycle (`POST .../cycles/{id}/approval`). |
61
+ | 5 | `data_planner`, `data_executor` | Plans test data; seeds it only where allowed (`SEED_ALLOWED=1`). |
62
+ | 6 | `script_builder` | Turns the approved scenarios into Playwright specs. |
63
+ | 7 | `executor` | **Pre-flight** first (`platform/preflight.py`): the runner answers and has its scenario files, the test user signs in, every area has test data (a warning only). A failed check stops the run before any browser starts. Then one Playwright run per test user: each area signs in as its own user (`FPT_FUSION_AREA_USERS`), on the remote runner when `FPT_REMOTE_RUNNER_URL` is set. A browser-level failure (nothing ran) is tried once more. |
64
+ | 8 | `self_heal` | For a renamed control, proposes a new locator from the failure's ARIA snapshot and uses it for one retry only; the permanent fix needs a person. |
65
+ | 9 | `triage` | Classifies failures (UI change, data, timing, real defect). |
66
+ | 10 | `human_review`, `ticket` | A QA approver confirms real defects or waives them; confirmed defects become tickets. |
67
+ | 11 | `reporter`, `learner` | Go / no-go by the QA rule; HTML and PDF report; test data clean-up summary. The Excel test script is built on download; Agent Studio events carry a signed link that opens it without a login for 7 days (`platform/links.py`). |
68
+ | 12 | Courier | Sends each cycle's events (`scripts_ready`, `failures_need_review`, `results`, `stopped`, `patch_update`) by push (a signed POST, or straight to Fusion), or queues them for the Fusion workflow to pull. |
69
+
70
+ On the practice pod the same graph runs with the practice scenarios and a local browser.
71
+
72
+ The run manager keeps queued jobs (`run_jobs`), so a gate answer survives a restart. A run that was running when the
73
+ server stopped is marked "interrupted" and is resumed by hand. LangGraph checkpoints (SQLite) let a paused run continue.
74
+
75
+ The LangGraph path runs each attempt as one Playwright run (one per test user); it does not split it into chunks.
76
+
77
+ **Temporal** (`FPT_ORCHESTRATOR=temporal`, the Compose shape) runs the same nodes as activities and splits execution
78
+ into chunks of `exec_chunk_size` (10). Its execute activity (`coworker/workflows/activities.py`) supports the practice
79
+ pod only: it starts the local practice pod (`ensure_mock`) and has no remote runner, no per-area test users and no
80
+ pre-flight. **Fusion pods are not supported under Temporal today.**
81
 
82
  ## Boundaries that matter
83
 
84
  - **Egress gate** (`platform/egress.py`): the only module that makes HTTP calls. It checks the kill switch, writes an
85
  audit record per call, pins each call to the configured host, and allows writes to Fusion only for seeding test
86
+ data (with `SEED_ALLOWED=1`) and cancelling it. Calls to the runner, the bucket and Agent Studio go through it too.
87
+ - **Vault** (`platform/vault.py`): a plain JSON file, `FPT_HOME/secrets/vault.json` (file mode 600), plus
88
+ `FPT_SECRET_<NAME>` environment overrides. It is **not encrypted on disk**; it is encrypted only inside the state
89
+ snapshot. It holds `EVIDENCE_KEY`, the key of the evidence store. API answers never contain secrets; child processes
90
+ get a scrubbed environment (`platform/procs.child_env`).
91
+ - **LLM router** (`llm/router.py`): client data never goes to an external model. A request is public, or masked first:
92
+ values that look like client data are replaced by placeholders before the call and put back in the answer
93
+ (`platform/step_writer.py` `_call`, `platform/redaction.py`). A payload that still looks like client data is not sent
94
+ to the external model; the local model or the built-in fallback answers instead.
95
  - **QA rule**: the decision is computed by `reports/generate_report.py`, never by the AI.
96
 
97
  ## Data
98
 
99
+ SQLite at `$FPT_HOME/fpt.sqlite` and `checkpoints.sqlite`, migrations in `coworker/platform/migrations/*.sql`
100
+ (forward-only, applied by `python -m coworker setup` at every start). Evidence (screenshots, videos, traces) is
101
+ encrypted under `$FPT_HOME/evidence`, with retention.
102
+
103
+ The Space has no persistent disk. `platform/statesync.py` saves an encrypted snapshot (Fernet, `FPT_STATE_KEY`) of the
104
+ two databases and the `secrets`, `runs`, `evidence`, `tickets`, `screens` and `library` folders to a bucket, and
105
+ restores it at start when the data folder is empty.
106
+
107
+ | Store | Set by | Notes |
108
+ |---|---|---|
109
+ | OCI Object Storage | `OCI_STATE_PAR_URL`: a pre-authenticated request URL on one private bucket (`platform/ocistore.py`) | Used when set. |
110
+ | Supabase Storage | `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `SUPABASE_BUCKET` | Used when no OCI URL is set. |
111
+
112
+ When a save happens:
113
+
114
+ - **Periodically**, when the databases changed: checked every `FPT_STATE_SYNC_INTERVAL` seconds (default 60; at least
115
+ 300 on OCI, to stay inside the bucket's request budget; at least 10 on Supabase).
116
+ - **At once** on key events (`save_soon`): a screen read finished, a run waits for a person, a run ended, a run was
117
+ cancelled.
118
+ - **On shutdown**: a forced save.
119
+ - **On request**: `POST /api/storage/save` (administrator). Call it before every restart or deploy.
120
+
121
+ At start, a screen read that the snapshot shows as running is marked interrupted (`PodRegistry.recover_screens`). The
122
+ snapshot serves one instance: two instances on one bucket overwrite each other.
123
 
124
  ## Web app
125
 
docs/AUDIT.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # Patchwise: production audit
2
 
3
  Branch `production-hardening`, started from `trio-apple-ui` at `1c7e8c0` on 3 Nov 2026. Every finding below comes from
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [ARCHITECTURE.md](ARCHITECTURE.md), [DEPLOYMENT.md](DEPLOYMENT.md), [RUNBOOK.md](RUNBOOK.md), [REMOTE_RUNNER.md](REMOTE_RUNNER.md) and [SECURITY.md](SECURITY.md).
2
+
3
  # Patchwise: production audit
4
 
5
  Branch `production-hardening`, started from `trio-apple-ui` at `1c7e8c0` on 3 Nov 2026. Every finding below comes from
docs/DEPLOYMENT.md CHANGED
@@ -1,12 +1,12 @@
1
  # Deployment
2
 
3
- Two supported shapes. Both use the same image (`Dockerfile`: a web build stage, then a Python 3.13 runtime with Node
4
- 22 and Chromium, running as a non-root user under tini).
5
 
6
- | Shape | When | Guide |
7
  |---|---|---|
8
- | Customer cloud: Docker Compose with Caddy (HTTPS) and Temporal, data on volumes | a client deployment | [deploy/DEPLOY.md](../deploy/DEPLOY.md) |
9
- | Single container on a host without a disk (Hugging Face Space, Render), data saved to Supabase | demos, pilots | this page |
10
 
11
  ## Environments
12
 
@@ -19,49 +19,95 @@ Dev, staging and production differ only in settings, never in code:
19
  | `FPT_CORS_ORIGINS` | the Vite dev server | `[]` |
20
  | `FPT_API_DOCS` | `1` | `0` |
21
  | `FPT_REGISTRATION` / `FPT_REGISTER_ROLE` | as needed | `0`, or `viewer` |
22
- | `SUPABASE_BUCKET` | own bucket | one bucket per environment, never shared |
 
23
  | `FPT_ENVIRONMENT` | `development` | `staging` / `production` (labels error reports) |
24
 
25
- Use one Hugging Face Space (or Compose project) per environment. Promote by deploying the same commit.
26
 
27
  ## Hugging Face Space
28
 
29
  The repository root is the Space: `README.md` front matter sets `sdk: docker` and `app_port: 8800`, and the
30
  `Dockerfile` carries the Space settings (viewer sign-ups, trusted proxy, no CORS, docs off, public URL).
31
 
32
- 1. Space **variables**: `SUPABASE_URL`, `FRONTIER_BASE_URL`, `FRONTIER_MODEL`, `FPT_BROWSER_RUNS=1` (16 GB hardware),
33
- `FPT_BROWSER_SLOWMO_MS`, `FPT_FUSION_BASE_URL`, `FPT_ADMIN_EMAILS`.
34
- 2. Space **secrets**: `FPT_BOOTSTRAP_ADMIN_USER`, `FPT_BOOTSTRAP_ADMIN_PASSWORD`, `SUPABASE_ANON_KEY`,
35
- `SUPABASE_SERVICE_KEY`, `FPT_STATE_KEY`, `FPT_SECRET_FRONTIER_API_KEY`, `FPT_SECRET_FUSION_USERNAME`,
36
- `FPT_SECRET_FUSION_PASSWORD`, optionally `FPT_SECRET_METRICS_TOKEN`, `SENTRY_DSN`.
37
- (Variables are public on a public Space; anything secret must be a secret.)
38
- 3. Upload the repository contents (or push to the Space's git remote). The Space builds the image and starts it.
 
 
 
 
 
 
 
 
 
 
39
  4. Check: `https://<space>.hf.space/api/ready` answers `"ready": true`; sign in; Test environments > Test connection
40
  on the Fusion pod shows all three checks.
41
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
42
  **Rollback**: every upload is a commit in the Space repository. Re-upload the previous revision (or revert it in the
43
- Space's Files tab); the data is untouched because it lives in Supabase. This was done on 24 Oct 2026 (revision
44
- `1f5bc011`) and restored the working app in about 10 minutes.
45
 
46
  ## Database migrations
47
 
48
  SQL files in `coworker/platform/migrations/` are applied in order by `python -m coworker setup`, which the container
49
  runs at every start. They are forward-only and additive (new tables and columns). To roll back a release that added a
50
- migration: restore the backup taken before the upgrade (below), then deploy the previous image.
51
 
52
  ## Backups
53
 
54
- - **Host without a disk**: the data folder is encrypted and saved to Supabase Storage every 60 s
55
- (`state/latest.bin`), plus `state/previous.bin` from the start of each process. Status: Settings > Storage and
56
- backups, `/api/ready` (signed in) and the metric `trio_backup_ok`. Manual: `python -m coworker state push|status`.
57
- - **Compose**: `deploy/backup.sh /secure/backups` on a schedule (the archive contains the secrets vault: keep it encrypted).
58
- - Try a restore once per quarter (RUNBOOK "Restore").
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
59
 
60
  ## Reverse proxy and TLS
61
 
62
  The app listens on plain http (port 8800). Put it behind a proxy that terminates TLS: Caddy in Compose
63
- (`deploy/Caddyfile`), or the platform's proxy (Hugging Face, Render). Set `FPT_TRUST_PROXY=1` only when the app is
64
- reachable through that proxy alone, and `FPT_COOKIE_SECURE=always`.
65
 
66
  Production run command (what the container runs): `python -m coworker api --host 0.0.0.0 --port 8800`, after
67
  `python -m coworker state restore --soft` and `python -m coworker setup` (`deploy/entrypoint.sh`).
@@ -71,7 +117,8 @@ Production run command (what the container runs): `python -m coworker api --host
71
  | Workload | Memory | CPU |
72
  |---|---|---|
73
  | Quick simulations only | 512 MB (CI rehearses this limit) | 0.5 |
74
- | Full browser runs (Chromium) | 2 GB minimum, 4 GB comfortable; `shm_size: 1gb` | 2 |
 
75
 
76
  ## Notifications (webhook)
77
 
@@ -107,8 +154,8 @@ them.
107
 
108
  ## Notifications (Telegram)
109
 
110
- Patchwise can send the same notifications to a Telegram chat itself, with no relay in between. Each message names the
111
- coworker in bold, then the title and one sentence, with an **Open in Patchwise** button (only when `FPT_PUBLIC_URL` is
112
  set, because Telegram accepts https links only).
113
 
114
  1. In Telegram, open **@BotFather**, send `/newbot`, choose a name and a username. BotFather answers with the bot token.
@@ -116,7 +163,7 @@ set, because Telegram accepts https links only).
116
  file, a commit or a chat message. (The vault name `TELEGRAM_BOT_TOKEN` and `FPT_SECRET_TELEGRAM_BOT_TOKEN` also work.)
117
  Restart the Space.
118
  3. In Telegram, open your new bot and send `/start` (for a group: add the bot to the group and send a message there).
119
- 4. In Patchwise, open **Settings > Notifications > Find my chat**, pick the chat, and Patchwise sends a welcome message.
120
  5. Press **Send a test message**.
121
 
122
  - **Chat**: chosen in Settings (stored in the app's settings), or fixed with `FPT_TELEGRAM_CHAT_ID`, which wins.
@@ -152,7 +199,7 @@ With the bot token set, the app also reads what people send to the bot (long pol
152
  answers as the Ask page does. Full design in [CHANNELS.md](CHANNELS.md).
153
 
154
  **What each person does once to link their own chat:**
155
- 1. In Patchwise, open **Account > Telegram** and press **Get a link code**.
156
  2. In Telegram, send the bot `/link CODE` within 10 minutes.
157
 
158
  From then on they get the notifications about runs they may read, and can use `/status`, `/run Procure-to-Pay quick`, or plain questions. Starting a run or approving scenarios always needs a button press; sign-off and failure decisions stay in the app.
 
1
  # Deployment
2
 
3
+ One image (`Dockerfile`: a web build stage, then a Python 3.13 runtime with Node 22 and Chromium, running as a
4
+ non-root user under tini), two shapes:
5
 
6
+ | Shape | What it runs | Guide |
7
  |---|---|---|
8
+ | **Hugging Face Space** (Docker) + remote browser runner + storage bucket | The running system: Fusion cycles, Agent Studio, the practice pod. Data is saved as an encrypted snapshot to OCI Object Storage or Supabase Storage. | this page, [REMOTE_RUNNER.md](REMOTE_RUNNER.md) |
9
+ | Docker Compose with Caddy (HTTPS) and Temporal, data on volumes | The practice pod only. **Fusion pods do not run in this shape today**: the Temporal execute activity (`coworker/workflows/activities.py`) starts the local practice pod and has no remote runner, per-area test users or pre-flight. | [deploy/DEPLOY.md](../deploy/DEPLOY.md) |
10
 
11
  ## Environments
12
 
 
19
  | `FPT_CORS_ORIGINS` | the Vite dev server | `[]` |
20
  | `FPT_API_DOCS` | `1` | `0` |
21
  | `FPT_REGISTRATION` / `FPT_REGISTER_ROLE` | as needed | `0`, or `viewer` |
22
+ | `OCI_STATE_PAR_URL` or `SUPABASE_BUCKET` | own bucket | one bucket per environment, never shared |
23
+ | `FPT_REMOTE_RUNNER_URL` | none (local browser) | one runner per environment |
24
  | `FPT_ENVIRONMENT` | `development` | `staging` / `production` (labels error reports) |
25
 
26
+ Use one Space per environment. Promote by deploying the same commit.
27
 
28
  ## Hugging Face Space
29
 
30
  The repository root is the Space: `README.md` front matter sets `sdk: docker` and `app_port: 8800`, and the
31
  `Dockerfile` carries the Space settings (viewer sign-ups, trusted proxy, no CORS, docs off, public URL).
32
 
33
+ 1. Space **variables**:
34
+ - `FRONTIER_BASE_URL`, `FRONTIER_MODEL`, `FPT_ADMIN_EMAILS`, `SUPABASE_URL` (sign-in);
35
+ - `FPT_FUSION_BASE_URL`, `FPT_FUSION_NAME`, `FPT_FUSION_MODULES`, `FPT_FUSION_RELEASE`;
36
+ - `FPT_FUSION_AREA_USERS` (JSON, the test user per area, for example `{"PO": "prc_impl"}`; same password) and
37
+ `FPT_FUSION_WORKERS` (browsers at once on the runner, 1 to 4; default 3);
38
+ - `FPT_REMOTE_RUNNER_URL` (`https://<runner>`), `FPT_BROWSER_RUNS=1`, `FPT_BROWSER_SLOWMO_MS`.
39
+ 2. Space **secrets**:
40
+ - `FPT_BOOTSTRAP_ADMIN_USER`, `FPT_BOOTSTRAP_ADMIN_PASSWORD`;
41
+ - `FPT_STATE_KEY`, the snapshot key (required with OCI, which has no service key to derive one from);
42
+ - `OCI_STATE_PAR_URL`, the bucket's pre-authenticated request URL (or Supabase Storage, below);
43
+ - `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_KEY` (sign-in, and the Supabase store);
44
+ - `FPT_SECRET_FRONTIER_API_KEY`, `FPT_SECRET_FUSION_USERNAME`, `FPT_SECRET_FUSION_PASSWORD`,
45
+ `FPT_SECRET_REMOTE_RUNNER_TOKEN`;
46
+ - optionally `FPT_SECRET_METRICS_TOKEN`, `SENTRY_DSN`.
47
+
48
+ Variables are public on a public Space; anything secret must be a secret.
49
+ 3. Deploy (next section). The Space builds the image and starts it.
50
  4. Check: `https://<space>.hf.space/api/ready` answers `"ready": true`; sign in; Test environments > Test connection
51
  on the Fusion pod shows all three checks.
52
 
53
+ ### Every deploy or restart
54
+
55
+ A Space deploy or restart stops the container. A test run that is running is interrupted, and anything changed since
56
+ the last save is lost unless it is saved first.
57
+
58
+ 1. **Check that nothing is running.** In the app, Home and Test runs show no run in progress and no pod card shows
59
+ its screens being read. Or: `GET /api/runs?status=running` and `GET /api/runs?status=queued` return no items, and
60
+ the runner's `GET https://<runner>/healthz` shows `"busy": false`. Wait, or cancel, before going on.
61
+ 2. **Save the state** and wait for the answer: `POST /api/storage/save` (administrator). It answers
62
+ `{"saved", "last_saved_at", "bytes"}`; 502 when the save failed, 409 when this server does not save its state.
63
+ 3. **Deploy**: upload the repository contents, or push to the Space's git remote.
64
+ 4. **Update the runner** on the same commit: `deploy/runner/sync.sh <ssh target> <ssh key> https://<runner>`
65
+ ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)). Pre-flight stops a Fusion run when the runner has no scenario files.
66
+ 5. **Check**: `/api/ready`; Settings > Storage and backups shows a save after the start; the runner's `/healthz` shows
67
+ the deployed commit as `version` and `"cases": true`.
68
+
69
  **Rollback**: every upload is a commit in the Space repository. Re-upload the previous revision (or revert it in the
70
+ Space's Files tab), then run `sync.sh` on that commit. The data is untouched because it lives in the bucket.
 
71
 
72
  ## Database migrations
73
 
74
  SQL files in `coworker/platform/migrations/` are applied in order by `python -m coworker setup`, which the container
75
  runs at every start. They are forward-only and additive (new tables and columns). To roll back a release that added a
76
+ migration: restore the snapshot taken before the upgrade (RUNBOOK "Restore"), then deploy the previous image.
77
 
78
  ## Backups
79
 
80
+ **Space (no disk).** `platform/statesync.py` saves an encrypted archive of `FPT_HOME` (databases, vault, runs,
81
+ evidence, tickets, screens, library) as `state/latest.bin` in the bucket, with `state/meta.json` beside it.
82
+
83
+ | Store | Settings |
84
+ |---|---|
85
+ | OCI Object Storage | `OCI_STATE_PAR_URL`: a pre-authenticated request on one private bucket, access "read and write objects", listing denied (`https://objectstorage.<region>.oraclecloud.com/p/<token>/n/<namespace>/b/<bucket>/o/`). Used when set. `FPT_STATE_KEY` is required. |
86
+ | Supabase Storage | `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `SUPABASE_BUCKET`. The key is `FPT_STATE_KEY`, or is derived from the service key when that is not set. |
87
+
88
+ When it saves:
89
+
90
+ - every `FPT_STATE_SYNC_INTERVAL` seconds (default 60) when the databases changed; at least every 300 s on OCI (the
91
+ Always Free tier allows 50,000 requests a month), at least every 10 s on Supabase;
92
+ - at once when a screen read finishes, a run waits for a person, a run ends, or a run is cancelled;
93
+ - on shutdown (a forced save);
94
+ - on `POST /api/storage/save`, and with `python -m coworker state push`.
95
+
96
+ The first save of each process copies what the bucket held to `state/previous.bin`. An archive above 45 MB leaves out
97
+ the evidence, then the folders of finished runs. If the start-up restore fails, saving pauses so the good copy is not
98
+ overwritten. Status: Settings > Storage and backups, `/api/ready` (`saved_state`, signed in), the metric
99
+ `trio_backup_ok`, `python -m coworker state status`.
100
+
101
+ **Compose.** `deploy/backup.sh /secure/backups` on a schedule. The archive is not encrypted and contains the secrets
102
+ vault: encrypt it and restrict who can read it.
103
+
104
+ Try a restore once per quarter (RUNBOOK "Restore").
105
 
106
  ## Reverse proxy and TLS
107
 
108
  The app listens on plain http (port 8800). Put it behind a proxy that terminates TLS: Caddy in Compose
109
+ (`deploy/Caddyfile`), or the platform's proxy (Hugging Face). Set `FPT_TRUST_PROXY=1` only when the app is reachable
110
+ through that proxy alone, and `FPT_COOKIE_SECURE=always`.
111
 
112
  Production run command (what the container runs): `python -m coworker api --host 0.0.0.0 --port 8800`, after
113
  `python -m coworker state restore --soft` and `python -m coworker setup` (`deploy/entrypoint.sh`).
 
117
  | Workload | Memory | CPU |
118
  |---|---|---|
119
  | Quick simulations only | 512 MB (CI rehearses this limit) | 0.5 |
120
+ | Browser runs on the server itself (practice pod) | 2 GB minimum, 4 GB comfortable; `shm_size: 1gb` | 2 |
121
+ | Remote runner for Fusion pods, 3 to 4 browsers ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)) | 16 GB | 4 vCPU |
122
 
123
  ## Notifications (webhook)
124
 
 
154
 
155
  ## Notifications (Telegram)
156
 
157
+ Astra can send the same notifications to a Telegram chat itself, with no relay in between. Each message names the
158
+ coworker in bold, then the title and one sentence, with an **Open in Astra** button (only when `FPT_PUBLIC_URL` is
159
  set, because Telegram accepts https links only).
160
 
161
  1. In Telegram, open **@BotFather**, send `/newbot`, choose a name and a username. BotFather answers with the bot token.
 
163
  file, a commit or a chat message. (The vault name `TELEGRAM_BOT_TOKEN` and `FPT_SECRET_TELEGRAM_BOT_TOKEN` also work.)
164
  Restart the Space.
165
  3. In Telegram, open your new bot and send `/start` (for a group: add the bot to the group and send a message there).
166
+ 4. In Astra, open **Settings > Notifications > Find my chat**, pick the chat, and Astra sends a welcome message.
167
  5. Press **Send a test message**.
168
 
169
  - **Chat**: chosen in Settings (stored in the app's settings), or fixed with `FPT_TELEGRAM_CHAT_ID`, which wins.
 
199
  answers as the Ask page does. Full design in [CHANNELS.md](CHANNELS.md).
200
 
201
  **What each person does once to link their own chat:**
202
+ 1. In Astra, open **Account > Telegram** and press **Get a link code**.
203
  2. In Telegram, send the bot `/link CODE` within 10 minutes.
204
 
205
  From then on they get the notifications about runs they may read, and can use `/status`, `/run Procure-to-Pay quick`, or plain questions. Starting a run or approving scenarios always needs a button press; sign-off and failure decisions stay in the app.
docs/FINAL_REPORT.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # Final report: production hardening
2
 
3
  Branch `production-hardening` (from `trio-apple-ui` at `1c7e8c0`), 3 Nov 2026. Detail and evidence per item:
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [ARCHITECTURE.md](ARCHITECTURE.md), [DEPLOYMENT.md](DEPLOYMENT.md), [RUNBOOK.md](RUNBOOK.md), [REMOTE_RUNNER.md](REMOTE_RUNNER.md) and [SECURITY.md](SECURITY.md).
2
+
3
  # Final report: production hardening
4
 
5
  Branch `production-hardening` (from `trio-apple-ui` at `1c7e8c0`), 3 Nov 2026. Detail and evidence per item:
docs/FRONTEND_AUDIT.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # Frontend audit (Patchwise web app)
2
 
3
  Branch `frontend-polish`, base commit `84145a2`. Step 1 of the frontend-polish plan: findings only, no code changed.
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](ARCHITECTURE.md), [DEPLOYMENT.md](DEPLOYMENT.md), [RUNBOOK.md](RUNBOOK.md), [REMOTE_RUNNER.md](REMOTE_RUNNER.md) and [SECURITY.md](SECURITY.md).
2
+
3
  # Frontend audit (Patchwise web app)
4
 
5
  Branch `frontend-polish`, base commit `84145a2`. Step 1 of the frontend-polish plan: findings only, no code changed.
docs/QUALITY.md CHANGED
@@ -1,6 +1,25 @@
1
- # Web app quality gates
2
 
3
- **Audience:** anyone changing the web app (`web/`).
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
4
 
5
  All commands run in `web/`. The browser gates start their own backend and practice app on a fresh, throwaway data folder (`e2e/playwright.config.ts`). Before the first run you need:
6
  - the Python virtual environment in `architecture/.venv` (or a global `python`);
 
1
+ # Quality gates
2
 
3
+ **Audience:** anyone changing Astra. The backend and agent gates come first; the web app gates follow.
4
+
5
+ ## Backend and agent gates
6
+
7
+ A release goes out only when every gate below passes. The first one runs in CI on every push; the others need a
8
+ Fusion test pod and are checked by a person on the release candidate, before the deploy.
9
+
10
+ | Gate | Checks | Run | Where |
11
+ |---|---|---|---|
12
+ | Full test suite | Every backend test, with the browser in stub mode; ruff lint; `pip-audit` | `PLAYWRIGHT_MODE=stub python -m pytest coworker/tests triage/tests -q`, `ruff check coworker triage reports qa` | CI (`backend`) |
13
+ | Container self-test | The image starts, serves the app, the practice pod answers; `selftest` offline and `--live`; `deploy/smoke_run.py` quick and `--full` on the practice pod | `.github/workflows/image.yml` | CI (`image`, on `main`) |
14
+ | Scenario yield per area | For each business area of a live Fusion run, the AI wrote scenarios and they reached the gate. The run's events carry one line per area: "AP: the AI model wrote N scenario(s), offered for approval ..." (or "... M passed the dry run" with `FPT_FUSION_AI_DRY_RUN=1`). An area with 0, or with "no new scenario was written", fails the gate until the reason in that line is fixed. | A live run on the Fusion pod; `GET /api/runs/{id}/events` | Release candidate |
15
+ | Screen coverage of key tasks | The screens read for each area include its key business tasks (`platform/fusion_catalog.py` `key_tasks`, for example Create Invoice, Manage Invoices for AP). The pod card lists the screens read and the ones that failed; a key task missing there means the AI designs from the wrong screens. | Test environments > the pod > Read screens; the pod's `screens` state | Release candidate |
16
+ | Test data from the right business unit | The pod's sampled test data (Test environments) uses the business unit the tests run in, and the invoice line account comes from that unit's chart of accounts. Unit test: `test_discovery.py` `test_the_line_account_comes_from_the_tests_business_unit`. | Test environments > Discover on the pod, then read its test data | CI and release candidate |
17
+ | Live smoke run | On the release candidate, after `deploy/runner/sync.sh`: a short live run (depth `smoke`, real browser) on the Fusion pod through the runner. Pre-flight passes (runner version is the deployed commit, sign-in works, test data present), the scenarios run in the browser, triage and the report finish, and the Excel test script downloads. | Start a run from the app on the Fusion pod | Release candidate |
18
+
19
+ The suite covers the design rules behind these gates (`test_regression_checks.py`: key screens first, no screen taking more than
20
+ its share, catalogue regression checks asked at depth `full` within the cap), but only a live run shows the yield on a real pod.
21
+
22
+ ## Web app gates
23
 
24
  All commands run in `web/`. The browser gates start their own backend and practice app on a fresh, throwaway data folder (`e2e/playwright.config.ts`). Before the first run you need:
25
  - the Python virtual environment in `architecture/.venv` (or a global `python`);
docs/REMOTE_RUNNER.md CHANGED
@@ -1,83 +1,141 @@
1
  # Remote browser runner
2
 
3
- Use the remote runner when the Patchwise server's network is refused by Oracle's edge. For example, Hugging Face Spaces
4
- get "Access Denied" from Akamai on Oracle demo pods. With the runner, the browser part of runs on an Oracle Fusion pod
5
- happens on another host. Everything else stays where it is: approvals, AI agents, triage, reports and evidence.
6
-
7
- - **Server side:** `coworker/adapters/remote_runner.py`, wired in `coworker/graph/nodes/execute.py` (`run_planned`) and
8
- `coworker/adapters/screens.py` (`explore`, `capture`).
9
- - **Runner side:** `automation/remote_runner/server.py` (standard library only).
10
- - **Scope:** everything that opens a browser on a Fusion pod goes to the runner:
11
- - test attempts (`playwright.fusion.config.ts`);
12
- - reading the pod's screens before scenarios are written (the explorer and single-screen capture).
13
-
14
- The practice pod and stub runs stay local.
15
-
16
- ## Reading screens on the runner
17
-
18
- `POST /v1/screens` takes:
19
-
20
- - `kind`: `explore` (with the explorer's `plan`) or `capture` (with a `task` such as "Payables > Invoices > Create
21
- Invoice");
22
- - `env`: the pod's address and test user only.
23
-
24
- It shares the one-browser lock with the attempts, and is polled and cancelled the same way. The poll takes
25
- `?since=<line>` to return the newest log lines, so the pod card shows the progress. The bundle holds the log and the
26
- `out/` files: the inventories (`<slug>.json`, Oracle's labels only) and the list choices (`<slug>.values`). Patchwise
27
- puts them in the pod's screens folder and checks them with the same privacy rule as a local read.
28
-
29
- ## How it works
30
-
31
- 1. **The attempt is sent.** Patchwise posts it through the egress gate (https, the runner's host only) to
32
- `POST /v1/attempts`. The body holds:
33
- - the case ids and the Playwright config;
34
- - the pod environment (address, test user, test data);
35
- - AI-written draft specs and approved library specs;
36
- - locator overrides from self-heal.
37
-
38
- The audit log records the ids and the config, never the password.
39
- 2. **It is polled.** Patchwise asks `GET /v1/attempts/{id}` every few seconds. The emergency stop cancels the attempt
40
- on the runner.
41
- 3. **The results come back.** `GET /v1/attempts/{id}/bundle` returns one zip with:
42
- - the Playwright JSON report, with attachment paths relative to the run directory;
43
- - the run directory (screenshots, videos, traces);
44
- - the pod values tried;
45
- - the ledger of created test records;
46
- - the log.
47
-
48
- Patchwise unpacks it where a local attempt leaves its files, so evidence, triage, clean-up and reports work unchanged.
49
-
50
- **The runner's safeguards:**
51
-
52
- - It runs one attempt at a time.
53
- - Every call needs `Authorization: Bearer <RUNNER_TOKEN>`, compared in constant time.
54
- - It accepts only known environment keys, the Patchwise configs, plain case ids and plain spec names.
55
- - It never ships the Fusion session cookies.
56
- - It deletes finished attempts after 24 hours.
57
- - The password exists only in the Playwright process's environment, never on disk.
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
58
 
59
  ## Set up a runner (Ubuntu 22.04)
60
 
61
- **1. Install the tools and the test suite.** Install Node 22 and Python 3, then copy the same version of the code that
62
- the Patchwise server runs:
63
 
64
- ```bash
65
- git archive main automation tests | tar -x -C ~/pw # from the repository
66
- cd ~/pw/automation && npm ci && npx playwright install --with-deps chromium
67
- ```
68
-
69
- **2. Store the token.** It needs at least 24 random characters. Keep it in a root-only file, `/etc/patchwise/runner.env`:
70
 
71
  ```
72
  RUNNER_TOKEN=<random>
73
- AUTOMATION_DIR=/home/ubuntu/pw/automation
74
  RUNNER_HOME=/home/ubuntu/runner-data
75
  ```
76
 
77
- **3. Run the service.** It listens on `127.0.0.1:8899`. Use a systemd unit with `User=ubuntu`, the environment file,
78
- `ExecStart=/usr/bin/python3 -I /home/ubuntu/pw/automation/remote_runner/server.py` and `Restart=always`.
 
 
 
 
79
 
80
- **4. Put HTTPS in front.** Caddy can serve a real certificate for an IP using `<ip-with-dashes>.sslip.io`:
81
 
82
  ```
83
  129-225-117-95.sslip.io {
@@ -87,12 +145,47 @@ RUNNER_HOME=/home/ubuntu/runner-data
87
 
88
  Open ports 80 and 443 in the cloud firewall. On Oracle's Ubuntu images, also open them in iptables.
89
 
90
- **5. Point the Patchwise server at the runner.** Set:
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
 
92
- - `FPT_REMOTE_RUNNER_URL=https://<host>`, as an environment variable;
93
- - `FPT_SECRET_REMOTE_RUNNER_TOKEN=<the token>`, as a secret.
94
 
95
- Remove `FPT_REMOTE_RUNNER_URL` to run browsers on the server itself again.
 
 
 
96
 
97
- The first runner is the OCI Always Free AMD Micro VM `patchwise-watcher` (1 GB RAM plus 2 GB swap): enough for one
98
- browser. Keep `FPT_FUSION_WORKERS=1` there.
 
1
  # Remote browser runner
2
 
3
+ Astra runs on a Hugging Face Space, and Oracle's edge (Akamai) answers "Access Denied" to the Space's network on
4
+ Oracle demo pods. So the browsers that test or read an Oracle Fusion pod run on another host: the remote runner.
5
+ Everything else stays on the Space: approvals, AI agents, triage, reports and evidence.
6
+
7
+ - **Server side:** `coworker/adapters/remote_runner.py`, used by `coworker/graph/nodes/execute.py` (`run_planned`) and
8
+ `coworker/adapters/screens.py` (`explore`, `capture`); pre-flight in `coworker/platform/preflight.py`.
9
+ - **Runner side:** `automation/remote_runner/server.py` (Python standard library only), behind Caddy for HTTPS.
10
+ - **Switched on by** `FPT_REMOTE_RUNNER_URL=https://<runner>` and the token in the vault as `remote_runner.token`
11
+ (`FPT_SECRET_REMOTE_RUNNER_TOKEN`). Remove the URL to run browsers on the server itself again.
12
+
13
+ ## What runs on the runner
14
+
15
+ | Job | Sent as | When |
16
+ |---|---|---|
17
+ | Test attempts on a Fusion pod (`playwright.fusion.config.ts`) | `POST /v1/attempts` | The executor step; one attempt per test user when areas sign in as different users (`FPT_FUSION_AREA_USERS`) |
18
+ | Screen reading: the explorer (`explore`, with the explorer's plan) and one screen (`capture`, a task such as "Payables > Invoices > Create Invoice") | `POST /v1/screens` | In a run, before the AI designs scenarios; in the background after discovery; Read screens on the pod's card |
19
+
20
+ The practice pod and quick simulations stay on the server.
21
+
22
+ The AI dry run (`FPT_FUSION_AI_DRY_RUN=1`, off by default) does **not** use the runner: `graph/nodes/ai_scenarios.py`
23
+ `dry_run` starts the browser on the Astra server itself. On a Space whose network Oracle's edge refuses, that dry run
24
+ fails. Keep it off while Fusion browsers need the runner.
25
+
26
+ ## One job at a time
27
+
28
+ The runner holds one lock for every job: attempts and screen reads share it. A second job while one is running gets
29
+ **HTTP 409** ("another attempt is running on this runner"). Astra does not wait or queue on a 409:
30
+
31
+ - a test run fails with "the remote browser runner refused the attempt (HTTP 409 ...)"; resume it when the runner is free;
32
+ - a screen read fails with the same reason on the pod's card; read the screens again.
33
+
34
+ The usual cause is a background screen read (after discovery, or a release change) overlapping a run. Check
35
+ `/healthz` (`busy`) before starting work by hand.
36
+
37
+ Within one job, `FPT_FUSION_WORKERS` (set on the Astra server, sent with each attempt; 1 to 4, default 3) is how many
38
+ browsers run at once.
39
+
40
+ ## Long runs, restarts and a busy runner
41
+
42
+ - **Each pass has a time budget for its size.** An attempt runs in passes of at most `FPT_FUSION_CHUNK_SCENARIOS`
43
+ scenarios (default 24). Each pass gets `FPT_FUSION_SCENARIO_MINUTES` (default 12) per scenario a worker runs, plus 10
44
+ minutes of start-up, kept between `FPT_FUSION_ATTEMPT_MIN_MINUTES` (30) and `FPT_FUSION_ATTEMPT_MAX_MINUTES` (240).
45
+ A pass that runs out of time is first asked to stop, so Playwright still writes its report; one that writes none
46
+ loses only its own scenarios, which are recorded as timed out and run again in the retry.
47
+ - **A restart of the Astra server does not lose the pass.** The runner job's id is kept in the run folder
48
+ (`remote-job.json`) while it runs. Resume the run: it follows the same job and collects its results. Finished passes
49
+ are kept. Cancelling the run instead stops the job and keeps the ledger of test records it made, for the clean-up.
50
+ - **A restart of the runner fails the pass in seconds.** The runner keeps each job's state in its folder (`job.json`). A
51
+ job that was running when it restarted is reported `lost`, and an older runner answers 404. Astra stops waiting at
52
+ once and says so.
53
+ - **A busy runner is waited for.** The runner takes one job at a time. A run or screen read that finds it busy waits up
54
+ to `FPT_REMOTE_RUNNER_BUSY_WAIT_MINUTES` (default 15) and notes it in the run's activity. Pre-flight reports a busy
55
+ runner as information, not as a failure.
56
+ - **Pre-flight compares versions.** When this server knows its commit (`FPT_COMMIT`, or a `VERSION` file at the repo
57
+ root), a runner on another commit fails pre-flight: run `deploy/runner/sync.sh` on the deployed commit.
58
+
59
+ ## How an attempt works
60
+
61
+ 1. **Sent.** Astra posts it through the egress gate (https, the runner's host only) to `POST /v1/attempts`. The body
62
+ holds the case ids and the Playwright config; the pod environment (address, test user and password, test data);
63
+ AI-written draft specs, approved library specs and their step files; locator overrides from self-heal. The audit
64
+ log records the ids and the config, never the password.
65
+ 2. **Polled.** Astra asks `GET /v1/attempts/{id}` every few seconds (every 2 s with the Live panel, which also pulls
66
+ `/v1/attempts/{id}/live` frames). The emergency stop cancels the job on the runner (`POST .../cancel`).
67
+ 3. **Collected.** `GET /v1/attempts/{id}/bundle` returns one zip: the Playwright JSON report (attachment paths
68
+ relative to the run directory), the run directory (screenshots, videos, traces, without the Fusion session file),
69
+ the pod values tried, the ledger of created test records, and the log. Astra unpacks it where a local attempt
70
+ leaves its files, so evidence, triage, clean-up and reports work unchanged.
71
+
72
+ A screen read works the same way through `POST /v1/screens`. Its poll takes `?since=<line>` and returns the newest log
73
+ lines for the pod card's progress. The bundle holds the log and the `out/` files: the inventories (`<slug>.json`,
74
+ Oracle's labels only) and the list choices (`<slug>.values`). Astra checks them with the same privacy rule as a local
75
+ read.
76
+
77
+ ## Jobs live in memory
78
+
79
+ The runner keeps its job table in memory. After a runner restart it no longer knows the jobs it was running: their
80
+ polls get 404, and Astra waits until the job's deadline (an attempt: its timeout plus 5 minutes) before failing the
81
+ run. Do not restart the runner while `/healthz` shows `"busy": true`; `sync.sh` refuses to.
82
+
83
+ ## Data on the runner
84
+
85
+ Each job has a folder, `RUNNER_HOME/job_<id>`, with the specs, the log, the report, screenshots, videos and traces.
86
+ These files are **not encrypted** on the runner. They are deleted `RUNNER_KEEP_HOURS` (default 24) after the job
87
+ started, by a sweep every 10 minutes. Folders left from before a runner restart are swept by their age on disk.
88
+
89
+ The Fusion sign-in session file is written in the run directory and removed by Playwright's teardown; it is never
90
+ put in the bundle. A job that was killed may leave it in its folder until the sweep.
91
+
92
+ ## Safeguards
93
+
94
+ - One job at a time (see above).
95
+ - Every call except `/healthz` needs `Authorization: Bearer <RUNNER_TOKEN>`, compared in constant time. The service
96
+ refuses to start without a token of at least 24 characters.
97
+ - Only known environment keys, the two Astra Playwright configs, plain case ids and plain spec names are accepted;
98
+ bodies are limited to 20 MB.
99
+ - The service listens on `127.0.0.1` only; Caddy serves HTTPS in front.
100
+ - The Fusion password is passed in the Playwright process's environment, not written to disk by the runner.
101
+ - The runner's token is never passed to the Playwright process.
102
+
103
+ ## `/healthz`
104
+
105
+ `GET /healthz` needs no token and returns:
106
+
107
+ | Field | Meaning |
108
+ |---|---|
109
+ | `ok` | The service has a token. |
110
+ | `busy` | A job holds the lock. |
111
+ | `automation` | `AUTOMATION_DIR` exists. |
112
+ | `cases` | The scenario files the step specs read (`tests/cases`, next to `automation/`) are there. |
113
+ | `version` | The commit `sync.sh` installed (the `VERSION` file), or `unknown`. |
114
+
115
+ Pre-flight reads it before every Fusion browser run: a runner that does not answer, has no token or no test code, or
116
+ has no scenario files stops the run before any browser starts.
117
 
118
  ## Set up a runner (Ubuntu 22.04)
119
 
120
+ **1. Tools.** Install Node 22, Python 3, and Caddy.
 
121
 
122
+ **2. Token and settings.** The token needs at least 24 random characters. Keep it in a root-only environment file,
123
+ for example `/etc/astra/runner.env`:
 
 
 
 
124
 
125
  ```
126
  RUNNER_TOKEN=<random>
127
+ AUTOMATION_DIR=/home/ubuntu/astra/automation
128
  RUNNER_HOME=/home/ubuntu/runner-data
129
  ```
130
 
131
+ Optional: `RUNNER_PORT` (default 8899), `RUNNER_KEEP_HOURS` (default 24).
132
+
133
+ **3. Service.** A systemd unit named `astra-runner` (the name `sync.sh` restarts; another name goes in
134
+ `RUNNER_SERVICE`), with `User=ubuntu`, `EnvironmentFile=/etc/astra/runner.env`,
135
+ `ExecStart=/usr/bin/python3 -I /home/ubuntu/astra/automation/remote_runner/server.py` and `Restart=always`. The
136
+ `ubuntu` user needs `sudo systemctl restart astra-runner` without a password, for `sync.sh`.
137
 
138
+ **4. HTTPS.** Caddy can serve a real certificate for an IP through `<ip-with-dashes>.sslip.io`:
139
 
140
  ```
141
  129-225-117-95.sslip.io {
 
145
 
146
  Open ports 80 and 443 in the cloud firewall. On Oracle's Ubuntu images, also open them in iptables.
147
 
148
+ **5. Install the code** with `sync.sh` from the repository (next section). The first time, also install the
149
+ browser's system libraries once: `cd ~/astra/automation && sudo npx playwright install-deps chromium`.
150
+
151
+ **6. Point Astra at the runner.** On the Space: `FPT_REMOTE_RUNNER_URL=https://<host>` (variable) and
152
+ `FPT_SECRET_REMOTE_RUNNER_TOKEN=<the token>` (secret). Restart (save first: RUNBOOK).
153
+
154
+ ## Update the runner: `deploy/runner/sync.sh`
155
+
156
+ Run it after **every** Astra deploy, from the repository, on the commit that was deployed:
157
+
158
+ ```bash
159
+ deploy/runner/sync.sh ubuntu@<runner> ~/.ssh/<runner key> https://<runner>
160
+ ```
161
+
162
+ What it does:
163
+
164
+ 1. Refuses when `automation/` or `tests/` has uncommitted changes, and when the runner's `/healthz` shows
165
+ `"busy": true` (exit 2).
166
+ 2. Packs the committed `automation/` and `tests/` (`git archive HEAD`) and unpacks them in `~/astra.new` on the
167
+ runner, with the commit in `VERSION`.
168
+ 3. Reuses `node_modules` when `package-lock.json` did not change, else runs `npm ci`; then installs Chromium.
169
+ 4. Checks `/healthz` again: a job that started during the install means nothing is switched (exit 2).
170
+ 5. Moves `~/astra` to `~/astra.prev`, puts the new copy in place, restarts the service.
171
+ 6. Verifies that `/healthz` reports the new commit as `version` and `"cases": true` (exit 3 otherwise: check the
172
+ service's `AUTOMATION_DIR`), and prints `/healthz` from outside when the URL is given.
173
+
174
+ To roll back, run it on the previous commit.
175
+
176
+ ## A PC as the runner
177
+
178
+ `deploy/pc-runner/start-pc-runner.ps1` runs the runner on a Windows PC (port 8898) and opens an SSH tunnel to the
179
+ runner VM, so the VM's port 8898 leads to the PC. The VM's Caddy must be set to send to port 8898 first while it
180
+ answers and to fall back to its own runner on 8899; that Caddy configuration is not in the repository. The PC runs
181
+ the repository's own `automation/`, so it is not updated by `sync.sh` and its `version` is `unknown`.
182
 
183
+ ## Sizing
 
184
 
185
+ | Host | Fits |
186
+ |---|---|
187
+ | 4 vCPU, 16 GB RAM | 3 to 4 browsers at once (`FPT_FUSION_WORKERS=3` or `4`): regression runs and screen reading of several areas. |
188
+ | 1 GB RAM (plus swap), for example an OCI Always Free AMD Micro | One browser for a short run, at best (`FPT_FUSION_WORKERS=1` on the Astra server). **Not enough for regression runs.** |
189
 
190
+ `FPT_FUSION_WORKERS` is a setting of the Astra server and applies to every Fusion run; lower it there when the runner
191
+ is small.
docs/RUNBOOK.md CHANGED
@@ -1,21 +1,40 @@
1
  # Runbook
2
 
3
- Commands are for the container (`docker compose exec app ...` in Compose; the Space's terminal or a local run
4
- otherwise). `python -m coworker <command>` is the CLI.
5
 
6
  ## Daily checks
7
 
8
  1. `/api/ready` answers `"ready": true`.
9
- 2. Settings > Storage and backups shows "Backups are working" (hosts without a disk).
10
- 3. Home: nothing unexpectedly "Waiting for you"; Settings > Schedules: no "The last start failed".
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
11
 
12
  ## Incidents
13
 
14
  | Symptom | What to do |
15
  |---|---|
16
  | The app does not start; log says `error parsing value for field "X"` | Fix setting X (the message names it); restart. |
17
- | `/api/ready` is 503, `worker: false` | Restart the app. Runs that were running become "interrupted": open each and press Resume. |
18
- | A run failed with "The test browser stopped unexpectedly" | The server ran out of memory. Run fewer business areas at once, or give the server more memory. |
 
 
 
19
  | A run says "N test invoices were left on the Oracle Fusion pod" | The automatic clean-up could not reach Fusion. Cancel those invoice numbers in Fusion (Payables > Manage Invoices). |
20
  | Test connection fails at "Sign-in" (HTTP 401) | The Fusion test user's password changed or the account is locked: fix it in Fusion, then Test environments > Sign-in details. Too many failed sign-ins lock Fusion users: do not retry in a loop. |
21
  | A schedule switched itself off | It failed 3 times in a row; the reason is on the schedule. Fix the cause and switch it on again. |
@@ -26,34 +45,60 @@ otherwise). `python -m coworker <command>` is the CLI.
26
 
27
  ## Backups
28
 
29
- **Host without a disk (Supabase).** The app saves `state/latest.bin` every 60 s and keeps `state/previous.bin` from
30
- the start of the current process. If a start-up restore fails, saving pauses (a notice in the app and
31
- `saved_state.paused` on `/api/ready`) so the good copy is not overwritten.
 
 
 
 
 
32
 
33
- - Status: `python -m coworker state status`
34
- - Save now: `python -m coworker state push`
35
- - **Restore**: stop the app; in the Supabase bucket copy `state/previous.bin` over `state/latest.bin` if the latest
36
- copy is bad; start the app with an empty data folder (a new container), which restores at start.
 
 
 
 
 
 
 
 
 
 
 
 
 
37
 
38
  **Compose.** `deploy/backup.sh /secure/backups`. Restore: stop the stack, put the archive's files back in the
39
- `fpt-data` volume, start the stack. Keep backup archives encrypted: they contain the secrets vault.
40
 
41
  ## Upgrade and rollback
42
 
43
- 1. Take a backup (above).
44
  2. Deploy the new image or upload the new revision. Migrations run at start (forward-only).
45
- 3. Smoke test: sign in, Test environments > Test connection, start a quick simulation and approve it.
46
- 4. Rollback: deploy the previous image or Space revision; if the release added a migration, restore the backup first.
 
 
47
 
48
  ## Rotating secrets
49
 
50
- Change the value in the platform's secret store, then restart. Revoke the old key at its provider (NVIDIA,
51
- Hugging Face, Supabase). For the Fusion test user, change the password in Fusion first.
52
- `FPT_STATE_KEY` is special: the backup is encrypted with it. To change it, take `state push` with the old key, set the
53
- new key, restart, and confirm a new save; keep the old key until the new backup is confirmed.
 
 
 
 
 
54
 
55
  ## Retention
56
 
57
  Screenshots, videos and traces: `EVIDENCE_RETENTION_DAYS` (30). Workflow checkpoints of finished runs:
58
  `CHECKPOINT_RETENTION_DAYS` (7). Run folders: `RUN_FILES_RETENTION_DAYS` (90). Run records and the audit log are
59
- kept. The clean-up runs daily from the scheduler; `python -m coworker purge` runs it now.
 
 
1
  # Runbook
2
 
3
+ Commands are for the container (the Space's terminal, `docker compose exec app ...` in Compose, or a local run).
4
+ `python -m coworker <command>` is the CLI.
5
 
6
  ## Daily checks
7
 
8
  1. `/api/ready` answers `"ready": true`.
9
+ 2. Settings > Storage and backups shows "Backups are working" and a recent save (hosts without a disk).
10
+ 3. The runner's `https://<runner>/healthz` answers `"ok": true`, `"automation": true`, `"cases": true`, and the
11
+ `version` is the commit the Space runs.
12
+ 4. Home: nothing unexpectedly "Waiting for you"; Settings > Schedules: no "The last start failed".
13
+
14
+ ## Before every deploy or restart
15
+
16
+ A deploy or restart of the Space interrupts a running test run and loses anything not saved yet. Check right before,
17
+ not an hour before.
18
+
19
+ 1. **No active work.** No run is running or queued (`GET /api/runs?status=running`, `?status=queued`), no pod is
20
+ reading its screens, and the runner's `/healthz` shows `"busy": false`. Wait for it to end, or cancel it.
21
+ 2. **Save.** `POST /api/storage/save` as an administrator, and wait for the answer (`saved`, `last_saved_at`). 502 means
22
+ the save failed: do not restart until it works. From the Space's terminal: `python -m coworker state push`.
23
+ 3. **Deploy or restart.**
24
+ 4. **Update the runner** on the commit just deployed: `deploy/runner/sync.sh <ssh target> <ssh key> https://<runner>`.
25
+ It refuses while the runner is busy (exit 2); run it again when the run ends.
26
+ 5. **Smoke test**: sign in, Test environments > Test connection, then a quick run on the Fusion pod.
27
 
28
  ## Incidents
29
 
30
  | Symptom | What to do |
31
  |---|---|
32
  | The app does not start; log says `error parsing value for field "X"` | Fix setting X (the message names it); restart. |
33
+ | `/api/ready` is 503, `worker: false` | Restart the app (save first, above). Runs that were running become "interrupted": open each and press Resume. |
34
+ | A pod card says "interrupted by a server restart: read the screens again" | The restart cut off a screen read. Press Read screens on the pod's card, or let the next run read them. |
35
+ | A run stopped with "Pre-flight check failed, no browser was started" | Read the reason: the runner does not answer or has no scenario files (run `sync.sh`), or the test user cannot sign in. |
36
+ | A run or screen read failed with "the remote browser runner refused ... (HTTP 409 ...)" | The runner was busy with another job (one at a time). Resume the run, or read the screens again, when `/healthz` shows `"busy": false`. |
37
+ | A run failed with "The test browser stopped unexpectedly" | The browser host ran out of memory. Lower `FPT_FUSION_WORKERS`, run fewer areas at once, or give the runner more memory (REMOTE_RUNNER.md "Sizing"). |
38
  | A run says "N test invoices were left on the Oracle Fusion pod" | The automatic clean-up could not reach Fusion. Cancel those invoice numbers in Fusion (Payables > Manage Invoices). |
39
  | Test connection fails at "Sign-in" (HTTP 401) | The Fusion test user's password changed or the account is locked: fix it in Fusion, then Test environments > Sign-in details. Too many failed sign-ins lock Fusion users: do not retry in a loop. |
40
  | A schedule switched itself off | It failed 3 times in a row; the reason is on the schedule. Fix the cause and switch it on again. |
 
45
 
46
  ## Backups
47
 
48
+ **Host without a disk.** The app saves `state/latest.bin` to the bucket (OCI Object Storage when `OCI_STATE_PAR_URL` is
49
+ set, else Supabase Storage): when the data changed, at most every `FPT_STATE_SYNC_INTERVAL` seconds (at least 300 on
50
+ OCI); at once when a screen read finishes or a run waits for a person, ends or is cancelled; and on shutdown. The first
51
+ save of each process keeps the archive it found as `state/previous.bin`. If a start-up restore fails, saving pauses
52
+ (a notice in the app and `saved_state.paused` on `/api/ready`) so the good copy is not overwritten.
53
+
54
+ - Status: `python -m coworker state status` (prints `state/meta.json`: when, how big, why, what was left out)
55
+ - Save now: `POST /api/storage/save`, or `python -m coworker state push`
56
 
57
+ ### Restore
58
+
59
+ The app restores at start when its data folder is empty, so a restore is: put the right archive in place as
60
+ `state/latest.bin`, then start a new container (a Space restart or a new deploy starts empty).
61
+
62
+ 1. Stop the app (pause the Space) so it cannot save over the archive you are about to put back.
63
+ 2. If the latest copy is bad, put `state/previous.bin` in place of `state/latest.bin`:
64
+ - **OCI Object Storage**: in the OCI console, open the bucket, download `state/previous.bin` and upload it as
65
+ `state/latest.bin`. Or with the pre-authenticated URL (keep it out of shell history and logs):
66
+ `curl -fsS -o previous.bin "$OCI_STATE_PAR_URL"state/previous.bin`, then
67
+ `curl -fsS -X PUT --data-binary @previous.bin "$OCI_STATE_PAR_URL"state/latest.bin`.
68
+ - **Supabase Storage**: in the Supabase dashboard, Storage > the bucket > `state/`: download `previous.bin` and
69
+ upload it as `latest.bin` (replace).
70
+ 3. Start the app. Check the log line `state restored from the OCI bucket` (or `from Supabase Storage`), then sign in
71
+ and open a recent run.
72
+ 4. If it says "the state archive cannot be decrypted with this key", `FPT_STATE_KEY` differs from the key the archive
73
+ was saved with: set the old key and restart.
74
 
75
  **Compose.** `deploy/backup.sh /secure/backups`. Restore: stop the stack, put the archive's files back in the
76
+ `fpt-data` volume, start the stack. Keep backup archives encrypted: they contain the secrets vault in plain text.
77
 
78
  ## Upgrade and rollback
79
 
80
+ 1. Follow "Before every deploy or restart" (above): nothing running, state saved.
81
  2. Deploy the new image or upload the new revision. Migrations run at start (forward-only).
82
+ 3. Update the runner with `sync.sh` on the same commit.
83
+ 4. Smoke test: sign in, Test environments > Test connection, a quick run on the Fusion pod and approve it.
84
+ 5. Rollback: deploy the previous image or Space revision and `sync.sh` that commit; if the release added a migration,
85
+ restore the snapshot taken before the upgrade first.
86
 
87
  ## Rotating secrets
88
 
89
+ Change the value in the platform's secret store, then restart (save first). Revoke the old key at its provider (NVIDIA,
90
+ Hugging Face, Supabase, OCI). For the Fusion test user, change the password in Fusion first. For the runner token,
91
+ change `RUNNER_TOKEN` on the runner and `FPT_SECRET_REMOTE_RUNNER_TOKEN` on the Space together.
92
+
93
+ `OCI_STATE_PAR_URL` grants access by itself: to rotate it, make a new pre-authenticated request on the bucket, set it,
94
+ restart, confirm a save, then delete the old request in the OCI console.
95
+
96
+ `FPT_STATE_KEY` is special: the snapshot is encrypted with it. To change it, `state push` with the old key, set the new
97
+ key, restart, and confirm a new save; keep the old key until the new save is confirmed.
98
 
99
  ## Retention
100
 
101
  Screenshots, videos and traces: `EVIDENCE_RETENTION_DAYS` (30). Workflow checkpoints of finished runs:
102
  `CHECKPOINT_RETENTION_DAYS` (7). Run folders: `RUN_FILES_RETENTION_DAYS` (90). Run records and the audit log are
103
+ kept. The clean-up runs daily from the scheduler; `python -m coworker purge` runs it now. On the runner, job folders
104
+ are deleted about `RUNNER_KEEP_HOURS` (24) after they start (REMOTE_RUNNER.md).
docs/SECURITY.md CHANGED
@@ -19,29 +19,42 @@ Report a vulnerability privately to the repository owner; do not open a public i
19
  | Outbound calls | one egress gate, host-pinned, audited, kill switch | `platform/egress.py` |
20
  | Notifications | webhook to the configured host only (https), HMAC-SHA256 signed, retried then given up; payload is plain words, run names, area names and counts, never secrets, test data or screenshots; errors redacted | `platform/notify.py` |
21
  | Telegram notifications | sent only to api.telegram.org through the egress gate; the bot token is a secret (vault / Space secret) that is never logged or returned: the audit shows `api.telegram.org/bot(hidden)/...`, error texts have it removed, and refused requests are audited with the hidden address too; same message content rules as the webhook; only administrators choose the chat | `platform/notify.py` |
22
- | Two-way bot (Telegram, Teams next) | a chat is linked to one Patchwise account by a one-time code made by that signed-in person (hashed, single use, 10 minutes, 5 tries per 10 minutes); the bot then acts as that person with their role: free text and /run go through the Ask service (propose, then the person's button press re-checks RBAC and state through api/actions.py); buttons carry only a random id, stored server-side and bound to chat, person, 24-hour expiry and single use; sign-off, failure verdicts, the kill switch and administration are never offered (links only); every step audited as `channel.*`; notifications reach a linked person only for runs they may read, from when they linked; the bot token is masked in HTTP client logs as well | `channels/`, `api/routes/channels.py`, docs/CHANNELS.md |
23
  | MCP connector | personal access tokens (`pwt_`, shown once, SHA-256 at rest, compared in constant time, 1 to 365 days, revocable by the owner or an administrator), accepted only on `/mcp` and refused on `/api`; always the owner's current role (disabled owners refused); scopes `read` or `read,act`; acting is propose → `confirm` (single use, 10 minutes, same person and token, re-checks role, run state and the emergency stop); sign-off, verdicts, the emergency stop and administration never offered; 60 requests a minute per token, 64 KB bodies, foreign browser origins refused, no CORS, cookies ignored; tokens masked in logs, never in the audit (`token.*`, `mcp.*` events) | `api/mcp.py`, `platform/api_tokens.py`, docs/MCP.md |
24
  | A2A agent | the same personal access tokens, scopes, per-token rate limit (shared with `/mcp`), origin guard and propose → confirm path as MCP, at `/a2a` (bodies up to 256 KB, 20 parts, 8,000 characters of text, 50 cases); the agent card at `/.well-known/agent-card.json` is public and holds no secrets; tasks are bound to their owner and token (admins can read, not act); a caller can never approve custom cases, scenarios or failures, sign off, waive or touch the emergency stop; caller facts (pod, patch changes) are stored as untrusted data, never sent to an LLM as instructions, and their URLs are displayed only, never fetched; every task, state change, proposal, confirm, run, refusal and cancel is audited as `a2a.*` without tokens | `api/a2a.py`, docs/A2A.md |
25
- | Secrets | env or encrypted vault; never in API answers, logs or child processes | `platform/vault.py`, `platform/procs.py` |
 
 
 
 
26
  | Fusion | production pods refused; read-only except seeding and cancelling test data; password kept out of traces | `platform/pods.py`, `automation/src/fusion/ui.ts` |
27
  | Audit | append-only, hash-chained, verifiable (`/api/audit/verify`) | `platform/audit.py` |
28
  | Public surface | anonymous `/api/ready` shows no internals; API docs off in production | `api/routes/admin.py` |
29
  | Exports | CSV cells that start with `= + - @` are neutralised | `api/routes/runs.py` |
30
 
31
- ## Known residual risks (decisions recorded in docs/AUDIT.md)
32
 
33
- - The backup archive key is derived from the Supabase service key unless `FPT_STATE_KEY` is set (S8).
34
- - Supabase "Confirm email" must stay on for the admin list to be safe (S5).
35
- - react-router 6 has two moderate advisories fixed only in 7.x; the open-redirect one is not reachable here (the
36
- return path after sign-in is checked).
37
- - A Copilot Studio agent using a personal token acts as that one person for everyone who uses the agent; use a `read`
38
- token from a least-privileged account until OAuth (docs/MCP.md, phase 2).
39
- - Python dependencies are pinned at top level only; base images are not digest-pinned.
 
 
 
 
 
 
 
 
40
 
41
  ## Rotating secrets
42
 
43
  Set the new value in the platform's secret store and restart. For the Fusion test user also update the user in
44
- Fusion first. Exposed keys must be revoked at the provider (NVIDIA, Hugging Face, Supabase), not only replaced here.
 
45
 
46
  ## Incoming-webhook integrations (Slack, Teams, Google Chat, Discord)
47
 
 
19
  | Outbound calls | one egress gate, host-pinned, audited, kill switch | `platform/egress.py` |
20
  | Notifications | webhook to the configured host only (https), HMAC-SHA256 signed, retried then given up; payload is plain words, run names, area names and counts, never secrets, test data or screenshots; errors redacted | `platform/notify.py` |
21
  | Telegram notifications | sent only to api.telegram.org through the egress gate; the bot token is a secret (vault / Space secret) that is never logged or returned: the audit shows `api.telegram.org/bot(hidden)/...`, error texts have it removed, and refused requests are audited with the hidden address too; same message content rules as the webhook; only administrators choose the chat | `platform/notify.py` |
22
+ | Two-way bot (Telegram, Teams next) | a chat is linked to one Astra account by a one-time code made by that signed-in person (hashed, single use, 10 minutes, 5 tries per 10 minutes); the bot then acts as that person with their role: free text and /run go through the Ask service (propose, then the person's button press re-checks RBAC and state through api/actions.py); buttons carry only a random id, stored server-side and bound to chat, person, 24-hour expiry and single use; sign-off, failure verdicts, the kill switch and administration are never offered (links only); every step audited as `channel.*`; notifications reach a linked person only for runs they may read, from when they linked; the bot token is masked in HTTP client logs as well | `channels/`, `api/routes/channels.py`, docs/CHANNELS.md |
23
  | MCP connector | personal access tokens (`pwt_`, shown once, SHA-256 at rest, compared in constant time, 1 to 365 days, revocable by the owner or an administrator), accepted only on `/mcp` and refused on `/api`; always the owner's current role (disabled owners refused); scopes `read` or `read,act`; acting is propose → `confirm` (single use, 10 minutes, same person and token, re-checks role, run state and the emergency stop); sign-off, verdicts, the emergency stop and administration never offered; 60 requests a minute per token, 64 KB bodies, foreign browser origins refused, no CORS, cookies ignored; tokens masked in logs, never in the audit (`token.*`, `mcp.*` events) | `api/mcp.py`, `platform/api_tokens.py`, docs/MCP.md |
24
  | A2A agent | the same personal access tokens, scopes, per-token rate limit (shared with `/mcp`), origin guard and propose → confirm path as MCP, at `/a2a` (bodies up to 256 KB, 20 parts, 8,000 characters of text, 50 cases); the agent card at `/.well-known/agent-card.json` is public and holds no secrets; tasks are bound to their owner and token (admins can read, not act); a caller can never approve custom cases, scenarios or failures, sign off, waive or touch the emergency stop; caller facts (pod, patch changes) are stored as untrusted data, never sent to an LLM as instructions, and their URLs are displayed only, never fetched; every task, state change, proposal, confirm, run, refusal and cancel is audited as `a2a.*` without tokens | `api/a2a.py`, docs/A2A.md |
25
+ | Oracle AI Agent Studio | OAuth 2.0 client credentials (client secret kept as a hash; bearer tokens `pwa_`, one hour, hashed at rest, scope `patchwise.invoke` only: start cycles, forward approvals, read their status); test data must be synthetic and values that look like personal or payment data are refused; callbacks HMAC-signed with the client's signing key (kept in the vault), sent through the egress gate to the client's own address only | `platform/agent_studio.py`, docs/AGENT_STUDIO.md |
26
+ | Secrets | `FPT_SECRET_*` environment values or the vault file (plain JSON, mode 600, encrypted only inside the state snapshot: see Residual risks); never in API answers, logs or child processes | `platform/vault.py`, `platform/procs.py` |
27
+ | State snapshot | `FPT_HOME` archived and encrypted (Fernet, `FPT_STATE_KEY`) before it leaves; the bucket holds ciphertext only; the OCI pre-authenticated URL is read from the environment or the vault only and audited with its token replaced by `***` | `platform/statesync.py`, `platform/ocistore.py` |
28
+ | Remote runner | HTTPS behind Caddy, bearer token compared in constant time, one job at a time, allow-listed environment keys, configs and file names; the token is never passed to Playwright; the Fusion session file is never returned | `automation/remote_runner/server.py`, docs/REMOTE_RUNNER.md |
29
+ | AI calls | client data masked before a request leaves and restored in the answer; a payload that still looks like client data is not sent to the external model | `platform/step_writer.py`, `platform/redaction.py`, `llm/router.py` |
30
  | Fusion | production pods refused; read-only except seeding and cancelling test data; password kept out of traces | `platform/pods.py`, `automation/src/fusion/ui.ts` |
31
  | Audit | append-only, hash-chained, verifiable (`/api/audit/verify`) | `platform/audit.py` |
32
  | Public surface | anonymous `/api/ready` shows no internals; API docs off in production | `api/routes/admin.py` |
33
  | Exports | CSV cells that start with `= + - @` are neutralised | `api/routes/runs.py` |
34
 
35
+ ## Residual risks
36
 
37
+ Risks that remain in the running system, with what limits them today.
38
+
39
+ | Risk | Detail | What limits it |
40
+ |---|---|---|
41
+ | Plain-text vault, and the evidence key in the same archive | The vault (`FPT_HOME/secrets/vault.json`) is a plain JSON file on the server's disk. It holds `EVIDENCE_KEY`, the pods' test-user passwords entered in the app, the AI model key saved in Settings, the link signing key, Agent Studio signing keys and Fusion client secrets, and the chat webhook addresses. The state snapshot and the Compose backup contain both the vault and the encrypted evidence, so whoever can open the archive can also read the evidence. | File mode 600; the snapshot is encrypted with `FPT_STATE_KEY` before it leaves; the Compose backup must be encrypted by the operator. Keep `FPT_STATE_KEY` apart from the bucket's credentials. |
42
+ | Snapshot key | Unless `FPT_STATE_KEY` is set, the snapshot key is derived from the Supabase service key (S8). | Set `FPT_STATE_KEY` (required with OCI). |
43
+ | Runner token and Fusion password on every attempt | Each attempt and screen read sends the runner token (header) and the Fusion test user's password (body) to the runner over HTTPS. On the runner the password is in the Playwright process's environment. | HTTPS only (egress gate, runner host pinned); the audit log never records the password; a test pod's test user only, never production. Rotate both if the runner host is compromised. |
44
+ | Unencrypted job data on the runner | Screenshots, videos, traces, logs and the values tried stay unencrypted in the runner's job folders for `RUNNER_KEEP_HOURS` (24 h), including folders from before a runner restart (swept by age). A killed job may leave the Fusion session file there until the sweep. | The service listens on loopback only, behind Caddy. Keep the runner host single-purpose, with few logins and an encrypted disk. |
45
+ | Signed Excel links need no login | The Excel test-script link in Agent Studio events (`/api/share/runs/{id}/test-script.xlsx?exp=...&sig=...`) opens without a login for 7 days. Anyone who has the link can download that one file. | HMAC-signed for one run and one file, read-only, expires; changing `LINK_SIGNING_KEY` in the vault ends every link already sent. |
46
+ | Masking before AI calls is pattern-based | `platform/redaction.py` masks e-mail addresses, amounts, document numbers, numbers of 4 digits or more, the client names the scout registered (business units, ledgers, suppliers and other sampled test data) and vault secrets. A client name it does not know, or free text in an unusual shape, is not recognised. Oracle's own screen labels are sent as they are. | Only public or masked payloads go to the external model; a payload the leak check still flags is not sent there. Custom test cases never go to any model. Use a local model when the client does not agree to an external one. |
47
+ | Supabase sign-up | Supabase "Confirm email" must stay on for the admin list to be safe (S5). | Keep it on in the Supabase project's settings. |
48
+ | Personal tokens in shared agents | A Copilot Studio agent using a personal token acts as that one person for everyone who uses the agent. | Use a `read` token from a least-privileged account until OAuth (docs/MCP.md, phase 2). |
49
+ | Dependencies | react-router 6 has two moderate advisories fixed only in 7.x; the open-redirect one is not reachable here (the return path after sign-in is checked). Python dependencies are pinned at top level only; base images are not digest-pinned. | `npm audit` in CI (QUALITY.md). |
50
+
51
+ Decisions on the older findings are recorded in [AUDIT.md](AUDIT.md).
52
 
53
  ## Rotating secrets
54
 
55
  Set the new value in the platform's secret store and restart. For the Fusion test user also update the user in
56
+ Fusion first. Exposed keys must be revoked at the provider (NVIDIA, Hugging Face, Supabase, OCI), not only replaced here.
57
+ For the runner token and `OCI_STATE_PAR_URL`, see RUNBOOK "Rotating secrets".
58
 
59
  ## Incoming-webhook integrations (Slack, Teams, Google Chat, Discord)
60
 
docs/design/BEUI.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # beUI in Patchwise
2
 
3
  Branch `beui-ui-upgrade`. beUI (https://beui.dev) components are added one screen at a time on top of the existing
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  # beUI in Patchwise
4
 
5
  Branch `beui-ui-upgrade`. beUI (https://beui.dev) components are added one screen at a time on top of the existing
docs/design/UI-APPLE.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  > Note (24 Oct 2026, graphite pass): the accent is now GRAPHITE, not blue. Wherever the text below says blue or `#0071e3`, read the graphite tokens in section 3.1: near-black `#1d1d1f` fills in light, near-white `#f5f5f7` fills in dark, links are the label colour with an underline, and colour is reserved for status (green, orange, red). The "Oracle Fusion pod" cue is a graphite outlined chip with a cloud icon.
2
  >
3
  > Note (24 Oct 2026): this is the design the app was built to on branch `trio-apple-ui`. The product is now named "Trio Co-Worker"; older documents in this folder keep the earlier name. Where the build differs from this text: Ask is a sidebar item that opens the Ask dock (the `Ctrl K` palette also opens it); there is no separate Ask page. See the build notes in the commit history.
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  > Note (24 Oct 2026, graphite pass): the accent is now GRAPHITE, not blue. Wherever the text below says blue or `#0071e3`, read the graphite tokens in section 3.1: near-black `#1d1d1f` fills in light, near-white `#f5f5f7` fills in dark, links are the label colour with an underline, and colour is reserved for status (green, orange, red). The "Oracle Fusion pod" cue is a graphite outlined chip with a cloud icon.
4
  >
5
  > Note (24 Oct 2026): this is the design the app was built to on branch `trio-apple-ui`. The product is now named "Trio Co-Worker"; older documents in this folder keep the earlier name. Where the build differs from this text: Ask is a sidebar item that opens the Ask dock (the `Ctrl K` palette also opens it); there is no separate Ask page. See the build notes in the commit history.
docs/design/UI-REDESIGN.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # Patch Testing Co-worker: UI redesign spec
2
 
3
  Status: design spec for the developer agent. Scope: `web/` only (React 18, TypeScript, Vite, Mantine 7, TanStack Query).
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  # Patch Testing Co-worker: UI redesign spec
4
 
5
  Status: design spec for the developer agent. Scope: `web/` only (React 18, TypeScript, Vite, Mantine 7, TanStack Query).
docs/design/UI-RESEARCH-RECOVERY.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # UI research for the run page, live view, approvals and pod clarity
2
 
3
  Written during the recovery of the Hugging Face demo (October 2026). It records what comparable products do, what we
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  # UI research for the run page, live view, approvals and pod clarity
4
 
5
  Written during the recovery of the Hugging Face demo (October 2026). It records what comparable products do, what we
docs/design/UI-REVIEW-1.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # UI review 1: steps 1 and 2 of UI-REDESIGN.md
2
 
3
  Reviewed: commits `c155a92` (step 1, tokens and shell) and `d1035cc` (step 2, run workspace and side panel), against
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  # UI review 1: steps 1 and 2 of UI-REDESIGN.md
4
 
5
  Reviewed: commits `c155a92` (step 1, tokens and shell) and `d1035cc` (step 2, run workspace and side panel), against
docs/design/UI-REVIEW-2.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # UI review 2: review-1 fixes and step 3 (Team board)
2
 
3
  Reviewed:
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  # UI review 2: review-1 fixes and step 3 (Team board)
4
 
5
  Reviewed:
docs/design/UI-REVIEW-3.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # UI review 3: review-2 fixes and step 4 (approvals and failure decision)
2
 
3
  Reviewed: `f9fab2a` (review-2 must-fixes), `4cae29d` (review-2 should-fixes + N2, N5), `6fe0316` (step 4), against `UI-REDESIGN.md`,
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  # UI review 3: review-2 fixes and step 4 (approvals and failure decision)
4
 
5
  Reviewed: `f9fab2a` (review-2 must-fixes), `4cae29d` (review-2 should-fixes + N2, N5), `6fe0316` (step 4), against `UI-REDESIGN.md`,
docs/design/UI-SIMPLIFY.md CHANGED
@@ -1,3 +1,5 @@
 
 
1
  # Make the UI calm and simple
2
 
3
  Status: binding for every UI step from now on. Where this file and `UI-REDESIGN.md` disagree, this file wins; `UI-REDESIGN.md`
 
1
+ > **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md).
2
+
3
  # Make the UI calm and simple
4
 
5
  Status: binding for every UI step from now on. Where this file and `UI-REDESIGN.md` disagree, this file wins; `UI-REDESIGN.md`