EnergyVenom commited on
Commit
5ce1088
·
verified ·
1 Parent(s): 152e0c1

Astra: data safety (fencing, history, audit), AP 26D fixes, dry runs via the runner, client polish (56e055deeb3e)

Browse files
Files changed (45) hide show
  1. .env.example +2 -0
  2. automation/src/fusion/steps.ts +1 -0
  3. automation/src/fusion/ui.ts +59 -1
  4. automation/tests/fusion/AP-FUS-002.spec.ts +4 -4
  5. automation/tests/fusion/AP-FUS-003.spec.ts +2 -1
  6. automation/tests/fusion/AP-FUS-005.spec.ts +1 -1
  7. coworker/adapters/remote_runner.py +58 -46
  8. coworker/api/app.py +9 -4
  9. coworker/api/routes/admin.py +20 -5
  10. coworker/api/routes/runs.py +14 -0
  11. coworker/api/runner.py +31 -1
  12. coworker/config.py +5 -0
  13. coworker/graph/nodes/ai_scenarios.py +7 -3
  14. coworker/platform/egress.py +84 -5
  15. coworker/platform/evidence.py +10 -1
  16. coworker/platform/notify.py +3 -0
  17. coworker/platform/ocistore.py +17 -1
  18. coworker/platform/statesync.py +270 -22
  19. coworker/platform/step_writer.py +7 -2
  20. coworker/platform/supabase.py +10 -0
  21. coworker/tests/test_ai_scenarios.py +22 -0
  22. coworker/tests/test_hardening.py +156 -0
  23. coworker/tests/test_ocistore.py +43 -0
  24. coworker/tests/test_remote_runner.py +5 -1
  25. coworker/tests/test_remote_screens.py +10 -2
  26. coworker/tests/test_runner_robust.py +4 -1
  27. coworker/tests/test_step_writer.py +21 -0
  28. coworker/tests/test_supabase.py +217 -1
  29. deploy/oci/update-app.sh +48 -0
  30. docs/ARCHITECTURE.md +13 -3
  31. docs/DEPLOYMENT.md +14 -5
  32. docs/RUNBOOK.md +28 -2
  33. tests/cases/AP-FUS-012.yaml +2 -2
  34. web/src/api/hooks.ts +1 -1
  35. web/src/components/Layout.tsx +5 -3
  36. web/src/components/common.tsx +1 -1
  37. web/src/domain/glossary.ts +24 -0
  38. web/src/pages/account/AccountPage.tsx +13 -2
  39. web/src/pages/run/FailureReview.tsx +8 -4
  40. web/src/pages/run/RunData.tsx +11 -5
  41. web/src/pages/run/RunGuide.tsx +5 -4
  42. web/src/pages/run/RunPage.tsx +4 -4
  43. web/src/pages/run/RunReport.tsx +19 -8
  44. web/src/pages/run/RunStages.tsx +1 -1
  45. web/src/pages/run/SignOffReport.tsx +8 -8
.env.example CHANGED
@@ -31,6 +31,8 @@ SUPABASE_ANON_KEY=
31
  SUPABASE_SERVICE_KEY= # secret: storage of the encrypted state archive
32
  SUPABASE_BUCKET=patch-coworker
33
  FPT_STATE_KEY= # secret: key of the state archive (recommended; without it a key is derived from the service key)
 
 
34
  FPT_REGISTRATION=1 # 0 to switch off self-registration
35
  FPT_REGISTER_ROLE=viewer # role of a self-registered account: viewer | consultant | qa_approver (never admin)
36
  FPT_ADMIN_EMAILS= # comma list; only applies to addresses the identity provider has confirmed
 
31
  SUPABASE_SERVICE_KEY= # secret: storage of the encrypted state archive
32
  SUPABASE_BUCKET=patch-coworker
33
  FPT_STATE_KEY= # secret: key of the state archive (recommended; without it a key is derived from the service key)
34
+ FPT_STATE_HISTORY=5 # earlier archives kept in the bucket (state/history/), so a bad save can be undone
35
+ FPT_SHUTDOWN_RUN_WAIT_S=20 # at shutdown, how long a running test run may take to reach its next step before the last save
36
  FPT_REGISTRATION=1 # 0 to switch off self-registration
37
  FPT_REGISTER_ROLE=viewer # role of a self-registered account: viewer | consultant | qa_approver (never admin)
38
  FPT_ADMIN_EMAILS= # comma list; only applies to addresses the identity provider has confirmed
automation/src/fusion/steps.ts CHANGED
@@ -127,6 +127,7 @@ const UI_BLOCKS: Record<string, { method: string; args: (s: Step, ctx: Ctx) => u
127
  { amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] },
128
  save: { method: 'save', args: () => [] },
129
  invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] },
 
130
  expect_status: { method: 'expectStatusText', args: (s, ctx) => [fill(s.value, ctx)] },
131
  };
132
 
 
127
  { amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] },
128
  save: { method: 'save', args: () => [] },
129
  invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] },
130
+ validate_invoice: { method: 'validateInvoice', args: () => [] },
131
  expect_status: { method: 'expectStatusText', args: (s, ctx) => [fill(s.value, ctx)] },
132
  };
133
 
automation/src/fusion/ui.ts CHANGED
@@ -560,15 +560,73 @@ export class FusionUi {
560
  const t = (await d.nth(i).innerText().catch(() => '')).replace(/\s+/g, ' ').replace('Click here to exit this popup.', '').trim();
561
  if (t) out.push(t);
562
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
563
  return out;
564
  }
565
 
566
  /** Answer the open Fusion message window with one of its buttons (OK by default). */
567
  async answerDialog(button = 'OK') {
568
- await this.page.getByRole('dialog').getByRole('button', { name: button, exact: true }).first().click();
 
 
 
569
  await this.settle(2000);
570
  }
571
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
572
  /** Press the page's Save button; returns what Fusion said in message windows (empty when it saved quietly). */
573
  async save(): Promise<string[]> {
574
  await this.page.getByRole('button', { name: 'Save', exact: true }).first().click();
 
560
  const t = (await d.nth(i).innerText().catch(() => '')).replace(/\s+/g, ' ').replace('Click here to exit this popup.', '').trim();
561
  if (t) out.push(t);
562
  }
563
+ // 26D shows some messages in a plain window (no dialog role): a heading Error / Warning / Information /
564
+ // Confirmation, the text and an OK button
565
+ const plain = await this.page.evaluate(() => {
566
+ const shown = (e: Element) => { const r = (e as HTMLElement).getBoundingClientRect(); return r.width > 0 && r.height > 0; };
567
+ const found: string[] = [];
568
+ for (const h of Array.from(document.querySelectorAll('div, span, td, h1, h2'))) {
569
+ if (h.children.length || !/^(Error|Warning|Information|Confirmation)$/.test((h.textContent || '').trim()) || !shown(h)) continue;
570
+ let c: Element | null = h.parentElement;
571
+ for (let up = 0; c && up < 6; up++, c = c.parentElement) {
572
+ const ok = Array.from(c.querySelectorAll('button, a[role="button"]'))
573
+ .some((b) => shown(b) && /^(OK|Yes|No|Continue)$/.test((b.textContent || '').trim()));
574
+ if (ok) { found.push((c as HTMLElement).innerText); break; }
575
+ }
576
+ }
577
+ return found;
578
+ }).catch(() => [] as string[]);
579
+ for (const raw of plain) {
580
+ const t = raw.replace(/\s+/g, ' ').trim();
581
+ if (t && !out.some((o) => o.includes(t) || t.includes(o))) out.push(t);
582
+ }
583
  return out;
584
  }
585
 
586
  /** Answer the open Fusion message window with one of its buttons (OK by default). */
587
  async answerDialog(button = 'OK') {
588
+ const inDialog = this.page.getByRole('dialog').getByRole('button', { name: button, exact: true }).filter({ visible: true });
589
+ // a plain message window (26D) has no dialog role: its button is the last one of that name on the page
590
+ const target = (await inDialog.count()) ? inDialog.first() : this.page.getByRole('button', { name: button, exact: true }).filter({ visible: true }).last();
591
+ await target.click();
592
  await this.settle(2000);
593
  }
594
 
595
+ /** The invoice's Total in the Totals section, and whether Fusion marks it "Out of Balance" with the invoice amount
596
+ * (tax or freight Fusion added). */
597
+ async invoiceTotal(): Promise<{ total: string; outOfBalance: boolean } | null> {
598
+ return this.page.evaluate(() => {
599
+ const shown = (e: Element) => { const r = (e as HTMLElement).getBoundingClientRect(); return r.width > 0 && r.height > 0; };
600
+ const label = Array.from(document.querySelectorAll('div, span, td, label'))
601
+ .find((e) => !e.children.length && (e.textContent || '').trim() === 'Total' && shown(e));
602
+ const cell = label?.nextElementSibling as HTMLElement | null;
603
+ const total = (cell?.innerText || '').replace(/[^\d.,-]/g, '').trim();
604
+ if (!total) return null;
605
+ const outOfBalance = !!cell?.querySelector('img[alt*="Out of Balance" i], img[title*="Out of Balance" i], [aria-label*="Out of Balance" i]');
606
+ return { total, outOfBalance };
607
+ }).catch(() => null);
608
+ }
609
+
610
+ /** Validate the way an AP clerk does: when Fusion's tax or freight leaves the invoice out of balance, the invoice
611
+ * amount becomes the Total (the supplier's invoice total includes tax), the invoice is saved, then validated; and
612
+ * once more if validating is what added the tax. A scenario that tests an amount mismatch uses invoiceAction. */
613
+ async validateInvoice() {
614
+ const balance = async () => {
615
+ const t = await this.invoiceTotal();
616
+ if (!t?.outOfBalance) return false;
617
+ await this.put('Amount', t.total);
618
+ await this.save();
619
+ return true;
620
+ };
621
+ await balance();
622
+ await this.invoiceAction('Validate');
623
+ await this.settle(3000);
624
+ if ((await this.statusOnPage()) !== 'Validated' && await balance()) {
625
+ await this.invoiceAction('Validate');
626
+ await this.settle(3000);
627
+ }
628
+ }
629
+
630
  /** Press the page's Save button; returns what Fusion said in message windows (empty when it saved quietly). */
631
  async save(): Promise<string[]> {
632
  await this.page.getByRole('button', { name: 'Save', exact: true }).first().click();
automation/tests/fusion/AP-FUS-002.spec.ts CHANGED
@@ -19,16 +19,16 @@ test('AP-FUS-002 Standard invoice is entered, saved and validated with no holds'
19
  expect(await fusion.save()).toEqual([]);
20
  await fusion.expectStatus('Not validated');
21
  });
22
- await test.step('Invoice Actions > Validate: the page shows "Validated"', async () => {
23
- await fusion.invoiceAction('Validate');
24
  expect(await fusion.dialogs()).toEqual([]);
25
  await fusion.expectStatus('Validated');
26
  });
27
- await test.step('Check in Fusion (REST): validated, amount 100, no holds', async () => {
28
  const inv = await apInvoices.rest.invoice(number, d.supplier);
29
  expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();
30
  expect(inv!.ValidationStatus).toBe('Validated');
31
- expect(inv!.InvoiceAmount).toBe(100);
32
  expect(inv!.CanceledFlag).toBe(false);
33
  expect(await apInvoices.rest.holds(number)).toEqual([]);
34
  });
 
19
  expect(await fusion.save()).toEqual([]);
20
  await fusion.expectStatus('Not validated');
21
  });
22
+ await test.step('Invoice Actions > Validate (the amount set to the Total when Fusion adds tax): the page shows "Validated"', async () => {
23
+ await fusion.validateInvoice();
24
  expect(await fusion.dialogs()).toEqual([]);
25
  await fusion.expectStatus('Validated');
26
  });
27
+ await test.step('Check in Fusion (REST): validated, amount 100 plus any tax, no holds', async () => {
28
  const inv = await apInvoices.rest.invoice(number, d.supplier);
29
  expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();
30
  expect(inv!.ValidationStatus).toBe('Validated');
31
+ expect(inv!.InvoiceAmount).toBeGreaterThanOrEqual(100); // 100, plus the tax Fusion adds on this pod
32
  expect(inv!.CanceledFlag).toBe(false);
33
  expect(await apInvoices.rest.holds(number)).toEqual([]);
34
  });
automation/tests/fusion/AP-FUS-003.spec.ts CHANGED
@@ -26,7 +26,8 @@ test('AP-FUS-003 Invoice whose lines do not equal the invoice amount is put on h
26
  const inv = await apInvoices.rest.invoice(number, d.supplier);
27
  expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();
28
  expect(inv!.ValidationStatus).not.toBe('Validated');
29
- expect(inv!.ActiveHoldFlag).toBe(true);
 
30
  const holds = await apInvoices.rest.holds(number);
31
  expect(holds.map((h) => h.HoldName)).toContain('Line variance');
32
  const lv = holds.find((h) => h.HoldName === 'Line variance')!;
 
26
  const inv = await apInvoices.rest.invoice(number, d.supplier);
27
  expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();
28
  expect(inv!.ValidationStatus).not.toBe('Validated');
29
+ // 26D's invoice record no longer returns ActiveHoldFlag: the holds list below is the proof either way
30
+ if (inv!.ActiveHoldFlag !== undefined) expect(inv!.ActiveHoldFlag).toBe(true);
31
  const holds = await apInvoices.rest.holds(number);
32
  expect(holds.map((h) => h.HoldName)).toContain('Line variance');
33
  const lv = holds.find((h) => h.HoldName === 'Line variance')!;
automation/tests/fusion/AP-FUS-005.spec.ts CHANGED
@@ -14,7 +14,7 @@ test('AP-FUS-005 Validated invoice can be cancelled', { tag: ['@AP-FUS-005', '@A
14
  await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' });
15
  await fusion.addLine(1, { amount: '100', account: d.account });
16
  expect(await fusion.save()).toEqual([]);
17
- await fusion.invoiceAction('Validate');
18
  await fusion.expectStatus('Validated');
19
  });
20
  await test.step('Invoice Actions > Cancel Invoice: Fusion asks to confirm', async () => {
 
14
  await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' });
15
  await fusion.addLine(1, { amount: '100', account: d.account });
16
  expect(await fusion.save()).toEqual([]);
17
+ await fusion.validateInvoice(); // the amount set to the Total first when Fusion adds tax
18
  await fusion.expectStatus('Validated');
19
  });
20
  await test.step('Invoice Actions > Cancel Invoice: Fusion asks to confirm', async () => {
coworker/adapters/remote_runner.py CHANGED
@@ -128,9 +128,11 @@ def runner_for(svc) -> tuple[str, str] | None:
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:
@@ -183,10 +185,10 @@ def _start_job(egress, base: str, hdr: dict, path: str, body: dict, log_body: di
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:
@@ -210,28 +212,32 @@ def run_screens_remote(egress, base_url: str, token: str, *, kind: str, env: dic
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})")
@@ -264,7 +270,7 @@ def _pull_live(egress, base: str, hdr: dict, jid: str, live_dir: Path, seen: dic
264
  attempt). Frames only: never stored with the evidence, never sent anywhere else."""
265
  try:
266
  v = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/live", allowed_base=base, headers=hdr,
267
- log_body=None, timeout=20).json()
268
  except Exception: # noqa: BLE001 - a missed frame is not an error
269
  return
270
  if v.get("status"):
@@ -348,27 +354,33 @@ def release_job(svc, run_id: str) -> bool:
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:
 
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
+ poll: str | None = None):
133
+ """`poll` names a series of repeated status GETs: the egress gate audits them as one row a minute (end_polls ends it)."""
134
  return egress.service_request("remote_runner", method, base + path, allowed_base=base, json_body=json_body, headers=hdr,
135
+ log_body=log_body, timeout=timeout, **({"poll": poll} if poll else {}))
136
 
137
 
138
  def _cancel(egress, base: str, hdr: dict, jid: str) -> None:
 
185
  pause = min(pause * 2, 60.0)
186
 
187
 
188
+ def _status(egress, base: str, hdr: dict, jid: str, query: str = "", poll: str | None = None) -> tuple[int, dict]:
189
  """(HTTP status, body) of one poll; (0, {}) when the poll itself was dropped (it is tried again)."""
190
  try:
191
+ r = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}{query}", poll=poll)
192
  except Exception: # noqa: BLE001 - a dropped poll is tried again; the job keeps running on the runner
193
  return 0, {}
194
  try:
 
212
  what="screen read", busy_wait_s=busy_wait_s, on_wait=on_wait)
213
  deadline = time.time() + timeout_s + 300
214
  seen, gone, st = 0, 0, {}
215
+ polls = f"screens {jid}" # the status polls are audited as one row a minute (platform/egress.py)
216
+ try:
217
+ while True:
218
+ time.sleep(poll_s)
219
+ code, st = _status(egress, base, hdr, jid, f"?since={seen}", poll=polls)
220
+ if code == 404:
221
+ gone += 1
222
+ if gone >= GONE_AFTER:
223
+ raise RemoteRunnerError("the remote browser runner no longer knows this screen read: it restarted while it ran")
224
+ continue
225
+ if code:
226
+ gone = 0
227
+ new = st.get("lines") or []
228
+ seen += len(new)
229
+ if on_line:
230
+ for line in new:
231
+ on_line(line)
232
+ if st.get("state") == "lost":
233
+ raise RemoteRunnerError("the remote browser runner restarted while it read the screens, so the read was lost")
234
+ if st.get("state") in ENDED:
235
+ break
236
+ if time.time() > deadline:
237
+ _cancel(egress, base, hdr, jid)
238
+ raise RemoteRunnerError(f"the remote browser runner did not finish reading the screens in {timeout_s // 60} minutes")
239
+ finally:
240
+ egress.end_polls(polls)
241
  z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)
242
  if z.status_code != 200:
243
  raise RemoteRunnerError(f"the remote browser runner did not return the screens (HTTP {z.status_code})")
 
270
  attempt). Frames only: never stored with the evidence, never sent anywhere else."""
271
  try:
272
  v = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/live", allowed_base=base, headers=hdr,
273
+ log_body=None, timeout=20, poll=f"live {jid}").json()
274
  except Exception: # noqa: BLE001 - a missed frame is not an error
275
  return
276
  if v.get("status"):
 
354
 
355
  def _follow(egress, base: str, hdr: dict, jid: str, deadline: float, *, kill, poll_s: float, live_dir: Path | None) -> dict | None:
356
  """Poll a job until it ends: its last status, {"state": "overdue"} past the deadline, or None when the runner no
357
+ longer knows it (GONE_AFTER 404s in a row: it restarted and lost its jobs). The status polls and live frames are
358
+ audited as one row a minute each (platform/egress.py), ended here however the following ends."""
359
  seen: dict = {}
360
  gone = 0
361
+ polls = f"attempt {jid}"
362
+ try:
363
+ while True:
364
+ if kill:
365
+ kill()
366
+ time.sleep(poll_s)
367
+ code, st = _status(egress, base, hdr, jid, poll=polls)
368
+ if code == 404:
369
+ gone += 1
370
+ if gone >= GONE_AFTER:
371
+ return None
372
+ continue
373
+ if code:
374
+ gone = 0
375
+ if live_dir and st.get("state") == "running":
376
+ _pull_live(egress, base, hdr, jid, Path(live_dir), seen)
377
+ if st.get("state") in ENDED:
378
+ return st
379
+ if time.time() > deadline:
380
+ return {"state": "overdue"}
381
+ finally:
382
+ egress.end_polls(polls)
383
+ egress.end_polls(f"live {jid}")
384
 
385
 
386
  def _resumable(egress, base: str, hdr: dict, log_dir: Path, pw_run_id: str, out_file: Path, ledger: str) -> dict | None:
coworker/api/app.py CHANGED
@@ -83,18 +83,23 @@ def create_app(svc: Services | None = None, cfg: Settings | None = None, *, back
83
  app.state.syncer = syncer
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()
 
 
 
 
 
 
91
  run_mgr.stop()
92
  from ..platform import notify
93
  notify.get(svc).stop()
94
  from ..channels import telegram as tg_channel
95
  tg_channel.stop(svc)
96
- if syncer:
97
- syncer.stop()
98
 
99
  app = FastAPI(title="Astra API", version=VERSION, lifespan=lifespan,
100
  description="Pilot backend. Runs against the local mock app or a registered Oracle Fusion TEST pod (never production); "
 
83
  app.state.syncer = syncer
84
  log.info("state is saved to Supabase Storage every %ss when it changes", syncer.interval)
85
  yield
86
+ # Shutdown: stop taking new work, let a running run stop at its next step (bounded: the host does not wait long),
87
+ # then the one last save, then everything else. Saving before the run stopped kept it as "running", so it came
88
+ # back interrupted after the restart.
89
  if getattr(app.state, "courier", None):
90
  app.state.courier.stop()
91
  sched.stop()
92
+ stop_runs = getattr(run_mgr, "stop_for_shutdown", None) # the Temporal orchestrator keeps its runs itself
93
+ if stop_runs and not stop_runs(cfg.shutdown_run_wait_s):
94
+ log.warning("a run step was still going after %ss: saving without it (that run comes back interrupted)",
95
+ cfg.shutdown_run_wait_s)
96
+ if syncer:
97
+ syncer.stop() # stops the saver and makes the last save
98
  run_mgr.stop()
99
  from ..platform import notify
100
  notify.get(svc).stop()
101
  from ..channels import telegram as tg_channel
102
  tg_channel.stop(svc)
 
 
103
 
104
  app = FastAPI(title="Astra API", version=VERSION, lifespan=lifespan,
105
  description="Pilot backend. Runs against the local mock app or a registered Oracle Fusion TEST pod (never production); "
coworker/api/routes/admin.py CHANGED
@@ -56,16 +56,19 @@ def ready(request: Request):
56
  "scheduler": "temporal-schedules" if runs.orchestrator == "temporal" else "in-process",
57
  "product_name": svc.cfg.product_name, "org_name": svc.cfg.org_name, "browser_runs": svc.cfg.browser_runs_allowed}
58
  # whether the data is being saved to Supabase Storage, and when it last worked (no details: this endpoint is public)
 
59
  syncer = getattr(request.app.state, "syncer", None)
60
- last = svc.extra.get("state_last") or {}
61
  body["saved_state"] = {"on": syncer is not None, "last_saved_at": last.get("saved_at"),
62
  "ok": syncer.last_error is None if syncer else None,
63
  "last_failed_at": syncer.last_error_at if syncer and syncer.last_error else None,
64
  # the last save left something out to stay under the storage limit (screenshots, old run folders)
65
  "left_out": last.get("left_out") or []}
66
  if syncer is not None:
67
- from ...platform import statesync
68
- body["saved_state"]["paused"] = statesync.restore_failed(svc.cfg.home) # the boot restore failed: not saving, to protect the saved copy
 
 
69
  if not _signed_in(request):
70
  # public callers (uptime monitors, the sign-in page) get only what they need; no internals
71
  body = {k: body[k] for k in ("ready", "checks", "version", "needs_bootstrap", "product_name", "org_name", "browser_runs")}
@@ -79,13 +82,22 @@ def ready(request: Request):
79
  def storage(request: Request, user: Principal = Depends(require("admin"))):
80
  """Administrator: what the saved state holds and how the last save went (with the error text), the retention
81
  settings and the last clean-up."""
 
82
  from ...platform.retention import sizes
83
  svc = request.app.state.svc
84
  syncer = getattr(request.app.state, "syncer", None)
85
- last = svc.extra.get("state_last") or {}
 
86
  return {"saved_state": {"on": syncer is not None, "last_saved_at": last.get("saved_at"), "bytes": last.get("bytes"),
87
  "left_out": last.get("left_out") or [], "reason": last.get("reason"),
88
- "last_error": syncer.last_error if syncer else None, "last_error_at": syncer.last_error_at if syncer else None},
 
 
 
 
 
 
 
89
  "on_disk": sizes(svc.cfg),
90
  "retention": {"evidence_days": svc.cfg.evidence_retention_days, "checkpoint_days": svc.cfg.checkpoint_retention_days,
91
  "run_files_days": svc.cfg.run_files_retention_days},
@@ -103,6 +115,9 @@ def save_storage_now(request: Request, user: Principal = Depends(require("admin"
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 {}
 
 
 
106
  if syncer.last_error:
107
  raise ApiError(502, "SAVE_FAILED", f"the state could not be saved: {syncer.last_error}")
108
  return {"saved": saved, "last_saved_at": last.get("saved_at"), "bytes": last.get("bytes")}
 
56
  "scheduler": "temporal-schedules" if runs.orchestrator == "temporal" else "in-process",
57
  "product_name": svc.cfg.product_name, "org_name": svc.cfg.org_name, "browser_runs": svc.cfg.browser_runs_allowed}
58
  # whether the data is being saved to Supabase Storage, and when it last worked (no details: this endpoint is public)
59
+ from ...platform import statesync
60
  syncer = getattr(request.app.state, "syncer", None)
61
+ last = statesync.last_meta(svc)
62
  body["saved_state"] = {"on": syncer is not None, "last_saved_at": last.get("saved_at"),
63
  "ok": syncer.last_error is None if syncer else None,
64
  "last_failed_at": syncer.last_error_at if syncer and syncer.last_error else None,
65
  # the last save left something out to stay under the storage limit (screenshots, old run folders)
66
  "left_out": last.get("left_out") or []}
67
  if syncer is not None:
68
+ # not saving, to protect the saved copy: the boot restore failed ("restore_failed"), or another instance has
69
+ # saved since this one started ("fenced")
70
+ why = statesync.paused_reason(svc.cfg.home)
71
+ body["saved_state"].update(paused=why is not None, paused_reason=why)
72
  if not _signed_in(request):
73
  # public callers (uptime monitors, the sign-in page) get only what they need; no internals
74
  body = {k: body[k] for k in ("ready", "checks", "version", "needs_bootstrap", "product_name", "org_name", "browser_runs")}
 
82
  def storage(request: Request, user: Principal = Depends(require("admin"))):
83
  """Administrator: what the saved state holds and how the last save went (with the error text), the retention
84
  settings and the last clean-up."""
85
+ from ...platform import statesync
86
  from ...platform.retention import sizes
87
  svc = request.app.state.svc
88
  syncer = getattr(request.app.state, "syncer", None)
89
+ last = statesync.last_meta(svc)
90
+ why = statesync.paused_reason(svc.cfg.home) if syncer is not None else None
91
  return {"saved_state": {"on": syncer is not None, "last_saved_at": last.get("saved_at"), "bytes": last.get("bytes"),
92
  "left_out": last.get("left_out") or [], "reason": last.get("reason"),
93
+ # what exactly the last save left out (file counts, sizes, run ids) and the sentence to show
94
+ "left_out_detail": last.get("left_out_detail") or {}, "left_out_note": statesync.left_out_note(last),
95
+ "last_error": syncer.last_error if syncer else None, "last_error_at": syncer.last_error_at if syncer else None,
96
+ "paused": why is not None, "paused_reason": why,
97
+ "fenced": statesync.fenced(svc.cfg.home) if why == "fenced" else None,
98
+ "generation": last.get("generation"), "instance": statesync.record(svc.cfg.home).get("instance"),
99
+ # earlier archives in the bucket, newest first: docs/RUNBOOK.md says how to go back to one
100
+ "history": last.get("history") or [], "history_keep": svc.cfg.state_history_keep},
101
  "on_disk": sizes(svc.cfg),
102
  "retention": {"evidence_days": svc.cfg.evidence_retention_days, "checkpoint_days": svc.cfg.checkpoint_retention_days,
103
  "run_files_days": svc.cfg.run_files_retention_days},
 
115
  svc = request.app.state.svc
116
  svc.audit.append("state.saved_on_request", actor=user.username, summary="saved" if saved else "unchanged")
117
  last = svc.extra.get("state_last") or {}
118
+ from ...platform.statesync import paused_reason
119
+ if syncer.last_error and paused_reason(svc.cfg.home):
120
+ raise ApiError(409, "SAVING_PAUSED", f"the state was not saved: {syncer.last_error}")
121
  if syncer.last_error:
122
  raise ApiError(502, "SAVE_FAILED", f"the state could not be saved: {syncer.last_error}")
123
  return {"saved": saved, "last_saved_at": last.get("saved_at"), "bytes": last.get("bytes")}
coworker/api/routes/runs.py CHANGED
@@ -284,6 +284,11 @@ def run_report_file(run_id: str, module: str, fmt: str, request: Request, downlo
284
  raise ApiError(400, "BAD_FORMAT", f"fmt must be one of {sorted(FMT)}")
285
  paths = (runs.state(run_id).get("report_paths") or {}).get(module.upper())
286
  if not paths or not paths.get(FMT[fmt][0]) or not Path(paths[FMT[fmt][0]]).exists():
 
 
 
 
 
287
  raise ApiError(404, "NOT_FOUND", f"no {fmt} report for {module} in run {run_id}")
288
  p = Path(paths[FMT[fmt][0]]).resolve()
289
  if not p.is_relative_to(svc.cfg.runs_dir.resolve()):
@@ -311,8 +316,17 @@ def delete_run_evidence(run_id: str, request: Request, user: Principal = Depends
311
  @router.get("/evidence/{evidence_id}")
312
  def evidence_file(evidence_id: int, request: Request, user: Principal = Depends(require("evidence.read"))):
313
  svc, _ = ctx(request)
 
 
314
  try:
315
  data, ctype = svc.evidence.open(evidence_id, actor=user.username)
 
 
 
 
 
 
 
316
  except FileNotFoundError as e: # a fixed sentence: the OS error text could show server paths
317
  raise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the "
318
  "retention clean-up, or it is no longer stored on this server.") from e
 
284
  raise ApiError(400, "BAD_FORMAT", f"fmt must be one of {sorted(FMT)}")
285
  paths = (runs.state(run_id).get("report_paths") or {}).get(module.upper())
286
  if not paths or not paths.get(FMT[fmt][0]) or not Path(paths[FMT[fmt][0]]).exists():
287
+ from ...platform.statesync import not_kept_after_restart
288
+ if paths and paths.get(FMT[fmt][0]) and not_kept_after_restart(svc.cfg.home, "run_folder", run_id=run_id):
289
+ raise ApiError(410, "NOT_KEPT", f"The {fmt} report of run {run_id} was not kept after a restart: the saved copy of "
290
+ "the data was over the size limit, so the folders of finished runs were left out. "
291
+ "The run's results and decisions are still here.")
292
  raise ApiError(404, "NOT_FOUND", f"no {fmt} report for {module} in run {run_id}")
293
  p = Path(paths[FMT[fmt][0]]).resolve()
294
  if not p.is_relative_to(svc.cfg.runs_dir.resolve()):
 
316
  @router.get("/evidence/{evidence_id}")
317
  def evidence_file(evidence_id: int, request: Request, user: Principal = Depends(require("evidence.read"))):
318
  svc, _ = ctx(request)
319
+ from ...platform.evidence import EvidenceMissing
320
+ from ...platform.statesync import not_kept_after_restart
321
  try:
322
  data, ctype = svc.evidence.open(evidence_id, actor=user.username)
323
+ except EvidenceMissing as e:
324
+ if not_kept_after_restart(svc.cfg.home, "evidence", created_at=e.created_at):
325
+ raise ApiError(410, "NOT_KEPT", f"Screenshot or recording {evidence_id} was not kept after a restart: the saved copy "
326
+ "of the data was over the size limit, so screenshots, videos and traces were left "
327
+ "out. The run's results are still here.") from e
328
+ raise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the "
329
+ "retention clean-up, or it is no longer stored on this server.") from e
330
  except FileNotFoundError as e: # a fixed sentence: the OS error text could show server paths
331
  raise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the "
332
  "retention clean-up, or it is no longer stored on this server.") from e
coworker/api/runner.py CHANGED
@@ -152,6 +152,8 @@ class RunManager:
152
  self.current: str | None = None
153
  self._cancel: set[str] = set()
154
  self._stop = threading.Event()
 
 
155
  self._thread: threading.Thread | None = None
156
  self.listeners: list = [] # callables(run_id, status) e.g. desktop notifications via SSE
157
 
@@ -199,6 +201,20 @@ class RunManager:
199
  if self._thread:
200
  self._thread.join(timeout=10)
201
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
202
  def drain(self, timeout: float = 600) -> None:
203
  """Tests/CLI: process queued jobs synchronously in the calling thread."""
204
  import time
@@ -213,6 +229,8 @@ class RunManager:
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
@@ -312,7 +330,7 @@ class RunManager:
312
  def _loop(self) -> None:
313
  while not self._stop.is_set():
314
  job = self.q.get()
315
- if job is None:
316
  continue
317
  try:
318
  self._execute(*job)
@@ -329,6 +347,15 @@ class RunManager:
329
  if job_id is not None:
330
  self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE id=?", (now_iso(), job_id))
331
 
 
 
 
 
 
 
 
 
 
332
  def _work(self, kind: str, run_id: str, payload, gate: str | None = None) -> None:
333
  run = self.svc.db.get_run(run_id)
334
  if not run or run["status"] == "cancelled" or run_id in self._cancel:
@@ -356,6 +383,9 @@ class RunManager:
356
  return
357
  if self.svc.kill.engaged():
358
  raise KillSwitchEngaged("kill switch engaged between steps")
 
 
 
359
  snap = self.graph.get_state(cfg)
360
  intr = self._interrupt(snap)
361
  if intr is not None:
 
152
  self.current: str | None = None
153
  self._cancel: set[str] = set()
154
  self._stop = threading.Event()
155
+ # the app is shutting down: no new run starts, no queued job is taken, a running run stops at its next step
156
+ self._shutting_down = threading.Event()
157
  self._thread: threading.Thread | None = None
158
  self.listeners: list = [] # callables(run_id, status) e.g. desktop notifications via SSE
159
 
 
201
  if self._thread:
202
  self._thread.join(timeout=10)
203
 
204
+ def stop_for_shutdown(self, wait_s: float) -> bool:
205
+ """Shutdown, before the last save: take no new work, and let a running run stop at its next safe point (between
206
+ two graph steps, where its checkpoint is complete). That run is queued to continue after the restart instead of
207
+ coming back interrupted. Waits at most wait_s; a step that takes longer (a browser attempt) is left to the old
208
+ behaviour (interrupted after the restart), so shutdown is never held up. True when the worker stopped in time."""
209
+ self._shutting_down.set()
210
+ self._stop.set()
211
+ self.q.put(None)
212
+ t = self._thread
213
+ if t is None or not t.is_alive():
214
+ return True
215
+ t.join(timeout=max(0.0, float(wait_s)))
216
+ return not t.is_alive()
217
+
218
  def drain(self, timeout: float = 600) -> None:
219
  """Tests/CLI: process queued jobs synchronously in the calling thread."""
220
  import time
 
229
 
230
  # ------------------------------------------------------------ API
231
  def start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str:
232
+ if self._shutting_down.is_set():
233
+ raise RunError("the server is restarting: start the run again in a minute", "SHUTTING_DOWN", 503)
234
  rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph", run_id=run_id)
235
  self._enqueue("start", rid, state)
236
  return rid
 
330
  def _loop(self) -> None:
331
  while not self._stop.is_set():
332
  job = self.q.get()
333
+ if job is None or self._stop.is_set(): # stopping: the job stays in run_jobs and runs after the restart
334
  continue
335
  try:
336
  self._execute(*job)
 
347
  if job_id is not None:
348
  self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE id=?", (now_iso(), job_id))
349
 
350
+ def _continue_after_restart(self, run_id: str) -> None:
351
+ """The app is shutting down between two steps of this run: queue it with a 'continue' job (kept in run_jobs, so
352
+ recover() picks it up at the next start) and let the last save hold it that way."""
353
+ self.svc.db.update_run(run_id, status="queued")
354
+ self.svc.db.insert("run_jobs", {"run_id": run_id, "kind": "continue", "gate": None, "payload": "null", "created_at": now_iso()})
355
+ self.svc.db.add_event(run_id, None, "status", {"status": "queued", "reason": "the server is restarting; the run continues after the restart"})
356
+ self.svc.audit.append("run.paused_for_restart", actor="system", run_id=run_id, summary="stopped between steps for a restart")
357
+ log.info("run %s stopped between steps for the restart; it continues after it", run_id)
358
+
359
  def _work(self, kind: str, run_id: str, payload, gate: str | None = None) -> None:
360
  run = self.svc.db.get_run(run_id)
361
  if not run or run["status"] == "cancelled" or run_id in self._cancel:
 
383
  return
384
  if self.svc.kill.engaged():
385
  raise KillSwitchEngaged("kill switch engaged between steps")
386
+ if self._shutting_down.is_set():
387
+ self._continue_after_restart(run_id)
388
+ return
389
  snap = self.graph.get_state(cfg)
390
  intr = self._interrupt(snap)
391
  if intr is not None:
coworker/config.py CHANGED
@@ -103,6 +103,11 @@ class Settings(BaseSettings):
103
  return [x for x in cleaned if x]
104
  state_sync: bool = Field(True, validation_alias=_alias("fpt_state_sync", "state_sync"))
105
  state_sync_interval_s: int = Field(60, validation_alias=_alias("fpt_state_sync_interval", "state_sync_interval_s"))
 
 
 
 
 
106
  # A site allowed to show this application inside its own page (a private Hugging Face Space is only reachable that
107
  # way). Empty = never framed by another site. Setting it relaxes the session cookies to SameSite=None.
108
  embed_origin: str = Field("", validation_alias=_alias("fpt_embed_origin", "embed_origin"))
 
103
  return [x for x in cleaned if x]
104
  state_sync: bool = Field(True, validation_alias=_alias("fpt_state_sync", "state_sync"))
105
  state_sync_interval_s: int = Field(60, validation_alias=_alias("fpt_state_sync_interval", "state_sync_interval_s"))
106
+ # how many earlier archives the bucket keeps as state/history/<time>.bin (0 = none), so a bad save can be undone
107
+ state_history_keep: int = Field(5, ge=0, le=50, validation_alias=_alias("fpt_state_history", "state_history_keep"))
108
+ # at shutdown, how long a running test run may take to reach its next step (where it can stop cleanly and continue
109
+ # after the restart) before the last save goes ahead without it. Keep it under the host's stop grace period.
110
+ shutdown_run_wait_s: int = Field(20, ge=0, le=300, validation_alias=_alias("fpt_shutdown_run_wait_s", "shutdown_run_wait_s"))
111
  # A site allowed to show this application inside its own page (a private Hugging Face Space is only reachable that
112
  # way). Empty = never framed by another site. Setting it relaxes the session cookies to SameSite=None.
113
  embed_origin: str = Field("", validation_alias=_alias("fpt_embed_origin", "embed_origin"))
coworker/graph/nodes/ai_scenarios.py CHANGED
@@ -122,9 +122,13 @@ def dry_run(state, svc, pod_id: int, drafts: list[dict]) -> None:
122
  svc.db.add_event(run_id, "test_generator", "ai_scenarios",
123
  {"message": f"dry run of {len(ids)} AI-written scenario(s) on {host if mode == 'live' else 'the simulation'}",
124
  "scenarios": ", ".join(ids)})
125
- res = pw.run_attempt(run_id=run_id, ids=ids, attempt=0, tag="-dryrun", mode=mode, out_file=run_dir / "ai-dry-run.json",
126
- stub_knobs=state.get("stub_knobs"), drafts_dir=specs_dir(svc, run_id), cred_env=cred_env,
127
- backend=svc.cfg.executor_backend, log_dir=run_dir, config="playwright.fusion.config.ts")
 
 
 
 
128
  results = read_dry_run(Path(res["file"]), ids)
129
  if mode == "live": # the values Fusion accepted are tried first next time on this pod
130
  PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).learn_test_data(pod_id, pw.testdata_used_file(run_dir / "ai-dry-run.json"))
 
122
  svc.db.add_event(run_id, "test_generator", "ai_scenarios",
123
  {"message": f"dry run of {len(ids)} AI-written scenario(s) on {host if mode == 'live' else 'the simulation'}",
124
  "scenarios": ", ".join(ids)})
125
+ # the same road as a test attempt: the remote browser runner when one is set (this server's network may be one
126
+ # Oracle's edge refuses), else this server
127
+ from .execute import FUSION_CONFIG, attempt_timeout_s, run_pass
128
+ res = run_pass({"run_id": run_id, "attempt": 0, "tag": "-dryrun", "ids": ids, "mode": mode,
129
+ "out_file": str(run_dir / "ai-dry-run.json"), "stub_knobs": state.get("stub_knobs"),
130
+ "drafts_dir": str(specs_dir(svc, run_id)), "library_dir": None, "overrides": None, "cred_env": cred_env,
131
+ "run_dir": str(run_dir), "config": FUSION_CONFIG, "timeout_s": attempt_timeout_s(svc.cfg, len(ids))}, svc)
132
  results = read_dry_run(Path(res["file"]), ids)
133
  if mode == "live": # the values Fusion accepted are tried first next time on this pod
134
  PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).learn_test_data(pod_id, pw.testdata_used_file(run_dir / "ai-dry-run.json"))
coworker/platform/egress.py CHANGED
@@ -1,19 +1,29 @@
1
  """EgressGate: the ONLY module in coworker/ that imports httpx (enforced by tests/test_single_egress.py).
2
  Every call: kill.check() -> policy -> audit 'egress.request' (exact body after redaction + sha256) -> send ->
3
- audit 'egress.response' (status, bytes, sha256). Auth headers are added here and never logged."""
 
 
 
 
 
 
4
  from __future__ import annotations
5
 
6
  import ipaddress
7
  import json
8
  import re
 
 
9
  from dataclasses import dataclass, field
10
  from typing import Any, Literal
11
  from urllib.parse import urlparse
12
 
13
  import httpx
14
 
15
- from .audit import canonical, sha256_text
 
16
 
 
17
  CLEANUP_PATH = re.compile(r"(/[^/]+)*/fscmRestApi/resources/[0-9A-Za-z._-]+/invoices/action/cancelInvoice")
18
 
19
 
@@ -66,6 +76,8 @@ class EgressGate:
66
  self.cfg, self.audit, self.redactor, self.kill, self.vault = cfg, audit, redactor, kill, vault
67
  self.transport = transport
68
  self.pod = PodContext()
 
 
69
 
70
  # ------------------------------------------------------------ plumbing
71
  def _client(self, timeout: float = 30.0) -> httpx.Client:
@@ -180,11 +192,12 @@ class EgressGate:
180
  # ------------------------------------------------------------ named external service (identity provider, file storage)
181
  def service_request(self, kind: str, method: str, url: str, *, allowed_base: str, headers: dict | None = None,
182
  json_body: dict | None = None, content: bytes | None = None, log_body: Any = None,
183
- timeout: float = 30.0, log_url: str | None = None) -> httpx.Response:
184
  """One call to a configured external service such as Supabase. https only, and only to that service's own host.
185
  `log_body` is what the audit log records: the caller passes a description WITHOUT secrets (never a password, a
186
  key, or file contents); headers are never logged. `log_url` replaces the address in the audit log when the path
187
- itself is a secret (a webhook URL with a token in its path)."""
 
188
  self.kill.check(f"egress.{kind}")
189
  b, u = urlparse(allowed_base), urlparse(url)
190
  shown = log_url or url.split("?", 1)[0] # a refusal is audited too: never with a secret in the address
@@ -192,12 +205,70 @@ class EgressGate:
192
  self._deny(kind, "https is required for an external service", shown, None)
193
  if not b.hostname or (u.scheme, u.hostname, u.port) != (b.scheme, b.hostname, b.port):
194
  self._deny(kind, f"host {u.hostname} is not the configured service {b.hostname}", shown, None)
 
 
195
  self._log_req(kind, method, shown, log_body, None)
196
  with self._client(timeout=timeout) as c:
197
  r = c.request(method, url, headers=headers, json=json_body, content=content)
198
  self._log_resp(kind, shown, r, None)
199
  return r
200
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
201
  # ------------------------------------------------------------ Hermes assistant (OpenAI-compatible /v1 API)
202
  def hermes_request(self, method: Literal["GET", "POST"], path: str, *, key: str, json_body: dict | None = None,
203
  session_id: str | None = None, log_body: Any = None, timeout: float = 120.0) -> httpx.Response:
@@ -280,7 +351,15 @@ class EgressGate:
280
  self._deny("llm_frontier", f"sensitivity {sensitivity} may never go to a frontier model", url, run_id)
281
  if self.vault is not None:
282
  self.redactor.add_secrets(self.vault.secret_values())
283
- leaks = self.redactor.find_leaks(body.get("messages", body))
 
 
 
 
 
 
 
 
284
  if leaks:
285
  self._deny("llm_frontier", f"refused: {len(leaks)} potential leak(s) in the body: {[l['kind'] for l in leaks][:5]}", url, run_id)
286
  self._log_req("llm_frontier", "POST", url, body, run_id, {"task": task, "sensitivity": sensitivity})
 
1
  """EgressGate: the ONLY module in coworker/ that imports httpx (enforced by tests/test_single_egress.py).
2
  Every call: kill.check() -> policy -> audit 'egress.request' (exact body after redaction + sha256) -> send ->
3
+ audit 'egress.response' (status, bytes, sha256). Auth headers are added here and never logged.
4
+
5
+ One exception to a row pair per call: a repeated status poll (service_request with `poll=`: the remote runner's attempt
6
+ state and live frames, every 2 to 5 s, about 7,000 rows an hour otherwise). Its first call is audited as above; later
7
+ 2xx answers are counted into one 'egress.<kind>.polls' row per minute and one when the caller ends the series, with a
8
+ digest over every answer, so the chain still commits to each of them. A poll that answers anything but 2xx, or fails,
9
+ is audited on its own. Refusals, writes and every other call are audited per call as always."""
10
  from __future__ import annotations
11
 
12
  import ipaddress
13
  import json
14
  import re
15
+ import threading
16
+ import time
17
  from dataclasses import dataclass, field
18
  from typing import Any, Literal
19
  from urllib.parse import urlparse
20
 
21
  import httpx
22
 
23
+ from .audit import GENESIS, canonical, sha256_text
24
+ from .rundb import now_iso
25
 
26
+ POLL_ROW_S = 60.0 # a series of polls writes at most one audit row a minute
27
  CLEANUP_PATH = re.compile(r"(/[^/]+)*/fscmRestApi/resources/[0-9A-Za-z._-]+/invoices/action/cancelInvoice")
28
 
29
 
 
76
  self.cfg, self.audit, self.redactor, self.kill, self.vault = cfg, audit, redactor, kill, vault
77
  self.transport = transport
78
  self.pod = PodContext()
79
+ self._polls: dict[str, dict] = {} # poll series -> what was counted and not written yet
80
+ self._polls_lock = threading.Lock()
81
 
82
  # ------------------------------------------------------------ plumbing
83
  def _client(self, timeout: float = 30.0) -> httpx.Client:
 
192
  # ------------------------------------------------------------ named external service (identity provider, file storage)
193
  def service_request(self, kind: str, method: str, url: str, *, allowed_base: str, headers: dict | None = None,
194
  json_body: dict | None = None, content: bytes | None = None, log_body: Any = None,
195
+ timeout: float = 30.0, log_url: str | None = None, poll: str | None = None) -> httpx.Response:
196
  """One call to a configured external service such as Supabase. https only, and only to that service's own host.
197
  `log_body` is what the audit log records: the caller passes a description WITHOUT secrets (never a password, a
198
  key, or file contents); headers are never logged. `log_url` replaces the address in the audit log when the path
199
+ itself is a secret (a webhook URL with a token in its path). `poll` names a series of identical GETs repeated
200
+ every few seconds (see the module docstring); the caller ends it with end_polls(poll)."""
201
  self.kill.check(f"egress.{kind}")
202
  b, u = urlparse(allowed_base), urlparse(url)
203
  shown = log_url or url.split("?", 1)[0] # a refusal is audited too: never with a secret in the address
 
205
  self._deny(kind, "https is required for an external service", shown, None)
206
  if not b.hostname or (u.scheme, u.hostname, u.port) != (b.scheme, b.hostname, b.port):
207
  self._deny(kind, f"host {u.hostname} is not the configured service {b.hostname}", shown, None)
208
+ if poll and method == "GET" and json_body is None and content is None:
209
+ return self._poll(kind, poll, url, shown, headers, log_body, timeout)
210
  self._log_req(kind, method, shown, log_body, None)
211
  with self._client(timeout=timeout) as c:
212
  r = c.request(method, url, headers=headers, json=json_body, content=content)
213
  self._log_resp(kind, shown, r, None)
214
  return r
215
 
216
+ def _poll(self, kind: str, key: str, url: str, shown: str, headers: dict | None, log_body: Any, timeout: float) -> httpx.Response:
217
+ """One GET of a poll series: the first is audited as usual, a later 2xx answer is counted (status, size, digest),
218
+ anything else is audited on its own."""
219
+ with self._polls_lock:
220
+ first = key not in self._polls
221
+ if first:
222
+ self._polls[key] = {"kind": kind, "url": shown, "since": now_iso(), "t0": time.monotonic(), "n": 0, "bytes": 0,
223
+ "digest": GENESIS, "last": None}
224
+ if first:
225
+ self._log_req(kind, "GET", shown, log_body, None, {"poll": key})
226
+ try:
227
+ with self._client(timeout=timeout) as c:
228
+ r = c.request("GET", url, headers=headers)
229
+ except httpx.HTTPError as e:
230
+ if not first:
231
+ self._log_req(kind, "GET", shown, log_body, None, {"poll": key})
232
+ self.audit.append(f"egress.{kind}.error", actor="system", summary=f"{type(e).__name__} {shown}",
233
+ payload={"error": type(e).__name__, "poll": key})
234
+ raise
235
+ if first or not 200 <= r.status_code < 300:
236
+ if not first:
237
+ self._log_req(kind, "GET", shown, log_body, None, {"poll": key})
238
+ self._log_resp(kind, shown, r, None)
239
+ return r
240
+ sha = sha256_text(r.content)
241
+ due = False
242
+ with self._polls_lock:
243
+ p = self._polls.get(key)
244
+ if p is not None:
245
+ p["n"] += 1
246
+ p["bytes"] += len(r.content)
247
+ p["digest"] = sha256_text(p["digest"] + sha) # chained in order: the row commits to every answer it counts
248
+ p["last"] = {"at": now_iso(), "status": r.status_code, "bytes": len(r.content), "sha256": sha}
249
+ due = time.monotonic() - p["t0"] >= POLL_ROW_S
250
+ if due:
251
+ self._write_polls(key, final=False)
252
+ return r
253
+
254
+ def end_polls(self, key: str) -> None:
255
+ """The caller's poll series is over (the attempt finished, failed or was stopped): write what was counted since
256
+ the last row, the last poll among it, and forget the series. Safe to call twice or for an unknown key."""
257
+ self._write_polls(key, final=True)
258
+
259
+ def _write_polls(self, key: str, final: bool) -> None:
260
+ with self._polls_lock:
261
+ p = self._polls.pop(key, None) if final else self._polls.get(key)
262
+ if p is None:
263
+ return
264
+ row = {k: p[k] for k in ("kind", "url", "since", "n", "bytes", "digest", "last")}
265
+ p.update(since=now_iso(), t0=time.monotonic(), n=0, bytes=0, digest=GENESIS, last=None)
266
+ if row["n"]:
267
+ self.audit.append(f"egress.{row['kind']}.polls", actor="system", summary=f"{row['n']} x GET {row['url']} answered 2xx",
268
+ payload={"poll": key, "count": row["n"], "bytes": row["bytes"], "since": row["since"],
269
+ "until": (row["last"] or {}).get("at"), "answers_sha256": row["digest"],
270
+ "last": row["last"], "final": final})
271
+
272
  # ------------------------------------------------------------ Hermes assistant (OpenAI-compatible /v1 API)
273
  def hermes_request(self, method: Literal["GET", "POST"], path: str, *, key: str, json_body: dict | None = None,
274
  session_id: str | None = None, log_body: Any = None, timeout: float = 120.0) -> httpx.Response:
 
351
  self._deny("llm_frontier", f"sensitivity {sensitivity} may never go to a frontier model", url, run_id)
352
  if self.vault is not None:
353
  self.redactor.add_secrets(self.vault.secret_values())
354
+ # the system message is a prompt file shipped with the product (checked for data by the test suite), never
355
+ # data: a client's name that happens to be an ordinary word in it ("Standard", "Payments") must not refuse
356
+ # every call. Everything else (the request's data) is checked, secrets included in every message.
357
+ msgs = body.get("messages", body)
358
+ data = [m for m in msgs if not (isinstance(m, dict) and m.get("role") == "system")] if isinstance(msgs, list) else msgs
359
+ leaks = self.redactor.find_leaks(data)
360
+ if isinstance(msgs, list):
361
+ system = [m for m in msgs if isinstance(m, dict) and m.get("role") == "system"]
362
+ leaks += [x for x in self.redactor.find_leaks(system) if x["kind"] == "secret"]
363
  if leaks:
364
  self._deny("llm_frontier", f"refused: {len(leaks)} potential leak(s) in the body: {[l['kind'] for l in leaks][:5]}", url, run_id)
365
  self._log_req("llm_frontier", "POST", url, body, run_id, {"task": task, "sensitivity": sensitivity})
coworker/platform/evidence.py CHANGED
@@ -31,6 +31,15 @@ class NotConfigured(RuntimeError):
31
  pass
32
 
33
 
 
 
 
 
 
 
 
 
 
34
  @dataclass
35
  class EvidenceRef:
36
  evidence_id: int
@@ -149,7 +158,7 @@ class LocalEncryptedStore:
149
  raise FileNotFoundError(f"evidence {evidence_id} not found or purged")
150
  blob = self._blob(row)
151
  if blob is None: # the file went away (lost disk, restore without evidence): no server path in the message
152
- raise FileNotFoundError(f"evidence {evidence_id} is no longer stored on this server")
153
  data = self._fernet().decrypt(blob)
154
  if self.audit:
155
  self.audit.append("evidence.read", actor=actor, run_id=row["run_id"], summary=f"evidence {evidence_id} {row['name']}")
 
31
  pass
32
 
33
 
34
+ class EvidenceMissing(FileNotFoundError):
35
+ """The evidence row exists but its file is gone (a lost disk, or a restore of an archive that left the evidence out).
36
+ Carries the row's run and time so the route can tell which of the two it was."""
37
+
38
+ def __init__(self, msg: str, run_id: str | None = None, created_at: str | None = None):
39
+ super().__init__(msg)
40
+ self.run_id, self.created_at = run_id, created_at
41
+
42
+
43
  @dataclass
44
  class EvidenceRef:
45
  evidence_id: int
 
158
  raise FileNotFoundError(f"evidence {evidence_id} not found or purged")
159
  blob = self._blob(row)
160
  if blob is None: # the file went away (lost disk, restore without evidence): no server path in the message
161
+ raise EvidenceMissing(f"evidence {evidence_id} is no longer stored on this server", row["run_id"], row.get("created_at"))
162
  data = self._fernet().decrypt(blob)
163
  if self.audit:
164
  self.audit.append("evidence.read", actor=actor, run_id=row["run_id"], summary=f"evidence {evidence_id} {row['name']}")
coworker/platform/notify.py CHANGED
@@ -377,6 +377,9 @@ class Notifier:
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(" ()", ""),
379
  "/tickets")
 
 
 
380
  return f"{self.cfg.product_name}: {kind}", "", f"/runs/{rid}" if rid else "/"
381
 
382
  # ------------------------------------------------------------ list (the app's notifications)
 
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(" ()", ""),
379
  "/tickets")
380
+ if kind == "state.left_out": # platform/statesync.py: the saved copy is over the size limit
381
+ return ("Some files are not in the saved copy", str(extra.get("note") or "The saved copy is over the size limit."),
382
+ "/admin?tab=storage")
383
  return f"{self.cfg.product_name}: {kind}", "", f"/runs/{rid}" if rid else "/"
384
 
385
  # ------------------------------------------------------------ list (the app's notifications)
coworker/platform/ocistore.py CHANGED
@@ -27,7 +27,7 @@ def par_url(vault=None) -> str:
27
 
28
 
29
  class OciParStore:
30
- """The storage half of platform/supabase.Supabase (ensure_bucket, upload, download, remove), on an OCI bucket."""
31
  kind = "oci"
32
 
33
  def __init__(self, cfg, egress, vault):
@@ -36,6 +36,7 @@ class OciParStore:
36
  u = urlparse(self.url)
37
  self.base = f"{u.scheme}://{u.netloc}" if self.url else ""
38
  self.shown = re.sub(r"/p/[^/]+/", "/p/***/", self.url) # what the audit log sees
 
39
 
40
  @property
41
  def storage_enabled(self) -> bool:
@@ -69,6 +70,21 @@ class OciParStore:
69
  raise SupabaseError("STORAGE", f"download from the OCI bucket failed: HTTP {r.status_code} {r.text[:160]}", 502)
70
  return r.content
71
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
72
  def remove(self, path: str) -> None:
73
  r = self._call("DELETE", path, action="remove")
74
  if r.status_code >= 400 and r.status_code != 404:
 
27
 
28
 
29
  class OciParStore:
30
+ """The storage half of platform/supabase.Supabase (ensure_bucket, upload, download, list, remove), on an OCI bucket."""
31
  kind = "oci"
32
 
33
  def __init__(self, cfg, egress, vault):
 
36
  u = urlparse(self.url)
37
  self.base = f"{u.scheme}://{u.netloc}" if self.url else ""
38
  self.shown = re.sub(r"/p/[^/]+/", "/p/***/", self.url) # what the audit log sees
39
+ self.list_denied = False
40
 
41
  @property
42
  def storage_enabled(self) -> bool:
 
70
  raise SupabaseError("STORAGE", f"download from the OCI bucket failed: HTTP {r.status_code} {r.text[:160]}", 502)
71
  return r.content
72
 
73
+ def list(self, prefix: str) -> list[str] | None:
74
+ """The names of the objects under `prefix`, or None when this address may not list (the recommended address
75
+ denies listing; statesync then keeps the names in meta.json). Asked once per process at most when refused."""
76
+ if self.list_denied:
77
+ return None
78
+ r = self.egress.service_request("oci_storage", "GET", f"{self.url}?prefix={quote(prefix, safe='')}&fields=name",
79
+ allowed_base=self.base, log_body={"action": "list", "prefix": prefix}, log_url=self.shown,
80
+ timeout=60)
81
+ if r.status_code in (401, 403, 404):
82
+ self.list_denied = True
83
+ return None
84
+ if r.status_code >= 400:
85
+ raise SupabaseError("STORAGE", f"listing the OCI bucket failed: HTTP {r.status_code} {r.text[:160]}", 502)
86
+ return [o["name"] for o in (r.json().get("objects") or []) if isinstance(o, dict) and o.get("name")]
87
+
88
  def remove(self, path: str) -> None:
89
  r = self._call("DELETE", path, action="remove")
90
  if r.status_code >= 400 and r.status_code != 404:
coworker/platform/statesync.py CHANGED
@@ -5,9 +5,15 @@ The product stores its state under FPT_HOME (SQLite database, secrets vault, rep
5
  On hosts without a persistent disk that folder is empty after every restart. This module saves an encrypted archive
6
  of it to a private Supabase bucket whenever business data has changed, and restores it when the folder is empty.
7
 
8
- This is snapshot persistence for a single instance: it is not a live Postgres database. Two instances writing to the
9
- same bucket would overwrite each other. The archive is encrypted before it leaves (Fernet); the key comes from
10
- FPT_STATE_KEY, or is derived from the Supabase service key when that is not set."""
 
 
 
 
 
 
11
  from __future__ import annotations
12
 
13
  import base64
@@ -20,6 +26,7 @@ import sqlite3
20
  import tarfile
21
  import tempfile
22
  import threading
 
23
  from pathlib import Path
24
 
25
  from cryptography.fernet import Fernet, InvalidToken
@@ -30,7 +37,11 @@ from .rundb import now_iso
30
  log = logging.getLogger("fpt.statesync")
31
  OBJECT, META = "state/latest.bin", "state/meta.json"
32
  PREVIOUS = "state/previous.bin" # the archive that was in the bucket when this process made its first save
 
33
  FAILED_MARKER = ".state-restore-failed" # written at boot when the saved state could not be read; blocks saving
 
 
 
34
  DATABASES = ("fpt.sqlite", "checkpoints.sqlite")
35
  # screens: what the scout read on each pod; library: the approved scenarios (the regression pack). Both are written next
36
  # to a database row that says they exist, so leaving them out made a restart forget them while the rows still claimed them
@@ -117,38 +128,252 @@ def restore_failed(home: Path | str) -> bool:
117
  return (Path(home) / FAILED_MARKER).exists()
118
 
119
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
120
  def push(svc, reason: str = "changed") -> dict:
 
 
121
  client = store_of(svc)
122
- home = svc.cfg.home
123
  if restore_failed(home):
124
  # Starting empty because the saved state could not be read must never replace that saved state with nothing.
125
  raise sb.SupabaseError("STATE_RESTORE_FAILED", "saving is paused: the saved state could not be read when this instance started. "
126
  "Restart the instance to try again.", 503)
 
 
 
 
127
  if "state_signature" not in svc.extra:
128
  _keep_previous(client)
129
- data = build_archive(home)
130
- note, left_out = "", []
131
- if len(data) > MAX_BYTES:
132
- data, note, left_out = build_archive(home, include_evidence=False), " (evidence left out: the archive was too large)", ["evidence"]
133
- if len(data) > MAX_BYTES: # still too large: leave out the folders of finished runs too (their rows and events stay)
134
- old = {r["run_id"] for r in svc.db.q("SELECT run_id FROM runs WHERE status IN ('completed','failed','killed','cancelled')")}
135
- data = build_archive(home, include_evidence=False, skip_runs=old)
136
- note, left_out = " (evidence and finished runs' folders left out: the archive was too large)", ["evidence", "finished_run_folders"]
137
- if len(data) > MAX_BYTES:
138
- raise sb.SupabaseError("STATE_TOO_LARGE", f"the saved state is {len(data) // (1024 * 1024)} MB even without evidence and old run "
139
- f"folders, above the {MAX_BYTES // (1024 * 1024)} MB limit; it was not saved", 507)
140
  blob = _fernet(client).encrypt(data)
141
  client.ensure_bucket()
 
 
 
 
 
 
142
  client.upload(OBJECT, blob)
143
  meta = {"saved_at": now_iso(), "bytes": len(blob), "sha256": hashlib.sha256(blob).hexdigest(), "reason": reason + note,
144
- "left_out": left_out}
 
 
145
  client.upload(META, json.dumps(meta).encode())
 
 
146
  svc.extra["state_signature"] = signature(svc)
147
  svc.extra["state_last"] = meta
148
- log.info("state saved to Supabase Storage: %d bytes (%s)", len(blob), reason + note)
 
149
  return meta
150
 
151
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
152
  def _keep_previous(client: sb.Supabase) -> None:
153
  """First save of this process: keep a copy of what the bucket holds now, so one bad save can always be undone by hand
154
  (copy state/previous.bin back over state/latest.bin). Best effort: a failure here never stops the save."""
@@ -161,18 +386,41 @@ def _keep_previous(client: sb.Supabase) -> None:
161
  log.warning("could not keep the previous state archive: %s", e)
162
 
163
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
164
  def restore_at_boot(cfg, client: sb.Supabase, attempts: int = 4, wait_s: float = 3.0, sleep=None) -> tuple[bool, str | None]:
165
  """The start-up restore: retries a few times (the network may not be up yet) and, when the saved state still cannot be
166
- read, writes FAILED_MARKER so this instance (which then starts empty) does not overwrite the saved state.
167
- Returns (restored, error). 'No saved state yet' is not an error."""
168
  import time
169
  sleep = sleep or time.sleep
170
  home = Path(cfg.home)
171
- (home / FAILED_MARKER).unlink(missing_ok=True) # a marker from an earlier start on a persistent disk is stale
172
- err = ""
 
173
  for i in range(max(1, attempts)):
174
  try:
175
- return restore(cfg, client), None
 
 
176
  except Exception as e: # noqa: BLE001 - network, storage and key problems all end the same way
177
  err = f"{type(e).__name__}: {str(e)[:200]}"
178
  log.warning("state restore attempt %d failed: %s", i + 1, err)
 
5
  On hosts without a persistent disk that folder is empty after every restart. This module saves an encrypted archive
6
  of it to a private Supabase bucket whenever business data has changed, and restores it when the folder is empty.
7
 
8
+ This is snapshot persistence for a single instance: it is not a live Postgres database. Two instances can still be up
9
+ for a while, though: a Hugging Face rebuild keeps the old container running while the new one restores and starts. So
10
+ meta.json carries a generation number and the id of the instance that wrote it. An instance takes the next generation
11
+ when it starts (restore_at_boot), every save first reads meta.json, and an instance that finds the bucket moved on by
12
+ another one stops saving (FENCED_MARKER) instead of overwriting the newer state. Each save also keeps a copy under
13
+ state/history/ (the newest Settings.state_history_keep of them), so a bad save can be undone (docs/RUNBOOK.md).
14
+
15
+ The archive is encrypted before it leaves (Fernet); the key comes from FPT_STATE_KEY, or is derived from the Supabase
16
+ service key when that is not set."""
17
  from __future__ import annotations
18
 
19
  import base64
 
26
  import tarfile
27
  import tempfile
28
  import threading
29
+ from datetime import datetime, timezone
30
  from pathlib import Path
31
 
32
  from cryptography.fernet import Fernet, InvalidToken
 
37
  log = logging.getLogger("fpt.statesync")
38
  OBJECT, META = "state/latest.bin", "state/meta.json"
39
  PREVIOUS = "state/previous.bin" # the archive that was in the bucket when this process made its first save
40
+ HISTORY = "state/history/" # one copy per save; the newest Settings.state_history_keep are kept
41
  FAILED_MARKER = ".state-restore-failed" # written at boot when the saved state could not be read; blocks saving
42
+ FENCED_MARKER = ".state-fenced" # written when another instance has saved since this one started; blocks saving
43
+ RECORD = ".state-sync.json" # this instance's id, the generation it last saw, what its restore lacked
44
+ PRUNE_EVERY_S = 3600 # old history copies are deleted at most once an hour (an OCI bucket counts requests)
45
  DATABASES = ("fpt.sqlite", "checkpoints.sqlite")
46
  # screens: what the scout read on each pod; library: the approved scenarios (the regression pack). Both are written next
47
  # to a database row that says they exist, so leaving them out made a restart forget them while the rows still claimed them
 
128
  return (Path(home) / FAILED_MARKER).exists()
129
 
130
 
131
+ def fenced(home: Path | str) -> dict | None:
132
+ """What fenced this instance off (another instance saved or started after it), or None while it may save."""
133
+ p = Path(home) / FENCED_MARKER
134
+ if not p.exists():
135
+ return None
136
+ try:
137
+ return json.loads(p.read_text(encoding="utf-8")) or {}
138
+ except (OSError, ValueError):
139
+ return {}
140
+
141
+
142
+ def paused_reason(home: Path | str) -> str | None:
143
+ """Why this instance does not save: "restore_failed", "fenced", or None when it saves."""
144
+ return "restore_failed" if restore_failed(home) else "fenced" if fenced(home) is not None else None
145
+
146
+
147
+ def record(home: Path | str) -> dict:
148
+ """This instance's record (RECORD): kept next to the data, never in the archive, so each container has its own."""
149
+ try:
150
+ r = json.loads((Path(home) / RECORD).read_text(encoding="utf-8"))
151
+ return r if isinstance(r, dict) else {}
152
+ except (OSError, ValueError):
153
+ return {}
154
+
155
+
156
+ def _write_record(home: Path | str, rec: dict) -> None:
157
+ p = Path(home) / RECORD
158
+ p.parent.mkdir(parents=True, exist_ok=True)
159
+ tmp = p.with_name(RECORD + ".tmp")
160
+ tmp.write_text(json.dumps(rec), encoding="utf-8")
161
+ tmp.replace(p)
162
+
163
+
164
+ def _new_instance() -> str:
165
+ """An id for this container: its host name (what an operator recognises in the logs) and a random part."""
166
+ import platform # not socket: only platform/egress.py imports network modules (tests/test_static.py)
167
+ import uuid
168
+ return f"{(platform.node() or 'instance')[:40]}-{uuid.uuid4().hex[:8]}"
169
+
170
+
171
+ def _read_meta(client) -> dict:
172
+ """meta.json as it is in the bucket now: {} when there is none, or when it cannot be parsed (then it counts as
173
+ generation 0, as written before generations existed). A failed download raises: nothing is saved blind."""
174
+ raw = client.download(META)
175
+ if not raw:
176
+ return {}
177
+ try:
178
+ m = json.loads(raw)
179
+ except ValueError:
180
+ log.warning("state/meta.json in the bucket is not valid JSON: treated as generation 0")
181
+ return {}
182
+ return m if isinstance(m, dict) else {}
183
+
184
+
185
+ def _generation(meta: dict) -> int:
186
+ try:
187
+ return int(meta.get("generation") or 0)
188
+ except (TypeError, ValueError):
189
+ return 0
190
+
191
+
192
+ def _fenced_error() -> sb.SupabaseError:
193
+ return sb.SupabaseError("STATE_FENCED", "saving is paused: another instance of the app has saved its data since this one "
194
+ "started, so this one no longer saves and cannot overwrite it. Restart the app to continue from "
195
+ "the newer data.", 409)
196
+
197
+
198
+ def _check_fence(svc, home: Path, meta: dict) -> tuple[dict, int]:
199
+ """Before a save: is the bucket still where this instance last left it? It is when meta.json holds the generation and
200
+ writer this instance last saw or wrote, or was written by this instance itself (a save whose answer was lost).
201
+ Anything else means another instance has saved or started since: write FENCED_MARKER, log, audit, notify, refuse.
202
+ Returns this instance's record and the generation the save writes."""
203
+ rec = record(home)
204
+ now = [_generation(meta), meta.get("instance")]
205
+ if not rec.get("instance"):
206
+ # no record: a process that did not start through the boot restore (the CLI, a disk kept from before
207
+ # generations existed) takes the bucket as it is now
208
+ rec = {"instance": _new_instance(), "seen": now, "adopted_at": now_iso()}
209
+ _write_record(home, rec)
210
+ if now[1] != rec["instance"] and now != list(rec.get("seen") or [0, None]):
211
+ info = {"at": now_iso(), "instance": rec["instance"], "seen": rec.get("seen"), "bucket_generation": now[0],
212
+ "bucket_instance": now[1], "bucket_saved_at": meta.get("saved_at"), "bucket_claimed_at": meta.get("claimed_at")}
213
+ (home / FENCED_MARKER).write_text(json.dumps(info), encoding="utf-8")
214
+ log.error("state saving stopped: the bucket is at generation %s written by %s, this instance (%s) last saw %s: "
215
+ "another instance has taken over", now[0], now[1], rec["instance"], rec.get("seen"))
216
+ # no notification: on Hugging Face this is the normal end of the old container at every rebuild (its shutdown
217
+ # save comes after the new one has started); the banner on that container and this audit entry say it
218
+ try:
219
+ svc.audit.append("state.fenced", actor="system", summary=f"saving stopped: the bucket is at generation {now[0]} "
220
+ f"written by {now[1]}; this instance {rec['instance']} last saw {rec.get('seen')}", payload=info)
221
+ except Exception: # noqa: BLE001 - the refusal below is what matters
222
+ log.exception("could not record that saving stopped")
223
+ raise _fenced_error()
224
+ return rec, now[0] + 1
225
+
226
+
227
+ def _folder_summary(p: Path) -> dict:
228
+ files = [f for f in p.rglob("*") if f.is_file()] if p.is_dir() else []
229
+ return {"files": len(files), "bytes": sum(f.stat().st_size for f in files),
230
+ "runs": sorted(c.name for c in p.iterdir() if c.is_dir()) if p.is_dir() else []}
231
+
232
+
233
+ def _archive_within_limit(svc, home: Path) -> tuple[bytes, list[str], dict]:
234
+ """The archive, and what had to be left out to keep it under MAX_BYTES: first the evidence (screenshots, videos,
235
+ traces), then the folders of finished runs (their rows and events stay). The detail says exactly what: file counts,
236
+ sizes and run ids, so the Storage page and the evidence routes can tell people."""
237
+ data = build_archive(home)
238
+ if len(data) <= MAX_BYTES:
239
+ return data, [], {}
240
+ left, detail = ["evidence"], {"evidence": _folder_summary(home / "evidence")}
241
+ data = build_archive(home, include_evidence=False)
242
+ if len(data) > MAX_BYTES: # still too large: leave out the folders of finished runs too (their rows and events stay)
243
+ old = {r["run_id"] for r in svc.db.q("SELECT run_id FROM runs WHERE status IN ('completed','failed','killed','cancelled')")}
244
+ runs = home / "runs"
245
+ present = sorted(c.name for c in runs.iterdir() if c.is_dir() and c.name in old) if runs.is_dir() else []
246
+ data = build_archive(home, include_evidence=False, skip_runs=old)
247
+ left.append("finished_run_folders")
248
+ detail["finished_run_folders"] = {"count": len(present), "runs": present}
249
+ if len(data) > MAX_BYTES:
250
+ raise sb.SupabaseError("STATE_TOO_LARGE", f"the saved state is {len(data) // (1024 * 1024)} MB even without evidence and old run "
251
+ f"folders, above the {MAX_BYTES // (1024 * 1024)} MB limit; it was not saved", 507)
252
+ return data, left, detail
253
+
254
+
255
+ def left_out_note(meta: dict | None) -> str | None:
256
+ """The sentence people see when the last save left something out; None when the saved copy holds everything."""
257
+ left = (meta or {}).get("left_out") or []
258
+ if not left:
259
+ return None
260
+ d = (meta or {}).get("left_out_detail") or {}
261
+ parts = []
262
+ if "evidence" in left:
263
+ ev = d.get("evidence") or {}
264
+ size = f" ({ev['files']} files, {max(1, round((ev.get('bytes') or 0) / (1024 * 1024)))} MB)" if ev.get("files") is not None else ""
265
+ parts.append("screenshots, videos and traces" + size)
266
+ if "finished_run_folders" in left:
267
+ n = (d.get("finished_run_folders") or {}).get("count")
268
+ parts.append(f"the folders of {n} finished runs (their reports and logs)" if n is not None
269
+ else "the folders of finished runs (their reports and logs)")
270
+ return ("The saved copy is over the size limit, so it does not hold " + " or ".join(parts) + ". They will not be there "
271
+ "after a restart; run records, results and the audit log are kept.")
272
+
273
+
274
+ def _warn_left_out(svc, before: dict, meta: dict) -> None:
275
+ """Once per change of what is left out (compared with the bucket's previous save, so a restart does not repeat it):
276
+ an audit entry, and a notification when something more is now missing. Never raises."""
277
+ was, now = set(before.get("left_out") or []), set(meta.get("left_out") or [])
278
+ if was == now:
279
+ return
280
+ try:
281
+ note = left_out_note(meta) or "The saved copy holds everything again."
282
+ svc.audit.append("state.left_out", actor="system", summary=note[:300],
283
+ payload={"left_out": sorted(now), "before": sorted(was), "detail": meta.get("left_out_detail")})
284
+ if now - was:
285
+ from . import notify
286
+ notify.get(svc).emit("state.left_out", None, note=note)
287
+ log.warning("state save: %s", note)
288
+ except Exception: # noqa: BLE001
289
+ log.exception("could not record what the save left out")
290
+
291
+
292
+ def _prune_history(client, meta: dict, keep: int) -> None:
293
+ """Delete history copies beyond the newest `keep`, at most once an hour. The names come from meta.json's own list and,
294
+ when the store may list (Supabase; an OCI address that allows it), from the bucket's listing too, which also finds
295
+ copies a lost meta.json forgot. Best effort: a copy that could not be deleted is tried again next time."""
296
+ last, now = meta.get("history_pruned_at"), datetime.now(timezone.utc) # one clock for the check and the record
297
+ try:
298
+ if last and (now - datetime.fromisoformat(last)).total_seconds() < PRUNE_EVERY_S:
299
+ return
300
+ except (TypeError, ValueError):
301
+ pass
302
+ names = set(meta.get("history") or [])
303
+ try:
304
+ names |= set(client.list(HISTORY) or [])
305
+ except Exception as e: # noqa: BLE001
306
+ log.warning("could not list the state history: %s", e)
307
+ ordered = sorted((n for n in names if n.startswith(HISTORY)), reverse=True) # the names are times: newest first
308
+ failed = []
309
+ for n in ordered[keep:]:
310
+ try:
311
+ client.remove(n)
312
+ except Exception as e: # noqa: BLE001
313
+ log.warning("could not delete the old state copy %s: %s", n, e)
314
+ failed.append(n)
315
+ meta["history"] = ordered[:keep] + failed
316
+ meta["history_pruned_at"] = now.isoformat(timespec="seconds")
317
+
318
+
319
  def push(svc, reason: str = "changed") -> dict:
320
+ """One save. Requests: GET meta.json (the fence check), PUT the history copy, PUT latest.bin, PUT meta.json; the first
321
+ save of a process also copies latest.bin to previous.bin, and once an hour old history copies are deleted."""
322
  client = store_of(svc)
323
+ home = Path(svc.cfg.home)
324
  if restore_failed(home):
325
  # Starting empty because the saved state could not be read must never replace that saved state with nothing.
326
  raise sb.SupabaseError("STATE_RESTORE_FAILED", "saving is paused: the saved state could not be read when this instance started. "
327
  "Restart the instance to try again.", 503)
328
+ if fenced(home) is not None:
329
+ raise _fenced_error() # no request: a fenced instance stays quiet until it is restarted
330
+ before = _read_meta(client)
331
+ rec, generation = _check_fence(svc, home, before)
332
  if "state_signature" not in svc.extra:
333
  _keep_previous(client)
334
+ data, left_out, detail = _archive_within_limit(svc, home)
335
+ note = ("", " (evidence left out: the archive was too large)",
336
+ " (evidence and finished runs' folders left out: the archive was too large)")[len(left_out)]
 
 
 
 
 
 
 
 
337
  blob = _fernet(client).encrypt(data)
338
  client.ensure_bucket()
339
+ keep = max(0, int(getattr(svc.cfg, "state_history_keep", 5)))
340
+ history = [h for h in before.get("history") or [] if isinstance(h, str) and h.startswith(HISTORY)]
341
+ if keep:
342
+ name = f"{HISTORY}{datetime.now(timezone.utc):%Y%m%dT%H%M%SZ}.bin"
343
+ client.upload(name, blob)
344
+ history = [name] + [h for h in history if h != name]
345
  client.upload(OBJECT, blob)
346
  meta = {"saved_at": now_iso(), "bytes": len(blob), "sha256": hashlib.sha256(blob).hexdigest(), "reason": reason + note,
347
+ "left_out": left_out, "left_out_detail": detail, "generation": generation, "instance": rec["instance"],
348
+ "history": history, "history_pruned_at": before.get("history_pruned_at")}
349
+ _prune_history(client, meta, keep)
350
  client.upload(META, json.dumps(meta).encode())
351
+ rec["seen"] = [generation, rec["instance"]]
352
+ _write_record(home, rec)
353
  svc.extra["state_signature"] = signature(svc)
354
  svc.extra["state_last"] = meta
355
+ _warn_left_out(svc, before, meta) # after the signature: its audit entry and notice go out with the next save
356
+ log.info("state saved: %d bytes, generation %d (%s)", len(blob), generation, reason + note)
357
  return meta
358
 
359
 
360
+ def last_meta(svc) -> dict:
361
+ """What the last save wrote; before this instance's first save, what the archive it restored said about itself."""
362
+ return svc.extra.get("state_last") or (record(svc.cfg.home).get("restored") or {})
363
+
364
+
365
+ def not_kept_after_restart(home: Path | str, what: str, run_id: str | None = None, created_at: str | None = None) -> bool:
366
+ """Was this file left out of the archive this instance restored (so it is gone, not merely missing)? `what` is
367
+ "evidence" (one evidence row, created at `created_at`) or "run_folder" (the folder of `run_id`)."""
368
+ r = record(home).get("restored") or {}
369
+ left, detail = r.get("left_out") or [], r.get("left_out_detail") or {}
370
+ if what == "evidence":
371
+ return "evidence" in left and (not created_at or not r.get("saved_at") or str(created_at) <= str(r["saved_at"]))
372
+ if what == "run_folder":
373
+ return "finished_run_folders" in left and run_id in ((detail.get("finished_run_folders") or {}).get("runs") or [])
374
+ return False
375
+
376
+
377
  def _keep_previous(client: sb.Supabase) -> None:
378
  """First save of this process: keep a copy of what the bucket holds now, so one bad save can always be undone by hand
379
  (copy state/previous.bin back over state/latest.bin). Best effort: a failure here never stops the save."""
 
386
  log.warning("could not keep the previous state archive: %s", e)
387
 
388
 
389
+ def _claim(home: Path, client) -> dict:
390
+ """Start-up, after the restore: this instance takes the bucket over by writing meta.json with the next generation and
391
+ its own id. An older instance still running (Hugging Face keeps the old container up while the new one starts) is
392
+ then refused at its next save, its shutdown save included, instead of overwriting what this one restored. Also
393
+ records what the restored archive had left out, so a missing screenshot can be explained (not_kept_after_restart)."""
394
+ meta = _read_meta(client)
395
+ rec = {"instance": _new_instance(), "restored_at": now_iso(),
396
+ "restored": {k: meta.get(k) for k in ("saved_at", "bytes", "generation", "instance", "left_out", "left_out_detail", "history")}}
397
+ claim = {**meta, "generation": _generation(meta) + 1, "instance": rec["instance"], "claimed_at": now_iso()}
398
+ try:
399
+ client.ensure_bucket()
400
+ client.upload(META, json.dumps(claim).encode())
401
+ rec["seen"] = [claim["generation"], rec["instance"]]
402
+ except Exception as e: # noqa: BLE001 - the first save then checks against what was read
403
+ log.warning("could not claim the saved state for this instance: %s", e)
404
+ rec["seen"] = [_generation(meta), meta.get("instance")]
405
+ _write_record(home, rec)
406
+ return rec
407
+
408
+
409
  def restore_at_boot(cfg, client: sb.Supabase, attempts: int = 4, wait_s: float = 3.0, sleep=None) -> tuple[bool, str | None]:
410
  """The start-up restore: retries a few times (the network may not be up yet) and, when the saved state still cannot be
411
+ read, writes FAILED_MARKER so this instance (which then starts empty) does not overwrite the saved state. Then this
412
+ instance claims the next generation (_claim). Returns (restored, error). 'No saved state yet' is not an error."""
413
  import time
414
  sleep = sleep or time.sleep
415
  home = Path(cfg.home)
416
+ for stale in (FAILED_MARKER, FENCED_MARKER): # a marker from an earlier start on a persistent disk is stale
417
+ (home / stale).unlink(missing_ok=True)
418
+ err, done = "", False
419
  for i in range(max(1, attempts)):
420
  try:
421
+ done = restore(cfg, client) or done # a retry after a failed claim finds the data already restored
422
+ _claim(home, client)
423
+ return done, None
424
  except Exception as e: # noqa: BLE001 - network, storage and key problems all end the same way
425
  err = f"{type(e).__name__}: {str(e)[:200]}"
426
  log.warning("state restore attempt %d failed: %s", i + 1, err)
coworker/platform/step_writer.py CHANGED
@@ -49,6 +49,9 @@ ALLOWED_ACTIONS: dict[str, str] = {
49
  "add_line": "value = the line amount; adds one Item line with the distribution account {{pod.ap.account}}",
50
  "save": "presses Save",
51
  "invoice_action": "value = an entry of the 'Invoice Actions' menu in the inventory (for example Validate)",
 
 
 
52
  "expect_status": "value = the status the page must show (for example Validated, Approved, Open)",
53
  # any screen
54
  "add_row": "field = the section whose table gets a new row (a section or table name in the inventory, e.g. Lines); "
@@ -269,9 +272,11 @@ def check_steps(draft: StepsDraft | dict, inv: dict, intent_type: str = "happy",
269
  number_entered = False
270
  opened_screens.add(norm_task(s.value))
271
  opened = True
272
- if a in ("enter", "expect_filled", "expect_value", "remember", "add_line", "save", "invoice_action", "click", "add_row",
273
  "enter_in_row", "menu_action", "expect_results") and not opened:
274
  problems.append(f"step {i}: {a} comes before open_task")
 
 
275
  if a == "invoice_action" and s.value and s.value not in sc.actions_menu:
276
  problems.append(f"step {i}: '{s.value}' is not in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
277
  if a == "click" and s.value and norm_label(s.value) not in sc.buttons:
@@ -685,7 +690,7 @@ def stub_write_steps(payload: dict) -> StepsDraft:
685
  steps += [{"action": "add_line", "value": "{{tv.amount}}", "expected": "One line with the distribution account."},
686
  {"action": "save", "expected": "The document is saved without errors."}]
687
  if "Validate" in menu:
688
- steps += [{"action": "invoice_action", "value": "Validate"},
689
  {"action": "expect_status", "value": "Validated", "expected": "The page shows the status Validated."}]
690
  result = "The document is saved" + (" and validated." if "Validate" in menu else ".")
691
  else:
 
49
  "add_line": "value = the line amount; adds one Item line with the distribution account {{pod.ap.account}}",
50
  "save": "presses Save",
51
  "invoice_action": "value = an entry of the 'Invoice Actions' menu in the inventory (for example Validate)",
52
+ "validate_invoice": "Invoice Actions > Validate as an AP clerk does it: when Fusion's tax or freight leaves the invoice out "
53
+ "of balance, the invoice amount is set to the Total and it is validated again. Use it when the "
54
+ "scenario expects the invoice to validate; never in a scenario that tests an amount mismatch",
55
  "expect_status": "value = the status the page must show (for example Validated, Approved, Open)",
56
  # any screen
57
  "add_row": "field = the section whose table gets a new row (a section or table name in the inventory, e.g. Lines); "
 
272
  number_entered = False
273
  opened_screens.add(norm_task(s.value))
274
  opened = True
275
+ if a in ("enter", "expect_filled", "expect_value", "remember", "add_line", "save", "invoice_action", "validate_invoice", "click", "add_row",
276
  "enter_in_row", "menu_action", "expect_results") and not opened:
277
  problems.append(f"step {i}: {a} comes before open_task")
278
+ if a == "validate_invoice" and "Validate" not in sc.actions_menu:
279
+ problems.append(f"step {i}: validate_invoice needs Validate in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
280
  if a == "invoice_action" and s.value and s.value not in sc.actions_menu:
281
  problems.append(f"step {i}: '{s.value}' is not in the Invoice Actions menu ({', '.join(sc.actions_menu) or 'no such menu on this screen'})")
282
  if a == "click" and s.value and norm_label(s.value) not in sc.buttons:
 
690
  steps += [{"action": "add_line", "value": "{{tv.amount}}", "expected": "One line with the distribution account."},
691
  {"action": "save", "expected": "The document is saved without errors."}]
692
  if "Validate" in menu:
693
+ steps += [{"action": "validate_invoice"},
694
  {"action": "expect_status", "value": "Validated", "expected": "The page shows the status Validated."}]
695
  result = "The document is saved" + (" and validated." if "Validate" in menu else ".")
696
  else:
coworker/platform/supabase.py CHANGED
@@ -140,6 +140,16 @@ class Supabase:
140
  if r.status_code >= 400 and r.status_code != 404 and not _not_found(r):
141
  raise SupabaseError("STORAGE", f"remove failed: HTTP {r.status_code} {r.text[:160]}", 502)
142
 
 
 
 
 
 
 
 
 
 
 
143
  def download(self, path: str) -> bytes | None:
144
  key = self.service_key()
145
  p = f"/storage/v1/object/{quote(self.cfg.supabase_bucket)}/{quote(path)}"
 
140
  if r.status_code >= 400 and r.status_code != 404 and not _not_found(r):
141
  raise SupabaseError("STORAGE", f"remove failed: HTTP {r.status_code} {r.text[:160]}", 502)
142
 
143
+ def list(self, prefix: str) -> list[str]:
144
+ """The names of the objects under `prefix` (a folder such as state/history/), as full paths."""
145
+ key = self.service_key()
146
+ folder = prefix.rstrip("/")
147
+ r = self._call("storage", "POST", f"/storage/v1/object/list/{quote(self.cfg.supabase_bucket)}", key=key,
148
+ json_body={"prefix": folder, "limit": 1000, "offset": 0}, log_body={"action": "list", "prefix": folder})
149
+ if r.status_code >= 400:
150
+ raise SupabaseError("STORAGE", f"listing failed: HTTP {r.status_code} {r.text[:160]}", 502)
151
+ return [f"{folder}/{o['name']}" for o in r.json() if isinstance(o, dict) and o.get("name") and o.get("id")]
152
+
153
  def download(self, path: str) -> bytes | None:
154
  key = self.service_key()
155
  p = f"/storage/v1/object/{quote(self.cfg.supabase_bucket)}/{quote(path)}"
coworker/tests/test_ai_scenarios.py CHANGED
@@ -181,6 +181,28 @@ class TestModelOffAndPracticePod(unittest.TestCase):
181
  app.state.runs.cancel(rid, "test")
182
 
183
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
184
  class TestDryRunReport(unittest.TestCase):
185
  def test_failing_step_and_message_from_a_live_report(self):
186
  rep = {"suites": [{"specs": [{"title": "AP-FUS-103 x", "tags": ["@AP-FUS-103"], "tests": [{"status": "unexpected", "results": [{
 
181
  app.state.runs.cancel(rid, "test")
182
 
183
 
184
+ class TestDryRunRoad(unittest.TestCase):
185
+ """The dry run takes the same road as a test attempt (execute.run_pass): the remote browser runner when one is set.
186
+ It used to start a browser on this server, which Oracle's edge may refuse."""
187
+
188
+ def test_the_dry_run_goes_through_run_pass_with_the_fusion_config(self):
189
+ from coworker.graph.nodes import execute
190
+ svc = mock.MagicMock()
191
+ svc.run_dir.return_value = Path(tempfile.mkdtemp())
192
+ svc.cfg.fusion_workers, svc.cfg.fusion_scenario_minutes = 3, 12
193
+ svc.cfg.fusion_attempt_min_minutes, svc.cfg.fusion_attempt_max_minutes = 30, 240
194
+ drafts = [{"id": "AP-FUS-101", "module": "AP"}, {"id": "AP-FUS-102", "module": "AP"}]
195
+ with mock.patch.object(ai_scenarios, "_pod_host", return_value="pod.example"), \
196
+ mock.patch.object(execute, "run_pass", return_value={"file": str(svc.run_dir.return_value / "none.json")}) as rp, \
197
+ mock.patch.object(ai_scenarios, "read_dry_run", return_value={"AP-FUS-101": {"status": "passed"},
198
+ "AP-FUS-102": {"status": "failed", "failed_step": "3", "message": "x"}}):
199
+ ai_scenarios.dry_run({"run_id": "r1", "playwright_mode": "stub"}, svc, 2, drafts)
200
+ plan = rp.call_args.args[0]
201
+ self.assertEqual((plan["config"], plan["tag"], plan["ids"]), (execute.FUSION_CONFIG, "-dryrun", ["AP-FUS-101", "AP-FUS-102"]))
202
+ self.assertGreaterEqual(plan["timeout_s"], 30 * 60)
203
+ self.assertEqual([d["runnable"] for d in drafts], [True, False])
204
+
205
+
206
  class TestDryRunReport(unittest.TestCase):
207
  def test_failing_step_and_message_from_a_live_report(self):
208
  rep = {"suites": [{"specs": [{"title": "AP-FUS-103 x", "tags": ["@AP-FUS-103"], "tests": [{"status": "unexpected", "results": [{
coworker/tests/test_hardening.py CHANGED
@@ -453,5 +453,161 @@ class TestRetention(unittest.TestCase):
453
  os.environ.pop("SUPABASE_SERVICE_KEY", None)
454
 
455
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
456
  if __name__ == "__main__":
457
  unittest.main()
 
453
  os.environ.pop("SUPABASE_SERVICE_KEY", None)
454
 
455
 
456
+ class TestPollAudit(unittest.TestCase):
457
+ """Architecture review: every remote-runner poll (every 2 s with live view) wrote two audit rows, about 7,000 an hour,
458
+ never pruned, and the database pushed the saved archive over its size limit."""
459
+
460
+ def gate(self, handler):
461
+ import httpx
462
+
463
+ from coworker.graph.services import build_services
464
+ from coworker.tests.fakes import temp_settings
465
+ return build_services(temp_settings(), transport=httpx.MockTransport(handler))
466
+
467
+ def test_a_hundred_polls_write_a_handful_of_audit_rows_and_the_chain_holds(self):
468
+ import httpx
469
+ seen = {"n": 0}
470
+
471
+ def handler(req):
472
+ if req.method == "POST":
473
+ return httpx.Response(202, json={"id": "job_1"})
474
+ seen["n"] += 1
475
+ return httpx.Response(503, json={"error": "busy"}) if seen["n"] == 50 else httpx.Response(200, json={"state": "running", "n": seen["n"]})
476
+ svc = self.gate(handler)
477
+ eg, base, head = svc.egress, "https://runner.example", svc.audit.head()["seq"]
478
+ eg.service_request("remote_runner", "POST", base + "/v1/attempts", allowed_base=base, json_body={"ids": ["X"]}, log_body={"ids": ["X"]})
479
+ for _ in range(100):
480
+ eg.service_request("remote_runner", "GET", base + "/v1/attempts/job_1", allowed_base=base, poll="attempt job_1")
481
+ eg.end_polls("attempt job_1")
482
+ rows = svc.audit.query(after=head, kind_prefix="egress.remote_runner", limit=1000)
483
+ self.assertLessEqual(len(rows), 8)
484
+ self.assertEqual([r["kind"].rsplit(".", 1)[1] for r in rows],
485
+ ["request", "response", # the POST, as always
486
+ "request", "response", # the first poll
487
+ "request", "response", # the one that answered 503, on its own
488
+ "polls"]) # the other 98, with the last one, in one row
489
+ self.assertEqual((rows[1]["payload"]["status"], rows[5]["payload"]["status"]), (202, 503))
490
+ last = rows[-1]["payload"]
491
+ self.assertEqual((last["count"], last["final"], last["last"]["status"]), (98, True, 200))
492
+ self.assertEqual(len(last["answers_sha256"]), 64)
493
+ self.assertTrue(svc.audit.verify()["ok"])
494
+
495
+ def test_a_long_series_writes_one_row_a_minute(self):
496
+ import httpx
497
+
498
+ from coworker.platform import egress
499
+ svc = self.gate(lambda req: httpx.Response(200, json={"state": "running"}))
500
+ old, egress.POLL_ROW_S = egress.POLL_ROW_S, 0.0 # every poll is "a minute later"
501
+ try:
502
+ for _ in range(4):
503
+ svc.egress.service_request("remote_runner", "GET", "https://runner.example/v1/attempts/j/live",
504
+ allowed_base="https://runner.example", poll="live j")
505
+ finally:
506
+ egress.POLL_ROW_S = old
507
+ svc.egress.end_polls("live j")
508
+ self.assertEqual(len(svc.audit.query(kind="egress.remote_runner.polls")), 3) # nothing left for the end row
509
+
510
+ def test_a_remote_attempt_with_live_view_polls_through_the_gate_quietly(self):
511
+ import shutil
512
+ import tempfile
513
+ from pathlib import Path
514
+
515
+ import httpx
516
+
517
+ from coworker.adapters import remote_runner as R
518
+ from coworker.tests.test_remote_runner import bundle
519
+ seen = {"n": 0}
520
+
521
+ def handler(req):
522
+ p = req.url.path
523
+ if req.method == "POST":
524
+ return httpx.Response(202, json={"id": "job_9"})
525
+ if p.endswith("/bundle"):
526
+ return httpx.Response(200, content=bundle())
527
+ if p.endswith("/live"):
528
+ return httpx.Response(200, json={"status": {"status": "running"}, "frame": None})
529
+ seen["n"] += 1
530
+ return httpx.Response(200, json={"state": "done" if seen["n"] > 100 else "running", "exit_code": 0})
531
+ svc = self.gate(handler)
532
+ head = svc.audit.head()["seq"]
533
+ with tempfile.TemporaryDirectory() as d:
534
+ d = Path(d)
535
+ res = R.run_attempt_remote(svc.egress, "https://runner.example", "tok-" + "x" * 30, run_id="r9", ids=["AP-FUS-001"],
536
+ attempt=0, out_file=d / "a.json", cred_env={}, drafts_dir=None, library_dir=None,
537
+ overrides_file=None, log_dir=d, config="playwright.fusion.config.ts", poll_s=0.0,
538
+ live_dir=d / "live")
539
+ shutil.rmtree(Path(res["run_dir"]), ignore_errors=True)
540
+ rows = svc.audit.query(after=head, kind_prefix="egress.remote_runner", limit=1000)
541
+ self.assertLessEqual(len(rows), 10) # POST, first status and first frame polls, their two end rows, the bundle
542
+ self.assertEqual(sum(r["payload"]["count"] for r in rows if r["kind"].endswith(".polls")), 100 + 99)
543
+
544
+
545
+ class TestShutdownOrder(unittest.TestCase):
546
+ """Architecture review: the shutdown save ran before the run worker stopped, so a running run was saved as running and
547
+ came back interrupted."""
548
+
549
+ def test_a_run_stops_between_steps_and_continues_after_the_restart(self):
550
+ from coworker.api.runner import RunManager
551
+ app, c, svc, _ = make_app()
552
+ runs = app.state.runs
553
+ rid = runs.start(DEFECT, "consultant")
554
+ runs._shutting_down.set() # the app is stopping while this run works
555
+ runs.drain()
556
+ self.assertEqual(svc.db.get_run(rid)["status"], "queued")
557
+ self.assertEqual([j["kind"] for j in svc.db.q("SELECT kind FROM run_jobs WHERE done_at IS NULL")], ["continue"])
558
+ with self.assertRaises(RunError) as e:
559
+ runs.start({"modules": ["O2C"], "playwright_mode": "stub"}, "consultant")
560
+ self.assertEqual((e.exception.code, e.exception.status), ("SHUTTING_DOWN", 503))
561
+ rm2 = RunManager(svc) # the restarted backend
562
+ self.assertEqual(rm2.recover(), []) # nothing interrupted
563
+ rm2.drain()
564
+ self.assertEqual(svc.db.get_run(rid)["status"], "waiting_approval")
565
+
566
+ def test_the_wait_for_a_running_step_is_bounded(self):
567
+ import time
568
+ app, c, svc, _ = make_app()
569
+ runs = app.state.runs
570
+ in_step, go = threading.Event(), threading.Event()
571
+ real = svc.kill.engaged
572
+
573
+ def slow_step(): # the worker is busy in a step until `go`
574
+ if threading.current_thread().name == "fpt-run-worker":
575
+ in_step.set()
576
+ go.wait(10)
577
+ return real()
578
+ svc.kill.engaged = slow_step
579
+ runs.start_worker()
580
+ rid = runs.start(DEFECT, "consultant")
581
+ self.assertTrue(in_step.wait(10))
582
+ t0 = time.monotonic()
583
+ self.assertFalse(runs.stop_for_shutdown(0.3)) # gives up in time: shutdown is never held up
584
+ self.assertLess(time.monotonic() - t0, 3)
585
+ go.set()
586
+ self.assertTrue(runs.stop_for_shutdown(10)) # once the step ends, the run stops at the next safe point
587
+ self.assertEqual(svc.db.get_run(rid)["status"], "queued")
588
+
589
+ def test_the_last_save_comes_after_the_runs_have_stopped(self):
590
+ import os
591
+
592
+ from fastapi.testclient import TestClient
593
+
594
+ from coworker.api.app import create_app
595
+ from coworker.tests.test_supabase import SERVICE, FakeSupabase, make
596
+ os.environ["SUPABASE_SERVICE_KEY"] = SERVICE
597
+ try:
598
+ _, _, svc = make(FakeSupabase(confirm=False))
599
+ app = create_app(svc, background=True)
600
+ order = []
601
+ with TestClient(app):
602
+ runs, syncer = app.state.runs, app.state.syncer
603
+ stop_runs, save = runs.stop_for_shutdown, syncer.stop
604
+ runs.stop_for_shutdown = lambda w: order.append(("runs", w)) or stop_runs(w)
605
+ syncer.stop = lambda: order.append(("save",)) or save()
606
+ self.assertEqual(order, [("runs", 20), ("save",)])
607
+ self.assertIsNone(syncer.last_error)
608
+ finally:
609
+ os.environ.pop("SUPABASE_SERVICE_KEY", None)
610
+
611
+
612
  if __name__ == "__main__":
613
  unittest.main()
coworker/tests/test_ocistore.py CHANGED
@@ -88,6 +88,49 @@ class TestOciStateStore(unittest.TestCase):
88
  self.assertEqual(statesync.Syncer(svc, 60).interval, 300)
89
  self.assertEqual(statesync.Syncer(svc, 900).interval, 900)
90
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
91
  def test_a_malformed_address_is_not_used(self):
92
  os.environ["OCI_STATE_PAR_URL"] = "https://evil.example/p/x/n/y/b/z/o/"
93
  self.assertEqual(ocistore.par_url(), "")
 
88
  self.assertEqual(statesync.Syncer(svc, 60).interval, 300)
89
  self.assertEqual(statesync.Syncer(svc, 900).interval, 900)
90
 
91
+ def test_a_save_costs_four_requests_and_old_copies_are_deleted_by_name(self):
92
+ """The address denies listing, so the history's names come from meta.json; listing is asked once per process."""
93
+ from coworker.tests.test_supabase import Clock
94
+ bucket = FakeBucket()
95
+ svc = make(bucket)
96
+ with Clock(step_min=31):
97
+ statesync.push(svc, "first")
98
+ n = len(bucket.seen)
99
+ svc.users.create("p0", PASSWORD, "viewer", created_by="test")
100
+ statesync.push(svc, "second")
101
+ self.assertEqual([r.method for r in bucket.seen[n:]], ["GET", "PUT", "PUT", "PUT"]) # meta, history, latest, meta
102
+ for i in range(6):
103
+ svc.users.create(f"q{i}", PASSWORD, "viewer", created_by="test")
104
+ statesync.push(svc, f"save {i}")
105
+ hist = sorted(k for k in bucket.objects if k.startswith(statesync.HISTORY))
106
+ self.assertEqual(len(hist), 5)
107
+ import json
108
+ meta = json.loads(bucket.objects[statesync.META])
109
+ self.assertEqual(meta["history"], sorted(hist, reverse=True))
110
+ self.assertEqual(bucket.objects[meta["history"][0]], bucket.objects[statesync.OBJECT])
111
+ self.assertEqual(sum(1 for r in bucket.seen if r.method == "DELETE"), 3)
112
+ self.assertEqual(sum(1 for r in bucket.seen if "prefix=" in str(r.url)), 1)
113
+
114
+ def test_an_old_instance_is_fenced_off_on_the_oci_bucket_too(self):
115
+ bucket = FakeBucket()
116
+ old = make(bucket)
117
+ statesync.push(old, "first")
118
+ fresh = Path(tempfile.mkdtemp(prefix="fpt-oci-new-"))
119
+ cfg2 = old.cfg.model_copy(update={"fpt_home": fresh})
120
+ self.assertEqual(statesync.restore_at_boot(cfg2, statesync.store_for(cfg2, old.egress, None), sleep=lambda s: None), (True, None))
121
+ restored = bucket.objects[statesync.OBJECT]
122
+ old.users.create("late", PASSWORD, "viewer", created_by="test")
123
+ with self.assertRaises(Exception) as e:
124
+ statesync.push(old, "shutdown")
125
+ self.assertEqual(getattr(e.exception, "code", None), "STATE_FENCED")
126
+ self.assertEqual(bucket.objects[statesync.OBJECT], restored)
127
+ n = len(bucket.seen)
128
+ with self.assertRaises(Exception):
129
+ statesync.push(old, "again")
130
+ self.assertEqual(len(bucket.seen), n) # a fenced instance spends no requests
131
+ new = build_services(cfg2, transport=old.egress.transport)
132
+ self.assertEqual(statesync.push(new, "new")["generation"], 3)
133
+
134
  def test_a_malformed_address_is_not_used(self):
135
  os.environ["OCI_STATE_PAR_URL"] = "https://evil.example/p/x/n/y/b/z/o/"
136
  self.assertEqual(ocistore.par_url(), "")
coworker/tests/test_remote_runner.py CHANGED
@@ -36,7 +36,11 @@ class FakeEgress:
36
  def __init__(self):
37
  self.calls, self.polls = [], 0
38
 
39
- def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0, log_url=None):
 
 
 
 
40
  self.calls.append({"method": method, "url": url, "body": json_body, "log": log_body, "auth": (headers or {}).get("Authorization")})
41
  assert kind == "remote_runner" and url.startswith(allowed_base)
42
  if method == "POST" and url.endswith("/v1/attempts"):
 
36
  def __init__(self):
37
  self.calls, self.polls = [], 0
38
 
39
+ def end_polls(self, key):
40
+ pass
41
+
42
+ def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0,
43
+ log_url=None, poll=None):
44
  self.calls.append({"method": method, "url": url, "body": json_body, "log": log_body, "auth": (headers or {}).get("Authorization")})
45
  assert kind == "remote_runner" and url.startswith(allowed_base)
46
  if method == "POST" and url.endswith("/v1/attempts"):
coworker/tests/test_remote_screens.py CHANGED
@@ -39,7 +39,11 @@ class FakeEgress:
39
  def __init__(self, inv=INV):
40
  self.calls, self.polls, self.inv = [], 0, inv
41
 
42
- def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0, log_url=None):
 
 
 
 
43
  self.calls.append({"method": method, "url": url, "body": json_body, "log": log_body})
44
  assert kind == "remote_runner" and url.startswith(allowed_base)
45
  if method == "POST" and url.endswith("/v1/screens"):
@@ -130,7 +134,11 @@ class LiveEgress:
130
  def __init__(self):
131
  self.calls, self.polls = [], 0
132
 
133
- def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0, log_url=None):
 
 
 
 
134
  import base64 as b64
135
  self.calls.append({"method": method, "url": url, "body": json_body})
136
  if method == "POST":
 
39
  def __init__(self, inv=INV):
40
  self.calls, self.polls, self.inv = [], 0, inv
41
 
42
+ def end_polls(self, key):
43
+ pass
44
+
45
+ def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0,
46
+ log_url=None, poll=None):
47
  self.calls.append({"method": method, "url": url, "body": json_body, "log": log_body})
48
  assert kind == "remote_runner" and url.startswith(allowed_base)
49
  if method == "POST" and url.endswith("/v1/screens"):
 
134
  def __init__(self):
135
  self.calls, self.polls = [], 0
136
 
137
+ def end_polls(self, key):
138
+ pass
139
+
140
+ def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None, timeout=30.0,
141
+ log_url=None, poll=None):
142
  import base64 as b64
143
  self.calls.append({"method": method, "url": url, "body": json_body})
144
  if method == "POST":
coworker/tests/test_runner_robust.py CHANGED
@@ -73,8 +73,11 @@ class Runner:
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))
 
73
  def _next(seq):
74
  return seq.pop(0) if len(seq) > 1 else seq[0]
75
 
76
+ def end_polls(self, key):
77
+ pass
78
+
79
  def service_request(self, kind, method, url, *, allowed_base, headers=None, json_body=None, content=None, log_body=None,
80
+ timeout=30.0, log_url=None, poll=None):
81
  assert kind == "remote_runner" and url.startswith(allowed_base)
82
  path = url[len(allowed_base):]
83
  self.calls.append((method, path, json_body))
coworker/tests/test_step_writer.py CHANGED
@@ -324,3 +324,24 @@ class TestPromptsPassTheLeakCheck(unittest.TestCase):
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)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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)
327
+
328
+
329
+ class TestSystemPromptIsNotData(unittest.TestCase):
330
+ """Seen live: after a screen read, a list value learned as a client name was also an ordinary word of a prompt, and
331
+ the egress check refused every design request. The prompt is product text; the request's data is still checked."""
332
+
333
+ def test_a_name_that_is_a_prompt_word_does_not_refuse_the_call(self):
334
+ fake = FakeModel([json.dumps(GOOD)])
335
+ svc = frontier_svc(fake)
336
+ svc.redactor.add_terms(["Invoice entry"], "name") # a word of write_steps.md, learned as a "name"
337
+ resp = sw._call(svc, "write_steps", {"intent": {"title": "Saved invoice validates"}}, StepsDraft, None)
338
+ self.assertEqual(resp.route.value, "frontier")
339
+
340
+ def test_the_same_name_in_the_data_is_still_refused(self):
341
+ from ..platform.egress import EgressDenied
342
+ svc = frontier_svc(FakeModel([json.dumps(GOOD)]))
343
+ svc.redactor.add_terms(["Lee Supplies"], "name")
344
+ body = {"model": "m", "messages": [{"role": "system", "content": "rules"},
345
+ {"role": "user", "content": "<untrusted>Lee Supplies</untrusted>"}]}
346
+ with self.assertRaises(EgressDenied):
347
+ svc.egress.llm_frontier(body, task="generate_tests", sensitivity="public", run_id=None)
coworker/tests/test_supabase.py CHANGED
@@ -16,7 +16,7 @@ import httpx
16
  from coworker.graph.services import build_services
17
  from coworker.platform import statesync
18
  from coworker.platform import supabase as sb
19
- from coworker.tests.fakes import PASSWORD, ROLES, FakePod, temp_settings
20
 
21
  URL = "https://demo-project.supabase.co"
22
  ANON, SERVICE = "anon-public-key", "service-SECRET-key-do-not-leak"
@@ -70,6 +70,14 @@ class FakeSupabase:
70
  self.buckets.add(name)
71
  return httpx.Response(200, json={"name": name})
72
  path = p.removeprefix("/storage/v1/object/")
 
 
 
 
 
 
 
 
73
  if req.method == "POST":
74
  self.objects[path] = req.content
75
  return httpx.Response(200, json={"Key": path})
@@ -366,3 +374,211 @@ class TestAuthHardening(unittest.TestCase):
366
  _, _, svc = make(FakeSupabase(confirm=False), admin_emails=["boss@example.com"])
367
  self.assertEqual(_role_for(svc, "boss@example.com", False), svc.cfg.register_role)
368
  self.assertEqual(_role_for(svc, "boss@example.com", True), "admin")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
16
  from coworker.graph.services import build_services
17
  from coworker.platform import statesync
18
  from coworker.platform import supabase as sb
19
+ from coworker.tests.fakes import PASSWORD, ROLES, FakePod, bearer, temp_settings
20
 
21
  URL = "https://demo-project.supabase.co"
22
  ANON, SERVICE = "anon-public-key", "service-SECRET-key-do-not-leak"
 
70
  self.buckets.add(name)
71
  return httpx.Response(200, json={"name": name})
72
  path = p.removeprefix("/storage/v1/object/")
73
+ if req.method == "POST" and path.startswith("list/"):
74
+ folder = f"{path[5:]}/{json.loads(req.content)['prefix'].strip('/')}/"
75
+ return httpx.Response(200, json=[{"name": k[len(folder):], "id": k} for k in self.objects
76
+ if k.startswith(folder) and "/" not in k[len(folder):]])
77
+ if req.method == "DELETE":
78
+ if self.objects.pop(path, None) is None:
79
+ return httpx.Response(400, json={"statusCode": "404", "error": "not_found", "message": "Object not found"})
80
+ return httpx.Response(200, json={"message": "Successfully deleted"})
81
  if req.method == "POST":
82
  self.objects[path] = req.content
83
  return httpx.Response(200, json={"Key": path})
 
374
  _, _, svc = make(FakeSupabase(confirm=False), admin_emails=["boss@example.com"])
375
  self.assertEqual(_role_for(svc, "boss@example.com", False), svc.cfg.register_role)
376
  self.assertEqual(_role_for(svc, "boss@example.com", True), "admin")
377
+
378
+
379
+ class Clock:
380
+ """statesync's clock in a test: each push names its history copy after now(), so saves a minute apart get their own."""
381
+
382
+ def __init__(self, step_min: float):
383
+ from datetime import datetime, timedelta, timezone
384
+ self.t, self.step, self.real = datetime(2026, 11, 18, 10, 0, tzinfo=timezone.utc), timedelta(minutes=step_min), datetime
385
+
386
+ def __enter__(self):
387
+ clock = self
388
+
389
+ class Fake(self.real):
390
+ @classmethod
391
+ def now(cls, tz=None):
392
+ clock.t += clock.step
393
+ return clock.t
394
+ self._old, statesync.datetime = statesync.datetime, Fake
395
+ return self
396
+
397
+ def __exit__(self, *a):
398
+ statesync.datetime = self._old
399
+
400
+
401
+ def obj(svc, name):
402
+ return f"{svc.cfg.supabase_bucket}/{name}"
403
+
404
+
405
+ class TestStateFencing(unittest.TestCase):
406
+ """Architecture review: during a Hugging Face rebuild the old container keeps running while the new one restores and
407
+ starts, and the old one's later saves (its shutdown save too) overwrote the new instance's state."""
408
+
409
+ def setUp(self):
410
+ os.environ["SUPABASE_SERVICE_KEY"] = SERVICE
411
+ os.environ.pop("FPT_STATE_KEY", None)
412
+
413
+ def tearDown(self):
414
+ os.environ.pop("SUPABASE_SERVICE_KEY", None)
415
+
416
+ def new_instance(self, svc, fake):
417
+ """A new container on the same bucket: empty disk, start-up restore (entrypoint: state restore), then the app."""
418
+ from fastapi.testclient import TestClient
419
+
420
+ from coworker.api.app import create_app
421
+ fresh = Path(tempfile.mkdtemp(prefix="fpt-new-"))
422
+ cfg = svc.cfg.model_copy(update={"fpt_home": fresh})
423
+ self.assertEqual(statesync.restore_at_boot(cfg, sb.Supabase(cfg, svc.egress, None), sleep=lambda s: None), (True, None))
424
+ svc2 = build_services(cfg, transport=svc.egress.transport)
425
+ app = create_app(svc2, background=False)
426
+ return svc2, app, TestClient(app)
427
+
428
+ def test_the_old_instance_is_fenced_off_once_a_new_one_has_started(self):
429
+ fake = FakeSupabase(confirm=False)
430
+ old_app, old_c, old = make(fake)
431
+ statesync.push(old, "first")
432
+ self.assertEqual(json.loads(fake.objects[obj(old, statesync.META)])["generation"], 1)
433
+ new, new_app, new_c = self.new_instance(old, fake)
434
+ claimed = json.loads(fake.objects[obj(old, statesync.META)])
435
+ self.assertEqual((claimed["generation"], claimed["instance"]), (2, statesync.record(new.cfg.home)["instance"]))
436
+ restored = fake.objects[obj(old, statesync.OBJECT)]
437
+ # the old container goes on working, then saves: refused, the new instance's archive is untouched
438
+ old.users.create("late-change", PASSWORD, "viewer", created_by="test")
439
+ s = statesync.Syncer(old, 60)
440
+ old_app.state.syncer = s
441
+ self.assertFalse(s.tick())
442
+ self.assertIn("another instance", s.last_error)
443
+ self.assertEqual(fake.objects[obj(old, statesync.OBJECT)], restored)
444
+ self.assertIsNotNone(statesync.fenced(old.cfg.home))
445
+ self.assertEqual(len(old.audit.query(kind="state.fenced")), 1)
446
+ # it stays quiet from then on, its forced shutdown save included: not one more request to the bucket
447
+ before = len(fake.seen)
448
+ self.assertFalse(s.tick("shutdown", force=True))
449
+ self.assertEqual(len(fake.seen), before)
450
+ self.assertEqual(len(old.audit.query(kind="state.fenced")), 1) # audited once
451
+ st = old_c.get("/api/ready", headers=bearer(old_c, "viewer")).json()["saved_state"]
452
+ self.assertEqual((st["paused"], st["paused_reason"]), (True, "fenced"))
453
+ d = old_c.get("/api/storage", headers=bearer(old_c, "admin")).json()["saved_state"]
454
+ self.assertEqual((d["paused_reason"], d["fenced"]["bucket_generation"]), ("fenced", 2))
455
+ self.assertEqual(old_c.post("/api/storage/save", headers={**bearer(old_c, "admin")}).status_code, 409)
456
+ # the new instance saves on, one generation at a time
457
+ self.assertEqual(statesync.push(new, "next")["generation"], 3)
458
+ self.assertEqual(statesync.push(new, "again")["generation"], 4)
459
+
460
+ def test_archives_saved_before_generations_restore_and_save_on(self):
461
+ fake = FakeSupabase(confirm=False)
462
+ _, c, svc = make(fake)
463
+ c.post("/api/auth/register", json={"email": "keep@example.com", "password": SECRET_PW})
464
+ statesync.push(svc, "test")
465
+ # what the bucket held before this change: an archive and a meta.json without generation or instance
466
+ fake.objects[obj(svc, statesync.META)] = json.dumps({"saved_at": "2026-11-01T00:00:00+00:00", "bytes": 1, "left_out": []}).encode()
467
+ new, _, _ = self.new_instance(svc, fake)
468
+ with sqlite3.connect(str(new.cfg.home / "fpt.sqlite")) as db:
469
+ self.assertEqual(db.execute("SELECT COUNT(*) FROM users WHERE username='keep@example.com'").fetchone()[0], 1)
470
+ self.assertEqual(json.loads(fake.objects[obj(svc, statesync.META)])["generation"], 1)
471
+ self.assertEqual(statesync.push(new, "after upgrade")["generation"], 2)
472
+
473
+ def test_a_save_whose_answer_was_lost_is_not_mistaken_for_another_instance(self):
474
+ fake = FakeSupabase(confirm=False)
475
+ _, _, svc = make(fake)
476
+ statesync.push(svc, "one")
477
+ meta = json.loads(fake.objects[obj(svc, statesync.META)])
478
+ fake.objects[obj(svc, statesync.META)] = json.dumps({**meta, "generation": 7}).encode() # written by us, answer lost
479
+ self.assertEqual(statesync.push(svc, "two")["generation"], 8)
480
+ self.assertIsNone(statesync.fenced(svc.cfg.home))
481
+
482
+ def test_a_meta_json_that_cannot_be_read_does_not_let_a_save_through_blind(self):
483
+ fake = FakeSupabase(confirm=False)
484
+ _, _, svc = make(fake)
485
+ statesync.push(svc, "one")
486
+ real = fake.handler
487
+ fake.handler = lambda req: httpx.Response(500, json={"message": "down"}) if req.method == "GET" and req.url.path.endswith("meta.json") else real(req)
488
+ s = statesync.Syncer(svc, 60)
489
+ self.assertFalse(s.tick(force=True))
490
+ self.assertIn("download failed", s.last_error)
491
+ self.assertIsNone(statesync.fenced(svc.cfg.home)) # not fenced: tried again next time
492
+ fake.handler = real
493
+ self.assertTrue(s.tick(force=True))
494
+
495
+
496
+ class TestStateHistory(unittest.TestCase):
497
+ def setUp(self):
498
+ os.environ["SUPABASE_SERVICE_KEY"] = SERVICE
499
+
500
+ def tearDown(self):
501
+ os.environ.pop("SUPABASE_SERVICE_KEY", None)
502
+
503
+ def test_the_last_n_archives_are_kept_and_older_ones_deleted_at_most_hourly(self):
504
+ fake = FakeSupabase(confirm=False)
505
+ _, c, svc = make(fake, state_history_keep=2)
506
+ hist = lambda: sorted(k for k in fake.objects if "/state/history/" in k) # noqa: E731
507
+ with Clock(step_min=31): # two clock reads per save: about an hour apart
508
+ blobs = []
509
+ for i in range(4):
510
+ svc.users.create(f"p{i}", PASSWORD, "viewer", created_by="test")
511
+ statesync.push(svc, f"save {i}")
512
+ blobs.append(fake.objects[obj(svc, statesync.OBJECT)])
513
+ self.assertEqual(len(hist()), 2)
514
+ meta = json.loads(fake.objects[obj(svc, statesync.META)])
515
+ self.assertEqual([obj(svc, n) for n in meta["history"]], sorted(hist(), reverse=True))
516
+ self.assertEqual(fake.objects[obj(svc, meta["history"][0])], blobs[-1]) # the newest copy is the latest save
517
+ self.assertEqual(fake.objects[obj(svc, meta["history"][1])], blobs[-2])
518
+ with Clock(step_min=1): # saves a minute apart: copies pile up until the next hourly clean-up
519
+ for i in range(3):
520
+ statesync.push(svc, f"quick {i}")
521
+ self.assertEqual(len(hist()), 2 + 3)
522
+ d = c.get("/api/storage", headers=bearer(c, "admin")).json()["saved_state"]
523
+ self.assertEqual((len(d["history"]), d["history_keep"]), (5, 2))
524
+
525
+ def test_no_history_when_switched_off(self):
526
+ fake = FakeSupabase(confirm=False)
527
+ _, _, svc = make(fake, state_history_keep=0)
528
+ statesync.push(svc, "one")
529
+ self.assertFalse([k for k in fake.objects if "/state/history/" in k])
530
+
531
+
532
+ class TestLeftOutIsVisible(unittest.TestCase):
533
+ """Over the size limit the evidence is left out of the archive. That stays, but people are told exactly what, once,
534
+ and a screenshot missing after the restart answers 410 'not kept after a restart' instead of a puzzling 404."""
535
+
536
+ def setUp(self):
537
+ os.environ["SUPABASE_SERVICE_KEY"] = SERVICE
538
+
539
+ def tearDown(self):
540
+ os.environ.pop("SUPABASE_SERVICE_KEY", None)
541
+
542
+ def test_left_out_evidence_is_recorded_announced_once_and_answers_410_after_a_restart(self):
543
+ from fastapi.testclient import TestClient
544
+
545
+ from coworker.api.app import create_app
546
+ fake = FakeSupabase(confirm=False)
547
+ _, c, svc = make(fake)
548
+ rid = "run-left-out"
549
+ src = svc.cfg.home / "trace.zip"
550
+ src.write_bytes(os.urandom(300_000))
551
+ ref = svc.evidence.ingest_file(rid, 0, src, "AP-001")
552
+ src.unlink()
553
+ small = len(statesync.build_archive(svc.cfg.home, include_evidence=False))
554
+ old_max = statesync.MAX_BYTES
555
+ statesync.MAX_BYTES = small + 60_000 # room for the audit rows a save adds, not for the 300 KB trace
556
+ try:
557
+ meta = statesync.push(svc, "test")
558
+ self.assertEqual(meta["left_out"], ["evidence"])
559
+ self.assertEqual((meta["left_out_detail"]["evidence"]["files"], meta["left_out_detail"]["evidence"]["runs"]), (1, [rid]))
560
+ self.assertEqual(json.loads(fake.objects[obj(svc, statesync.META)])["left_out"], ["evidence"])
561
+ statesync.push(svc, "again")
562
+ finally:
563
+ statesync.MAX_BYTES = old_max
564
+ self.assertEqual(len(svc.audit.query(kind="state.left_out")), 1) # once per change, not per save
565
+ self.assertEqual(len(svc.db.q("SELECT id FROM notify_events WHERE kind='state.left_out'")), 1)
566
+ d = c.get("/api/storage", headers=bearer(c, "admin")).json()["saved_state"]
567
+ self.assertEqual(d["left_out"], ["evidence"])
568
+ self.assertIn("screenshots, videos and traces (1 files", d["left_out_note"])
569
+ self.assertIn("not be there after a restart", d["left_out_note"])
570
+ self.assertEqual(c.get(f"/api/evidence/{ref.evidence_id}", headers=bearer(c, "admin")).status_code, 200)
571
+ # a restart: the new instance restores the archive without the evidence
572
+ fresh = Path(tempfile.mkdtemp(prefix="fpt-new-"))
573
+ cfg = svc.cfg.model_copy(update={"fpt_home": fresh})
574
+ self.assertEqual(statesync.restore_at_boot(cfg, sb.Supabase(cfg, svc.egress, None), sleep=lambda s: None), (True, None))
575
+ svc2 = build_services(cfg, transport=svc.egress.transport)
576
+ # rows keep the file's absolute path, the same on the real host; here the old container's disk is still there
577
+ Path(svc2.db.one("SELECT blob_path FROM evidence WHERE evidence_id=?", (ref.evidence_id,))["blob_path"]).unlink()
578
+ c2 = TestClient(create_app(svc2, background=False))
579
+ r = c2.get(f"/api/evidence/{ref.evidence_id}", headers=bearer(c2, "admin"))
580
+ self.assertEqual((r.status_code, r.json()["code"]), (410, "NOT_KEPT"))
581
+ self.assertIn("not kept after a restart", r.json()["detail"])
582
+ self.assertEqual(c2.get("/api/evidence/999999", headers=bearer(c2, "admin")).status_code, 404) # unknown stays 404
583
+ d2 = c2.get("/api/storage", headers=bearer(c2, "admin")).json()["saved_state"] # before its first save: the restored one's
584
+ self.assertIn("screenshots", d2["left_out_note"])
deploy/oci/update-app.sh ADDED
@@ -0,0 +1,48 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Puts this repo's committed HEAD into the Astra container on an OCI server (the "Option A" copy that sits next to the
3
+ # browser runner): builds the image there, saves the running app's state, swaps the container, checks its health.
4
+ # deploy/oci/update-app.sh ubuntu@server ~/.ssh/key https://astra-<server>.sslip.io
5
+ # The container's settings live on the server in /etc/astra/app.env (root only, never in the repo). Its data lives in
6
+ # /home/ubuntu/astra-data on the server's own disk, so a restart loses nothing. Refuses while a test run is active, and
7
+ # keeps the previous image tag so a bad release is undone with one docker run.
8
+ set -euo pipefail
9
+ HOST=${1:?ssh target, e.g. ubuntu@server}
10
+ KEY=${2:?ssh private key file}
11
+ URL=${3:?the app address, e.g. https://astra-1-2-3-4.sslip.io}
12
+ REV=$(git rev-parse --short=12 HEAD)
13
+ git diff --quiet HEAD || { echo "uncommitted changes: commit first" >&2; exit 1; }
14
+ SSH=(ssh -i "$KEY" -o BatchMode=yes "$HOST")
15
+
16
+ PKG=$(mktemp -t astra-app.XXXXXX.tgz)
17
+ trap 'rm -f "$PKG"' EXIT
18
+ git archive --format=tar.gz -o "$PKG" HEAD
19
+ scp -q -i "$KEY" -o BatchMode=yes "$PKG" "$HOST:astra-app.tgz"
20
+
21
+ "${SSH[@]}" bash -s -- "$REV" <<'REMOTE'
22
+ set -euo pipefail
23
+ REV=$1
24
+ rm -rf ~/astra-app && mkdir ~/astra-app && tar -xzf ~/astra-app.tgz -C ~/astra-app && rm -f ~/astra-app.tgz
25
+ cd ~/astra-app && sudo docker build -q -t "astra:$REV" . >/dev/null
26
+ # the running app: refuse while a run is active (it would be cut off), then save its state (its disk keeps it anyway)
27
+ if sudo docker ps --format '{{.Names}}' | grep -qx astra; then
28
+ # a run executing its browsers keeps the runner on this server busy
29
+ if curl -s --max-time 10 http://127.0.0.1:${RUNNER_PORT:-8899}/healthz | grep -q '"busy": true'; then
30
+ echo "a test run is using the browser runner: try again when it ends" >&2; exit 2
31
+ fi
32
+ PREV=$(sudo docker inspect -f '{{.Config.Image}}' astra)
33
+ echo "previous image: $PREV (to roll back: docker rm -f astra and run that tag)"
34
+ fi
35
+ sudo sed -i "s/^FPT_COMMIT=.*/FPT_COMMIT=$REV/" /etc/astra/app.env
36
+ grep -q '^FPT_COMMIT=' /etc/astra/app.env || echo "FPT_COMMIT=$REV" | sudo tee -a /etc/astra/app.env >/dev/null
37
+ sudo docker rm -f astra >/dev/null 2>&1 || true
38
+ sudo docker run -d --name astra --restart unless-stopped -p 127.0.0.1:8800:8800 --env-file /etc/astra/app.env \
39
+ -v /home/ubuntu/astra-data:/data "astra:$REV" >/dev/null
40
+ for i in $(seq 1 60); do
41
+ [ "$(curl -s -o /dev/null -w '%{http_code}' http://127.0.0.1:8800/api/health)" = 200 ] && break; sleep 3
42
+ done
43
+ curl -s -o /dev/null -w "app health: %{http_code}\n" http://127.0.0.1:8800/api/health
44
+ sudo docker image prune -f >/dev/null
45
+ REMOTE
46
+
47
+ echo "from outside: $(curl -s -o /dev/null -w '%{http_code} in %{time_total}s' --max-time 30 "$URL/api/health")"
48
+ echo "Astra on OCI now on $REV; sync the runner to the same commit: deploy/runner/sync.sh"
docs/ARCHITECTURE.md CHANGED
@@ -84,6 +84,9 @@ pre-flight. **Fusion pods are not supported under Temporal today.**
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
@@ -115,11 +118,18 @@ When a save happens:
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
 
 
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
+ Repeated status polls of the remote runner (attempt state, screen reads, live frames) are the one exception to a
88
+ record per call: the first is audited as usual, the rest as one row a minute and one at the end, with a count and a
89
+ digest over every answer; a non-2xx answer or a failed poll is audited on its own.
90
  - **Vault** (`platform/vault.py`): a plain JSON file, `FPT_HOME/secrets/vault.json` (file mode 600), plus
91
  `FPT_SECRET_<NAME>` environment overrides. It is **not encrypted on disk**; it is encrypted only inside the state
92
  snapshot. It holds `EVIDENCE_KEY`, the key of the evidence store. API answers never contain secrets; child processes
 
118
  300 on OCI, to stay inside the bucket's request budget; at least 10 on Supabase).
119
  - **At once** on key events (`save_soon`): a screen read finished, a run waits for a person, a run ended, a run was
120
  cancelled.
121
+ - **On shutdown**: a forced save, after the run worker has stopped (a running run stops between two steps and is
122
+ queued to continue after the restart; the wait is bounded by `FPT_SHUTDOWN_RUN_WAIT_S`, default 20 s).
123
  - **On request**: `POST /api/storage/save` (administrator). Call it before every restart or deploy.
124
 
125
+ At start, a screen read that the snapshot shows as running is marked interrupted (`PodRegistry.recover_screens`).
126
+
127
+ The snapshot serves one instance, but a Hugging Face rebuild keeps the old container running while the new one starts.
128
+ So `state/meta.json` carries a generation number and the id of the instance that wrote it: each start takes the next
129
+ generation after its restore, every save reads `meta.json` first (one GET), and an instance that finds the bucket
130
+ moved on by another one stops saving (`.state-fenced`, `paused_reason: "fenced"`, audit `state.fenced`) instead of
131
+ overwriting it. Each save also keeps a copy as `state/history/<time>.bin`; the newest `FPT_STATE_HISTORY` (default 5)
132
+ are kept, older ones deleted at most once an hour (RUNBOOK "Going back to an earlier save").
133
 
134
  ## Web app
135
 
docs/DEPLOYMENT.md CHANGED
@@ -90,13 +90,22 @@ When it saves:
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.
 
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, after a running run has stopped at its next step, waiting at most
94
+ `FPT_SHUTDOWN_RUN_WAIT_S`, default 20 s);
95
  - on `POST /api/storage/save`, and with `python -m coworker state push`.
96
 
97
+ A save costs four requests: GET `state/meta.json` (the generation check), PUT `state/history/<time>.bin`, PUT
98
+ `state/latest.bin`, PUT `state/meta.json`. The first save of each process also copies what the bucket held to
99
+ `state/previous.bin`; once an hour history copies beyond `FPT_STATE_HISTORY` (default 5) are deleted (by the names in
100
+ `meta.json`, since the OCI address may not list). Each start writes `meta.json` once to take the next generation, so an
101
+ older container still running is refused at its next save instead of overwriting the newer state.
102
+
103
+ An archive above 45 MB leaves out the evidence, then the folders of finished runs: `meta.json` and `/api/storage`
104
+ (`left_out_detail`, `left_out_note`) say exactly what, once per change it is audited (`state.left_out`) and notified,
105
+ and after a restart those files answer 410. If the start-up restore fails, or another instance has taken over
106
+ (`paused_reason` `restore_failed` or `fenced`), saving pauses so the good copy is not overwritten. Status: Settings >
107
+ Storage and backups, `/api/ready` (`saved_state`, signed in), the metric `trio_backup_ok`,
108
+ `python -m coworker state status`.
109
 
110
  **Compose.** `deploy/backup.sh /secure/backups` on a schedule. The archive is not encrypted and contains the secrets
111
  vault: encrypt it and restrict who can read it.
docs/RUNBOOK.md CHANGED
@@ -48,8 +48,20 @@ not an hour before.
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`
@@ -72,6 +84,20 @@ The app restores at start when its data folder is empty, so a restore is: put th
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
 
 
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`, and every save also keeps a copy as
52
+ `state/history/<time>.bin` (the newest `FPT_STATE_HISTORY`, default 5; older ones are deleted once an hour). If a
53
+ start-up restore fails, saving pauses (a notice in the app and `saved_state.paused` on `/api/ready`) so the good copy
54
+ is not overwritten.
55
+
56
+ `state/meta.json` carries a generation number and the instance that wrote it. Each start takes the next generation;
57
+ an older container that is still running (a Hugging Face rebuild keeps it up for a while) finds that at its next save
58
+ and stops saving: `saved_state.paused_reason` is `fenced`, the audit log has `state.fenced`, and the app shows
59
+ "Saving has stopped". Nothing to do: that container is the one being replaced. If it shows on the only running
60
+ instance, restart it (it restores the newer copy).
61
+
62
+ When the archive is over the size limit, evidence (then the folders of finished runs) is left out of it. Settings >
63
+ Storage says exactly what (`left_out_detail` on `/api/storage`), the audit log has `state.left_out`, and after a
64
+ restart those files answer 410 "not kept after a restart".
65
 
66
  - Status: `python -m coworker state status` (prints `state/meta.json`: when, how big, why, what was left out)
67
  - Save now: `POST /api/storage/save`, or `python -m coworker state push`
 
84
  4. If it says "the state archive cannot be decrypted with this key", `FPT_STATE_KEY` differs from the key the archive
85
  was saved with: set the old key and restart.
86
 
87
+ ### Going back to an earlier save (history)
88
+
89
+ 1. Pick the copy: the names are in `saved_state.history` on `/api/storage` (newest first; Settings > Storage shows
90
+ how many) and in `state/meta.json`. The name is the save time in UTC, e.g. `state/history/20261118T101500Z.bin`.
91
+ 2. Fence off the running app first, so none of its saves (its shutdown save included) lands on your copy: in
92
+ `state/meta.json` raise `generation` by one and set `instance` to `manual-restore`. Its next save is refused
93
+ (`state.fenced`). If the host can stop the app instead, stopping it before step 3 does the same.
94
+ 3. In the bucket, copy that object over `state/latest.bin` (Supabase: download it and upload it as `latest.bin`; OCI:
95
+ console "Copy", or `curl -fsS -o copy.bin "$OCI_STATE_PAR_URL"state/history/<time>.bin`, then
96
+ `curl -fsS -X PUT --data-binary @copy.bin "$OCI_STATE_PAR_URL"state/latest.bin`).
97
+ 4. Restart the app (Hugging Face: Restart, which starts with an empty data folder). It restores the copy and takes
98
+ the next generation. Anything saved after that copy is not restored; it stays in the newer history copies until
99
+ they age out.
100
+
101
  **Compose.** `deploy/backup.sh /secure/backups`. Restore: stop the stack, put the archive's files back in the
102
  `fpt-data` volume, start the stack. Keep backup archives encrypted: they contain the secrets vault in plain text.
103
 
tests/cases/AP-FUS-012.yaml CHANGED
@@ -58,8 +58,8 @@ steps:
58
  action: save
59
  expected: The invoice is saved without errors.
60
  - n: 10
61
- action: invoice_action
62
- value: Validate
63
  - n: 11
64
  action: expect_status
65
  value: Validated
 
58
  action: save
59
  expected: The invoice is saved without errors.
60
  - n: 10
61
+ action: validate_invoice
62
+ expected: Validated; when Fusion's tax leaves it out of balance, the amount is set to the Total first.
63
  - n: 11
64
  action: expect_status
65
  value: Validated
web/src/api/hooks.ts CHANGED
@@ -214,7 +214,7 @@ export function useSignOff(id: string) {
214
  }
215
 
216
  /** Whether the app's data is being saved to backup storage (public /api/ready); refreshed once a minute. */
217
- export type SavedState = { on: boolean; ok: boolean | null; paused?: boolean; last_saved_at?: string | null };
218
  export const useSavedState = () =>
219
  useQuery({ queryKey: ['saved-state'], refetchInterval: 60_000, retry: false,
220
  queryFn: async () => (await getJson<{ saved_state?: SavedState }>('/api/ready')).saved_state ?? null });
 
214
  }
215
 
216
  /** Whether the app's data is being saved to backup storage (public /api/ready); refreshed once a minute. */
217
+ export type SavedState = { on: boolean; ok: boolean | null; paused?: boolean; paused_reason?: 'restore_failed' | 'fenced' | null; last_saved_at?: string | null };
218
  export const useSavedState = () =>
219
  useQuery({ queryKey: ['saved-state'], refetchInterval: 60_000, retry: false,
220
  queryFn: async () => (await getJson<{ saved_state?: SavedState }>('/api/ready')).saved_state ?? null });
web/src/components/Layout.tsx CHANGED
@@ -33,9 +33,11 @@ function SavedStateNotice() {
33
  if (!s || !s.on || (s.ok !== false && !s.paused)) return null;
34
  return (
35
  <div className="fpt-savednotice" role="alert" data-testid="saved-state-notice">
36
- {s.paused
37
- ? 'Saving is paused: this instance could not read its saved data when it started, so it will not overwrite it. Restart the Space to try again; nothing you do now is saved.'
38
- : 'The latest changes could not be saved to backup storage. They will be lost if the app restarts before this clears.'}
 
 
39
  </div>
40
  );
41
  }
 
33
  if (!s || !s.on || (s.ok !== false && !s.paused)) return null;
34
  return (
35
  <div className="fpt-savednotice" role="alert" data-testid="saved-state-notice">
36
+ {s.paused && s.paused_reason === 'fenced'
37
+ ? 'Saving has stopped: a newer copy of the app has started and saved since this one did, so this one will not overwrite it. Reload the page in a minute to reach the newer copy; nothing you do here is saved.'
38
+ : s.paused
39
+ ? 'Saving is paused: this instance could not read its saved data when it started, so it will not overwrite it. Restart the Space to try again; nothing you do now is saved.'
40
+ : 'The latest changes could not be saved to backup storage. They will be lost if the app restarts before this clears.'}
41
  </div>
42
  );
43
  }
web/src/components/common.tsx CHANGED
@@ -75,7 +75,7 @@ const STATUS_LABEL: Record<string, string> = RUN_STATUS_WORDS;
75
 
76
  export function StatusBadge({ status }: { status?: string | null }) {
77
  if (!status) return <Pill>-</Pill>;
78
- return <Pill tone={STATUS_TONE[status] ?? 'neutral'} testId={`status-${status}`}>{STATUS_LABEL[status] ?? status.replace('_', ' ')}</Pill>;
79
  }
80
 
81
  /** Decision in consultant words ("Ready" / "Not ready" / "On hold"); the exact rule result stays on the element
 
75
 
76
  export function StatusBadge({ status }: { status?: string | null }) {
77
  if (!status) return <Pill>-</Pill>;
78
+ return <Pill tone={STATUS_TONE[status] ?? 'neutral'} testId={`status-${status}`}>{STATUS_LABEL[status] ?? status.replace(/_/g, ' ')}</Pill>;
79
  }
80
 
81
  /** Decision in consultant words ("Ready" / "Not ready" / "On hold"); the exact rule result stays on the element
web/src/domain/glossary.ts CHANGED
@@ -52,3 +52,27 @@ export function reviewAnswer(choice: FailureChoice | undefined, extra: { note?:
52
  if (extra.owner) out.owner = extra.owner;
53
  return out;
54
  }
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  if (extra.owner) out.owner = extra.owner;
53
  return out;
54
  }
55
+
56
+ /** The failure analysis's suggested cause, in plain words, with a tone that keeps likely product defects (red) apart
57
+ * from causes on the testing side: a changed screen the script must follow, test data, or timing/environment. */
58
+ export const FAILURE_CAUSE: Record<string, { words: string; tone: 'red' | 'lav' | 'amber' | 'ink' | 'neutral'; side: 'product' | 'testing' | 'unknown' }> = {
59
+ real_defect: { words: 'Likely product defect', tone: 'red', side: 'product' },
60
+ ui_change: { words: 'Screen changed: test script needs updating', tone: 'lav', side: 'testing' },
61
+ data: { words: 'Test data problem', tone: 'amber', side: 'testing' },
62
+ timing: { words: 'Timing or environment problem', tone: 'ink', side: 'testing' },
63
+ unclassified: { words: 'Cause not clear yet', tone: 'neutral', side: 'unknown' },
64
+ };
65
+ export const failureCause = (category?: string | null) =>
66
+ FAILURE_CAUSE[category ?? 'unclassified'] ?? { words: 'Cause not clear yet', tone: 'neutral' as const, side: 'unknown' as const };
67
+
68
+ /** A run's stop reason for people: newer runs store a plain sentence; older ones may hold "SomeError: text" or a
69
+ * traceback, which reads as the text after the class name, or a generic sentence when nothing readable is left. */
70
+ export function plainReason(error?: string | null): string {
71
+ const raw = (error ?? '').trim();
72
+ if (!raw || /^(none|null|undefined)$/i.test(raw)) return '';
73
+ if (/^Traceback \(most recent call last\)/.test(raw)) return 'An internal error stopped the test run. An administrator can see the details in the audit log.';
74
+ const t = raw.replace(/^(?:[\w.]+\.)?[A-Z]\w*(?:Error|Exception|Engaged|Interrupt)\s*:\s*/, '').trim();
75
+ if (!t) return 'An internal error stopped the test run. An administrator can see the details in the audit log.';
76
+ const u = t.charAt(0).toUpperCase() + t.slice(1);
77
+ return /[.!?]$/.test(u) ? u : `${u}.`;
78
+ }
web/src/pages/account/AccountPage.tsx CHANGED
@@ -135,7 +135,10 @@ export function FeaturesPanel() {
135
  }
136
 
137
  interface Storage {
138
- saved_state: { on: boolean; last_saved_at: string | null; bytes: number | null; left_out: string[]; reason: string | null; last_error: string | null; last_error_at: string | null };
 
 
 
139
  on_disk: Record<string, number>;
140
  retention: { evidence_days: number; checkpoint_days: number; run_files_days: number };
141
  last_prune: unknown;
@@ -154,9 +157,17 @@ export function StoragePanel() {
154
  {q.isLoading && <Skeleton height={160} />}
155
  {st && (
156
  !st.on ? <Alert color="gray" title="No off-site backup">This server keeps its data on its own disk only.</Alert>
 
 
 
157
  : st.last_error ? <Alert color="red" title="The last backup failed">{st.last_error_at ? `${shortWhen(st.last_error_at)}: ` : ''}{st.last_error}</Alert>
158
  : <Alert color="green" title="Backups are working">Last saved {st.last_saved_at ? shortWhen(st.last_saved_at) : 'not yet'}{st.bytes ? ` (${mb(st.bytes)})` : ''}.
159
- {st.left_out.length ? ` Left out to stay under the size limit: ${st.left_out.join(', ')}.` : ''}</Alert>
 
 
 
 
 
160
  )}
161
  {q.data && (
162
  <Table verticalSpacing={6} aria-label="Storage on this server">
 
135
  }
136
 
137
  interface Storage {
138
+ saved_state: {
139
+ on: boolean; last_saved_at: string | null; bytes: number | null; left_out: string[]; reason: string | null; last_error: string | null; last_error_at: string | null;
140
+ left_out_note?: string | null; paused?: boolean; paused_reason?: 'restore_failed' | 'fenced' | null; history?: string[]; history_keep?: number;
141
+ };
142
  on_disk: Record<string, number>;
143
  retention: { evidence_days: number; checkpoint_days: number; run_files_days: number };
144
  last_prune: unknown;
 
157
  {q.isLoading && <Skeleton height={160} />}
158
  {st && (
159
  !st.on ? <Alert color="gray" title="No off-site backup">This server keeps its data on its own disk only.</Alert>
160
+ : st.paused ? <Alert color="red" title="Saving is paused">{st.paused_reason === 'fenced'
161
+ ? 'A newer copy of the app has started and saved since this one did, so this one no longer saves and cannot overwrite it.'
162
+ : 'This copy of the app could not read its saved data when it started, so it does not save over it. Restart the app to try again.'}</Alert>
163
  : st.last_error ? <Alert color="red" title="The last backup failed">{st.last_error_at ? `${shortWhen(st.last_error_at)}: ` : ''}{st.last_error}</Alert>
164
  : <Alert color="green" title="Backups are working">Last saved {st.last_saved_at ? shortWhen(st.last_saved_at) : 'not yet'}{st.bytes ? ` (${mb(st.bytes)})` : ''}.
165
+ {st.history?.length ? ` ${st.history.length} earlier ${st.history.length === 1 ? 'copy is' : 'copies are'} kept to go back to.` : ''}</Alert>
166
+ )}
167
+ {st?.on && (st.left_out_note || st.left_out.length > 0) && (
168
+ <Alert color="yellow" title="Not everything is in the saved copy" data-testid="storage-left-out">
169
+ {st.left_out_note ?? `Left out to stay under the size limit: ${st.left_out.join(', ')}.`}
170
+ </Alert>
171
  )}
172
  {q.data && (
173
  <Table verticalSpacing={6} aria-label="Storage on this server">
web/src/pages/run/FailureReview.tsx CHANGED
@@ -6,7 +6,7 @@ import { useHumanReview, useRun, useRunFailures } from '../../api/hooks';
6
  import { FailedScreen } from './FailedScreen';
7
  import type { Failure } from '../../api/types';
8
  import { Can, ErrorAlert, Pill, Term } from '../../components/common';
9
- import { reviewAnswer, type FailureChoice } from '../../domain/glossary';
10
  import { Presence } from './ScenarioReview';
11
  import './review.css';
12
  import './split.css';
@@ -34,6 +34,7 @@ export function FailureCard({ f, draft, onChange, editable, quick = false }: { f
34
  const done = f.answer;
35
  const shot = quick || (f.screenshots.length > 0 && can('evidence.read'));
36
  const waiver = f.ask === 'confirm' && draft.choice === 'real_defect' && f.priority === 'P2';
 
37
  return (
38
  <div className="fpt-card pw-card rv-failure" data-testid={`failure-${f.case_id}`}>
39
  <Group justify="space-between" wrap="wrap" gap={6}>
@@ -43,7 +44,10 @@ export function FailureCard({ f, draft, onChange, editable, quick = false }: { f
43
  {[f.outcome === 'flaky' ? `Passed only on retry${f.step ? ` (step ${f.step})` : ''}.` : f.step ? `Failed at ${f.step}.` : 'Failed.', f.priority_words ? `${f.priority_words}.` : ''].filter(Boolean).join(' ')}
44
  </Text>
45
  </div>
46
- {done && <Pill tone="green">answered: {done.confirmed ? ANSWER_WORDS[done.confirmed] ?? done.confirmed.replace(/_/g, ' ') : done.owner ? `owner ${done.owner}` : 'yes'}</Pill>}
 
 
 
47
  </Group>
48
  <SimpleGrid cols={{ base: 1, md: shot ? 2 : 1 }} spacing="sm" mt="sm">
49
  <div>
@@ -52,7 +56,7 @@ export function FailureCard({ f, draft, onChange, editable, quick = false }: { f
52
  <dt>Actual</dt><dd>{f.actual ?? 'not stated in the test output'}</dd>
53
  </dl>
54
  <div className="rv-suggest">
55
- <Text size="sm"><IconBulb size={13} className="rv-inline-icon" aria-hidden /> <b><Term k="Failure analysis">Suggestion</Term>:</b> {f.suggestion} <Text span size="xs" c="dimmed">({Math.round((f.confidence ?? 0) * 100)}% sure)</Text></Text>
56
  </div>
57
  </div>
58
  {shot && <FailedScreen f={f} quick={quick} />}
@@ -124,7 +128,7 @@ export function FailureReview({ id, waiting }: { id: string; waiting: boolean })
124
  return (
125
  <button key={f.case_id} type="button" className="sp-item" data-k={st.k} aria-current={cur.case_id === f.case_id || undefined} onClick={() => setPick(f.case_id)}>
126
  <span className="sp-dot" data-k={st.k} aria-hidden />
127
- <span className="sp-it"><b>{f.title ?? f.case_id}</b><span className="sp-sub">{f.case_id}{f.priority_words ? ` · ${f.priority_words}` : ''} · {st.words}</span></span>
128
  </button>
129
  );
130
  })}
 
6
  import { FailedScreen } from './FailedScreen';
7
  import type { Failure } from '../../api/types';
8
  import { Can, ErrorAlert, Pill, Term } from '../../components/common';
9
+ import { failureCause, reviewAnswer, type FailureChoice } from '../../domain/glossary';
10
  import { Presence } from './ScenarioReview';
11
  import './review.css';
12
  import './split.css';
 
34
  const done = f.answer;
35
  const shot = quick || (f.screenshots.length > 0 && can('evidence.read'));
36
  const waiver = f.ask === 'confirm' && draft.choice === 'real_defect' && f.priority === 'P2';
37
+ const cause = failureCause(f.category);
38
  return (
39
  <div className="fpt-card pw-card rv-failure" data-testid={`failure-${f.case_id}`}>
40
  <Group justify="space-between" wrap="wrap" gap={6}>
 
44
  {[f.outcome === 'flaky' ? `Passed only on retry${f.step ? ` (step ${f.step})` : ''}.` : f.step ? `Failed at ${f.step}.` : 'Failed.', f.priority_words ? `${f.priority_words}.` : ''].filter(Boolean).join(' ')}
45
  </Text>
46
  </div>
47
+ <Group gap={6} wrap="wrap">
48
+ <Pill tone={cause.tone} testId={`failure-cause-${f.case_id}`} title={cause.side === 'testing' ? 'A suggested cause on the testing side, not in the product' : cause.side === 'product' ? 'Suggested cause; a reviewer confirms every defect' : undefined}>{cause.words}</Pill>
49
+ {done && <Pill tone="green">Answered: {done.confirmed ? ANSWER_WORDS[done.confirmed] ?? done.confirmed.replace(/_/g, ' ') : done.owner ? `owner ${done.owner}` : 'yes'}</Pill>}
50
+ </Group>
51
  </Group>
52
  <SimpleGrid cols={{ base: 1, md: shot ? 2 : 1 }} spacing="sm" mt="sm">
53
  <div>
 
56
  <dt>Actual</dt><dd>{f.actual ?? 'not stated in the test output'}</dd>
57
  </dl>
58
  <div className="rv-suggest">
59
+ <Text size="sm"><IconBulb size={13} className="rv-inline-icon" aria-hidden /> <b><Term k="Failure analysis">Suggestion</Term>:</b> {f.suggestion || 'No suggestion for this failure.'}{f.confidence ? <Text span size="xs" c="dimmed"> ({Math.round(f.confidence * 100)}% sure)</Text> : null}</Text>
60
  </div>
61
  </div>
62
  {shot && <FailedScreen f={f} quick={quick} />}
 
128
  return (
129
  <button key={f.case_id} type="button" className="sp-item" data-k={st.k} aria-current={cur.case_id === f.case_id || undefined} onClick={() => setPick(f.case_id)}>
130
  <span className="sp-dot" data-k={st.k} aria-hidden />
131
+ <span className="sp-it"><b>{f.title ?? f.case_id}</b><span className="sp-sub">{failureCause(f.category).words}{f.priority_words ? ` · ${f.priority_words}` : ''} · {st.words}</span></span>
132
  </button>
133
  );
134
  })}
web/src/pages/run/RunData.tsx CHANGED
@@ -1,6 +1,12 @@
1
  import { Badge, Card, Loader, Stack, Table, Text, Title } from '@mantine/core';
2
  import { useDataPlan, useScripts } from '../../api/hooks';
3
- import { ErrorAlert, StatusBadge } from '../../components/common';
 
 
 
 
 
 
4
 
5
  const DATA_COLOR: Record<string, string> = { found: 'teal', not_found: 'red', seeded: 'dark', seed_refused: 'orange', unsupported: 'gray', skipped: 'gray' };
6
 
@@ -20,8 +26,8 @@ export function RunData({ id }: { id: string }) {
20
  <Table.Tbody>
21
  {Object.values(d.data_refs).map((r) => (
22
  <Table.Tr key={r.recipe_id}><Table.Td>{r.recipe_id}</Table.Td><Table.Td>{r.strategy}</Table.Td>
23
- <Table.Td><Badge size="xs" color={DATA_COLOR[r.status] ?? 'gray'}>{r.status}</Badge></Table.Td>
24
- <Table.Td>{JSON.stringify(r.outputs)}</Table.Td><Table.Td>{r.note}</Table.Td></Table.Tr>
25
  ))}
26
  </Table.Tbody>
27
  </Table>
@@ -45,7 +51,7 @@ export function RunScripts({ id }: { id: string }) {
45
  if (q.isLoading) return <Loader />;
46
  if (q.error) return <ErrorAlert error={q.error} />;
47
  const rows = Object.values(q.data ?? {});
48
- const yn = (v: boolean | null) => (v === null ? '-' : v ? 'ok' : 'FAIL');
49
  return (
50
  <Card withBorder>
51
  <Title order={2} size="h5">Scripts ({rows.length}): {rows.filter((r) => r.status === 'existing').length} existing, {rows.filter((r) => r.status === 'generated').length} generated drafts</Title>
@@ -56,7 +62,7 @@ export function RunScripts({ id }: { id: string }) {
56
  {rows.map((s) => (
57
  <Table.Tr key={s.case_id}><Table.Td>{s.case_id}</Table.Td><Table.Td><Badge size="xs" variant="light" color={s.status === 'existing' ? 'dark' : 'gray'}>{s.status}</Badge></Table.Td>
58
  <Table.Td style={{ wordBreak: 'break-all' }}>{s.path || s.note}</Table.Td><Table.Td>{yn(s.lint_ok)}</Table.Td><Table.Td>{yn(s.dry_run_ok)}</Table.Td>
59
- <Table.Td><StatusBadge status={s.last_outcome === 'passed' ? 'completed' : s.last_outcome === 'failed' ? 'failed' : s.last_outcome ?? undefined} /> {s.last_outcome}</Table.Td></Table.Tr>
60
  ))}
61
  </Table.Tbody>
62
  </Table>
 
1
  import { Badge, Card, Loader, Stack, Table, Text, Title } from '@mantine/core';
2
  import { useDataPlan, useScripts } from '../../api/hooks';
3
+ import { ErrorAlert } from '../../components/common';
4
+
5
+ /** A recipe's outputs as "name: value" pairs, not a JSON blob. */
6
+ function outputWords(o: unknown): string {
7
+ if (o == null || typeof o !== 'object') return o == null ? '' : String(o);
8
+ return Object.entries(o as Record<string, unknown>).map(([k, v]) => `${k}: ${v == null ? '' : typeof v === 'object' ? JSON.stringify(v) : String(v)}`).join(', ');
9
+ }
10
 
11
  const DATA_COLOR: Record<string, string> = { found: 'teal', not_found: 'red', seeded: 'dark', seed_refused: 'orange', unsupported: 'gray', skipped: 'gray' };
12
 
 
26
  <Table.Tbody>
27
  {Object.values(d.data_refs).map((r) => (
28
  <Table.Tr key={r.recipe_id}><Table.Td>{r.recipe_id}</Table.Td><Table.Td>{r.strategy}</Table.Td>
29
+ <Table.Td><Badge size="xs" color={DATA_COLOR[r.status] ?? 'gray'}>{r.status.replace(/_/g, ' ')}</Badge></Table.Td>
30
+ <Table.Td>{outputWords(r.outputs)}</Table.Td><Table.Td>{r.note}</Table.Td></Table.Tr>
31
  ))}
32
  </Table.Tbody>
33
  </Table>
 
51
  if (q.isLoading) return <Loader />;
52
  if (q.error) return <ErrorAlert error={q.error} />;
53
  const rows = Object.values(q.data ?? {});
54
+ const yn = (v: boolean | null) => (v === null ? 'Not checked' : v ? 'Passed' : 'Failed');
55
  return (
56
  <Card withBorder>
57
  <Title order={2} size="h5">Scripts ({rows.length}): {rows.filter((r) => r.status === 'existing').length} existing, {rows.filter((r) => r.status === 'generated').length} generated drafts</Title>
 
62
  {rows.map((s) => (
63
  <Table.Tr key={s.case_id}><Table.Td>{s.case_id}</Table.Td><Table.Td><Badge size="xs" variant="light" color={s.status === 'existing' ? 'dark' : 'gray'}>{s.status}</Badge></Table.Td>
64
  <Table.Td style={{ wordBreak: 'break-all' }}>{s.path || s.note}</Table.Td><Table.Td>{yn(s.lint_ok)}</Table.Td><Table.Td>{yn(s.dry_run_ok)}</Table.Td>
65
+ <Table.Td>{s.last_outcome ? <Badge size="xs" variant="light" color={s.last_outcome === 'passed' ? 'teal' : s.last_outcome === 'failed' ? 'red' : 'gray'}>{s.last_outcome.replace(/_/g, ' ')}</Badge> : <Text span size="xs" c="dimmed">Not run yet</Text>}</Table.Td></Table.Tr>
66
  ))}
67
  </Table.Tbody>
68
  </Table>
web/src/pages/run/RunGuide.tsx CHANGED
@@ -7,8 +7,8 @@ import { Link } from 'react-router-dom';
7
  import type { Schemas } from '../../api/client';
8
  import { useApproveCases, useGate, usePods, useHumanReview, useRunAction, useRunFailures, useRunReadiness } from '../../api/hooks';
9
  import type { ApproveGate, Failure } from '../../api/types';
10
- import { Can, ErrorAlert } from '../../components/common';
11
- import { decisionWords, reviewAnswer, type FailureChoice } from '../../domain/glossary';
12
  import { FailedScreen } from './FailedScreen';
13
  import { useSidePanelOptional } from '../../components/shell/SidePanel';
14
  import { LiveView } from './LiveView';
@@ -192,6 +192,7 @@ export function Judge({ r, onShowScreen, onShowSteps }: { r: Run; onShowScreen?:
192
  <div className="fpt-judge trio-judge" data-testid={`guide-failure-${f.case_id}`}>
193
  <div className="fpt-judge-text">
194
  <Text fw={600}>{f.title ?? f.case_id}</Text>
 
195
  {f.step && <Text size="xs" c="dimmed" mb="sm">It stopped at: {f.step}</Text>}
196
  {f.ask === 'owner' ? (
197
  <>
@@ -209,7 +210,7 @@ export function Judge({ r, onShowScreen, onShowSteps }: { r: Run; onShowScreen?:
209
  <Text size="sm" c="dimmed" mt={6} className="fpt-judge-noscreen"><IconPhotoOff size={14} style={{ verticalAlign: -2 }} aria-hidden /> No screen: quick simulations don&apos;t open a browser.</Text>
210
  )}
211
  {onShowSteps && <Button variant="subtle" size="compact-xs" mt={6} px={0} leftSection={<IconListDetails size={14} />} onClick={() => onShowSteps(f.case_id)}>Show the steps</Button>}
212
- <Text size="sm" mt="sm"><b>Our suggestion:</b> {f.suggestion}</Text>
213
  <Text size="sm" fw={600} mt="md" mb={2}>Is this a real problem?</Text>
214
  <div className="trio-radiolist" role="radiogroup" aria-label="Is this a real problem?">
215
  {CHOICES.map((c) => (
@@ -285,7 +286,7 @@ export function Stopped({ r }: { r: Run }) {
285
  return (
286
  <Stack gap="sm">
287
  <h3 className="trio-card-h">{r.status === 'cancelled' ? 'This test run was cancelled' : r.status === 'killed' ? 'This test run was stopped by the emergency stop' : 'This test run stopped before it finished'}</h3>
288
- {r.error && <p className="trio-lede">Reason: {r.error}</p>}
289
  <ErrorAlert error={action.error} />
290
  <Can perm="run.control">
291
  {['interrupted', 'failed'].includes(r.status) && <Button w="fit-content" variant="filled" onClick={() => action.mutate({ id: r.run_id, action: 'resume' })} loading={action.isPending}>Carry on from where it stopped</Button>}
 
7
  import type { Schemas } from '../../api/client';
8
  import { useApproveCases, useGate, usePods, useHumanReview, useRunAction, useRunFailures, useRunReadiness } from '../../api/hooks';
9
  import type { ApproveGate, Failure } from '../../api/types';
10
+ import { Can, ErrorAlert, Pill } from '../../components/common';
11
+ import { decisionWords, failureCause, plainReason, reviewAnswer, type FailureChoice } from '../../domain/glossary';
12
  import { FailedScreen } from './FailedScreen';
13
  import { useSidePanelOptional } from '../../components/shell/SidePanel';
14
  import { LiveView } from './LiveView';
 
192
  <div className="fpt-judge trio-judge" data-testid={`guide-failure-${f.case_id}`}>
193
  <div className="fpt-judge-text">
194
  <Text fw={600}>{f.title ?? f.case_id}</Text>
195
+ {f.ask !== 'owner' && <Pill tone={failureCause(f.category).tone} testId={`guide-cause-${f.case_id}`}>{failureCause(f.category).words}</Pill>}
196
  {f.step && <Text size="xs" c="dimmed" mb="sm">It stopped at: {f.step}</Text>}
197
  {f.ask === 'owner' ? (
198
  <>
 
210
  <Text size="sm" c="dimmed" mt={6} className="fpt-judge-noscreen"><IconPhotoOff size={14} style={{ verticalAlign: -2 }} aria-hidden /> No screen: quick simulations don&apos;t open a browser.</Text>
211
  )}
212
  {onShowSteps && <Button variant="subtle" size="compact-xs" mt={6} px={0} leftSection={<IconListDetails size={14} />} onClick={() => onShowSteps(f.case_id)}>Show the steps</Button>}
213
+ <Text size="sm" mt="sm"><b>Our suggestion:</b> {f.suggestion || 'No suggestion for this failure.'}</Text>
214
  <Text size="sm" fw={600} mt="md" mb={2}>Is this a real problem?</Text>
215
  <div className="trio-radiolist" role="radiogroup" aria-label="Is this a real problem?">
216
  {CHOICES.map((c) => (
 
286
  return (
287
  <Stack gap="sm">
288
  <h3 className="trio-card-h">{r.status === 'cancelled' ? 'This test run was cancelled' : r.status === 'killed' ? 'This test run was stopped by the emergency stop' : 'This test run stopped before it finished'}</h3>
289
+ {plainReason(r.error) && <p className="trio-lede">Reason: {plainReason(r.error)}</p>}
290
  <ErrorAlert error={action.error} />
291
  <Can perm="run.control">
292
  {['interrupted', 'failed'].includes(r.status) && <Button w="fit-content" variant="filled" onClick={() => action.mutate({ id: r.run_id, action: 'resume' })} loading={action.isPending}>Carry on from where it stopped</Button>}
web/src/pages/run/RunPage.tsx CHANGED
@@ -9,7 +9,7 @@ import { AGENT_BY_NODE, stepName } from '../../domain/agents';
9
  import { shortWhenSec } from '../../domain/runName';
10
  import { api, unwrap } from '../../api/client';
11
  import { useGraphSpec, useReport, useRun, useRunReadiness, useTemporal } from '../../api/hooks';
12
- import { decisionWords } from '../../domain/glossary';
13
  import { ModuleCard, PatchChanges } from '../home/ReadinessPage';
14
  import { Can, ErrorAlert, fmtTs, Pill } from '../../components/common';
15
  import { GraphView } from '../../components/GraphView';
@@ -223,13 +223,13 @@ export function NextStep({ r, here, compact = false }: {
223
  action = { to: `/runs/${r.run_id}/report`, label: 'Open report & sign-off' };
224
  } else if (r.status === 'interrupted') {
225
  tone = 'amber'; title = 'Paused: you can carry on';
226
- body = r.error ? `Reason: ${r.error}` : 'The run did not finish. Someone with run control can resume it from the last completed step.';
227
  } else if (r.status === 'cancelled') {
228
  tone = 'neutral'; title = 'Cancelled';
229
- body = r.error ? `Reason: ${r.error}` : 'This test run was cancelled before it finished.';
230
  } else {
231
  tone = 'red'; title = 'Stopped';
232
- body = r.error ? `Reason: ${r.error}` : 'The run did not finish. Someone with run control can resume it from the last completed step.';
233
  }
234
  if (action && here && action.to.endsWith(`/${here}`)) action = null; // never a button to the page you are on
235
  if (compact && !action) {
 
9
  import { shortWhenSec } from '../../domain/runName';
10
  import { api, unwrap } from '../../api/client';
11
  import { useGraphSpec, useReport, useRun, useRunReadiness, useTemporal } from '../../api/hooks';
12
+ import { decisionWords, plainReason } from '../../domain/glossary';
13
  import { ModuleCard, PatchChanges } from '../home/ReadinessPage';
14
  import { Can, ErrorAlert, fmtTs, Pill } from '../../components/common';
15
  import { GraphView } from '../../components/GraphView';
 
223
  action = { to: `/runs/${r.run_id}/report`, label: 'Open report & sign-off' };
224
  } else if (r.status === 'interrupted') {
225
  tone = 'amber'; title = 'Paused: you can carry on';
226
+ body = plainReason(r.error) ? `Reason: ${plainReason(r.error)}` : 'The run did not finish. Someone with run control can resume it from the last completed step.';
227
  } else if (r.status === 'cancelled') {
228
  tone = 'neutral'; title = 'Cancelled';
229
+ body = plainReason(r.error) ? `Reason: ${plainReason(r.error)}` : 'This test run was cancelled before it finished.';
230
  } else {
231
  tone = 'red'; title = 'Stopped';
232
+ body = plainReason(r.error) ? `Reason: ${plainReason(r.error)}` : 'The run did not finish. Someone with run control can resume it from the last completed step.';
233
  }
234
  if (action && here && action.to.endsWith(`/${here}`)) action = null; // never a button to the page you are on
235
  if (compact && !action) {
web/src/pages/run/RunReport.tsx CHANGED
@@ -8,6 +8,17 @@ import { Can, DecisionBadge, ErrorAlert } from '../../components/common';
8
  import { EmptyState, LoadingState } from '../../components/states';
9
  import './report.css';
10
 
 
 
 
 
 
 
 
 
 
 
 
11
  /** The technical report (admin view): the exact rule result per area, the counts, the criteria, the open gaps, the
12
  * generated report itself and the run's evidence files. */
13
  export function RunReport({ id, done }: { id: string; done: boolean }) {
@@ -21,7 +32,7 @@ export function RunReport({ id, done }: { id: string; done: boolean }) {
21
  setDeleting(true);
22
  try {
23
  const r = await unwrap(api.DELETE('/api/runs/{run_id}/evidence', { params: { path: { run_id: id } } })) as { files: number };
24
- setDelMsg(`Deleted ${r.files} evidence file(s).`);
25
  await qc.invalidateQueries({ queryKey: ['run', id] });
26
  void ev.refetch();
27
  } catch (x) {
@@ -47,7 +58,7 @@ export function RunReport({ id, done }: { id: string; done: boolean }) {
47
  <Stack gap="md" className="rpt">
48
  <div className="pw-card rpt-notice" role="note">
49
  <b>{r.target}</b>
50
- <span>Decisions come only from reports/generate_report.py (QA rule C1-C6). {r.run_mode === 'stub' ? 'STUB RUN: synthetic results, no browser.' : r.target?.startsWith('Oracle Fusion') ? `Live run against the ${r.target}.` : 'Live run against the local mock app.'}</span>
51
  </div>
52
  {mods.length > 1 && <SegmentedControl aria-label="Business area" value={m} onChange={setMod} data={mods} className="rpt-areas" />}
53
  <section className="pw-card rpt-section" aria-labelledby="rpt-tech-h">
@@ -56,8 +67,8 @@ export function RunReport({ id, done }: { id: string; done: boolean }) {
56
  <Group gap="md" className="rpt-links">
57
  <Anchor href={`${base}/md?download=true`} download>Markdown</Anchor>
58
  <Anchor href={`${base}/html?download=true`} download>HTML</Anchor>
59
- {r.files[m]?.pdf ? <Anchor href={`${base}/pdf`} download data-testid="pdf-link">PDF</Anchor> : <Text size="sm" c="dimmed">PDF n/a</Text>}
60
- <Anchor href={`${base}/summary?download=true`} download>run-summary.json</Anchor>
61
  </Group>
62
  </Group>
63
  <Text size="sm" data-testid="exec-summary">{r.executive_summary[m]}</Text>
@@ -66,12 +77,12 @@ export function RunReport({ id, done }: { id: string; done: boolean }) {
66
  <Table.Thead><Table.Tr><Table.Th>Criterion</Table.Th><Table.Th>Met</Table.Th><Table.Th>Detail</Table.Th></Table.Tr></Table.Thead>
67
  <Table.Tbody>
68
  {Object.entries(r.criteria[m] ?? {}).map(([k, c]) => (
69
- <Table.Tr key={k}><Table.Td>{k}</Table.Td><Table.Td><span className="pw-status" data-tone={c.ok ? 'green' : 'red'}>{c.ok ? 'met' : 'NOT met'}</span></Table.Td><Table.Td><Text size="xs">{c.detail}</Text></Table.Td></Table.Tr>
70
  ))}
71
  </Table.Tbody>
72
  </Table>
73
  <Title order={3} className="rpt-h3">Open gaps</Title>
74
- {(r.gaps[m] ?? []).length === 0 ? <Text size="xs" c="dimmed">None.</Text> : (
75
  <ul className="rpt-list">{(r.gaps[m] ?? []).map((g, i) => <li key={i}>{g}</li>)}</ul>
76
  )}
77
  </section>
@@ -88,10 +99,10 @@ export function RunReport({ id, done }: { id: string; done: boolean }) {
88
  </Can>
89
  </Group>
90
  {delMsg && <Text size="xs" role="status">{delMsg}</Text>}
91
- {(ev.data ?? []).length === 0 ? <Text size="xs" c="dimmed">No evidence (stub runs have no browser artifacts).</Text> : (
92
  <Table fz="xs" aria-label="evidence" className="pw-table"><Table.Tbody>
93
  {(ev.data ?? []).slice(0, 200).map((e) => (
94
- <Table.Tr key={e.evidence_id}><Table.Td>{e.case_id}</Table.Td><Table.Td>attempt {e.attempt}</Table.Td><Table.Td>{e.available === false ? <Text span size="xs" c="dimmed" title="No longer stored on the server">{e.name} (no longer stored)</Text> : <Anchor href={`/api/evidence/${e.evidence_id}`} target="_blank" rel="noopener">{e.name}</Anchor>}</Table.Td><Table.Td>{e.content_type}</Table.Td><Table.Td className="pw-num">{Math.round(e.size / 1024)} KB</Table.Td></Table.Tr>
95
  ))}
96
  </Table.Tbody></Table>
97
  )}
 
8
  import { EmptyState, LoadingState } from '../../components/states';
9
  import './report.css';
10
 
11
+ /** A file's media type in plain words ("Screenshot" rather than "image/png"). */
12
+ function fileKind(t?: string | null): string {
13
+ if (!t) return 'File';
14
+ if (t.startsWith('image/')) return 'Screenshot';
15
+ if (t.startsWith('video/')) return 'Video';
16
+ if (t.includes('zip')) return 'Trace';
17
+ if (t.includes('json')) return 'Data (JSON)';
18
+ if (t.startsWith('text/')) return 'Text';
19
+ return t;
20
+ }
21
+
22
  /** The technical report (admin view): the exact rule result per area, the counts, the criteria, the open gaps, the
23
  * generated report itself and the run's evidence files. */
24
  export function RunReport({ id, done }: { id: string; done: boolean }) {
 
32
  setDeleting(true);
33
  try {
34
  const r = await unwrap(api.DELETE('/api/runs/{run_id}/evidence', { params: { path: { run_id: id } } })) as { files: number };
35
+ setDelMsg(`Deleted ${r.files} evidence ${r.files === 1 ? 'file' : 'files'}.`);
36
  await qc.invalidateQueries({ queryKey: ['run', id] });
37
  void ev.refetch();
38
  } catch (x) {
 
58
  <Stack gap="md" className="rpt">
59
  <div className="pw-card rpt-notice" role="note">
60
  <b>{r.target}</b>
61
+ <span>Go/no-go decisions come only from the fixed QA rules (C1–C6), never from the AI. {r.run_mode === 'stub' ? 'Quick simulation: example results, no browser was opened.' : r.target?.startsWith('Oracle Fusion') ? `Live test run against the ${r.target}.` : 'Live test run against the practice app.'}</span>
62
  </div>
63
  {mods.length > 1 && <SegmentedControl aria-label="Business area" value={m} onChange={setMod} data={mods} className="rpt-areas" />}
64
  <section className="pw-card rpt-section" aria-labelledby="rpt-tech-h">
 
67
  <Group gap="md" className="rpt-links">
68
  <Anchor href={`${base}/md?download=true`} download>Markdown</Anchor>
69
  <Anchor href={`${base}/html?download=true`} download>HTML</Anchor>
70
+ {r.files[m]?.pdf ? <Anchor href={`${base}/pdf`} download data-testid="pdf-link">PDF</Anchor> : <Text size="sm" c="dimmed">PDF not available</Text>}
71
+ <Anchor href={`${base}/summary?download=true`} download>Summary (JSON)</Anchor>
72
  </Group>
73
  </Group>
74
  <Text size="sm" data-testid="exec-summary">{r.executive_summary[m]}</Text>
 
77
  <Table.Thead><Table.Tr><Table.Th>Criterion</Table.Th><Table.Th>Met</Table.Th><Table.Th>Detail</Table.Th></Table.Tr></Table.Thead>
78
  <Table.Tbody>
79
  {Object.entries(r.criteria[m] ?? {}).map(([k, c]) => (
80
+ <Table.Tr key={k}><Table.Td>{k}</Table.Td><Table.Td><span className="pw-status" data-tone={c.ok ? 'green' : 'red'}>{c.ok ? 'Met' : 'Not met'}</span></Table.Td><Table.Td><Text size="xs">{c.detail}</Text></Table.Td></Table.Tr>
81
  ))}
82
  </Table.Tbody>
83
  </Table>
84
  <Title order={3} className="rpt-h3">Open gaps</Title>
85
+ {(r.gaps[m] ?? []).length === 0 ? <Text size="xs" c="dimmed">No open gaps.</Text> : (
86
  <ul className="rpt-list">{(r.gaps[m] ?? []).map((g, i) => <li key={i}>{g}</li>)}</ul>
87
  )}
88
  </section>
 
99
  </Can>
100
  </Group>
101
  {delMsg && <Text size="xs" role="status">{delMsg}</Text>}
102
+ {(ev.data ?? []).length === 0 ? <Text size="xs" c="dimmed">No screenshots, videos or traces for this test run. Quick simulations don&apos;t open a browser, so they have none.</Text> : (
103
  <Table fz="xs" aria-label="evidence" className="pw-table"><Table.Tbody>
104
  {(ev.data ?? []).slice(0, 200).map((e) => (
105
+ <Table.Tr key={e.evidence_id}><Table.Td>{e.case_id}</Table.Td><Table.Td>Attempt {e.attempt + 1}</Table.Td><Table.Td>{e.available === false ? <Text span size="xs" c="dimmed" title="No longer stored on the server">{e.name} (no longer stored)</Text> : <Anchor href={`/api/evidence/${e.evidence_id}`} target="_blank" rel="noopener">{e.name}</Anchor>}</Table.Td><Table.Td>{fileKind(e.content_type)}</Table.Td><Table.Td className="pw-num">{Math.round(e.size / 1024)} KB</Table.Td></Table.Tr>
106
  ))}
107
  </Table.Tbody></Table>
108
  )}
web/src/pages/run/RunStages.tsx CHANGED
@@ -175,7 +175,7 @@ export function RunStages({ id }: { id: string }) {
175
  if (run.error || !r) {
176
  return (
177
  <div className="fpt-ws-scroll"><div className="trio-stages">
178
- <ErrorAlert error={run.error ?? new Error('test run not found')} />
179
  <Button component={Link} to="/runs" variant="default" w="fit-content" mt="sm">Back to test runs</Button>
180
  </div></div>
181
  );
 
175
  if (run.error || !r) {
176
  return (
177
  <div className="fpt-ws-scroll"><div className="trio-stages">
178
+ <ErrorAlert error={run.error ?? new Error('This test run could not be found. It may have been deleted, or the link is out of date.')} />
179
  <Button component={Link} to="/runs" variant="default" w="fit-content" mt="sm">Back to test runs</Button>
180
  </div></div>
181
  );
web/src/pages/run/SignOffReport.tsx CHANGED
@@ -11,7 +11,7 @@ import { coworkerForNode } from '../../domain/coworkers';
11
  import './report.css';
12
  import { shortWhen } from '../../domain/runName';
13
  import { scriptUrl } from './RunGuide';
14
- import { DECISION_WORDS, RUN_STATUS_WORDS } from '../../domain/glossary';
15
  import type { Criterion } from '../../api/types';
16
 
17
  const CHECK_NAMES: Record<string, string> = { C1: 'Coverage', C2: 'Critical and High scenarios', C3: 'Stability', C4: 'False failures', C5: 'Independent recount', C6: 'Honest labelling' };
@@ -29,7 +29,7 @@ export function decisionSentence(d: string, crit: Record<string, Criterion>, tar
29
  const failed = Object.entries(crit).filter(([, c]) => !c.ok);
30
  return d === 'GO' ? `${DECISION_WORDS[d]}: every required check passed${target?.startsWith('Oracle Fusion') ? ' on the Oracle Fusion pod' : ' on the mock app'}.`
31
  : d === 'HELD' ? `${DECISION_WORDS[d]}: the scenarios of this area are on hold, so no decision is made.`
32
- : `${DECISION_WORDS[d] ?? d}: ${failed.length} required check(s) not met: ${failed.map(([k]) => CRITERIA_WORDS[k] ?? k).join('; ')}.`;
33
  }
34
 
35
  const STOPPED = ['failed', 'killed', 'cancelled', 'interrupted'];
@@ -83,7 +83,7 @@ export function SignOffReport({ id }: { id: string }) {
83
  <Title order={2} className="rpt-h2">This run did not finish, so there is no report</Title>
84
  <Text size="sm" c="dimmed" mt={4}>
85
  {r.status === 'cancelled' ? 'It was cancelled' : r.status === 'killed' ? 'It was stopped by the emergency stop' : r.status === 'interrupted' ? 'It was paused before the end' : 'It stopped with an error'}
86
- {r.error ? `: ${r.error}` : '.'} Start a new test run to get a report{r.status === 'interrupted' || r.status === 'failed' ? ', or carry on from where it stopped on the test run page' : ''}.
87
  </Text>
88
  <Anchor component={Link} to={`/runs/${id}`} size="sm">Back to the test run</Anchor>
89
  </div>
@@ -177,10 +177,10 @@ export function SignOffReport({ id }: { id: string }) {
177
  columns={['Process step', 'Scenarios', 'Passed', 'Failed', 'Not run', ...(patchCol ? ['In patch'] : [])]}>
178
  {mods.flatMap((m) => m.steps.filter((s) => s.scenarios > 0 || s.state === 'gap').map((s) => (
179
  <Table.Tr key={`${m.module}-${s.key}`}>
180
- <Table.Td>{mods.length > 1 ? `${m.module}: ` : ''}{s.name}</Table.Td>
181
  <Table.Td className="pw-num">{s.state === 'gap' && s.scenarios === 0 ? <span className="fpt-nocov">No scenario</span> : s.scenarios}</Table.Td>
182
  <Table.Td className="pw-num">{s.passed + s.flaky}</Table.Td><Table.Td className="pw-num">{s.failed}</Table.Td><Table.Td className="pw-num">{s.not_run}</Table.Td>
183
- {patchCol && <Table.Td>{s.touched ? 'yes' : 'no'}</Table.Td>}
184
  </Table.Tr>
185
  )))}
186
  </DataTable>
@@ -201,7 +201,7 @@ export function SignOffReport({ id }: { id: string }) {
201
  {gapSteps.length > 0 && <Text size="sm">Process steps with no scenario: {gapSteps.join(', ')}.</Text>}
202
  {gapChanges.length > 0 && <Text size="sm">Changes in this patch that no scenario tests yet ({gapChanges.length}): {gapChanges.slice(0, 8).join(', ')}{gapChanges.length > 8 ? ', …' : ''}. <Anchor component={Link} to={`/runs/${id}/changes`}>See what this patch changes</Anchor></Text>}
203
  {gapSteps.length === 0 && gapChanges.length === 0 && <Text size="sm" c="dimmed">No open coverage gaps for the steps in this test run.</Text>}
204
- {allGaps > 0 && <Text size="xs" c="dimmed">The full list of {allGaps} open point(s) is under Audit details below.</Text>}
205
  </Stack>
206
  </section>
207
  </div>
@@ -252,12 +252,12 @@ export function SignOffReport({ id }: { id: string }) {
252
  {Object.entries(rep.data?.criteria ?? {}).map(([m, crit]) => (
253
  <Table key={m} aria-label="criteria" fz="xs" mb="sm" className="pw-table">
254
  <Table.Thead><Table.Tr><Table.Th>{m} check</Table.Th><Table.Th>Met</Table.Th><Table.Th>Detail</Table.Th></Table.Tr></Table.Thead>
255
- <Table.Tbody>{Object.entries(crit).map(([k, c]) => <Table.Tr key={k}><Table.Td>{k} {CHECK_NAMES[k] ?? ''}</Table.Td><Table.Td><span className="pw-status" data-tone={c.ok ? 'green' : 'red'}>{c.ok ? 'met' : 'NOT met'}</span></Table.Td><Table.Td>{c.detail}</Table.Td></Table.Tr>)}</Table.Tbody>
256
  </Table>
257
  ))}
258
  {allGaps > 0 && (
259
  <details className="rpt-details">
260
- <summary>All {allGaps} open point(s) listed by the report</summary>
261
  <Stack gap={2} mt={6}>{Object.entries(rep.data?.gaps ?? {}).flatMap(([m, gs]) => gs.map((g, i) => <Text key={`${m}${i}`} size="xs">• {g}</Text>))}</Stack>
262
  </details>
263
  )}
 
11
  import './report.css';
12
  import { shortWhen } from '../../domain/runName';
13
  import { scriptUrl } from './RunGuide';
14
+ import { DECISION_WORDS, plainReason, RUN_STATUS_WORDS } from '../../domain/glossary';
15
  import type { Criterion } from '../../api/types';
16
 
17
  const CHECK_NAMES: Record<string, string> = { C1: 'Coverage', C2: 'Critical and High scenarios', C3: 'Stability', C4: 'False failures', C5: 'Independent recount', C6: 'Honest labelling' };
 
29
  const failed = Object.entries(crit).filter(([, c]) => !c.ok);
30
  return d === 'GO' ? `${DECISION_WORDS[d]}: every required check passed${target?.startsWith('Oracle Fusion') ? ' on the Oracle Fusion pod' : ' on the mock app'}.`
31
  : d === 'HELD' ? `${DECISION_WORDS[d]}: the scenarios of this area are on hold, so no decision is made.`
32
+ : `${DECISION_WORDS[d] ?? d}: ${failed.length} required ${failed.length === 1 ? 'check' : 'checks'} not met: ${failed.map(([k]) => CRITERIA_WORDS[k] ?? k).join('; ')}.`;
33
  }
34
 
35
  const STOPPED = ['failed', 'killed', 'cancelled', 'interrupted'];
 
83
  <Title order={2} className="rpt-h2">This run did not finish, so there is no report</Title>
84
  <Text size="sm" c="dimmed" mt={4}>
85
  {r.status === 'cancelled' ? 'It was cancelled' : r.status === 'killed' ? 'It was stopped by the emergency stop' : r.status === 'interrupted' ? 'It was paused before the end' : 'It stopped with an error'}
86
+ {plainReason(r.error) ? `: ${plainReason(r.error).replace(/[.!?]$/, '')}.` : '.'} Start a new test run to get a report{r.status === 'interrupted' || r.status === 'failed' ? ', or carry on from where it stopped on the test run page' : ''}.
87
  </Text>
88
  <Anchor component={Link} to={`/runs/${id}`} size="sm">Back to the test run</Anchor>
89
  </div>
 
177
  columns={['Process step', 'Scenarios', 'Passed', 'Failed', 'Not run', ...(patchCol ? ['In patch'] : [])]}>
178
  {mods.flatMap((m) => m.steps.filter((s) => s.scenarios > 0 || s.state === 'gap').map((s) => (
179
  <Table.Tr key={`${m.module}-${s.key}`}>
180
+ <Table.Td>{mods.length > 1 ? `${MODULE_NAMES[m.module] ?? m.module}: ` : ''}{s.name}</Table.Td>
181
  <Table.Td className="pw-num">{s.state === 'gap' && s.scenarios === 0 ? <span className="fpt-nocov">No scenario</span> : s.scenarios}</Table.Td>
182
  <Table.Td className="pw-num">{s.passed + s.flaky}</Table.Td><Table.Td className="pw-num">{s.failed}</Table.Td><Table.Td className="pw-num">{s.not_run}</Table.Td>
183
+ {patchCol && <Table.Td>{s.touched ? 'Yes' : 'No'}</Table.Td>}
184
  </Table.Tr>
185
  )))}
186
  </DataTable>
 
201
  {gapSteps.length > 0 && <Text size="sm">Process steps with no scenario: {gapSteps.join(', ')}.</Text>}
202
  {gapChanges.length > 0 && <Text size="sm">Changes in this patch that no scenario tests yet ({gapChanges.length}): {gapChanges.slice(0, 8).join(', ')}{gapChanges.length > 8 ? ', …' : ''}. <Anchor component={Link} to={`/runs/${id}/changes`}>See what this patch changes</Anchor></Text>}
203
  {gapSteps.length === 0 && gapChanges.length === 0 && <Text size="sm" c="dimmed">No open coverage gaps for the steps in this test run.</Text>}
204
+ {allGaps > 0 && <Text size="xs" c="dimmed">The full list of {allGaps} open {allGaps === 1 ? 'point' : 'points'} is under Audit details below.</Text>}
205
  </Stack>
206
  </section>
207
  </div>
 
252
  {Object.entries(rep.data?.criteria ?? {}).map(([m, crit]) => (
253
  <Table key={m} aria-label="criteria" fz="xs" mb="sm" className="pw-table">
254
  <Table.Thead><Table.Tr><Table.Th>{m} check</Table.Th><Table.Th>Met</Table.Th><Table.Th>Detail</Table.Th></Table.Tr></Table.Thead>
255
+ <Table.Tbody>{Object.entries(crit).map(([k, c]) => <Table.Tr key={k}><Table.Td>{k} {CHECK_NAMES[k] ?? ''}</Table.Td><Table.Td><span className="pw-status" data-tone={c.ok ? 'green' : 'red'}>{c.ok ? 'Met' : 'Not met'}</span></Table.Td><Table.Td>{c.detail}</Table.Td></Table.Tr>)}</Table.Tbody>
256
  </Table>
257
  ))}
258
  {allGaps > 0 && (
259
  <details className="rpt-details">
260
+ <summary>All {allGaps} open {allGaps === 1 ? 'point' : 'points'} listed by the report</summary>
261
  <Stack gap={2} mt={6}>{Object.entries(rep.data?.gaps ?? {}).flatMap(([m, gs]) => gs.map((g, i) => <Text key={`${m}${i}`} size="xs">• {g}</Text>))}</Stack>
262
  </details>
263
  )}