diff --git a/automation/remote_runner/server.py b/automation/remote_runner/server.py index f09bbfc167c3f5f59404565d900db0df5f4803da..6f3f4d87ad080d7b3dc674206aace8dc484ab64f 100644 --- a/automation/remote_runner/server.py +++ b/automation/remote_runner/server.py @@ -5,12 +5,17 @@ The Patchwise server posts an attempt (case ids, config, the run's environment, polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), the run directory (screenshots, videos, traces), the pod values tried and the ledger of created test records. +An attempt that reaches its own deadline is first asked to stop (SIGINT: Playwright ends the tests that run and still +writes its report), and only killed after RUNNER_GRACE_S. Each job's metadata is kept in its folder (job.json), so after a +runner restart a finished job still answers its status and bundle, and a job that was running is reported "lost" (the +Patchwise server then fails it at once instead of waiting for its deadline). + Security: every call needs `Authorization: Bearer ` (compared in constant time). Only known environment keys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password exists only in the Playwright process's environment, never on disk. Put it behind HTTPS (deploy/remote-runner/Caddyfile). Environment: RUNNER_TOKEN (required), RUNNER_PORT (default 8899), RUNNER_HOME (default ~/runner-data), -AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24).""" +AUTOMATION_DIR (default: ../ of this file), RUNNER_KEEP_HOURS (default 24), RUNNER_GRACE_S (default 90).""" from __future__ import annotations import base64 @@ -34,6 +39,7 @@ PORT = int(os.environ.get("RUNNER_PORT", "8899")) HOME = Path(os.environ.get("RUNNER_HOME", str(Path.home() / "runner-data"))) AUTOMATION = Path(os.environ.get("AUTOMATION_DIR", str(Path(__file__).resolve().parents[1]))) KEEP_S = float(os.environ.get("RUNNER_KEEP_HOURS", "24")) * 3600 +GRACE_S = float(os.environ.get("RUNNER_GRACE_S", "90")) # an attempt past its deadline gets this long to write its report # the scenario files the repo's own step specs read (../tests/cases), and the commit deploy/runner/sync.sh installed CASES = AUTOMATION.parent / "tests" / "cases" VERSION_FILE = AUTOMATION.parent / "VERSION" @@ -47,6 +53,40 @@ MAX_BODY = 20_000_000 GROUP = {"start_new_session": True} if os.name == "posix" else {"creationflags": subprocess.CREATE_NEW_PROCESS_GROUP} LOCK = threading.Lock() # one attempt at a time: the runner is sized for one browser JOBS: dict[str, dict] = {} +META = ("id", "kind", "state", "started", "deadline", "pw_run_id", "exit_code", "timed_out", "error") +ENDED = ("done", "cancelled", "failed") + + +def save_meta(job: dict) -> None: + """The job's metadata (never its environment) in its folder, written whole, so a restarted runner can answer for it.""" + try: + tmp = job["dir"] / ".job.json.tmp" + tmp.write_text(json.dumps({k: job.get(k) for k in META}), encoding="utf-8") + tmp.replace(job["dir"] / "job.json") + except OSError: + pass + + +def load_jobs() -> None: + """After a restart: jobs kept on disk answer again. A finished one as it ended; one that was running is "lost" (its + processes died with the old runner), and what it left (its ledger of test records, its run folder) still ships.""" + for d in sorted(HOME.glob("job_*")): + try: + meta = json.loads((d / "job.json").read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + jid = str(meta.get("id") or "") + if jid != d.name or jid in JOBS or not re.fullmatch(r"job_[0-9a-f]{12}", jid): + continue + job = {**{k: meta.get(k) for k in META}, "dir": d, "started": float(meta.get("started") or d.stat().st_mtime)} + if job["state"] not in ENDED: + job["state"] = "lost" + try: + _collect(job) + except OSError: + pass # what could not be moved stays where it is; the job still answers + save_meta(job) + JOBS[jid] = job def grep_for(ids: list[str]) -> str: @@ -144,9 +184,10 @@ def start(body: dict) -> dict: "--retries=0", "--reporter=json", "--grep", grep_for(ids)] log = open(jd / "playwright.log", "wb") p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP) - job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(), + job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": pw_run_id, "started": time.time(), "kind": "attempt", "deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None} JOBS[jid] = job + save_meta(job) threading.Thread(target=_watch, args=(job,), daemon=True).start() return {"id": jid, "state": "running"} except BaseException: @@ -192,6 +233,7 @@ def start_screens(body: dict) -> dict: job = {"id": jid, "dir": jd, "proc": p, "log": log, "pw_run_id": jid, "started": time.time(), "kind": kind, "deadline": time.time() + min(float(body.get("timeout_s") or 5400), 4 * 3600), "state": "running", "exit_code": None} JOBS[jid] = job + save_meta(job) threading.Thread(target=_watch, args=(job,), daemon=True).start() return {"id": jid, "state": "running"} except BaseException: @@ -241,24 +283,54 @@ def _kill_tree(p: subprocess.Popen) -> None: pass +def _interrupt(p: subprocess.Popen) -> bool: + """Ask Playwright to stop as Ctrl+C does: it ends the running tests, marks the rest as not run and still writes its + JSON report. False where that cannot be asked (Windows: the attempt is killed at once).""" + if os.name != "posix": + return False + try: + os.kill(p.pid, signal.SIGINT) + return True + except OSError: + return False + + +def _collect(job: dict) -> None: + """What the attempt left becomes the job's: the report (attachment paths made relative) and the run folder.""" + run_dir = AUTOMATION / "results" / "runs" / str(job.get("pw_run_id") or "") + report = job["dir"] / "report.json" + if report.exists(): + try: + _relativize(report, run_dir) + except (OSError, ValueError): + pass # a report cut off mid-write still ships as it is + if job.get("pw_run_id") and run_dir.is_dir() and not (job["dir"] / "run").exists(): + shutil.move(str(run_dir), str(job["dir"] / "run")) # the evidence moves into the job (the automation folder never piles up) + + def _watch(job: dict) -> None: p = job["proc"] try: + stop_at = None while p.poll() is None: - if time.time() > job["deadline"] or job.get("cancel"): - job["timed_out"] = not job.get("cancel") + if job.get("cancel"): _kill_tree(p) + elif time.time() > job["deadline"]: + if stop_at is None: # its own time is up: stopped gently first, so its report is not lost + job["timed_out"] = True + stop_at = time.time() + (GRACE_S if _interrupt(p) else 0) + if time.time() >= stop_at: + _kill_tree(p) time.sleep(2) job["exit_code"] = p.returncode job["log"].close() - run_dir = AUTOMATION / "results" / "runs" / job["pw_run_id"] - report = job["dir"] / "report.json" - if report.exists(): - _relativize(report, run_dir) - if run_dir.exists(): # the run's evidence moves into the job (so the automation folder never piles up) - shutil.move(str(run_dir), str(job["dir"] / "run")) + _collect(job) job["state"] = "cancelled" if job.get("cancel") else "done" + except Exception as e: # noqa: BLE001 - the job ends as failed, never stays "running" once the lock is released + job["state"], job["error"] = "failed", f"{type(e).__name__}: {e}"[:300] + _kill_tree(p) finally: + save_meta(job) LOCK.release() @@ -343,8 +415,9 @@ class H(BaseHTTPRequestHandler): if job["state"] == "running": return self._send(409, {"error": "the attempt is still running"}) return self._send(200, raw=bundle(job), ctype="application/zip") - st = {"id": job["id"], "state": job["state"], "exit_code": job["exit_code"], "timed_out": bool(job.get("timed_out")), - "progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists()} + st = {"id": job["id"], "state": job["state"], "exit_code": job.get("exit_code"), "timed_out": bool(job.get("timed_out")), + "progress": _progress(job["dir"] / "playwright.log"), "report": (job["dir"] / "report.json").exists(), + "started": job.get("started"), "pw_run_id": job.get("pw_run_id")} if m.group(3) is not None: # a screen read follows its log lines ("[explore] ...") for its progress st["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3))) self._send(200, st) @@ -367,8 +440,9 @@ class H(BaseHTTPRequestHandler): if m: job = self._job(m.group(1)) if job: - job["cancel"] = True - self._send(202, {"id": job["id"], "state": "cancelling"}) + if job["state"] == "running": + job["cancel"] = True + self._send(202, {"id": job["id"], "state": "cancelling" if job["state"] == "running" else job["state"]}) return self._send(404, {"error": "not found"}) @@ -377,6 +451,7 @@ if __name__ == "__main__": if not TOKEN or len(TOKEN) < 24: raise SystemExit("set RUNNER_TOKEN (at least 24 characters)") HOME.mkdir(parents=True, exist_ok=True) + load_jobs() threading.Thread(target=sweep, daemon=True).start() print(f"Patchwise remote runner on 127.0.0.1:{PORT}, automation {AUTOMATION}", flush=True) ThreadingHTTPServer(("127.0.0.1", PORT), H).serve_forever() diff --git a/automation/src/fusion/rest.ts b/automation/src/fusion/rest.ts index d7d1d3e07880fefc3c0a05c368f6887870b91433..db8776a59b29b8f3ca63c8b82fe55a1863653215 100644 --- a/automation/src/fusion/rest.ts +++ b/automation/src/fusion/rest.ts @@ -56,6 +56,11 @@ export class FusionRest { return (await this.invoices(number, supplier))[0] || null; } + /** The invoice with this number, whatever its supplier (test numbers are unique per run). */ + async invoiceByNumber(number: string): Promise { + return (await this.get('invoices', `InvoiceNumber='${q(number)}'`))[0] || null; + } + holds(number: string): Promise { return this.get('invoiceHolds', `InvoiceNumber='${q(number)}'`); } diff --git a/automation/src/fusion/ui.ts b/automation/src/fusion/ui.ts index deb304152f496034d32b2e92a4708bdf352f0a59..7d8e863929615355659ca02959ddcd202cce79d2 100644 --- a/automation/src/fusion/ui.ts +++ b/automation/src/fusion/ui.ts @@ -228,12 +228,18 @@ export class FusionUi { /** The task is open: the page title names it ("Create Invoice - Oracle Fusion ...", "Invoice Workbench - Create * Recurring Invoices - ..."), or a dialog named after it is showing (Create Order opens a dialog over the work area, - * and the page title stays the work area's). */ + * and the page title stays the work area's), or a page heading names it (26D opens some tasks in place), or a + * Create task's document opened for editing ("Create Noncatalog Request" -> "Noncatalog Request - Edit"). */ async expectTitle(task: string) { const title = new RegExp(`(^|[-–:|]\\s*)${esc(task)}\\b`, 'i'); const dialog = this.page.getByRole('dialog').filter({ hasText: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true }); - await expect.poll(async () => title.test(await this.page.title()) || (await dialog.count()) > 0, - { message: `"${task}" should open (its page or its dialog)`, timeout: 60_000 }).toBe(true); + const heading = this.page.getByRole('heading', { name: new RegExp(`^\\s*${esc(task)}\\b`, 'i') }).filter({ visible: true }); + const noun = /^create\s+(.+)$/i.exec(task.trim())?.[1]; + const editing = noun ? new RegExp(`(^|[-–:|]\\s*)${esc(noun)}\\s*[-–:]\\s*(Edit|Create)\\b`, 'i') : null; + await expect.poll(async () => { + const t = await this.page.title(); + return title.test(t) || (editing?.test(t) ?? false) || (await dialog.count()) > 0 || (await heading.count()) > 0; + }, { message: `"${task}" should open (its page, its dialog or its heading)`, timeout: 60_000 }).toBe(true); } /** The Tasks list of a work area: the panel region whose id ends "_FndTasksList" (its tab: "..._FndTasksList::disAcr"). @@ -481,10 +487,13 @@ export class FusionUi { } /** One row of the invoice Lines table. Up to 26C Fusion names each row "Select Row ..."; from 26D each line - * is a nested table in table "Invoice Lines" whose first cell is the line number. */ + * is a nested table in table "Invoice Lines" whose first cell is the line number. Only the innermost rows count (a + * row holding no table of its own), so the outer row that wraps a line's table is never taken for it. (Matching the + * number in the first cell only, by CSS position, found no row at all on the 26D page: the cell name match stays.) */ lineRow(n: number): Locator { const named = this.page.getByRole('row', { name: new RegExp(`^Select Row ${n} ${n} `) }); const nested = this.page.getByRole('table', { name: 'Invoice Lines' }).getByRole('row') + .filter({ hasNot: this.page.getByRole('table') }) // data tables only: ADF lays inputs out in presentation tables .filter({ has: this.page.getByRole('cell', { name: String(n), exact: true }) }); return named.or(nested).first(); } @@ -513,17 +522,28 @@ export class FusionUi { * the account is then cleared and the pod's next candidate tried, and the one Fusion takes is remembered. */ private async putLineAccount(account: Locator, first: string) { const tried: string[] = []; - for (const v of [first, ...podCandidates('AP', 'account')].filter((x, i, all) => x && all.indexOf(x) === i).slice(0, 6)) { + let pod: string[] = []; + try { pod = podCandidates('AP', 'account'); } catch { /* the step's own account only: a pod without account data */ } + // an account Fusion took may come back reformatted (separators, spaces): compared without them + const bare = (s: string) => s.replace(/[\s.\-_]/g, '').toUpperCase(); + const segments = this.page.getByRole('dialog', { name: /Distribution Combination/ }).filter({ visible: true }); + const errorText = /You must enter a combination|is not a valid (account|combination)|combination .* (does not exist|is not valid)/i; + for (const v of [first, ...pod].filter((x, i, all) => x && all.indexOf(x) === i).slice(0, 6)) { + // errors already on the page (an earlier line, an earlier candidate) are not this candidate's + const before = await this.page.getByText(errorText).filter({ visible: true }).count(); await account.click(); await account.fill(v); await account.press('Tab'); await this.settle(2500); - const segments = this.page.getByRole('dialog', { name: /Distribution Combination/ }).filter({ visible: true }); - const error = this.page.getByText(/You must enter a combination|is not a valid (account|combination)|combination .* (does not exist|is not valid)/i) - .filter({ visible: true }); - const refused = (await segments.count()) > 0 || (await error.count()) > 0 - || (await account.inputValue().catch(() => '')).trim() !== v.trim(); + const message = this.page.getByRole('dialog').filter({ hasText: errorText }).filter({ visible: true }); + let refused = (await segments.count()) > 0 || (await message.count()) > 0 + || (await this.page.getByText(errorText).filter({ visible: true }).count()) > before; + if (!refused) { // Fusion may redraw the value a moment later: read it until it settles + refused = !(await expect.poll(async () => bare(await account.inputValue().catch(() => '')), { timeout: 5_000 }) + .toBe(bare(v)).then(() => true, () => false)); + } if (!refused) { used('AP', 'account', v, true); return; } used('AP', 'account', v, false); tried.push(v); if (await segments.count()) await segments.getByRole('button', { name: 'Cancel', exact: true }).first().click().catch(() => this.page.keyboard.press('Escape')); + if (await message.count()) await message.getByRole('button', { name: /^(OK|Close)$/ }).first().click().catch(() => this.page.keyboard.press('Escape')); await this.settle(1000); await account.fill(''); await account.press('Tab'); await this.settle(1000); } @@ -815,10 +835,21 @@ export class FusionUi { { message: `the page should show the status ${status}` }).toBeVisible({ timeout: 60_000 }); } - /** The invoice status Fusion shows beside the page title (Not validated, Validated, Needs revalidation, Canceled). */ + /** The invoice status Fusion shows beside the page title (Not validated, Validated, Needs revalidation, Canceled). + * A page that shows no status link (a layout without it) is answered by Fusion itself: the status of the invoice + * whose number the page holds, read over REST, so a moved status link never fails a test that worked. */ async statusOnPage(): Promise { const link = this.page.getByRole('link', { name: new RegExp(`^(${INVOICE_STATUSES.join('|')})$`) }).first(); - return (await link.innerText({ timeout: 5_000 }).catch(() => '')).trim(); + const shown = (await link.innerText({ timeout: 5_000 }).catch(() => '')).trim(); + if (shown) return shown; + const number = await this.field('Number').inputValue({ timeout: 2_000 }).catch(() => ''); + if (!number.trim()) return ''; + const { FusionRest } = await import('./rest'); + const inv = await new FusionRest().invoiceByNumber(number.trim()).catch(() => null); + if (!inv) return ''; + if (inv.CanceledFlag) return 'Canceled'; + const rest = String(inv.ValidationStatus || '').trim().toLowerCase(); // in the page's own spelling + return INVOICE_STATUSES.find((s) => s.toLowerCase() === rest) ?? String(inv.ValidationStatus || ''); } async expectStatus(status: (typeof INVOICE_STATUSES)[number]) { diff --git a/coworker/adapters/playwright.py b/coworker/adapters/playwright.py index 55433dc39c3d65e43bd5553cf753e498346029b6..f457ae4efd4e1fb103e6805e0601148f52373c5c 100644 --- a/coworker/adapters/playwright.py +++ b/coworker/adapters/playwright.py @@ -209,31 +209,101 @@ def merge_chunk_reports(files: list[Path], out_file: Path) -> Path: return out_file +NO_RESULT = "_no_result" # a scenario entry written for a pass that ran out of time before it reported (its case id) + + +def timed_out_report(ids: list[str], out_file: Path, why: str) -> Path: + """The report of a pass that ran out of time and wrote none: each of its scenarios is recorded as timed out with the + reason, so it is counted, shown and retried like any failure instead of vanishing from the run.""" + specs = [{"title": cid, "file": "", NO_RESULT: cid, "tags": [f"@{cid}"], "ok": False, + "tests": [{"status": "unexpected", "results": [{"status": "timedOut", "duration": 0, "errors": [{"message": why}], + "attachments": []}]}]} for cid in ids] + out_file.write_text(json.dumps({"config": {"projects": []}, "suites": [{"title": "no result", "file": "", "specs": specs}], + "errors": [], "stats": {}}, indent=1), encoding="utf-8") + return out_file + + def run_attempt_chunked(*, ids: list[str], out_file: Path, chunk_size: int, done: dict | None = None, - done_dirs: dict | None = None, on_chunk=None, **kw) -> dict: + done_dirs: dict | None = None, on_chunk=None, run=None, tag: str = "", lost_ok: bool = False, + single_as_attempt: bool = False, **kw) -> dict: """Resumable attempt: cases run in chunks of chunk_size, each with its own JSON report and Playwright run dir. `done` / `done_dirs` map chunk index -> report file / run dir from a previous (crashed) try of the same attempt; those chunks are skipped but their reports AND run dirs are still returned (so their evidence is ingested). - on_chunk(k, file, n_chunks, run_dir) is called after each chunk (the Temporal activity heartbeats it).""" + on_chunk(k, file, n_chunks, run_dir) is called after each chunk (the Temporal activity heartbeats it). + `run` runs one chunk (default run_attempt; the LangGraph path passes one that may use the remote runner) and `tag` + prefixes the chunk tags. lost_ok: a chunk that runs out of time with no report is recorded as timed out + (timed_out_report) and the next chunk runs, unless no chunk of the attempt produced a report. single_as_attempt: an + attempt that fits in one chunk keeps the attempt's own report file and tag, as an unchunked run would.""" + from ..platform.failures import ExecutionError chunks = [ids[i:i + chunk_size] for i in range(0, len(ids), max(1, chunk_size))] or [[]] done = {int(k): v for k, v in (done or {}).items() if Path(v).exists()} dirs = {int(k): v for k, v in (done_dirs or {}).items() if v} - skipped = [] + files = dict(done) + skipped, lost, code, timed_out, last_err = [], [], 0, False, None + whole = single_as_attempt and len(chunks) == 1 for k, chunk in enumerate(chunks): - cf = out_file.with_name(f"{out_file.stem}.c{k}.json") + cf = out_file if whole else out_file.with_name(f"{out_file.stem}.c{k}.json") if k in done: skipped.append(k) continue - res = run_attempt(ids=chunk, out_file=cf, tag=f"-c{k}", live_meta={"all_ids": ids, "chunk": k, "chunks": len(chunks)}, **kw) + try: + res = (run or run_attempt)(ids=chunk, out_file=cf, tag=tag if whole else f"{tag}-c{k}", + live_meta={"all_ids": ids, "chunk": k, "chunks": len(chunks)}, **kw) or {} + except ExecutionError as e: + if not (lost_ok and e.timed_out and len(chunks) > 1): + raise + log_.warning("chunk %s of %s ran out of time with no report: its %s scenario(s) are recorded as timed out", + k + 1, len(chunks), len(chunk)) + files[k] = str(timed_out_report(chunk, cf, f"{e} This pass ({len(chunk)} scenarios) stopped before it reported, " + "so they have no result of their own; the retry runs them again.")) + lost.append(k) + last_err, timed_out = e, True + continue if res.get("run_dir"): dirs[k] = res["run_dir"] - done[k] = str(cf) + done[k] = files[k] = str(cf) + code, timed_out = code or res.get("exit_code") or 0, timed_out or bool(res.get("timed_out")) if on_chunk: on_chunk(k, str(cf), len(chunks), res.get("run_dir")) - merge_chunk_reports([Path(done[k]) for k in range(len(chunks))], out_file) + if last_err is not None and len(lost) == len(chunks): # nothing at all was learned: the attempt fails as one would + raise last_err + merge_chunk_reports([Path(files[k]) for k in range(len(chunks))], out_file) run_dirs = [dirs[k] for k in range(len(chunks)) if dirs.get(k)] return {"file": str(out_file), "run_dirs": run_dirs, "run_dir": run_dirs[-1] if run_dirs else None, - "chunks": len(chunks), "skipped_chunks": skipped, "mode": kw.get("mode")} + "chunks": len(chunks), "skipped_chunks": skipped, "lost_chunks": lost, "exit_code": code, "timed_out": timed_out, + "mode": kw.get("mode")} + + +def adopt_no_result(files: list) -> None: + """A scenario recorded as timed out (timed_out_report) has no spec file or title of its own, so the retry's result + could not be matched to it when attempts are merged: it takes them from the later attempt that ran it.""" + first = Path(files[0]) + try: + data = json.loads(first.read_text(encoding="utf-8")) + except (OSError, ValueError): + return + holes = [sp for sp in _walk_specs(data.get("suites")) if sp.get(NO_RESULT)] + if not holes: + return + real: dict[str, dict] = {} + for f in files[1:]: + try: + later = json.loads(Path(f).read_text(encoding="utf-8")) + except (OSError, ValueError): + continue + for sp in _walk_specs(later.get("suites")): + if not sp.get(NO_RESULT): + for t in sp.get("tags") or []: + real.setdefault(str(t).lstrip("@"), sp) + changed = False + for sp in holes: + got = real.get(str(sp[NO_RESULT])) + if got: + sp.update({"file": got.get("file", ""), "title": got.get("title", sp["title"]), "tags": got.get("tags") or sp["tags"]}) + sp.pop(NO_RESULT, None) + changed = True + if changed: + first.write_text(json.dumps(data, indent=1), encoding="utf-8") def attachments_by_case(report_file: Path) -> dict[str, str]: diff --git a/coworker/adapters/remote_runner.py b/coworker/adapters/remote_runner.py index 6b0dc7835e824f42b5f9b97c176ca457408fec54..bf4abd775f7afc202e2ced10fe59503b1fbf47b0 100644 --- a/coworker/adapters/remote_runner.py +++ b/coworker/adapters/remote_runner.py @@ -5,12 +5,18 @@ remote_runner.token, or FPT_SECRET_REMOTE_RUNNER_TOKEN): this host may sit on a attempt goes out through the egress gate (https, the runner's host only; the audit log never sees the password), is polled, and its bundle is unpacked where a local attempt would leave its files: the JSON report at out_file (attachment paths made absolute here), the run directory under automation/results/runs, the pod values tried and the -ledger of created test records. Everything after that (evidence, triage, clean-up, reports) runs unchanged.""" +ledger of created test records. Everything after that (evidence, triage, clean-up, reports) runs unchanged. + +The runner drives one browser job at a time. A job that finds it busy (HTTP 409) waits for it, for a bounded time. The +id of the job an attempt follows is kept in the run folder (remote-job.json) until its results are in, so a server that +restarts mid-attempt and is resumed follows the same job again instead of starting a second one, and a runner that +restarted (it no longer knows the job, or reports it "lost") fails the attempt in seconds instead of at its deadline.""" from __future__ import annotations import base64 import io import json +import logging import re import time import zipfile @@ -18,8 +24,17 @@ from pathlib import Path from .playwright import AUTOMATION, testdata_used_file +log = logging.getLogger("fpt.remote_runner") + ENV_KEYS = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES", "FPT_FUSION_WORKERS", "FPT_BROWSER_SLOWMO_MS") +JOB_FILE = "remote-job.json" +JOB_ID = re.compile(r"job_[0-9a-f]{12}") +# a job's last states; "failed" (the runner's own error) and "lost" (it restarted mid-job) come from runners that keep +# their jobs across a restart, older ones only say done or cancelled +ENDED = ("done", "cancelled", "failed", "lost") +GONE_AFTER = 2 # consecutive 404s for a job: the runner restarted and no longer knows it +BUSY_WAIT_S = 900 # how long a job waits for a busy runner when the caller does not say (Settings has the knob) class RemoteRunnerError(RuntimeError): @@ -65,6 +80,13 @@ def _absolutize(report: Path, run_dir: Path) -> None: report.write_text(json.dumps(data), encoding="utf-8") +def _append(dest: Path, data: bytes) -> None: + """JSON lines from one more pass (or job) go after the earlier ones, each pass starting its own line.""" + dest.parent.mkdir(parents=True, exist_ok=True) + with dest.open("ab") as fh: + fh.write(data if not data or data.endswith(b"\n") else data + b"\n") + + def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: str, attempt: int | str) -> bool: with zipfile.ZipFile(io.BytesIO(blob)) as z: for info in z.infolist(): @@ -81,9 +103,8 @@ def _unpack(blob: bytes, out_file: Path, run_dir: Path, log_dir: Path, ledger: s if dest is None: continue dest.parent.mkdir(parents=True, exist_ok=True) - if name == "created.jsonl" and dest.exists(): # records made by an earlier pass stay listed for cleanup - with dest.open("ab") as fh: - fh.write(z.read(info)) + if name in ("created.jsonl", "testdata-used.jsonl"): # an earlier pass's records and values stay listed + _append(dest, z.read(info)) else: dest.write_bytes(z.read(info)) if out_file.exists(): @@ -107,42 +128,111 @@ def runner_for(svc) -> tuple[str, str] | None: SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA") +def _call(egress, base: str, hdr: dict, method: str, path: str, *, log_body=None, json_body=None, timeout: float = 30): + return egress.service_request("remote_runner", method, base + path, allowed_base=base, json_body=json_body, headers=hdr, + log_body=log_body, timeout=timeout) + + +def _cancel(egress, base: str, hdr: dict, jid: str) -> None: + """Ask the runner to stop a job (it frees the browser for the next one). Never raises: a runner that does not answer + stops the job at its own deadline.""" + try: + _call(egress, base, hdr, "POST", f"/v1/attempts/{jid}/cancel", log_body={"cancel": jid}) + except Exception as e: # noqa: BLE001 + log.warning("could not cancel runner job %s: %s", jid, type(e).__name__) + + +def _pause(seconds: float, kill=None) -> None: + """Sleep in short steps, so a cancelled run or the kill switch is noticed while it waits.""" + end = time.time() + seconds + while True: + if kill: + kill() + left = end - time.time() + if left <= 0: + return + time.sleep(min(5.0, left)) + + +def _start_job(egress, base: str, hdr: dict, path: str, body: dict, log_body: dict, *, what: str, busy_wait_s: float, + on_wait=None, kill=None) -> str: + """Start a job on the runner and return its id. The runner drives one browser at a time and answers 409 while another + job runs (another run, a screen read, or a job of this run from before a restart that is ending): that is waited for, + with growing pauses, for up to busy_wait_s, and only then refused. on_wait(message) hears once that it waits.""" + first, pause, told = time.time(), 10.0, False + while True: + r = _call(egress, base, hdr, "POST", path, json_body=body, log_body=log_body, timeout=60) + if r.status_code == 202: + if told: + log.info("the remote browser runner is free: the %s starts", what) + return r.json()["id"] + waited = time.time() - first + if r.status_code != 409: + raise RemoteRunnerError(f"the remote browser runner refused the {what} (HTTP {r.status_code}: {r.text[:200]})") + if waited >= busy_wait_s: + raise RemoteRunnerError(f"the remote browser runner stayed busy with another job for {max(1, round(waited / 60))} " + f"minutes, so the {what} could not start: try again when it is free") + if not told: + told = True + msg = (f"Waiting for the browser runner: it is busy with another job (the {what} waits up to " + f"{max(1, round(busy_wait_s / 60))} minutes).") + log.info(msg) + if on_wait: + on_wait(msg) + _pause(min(pause, max(1.0, busy_wait_s - waited)), kill) + pause = min(pause * 2, 60.0) + + +def _status(egress, base: str, hdr: dict, jid: str, query: str = "") -> tuple[int, dict]: + """(HTTP status, body) of one poll; (0, {}) when the poll itself was dropped (it is tried again).""" + try: + r = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}{query}") + except Exception: # noqa: BLE001 - a dropped poll is tried again; the job keeps running on the runner + return 0, {} + try: + return r.status_code, (r.json() if r.status_code == 200 else {}) + except ValueError: + return r.status_code, {} + + def run_screens_remote(egress, base_url: str, token: str, *, kind: str, env: dict, out_dir: Path, plan: dict | None = None, - task: str | None = None, timeout_s: int = 5400, on_line=None, poll_s: float = 5.0) -> tuple[int | None, list[str]]: + task: str | None = None, timeout_s: int = 5400, on_line=None, poll_s: float = 5.0, + busy_wait_s: float = BUSY_WAIT_S, on_wait=None) -> tuple[int | None, list[str]]: """Read the pod's screens on the runner ("explore" with a plan, "capture" of one task). The files it wrote (inventories - and list choices) land in out_dir; returns (exit code, the log's lines). on_line gets each new line as it comes.""" + and list choices) land in out_dir; returns (exit code, the log's lines). on_line gets each new line as it comes; + on_wait(message) hears that the read waits for a busy runner.""" base = base_url.rstrip("/") hdr = {"Authorization": f"Bearer {token}"} body = {"kind": kind, "env": {k: str(v) for k, v in (env or {}).items() if k in SCREEN_ENV and v}, "timeout_s": timeout_s, **({"plan": plan} if plan is not None else {}), **({"task": task} if task else {})} - r = egress.service_request("remote_runner", "POST", base + "/v1/screens", allowed_base=base, json_body=body, headers=hdr, - log_body={"kind": kind, "task": task, "areas": [a.get("code") for a in (plan or {}).get("areas") or [] if isinstance(a, dict)]}, - timeout=60) - if r.status_code != 202: - raise RemoteRunnerError(f"the remote browser runner refused the screen read (HTTP {r.status_code}: {r.text[:200]})") - jid = r.json()["id"] + jid = _start_job(egress, base, hdr, "/v1/screens", body, + {"kind": kind, "task": task, "areas": [a.get("code") for a in (plan or {}).get("areas") or [] if isinstance(a, dict)]}, + what="screen read", busy_wait_s=busy_wait_s, on_wait=on_wait) deadline = time.time() + timeout_s + 300 - seen, st = 0, {} + seen, gone, st = 0, 0, {} while True: time.sleep(poll_s) - try: - st = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}?since={seen}", allowed_base=base, headers=hdr, - log_body=None, timeout=30).json() - except Exception: # noqa: BLE001 - a dropped poll is tried again; the read keeps going on the runner - st = {} + code, st = _status(egress, base, hdr, jid, f"?since={seen}") + if code == 404: + gone += 1 + if gone >= GONE_AFTER: + raise RemoteRunnerError("the remote browser runner no longer knows this screen read: it restarted while it ran") + continue + if code: + gone = 0 new = st.get("lines") or [] seen += len(new) if on_line: for line in new: on_line(line) - if st.get("state") in ("done", "cancelled"): + if st.get("state") == "lost": + raise RemoteRunnerError("the remote browser runner restarted while it read the screens, so the read was lost") + if st.get("state") in ENDED: break if time.time() > deadline: - egress.service_request("remote_runner", "POST", f"{base}/v1/attempts/{jid}/cancel", allowed_base=base, headers=hdr, - log_body={"cancel": jid}, timeout=30) + _cancel(egress, base, hdr, jid) raise RemoteRunnerError(f"the remote browser runner did not finish reading the screens in {timeout_s // 60} minutes") - z = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/bundle", allowed_base=base, headers=hdr, - log_body=None, timeout=300) + z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300) if z.status_code != 200: raise RemoteRunnerError(f"the remote browser runner did not return the screens (HTTP {z.status_code})") out = Path(out_dir) @@ -187,69 +277,196 @@ def _pull_live(egress, base: str, hdr: dict, jid: str, live_dir: Path, seen: dic _write_atomic(live_dir, "failed.jpg", base64.b64decode(v["failed"])) +# ------------------------------------------------------------------ the job an attempt follows, kept in the run folder +def saved_job(run_dir: Path) -> dict | None: + """The runner job a run's attempt was following when this server last stopped, or None.""" + try: + job = json.loads((Path(run_dir) / JOB_FILE).read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + return job if isinstance(job, dict) and JOB_ID.fullmatch(str(job.get("job_id") or "")) else None + + +def _save_job(run_dir: Path, job: dict) -> None: + d = Path(run_dir) + d.mkdir(parents=True, exist_ok=True) + tmp = d / f".{JOB_FILE}.tmp" + tmp.write_text(json.dumps(job), encoding="utf-8") + tmp.replace(d / JOB_FILE) + + +def _drop_job(run_dir: Path, jid: str) -> None: + job = saved_job(run_dir) + if job and job["job_id"] == jid: + (Path(run_dir) / JOB_FILE).unlink(missing_ok=True) + + +def _salvage(egress, base: str, hdr: dict, jid: str, log_dir: Path, ledger: str, wait_s: float = 90.0) -> bool: + """Keep the ledger of test records a job made when its results are not used (it was stopped, overran, or belongs to + a pass nobody follows any more), so the run's clean-up still finds them. True when the runner answered. Never raises.""" + try: + end = time.time() + wait_s + while True: + code, st = _status(egress, base, hdr, jid) + if code == 404: + return True # nothing left to fetch + if code == 200 and st.get("state") != "running" or time.time() > end: + break + time.sleep(3) + z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300) + if z.status_code != 200: + return False + with zipfile.ZipFile(io.BytesIO(z.content)) as zf: + if "created.jsonl" in zf.namelist(): + _append(Path(log_dir) / ledger, zf.read("created.jsonl")) + return True + except Exception as e: # noqa: BLE001 - salvage is best effort + log.warning("could not fetch the records runner job %s made: %s", jid, type(e).__name__) + return False + + +def release_job(svc, run_id: str) -> bool: + """A run that will not follow its runner job any more (it was cancelled after a restart left the job running): stop + the job so the runner is free for the next run, and keep the records it made for the clean-up. Never raises.""" + from ..platform.cleanup import LEDGER + try: + run_dir = svc.run_dir(run_id) + job = saved_job(run_dir) + rt = runner_for(svc) if job else None + if not job or not rt: + return False + base, hdr = rt[0], {"Authorization": f"Bearer {rt[1]}"} + if job.get("base_url") == base: + _cancel(svc.egress, base, hdr, job["job_id"]) + _salvage(svc.egress, base, hdr, job["job_id"], run_dir, LEDGER) + _drop_job(run_dir, job["job_id"]) + return True + except Exception: # noqa: BLE001 + log.exception("could not release the runner job of run %s", run_id) + return False + + +def _follow(egress, base: str, hdr: dict, jid: str, deadline: float, *, kill, poll_s: float, live_dir: Path | None) -> dict | None: + """Poll a job until it ends: its last status, {"state": "overdue"} past the deadline, or None when the runner no + longer knows it (GONE_AFTER 404s in a row: it restarted and lost its jobs).""" + seen: dict = {} + gone = 0 + while True: + if kill: + kill() + time.sleep(poll_s) + code, st = _status(egress, base, hdr, jid) + if code == 404: + gone += 1 + if gone >= GONE_AFTER: + return None + continue + if code: + gone = 0 + if live_dir and st.get("state") == "running": + _pull_live(egress, base, hdr, jid, Path(live_dir), seen) + if st.get("state") in ENDED: + return st + if time.time() > deadline: + return {"state": "overdue"} + + +def _resumable(egress, base: str, hdr: dict, log_dir: Path, pw_run_id: str, out_file: Path, ledger: str) -> dict | None: + """The saved job of this very pass (same runner, same pass id and report file), to be followed again after a + restart. A saved job of another pass (the plan changed) is not: it is stopped so it frees the runner, its records kept.""" + job = saved_job(log_dir) + if not job: + return None + if job.get("base_url") == base and job.get("pw_run_id") == pw_run_id and job.get("out_file") == str(out_file): + return job + if job.get("base_url") == base: + _cancel(egress, base, hdr, job["job_id"]) + _salvage(egress, base, hdr, job["job_id"], log_dir, ledger) + _drop_job(log_dir, job["job_id"]) + return None + + def run_attempt_remote(egress, base_url: str, token: str, *, run_id: str, ids: list[str], attempt: int, out_file: Path, cred_env: dict | None, drafts_dir: Path | None, library_dir: Path | None, overrides_file: Path | None, log_dir: Path, config: str, timeout_s: int = 3600, kill=None, poll_s: float = 5.0, - live_dir: Path | None = None, live_meta: dict | None = None, tag: str = "") -> dict: - """One attempt on the remote runner. `tag` names a pass of the attempt (one per test user) so passes keep their own - run folder and log.""" + live_dir: Path | None = None, live_meta: dict | None = None, tag: str = "", + busy_wait_s: float = BUSY_WAIT_S, on_event=None) -> dict: + """One attempt on the remote runner. `tag` names a pass of the attempt (one per test user, one per chunk) so passes + keep their own run folder and log. While the job runs its id is kept in log_dir (the run folder): a resumed run whose + server restarted mid-pass follows the same job and gets its results; one the runner no longer knows starts again. + on_event(message) hears what a person watching the run should know (a wait for a busy runner, a re-attach).""" from ..platform.cleanup import LEDGER from ..platform.failures import ExecutionError base = base_url.rstrip("/") hdr = {"Authorization": f"Bearer {token}"} pw_run_id = f"fpt-{run_id}-a{attempt}{tag}" - env = {k: str(v) for k, v in (cred_env or {}).items() if k in ENV_KEYS} - if overrides_file and Path(overrides_file).exists(): - ov = json.loads(Path(overrides_file).read_text(encoding="utf-8") or "{}") - if ov: - env["PW_LOCATOR_OVERRIDES"] = json.dumps(ov) - body = {"ids": ids, "pw_run_id": pw_run_id, "config": config, "env": env, "timeout_s": timeout_s, - "drafts": _specs(drafts_dir), "library": _specs(library_dir)} - body["steps"] = _step_yamls(body["drafts"], body["library"]) + out_file, log_dir = Path(out_file), Path(log_dir) + note = on_event or (lambda _msg: None) + live = None if live_dir: # Live panel: the runner's browser hook writes frames there, this side copies them into the run from ..platform import liveview meta = {"attempt_key": f"{run_id}-a{attempt}", "attempt": attempt, "ids": ids, "all_ids": ids, "chunk": 0, "chunks": 1, **(live_meta or {})} liveview.prepare(Path(live_dir), meta) - body["live"] = {"attempt": meta["attempt_key"]} + live = {"attempt": meta["attempt_key"]} poll_s = min(poll_s, 2.0) - seen: dict = {} - r = egress.service_request("remote_runner", "POST", base + "/v1/attempts", allowed_base=base, json_body=body, headers=hdr, - log_body={"ids": ids, "config": config, "pw_run_id": pw_run_id, "specs": len(body["drafts"]) + len(body["library"]), - "steps": len(body["steps"])}, - timeout=60) - if r.status_code != 202: - raise RemoteRunnerError(f"the remote browser runner refused the attempt (HTTP {r.status_code}: {r.text[:200]})") - jid = r.json()["id"] - deadline = time.time() + timeout_s + 300 - st = {} + job = _resumable(egress, base, hdr, log_dir, pw_run_id, out_file, LEDGER) while True: + if job: + jid, started, budget = job["job_id"], float(job.get("started") or time.time()), int(job.get("timeout_s") or timeout_s) + log.info("run %s: following runner job %s again (%s)", run_id, jid, pw_run_id) + note("Following the browser runner's job for this pass again: it started before the server restarted.") + else: + env = {k: str(v) for k, v in (cred_env or {}).items() if k in ENV_KEYS} + if overrides_file and Path(overrides_file).exists(): + ov = json.loads(Path(overrides_file).read_text(encoding="utf-8") or "{}") + if ov: + env["PW_LOCATOR_OVERRIDES"] = json.dumps(ov) + body = {"ids": ids, "pw_run_id": pw_run_id, "config": config, "env": env, "timeout_s": timeout_s, + "drafts": _specs(drafts_dir), "library": _specs(library_dir), **({"live": live} if live else {})} + body["steps"] = _step_yamls(body["drafts"], body["library"]) + jid = _start_job(egress, base, hdr, "/v1/attempts", body, + {"ids": ids, "config": config, "pw_run_id": pw_run_id, "specs": len(body["drafts"]) + len(body["library"]), + "steps": len(body["steps"])}, what="attempt", busy_wait_s=busy_wait_s, on_wait=note, kill=kill) + started, budget = time.time(), timeout_s + _save_job(log_dir, {"job_id": jid, "base_url": base, "attempt": attempt, "tag": tag, "pw_run_id": pw_run_id, + "out_file": str(out_file), "started": started, "timeout_s": timeout_s}) try: - if kill: - kill() - except BaseException: - egress.service_request("remote_runner", "POST", f"{base}/v1/attempts/{jid}/cancel", allowed_base=base, headers=hdr, - log_body={"cancel": jid}, timeout=30) + st = _follow(egress, base, hdr, jid, started + budget + 300, kill=kill, poll_s=poll_s, live_dir=live_dir) + except BaseException: # cancelled or the kill switch: stop the job and keep the records it made; when the + _cancel(egress, base, hdr, jid) # runner cannot be reached, the saved id lets a resume or a cancel collect them + if _salvage(egress, base, hdr, jid, log_dir, LEDGER, wait_s=30): + _drop_job(log_dir, jid) raise - time.sleep(poll_s) - try: - st = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}", allowed_base=base, headers=hdr, - log_body=None, timeout=30).json() - except Exception: # noqa: BLE001 - a dropped poll is tried again; the attempt keeps running on the runner - st = {} - if live_dir and st.get("state") == "running": - _pull_live(egress, base, hdr, jid, Path(live_dir), seen) - if st.get("state") in ("done", "cancelled"): - break - if time.time() > deadline: - raise ExecutionError("The remote browser runner did not finish the attempt in time.", timed_out=True, minutes=timeout_s // 60) - z = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/bundle", allowed_base=base, headers=hdr, - log_body=None, timeout=300) - if z.status_code != 200: - raise RemoteRunnerError(f"the remote browser runner did not return the results (HTTP {z.status_code})") - run_dir = AUTOMATION / "results" / "runs" / pw_run_id - if not _unpack(z.content, Path(out_file), run_dir, Path(log_dir), LEDGER, f"{attempt}{tag}"): - raise ExecutionError(f"The remote browser run produced no report (exit {st.get('exit_code')}), so no scenario result was recorded.", - exit_code=st.get("exit_code"), timed_out=bool(st.get("timed_out")), minutes=max(1, timeout_s // 60)) - return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(run_dir), "exit_code": st.get("exit_code"), - "mode": "live", "timed_out": bool(st.get("timed_out")), "remote": True} + if st is None: + _drop_job(log_dir, jid) + if job: + note("The browser runner no longer knows the job from before the restart (it restarted too): starting the pass again.") + job = None + continue + raise RemoteRunnerError("the remote browser runner no longer knows this attempt: it restarted while the attempt ran, " + "so its results are lost") + if st.get("state") == "overdue": + _cancel(egress, base, hdr, jid) + _salvage(egress, base, hdr, jid, log_dir, LEDGER) + _drop_job(log_dir, jid) + raise ExecutionError("The remote browser runner did not finish the attempt in time.", timed_out=True, + minutes=max(1, budget // 60)) + z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300) + if z.status_code != 200: + _drop_job(log_dir, jid) + raise RemoteRunnerError(f"the remote browser runner did not return the results (HTTP {z.status_code})") + run_dir = AUTOMATION / "results" / "runs" / pw_run_id + got = _unpack(z.content, out_file, run_dir, log_dir, LEDGER, f"{attempt}{tag}") + _drop_job(log_dir, jid) + if not got and job and st.get("state") in ("lost", "cancelled"): # the old job died with no report: run it again + note("The browser runner's job from before the restart ended without results: starting the pass again.") + job = None + continue + if not got and st.get("state") == "lost": + raise RemoteRunnerError("the remote browser runner restarted while the attempt ran, so its results are lost") + if not got: + raise ExecutionError(f"The remote browser run produced no report (exit {st.get('exit_code')}), so no scenario result was recorded.", + exit_code=st.get("exit_code"), timed_out=bool(st.get("timed_out")), minutes=max(1, budget // 60)) + return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(run_dir), "exit_code": st.get("exit_code"), + "mode": "live", "timed_out": bool(st.get("timed_out")), "remote": True} diff --git a/coworker/adapters/screens.py b/coworker/adapters/screens.py index dddbde1d51cb93989a37b5d586523490a82c12e1..d9308380188ed2ff2736cb167b664b665de68c57 100644 --- a/coworker/adapters/screens.py +++ b/coworker/adapters/screens.py @@ -97,6 +97,15 @@ def _remote(svc): return runner_for(svc) +def _busy_wait_s(svc) -> float: + """How long a screen read waits for a busy remote runner (Settings.remote_runner_busy_wait_minutes).""" + from .remote_runner import BUSY_WAIT_S + try: + return 60.0 * float(svc.cfg.remote_runner_busy_wait_minutes) + except (AttributeError, TypeError, ValueError): + return BUSY_WAIT_S + + def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int = 1200, svc=None) -> dict: """Run the capture CLI against the pod in `env` (FUSION_BASE_URL/USERNAME/PASSWORD from PodRegistry.executor_env) and return the stored inventory. Nothing is saved on the pod; the credentials go to the child process only. With a @@ -113,7 +122,8 @@ def capture(task: str, env: dict, *, out_dir: Path | None = None, timeout_s: int if remote: from .remote_runner import RemoteRunnerError, run_screens_remote try: - rc, lines = run_screens_remote(svc.egress, *remote, kind="capture", env=env, out_dir=out, task=task, timeout_s=timeout_s) + rc, lines = run_screens_remote(svc.egress, *remote, kind="capture", env=env, out_dir=out, task=task, timeout_s=timeout_s, + busy_wait_s=_busy_wait_s(svc)) except RemoteRunnerError as e: raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed on the remote runner: {e}", 502) from None text = _scrub("\n".join(lines), env) @@ -174,7 +184,8 @@ def explore(plan: dict, env: dict, out_dir: Path, *, timeout_s: int = 5400, on_l on_line(line[len("[explore] "):]) try: rc, raw_lines = run_screens_remote(svc.egress, *remote, kind="explore", env=env, out_dir=out, plan=plan, - timeout_s=timeout_s, on_line=relay) + timeout_s=timeout_s, on_line=relay, busy_wait_s=_busy_wait_s(svc), + on_wait=on_line) except RemoteRunnerError as e: raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed on the remote runner: {e}", 502) from None lines = [_scrub(line, env).rstrip() for line in raw_lines] diff --git a/coworker/api/app.py b/coworker/api/app.py index a0ce055a6d73d4682b36a889e0c957281c707389..6d992808134ee7e58cf641bef7681743f59d4ed7 100644 --- a/coworker/api/app.py +++ b/coworker/api/app.py @@ -84,7 +84,7 @@ def create_app(svc: Services | None = None, cfg: Settings | None = None, *, back log.info("state is saved to Supabase Storage every %ss when it changes", syncer.interval) yield if syncer: # save first: the host may stop this process before the services below have all stopped - syncer.tick("shutdown") + syncer.tick("shutdown", force=True) if getattr(app.state, "courier", None): app.state.courier.stop() sched.stop() diff --git a/coworker/api/routes/admin.py b/coworker/api/routes/admin.py index 16ef2a84439eaa4e6a00646cf45697bd255541ea..3d8f6f0d57731ae115a2cd84a3e58a38e8daf608 100644 --- a/coworker/api/routes/admin.py +++ b/coworker/api/routes/admin.py @@ -99,7 +99,7 @@ def save_storage_now(request: Request, user: Principal = Depends(require("admin" syncer = getattr(request.app.state, "syncer", None) if syncer is None: raise ApiError(409, "NOT_SAVING", "this server does not save its state (no state store configured)") - saved = syncer.tick("before restart") + saved = syncer.tick("before restart", force=True) svc = request.app.state.svc svc.audit.append("state.saved_on_request", actor=user.username, summary="saved" if saved else "unchanged") last = svc.extra.get("state_last") or {} diff --git a/coworker/api/routes/agent_studio.py b/coworker/api/routes/agent_studio.py index 74123bef2758a4a16329f100ac3c364b395d3171..2bac90ef9d570a7c55571931721996f72a214abc 100644 --- a/coworker/api/routes/agent_studio.py +++ b/coworker/api/routes/agent_studio.py @@ -3,20 +3,22 @@ For the Fusion side (OAuth 2.0 client credentials, scope patchwise.invoke): POST /oauth/token client_credentials -> bearer token (one hour) POST /api/agent-studio/v1/test-data/check is this test data acceptable (synthetic, well formed)? - POST /api/agent-studio/v1/cycles approved synthetic test data starts a test cycle + POST /api/agent-studio/v1/cycles approved synthetic test data starts a test cycle (a retry with the + same Idempotency-Key or correlation_id returns that cycle) GET /api/agent-studio/v1/cycles/{cycle_id} where the cycle is POST /api/agent-studio/v1/cycles/{cycle_id}/approval the person's start-testing decision, made in Fusion POST /api/agent-studio/v1/events/claim delivery mode pull: pick up waiting events POST /api/agent-studio/v1/events/ack confirm them -For Patchwise administrators (signed-in session): clients, cycles, callbacks sent, the release watch, the stand-in.""" +For Astra administrators (signed-in session): clients, cycles, callbacks sent (dead letters sent again), the release +watch, the stand-in.""" from __future__ import annotations import base64 import json from typing import Any, Literal -from fastapi import APIRouter, Depends, Request +from fastapi import APIRouter, Depends, Request, Response from pydantic import BaseModel, Field from ...platform.agent_studio import AgentStudio, AgentStudioError, verify_signature @@ -126,11 +128,18 @@ def check_test_data(body: dict, request: Request, client: dict = Depends(agent_c @router.post("/agent-studio/v1/cycles", status_code=202, summary="Start a test cycle with approved synthetic test data") -def start_cycle(body: CycleIn, request: Request, client: dict = Depends(agent_client)): +def start_cycle(body: CycleIn, request: Request, response: Response, client: dict = Depends(agent_client)): + """Safe to send again: with the same Idempotency-Key header (optional), or the same correlation_id while that cycle + is still going, it starts nothing and answers with the cycle the first call made (202, same body; the header + Idempotent-Replayed: true says so).""" try: - return _studio(request).start_cycle(client, body.model_dump(exclude_none=True), request.app.state.runs) + cycle, replayed = _studio(request).start_or_replay(client, body.model_dump(exclude_none=True), request.app.state.runs, + request.headers.get("idempotency-key")) except AgentStudioError as e: _fail(e) + if replayed: + response.headers["Idempotent-Replayed"] = "true" + return cycle @router.get("/agent-studio/v1/cycles/{cycle_id}", summary="Where a test cycle is") @@ -169,8 +178,9 @@ class AckIn(BaseModel): @router.post("/agent-studio/v1/events/claim", summary="Pick up waiting events (delivery mode pull)") def claim_events(body: ClaimIn, request: Request, client: dict = Depends(agent_client)): - """The events Patchwise would have sent (scripts_ready, failures_need_review, results, stopped, patch_update), oldest - first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again.""" + """The events Astra would have sent (scripts_ready, failures_need_review, results, stopped, paused, patch_update), oldest + first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again (at least once: + the same event keeps its delivery_id).""" return _studio(request).claim(client["client_id"], body.max, body.cycle_id) @@ -264,8 +274,20 @@ def list_cycles(request: Request, user: Principal = Depends(require("read"))): @router.get("/agent-studio/deliveries") -def list_deliveries(request: Request, user: Principal = Depends(require("admin"))): - return {"items": _studio(request).deliveries()} +def list_deliveries(request: Request, state: Literal["dead"] | None = None, user: Principal = Depends(require("admin"))): + """The callbacks, newest first, each with its state (queued, picked_up, retrying, delivered, superseded, dead). + ?state=dead lists the dead letters only: events that ran out of tries; send one again with .../requeue.""" + studio = _studio(request) + return {"items": studio.deliveries(state=state), "dead_letters": studio.dead_letters()} + + +@router.post("/agent-studio/deliveries/{delivery_id}/requeue") +def requeue_delivery(delivery_id: str, request: Request, user: Principal = Depends(require("admin"))): + """Send a dead letter (or an event still retrying) again: its tries start over, with the same delivery_id.""" + try: + return _studio(request).requeue(delivery_id, user.username) + except AgentStudioError as e: + _fail(e) @router.get("/agent-studio/release-watch") diff --git a/coworker/api/runner.py b/coworker/api/runner.py index 6166e7603fd48bf828ddda8c6fc9072781bea8be..f2dc8ea7291cb1a1e24b4fae5145c62b75c770ff 100644 --- a/coworker/api/runner.py +++ b/coworker/api/runner.py @@ -88,9 +88,11 @@ def _create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod "inputs": state, "status": "queued", "orchestrator": orchestrator, "pod_id": pod["id"]}) -def create_run_record(svc, inputs: dict, actor: str, trigger: str = "manual", orchestrator: str = "langgraph") -> tuple[str, dict]: +def create_run_record(svc, inputs: dict, actor: str, trigger: str = "manual", orchestrator: str = "langgraph", + run_id: str | None = None) -> tuple[str, dict]: """Validate inputs, create the run row (status queued), the initial shared state, the queued event and the audit entry. - Shared by both orchestrators (LangGraph RunManager and the Temporal one).""" + Shared by both orchestrators (LangGraph RunManager and the Temporal one). `run_id`: an id the caller reserved + beforehand (an Agent Studio cycle records it before the run exists); a new one otherwise.""" svc.kill.check("run.start") from ..platform.pods import PodError, PodRegistry reg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit) @@ -110,7 +112,7 @@ def create_run_record(svc, inputs: dict, actor: str, trigger: str = "manual", or if failed: svc.db.update("pods", "id", pod["id"], last_check_at=now_iso(), last_check_ok=0, last_check_detail=failed["detail"]) raise RunError(f"{pod['name']}: {failed['detail']}", "POD_CHECK_FAILED", 409) - rid = new_run_id() + rid = run_id or new_run_id() mods = [m.upper() for m in inputs.get("modules") or []] state = {"run_id": rid, "patch_id": inputs.get("patch_id") or "", "trigger": trigger, "modules_requested": mods, "include_p2": bool(inputs.get("include_p2")), "case_filter": [str(x) for x in inputs.get("case_ids") or []], @@ -210,8 +212,8 @@ class RunManager: self._execute(*job) # ------------------------------------------------------------ API - def start(self, inputs: dict, actor: str, trigger: str = "manual") -> str: - rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph") + def start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str: + rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph", run_id=run_id) self._enqueue("start", rid, state) return rid @@ -253,7 +255,14 @@ class RunManager: from ..platform.statesync import save_soon save_soon("run cancelled") if self.current != run_id: # a running one is swept by the worker once Playwright is gone - threading.Thread(target=sweep_test_data, args=(self.svc, run_id, "cancelled"), daemon=True).start() + threading.Thread(target=self._release_and_sweep, args=(run_id,), daemon=True).start() + + def _release_and_sweep(self, run_id: str) -> None: + """A cancelled run that is not running here may still own a job on the remote browser runner (a restart left it + running): stop it, so the runner is free, and fetch the records it made before the clean-up looks for them.""" + from ..adapters.remote_runner import release_job + release_job(self.svc, run_id) + sweep_test_data(self.svc, run_id, "cancelled") def gate_payload(self, run_id: str) -> dict | None: snap = self.graph.get_state(run_config(run_id, self.svc.cfg)) diff --git a/coworker/config.py b/coworker/config.py index d0fc1fc8ef8070677afc9aadd701a8056913a0bb..735856d8ce8170a9d18eb3a13cf055c53d9cef4b 100644 --- a/coworker/config.py +++ b/coworker/config.py @@ -15,6 +15,25 @@ ROOT = Path(__file__).resolve().parents[1] CONFIG_YAML = Path(os.getenv("FPT_CONFIG", ROOT / "config" / "coworker.yaml")) VERSION = "1.0.0-pilot" MOCK_BANNER = "Mock app, not Oracle Fusion" +# where a deploy may record the commit it installed (deploy/runner/sync.sh writes the same file on a browser runner) +COMMIT_ENV = ("FPT_COMMIT", "GIT_COMMIT", "SOURCE_COMMIT", "RENDER_GIT_COMMIT") +COMMIT_FILE = ROOT / "VERSION" + + +def server_commit() -> str: + """The commit this server runs, when its deploy recorded one (an environment variable or a VERSION file at the repo + root); "" when it cannot know, and then nothing compares against it.""" + import re + vals = [os.getenv(k) or "" for k in COMMIT_ENV] + try: + vals.append(COMMIT_FILE.read_text(encoding="utf-8") if COMMIT_FILE.is_file() else "") + except OSError: + pass + for v in vals: + v = v.strip().lower() + if re.fullmatch(r"[0-9a-f]{7,40}", v): + return v + return "" def _alias(*names: str): @@ -138,9 +157,24 @@ class Settings(BaseSettings): fusion_ai_scenarios_max: int = Field(12, validation_alias=_alias("fpt_fusion_ai_scenarios_max", "fusion_ai_scenarios_max")) # regression (depth full): end-to-end flows per area, one per business process, at most this many (0: none) fusion_regression_flows: int = Field(3, validation_alias=_alias("fpt_fusion_regression_flows", "fusion_regression_flows")) + # regression (depth full): the area's standard regression and edge-case checks (fusion_catalog "regression") that no + # library scenario covers yet, one AI-designed scenario each, at most this many per area (0: none) + fusion_regression_checks: int = Field(25, validation_alias=_alias("fpt_fusion_regression_checks", "fusion_regression_checks")) # browsers working at once on a Fusion pod (screen reading, dry runs, test runs) and areas the AI designs at once. # Fusion's own server is the slow part, so a small server still runs about 3 well; 1 = one at a time fusion_workers: int = Field(3, validation_alias=_alias("fpt_fusion_workers", "fusion_workers")) + # a browser pass on a Fusion pod gets this many minutes per scenario each worker runs (Playwright stops one test after + # 10), plus start-up, kept between the floor and the ceiling below; a pass past its time is stopped and loses its results + fusion_scenario_minutes: int = Field(12, validation_alias=_alias("fpt_fusion_scenario_minutes", "fusion_scenario_minutes")) + fusion_attempt_min_minutes: int = Field(30, validation_alias=_alias("fpt_fusion_attempt_min_minutes", "fusion_attempt_min_minutes")) + # the remote runner stops any job after 4 hours whatever is asked, so a higher ceiling only helps local browsers + fusion_attempt_max_minutes: int = Field(240, validation_alias=_alias("fpt_fusion_attempt_max_minutes", "fusion_attempt_max_minutes")) + # a bigger attempt on a Fusion pod runs as passes of this many scenarios, each with its own time budget and report, + # so a pass that runs out of time loses only its own scenarios and a resumed run keeps the finished passes (0: one pass) + fusion_chunk_scenarios: int = Field(24, validation_alias=_alias("fpt_fusion_chunk_scenarios", "fusion_chunk_scenarios")) + # the remote runner drives one browser job at a time: a run or screen read that finds it busy waits this long for it + remote_runner_busy_wait_minutes: int = Field(15, validation_alias=_alias("fpt_remote_runner_busy_wait_minutes", + "remote_runner_busy_wait_minutes")) # read the screens of a Fusion pod's areas in the background as soon as they are discovered or its release changes, # so a run finds them ready instead of reading them itself fusion_screens_on_setup: bool = Field(True, validation_alias=_alias("fpt_fusion_screens_on_setup", "fusion_screens_on_setup")) diff --git a/coworker/graph/nodes/ai_scenarios.py b/coworker/graph/nodes/ai_scenarios.py index fb2831e3a8c6139183997c7405ea47f6db39bc51..08174d687873c4e41205c96a974887770ddc64f6 100644 --- a/coworker/graph/nodes/ai_scenarios.py +++ b/coworker/graph/nodes/ai_scenarios.py @@ -268,6 +268,80 @@ def _design_area_flows(svc, run_id: str, area: str, processes: list[str], change module=area) +PER_SCREEN = 3 # scenarios one screen may take in an area's general design (flows and regression checks aside) + + +def key_screens(screens: list[dict], key_tasks: list[str]) -> list[dict]: + """The screens of the area's key business tasks (catalog key_tasks, matched on the task's last part), in that order; + empty when none of them was read.""" + last = lambda s: step_writer.norm_task(str(s.get("task") or "").split(">")[-1]) # noqa: E731 + order = [step_writer.norm_task(k) for k in key_tasks] + return sorted((s for s in screens if last(s) in order), key=lambda s: order.index(last(s))) + + +def spread(intents) -> list[dict]: + """At most PER_SCREEN scenarios per screen, in the model's order: coverage across the area, not one screen's corners.""" + out, per = [], {} + for i in intents: + k = step_writer.norm_task(str(i.get("task") or "")) + per[k] = per.get(k, 0) + 1 + if per[k] <= PER_SCREEN: + out.append(i) + return out + + +REGRESSION_BATCH = 8 # regression checks asked of the model in one call (more makes its answers vaguer) + + +def regression_checks(checks: list, titles: list[str]) -> list[dict]: + """The area's catalog regression checks that no scenario covers yet (a title that says the same thing), taken one + process at a time in turn, so a cap still reaches every business process of the area.""" + by_process: dict[str, list[dict]] = {} + for c in checks or []: + if not isinstance(c, dict) or not str(c.get("check") or "").strip(): + continue + if not any(step_writer.same_title(c["check"], t) for t in titles): + by_process.setdefault(str(c.get("process") or ""), []).append(c) + out: list[dict] = [] + queues = list(by_process.values()) + while any(queues): + out += [q.pop(0) for q in queues if q] + return out + + +def _design_regression_checks(svc, run_id: str, area: str, checks: list, screens: list[dict], titles: list[str], example: str, + taken: set[str], drafts: list[dict], placeholders: list[str], lock=None) -> None: + """Regression (depth full): one scenario for each of the area's standard regression and edge-case checks + (fusion_catalog "regression") that the library and this run do not cover yet, at most FPT_FUSION_REGRESSION_CHECKS, + asked in batches. Each draft goes through the same step checks as every AI scenario: one whose steps fail them is + shown as not written and never offered as runnable.""" + cap = max(0, int(svc.cfg.fusion_regression_checks or 0)) + todo = regression_checks(checks, titles)[:cap] + if not todo: + return + seen, designed = list(titles), [] + for start in range(0, len(todo), REGRESSION_BATCH): + batch = todo[start:start + REGRESSION_BATCH] + asks = [f"{c.get('process') or area}: regression check: {c['check']} (one scenario that tests exactly this)" for c in batch] + try: # no release changes here: those were covered first, these scenarios are the checks themselves + intents = step_writer.design_scenarios(svc, area, asks, [], screens, count=len(batch), run_id=run_id, + existing_titles=list(seen)) + except Exception as e: # noqa: BLE001 - the model is down or refused: the next batches would fail the same way + _note(svc, run_id, f"{area}: the AI model could not design regression checks ({type(e).__name__})" + + (f"; {len(designed)} were designed before." if designed else "."), module=area) + return + intents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value)] + if intents: + _write_intents(svc, run_id, area, intents, screens, example, taken, drafts, placeholders, lock) + seen += [i["title"] for i in intents] + designed += intents + if designed: + _note(svc, run_id, f"{area}: {len(designed)} regression check(s) designed: " + "; ".join(i["title"] for i in designed)[:300] + ".", + module=area, asked=len(todo)) + else: + _note(svc, run_id, f"{area}: no regression check was designed this time ({len(todo)} asked).", module=area, asked=len(todo)) + + # ====================================================================== writing def write_ai_scenarios(state, svc, library: list[dict]) -> dict: """{"cases": [test cases for drafts whose dry run passed], "drafts": [every AI draft with its result]}; {} when the @@ -317,14 +391,17 @@ def write_ai_scenarios(state, svc, library: list[dict]) -> dict: auto = sum(1 for c in changes if c.get("on_by_default")) n = scenario_count(count, auto, int(svc.cfg.fusion_ai_scenarios_max or count), len(screens)) titles = [c["title"] for c in library if c.get("module") == area and c.get("title")] + # the area's main business screens (catalog key_tasks) first: given every screen read, the model once spent most + # of an AP run on a bank-file screen; flows and regression checks below still see every screen + key = key_screens(screens, cat.get("key_tasks") or []) try: - intents = step_writer.design_scenarios(svc, area, processes, changes, screens, count=n, + intents = step_writer.design_scenarios(svc, area, processes, changes, key or screens, count=n, run_id=run_id, existing_titles=titles) except Exception as e: # noqa: BLE001 _note(svc, run_id, f"{area}: the AI model could not design new scenarios ({type(e).__name__}).", module=area) return why = next((i.get("fallback_reason") for i in intents if i.get("fallback_reason")), None) - intents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value)] + intents = spread(i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value)) if not intents: # say why: a model that was not reached is a fault to fix, not an empty answer _note(svc, run_id, f"{area}: no new scenario was written: " + (f"the AI model could not be used ({why[:200]})." if why else "the AI model proposed none for these screens."), @@ -338,6 +415,9 @@ def write_ai_scenarios(state, svc, library: list[dict]) -> dict: flows = list(dict.fromkeys(list(cat.get("processes") or []) + step_writer.area_processes(area))) _design_area_flows(svc, run_id, area, flows, changes, screens, titles + [i["title"] for i in intents], example, taken, drafts, placeholders, lock) + # then every standard regression and edge-case check of the area that nothing above covers + _design_regression_checks(svc, run_id, area, cat.get("regression") or [], screens, titles + [d["title"] for d in drafts], + example, taken, drafts, placeholders, lock) workers = max(1, min(int(svc.cfg.fusion_workers or 1), len(areas) or 1)) with ThreadPoolExecutor(max_workers=workers, thread_name_prefix=f"design-{run_id[-6:]}") as ex: diff --git a/coworker/graph/nodes/execute.py b/coworker/graph/nodes/execute.py index 685272b980bbdda86b70e1096154f8b4cdece980..429bb450115cd294210f19f6568ec09c3d841976 100644 --- a/coworker/graph/nodes/execute.py +++ b/coworker/graph/nodes/execute.py @@ -66,14 +66,17 @@ def browser_failure(out_file: str | Path, res: dict | None) -> str | None: return why + (f": {errs[0]}" if errs and errs[0] else "") + "." -def plan_attempt(state, svc, clean: bool = True) -> dict: - """Which cases this attempt runs (attempt 0: in-scope; attempt 1: failed ids only) and the run_attempt arguments.""" +def plan_attempt(state, svc, clean: bool | None = None) -> dict: + """Which cases this attempt runs (attempt 0: in-scope; attempt 1: failed ids only) and the run_attempt arguments. + clean: whether attempt 0 deletes old reports first; None decides it from the run folder (resumed_attempt).""" run_id = state["run_id"] run_dir = svc.run_dir(run_id) files = list(state.get("attempt_files") or []) attempt = len(files) mode = state.get("playwright_mode") or svc.cfg.playwright_mode if attempt == 0: + if clean is None: + clean = not resumed_attempt(run_dir) if clean: # a fresh attempt 0 never reuses old reports (a resumed one keeps its finished chunks) for f in run_dir.glob("attempt-*.json"): f.unlink() @@ -123,22 +126,138 @@ def user_groups(reg, pod_id: int, run_id: str, ids: list[str], module_of: dict[s return list(groups.values()) if len(groups) > 1 else None +FUSION_CONFIG = "playwright.fusion.config.ts" +STARTUP_MINUTES = 10 # a pass's own start-up: Playwright, the browser and the test user's one sign-in + + +def attempt_timeout_s(cfg, scenarios: int, workers=None) -> int: + """How long a browser pass of this many scenarios on a Fusion pod may take: its scenarios shared over the workers that + run at once (FPT_FUSION_WORKERS), fusion_scenario_minutes each, plus start-up, kept between the floor and the ceiling. + A fixed hour stopped every big pass at its deadline, and a pass stopped that way loses all its results.""" + w = max(1, min(4, int(workers or cfg.fusion_workers or 1))) + rounds = -(-max(1, int(scenarios)) // w) + minutes = STARTUP_MINUTES + rounds * max(1, int(cfg.fusion_scenario_minutes)) + return 60 * max(int(cfg.fusion_attempt_min_minutes), min(int(cfg.fusion_attempt_max_minutes), minutes)) + + +class RunCancelled(RuntimeError): + pass + + +def _stop_check(svc, run_id: str) -> None: + """Called while a remote pass runs: the kill switch, or a person cancelling the run, stops the runner's job too + (nothing else would: the browser is not a process of this server).""" + svc.kill.check("executor.remote") + r = svc.db.get_run(run_id) + if isinstance(r, dict) and r.get("status") == "cancelled": + raise RunCancelled(f"run {run_id} was cancelled") + + +def progress_file(out_file: str | Path) -> Path: + """Where a Fusion attempt lists its finished passes (next to its report; a fresh attempt 0 deletes it with the reports).""" + out = Path(out_file) + return out.with_name(f"{out.stem}.chunks.json") + + +def _finished_passes(prog: Path, ids: list[str], size: int) -> tuple[dict, dict]: + """(chunk -> report, chunk -> run dir) of the passes an earlier try of this attempt finished, when it planned the + same scenarios in the same passes; nothing otherwise.""" + try: + d = json.loads(prog.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {}, {} + if not isinstance(d, dict) or d.get("ids") != ids or d.get("size") != size: + return {}, {} + done = {int(k): v for k, v in (d.get("done") or {}).items() if Path(v).exists()} + return done, {k: v for k, v in ((int(k), v) for k, v in (d.get("dirs") or {}).items()) if k in done and v} + + +def forget_passes(out_file: str | Path) -> None: + """A try of the attempt is thrown away (nothing ran): its pass reports and their list go, so the next try runs all.""" + out = Path(out_file) + for f in out.parent.glob(f"{out.stem}.*.json"): + f.unlink(missing_ok=True) + + +def resumed_attempt(run_dir: str | Path) -> bool: + """Attempt 0 entered again (the run was resumed after a restart or a failure) keeps its finished passes: a list of + them, or the runner job it was following, is still in the run folder. A first entry finds neither.""" + from ...adapters.remote_runner import saved_job + job = saved_job(Path(run_dir)) + return any(Path(run_dir).glob("attempt-0*.chunks.json")) or bool(job and job.get("attempt") == 0) + + def run_planned(plan: dict, svc, **extra) -> dict: - """Default runner: one Playwright invocation for the whole attempt (LangGraph path); one per test user when the - areas sign in as different users (plan["groups"]), merged into the attempt's one report.""" + """Default runner (LangGraph path): one Playwright invocation for the attempt; one per test user when the areas sign + in as different users (plan["groups"]), merged into the attempt's one report. On a Fusion pod an attempt runs in + passes of at most fusion_chunk_scenarios, each with a time budget for its size (run_fusion).""" if plan.get("groups"): return run_groups(plan, svc, **extra) + if plan["mode"] == "live" and plan.get("config") == FUSION_CONFIG and plan["ids"]: + return run_fusion(plan, svc, **extra) + return run_pass(plan, svc, **extra) + + +def run_fusion(plan: dict, svc, **extra) -> dict: + """A browser attempt on a Fusion pod: passes of at most fusion_chunk_scenarios scenarios (pw.run_attempt_chunked, as + under Temporal), each with its own time budget and report, merged into the attempt's one report. A pass that runs + out of time loses only its own scenarios (recorded as timed out, so the retry runs them), and the finished passes are + listed next to the report so a resumed run skips them. An attempt that fits in one pass keeps its usual names.""" + ids, out = list(plan["ids"]), Path(plan["out_file"]) + size = int(svc.cfg.fusion_chunk_scenarios or 0) + size = size if 0 < size < len(ids) else len(ids) + prog = progress_file(out) + done, dirs = _finished_passes(prog, ids, size) + workers = (plan.get("cred_env") or {}).get("FPT_FUSION_WORKERS") + if done: + svc.db.add_event(plan["run_id"], "executor", "resumed", {"attempt": plan["attempt"], "skipped_chunks": sorted(done), + "message": f"{len(done)} finished pass(es) of this attempt are kept."}) + + def one(*, ids: list[str], out_file: Path, tag: str, live_meta: dict, **_): + sub = {**plan, "ids": ids, "out_file": str(out_file), "tag": tag, "live_meta": live_meta, "groups": None, + "timeout_s": attempt_timeout_s(svc.cfg, len(ids), workers)} + return run_pass(sub, svc, **extra) + + def on_chunk(k: int, f: str, total: int, run_dir: str | None) -> None: + done[k] = f + if run_dir: + dirs[k] = run_dir + tmp = prog.with_name(f".{prog.name}.tmp") + tmp.write_text(json.dumps({"ids": ids, "size": size, "done": done, "dirs": dirs}), encoding="utf-8") + tmp.replace(prog) + if total > 1: + svc.db.add_event(plan["run_id"], "executor", "progress", {"attempt": plan["attempt"], "chunk": k + 1, "of": total}) + + res = pw.run_attempt_chunked(ids=ids, out_file=out, chunk_size=size, done=done, done_dirs=dirs, on_chunk=on_chunk, run=one, + tag=plan.get("tag") or "", lost_ok=True, single_as_attempt=True) + if res.get("lost_chunks"): + svc.db.add_event(plan["run_id"], "executor", "execution_error", { + "attempt": plan["attempt"], "lost_chunks": res["lost_chunks"], "retrying": False, + "error": f"{len(res['lost_chunks'])} of {res['chunks']} passes ran out of time before they reported; their " + "scenarios are recorded as timed out and tried again in the retry."}) + return {**res, "mode": plan["mode"]} + + +def run_pass(plan: dict, svc, **extra) -> dict: + """One Playwright invocation: on the remote runner for a Fusion pod when one is set, else on this server.""" remote = (svc.cfg.remote_runner_url or "").strip() - if remote and plan["mode"] == "live" and plan.get("config") == "playwright.fusion.config.ts": + if remote and plan["mode"] == "live" and plan.get("config") == FUSION_CONFIG: from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs there token = svc.vault.get("remote_runner.token") or "" if token: svc.redactor.add_secrets([token]) - return run_attempt_remote(svc.egress, remote, token, run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"], + rid, attempt = plan["run_id"], plan["attempt"] + + def note(message: str) -> None: + svc.db.add_event(rid, "executor", "runner", {"message": message, "attempt": attempt, "pass": plan.get("tag") or None}) + + return run_attempt_remote(svc.egress, remote, token, run_id=rid, ids=plan["ids"], attempt=attempt, out_file=Path(plan["out_file"]), cred_env=plan["cred_env"], drafts_dir=Path(plan["drafts_dir"]), library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None, overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, log_dir=Path(plan["run_dir"]), - config=plan["config"], kill=lambda: svc.kill.check("executor.remote"), + config=plan["config"], kill=lambda: _stop_check(svc, rid), + timeout_s=int(plan.get("timeout_s") or 3600), live_meta=plan.get("live_meta"), + busy_wait_s=60 * int(svc.cfg.remote_runner_busy_wait_minutes), on_event=note, live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, tag=plan.get("tag") or "") if plan["mode"] == "live" and not plan.get("config"): pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs")) @@ -146,6 +265,10 @@ def run_planned(plan: dict, svc, **extra) -> dict: extra.setdefault("config", plan["config"]) if plan.get("tag"): extra.setdefault("tag", plan["tag"]) + if plan.get("timeout_s"): + extra.setdefault("timeout_s", int(plan["timeout_s"])) + if plan.get("live_meta"): + extra.setdefault("live_meta", plan["live_meta"]) return pw.run_attempt(run_id=plan["run_id"], ids=plan["ids"], attempt=plan["attempt"], mode=plan["mode"], out_file=Path(plan["out_file"]), stub_knobs=plan["stub_knobs"], drafts_dir=Path(plan["drafts_dir"]), library_dir=Path(plan["library_dir"]) if plan.get("library_dir") else None, @@ -199,6 +322,8 @@ def finish_attempt(state, svc, plan: dict, res: dict | None) -> dict: except Exception as e: # noqa: BLE001 svc.audit.append("evidence.error", actor="system", run_id=run_id, summary=str(e)[:300]) files = plan["files"] + [str(out_file)] + if len(files) > 1: # a scenario recorded as timed out (its pass overran) is matched to its retry's result + pw.adopt_no_result(files) merged = merge_attempts(files, Path(plan["run_dir"]) / "merged-results.json") outs, counts = outcomes(str(merged)) fails = failing_ids(str(out_file)) if plan["ids"] else [] @@ -233,6 +358,7 @@ def executor(state, config, svc) -> dict: raise ExecutionError(f"The browser test run failed twice before any scenario ran. {why}", exit_code=(res or {}).get("exit_code"), timed_out=bool((res or {}).get("timed_out"))) Path(plan["out_file"]).unlink(missing_ok=True) + forget_passes(plan["out_file"]) # the retry runs every pass again: none of them recorded anything return finish_attempt(state, svc, plan, res) @@ -243,7 +369,8 @@ def preflight_or_stop(state, svc, plan: dict) -> None: if pid is None: return from ...platform import preflight - areas = sorted({c["module"] for c in state.get("test_cases") or []}) + ids = set(plan["ids"]) # the areas this attempt runs, not every area the run designed for + areas = sorted({c["module"] for c in state.get("test_cases") or [] if c["id"] in ids}) results = preflight.check(svc, pid, plan["run_id"], areas) bad = preflight.problems(results) svc.db.add_event(plan["run_id"], "executor", "preflight", {"ok": not bad, "checks": results}) diff --git a/coworker/llm/prompts/design_scenarios.md b/coworker/llm/prompts/design_scenarios.md index 8f48c848d74b93dd865b31a2aa1715b380d1d5b2..7712f9ea9f9c54d6de3802f3b9f47616029165f4 100644 --- a/coworker/llm/prompts/design_scenarios.md +++ b/coworker/llm/prompts/design_scenarios.md @@ -44,6 +44,12 @@ Rules: the choice changes them; - search: find the document just created by its number, and a search that should find nothing. At least half of the scenarios that are not change coverage must be `negative` or edge cases (P3). + Only propose edge cases Fusion refuses on Save, Submit or an action (not a value a field rejects while typing, and + never an invalid choice in a drop-down list, which offers only its own choices). +- When the input's processes say "regression check: ...", each is one standard check a senior tester runs every cycle: + propose exactly one scenario per check that tests exactly what it says, with a title close to the check's words, on + the input screen (or flow) that shows it. Skip a check none of the input screens can show; the rules above about the + mix of scenarios do not apply then. - Say in `why` (one sentence) which change it covers, or that it is a regression check, or which edge case it tests. P1 = core flow a business cannot work without, or a change switched on by the update; P2 = important variant; P3 = edge case. diff --git a/coworker/llm/prompts/write_steps.md b/coworker/llm/prompts/write_steps.md index 96af310d7e0a66cfe136b986e799ffe9ff077365..025c211c2a6015b30c940ad7bc76b81d21aa88ed 100644 --- a/coworker/llm/prompts/write_steps.md +++ b/coworker/llm/prompts/write_steps.md @@ -41,6 +41,15 @@ Rules: - Every scenario proves its title with at least one check step (`expect_filled`, `expect_value`, `expect_status`, `expect_no_error` after a save or action, `expect_message` for a message the scenario expects, `expect_results` after a search), and `expected_result` says in one sentence what it proves. Write the WHOLE scenario, to its last check. +- Negative and edge cases as Fusion really behaves (seen on live pods): + - a drop-down list (`kind: list`) only offers its own choices: never enter an invalid or made-up choice in it; test a + list by choosing a valid entry and checking what it changes; + - a value the field itself refuses while typing (a malformed date, letters in a number) stops the test at that step: + test refusals that happen on Save, Submit or an action instead (a required field left empty, lines that do not add + up, a duplicate number, an amount over what is allowed), and check them with `expect_message`; + - `expect_message` takes one or two words Fusion is sure to use in that message ("required", "duplicate", "hold", + "exceeds"), never a whole sentence you expect it to say; + - type dates with the `{{today}}` placeholder or in the pod's own format; never type a date in another format (an ISO year-month-day date is refused by the field). - A scenario that does not need to keep anything ends with `cancel_without_saving`. - `process` is the short business process name, for example "Invoice entry" or "Invoice validation and holds". - To check that a field is empty, use `expect_value` with value "". diff --git a/coworker/platform/agent_studio.py b/coworker/platform/agent_studio.py index 241794f298c2a80a6a7ea53f48540077228d74c9..dd1340b55c64fff7c3b8d9b4700c014587968bb2 100644 --- a/coworker/platform/agent_studio.py +++ b/coworker/platform/agent_studio.py @@ -1,20 +1,24 @@ -"""Oracle Fusion AI Agent Studio drives Patchwise (docs/AGENT_STUDIO.md). +"""Oracle Fusion AI Agent Studio drives Astra (docs/AGENT_STUDIO.md). The Fusion side (a weekly scheduler and an AI Agent Studio workflow) reads the module space, generates SYNTHETIC test -data, masks and validates it, and a person approves it in Fusion. It then calls Patchwise with an OAuth 2.0 client +data, masks and validates it, and a person approves it in Fusion. It then calls Astra with an OAuth 2.0 client (client credentials, invoke-only): POST /oauth/token -> a bearer token (one hour, scope patchwise.invoke) - POST /api/agent-studio/v1/cycles -> the approved test data JSON starts a test cycle (one Patchwise run) + POST /api/agent-studio/v1/cycles -> the approved test data JSON starts a test cycle (one Astra run); sent + again (same correlation_id or Idempotency-Key) it returns that cycle callback scripts_ready <- the scenarios and their Excel script, waiting for approval in Fusion POST /api/agent-studio/v1/cycles/{id}/approval -> the person's "start testing" decision, made in Fusion - callback failures_need_review <- failed tests wait for a person to decide (in Patchwise) + callback failures_need_review <- failed tests wait for a person to decide (in Astra) callback results / stopped <- verdicts per area, report and PDF links + callback paused <- (optional) the run was interrupted by a restart; it can be resumed callback patch_update <- the release watch: new or changed items in Oracle's What's New Callbacks are signed (X-Patchwise-Signature: sha256=HMAC of the body with the client's signing key), sent through the -egress gate to the client's own callback address only, and retried. Test data is synthetic by contract and checked: -anything that looks like personal data (an email, a phone or card number, a national id) is refused.""" +egress gate to the client's own callback address only, and retried: delivery is at least once, and the same logical +event always has the same delivery_id, so the Fusion side drops repeats by that id. An event that runs out of tries is +kept as a dead letter an admin can send again. Test data is synthetic by contract and checked: anything that looks like +personal data (an email, a phone or card number, a national id) is refused.""" from __future__ import annotations import base64 @@ -37,10 +41,22 @@ _TOKENS: dict[str, tuple[str, float]] = {} # client_id -> (Oracle access token SCOPE = "patchwise.invoke" TOKEN_TTL_S = 3600 TOKEN_PREFIX = "pwa_" -EVENTS = ("scripts_ready", "failures_need_review", "results", "stopped", "patch_update") +# Access tokens are signed (HMAC-SHA256), not looked up: pwa_2..... A restart that +# restores an older snapshot keeps every token the Fusion side holds valid; the client row (revoked or not) still decides. +# The key is the vault's agent_studio.token_key (FPT_SECRET_AGENT_STUDIO_TOKEN_KEY), made once when it is missing. +TOKEN_VERSION = "2" +TOKEN_KEY = "agent_studio.token_key" +# "paused" is the one event older Fusion callback workflows do not know: they ignore it (the others never change) +EVENTS = ("scripts_ready", "failures_need_review", "results", "stopped", "paused", "patch_update") DEPTHS = {"regression": "full", "full": "full", "standard": "standard", "smoke": "smoke"} MAX_ATTEMPTS = 6 -STOPPED = ("failed", "killed", "cancelled", "interrupted") +STOPPED = ("failed", "killed", "cancelled") +# a run the backend restart interrupted is not over: it can be resumed, so the cycle is "paused", not "stopped" +PAUSED = ("interrupted",) +# a cycle is watched until its run cannot move on any more (failed and interrupted runs can be resumed) +FINAL = ("completed", "killed", "cancelled") +# a start sent again with the same correlation_id returns the cycle while its run is still going +ACTIVE = ("queued", "running", "waiting_approval", "waiting_review") # test data must be synthetic: values that look like personal or payment data are refused outright _PII = [ @@ -117,6 +133,49 @@ def _hash(s: str) -> str: return hashlib.sha256(s.encode()).hexdigest() +def _save_soon(reason: str) -> None: + """Ask for a state save now: a restart minutes later must not lose a cycle, an approval or a client.""" + from .statesync import save_soon + save_soon(reason) + + +def delivery_id_for(scope: str, event: str, seq: int) -> str: + """The same logical event always gets the same id: (cycle, or client for the release watch; event; how many of + that event the cycle had before). A snapshot restored after a restart re-creates a lost event with its old id.""" + return "dlv_" + hashlib.sha256(f"{scope}|{event}|{seq}".encode()).hexdigest()[:16] + + +def _token_key(svc) -> bytes: + k = svc.vault.get(TOKEN_KEY) + if not k: + if not hasattr(svc.vault, "set"): + raise AgentStudioError("server_error", "the vault cannot keep a token key; set FPT_SECRET_AGENT_STUDIO_TOKEN_KEY", 500) + k = secrets.token_urlsafe(32) + svc.vault.set(TOKEN_KEY, k) + _save_soon("agent studio token key made") + return k.encode() + + +def _token_mac(svc, body: str) -> str: + return base64.urlsafe_b64encode(hmac.new(_token_key(svc), body.encode(), hashlib.sha256).digest()).decode().rstrip("=") + + +def sign_token(svc, client_id: str, ttl_s: int = TOKEN_TTL_S, now: float | None = None) -> str: + body = f"{TOKEN_VERSION}.{client_id}.{int((now or time.time()) + ttl_s)}.{secrets.token_hex(8)}" + return f"{TOKEN_PREFIX}{body}.{_token_mac(svc, body)}" + + +def token_client_id(svc, token: str, now: float | None = None) -> str | None: + """The client id of a signed token that is genuine and not expired; None otherwise (no database read).""" + parts = token[len(TOKEN_PREFIX):].split(".") + if len(parts) != 5 or parts[0] != TOKEN_VERSION or not parts[2].isdigit(): + return None + body = ".".join(parts[:4]) + if not hmac.compare_digest(_token_mac(svc, body), parts[4]) or int(parts[2]) < (now or time.time()): + return None + return parts[1] + + def _utc(ts: str) -> datetime: d = datetime.fromisoformat(ts.replace("Z", "+00:00")) return d if d.tzinfo else d.replace(tzinfo=timezone.utc) @@ -199,6 +258,7 @@ class AgentStudio: "created_by": actor, "created_at": now_iso()}) self.svc.vault.set(f"agent_studio.{cid}.signing", signing) self.svc.audit.append("agent_studio.client_created", actor=actor, summary=f"{cid} {name}", payload={"client_id": cid, "name": name}) + _save_soon("agent studio client created") # the secret is shown once: a restart must not forget the client return {"client_id": cid, "client_secret": secret, "signing_key": signing, "name": name, "callback_url": callback_url, "release_watch_url": release_watch_url} @@ -258,6 +318,7 @@ class AgentStudio: self.db.update("agent_clients", "client_id", client_id, revoked_at=now_iso()) self.db.x("DELETE FROM agent_tokens WHERE client_id=?", (client_id,)) self.svc.audit.append("agent_studio.client_revoked", actor=actor, summary=client_id, payload={"client_id": client_id}) + _save_soon("agent studio client revoked") # signed tokens end with the client: the revocation must survive a restart def _shown(self, r: dict) -> dict: out = {k: v for k, v in r.items() if k not in ("secret_hash", "fusion")} @@ -379,28 +440,61 @@ class AgentStudio: raise AgentStudioError("invalid_client", "unknown client or wrong secret", 401) if scope and scope.strip() != SCOPE: raise AgentStudioError("invalid_scope", f"the only scope is {SCOPE}", 400) - token = TOKEN_PREFIX + secrets.token_urlsafe(32) + # signed, not stored: a restored snapshot cannot forget it (tokens issued before this kept their rows, below) + token = sign_token(self.svc, client_id) self.db.x("DELETE FROM agent_tokens WHERE expires_at < ?", (now_iso(),)) - self.db.insert("agent_tokens", {"token_hash": _hash(token), "client_id": client_id, "scope": SCOPE, - "created_at": now_iso(), "expires_at": _later(TOKEN_TTL_S)}) self.db.update("agent_clients", "client_id", client_id, last_used_at=now_iso()) return {"access_token": token, "token_type": "Bearer", "expires_in": TOKEN_TTL_S, "scope": SCOPE} def client_for_token(self, token: str) -> dict: + """The client of a bearer token: a signed one (checked with the token key, no row needed) or one issued before + tokens were signed (its row, until it expires). Either way the client must exist and not be revoked.""" if not token or not token.startswith(TOKEN_PREFIX): raise AgentStudioError("invalid_token", "a bearer token from /oauth/token is needed", 401) - t = self.db.one("SELECT * FROM agent_tokens WHERE token_hash=?", (_hash(token),)) - if not t or _utc(t["expires_at"]) < datetime.now(timezone.utc): + if "." in token: + cid = token_client_id(self.svc, token) + else: + t = self.db.one("SELECT * FROM agent_tokens WHERE token_hash=?", (_hash(token),)) + cid = t["client_id"] if t and _utc(t["expires_at"]) >= datetime.now(timezone.utc) else None + if not cid: raise AgentStudioError("invalid_token", "the token is unknown or expired: ask /oauth/token for a new one", 401) - c = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (t["client_id"],)) + c = self.db.one("SELECT * FROM agent_clients WHERE client_id=?", (cid,)) if not c or c.get("revoked_at"): raise AgentStudioError("invalid_token", "this client was revoked", 401) return {k: v for k, v in c.items() if k != "secret_hash"} # ------------------------------------------------------------ test cycles - def start_cycle(self, client: dict, body: dict, runs) -> dict: - """The Fusion workflow's approved test data starts one Patchwise run (a full browser run as the action-only - test user). Returns the cycle; its first callback is scripts_ready.""" + def start_cycle(self, client: dict, body: dict, runs, idempotency_key: str | None = None) -> dict: + return self.start_or_replay(client, body, runs, idempotency_key)[0] + + def _replay(self, client_id: str, correlation_id: str | None, idempotency_key: str | None) -> str | None: + """The cycle an earlier start with the same Idempotency-Key made (any time), or the same correlation_id while + that cycle's run is still going (or being created). A finished, failed or interrupted cycle is not replayed: + a new start with its correlation_id is a new cycle.""" + if idempotency_key: + r = self.db.one("SELECT cycle_id FROM agent_cycles WHERE client_id=? AND idempotency_key=? ORDER BY created_at DESC LIMIT 1", + (client_id, idempotency_key)) + if r: + return r["cycle_id"] + if correlation_id: + r = self.db.one("SELECT c.cycle_id, r.status FROM agent_cycles c LEFT JOIN runs r ON r.run_id=c.run_id " + "WHERE c.client_id=? AND c.correlation_id=? ORDER BY c.created_at DESC, c.rowid DESC LIMIT 1", + (client_id, correlation_id)) + if r and (r["status"] is None or r["status"] in ACTIVE): + return r["cycle_id"] + return None + + def start_or_replay(self, client: dict, body: dict, runs, idempotency_key: str | None = None) -> tuple[dict, bool]: + """The Fusion workflow's approved test data starts one Astra run (a full browser run as the action-only test + user). Returns (the cycle, False); its first callback is scripts_ready. Sent again (a retry: same Idempotency-Key, + or same correlation_id while that cycle is going) it starts nothing and returns (that cycle, True). + The cycle row is written before the run starts, so the runner always finds the cycle's test data, and a save is + asked for at once, so a restart does not forget the cycle.""" + corr = str(body.get("correlation_id") or "")[:120] or None + key = str(idempotency_key or "").strip()[:200] or None + again = self._replay(client["client_id"], corr, key) + if again: + return self.cycle(again), True approved_by = str(body.get("data_approved_by") or "").strip()[:120] if not approved_by: raise AgentStudioError("NOT_APPROVED", "data_approved_by is required: a person approves the test data in Fusion first") @@ -443,27 +537,35 @@ class AgentStudio: reg.update(pod["id"], {"release": str(body["release"]).upper()}, f"agent-studio:{client['client_id']}") except PodError as e: raise AgentStudioError(e.code, str(e), e.status) from e - from ..api.runner import RunError - try: - run_id = runs.start(inputs, actor=f"Oracle AI Agent Studio ({client['name']})", trigger="agent_studio") - except RunError as e: - raise AgentStudioError(e.code, str(e), e.status) from e - cycle_id = "cyc_" + secrets.token_hex(6) + from ..api.runner import RunError, new_run_id + cycle_id, run_id = "cyc_" + secrets.token_hex(6), new_run_id() meta = {k: body.get(k) for k in ("generated_by", "masked", "validated", "module_space", "correlation_id") if body.get(k) is not None} - self.db.insert("agent_cycles", {"cycle_id": cycle_id, "run_id": run_id, "client_id": client["client_id"], - "correlation_id": str(body.get("correlation_id") or "")[:120] or None, "pod_id": pod["id"], - "release": body.get("release"), "areas": json.dumps(areas), "test_data": json.dumps(td), - "skipped_areas": json.dumps(skipped), "package": package_json, - "package_id": str((package or {}).get("package_id") or "")[:120] or None, - "data_meta": json.dumps(meta), "data_approved_by": approved_by, "callback_url": callback, - "last_status": "queued", "created_at": now_iso(), "updated_at": now_iso()}) + with self.db.write_lock: # the retry check and the cycle row are one step: two copies of a start make one cycle + again = self._replay(client["client_id"], corr, key) + if again: + return self.cycle(again), True + self.db.insert("agent_cycles", {"cycle_id": cycle_id, "run_id": run_id, "client_id": client["client_id"], + "correlation_id": corr, "idempotency_key": key, "pod_id": pod["id"], + "release": body.get("release"), "areas": json.dumps(areas), "test_data": json.dumps(td), + "skipped_areas": json.dumps(skipped), "package": package_json, + "package_id": str((package or {}).get("package_id") or "")[:120] or None, + "data_meta": json.dumps(meta), "data_approved_by": approved_by, "callback_url": callback, + "last_status": "queued", "created_at": now_iso(), "updated_at": now_iso()}) + try: # the run gets the id the cycle row already holds + runs.start(inputs, actor=f"Oracle AI Agent Studio ({client['name']})", trigger="agent_studio", run_id=run_id) + except BaseException as e: + self.db.x("DELETE FROM agent_cycles WHERE cycle_id=?", (cycle_id,)) + if isinstance(e, RunError): + raise AgentStudioError(e.code, str(e), e.status) from e + raise self.db.add_event(run_id, "agent_studio", "message", {"message": f"Started by Oracle AI Agent Studio with synthetic test data " f"approved in Fusion by {approved_by}."}) self.svc.audit.append("agent_studio.cycle_started", actor=f"agent-studio:{client['client_id']}", run_id=run_id, summary=f"{cycle_id} {areas} data approved by {approved_by}", payload={"cycle_id": cycle_id, "areas": areas, "skipped_areas": [x["area"] for x in skipped], "package_id": (package or {}).get("package_id"), "keys": {a: sorted(k) for a, k in td.items()}}) - return self.cycle(cycle_id) + _save_soon("agent studio cycle started") + return self.cycle(cycle_id), False def cycle(self, cycle_id: str, client_id: str | None = None) -> dict: c = self.db.one("SELECT * FROM agent_cycles WHERE cycle_id=?", (cycle_id,)) @@ -523,6 +625,7 @@ class AgentStudio: self.db.update("agent_cycles", "cycle_id", cycle_id, scripts_approved_by=who, scripts_approved_at=now_iso(), updated_at=now_iso()) self.svc.audit.append("agent_studio.approval", actor=actor, run_id=c["run_id"], summary=f"{cycle_id} {decision}", payload={"cycle_id": cycle_id, "decision": decision}) + _save_soon(f"agent studio {decision}") # the decision made in Fusion must survive a restart return {**self.cycle(cycle_id), "decision": decision} def _links(self, run_id: str) -> dict: @@ -548,24 +651,36 @@ class AgentStudio: # ------------------------------------------------------------ callbacks def queue(self, client_id: str, url: str | None, event: str, payload: dict, cycle_id: str | None = None) -> str | None: + """One event for the client, delivered at least once. Its delivery_id is stable (delivery_id_for): queued again + for the same step (a restored snapshot re-creating a lost event) it keeps the id the Fusion side may have seen. + A newer event of the cycle drops a "paused" one that was not delivered yet (it would arrive out of date).""" url = self._target(client_id, url) if not url: return None - did = "dlv_" + secrets.token_hex(8) - body = {"event": event, "delivery_id": did, "sent_at": now_iso(), **({"cycle_id": cycle_id} if cycle_id else {}), **payload} - self.db.insert("agent_callbacks", {"delivery_id": did, "client_id": client_id, "cycle_id": cycle_id, "event": event, "url": url, - "payload": json.dumps(body), "attempts": 0, "next_at": now_iso(), "created_at": now_iso()}) + scope = cycle_id or f"client:{client_id}" + with self.db.write_lock: # the count and the insert are one step: two threads never compute the same id + if cycle_id: + n = self.db.one("SELECT COUNT(*) AS n FROM agent_callbacks WHERE cycle_id=? AND event=?", (cycle_id, event))["n"] + else: + n = self.db.one("SELECT COUNT(*) AS n FROM agent_callbacks WHERE cycle_id IS NULL AND client_id=? AND event=?", + (client_id, event))["n"] + did = delivery_id_for(scope, event, int(n)) + body = {"event": event, "delivery_id": did, "sent_at": now_iso(), **({"cycle_id": cycle_id} if cycle_id else {}), **payload} + self.db.x("INSERT OR IGNORE INTO agent_callbacks (delivery_id, client_id, cycle_id, event, url, payload, attempts, next_at, created_at) " + "VALUES (?,?,?,?,?,?,0,?,?)", (did, client_id, cycle_id, event, url, json.dumps(body), now_iso(), now_iso())) + if cycle_id and event != "paused": + self.db.x("UPDATE agent_callbacks SET superseded_by=? WHERE cycle_id=? AND event='paused' AND delivered_at IS NULL " + "AND dead_at IS NULL AND superseded_by IS NULL", (did, cycle_id)) return did def deliver_due(self) -> int: - """Send callbacks that are due; a failure is tried again later (1, 2, 4, 8, 16 minutes), six tries in all.""" + """Send callbacks that are due; a failure is tried again later (1, 2, 4, 8, 16 minutes), six tries in all. One + that runs out of tries becomes a dead letter (bury_dead).""" sent = 0 - for d in self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND attempts < ? AND next_at <= ? AND url <> ? " - "ORDER BY id LIMIT 20", (MAX_ATTEMPTS, now_iso(), PULL)): - key = self.svc.vault.get(f"agent_studio.{d['client_id']}.signing") or "" + for d in self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND dead_at IS NULL AND superseded_by IS NULL " + "AND attempts < ? AND next_at <= ? AND url <> ? ORDER BY id LIMIT 20", (MAX_ATTEMPTS, now_iso(), PULL)): payload = _j(d["payload"]) body = json.dumps(payload).encode() - sig = "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest() code, err, job = None, None, None fusion = self._fusion(d["client_id"]) try: @@ -576,7 +691,12 @@ class AgentStudio: job = out or None else: err = out + elif not (key := self.svc.vault.get(f"agent_studio.{d['client_id']}.signing")): + # never sign with an empty key: the receiver could not tell this callback from a forged one + err = f"no signing key for client {d['client_id']} in the vault: not sent (unsigned callbacks are never sent)" + log.error("agent studio: %s (delivery %s)", err, d["delivery_id"]) else: + sig = "sha256=" + hmac.new(key.encode(), body, hashlib.sha256).hexdigest() r = self.svc.egress.service_request("agent_callback", "POST", d["url"], allowed_base=d["url"], content=body, headers={"Content-Type": "application/json", "X-Patchwise-Event": d["event"], "X-Patchwise-Delivery": d["delivery_id"], "X-Patchwise-Signature": sig}, @@ -592,13 +712,51 @@ class AgentStudio: sent += 1 else: self.db.update("agent_callbacks", "id", d["id"], attempts=n, status_code=code, error=err, next_at=_later(60 * 2 ** (n - 1))) + self.bury_dead() return sent + def bury_dead(self) -> list[str]: + """Events that ran out of tries (six sends, or 20 pickups without a confirmation) become dead letters: kept, + audited, shown under Callbacks and told to the admins in one notification. An admin sends one again (requeue).""" + rows = self.db.q("SELECT * FROM agent_callbacks WHERE delivered_at IS NULL AND dead_at IS NULL AND superseded_by IS NULL " + "AND ((url<>? AND attempts>=?) OR (url=? AND attempts>=? AND next_at<=?)) ORDER BY id", + (PULL, MAX_ATTEMPTS, PULL, MAX_PICKUPS, now_iso())) + for d in rows: + why = d.get("error") or (f"not confirmed after {d['attempts']} pickups" if d["url"] == PULL else "no answer") + self.db.update("agent_callbacks", "id", d["id"], dead_at=now_iso(), error=why) + self.svc.audit.append("agent_studio.dead_letter", actor="agent-studio", run_id=(self.cycle_for_id(d["cycle_id"]) or {}).get("run_id"), + summary=f"{d['delivery_id']} {d['event']} not delivered after {d['attempts']} tries: {why}"[:300], + payload={"delivery_id": d["delivery_id"], "client_id": d["client_id"], "cycle_id": d["cycle_id"], + "event": d["event"], "attempts": d["attempts"], "error": why[:300]}) + if rows: + from . import notify + run_ids = {(self.cycle_for_id(d["cycle_id"]) or {}).get("run_id") for d in rows} + run = self.db.get_run(next(iter(run_ids))) if len(run_ids) == 1 and None not in run_ids else None + notify.get(self.svc).emit("agent_studio.dead_letter", run, count=len(rows), events=sorted({d["event"] for d in rows})) + return [d["delivery_id"] for d in rows] + + def requeue(self, delivery_id: str, actor: str) -> dict: + """An admin sends an event again (a dead letter, or one still retrying): its tries start over, same delivery_id.""" + d = self.db.one("SELECT * FROM agent_callbacks WHERE delivery_id=?", (delivery_id,)) + if not d: + raise AgentStudioError("NO_DELIVERY", f"no callback {delivery_id}", 404) + if d.get("delivered_at"): + raise AgentStudioError("ALREADY_DELIVERED", f"{delivery_id} was delivered at {d['delivered_at']}", 409) + self.db.update("agent_callbacks", "id", d["id"], attempts=0, next_at=now_iso(), dead_at=None, superseded_by=None, error=None) + self.svc.audit.append("agent_studio.requeued", actor=actor, run_id=(self.cycle_for_id(d["cycle_id"]) or {}).get("run_id"), + summary=f"{delivery_id} {d['event']}", payload={"delivery_id": delivery_id, "event": d["event"], + "was_dead": bool(d.get("dead_at"))}) + return self.delivery(delivery_id) + + def cycle_for_id(self, cycle_id: str | None) -> dict | None: + return self.db.one("SELECT * FROM agent_cycles WHERE cycle_id=?", (cycle_id,)) if cycle_id else None + def claim(self, client_id: str, limit: int = 5, cycle_id: str | None = None) -> dict: """The pull client's waiting events, oldest first (one cycle's, when cycle_id is given). Each is held for LEASE_S; one not confirmed with ack() by then is handed out again.""" limit = max(1, min(int(limit or 5), 20)) - where, args = "client_id=? AND url=? AND delivered_at IS NULL AND attempts < ? AND next_at <= ?", [client_id, PULL, MAX_PICKUPS, now_iso()] + where, args = ("client_id=? AND url=? AND delivered_at IS NULL AND dead_at IS NULL AND superseded_by IS NULL AND attempts < ? " + "AND next_at <= ?"), [client_id, PULL, MAX_PICKUPS, now_iso()] if cycle_id: where, args = where + " AND cycle_id=?", args + [cycle_id] rows = self.db.q(f"SELECT * FROM agent_callbacks WHERE {where} ORDER BY id LIMIT ?", (*args, limit + 1)) @@ -611,28 +769,55 @@ class AgentStudio: return {"events": out, "count": len(out), "more": len(rows) > limit, "confirm_within_s": LEASE_S} def ack(self, client_id: str, delivery_ids: list[str]) -> dict: - """Confirms picked-up events: they are not handed out again. Ids of other clients or unknown ids are ignored.""" + """Confirms picked-up events: they are not handed out again. Ids of other clients or unknown ids are ignored. A + confirmation that arrives late (the event became a dead letter meanwhile) still counts.""" done = [] for did in dict.fromkeys(str(x) for x in delivery_ids or []): d = self.db.one("SELECT id FROM agent_callbacks WHERE delivery_id=? AND client_id=? AND url=? AND delivered_at IS NULL", (did, client_id, PULL)) if d: - self.db.update("agent_callbacks", "id", d["id"], delivered_at=now_iso(), status_code=200, error=None) + self.db.update("agent_callbacks", "id", d["id"], delivered_at=now_iso(), status_code=200, error=None, dead_at=None) done.append(did) return {"confirmed": done, "count": len(done)} - def deliveries(self, limit: int = 50) -> list[dict]: - return [{k: (_j(v) if k == "payload" else v) for k, v in r.items()} - for r in self.db.q("SELECT * FROM agent_callbacks ORDER BY id DESC LIMIT ?", (limit,))] + @staticmethod + def _delivery(r: dict) -> dict: + state = ("delivered" if r.get("delivered_at") else "dead" if r.get("dead_at") else "superseded" if r.get("superseded_by") + else "retrying" if r.get("attempts") and r.get("url") != PULL else "picked_up" if r.get("attempts") else "queued") + return {**{k: (_j(v) if k == "payload" else v) for k, v in r.items()}, "state": state} + + def deliveries(self, limit: int = 50, state: str | None = None) -> list[dict]: + """The callbacks, newest first; state "dead" lists only the dead letters (up to 500, however old).""" + if state == "dead": + rows = self.db.q("SELECT * FROM agent_callbacks WHERE dead_at IS NOT NULL AND delivered_at IS NULL ORDER BY id DESC LIMIT ?", + (max(limit, 500),)) + else: + rows = self.db.q("SELECT * FROM agent_callbacks ORDER BY id DESC LIMIT ?", (limit,)) + return [self._delivery(r) for r in rows] + + def dead_letters(self) -> int: + return int(self.db.one("SELECT COUNT(*) AS n FROM agent_callbacks WHERE dead_at IS NOT NULL AND delivered_at IS NULL")["n"]) + + def delivery(self, delivery_id: str) -> dict: + r = self.db.one("SELECT * FROM agent_callbacks WHERE delivery_id=?", (delivery_id,)) + if not r: + raise AgentStudioError("NO_DELIVERY", f"no callback {delivery_id}", 404) + return self._delivery(r) def watch_runs(self, runs) -> int: """Callbacks for each cycle whose run reached a new step: scripts_ready (waiting for approval), - failures_need_review, results, stopped. Idempotent: a step is reported once.""" + failures_need_review, results, stopped, paused (interrupted by a restart). Idempotent: a step is reported once. + A cycle is watched until its run cannot move on any more: a failed or interrupted run can be resumed, and the + cycle reports again when it does. A cycle whose run does not exist (yet) is left alone.""" queued = 0 - for c in self.db.q("SELECT * FROM agent_cycles WHERE last_status NOT IN ('completed','failed','killed','cancelled') OR last_status IS NULL"): + final = ",".join("?" * len(FINAL)) + for c in self.db.q(f"SELECT c.* FROM agent_cycles c JOIN runs r ON r.run_id=c.run_id " + f"WHERE (c.last_status IS NULL OR c.last_status NOT IN ({final})) " + f"AND (c.last_status IS NULL OR r.status<>c.last_status OR COALESCE(r.pending_gate,'')<>COALESCE(c.last_gate,''))", + FINAL): run = self.db.get_run(c["run_id"]) or {} status, gate = run.get("status"), run.get("pending_gate") - if (status, gate) == (c["last_status"], c["last_gate"]): + if not run or (status, gate) == (c["last_status"], c["last_gate"]): continue event, payload = None, {} if status == "waiting_approval" and gate == "approve_cases": @@ -651,7 +836,11 @@ class AgentStudio: elif status == "completed": event, payload = "results", self._results(c["run_id"], runs) elif status in STOPPED: - event, payload = "stopped", {"status": status, "reason": run.get("error")} + event, payload = "stopped", {"status": status, "reason": run.get("error"), "resumable": status == "failed"} + elif status in PAUSED: # not over: Astra restarted mid-run; an admin resumes it and the cycle reports on + event, payload = "paused", {"status": status, "resumable": True, + "reason": run.get("error") or "Astra restarted while this cycle's run was going. It continues " + "from where it stopped once it is resumed in Astra."} if event: self.queue(c["client_id"], c["callback_url"], event, {"run_id": c["run_id"], "correlation_id": c["correlation_id"], "links": self._links(c["run_id"]), **payload}, c["cycle_id"]) diff --git a/coworker/platform/fusion_catalog.py b/coworker/platform/fusion_catalog.py index ac77505603bae13fa2c5b07e0c2d127407434d89..8213d727e44e8cfa14cc1ee029a48155828ccf95 100644 --- a/coworker/platform/fusion_catalog.py +++ b/coworker/platform/fusion_catalog.py @@ -7,6 +7,13 @@ to sample and the placeholder key each becomes, used as {{pod..}} in its quarterly What's New (`readiness`: the guide's family and product on docs.oracle.com/en/cloud/saas/readiness, and the words that pick the area's rows from a guide shared by several areas; empty `match` = every row of the guide). +`regression` lists the standard regression and edge-case checks a senior functional tester runs on the area every +cycle, in business language, each with the process it belongs to ({"process": one of the area's `processes`, "check": +"Invoice without a supplier site is refused"}): happy paths, refusals, boundaries, duplicates, state changes, defaults +and searches. Only checks the area's own screens can show (a status, a field's value, a message, a search result); no +reports, batch jobs, setup changes or other products. A full regression run asks the AI model for one scenario per +check that no library scenario covers yet (graph/nodes/ai_scenarios.py). + Nothing here is pod-specific. A deployment can add or change areas without a code change with FPT_HOME/fusion_areas.json (a list in the same shape; an entry whose "code" matches replaces the built-in one). Resource names are the standard Fusion REST resources of /fscmRestApi/resources/11.13.18.05; a resource a pod does not have answers 404 and the area @@ -21,11 +28,50 @@ log = logging.getLogger("coworker.fusion_catalog") FSCM = "/fscmRestApi/resources/11.13.18.05" + +def _checks(process: str, *checks: str) -> list[dict]: + """Regression checks of one business process, in the catalog's shape.""" + return [{"process": process, "check": c} for c in checks] + + AREAS: list[dict] = [ {"code": "AP", "id": "payables", "name": "Payables", "probes": ["invoices", "suppliers"], "processes": ["Invoice entry", "Invoice validation and holds", "Invoice matching", "Credit memos", "Prepayments", "Payments"], "navigator": ["Payables > Invoices", "Payables > Payments"], "key_tasks": ["Create Invoice", "Manage Invoices", "Create Payment", "Manage Payments", "Submit Payment Process Request"], + "regression": [ + *_checks("Invoice entry", + "Standard invoice with one item line saves and gets an invoice number", + "Supplier site, payment terms and currency default from the supplier", + "Invoice without a supplier site is refused", + "Invoice without an invoice amount is refused", + "Duplicate invoice number for the same supplier is refused", + "Negative amount on a standard invoice is refused", + "Amount with more decimals than the invoice currency allows is refused or rounded", + "Accounting date in a closed period is refused", + "Cancel without saving leaves no invoice behind (a search by its number finds nothing)", + "Saved invoice is found by its number in Manage Invoices"), + *_checks("Invoice validation and holds", + "Invoice whose lines equal the header amount validates with no holds", + "Lines one cent short of the header amount put the invoice on a line variance hold", + "Changing the amount of a validated invoice makes it need revalidation", + "Canceled invoice shows status Canceled and cannot be validated again"), + *_checks("Invoice matching", + "Invoice matched to a purchase order takes the order's supplier and lines", + "Billing more than the ordered quantity puts the matched invoice on a quantity ordered hold", + "Invoice matched to an unknown or closed purchase order number is refused"), + *_checks("Credit memos", + "Credit memo with a negative amount saves and validates", + "Credit memo with a positive amount is refused"), + *_checks("Prepayments", + "Prepayment invoice saves with type Prepayment and validates", + "Applying more than the prepayment's available amount is refused"), + *_checks("Payments", + "Payment of a validated invoice is created and found in Manage Payments", + "Paying more than the invoice's unpaid amount is refused", + "Voided payment shows status Voided", + "Payment process request without a name or pay through date is refused") + ], "readiness": {"family": "erp", "product": "fins", "match": ["Payables", "Payment", "Supplier Invoice", "Invoice Imaging", "Withholding"]}, "test_data": [{"resource": "invoices", "order_by": "InvoiceId:desc", "key_field": "InvoiceId", "own_field": "InvoiceNumber", "fields": {"business_unit": "BusinessUnit", "supplier": "Supplier", "supplier_site": "SupplierSite", @@ -36,6 +82,36 @@ AREAS: list[dict] = [ "processes": ["Requisition entry", "Requisition approval", "Purchase order creation", "Change orders", "Receiving"], "navigator": ["Procurement > Purchase Requisitions", "Procurement > Purchase Orders"], "key_tasks": ["Create Order", "Manage Orders", "Manage Requisitions", "Manage Agreements"], + "regression": [ + *_checks("Requisition entry", + "Requisition with one noncatalog line saves with status Incomplete", + "Requisition line with zero quantity is refused", + "Requisition line with a negative price is refused", + "Need-by date in the past is refused or warned", + "Saved requisition is found by its number in Manage Requisitions"), + *_checks("Requisition approval", + "Submitted requisition shows status Pending approval", + "Requisition line without a charge account cannot be submitted", + "Withdrawn requisition returns to status Incomplete and can be changed"), + *_checks("Purchase order creation", + "Purchase order with one goods line saves; supplier site, currency and payment terms default from the supplier", + "Order without a supplier is refused", + "Order line with zero quantity is refused", + "Order line with a negative price is refused", + "Price with more decimals than allowed is refused or rounded", + "Order total equals quantity times price of its lines", + "Submitted order shows status Pending approval or Open", + "Cancel without saving leaves no draft order behind (a search finds nothing)", + "Order is found by its number in Manage Orders and an unknown number finds nothing"), + *_checks("Change orders", + "Change order raising a line quantity on an open order shows a new revision", + "Reducing an order line below the quantity already received is refused", + "Canceled order shows status Canceled", + "Canceled order cannot be changed"), + *_checks("Receiving", + "Receipt for an open order line shows the received quantity on the order", + "Receiving more than the ordered quantity plus tolerance is refused") + ], "readiness": {"family": "scm", "product": "proc", "match": []}, "test_data": [{"resource": "purchaseOrders", "order_by": "POHeaderId:desc", "fields": {"business_unit": "ProcurementBU", "supplier": "Supplier", "supplier_site": "SupplierSite", @@ -46,6 +122,36 @@ AREAS: list[dict] = [ "processes": ["Transaction entry", "Credit memos", "Receipts", "Receipt application", "Customer statements"], "navigator": ["Receivables > Billing", "Receivables > Accounts Receivable"], "key_tasks": ["Create Transaction", "Manage Transactions", "Create Receipt", "Manage Receipts"], + "regression": [ + *_checks("Transaction entry", + "Invoice with one line completes and shows status Complete", + "Bill-to site, payment terms and currency default from the customer and transaction type", + "Transaction without a customer is refused", + "Transaction without a transaction type is refused", + "Completing a transaction without lines is refused", + "Duplicate transaction number for the same transaction source is refused", + "Line amount equals quantity times unit price", + "Accounting date in a closed period is refused", + "Completed transaction must be made incomplete before its lines can change", + "Saved transaction is found by its number in Manage Transactions"), + *_checks("Credit memos", + "Credit memo against a completed invoice reduces its balance due", + "Crediting more than the invoice's balance due is refused", + "Credit memo line with a positive amount is refused"), + *_checks("Receipts", + "Standard receipt with a receipt method saves and shows status Unapplied", + "Receipt without a receipt method or amount is refused", + "Receipt with a zero or negative amount is refused", + "Reversed receipt shows status Reversed", + "Duplicate receipt number for the same customer and date is refused or warned"), + *_checks("Receipt application", + "Receipt applied in full to an invoice closes the invoice's balance due", + "Applying more than the receipt's unapplied amount is refused", + "Partial application leaves the rest of the receipt unapplied", + "Unapplying a receipt restores the invoice's balance due"), + *_checks("Customer statements", + "Search by customer in Manage Transactions lists that customer's open transactions with their balance") + ], "readiness": {"family": "erp", "product": "fins", "match": ["Receivables", "Collections", "Collector", "Billing", "Customer Payments", "Receipt"]}, "test_data": [{"resource": "receivablesInvoices", "order_by": "CustomerTransactionId:desc", "fields": {"business_unit": "BusinessUnit", "customer": "BillToCustomerName", "transaction_type": "TransactionType", @@ -56,6 +162,32 @@ AREAS: list[dict] = [ "processes": ["Journal entry", "Journal approval and posting", "Period close", "Account inquiry"], "navigator": ["General Accounting > Journals", "General Accounting > Period Close"], "key_tasks": ["Create Journal", "Manage Journals", "Manage Accounting Periods"], + "regression": [ + *_checks("Journal entry", + "Balanced journal with one debit and one credit line saves", + "Unbalanced journal (debits not equal to credits) is refused", + "One-cent difference between debits and credits is refused", + "Journal without a category is refused", + "Line with both a debit and a credit amount is refused", + "Line with an invalid or disabled account combination is refused", + "Accounting period defaults from the accounting date", + "Journal with an accounting date in a closed period is refused", + "Amount with more decimals than the currency allows is refused or rounded", + "Foreign currency journal defaults a conversion rate type and needs a rate", + "Journal is found by its batch name in Manage Journals and an unknown name finds nothing"), + *_checks("Journal approval and posting", + "Posted journal shows status Posted", + "Posted journal cannot be edited or deleted", + "Reversing a posted journal creates its reversal journal", + "Reversing the same journal twice is refused", + "Journal that needs approval shows an approval status after Post", + "Unposted journal can be deleted and is no longer found"), + *_checks("Period close", + "Manage Accounting Periods shows the ledger's periods with their statuses", + "Journal in a period with status Future Entry saves but cannot be posted"), + *_checks("Account inquiry", + "Searching journals by account finds the posted journal lines") + ], "readiness": {"family": "erp", "product": "fins", "match": ["General Ledger", "Ledger", "Intercompany", "Financial Reporting", "Period Close", "Subledger Accounting", "Budgetary Control", "Journal"]}, "test_data": [{"resource": "ledgersLOV", "fields": {"ledger": "Name"}}, {"resource": "journalBatches", "order_by": "JeBatchId:desc", @@ -64,29 +196,150 @@ AREAS: list[dict] = [ "processes": ["Expense entry", "Expense report approval", "Expense audit", "Reimbursement"], "navigator": ["Me > Expenses"], "key_tasks": ["Create Expense Report", "Create Report", "Manage Expense Reports"], + "regression": [ + *_checks("Expense entry", + "Expense report with one expense item saves with status Saved", + "Expense item without an expense type is refused", + "Expense item without an amount is refused", + "Expense item with a zero or negative amount is refused", + "Expense date in the future is refused", + "Expense older than the policy allows is flagged as a policy violation", + "Amount over the expense type's limit shows a policy warning", + "Expense in a foreign currency gets a conversion rate and reimbursable amount", + "Reimbursement currency defaults to the person's currency", + "Itemized expense lines must add up to the expense amount", + "Itemization one cent off the expense amount is refused", + "Report total equals the sum of its expense items", + "The same expense entered twice is flagged as a possible duplicate", + "Purpose longer than the field allows is refused or cut"), + *_checks("Expense report approval", + "Submitted report shows status Pending manager approval", + "Report without a purpose cannot be submitted", + "Withdrawn report returns to status Saved and can be changed"), + *_checks("Expense audit", + "Policy violation needs a justification before the report can be submitted", + "Expense that needs a receipt cannot be submitted without one or a missing receipt justification"), + *_checks("Reimbursement", + "Report is found by its number in Manage Expense Reports with its reimbursable amount") + ], "readiness": {"family": "erp", "product": "fins", "match": ["Expense"]}, "test_data": [{"resource": "expenseReports", "order_by": "ExpenseReportId:desc", "fields": {"currency": "ReimbursementCurrencyCode"}}]}, {"code": "FA", "id": "assets", "name": "Fixed Assets", "probes": ["fixedAssets"], "processes": ["Asset additions", "Asset adjustments", "Depreciation", "Retirements"], "navigator": ["Fixed Assets > Assets"], + "regression": [ + *_checks("Asset additions", + "Asset added with a category and cost saves and gets an asset number", + "Book, depreciation method and life default from the asset category", + "Asset without a category is refused", + "Asset without a cost is refused", + "Asset without an assignment (location and expense account) is refused", + "Date placed in service in the future is refused", + "Asset with zero units is refused", + "Duplicate tag number is refused", + "Asset is found by its number in Manage Assets and an unknown number finds nothing"), + *_checks("Asset adjustments", + "Cost adjustment changes the asset's current cost", + "Transfer to a new location shows the new assignment", + "Transferring more units than the asset has is refused"), + *_checks("Depreciation", + "Salvage value greater than the cost is refused", + "Asset with Depreciate switched off shows no depreciation"), + *_checks("Retirements", + "Full retirement shows the asset as retired", + "Retiring more than the asset's cost or units is refused", + "Retirement date before the date placed in service is refused", + "Adjusting a fully retired asset is refused") + ], "readiness": {"family": "erp", "product": "fins", "match": ["Assets", "Asset "]}, "test_data": [{"resource": "fixedAssets", "order_by": "AssetId:desc", "fields": {"book": "BookTypeCode", "category": "AssetCategory"}}]}, {"code": "CM", "id": "cash-management", "name": "Cash Management", "probes": ["cashBankAccounts", "cashBankStatements"], "processes": ["Bank statements", "Reconciliation", "Cash positioning"], "navigator": ["Cash Management > Bank Statements and Reconciliation"], "key_tasks": ["Create Bank Statement", "Manage Bank Statements", "Manage Reconciliation Exceptions", "Create External Cash Transaction"], + "regression": [ + *_checks("Bank statements", + "Manual bank statement with one line saves for a bank account", + "Statement without a bank account is refused", + "Statement without a statement number or statement date is refused", + "Duplicate statement number for the same bank account is refused", + "Closing balance one cent off the opening balance plus lines is refused or flagged", + "Statement line without an amount or transaction type is refused", + "Statement line with a zero amount is refused", + "Statement date in the future is refused", + "Statement is found by its number in Manage Bank Statements and an unknown number finds nothing"), + *_checks("Reconciliation", + "Statement line manually reconciled to a matching transaction shows status Reconciled", + "Reconciling a line to a transaction of a different amount is refused", + "Unreconciling a reconciled line returns it to Unreconciled", + "Reconciliation exceptions search lists the unreconciled lines of a statement", + "External cash transaction saves with status Unreconciled", + "External transaction without an amount, date or bank account is refused", + "External transaction with a negative amount is refused"), + *_checks("Cash positioning", + "External transaction takes the bank account's currency", + "Bank account search finds the account with its currency") + ], "readiness": {"family": "erp", "product": "fins", "match": ["Cash Management", "Cash Processing", "Bank Statement", "Cash Positioning", "Reconciliation"]}, "test_data": [{"resource": "cashBankAccounts", "fields": {"bank_account": "BankAccountName"}}]}, {"code": "PPM", "id": "projects", "name": "Project Management", "probes": ["projects"], "processes": ["Project creation", "Project costing", "Project billing"], "navigator": ["Projects > Project Financial Management"], "key_tasks": ["Create Project", "Manage Projects", "Manage Project Costs"], + "regression": [ + *_checks("Project creation", + "Project created from a template saves with status Unapproved", + "Project without a name or number is refused", + "Duplicate project number or name is refused", + "Finish date before the start date is refused", + "Business unit, organization and currency default from the template", + "Project name longer than the field allows is refused or cut", + "Task with dates outside the project's dates is refused", + "Changing the status to Active is saved and shown", + "Project is found by its number in Manage Projects and an unknown number finds nothing"), + *_checks("Project costing", + "Miscellaneous cost on a chargeable task of an active project saves", + "Cost on a task that is not chargeable is refused", + "Cost with an expenditure date outside the task's dates is refused", + "Cost with a zero quantity is refused", + "Cost on a closed project is refused", + "Cost without an expenditure type is refused", + "Search by project in Manage Project Costs lists the project's costs"), + *_checks("Project billing", + "Billable flag defaults from the task on a new cost", + "Cost on a task that is not billable shows as not billable") + ], "readiness": {"family": "erp", "product": "ppm", "match": []}, "test_data": [{"resource": "projects", "order_by": "ProjectId:desc", "fields": {"business_unit": "OwningOrganizationName"}}]}, {"code": "OM", "id": "order-management", "name": "Order Management", "probes": ["salesOrdersForOrderHub"], "processes": ["Sales order entry", "Order fulfilment", "Returns"], "navigator": ["Order Management > Order Management"], "key_tasks": ["Create Order", "Manage Orders"], + "regression": [ + *_checks("Sales order entry", + "Order with one line submits and shows status Processing", + "Draft order saves with status Draft", + "Bill-to, ship-to and payment terms default from the customer", + "Order without a customer is refused", + "Submitting an order without lines is refused", + "Line with a zero or negative quantity is refused", + "Decimal quantity for an item sold in whole units is refused", + "Line amount equals quantity times the price list price", + "Requested ship date in the past is refused or warned", + "Duplicate customer purchase order number is warned", + "Order is found by its number in Manage Orders and an unknown number finds nothing", + "Copying an order creates a new draft with the same lines"), + *_checks("Order fulfilment", + "Hold applied to an order shows the hold on the order", + "Releasing the hold removes it from the order", + "Canceling a submitted order shows status Canceled", + "Canceling a shipped line is refused", + "Revising a submitted order's quantity creates a new order version"), + *_checks("Returns", + "Return line referencing an original order line saves", + "Returning more than the shipped quantity is refused", + "Return without a return reason is refused") + ], "readiness": {"family": "scm", "product": "order", "match": []}, "test_data": [{"resource": "salesOrdersForOrderHub", "order_by": "HeaderId:desc", "fields": {"business_unit": "BusinessUnitName", "customer": "BuyingPartyName"}}]}, @@ -94,11 +347,36 @@ AREAS: list[dict] = [ "processes": ["Item setup", "Transfers", "Cycle counts", "Receipts into stock"], "navigator": ["Supply Chain Execution > Inventory Management (Classic)", "Supply Chain Execution > Inventory Management"], "key_tasks": ["Create Miscellaneous Transaction", "Manage Item Quantities", "Create Transfer Order"], + "regression": [ + *_checks("Receipts into stock", + "Miscellaneous receipt into a subinventory increases the on-hand quantity", + "Miscellaneous transaction without an item, subinventory or quantity is refused", + "Miscellaneous transaction with a zero quantity is refused", + "Lot-controlled item without a lot number is refused", + "Serial-controlled item needs as many serial numbers as the quantity", + "Transaction date in a closed inventory period is refused", + "Quantity with more decimals than the unit of measure allows is refused or rounded", + "Locator-controlled subinventory without a locator is refused"), + *_checks("Transfers", + "Miscellaneous issue larger than the on-hand quantity is refused", + "Subinventory transfer moves the quantity from one subinventory to the other", + "Transfer to the same subinventory and locator is refused", + "Transfer order with one line saves and is found again", + "Transfer order without a destination organization is refused"), + *_checks("Cycle counts", + "Manage Item Quantities shows on-hand and available quantity by subinventory", + "Item quantity search for an unknown item finds nothing", + "Available quantity is the on-hand quantity less reservations"), + *_checks("Item setup", + "Unit of measure defaults from the item on a transaction", + "Transaction for an item not assigned to the organization is refused", + "Item is found by its number in Manage Item Quantities") + ], "readiness": {"family": "scm", "product": "inv", "match": []}, "test_data": [{"resource": "inventoryOrganizations", "fields": {"organization": "OrganizationCode"}}]}, ] -KEYS = ("code", "id", "name", "probes", "processes", "navigator", "test_data", "readiness", "words") +KEYS = ("code", "id", "name", "probes", "processes", "navigator", "key_tasks", "test_data", "readiness", "words", "regression") # what people call each area in a request ("start a run of Payables"), besides its name and code WORDS: dict[str, tuple[str, ...]] = { diff --git a/coworker/platform/migrations/026_agent_studio_delivery_contract.sql b/coworker/platform/migrations/026_agent_studio_delivery_contract.sql new file mode 100644 index 0000000000000000000000000000000000000000..8aabca590a2ff74ef7164953f86f2c24bfbaf7b8 --- /dev/null +++ b/coworker/platform/migrations/026_agent_studio_delivery_contract.sql @@ -0,0 +1,9 @@ +-- 026: the Agent Studio contract made safe to repeat (docs/AGENT_STUDIO.md). +-- agent_cycles.idempotency_key: a start sent again with the same Idempotency-Key header returns the cycle it made. +-- agent_callbacks.dead_at: an event that ran out of tries (push or pull) is kept as a dead letter for an admin to send again. +-- agent_callbacks.superseded_by: a "paused" event not delivered yet is dropped once a newer event of its cycle is queued. +ALTER TABLE agent_cycles ADD COLUMN idempotency_key TEXT; +CREATE INDEX IF NOT EXISTS agent_cycles_client_correlation ON agent_cycles (client_id, correlation_id); +CREATE INDEX IF NOT EXISTS agent_cycles_client_idempotency ON agent_cycles (client_id, idempotency_key); +ALTER TABLE agent_callbacks ADD COLUMN dead_at TEXT; +ALTER TABLE agent_callbacks ADD COLUMN superseded_by TEXT; diff --git a/coworker/platform/notify.py b/coworker/platform/notify.py index 306c999bd99a528a762b37fd8395721f48a9bc0b..7d0e558d9376316dfa3b0086532101ade5f4db11 100644 --- a/coworker/platform/notify.py +++ b/coworker/platform/notify.py @@ -54,6 +54,7 @@ COWORKER = { "run.failed": "Astra", "run.stopped": "Astra", "defect.created": "Triage", + "agent_studio.dead_letter": "Astra", "test": "Astra", } DECISION_WORDS = {"GO": "Ready", "NO-GO": "Not ready", "HELD": "Held"} @@ -367,6 +368,11 @@ class Notifier: if kind == "run.stopped": how = "by the emergency stop" if run.get("status") == "killed" else "by a person" return f"{name} was stopped", f"The test run was stopped {how}. Nothing more runs for it.", f"/runs/{rid}" + if kind == "agent_studio.dead_letter": + n, events = int(extra.get("count") or 1), ", ".join(str(e).replace("_", " ") for e in extra.get("events") or []) + return (f"{n} event(s) could not be delivered to Oracle Fusion", + f"Astra gave up on {events or 'them'} after every retry. Open Agent Studio, Callbacks, to see why and send " + f"them again.", "/agent-studio") if kind == "defect.created": tid, case = extra.get("ticket_id") or "", extra.get("case_id") or "" return (f"Defect {tid} raised", f"A person confirmed a real defect in {case} ({name}).".replace(" ()", ""), diff --git a/coworker/platform/preflight.py b/coworker/platform/preflight.py index c14170f229b75ccde313c69f95398438ceaafdf2..7c396dd5e698420d219e0ad5b29197cd28c70921 100644 --- a/coworker/platform/preflight.py +++ b/coworker/platform/preflight.py @@ -1,11 +1,24 @@ """Pre-flight: before a Fusion run starts its browsers, the things it needs are checked in seconds, so a run that cannot work stops with the reason instead of spending its browser time failing. -Checks, read-only: the remote browser runner answers and has the scenario files its step specs read (tests/cases); the -pod accepts the test user (the pod's connection test); every area of the run has test data. Each result is -{name, ok, detail}; `problems` lists the failed ones' details.""" +Checks, read-only: the remote browser runner answers, has the scenario files its step specs read (tests/cases) and runs +the same commit as this server when both know theirs; the pod accepts the test user (the pod's connection test); every +area of the run has test data (a warning only). A busy runner is information, not a stop: the run waits for it. Each +result is {name, ok, detail}; `problems` lists the failed ones' details.""" from __future__ import annotations +import re + +from ..config import server_commit + +COMMIT = re.compile(r"[0-9a-f]{7,40}") + + +def _same_commit(a: str, b: str) -> bool: + """Two commit ids name the same commit: one is a prefix of the other (sync.sh writes a 12-character short id).""" + n = min(len(a), len(b)) + return n >= 7 and a[:n] == b[:n] + def runner_check(svc) -> dict | None: """The remote runner's /healthz, or None when browsers run on this server.""" @@ -25,7 +38,22 @@ def runner_check(svc) -> dict | None: if h.get("cases") is False: return {"name": "runner", "ok": False, "detail": f"The browser runner at {base} has no scenario files (tests/cases): " "update it with deploy/runner/sync.sh."} - return {"name": "runner", "ok": True, "detail": f"Browser runner ready (version {h.get('version') or 'unknown'})."} + version = str(h.get("version") or "unknown").strip().lower() + mine = server_commit() + if mine and COMMIT.fullmatch(version) and not _same_commit(version, mine): + return {"name": "runner", "ok": False, "detail": f"The browser runner at {base} runs commit {version[:12]} but this server " + f"runs {mine[:12]}: update it with deploy/runner/sync.sh on {mine[:12]}."} + out = {"name": "runner", "ok": True, "detail": f"Browser runner ready (version {version})."} + if mine and not COMMIT.fullmatch(version): # installed some other way: it may run older scenarios or step code + out.update(warning=True, detail=f"Browser runner ready, but it does not say which commit it runs (this server runs " + f"{mine[:12]}): update it with deploy/runner/sync.sh.") + if h.get("busy"): # one browser job at a time: the run waits for it (remote_runner_busy_wait_minutes), not fails + try: + wait = f"up to {int(svc.cfg.remote_runner_busy_wait_minutes)} minutes" + except (TypeError, ValueError): + wait = "for a while" + out.update(busy=True, detail=out["detail"] + f" It is busy with another job right now: this run waits for it ({wait}).") + return out def check(svc, pod_id: int, run_id: str, areas: list[str]) -> list[dict]: @@ -40,9 +68,11 @@ def check(svc, pod_id: int, run_id: str, areas: list[str]) -> list[dict]: out.append(failed or {"name": "fusion", "ok": True, "detail": sign_in[-1]["detail"] if sign_in else "Oracle Fusion answers."}) cands = reg.test_data_candidates(pod_id, run_id) missing = [a for a in areas if not cands.get(a.upper())] - out.append({"name": "test_data", "ok": not missing, "detail": - f"No test data for {', '.join(missing)} on this pod: run Discover on the Test environments page, or set it there." - if missing else f"Test data for {', '.join(areas)}."}) + # a warning, not a stop: an area with no records yet has no sampled data, and its scenarios that use no pod value + # can still pass; the ones that need one fail with the same message + out.append({"name": "test_data", "ok": True, "warning": bool(missing), "detail": + f"No test data for {', '.join(missing)} on this pod: scenarios that need it will fail. Run Discover on the Test " + "environments page, or set it there." if missing else f"Test data for {', '.join(areas)}."}) return out diff --git a/coworker/platform/statesync.py b/coworker/platform/statesync.py index d790fb8113da8e3d653e5030e4cd6d3b706ab5ba..e63a85ce565db5e7ba46b2fcb93bf37180f69948 100644 --- a/coworker/platform/statesync.py +++ b/coworker/platform/statesync.py @@ -221,20 +221,25 @@ class Syncer: self._stop = threading.Event() self._wake = threading.Event() # soon(): save now instead of at the next interval self._reason = "changed" + # soon() was asked: push even when the signature looks saved. A save that was uploading while the event wrote + # records a signature that already includes the write its archive does not hold, so the signature alone would skip it + self._dirty = False self._lock = threading.Lock() # one save at a time (the loop, soon(), an administrator's save, shutdown) self._thread: threading.Thread | None = None self.last_error: str | None = None self.last_error_at: str | None = None - def tick(self, reason: str = "changed") -> bool: + def tick(self, reason: str = "changed", force: bool = False) -> bool: with self._lock: + dirty, self._dirty = self._dirty, False try: - if signature(self.svc) == self.svc.extra.get("state_signature"): + if not (force or dirty) and signature(self.svc) == self.svc.extra.get("state_signature"): return False push(self.svc, reason) self.last_error = None return True except Exception as e: # noqa: BLE001 - never take the application down because a save failed + self._dirty = self._dirty or dirty # the asked-for save did not happen: still owed self.last_error = f"{type(e).__name__}: {str(e)[:200]}" self.last_error_at = now_iso() log.warning("state save failed: %s", self.last_error) @@ -244,6 +249,7 @@ class Syncer: """Save as soon as possible: something a restart must not lose has just finished (a screen read, a run that now waits for a person or has ended). Only such moments call it, so the bucket's request budget still holds.""" self._reason = reason + self._dirty = True self._wake.set() def start(self) -> None: @@ -268,7 +274,7 @@ class Syncer: _RUNNING = None self._stop.set() self._wake.set() - self.tick("shutdown") # one last save so a restart continues from here + self.tick("shutdown", force=True) # one last save so a restart continues from here _RUNNING: Syncer | None = None # the API process's saver, once started diff --git a/coworker/platform/step_writer.py b/coworker/platform/step_writer.py index da47245967f277ac9a6dfac8d94699ddd1ec734b..f912842e6876dd9620a537d8d3fecb3b3c71e250 100644 --- a/coworker/platform/step_writer.py +++ b/coworker/platform/step_writer.py @@ -71,6 +71,7 @@ def pod_placeholders(home=None) -> set[str]: AREA_TAGS = {"AP": "payables", "AR": "receivables", "GL": "general-ledger", "PO": "purchasing", "EXP": "expenses"} NUMBER_RE = re.compile(r"[$€£]?\d[\d,.]*\d|\d") # any figure in public notes: an amount or id to the leak check PH_RE = re.compile(r"\{\{\s*([^{}]*?)\s*\}\}") +MASK_RE = re.compile(r"<(?:EMAIL|AMOUNT|ID|NAME|SECRET)_\d+>") # the leak mask's placeholders (platform/redaction.py) SINGLE_BRACE_RE = re.compile(r"(? dict: + r = self.c.post("/api/agent-studio/clients", json={"name": name, "callback_url": "https://fusion.example/cb"}, headers=self.h["admin"]) + self.assertEqual(r.status_code, 201, r.text) + return r.json() + + def _row(self, client_id: str) -> dict: + return AgentStudio(self.svc).client_for_token(sign_token(self.svc, client_id)) + + def _fake_cycle(self, client_id: str, status: str) -> tuple[str, str]: + """A cycle whose run is a bare row the test moves from status to status (no graph behind it).""" + rid, cid = "t-" + secrets.token_hex(4), "cyc_" + secrets.token_hex(6) + self.svc.db.create_run({"run_id": rid, "created_by": "test", "trigger": "agent_studio", "modules": ["AP"], "include_p2": 0, + "playwright_mode": "stub", "inputs": {}, "status": status, "orchestrator": "langgraph", "pod_id": self.pod_id}) + self.svc.db.insert("agent_cycles", {"cycle_id": cid, "run_id": rid, "client_id": client_id, "test_data": "{}", + "data_approved_by": "X", "callback_url": "https://fusion.example/cb", "last_status": status, + "created_at": "2026-01-01T00:00:00+00:00", "updated_at": "2026-01-01T00:00:00+00:00"}) + return cid, rid + + def test_a_retried_start_returns_the_cycle_it_made(self): + h = {"Authorization": f"Bearer {self.token()}"} + body = {"test_data": TD, "data_approved_by": "Priya (Fusion QA)", "areas": ["AP"], "correlation_id": "wf-retry-1"} + runs = self.app.state.runs + made = [] + try: + first = self.c.post("/api/agent-studio/v1/cycles", json=body, headers=h) + self.assertEqual(first.status_code, 202, first.text) + made.append(first.json()["run_id"]) + again = self.c.post("/api/agent-studio/v1/cycles", json=body, headers=h) # Fusion retried: no second run + self.assertEqual(again.status_code, 202, again.text) + self.assertEqual(again.headers.get("idempotent-replayed"), "true") + self.assertIsNone(first.headers.get("idempotent-replayed")) + self.assertEqual(set(again.json()), set(first.json())) # the same shape + self.assertEqual((again.json()["cycle_id"], again.json()["run_id"]), (first.json()["cycle_id"], first.json()["run_id"])) + self.assertEqual(self.svc.db.one("SELECT COUNT(*) AS n FROM agent_cycles WHERE correlation_id='wf-retry-1'")["n"], 1) + runs.cancel(first.json()["run_id"], "test", "done") + # once that cycle is over, the same correlation_id starts a new one (a later week's workflow) + later = self.c.post("/api/agent-studio/v1/cycles", json=body, headers=h) + self.assertEqual(later.status_code, 202, later.text) + made.append(later.json()["run_id"]) + self.assertNotEqual(later.json()["cycle_id"], first.json()["cycle_id"]) + runs.cancel(later.json()["run_id"], "test", "done") + # an Idempotency-Key replays whatever became of its cycle + k = {**h, "Idempotency-Key": "fusion-req-77"} + nocorr = {x: v for x, v in body.items() if x != "correlation_id"} + one = self.c.post("/api/agent-studio/v1/cycles", json=nocorr, headers=k) + self.assertEqual(one.status_code, 202, one.text) + made.append(one.json()["run_id"]) + runs.cancel(one.json()["run_id"], "test", "done") + two = self.c.post("/api/agent-studio/v1/cycles", json=nocorr, headers=k) + self.assertEqual((two.status_code, two.json()["cycle_id"], two.headers.get("idempotent-replayed")), (202, one.json()["cycle_id"], "true")) + finally: + for rid in made: + if (self.svc.db.get_run(rid) or {}).get("status") not in ("cancelled", "completed", "failed"): + runs.cancel(rid, "test", "done") + + def test_a_cycle_row_is_written_before_its_run_and_saved_at_once(self): + studio = AgentStudio(self.svc) + client = self._row(self.client["client_id"]) + seen = {} + + class Runs: + def start(_, inputs, actor, trigger="manual", run_id=None): + seen["cycle"] = studio.cycle_for_run(run_id) # what the runner reads for the test data + seen["test_data"] = studio.test_data_for_run(run_id) + return run_id + + with mock.patch("coworker.platform.statesync.save_soon") as save: + cyc = studio.start_cycle(client, {"test_data": TD, "data_approved_by": "X", "areas": ["AP"]}, Runs()) + self.assertEqual(seen["cycle"]["cycle_id"], cyc["cycle_id"]) + self.assertEqual(seen["test_data"]["AP"]["supplier"][0], "Test Supplier A") + self.assertIn("agent studio cycle started", [c.args[0] for c in save.call_args_list]) + from coworker.api.runner import RunError + + class Refuses: + def start(_, inputs, actor, trigger="manual", run_id=None): + seen["refused"] = run_id + raise RunError("the pod check failed", "POD_CHECK_FAILED", 409) + + with self.assertRaises(AgentStudioError) as e: + studio.start_cycle(client, {"test_data": TD, "data_approved_by": "X", "areas": ["AP"], "correlation_id": "wf-refused"}, Refuses()) + self.assertEqual((e.exception.code, e.exception.status), ("POD_CHECK_FAILED", 409)) + self.assertIsNone(studio.cycle_for_run(seen["refused"])) # no cycle is left without its run + + def test_an_event_keeps_its_delivery_id(self): + studio = AgentStudio(self.svc) + cid = "cyc_" + secrets.token_hex(6) + first = studio.queue(self.client["client_id"], "https://fusion.example/cb", "scripts_ready", {"n": 1}, cid) + self.assertEqual(first, delivery_id_for(cid, "scripts_ready", 0)) + # a restart restored a snapshot taken before the event: the same step makes the same event, with the same id + self.svc.db.x("DELETE FROM agent_callbacks WHERE delivery_id=?", (first,)) + self.assertEqual(studio.queue(self.client["client_id"], "https://fusion.example/cb", "scripts_ready", {"n": 1}, cid), first) + # a later step of the same kind (the run resumed and asks again) is a new event + second = studio.queue(self.client["client_id"], "https://fusion.example/cb", "scripts_ready", {"n": 2}, cid) + self.assertNotEqual(second, first) + self.assertEqual(studio.delivery(second)["payload"]["delivery_id"], second) + + def test_an_interrupted_run_is_paused_and_the_cycle_reports_again_after_a_resume(self): + studio = AgentStudio(self.svc) + + class Runs: + def state(_, run_id): + return {} + + def gate_payload(_, run_id): + return {"pending": []} + + cid, rid = self._fake_cycle(self.client["client_id"], "running") + + def evs(): + return [d for d in studio.deliveries(500) if d["cycle_id"] == cid][::-1] + + self.svc.db.update_run(rid, status="interrupted") # recover() after a restart + studio.watch_runs(Runs()) + self.assertEqual([d["event"] for d in evs()], ["paused"]) + p = evs()[0]["payload"] + self.assertEqual((p["status"], p["resumable"]), ("interrupted", True)) + self.assertTrue(p["reason"]) + self.svc.db.update_run(rid, status="queued") # resume() + studio.watch_runs(Runs()) + self.svc.db.update_run(rid, status="failed", error="the browser stopped") + studio.watch_runs(Runs()) + self.assertEqual([d["event"] for d in evs()], ["paused", "stopped"]) + self.assertEqual(evs()[1]["payload"]["resumable"], True) + self.assertEqual(evs()[0]["state"], "superseded") # the paused event never arrives after the newer one + self.svc.db.update_run(rid, status="running", error=None) # a failed run resumed: the cycle is still watched + studio.watch_runs(Runs()) + self.svc.db.update_run(rid, status="completed") + studio.watch_runs(Runs()) + self.assertEqual([d["event"] for d in evs()], ["paused", "stopped", "results"]) + studio.watch_runs(Runs()) + self.assertEqual(len(evs()), 3) + + def test_an_event_that_runs_out_of_tries_is_a_dead_letter_an_admin_sends_again(self): + studio = AgentStudio(self.svc) + did = studio.queue(self.client["client_id"], "https://fusion.example/cb", "results", {"verdict": "Ready"}, "cyc_" + secrets.token_hex(6)) + self.svc.db.x("UPDATE agent_callbacks SET attempts=?, next_at='2000-01-01T00:00:00+00:00' WHERE delivery_id=?", (MAX_ATTEMPTS - 1, did)) + studio.deliver_due() + d = studio.delivery(did) + self.assertEqual((d["state"], d["attempts"]), ("dead", MAX_ATTEMPTS)) + self.assertTrue(d["dead_at"] and d["error"]) + self.assertTrue(self.svc.db.one("SELECT 1 AS x FROM audit_log WHERE kind='agent_studio.dead_letter' AND summary LIKE ?", (f"{did}%",))) + self.assertTrue(self.svc.db.one("SELECT 1 AS x FROM notify_events WHERE kind='agent_studio.dead_letter'")) + studio.deliver_due() # a dead letter is not sent again by itself + self.assertEqual(studio.delivery(did)["attempts"], MAX_ATTEMPTS) + listed = self.c.get("/api/agent-studio/deliveries?state=dead", headers=self.h["admin"]).json() + self.assertIn(did, [x["delivery_id"] for x in listed["items"]]) + self.assertGreaterEqual(listed["dead_letters"], 1) + self.assertEqual(self.c.get("/api/agent-studio/deliveries", headers=self.h["viewer"]).status_code, 403) + r = self.c.post(f"/api/agent-studio/deliveries/{did}/requeue", headers=self.h["admin"]) + self.assertEqual(r.status_code, 200, r.text) + self.assertEqual((r.json()["state"], r.json()["attempts"], r.json()["delivery_id"]), ("queued", 0, did)) + self.assertEqual(self.c.post("/api/agent-studio/deliveries/dlv_none/requeue", headers=self.h["admin"]).status_code, 404) + self.assertEqual(self.c.post(f"/api/agent-studio/deliveries/{did}/requeue", headers=self.h["consultant"]).status_code, 403) + + # pull: 20 pickups without a confirmation; a confirmation that comes late still counts + pull = self._new_client("Fusion pull pod") + self.c.put(f"/api/agent-studio/clients/{pull['client_id']}/delivery", json={"mode": "pull"}, headers=self.h["admin"]) + pid = studio.queue(pull["client_id"], None, "scripts_ready", {"count": 0}, "cyc_" + secrets.token_hex(6)) + self.svc.db.x("UPDATE agent_callbacks SET attempts=?, next_at='2000-01-01T00:00:00+00:00' WHERE delivery_id=?", (MAX_PICKUPS, pid)) + self.assertIn(pid, studio.bury_dead()) + self.assertEqual(studio.claim(pull["client_id"])["count"], 0) + self.assertEqual(studio.ack(pull["client_id"], [pid])["confirmed"], [pid]) + self.assertEqual(studio.delivery(pid)["state"], "delivered") + + def test_a_callback_is_never_signed_with_an_empty_key(self): + studio = AgentStudio(self.svc) + cl = self._new_client("Fusion pod without a key") + self.svc.vault.set(f"agent_studio.{cl['client_id']}.signing", "") + did = studio.queue(cl["client_id"], "https://fusion.example/cb", "results", {"verdict": "Ready"}, "cyc_" + secrets.token_hex(6)) + with mock.patch.object(self.svc.egress, "service_request", wraps=self.svc.egress.service_request) as sent: + studio.deliver_due() + self.assertFalse([c for c in sent.call_args_list if (c.kwargs.get("headers") or {}).get("X-Patchwise-Delivery") == did]) + d = studio.delivery(did) + self.assertIn("no signing key", d["error"]) + self.assertIsNone(d["delivered_at"]) + self.assertIsNone(d["status_code"]) + + def test_a_token_is_signed_and_needs_no_row(self): + cl = self._new_client("Fusion pod, tokens") + r = self.c.post("/oauth/token", data={"grant_type": "client_credentials", "client_id": cl["client_id"], "client_secret": cl["client_secret"]}) + tok = r.json()["access_token"] + self.assertTrue(tok.startswith("pwa_")) + self.svc.db.x("DELETE FROM agent_tokens") # a restart restored a snapshot older than the token + + def status(t): + return self.c.get("/api/agent-studio/v1/cycles/cyc_none", headers={"Authorization": f"Bearer {t}"}).status_code + + self.assertEqual(status(tok), 404) # accepted (the cycle does not exist) + self.assertEqual(status(tok[:-3] + ("AAA" if not tok.endswith("AAA") else "BBB")), 401) # forged + self.assertEqual(status(tok.replace(cl["client_id"], self.client["client_id"])), 401) # another client's id + self.assertEqual(status(sign_token(self.svc, cl["client_id"], now=1000)), 401) # expired + # a token issued before tokens were signed keeps working until it expires + legacy = "pwa_" + secrets.token_urlsafe(32) + self.svc.db.insert("agent_tokens", {"token_hash": _hash(legacy), "client_id": cl["client_id"], "scope": "patchwise.invoke", + "created_at": "2026-01-01T00:00:00+00:00", "expires_at": "2999-01-01T00:00:00+00:00"}) + self.assertEqual(status(legacy), 404) + old = "pwa_" + secrets.token_urlsafe(32) + self.svc.db.insert("agent_tokens", {"token_hash": _hash(old), "client_id": cl["client_id"], "scope": "patchwise.invoke", + "created_at": "2000-01-01T00:00:00+00:00", "expires_at": "2000-01-01T01:00:00+00:00"}) + self.assertEqual(status(old), 401) + # revoking the client ends its signed tokens at once + self.assertEqual(self.c.delete(f"/api/agent-studio/clients/{cl['client_id']}", headers=self.h["admin"]).status_code, 204) + self.assertEqual((status(tok), status(legacy)), (401, 401)) + def test_a_callback_that_fails_is_tried_again_later(self): studio = AgentStudio(self.svc) did = studio.queue(self.client["client_id"], "https://fusion.example/cb", "stopped", {"status": "failed"}) diff --git a/coworker/tests/test_area_user_passes.py b/coworker/tests/test_area_user_passes.py index 01efe7497099d814ca87ac775797df4aad1125b1..60b14a0be7e0eb2be081d32fc085d16e82200940 100644 --- a/coworker/tests/test_area_user_passes.py +++ b/coworker/tests/test_area_user_passes.py @@ -49,7 +49,11 @@ class TestAreaUserPasses(unittest.TestCase): "config": "playwright.fusion.config.ts", "cred_env": {}, "groups": execute.user_groups(Reg(), 1, "r", list(mods), mods, {})} events = [] - svc = SimpleNamespace(cfg=SimpleNamespace(remote_runner_url="", executor_backend="local"), + from coworker.config import Settings + knobs = {k: getattr(Settings.model_construct(), k) for k in ( + "fusion_chunk_scenarios", "fusion_workers", "fusion_scenario_minutes", "fusion_attempt_min_minutes", + "fusion_attempt_max_minutes")} + svc = SimpleNamespace(cfg=SimpleNamespace(remote_runner_url="", executor_backend="local", **knobs), db=SimpleNamespace(add_event=lambda *a: events.append(a[3]))) with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run): res = execute.run_planned(plan, svc) diff --git a/coworker/tests/test_preflight.py b/coworker/tests/test_preflight.py index 10a6e1fccf8ba2b2b02f5ade3ad089d38f68be92..7c52a03c90fd1915eeaeee6dc9ddc9c1b92907cc 100644 --- a/coworker/tests/test_preflight.py +++ b/coworker/tests/test_preflight.py @@ -54,11 +54,17 @@ class TestPreflight(unittest.TestCase): (svc_with(OSError("refused")), reg_with(), "does not answer"), (svc_with({"ok": False, "automation": True}), reg_with(), "not ready"), (svc_with(None), reg_with(sign_in_ok=False), "HTTP 401"), - (svc_with(None), reg_with(cands={}), "No test data for AP"), ] for svc, reg, needle in cases: self.assertTrue(any(needle in p for p in preflight.problems(self.run_check(svc, reg))), needle) + def test_missing_test_data_is_a_warning_not_a_stop(self): + res = self.run_check(svc_with(None), reg_with(cands={})) + self.assertEqual(preflight.problems(res), []) + td = next(r for r in res if r["name"] == "test_data") + self.assertTrue(td["warning"]) + self.assertIn("No test data for AP", td["detail"]) + def test_a_run_that_cannot_work_stops_before_any_browser(self): svc = mock.MagicMock() svc.fusion_pod_id.return_value = 2 diff --git a/coworker/tests/test_regression_checks.py b/coworker/tests/test_regression_checks.py new file mode 100644 index 0000000000000000000000000000000000000000..7028c2ccef520eeb61210975ac3898c4e4dfe289 --- /dev/null +++ b/coworker/tests/test_regression_checks.py @@ -0,0 +1,155 @@ +"""Regression (depth full): each area's standard regression and edge-case checks (fusion_catalog "regression") are asked +of the AI model, one scenario per check, in batches; checks a library scenario already covers are skipped, the number is +capped by FPT_FUSION_REGRESSION_CHECKS (0 = off), and every catalog area with screens has such a list.""" +from __future__ import annotations + +import unittest +from types import SimpleNamespace +from unittest import mock + +from coworker.config import Settings +from coworker.graph.nodes import ai_scenarios +from coworker.llm.base import Route +from coworker.platform import fusion_catalog + +SCREENS = [{"task": "Payables > Invoices > Create Invoice"}, {"task": "Payables > Invoices > Manage Invoices"}] +FR = Route.FRONTIER.value +WORDS = ["alpha", "bravo", "charlie", "delta", "echo", "foxtrot", "golf", "hotel", "india", "juliet", "kilo", "lima"] +CHECKS = [{"process": "Invoice entry", "check": f"Entry check {w}"} for w in WORDS] \ + + [{"process": "Payments", "check": f"Payment check {w}"} for w in WORDS[:6]] + + +def svc(checks=25): + return SimpleNamespace(cfg=SimpleNamespace(fusion_regression_checks=checks)) + + +def answer(*args, **kw): + """The fake model: one scenario per regression check asked, titled with the check's words.""" + return [{"title": a.split("regression check: ", 1)[1].split(" (one scenario", 1)[0], "task": SCREENS[0]["task"], + "designed_by": FR} for a in args[2]] + + +class TestRegressionChecks(unittest.TestCase): + def run_checks(self, checks=CHECKS, cap=25, titles=(), side_effect=answer): + notes, written = [], [] + design = mock.Mock(side_effect=side_effect) + with mock.patch.object(ai_scenarios.step_writer, "design_scenarios", design), \ + mock.patch.object(ai_scenarios, "_write_intents", lambda *a, **k: written.extend(a[3])), \ + mock.patch.object(ai_scenarios, "_note", lambda s, rid, text, **k: notes.append(text)): + ai_scenarios._design_regression_checks(svc(cap), "r", "AP", list(checks), SCREENS, list(titles), "", set(), [], []) + return design, written, notes + + def test_every_check_is_asked_in_batches(self): + design, written, notes = self.run_checks() + self.assertEqual(design.call_count, 3) # 18 checks, at most 8 per call + self.assertEqual([len(c.args[2]) for c in design.call_args_list], [8, 8, 2]) + self.assertEqual(design.call_args_list[0].kwargs["count"], 8) + self.assertTrue(design.call_args_list[0].args[2][0].startswith("Invoice entry: regression check: Entry check alpha")) + self.assertTrue(design.call_args_list[0].args[2][1].startswith("Payments: regression check: Payment check alpha")) # processes in turn + self.assertEqual(design.call_args_list[0].args[3], []) # the checks themselves, not the release's changes + self.assertEqual(len(written), 18) + later = design.call_args_list[1].kwargs["existing_titles"] + self.assertEqual(len(later), 8) # what was designed is not asked again + self.assertIn("AP: 18 regression check(s) designed: ", notes[-1]) + + def test_checks_the_library_covers_are_skipped(self): + design, written, _ = self.run_checks(titles=["Entry check delta", "payment check: foxtrot."]) + asked = [a for c in design.call_args_list for a in c.args[2]] + self.assertEqual(len(asked), 16) + self.assertFalse(any("Entry check delta " in a or "Payment check foxtrot " in a for a in asked)) + self.assertEqual(design.call_args_list[0].kwargs["existing_titles"], ["Entry check delta", "payment check: foxtrot."]) + + def test_the_cap_is_respected(self): + design, written, _ = self.run_checks(cap=5) + self.assertEqual(design.call_count, 1) + self.assertEqual(len(design.call_args.args[2]), 5) + self.assertEqual(len(written), 5) + + def test_zero_turns_it_off(self): + design, written, notes = self.run_checks(cap=0) + design.assert_not_called() + self.assertEqual((written, notes), ([], [])) + self.assertEqual(Settings().fusion_regression_checks, 25) + + def test_only_model_answers_are_kept_and_a_failure_is_a_note(self): + _, written, notes = self.run_checks(side_effect=lambda *a, **k: [{"title": "Fallback", "task": SCREENS[0]["task"], "designed_by": "baseline"}]) + self.assertEqual(written, []) + self.assertIn("no regression check was designed", notes[-1]) + design, written, notes = self.run_checks(side_effect=RuntimeError("down")) + self.assertEqual(design.call_count, 1) # stops at the first failure + self.assertIn("could not design regression checks", notes[-1]) + + def test_asked_only_at_depth_full(self): + """Through write_ai_scenarios: the catalog's checks are asked in a full run only.""" + def run(depth): + asks = [] + + def design(s, area, processes, *a, **k): + asks.extend(processes) + return [{"title": "First", "task": SCREENS[0]["task"], "designed_by": FR}] + reg = mock.Mock() + reg.area_screens.return_value = list(SCREENS) + reg.test_data_keys.return_value = [] + cfg = SimpleNamespace(fusion_ai_scenarios=4, fusion_ai_scenarios_max=8, fusion_regression_flows=0, + fusion_regression_checks=25, fusion_workers=1, fusion_ai_dry_run=False, home=None) + s = SimpleNamespace(cfg=cfg, db=None, vault=None, egress=None, audit=None, fusion_pod_id=lambda rid: 1, + router=SimpleNamespace(frontier_ready=lambda: True)) + state = {"run_id": "r", "depth": depth, "scope": {"modules": ["AP"]}, "playwright_mode": "stub"} + with mock.patch("coworker.platform.pods.PodRegistry", return_value=reg), \ + mock.patch("coworker.graph.nodes.research.scope_modules", return_value=["AP"]), \ + mock.patch.object(ai_scenarios.step_writer, "design_scenarios", design), \ + mock.patch.object(ai_scenarios.step_writer, "area_changes", return_value=[]), \ + mock.patch.object(ai_scenarios, "_write_intents", lambda *a, **k: None), \ + mock.patch.object(ai_scenarios, "_note", lambda *a, **k: None): + ai_scenarios.write_ai_scenarios(state, s, []) + return [a for a in asks if "regression check: " in a] + self.assertEqual(run("standard"), []) + self.assertEqual(len(run("full")), 25) + + +class TestCatalogRegression(unittest.TestCase): + def test_every_area_with_screens_has_its_regression_checks(self): + for a in fusion_catalog.AREAS: + if not a.get("navigator"): + continue + checks = a.get("regression") or [] + self.assertGreaterEqual(len(checks), 15, a["code"]) + self.assertLessEqual(len(checks), 30, a["code"]) + for c in checks: + self.assertIn(c["process"], a["processes"], f"{a['code']}: {c['check']}") + self.assertTrue(c["check"].strip(), a["code"]) + names = [c["check"].lower() for c in checks] + self.assertEqual(len(names), len(set(names)), f"{a['code']}: a check is listed twice") + + def test_an_override_keeps_the_built_in_checks(self): + import json + import tempfile + from pathlib import Path + home = Path(tempfile.mkdtemp()) + (home / "fusion_areas.json").write_text(json.dumps([{"code": "AP", "name": "Payables (client)", "probes": ["invoices"]}]), + encoding="utf-8") + self.assertEqual(fusion_catalog.by_code("AP", home)["regression"], fusion_catalog.by_code("AP")["regression"]) + + +if __name__ == "__main__": + unittest.main() + + +class TestScreenFocus(unittest.TestCase): + """Seen on a live AP run: given every screen read, the model put 8 of its 11 scenarios on Create Positive Pay File. + The general design now starts from the area's key screens and no screen takes more than PER_SCREEN scenarios.""" + + def test_key_screens_come_first_in_key_order(self): + screens = [{"task": t} for t in ("Payables > Payments > Create Positive Pay File", "Payables > Manage Invoices", + "Payables > Create Invoice", "Payables > Payments > Create Payment")] + got = ai_scenarios.key_screens(screens, ["Create Invoice", "Manage Invoices", "Create Payment", "Manage Payments"]) + self.assertEqual([s["task"] for s in got], ["Payables > Create Invoice", "Payables > Manage Invoices", + "Payables > Payments > Create Payment"]) + self.assertEqual(ai_scenarios.key_screens(screens, []), []) + + def test_no_screen_takes_more_than_its_share(self): + intents = [{"task": "Payables > Payments > Create Positive Pay File", "title": f"p{i}"} for i in range(8)] + intents += [{"task": "Payables > Create Invoice", "title": "c1"}] + got = ai_scenarios.spread(intents) + self.assertEqual(sum(1 for i in got if "Positive Pay" in i["task"]), ai_scenarios.PER_SCREEN) + self.assertEqual(got[-1]["title"], "c1") diff --git a/coworker/tests/test_runner_robust.py b/coworker/tests/test_runner_robust.py new file mode 100644 index 0000000000000000000000000000000000000000..e231c72c7fc7c82f7a94e047cce16ad3a21f8ff6 --- /dev/null +++ b/coworker/tests/test_runner_robust.py @@ -0,0 +1,542 @@ +"""The browser execution path survives long runs, restarts and a busy runner: a pass's time budget grows with its +scenarios and a big attempt runs in passes, so one pass that overruns loses only its own scenarios; a restarted server +follows the runner job it had started instead of starting another; a restarted runner fails the pass in seconds; a pass +that overruns cancels its job; a busy runner is waited for (and given up on after a bounded time); pre-flight names a +runner on another commit. The runner keeps its jobs' state on disk and stops an overrunning attempt gently.""" +from __future__ import annotations + +import io +import json +import shutil +import subprocess +import sys +import tempfile +import time as real_time +import unittest +import zipfile +from pathlib import Path +from types import SimpleNamespace +from unittest import mock + +import httpx + +from coworker.adapters import playwright as pwa +from coworker.adapters import remote_runner as R +from coworker.config import Settings +from coworker.graph.nodes import execute +from coworker.platform import preflight +from coworker.platform.failures import ExecutionError +from coworker.tests.test_remote_runner import load_server + +OLD_JOB, NEW_JOB = "job_0000000000aa", "job_0000000000bb" +TOKEN = "tok-" + "x" * 30 + + +def report(*ids: str) -> dict: + return {"suites": [{"title": f"{i}.spec.ts", "file": f"{i}.spec.ts", "specs": [ + {"title": f"{i} scenario", "file": f"{i}.spec.ts", "tags": [f"@{i}"], + "tests": [{"status": "expected", "results": [{"status": "passed", "attachments": []}]}]}]} for i in ids], "errors": []} + + +def bundle(*ids: str, ledger: str = '{"invoice":"TEST_1"}\n', with_report: bool = True) -> bytes: + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as z: + if with_report: + z.writestr("report.json", json.dumps(report(*(ids or ("AP-FUS-001",))))) + z.writestr("created.jsonl", ledger) + z.writestr("playwright.log", "[1/1]\n") + return buf.getvalue() + + +class Clock: + """Virtual time for the adapter: a sleep moves the clock instead of waiting.""" + + def __init__(self): + self.t = 1_000_000.0 + + def time(self): + return self.t + + def sleep(self, s): + self.t += max(float(s), 0.001) + + +class Runner: + """A fake runner behind the egress gate. `starts`: HTTP codes of successive job starts (the last repeats); `polls`: + successive status answers, a dict or an HTTP code (the last repeats).""" + + def __init__(self, starts=(202,), polls=({"state": "done", "exit_code": 0},), blob: bytes | None = None, new_id=NEW_JOB): + self.calls: list[tuple[str, str, dict | None]] = [] + self.starts, self.polls, self.blob, self.new_id = list(starts), list(polls), blob or bundle(), new_id + + @staticmethod + def _next(seq): + return seq.pop(0) if len(seq) > 1 else seq[0] + + 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): + assert kind == "remote_runner" and url.startswith(allowed_base) + path = url[len(allowed_base):] + self.calls.append((method, path, json_body)) + if method == "POST" and path in ("/v1/attempts", "/v1/screens"): + code = self._next(self.starts) + return httpx.Response(code, json={"id": self.new_id, "state": "running"} if code == 202 else {"error": "busy"}) + if path.endswith("/cancel"): + return httpx.Response(202, json={"state": "cancelling"}) + if path.endswith("/bundle"): + return httpx.Response(200, content=self.blob) + if path.endswith("/live"): + return httpx.Response(200, json={}) + ans = self._next(self.polls) + if isinstance(ans, int): + return httpx.Response(ans, json={"error": "no such attempt"}) + return httpx.Response(200, json=ans) + + def posts(self, suffix="/v1/attempts"): + return [b for m, p, b in self.calls if m == "POST" and p == suffix] + + def cancels(self): + return [p for m, p, _ in self.calls if p.endswith("/cancel")] + + +def cfg(**over): + base = {k: getattr(Settings.model_construct(), k) for k in ( + "fusion_chunk_scenarios", "fusion_workers", "fusion_scenario_minutes", "fusion_attempt_min_minutes", + "fusion_attempt_max_minutes", "remote_runner_busy_wait_minutes")} + return SimpleNamespace(**{"remote_runner_url": "", "executor_backend": "local", **base, **over}) + + +class Base(unittest.TestCase): + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.clock = Clock() + p = mock.patch.object(R, "time", self.clock) + p.start() + self.addCleanup(p.stop) + self.addCleanup(shutil.rmtree, self.tmp, True) + + def tearDown(self): + for d in (R.AUTOMATION / "results" / "runs").glob("fpt-rr-*"): + shutil.rmtree(d, ignore_errors=True) + + def remote(self, eg, *, attempt=0, tag="", timeout_s=1800, **kw): + return R.run_attempt_remote(eg, "https://runner.example", TOKEN, run_id="rr-1", ids=["AP-FUS-001"], attempt=attempt, + out_file=self.tmp / "attempt-0.json", cred_env={}, drafts_dir=None, library_dir=None, + overrides_file=None, log_dir=self.tmp, config="playwright.fusion.config.ts", poll_s=5, + timeout_s=timeout_s, tag=tag, **kw) + + +# ---------------------------------------------------------------------------------------------------------------- 1 +class TestTimeBudget(unittest.TestCase): + def test_the_budget_grows_with_the_scenarios_and_shrinks_with_workers(self): + c = cfg(fusion_workers=3, fusion_scenario_minutes=12, fusion_attempt_min_minutes=30, fusion_attempt_max_minutes=240) + self.assertEqual(execute.attempt_timeout_s(c, 1), 30 * 60) # the floor + self.assertEqual(execute.attempt_timeout_s(c, 12), (10 + 4 * 12) * 60) # 12 scenarios over 3 workers: 4 rounds + self.assertGreater(execute.attempt_timeout_s(c, 24), execute.attempt_timeout_s(c, 12)) + self.assertEqual(execute.attempt_timeout_s(c, 500), 240 * 60) # the ceiling + self.assertEqual(execute.attempt_timeout_s(c, 12, workers="1"), (10 + 12 * 12) * 60) # the pass's own workers count + self.assertEqual(execute.attempt_timeout_s(c, 12, workers="9"), (10 + 3 * 12) * 60) # Playwright runs at most 4 + + def test_a_big_attempt_runs_in_passes_each_with_its_own_budget(self): + calls = [] + + def fake_run(**kw): + calls.append((kw["ids"], kw["tag"], kw["timeout_s"], Path(kw["out_file"]).name)) + Path(kw["out_file"]).write_text(json.dumps(report(*kw["ids"])), encoding="utf-8") + return {"run_dir": f"run{kw['tag']}", "exit_code": 0} + + with tempfile.TemporaryDirectory() as d: + ids = [f"AP-FUS-{i:03d}" for i in range(1, 6)] + plan = plan_for(d, ids) + svc = SimpleNamespace(cfg=cfg(fusion_chunk_scenarios=2), db=SimpleNamespace(add_event=lambda *a: None)) + with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run): + res = execute.run_planned(plan, svc) + self.assertEqual([c[0] for c in calls], [ids[0:2], ids[2:4], ids[4:]]) + self.assertEqual([c[1] for c in calls], ["-c0", "-c1", "-c2"]) + self.assertEqual([c[2] for c in calls], [execute.attempt_timeout_s(svc.cfg, n) for n in (2, 2, 1)]) + merged = json.loads((Path(d) / "attempt-0.json").read_text()) + self.assertEqual(len(merged["suites"]), 5) + self.assertEqual(res["run_dirs"], ["run-c0", "run-c1", "run-c2"]) + + def test_one_overrunning_pass_loses_only_its_own_scenarios(self): + def fake_run(**kw): + if kw["tag"] == "-c1": + raise ExecutionError("The browser tests did not finish.", timed_out=True, minutes=30) + Path(kw["out_file"]).write_text(json.dumps(report(*kw["ids"])), encoding="utf-8") + return {"run_dir": f"run{kw['tag']}", "exit_code": 0} + + with tempfile.TemporaryDirectory() as d: + ids = ["AP-FUS-001", "AP-FUS-002", "AP-FUS-003", "AP-FUS-004"] + svc = SimpleNamespace(cfg=cfg(fusion_chunk_scenarios=2), db=SimpleNamespace(add_event=lambda *a: None)) + with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run): + res = execute.run_planned(plan_for(d, ids), svc) + self.assertEqual(res["lost_chunks"], [1]) + outs, counts = execute.outcomes(str(Path(d) / "attempt-0.json")) + self.assertEqual(outs, {"AP-FUS-001": "passed", "AP-FUS-002": "passed", "AP-FUS-003": "failed", "AP-FUS-004": "failed"}) + self.assertEqual(sorted(execute.failing_ids(str(Path(d) / "attempt-0.json"))), ["AP-FUS-003", "AP-FUS-004"]) + # the retry's results land on the timed-out entries when the attempts are merged + retry = Path(d) / "attempt-1.json" + retry.write_text(json.dumps(report("AP-FUS-003", "AP-FUS-004")), encoding="utf-8") + pwa.adopt_no_result([str(Path(d) / "attempt-0.json"), str(retry)]) + merged = execute.merge_attempts([str(Path(d) / "attempt-0.json"), str(retry)], Path(d) / "merged.json") + self.assertEqual(execute.outcomes(str(merged))[0]["AP-FUS-003"], "flaky") + # a resumed attempt reruns only the lost pass + again = [] + with mock.patch.object(execute.pw, "run_attempt", side_effect=lambda **kw: again.append(kw["tag"]) or fake_run( + **{**kw, "tag": "-ok"})): + execute.run_planned(plan_for(d, ids), svc) + self.assertEqual(again, ["-c1"]) + + def test_when_every_pass_overruns_the_attempt_fails_as_before(self): + def fake_run(**kw): + raise ExecutionError("did not finish", timed_out=True, minutes=30) + + with tempfile.TemporaryDirectory() as d: + svc = SimpleNamespace(cfg=cfg(fusion_chunk_scenarios=1), db=SimpleNamespace(add_event=lambda *a: None)) + with mock.patch.object(execute.pw, "run_attempt", side_effect=fake_run), self.assertRaises(ExecutionError): + execute.run_planned(plan_for(d, ["AP-FUS-001", "AP-FUS-002"]), svc) + + +def plan_for(d, ids, **over) -> dict: + return {"run_id": "rr-1", "attempt": 0, "ids": ids, "mode": "live", "out_file": str(Path(d) / "attempt-0.json"), + "stub_knobs": None, "drafts_dir": str(d), "library_dir": None, "overrides": None, "run_dir": str(d), "live_dir": None, + "config": "playwright.fusion.config.ts", "cred_env": {}, "groups": None, **over} + + +# ---------------------------------------------------------------------------------------------------------------- 2 +class TestReattach(Base): + def save_old(self, **over): + R._save_job(self.tmp, {"job_id": OLD_JOB, "base_url": "https://runner.example", "attempt": 0, "tag": "", + "pw_run_id": "fpt-rr-1-a0", "out_file": str(self.tmp / "attempt-0.json"), + "started": self.clock.t - 600, "timeout_s": 1800, **over}) + + def test_an_accepted_job_is_kept_in_the_run_folder_until_its_results_are_in(self): + eg = Runner(polls=[{"state": "running"}, {"state": "done", "exit_code": 0}]) + seen = [] + orig = R._follow + + def spy(*a, **kw): + seen.append(R.saved_job(self.tmp)) + return orig(*a, **kw) + + with mock.patch.object(R, "_follow", side_effect=spy): + self.remote(eg) + self.assertEqual((seen[0]["job_id"], seen[0]["pw_run_id"], seen[0]["timeout_s"]), (NEW_JOB, "fpt-rr-1-a0", 1800)) + self.assertIsNone(R.saved_job(self.tmp)) # collected: nothing left to follow + + def test_a_resumed_run_follows_the_job_it_had_started(self): + self.save_old() + eg = Runner(polls=[{"state": "running"}, {"state": "done", "exit_code": 0}]) + events = [] + res = self.remote(eg, on_event=events.append) + self.assertEqual(eg.posts(), []) # no second job on the runner + self.assertTrue(any(p == f"/v1/attempts/{OLD_JOB}/bundle" for _, p, _ in eg.calls)) + self.assertEqual(res["pw_run_id"], "fpt-rr-1-a0") + self.assertTrue((self.tmp / "created-test-data.jsonl").read_text().strip()) # its ledger is fetched for clean-up + self.assertIsNone(R.saved_job(self.tmp)) + self.assertTrue(any("again" in e for e in events)) + + def test_a_job_the_restarted_runner_does_not_know_is_started_again(self): + self.save_old() + eg = Runner(polls=[404, 404, {"state": "done", "exit_code": 0}]) + res = self.remote(eg) + self.assertEqual(len(eg.posts()), 1) + self.assertEqual(res["exit_code"], 0) + + def test_a_lost_job_is_started_again_and_its_ledger_kept(self): + self.save_old() + eg = Runner(polls=[{"state": "lost"}, {"state": "done", "exit_code": 0}], + blob=bundle(ledger='{"invoice":"TEST_LOST"}\n', with_report=False)) + real = eg.service_request + + def answer(*a, **kw): # the lost job's bundle has only its ledger; the new job's has a report + r = real(*a, **kw) + if a[2].endswith("/bundle"): + eg.blob = bundle(ledger='{"invoice":"TEST_NEW"}\n') + return r + eg.service_request = answer + self.remote(eg) + self.assertEqual(len(eg.posts()), 1) + ledger = (self.tmp / "created-test-data.jsonl").read_text() + self.assertIn("TEST_LOST", ledger) + self.assertIn("TEST_NEW", ledger) + + def test_a_saved_job_of_another_pass_is_stopped_so_it_frees_the_runner(self): + self.save_old(pw_run_id="fpt-rr-1-a0-c3", out_file=str(self.tmp / "attempt-0.c3.json")) + eg = Runner(polls=[{"state": "cancelled"}, {"state": "done", "exit_code": 0}]) + self.remote(eg) + self.assertEqual(eg.cancels(), [f"/v1/attempts/{OLD_JOB}/cancel"]) + self.assertEqual(len(eg.posts()), 1) + + def test_a_resumed_attempt_0_keeps_its_finished_passes(self): + (self.tmp / "attempt-0.c0.json").write_text("{}") + (self.tmp / "attempt-0.chunks.json").write_text(json.dumps({"ids": ["A"], "size": 1, "done": {}})) + self.assertTrue(execute.resumed_attempt(self.tmp)) + state = {"run_id": "rr-1", "test_cases": [], "playwright_mode": "stub"} + svc = mock.MagicMock() + svc.run_dir.return_value = self.tmp + svc.fusion_pod_id.return_value = None + with mock.patch.object(execute.liveview, "availability", return_value=(False, "")), \ + mock.patch.object(execute.ai_scenarios, "library_root", return_value=self.tmp): + execute.plan_attempt(state, svc) + self.assertTrue((self.tmp / "attempt-0.c0.json").exists()) # resumed: kept + (self.tmp / "attempt-0.chunks.json").unlink() + self.assertFalse(execute.resumed_attempt(self.tmp)) + execute.plan_attempt(state, svc) + self.assertFalse((self.tmp / "attempt-0.c0.json").exists()) # a fresh attempt 0 starts clean + self.save_old() + self.assertTrue(execute.resumed_attempt(self.tmp)) # a job still followed counts as a resume + + def test_cancelling_an_orphaned_run_stops_its_job_and_keeps_its_records(self): + self.save_old() + eg = Runner(polls=[{"state": "cancelled"}]) + svc = SimpleNamespace(cfg=SimpleNamespace(remote_runner_url="https://runner.example"), egress=eg, + vault=SimpleNamespace(get=lambda k: TOKEN), run_dir=lambda rid: self.tmp) + self.assertTrue(R.release_job(svc, "rr-1")) + self.assertEqual(eg.cancels(), [f"/v1/attempts/{OLD_JOB}/cancel"]) + self.assertIn("TEST_1", (self.tmp / "created-test-data.jsonl").read_text()) + self.assertIsNone(R.saved_job(self.tmp)) + + +# ---------------------------------------------------------------------------------------------------------------- 3 +class TestRunnerErrors(Base): + def test_a_runner_that_forgot_the_job_fails_the_pass_in_seconds(self): + eg = Runner(polls=[{"state": "running"}, 404, 404, {"state": "done"}]) + start = self.clock.t + with self.assertRaises(R.RemoteRunnerError) as e: + self.remote(eg) + self.assertIn("no longer knows", str(e.exception)) + self.assertLess(self.clock.t - start, 60) # not at the deadline (35 minutes away) + self.assertIsNone(R.saved_job(self.tmp)) + + def test_one_dropped_404_is_not_a_restart(self): + eg = Runner(polls=[404, {"state": "running"}, 404, {"state": "done", "exit_code": 0}]) + self.assertEqual(self.remote(eg)["exit_code"], 0) + + def test_a_lost_job_fails_the_pass_with_a_clear_reason(self): + eg = Runner(polls=[{"state": "lost"}], blob=bundle(with_report=False)) + with self.assertRaises(R.RemoteRunnerError) as e: + self.remote(eg) + self.assertIn("restarted", str(e.exception)) + self.assertIn("TEST_1", (self.tmp / "created-test-data.jsonl").read_text()) # what it made is still cleaned up + + def test_past_the_deadline_the_job_is_cancelled(self): + eg = Runner(polls=[{"state": "running"}]) + with self.assertRaises(ExecutionError) as e: + self.remote(eg, timeout_s=600) + self.assertTrue(e.exception.timed_out) + self.assertEqual(eg.cancels(), [f"/v1/attempts/{NEW_JOB}/cancel"]) + self.assertIn("TEST_1", (self.tmp / "created-test-data.jsonl").read_text()) + self.assertIsNone(R.saved_job(self.tmp)) + + def test_a_busy_runner_is_waited_for_then_the_attempt_starts(self): + eg = Runner(starts=[409, 409, 409, 202]) + events = [] + start = self.clock.t + res = self.remote(eg, on_event=events.append, busy_wait_s=900) + self.assertEqual(len(eg.posts()), 4) + self.assertEqual(res["exit_code"], 0) + self.assertEqual(len([e for e in events if "Waiting for the browser runner" in e]), 1) # said once, not per try + self.assertGreater(self.clock.t - start, 60) # it really waited (with backoff) + + def test_a_runner_busy_for_too_long_is_given_up_on(self): + eg = Runner(starts=[409]) + start = self.clock.t + with self.assertRaises(R.RemoteRunnerError) as e: + self.remote(eg, busy_wait_s=300) + self.assertIn("busy", str(e.exception)) + self.assertGreaterEqual(self.clock.t - start, 300) + self.assertLess(self.clock.t - start, 400) + self.assertIsNone(R.saved_job(self.tmp)) + + def test_another_refusal_is_not_waited_for(self): + eg = Runner(starts=[400]) + with self.assertRaises(R.RemoteRunnerError) as e: + self.remote(eg) + self.assertIn("HTTP 400", str(e.exception)) + self.assertEqual(len(eg.posts()), 1) + + def test_a_screen_read_waits_for_a_busy_runner_too(self): + buf = io.BytesIO() + with zipfile.ZipFile(buf, "w") as z: + z.writestr("playwright.log", "CAPTURED x\n") + eg = Runner(starts=[409, 202], polls=[{"state": "done", "exit_code": 0, "lines": []}], blob=buf.getvalue()) + waits = [] + rc, lines = R.run_screens_remote(eg, "https://runner.example", TOKEN, kind="capture", env={}, out_dir=self.tmp / "out", + task="Payables > Invoices > Create Invoice", on_wait=waits.append, busy_wait_s=600) + self.assertEqual((rc, lines), (0, ["CAPTURED x"])) + self.assertEqual(len(eg.posts("/v1/screens")), 2) + self.assertEqual(len(waits), 1) + with self.assertRaises(R.RemoteRunnerError): + R.run_screens_remote(Runner(starts=[409]), "https://runner.example", TOKEN, kind="capture", env={}, out_dir=self.tmp, + task="Payables > Invoices > Create Invoice", busy_wait_s=60) + + def test_a_cancelled_run_stops_its_runner_job(self): + eg = Runner(polls=[{"state": "running"}]) + status = {"status": "running"} + svc = mock.MagicMock() + svc.db.get_run.side_effect = lambda rid: dict(status) + n = {"polls": 0} + + def kill(): + n["polls"] += 1 + if n["polls"] > 2: + status["status"] = "cancelled" + execute._stop_check(svc, "rr-1") + + with self.assertRaises(execute.RunCancelled): + self.remote(eg, kill=kill) + self.assertEqual(eg.cancels(), [f"/v1/attempts/{NEW_JOB}/cancel"]) + self.assertIsNone(R.saved_job(self.tmp)) # stopped and its records fetched + + def test_the_langgraph_path_sends_each_pass_with_its_budget_and_notes_waits(self): + eg = Runner(starts=[409, 202, 202], new_id=NEW_JOB) + svc = mock.MagicMock() + svc.cfg = cfg(remote_runner_url="https://runner.example", fusion_chunk_scenarios=2) + svc.egress, svc.vault.get.return_value = eg, TOKEN + svc.db.get_run.return_value = {"status": "running"} + ids = ["AP-FUS-001", "AP-FUS-002", "AP-FUS-003"] + eg.blob = bundle(*ids) + try: + res = execute.run_planned(plan_for(self.tmp, ids, run_id="rr-1"), svc) + finally: + for d in (R.AUTOMATION / "results" / "runs").glob("fpt-rr-1-a0-c*"): + shutil.rmtree(d, ignore_errors=True) + self.assertEqual([b["timeout_s"] for b in eg.posts()][-2:], [execute.attempt_timeout_s(svc.cfg, n) for n in (2, 1)]) + self.assertEqual([b["pw_run_id"] for b in eg.posts()][-2:], ["fpt-rr-1-a0-c0", "fpt-rr-1-a0-c1"]) + self.assertEqual(res["chunks"], 2) + kinds = [(c.args[2], c.args[3].get("message", "")) for c in svc.db.add_event.call_args_list] + self.assertTrue(any(k == "runner" and "Waiting for the browser runner" in m for k, m in kinds)) + + +# ---------------------------------------------------------------------------------------------------------------- 4 +class Resp: + def __init__(self, body): + self.status_code, self._body = 200, body + + def json(self): + return self._body + + +class TestPreflightVersion(unittest.TestCase): + def check(self, health: dict, commit: str) -> dict: + svc = mock.MagicMock() + svc.cfg.remote_runner_url = "https://runner.example" + svc.cfg.remote_runner_busy_wait_minutes = 15 + svc.vault.get.return_value = TOKEN + svc.egress.service_request.return_value = Resp({"ok": True, "automation": True, "cases": True, **health}) + with mock.patch.object(preflight, "server_commit", return_value=commit): + return preflight.runner_check(svc) + + def test_a_runner_on_another_commit_fails_pre_flight(self): + r = self.check({"version": "0123456789ab"}, "fedcba9876543210fedcba9876543210fedcba98") + self.assertFalse(r["ok"]) + self.assertIn("deploy/runner/sync.sh", r["detail"]) + self.assertEqual(preflight.problems([r]), [r["detail"]]) + + def test_the_same_commit_short_or_long_passes(self): + self.assertTrue(self.check({"version": "0123456789ab"}, "0123456789abcdef0123456789abcdef01234567")["ok"]) + + def test_without_its_own_commit_the_server_does_not_compare(self): + r = self.check({"version": "0123456789ab"}, "") + self.assertTrue(r["ok"]) + self.assertNotIn("warning", r) + + def test_a_runner_that_does_not_say_its_commit_is_a_warning(self): + r = self.check({"version": "unknown"}, "0123456789ab") + self.assertTrue(r["ok"] and r["warning"]) + + def test_a_busy_runner_is_information_not_a_failure(self): + r = self.check({"version": "0123456789ab", "busy": True}, "") + self.assertTrue(r["ok"] and r["busy"]) + self.assertIn("waits for it (up to 15 minutes)", r["detail"]) + self.assertEqual(preflight.problems([r]), []) + + def test_the_server_reads_its_commit_from_its_deploy(self): + from coworker import config + with tempfile.TemporaryDirectory() as d: + f = Path(d) / "VERSION" + with mock.patch.object(config, "COMMIT_FILE", f), mock.patch.dict("os.environ", {k: "" for k in config.COMMIT_ENV}): + self.assertEqual(config.server_commit(), "") + f.write_text("0123456789AB\n") + self.assertEqual(config.server_commit(), "0123456789ab") + with mock.patch.dict("os.environ", {"FPT_COMMIT": "not a commit"}): + self.assertEqual(config.server_commit(), "0123456789ab") + with mock.patch.dict("os.environ", {"FPT_COMMIT": "abcdef1"}): + self.assertEqual(config.server_commit(), "abcdef1") + + +# ---------------------------------------------------------------------------------------------------------------- 5 +class TestRunnerServerJobs(unittest.TestCase): + def setUp(self): + self.S = load_server() + self.home = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.home, True) + self.S.HOME = self.home + self.S.JOBS.clear() + + def job(self, state: str, jid: str) -> Path: + d = self.home / jid + d.mkdir() + (d / "created.jsonl").write_text('{"invoice":"TEST_1"}\n') + self.S.save_meta({"id": jid, "dir": d, "kind": "attempt", "state": state, "started": real_time.time(), "pw_run_id": "fpt-x", + "exit_code": 0 if state == "done" else None, "proc": object(), "log": object()}) + return d + + def test_a_restarted_runner_answers_for_its_jobs(self): + self.job("done", "job_0000000000d1") + self.job("running", "job_0000000000d2") + meta = json.loads((self.home / "job_0000000000d1" / "job.json").read_text()) + self.assertNotIn("env", meta) + self.assertEqual(set(meta), set(self.S.META)) + self.S.load_jobs() + self.assertEqual(self.S.JOBS["job_0000000000d1"]["state"], "done") + self.assertEqual(self.S.JOBS["job_0000000000d2"]["state"], "lost") # it died with the old runner + self.assertEqual(json.loads((self.home / "job_0000000000d2" / "job.json").read_text())["state"], "lost") + names = zipfile.ZipFile(io.BytesIO(self.S.bundle(self.S.JOBS["job_0000000000d2"]))).namelist() + self.assertIn("created.jsonl", names) # its ledger still ships + + def test_a_folder_that_is_not_a_job_is_ignored(self): + d = self.home / "job_0000000000d3" + d.mkdir() + (d / "job.json").write_text(json.dumps({"id": "job_0000000000ff", "state": "done"})) # names another job + self.S.load_jobs() + self.assertEqual(self.S.JOBS, {}) + + def run_watch(self, deadline_in: float, code: str) -> dict: + d = self.home / "job_0000000000e1" + d.mkdir() + log = open(d / "playwright.log", "wb") + p = subprocess.Popen([sys.executable, "-c", code], stdout=log, stderr=subprocess.STDOUT, **self.S.GROUP) + job = {"id": "job_0000000000e1", "dir": d, "proc": p, "log": log, "pw_run_id": "fpt-none", "started": real_time.time(), + "kind": "attempt", "deadline": real_time.time() + deadline_in, "state": "running", "exit_code": None} + self.S.LOCK.acquire() + self.S.GRACE_S = 5 + self.S._watch(job) + return job + + def test_a_finished_attempt_is_recorded_and_frees_the_runner(self): + job = self.run_watch(60, "print('[1/1] ok')") + self.assertEqual((job["state"], job["exit_code"]), ("done", 0)) + self.assertFalse(self.S.LOCK.locked()) + self.assertEqual(json.loads((self.home / job["id"] / "job.json").read_text())["state"], "done") + + def test_an_attempt_past_its_deadline_is_stopped_and_still_reports(self): + # a Playwright stand-in that writes its report when asked to stop (SIGINT), as the JSON reporter does + code = ("import json, signal, sys, time, pathlib\n" + "def stop(*a):\n" + " pathlib.Path(sys.argv[1]).write_text(json.dumps({'suites': [], 'errors': [], 'stats': {'interrupted': True}}))\n" + " sys.exit(130)\n" + "signal.signal(signal.SIGINT, stop)\n" + "time.sleep(60)\n") + d = self.home / "job_0000000000e1" + job = self.run_watch(0, code.replace("sys.argv[1]", repr(str(d / "report.json")))) + self.assertTrue(job["timed_out"]) + self.assertEqual(job["state"], "done") + self.assertFalse(self.S.LOCK.locked()) + if self.S.os.name == "posix": # Windows has no gentle stop: killed at once + self.assertTrue((d / "report.json").exists()) + + +if __name__ == "__main__": + unittest.main() diff --git a/coworker/tests/test_step_writer.py b/coworker/tests/test_step_writer.py index 12ded67e1c2d4100a498a8444fceeefa5fe89b11..6ed0ec8390ba99942f1f8c1b3ba670b261f29517 100644 --- a/coworker/tests/test_step_writer.py +++ b/coworker/tests/test_step_writer.py @@ -116,6 +116,10 @@ class TestChecker(unittest.TestCase): self.assertIn("{{saved.later}} is used before", p) self.assertNotIn("{{saved.amt}}", p) + def test_a_mask_left_in_a_step_is_refused(self): + bad = {**GOOD, "steps": GOOD["steps"][:4] + [{"action": "enter", "field": "Description", "value": "Paid to "}]} + self.assertIn("'' is a masked value", "\n".join(sw.check_steps(bad, INV))) + def test_empty_expected_value_is_allowed_but_missing_is_not(self): base = {**GOOD, "steps": GOOD["steps"][:4]} ok = {**base, "steps": base["steps"] + [{"action": "expect_value", "field": "Description", "value": ""}]} @@ -308,3 +312,15 @@ class TestFrontierProvider(unittest.TestCase): if __name__ == "__main__": unittest.main() + + +class TestPromptsPassTheLeakCheck(unittest.TestCase): + """Every model request carries its system prompt, and the egress leak check reads the whole request: a prompt with + something that looks like data (an example date, an id, an amount) would refuse every call of that task. Seen before + deploy: an example date in write_steps.md sent every step-writing call to the built-in rules.""" + + def test_no_prompt_looks_like_client_data(self): + from ..platform.redaction import Redactor + red = Redactor([]) + for f in sorted((Path(sw.__file__).parents[1] / "llm" / "prompts").glob("*.md")): + self.assertEqual(red.find_leaks(f.read_text(encoding="utf-8")), [], f.name) diff --git a/coworker/tests/test_supabase.py b/coworker/tests/test_supabase.py index 2a0edd5327fd5d345519a4538bb6964b976aa034..6a8b4574681fe1d836de7aea0296e709763c01fd 100644 --- a/coworker/tests/test_supabase.py +++ b/coworker/tests/test_supabase.py @@ -260,6 +260,19 @@ class TestStateSync(unittest.TestCase): statesync.restore(cfg2, sb.Supabase(cfg2, svc.egress, None)) self.assertFalse((fresh / "fpt.sqlite").exists()) + def test_an_asked_for_save_happens_even_when_the_signature_looks_saved(self): + """Race found in review: a save uploading while an event writes records a signature that already includes the + write, though its archive does not; the asked-for save must not be skipped as 'unchanged'.""" + fake = FakeSupabase(confirm=False) + _, c, svc = make(fake) + s = statesync.Syncer(svc, 3600) + self.assertTrue(s.tick()) + self.assertFalse(s.tick()) # nothing changed, nothing asked: skipped + s.soon("run completed") # the loop is not started: tick by hand + self.assertTrue(s.tick()) # asked for: saved even though the signature matches + self.assertFalse(s.tick()) # owed once only + self.assertTrue(s.tick("before restart", force=True)) + def test_a_finished_screen_read_or_paused_run_is_saved_at_once_not_at_the_next_interval(self): """Seen on the live Space: a deploy restarted it minutes after an hour of screen reading had finished, before the periodic save, and the restore brought back the old screens with the read still 'running'.""" diff --git a/coworker/workflows/client.py b/coworker/workflows/client.py index f5474340a34144316adcd83d3cdb1af4e5547131..51849c71192bc130610e7eee7b35038ea93787b8 100644 --- a/coworker/workflows/client.py +++ b/coworker/workflows/client.py @@ -79,8 +79,8 @@ class TemporalRunManager: return self.client.get_workflow_handle(run_id) # ---------------------------------------------------------------- API - def start(self, inputs: dict, actor: str, trigger: str = "manual") -> str: - rid, _ = create_run_record(self.svc, inputs, actor, trigger, orchestrator="temporal") + def start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str: + rid, _ = create_run_record(self.svc, inputs, actor, trigger, orchestrator="temporal", run_id=run_id) self._loop.run(self.client.start_workflow("PatchCycleWorkflow", workflow_input(self.cfg, rid), id=rid, task_queue=self.cfg.temporal_task_queue)) return rid diff --git a/deploy/DEPLOY.md b/deploy/DEPLOY.md index 7fdf3d4ed0640c5c9d34f2e1f05998cfe34d5e8e..a262df6c0a7df7d78cb20c399f01b8d86e9d64d1 100644 --- a/deploy/DEPLOY.md +++ b/deploy/DEPLOY.md @@ -1,8 +1,14 @@ -# Deploying Patchwise in a customer's cloud +# Deploying Astra in a customer's cloud One deployment serves one customer. Everything the product stores stays on the customer's own server, in Docker volumes: nothing is kept outside their environment. +> **Oracle Fusion pods do not run in this shape today.** This stack runs the workflow on Temporal, and the Temporal +> execute activity (`coworker/workflows/activities.py`) supports the practice pod only: it starts the local practice +> pod and has no remote browser runner, no per-area test users and no pre-flight. Fusion test cycles run on the +> Hugging Face Space shape with a remote runner ([docs/DEPLOYMENT.md](../docs/DEPLOYMENT.md)). Say this plainly to a +> buyer. + > **Status of this package.** The application image is built and checked automatically on every push to `main` > (`.github/workflows/image.yml`): it starts, serves the web app, the practice pod answers, sign-in works, and the > self-tests pass inside the container (35 checks offline, 42 with three scenarios in Chromium). Image size: 1.8 GB. @@ -74,7 +80,7 @@ Live view, and download the report and the Excel test script. | Logs | `docker compose logs -f app` | | Backup | `./backup.sh /secure/backups` (the archive includes the secrets vault: keep it encrypted) | | Upgrade | take a backup, load or build the new image, `docker compose up -d` (database upgrades run on start) | -| Upgrade the browser runner (when Fusion tests run on a separate runner, `FPT_REMOTE_RUNNER_URL`) | right after every upgrade, on the same commit: `deploy/runner/sync.sh ubuntu@ https://`. It refuses while a test run is using the runner; its `/healthz` then shows the commit as `version` and `cases: true` | +| Upgrade the browser runner (Space shape only: Fusion tests on a separate runner, `FPT_REMOTE_RUNNER_URL`) | right after every upgrade, on the same commit: `deploy/runner/sync.sh ubuntu@ https://`. It refuses while a test run is using the runner; its `/healthz` then shows the commit as `version` and `cases: true` | | Temporal UI | `ssh -L 8233:127.0.0.1:8233 ` then open `http://127.0.0.1:8233` | | Emergency stop | in the product: Settings > Emergency stop, or `docker compose exec app python -m coworker kill` | | Check the audit log | `docker compose exec app python -m coworker verify-audit` | @@ -92,9 +98,9 @@ Live view, and download the report and the Excel test script. These are the limits of the product today, not of the packaging. Say them plainly to a buyer. -- **Oracle Fusion coverage is Payables only.** Runs on a registered Fusion test pod work end to end for Payables - (verified on a real pod on 31 Oct 2026: 6 of 6 scenarios in the browser). Other business areas run on the - practice pod only until their Fusion scripts are written and verified. +- **No Oracle Fusion pods in this shape** (see the note at the top). On the Space shape, the committed Fusion + scenario library is Payables (`AP-FUS-*`); scenarios for the other areas are written by the AI model from the + pod's screens during a run; approved ones join the library when `FPT_CASE_WRITEBACK=1`. - **Single sign-on** (SAML/OIDC) is not built; accounts are local or come from Supabase. - **SQLite and a single-node Temporal dev server.** Fine for one customer on one server; not highly available. - **Jira / ServiceNow**: tickets are written to files; the connectors are stubs. @@ -104,7 +110,8 @@ These are the limits of the product today, not of the packaging. Say them plainl ## Settings that make the demo survive a restart (Hugging Face Space or any host without a disk) -The app keeps its data in an encrypted snapshot in Supabase Storage and restores it at start. These settings rebuild the +The app keeps its data in an encrypted snapshot in a bucket (OCI Object Storage when `OCI_STATE_PAR_URL` is set, else +Supabase Storage) and restores it at start. These settings rebuild the essentials from the environment, so a lost or unreadable snapshot never leaves the product without its pod or its AI model. | Setting | Kind | Effect | @@ -112,12 +119,15 @@ essentials from the environment, so a lost or unreadable snapshot never leaves t | `FPT_FUSION_BASE_URL` (`https://.fa.ocs.oraclecloud.com`), `FPT_FUSION_NAME`, `FPT_FUSION_ENVIRONMENT`, `FPT_FUSION_MODULES` | variable | The Oracle Fusion test pod exists after every start. Production addresses are refused. | | `FPT_SECRET_FUSION_USERNAME`, `FPT_SECRET_FUSION_PASSWORD` | secret | The pod's test user. Never written to the vault file or shown. | | `FRONTIER_BASE_URL` (https), `FRONTIER_MODEL`, `FPT_SECRET_FRONTIER_API_KEY` | variable, variable, secret | The external model is switched on at start when no AI settings are saved in the app. `FPT_FRONTIER_AUTO=0` turns this off. | -| `SUPABASE_BUCKET`, `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `FPT_STATE_KEY` | variable and secrets | One bucket per deployment; never share a bucket between two instances (the last writer wins). | +| `OCI_STATE_PAR_URL`, `FPT_STATE_KEY` | secrets | The OCI bucket's pre-authenticated request URL (read and write objects, listing denied) and the snapshot key, which OCI requires. Periodic saves at most every 300 s there; event saves go at once. One bucket per deployment. | +| `SUPABASE_BUCKET`, `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `FPT_STATE_KEY` | variable and secrets | Supabase Storage instead. One bucket per deployment; never share a bucket between two instances (the last writer wins). | If the start-up restore fails, the instance starts empty and **stops saving** (`/api/ready` shows `saved_state.paused`, and the app shows a notice) so the good snapshot is not overwritten; restart to retry. The first save of every start keeps the archive it found as `state/previous.bin` in the bucket; copy it over `state/latest.bin` to undo a bad save. -**Before every restart or deploy**, save the state and wait for the answer: `POST /api/storage/save` (administrator). -The app also saves at once when a screen read finishes and when a run waits for a person or ends, and first thing on -shutdown; a screen read cut off by a restart shows as interrupted after it, never as still running. +**Before every restart or deploy**, check that no run is running or queued and the runner is not busy, then save the +state and wait for the answer: `POST /api/storage/save` (administrator). After the deploy, run `deploy/runner/sync.sh` +on the same commit. The app also saves at once when a screen read finishes and when a run waits for a person, ends or +is cancelled, and first thing on shutdown; a screen read cut off by a restart shows as interrupted after it, never as +still running. Full steps: docs/RUNBOOK.md "Before every deploy or restart". diff --git a/deploy/runner/sync.sh b/deploy/runner/sync.sh index 8160aa68d8e99f60e7b208b0b1e6a8d243ae232e..72c014e1be2516f1e50416b48c037027e4998b3c 100644 --- a/deploy/runner/sync.sh +++ b/deploy/runner/sync.sh @@ -36,12 +36,20 @@ else npm ci --no-audit --no-fund --loglevel=error fi npx playwright install chromium >/dev/null +# the install took minutes: a test run may have started meanwhile, and the restart would kill its browsers +if curl -s --max-time 10 http://127.0.0.1:${RUNNER_PORT:-8899}/healthz | grep -q '"busy": true'; then + echo "a test run started on the runner during the install: nothing switched; run this again when it ends" >&2 + rm -rf ~/astra.new + exit 2 +fi rm -rf ~/astra.prev [ -d ~/astra ] && mv ~/astra ~/astra.prev mv ~/astra.new ~/astra sudo systemctl restart "$SERVICE" sleep 3 -curl -s http://127.0.0.1:${RUNNER_PORT:-8899}/healthz; echo +H=$(curl -s http://127.0.0.1:${RUNNER_PORT:-8899}/healthz); echo "$H" +# the service must run the copy just installed (its AUTOMATION_DIR is ~/astra/automation) and have its scenario files +echo "$H" | grep -q "\"version\": \"$REV\"" && echo "$H" | grep -q '"cases": true' || { echo "the runner does not report $REV with its scenario files: check the service's AUTOMATION_DIR" >&2; exit 3; } REMOTE if [ -n "$URL" ]; then diff --git a/docs/AGENT_STUDIO.md b/docs/AGENT_STUDIO.md index 0198bab354e6c12439a5661d20dadbe10cbfc70a..9fe225c9cf827522a3d77934da70774b2c5ba31a 100644 --- a/docs/AGENT_STUDIO.md +++ b/docs/AGENT_STUDIO.md @@ -1,12 +1,15 @@ -# Oracle AI Agent Studio → Patchwise +# Oracle AI Agent Studio → Astra -This guide explains how an Oracle Fusion Cloud AI Agent Studio workflow runs a patch test cycle in Patchwise. Fusion -owns the schedule, the synthetic test data and both human approvals. Patchwise (LangGraph) writes the test scripts, +This guide explains how an Oracle Fusion Cloud AI Agent Studio workflow runs a patch test cycle in Astra. Fusion +owns the schedule, the synthetic test data and both human approvals. Astra (LangGraph) writes the test scripts, runs the browser tests and reports back. The OpenAPI spec is `web/src/api/openapi.json` (tag **agent-studio**). The live `/api/docs` page is off on the public Space (`FPT_API_DOCS=0`). +Some names on the wire still say `patchwise` (the scope `patchwise.invoke`, the `X-Patchwise-*` headers, the +`pwc_`/`pws_`/`pwk_`/`pwa_` prefixes). They are part of the contract the Fusion workflows already use and do not change. + ``` -Oracle Fusion Cloud Patchwise -─────────────────── ───────── +Oracle Fusion Cloud Astra +─────────────────── ───── Scheduler (weekly) └ AI Agent Studio workflow 1 Read module space @@ -16,25 +19,26 @@ Scheduler (weekly) 5 Email + notification ◀── callback scripts_ready ──────────────────────┘ 6 Human approval (start) ── POST /api/agent-studio/v1/cycles/{id}/approval ▶ Playwright browser runner (User B, TEST_US_BU) - ◀── callback failures_need_review (if any) ─────── triage (a person, in Patchwise) + ◀── callback failures_need_review (if any) ─────── triage (a person, in Astra) 7 Email + notification ◀── callback results / stopped ────────────────── reports + ◀── callback paused (optional, may be ignored) ─── a restart interrupted the run Release watch agent ◀── callback patch_update ───────────────────── web crawler of Oracle release notes ``` -**Contract:** test data is **synthetic only**, with no personal data and no real transactions. Patchwise refuses values +**Contract:** test data is **synthetic only**, with no personal data and no real transactions. Astra refuses values that look like an email address, a phone or card number, or a national id (`NOT_SYNTHETIC`). Every approval is made by a person: the two in Fusion are forwarded with that person's name, and test failures are always decided by a person -in Patchwise, never automatically. +in Astra, never automatically. ## Users and privileges | Who | Where | Can | |---|---|---| -| User A | Fusion only | data roles for the workflow; never given to Patchwise | +| User A | Fusion only | data roles for the workflow; never given to Astra | | User C | the OAuth client (`patchwise.invoke`) | start cycles, read them, forward approvals. Cannot list runs or touch anything else | -| User B | the Fusion test pod's sign-in, stored in Patchwise | the browser tests: action privileges only, in test business unit `TEST_US_BU` | +| User B | the Fusion test pod's sign-in, stored in Astra | the browser tests: action privileges only, in test business unit `TEST_US_BU` | -## 1. Set up (a Patchwise admin) +## 1. Set up (an Astra admin) 1. **Test environments**: register the Fusion test pod with User B's sign-in (it is stored in the vault and never shown). 2. **Agent Studio → Clients → New client**: name it and give the HTTPS **callback address** (step 5/7 in Fusion), and @@ -58,18 +62,28 @@ grant_type=client_credentials&client_id=…&client_secret=…&scope=patchwise.in ``` HTTP Basic or a JSON body also work. The response is `{"access_token":"pwa_…","token_type":"Bearer","expires_in":3600,"scope":"patchwise.invoke"}`. -Send it as `Authorization: Bearer pwa_…` on every call below. +Send it as `Authorization: Bearer pwa_…` on every call below. Treat the token as opaque; only its `pwa_` prefix is +fixed. + +**How tokens behave.** A token is signed by Astra (HMAC-SHA256 over the client id and the expiry time), so Astra checks +it without looking it up. A restart that restores an older saved state therefore does not end a token the Fusion side +has cached: it stays valid for its hour. The key is the vault secret `agent_studio.token_key`. Set +`FPT_SECRET_AGENT_STUDIO_TOKEN_KEY` on the server to keep it fixed; otherwise Astra makes one the first time and keeps +it in the saved state. Changing the key ends every token already issued, and the Fusion side then asks for a new one. +Every call still checks the client: a revoked client's tokens are refused at once (`401 invalid_token`). Tokens issued +before tokens were signed keep working until they expire. ### Check test data (optional) `POST /test-data/check` with `{"test_data": {...}}` returns `{"ok": true, "areas": {...}, "mapped": {...}, "not_testable": [...]}` -or `{"ok": false, "code", "problem"}`. `mapped` lists the Fusion workflow's own area codes Patchwise renamed (below); -`not_testable` lists areas Patchwise has no Fusion tests for (HCM, PAY, ABS, BEN, IRC today). +or `{"ok": false, "code", "problem"}`. `mapped` lists the Fusion workflow's own area codes Astra renamed (below); +`not_testable` lists areas Astra has no Fusion tests for (HCM, PAY, ABS, BEN, IRC today). ### Start a cycle (after the person approves the data) ```http POST /cycles +Idempotency-Key: 6c1f… (optional) { "test_data": {"AP": {"business_unit": "TEST_US_BU", "supplier": ["Test Supplier A", "Test Supplier B"], "currency": "USD"}}, "data_approved_by": "Priya (Fusion QA)", @@ -86,17 +100,30 @@ POST /cycles | `data_approved_by` | required: who approved the data in Fusion | | `areas` | defaults to the test data's areas. Areas the pod cannot test are skipped and listed in `skipped_areas`; the cycle is refused (`BAD_TEST_DATA`) only when none can be tested | | `package` | optional: the approved test data package of the V3.6 workflows (up to 2 MB). Kept with the cycle; its `package_id` is in the response and admins read it at `GET /api/agent-studio/cycles/{cycle_id}/package` | -| `depth` | `regression` (default): every approved scenario of each area, every priority, plus one end-to-end flow per business process of the area (at most `FPT_FUSION_REGRESSION_FLOWS`, 3) and the cross-area flows (Procure-to-Pay ...) when all their areas are tested. `standard`: the patch's P1 scenarios and the ones its changes touch. `smoke`: the quickest check. Anything else is refused (`BAD_DEPTH`) | -| `environment` | the Patchwise test environment's name; defaults to the default Fusion pod | +| `depth` | `regression` (default): every approved scenario of each area, every priority, plus one end-to-end flow per business process of the area (at most `FPT_FUSION_REGRESSION_FLOWS`, 3) and the cross-area flows (Procure-to-Pay ...) when all their areas are tested. It also asks the AI model for one scenario per standard regression and edge-case check of the area (the `regression` list of `coworker/platform/fusion_catalog.py`: refusals, boundaries, duplicates, state changes, defaults, searches) that no library scenario covers yet, at most `FPT_FUSION_REGRESSION_CHECKS` (25, 0 = off) per area. `standard`: the patch's P1 scenarios and the ones its changes touch. `smoke`: the quickest check. Anything else is refused (`BAD_DEPTH`) | +| `environment` | the Astra test environment's name; defaults to the default Fusion pod | | `callback_url` | defaults to the client's callback address | -| `correlation_id` | your workflow's id, echoed in every callback | +| `correlation_id` | your workflow's id, echoed in every callback. Also makes the start safe to retry (below) | The response is **202** with `{"cycle_id": "cyc_…", "run_id": "…", "areas", "skipped_areas", "package_id", "status", "waiting_for", "links": {"run", "excel", "report"}}`. The approval answer has the same shape plus `decision`. +**Starting is safe to retry.** A call that timed out or got no answer can be sent again. Astra does not start a second +cycle or run in these cases: + +- **Same `Idempotency-Key` header** (optional, up to 200 characters, per client). Astra returns the cycle that key + made, whatever state it is in now. +- **Same `correlation_id`** from the same client while that cycle's run is still going (queued, running, or waiting + for an approval or a decision). Once that cycle has finished, failed, been interrupted or been cancelled, the same + `correlation_id` starts a new cycle. A workflow that sends the same id every week keeps working. + +A repeated start gets the same **202** and the same body as the first call, plus the response header +`Idempotent-Replayed: true`. Astra saves the cycle as soon as it starts, and saves the start-testing decision as soon +as it is made, so a restart a few minutes later does not lose either one. + ### Where a cycle is -`GET /cycles/{cycle_id}` returns the same shape. `waiting_for` is one of: +`GET /cycles/{cycle_id}` returns the same shape. `waiting_for` is one of these exact strings (they do not change): - `"approval in Oracle Fusion (start testing)"`; - `"a person to decide the failures (in Patchwise)"`; - `null`. @@ -110,7 +137,7 @@ POST /cycles/{cycle_id}/approval - Leaving out `scenario_ids` approves every scenario offered. - `"reject"` cancels the cycle; `comment` is kept. -- Patchwise records the actor as `Priya (Fusion QA) (in Oracle Fusion)`. +- Astra records the actor as `Priya (Fusion QA) (in Oracle Fusion)`. ### Errors @@ -124,14 +151,31 @@ The body is `{"code", "detail", "request_id"}`. | 409 | the run is not waiting for that decision, or no Fusion environment exists | | 422 | a required field is missing | -## 3. Callbacks (Patchwise → Fusion) +## 3. Callbacks (Astra → Fusion) Each OAuth client chooses how its events reach Fusion (**Agent Studio → OAuth clients → Delivery**). +### Delivery semantics (all three modes) + +- **At least once.** An event can arrive more than once: a retry after a lost answer, a pull event handed out again, + an admin sending a dead letter again, or an event made again after a restart restored an older saved state. +- **Stable ids.** Every event has a `delivery_id` (in the body, the `X-Patchwise-Delivery` header and the `deliveryId` + parameter). The same logical event always has the same id. Astra derives it from the cycle, the event type and how + many events of that type the cycle had before, so a copy made again after a restore keeps its id. Use + `delivery_id` to drop repeats. +- **Order.** Events of one cycle are queued in the order they happen. A `paused` event that was not delivered before a + newer event of its cycle is dropped (listed as `superseded`), so it never arrives after the cycle has moved on. +- **Dead letters.** An event that runs out of tries is kept as a **dead letter**: 6 sends for the URL and Fusion + modes, or 20 pickups without a confirmation in pull mode. Astra writes an audit entry + (`agent_studio.dead_letter`) and sends the admins one notification ("event(s) could not be delivered to Oracle + Fusion"). The event shows as `dead` under **Agent Studio → Callbacks**. An admin sends it again with **Send again** + (`POST /api/agent-studio/deliveries/{delivery_id}/requeue`); its tries start over with the same `delivery_id`. A + pull confirmation that arrives after the event became a dead letter still counts. + ### Oracle Fusion directly (recommended; no relay) -Patchwise signs in to your OCI IAM identity domain with a confidential app (client credentials). The client secret is -write-only and kept in the vault; the token is held in memory only. Patchwise then starts the callback workflow: +Astra signs in to your OCI IAM identity domain with a confidential app (client credentials). The client secret is +write-only and kept in the vault; the token is held in memory only. Astra then starts the callback workflow: `POST {Fusion address}/api/fusion-ai/orchestrator/agent/v2/{workflow code}/invokeAsync`, by default `PATCH_TEST_CALLBACK_V3_7`. @@ -163,33 +207,46 @@ in a **While Loop** with a **Wait** of 2 to 5 minutes after `createCycle`. optional. The answer is `{events, count, more, confirm_within_s}`. Each event is the callback body below, plus `delivery_id` and `pickup` (how many times it was handed out). - **Confirm:** `POST /api/agent-studio/v1/events/ack` with `{"delivery_ids": ["dlv_…"]}`. A confirmed event is not - handed out again. + handed out again. Confirm every event you pick up, including types your workflow ignores (such as `paused`). -An event that isn't confirmed within 5 minutes is handed out again, up to 20 times. A client only sees and confirms -its own events. To keep this mode on a server without saved state, add `"delivery": "pull"` to the client in -`FPT_SECRET_AGENT_STUDIO_BOOTSTRAP_CLIENTS`. +`POST /test-data/check` with `{"pickup": {"max": 1, "cycle_id": "cyc_…"}}` answers as `/events/claim`, and +`{"confirm": ["dlv_…"]}` answers as `/events/ack`, so a workflow can use its existing tool function. + +An event that isn't confirmed within 5 minutes is handed out again, up to 20 times; after that it is a dead letter +(above). A client only sees and confirms its own events. To keep this mode on a server without saved state, add +`"delivery": "pull"` to the client in `FPT_SECRET_AGENT_STUDIO_BOOTSTRAP_CLIENTS`. ### Callback address (a relay or any receiver) Callbacks are sent with `POST` to the callback address, as `Content-Type: application/json`, with these headers: - `X-Patchwise-Event`: the event's name. -- `X-Patchwise-Delivery`: a unique id; use it to ignore duplicates. +- `X-Patchwise-Delivery`: the event's stable id; use it to ignore duplicates. - `X-Patchwise-Signature: sha256=`: an HMAC-SHA256 of the **raw body** with the client's signing key. Answer with any 2xx code. Anything else, or no answer within 20 s, is retried after 1, 2, 4, 8 and 16 minutes (six -tries in all). Delivery state is listed under **Agent Studio → Callbacks**. +tries in all). Delivery state is listed under **Agent Studio → Callbacks**. A callback is never sent unsigned: if the +client's signing key is missing from the vault, Astra logs an error and does not send it. The try counts as failed, +with the error "no signing key …", so the event ends up as a dead letter an admin can send again once the key is +back. Every body has `event`, `delivery_id`, `sent_at`, `cycle_id`, `run_id`, `correlation_id` and `links`, plus: | Event | When | Extra fields | |---|---|---| -| `scripts_ready` | test scripts written, waiting for step 6 | `scenarios[]` (`id`, `title`, `area`, `priority`, `written_by`, `covers_patch_change`), `count`, `approve_with`. `links.excel` is the test script | -| `failures_need_review` | some tests failed | `note`: a person decides each failure in Patchwise | -| `results` | finished | `verdict` (`Ready` / `Not ready`), `areas[]` (`area`, `verdict`, `rule_result`, `counts`) | -| `stopped` | failed, cancelled, killed or interrupted | `status`, `reason` | +| `scripts_ready` | test scripts written, waiting for step 6 | `scenarios[]` (`id`, `title`, `area`, `priority`, `written_by`, `covers_patch_change`, `steps`), `count`, `approve_with`. `links.excel` is the test script | +| `failures_need_review` | some tests failed | `note`: a person decides each failure in Astra; `scenarios[]`, `count` | +| `results` | finished | `verdict` (`Ready` / `Not ready`), `areas[]` (`area`, `verdict`, `rule_result`, `counts`), `scenarios[]` | +| `stopped` | failed, cancelled or killed | `status`, `reason`, `resumable` (true for `failed`: an admin can resume the run, and the cycle then reports again) | +| `paused` | **optional, new.** A backend restart interrupted the run. It is not over: once an admin resumes it, the cycle goes on and sends its next events as usual | `status` (`interrupted`), `reason`, `resumable: true` | | `patch_update` | the release watch found new items (to the release watch address) | `release`, `count`, `changes[]` (`id`, `area`, `title`, `on_by_default`, `impact`, `action_to_enable`, `link`) | +`paused` is the only event type the existing callback workflows (up to V3.11) do not know. They can ignore it. An +interrupted run used to be reported as `stopped`, but it can be resumed, so it is now `paused`. Astra keeps watching a +cycle whose run failed or was interrupted, and reports again (`scripts_ready`, `failures_need_review`, `results` or +`stopped`) when the resumed run moves on. New optional fields such as `resumable` may appear in any event; ignore +fields you do not know. + Verify a callback before using it: ```python @@ -201,7 +258,7 @@ def verify(signing_key: str, raw_body: bytes, header: str) -> bool: ## 4. The release watch -Every 24 hours (setting `agent_studio_watch_hours`; 0 turns it off), Patchwise reads Oracle's What's New for each +Every 24 hours (setting `agent_studio_watch_hours`; 0 turns it off), Astra reads Oracle's What's New for each Fusion pod's release and for the areas in use. New items go to every client's release watch address as one `patch_update`. The Fusion release watch agent drafts the impact assessment and emails it. Admins can run a check at once with **Agent Studio → Release watch → Check now** (`POST /api/agent-studio/release-watch/check`). @@ -220,20 +277,24 @@ The console only calls what Fusion would call. It cannot skip a human decision. ## 6. Where the data lives -The backend is the same as Patchwise v1. Supabase Auth handles sign-in and registration. An encrypted snapshot of the -app's data (the SQLite database, which holds the `agent_*` tables, plus the vault with the signing keys, reports and -evidence) is saved to a private Supabase Storage bucket whenever the database changes, and restored after a restart. +The backend is the same as Astra v1. Supabase Auth handles sign-in and registration. An encrypted snapshot of the +app's data (the SQLite database, which holds the `agent_*` tables, plus the vault with the signing keys and the token +key, reports and evidence) is saved to a private Supabase Storage bucket whenever the database changes, and restored +after a restart. A new client, a revoked client, a new cycle and a start-testing decision ask for a save at once. This Space uses **its own bucket, `patchwise-agent-studio`** (set in the Dockerfile), in the same Supabase project, so it never overwrites v1's saved state. It also has its own `FPT_STATE_KEY`. Space secrets to set: - `SUPABASE_ANON_KEY` and `SUPABASE_SERVICE_KEY` (the same project as v1); - `FPT_SECRET_FRONTIER_API_KEY`; -- `FPT_SECRET_FUSION_USERNAME` and `FPT_SECRET_FUSION_PASSWORD` (User B). +- `FPT_SECRET_FUSION_USERNAME` and `FPT_SECRET_FUSION_PASSWORD` (User B); +- optionally `FPT_SECRET_AGENT_STUDIO_TOKEN_KEY`, so tokens stay valid even if the saved state is lost. ## 7. Security notes -- Client secrets and tokens are stored hashed. Signing keys are kept in the vault. +- Client secrets are stored hashed. Signing keys and the token key are kept in the vault. Access tokens are signed, + not stored; tokens from before that change are stored hashed until they expire. - A token is for this API only: it cannot read runs or call any other `/api` route. -- Callbacks go only to the client's own HTTPS address, through the egress gate, and every one is audited. +- Callbacks go only to the client's own HTTPS address, through the egress gate, and every one is audited. They are + never sent without a signature. - Rotate a client's credentials by creating a new client and revoking the old one. diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 58a7cd910291026d4eb9f7c4b859059b9b606ab0..5a7ed075206fb377913fe77c3a0ef5cfc65ef48d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,64 +1,125 @@ # Architecture +Astra is an AI QA co-worker that tests Oracle Fusion Cloud TEST pods. The running system is one container (a Hugging +Face Space), a remote browser runner for Fusion pods, and a storage bucket that holds an encrypted snapshot of the data. + ## Components ```mermaid flowchart LR U[Browser: consultant, QA approver, admin] -->|HTTPS, session cookie + CSRF header| API - subgraph Container [One Docker image, non-root, tini] + AS[Oracle Fusion AI Agent Studio
workflows] -->|OAuth client: cycles, approval,
pull of events| API + subgraph Container [One Docker image, non-root, tini: the Hugging Face Space] API[FastAPI app
coworker/api] --> RM[Run manager
api/runner.py, run_jobs queue] RM --> G[LangGraph workflow
coworker/graph] - G --> PW[Playwright executor
automation/, adapters/playwright.py] + G --> PW[Playwright adapters
adapters/playwright.py, adapters/remote_runner.py] G --> RR[QA rule C1-C6
reports/generate_report.py, qa/audit.py] G --> TR[Triage
triage/classifier.py] - API --> DB[(SQLite: runs, events, users, sessions,
pods, schedules, audit chain)] - API --> V[(Vault: secrets/vault.json
+ FPT_SECRET_* env)] + API --> DB[(SQLite: runs, events, users, sessions,
pods, schedules, Agent Studio cycles, audit chain)] + API --> V[(Vault: FPT_HOME/secrets/vault.json
+ FPT_SECRET_* env)] SCH[Scheduler
platform/scheduler.py] --> RM + COU[Courier
platform/agent_studio.py] --> RM SYNC[State sync
platform/statesync.py] --> DB MOCK[Practice pod
mock-app :3100] end G -->|EgressGate| LLM[AI model
llm/router.py] - G -->|EgressGate: REST| FUS[Oracle Fusion test pod] - PW -->|browser| FUS - PW --> MOCK - API -->|EgressGate| SB[Supabase: identity, encrypted backup] - API -->|EgressGate, optional| H[Hermes assistant] + G -->|EgressGate: REST, read-only| FUS[Oracle Fusion test pod] + PW -->|EgressGate: HTTPS + runner token| RUN[Remote runner
automation/remote_runner/server.py
behind Caddy] + RUN -->|browser| FUS + PW -->|local browser| MOCK + COU -->|EgressGate: signed callbacks, push mode| AS + SYNC -->|EgressGate: encrypted snapshot| BKT[(Bucket: OCI Object Storage
or Supabase Storage)] + API -->|EgressGate| SB[Supabase: identity] ``` -## A test run, step by step +| Part | What it is | Code | +|---|---|---| +| API and web app | FastAPI serving the React app, the REST API, `/mcp`, `/a2a` and `/oauth/token` | `coworker/api` | +| Run manager | One worker thread; queued jobs are kept in `run_jobs` | `coworker/api/runner.py` | +| Workflow | LangGraph graph, one checkpoint per step (SQLite) | `coworker/graph` | +| Remote runner | Runs the browsers of Fusion test attempts and screen reads, one job at a time ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)) | `automation/remote_runner/server.py` | +| Agent Studio API and courier | Fusion workflows start test cycles and approve them; the courier sends or queues the cycle events and runs the release watch ([AGENT_STUDIO.md](AGENT_STUDIO.md)) | `coworker/platform/agent_studio.py`, `coworker/api/routes/agent_studio.py` | +| State sync | Saves an encrypted snapshot of `FPT_HOME` to the bucket and restores it at start | `coworker/platform/statesync.py`, `coworker/platform/ocistore.py` | + +## A Fusion test cycle, step by step + +A cycle starts from the web app, a schedule, or Oracle AI Agent Studio (`POST /api/agent-studio/v1/cycles`; there the +depth defaults to `regression`, which is depth `full`). Nodes are in `coworker/graph/nodes/`; the graph is in +`coworker/graph/build.py`. -| Step | Node (`coworker/graph/nodes/`) | What happens | +| Step | Node | What happens | |---|---|---| -| 1 | `research.scout` | Reads the pod; stops on a production pod. On a Fusion pod it first discovers which business areas the pod uses and samples their test data from the pod's own records (`platform/discovery.py`, docs/DISCOVERY.md) | -| 2 | `research.*` | Reads what the patch changes; the AI model summarises (public or redacted data only) | -| 3 | `design.*` | Chooses scenarios from the library (`tests/cases`), coverage maps (`analysis/`); AI may draft extra scenarios, which are dry-run | -| 4 | `design.approval_gate` | Pauses; a consultant approves or skips each scenario (one answer per gate, atomic) | -| 5 | `data.*` | Plans test data | -| 6 | `execute.executor` | Runs Playwright in chunks; live view frames; retries a crashed attempt once | -| 7 | `triage.*` | Classifies failures (UI change, data, timing, real defect) | -| 8 | human review gate | A QA approver confirms real defects or waives | -| 9 | `report.*` | Go / no-go by the QA rule, PDF/HTML/Excel; test data clean-up summary | - -The run manager persists queued jobs (`run_jobs`) so answers survive a restart; LangGraph checkpoints (SQLite) let a -paused run continue. Temporal is an alternative orchestrator (`FPT_ORCHESTRATOR=temporal`) for long runs on a -dedicated server. +| 1 | `scout` | Reads the pod; stops on a production pod. On a Fusion pod it finds which business areas the pod uses and samples their test data from the pod's own records (`platform/discovery.py`, [DISCOVERY.md](DISCOVERY.md)). Invoice lines are read from the business unit the tests use first, so the line account belongs to that unit's chart of accounts. | +| 2 | `research_module`, `synthesizer` | Reads Oracle's What's New for the pod's release, per area (public data), and ranks the release changes into the coverage view. | +| 3 | `test_generator` | Picks scenarios from the library (`tests/cases` and the approved ones in `FPT_HOME/library`; at depth `full`, every approved scenario of the areas). With an AI model configured it then designs new ones (`graph/nodes/ai_scenarios.py`), steps 3a to 3e. | +| 3a | | **Screen reading** of the areas whose screens are missing (never read, read on another release, or files gone), inside the run, on the runner. Each area's key business tasks (`platform/fusion_catalog.py` `key_tasks`) are read first. Live runs only. | +| 3b | | **AI scenarios** from the area's key screens, at most 3 per screen (`PER_SCREEN`). | +| 3c | | **End-to-end flows**: at depth `full`, one per business process of each area (at most `FPT_FUSION_REGRESSION_FLOWS`, default 3); and cross-area flows (Procure-to-Pay, Order-to-Cash, Record-to-Report) when the run tests all their areas. | +| 3d | | **Regression checks**: at depth `full`, one scenario per catalogue check (`fusion_catalog` `regression`) that no scenario covers yet, at most `FPT_FUSION_REGRESSION_CHECKS` (default 25) per area. | +| 3e | | **Dry run** of the AI scenarios on the pod, only when `FPT_FUSION_AI_DRY_RUN=1` (off by default). With it off, nothing runs on the pod before a person approves. | +| 4 | `approval_gate` | Pauses. A person approves or skips each scenario: in the app, or in Fusion for an Agent Studio cycle (`POST .../cycles/{id}/approval`). | +| 5 | `data_planner`, `data_executor` | Plans test data; seeds it only where allowed (`SEED_ALLOWED=1`). | +| 6 | `script_builder` | Turns the approved scenarios into Playwright specs. | +| 7 | `executor` | **Pre-flight** first (`platform/preflight.py`): the runner answers and has its scenario files, the test user signs in, every area has test data (a warning only). A failed check stops the run before any browser starts. Then one Playwright run per test user: each area signs in as its own user (`FPT_FUSION_AREA_USERS`), on the remote runner when `FPT_REMOTE_RUNNER_URL` is set. A browser-level failure (nothing ran) is tried once more. | +| 8 | `self_heal` | For a renamed control, proposes a new locator from the failure's ARIA snapshot and uses it for one retry only; the permanent fix needs a person. | +| 9 | `triage` | Classifies failures (UI change, data, timing, real defect). | +| 10 | `human_review`, `ticket` | A QA approver confirms real defects or waives them; confirmed defects become tickets. | +| 11 | `reporter`, `learner` | Go / no-go by the QA rule; HTML and PDF report; test data clean-up summary. The Excel test script is built on download; Agent Studio events carry a signed link that opens it without a login for 7 days (`platform/links.py`). | +| 12 | Courier | Sends each cycle's events (`scripts_ready`, `failures_need_review`, `results`, `stopped`, `patch_update`) by push (a signed POST, or straight to Fusion), or queues them for the Fusion workflow to pull. | + +On the practice pod the same graph runs with the practice scenarios and a local browser. + +The run manager keeps queued jobs (`run_jobs`), so a gate answer survives a restart. A run that was running when the +server stopped is marked "interrupted" and is resumed by hand. LangGraph checkpoints (SQLite) let a paused run continue. + +The LangGraph path runs each attempt as one Playwright run (one per test user); it does not split it into chunks. + +**Temporal** (`FPT_ORCHESTRATOR=temporal`, the Compose shape) runs the same nodes as activities and splits execution +into chunks of `exec_chunk_size` (10). Its execute activity (`coworker/workflows/activities.py`) supports the practice +pod only: it starts the local practice pod (`ensure_mock`) and has no remote runner, no per-area test users and no +pre-flight. **Fusion pods are not supported under Temporal today.** ## Boundaries that matter - **Egress gate** (`platform/egress.py`): the only module that makes HTTP calls. It checks the kill switch, writes an audit record per call, pins each call to the configured host, and allows writes to Fusion only for seeding test - data (with `SEED_ALLOWED=1`) and cancelling it. -- **Vault** (`platform/vault.py`): secrets live in the environment (`FPT_SECRET_*`) or the encrypted vault file; API - answers never contain them; child processes get a scrubbed environment (`platform/procs.child_env`). -- **LLM router** (`llm/router.py`): client data never goes to an external model; only public or redacted payloads. + data (with `SEED_ALLOWED=1`) and cancelling it. Calls to the runner, the bucket and Agent Studio go through it too. +- **Vault** (`platform/vault.py`): a plain JSON file, `FPT_HOME/secrets/vault.json` (file mode 600), plus + `FPT_SECRET_` environment overrides. It is **not encrypted on disk**; it is encrypted only inside the state + snapshot. It holds `EVIDENCE_KEY`, the key of the evidence store. API answers never contain secrets; child processes + get a scrubbed environment (`platform/procs.child_env`). +- **LLM router** (`llm/router.py`): client data never goes to an external model. A request is public, or masked first: + values that look like client data are replaced by placeholders before the call and put back in the answer + (`platform/step_writer.py` `_call`, `platform/redaction.py`). A payload that still looks like client data is not sent + to the external model; the local model or the built-in fallback answers instead. - **QA rule**: the decision is computed by `reports/generate_report.py`, never by the AI. ## Data -SQLite at `$FPT_HOME/fpt.sqlite`, migrations in `coworker/platform/migrations/*.sql` (forward-only, applied by -`python -m coworker setup` at every start). Evidence (screenshots, videos, traces) encrypted under `$FPT_HOME/evidence` -with retention. Without a persistent disk, the whole data folder is saved encrypted to Supabase Storage every 60 s and -restored at boot. +SQLite at `$FPT_HOME/fpt.sqlite` and `checkpoints.sqlite`, migrations in `coworker/platform/migrations/*.sql` +(forward-only, applied by `python -m coworker setup` at every start). Evidence (screenshots, videos, traces) is +encrypted under `$FPT_HOME/evidence`, with retention. + +The Space has no persistent disk. `platform/statesync.py` saves an encrypted snapshot (Fernet, `FPT_STATE_KEY`) of the +two databases and the `secrets`, `runs`, `evidence`, `tickets`, `screens` and `library` folders to a bucket, and +restores it at start when the data folder is empty. + +| Store | Set by | Notes | +|---|---|---| +| OCI Object Storage | `OCI_STATE_PAR_URL`: a pre-authenticated request URL on one private bucket (`platform/ocistore.py`) | Used when set. | +| Supabase Storage | `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `SUPABASE_BUCKET` | Used when no OCI URL is set. | + +When a save happens: + +- **Periodically**, when the databases changed: checked every `FPT_STATE_SYNC_INTERVAL` seconds (default 60; at least + 300 on OCI, to stay inside the bucket's request budget; at least 10 on Supabase). +- **At once** on key events (`save_soon`): a screen read finished, a run waits for a person, a run ended, a run was + cancelled. +- **On shutdown**: a forced save. +- **On request**: `POST /api/storage/save` (administrator). Call it before every restart or deploy. + +At start, a screen read that the snapshot shows as running is marked interrupted (`PodRegistry.recover_screens`). The +snapshot serves one instance: two instances on one bucket overwrite each other. ## Web app diff --git a/docs/AUDIT.md b/docs/AUDIT.md index 00657b61dd4f456aeaad36096c8abb24792809fe..e956f85b6b6983b85400f7aa01fd9368161b5d53 100644 --- a/docs/AUDIT.md +++ b/docs/AUDIT.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [ARCHITECTURE.md](ARCHITECTURE.md), [DEPLOYMENT.md](DEPLOYMENT.md), [RUNBOOK.md](RUNBOOK.md), [REMOTE_RUNNER.md](REMOTE_RUNNER.md) and [SECURITY.md](SECURITY.md). + # Patchwise: production audit Branch `production-hardening`, started from `trio-apple-ui` at `1c7e8c0` on 3 Nov 2026. Every finding below comes from diff --git a/docs/DEPLOYMENT.md b/docs/DEPLOYMENT.md index ee0c187799e5329fdd15cf5460dd2640ba1502e4..523a12cda85498036b21d1a8c72cf3ef5f0e84bc 100644 --- a/docs/DEPLOYMENT.md +++ b/docs/DEPLOYMENT.md @@ -1,12 +1,12 @@ # Deployment -Two supported shapes. Both use the same image (`Dockerfile`: a web build stage, then a Python 3.13 runtime with Node -22 and Chromium, running as a non-root user under tini). +One image (`Dockerfile`: a web build stage, then a Python 3.13 runtime with Node 22 and Chromium, running as a +non-root user under tini), two shapes: -| Shape | When | Guide | +| Shape | What it runs | Guide | |---|---|---| -| Customer cloud: Docker Compose with Caddy (HTTPS) and Temporal, data on volumes | a client deployment | [deploy/DEPLOY.md](../deploy/DEPLOY.md) | -| Single container on a host without a disk (Hugging Face Space, Render), data saved to Supabase | demos, pilots | this page | +| **Hugging Face Space** (Docker) + remote browser runner + storage bucket | The running system: Fusion cycles, Agent Studio, the practice pod. Data is saved as an encrypted snapshot to OCI Object Storage or Supabase Storage. | this page, [REMOTE_RUNNER.md](REMOTE_RUNNER.md) | +| Docker Compose with Caddy (HTTPS) and Temporal, data on volumes | The practice pod only. **Fusion pods do not run in this shape today**: the Temporal execute activity (`coworker/workflows/activities.py`) starts the local practice pod and has no remote runner, per-area test users or pre-flight. | [deploy/DEPLOY.md](../deploy/DEPLOY.md) | ## Environments @@ -19,49 +19,95 @@ Dev, staging and production differ only in settings, never in code: | `FPT_CORS_ORIGINS` | the Vite dev server | `[]` | | `FPT_API_DOCS` | `1` | `0` | | `FPT_REGISTRATION` / `FPT_REGISTER_ROLE` | as needed | `0`, or `viewer` | -| `SUPABASE_BUCKET` | own bucket | one bucket per environment, never shared | +| `OCI_STATE_PAR_URL` or `SUPABASE_BUCKET` | own bucket | one bucket per environment, never shared | +| `FPT_REMOTE_RUNNER_URL` | none (local browser) | one runner per environment | | `FPT_ENVIRONMENT` | `development` | `staging` / `production` (labels error reports) | -Use one Hugging Face Space (or Compose project) per environment. Promote by deploying the same commit. +Use one Space per environment. Promote by deploying the same commit. ## Hugging Face Space The repository root is the Space: `README.md` front matter sets `sdk: docker` and `app_port: 8800`, and the `Dockerfile` carries the Space settings (viewer sign-ups, trusted proxy, no CORS, docs off, public URL). -1. Space **variables**: `SUPABASE_URL`, `FRONTIER_BASE_URL`, `FRONTIER_MODEL`, `FPT_BROWSER_RUNS=1` (16 GB hardware), - `FPT_BROWSER_SLOWMO_MS`, `FPT_FUSION_BASE_URL`, `FPT_ADMIN_EMAILS`. -2. Space **secrets**: `FPT_BOOTSTRAP_ADMIN_USER`, `FPT_BOOTSTRAP_ADMIN_PASSWORD`, `SUPABASE_ANON_KEY`, - `SUPABASE_SERVICE_KEY`, `FPT_STATE_KEY`, `FPT_SECRET_FRONTIER_API_KEY`, `FPT_SECRET_FUSION_USERNAME`, - `FPT_SECRET_FUSION_PASSWORD`, optionally `FPT_SECRET_METRICS_TOKEN`, `SENTRY_DSN`. - (Variables are public on a public Space; anything secret must be a secret.) -3. Upload the repository contents (or push to the Space's git remote). The Space builds the image and starts it. +1. Space **variables**: + - `FRONTIER_BASE_URL`, `FRONTIER_MODEL`, `FPT_ADMIN_EMAILS`, `SUPABASE_URL` (sign-in); + - `FPT_FUSION_BASE_URL`, `FPT_FUSION_NAME`, `FPT_FUSION_MODULES`, `FPT_FUSION_RELEASE`; + - `FPT_FUSION_AREA_USERS` (JSON, the test user per area, for example `{"PO": "prc_impl"}`; same password) and + `FPT_FUSION_WORKERS` (browsers at once on the runner, 1 to 4; default 3); + - `FPT_REMOTE_RUNNER_URL` (`https://`), `FPT_BROWSER_RUNS=1`, `FPT_BROWSER_SLOWMO_MS`. +2. Space **secrets**: + - `FPT_BOOTSTRAP_ADMIN_USER`, `FPT_BOOTSTRAP_ADMIN_PASSWORD`; + - `FPT_STATE_KEY`, the snapshot key (required with OCI, which has no service key to derive one from); + - `OCI_STATE_PAR_URL`, the bucket's pre-authenticated request URL (or Supabase Storage, below); + - `SUPABASE_ANON_KEY`, `SUPABASE_SERVICE_KEY` (sign-in, and the Supabase store); + - `FPT_SECRET_FRONTIER_API_KEY`, `FPT_SECRET_FUSION_USERNAME`, `FPT_SECRET_FUSION_PASSWORD`, + `FPT_SECRET_REMOTE_RUNNER_TOKEN`; + - optionally `FPT_SECRET_METRICS_TOKEN`, `SENTRY_DSN`. + + Variables are public on a public Space; anything secret must be a secret. +3. Deploy (next section). The Space builds the image and starts it. 4. Check: `https://.hf.space/api/ready` answers `"ready": true`; sign in; Test environments > Test connection on the Fusion pod shows all three checks. +### Every deploy or restart + +A Space deploy or restart stops the container. A test run that is running is interrupted, and anything changed since +the last save is lost unless it is saved first. + +1. **Check that nothing is running.** In the app, Home and Test runs show no run in progress and no pod card shows + its screens being read. Or: `GET /api/runs?status=running` and `GET /api/runs?status=queued` return no items, and + the runner's `GET https:///healthz` shows `"busy": false`. Wait, or cancel, before going on. +2. **Save the state** and wait for the answer: `POST /api/storage/save` (administrator). It answers + `{"saved", "last_saved_at", "bytes"}`; 502 when the save failed, 409 when this server does not save its state. +3. **Deploy**: upload the repository contents, or push to the Space's git remote. +4. **Update the runner** on the same commit: `deploy/runner/sync.sh https://` + ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)). Pre-flight stops a Fusion run when the runner has no scenario files. +5. **Check**: `/api/ready`; Settings > Storage and backups shows a save after the start; the runner's `/healthz` shows + the deployed commit as `version` and `"cases": true`. + **Rollback**: every upload is a commit in the Space repository. Re-upload the previous revision (or revert it in the -Space's Files tab); the data is untouched because it lives in Supabase. This was done on 24 Oct 2026 (revision -`1f5bc011`) and restored the working app in about 10 minutes. +Space's Files tab), then run `sync.sh` on that commit. The data is untouched because it lives in the bucket. ## Database migrations SQL files in `coworker/platform/migrations/` are applied in order by `python -m coworker setup`, which the container runs at every start. They are forward-only and additive (new tables and columns). To roll back a release that added a -migration: restore the backup taken before the upgrade (below), then deploy the previous image. +migration: restore the snapshot taken before the upgrade (RUNBOOK "Restore"), then deploy the previous image. ## Backups -- **Host without a disk**: the data folder is encrypted and saved to Supabase Storage every 60 s - (`state/latest.bin`), plus `state/previous.bin` from the start of each process. Status: Settings > Storage and - backups, `/api/ready` (signed in) and the metric `trio_backup_ok`. Manual: `python -m coworker state push|status`. -- **Compose**: `deploy/backup.sh /secure/backups` on a schedule (the archive contains the secrets vault: keep it encrypted). -- Try a restore once per quarter (RUNBOOK "Restore"). +**Space (no disk).** `platform/statesync.py` saves an encrypted archive of `FPT_HOME` (databases, vault, runs, +evidence, tickets, screens, library) as `state/latest.bin` in the bucket, with `state/meta.json` beside it. + +| Store | Settings | +|---|---| +| OCI Object Storage | `OCI_STATE_PAR_URL`: a pre-authenticated request on one private bucket, access "read and write objects", listing denied (`https://objectstorage..oraclecloud.com/p//n//b//o/`). Used when set. `FPT_STATE_KEY` is required. | +| Supabase Storage | `SUPABASE_URL`, `SUPABASE_SERVICE_KEY`, `SUPABASE_BUCKET`. The key is `FPT_STATE_KEY`, or is derived from the service key when that is not set. | + +When it saves: + +- every `FPT_STATE_SYNC_INTERVAL` seconds (default 60) when the databases changed; at least every 300 s on OCI (the + Always Free tier allows 50,000 requests a month), at least every 10 s on Supabase; +- at once when a screen read finishes, a run waits for a person, a run ends, or a run is cancelled; +- on shutdown (a forced save); +- on `POST /api/storage/save`, and with `python -m coworker state push`. + +The first save of each process copies what the bucket held to `state/previous.bin`. An archive above 45 MB leaves out +the evidence, then the folders of finished runs. If the start-up restore fails, saving pauses so the good copy is not +overwritten. Status: Settings > Storage and backups, `/api/ready` (`saved_state`, signed in), the metric +`trio_backup_ok`, `python -m coworker state status`. + +**Compose.** `deploy/backup.sh /secure/backups` on a schedule. The archive is not encrypted and contains the secrets +vault: encrypt it and restrict who can read it. + +Try a restore once per quarter (RUNBOOK "Restore"). ## Reverse proxy and TLS The app listens on plain http (port 8800). Put it behind a proxy that terminates TLS: Caddy in Compose -(`deploy/Caddyfile`), or the platform's proxy (Hugging Face, Render). Set `FPT_TRUST_PROXY=1` only when the app is -reachable through that proxy alone, and `FPT_COOKIE_SECURE=always`. +(`deploy/Caddyfile`), or the platform's proxy (Hugging Face). Set `FPT_TRUST_PROXY=1` only when the app is reachable +through that proxy alone, and `FPT_COOKIE_SECURE=always`. Production run command (what the container runs): `python -m coworker api --host 0.0.0.0 --port 8800`, after `python -m coworker state restore --soft` and `python -m coworker setup` (`deploy/entrypoint.sh`). @@ -71,7 +117,8 @@ Production run command (what the container runs): `python -m coworker api --host | Workload | Memory | CPU | |---|---|---| | Quick simulations only | 512 MB (CI rehearses this limit) | 0.5 | -| Full browser runs (Chromium) | 2 GB minimum, 4 GB comfortable; `shm_size: 1gb` | 2 | +| Browser runs on the server itself (practice pod) | 2 GB minimum, 4 GB comfortable; `shm_size: 1gb` | 2 | +| Remote runner for Fusion pods, 3 to 4 browsers ([REMOTE_RUNNER.md](REMOTE_RUNNER.md)) | 16 GB | 4 vCPU | ## Notifications (webhook) @@ -107,8 +154,8 @@ them. ## Notifications (Telegram) -Patchwise can send the same notifications to a Telegram chat itself, with no relay in between. Each message names the -coworker in bold, then the title and one sentence, with an **Open in Patchwise** button (only when `FPT_PUBLIC_URL` is +Astra can send the same notifications to a Telegram chat itself, with no relay in between. Each message names the +coworker in bold, then the title and one sentence, with an **Open in Astra** button (only when `FPT_PUBLIC_URL` is set, because Telegram accepts https links only). 1. In Telegram, open **@BotFather**, send `/newbot`, choose a name and a username. BotFather answers with the bot token. @@ -116,7 +163,7 @@ set, because Telegram accepts https links only). file, a commit or a chat message. (The vault name `TELEGRAM_BOT_TOKEN` and `FPT_SECRET_TELEGRAM_BOT_TOKEN` also work.) Restart the Space. 3. In Telegram, open your new bot and send `/start` (for a group: add the bot to the group and send a message there). -4. In Patchwise, open **Settings > Notifications > Find my chat**, pick the chat, and Patchwise sends a welcome message. +4. In Astra, open **Settings > Notifications > Find my chat**, pick the chat, and Astra sends a welcome message. 5. Press **Send a test message**. - **Chat**: chosen in Settings (stored in the app's settings), or fixed with `FPT_TELEGRAM_CHAT_ID`, which wins. @@ -152,7 +199,7 @@ With the bot token set, the app also reads what people send to the bot (long pol answers as the Ask page does. Full design in [CHANNELS.md](CHANNELS.md). **What each person does once to link their own chat:** -1. In Patchwise, open **Account > Telegram** and press **Get a link code**. +1. In Astra, open **Account > Telegram** and press **Get a link code**. 2. In Telegram, send the bot `/link CODE` within 10 minutes. From then on they get the notifications about runs they may read, and can use `/status`, `/run Procure-to-Pay quick`, or plain questions. Starting a run or approving scenarios always needs a button press; sign-off and failure decisions stay in the app. diff --git a/docs/FINAL_REPORT.md b/docs/FINAL_REPORT.md index 11af4e23dd9ddc3790a380718e6449d19c0626e2..15664acebe6732fda8abd7359c9a5c29daa222a7 100644 --- a/docs/FINAL_REPORT.md +++ b/docs/FINAL_REPORT.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [ARCHITECTURE.md](ARCHITECTURE.md), [DEPLOYMENT.md](DEPLOYMENT.md), [RUNBOOK.md](RUNBOOK.md), [REMOTE_RUNNER.md](REMOTE_RUNNER.md) and [SECURITY.md](SECURITY.md). + # Final report: production hardening Branch `production-hardening` (from `trio-apple-ui` at `1c7e8c0`), 3 Nov 2026. Detail and evidence per item: diff --git a/docs/FRONTEND_AUDIT.md b/docs/FRONTEND_AUDIT.md index e2f6e04a67bec9a0da4cc5db2e4b908df28403cd..e49c4c8adec90b6b7400b0336d0af577cc57d330 100644 --- a/docs/FRONTEND_AUDIT.md +++ b/docs/FRONTEND_AUDIT.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](ARCHITECTURE.md), [DEPLOYMENT.md](DEPLOYMENT.md), [RUNBOOK.md](RUNBOOK.md), [REMOTE_RUNNER.md](REMOTE_RUNNER.md) and [SECURITY.md](SECURITY.md). + # Frontend audit (Patchwise web app) Branch `frontend-polish`, base commit `84145a2`. Step 1 of the frontend-polish plan: findings only, no code changed. diff --git a/docs/QUALITY.md b/docs/QUALITY.md index 58973d6c299cd52eaece67aaa26bab5aac873c5c..3542b59c4f857ddbbe5b8704c924c65aba400585 100644 --- a/docs/QUALITY.md +++ b/docs/QUALITY.md @@ -1,6 +1,25 @@ -# Web app quality gates +# Quality gates -**Audience:** anyone changing the web app (`web/`). +**Audience:** anyone changing Astra. The backend and agent gates come first; the web app gates follow. + +## Backend and agent gates + +A release goes out only when every gate below passes. The first one runs in CI on every push; the others need a +Fusion test pod and are checked by a person on the release candidate, before the deploy. + +| Gate | Checks | Run | Where | +|---|---|---|---| +| Full test suite | Every backend test, with the browser in stub mode; ruff lint; `pip-audit` | `PLAYWRIGHT_MODE=stub python -m pytest coworker/tests triage/tests -q`, `ruff check coworker triage reports qa` | CI (`backend`) | +| Container self-test | The image starts, serves the app, the practice pod answers; `selftest` offline and `--live`; `deploy/smoke_run.py` quick and `--full` on the practice pod | `.github/workflows/image.yml` | CI (`image`, on `main`) | +| Scenario yield per area | For each business area of a live Fusion run, the AI wrote scenarios and they reached the gate. The run's events carry one line per area: "AP: the AI model wrote N scenario(s), offered for approval ..." (or "... M passed the dry run" with `FPT_FUSION_AI_DRY_RUN=1`). An area with 0, or with "no new scenario was written", fails the gate until the reason in that line is fixed. | A live run on the Fusion pod; `GET /api/runs/{id}/events` | Release candidate | +| Screen coverage of key tasks | The screens read for each area include its key business tasks (`platform/fusion_catalog.py` `key_tasks`, for example Create Invoice, Manage Invoices for AP). The pod card lists the screens read and the ones that failed; a key task missing there means the AI designs from the wrong screens. | Test environments > the pod > Read screens; the pod's `screens` state | Release candidate | +| Test data from the right business unit | The pod's sampled test data (Test environments) uses the business unit the tests run in, and the invoice line account comes from that unit's chart of accounts. Unit test: `test_discovery.py` `test_the_line_account_comes_from_the_tests_business_unit`. | Test environments > Discover on the pod, then read its test data | CI and release candidate | +| Live smoke run | On the release candidate, after `deploy/runner/sync.sh`: a short live run (depth `smoke`, real browser) on the Fusion pod through the runner. Pre-flight passes (runner version is the deployed commit, sign-in works, test data present), the scenarios run in the browser, triage and the report finish, and the Excel test script downloads. | Start a run from the app on the Fusion pod | Release candidate | + +The suite covers the design rules behind these gates (`test_regression_checks.py`: key screens first, no screen taking more than +its share, catalogue regression checks asked at depth `full` within the cap), but only a live run shows the yield on a real pod. + +## Web app gates All commands run in `web/`. The browser gates start their own backend and practice app on a fresh, throwaway data folder (`e2e/playwright.config.ts`). Before the first run you need: - the Python virtual environment in `architecture/.venv` (or a global `python`); diff --git a/docs/REMOTE_RUNNER.md b/docs/REMOTE_RUNNER.md index 03036b57d6c5db1d266ae3baf48b5ebe4c3036c8..7e4d4d870b15d51a45c670503821a398c47ee2b0 100644 --- a/docs/REMOTE_RUNNER.md +++ b/docs/REMOTE_RUNNER.md @@ -1,83 +1,141 @@ # Remote browser runner -Use the remote runner when the Patchwise server's network is refused by Oracle's edge. For example, Hugging Face Spaces -get "Access Denied" from Akamai on Oracle demo pods. With the runner, the browser part of runs on an Oracle Fusion pod -happens on another host. Everything else stays where it is: approvals, AI agents, triage, reports and evidence. - -- **Server side:** `coworker/adapters/remote_runner.py`, wired in `coworker/graph/nodes/execute.py` (`run_planned`) and - `coworker/adapters/screens.py` (`explore`, `capture`). -- **Runner side:** `automation/remote_runner/server.py` (standard library only). -- **Scope:** everything that opens a browser on a Fusion pod goes to the runner: - - test attempts (`playwright.fusion.config.ts`); - - reading the pod's screens before scenarios are written (the explorer and single-screen capture). - - The practice pod and stub runs stay local. - -## Reading screens on the runner - -`POST /v1/screens` takes: - -- `kind`: `explore` (with the explorer's `plan`) or `capture` (with a `task` such as "Payables > Invoices > Create - Invoice"); -- `env`: the pod's address and test user only. - -It shares the one-browser lock with the attempts, and is polled and cancelled the same way. The poll takes -`?since=` to return the newest log lines, so the pod card shows the progress. The bundle holds the log and the -`out/` files: the inventories (`.json`, Oracle's labels only) and the list choices (`.values`). Patchwise -puts them in the pod's screens folder and checks them with the same privacy rule as a local read. - -## How it works - -1. **The attempt is sent.** Patchwise posts it through the egress gate (https, the runner's host only) to - `POST /v1/attempts`. The body holds: - - the case ids and the Playwright config; - - the pod environment (address, test user, test data); - - AI-written draft specs and approved library specs; - - locator overrides from self-heal. - - The audit log records the ids and the config, never the password. -2. **It is polled.** Patchwise asks `GET /v1/attempts/{id}` every few seconds. The emergency stop cancels the attempt - on the runner. -3. **The results come back.** `GET /v1/attempts/{id}/bundle` returns one zip with: - - the Playwright JSON report, with attachment paths relative to the run directory; - - the run directory (screenshots, videos, traces); - - the pod values tried; - - the ledger of created test records; - - the log. - - Patchwise unpacks it where a local attempt leaves its files, so evidence, triage, clean-up and reports work unchanged. - -**The runner's safeguards:** - -- It runs one attempt at a time. -- Every call needs `Authorization: Bearer `, compared in constant time. -- It accepts only known environment keys, the Patchwise configs, plain case ids and plain spec names. -- It never ships the Fusion session cookies. -- It deletes finished attempts after 24 hours. -- The password exists only in the Playwright process's environment, never on disk. +Astra runs on a Hugging Face Space, and Oracle's edge (Akamai) answers "Access Denied" to the Space's network on +Oracle demo pods. So the browsers that test or read an Oracle Fusion pod run on another host: the remote runner. +Everything else stays on the Space: approvals, AI agents, triage, reports and evidence. + +- **Server side:** `coworker/adapters/remote_runner.py`, used by `coworker/graph/nodes/execute.py` (`run_planned`) and + `coworker/adapters/screens.py` (`explore`, `capture`); pre-flight in `coworker/platform/preflight.py`. +- **Runner side:** `automation/remote_runner/server.py` (Python standard library only), behind Caddy for HTTPS. +- **Switched on by** `FPT_REMOTE_RUNNER_URL=https://` and the token in the vault as `remote_runner.token` + (`FPT_SECRET_REMOTE_RUNNER_TOKEN`). Remove the URL to run browsers on the server itself again. + +## What runs on the runner + +| Job | Sent as | When | +|---|---|---| +| Test attempts on a Fusion pod (`playwright.fusion.config.ts`) | `POST /v1/attempts` | The executor step; one attempt per test user when areas sign in as different users (`FPT_FUSION_AREA_USERS`) | +| Screen reading: the explorer (`explore`, with the explorer's plan) and one screen (`capture`, a task such as "Payables > Invoices > Create Invoice") | `POST /v1/screens` | In a run, before the AI designs scenarios; in the background after discovery; Read screens on the pod's card | + +The practice pod and quick simulations stay on the server. + +The AI dry run (`FPT_FUSION_AI_DRY_RUN=1`, off by default) does **not** use the runner: `graph/nodes/ai_scenarios.py` +`dry_run` starts the browser on the Astra server itself. On a Space whose network Oracle's edge refuses, that dry run +fails. Keep it off while Fusion browsers need the runner. + +## One job at a time + +The runner holds one lock for every job: attempts and screen reads share it. A second job while one is running gets +**HTTP 409** ("another attempt is running on this runner"). Astra does not wait or queue on a 409: + +- a test run fails with "the remote browser runner refused the attempt (HTTP 409 ...)"; resume it when the runner is free; +- a screen read fails with the same reason on the pod's card; read the screens again. + +The usual cause is a background screen read (after discovery, or a release change) overlapping a run. Check +`/healthz` (`busy`) before starting work by hand. + +Within one job, `FPT_FUSION_WORKERS` (set on the Astra server, sent with each attempt; 1 to 4, default 3) is how many +browsers run at once. + +## Long runs, restarts and a busy runner + +- **Each pass has a time budget for its size.** An attempt runs in passes of at most `FPT_FUSION_CHUNK_SCENARIOS` + scenarios (default 24). Each pass gets `FPT_FUSION_SCENARIO_MINUTES` (default 12) per scenario a worker runs, plus 10 + minutes of start-up, kept between `FPT_FUSION_ATTEMPT_MIN_MINUTES` (30) and `FPT_FUSION_ATTEMPT_MAX_MINUTES` (240). + A pass that runs out of time is first asked to stop, so Playwright still writes its report; one that writes none + loses only its own scenarios, which are recorded as timed out and run again in the retry. +- **A restart of the Astra server does not lose the pass.** The runner job's id is kept in the run folder + (`remote-job.json`) while it runs. Resume the run: it follows the same job and collects its results. Finished passes + are kept. Cancelling the run instead stops the job and keeps the ledger of test records it made, for the clean-up. +- **A restart of the runner fails the pass in seconds.** The runner keeps each job's state in its folder (`job.json`). A + job that was running when it restarted is reported `lost`, and an older runner answers 404. Astra stops waiting at + once and says so. +- **A busy runner is waited for.** The runner takes one job at a time. A run or screen read that finds it busy waits up + to `FPT_REMOTE_RUNNER_BUSY_WAIT_MINUTES` (default 15) and notes it in the run's activity. Pre-flight reports a busy + runner as information, not as a failure. +- **Pre-flight compares versions.** When this server knows its commit (`FPT_COMMIT`, or a `VERSION` file at the repo + root), a runner on another commit fails pre-flight: run `deploy/runner/sync.sh` on the deployed commit. + +## How an attempt works + +1. **Sent.** Astra posts it through the egress gate (https, the runner's host only) to `POST /v1/attempts`. The body + holds the case ids and the Playwright config; the pod environment (address, test user and password, test data); + AI-written draft specs, approved library specs and their step files; locator overrides from self-heal. The audit + log records the ids and the config, never the password. +2. **Polled.** Astra asks `GET /v1/attempts/{id}` every few seconds (every 2 s with the Live panel, which also pulls + `/v1/attempts/{id}/live` frames). The emergency stop cancels the job on the runner (`POST .../cancel`). +3. **Collected.** `GET /v1/attempts/{id}/bundle` returns one zip: the Playwright JSON report (attachment paths + relative to the run directory), the run directory (screenshots, videos, traces, without the Fusion session file), + the pod values tried, the ledger of created test records, and the log. Astra unpacks it where a local attempt + leaves its files, so evidence, triage, clean-up and reports work unchanged. + +A screen read works the same way through `POST /v1/screens`. Its poll takes `?since=` and returns the newest log +lines for the pod card's progress. The bundle holds the log and the `out/` files: the inventories (`.json`, +Oracle's labels only) and the list choices (`.values`). Astra checks them with the same privacy rule as a local +read. + +## Jobs live in memory + +The runner keeps its job table in memory. After a runner restart it no longer knows the jobs it was running: their +polls get 404, and Astra waits until the job's deadline (an attempt: its timeout plus 5 minutes) before failing the +run. Do not restart the runner while `/healthz` shows `"busy": true`; `sync.sh` refuses to. + +## Data on the runner + +Each job has a folder, `RUNNER_HOME/job_`, with the specs, the log, the report, screenshots, videos and traces. +These files are **not encrypted** on the runner. They are deleted `RUNNER_KEEP_HOURS` (default 24) after the job +started, by a sweep every 10 minutes. Folders left from before a runner restart are swept by their age on disk. + +The Fusion sign-in session file is written in the run directory and removed by Playwright's teardown; it is never +put in the bundle. A job that was killed may leave it in its folder until the sweep. + +## Safeguards + +- One job at a time (see above). +- Every call except `/healthz` needs `Authorization: Bearer `, compared in constant time. The service + refuses to start without a token of at least 24 characters. +- Only known environment keys, the two Astra Playwright configs, plain case ids and plain spec names are accepted; + bodies are limited to 20 MB. +- The service listens on `127.0.0.1` only; Caddy serves HTTPS in front. +- The Fusion password is passed in the Playwright process's environment, not written to disk by the runner. +- The runner's token is never passed to the Playwright process. + +## `/healthz` + +`GET /healthz` needs no token and returns: + +| Field | Meaning | +|---|---| +| `ok` | The service has a token. | +| `busy` | A job holds the lock. | +| `automation` | `AUTOMATION_DIR` exists. | +| `cases` | The scenario files the step specs read (`tests/cases`, next to `automation/`) are there. | +| `version` | The commit `sync.sh` installed (the `VERSION` file), or `unknown`. | + +Pre-flight reads it before every Fusion browser run: a runner that does not answer, has no token or no test code, or +has no scenario files stops the run before any browser starts. ## Set up a runner (Ubuntu 22.04) -**1. Install the tools and the test suite.** Install Node 22 and Python 3, then copy the same version of the code that -the Patchwise server runs: +**1. Tools.** Install Node 22, Python 3, and Caddy. -```bash -git archive main automation tests | tar -x -C ~/pw # from the repository -cd ~/pw/automation && npm ci && npx playwright install --with-deps chromium -``` - -**2. Store the token.** It needs at least 24 random characters. Keep it in a root-only file, `/etc/patchwise/runner.env`: +**2. Token and settings.** The token needs at least 24 random characters. Keep it in a root-only environment file, +for example `/etc/astra/runner.env`: ``` RUNNER_TOKEN= -AUTOMATION_DIR=/home/ubuntu/pw/automation +AUTOMATION_DIR=/home/ubuntu/astra/automation RUNNER_HOME=/home/ubuntu/runner-data ``` -**3. Run the service.** It listens on `127.0.0.1:8899`. Use a systemd unit with `User=ubuntu`, the environment file, -`ExecStart=/usr/bin/python3 -I /home/ubuntu/pw/automation/remote_runner/server.py` and `Restart=always`. +Optional: `RUNNER_PORT` (default 8899), `RUNNER_KEEP_HOURS` (default 24). + +**3. Service.** A systemd unit named `astra-runner` (the name `sync.sh` restarts; another name goes in +`RUNNER_SERVICE`), with `User=ubuntu`, `EnvironmentFile=/etc/astra/runner.env`, +`ExecStart=/usr/bin/python3 -I /home/ubuntu/astra/automation/remote_runner/server.py` and `Restart=always`. The +`ubuntu` user needs `sudo systemctl restart astra-runner` without a password, for `sync.sh`. -**4. Put HTTPS in front.** Caddy can serve a real certificate for an IP using `.sslip.io`: +**4. HTTPS.** Caddy can serve a real certificate for an IP through `.sslip.io`: ``` 129-225-117-95.sslip.io { @@ -87,12 +145,47 @@ RUNNER_HOME=/home/ubuntu/runner-data Open ports 80 and 443 in the cloud firewall. On Oracle's Ubuntu images, also open them in iptables. -**5. Point the Patchwise server at the runner.** Set: +**5. Install the code** with `sync.sh` from the repository (next section). The first time, also install the +browser's system libraries once: `cd ~/astra/automation && sudo npx playwright install-deps chromium`. + +**6. Point Astra at the runner.** On the Space: `FPT_REMOTE_RUNNER_URL=https://` (variable) and +`FPT_SECRET_REMOTE_RUNNER_TOKEN=` (secret). Restart (save first: RUNBOOK). + +## Update the runner: `deploy/runner/sync.sh` + +Run it after **every** Astra deploy, from the repository, on the commit that was deployed: + +```bash +deploy/runner/sync.sh ubuntu@ ~/.ssh/ https:// +``` + +What it does: + +1. Refuses when `automation/` or `tests/` has uncommitted changes, and when the runner's `/healthz` shows + `"busy": true` (exit 2). +2. Packs the committed `automation/` and `tests/` (`git archive HEAD`) and unpacks them in `~/astra.new` on the + runner, with the commit in `VERSION`. +3. Reuses `node_modules` when `package-lock.json` did not change, else runs `npm ci`; then installs Chromium. +4. Checks `/healthz` again: a job that started during the install means nothing is switched (exit 2). +5. Moves `~/astra` to `~/astra.prev`, puts the new copy in place, restarts the service. +6. Verifies that `/healthz` reports the new commit as `version` and `"cases": true` (exit 3 otherwise: check the + service's `AUTOMATION_DIR`), and prints `/healthz` from outside when the URL is given. + +To roll back, run it on the previous commit. + +## A PC as the runner + +`deploy/pc-runner/start-pc-runner.ps1` runs the runner on a Windows PC (port 8898) and opens an SSH tunnel to the +runner VM, so the VM's port 8898 leads to the PC. The VM's Caddy must be set to send to port 8898 first while it +answers and to fall back to its own runner on 8899; that Caddy configuration is not in the repository. The PC runs +the repository's own `automation/`, so it is not updated by `sync.sh` and its `version` is `unknown`. -- `FPT_REMOTE_RUNNER_URL=https://`, as an environment variable; -- `FPT_SECRET_REMOTE_RUNNER_TOKEN=`, as a secret. +## Sizing -Remove `FPT_REMOTE_RUNNER_URL` to run browsers on the server itself again. +| Host | Fits | +|---|---| +| 4 vCPU, 16 GB RAM | 3 to 4 browsers at once (`FPT_FUSION_WORKERS=3` or `4`): regression runs and screen reading of several areas. | +| 1 GB RAM (plus swap), for example an OCI Always Free AMD Micro | One browser for a short run, at best (`FPT_FUSION_WORKERS=1` on the Astra server). **Not enough for regression runs.** | -The first runner is the OCI Always Free AMD Micro VM `patchwise-watcher` (1 GB RAM plus 2 GB swap): enough for one -browser. Keep `FPT_FUSION_WORKERS=1` there. +`FPT_FUSION_WORKERS` is a setting of the Astra server and applies to every Fusion run; lower it there when the runner +is small. diff --git a/docs/RUNBOOK.md b/docs/RUNBOOK.md index b5a679ba68a2748ed364d1293a309022a4931e99..885e54c5cdf31244a9c92a3a8c1d5c76b0396735 100644 --- a/docs/RUNBOOK.md +++ b/docs/RUNBOOK.md @@ -1,21 +1,40 @@ # Runbook -Commands are for the container (`docker compose exec app ...` in Compose; the Space's terminal or a local run -otherwise). `python -m coworker ` is the CLI. +Commands are for the container (the Space's terminal, `docker compose exec app ...` in Compose, or a local run). +`python -m coworker ` is the CLI. ## Daily checks 1. `/api/ready` answers `"ready": true`. -2. Settings > Storage and backups shows "Backups are working" (hosts without a disk). -3. Home: nothing unexpectedly "Waiting for you"; Settings > Schedules: no "The last start failed". +2. Settings > Storage and backups shows "Backups are working" and a recent save (hosts without a disk). +3. The runner's `https:///healthz` answers `"ok": true`, `"automation": true`, `"cases": true`, and the + `version` is the commit the Space runs. +4. Home: nothing unexpectedly "Waiting for you"; Settings > Schedules: no "The last start failed". + +## Before every deploy or restart + +A deploy or restart of the Space interrupts a running test run and loses anything not saved yet. Check right before, +not an hour before. + +1. **No active work.** No run is running or queued (`GET /api/runs?status=running`, `?status=queued`), no pod is + reading its screens, and the runner's `/healthz` shows `"busy": false`. Wait for it to end, or cancel it. +2. **Save.** `POST /api/storage/save` as an administrator, and wait for the answer (`saved`, `last_saved_at`). 502 means + the save failed: do not restart until it works. From the Space's terminal: `python -m coworker state push`. +3. **Deploy or restart.** +4. **Update the runner** on the commit just deployed: `deploy/runner/sync.sh https://`. + It refuses while the runner is busy (exit 2); run it again when the run ends. +5. **Smoke test**: sign in, Test environments > Test connection, then a quick run on the Fusion pod. ## Incidents | Symptom | What to do | |---|---| | The app does not start; log says `error parsing value for field "X"` | Fix setting X (the message names it); restart. | -| `/api/ready` is 503, `worker: false` | Restart the app. Runs that were running become "interrupted": open each and press Resume. | -| A run failed with "The test browser stopped unexpectedly" | The server ran out of memory. Run fewer business areas at once, or give the server more memory. | +| `/api/ready` is 503, `worker: false` | Restart the app (save first, above). Runs that were running become "interrupted": open each and press Resume. | +| A pod card says "interrupted by a server restart: read the screens again" | The restart cut off a screen read. Press Read screens on the pod's card, or let the next run read them. | +| A run stopped with "Pre-flight check failed, no browser was started" | Read the reason: the runner does not answer or has no scenario files (run `sync.sh`), or the test user cannot sign in. | +| A run or screen read failed with "the remote browser runner refused ... (HTTP 409 ...)" | The runner was busy with another job (one at a time). Resume the run, or read the screens again, when `/healthz` shows `"busy": false`. | +| A run failed with "The test browser stopped unexpectedly" | The browser host ran out of memory. Lower `FPT_FUSION_WORKERS`, run fewer areas at once, or give the runner more memory (REMOTE_RUNNER.md "Sizing"). | | A run says "N test invoices were left on the Oracle Fusion pod" | The automatic clean-up could not reach Fusion. Cancel those invoice numbers in Fusion (Payables > Manage Invoices). | | Test connection fails at "Sign-in" (HTTP 401) | The Fusion test user's password changed or the account is locked: fix it in Fusion, then Test environments > Sign-in details. Too many failed sign-ins lock Fusion users: do not retry in a loop. | | A schedule switched itself off | It failed 3 times in a row; the reason is on the schedule. Fix the cause and switch it on again. | @@ -26,34 +45,60 @@ otherwise). `python -m coworker ` is the CLI. ## Backups -**Host without a disk (Supabase).** The app saves `state/latest.bin` every 60 s and keeps `state/previous.bin` from -the start of the current process. If a start-up restore fails, saving pauses (a notice in the app and -`saved_state.paused` on `/api/ready`) so the good copy is not overwritten. +**Host without a disk.** The app saves `state/latest.bin` to the bucket (OCI Object Storage when `OCI_STATE_PAR_URL` is +set, else Supabase Storage): when the data changed, at most every `FPT_STATE_SYNC_INTERVAL` seconds (at least 300 on +OCI); at once when a screen read finishes or a run waits for a person, ends or is cancelled; and on shutdown. The first +save of each process keeps the archive it found as `state/previous.bin`. If a start-up restore fails, saving pauses +(a notice in the app and `saved_state.paused` on `/api/ready`) so the good copy is not overwritten. + +- Status: `python -m coworker state status` (prints `state/meta.json`: when, how big, why, what was left out) +- Save now: `POST /api/storage/save`, or `python -m coworker state push` -- Status: `python -m coworker state status` -- Save now: `python -m coworker state push` -- **Restore**: stop the app; in the Supabase bucket copy `state/previous.bin` over `state/latest.bin` if the latest - copy is bad; start the app with an empty data folder (a new container), which restores at start. +### Restore + +The app restores at start when its data folder is empty, so a restore is: put the right archive in place as +`state/latest.bin`, then start a new container (a Space restart or a new deploy starts empty). + +1. Stop the app (pause the Space) so it cannot save over the archive you are about to put back. +2. If the latest copy is bad, put `state/previous.bin` in place of `state/latest.bin`: + - **OCI Object Storage**: in the OCI console, open the bucket, download `state/previous.bin` and upload it as + `state/latest.bin`. Or with the pre-authenticated URL (keep it out of shell history and logs): + `curl -fsS -o previous.bin "$OCI_STATE_PAR_URL"state/previous.bin`, then + `curl -fsS -X PUT --data-binary @previous.bin "$OCI_STATE_PAR_URL"state/latest.bin`. + - **Supabase Storage**: in the Supabase dashboard, Storage > the bucket > `state/`: download `previous.bin` and + upload it as `latest.bin` (replace). +3. Start the app. Check the log line `state restored from the OCI bucket` (or `from Supabase Storage`), then sign in + and open a recent run. +4. If it says "the state archive cannot be decrypted with this key", `FPT_STATE_KEY` differs from the key the archive + was saved with: set the old key and restart. **Compose.** `deploy/backup.sh /secure/backups`. Restore: stop the stack, put the archive's files back in the -`fpt-data` volume, start the stack. Keep backup archives encrypted: they contain the secrets vault. +`fpt-data` volume, start the stack. Keep backup archives encrypted: they contain the secrets vault in plain text. ## Upgrade and rollback -1. Take a backup (above). +1. Follow "Before every deploy or restart" (above): nothing running, state saved. 2. Deploy the new image or upload the new revision. Migrations run at start (forward-only). -3. Smoke test: sign in, Test environments > Test connection, start a quick simulation and approve it. -4. Rollback: deploy the previous image or Space revision; if the release added a migration, restore the backup first. +3. Update the runner with `sync.sh` on the same commit. +4. Smoke test: sign in, Test environments > Test connection, a quick run on the Fusion pod and approve it. +5. Rollback: deploy the previous image or Space revision and `sync.sh` that commit; if the release added a migration, + restore the snapshot taken before the upgrade first. ## Rotating secrets -Change the value in the platform's secret store, then restart. Revoke the old key at its provider (NVIDIA, -Hugging Face, Supabase). For the Fusion test user, change the password in Fusion first. -`FPT_STATE_KEY` is special: the backup is encrypted with it. To change it, take `state push` with the old key, set the -new key, restart, and confirm a new save; keep the old key until the new backup is confirmed. +Change the value in the platform's secret store, then restart (save first). Revoke the old key at its provider (NVIDIA, +Hugging Face, Supabase, OCI). For the Fusion test user, change the password in Fusion first. For the runner token, +change `RUNNER_TOKEN` on the runner and `FPT_SECRET_REMOTE_RUNNER_TOKEN` on the Space together. + +`OCI_STATE_PAR_URL` grants access by itself: to rotate it, make a new pre-authenticated request on the bucket, set it, +restart, confirm a save, then delete the old request in the OCI console. + +`FPT_STATE_KEY` is special: the snapshot is encrypted with it. To change it, `state push` with the old key, set the new +key, restart, and confirm a new save; keep the old key until the new save is confirmed. ## Retention Screenshots, videos and traces: `EVIDENCE_RETENTION_DAYS` (30). Workflow checkpoints of finished runs: `CHECKPOINT_RETENTION_DAYS` (7). Run folders: `RUN_FILES_RETENTION_DAYS` (90). Run records and the audit log are -kept. The clean-up runs daily from the scheduler; `python -m coworker purge` runs it now. +kept. The clean-up runs daily from the scheduler; `python -m coworker purge` runs it now. On the runner, job folders +are deleted about `RUNNER_KEEP_HOURS` (24) after they start (REMOTE_RUNNER.md). diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 28546db39aceecedc7b4aa60a31d8189cc40f324..fe13954e252cc719da2c1ab1c1afc55d9ee189be 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -19,29 +19,42 @@ Report a vulnerability privately to the repository owner; do not open a public i | Outbound calls | one egress gate, host-pinned, audited, kill switch | `platform/egress.py` | | Notifications | webhook to the configured host only (https), HMAC-SHA256 signed, retried then given up; payload is plain words, run names, area names and counts, never secrets, test data or screenshots; errors redacted | `platform/notify.py` | | Telegram notifications | sent only to api.telegram.org through the egress gate; the bot token is a secret (vault / Space secret) that is never logged or returned: the audit shows `api.telegram.org/bot(hidden)/...`, error texts have it removed, and refused requests are audited with the hidden address too; same message content rules as the webhook; only administrators choose the chat | `platform/notify.py` | -| Two-way bot (Telegram, Teams next) | a chat is linked to one Patchwise account by a one-time code made by that signed-in person (hashed, single use, 10 minutes, 5 tries per 10 minutes); the bot then acts as that person with their role: free text and /run go through the Ask service (propose, then the person's button press re-checks RBAC and state through api/actions.py); buttons carry only a random id, stored server-side and bound to chat, person, 24-hour expiry and single use; sign-off, failure verdicts, the kill switch and administration are never offered (links only); every step audited as `channel.*`; notifications reach a linked person only for runs they may read, from when they linked; the bot token is masked in HTTP client logs as well | `channels/`, `api/routes/channels.py`, docs/CHANNELS.md | +| Two-way bot (Telegram, Teams next) | a chat is linked to one Astra account by a one-time code made by that signed-in person (hashed, single use, 10 minutes, 5 tries per 10 minutes); the bot then acts as that person with their role: free text and /run go through the Ask service (propose, then the person's button press re-checks RBAC and state through api/actions.py); buttons carry only a random id, stored server-side and bound to chat, person, 24-hour expiry and single use; sign-off, failure verdicts, the kill switch and administration are never offered (links only); every step audited as `channel.*`; notifications reach a linked person only for runs they may read, from when they linked; the bot token is masked in HTTP client logs as well | `channels/`, `api/routes/channels.py`, docs/CHANNELS.md | | MCP connector | personal access tokens (`pwt_`, shown once, SHA-256 at rest, compared in constant time, 1 to 365 days, revocable by the owner or an administrator), accepted only on `/mcp` and refused on `/api`; always the owner's current role (disabled owners refused); scopes `read` or `read,act`; acting is propose → `confirm` (single use, 10 minutes, same person and token, re-checks role, run state and the emergency stop); sign-off, verdicts, the emergency stop and administration never offered; 60 requests a minute per token, 64 KB bodies, foreign browser origins refused, no CORS, cookies ignored; tokens masked in logs, never in the audit (`token.*`, `mcp.*` events) | `api/mcp.py`, `platform/api_tokens.py`, docs/MCP.md | | A2A agent | the same personal access tokens, scopes, per-token rate limit (shared with `/mcp`), origin guard and propose → confirm path as MCP, at `/a2a` (bodies up to 256 KB, 20 parts, 8,000 characters of text, 50 cases); the agent card at `/.well-known/agent-card.json` is public and holds no secrets; tasks are bound to their owner and token (admins can read, not act); a caller can never approve custom cases, scenarios or failures, sign off, waive or touch the emergency stop; caller facts (pod, patch changes) are stored as untrusted data, never sent to an LLM as instructions, and their URLs are displayed only, never fetched; every task, state change, proposal, confirm, run, refusal and cancel is audited as `a2a.*` without tokens | `api/a2a.py`, docs/A2A.md | -| Secrets | env or encrypted vault; never in API answers, logs or child processes | `platform/vault.py`, `platform/procs.py` | +| Oracle AI Agent Studio | OAuth 2.0 client credentials (client secret kept as a hash; bearer tokens `pwa_`, one hour, hashed at rest, scope `patchwise.invoke` only: start cycles, forward approvals, read their status); test data must be synthetic and values that look like personal or payment data are refused; callbacks HMAC-signed with the client's signing key (kept in the vault), sent through the egress gate to the client's own address only | `platform/agent_studio.py`, docs/AGENT_STUDIO.md | +| Secrets | `FPT_SECRET_*` environment values or the vault file (plain JSON, mode 600, encrypted only inside the state snapshot: see Residual risks); never in API answers, logs or child processes | `platform/vault.py`, `platform/procs.py` | +| State snapshot | `FPT_HOME` archived and encrypted (Fernet, `FPT_STATE_KEY`) before it leaves; the bucket holds ciphertext only; the OCI pre-authenticated URL is read from the environment or the vault only and audited with its token replaced by `***` | `platform/statesync.py`, `platform/ocistore.py` | +| Remote runner | HTTPS behind Caddy, bearer token compared in constant time, one job at a time, allow-listed environment keys, configs and file names; the token is never passed to Playwright; the Fusion session file is never returned | `automation/remote_runner/server.py`, docs/REMOTE_RUNNER.md | +| AI calls | client data masked before a request leaves and restored in the answer; a payload that still looks like client data is not sent to the external model | `platform/step_writer.py`, `platform/redaction.py`, `llm/router.py` | | Fusion | production pods refused; read-only except seeding and cancelling test data; password kept out of traces | `platform/pods.py`, `automation/src/fusion/ui.ts` | | Audit | append-only, hash-chained, verifiable (`/api/audit/verify`) | `platform/audit.py` | | Public surface | anonymous `/api/ready` shows no internals; API docs off in production | `api/routes/admin.py` | | Exports | CSV cells that start with `= + - @` are neutralised | `api/routes/runs.py` | -## Known residual risks (decisions recorded in docs/AUDIT.md) +## Residual risks -- The backup archive key is derived from the Supabase service key unless `FPT_STATE_KEY` is set (S8). -- Supabase "Confirm email" must stay on for the admin list to be safe (S5). -- react-router 6 has two moderate advisories fixed only in 7.x; the open-redirect one is not reachable here (the - return path after sign-in is checked). -- A Copilot Studio agent using a personal token acts as that one person for everyone who uses the agent; use a `read` - token from a least-privileged account until OAuth (docs/MCP.md, phase 2). -- Python dependencies are pinned at top level only; base images are not digest-pinned. +Risks that remain in the running system, with what limits them today. + +| Risk | Detail | What limits it | +|---|---|---| +| Plain-text vault, and the evidence key in the same archive | The vault (`FPT_HOME/secrets/vault.json`) is a plain JSON file on the server's disk. It holds `EVIDENCE_KEY`, the pods' test-user passwords entered in the app, the AI model key saved in Settings, the link signing key, Agent Studio signing keys and Fusion client secrets, and the chat webhook addresses. The state snapshot and the Compose backup contain both the vault and the encrypted evidence, so whoever can open the archive can also read the evidence. | File mode 600; the snapshot is encrypted with `FPT_STATE_KEY` before it leaves; the Compose backup must be encrypted by the operator. Keep `FPT_STATE_KEY` apart from the bucket's credentials. | +| Snapshot key | Unless `FPT_STATE_KEY` is set, the snapshot key is derived from the Supabase service key (S8). | Set `FPT_STATE_KEY` (required with OCI). | +| Runner token and Fusion password on every attempt | Each attempt and screen read sends the runner token (header) and the Fusion test user's password (body) to the runner over HTTPS. On the runner the password is in the Playwright process's environment. | HTTPS only (egress gate, runner host pinned); the audit log never records the password; a test pod's test user only, never production. Rotate both if the runner host is compromised. | +| Unencrypted job data on the runner | Screenshots, videos, traces, logs and the values tried stay unencrypted in the runner's job folders for `RUNNER_KEEP_HOURS` (24 h), including folders from before a runner restart (swept by age). A killed job may leave the Fusion session file there until the sweep. | The service listens on loopback only, behind Caddy. Keep the runner host single-purpose, with few logins and an encrypted disk. | +| Signed Excel links need no login | The Excel test-script link in Agent Studio events (`/api/share/runs/{id}/test-script.xlsx?exp=...&sig=...`) opens without a login for 7 days. Anyone who has the link can download that one file. | HMAC-signed for one run and one file, read-only, expires; changing `LINK_SIGNING_KEY` in the vault ends every link already sent. | +| Masking before AI calls is pattern-based | `platform/redaction.py` masks e-mail addresses, amounts, document numbers, numbers of 4 digits or more, the client names the scout registered (business units, ledgers, suppliers and other sampled test data) and vault secrets. A client name it does not know, or free text in an unusual shape, is not recognised. Oracle's own screen labels are sent as they are. | Only public or masked payloads go to the external model; a payload the leak check still flags is not sent there. Custom test cases never go to any model. Use a local model when the client does not agree to an external one. | +| Supabase sign-up | Supabase "Confirm email" must stay on for the admin list to be safe (S5). | Keep it on in the Supabase project's settings. | +| Personal tokens in shared agents | A Copilot Studio agent using a personal token acts as that one person for everyone who uses the agent. | Use a `read` token from a least-privileged account until OAuth (docs/MCP.md, phase 2). | +| Dependencies | react-router 6 has two moderate advisories fixed only in 7.x; the open-redirect one is not reachable here (the return path after sign-in is checked). Python dependencies are pinned at top level only; base images are not digest-pinned. | `npm audit` in CI (QUALITY.md). | + +Decisions on the older findings are recorded in [AUDIT.md](AUDIT.md). ## Rotating secrets Set the new value in the platform's secret store and restart. For the Fusion test user also update the user in -Fusion first. Exposed keys must be revoked at the provider (NVIDIA, Hugging Face, Supabase), not only replaced here. +Fusion first. Exposed keys must be revoked at the provider (NVIDIA, Hugging Face, Supabase, OCI), not only replaced here. +For the runner token and `OCI_STATE_PAR_URL`, see RUNBOOK "Rotating secrets". ## Incoming-webhook integrations (Slack, Teams, Google Chat, Discord) diff --git a/docs/design/BEUI.md b/docs/design/BEUI.md index 81b4db9e71c76101c6ee9715c505c58ca7a62500..35292aef6e20fa6492767123841cbf489eb2fdf4 100644 --- a/docs/design/BEUI.md +++ b/docs/design/BEUI.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + # beUI in Patchwise Branch `beui-ui-upgrade`. beUI (https://beui.dev) components are added one screen at a time on top of the existing diff --git a/docs/design/UI-APPLE.md b/docs/design/UI-APPLE.md index 28be73dd27f71ba0f61ea1a1af67117a5092ef48..3b9cbe2fcf58cee1c11606401764b58a1bd6e691 100644 --- a/docs/design/UI-APPLE.md +++ b/docs/design/UI-APPLE.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + > Note (24 Oct 2026, graphite pass): the accent is now GRAPHITE, not blue. Wherever the text below says blue or `#0071e3`, read the graphite tokens in section 3.1: near-black `#1d1d1f` fills in light, near-white `#f5f5f7` fills in dark, links are the label colour with an underline, and colour is reserved for status (green, orange, red). The "Oracle Fusion pod" cue is a graphite outlined chip with a cloud icon. > > Note (24 Oct 2026): this is the design the app was built to on branch `trio-apple-ui`. The product is now named "Trio Co-Worker"; older documents in this folder keep the earlier name. Where the build differs from this text: Ask is a sidebar item that opens the Ask dock (the `Ctrl K` palette also opens it); there is no separate Ask page. See the build notes in the commit history. diff --git a/docs/design/UI-REDESIGN.md b/docs/design/UI-REDESIGN.md index fbd4119b59c4ac244bd893a392081eda3baf2438..b06ae60dc31acc1b044ca4b711c12b8a8ab9eec6 100644 --- a/docs/design/UI-REDESIGN.md +++ b/docs/design/UI-REDESIGN.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + # Patch Testing Co-worker: UI redesign spec Status: design spec for the developer agent. Scope: `web/` only (React 18, TypeScript, Vite, Mantine 7, TanStack Query). diff --git a/docs/design/UI-RESEARCH-RECOVERY.md b/docs/design/UI-RESEARCH-RECOVERY.md index 8bb477b1babaf2f2e79bf5c5814b9404e60c6595..c3037cff92216773c8d52e187568e2429a871283 100644 --- a/docs/design/UI-RESEARCH-RECOVERY.md +++ b/docs/design/UI-RESEARCH-RECOVERY.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + # UI research for the run page, live view, approvals and pod clarity Written during the recovery of the Hugging Face demo (October 2026). It records what comparable products do, what we diff --git a/docs/design/UI-REVIEW-1.md b/docs/design/UI-REVIEW-1.md index 889b9b5cb9366d27c39b13e70137b2d7d75137b2..fbda7ce5094fde0593525da578cf1745816db0af 100644 --- a/docs/design/UI-REVIEW-1.md +++ b/docs/design/UI-REVIEW-1.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + # UI review 1: steps 1 and 2 of UI-REDESIGN.md Reviewed: commits `c155a92` (step 1, tokens and shell) and `d1035cc` (step 2, run workspace and side panel), against diff --git a/docs/design/UI-REVIEW-2.md b/docs/design/UI-REVIEW-2.md index 999a233f7c5228b624c241d7231e306fe0799351..9ff67a375428b2bee1807bfccf6f8db590c3b8c1 100644 --- a/docs/design/UI-REVIEW-2.md +++ b/docs/design/UI-REVIEW-2.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + # UI review 2: review-1 fixes and step 3 (Team board) Reviewed: diff --git a/docs/design/UI-REVIEW-3.md b/docs/design/UI-REVIEW-3.md index 25076adfc2e9bec0e9fd30db2faf77a7e6c55381..2a484beb70ee2365507d26dc0fd50ecb2531b089 100644 --- a/docs/design/UI-REVIEW-3.md +++ b/docs/design/UI-REVIEW-3.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + # UI review 3: review-2 fixes and step 4 (approvals and failure decision) Reviewed: `f9fab2a` (review-2 must-fixes), `4cae29d` (review-2 should-fixes + N2, N5), `6fe0316` (step 4), against `UI-REDESIGN.md`, diff --git a/docs/design/UI-SIMPLIFY.md b/docs/design/UI-SIMPLIFY.md index ad609abb26e95040689109525edef8159819a4d3..7018fcdf1be4500f808d491c9fde8a21885f0ade 100644 --- a/docs/design/UI-SIMPLIFY.md +++ b/docs/design/UI-SIMPLIFY.md @@ -1,3 +1,5 @@ +> **Historical record.** This page describes the product as it was when it was written, under an earlier name, and is not kept up to date. For the current system (Astra) read [DESIGN_SYSTEM.md](../DESIGN_SYSTEM.md) for the UI, and [ARCHITECTURE.md](../ARCHITECTURE.md), [DEPLOYMENT.md](../DEPLOYMENT.md), [RUNBOOK.md](../RUNBOOK.md), [REMOTE_RUNNER.md](../REMOTE_RUNNER.md) and [SECURITY.md](../SECURITY.md). + # Make the UI calm and simple Status: binding for every UI step from now on. Where this file and `UI-REDESIGN.md` disagree, this file wins; `UI-REDESIGN.md` diff --git a/web/src/api/openapi.json b/web/src/api/openapi.json index 43d234ee1cc0103394301d5c3cf7e1c416212b07..c2e8fc675dfc3fb8202cff39454c4b08e2fd8d66 100644 --- a/web/src/api/openapi.json +++ b/web/src/api/openapi.json @@ -5193,7 +5193,27 @@ }, "/api/agent-studio/deliveries": { "get": { + "description": "The callbacks, newest first, each with its state (queued, picked_up, retrying, delivered, superseded, dead).\n?state=dead lists the dead letters only: events that ran out of tries; send one again with .../requeue.", "operationId": "list_deliveries_api_agent_studio_deliveries_get", + "parameters": [ + { + "in": "query", + "name": "state", + "required": false, + "schema": { + "anyOf": [ + { + "const": "dead", + "type": "string" + }, + { + "type": "null" + } + ], + "title": "State" + } + } + ], "responses": { "200": { "content": { @@ -5202,6 +5222,16 @@ } }, "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" } }, "summary": "List Deliveries", @@ -5210,6 +5240,47 @@ ] } }, + "/api/agent-studio/deliveries/{delivery_id}/requeue": { + "post": { + "description": "Send a dead letter (or an event still retrying) again: its tries start over, with the same delivery_id.", + "operationId": "requeue_delivery_api_agent_studio_deliveries__delivery_id__requeue_post", + "parameters": [ + { + "in": "path", + "name": "delivery_id", + "required": true, + "schema": { + "title": "Delivery Id", + "type": "string" + } + } + ], + "responses": { + "200": { + "content": { + "application/json": { + "schema": {} + } + }, + "description": "Successful Response" + }, + "422": { + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HTTPValidationError" + } + } + }, + "description": "Validation Error" + } + }, + "summary": "Requeue Delivery", + "tags": [ + "agent-studio" + ] + } + }, "/api/agent-studio/release-watch": { "get": { "operationId": "release_watch_api_agent_studio_release_watch_get", @@ -5269,6 +5340,7 @@ }, "/api/agent-studio/v1/cycles": { "post": { + "description": "Safe to send again: with the same Idempotency-Key header (optional), or the same correlation_id while that cycle\nis still going, it starts nothing and answers with the cycle the first call made (202, same body; the header\nIdempotent-Replayed: true says so).", "operationId": "start_cycle_api_agent_studio_v1_cycles_post", "requestBody": { "content": { @@ -5437,7 +5509,7 @@ }, "/api/agent-studio/v1/events/claim": { "post": { - "description": "The events Patchwise would have sent (scripts_ready, failures_need_review, results, stopped, patch_update), oldest\nfirst. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again.", + "description": "The events Astra would have sent (scripts_ready, failures_need_review, results, stopped, paused, patch_update), oldest\nfirst. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again (at least once:\nthe same event keeps its delivery_id).", "operationId": "claim_events_api_agent_studio_v1_events_claim_post", "requestBody": { "content": { diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index f9ea76507146995107de0bb278affddf226ea144..ec51b04bddc6490d1fa9ae9af8a566e9d7f954cc 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -193,7 +193,11 @@ export interface paths { path?: never; cookie?: never; }; - /** List Deliveries */ + /** + * List Deliveries + * @description The callbacks, newest first, each with its state (queued, picked_up, retrying, delivered, superseded, dead). + * ?state=dead lists the dead letters only: events that ran out of tries; send one again with .../requeue. + */ get: operations["list_deliveries_api_agent_studio_deliveries_get"]; put?: never; post?: never; @@ -203,6 +207,26 @@ export interface paths { patch?: never; trace?: never; }; + "/api/agent-studio/deliveries/{delivery_id}/requeue": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + get?: never; + put?: never; + /** + * Requeue Delivery + * @description Send a dead letter (or an event still retrying) again: its tries start over, with the same delivery_id. + */ + post: operations["requeue_delivery_api_agent_studio_deliveries__delivery_id__requeue_post"]; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/api/agent-studio/release-watch": { parameters: { query?: never; @@ -263,7 +287,12 @@ export interface paths { }; get?: never; put?: never; - /** Start a test cycle with approved synthetic test data */ + /** + * Start a test cycle with approved synthetic test data + * @description Safe to send again: with the same Idempotency-Key header (optional), or the same correlation_id while that cycle + * is still going, it starts nothing and answers with the cycle the first call made (202, same body; the header + * Idempotent-Replayed: true says so). + */ post: operations["start_cycle_api_agent_studio_v1_cycles_post"]; delete?: never; options?: never; @@ -333,8 +362,9 @@ export interface paths { put?: never; /** * Pick up waiting events (delivery mode pull) - * @description The events Patchwise would have sent (scripts_ready, failures_need_review, results, stopped, patch_update), oldest - * first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again. + * @description The events Astra would have sent (scripts_ready, failures_need_review, results, stopped, paused, patch_update), oldest + * first. Confirm each with /events/ack; one not confirmed within confirm_within_s is handed out again (at least once: + * the same event keeps its delivery_id). */ post: operations["claim_events_api_agent_studio_v1_events_claim_post"]; delete?: never; @@ -4593,7 +4623,9 @@ export interface operations { }; list_deliveries_api_agent_studio_deliveries_get: { parameters: { - query?: never; + query?: { + state?: "dead" | null; + }; header?: never; path?: never; cookie?: never; @@ -4609,6 +4641,46 @@ export interface operations { "application/json": unknown; }; }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; + }; + }; + requeue_delivery_api_agent_studio_deliveries__delivery_id__requeue_post: { + parameters: { + query?: never; + header?: never; + path: { + delivery_id: string; + }; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description Successful Response */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": unknown; + }; + }; + /** @description Validation Error */ + 422: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": components["schemas"]["HTTPValidationError"]; + }; + }; }; }; release_watch_api_agent_studio_release_watch_get: { diff --git a/web/src/pages/setup/AgentStudioPage.tsx b/web/src/pages/setup/AgentStudioPage.tsx index db7b7dd0320fe2a42ad399d57f0ebc31ab0bdcab..5f6011933a9f29f22ae3f2b6f4db15df5c985487 100644 --- a/web/src/pages/setup/AgentStudioPage.tsx +++ b/web/src/pages/setup/AgentStudioPage.tsx @@ -11,7 +11,7 @@ interface FusionDelivery { base_url: string; token_url: string; client_id: strin interface Client { client_id: string; name: string; callback_url: string | null; release_watch_url: string | null; created_at: string; last_used_at: string | null; revoked_at: string | null; delivery?: 'url' | 'fusion' | 'pull'; fusion?: FusionDelivery | null } interface Created extends Client { client_secret: string; signing_key: string } interface Cycle { cycle_id: string; run_id: string; areas: string[]; status: string | null; waiting_for: string | null; data_approved_by: string; scripts_approved_by: string | null; created_at: string; correlation_id: string | null } -interface Delivery { id: number; delivery_id: string; event: string; cycle_id: string | null; attempts: number; status_code: number | null; error: string | null; created_at: string; delivered_at: string | null; job_id?: string | null } +interface Delivery { id: number; delivery_id: string; event: string; cycle_id: string | null; attempts: number; status_code: number | null; error: string | null; created_at: string; delivered_at: string | null; job_id?: string | null; dead_at?: string | null; state?: 'queued' | 'picked_up' | 'retrying' | 'delivered' | 'superseded' | 'dead' } interface Watch { checked_at?: string; checked?: { release: string; area: string; changes?: number; new?: number; error?: string }[]; updates?: number } interface InboxItem { id: number; event: string; signature_ok: boolean; received_at: string; payload: Record & { cycle_id?: string; scenarios?: { id: string; title: string; area: string; written_by: string }[]; verdict?: string; areas?: { area: string; verdict: string }[] } } @@ -27,6 +27,8 @@ const FLOW: { n: number; text: string; who: 'fusion' | 'patchwise' | 'person' }[ ]; const deliveryState = (d: Delivery) => (d.delivered_at ? { tone: 'green', words: `Delivered${d.attempts > 1 ? ` after ${d.attempts} tries` : ''}${d.job_id ? ` (Fusion job ${d.job_id})` : ''}` } + : d.state === 'dead' || d.dead_at ? { tone: 'red', words: `Not delivered: ${d.error ?? ''}` } + : d.state === 'superseded' ? { tone: 'neutral', words: 'Replaced by a newer event' } : d.attempts >= 6 ? { tone: 'red', words: `Failed: ${d.error ?? ''}` } : d.attempts ? { tone: 'orange', words: `Retrying (${d.error ?? 'no answer'})` } : { tone: 'neutral', words: 'Queued' }); function Secret({ label, value }: { label: string; value: string }) { @@ -187,12 +189,15 @@ function Cycles() { } function Callbacks() { - const q = useQuery({ queryKey: ['as-deliveries'], queryFn: () => getJson<{ items: Delivery[] }>('/api/agent-studio/deliveries'), refetchInterval: 10_000 }); + const qc = useQueryClient(); + const q = useQuery({ queryKey: ['as-deliveries'], queryFn: () => getJson<{ items: Delivery[]; dead_letters?: number }>('/api/agent-studio/deliveries'), refetchInterval: 10_000 }); + const requeue = useMutation({ mutationFn: (id: string) => sendJson('POST', `/api/agent-studio/deliveries/${id}/requeue`), onSuccess: () => void qc.invalidateQueries({ queryKey: ['as-deliveries'] }) }); const items = q.data?.items ?? []; return (

Callbacks to Fusion

Signed with the client’s key, retried for about half an hour when Fusion does not answer.

- + + {!!q.data?.dead_letters && {q.data.dead_letters} event(s) could not be delivered after every retry. Send them again once Fusion answers.} {items.length === 0 ? Nothing sent yet. : ( EventCycleDeliveryWhen @@ -202,7 +207,8 @@ function Callbacks() { {d.event.replace(/_/g, ' ')} {d.cycle_id ?? '—'} - {s.words} + {s.words} + {(d.state === 'dead' || !!d.dead_at) && !d.delivered_at && } {fmtTs(d.delivered_at ?? d.created_at)} );