Astra: PO/GL actions, usage coverage, assisted sign-in, self-healing, recorder, new top navigation and theme (172a4e22a2bf)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
Files changed (50)
- automation/playwright.fusion.config.ts+62-59
- automation/remote_runner/server.py+710-457
- automation/scripts/check-heal.tsAdded+33
- automation/scripts/sign-in-session.tsAdded+127
- automation/src/fusion/fixtures.ts+142-64
- automation/src/fusion/heal.tsAdded+103
- automation/src/fusion/rest.ts+329-113
- automation/src/fusion/session.ts+73-42
- automation/src/fusion/steps.ts+511-295
- automation/src/fusion/ui.ts
- automation/tests/fusion/AP-FUS-002.spec.ts+37-35
- automation/tests/fusion/AP-FUS-003.spec.ts+36-36
- automation/tests/fusion/AP-FUS-004.spec.ts+36-36
- automation/tests/fusion/AP-FUS-005.spec.ts+35-35
- automation/tests/fusion/steps/CANARY-GL.spec.tsAdded+4
- automation/tests/fusion/steps/CANARY-PO.spec.tsAdded+4
- coworker/adapters/playwright.py+466-372
- coworker/adapters/remote_runner.py+488-484
- coworker/adapters/screens.py+313-282
- coworker/adapters/triage_rule.py+44-42
- coworker/api/a2a.py+737-735
- coworker/api/app.py+172-163
- coworker/api/routes/consultant.py+295-287
- coworker/api/routes/heals.pyAdded+52
- coworker/api/routes/pods.py+135-106
- coworker/api/routes/recordings.pyAdded+90
- coworker/api/routes/runs.py+380-380
- coworker/api/routes/signin.pyAdded+97
- coworker/api/runner.py+433-420
- coworker/api/schemas.py+470-395
- coworker/channels/core.py+397-396
- coworker/chat/tools.py+473-470
- coworker/config.py+351-348
- coworker/graph/build.py+81-77
- coworker/graph/nodes/ai_scenarios.py+583-542
- coworker/graph/nodes/design.py+450-442
- coworker/graph/nodes/execute.py+674-594
- coworker/graph/nodes/report.py
- coworker/graph/nodes/research.py
- coworker/graph/nodes/signin.pyAdded
- coworker/graph/services.py
- coworker/llm/prompts/design_scenarios.md
- coworker/llm/prompts/tidy_recording.mdAdded
- coworker/llm/prompts/triage.md
- coworker/llm/prompts/write_steps.md
- coworker/llm/schemas.py
- coworker/platform/agent_studio.py
- coworker/platform/assisted_signin.pyAdded
- coworker/platform/canary.py
- coworker/platform/cleanup.py
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859import { defineConfig, devices } from '@playwright/test';import * as path from 'path';/** Runs against a REAL Oracle Fusion pod (tests/fusion). The pod address and its test user come from the environment* (FUSION_BASE_URL, FUSION_USERNAME, FUSION_PASSWORD), set by the co-worker from the pod registration and its vault.* Fusion pages are slow, so timeouts are far longer than for the practice pod. The test user signs in ONCE for the run* (src/fusion/session.ts) and every test starts from that session; FPT_FUSION_WORKERS tests run at once (default 1).*/if (!process.env.PW_RUN_ID) {const d = new Date(); const p2 = (n: number) => String(n).padStart(2, '0');process.env.PW_RUN_ID = `fusion-${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}${p2(d.getSeconds())}`;}const RUN_DIR = path.join(__dirname, 'results', 'runs', process.env.PW_RUN_ID);const DRAFTS = process.env.FPT_DRAFTS_DIR;const LIBRARY = process.env.FPT_LIBRARY_DIR; // approved scenarios kept in FPT_HOME/library (they survive redeploys)// the run's one sign-in: written by the global setup, deleted by the teardown (it holds session cookies)const SESSION = path.join(RUN_DIR, '.fusion-session.json');process.env.FPT_FUSION_SESSION_FILE = SESSION;// Fusion's own server is the slow part: a few browsers at once finish far sooner, even on a small machineconst WORKERS = Math.max(1, Math.min(4, Number(process.env.FPT_FUSION_WORKERS) || 1));const SLOW_MO = process.env.FPT_LIVE_VIEW_DIR ? Math.max(0, Math.min(3000, Number(process.env.FPT_BROWSER_SLOWMO_MS) || 0)) : 0;export default defineConfig({testDir: './tests/fusion',outputDir: path.join(RUN_DIR, 'artifacts'),fullyParallel: false,workers: WORKERS,globalSetup: require.resolve('./src/fusion/session-setup'),globalTeardown: require.resolve('./src/fusion/session-teardown'),retries: 0, // the co-worker owns the single retrytimeout: 600_000 + SLOW_MO * 400,expect: { timeout: 30_000 },metadata: { target: `Oracle Fusion pod ${process.env.FUSION_BASE_URL || '(not set)'}`, runId: process.env.PW_RUN_ID },reporter: [['list'],['json', { outputFile: process.env.PLAYWRIGHT_JSON_OUTPUT_NAME || path.join(RUN_DIR, 'results.pwjson') }],],use: {// a trace taken after sign-in holds the Fusion session cookies in its network log: kept only when a test fails,// where it is needed to see why (screenshots are kept for every test)trace: 'retain-on-failure',screenshot: 'on',video: 'retain-on-failure',actionTimeout: 60_000,navigationTimeout: 120_000,viewport: { width: 1440, height: 900 },launchOptions: { slowMo: SLOW_MO },storageState: SESSION,},projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } },// AI-written steps scenarios staged by the co-worker (FPT_DRAFTS_DIR, outside automation/): their dry run before// the consultant approves them, and runs from staging. Invisible to `npm test` and to qa/audit.py....(DRAFTS ? [{ name: 'drafts', testDir: DRAFTS, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []),// the persistent library: AI-written and client scenarios a person approved, re-run in every later run...(LIBRARY ? [{ name: 'library', testDir: LIBRARY, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []),],});1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162import { defineConfig, devices } from '@playwright/test';import * as path from 'path';/** Runs against a REAL Oracle Fusion pod (tests/fusion). The pod address and its test user come from the environment* (FUSION_BASE_URL, FUSION_USERNAME, FUSION_PASSWORD), set by the co-worker from the pod registration and its vault.* Fusion pages are slow, so timeouts are far longer than for the practice pod. The test user signs in ONCE for the run* (src/fusion/session.ts) and every test starts from that session; FPT_FUSION_WORKERS tests run at once (default 1).*/if (!process.env.PW_RUN_ID) {const d = new Date(); const p2 = (n: number) => String(n).padStart(2, '0');process.env.PW_RUN_ID = `fusion-${d.getFullYear()}${p2(d.getMonth() + 1)}${p2(d.getDate())}-${p2(d.getHours())}${p2(d.getMinutes())}${p2(d.getSeconds())}`;}const RUN_DIR = path.join(__dirname, 'results', 'runs', process.env.PW_RUN_ID);const DRAFTS = process.env.FPT_DRAFTS_DIR;const LIBRARY = process.env.FPT_LIBRARY_DIR; // approved scenarios kept in FPT_HOME/library (they survive redeploys)// the run's one sign-in: written by the global setup, deleted by the teardown (it holds session cookies)const SESSION = path.join(RUN_DIR, '.fusion-session.json');process.env.FPT_FUSION_SESSION_FILE = SESSION;// assisted sign-in: the pass's marker that the session a person signed in has expired (src/fusion/ui.ts, fixtures.ts);// a provided session (FPT_FUSION_STORAGE_STATE) becomes SESSION in the global setup instead of a sign-inprocess.env.FPT_SIGN_IN_EXPIRED_FILE = path.join(RUN_DIR, '.sign-in-expired');// Fusion's own server is the slow part: a few browsers at once finish far sooner, even on a small machineconst WORKERS = Math.max(1, Math.min(4, Number(process.env.FPT_FUSION_WORKERS) || 1));const SLOW_MO = process.env.FPT_LIVE_VIEW_DIR ? Math.max(0, Math.min(3000, Number(process.env.FPT_BROWSER_SLOWMO_MS) || 0)) : 0;export default defineConfig({testDir: './tests/fusion',outputDir: path.join(RUN_DIR, 'artifacts'),fullyParallel: false,workers: WORKERS,globalSetup: require.resolve('./src/fusion/session-setup'),globalTeardown: require.resolve('./src/fusion/session-teardown'),retries: 0, // the co-worker owns the single retrytimeout: 600_000 + SLOW_MO * 400,expect: { timeout: 30_000 },metadata: { target: `Oracle Fusion pod ${process.env.FUSION_BASE_URL || '(not set)'}`, runId: process.env.PW_RUN_ID },reporter: [['list'],['json', { outputFile: process.env.PLAYWRIGHT_JSON_OUTPUT_NAME || path.join(RUN_DIR, 'results.pwjson') }],],use: {// a trace taken after sign-in holds the Fusion session cookies in its network log: kept only when a test fails,// where it is needed to see why (screenshots are kept for every test)trace: 'retain-on-failure',screenshot: 'on',video: 'retain-on-failure',actionTimeout: 60_000,navigationTimeout: 120_000,viewport: { width: 1440, height: 900 },launchOptions: { slowMo: SLOW_MO },storageState: SESSION,},projects: [{ name: 'chromium', use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } },// AI-written steps scenarios staged by the co-worker (FPT_DRAFTS_DIR, outside automation/): their dry run before// the consultant approves them, and runs from staging. Invisible to `npm test` and to qa/audit.py....(DRAFTS ? [{ name: 'drafts', testDir: DRAFTS, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []),// the persistent library: AI-written and client scenarios a person approved, re-run in every later run...(LIBRARY ? [{ name: 'library', testDir: LIBRARY, testIgnore: [] as string[], use: { ...devices['Desktop Chrome'], viewport: { width: 1440, height: 900 } } }] : []),],});
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457"""Patchwise remote browser runner: runs one Playwright attempt at a time for a Patchwise server that cannot drive abrowser itself (for example a host whose network Oracle's edge refuses). Standard library only; Python 3.10+.The Patchwise server posts an attempt (case ids, config, the run's environment, any AI-written or library specs),polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), therun 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 stillwrites its report), and only killed after RUNNER_GRACE_S. Each job's metadata is kept in its folder (job.json), so after arunner restart a finished job still answers its status and bundle, and a job that was running is reported "lost" (thePatchwise server then fails it at once instead of waiting for its deadline).Security: every call needs `Authorization: Bearer <RUNNER_TOKEN>` (compared in constant time). Only known environmentkeys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password existsonly 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), RUNNER_GRACE_S (default 90)."""from __future__ import annotationsimport base64import hmacimport ioimport jsonimport osimport reimport secretsimport shutilimport signalimport subprocessimport threadingimport timeimport zipfilefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import PathTOKEN = os.environ.get("RUNNER_TOKEN", "")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")) * 3600GRACE_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 installedCASES = AUTOMATION.parent / "tests" / "cases"VERSION_FILE = AUTOMATION.parent / "VERSION"CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"}ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES","FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS"}SPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$")ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$")MAX_BODY = 20_000_000# each attempt in its own process group, so a cancel stops it and every browser it started (Linux and Windows)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 browserJOBS: 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:passdef load_jobs() -> None:"""After a restart: jobs kept on disk answer again. A finished one as it ended; one that was running is "lost" (itsprocesses 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):continuejid = str(meta.get("id") or "")if jid != d.name or jid in JOBS or not re.fullmatch(r"job_[0-9a-f]{12}", jid):continuejob = {**{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 answerssave_meta(job)JOBS[jid] = jobdef grep_for(ids: list[str]) -> str:return "|".join(re.escape(i) for i in ids)def _progress(log: Path) -> dict:try:b = log.read_bytes()[-20000:]except OSError:return {}m = list(re.finditer(rb"\[(\d+)/(\d+)\]", b))return {"done": int(m[-1].group(1)), "total": int(m[-1].group(2))} if m else {}def _relativize(report: Path, run_dir: Path) -> None:"""Attachment paths in the report become relative to the run directory (the server maps them to its own)."""data = json.loads(report.read_text(encoding="utf-8"))def walk(suites):for s in suites or []:for sp in s.get("specs") or []:for t in sp.get("tests") or []:for r in t.get("results") or []:for a in r.get("attachments") or []:p = a.get("path")if p:try:a["path"] = str(Path(p).resolve().relative_to(run_dir.resolve())).replace("\\", "/")except ValueError:a["path"] = None # outside the run directory: not shippedwalk(s.get("suites"))walk(data.get("suites"))report.write_text(json.dumps(data), encoding="utf-8")YAML_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}\.yaml$")_IMPORT_SRC = re.compile(r"""(from\s+)(["'])[^"'\n]*?/automation/src/""")_STEPS_DIR = re.compile(r"""(dir:\s*)"(?:[^"\\\n]|\\.)*\"""")def local_spec(text: str, steps_dir: Path) -> str:"""A spec written on the Patchwise server, made runnable here: its imports of the server's automation/src point tothis runner's, and a steps scenario reads its YAML from the job's steps folder."""text = _IMPORT_SRC.sub(lambda m: f"{m.group(1)}{m.group(2)}{(AUTOMATION / 'src').as_posix()}/", text)return _STEPS_DIR.sub(lambda m: m.group(1) + json.dumps(steps_dir.as_posix()), text)def start(body: dict) -> dict:ids = [str(i) for i in body.get("ids") or []]if not ids or not all(ID.match(i) for i in ids):raise ValueError("ids: case ids such as AP-FUS-001")pw_run_id = str(body.get("pw_run_id") or "")if not ID.match(pw_run_id):raise ValueError("pw_run_id is missing or not a plain id")config = str(body.get("config") or "playwright.fusion.config.ts")if config not in CONFIGS:raise ValueError(f"config is one of {sorted(CONFIGS)}")env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in ENV_KEYS}if not LOCK.acquire(blocking=False):raise BlockingIOError("another attempt is running on this runner")try:jid = "job_" + secrets.token_hex(6)jd = HOME / jid(jd / "drafts").mkdir(parents=True)(jd / "library").mkdir()(jd / "steps").mkdir()for name, text in (body.get("steps") or {}).items(): # the steps scenarios' YAML (the server's copy is not here)if not YAML_NAME.match(name):raise ValueError(f"steps: {name!r} is not a scenario file name")(jd / "steps" / name).write_text(str(text), encoding="utf-8")for kind in ("drafts", "library"):for name, text in (body.get(kind) or {}).items():if not SPEC.match(name):raise ValueError(f"{kind}: {name!r} is not a spec file name")(jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8")report = jd / "report.json"env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}env.update(env_in)env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report),"FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")})live = body.get("live") or {}for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"):env.pop(k, None)if live and ID.match(str(live.get("attempt") or "")): # live view: the browser hook drops its latest frame here(jd / "live").mkdir()env.update({"FPT_LIVE_VIEW_DIR": str(jd / "live"), "FPT_LIVE_VIEW_ATTEMPT": str(live["attempt"]), "FPT_LIVE_VIEW_CHUNK": "0"})for kind in ("drafts", "library"):key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR"if any((jd / kind).glob("*.spec.ts")):env[key] = str(jd / kind)else:env.pop(key, None)cmd = ["node", str(AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"), "test", "--config", config,"--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(), "kind": "attempt","deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None}JOBS[jid] = jobsave_meta(job)threading.Thread(target=_watch, args=(job,), daemon=True).start()return {"id": jid, "state": "running"}except BaseException:LOCK.release()raiseSCREEN_SCRIPTS = {"explore": "scripts/explore-fusion.ts", "capture": "scripts/capture-fusion.ts"}SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")TASK = re.compile(r"^[^\r\n<>]{5,250}$")OUT_FILE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,160}\.(json|values)$")def start_screens(body: dict) -> dict:"""Read a pod's screens (labels only): "explore" with a plan of areas, or "capture" of one "Area > Page > Task".Same lock as the attempts (one browser); the files land in the job's out/ folder and come back in the bundle."""kind = str(body.get("kind") or "")if kind not in SCREEN_SCRIPTS:raise ValueError(f"kind is one of {sorted(SCREEN_SCRIPTS)}")env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in SCREEN_ENV}if not all(env_in.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):raise ValueError("env needs FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD")task = str(body.get("task") or "")if kind == "capture" and not TASK.match(task):raise ValueError('task is "Area > Page > Task"')if kind == "explore" and not isinstance(body.get("plan"), dict):raise ValueError("plan is the explorer's plan (an object)")if not LOCK.acquire(blocking=False):raise BlockingIOError("another attempt is running on this runner")try:jid = "job_" + secrets.token_hex(6)jd = HOME / jid(jd / "out").mkdir(parents=True)arg = taskif kind == "explore":(jd / "plan.json").write_text(json.dumps(body["plan"]), encoding="utf-8")arg = str(jd / "plan.json")env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}env.update(env_in)cmd = ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), SCREEN_SCRIPTS[kind], arg, "--out-dir", str(jd / "out")]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": 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] = jobsave_meta(job)threading.Thread(target=_watch, args=(job,), daemon=True).start()return {"id": jid, "state": "running"}except BaseException:LOCK.release()raisedef live_now(job: dict) -> dict:"""The live view of a running attempt: the latest frame and the failed scenario's last frame (JPEG, base64) and thehook's status. The hook never writes a sign-in screen (it masks pages with a password field)."""d = job["dir"] / "live"out: dict = {"status": None, "frame": None, "failed": None, "frame_at": None}if not d.is_dir():return outtry:out["status"] = json.loads((d / "status.json").read_text(encoding="utf-8"))except (OSError, ValueError):passfor key, name in (("frame", "frame.jpg"), ("failed", "failed.jpg")):f = d / nametry:if key == "frame":out["frame_at"] = f.stat().st_mtimeout[key] = base64.b64encode(f.read_bytes()).decode()except OSError:passreturn outdef _lines(log: Path, since: int) -> tuple[list[str], int]:"""The log's lines from `since` on (at most 200), and how many lines it has."""try:lines = log.read_text(encoding="utf-8", errors="replace").splitlines()except OSError:return [], 0return [ln[:500] for ln in lines[since:since + 200]], len(lines)def _kill_tree(p: subprocess.Popen) -> None:"""Stop the attempt and every browser it started (a process group on Linux, a process tree on Windows)."""try:if os.name == "posix":os.killpg(p.pid, signal.SIGKILL)else:subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], capture_output=True, timeout=30)except (OSError, subprocess.SubprocessError):passdef _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 itsJSON report. False where that cannot be asked (Windows: the attempt is killed at once)."""if os.name != "posix":return Falsetry:os.kill(p.pid, signal.SIGINT)return Trueexcept OSError:return Falsedef _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 isif 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 = Nonewhile p.poll() is None: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 lostjob["timed_out"] = Truestop_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.returncodejob["log"].close()_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 releasedjob["state"], job["error"] = "failed", f"{type(e).__name__}: {e}"[:300]_kill_tree(p)finally:save_meta(job)LOCK.release()def bundle(job: dict) -> bytes:buf = io.BytesIO()with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:for name in ("report.json", "testdata-used.jsonl", "created.jsonl", "playwright.log"):f = job["dir"] / nameif f.exists():z.write(f, name)out = job["dir"] / "out" # a screen read: the inventories (labels) and the list choices it foundif out.exists():for f in out.iterdir():if f.is_file() and OUT_FILE.match(f.name):z.write(f, "out/" + f.name)run = job["dir"] / "run"if run.exists():for f in run.rglob("*"):if f.is_file() and f.name != ".fusion-session.json": # never ship the session cookiesz.write(f, "run/" + str(f.relative_to(run)).replace("\\", "/"))return buf.getvalue()def sweep() -> None:while True:cut = time.time() - KEEP_Sfor jid, job in list(JOBS.items()):if job["state"] != "running" and job["started"] < cut:shutil.rmtree(job["dir"], ignore_errors=True)JOBS.pop(jid, None)# folders of jobs from before a restart are not in JOBS: their age on disk decidesfor d in HOME.glob("job_*"):if d.is_dir() and d.name not in JOBS and d.stat().st_mtime < cut:shutil.rmtree(d, ignore_errors=True)time.sleep(600)class H(BaseHTTPRequestHandler):server_version = "PatchwiseRunner/1"def log_message(self, fmt, *args): # one quiet line per call, never a header or a bodyprint(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True)def _send(self, code: int, obj=None, raw: bytes | None = None, ctype="application/json"):b = raw if raw is not None else json.dumps(obj).encode()self.send_response(code)self.send_header("Content-Type", ctype)self.send_header("Content-Length", str(len(b)))self.send_header("Cache-Control", "no-store")self.end_headers()self.wfile.write(b)def _auth(self) -> bool:h = self.headers.get("Authorization", "")ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN)if not ok:self._send(401, {"error": "a valid runner token is needed"})return okdef _job(self, jid: str):job = JOBS.get(jid)if not job:self._send(404, {"error": "no such attempt"})return jobdef do_GET(self):if self.path == "/healthz":version = VERSION_FILE.read_text(encoding="utf-8").strip()[:40] if VERSION_FILE.is_file() else "unknown"return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists(), "cases": CASES.is_dir(),"version": version})if not self._auth():returnm = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle|/live)?(?:\?since=(\d{1,7}))?", self.path)if not m:return self._send(404, {"error": "not found"})job = self._job(m.group(1))if not job:returnif m.group(2) == "/live":return self._send(200, live_now(job) if job["state"] == "running" else {"status": None, "frame": None, "failed": None, "frame_at": None})if m.group(2):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.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 progressst["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3)))self._send(200, st)def do_POST(self):if not self._auth():returnn = int(self.headers.get("Content-Length") or 0)if n > MAX_BODY:return self._send(413, {"error": "body too large"})if self.path in ("/v1/attempts", "/v1/screens"):try:body = json.loads(self.rfile.read(n) or b"{}")return self._send(202, start(body) if self.path == "/v1/attempts" else start_screens(body))except BlockingIOError as e:return self._send(409, {"error": str(e)})except (ValueError, TypeError) as e:return self._send(400, {"error": str(e)})m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})/cancel", self.path)if m:job = self._job(m.group(1))if job:if job["state"] == "running":job["cancel"] = Trueself._send(202, {"id": job["id"], "state": "cancelling" if job["state"] == "running" else job["state"]})returnself._send(404, {"error": "not found"})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()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710"""Patchwise remote browser runner: runs one Playwright attempt at a time for a Patchwise server that cannot drive abrowser itself (for example a host whose network Oracle's edge refuses). Standard library only; Python 3.10+.The Patchwise server posts an attempt (case ids, config, the run's environment, any AI-written or library specs),polls it, then downloads one zip: the Playwright JSON report (attachment paths relative to the run directory), therun 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 stillwrites its report), and only killed after RUNNER_GRACE_S. Each job's metadata is kept in its folder (job.json), so after arunner restart a finished job still answers its status and bundle, and a job that was running is reported "lost" (thePatchwise server then fails it at once instead of waiting for its deadline).Assisted sign-in (a pod whose sign-in goes through the company's identity provider, with MFA): a person signs inthrough Astra's run page in a browser that runs here (scripts/sign-in-session.ts). POST /v1/sign-in opens it on the pod,GET /v1/sign-in/<id> returns its latest frame, POST .../input applies the person's clicks and keys, POST .../finish handsthe signed-in session (Playwright storage state) back once and deletes it here, POST .../cancel closes it. It holds thesame one-browser lock as an attempt and closes by itself after RUNNER_SIGN_IN_IDLE_S without input (default 900). Anattempt may then carry that session ("storage_state"): it is written to the job folder (mode 0600) for the tests to startfrom instead of signing in, and deleted when the attempt ends; it never ships in a bundle.Security: every call needs `Authorization: Bearer <RUNNER_TOKEN>` (compared in constant time). Only known environmentkeys and the Patchwise Playwright configs are accepted; spec names are plain file names. The Fusion password existsonly in the Playwright process's environment, never on disk. What a person types in a sign-in session is never logged.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), RUNNER_GRACE_S (default 90),RUNNER_SIGN_IN_IDLE_S (default 900)."""from __future__ import annotationsimport base64import hmacimport ioimport jsonimport osimport reimport secretsimport shutilimport signalimport subprocessimport threadingimport timeimport zipfilefrom http.server import BaseHTTPRequestHandler, ThreadingHTTPServerfrom pathlib import PathTOKEN = os.environ.get("RUNNER_TOKEN", "")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")) * 3600GRACE_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 installedCASES = AUTOMATION.parent / "tests" / "cases"VERSION_FILE = AUTOMATION.parent / "VERSION"CONFIGS = {"playwright.fusion.config.ts", "playwright.agent.config.ts"}ENV_KEYS = {"FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES","FPT_FUSION_WORKERS", "PW_LOCATOR_OVERRIDES", "FPT_BROWSER_SLOWMO_MS", "FPT_SIGN_IN_MODE", "FPT_HEALS"}SESSION_STATE = "sign-in-state.json" # an attempt's signed-in session (assisted sign-in), in its job folder while it runsSPEC = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,120}\.spec\.ts$")ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,80}$")MAX_BODY = 20_000_000# each attempt in its own process group, so a cancel stops it and every browser it started (Linux and Windows)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 browserJOBS: dict[str, dict] = {}META = ("id", "kind", "state", "started", "deadline", "pw_run_id", "exit_code", "timed_out", "error")ENDED = ("done", "cancelled", "failed")def write_secret(f: Path, text: str) -> None:"""A file only this user can read, created that way (never world-readable, not even for a moment)."""fd = os.open(str(f), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)with os.fdopen(fd, "w", encoding="utf-8") as fh:fh.write(text)def write_session(jd: Path, state) -> Path:"""The signed-in session an attempt starts from (a Playwright storage state), checked for its shape."""if not isinstance(state, dict) or not isinstance(state.get("cookies"), list) or not isinstance(state.get("origins", []), list):raise ValueError("storage_state is a Playwright storage state ({cookies, origins})")f = jd / SESSION_STATEwrite_secret(f, json.dumps({"cookies": state["cookies"], "origins": state.get("origins") or []}))return fdef drop_session(job: dict) -> None:try:(job["dir"] / SESSION_STATE).unlink(missing_ok=True)except OSError:passdef 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:passdef load_jobs() -> None:"""After a restart: jobs kept on disk answer again. A finished one as it ended; one that was running is "lost" (itsprocesses 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):continuejid = str(meta.get("id") or "")if jid != d.name or jid in JOBS or not re.fullmatch(r"job_[0-9a-f]{12}", jid):continuejob = {**{k: meta.get(k) for k in META}, "dir": d, "started": float(meta.get("started") or d.stat().st_mtime)}drop_session(job) # a session cookie file outlives no runnerif 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 answerssave_meta(job)JOBS[jid] = jobdef grep_for(ids: list[str]) -> str:return "|".join(re.escape(i) for i in ids)def _progress(log: Path) -> dict:try:b = log.read_bytes()[-20000:]except OSError:return {}m = list(re.finditer(rb"\[(\d+)/(\d+)\]", b))return {"done": int(m[-1].group(1)), "total": int(m[-1].group(2))} if m else {}def _relativize(report: Path, run_dir: Path) -> None:"""Attachment paths in the report become relative to the run directory (the server maps them to its own)."""data = json.loads(report.read_text(encoding="utf-8"))def walk(suites):for s in suites or []:for sp in s.get("specs") or []:for t in sp.get("tests") or []:for r in t.get("results") or []:for a in r.get("attachments") or []:p = a.get("path")if p:try:a["path"] = str(Path(p).resolve().relative_to(run_dir.resolve())).replace("\\", "/")except ValueError:a["path"] = None # outside the run directory: not shippedwalk(s.get("suites"))walk(data.get("suites"))report.write_text(json.dumps(data), encoding="utf-8")YAML_NAME = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,80}\.yaml$")_IMPORT_SRC = re.compile(r"""(from\s+)(["'])[^"'\n]*?/automation/src/""")_STEPS_DIR = re.compile(r"""(dir:\s*)"(?:[^"\\\n]|\\.)*\"""")def local_spec(text: str, steps_dir: Path) -> str:"""A spec written on the Patchwise server, made runnable here: its imports of the server's automation/src point tothis runner's, and a steps scenario reads its YAML from the job's steps folder."""text = _IMPORT_SRC.sub(lambda m: f"{m.group(1)}{m.group(2)}{(AUTOMATION / 'src').as_posix()}/", text)return _STEPS_DIR.sub(lambda m: m.group(1) + json.dumps(steps_dir.as_posix()), text)def start(body: dict) -> dict:ids = [str(i) for i in body.get("ids") or []]if not ids or not all(ID.match(i) for i in ids):raise ValueError("ids: case ids such as AP-FUS-001")pw_run_id = str(body.get("pw_run_id") or "")if not ID.match(pw_run_id):raise ValueError("pw_run_id is missing or not a plain id")config = str(body.get("config") or "playwright.fusion.config.ts")if config not in CONFIGS:raise ValueError(f"config is one of {sorted(CONFIGS)}")env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in ENV_KEYS}if not LOCK.acquire(blocking=False):raise BlockingIOError("another attempt is running on this runner")try:jid = "job_" + secrets.token_hex(6)jd = HOME / jid(jd / "drafts").mkdir(parents=True)(jd / "library").mkdir()(jd / "steps").mkdir()for name, text in (body.get("steps") or {}).items(): # the steps scenarios' YAML (the server's copy is not here)if not YAML_NAME.match(name):raise ValueError(f"steps: {name!r} is not a scenario file name")(jd / "steps" / name).write_text(str(text), encoding="utf-8")for kind in ("drafts", "library"):for name, text in (body.get(kind) or {}).items():if not SPEC.match(name):raise ValueError(f"{kind}: {name!r} is not a spec file name")(jd / kind / name).write_text(local_spec(str(text), jd / "steps"), encoding="utf-8")report = jd / "report.json"env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE")}env.update(env_in)if body.get("storage_state") is not None: # assisted sign-in: the tests start from the session a person signed inenv["FPT_FUSION_STORAGE_STATE"] = str(write_session(jd, body["storage_state"]))env.update({"PLAYWRIGHT_MODE": "live", "PW_RETRIES": "0", "PW_RUN_ID": pw_run_id, "PLAYWRIGHT_JSON_OUTPUT_NAME": str(report),"FPT_TESTDATA_USED": str(jd / "testdata-used.jsonl"), "FPT_CREATED_FILE": str(jd / "created.jsonl")})live = body.get("live") or {}for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"):env.pop(k, None)if live and ID.match(str(live.get("attempt") or "")): # live view: the browser hook drops its latest frame here(jd / "live").mkdir()env.update({"FPT_LIVE_VIEW_DIR": str(jd / "live"), "FPT_LIVE_VIEW_ATTEMPT": str(live["attempt"]), "FPT_LIVE_VIEW_CHUNK": "0"})for kind in ("drafts", "library"):key = "FPT_DRAFTS_DIR" if kind == "drafts" else "FPT_LIBRARY_DIR"if any((jd / kind).glob("*.spec.ts")):env[key] = str(jd / kind)else:env.pop(key, None)cmd = ["node", str(AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"), "test", "--config", config,"--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(), "kind": "attempt","deadline": time.time() + min(float(body.get("timeout_s") or 3600), 4 * 3600), "state": "running", "exit_code": None}JOBS[jid] = jobsave_meta(job)threading.Thread(target=_watch, args=(job,), daemon=True).start()return {"id": jid, "state": "running"}except BaseException:LOCK.release()raiseSCREEN_SCRIPTS = {"explore": "scripts/explore-fusion.ts", "capture": "scripts/capture-fusion.ts"}SCREEN_ENV = ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA")TASK = re.compile(r"^[^\r\n<>]{5,250}$")OUT_FILE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,160}\.(json|values)$")def start_screens(body: dict) -> dict:"""Read a pod's screens (labels only): "explore" with a plan of areas, or "capture" of one "Area > Page > Task".Same lock as the attempts (one browser); the files land in the job's out/ folder and come back in the bundle."""kind = str(body.get("kind") or "")if kind not in SCREEN_SCRIPTS:raise ValueError(f"kind is one of {sorted(SCREEN_SCRIPTS)}")env_in = {k: str(v) for k, v in (body.get("env") or {}).items() if k in SCREEN_ENV}if not all(env_in.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):raise ValueError("env needs FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD")task = str(body.get("task") or "")if kind == "capture" and not TASK.match(task):raise ValueError('task is "Area > Page > Task"')if kind == "explore" and not isinstance(body.get("plan"), dict):raise ValueError("plan is the explorer's plan (an object)")if not LOCK.acquire(blocking=False):raise BlockingIOError("another attempt is running on this runner")try:jid = "job_" + secrets.token_hex(6)jd = HOME / jid(jd / "out").mkdir(parents=True)arg = taskif kind == "explore":(jd / "plan.json").write_text(json.dumps(body["plan"]), encoding="utf-8")arg = str(jd / "plan.json")env = {k: v for k, v in os.environ.items() if k not in ("RUNNER_TOKEN",)}env.update(env_in)cmd = ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), SCREEN_SCRIPTS[kind], arg, "--out-dir", str(jd / "out")]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": 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] = jobsave_meta(job)threading.Thread(target=_watch, args=(job,), daemon=True).start()return {"id": jid, "state": "running"}except BaseException:LOCK.release()raisedef live_now(job: dict) -> dict:"""The live view of a running attempt: the latest frame and the failed scenario's last frame (JPEG, base64) and thehook's status. The hook never writes a sign-in screen (it masks pages with a password field)."""d = job["dir"] / "live"out: dict = {"status": None, "frame": None, "failed": None, "frame_at": None}if not d.is_dir():return outtry:out["status"] = json.loads((d / "status.json").read_text(encoding="utf-8"))except (OSError, ValueError):passfor key, name in (("frame", "frame.jpg"), ("failed", "failed.jpg")):f = d / nametry:if key == "frame":out["frame_at"] = f.stat().st_mtimeout[key] = base64.b64encode(f.read_bytes()).decode()except OSError:passreturn outdef _lines(log: Path, since: int) -> tuple[list[str], int]:"""The log's lines from `since` on (at most 200), and how many lines it has."""try:lines = log.read_text(encoding="utf-8", errors="replace").splitlines()except OSError:return [], 0return [ln[:500] for ln in lines[since:since + 200]], len(lines)def _kill_tree(p: subprocess.Popen) -> None:"""Stop the attempt and every browser it started (a process group on Linux, a process tree on Windows)."""try:if os.name == "posix":os.killpg(p.pid, signal.SIGKILL)else:subprocess.run(["taskkill", "/PID", str(p.pid), "/T", "/F"], capture_output=True, timeout=30)except (OSError, subprocess.SubprocessError):passdef _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 itsJSON report. False where that cannot be asked (Windows: the attempt is killed at once)."""if os.name != "posix":return Falsetry:os.kill(p.pid, signal.SIGINT)return Trueexcept OSError:return Falsedef _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 isif 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 = Nonewhile p.poll() is None: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 lostjob["timed_out"] = Truestop_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.returncodejob["log"].close()_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 releasedjob["state"], job["error"] = "failed", f"{type(e).__name__}: {e}"[:300]_kill_tree(p)finally:drop_session(job)save_meta(job)LOCK.release()# ------------------------------------------------------------------ assisted sign-in: a browser a person signs in withSIGN_INS: dict[str, dict] = {}SIGN_IN_IDLE_S = float(os.environ.get("RUNNER_SIGN_IN_IDLE_S", "900"))SIGN_IN_KEEP_S = 600 # a signed-in session nobody fetched is deleted after this longPOD_URL = re.compile(r"^https://[A-Za-z0-9](?:[A-Za-z0-9.-]{0,251}[A-Za-z0-9])?(?::\d{1,5})?$")KEY = re.compile(r"^(?:(?:Control|Shift|Alt|Meta)\+)*(?:[A-Za-z0-9]|Enter|Tab|Backspace|Delete|Escape|ArrowUp|ArrowDown|ArrowLeft"r"|ArrowRight|Home|End|PageUp|PageDown|Space)$")VIEW = (1280, 800) # the sign-in browser's viewport (scripts/sign-in-session.ts): clicks are in its pixelsdef sign_in_cmd(folder: Path) -> list[str]:"""The sign-in browser (scripts/sign-in-session.ts), driven through `folder`."""return ["node", str(AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"), "scripts/sign-in-session.ts", str(folder)]def check_events(events) -> list[dict]:"""The person's clicks, text, keys and scrolls, checked (at most 50 per call): anything else is refused whole."""if not isinstance(events, list) or not 1 <= len(events) <= 50:raise ValueError("events: 1 to 50 input events")out = []for e in events:t = e.get("type") if isinstance(e, dict) else Nonenum = lambda k: isinstance(e.get(k), (int, float)) and not isinstance(e.get(k), bool) # noqa: E731if t == "click" and num("x") and num("y") and 0 <= e["x"] <= VIEW[0] and 0 <= e["y"] <= VIEW[1]:out.append({"type": "click", "x": round(float(e["x"]), 1), "y": round(float(e["y"]), 1)})elif t == "type" and isinstance(e.get("text"), str) and 0 < len(e["text"]) <= 500:out.append({"type": "type", "text": e["text"]})elif t == "press" and isinstance(e.get("key"), str) and KEY.match(e["key"]):out.append({"type": "press", "key": e["key"]})elif t == "scroll" and num("dy") and abs(e["dy"]) <= 2000:out.append({"type": "scroll", "dy": float(e["dy"])})else:raise ValueError(f"event {len(out) + 1} is not a click, text, key or scroll this browser accepts")return outdef _say(s: dict, events: list[dict]) -> None:with open(s["dir"] / "input.jsonl", "a", encoding="utf-8") as fh:for e in events:fh.write(json.dumps(e) + "\n")def start_sign_in(body: dict) -> dict:base = str(body.get("base_url") or "").strip().rstrip("/")if not POD_URL.match(base):raise ValueError("base_url is the pod's https address")try:idle = max(60.0, min(float(body.get("idle_s") or SIGN_IN_IDLE_S), 3600.0))except (TypeError, ValueError):raise ValueError("idle_s is a number of seconds") from Noneif not LOCK.acquire(blocking=False):raise BlockingIOError("another attempt is running on this runner")try:sid = "si_" + secrets.token_hex(6)d = HOME / sidd.mkdir(parents=True)env = {k: v for k, v in os.environ.items() if k not in ENV_KEYS and k not in ("RUNNER_TOKEN", "FPT_FUSION_STORAGE_STATE")}env.update({"FUSION_BASE_URL": base, "FPT_SIGN_IN_MAX_S": "3600"})log = open(d / "sign-in.log", "wb")p = subprocess.Popen(sign_in_cmd(d), cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **GROUP)s = {"id": sid, "dir": d, "proc": p, "log": log, "started": time.time(), "last_input": time.time(), "idle_s": idle,"state": "open"}SIGN_INS[sid] = sthreading.Thread(target=_watch_sign_in, args=(s,), daemon=True).start()return {"id": sid, "state": "starting"}except BaseException:LOCK.release()raisedef sign_in_now(s: dict) -> dict:"""The session as Astra's run page shows it: its state, which kind of page is open, the latest frame (JPEG, base64)."""d = s["dir"]try:st = json.loads((d / "status.json").read_text(encoding="utf-8"))except (OSError, ValueError):st = {}state = s["state"] if s["state"] != "open" else (st.get("state") or "starting")if state == "closed" and (d / "state.json").exists():state = "signed_in"out = {"id": s["id"], "state": state, "page": st.get("page"), "error": st.get("error") if state == "failed" else None,"frame": None, "frame_at": None, "idle_left_s": max(0, int(s["idle_s"] - (time.time() - s["last_input"])))}if state in ("starting", "open"):try:out["frame_at"] = (d / "frame.jpg").stat().st_mtimeout["frame"] = base64.b64encode((d / "frame.jpg").read_bytes()).decode()except OSError:passreturn outdef sign_in_input(s: dict, body: dict) -> dict:if s["state"] != "open" or s["proc"].poll() is not None:raise LookupError("this sign-in session is not open any more")events = check_events(body.get("events"))_say(s, events)s["last_input"] = time.time()return {"accepted": len(events)}def finish_sign_in(s: dict, wait_s: float = 20.0) -> dict | None:"""The signed-in session, handed back once: the browser saves it when asked (or saved it on reaching the Fusionhome page), then it is deleted here with the session's folder."""f = s["dir"] / "state.json"if not f.exists() and s["state"] == "open" and s["proc"].poll() is None:_say(s, [{"type": "finish"}])end = time.time() + wait_swhile not f.exists() and s["proc"].poll() is None and time.time() < end:time.sleep(0.2)for _ in range(10): # the browser writes the file, then closes: give it a moment to finishif s["proc"].poll() is not None:breaktime.sleep(0.2)try:data = json.loads(f.read_text(encoding="utf-8"))except (OSError, ValueError):return Nones["state"] = "finished"_close_sign_in(s)return datadef cancel_sign_in(s: dict) -> None:if s["state"] == "open" and s["proc"].poll() is None:s["cancel"] = Truetry:_say(s, [{"type": "cancel"}])except OSError:passelse:s["state"] = "cancelled" if s["state"] in ("open", "signed_in") else s["state"]_close_sign_in(s)def _close_sign_in(s: dict) -> None:if s["proc"].poll() is None:_kill_tree(s["proc"])try:s["proc"].wait(timeout=10)except subprocess.TimeoutExpired:passtry:s["log"].close() # its log is in the folder (Windows keeps an open file)except OSError:passshutil.rmtree(s["dir"], ignore_errors=True) # frames, the session, the inbox: nothing of it stays on diskdef _watch_sign_in(s: dict) -> None:"""The browser runs until the person signs in, finishes, cancels, or leaves it idle; the lock is free once it is gone."""p = s["proc"]try:stop_at = Nonewhile p.poll() is None:idle = time.time() - s["last_input"] > s["idle_s"]if s.get("cancel") or idle:s["expired"] = s.get("expired") or (idle and not s.get("cancel"))stop_at = stop_at or time.time() + 5 # asked to close first, then stoppedif time.time() >= stop_at:_kill_tree(p)time.sleep(0.5)s["log"].close()except Exception: # noqa: BLE001 - the session ends as failed, the lock is never kept_kill_tree(p)finally:LOCK.release()if s["state"] != "open": # handed back (or cancelled) while the browser closedreturnsaved = (s["dir"] / "state.json").exists()state = "cancelled" if s.get("cancel") else "expired" if s.get("expired") else "signed_in" if saved else "closed"if state != "signed_in":_close_sign_in(s) # nothing of it on disk before it reads as endeds["state"] = statereturns["state"] = stateend = time.time() + SIGN_IN_KEEP_S # waiting for Astra to fetch it, but not for everwhile time.time() < end and s["state"] == "signed_in":time.sleep(1)if s["state"] == "signed_in":s["state"] = "expired"_close_sign_in(s)def bundle(job: dict) -> bytes:buf = io.BytesIO()with zipfile.ZipFile(buf, "w", zipfile.ZIP_DEFLATED) as z:for name in ("report.json", "testdata-used.jsonl", "created.jsonl", "playwright.log"):f = job["dir"] / nameif f.exists():z.write(f, name)out = job["dir"] / "out" # a screen read: the inventories (labels) and the list choices it foundif out.exists():for f in out.iterdir():if f.is_file() and OUT_FILE.match(f.name):z.write(f, "out/" + f.name)run = job["dir"] / "run"if run.exists():for f in run.rglob("*"):if f.is_file() and f.name != ".fusion-session.json": # never ship the session cookiesz.write(f, "run/" + str(f.relative_to(run)).replace("\\", "/"))return buf.getvalue()def sweep() -> None:while True:cut = time.time() - KEEP_Sfor jid, job in list(JOBS.items()):if job["state"] != "running" and job["started"] < cut:shutil.rmtree(job["dir"], ignore_errors=True)JOBS.pop(jid, None)# folders of jobs from before a restart are not in JOBS: their age on disk decidesfor d in HOME.glob("job_*"):if d.is_dir() and d.name not in JOBS and d.stat().st_mtime < cut:shutil.rmtree(d, ignore_errors=True)time.sleep(600)class H(BaseHTTPRequestHandler):server_version = "PatchwiseRunner/1"def log_message(self, fmt, *args): # one quiet line per call, never a header or a bodyprint(time.strftime("%H:%M:%S"), self.command, self.path.split("?")[0], args[1] if len(args) > 1 else "", flush=True)def _send(self, code: int, obj=None, raw: bytes | None = None, ctype="application/json"):b = raw if raw is not None else json.dumps(obj).encode()self.send_response(code)self.send_header("Content-Type", ctype)self.send_header("Content-Length", str(len(b)))self.send_header("Cache-Control", "no-store")self.end_headers()self.wfile.write(b)def _auth(self) -> bool:h = self.headers.get("Authorization", "")ok = bool(TOKEN) and h.startswith("Bearer ") and hmac.compare_digest(h[7:].strip(), TOKEN)if not ok:self._send(401, {"error": "a valid runner token is needed"})return okdef _job(self, jid: str):job = JOBS.get(jid)if not job:self._send(404, {"error": "no such attempt"})return jobdef do_GET(self):if self.path == "/healthz":version = VERSION_FILE.read_text(encoding="utf-8").strip()[:40] if VERSION_FILE.is_file() else "unknown"return self._send(200, {"ok": bool(TOKEN), "busy": LOCK.locked(), "automation": AUTOMATION.exists(), "cases": CASES.is_dir(),"version": version})if not self._auth():returnsi = re.fullmatch(r"/v1/sign-in/(si_[0-9a-f]{12})", self.path)if si:s = SIGN_INS.get(si.group(1))return self._send(200, sign_in_now(s)) if s else self._send(404, {"error": "no such sign-in session"})m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})(/bundle|/live)?(?:\?since=(\d{1,7}))?", self.path)if not m:return self._send(404, {"error": "not found"})job = self._job(m.group(1))if not job:returnif m.group(2) == "/live":return self._send(200, live_now(job) if job["state"] == "running" else {"status": None, "frame": None, "failed": None, "frame_at": None})if m.group(2):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.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 progressst["lines"], st["line_count"] = _lines(job["dir"] / "playwright.log", int(m.group(3)))self._send(200, st)def do_POST(self):if not self._auth():returnn = int(self.headers.get("Content-Length") or 0)if n > MAX_BODY:return self._send(413, {"error": "body too large"})if self.path in ("/v1/attempts", "/v1/screens"):try:body = json.loads(self.rfile.read(n) or b"{}")return self._send(202, start(body) if self.path == "/v1/attempts" else start_screens(body))except BlockingIOError as e:return self._send(409, {"error": str(e)})except (ValueError, TypeError) as e:return self._send(400, {"error": str(e)})if self.path == "/v1/sign-in":try:return self._send(202, start_sign_in(json.loads(self.rfile.read(n) or b"{}")))except BlockingIOError as e:return self._send(409, {"error": str(e)})except (ValueError, TypeError, AttributeError) as e:return self._send(400, {"error": str(e)})si = re.fullmatch(r"/v1/sign-in/(si_[0-9a-f]{12})/(input|finish|cancel)", self.path)if si:s = SIGN_INS.get(si.group(1))if not s:return self._send(404, {"error": "no such sign-in session"})try:if si.group(2) == "input": # only the session this id opened, and only while it is openreturn self._send(200, sign_in_input(s, json.loads(self.rfile.read(n) or b"{}")))if si.group(2) == "finish":state = finish_sign_in(s)if state is None:return self._send(409, {"error": "the sign-in session holds no signed-in session (not signed in yet, or closed)"})return self._send(200, {"id": s["id"], "state": "finished", "storage_state": state})cancel_sign_in(s)return self._send(202, {"id": s["id"], "state": "cancelling" if s.get("cancel") else s["state"]})except LookupError as e:return self._send(409, {"error": str(e)})except (ValueError, TypeError, AttributeError) as e:return self._send(400, {"error": str(e)})m = re.fullmatch(r"/v1/attempts/(job_[0-9a-f]{12})/cancel", self.path)if m:job = self._job(m.group(1))if job:if job["state"] == "running":job["cancel"] = Trueself._send(202, {"id": job["id"], "state": "cancelling" if job["state"] == "running" else job["state"]})returnself._send(404, {"error": "not found"})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)for old in HOME.glob("si_*"): # a sign-in session never outlives the runner: its frames and cookies goshutil.rmtree(old, ignore_errors=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()
123456789101112131415161718192021222324252627282930313233/* Checks the control-name healing logic (src/fusion/heal.ts) without a browser: `npx tsx scripts/check-heal.ts`. */import assert from 'node:assert/strict';import { closeMatch, normalise, normalisedMatch, parseHeals, pick } from '../src/fusion/heal';
assert.equal(normalise(' Invoice Number (Required) '), 'invoice number');assert.equal(normalise('Amount: 3'), 'amount');assert.equal(normalisedMatch('Invoice Number', ['Amount', 'invoice number', 'Supplier']), 'invoice number');assert.equal(normalisedMatch('Save', ['Save', 'SAVE']), null); // two ways to write it: not unambiguous// close names: one clear candidate onlyassert.equal(closeMatch('Business Unit', ['Business Units', 'Supplier']), 'Business Units');assert.equal(closeMatch('Validate', ['Invalidate']), null); // a different action, not a relabelassert.equal(closeMatch('Amount 1', ['Amount 2']), null); // a different rowassert.equal(closeMatch('Cancel', ['Cancel Invoice']), null);assert.equal(closeMatch('Add Row', ['Add Rows', 'Add Rowz']), null); // two candidates, no clear winnerassert.equal(closeMatch('UOM', ['UOMs']), null); // too short to guessassert.equal(closeMatch('Supplier', []), null);// order: approved, then same name, then closeconst rules = [{ kind: 'button' as const, wanted: 'Submit', to: 'Send for Approval', where: 'Purchasing > Orders > Create Order' }];assert.deepEqual(pick(rules, 'button', 'Submit', 'Purchasing > Orders > Create Order', ['Send for Approval', 'Cancel']), { used: 'Send for Approval', how: 'approved' });assert.equal(pick(rules, 'button', 'Submit', 'Payables > Invoices > Create Invoice', ['Send for Approval']), null); // another task: not that healassert.equal(pick(rules, 'field', 'Submit', 'Purchasing > Orders > Create Order', ['Send for Approval']), null); // another kindassert.equal(pick(rules, 'button', 'Submit', 'Purchasing > Orders > Create Order', ['Cancel']), null); // approved name gone: no guessassert.deepEqual(pick([], 'field', 'Invoice Date', '', ['invoice date']), { used: 'invoice date', how: 'normalised' });assert.deepEqual(pick([], 'menu', 'Cancel Document', '', ['Cancel Documents']), { used: 'Cancel Documents', how: 'close' });// a heal a person rejected is never picked on the spot (that place only), and is not an approvalconst no = [{ kind: 'menu' as const, wanted: 'Cancel Document', to: 'Cancel Documents', where: 'Purchasing > Orders', rejected: true }];assert.equal(pick(no, 'menu', 'Cancel Document', 'Purchasing > Orders', ['Cancel Documents']), null);assert.deepEqual(pick(no, 'menu', 'Cancel Document', 'Payables > Invoices', ['Cancel Documents']), { used: 'Cancel Documents', how: 'close' });// FPT_HEALS: bad input is ignoredassert.deepEqual(parseHeals(undefined), []);assert.deepEqual(parseHeals('not json'), []);assert.deepEqual(parseHeals('[{"kind":"field","wanted":"A","to":"B"},{"kind":"x"},5]'), [{ kind: 'field', wanted: 'A', to: 'B' }]);console.log('heal: all checks pass');123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127// Assisted sign-in: a browser a PERSON signs in with, for a pod whose sign-in goes through the company's identity provider// (Entra, Okta, with MFA), which no unattended browser can complete. Started by Astra on this server or by the remote// runner (automation/remote_runner/server.py); both drive it through one folder://// FUSION_BASE_URL=https://pod.example npx tsx scripts/sign-in-session.ts <folder>//// <folder>/frame.jpg the page as it looks now (replaced about twice a second)// <folder>/status.json {state: starting | open | signed_in | saved | closed | failed, page: pod | identity provider | blank,// at, error?}: never the page address (a sign-in address can carry one-time codes)// <folder>/input.jsonl what the person does, one JSON event per line, appended by the controller:// {"type": "click", "x", "y"} | {"type": "type", "text"} | {"type": "press", "key"} |// {"type": "scroll", "dy"} | {"type": "finish"} | {"type": "cancel"}// <folder>/state.json the signed-in session (Playwright storage state: the pod's cookies), mode 0600, written once// the Fusion home page opens (the same check FusionUi.signIn() uses) or on "finish"//// Nothing the person types is printed, recorded or kept: no trace, no video, no log line with an event's content. The// browser stops after FPT_SIGN_IN_MAX_S seconds (default 1800) whatever happens; the controller stops it sooner when// nobody uses it (15 minutes).import * as fs from 'fs';import * as path from 'path';import { chromium, type Page } from '@playwright/test';
export const VIEWPORT = { width: 1280, height: 800 };/** The Fusion home page: where signIn() knows a sign-in has worked (src/fusion/ui.ts). */export const HOME = /AtkHomePageWelcome|FuseWelcome/;const KEY = /^(?:(?:Control|Shift|Alt|Meta)\+)*(?:[A-Za-z0-9]|Enter|Tab|Backspace|Delete|Escape|ArrowUp|ArrowDown|ArrowLeft|ArrowRight|Home|End|PageUp|PageDown|Space)$/;
type Event = { type: string; x?: number; y?: number; text?: string; key?: string; dy?: number };
function write(folder: string, name: string, data: string | Buffer, mode?: number) { const tmp = path.join(folder, `.${name}.tmp`); fs.writeFileSync(tmp, data, mode ? { mode } : undefined); fs.renameSync(tmp, path.join(folder, name));}
/** Which kind of page is open, never its address: the pod itself, the identity provider, or nothing yet. */export function pageKind(url: string, podHost: string): 'pod' | 'identity provider' | 'blank' { try { const u = new URL(url); if (u.protocol === 'about:' || !u.hostname) return 'blank'; return u.hostname === podHost ? 'pod' : 'identity provider'; } catch { return 'blank'; }}
/** The Fusion home page of the pod, so the session holds what the tests need. */export function onHome(url: string, podHost: string): boolean { try { const u = new URL(url); return u.hostname === podHost && HOME.test(u.pathname); } catch { return false; }}
async function apply(page: Page, e: Event): Promise<void> { if (e.type === 'click' && Number.isFinite(e.x) && Number.isFinite(e.y)) { await page.mouse.click(Math.max(0, Math.min(VIEWPORT.width, Number(e.x))), Math.max(0, Math.min(VIEWPORT.height, Number(e.y)))); } else if (e.type === 'type' && typeof e.text === 'string') { await page.keyboard.type(e.text.slice(0, 500)); } else if (e.type === 'press' && typeof e.key === 'string' && KEY.test(e.key)) { await page.keyboard.press(e.key === 'Space' ? ' ' : e.key); } else if (e.type === 'scroll' && Number.isFinite(e.dy)) { await page.mouse.wheel(0, Math.max(-2000, Math.min(2000, Number(e.dy)))); }}
async function main() { const folder = path.resolve(process.argv[2] || ''); const base = (process.env.FUSION_BASE_URL || '').replace(/\/$/, ''); if (!process.argv[2] || !fs.existsSync(folder)) throw new Error('usage: sign-in-session.ts <folder> (FUSION_BASE_URL set)'); if (!/^https:\/\//.test(base)) throw new Error('FUSION_BASE_URL must be the pod address (https)'); const host = new URL(base).hostname; const maxMs = Math.max(60, Math.min(3600, Number(process.env.FPT_SIGN_IN_MAX_S) || 1800)) * 1000; const end = Date.now() + maxMs; const status = (state: string, extra: Record<string, unknown> = {}) => write(folder, 'status.json', JSON.stringify({ state, at: new Date().toISOString(), ...extra })); status('starting', { page: 'blank' }); const browser = await chromium.launch({ headless: true }); let state = 'closed'; try { const context = await browser.newContext({ viewport: VIEWPORT }); const page = await context.newPage(); page.setDefaultTimeout(30_000); await page.goto(`${base}/`, { waitUntil: 'domcontentloaded', timeout: 120_000 }).catch(() => {}); const inbox = path.join(folder, 'input.jsonl'); let offset = 0; let finish = false; while (Date.now() < end) { // what the person did since the last look (a partial last line waits for the next round) let events: Event[] = []; try { const buf = fs.readFileSync(inbox); const upto = buf.lastIndexOf(10) + 1; if (upto > offset) { events = buf.subarray(offset, upto).toString('utf-8').split('\n').filter(Boolean).flatMap((l) => { try { return [JSON.parse(l) as Event]; } catch { return []; } }); offset = upto; } } catch { /* nothing sent yet */ } if (events.some((e) => e.type === 'cancel')) { state = 'closed'; break; } for (const e of events) { if (e.type === 'finish') { finish = true; break; } await apply(page, e).catch(() => {}); // a click that lands nowhere is the person's to repeat } const url = page.url(); if (finish || onHome(url, host)) { await page.waitForLoadState('domcontentloaded').catch(() => {}); write(folder, 'state.json', JSON.stringify(await context.storageState()), 0o600); state = finish && !onHome(url, host) ? 'saved' : 'signed_in'; break; } const shot = await page.screenshot({ type: 'jpeg', quality: 60, timeout: 10_000 }).catch(() => null); if (shot) write(folder, 'frame.jpg', shot); status('open', { page: pageKind(url, host) }); await page.waitForTimeout(events.length ? 150 : 450); } } catch (e) { state = 'failed'; status('failed', { page: 'blank', error: String((e as Error).message || e).split('\n')[0].slice(0, 200) }); } finally { await browser.close().catch(() => {}); } if (state !== 'failed') status(state, { page: state === 'closed' ? 'blank' : 'pod' });}
if (require.main === module) { main().catch((e) => { console.error(`[sign-in] ${String((e as Error).message || e).split('\n')[0]}`); process.exit(1); });}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364import { appendFileSync } from 'node:fs';import { test as base, expect } from '@playwright/test';import { beginLiveStatus, liveViewDir, startLiveView } from '../live-view';import { FusionRest } from './rest';import { apData, FusionUi } from './ui';/** Payables test invoices of one test: REST for checks, and every number registered here is cancelled afterwards. */export interface ApInvoices {rest: FusionRest;/** Register a test invoice number BEFORE saving it, so it is cleaned up even if the test fails half-way. */track(number: string): string;}/*** The run's test-data ledger (FPT_CREATED_FILE, a JSON-lines file in the co-worker's run folder). A number is written* here BEFORE the invoice is saved, and its clean-up result after; if the run is cancelled, killed, times out or the* server restarts before the clean-up below runs, the co-worker cancels what is left through Fusion REST.*/function ledger(rec: Record<string, unknown>): void {const f = process.env.FPT_CREATED_FILE;if (!f) return;appendFileSync(f, JSON.stringify({ ...rec, ts: new Date().toISOString() }) + '\n', 'utf-8'); // synchronous: on disk before the save}/** Live view follows ONE browser: with several tests at once (FPT_FUSION_WORKERS), the first worker's. The Live tab* shows one picture, and frames from several browsers would only flicker between tests. */const watched = (testInfo: { parallelIndex: number }) => !!liveViewDir() && testInfo.parallelIndex === 0;/** Fixtures for tests against a real Oracle Fusion pod: the Fusion steps plus the same live view as mock runs. */export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; liveStatus: void }>({page: async ({ page }, use, testInfo) => {const stopLive = watched(testInfo) ? await startLiveView(page, testInfo) : null;await use(page);if (stopLive) await stopLive();},fusion: async ({ page }, use) => { await use(new FusionUi(page)); },apInvoices: async ({}, use, testInfo) => {const rest = new FusionRest();const numbers: string[] = [];const d = apData();await use({rest,track: (n) => {if (!numbers.includes(n)) {ledger({ kind: 'ap_invoice', number: n, businessUnit: d.businessUnit, supplier: d.supplier, test: testInfo.title });numbers.push(n);}return n;},});// Clean-up runs whether the test passed or failed; a clean-up failure fails the test (data left on the pod).const errors: string[] = [];for (const n of numbers) {try {const done = await rest.cancelIfPresent(n, d.businessUnit, d.supplier);testInfo.annotations.push({ type: 'cleanup', description: done });ledger({ kind: 'ap_invoice', number: n, cleaned: done });} catch (e) { errors.push(String((e as Error).message || e)); }}if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`);},liveStatus: [async ({}, use, testInfo) => { const done = watched(testInfo) ? beginLiveStatus(testInfo) : null; await use(); if (done) done(); }, { auto: true }],});export { expect };123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142import { appendFileSync } from 'node:fs';import { test as base, expect } from '@playwright/test';import { beginLiveStatus, liveViewDir, startLiveView } from '../live-view';import { FusionRest, NeedsScreen, NO_REST_WHY, REST_SKIPPED } from './rest';import { apData, assistedSignIn, FusionUi, markSignInExpired, SIGN_IN_EXPIRED, signInExpiredReason } from './ui';/** Payables test invoices of one test: REST for checks, and every number registered here is cancelled afterwards. */export interface ApInvoices {rest: FusionRest;/** Register a test invoice number BEFORE saving it, so it is cleaned up even if the test fails half-way. */track(number: string): string;/** A check through Fusion REST: run when REST is available; on a pod with assisted sign-in (no password) skipped with* a note on the test, and the screen result stands. */check(what: string, fn: () => Promise<void>): Promise<void>;}/** The Purchasing and General Ledger test documents a test creates, by the reference registered BEFORE the save (the* test's FPT- tag in a requisition's or an order's Description, a journal batch's name): Fusion gives a requisition* or an order its number only when it is saved. */export type DocKind = 'po_requisition' | 'po_order' | 'gl_journal';export interface FusionDocs {/** Register a test document BEFORE saving it, so it is cleaned up even if the test fails half-way. */track(kind: DocKind, ref: string): string;}/** Clean-up of one test document over REST (rest.ts): a requisition or order cancelled or deleted, a journal deleted* while unposted. What REST cannot do (a submitted requisition, an order pending approval) is done on the screens* with the business action's own steps, then REST is asked again. */async function cleanDoc(rest: FusionRest, ui: FusionUi, kind: DocKind, ref: string): Promise<string> {const clean = () => (kind === 'po_requisition' ? rest.cleanRequisition(ref) : kind === 'po_order' ? rest.cleanPurchaseOrder(ref) : rest.cleanJournal(ref));try {return await clean();} catch (e) {if (!(e instanceof NeedsScreen)) throw e;if (kind === 'po_requisition') await ui.cancelRequisition(ref);else if (kind === 'po_order') await ui.cancelPurchaseOrder(ref);else throw e;return `${await clean()} (on the screens: ${e.message})`;}}/*** The run's test-data ledger (FPT_CREATED_FILE, a JSON-lines file in the co-worker's run folder). A number is written* here BEFORE the invoice is saved, and its clean-up result after; if the run is cancelled, killed, times out or the* server restarts before the clean-up below runs, the co-worker cancels what is left through Fusion REST.*/function ledger(rec: Record<string, unknown>): void {const f = process.env.FPT_CREATED_FILE;if (!f) return;appendFileSync(f, JSON.stringify({ ...rec, ts: new Date().toISOString() }) + '\n', 'utf-8'); // synchronous: on disk before the save}/** Live view follows ONE browser: with several tests at once (FPT_FUSION_WORKERS), the first worker's. The Live tab* shows one picture, and frames from several browsers would only flicker between tests. */const watched = (testInfo: { parallelIndex: number }) => !!liveViewDir() && testInfo.parallelIndex === 0;/** Fixtures for tests against a real Oracle Fusion pod: the Fusion steps plus the same live view as mock runs. */export const test = base.extend<{ fusion: FusionUi; apInvoices: ApInvoices; fusionDocs: FusionDocs; liveStatus: void; signInGuard: void }>({page: async ({ page }, use, testInfo) => {const stopLive = watched(testInfo) ? await startLiveView(page, testInfo) : null;await use(page);if (stopLive) await stopLive();},fusion: async ({ page }, use) => { await use(new FusionUi(page)); },apInvoices: async ({}, use, testInfo) => {const rest = new FusionRest();const numbers: string[] = [];const d = apData();await use({rest,track: (n) => {if (!numbers.includes(n)) {ledger({ kind: 'ap_invoice', number: n, businessUnit: d.businessUnit, supplier: d.supplier, test: testInfo.title });numbers.push(n);}return n;},check: async (what, fn) => {if (rest.available) return fn();testInfo.annotations.push({ type: REST_SKIPPED, description: `${what}: ${NO_REST_WHY}` });},});if (!rest.available) { // assisted sign-in, no REST: the ledger keeps them listed, the run asks a person to cancel themfor (const n of numbers) testInfo.annotations.push({ type: 'cleanup', description: `${n}: not cancelled (no Fusion REST on this pod); cancel it by hand` });return;}// Clean-up runs whether the test passed or failed; a clean-up failure fails the test (data left on the pod).const errors: string[] = [];for (const n of numbers) {try {const done = await rest.cancelIfPresent(n, d.businessUnit, d.supplier);testInfo.annotations.push({ type: 'cleanup', description: done });ledger({ kind: 'ap_invoice', number: n, cleaned: done });} catch (e) { errors.push(String((e as Error).message || e)); }}if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`);},// The same for requisitions, orders and journals. It uses the test's own browser for what REST cannot clean up, so// it is torn down before the page (it depends on `fusion`).fusionDocs: async ({ fusion }, use, testInfo) => {const docs: [DocKind, string][] = [];await use({track: (kind, ref) => {if (!docs.some(([k, r]) => k === kind && r === ref)) {ledger({ kind, number: ref, by: kind === 'gl_journal' ? 'name' : 'description', test: testInfo.title });docs.push([kind, ref]);}return ref;},});if (!docs.length) return;const rest = new FusionRest();const errors: string[] = [];// the newest first: an order made from a requisition goes before the requisitionfor (const [kind, ref] of [...docs].reverse()) {try {const done = await cleanDoc(rest, fusion, kind, ref);testInfo.annotations.push({ type: 'cleanup', description: done });ledger({ kind, number: ref, cleaned: done });} catch (e) { errors.push(String((e as Error).message || e).split('\n')[0]); }}if (errors.length) throw new Error(`Clean-up failed, test data may be left on the pod: ${errors.join('; ')}`);},// Assisted sign-in: a test after the session expired is skipped with the reason, and a test that stopped on a sign-in// page is marked, so Astra runs both again after a new sign-in instead of reporting them as failures.signInGuard: [async ({ page }, use, testInfo) => {if (!assistedSignIn()) return use();const before = signInExpiredReason();if (before) {testInfo.annotations.push({ type: SIGN_IN_EXPIRED, description: before });testInfo.skip(true, before);}await use();if (testInfo.status === testInfo.expectedStatus) return;const why = signInExpiredReason() ?? (await new FusionUi(page).onSignInPage()? markSignInExpired('Sign-in expired: the test landed on the sign-in page mid-way (assisted sign-in). Astra asks for a new sign-in and runs it again.'): null);if (why) testInfo.annotations.push({ type: SIGN_IN_EXPIRED, description: why });}, { auto: true }],liveStatus: [async ({}, use, testInfo) => { const done = watched(testInfo) ? beginLiveStatus(testInfo) : null; await use(); if (done) done(); }, { auto: true }],});export { expect };
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103/** * Self-healing of control names, as pure functions (no browser): when Oracle relabels a field, button or menu entry, * which of the names the page shows does the test mean? Deliberately strict: a heal that picks the wrong control would * make a test pass for the wrong reason, so it takes a single, unambiguous candidate or nothing. Business assertions * (statuses, amounts, messages) never come through here: ui.ts calls this only to LOCATE a control. */
export type HealKind = 'field' | 'button' | 'menu';/** How the name was found, in the order tried: a person approved it, only case/space/punctuation differ, a close name. */export type HealHow = 'approved' | 'normalised' | 'close';
/** One decided heal (the run's FPT_HEALS, a JSON array): `wanted` is shown as `to` on this pod, optionally only on `where`. * A rejected one says a person looked and `to` is NOT that control: no heal may pick it. */export interface HealRule { kind: HealKind; wanted: string; to: string; where?: string; rejected?: boolean }
const applies = (r: HealRule, kind: HealKind, wanted: string, where: string) => r.kind === kind && normalise(r.wanted) === normalise(wanted) && (!r.where || normalise(r.where) === normalise(where));
/** The closeness (0..1) two names must reach to count as the same control. 0.85 lets "Invoice Number" match "Invoice Num." * but not "Validate" for "Invalidate" (0.8) or "Cancel" for "Cancel Invoice". */export const CLOSE = 0.85;/** A name must be this much closer than the runner-up, so two similar controls ("Amount 1", "Amount 2") are never guessed. */export const GAP = 0.1;
/** A name as a person reads it: no case, no punctuation, one space between words; Fusion's "(Required)" and a table * cell's ": <row>" suffix are not part of the name. */export function normalise(s: string): string { return s.replace(/\(\s*required\s*\)/gi, ' ').replace(/:\s*\d+\s*$/, '') .toLowerCase().replace(/[^\p{L}\p{N}]+/gu, ' ').trim();}
/** 1 - (edit distance / longer length) of two names, 0..1. */export function similarity(a: string, b: string): number { if (a === b) return 1; const n = Math.max(a.length, b.length); if (!n) return 1; let prev = Array.from({ length: b.length + 1 }, (_, j) => j); for (let i = 1; i <= a.length; i++) { const row = [i]; for (let j = 1; j <= b.length; j++) row.push(Math.min(prev[j] + 1, row[j - 1] + 1, prev[j - 1] + (a[i - 1] === b[j - 1] ? 0 : 1))); prev = row; } return 1 - prev[b.length] / n;}
const digits = (s: string) => (s.match(/\d+/g) ?? []).join(',');
/** The one name among `names` that is `wanted` with only case, spaces or punctuation changed; null when none, or when * two different names qualify. */export function normalisedMatch(wanted: string, names: string[]): string | null { const w = normalise(wanted); if (!w) return null; const hits = unique(names.filter((n) => normalise(n) === w)); return hits.length === 1 ? hits[0] : null;}
/** The one name among `names` closer than CLOSE to `wanted`, and GAP closer than any other; null otherwise. Names of * fewer than 4 letters, and names that differ in a number ("Line 1" / "Line 2"), are never matched this way. */export function closeMatch(wanted: string, names: string[]): string | null { const w = normalise(wanted); if (w.length < 4) return null; const scored = unique(names).map((n) => ({ n, k: normalise(n) })).filter(({ k }) => k && k !== w) .map(({ n, k }) => ({ n, s: similarity(w, k), same: digits(w) === digits(k) })) .sort((x, y) => y.s - x.s); const [best, next] = scored; if (!best || !best.same || best.s < CLOSE) return null; return next && best.s - next.s < GAP ? null : best.n;}
/** The approved heal for `wanted` (this kind, and this place when the rule names one) that the page really shows now. */export function approvedMatch(rules: HealRule[], kind: HealKind, wanted: string, where: string, names: string[]): string | null { for (const r of rules) { if (r.rejected || !applies(r, kind, wanted, where)) continue; const shown = names.find((n) => normalise(n) === normalise(r.to)); if (shown) return shown; } return null;}
/** What to use instead of `wanted`: an approved heal, else the same name written differently, else a close name. */export function pick(rules: HealRule[], kind: HealKind, wanted: string, where: string, names: string[]): { used: string; how: HealHow } | null { const approved = approvedMatch(rules, kind, wanted, where, names); if (approved) return { used: approved, how: 'approved' }; const refused = new Set(rules.filter((r) => r.rejected && applies(r, kind, wanted, where)).map((r) => normalise(r.to))); const ok = (n: string | null) => (n && !refused.has(normalise(n)) ? n : null); const same = ok(normalisedMatch(wanted, names)); if (same) return { used: same, how: 'normalised' }; const close = ok(closeMatch(wanted, names)); return close ? { used: close, how: 'close' } : null;}
/** The approved heals of the run (FPT_HEALS): a JSON array; anything malformed is ignored, never an error. */export function parseHeals(raw: string | undefined): HealRule[] { if (!raw) return []; try { const list = JSON.parse(raw); return Array.isArray(list) ? list.filter((r): r is HealRule => !!r && ['field', 'button', 'menu'].includes(r.kind) && typeof r.wanted === 'string' && typeof r.to === 'string') : []; } catch { return []; }}
const unique = (xs: string[]) => Array.from(new Set(xs));123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113import { fusionEnv } from './ui';/** Fusion REST, used ONLY to check what a UI step did (precisely, without screen scraping) and to clean up test data.* The step under test always runs through the Fusion screens. Credentials come from the environment, never from code.* Node's own fetch is used on purpose, not Playwright's request context: Playwright traces record request headers,* and the Basic authorization header carries the password.*/const API = '/fscmRestApi/resources/11.13.18.05';export interface Invoice {InvoiceId: number; InvoiceNumber: string; InvoiceAmount: number; ValidationStatus: string; CanceledFlag: boolean;ActiveHoldFlag?: boolean; BusinessUnit: string; Supplier: string; [k: string]: unknown;}export interface InvoiceHold { HoldId: number; HoldName: string; HoldReason?: string; ReleaseName?: string | null; [k: string]: unknown }const q = (s: string) => s.replace(/'/g, "''");/** What a step expects of an invoice in Fusion (business action expect_invoice). */export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean }/** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled');/** Every way the invoice differs from what is expected, in words (empty: as expected). `amountAtLeast` is for the* invoice total when the pod adds tax on top of the lines: the total is then the amount plus that tax. */export function invoiceProblems(number: string, inv: Invoice | null, want: InvoiceExpectation): string[] {if (!inv) return [`invoice ${number} is not in Fusion`];const out: string[] = [];const amount = Number(inv.InvoiceAmount);if (want.status && spelling(String(inv.ValidationStatus ?? '')) !== spelling(want.status)&& !(spelling(want.status) === 'canceled' && inv.CanceledFlag)) {out.push(`its status is "${inv.ValidationStatus ?? ''}", expected "${want.status}"`);}if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${inv.InvoiceAmount}, expected ${want.amount}`);if (want.amountAtLeast !== undefined && !(amount >= want.amountAtLeast - 0.005)) {out.push(`its amount is ${inv.InvoiceAmount}, expected at least ${want.amountAtLeast}`);}if (want.canceled !== undefined && !!inv.CanceledFlag !== want.canceled) out.push(want.canceled ? 'it is not canceled' : 'it is canceled');return out;}/** The holds still on the invoice: a released hold carries the name of its release. */export const activeHolds = (holds: InvoiceHold[]) => holds.filter((h) => !h.ReleaseName);export class FusionRest {private readonly baseUrl: string;constructor() {const { baseUrl, username, password } = fusionEnv();if (!baseUrl || !username || !password) throw new Error('FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD must be set for a Fusion run');this.baseUrl = baseUrl;}private async call(method: 'GET' | 'POST', path: string, body?: unknown, contentType?: string): Promise<{ status: number; text: string }> {const { username, password } = fusionEnv();const res = await fetch(`${this.baseUrl}${API}/${path}`, {method,headers: {Authorization: `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`,Accept: 'application/json',...(contentType ? { 'Content-Type': contentType } : {}),},body: body === undefined ? undefined : JSON.stringify(body),signal: AbortSignal.timeout(120_000),});return { status: res.status, text: await res.text() };}private async get<T>(resource: string, query: string): Promise<T[]> {const params = new URLSearchParams({ q: query, onlyData: 'true', limit: '100' });const r = await this.call('GET', `${resource}?${params}`);if (r.status !== 200) throw new Error(`GET ${resource} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`);return (JSON.parse(r.text).items || []) as T[];}/** Every invoice with this number for the supplier (more than one would mean a duplicate got through). */invoices(number: string, supplier: string): Promise<Invoice[]> {return this.get<Invoice>('invoices', `InvoiceNumber='${q(number)}';Supplier='${q(supplier)}'`);}async invoice(number: string, supplier: string): Promise<Invoice | null> {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<Invoice | null> {return (await this.get<Invoice>('invoices', `InvoiceNumber='${q(number)}'`))[0] || null;}holds(number: string): Promise<InvoiceHold[]> {return this.get<InvoiceHold>('invoiceHolds', `InvoiceNumber='${q(number)}'`);}/** Run an invoice action (validateInvoice, cancelInvoice, ...) the way Fusion's REST service offers it. */async invoiceAction(action: string, body: Record<string, unknown>): Promise<string> {const r = await this.call('POST', `invoices/action/${action}`, body, 'application/vnd.oracle.adf.action+json');if (r.status < 200 || r.status >= 300) throw new Error(`${action} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`);return r.text;}/** Clean-up: cancel the test invoice if it exists and is not cancelled yet. Returns what was done. */async cancelIfPresent(number: string, businessUnit: string, supplier: string): Promise<string> {// a step may have saved it with another of the pod's suppliers than the first (the one Fusion offered): by numberconst inv = await this.invoice(number, supplier) ?? await this.invoiceByNumber(number);if (!inv) return `${number}: not saved, nothing to clean up`;if (inv.CanceledFlag) return `${number}: already cancelled`;await this.invoiceAction('cancelInvoice', { InvoiceNumber: number, BusinessUnit: inv.BusinessUnit || businessUnit, Supplier: inv.Supplier || supplier });const after = await this.invoice(number, inv.Supplier || supplier);if (!after?.CanceledFlag) throw new Error(`${number}: cancelInvoice reported success but the invoice is not cancelled`);return `${number}: cancelled by clean-up`;}}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329import { fusionEnv } from './ui';/** Fusion REST, used ONLY to check what a UI step did (precisely, without screen scraping) and to clean up test data.* The step under test always runs through the Fusion screens. Credentials come from the environment, never from code.* Node's own fetch is used on purpose, not Playwright's request context: Playwright traces record request headers,* and the Basic authorization header carries the password.** Where the Authorization header comes from is a RestAuth: Basic with the test user's password, or (later) an OAuth* token source registered with useRestAuth(). A pod with assisted sign-in has no password and, until such a source* exists, no REST: FusionRest.available is false, REST checks are skipped with a note (the screen result stands) and* clean-up leaves its test records listed for a person.*/const API = '/fscmRestApi/resources/11.13.18.05';/** A source of the Authorization header for Fusion REST. */export interface RestAuth {readonly kind: 'basic' | 'oauth';header(): Promise<string>;}/** Basic authentication with the test user's name and password (read when needed, never kept in a string field). */export class BasicAuth implements RestAuth {readonly kind = 'basic' as const;async header(): Promise<string> {const { username, password } = fusionEnv();return `Basic ${Buffer.from(`${username}:${password}`).toString('base64')}`;}}let tokenSource: RestAuth | null = null;/** The seam for an OAuth client (a pod with assisted sign-in): a token source registered here is used for REST. */export function useRestAuth(source: RestAuth | null): void { tokenSource = source; }/** How this run reaches Fusion REST: a registered token source, else Basic with the test user's password, else none. */export function restAuth(): RestAuth | null {if (tokenSource) return tokenSource;const { username, password } = fusionEnv();return username && password ? new BasicAuth() : null;}/** Fusion REST cannot be called on this run (no password and no token source). */export class RestUnavailable extends Error {}/** The annotation a test gets for each REST check it skipped. */export const REST_SKIPPED = 'rest-skipped';export const NO_REST_WHY = 'not checked through Fusion REST: this pod uses assisted sign-in, so there is no password for REST; '+ 'the screen result stands';export interface Invoice {InvoiceId: number; InvoiceNumber: string; InvoiceAmount: number; ValidationStatus: string; CanceledFlag: boolean;ActiveHoldFlag?: boolean; BusinessUnit: string; Supplier: string; [k: string]: unknown;}export interface InvoiceHold { HoldId: number; HoldName: string; HoldReason?: string; ReleaseName?: string | null; [k: string]: unknown }const q = (s: string) => s.replace(/'/g, "''");/** What a step expects of an invoice in Fusion (business action expect_invoice). */export interface InvoiceExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean }/** A status as the page and REST both mean it: case, spacing and the British "Cancelled" do not matter. */const spelling = (s: string) => s.trim().toLowerCase().replace(/\s+/g, ' ').replace('cancelled', 'canceled');/** Every way the invoice differs from what is expected, in words (empty: as expected). `amountAtLeast` is for the* invoice total when the pod adds tax on top of the lines: the total is then the amount plus that tax. */export function invoiceProblems(number: string, inv: Invoice | null, want: InvoiceExpectation): string[] {if (!inv) return [`invoice ${number} is not in Fusion`];const out: string[] = [];const amount = Number(inv.InvoiceAmount);if (want.status && spelling(String(inv.ValidationStatus ?? '')) !== spelling(want.status)&& !(spelling(want.status) === 'canceled' && inv.CanceledFlag)) {out.push(`its status is "${inv.ValidationStatus ?? ''}", expected "${want.status}"`);}if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${inv.InvoiceAmount}, expected ${want.amount}`);if (want.amountAtLeast !== undefined && !(amount >= want.amountAtLeast - 0.005)) {out.push(`its amount is ${inv.InvoiceAmount}, expected at least ${want.amountAtLeast}`);}if (want.canceled !== undefined && !!inv.CanceledFlag !== want.canceled) out.push(want.canceled ? 'it is not canceled' : 'it is canceled');return out;}/** The holds still on the invoice: a released hold carries the name of its release. */export const activeHolds = (holds: InvoiceHold[]) => holds.filter((h) => !h.ReleaseName);/** Purchasing and General Ledger. Every test document carries the test's own FPT- tag where Fusion keeps a free text* (a requisition's and an order's Description, a journal batch's name): the number Fusion gives a requisition or an* order is only known after the save, so the tag is what clean-up registers BEFORE the save and what REST finds the* document by. Attribute names are the documented ones of 11.13.18.05; where pods and releases differ, several are read.*/export interface Requisition { RequisitionHeaderId: number; Requisition: string; Description?: string; DocumentStatus?: string;DocumentStatusCode?: string; RequisitioningBU?: string; [k: string]: unknown }export interface PurchaseOrder { POHeaderId: number; OrderNumber: string; Description?: string; Status?: string; StatusCode?: string;ProcurementBU?: string; Supplier?: string; Total?: number; Ordered?: number; [k: string]: unknown }export interface JournalBatch { JeBatchId: number; BatchName: string; Status?: string; StatusMeaning?: string; [k: string]: unknown }/** What a step expects of a requisition, an order or a journal batch (expect_requisition, expect_purchase_order,* expect_journal). */export interface DocExpectation { status?: string; amount?: number; amountAtLeast?: number; canceled?: boolean; posted?: boolean }/** A requisition's status in words (DocumentStatus; the code when a pod returns only that). */export const requisitionStatus = (r: Requisition) => String(r.DocumentStatus || r.DocumentStatusCode || '').trim();/** An order's status in words ("Open", "Pending Approval", "Incomplete", "Canceled", ...). */export const orderStatus = (o: PurchaseOrder) => String(o.Status || o.StatusCode || '').trim();/** An order's amount: its total, or the ordered amount on pods that return only that. NaN when it carries neither. */export const orderAmount = (o: PurchaseOrder) => Number(['Total', 'Ordered', 'TotalAmount', 'Amount'].map((k) => o[k]).find((v) => v !== undefined && v !== null && v !== '') ?? NaN);/** A journal batch's status in words: StatusMeaning, else Fusion's one-letter code (P posted, U unposted, S selected for* posting, I posting in process; any other code is a posting error). */export function journalStatus(b: JournalBatch): string {const said = String(b.StatusMeaning || '').trim();if (said) return said;const code = String(b.Status || '').trim();return ({ P: 'Posted', U: 'Unposted', S: 'Selected for posting', I: 'Posting in process' } as Record<string, string>)[code.toUpperCase()] ?? code;}export const journalPosted = (b: JournalBatch) => String(b.Status || '').trim().toUpperCase() === 'P' || spelling(journalStatus(b)) === 'posted';/** A requisition or order that is out of the way: cancelled, or (a requisition) withdrawn. */const canceledStatus = (s: string) => /^(canceled|withdrawn)$/.test(spelling(s));/** Every way a document differs from what is expected, in words (empty: as expected). `what` names it ("order 1234"). */function docProblems(what: string, status: string, amount: number, posted: boolean | undefined, want: DocExpectation): string[] {const out: string[] = [];const shown = (n: number) => (Number.isNaN(n) ? 'not given by Fusion' : String(n));if (want.status && spelling(status) !== spelling(want.status)) out.push(`its status is "${status}", expected "${want.status}"`);if (want.amount !== undefined && !(Math.abs(amount - want.amount) < 0.005)) out.push(`its amount is ${shown(amount)}, expected ${want.amount}`);if (want.amountAtLeast !== undefined && !(amount >= want.amountAtLeast - 0.005)) {out.push(`its amount is ${shown(amount)}, expected at least ${want.amountAtLeast}`);}if (want.canceled !== undefined && canceledStatus(status) !== want.canceled) out.push(want.canceled ? 'it is not canceled' : 'it is canceled');if (want.posted !== undefined && posted !== want.posted) out.push(want.posted ? `it is not posted (${status || 'no status'})` : 'it is posted');return out.map((p) => `${what}: ${p}`);}export function requisitionProblems(number: string, r: Requisition | null, want: DocExpectation): string[] {if (!r) return [`requisition ${number} is not in Fusion`];return docProblems(`requisition ${number}`, requisitionStatus(r), NaN, undefined, want);}export function purchaseOrderProblems(number: string, o: PurchaseOrder | null, want: DocExpectation): string[] {if (!o) return [`purchase order ${number} is not in Fusion`];return docProblems(`purchase order ${number}`, orderStatus(o), orderAmount(o), undefined, want);}export function journalProblems(name: string, b: JournalBatch | null, want: DocExpectation): string[] {if (!b) return [`journal batch ${name} is not in Fusion`];return docProblems(`journal batch ${name}`, journalStatus(b), NaN, journalPosted(b), want);}/** Clean-up that REST cannot do (a submitted requisition: Fusion's REST service offers no cancel for it): the fixture* does it on the screens instead, then asks REST again. */export class NeedsScreen extends Error {}export class FusionRest {private readonly baseUrl: string;private readonly auth: RestAuth | null;constructor(auth: RestAuth | null = restAuth()) {const { baseUrl } = fusionEnv();if (!baseUrl) throw new Error('FUSION_BASE_URL must be set for a Fusion run');if (!auth && !process.env.FPT_SIGN_IN_MODE) throw new Error('FUSION_BASE_URL, FUSION_USERNAME and FUSION_PASSWORD must be set for a Fusion run');this.baseUrl = baseUrl;this.auth = auth;}/** REST can be called on this run (false on a pod with assisted sign-in until an OAuth token source exists). */get available(): boolean { return !!this.auth; }private async call(method: 'GET' | 'POST' | 'DELETE', path: string, body?: unknown, contentType?: string): Promise<{ status: number; text: string }> {if (!this.auth) throw new RestUnavailable(NO_REST_WHY);const res = await fetch(`${this.baseUrl}${API}/${path}`, {method,headers: {Authorization: await this.auth.header(),Accept: 'application/json',...(contentType ? { 'Content-Type': contentType } : {}),},body: body === undefined ? undefined : JSON.stringify(body),signal: AbortSignal.timeout(120_000),});return { status: res.status, text: await res.text() };}private async get<T>(resource: string, query: string): Promise<T[]> {const params = new URLSearchParams({ q: query, onlyData: 'true', limit: '100' });const r = await this.call('GET', `${resource}?${params}`);if (r.status !== 200) throw new Error(`GET ${resource} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`);return (JSON.parse(r.text).items || []) as T[];}/** Every invoice with this number for the supplier (more than one would mean a duplicate got through). */invoices(number: string, supplier: string): Promise<Invoice[]> {return this.get<Invoice>('invoices', `InvoiceNumber='${q(number)}';Supplier='${q(supplier)}'`);}async invoice(number: string, supplier: string): Promise<Invoice | null> {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<Invoice | null> {return (await this.get<Invoice>('invoices', `InvoiceNumber='${q(number)}'`))[0] || null;}holds(number: string): Promise<InvoiceHold[]> {return this.get<InvoiceHold>('invoiceHolds', `InvoiceNumber='${q(number)}'`);}/** Run an invoice action (validateInvoice, cancelInvoice, ...) the way Fusion's REST service offers it. */async invoiceAction(action: string, body: Record<string, unknown>): Promise<string> {const r = await this.call('POST', `invoices/action/${action}`, body, 'application/vnd.oracle.adf.action+json');if (r.status < 200 || r.status >= 300) throw new Error(`${action} failed: HTTP ${r.status} ${r.text.slice(0, 300)}`);return r.text;}/** Clean-up: cancel the test invoice if it exists and is not cancelled yet. Returns what was done. */async cancelIfPresent(number: string, businessUnit: string, supplier: string): Promise<string> {// a step may have saved it with another of the pod's suppliers than the first (the one Fusion offered): by numberconst inv = await this.invoice(number, supplier) ?? await this.invoiceByNumber(number);if (!inv) return `${number}: not saved, nothing to clean up`;if (inv.CanceledFlag) return `${number}: already cancelled`;await this.invoiceAction('cancelInvoice', { InvoiceNumber: number, BusinessUnit: inv.BusinessUnit || businessUnit, Supplier: inv.Supplier || supplier });const after = await this.invoice(number, inv.Supplier || supplier);if (!after?.CanceledFlag) throw new Error(`${number}: cancelInvoice reported success but the invoice is not cancelled`);return `${number}: cancelled by clean-up`;}/** The first item of a resource matching `query`, or null. A query the resource refuses (an attribute this pod does not* have: HTTP 400) answers null, so the caller's next way of finding it is tried. */private async first<T>(resource: string, query: string): Promise<T | null> {try { return (await this.get<T>(resource, query))[0] || null; } catch (e) {if (/HTTP 400\b/.test(String((e as Error).message))) return null;throw e;}}/** The requisition with this number (Requisition), else the one whose Description starts with the test's tag. */async requisition(numberOrTag: string): Promise<Requisition | null> {return await this.first<Requisition>('purchaseRequisitions', `Requisition='${q(numberOrTag)}'`)?? await this.first<Requisition>('purchaseRequisitions', `Description LIKE '${q(numberOrTag)}%'`);}/** The order with this number, else the one whose Description starts with the test's tag. Orders not submitted yet* (Incomplete) are drafts: on pods that keep them out of purchaseOrders, draftPurchaseOrders has them. */async purchaseOrder(numberOrTag: string): Promise<(PurchaseOrder & { draft?: boolean }) | null> {for (const resource of ['purchaseOrders', 'draftPurchaseOrders']) {const o = await this.first<PurchaseOrder>(resource, `OrderNumber='${q(numberOrTag)}'`)?? await this.first<PurchaseOrder>(resource, `Description LIKE '${q(numberOrTag)}%'`);if (o) return resource === 'draftPurchaseOrders' ? { ...o, draft: true } : o;}return null;}async journalBatch(name: string): Promise<JournalBatch | null> {return this.first<JournalBatch>('journalBatches', `BatchName='${q(name)}'`);}/** The batches whose name holds the test's batch name: the batch itself and the reversal Fusion makes of it (Fusion* names a reversal after the batch it reverses). Null when this pod refuses the LIKE query. */async journalBatchesNamed(name: string): Promise<JournalBatch[] | null> {try { return await this.get<JournalBatch>('journalBatches', `BatchName LIKE '%${q(name)}%'`); } catch (e) {if (/HTTP 400\b/.test(String((e as Error).message))) return null;throw e;}}private async remove(path: string, what: string): Promise<void> {const r = await this.call('DELETE', path);if (r.status < 200 || r.status >= 300) throw new Error(`${what}: Fusion refused the delete (HTTP ${r.status} ${r.text.slice(0, 200)})`);}/** Clean-up of a test requisition (found by its tag): an Incomplete one is deleted; a canceled, withdrawn or rejected* one needs nothing. A submitted one has no cancel over REST: NeedsScreen, and the fixture cancels it on the screens. */async cleanRequisition(tag: string): Promise<string> {const r = await this.requisition(tag);if (!r) return `${tag}: no requisition saved, nothing to clean up`;const status = requisitionStatus(r);if (/^(canceled|withdrawn|rejected)$/.test(spelling(status))) return `requisition ${r.Requisition}: already ${status.toLowerCase()}`;if (spelling(status) === 'incomplete') {await this.remove(`purchaseRequisitions/${r.RequisitionHeaderId}`, `requisition ${r.Requisition}`);if (await this.requisition(tag)) throw new Error(`requisition ${r.Requisition}: Fusion accepted the delete but it is still there`);return `requisition ${r.Requisition}: deleted by clean-up (never submitted)`;}throw new NeedsScreen(`requisition ${r.Requisition} is ${status}: it is cancelled on Manage Requisitions`);}/** Clean-up of a test order (found by its tag): an Incomplete draft is deleted, an open one cancelled with Fusion's* cancel action; canceled and closed ones need nothing. One pending approval cannot be cancelled until it is* withdrawn, and a cancel action this pod does not offer is done on the screens: NeedsScreen for both. */async cleanPurchaseOrder(tag: string): Promise<string> {const o = await this.purchaseOrder(tag);if (!o) return `${tag}: no purchase order saved, nothing to clean up`;const status = orderStatus(o);const s = spelling(status);if (s === 'canceled' || s.includes('closed')) return `purchase order ${o.OrderNumber}: already ${status.toLowerCase()}`;if (s === 'incomplete') {await this.remove(`draftPurchaseOrders/${o.POHeaderId}`, `purchase order ${o.OrderNumber}`);return `purchase order ${o.OrderNumber}: deleted by clean-up (never submitted)`;}if (s.includes('pending')) throw new NeedsScreen(`purchase order ${o.OrderNumber} is ${status}: it is withdrawn and deleted on the screens`);const r = await this.call('POST', `purchaseOrders/${o.POHeaderId}/action/cancel`, {}, 'application/vnd.oracle.adf.action+json');if (r.status < 200 || r.status >= 300) throw new NeedsScreen(`purchase order ${o.OrderNumber}: the cancel action answered HTTP ${r.status}`);const after = await this.purchaseOrder(o.OrderNumber);if (after && spelling(orderStatus(after)) !== 'canceled') {throw new Error(`purchase order ${o.OrderNumber}: the cancel action answered but its status is ${orderStatus(after)}`);}return `purchase order ${o.OrderNumber}: cancelled by clean-up`;}/** Clean-up of a test journal batch and of the reversal Fusion made of it: an unposted one is deleted. A posted one* stays (Fusion never deletes a posted journal): the test's journals debit and credit the same amount on the same* account, so a posted one leaves every balance as it was. */async cleanJournal(name: string): Promise<string> {const batches = (await this.journalBatchesNamed(name)) ?? [await this.journalBatch(name)].filter((b): b is JournalBatch => !!b);if (!batches.length) return `${name}: no journal saved, nothing to clean up`;const done: string[] = [];for (const b of batches) {if (journalPosted(b)) { done.push(`${b.BatchName}: posted (debit and credit on one account, balances unchanged)`); continue; }await this.remove(`journalBatches/${b.JeBatchId}`, `journal batch ${b.BatchName}`);done.push(`${b.BatchName}: deleted by clean-up (unposted)`);}return done.join('; ');}}
123456789101112131415161718192021222324252627282930313233343536373839404142// One sign-in for the whole run (playwright.fusion.config.ts globalSetup / globalTeardown): the test user signs in once,// and every test starts from that session instead of signing in again (20-60 s each). The session file holds Fusion's// session cookies (never the password), sits in the run's own folder and is deleted when the run ends. When the// sign-in here fails, an empty session is written and each test signs in by itself, as before.import * as fs from 'fs';import * as path from 'path';import { chromium } from '@playwright/test';import { FusionUi } from './ui';const EMPTY = { cookies: [], origins: [] };export function sessionFile(): string {const f = process.env.FPT_FUSION_SESSION_FILE;if (!f) throw new Error('FPT_FUSION_SESSION_FILE is not set (playwright.fusion.config.ts sets it)');return f;}export async function setup(): Promise<void> {const file = sessionFile();fs.mkdirSync(path.dirname(file), { recursive: true });fs.writeFileSync(file, JSON.stringify(EMPTY), { mode: 0o600 });if (!process.env.FUSION_BASE_URL || !process.env.FUSION_USERNAME || !process.env.FUSION_PASSWORD) return;const browser = await chromium.launch({ headless: true });try {const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });const page = await context.newPage();page.setDefaultTimeout(60_000);page.setDefaultNavigationTimeout(120_000);await new FusionUi(page).signIn();await context.storageState({ path: file });fs.chmodSync(file, 0o600);console.log('[session] signed in once for this run; every test reuses the session');} catch (e) {console.log(`[session] one sign-in for the run failed, so each test signs in by itself: ${String((e as Error).message || e).split('\n')[0]}`);} finally {await browser.close().catch(() => {});}}export async function teardown(): Promise<void> {try { fs.unlinkSync(sessionFile()); } catch { /* already gone */ }}12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273// One sign-in for the whole run (playwright.fusion.config.ts globalSetup / globalTeardown): the test user signs in once,// and every test starts from that session instead of signing in again (20-60 s each). The session file holds Fusion's// session cookies (never the password), sits in the run's own folder and is deleted when the run ends. When the// sign-in here fails, an empty session is written and each test signs in by itself, as before.//// Assisted sign-in (FPT_SIGN_IN_MODE=assisted: the pod signs in through the company's identity provider, with MFA): a// person signed in on Astra's run page, and FPT_FUSION_STORAGE_STATE points to that session (written by Astra or the// runner for this pass only). It is checked once here; when the pod no longer accepts it, every test of the pass is// skipped as "sign-in expired" (fixtures.ts) and Astra asks for a new sign-in instead of failing them all.import * as fs from 'fs';import * as path from 'path';import { chromium } from '@playwright/test';import { assistedSignIn, clearSignInExpired, FusionUi, markSignInExpired } from './ui';const EMPTY = { cookies: [], origins: [] };export function sessionFile(): string {const f = process.env.FPT_FUSION_SESSION_FILE;if (!f) throw new Error('FPT_FUSION_SESSION_FILE is not set (playwright.fusion.config.ts sets it)');return f;}/** Assisted sign-in: the session a person signed in becomes this run's session, if the pod still accepts it. */async function provided(file: string): Promise<void> {const given = process.env.FPT_FUSION_STORAGE_STATE;if (!given || !fs.existsSync(given)) {markSignInExpired('Sign-in expired: no signed-in session was given for this pod (assisted sign-in); Astra asks a person to sign in.');return;}fs.writeFileSync(file, fs.readFileSync(given), { mode: 0o600 });if (!process.env.FUSION_BASE_URL) return;const browser = await chromium.launch({ headless: true });try {const context = await browser.newContext({ viewport: { width: 1440, height: 900 }, storageState: file });const page = await context.newPage();page.setDefaultNavigationTimeout(120_000);if (await new FusionUi(page).isSignedIn()) console.log('[session] the session a person signed in is accepted; every test reuses it');else markSignInExpired('Sign-in expired: the pod no longer accepts the session a person signed in (assisted sign-in); Astra asks for a new sign-in.');} catch (e) {console.log(`[session] the signed-in session could not be checked, the tests try it: ${String((e as Error).message || e).split('\n')[0]}`);} finally {await browser.close().catch(() => {});}}export async function setup(): Promise<void> {const file = sessionFile();fs.mkdirSync(path.dirname(file), { recursive: true });fs.writeFileSync(file, JSON.stringify(EMPTY), { mode: 0o600 });clearSignInExpired();if (assistedSignIn()) return provided(file);if (!process.env.FUSION_BASE_URL || !process.env.FUSION_USERNAME || !process.env.FUSION_PASSWORD) return;const browser = await chromium.launch({ headless: true });try {const context = await browser.newContext({ viewport: { width: 1440, height: 900 } });const page = await context.newPage();page.setDefaultTimeout(60_000);page.setDefaultNavigationTimeout(120_000);await new FusionUi(page).signIn();await context.storageState({ path: file });fs.chmodSync(file, 0o600);console.log('[session] signed in once for this run; every test reuses the session');} catch (e) {console.log(`[session] one sign-in for the run failed, so each test signs in by itself: ${String((e as Error).message || e).split('\n')[0]}`);} finally {await browser.close().catch(() => {});}}export async function teardown(): Promise<void> {try { fs.unlinkSync(sessionFile()); } catch { /* already gone */ }clearSignInExpired();}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295import * as fs from 'fs';import * as path from 'path';import YAML from 'yaml';import { expect, test } from './fixtures';import { activeHolds, invoiceProblems, type FusionRest, type InvoiceExpectation } from './rest';import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui';/** Step runner: executes a scenario written as plain steps in tests/cases/<ID>.yaml (runner: steps), with no* hand-written code. Each step names one proven Fusion action; the model (or a consultant) writes the steps, Playwright* runs them the same way every time. Unknown actions fail the step with a clear message, never guess.** Step fields: action, field, value, expected (shown in the report and the live view).* Values may use {{pod.<area>.<key>}} (the pod's test data, e.g. {{pod.ap.supplier}}), {{today}}, {{unique:TAG}},* {{tv.<test_values key>}} and {{saved.<name>}} (a value remembered by an earlier `remember` step).** Business actions (Payables first) do a whole piece of business the proven way, so a scenario made of them does not* break on every Fusion quirk: create_invoice, validate_invoice, find_invoice, cancel_invoice, expect_invoice,* expect_hold, expect_no_holds. Their extra fields: lines, status, amount, amount_at_least, canceled. A canary scenario* per area (tests/cases/CANARY-<AREA>.yaml) runs each of them once before a run, to prove they still work on the pod.*/export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[];lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean }export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record<string, unknown>;canary?: boolean } // a canary (tests/cases/CANARY-<AREA>.yaml): create_invoice tries the pod's data sets in turnconst CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases');/*** The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds* that id (the co-worker's staging folder for drafts), else from the script library tests/cases/.*/export function stepCaseFile(id: string, dir?: string): string {for (const d of [dir, process.env.FPT_STEPS_DIR]) {if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`);}return path.join(CASES_DIR, `${id}.yaml`);}export function loadStepCase(id: string, dir?: string): StepCase {const f = stepCaseFile(id, dir);const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase;if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`);return c;}type Ctx = { ui: FusionUi; c: StepCase; saved: Record<string, string>; uniques: Record<string, string>; track: (n: string) => string;chosen: Record<string, string>; // the pod value Fusion accepted, per "area.key", used again for the rest of the testrest: FusionRest }; // Fusion REST, for the business actions that check what the screens didfunction fill(raw: unknown, ctx: Ctx): string {return String(raw ?? '').replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_m, key: string) => {const pod = /^pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)$/i.exec(key);if (pod) return ctx.chosen[`${pod[1]}.${pod[2]}`.toLowerCase()] ?? podValue(pod[1], pod[2]); // the pod's own test dataif (key === 'today') return fusionDate();if (key.startsWith('unique:')) { const t = key.slice(7); return (ctx.uniques[t] ??= testNumber(t)); }if (key.startsWith('tv.')) return String(ctx.c.test_values?.[key.slice(3)] ?? '');if (key.startsWith('saved.')) return ctx.saved[key.slice(6)] ?? '';throw new Error(`unknown placeholder {{${key}}}`);});}/** Enter a value. A value that is exactly one pod test data placeholder ({{pod.ap.business_unit}}) is tried with each* value the pod has for it, in order, until Fusion accepts one (a business unit this user may use, a source that* exists on this pod): the first that works is kept for the rest of the test and remembered for the next run. */async function putValue(s: Step, ctx: Ctx, put: (v: string) => Promise<void>): Promise<void> {const ref = /^\s*\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}\s*$/i.exec(String(s.value ?? ''));const key = ref ? `${ref[1]}.${ref[2]}`.toLowerCase() : '';if (!ref || ctx.chosen[key]) return put(fill(s.value, ctx));const tried: string[] = [];for (const v of podCandidates(ref[1], ref[2])) {try {await put(v);ctx.chosen[key] = v;used(ref[1], ref[2], v, true);return;} catch (e) {if (!(e instanceof ValueRefused)) throw e;used(ref[1], ref[2], v, false);tried.push(v);}}throw new Error(`Fusion accepted none of the ${tried.length} value(s) this pod has for ${ref[2].replace(/_/g, ' ')} in ` +`"${s.field}" (${tried.join(', ')}): this test user is not offered any of them; set one it may use on the Test environments page`);}/** The invoice a business action works on: the number create_invoice (or a `remember` step) stored under the step's* `name`, "invoice_number" when it names none. */function invoiceNumber(s: Step, ctx: Ctx): string {const name = s.name || 'invoice_number';const n = ctx.saved[name];if (!n) throw new Error(`${s.action} needs an invoice: no invoice number is remembered as "${name}" (create_invoice or remember it first)`);return n;}/** A number a step gives (an amount), filled in from its placeholders. */function amountOf(raw: string | number, ctx: Ctx, what: string): number {const v = Number(fill(raw, ctx).replace(/,/g, ''));if (!Number.isFinite(v)) throw new Error(`${what} must be a number, got "${fill(raw, ctx)}"`);return v;}/** Ask Fusion (REST) until `problems` comes back empty: REST can lag a few seconds behind what the screen saved. Fails* with the last problems in words. */async function untilRight(problems: () => Promise<string[]>, what: string, timeoutMs = 60_000) {const end = Date.now() + timeoutMs;for (;;) {const p = await problems();if (!p.length) return;if (Date.now() > end) throw new Error(`${what}: ${p.join('; ')}`);await new Promise((r) => setTimeout(r, 3000));}}/** The pod values to try for an AP test data key: the one Fusion already took in this test, else the pod's candidates. */const apChoices = (ctx: Ctx, key: string) => ctx.chosen[`ap.${key}`] ? [ctx.chosen[`ap.${key}`]] : podCandidates('ap', key);/** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } };const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200);/** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an* invoice. A shared pod's sampled data can be whoever used it last (a supplier without a default site, an account of* another ledger); the set that works is recorded as accepted (FPT_TESTDATA_USED), so the co-worker learns it and the* run's other scenarios and the next run try it first. When no set validates, the first set that saved is kept, so* the canary's own validate_invoice step shows what is broken; when none saves, create_invoice fails with each reason. */async function createWithDataSets(ctx: Ctx, h: { amount: string; lines: string[]; name: string }) {const sets = apDataSets();const why: string[] = [];let saved: ApDataSet | null = null;let last = false; // the invoice the last set saved is the one on the pageconst create = async (set: ApDataSet, k: number) => {const number = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`));const got = await ctx.ui.createInvoice({ businessUnit: set.businessUnit, supplier: set.supplier, site: set.site, number,amount: h.amount, lines: h.lines, account: set.account });ctx.saved[h.name] = number;return got;};for (const [k, set] of sets.entries()) {const label = `${set.businessUnit} / ${set.supplier}`;last = false;let got;try { got = await create(set, k); } catch (e) { why.push(`${label}: ${errorText(e)}`); continue; }saved ??= set;last = true;try {await ctx.ui.validateInvoice();await ctx.ui.expectStatus('Validated', ctx.saved[h.name]);} catch (e) { why.push(`${label}: saved but did not validate (${errorText(e)})`); continue; }for (const [key, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site], ['account', got.account]]) {if (v) { used('AP', key, v, true); ctx.chosen[`ap.${key}`] = v; }}if (k) console.log(`[canary] Payables data set ${k + 1} of ${sets.length} works (${label}); tried: ${why.join(' | ')}`);return;}if (!saved) throw new Error(`create_invoice failed with each of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`);console.log(`[canary] no Payables data set validates: ${why.join(' | ')}`);if (!last) await create(saved, sets.length);}/** The proven actions. Optional ones call a FusionUi method only if that building block exists. */const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {sign_in: async (_s, { ui }) => ui.signIn(),open_task: async (s, ctx) => {await ctx.ui.openPath(fill(s.value, ctx)); // "Group > Page > Task", or "Group > Action" for a quick action},enter: async (s, ctx) => {if (!s.field) throw new Error('enter needs a field');if (s.field === 'Number') ctx.track(fill(s.value, ctx)); // a saved test invoice is cancelled after the test, pass or failawait putValue(s, ctx, (v) => ctx.ui.put(s.field!, v));},expect_filled: async (s, ctx) => { for (const f of s.fields ?? (s.field ? [s.field] : [])) await ctx.ui.expectFilled(f); },expect_value: async (s, ctx) => {if (!s.field) throw new Error('expect_value needs a field');await expect.poll(() => ctx.ui.value(s.field!), { message: `${s.field} should be "${fill(s.value, ctx)}"`, timeout: 30_000 }).toBe(fill(s.value, ctx));},remember: async (s, ctx) => { if (!s.field || !s.name) throw new Error('remember needs field and name'); ctx.saved[s.name] = await ctx.ui.value(s.field); },click: async (s, ctx) => {const name = fill(s.value, ctx);await ctx.ui.pressEnabled(ctx.ui.page.getByRole('button', { name, exact: true }).filter({ visible: true }).first(), name);await ctx.ui.settle();},confirm_if_asked: async (_s, ctx) => {const yes = ctx.ui.page.getByRole('button', { name: /^(Yes|OK)$/ });if (await yes.count()) { await yes.first().click(); await ctx.ui.settle(); }},// any screen: tables, menus, messages, searches and statuses (the AI writes these for every business area)add_row: async (s, ctx) => { if (!s.field) throw new Error('add_row needs the table section as field'); await ctx.ui.addRow(s.field); },enter_in_row: async (s, ctx) => {if (!s.field) throw new Error('enter_in_row needs a field');await putValue(s, ctx, (v) => ctx.ui.putInRow(s.field!, v));},menu_action: async (s, ctx) => {if (!s.field) throw new Error('menu_action needs the menu as field');await ctx.ui.menuAction(s.field, fill(s.value, ctx));},expect_no_error: async (_s, ctx) => ctx.ui.expectNoError(),expect_message: async (s, ctx) => ctx.ui.expectMessage(fill(s.value, ctx)),expect_results: async (_s, ctx) => ctx.ui.expectResults(),cancel_without_saving: async (_s, ctx) => {await ctx.ui.page.getByRole('button', { name: 'Cancel', exact: true }).first().click();await ctx.ui.settle(2000);await ACTIONS.confirm_if_asked({ action: 'confirm_if_asked' }, ctx);},// Payables business actions/** Create and save a Payables invoice on its own screen (no open_task before it). value = the invoice amount (default* {{tv.amount}}); lines = the line amounts (default one line of the whole amount; the amount defaults to their sum);* name = what to remember the new FPT- number as (default invoice_number, used as {{saved.invoice_number}}). The* number is registered for clean-up before the save, so the invoice is cancelled after the test, pass or fail. */create_invoice: async (s, ctx) => {const lines = (s.lines ?? []).map((l) => fill(l, ctx));const amount = s.value !== undefined && s.value !== '' ? fill(s.value, ctx): lines.length ? lines.reduce((sum, l, i) => sum + amountOf(l, ctx, `line ${i + 1}`), 0).toFixed(2): ctx.c.test_values?.amount !== undefined ? fill('{{tv.amount}}', ctx) : '';if (!amount) throw new Error('create_invoice needs an amount: value, lines, or the test value "amount"');if (ctx.c.canary) return createWithDataSets(ctx, { amount, lines, name: s.name || 'invoice_number' });const number = ctx.track(testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, '')));const got = await ctx.ui.createInvoice({ businessUnit: apChoices(ctx, 'business_unit'), supplier: apChoices(ctx, 'supplier'), number, amount,lines, account: ctx.chosen['ap.account'] ?? podValue('ap', 'account'), site: apSites(ctx) });ctx.chosen['ap.business_unit'] = got.businessUnit;ctx.chosen['ap.supplier'] = got.supplier;ctx.saved[s.name || 'invoice_number'] = number;},/** Check the invoice in Fusion (REST) by its number. status = the status it must have (Validated, Needs revalidation,* Canceled ...: matched without regard to case); amount = its exact amount; amount_at_least = at least this amount* (the pod may add tax on top); canceled = true or false. With none of them, it checks that the invoice exists. */expect_invoice: async (s, ctx) => {const number = invoiceNumber(s, ctx);const want: InvoiceExpectation = {status: s.status ? fill(s.status, ctx) : undefined,amount: s.amount !== undefined ? amountOf(s.amount, ctx, 'amount') : undefined,amountAtLeast: s.amount_at_least !== undefined ? amountOf(s.amount_at_least, ctx, 'amount_at_least') : undefined,canceled: s.canceled,};await untilRight(async () => invoiceProblems(number, await ctx.rest.invoiceByNumber(number), want), `invoice ${number} in Fusion`);},/** The invoice carries a hold that is not released: value = the hold's name as Fusion lists it (any case). */expect_hold: async (s, ctx) => {const number = invoiceNumber(s, ctx);const name = fill(s.value, ctx).trim().toLowerCase();if (!name) throw new Error('expect_hold needs the hold name as value');await untilRight(async () => {const holds = activeHolds(await ctx.rest.holds(number));return holds.some((h) => String(h.HoldName || '').trim().toLowerCase() === name) ? []: [`no "${fill(s.value, ctx)}" hold (holds: ${holds.map((h) => h.HoldName).join(', ') || 'none'})`];}, `invoice ${number}`);},/** The invoice carries no hold that is not released (the holds list: 26D no longer returns ActiveHoldFlag). */expect_no_holds: async (s, ctx) => {const number = invoiceNumber(s, ctx);await untilRight(async () => {const holds = activeHolds(await ctx.rest.holds(number));return holds.length ? [`it is on hold: ${holds.map((h) => h.HoldName).join(', ')}`] : [];}, `invoice ${number}`, 20_000);},};/** Building blocks that live on FusionUi (added module by module): action name -> method name and argument fields. */const UI_BLOCKS: Record<string, { method: string; args: (s: Step, ctx: Ctx) => unknown[] }> = {add_line: { method: 'addLine', args: (s, ctx) => [Number((s as { line?: number }).line ?? 1),{ amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] },save: { method: 'save', args: () => [] },invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] },validate_invoice: { method: 'validateInvoice', args: () => [] },/** Find the invoice remembered as `name` (default invoice_number) on Manage Invoices: exactly it must be listed. */find_invoice: { method: 'findInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] },/** Invoice Actions > Cancel Invoice on the invoice remembered as `name`, confirmed: it must then show Canceled. */cancel_invoice: { method: 'cancelInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] },expect_status: { method: 'expectStatusText', args: (s, ctx) => [fill(s.value, ctx)] },};export const supportedActions = () => [...Object.keys(ACTIONS), ...Object.keys(UI_BLOCKS)];async function runStep(s: Step, ctx: Ctx) {const direct = ACTIONS[s.action];if (direct) return direct(s, ctx);const block = UI_BLOCKS[s.action];const fn = block && (ctx.ui as unknown as Record<string, unknown>)[block.method];if (typeof fn !== 'function') throw new Error(`step action "${s.action}" is not supported yet (known: ${supportedActions().join(', ')})`);await (fn as (...a: unknown[]) => Promise<void>).apply(ctx.ui, block.args(s, ctx));}/** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/<ID>.spec.ts, or* from a staged draft's entry (opts.dir = the staging folder holding its YAML). */export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {const c = loadStepCase(id, opts.dir);test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices }) => {const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, chosen: {}, rest: apInvoices.rest };for (const [i, s] of c.steps.entries()) {const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`;await test.step(s.expected ? `${label} (expect: ${s.expected})` : label, () => runStep(s, ctx));}});}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511import * as fs from 'fs';import * as path from 'path';import YAML from 'yaml';import { expect, test, type DocKind, type FusionDocs } from './fixtures';import { activeHolds, invoiceProblems, journalPosted, journalProblems, journalStatus, NO_REST_WHY, purchaseOrderProblems, requisitionProblems,REST_SKIPPED, type DocExpectation, type FusionRest, type InvoiceExpectation } from './rest';import { apDataSets, fusionDate, podCandidates, podValue, testNumber, used, ValueRefused, type ApDataSet, type FusionUi } from './ui';/** Step runner: executes a scenario written as plain steps in tests/cases/<ID>.yaml (runner: steps), with no* hand-written code. Each step names one proven Fusion action; the model (or a consultant) writes the steps, Playwright* runs them the same way every time. Unknown actions fail the step with a clear message, never guess.** Step fields: action, field, value, expected (shown in the report and the live view).* Values may use {{pod.<area>.<key>}} (the pod's test data, e.g. {{pod.ap.supplier}}), {{today}}, {{unique:TAG}},* {{tv.<test_values key>}} and {{saved.<name>}} (a value remembered by an earlier `remember` step).** Business actions (Payables first) do a whole piece of business the proven way, so a scenario made of them does not* break on every Fusion quirk: create_invoice, validate_invoice, find_invoice, cancel_invoice, expect_invoice,* expect_hold, expect_no_holds. Their extra fields: lines, status, amount, amount_at_least, canceled. A canary scenario* per area (tests/cases/CANARY-<AREA>.yaml) runs each of them once before a run, to prove they still work on the pod.* Purchasing: create_requisition, expect_requisition, cancel_requisition, create_purchase_order, submit_purchase_order,* find_purchase_order, expect_purchase_order, cancel_purchase_order (extra fields quantity, price). General Ledger:* create_journal, post_journal, find_journal, expect_journal, reverse_journal (extra field posted).*/export interface Step { n?: number; action: string; field?: string; value?: string | number; expected?: string; name?: string; fields?: string[];lines?: (string | number)[]; status?: string; amount?: string | number; amount_at_least?: string | number; canceled?: boolean;quantity?: string | number; price?: string | number; posted?: boolean }export interface StepCase { id: string; title: string; runner?: string; steps: Step[]; test_values?: Record<string, unknown>;canary?: boolean } // a canary (tests/cases/CANARY-<AREA>.yaml): create_invoice tries the pod's data sets in turnconst CASES_DIR = path.join(__dirname, '..', '..', '..', 'tests', 'cases');/*** The scenario's YAML: from `dir` when given (a staged AI draft's own folder), else from FPT_STEPS_DIR when it holds* that id (the co-worker's staging folder for drafts), else from the script library tests/cases/.*/export function stepCaseFile(id: string, dir?: string): string {for (const d of [dir, process.env.FPT_STEPS_DIR]) {if (d && fs.existsSync(path.join(d, `${id}.yaml`))) return path.join(d, `${id}.yaml`);}return path.join(CASES_DIR, `${id}.yaml`);}export function loadStepCase(id: string, dir?: string): StepCase {const f = stepCaseFile(id, dir);const c = YAML.parse(fs.readFileSync(f, 'utf8')) as StepCase;if (c.runner !== 'steps') throw new Error(`${id}: runner is not "steps"`);return c;}type Ctx = { ui: FusionUi; c: StepCase; saved: Record<string, string>; uniques: Record<string, string>; track: (n: string) => string;chosen: Record<string, string>; // the pod value Fusion accepted, per "area.key", used again for the rest of the testrest: FusionRest; // Fusion REST, for the business actions that check what the screens diddocs: FusionDocs }; // Purchasing and General Ledger test documents, cleaned up after the testfunction fill(raw: unknown, ctx: Ctx): string {return String(raw ?? '').replace(/\{\{\s*([^}]+?)\s*\}\}/g, (_m, key: string) => {const pod = /^pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)$/i.exec(key);if (pod) return ctx.chosen[`${pod[1]}.${pod[2]}`.toLowerCase()] ?? podValue(pod[1], pod[2]); // the pod's own test dataif (key === 'today') return fusionDate();if (key.startsWith('unique:')) { const t = key.slice(7); return (ctx.uniques[t] ??= testNumber(t)); }if (key.startsWith('tv.')) return String(ctx.c.test_values?.[key.slice(3)] ?? '');if (key.startsWith('saved.')) return ctx.saved[key.slice(6)] ?? '';throw new Error(`unknown placeholder {{${key}}}`);});}/** Enter a value. A value that is exactly one pod test data placeholder ({{pod.ap.business_unit}}) is tried with each* value the pod has for it, in order, until Fusion accepts one (a business unit this user may use, a source that* exists on this pod): the first that works is kept for the rest of the test and remembered for the next run. */async function putValue(s: Step, ctx: Ctx, put: (v: string) => Promise<void>): Promise<void> {const ref = /^\s*\{\{\s*pod\.([a-z0-9]+)\.([a-z][a-z0-9_]*)\s*\}\}\s*$/i.exec(String(s.value ?? ''));const key = ref ? `${ref[1]}.${ref[2]}`.toLowerCase() : '';if (!ref || ctx.chosen[key]) return put(fill(s.value, ctx));const tried: string[] = [];for (const v of podCandidates(ref[1], ref[2])) {try {await put(v);ctx.chosen[key] = v;used(ref[1], ref[2], v, true);return;} catch (e) {if (!(e instanceof ValueRefused)) throw e;used(ref[1], ref[2], v, false);tried.push(v);}}throw new Error(`Fusion accepted none of the ${tried.length} value(s) this pod has for ${ref[2].replace(/_/g, ' ')} in ` +`"${s.field}" (${tried.join(', ')}): this test user is not offered any of them; set one it may use on the Test environments page`);}/** The invoice a business action works on: the number create_invoice (or a `remember` step) stored under the step's* `name`, "invoice_number" when it names none. */function invoiceNumber(s: Step, ctx: Ctx): string {const name = s.name || 'invoice_number';const n = ctx.saved[name];if (!n) throw new Error(`${s.action} needs an invoice: no invoice number is remembered as "${name}" (create_invoice or remember it first)`);return n;}/** A number a step gives (an amount), filled in from its placeholders. */function amountOf(raw: string | number, ctx: Ctx, what: string): number {const v = Number(fill(raw, ctx).replace(/,/g, ''));if (!Number.isFinite(v)) throw new Error(`${what} must be a number, got "${fill(raw, ctx)}"`);return v;}/** Ask Fusion (REST) until `problems` comes back empty: REST can lag a few seconds behind what the screen saved. Fails* with the last problems in words. */async function untilRight(problems: () => Promise<string[]>, what: string, timeoutMs = 60_000) {const end = Date.now() + timeoutMs;for (;;) {const p = await problems();if (!p.length) return;if (Date.now() > end) throw new Error(`${what}: ${p.join('; ')}`);await new Promise((r) => setTimeout(r, 3000));}}/** A business action's check through Fusion REST. On a pod with assisted sign-in there is no password for REST: the* check is skipped with a note on the test (the screen steps before it already ran and stand). */async function restCheck(ctx: Ctx, what: string, fn: () => Promise<void>): Promise<void> {if (ctx.rest.available) return fn();test.info().annotations.push({ type: REST_SKIPPED, description: `${what}: ${NO_REST_WHY}` });}/** The pod values to try for an AP test data key: the one Fusion already took in this test, else the pod's candidates. */const apChoices = (ctx: Ctx, key: string) => ctx.chosen[`ap.${key}`] ? [ctx.chosen[`ap.${key}`]] : podCandidates('ap', key);/** The pod's supplier sites to try when Fusion leaves Supplier Site empty (none: the first site Fusion lists). */const apSites = (ctx: Ctx) => { try { return apChoices(ctx, 'supplier_site'); } catch { return []; } };const errorText = (e: unknown) => String((e as Error)?.message || e).split('\n')[0].slice(0, 200);/** The canary's create_invoice: the pod's Payables data sets (apDataSets) in turn until one creates AND validates an* invoice. A shared pod's sampled data can be whoever used it last (a supplier without a default site, an account of* another ledger); the set that works is recorded as accepted (FPT_TESTDATA_USED), so the co-worker learns it and the* run's other scenarios and the next run try it first. When no set validates, the first set that saved is kept, so* the canary's own validate_invoice step shows what is broken; when none saves, create_invoice fails with each reason. */async function createWithDataSets(ctx: Ctx, h: { amount: string; lines: string[]; name: string }) {const sets = apDataSets();const why: string[] = [];let saved: ApDataSet | null = null;let last = false; // the invoice the last set saved is the one on the pageconst create = async (set: ApDataSet, k: number) => {const number = ctx.track(testNumber(`${ctx.c.id.replace(/[^A-Za-z0-9]/g, '')}${k || ''}`));const got = await ctx.ui.createInvoice({ businessUnit: set.businessUnit, supplier: set.supplier, site: set.site, number,amount: h.amount, lines: h.lines, account: set.account });ctx.saved[h.name] = number;return got;};for (const [k, set] of sets.entries()) {const label = `${set.businessUnit} / ${set.supplier}`;last = false;let got;try { got = await create(set, k); } catch (e) { why.push(`${label}: ${errorText(e)}`); continue; }saved ??= set;last = true;try {await ctx.ui.validateInvoice();await ctx.ui.expectStatus('Validated', ctx.saved[h.name]);} catch (e) { why.push(`${label}: saved but did not validate (${errorText(e)})`); continue; }for (const [key, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site], ['account', got.account]]) {if (v) { used('AP', key, v, true); ctx.chosen[`ap.${key}`] = v; }}if (k) console.log(`[canary] Payables data set ${k + 1} of ${sets.length} works (${label}); tried: ${why.join(' | ')}`);return;}if (!saved) throw new Error(`create_invoice failed with each of the pod's ${sets.length} Payables data set(s): ${why.join(' | ')}`);console.log(`[canary] no Payables data set validates: ${why.join(' | ')}`);if (!last) await create(saved, sets.length);}/** The pod's values to try for one test data key, the one Fusion already took in this test first; none when the pod* has no such test data (Fusion's own default is then kept, or its list's first choice taken). `also` = keys of other* areas tried after it: a journal's account may be the Payables one, which belongs to a ledger of the same pod. */function choices(ctx: Ctx, area: string, key: string, ...also: [string, string][]): string[] {const out: string[] = [];for (const [a, k] of [[area, key] as [string, string], ...also]) {const took = ctx.chosen[`${a}.${k}`.toLowerCase()];if (took) { out.push(took); continue; }try { out.push(...podCandidates(a, k)); } catch { /* the pod has no such test data */ }}return out.filter((v, i, all) => v && all.indexOf(v) === i);}/** A new test reference for a document of this scenario (FPT-<id>-<time>): what clean-up registers before the save. */const docTag = (ctx: Ctx) => testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, ''));/** The document a business action works on: what its create action (or a `remember` step) stored under the step's* `name`, `fallback` when it names none. */function docRef(s: Step, ctx: Ctx, fallback: string, noun: string, creator: string): string {const name = s.name || fallback;const n = ctx.saved[name];if (!n) throw new Error(`${s.action} needs ${noun}: nothing is remembered as "${name}" (${creator} or remember it first)`);return n;}const requisitionNumber = (s: Step, ctx: Ctx) => docRef(s, ctx, 'requisition_number', 'a requisition', 'create_requisition');const orderNumber = (s: Step, ctx: Ctx) => docRef(s, ctx, 'order_number', 'a purchase order', 'create_purchase_order');const journalBatch = (s: Step, ctx: Ctx) => docRef(s, ctx, 'journal_batch', 'a journal', 'create_journal');/** A line's quantity and price: the step's own, else the test values "quantity" (default one) and "price" (else* "amount"). */function linePrice(s: Step, ctx: Ctx): { quantity: string; price: string } {const tv = ctx.c.test_values ?? {};const given = (v: unknown) => v !== undefined && v !== '';const quantity = given(s.quantity) ? fill(s.quantity, ctx) : given(tv.quantity) ? fill('{{tv.quantity}}', ctx) : '1';const price = given(s.price) ? fill(s.price, ctx) : given(tv.price) ? fill('{{tv.price}}', ctx) : given(tv.amount) ? fill('{{tv.amount}}', ctx) : '';if (!price) throw new Error(`${s.action} needs a price: price, or the test value "price" (or "amount")`);amountOf(quantity, ctx, 'quantity');amountOf(price, ctx, 'price');return { quantity, price };}/** What an expect_ step of Purchasing or General Ledger asks of its document. */const expectation = (s: Step, ctx: Ctx): DocExpectation => ({status: s.status ? fill(s.status, ctx) : undefined,amount: s.amount !== undefined ? amountOf(s.amount, ctx, 'amount') : undefined,amountAtLeast: s.amount_at_least !== undefined ? amountOf(s.amount_at_least, ctx, 'amount_at_least') : undefined,canceled: s.canceled,posted: s.posted,});/** Ask Fusion (REST) until `find` answers something: a document just saved can take a few seconds to show. */async function untilFound<T>(find: () => Promise<T | null | undefined>, what: string, timeoutMs = 60_000): Promise<T> {const end = Date.now() + timeoutMs;for (;;) {const v = await find();if (v) return v;if (Date.now() > end) throw new Error(what);await new Promise((r) => setTimeout(r, 3000));}}/** A new test document registered for clean-up BEFORE its save (its tag), so it is cleaned up even if the step fails. */const track = (ctx: Ctx, kind: DocKind) => ctx.docs.track(kind, docTag(ctx));/** The proven actions. Optional ones call a FusionUi method only if that building block exists. */const ACTIONS: Record<string, (s: Step, ctx: Ctx) => Promise<void>> = {sign_in: async (_s, { ui }) => ui.signIn(),open_task: async (s, ctx) => {await ctx.ui.openPath(fill(s.value, ctx)); // "Group > Page > Task", or "Group > Action" for a quick action},enter: async (s, ctx) => {if (!s.field) throw new Error('enter needs a field');if (s.field === 'Number') ctx.track(fill(s.value, ctx)); // a saved test invoice is cancelled after the test, pass or failawait putValue(s, ctx, (v) => ctx.ui.put(s.field!, v));},expect_filled: async (s, ctx) => { for (const f of s.fields ?? (s.field ? [s.field] : [])) await ctx.ui.expectFilled(f); },expect_value: async (s, ctx) => {if (!s.field) throw new Error('expect_value needs a field');await expect.poll(() => ctx.ui.value(s.field!), { message: `${s.field} should be "${fill(s.value, ctx)}"`, timeout: 30_000 }).toBe(fill(s.value, ctx));},remember: async (s, ctx) => { if (!s.field || !s.name) throw new Error('remember needs field and name'); ctx.saved[s.name] = await ctx.ui.value(s.field); },click: async (s, ctx) => {const name = fill(s.value, ctx);await ctx.ui.pressButton(name);},confirm_if_asked: async (_s, ctx) => {const yes = ctx.ui.page.getByRole('button', { name: /^(Yes|OK)$/ });if (await yes.count()) { await yes.first().click(); await ctx.ui.settle(); }},// any screen: tables, menus, messages, searches and statuses (the AI writes these for every business area)add_row: async (s, ctx) => { if (!s.field) throw new Error('add_row needs the table section as field'); await ctx.ui.addRow(s.field); },enter_in_row: async (s, ctx) => {if (!s.field) throw new Error('enter_in_row needs a field');await putValue(s, ctx, (v) => ctx.ui.putInRow(s.field!, v));},menu_action: async (s, ctx) => {if (!s.field) throw new Error('menu_action needs the menu as field');await ctx.ui.menuAction(s.field, fill(s.value, ctx));},expect_no_error: async (_s, ctx) => ctx.ui.expectNoError(),expect_message: async (s, ctx) => ctx.ui.expectMessage(fill(s.value, ctx)),expect_results: async (_s, ctx) => ctx.ui.expectResults(),cancel_without_saving: async (_s, ctx) => {await ctx.ui.page.getByRole('button', { name: 'Cancel', exact: true }).first().click();await ctx.ui.settle(2000);await ACTIONS.confirm_if_asked({ action: 'confirm_if_asked' }, ctx);},// Payables business actions/** Create and save a Payables invoice on its own screen (no open_task before it). value = the invoice amount (default* {{tv.amount}}); lines = the line amounts (default one line of the whole amount; the amount defaults to their sum);* name = what to remember the new FPT- number as (default invoice_number, used as {{saved.invoice_number}}). The* number is registered for clean-up before the save, so the invoice is cancelled after the test, pass or fail. */create_invoice: async (s, ctx) => {const lines = (s.lines ?? []).map((l) => fill(l, ctx));const amount = s.value !== undefined && s.value !== '' ? fill(s.value, ctx): lines.length ? lines.reduce((sum, l, i) => sum + amountOf(l, ctx, `line ${i + 1}`), 0).toFixed(2): ctx.c.test_values?.amount !== undefined ? fill('{{tv.amount}}', ctx) : '';if (!amount) throw new Error('create_invoice needs an amount: value, lines, or the test value "amount"');if (ctx.c.canary) return createWithDataSets(ctx, { amount, lines, name: s.name || 'invoice_number' });const number = ctx.track(testNumber(ctx.c.id.replace(/[^A-Za-z0-9]/g, '')));const got = await ctx.ui.createInvoice({ businessUnit: apChoices(ctx, 'business_unit'), supplier: apChoices(ctx, 'supplier'), number, amount,lines, account: ctx.chosen['ap.account'] ?? podValue('ap', 'account'), site: apSites(ctx) });ctx.chosen['ap.business_unit'] = got.businessUnit;ctx.chosen['ap.supplier'] = got.supplier;ctx.saved[s.name || 'invoice_number'] = number;},/** Check the invoice in Fusion (REST) by its number. status = the status it must have (Validated, Needs revalidation,* Canceled ...: matched without regard to case); amount = its exact amount; amount_at_least = at least this amount* (the pod may add tax on top); canceled = true or false. With none of them, it checks that the invoice exists. */expect_invoice: async (s, ctx) => {const number = invoiceNumber(s, ctx);const want: InvoiceExpectation = {status: s.status ? fill(s.status, ctx) : undefined,amount: s.amount !== undefined ? amountOf(s.amount, ctx, 'amount') : undefined,amountAtLeast: s.amount_at_least !== undefined ? amountOf(s.amount_at_least, ctx, 'amount_at_least') : undefined,canceled: s.canceled,};await restCheck(ctx, `expect_invoice ${number}`, () =>untilRight(async () => invoiceProblems(number, await ctx.rest.invoiceByNumber(number), want), `invoice ${number} in Fusion`));},/** The invoice carries a hold that is not released: value = the hold's name as Fusion lists it (any case). */expect_hold: async (s, ctx) => {const number = invoiceNumber(s, ctx);const name = fill(s.value, ctx).trim().toLowerCase();if (!name) throw new Error('expect_hold needs the hold name as value');await restCheck(ctx, `expect_hold ${number}`, () => untilRight(async () => {const holds = activeHolds(await ctx.rest.holds(number));return holds.some((h) => String(h.HoldName || '').trim().toLowerCase() === name) ? []: [`no "${fill(s.value, ctx)}" hold (holds: ${holds.map((h) => h.HoldName).join(', ') || 'none'})`];}, `invoice ${number}`));},/** The invoice carries no hold that is not released (the holds list: 26D no longer returns ActiveHoldFlag). */expect_no_holds: async (s, ctx) => {const number = invoiceNumber(s, ctx);await restCheck(ctx, `expect_no_holds ${number}`, () => untilRight(async () => {const holds = activeHolds(await ctx.rest.holds(number));return holds.length ? [`it is on hold: ${holds.map((h) => h.HoldName).join(', ')}`] : [];}, `invoice ${number}`, 20_000));},// Purchasing business actions/** Create a requisition of one noncatalog line on its own screen and submit it. value = the item's description* (after the test's tag); quantity (default the test value "quantity", else one) and price (default the test value* "price", else "amount"); name = what to remember its number as (default requisition_number). */create_requisition: async (s, ctx) => {const { quantity, price } = linePrice(s, ctx);const tag = track(ctx, 'po_requisition');const said = await ctx.ui.createRequisition({ description: `${tag} ${fill(s.value, ctx).trim() || 'Test item'}`, quantity, price,bu: choices(ctx, 'po', 'requisitioning_bu'), category: choices(ctx, 'po', 'category'), uom: choices(ctx, 'po', 'uom'),account: choices(ctx, 'po', 'charge_account', ['gl', 'account'], ['ap', 'account']) });// its number: Fusion's confirmation names it, else REST finds the requisition by the tag in its descriptionconst m = /\bRequisition\s+([A-Za-z0-9][\w-]*)\s+(?:was|has been)\s+submitted/i.exec(said.join(' '));if (!ctx.rest.available && m) { // assisted sign-in: Fusion's own confirmation names itctx.saved[s.name || 'requisition_number'] = m[1];return restCheck(ctx, `requisition ${m[1]} in Fusion`, async () => {});}const r = await untilFound(async () => (m ? await ctx.rest.requisition(m[1]) : null) ?? ctx.rest.requisition(tag),`requisition ${m?.[1] ?? tag} should be in Fusion after the submit`);ctx.saved[s.name || 'requisition_number'] = r.Requisition;},/** Check the requisition in Fusion (REST): status (Incomplete, Pending approval, Approved, Rejected, Canceled ...:* any case), canceled = true or false. With neither, that it exists. */expect_requisition: async (s, ctx) => {const number = requisitionNumber(s, ctx);const want = expectation(s, ctx);await restCheck(ctx, `expect_requisition ${number}`, () =>untilRight(async () => requisitionProblems(number, await ctx.rest.requisition(number), want), `requisition ${number} in Fusion`));},/** Create a purchase order of one goods line on its own screen and save it (not submitted). value = the line's* description (after the test's tag); quantity, price as for create_requisition; name = what to remember its number* as (default order_number). */create_purchase_order: async (s, ctx) => {const { quantity, price } = linePrice(s, ctx);const supplier = choices(ctx, 'po', 'supplier');if (!supplier.length) podValue('po', 'supplier'); // fails saying where to set itconst tag = track(ctx, 'po_order');const got = await ctx.ui.createPurchaseOrder({ description: `${tag} ${fill(s.value, ctx).trim() || 'Test item'}`, quantity, price,bu: choices(ctx, 'po', 'business_unit'), supplier, site: choices(ctx, 'po', 'supplier_site'), category: choices(ctx, 'po', 'category'),uom: choices(ctx, 'po', 'uom') });for (const [k, v] of [['business_unit', got.businessUnit], ['supplier', got.supplier], ['supplier_site', got.site]]) if (v) ctx.chosen[`po.${k}`] = v;const shown = await ctx.ui.orderNumberOnPage();if (!ctx.rest.available && shown) { // assisted sign-in: the number Fusion shows on the orderctx.saved[s.name || 'order_number'] = shown;return restCheck(ctx, `purchase order ${shown} in Fusion`, async () => {});}const o = await untilFound(async () => (await ctx.rest.purchaseOrder(tag)) ?? (shown ? ctx.rest.purchaseOrder(shown) : null),`purchase order ${shown || tag} should be in Fusion after the save`);ctx.saved[s.name || 'order_number'] = o.OrderNumber;},/** Submit the order (opened from Manage Orders when it is not on the page): Fusion must take it out of Incomplete* (Pending Approval, or Open where no approval is needed). */submit_purchase_order: async (s, ctx) => {const number = orderNumber(s, ctx);await ctx.ui.submitPurchaseOrder(number);await restCheck(ctx, `submit_purchase_order ${number}`, () => untilRight(async () => {const o = await ctx.rest.purchaseOrder(number);if (!o) return [`purchase order ${number} is not in Fusion`];return /^incomplete$/i.test(String(o.Status || o.StatusCode || '')) ? [`purchase order ${number} is still Incomplete`] : [];}, `purchase order ${number} after Submit`, 120_000));},/** Check the order in Fusion (REST): status (Open, Pending Approval, Incomplete, Canceled ...: any case), amount =* its exact total, amount_at_least = at least this (the pod may add tax), canceled = true or false. */expect_purchase_order: async (s, ctx) => {const number = orderNumber(s, ctx);const want = expectation(s, ctx);await restCheck(ctx, `expect_purchase_order ${number}`, () =>untilRight(async () => purchaseOrderProblems(number, await ctx.rest.purchaseOrder(number), want), `purchase order ${number} in Fusion`));},// General Ledger business actions/** Create and save a journal batch on its own screen: one debit and one credit of value (default {{tv.amount}}) on* the same account of the pod. name = what to remember the batch name as (default journal_batch). */create_journal: async (s, ctx) => {const amount = s.value !== undefined && s.value !== '' ? fill(s.value, ctx): ctx.c.test_values?.amount !== undefined ? fill('{{tv.amount}}', ctx) : '';if (!amount) throw new Error('create_journal needs an amount: value, or the test value "amount"');amountOf(amount, ctx, 'the journal amount');const batch = track(ctx, 'gl_journal');const got = await ctx.ui.createJournal({ batch, amount, ledger: choices(ctx, 'gl', 'ledger'), category: choices(ctx, 'gl', 'category'),period: choices(ctx, 'gl', 'accounting_period'), account: choices(ctx, 'gl', 'account', ['ap', 'account']) });for (const [k, v] of Object.entries(got)) if (v) ctx.chosen[`gl.${k}`] = v;await restCheck(ctx, `create_journal ${batch}`, async () => {await untilFound(() => ctx.rest.journalBatch(batch), `journal batch ${batch} should be in Fusion after the save`);});ctx.saved[s.name || 'journal_batch'] = batch;},/** Post the journal batch (opened from Manage Journals when it is not on the page). Posting runs as a process: the* step waits until REST shows the batch posted, or sent for approval (then expect_journal posted: true fails, which* says so); a posting error fails it at once. */post_journal: async (s, ctx) => {const batch = journalBatch(s, ctx);await ctx.ui.postJournal(batch);await restCheck(ctx, `post_journal ${batch}`, () => untilRight(async () => {const b = await ctx.rest.journalBatch(batch);if (!b) return [`journal batch ${batch} is not in Fusion`];if (journalPosted(b)) return [];const approval = String(b.ApprovalStatusMeaning || b.ApprovalStatus || '').trim();if (/in process|pending|waiting|progress/i.test(approval)) {console.log(`[post_journal] ${batch} went for approval (${approval}): it posts once approved`);return [];}const status = journalStatus(b);if (!/^(unposted|selected for posting|posting in process|processing)?$/i.test(status)) {throw new Error(`journal batch ${batch} did not post: its status is "${status}"`);}return [`journal batch ${batch} is still ${status || 'not posted'}`];}, `journal batch ${batch} after Post`, 300_000));},/** Check the journal batch in Fusion (REST): status (Posted, Unposted ...: any case), posted = true or false. */expect_journal: async (s, ctx) => {const batch = journalBatch(s, ctx);const want = expectation(s, ctx);await restCheck(ctx, `expect_journal ${batch}`, () =>untilRight(async () => journalProblems(batch, await ctx.rest.journalBatch(batch), want), `journal batch ${batch} in Fusion`));},/** Reverse the posted journal batch (opened from Manage Journals when it is not on the page). Fusion's reversal is a* batch it names after this one: the step waits until REST shows it (or the batch says it is reversed; on a pod that* refuses the name search, Fusion's own confirmation of the reversal). */reverse_journal: async (s, ctx) => {const batch = journalBatch(s, ctx);const said = await ctx.ui.reverseJournal(batch);await restCheck(ctx, `reverse_journal ${batch}`, () => untilRight(async () => {const named = await ctx.rest.journalBatchesNamed(batch);if (named?.some((b) => b.BatchName !== batch)) return [];const b = await ctx.rest.journalBatch(batch);const flagged = b && Object.entries(b).some(([k, v]) => /revers/i.test(k) && v !== null && v !== ''&& !/^(n|no|false|not reversed)$/i.test(String(v)));if (flagged) return [];if (named === null && said.some((t) => /revers|submitted|process/i.test(t))) return [];return [`no reversal of it is in Fusion yet${said.length ? ` (Fusion said: ${said.join(' | ').slice(0, 200)})` : ''}`];}, `journal batch ${batch} reversal`, 180_000));},};/** Building blocks that live on FusionUi (added module by module): action name -> method name and argument fields. */const UI_BLOCKS: Record<string, { method: string; args: (s: Step, ctx: Ctx) => unknown[] }> = {add_line: { method: 'addLine', args: (s, ctx) => [Number((s as { line?: number }).line ?? 1),{ amount: fill(s.value, ctx), account: fill((s as { account?: string }).account ?? '{{pod.ap.account}}', ctx) }] },save: { method: 'save', args: () => [] },invoice_action: { method: 'invoiceAction', args: (s, ctx) => [fill(s.value, ctx)] },validate_invoice: { method: 'validateInvoice', args: () => [] },/** Find the invoice remembered as `name` (default invoice_number) on Manage Invoices: exactly it must be listed. */find_invoice: { method: 'findInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] },/** Invoice Actions > Cancel Invoice on the invoice remembered as `name`, confirmed: it must then show Canceled. */cancel_invoice: { method: 'cancelInvoice', args: (s, ctx) => [invoiceNumber(s, ctx)] },expect_status: { method: 'expectStatusText', args: (s, ctx) => [fill(s.value, ctx)] },/** Cancel the requisition remembered as `name` (default requisition_number), or withdraw it while pending approval. */cancel_requisition: { method: 'cancelRequisition', args: (s, ctx) => [requisitionNumber(s, ctx)] },/** Find the order remembered as `name` (default order_number) on Manage Orders: exactly it must be listed. */find_purchase_order: { method: 'findPurchaseOrder', args: (s, ctx) => [orderNumber(s, ctx)] },/** Cancel the order remembered as `name` (withdrawn and deleted while pending approval): Canceled or gone after. */cancel_purchase_order: { method: 'cancelPurchaseOrder', args: (s, ctx) => [orderNumber(s, ctx)] },/** Find the journal batch remembered as `name` (default journal_batch) on Manage Journals: exactly it is listed. */find_journal: { method: 'findJournal', args: (s, ctx) => [journalBatch(s, ctx)] },};export const supportedActions = () => [...Object.keys(ACTIONS), ...Object.keys(UI_BLOCKS)];async function runStep(s: Step, ctx: Ctx) {const direct = ACTIONS[s.action];if (direct) return direct(s, ctx);const block = UI_BLOCKS[s.action];const fn = block && (ctx.ui as unknown as Record<string, unknown>)[block.method];if (typeof fn !== 'function') throw new Error(`step action "${s.action}" is not supported yet (known: ${supportedActions().join(', ')})`);await (fn as (...a: unknown[]) => Promise<void>).apply(ctx.ui, block.args(s, ctx));}/** Registers one Playwright test for a steps scenario. Called from the generated tests/fusion/steps/<ID>.spec.ts, or* from a staged draft's entry (opts.dir = the staging folder holding its YAML). */export function stepsTest(id: string, tags: string[], opts: { dir?: string } = {}) {const c = loadStepCase(id, opts.dir);test(`${id} ${c.title}`, { tag: tags }, async ({ fusion, apInvoices, fusionDocs }) => {const ctx: Ctx = { ui: fusion, c, saved: {}, uniques: {}, track: apInvoices.track, chosen: {}, rest: apInvoices.rest, docs: fusionDocs };for (const [i, s] of c.steps.entries()) {const label = `${s.n ?? i + 1}. ${s.action}${s.field ? ` ${s.field}` : ''}${s.value !== undefined ? ` = ${fill(s.value, ctx)}` : ''}`;await test.step(s.expected ? `${label} (expect: ${s.expected})` : label, () => runStep(s, ctx));}});}
1234567891011121314151617181920212223242526272829303132333435// AP-FUS-002 (YAML: tests/cases/AP-FUS-002.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves one invoice through the screens; the apInvoices fixture cancels it afterwards (REST).test('AP-FUS-002 Standard invoice is entered, saved and validated with no holds', { tag: ['@AP-FUS-002', '@AP', '@P1'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP2'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step('Open Payables > Invoices > Create Invoice', async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);});await test.step(`Enter the invoice header: ${number}, amount 100`, () =>fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' }));await test.step('Add one Item line of 100 charged to the distribution combination', () =>fusion.addLine(1, { amount: '100', account: d.account }));await test.step('Save: Fusion saves without messages and shows "Not validated"', async () => {expect(await fusion.save()).toEqual([]);await fusion.expectStatus('Not validated');});await test.step('Invoice Actions > Validate (the amount set to the Total when Fusion adds tax): the page shows "Validated"', async () => {await fusion.validateInvoice();expect(await fusion.dialogs()).toEqual([]);await fusion.expectStatus('Validated');});await test.step('Check in Fusion (REST): validated, amount 100 plus any tax, no holds', async () => {const inv = await apInvoices.rest.invoice(number, d.supplier);expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();expect(inv!.ValidationStatus).toBe('Validated');expect(inv!.InvoiceAmount).toBeGreaterThanOrEqual(100); // 100, plus the tax Fusion adds on this podexpect(inv!.CanceledFlag).toBe(false);expect(await apInvoices.rest.holds(number)).toEqual([]);});});12345678910111213141516171819202122232425262728293031323334353637// AP-FUS-002 (YAML: tests/cases/AP-FUS-002.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves one invoice through the screens; the apInvoices fixture cancels it afterwards (REST).test('AP-FUS-002 Standard invoice is entered, saved and validated with no holds', { tag: ['@AP-FUS-002', '@AP', '@P1'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP2'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step('Open Payables > Invoices > Create Invoice', async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);});await test.step(`Enter the invoice header: ${number}, amount 100`, () =>fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' }));await test.step('Add one Item line of 100 charged to the distribution combination', () =>fusion.addLine(1, { amount: '100', account: d.account }));await test.step('Save: Fusion saves without messages and shows "Not validated"', async () => {expect(await fusion.save()).toEqual([]);await fusion.expectStatus('Not validated');});await test.step('Invoice Actions > Validate (the amount set to the Total when Fusion adds tax): the page shows "Validated"', async () => {await fusion.validateInvoice();expect(await fusion.dialogs()).toEqual([]);await fusion.expectStatus('Validated');});await test.step('Check in Fusion (REST): validated, amount 100 plus any tax, no holds', () => apInvoices.check('AP-FUS-002 REST check', async () => {const inv = await apInvoices.rest.invoice(number, d.supplier);expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();expect(inv!.ValidationStatus).toBe('Validated');expect(inv!.InvoiceAmount).toBeGreaterThanOrEqual(100); // 100, plus the tax Fusion adds on this podexpect(inv!.CanceledFlag).toBe(false);// a hold Fusion released (the line variance from before the tax line was balanced) carries a ReleaseName: only// holds still active fail the checkexpect((await apInvoices.rest.holds(number)).filter((h) => !h.ReleaseName).map((h) => h.HoldName)).toEqual([]);}));});
123456789101112131415161718192021222324252627282930313233343536// AP-FUS-003 (YAML: tests/cases/AP-FUS-003.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves one invoice through the screens; the apInvoices fixture cancels it afterwards (REST).test('AP-FUS-003 Invoice whose lines do not equal the invoice amount is put on hold', { tag: ['@AP-FUS-003', '@AP', '@P1'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP3'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step('Open Payables > Invoices > Create Invoice', async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);});await test.step(`Enter the invoice header: ${number}, amount 100`, () =>fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' }));await test.step('Add one Item line of only 90', () => fusion.addLine(1, { amount: '90', account: d.account }));await test.step('Save: Fusion accepts the invoice as entered and shows "Not validated"', async () => {expect(await fusion.save()).toEqual([]);await fusion.expectStatus('Not validated');});await test.step('Invoice Actions > Validate: the page shows "Needs revalidation", not "Validated"', async () => {await fusion.invoiceAction('Validate');await fusion.expectStatus('Needs revalidation');});await test.step('Check in Fusion (REST): not validated and a system Line variance hold', async () => {const inv = await apInvoices.rest.invoice(number, d.supplier);expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();expect(inv!.ValidationStatus).not.toBe('Validated');// 26D's invoice record no longer returns ActiveHoldFlag: the holds list below is the proof either wayif (inv!.ActiveHoldFlag !== undefined) expect(inv!.ActiveHoldFlag).toBe(true);const holds = await apInvoices.rest.holds(number);expect(holds.map((h) => h.HoldName)).toContain('Line variance');const lv = holds.find((h) => h.HoldName === 'Line variance')!;expect(lv.HoldReason).toMatch(/lines does not equal invoice amount/i);});});123456789101112131415161718192021222324252627282930313233343536// AP-FUS-003 (YAML: tests/cases/AP-FUS-003.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves one invoice through the screens; the apInvoices fixture cancels it afterwards (REST).test('AP-FUS-003 Invoice whose lines do not equal the invoice amount is put on hold', { tag: ['@AP-FUS-003', '@AP', '@P1'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP3'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step('Open Payables > Invoices > Create Invoice', async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);});await test.step(`Enter the invoice header: ${number}, amount 100`, () =>fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' }));await test.step('Add one Item line of only 90', () => fusion.addLine(1, { amount: '90', account: d.account }));await test.step('Save: Fusion accepts the invoice as entered and shows "Not validated"', async () => {expect(await fusion.save()).toEqual([]);await fusion.expectStatus('Not validated');});await test.step('Invoice Actions > Validate: the page shows "Needs revalidation", not "Validated"', async () => {await fusion.invoiceAction('Validate');await fusion.expectStatus('Needs revalidation');});await test.step('Check in Fusion (REST): not validated and a system Line variance hold', () => apInvoices.check('AP-FUS-003 REST check', async () => {const inv = await apInvoices.rest.invoice(number, d.supplier);expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();expect(inv!.ValidationStatus).not.toBe('Validated');// 26D's invoice record no longer returns ActiveHoldFlag: the holds list below is the proof either wayif (inv!.ActiveHoldFlag !== undefined) expect(inv!.ActiveHoldFlag).toBe(true);const holds = await apInvoices.rest.holds(number);expect(holds.map((h) => h.HoldName)).toContain('Line variance');const lv = holds.find((h) => h.HoldName === 'Line variance')!;expect(lv.HoldReason).toMatch(/lines does not equal invoice amount/i);}));});
123456789101112131415161718192021222324252627282930313233343536// AP-FUS-004 (YAML: tests/cases/AP-FUS-004.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves one invoice through the screens (the original), tries a second one with the same// number, which Fusion must refuse; the apInvoices fixture cancels the original afterwards (REST).test('AP-FUS-004 Duplicate invoice number is rejected', { tag: ['@AP-FUS-004', '@AP', '@P1'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP4'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step(`Set-up: enter and save the original invoice ${number} (amount 100, one line)`, async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' });await fusion.addLine(1, { amount: '100', account: d.account });expect(await fusion.save()).toEqual([]);await fusion.expectStatus('Not validated');});await test.step('Open Create Invoice again and enter a second invoice with the same number and supplier', async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '50' });});await test.step('Save: Fusion refuses the duplicate number (AP-810245)', async () => {const msgs = await fusion.save();expect(msgs.join(' | ')).toMatch(/already an invoice with that number/i);expect(msgs.join(' | ')).toContain('AP-810245');await fusion.answerDialog('OK');await fusion.cancelPage();});await test.step('Check in Fusion (REST): still exactly one invoice with that number, the original of 100', async () => {const all = await apInvoices.rest.invoices(number, d.supplier);expect(all).toHaveLength(1);expect(all[0].InvoiceAmount).toBe(100);});});123456789101112131415161718192021222324252627282930313233343536// AP-FUS-004 (YAML: tests/cases/AP-FUS-004.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves one invoice through the screens (the original), tries a second one with the same// number, which Fusion must refuse; the apInvoices fixture cancels the original afterwards (REST).test('AP-FUS-004 Duplicate invoice number is rejected', { tag: ['@AP-FUS-004', '@AP', '@P1'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP4'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step(`Set-up: enter and save the original invoice ${number} (amount 100, one line)`, async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' });await fusion.addLine(1, { amount: '100', account: d.account });expect(await fusion.save()).toEqual([]);await fusion.expectStatus('Not validated');});await test.step('Open Create Invoice again and enter a second invoice with the same number and supplier', async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '50' });});await test.step('Save: Fusion refuses the duplicate number (AP-810245)', async () => {const msgs = await fusion.save();expect(msgs.join(' | ')).toMatch(/already an invoice with that number/i);expect(msgs.join(' | ')).toContain('AP-810245');await fusion.answerDialog('OK');await fusion.cancelPage();});await test.step('Check in Fusion (REST): still exactly one invoice with that number, the original of 100', () => apInvoices.check('AP-FUS-004 REST check', async () => {const all = await apInvoices.rest.invoices(number, d.supplier);expect(all).toHaveLength(1);expect(all[0].InvoiceAmount).toBe(100);}));});
1234567891011121314151617181920212223242526272829303132333435// AP-FUS-005 (YAML: tests/cases/AP-FUS-005.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves, validates and cancels one invoice through the screens. If the test stops before the// cancel, the apInvoices fixture cancels the invoice afterwards (REST).test('AP-FUS-005 Validated invoice can be cancelled', { tag: ['@AP-FUS-005', '@AP', '@P2'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP5'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step(`Set-up: enter, save and validate invoice ${number} (amount 100, one line)`, async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' });await fusion.addLine(1, { amount: '100', account: d.account });expect(await fusion.save()).toEqual([]);await fusion.validateInvoice(); // the amount set to the Total first when Fusion adds taxawait fusion.expectStatus('Validated');});await test.step('Invoice Actions > Cancel Invoice: Fusion asks to confirm', async () => {await fusion.invoiceAction('Cancel Invoice');expect((await fusion.dialogs()).join(' | ')).toMatch(/invoice will be canceled/i);});await test.step('Confirm with OK: the page shows "Canceled"', async () => {await fusion.answerDialog('OK');await fusion.expectStatus('Canceled');});await test.step('Check in Fusion (REST): cancelled, amount 0, status Canceled', async () => {const inv = await apInvoices.rest.invoice(number, d.supplier);expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();expect(inv!.CanceledFlag).toBe(true);expect(inv!.ValidationStatus).toBe('Canceled');expect(inv!.InvoiceAmount).toBe(0);});});1234567891011121314151617181920212223242526272829303132333435// AP-FUS-005 (YAML: tests/cases/AP-FUS-005.yaml). Runs against a REAL Oracle Fusion pod (playwright.fusion.config.ts).import { test, expect } from '../../src/fusion/fixtures';import { apData, testNumber } from '../../src/fusion/ui';// Real Oracle Fusion pod. Saves, validates and cancels one invoice through the screens. If the test stops before the// cancel, the apInvoices fixture cancels the invoice afterwards (REST).test('AP-FUS-005 Validated invoice can be cancelled', { tag: ['@AP-FUS-005', '@AP', '@P2'] }, async ({ fusion, apInvoices, page }) => {const d = apData();const number = apInvoices.track(testNumber('AP5'));await test.step('Sign in as the Payables test user', () => fusion.signIn());await test.step(`Set-up: enter, save and validate invoice ${number} (amount 100, one line)`, async () => {await fusion.openTask('Payables', 'Invoices', 'Create Invoice');await expect(page).toHaveTitle(/Create Invoice/);await fusion.enterInvoiceHeader({ businessUnit: d.businessUnit, supplier: d.supplier, number, amount: '100' });await fusion.addLine(1, { amount: '100', account: d.account });expect(await fusion.save()).toEqual([]);await fusion.validateInvoice(); // the amount set to the Total first when Fusion adds taxawait fusion.expectStatus('Validated');});await test.step('Invoice Actions > Cancel Invoice: Fusion asks to confirm', async () => {await fusion.invoiceAction('Cancel Invoice');expect((await fusion.dialogs()).join(' | ')).toMatch(/invoice will be canceled/i);});await test.step('Confirm with OK: the page shows "Canceled"', async () => {await fusion.answerDialog('OK');await fusion.expectStatus('Canceled');});await test.step('Check in Fusion (REST): cancelled, amount 0, status Canceled', () => apInvoices.check('AP-FUS-005 REST check', async () => {const inv = await apInvoices.rest.invoice(number, d.supplier);expect(inv, `invoice ${number} should exist in Fusion`).not.toBeNull();expect(inv!.CanceledFlag).toBe(true);expect(inv!.ValidationStatus).toBe('Canceled');expect(inv!.InvoiceAmount).toBe(0);}));});
1234// CANARY-GL (YAML: tests/cases/CANARY-GL.yaml, runner: steps). Generated by scripts/gen-fusion-steps.js; edit the YAML, not this file.import { stepsTest } from '../../../src/fusion/steps';
stepsTest('CANARY-GL', ['@CANARY-GL','@CANARY','@P1']);1234// CANARY-PO (YAML: tests/cases/CANARY-PO.yaml, runner: steps). Generated by scripts/gen-fusion-steps.js; edit the YAML, not this file.import { stepsTest } from '../../../src/fusion/steps';
stepsTest('CANARY-PO', ['@CANARY-PO','@CANARY','@P1']);123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372"""Executor adapter: one Playwright attempt per call, ALWAYS --retries=0 (the graph owns the single retry).Live: real Chromium against mock-app via automation/playwright.agent.config.ts (adds the drafts project).Stub: the legacy synthetic report (architecture/p2p_graph._stub_report) driven by the run's stub_knobs.Docker backend: nice-to-have, not implemented in this pilot (raises)."""from __future__ import annotationsimport jsonimport loggingimport osimport reimport subprocessimport sysimport threadingimport timefrom contextlib import contextmanagerfrom pathlib import Pathfrom ..config import ROOTfrom ..platform import procsfrom .legacy import _stub_report, _walk_specslog_ = logging.getLogger("fpt.playwright")AUTOMATION = ROOT / "automation"PW_CLI = AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"MOCK_SERVER = ROOT / "mock-app" / "server.js"STUB_KEYS = ("STUB_FAIL", "STUB_DEFECT", "STUB_UI", "STUB_FLAKY")_env_lock = threading.Lock()@contextmanagerdef stub_env(knobs: dict | None):"""The legacy stub reads STUB_* from os.environ; set them only for the duration of one call."""with _env_lock:saved = {k: os.environ.get(k) for k in STUB_KEYS}try:for k in STUB_KEYS:v = (knobs or {}).get(k)if isinstance(v, list):v = ",".join(v)if v:os.environ[k] = str(v)else:os.environ.pop(k, None)yieldfinally:for k, v in saved.items():if v is None:os.environ.pop(k, None)else:os.environ[k] = vdef existing_spec_path(case_id: str) -> Path | None:for p in (AUTOMATION / "tests").rglob(f"{case_id}.spec.ts"):return preturn Nonedef grep_for(ids: list[str]) -> str:return "(?:" + "|".join("@" + re.escape(i) for i in ids) + ")(?![\\w-])"def command(ids: list[str], config: str = "playwright.agent.config.ts") -> list[str]:return ["node", str(PW_CLI), "test", "--config", config, "--retries=0", "--reporter=json","--grep", grep_for(ids)]def mock_up(egress, base_url: str) -> bool:return egress.probe(base_url.rstrip("/") + "/api/health")def ensure_mock(egress, base_url: str, log_dir: Path) -> subprocess.Popen | None:"""Start node mock-app/server.js if the mock is not answering; register it for the kill switch."""if mock_up(egress, base_url):return Nonelog_dir.mkdir(parents=True, exist_ok=True)port = base_url.rsplit(":", 1)[-1].strip("/") or "3100"f = open(log_dir / "mock-app.log", "ab")p = subprocess.Popen(["node", str(MOCK_SERVER)], cwd=str(ROOT / "mock-app"), stdout=f, stderr=subprocess.STDOUT,env=procs.child_env(PORT=port), **procs.popen_kwargs())procs.register(p, "mock-app")for _ in range(60):if mock_up(egress, base_url):return ptime.sleep(0.25)raise RuntimeError("mock-app did not start on " + base_url)def testdata_used_file(out_file: Path) -> Path:"""Where a Fusion attempt records the pod values it tried (one JSON line each), next to its result file."""return Path(out_file).parent / "testdata-used.jsonl"def run_attempt(*, run_id: str, ids: list[str], attempt: int, mode: str, out_file: Path, stub_knobs: dict | None = None,drafts_dir: Path | None = None, overrides_file: Path | None = None, cred_env: dict | None = None,library_dir: Path | None = None,backend: str = "local", timeout_s: int = 3600, log_dir: Path | None = None, tag: str = "",poll=None, poll_s: float = 5.0, live_dir: Path | None = None, live_meta: dict | None = None,config: str = "playwright.agent.config.ts") -> dict:"""poll(progress: dict) is called every poll_s seconds while Playwright runs (heartbeats); if it raises, thePlaywright process tree is killed and the exception propagates (cancellation / kill switch)."""out_file.parent.mkdir(parents=True, exist_ok=True)pw_run_id = f"fpt-{run_id}-a{attempt}{tag}"if mode == "stub":with stub_env(stub_knobs):rep = _stub_report(ids, attempt)out_file.write_text(json.dumps(rep, indent=1), encoding="utf-8")return {"file": str(out_file), "pw_run_id": None, "run_dir": None, "exit_code": 0, "mode": "stub"}if backend != "local":raise NotImplementedError("EXECUTOR_BACKEND=docker is a Phase 9 nice-to-have, not implemented in this pilot")env = procs.child_env(PLAYWRIGHT_MODE="live", PW_RETRIES="0", PW_REUSE_SERVER="1", PW_RUN_ID=pw_run_id,PLAYWRIGHT_JSON_OUTPUT_NAME=str(out_file), **(cred_env or {}))env.pop("PW_LOCATOR_OVERRIDES", None)for k in STUB_KEYS:env.pop(k, None)# Live view: the fixture hook (automation/src/live-view.ts) is active only when FPT_LIVE_VIEW_DIR is set.for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"):env.pop(k, None)if live_dir:from ..platform import liveviewmeta = {"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)env.update({"FPT_LIVE_VIEW_DIR": str(live_dir), "FPT_LIVE_VIEW_ATTEMPT": meta["attempt_key"],"FPT_LIVE_VIEW_CHUNK": str(meta["chunk"])})if drafts_dir and Path(drafts_dir).is_dir() and any(Path(drafts_dir).glob("*.spec.ts")):env["FPT_DRAFTS_DIR"] = str(drafts_dir)else:env.pop("FPT_DRAFTS_DIR", None)if library_dir and Path(library_dir).is_dir() and any(Path(library_dir).glob("*.spec.ts")):env["FPT_LIBRARY_DIR"] = str(library_dir) # approved scenarios kept in FPT_HOME (playwright.fusion.config.ts)else:env.pop("FPT_LIBRARY_DIR", None)if env.get("FUSION_BASE_URL"): # the pod values Fusion accepted or refused (automation/src/fusion/steps.ts)env["FPT_TESTDATA_USED"] = str(testdata_used_file(out_file))else:env.pop("FPT_TESTDATA_USED", None)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)cmd = command(ids, config)if sys.platform != "win32":cmd = ["node", str(PW_CLI), *cmd[2:]]log_dir = log_dir or out_file.parent# Fusion fixtures write each test invoice here BEFORE saving it (platform/cleanup.py sweeps what a broken run left)from ..platform.cleanup import LEDGERenv["FPT_CREATED_FILE"] = str(Path(log_dir) / LEDGER)log_path = log_dir / f"playwright-a{attempt}{tag}.log"with open(log_path, "wb") as log:p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **procs.popen_kwargs())procs.register(p, f"playwright:{run_id}")deadline = time.time() + timeout_stimed_out = Falsetry:while True:try:code = p.wait(timeout=poll_s if poll else max(1, deadline - time.time()))breakexcept subprocess.TimeoutExpired:if time.time() >= deadline:procs.kill_tree(p.pid)code, timed_out = -9, Truebreakif poll:try:poll(log_progress(log_path))except BaseException:procs.kill_tree(p.pid)raisefinally:procs.unregister(p)if not out_file.exists():from ..platform.failures import ExecutionErrorlog_.warning("Playwright produced no JSON report at %s (exit %s); see %s", out_file, code, log_dir)raise ExecutionError(f"Playwright produced no report (exit {code}), so no scenario result was recorded. ""The browser tests may not have started; an administrator can see the run log.",exit_code=code, timed_out=timed_out, minutes=max(1, timeout_s // 60))return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(AUTOMATION / "results" / "runs" / pw_run_id),"exit_code": code, "mode": "live", "timed_out": timed_out}PROGRESS_RE = re.compile(rb"\[(\d+)/(\d+)\]")def log_progress(log_path: Path) -> dict:"""Progress from Playwright's line output ('[k/N]'), for heartbeats."""try:tail = Path(log_path).read_bytes()[-20000:]except OSError:return {"done": 0, "total": None}m = PROGRESS_RE.findall(tail)return {"done": int(m[-1][0]), "total": int(m[-1][1])} if m else {"done": 0, "total": None}def merge_chunk_reports(files: list[Path], out_file: Path) -> Path:"""Concatenate chunk reports of ONE attempt into one Playwright-shaped report (suites/errors appended)."""base = Nonefor f in files:d = json.loads(Path(f).read_text(encoding="utf-8"))if base is None:base = dcontinuebase.setdefault("suites", []).extend(d.get("suites") or [])base.setdefault("errors", []).extend(d.get("errors") or [])out_file.write_text(json.dumps(base or {"config": {"projects": []}, "suites": [], "errors": [], "stats": {}}, indent=1),encoding="utf-8")return out_fileNO_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 thereason, 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_filedef run_attempt_chunked(*, ids: list[str], out_file: Path, chunk_size: int, done: dict | None = None,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; thosechunks 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).`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: anattempt that fits in one chunk keeps the attempt's own report file and tag, as an unchunked run would."""from ..platform.failures import ExecutionErrorchunks = [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}files = dict(done)skipped, lost, code, timed_out, last_err = [], [], 0, False, Nonewhole = single_as_attempt and len(chunks) == 1for k, chunk in enumerate(chunks):cf = out_file if whole else out_file.with_name(f"{out_file.stem}.c{k}.json")if k in done:skipped.append(k)continuetry: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):raiselog_.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, Truecontinueif res.get("run_dir"):dirs[k] = res["run_dir"]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"))if last_err is not None and len(lost) == len(chunks): # nothing at all was learned: the attempt fails as one wouldraise last_errmerge_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, "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 resultcould 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):returnholes = [sp for sp in _walk_specs(data.get("suites")) if sp.get(NO_RESULT)]if not holes:returnreal: dict[str, dict] = {}for f in files[1:]:try:later = json.loads(Path(f).read_text(encoding="utf-8"))except (OSError, ValueError):continuefor 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 = Falsefor 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 = Trueif changed:first.write_text(json.dumps(data, indent=1), encoding="utf-8")def attachments_by_case(report_file: Path) -> dict[str, str]:"""{absolute attachment path: case id} from a Playwright JSON report (for evidence ingest)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):tags = spec.get("tags") or []cid = next((t.lstrip("@") for t in tags if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), None)for t in spec.get("tests", []):for r in t.get("results", []):for a in r.get("attachments", []):if a.get("path"):out[a["path"]] = cidreturn outdef error_contexts(report_file: Path) -> dict[str, str]:"""{case id: error-context text} for failed results (Playwright attaches an ARIA snapshot on failure)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):cid = next((t.lstrip("@") for t in (spec.get("tags") or []) if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), None)for t in spec.get("tests", []):for r in t.get("results", []):for a in r.get("attachments", []):if a.get("name") == "error-context":txt = ""if a.get("path") and Path(a["path"]).exists():txt = Path(a["path"]).read_text(encoding="utf-8", errors="replace")elif a.get("body"):import base64try:txt = base64.b64decode(a["body"]).decode("utf-8", "replace")except ValueError:txt = str(a["body"])if cid and txt:out[cid] = txtreturn outdef stacks_by_case(report_file: Path) -> dict[str, str]:"""{case id: concatenated error stacks} (to locate the failing source line)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):cid = next((t.lstrip("@") for t in (spec.get("tags") or []) if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), spec.get("id"))for t in spec.get("tests", []):for r in t.get("results", []):st = "\n".join((e.get("stack") or "") + "\n" + json.dumps(e.get("location") or {}) for e in r.get("errors", []) or [])if st.strip() and cid:out[cid] = streturn outdef errors_by_case(report_file: Path) -> dict[str, str]:data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):cid = next((t.lstrip("@") for t in (spec.get("tags") or []) if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), spec.get("id"))for t in spec.get("tests", []):for r in t.get("results", []):msgs = [e.get("message", "") for e in r.get("errors", []) or []]if msgs and cid:out[cid] = "\n".join(msgs)return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466"""Executor adapter: one Playwright attempt per call, ALWAYS --retries=0 (the graph owns the single retry).Live: real Chromium against mock-app via automation/playwright.agent.config.ts (adds the drafts project).Stub: the legacy synthetic report (architecture/p2p_graph._stub_report) driven by the run's stub_knobs.Docker backend: nice-to-have, not implemented in this pilot (raises)."""from __future__ import annotationsimport jsonimport loggingimport osimport reimport subprocessimport sysimport threadingimport timefrom contextlib import contextmanagerfrom pathlib import Pathfrom ..config import ROOTfrom ..platform import procsfrom .legacy import _stub_report, _walk_specslog_ = logging.getLogger("fpt.playwright")AUTOMATION = ROOT / "automation"PW_CLI = AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"MOCK_SERVER = ROOT / "mock-app" / "server.js"STUB_KEYS = ("STUB_FAIL", "STUB_DEFECT", "STUB_UI", "STUB_FLAKY")_env_lock = threading.Lock()@contextmanagerdef stub_env(knobs: dict | None):"""The legacy stub reads STUB_* from os.environ; set them only for the duration of one call."""with _env_lock:saved = {k: os.environ.get(k) for k in STUB_KEYS}try:for k in STUB_KEYS:v = (knobs or {}).get(k)if isinstance(v, list):v = ",".join(v)if v:os.environ[k] = str(v)else:os.environ.pop(k, None)yieldfinally:for k, v in saved.items():if v is None:os.environ.pop(k, None)else:os.environ[k] = vdef existing_spec_path(case_id: str) -> Path | None:for p in (AUTOMATION / "tests").rglob(f"{case_id}.spec.ts"):return preturn Nonedef grep_for(ids: list[str]) -> str:return "(?:" + "|".join("@" + re.escape(i) for i in ids) + ")(?![\\w-])"def command(ids: list[str], config: str = "playwright.agent.config.ts") -> list[str]:return ["node", str(PW_CLI), "test", "--config", config, "--retries=0", "--reporter=json","--grep", grep_for(ids)]def mock_up(egress, base_url: str) -> bool:return egress.probe(base_url.rstrip("/") + "/api/health")def ensure_mock(egress, base_url: str, log_dir: Path) -> subprocess.Popen | None:"""Start node mock-app/server.js if the mock is not answering; register it for the kill switch."""if mock_up(egress, base_url):return Nonelog_dir.mkdir(parents=True, exist_ok=True)port = base_url.rsplit(":", 1)[-1].strip("/") or "3100"f = open(log_dir / "mock-app.log", "ab")p = subprocess.Popen(["node", str(MOCK_SERVER)], cwd=str(ROOT / "mock-app"), stdout=f, stderr=subprocess.STDOUT,env=procs.child_env(PORT=port), **procs.popen_kwargs())procs.register(p, "mock-app")for _ in range(60):if mock_up(egress, base_url):return ptime.sleep(0.25)raise RuntimeError("mock-app did not start on " + base_url)def testdata_used_file(out_file: Path) -> Path:"""Where a Fusion attempt records the pod values it tried (one JSON line each), next to its result file."""return Path(out_file).parent / "testdata-used.jsonl"def run_attempt(*, run_id: str, ids: list[str], attempt: int, mode: str, out_file: Path, stub_knobs: dict | None = None,drafts_dir: Path | None = None, overrides_file: Path | None = None, cred_env: dict | None = None,library_dir: Path | None = None,backend: str = "local", timeout_s: int = 3600, log_dir: Path | None = None, tag: str = "",poll=None, poll_s: float = 5.0, live_dir: Path | None = None, live_meta: dict | None = None,config: str = "playwright.agent.config.ts", storage_state: dict | None = None) -> dict:"""poll(progress: dict) is called every poll_s seconds while Playwright runs (heartbeats); if it raises, thePlaywright process tree is killed and the exception propagates (cancellation / kill switch). storage_state: thesession a person signed in (assisted sign-in), written for this attempt only (mode 0600) and deleted after it."""out_file.parent.mkdir(parents=True, exist_ok=True)pw_run_id = f"fpt-{run_id}-a{attempt}{tag}"if mode == "stub":with stub_env(stub_knobs):rep = _stub_report(ids, attempt)out_file.write_text(json.dumps(rep, indent=1), encoding="utf-8")return {"file": str(out_file), "pw_run_id": None, "run_dir": None, "exit_code": 0, "mode": "stub"}if backend != "local":raise NotImplementedError("EXECUTOR_BACKEND=docker is a Phase 9 nice-to-have, not implemented in this pilot")env = procs.child_env(PLAYWRIGHT_MODE="live", PW_RETRIES="0", PW_REUSE_SERVER="1", PW_RUN_ID=pw_run_id,PLAYWRIGHT_JSON_OUTPUT_NAME=str(out_file), **(cred_env or {}))env.pop("PW_LOCATOR_OVERRIDES", None)env.pop("FPT_FUSION_STORAGE_STATE", None)for k in STUB_KEYS:env.pop(k, None)# Live view: the fixture hook (automation/src/live-view.ts) is active only when FPT_LIVE_VIEW_DIR is set.for k in ("FPT_LIVE_VIEW_DIR", "FPT_LIVE_VIEW_ATTEMPT", "FPT_LIVE_VIEW_CHUNK"):env.pop(k, None)if live_dir:from ..platform import liveviewmeta = {"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)env.update({"FPT_LIVE_VIEW_DIR": str(live_dir), "FPT_LIVE_VIEW_ATTEMPT": meta["attempt_key"],"FPT_LIVE_VIEW_CHUNK": str(meta["chunk"])})if drafts_dir and Path(drafts_dir).is_dir() and any(Path(drafts_dir).glob("*.spec.ts")):env["FPT_DRAFTS_DIR"] = str(drafts_dir)else:env.pop("FPT_DRAFTS_DIR", None)if library_dir and Path(library_dir).is_dir() and any(Path(library_dir).glob("*.spec.ts")):env["FPT_LIBRARY_DIR"] = str(library_dir) # approved scenarios kept in FPT_HOME (playwright.fusion.config.ts)else:env.pop("FPT_LIBRARY_DIR", None)if env.get("FUSION_BASE_URL"): # the pod values Fusion accepted or refused (automation/src/fusion/steps.ts)env["FPT_TESTDATA_USED"] = str(testdata_used_file(out_file))else:env.pop("FPT_TESTDATA_USED", None)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)cmd = command(ids, config)if sys.platform != "win32":cmd = ["node", str(PW_CLI), *cmd[2:]]log_dir = log_dir or out_file.parent# Fusion fixtures write each test invoice here BEFORE saving it (platform/cleanup.py sweeps what a broken run left)from ..platform.cleanup import LEDGERenv["FPT_CREATED_FILE"] = str(Path(log_dir) / LEDGER)log_path = log_dir / f"playwright-a{attempt}{tag}.log"session = Path(log_dir) / f".sign-in-state-a{attempt}{tag}.json" if storage_state is not None else Noneif session is not None: # the tests start from it instead of signing in (automation/src/fusion/session.ts)_write_secret(session, json.dumps(storage_state))env["FPT_FUSION_STORAGE_STATE"] = str(session)try:code, timed_out = _run_logged(cmd, env, log_path, run_id, timeout_s, poll, poll_s)finally:if session is not None:session.unlink(missing_ok=True)if not out_file.exists():from ..platform.failures import ExecutionErrorlog_.warning("Playwright produced no JSON report at %s (exit %s); see %s", out_file, code, log_dir)raise ExecutionError(f"Playwright produced no report (exit {code}), so no scenario result was recorded. ""The browser tests may not have started; an administrator can see the run log.",exit_code=code, timed_out=timed_out, minutes=max(1, timeout_s // 60))return {"file": str(out_file), "pw_run_id": pw_run_id, "run_dir": str(AUTOMATION / "results" / "runs" / pw_run_id),"exit_code": code, "mode": "live", "timed_out": timed_out}def _write_secret(f: Path, text: str) -> None:"""A file only this user can read, created that way."""fd = os.open(str(f), os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600)with os.fdopen(fd, "w", encoding="utf-8") as fh:fh.write(text)def _run_logged(cmd: list[str], env: dict, log_path: Path, run_id: str, timeout_s: int, poll, poll_s: float) -> tuple[int, bool]:"""Run Playwright with its output in log_path until it ends or its time is up: (exit code, timed out)."""with open(log_path, "wb") as log:p = subprocess.Popen(cmd, cwd=str(AUTOMATION), env=env, stdout=log, stderr=subprocess.STDOUT, **procs.popen_kwargs())procs.register(p, f"playwright:{run_id}")deadline = time.time() + timeout_stimed_out = Falsetry:while True:try:code = p.wait(timeout=poll_s if poll else max(1, deadline - time.time()))breakexcept subprocess.TimeoutExpired:if time.time() >= deadline:procs.kill_tree(p.pid)code, timed_out = -9, Truebreakif poll:try:poll(log_progress(log_path))except BaseException:procs.kill_tree(p.pid)raisefinally:procs.unregister(p)return code, timed_outPROGRESS_RE = re.compile(rb"\[(\d+)/(\d+)\]")def log_progress(log_path: Path) -> dict:"""Progress from Playwright's line output ('[k/N]'), for heartbeats."""try:tail = Path(log_path).read_bytes()[-20000:]except OSError:return {"done": 0, "total": None}m = PROGRESS_RE.findall(tail)return {"done": int(m[-1][0]), "total": int(m[-1][1])} if m else {"done": 0, "total": None}def merge_chunk_reports(files: list[Path], out_file: Path) -> Path:"""Concatenate chunk reports of ONE attempt into one Playwright-shaped report (suites/errors appended)."""base = Nonefor f in files:d = json.loads(Path(f).read_text(encoding="utf-8"))if base is None:base = dcontinuebase.setdefault("suites", []).extend(d.get("suites") or [])base.setdefault("errors", []).extend(d.get("errors") or [])out_file.write_text(json.dumps(base or {"config": {"projects": []}, "suites": [], "errors": [], "stats": {}}, indent=1),encoding="utf-8")return out_fileNO_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 thereason, 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_filedef run_attempt_chunked(*, ids: list[str], out_file: Path, chunk_size: int, done: dict | None = None,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; thosechunks 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).`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: anattempt that fits in one chunk keeps the attempt's own report file and tag, as an unchunked run would."""from ..platform.failures import ExecutionErrorchunks = [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}files = dict(done)skipped, lost, code, timed_out, last_err = [], [], 0, False, Nonewhole = single_as_attempt and len(chunks) == 1for k, chunk in enumerate(chunks):cf = out_file if whole else out_file.with_name(f"{out_file.stem}.c{k}.json")if k in done:skipped.append(k)continuetry: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):raiselog_.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, Truecontinueif res.get("run_dir"):dirs[k] = res["run_dir"]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"))if last_err is not None and len(lost) == len(chunks): # nothing at all was learned: the attempt fails as one wouldraise last_errmerge_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, "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 resultcould 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):returnholes = [sp for sp in _walk_specs(data.get("suites")) if sp.get(NO_RESULT)]if not holes:returnreal: dict[str, dict] = {}for f in files[1:]:try:later = json.loads(Path(f).read_text(encoding="utf-8"))except (OSError, ValueError):continuefor 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 = Falsefor 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 = Trueif changed:first.write_text(json.dumps(data, indent=1), encoding="utf-8")def attachments_by_case(report_file: Path) -> dict[str, str]:"""{absolute attachment path: case id} from a Playwright JSON report (for evidence ingest)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):tags = spec.get("tags") or []cid = next((t.lstrip("@") for t in tags if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), None)for t in spec.get("tests", []):for r in t.get("results", []):for a in r.get("attachments", []):if a.get("path"):out[a["path"]] = cidreturn outdef error_contexts(report_file: Path) -> dict[str, str]:"""{case id: error-context text} for failed results (Playwright attaches an ARIA snapshot on failure)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):cid = next((t.lstrip("@") for t in (spec.get("tags") or []) if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), None)for t in spec.get("tests", []):for r in t.get("results", []):for a in r.get("attachments", []):if a.get("name") == "error-context":txt = ""if a.get("path") and Path(a["path"]).exists():txt = Path(a["path"]).read_text(encoding="utf-8", errors="replace")elif a.get("body"):import base64try:txt = base64.b64decode(a["body"]).decode("utf-8", "replace")except ValueError:txt = str(a["body"])if cid and txt:out[cid] = txtreturn outdef stacks_by_case(report_file: Path) -> dict[str, str]:"""{case id: concatenated error stacks} (to locate the failing source line)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):cid = next((t.lstrip("@") for t in (spec.get("tags") or []) if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), spec.get("id"))for t in spec.get("tests", []):for r in t.get("results", []):st = "\n".join((e.get("stack") or "") + "\n" + json.dumps(e.get("location") or {}) for e in r.get("errors", []) or [])if st.strip() and cid:out[cid] = streturn outdef errors_by_case(report_file: Path) -> dict[str, str]:data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = {}for spec in _walk_specs(data.get("suites")):cid = next((t.lstrip("@") for t in (spec.get("tags") or []) if re.match(r"^@?[A-Z][A-Z0-9]{1,5}-", t)), spec.get("id"))for t in spec.get("tests", []):for r in t.get("results", []):msgs = [e.get("message", "") for e in r.get("errors", []) or []]if msgs and cid:out[cid] = "\n".join(msgs)return outCASE_TAG = re.compile(r"^@?[A-Z][A-Z0-9]{1,5}-")def _case_of(spec: dict) -> str | None:return next((t.lstrip("@") for t in (spec.get("tags") or []) if CASE_TAG.match(t)), None)def annotated(report_file: Path, kind: str) -> dict[str, list[str]]:"""{case id: descriptions} of the scenarios a Fusion fixture marked with an annotation of this kind (on the test, oron its last result: Playwright keeps a run-time annotation on either, by version)."""try:data = json.loads(Path(report_file).read_text(encoding="utf-8"))except (OSError, ValueError):return {}out: dict[str, list[str]] = {}for spec in _walk_specs(data.get("suites")):cid = _case_of(spec)if not cid:continuefor t in spec.get("tests") or []:notes = list(t.get("annotations") or [])for r in (t.get("results") or [])[-1:]:notes += list(r.get("annotations") or [])for a in notes:if isinstance(a, dict) and a.get("type") == kind:have = out.setdefault(cid, [])d = str(a.get("description") or "")if d not in have:have.append(d)return outdef sign_in_expired_ids(report_file: Path) -> list[str]:"""Scenarios that met an expired sign-in (assisted sign-in): they did not run, or stopped on the sign-in page."""return sorted(annotated(report_file, "sign-in-expired"))def drop_cases(report_file: Path, ids: list[str], out_file: Path) -> Path:"""A copy of the report without these scenarios (they run again after a new sign-in, and their new result replacesthem when the attempt's reports are merged)."""gone = set(ids)data = json.loads(Path(report_file).read_text(encoding="utf-8"))def keep(suites):out = []for s in suites or []:s = {**s, "specs": [sp for sp in s.get("specs") or [] if _case_of(sp) not in gone], "suites": keep(s.get("suites"))}if s["specs"] or s["suites"]:out.append(s)return outdata["suites"] = keep(data.get("suites"))Path(out_file).write_text(json.dumps(data, indent=1), encoding="utf-8")return Path(out_file)def notes_by_case(report_file: Path) -> list[dict]:"""[{case_id, failed, error, annotations}] per test of a Playwright JSON report that carries a healing note: whatthe automation recorded (a "healed" step, or the "heal-names" the screen showed where a control was not found)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out = []for spec in _walk_specs(data.get("suites")):cid = _case_of(spec) or spec.get("id")for t in spec.get("tests", []):notes = [a for a in t.get("annotations") or [] if isinstance(a, dict) and a.get("type") in ("healed", "heal-names")]res = (t.get("results") or [{}])[-1]if cid and notes:out.append({"case_id": cid, "failed": res.get("status") in ("failed", "timedOut", "interrupted"),"error": "\n".join(e.get("message", "") for e in res.get("errors") or []), "annotations": notes})return out
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484"""A browser attempt run on the remote runner (automation/remote_runner/server.py) instead of this host.Used for Oracle Fusion pods when FPT_REMOTE_RUNNER_URL is set (and the runner token is in the vault asremote_runner.token, or FPT_SECRET_REMOTE_RUNNER_TOKEN): this host may sit on a network Oracle's edge refuses. Theattempt goes out through the egress gate (https, the runner's host only; the audit log never sees the password), ispolled, 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 theledger 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. Theid of the job an attempt follows is kept in the run folder (remote-job.json) until its results are in, so a server thatrestarts mid-attempt and is resumed follows the same job again instead of starting a second one, and a runner thatrestarted (it no longer knows the job, or reports it "lost") fails the attempt in seconds instead of at its deadline."""from __future__ import annotationsimport base64import ioimport jsonimport loggingimport reimport timeimport zipfilefrom pathlib import Pathfrom .playwright import AUTOMATION, testdata_used_filelog = 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 cancelledENDED = ("done", "cancelled", "failed", "lost")GONE_AFTER = 2 # consecutive 404s for a job: the runner restarted and no longer knows itBUSY_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):passdef _specs(d: Path | None) -> dict[str, str]:if not d or not Path(d).is_dir():return {}return {p.name: p.read_text(encoding="utf-8") for p in Path(d).glob("*.spec.ts")}_STEPS_ENTRY = re.compile(r"stepsTest\('([A-Za-z0-9][A-Za-z0-9._-]{0,80})',.*?dir:\s*(\"(?:[^\"\\]|\\.)*\")", re.S)def _step_yamls(*spec_sets: dict[str, str]) -> dict[str, str]:"""The YAML of every steps scenario the specs run (stepsTest(id, tags, { dir })): the runner has no copy of thisserver's staging folder or library, so the steps travel with the attempt."""out: dict[str, str] = {}for specs in spec_sets:for text in specs.values():for cid, d in _STEPS_ENTRY.findall(text):f = Path(json.loads(d)) / f"{cid}.yaml"if f.is_file():out[f"{cid}.yaml"] = f.read_text(encoding="utf-8")return outdef _absolutize(report: Path, run_dir: Path) -> None:data = json.loads(report.read_text(encoding="utf-8"))def walk(suites):for s in suites or []:for sp in s.get("specs") or []:for t in sp.get("tests") or []:for r in t.get("results") or []:for a in r.get("attachments") or []:if a.get("path"):p = (run_dir / a["path"]).resolve()a["path"] = str(p) if p.is_relative_to(run_dir.resolve()) else Nonewalk(s.get("suites"))walk(data.get("suites"))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():name = info.filenameif info.is_dir():continueif name.startswith("run/"):dest = (run_dir / name[4:]).resolve()if not dest.is_relative_to(run_dir.resolve()): # a path that climbs out of the run directory is droppedcontinueelse:dest = {"report.json": out_file, "testdata-used.jsonl": testdata_used_file(out_file),"created.jsonl": log_dir / ledger, "playwright.log": log_dir / f"playwright-a{attempt}.log"}.get(name)if dest is None:continuedest.parent.mkdir(parents=True, exist_ok=True)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():_absolutize(out_file, run_dir)return Truereturn Falsedef runner_for(svc) -> tuple[str, str] | None:"""(runner address, token) when this server sends Fusion browsers to a remote runner (FPT_REMOTE_RUNNER_URL), else None.`svc` is anything with cfg and vault (Services, PodRegistry); its redactor, when it has one, learns the token."""base = (getattr(svc.cfg, "remote_runner_url", "") or "").strip()if not base:return Nonetoken = svc.vault.get("remote_runner.token") or ""if token and getattr(svc, "redactor", None):svc.redactor.add_secrets([token])return base.rstrip("/"), tokenSCREEN_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,poll: str | None = None):"""`poll` names a series of repeated status GETs: the egress gate audits them as one row a minute (end_polls ends it)."""return egress.service_request("remote_runner", method, base + path, allowed_base=base, json_body=json_body, headers=hdr,log_body=log_body, timeout=timeout, **({"poll": poll} if poll else {}))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 answerstops 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: BLE001log.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() + secondswhile True:if kill:kill()left = end - time.time()if left <= 0:returntime.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 anotherjob 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, Falsewhile 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() - firstif 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 = Truemsg = (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 = "", poll: str | None = None) -> 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}", poll=poll)except Exception: # noqa: BLE001 - a dropped poll is tried again; the job keeps running on the runnerreturn 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,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 (inventoriesand 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 {})}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 + 300seen, gone, st = 0, 0, {}polls = f"screens {jid}" # the status polls are audited as one row a minute (platform/egress.py)try:while True:time.sleep(poll_s)code, st = _status(egress, base, hdr, jid, f"?since={seen}", poll=polls)if code == 404:gone += 1if gone >= GONE_AFTER:raise RemoteRunnerError("the remote browser runner no longer knows this screen read: it restarted while it ran")continueif code:gone = 0new = st.get("lines") or []seen += len(new)if on_line:for line in new:on_line(line)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:breakif time.time() > deadline:_cancel(egress, base, hdr, jid)raise RemoteRunnerError(f"the remote browser runner did not finish reading the screens in {timeout_s // 60} minutes")finally:egress.end_polls(polls)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)out.mkdir(parents=True, exist_ok=True)lines: list[str] = []with zipfile.ZipFile(io.BytesIO(z.content)) as zf:for info in zf.infolist():name = info.filenameif name == "playwright.log":lines = zf.read(info).decode("utf-8", "replace").splitlines()elif name.startswith("out/") and "/" not in name[4:] and name.endswith((".json", ".values")) and not name[4:].startswith("."):dest = (out / name[4:]).resolve()if dest.is_relative_to(out.resolve()):dest.write_bytes(zf.read(info))return st.get("exit_code"), linesdef _write_atomic(d: Path, name: str, data: bytes) -> None:tmp = d / f".{name}.remote.tmp"try:tmp.write_bytes(data)tmp.replace(d / name)except OSError: # a reader holding the file (Windows): this frame is skippedtmp.unlink(missing_ok=True)def _pull_live(egress, base: str, hdr: dict, jid: str, live_dir: Path, seen: dict) -> None:"""Copy the runner's latest frame and status into this run's live folder (the Live panel reads it as for a localattempt). Frames only: never stored with the evidence, never sent anywhere else."""try:v = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/live", allowed_base=base, headers=hdr,log_body=None, timeout=20, poll=f"live {jid}").json()except Exception: # noqa: BLE001 - a missed frame is not an errorreturnif v.get("status"):_write_atomic(live_dir, "status.json", json.dumps(v["status"]).encode())if v.get("frame") and v.get("frame_at") != seen.get("frame_at"):seen["frame_at"] = v.get("frame_at")_write_atomic(live_dir, "frame.jpg", base64.b64decode(v["frame"]))if v.get("failed") and v["failed"] != seen.get("failed"):seen["failed"] = v["failed"]_write_atomic(live_dir, "failed.jpg", base64.b64decode(v["failed"]))# ------------------------------------------------------------------ the job an attempt follows, kept in the run folderdef 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 Nonereturn job if isinstance(job, dict) and JOB_ID.fullmatch(str(job.get("job_id") or "")) else Nonedef _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 toa 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_swhile True:code, st = _status(egress, base, hdr, jid)if code == 404:return True # nothing left to fetchif code == 200 and st.get("state") != "running" or time.time() > end:breaktime.sleep(3)z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)if z.status_code != 200:return Falsewith zipfile.ZipFile(io.BytesIO(z.content)) as zf:if "created.jsonl" in zf.namelist():_append(Path(log_dir) / ledger, zf.read("created.jsonl"))return Trueexcept Exception as e: # noqa: BLE001 - salvage is best effortlog.warning("could not fetch the records runner job %s made: %s", jid, type(e).__name__)return Falsedef 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): stopthe 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 LEDGERtry:run_dir = svc.run_dir(run_id)job = saved_job(run_dir)rt = runner_for(svc) if job else Noneif not job or not rt:return Falsebase, 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 Trueexcept Exception: # noqa: BLE001log.exception("could not release the runner job of run %s", run_id)return Falsedef _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 nolonger knows it (GONE_AFTER 404s in a row: it restarted and lost its jobs). The status polls and live frames areaudited as one row a minute each (platform/egress.py), ended here however the following ends."""seen: dict = {}gone = 0polls = f"attempt {jid}"try:while True:if kill:kill()time.sleep(poll_s)code, st = _status(egress, base, hdr, jid, poll=polls)if code == 404:gone += 1if gone >= GONE_AFTER:return Nonecontinueif code:gone = 0if live_dir and st.get("state") == "running":_pull_live(egress, base, hdr, jid, Path(live_dir), seen)if st.get("state") in ENDED:return stif time.time() > deadline:return {"state": "overdue"}finally:egress.end_polls(polls)egress.end_polls(f"live {jid}")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 arestart. 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 Noneif job.get("base_url") == base and job.get("pw_run_id") == pw_run_id and job.get("out_file") == str(out_file):return jobif 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 Nonedef 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 = "",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 passeskeep their own run folder and log. While the job runs its id is kept in log_dir (the run folder): a resumed run whoseserver 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 LEDGERfrom ..platform.failures import ExecutionErrorbase = base_url.rstrip("/")hdr = {"Authorization": f"Bearer {token}"}pw_run_id = f"fpt-{run_id}-a{attempt}{tag}"out_file, log_dir = Path(out_file), Path(log_dir)note = on_event or (lambda _msg: None)live = Noneif live_dir: # Live panel: the runner's browser hook writes frames there, this side copies them into the runfrom ..platform import liveviewmeta = {"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)live = {"attempt": meta["attempt_key"]}poll_s = min(poll_s, 2.0)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: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 themif _salvage(egress, base, hdr, jid, log_dir, LEDGER, wait_s=30):_drop_job(log_dir, jid)raiseif 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 = Nonecontinueraise 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_idgot = _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 againnote("The browser runner's job from before the restart ended without results: starting the pass again.")job = Nonecontinueif 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}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488"""A browser attempt run on the remote runner (automation/remote_runner/server.py) instead of this host.Used for Oracle Fusion pods when FPT_REMOTE_RUNNER_URL is set (and the runner token is in the vault asremote_runner.token, or FPT_SECRET_REMOTE_RUNNER_TOKEN): this host may sit on a network Oracle's edge refuses. Theattempt goes out through the egress gate (https, the runner's host only; the audit log never sees the password), ispolled, 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 theledger 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. Theid of the job an attempt follows is kept in the run folder (remote-job.json) until its results are in, so a server thatrestarts mid-attempt and is resumed follows the same job again instead of starting a second one, and a runner thatrestarted (it no longer knows the job, or reports it "lost") fails the attempt in seconds instead of at its deadline."""from __future__ import annotationsimport base64import ioimport jsonimport loggingimport reimport timeimport zipfilefrom pathlib import Pathfrom .playwright import AUTOMATION, testdata_used_filelog = 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", "FPT_SIGN_IN_MODE", "FPT_HEALS")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 cancelledENDED = ("done", "cancelled", "failed", "lost")GONE_AFTER = 2 # consecutive 404s for a job: the runner restarted and no longer knows itBUSY_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):passdef _specs(d: Path | None) -> dict[str, str]:if not d or not Path(d).is_dir():return {}return {p.name: p.read_text(encoding="utf-8") for p in Path(d).glob("*.spec.ts")}_STEPS_ENTRY = re.compile(r"stepsTest\('([A-Za-z0-9][A-Za-z0-9._-]{0,80})',.*?dir:\s*(\"(?:[^\"\\]|\\.)*\")", re.S)def _step_yamls(*spec_sets: dict[str, str]) -> dict[str, str]:"""The YAML of every steps scenario the specs run (stepsTest(id, tags, { dir })): the runner has no copy of thisserver's staging folder or library, so the steps travel with the attempt."""out: dict[str, str] = {}for specs in spec_sets:for text in specs.values():for cid, d in _STEPS_ENTRY.findall(text):f = Path(json.loads(d)) / f"{cid}.yaml"if f.is_file():out[f"{cid}.yaml"] = f.read_text(encoding="utf-8")return outdef _absolutize(report: Path, run_dir: Path) -> None:data = json.loads(report.read_text(encoding="utf-8"))def walk(suites):for s in suites or []:for sp in s.get("specs") or []:for t in sp.get("tests") or []:for r in t.get("results") or []:for a in r.get("attachments") or []:if a.get("path"):p = (run_dir / a["path"]).resolve()a["path"] = str(p) if p.is_relative_to(run_dir.resolve()) else Nonewalk(s.get("suites"))walk(data.get("suites"))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():name = info.filenameif info.is_dir():continueif name.startswith("run/"):dest = (run_dir / name[4:]).resolve()if not dest.is_relative_to(run_dir.resolve()): # a path that climbs out of the run directory is droppedcontinueelse:dest = {"report.json": out_file, "testdata-used.jsonl": testdata_used_file(out_file),"created.jsonl": log_dir / ledger, "playwright.log": log_dir / f"playwright-a{attempt}.log"}.get(name)if dest is None:continuedest.parent.mkdir(parents=True, exist_ok=True)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():_absolutize(out_file, run_dir)return Truereturn Falsedef runner_for(svc) -> tuple[str, str] | None:"""(runner address, token) when this server sends Fusion browsers to a remote runner (FPT_REMOTE_RUNNER_URL), else None.`svc` is anything with cfg and vault (Services, PodRegistry); its redactor, when it has one, learns the token."""base = (getattr(svc.cfg, "remote_runner_url", "") or "").strip()if not base:return Nonetoken = svc.vault.get("remote_runner.token") or ""if token and getattr(svc, "redactor", None):svc.redactor.add_secrets([token])return base.rstrip("/"), tokenSCREEN_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,poll: str | None = None):"""`poll` names a series of repeated status GETs: the egress gate audits them as one row a minute (end_polls ends it)."""return egress.service_request("remote_runner", method, base + path, allowed_base=base, json_body=json_body, headers=hdr,log_body=log_body, timeout=timeout, **({"poll": poll} if poll else {}))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 answerstops 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: BLE001log.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() + secondswhile True:if kill:kill()left = end - time.time()if left <= 0:returntime.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 anotherjob 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, Falsewhile 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() - firstif 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 = Truemsg = (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 = "", poll: str | None = None) -> 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}", poll=poll)except Exception: # noqa: BLE001 - a dropped poll is tried again; the job keeps running on the runnerreturn 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,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 (inventoriesand 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 {})}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 + 300seen, gone, st = 0, 0, {}polls = f"screens {jid}" # the status polls are audited as one row a minute (platform/egress.py)try:while True:time.sleep(poll_s)code, st = _status(egress, base, hdr, jid, f"?since={seen}", poll=polls)if code == 404:gone += 1if gone >= GONE_AFTER:raise RemoteRunnerError("the remote browser runner no longer knows this screen read: it restarted while it ran")continueif code:gone = 0new = st.get("lines") or []seen += len(new)if on_line:for line in new:on_line(line)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:breakif time.time() > deadline:_cancel(egress, base, hdr, jid)raise RemoteRunnerError(f"the remote browser runner did not finish reading the screens in {timeout_s // 60} minutes")finally:egress.end_polls(polls)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)out.mkdir(parents=True, exist_ok=True)lines: list[str] = []with zipfile.ZipFile(io.BytesIO(z.content)) as zf:for info in zf.infolist():name = info.filenameif name == "playwright.log":lines = zf.read(info).decode("utf-8", "replace").splitlines()elif name.startswith("out/") and "/" not in name[4:] and name.endswith((".json", ".values")) and not name[4:].startswith("."):dest = (out / name[4:]).resolve()if dest.is_relative_to(out.resolve()):dest.write_bytes(zf.read(info))return st.get("exit_code"), linesdef _write_atomic(d: Path, name: str, data: bytes) -> None:tmp = d / f".{name}.remote.tmp"try:tmp.write_bytes(data)tmp.replace(d / name)except OSError: # a reader holding the file (Windows): this frame is skippedtmp.unlink(missing_ok=True)def _pull_live(egress, base: str, hdr: dict, jid: str, live_dir: Path, seen: dict) -> None:"""Copy the runner's latest frame and status into this run's live folder (the Live panel reads it as for a localattempt). Frames only: never stored with the evidence, never sent anywhere else."""try:v = egress.service_request("remote_runner", "GET", f"{base}/v1/attempts/{jid}/live", allowed_base=base, headers=hdr,log_body=None, timeout=20, poll=f"live {jid}").json()except Exception: # noqa: BLE001 - a missed frame is not an errorreturnif v.get("status"):_write_atomic(live_dir, "status.json", json.dumps(v["status"]).encode())if v.get("frame") and v.get("frame_at") != seen.get("frame_at"):seen["frame_at"] = v.get("frame_at")_write_atomic(live_dir, "frame.jpg", base64.b64decode(v["frame"]))if v.get("failed") and v["failed"] != seen.get("failed"):seen["failed"] = v["failed"]_write_atomic(live_dir, "failed.jpg", base64.b64decode(v["failed"]))# ------------------------------------------------------------------ the job an attempt follows, kept in the run folderdef 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 Nonereturn job if isinstance(job, dict) and JOB_ID.fullmatch(str(job.get("job_id") or "")) else Nonedef _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 toa 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_swhile True:code, st = _status(egress, base, hdr, jid)if code == 404:return True # nothing left to fetchif code == 200 and st.get("state") != "running" or time.time() > end:breaktime.sleep(3)z = _call(egress, base, hdr, "GET", f"/v1/attempts/{jid}/bundle", timeout=300)if z.status_code != 200:return Falsewith zipfile.ZipFile(io.BytesIO(z.content)) as zf:if "created.jsonl" in zf.namelist():_append(Path(log_dir) / ledger, zf.read("created.jsonl"))return Trueexcept Exception as e: # noqa: BLE001 - salvage is best effortlog.warning("could not fetch the records runner job %s made: %s", jid, type(e).__name__)return Falsedef 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): stopthe 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 LEDGERtry:run_dir = svc.run_dir(run_id)job = saved_job(run_dir)rt = runner_for(svc) if job else Noneif not job or not rt:return Falsebase, 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 Trueexcept Exception: # noqa: BLE001log.exception("could not release the runner job of run %s", run_id)return Falsedef _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 nolonger knows it (GONE_AFTER 404s in a row: it restarted and lost its jobs). The status polls and live frames areaudited as one row a minute each (platform/egress.py), ended here however the following ends."""seen: dict = {}gone = 0polls = f"attempt {jid}"try:while True:if kill:kill()time.sleep(poll_s)code, st = _status(egress, base, hdr, jid, poll=polls)if code == 404:gone += 1if gone >= GONE_AFTER:return Nonecontinueif code:gone = 0if live_dir and st.get("state") == "running":_pull_live(egress, base, hdr, jid, Path(live_dir), seen)if st.get("state") in ENDED:return stif time.time() > deadline:return {"state": "overdue"}finally:egress.end_polls(polls)egress.end_polls(f"live {jid}")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 arestart. 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 Noneif job.get("base_url") == base and job.get("pw_run_id") == pw_run_id and job.get("out_file") == str(out_file):return jobif 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 Nonedef 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 = "",busy_wait_s: float = BUSY_WAIT_S, on_event=None, storage_state: dict | None = None) -> dict:"""One attempt on the remote runner. storage_state: the session a person signed in (assisted sign-in); it travelsin the attempt's body only (never in the audit log), the runner keeps it for the attempt and deletes it after. `tag` names a pass of the attempt (one per test user, one per chunk) so passeskeep their own run folder and log. While the job runs its id is kept in log_dir (the run folder): a resumed run whoseserver 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 LEDGERfrom ..platform.failures import ExecutionErrorbase = base_url.rstrip("/")hdr = {"Authorization": f"Bearer {token}"}pw_run_id = f"fpt-{run_id}-a{attempt}{tag}"out_file, log_dir = Path(out_file), Path(log_dir)note = on_event or (lambda _msg: None)live = Noneif live_dir: # Live panel: the runner's browser hook writes frames there, this side copies them into the runfrom ..platform import liveviewmeta = {"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)live = {"attempt": meta["attempt_key"]}poll_s = min(poll_s, 2.0)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"])if storage_state is not None:body["storage_state"] = storage_statejid = _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"]), "signed_in_session": storage_state is not None},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: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 themif _salvage(egress, base, hdr, jid, log_dir, LEDGER, wait_s=30):_drop_job(log_dir, jid)raiseif 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 = Nonecontinueraise 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_idgot = _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 againnote("The browser runner's job from before the restart ended without results: starting the pass again.")job = Nonecontinueif 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}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282"""Screen capture adapter: records a Fusion screen's inventory (field labels and kinds, buttons, menus, sections) byrunning automation/scripts/capture-fusion.ts against a pod, and reads the stored inventories in tests/screens/.The model step-writer reads these files to write steps with the screen's real labels. Contract (one file per task):tests/screens/<slug>.json, slug = task lower-cased with every run of non-alphanumerics turned into '-'.{"task", "captured_at", "source": "captured", "pod_host", "sections", "fields": [{label, kind, required, section}],"line_fields": [{label, kind, required}], "buttons", "menus": {menu: [entries]}, "tables": {section: [columns]}}Privacy: an inventory holds Oracle's labels only. A file carrying values, list options, URLs or the like is refused."""from __future__ import annotationsimport jsonimport osimport reimport subprocessimport sysimport threadingfrom pathlib import Pathfrom ..config import ROOTfrom ..platform import procsAUTOMATION = ROOT / "automation"TSX_CLI = AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"SCRIPT = "scripts/capture-fusion.ts"FORBIDDEN_KEYS = {"value", "values", "options", "option", "default", "selected", "url", "href", "user", "username"}FIELD_KINDS = {"text", "list", "lov", "date", "number", "checkbox", "textarea"}_popen = subprocess.Popen # replaced by tests (no browser, no network)_busy = threading.Lock() # one browser at a timeclass ScreenError(ValueError):def __init__(self, code: str, msg: str, status: int = 422):super().__init__(msg)self.code, self.status = code, statusdef screens_dir() -> Path:return Path(os.environ.get("FPT_SCREENS_DIR") or ROOT / "tests" / "screens")def slug(task: str) -> str:return re.sub(r"[^a-z0-9]+", "-", task.lower()).strip("-")def normalize_task(task: str) -> str:"""'Area > Page > Task' with single spaces around '>' (the form the step runner's open_task takes)."""parts = [p.strip() for p in (task or "").split(">") if p.strip()]if len(parts) != 3 or any(len(p) > 80 for p in parts):raise ScreenError("BAD_TASK", 'give the task as "Area > Page > Task", e.g. "Payables > Invoices > Create Invoice"')return " > ".join(parts)def check_no_data(inv, path: str = "$") -> None:"""Raise ScreenError when an inventory carries anything but labels (forbidden keys, URLs)."""if isinstance(inv, list):for i, v in enumerate(inv):check_no_data(v, f"{path}[{i}]")elif isinstance(inv, dict):for k, v in inv.items():if str(k).lower() in FORBIDDEN_KEYS:raise ScreenError("PRIVACY", f"screen inventory must not hold {k!r} (at {path})")check_no_data(v, f"{path}.{k}")elif isinstance(inv, str) and re.search(r"https?://|www\.", inv, re.I):raise ScreenError("PRIVACY", f"screen inventory must not hold a URL (at {path})")def validate(inv: dict) -> dict:check_no_data(inv)for k in ("task", "captured_at", "source", "sections", "fields", "buttons", "menus"):if k not in inv:raise ScreenError("BAD_INVENTORY", f"screen inventory has no {k!r}")for f in [*inv.get("fields", []), *inv.get("line_fields", [])]:if f.get("kind") not in FIELD_KINDS:raise ScreenError("BAD_INVENTORY", f"field {f.get('label')!r} has unknown kind {f.get('kind')!r}")inv.setdefault("line_fields", [])inv.setdefault("tables", {})return invdef command(task: str, out_dir: Path) -> list[str]:return ["node", str(TSX_CLI), SCRIPT, task, "--out-dir", str(out_dir)]def _scrub(text: str, env: dict) -> str:for k in ("FUSION_PASSWORD", "FUSION_USERNAME"):if env.get(k):text = text.replace(env[k], "***")return textdef _remote(svc):"""(runner address, token) when Fusion browsers run on the remote runner (FPT_REMOTE_RUNNER_URL), else None."""if svc is None:return Nonefrom .remote_runner import runner_forreturn 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_Stry:return 60.0 * float(svc.cfg.remote_runner_busy_wait_minutes)except (AttributeError, TypeError, ValueError):return BUSY_WAIT_Sdef 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 aremote runner (svc given, FPT_REMOTE_RUNNER_URL set) the browser runs there, since Oracle's edge may refuse this host."""task = normalize_task(task)if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to capture a screen", 409)if not _busy.acquire(blocking=False):raise ScreenError("CAPTURE_BUSY", "a screen capture is already running; one browser at a time", 409)try:out = Path(out_dir or screens_dir())out.mkdir(parents=True, exist_ok=True)remote = _remote(svc)if remote:from .remote_runner import RemoteRunnerError, run_screens_remotetry: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 Nonetext = _scrub("\n".join(lines), env)else:child_env = procs.child_env(**{k: env[k] for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")})for k in ("FPT_LIVE_VIEW_DIR", "PW_LOCATOR_OVERRIDES"):child_env.pop(k, None)p = _popen(command(task, out), cwd=str(AUTOMATION), env=child_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,**procs.popen_kwargs())procs.register(p, f"screen-capture:{slug(task)}")try:stdout, _ = p.communicate(timeout=timeout_s)except subprocess.TimeoutExpired:procs.kill_tree(p.pid)raise ScreenError("CAPTURE_TIMEOUT", f"screen capture of {task} did not finish in {timeout_s}s", 504) from Nonefinally:procs.unregister(p)rc = p.returncodetext = _scrub((stdout or b"").decode("utf-8", "replace") if isinstance(stdout, bytes) else (stdout or ""), env)m = re.findall(r"^CAPTURED (.+)$", text, re.M)if rc != 0 or not m:tail = " | ".join(line for line in text.strip().splitlines()[-4:])raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed (exit {rc}): {tail[:400]}", 502)f = out / f"{slug(task)}.json"try:inv = validate(json.loads(f.read_text(encoding="utf-8")))except ScreenError:f.unlink(missing_ok=True) # never keep a file that breaks the privacy ruleraisereturn invfinally:_busy.release()EXPLORE_SCRIPT = "scripts/explore-fusion.ts"def explore(plan: dict, env: dict, out_dir: Path, *, timeout_s: int = 5400, on_line=None, svc=None) -> dict:"""Run the explorer (automation/scripts/explore-fusion.ts) on the pod in `env`: for each area of `plan`, list thetasks of its work areas and capture the chosen ones into `out_dir`. Returns {"areas": [...]} with only the capturedfiles that pass the privacy check (any other is deleted). Nothing is saved on the pod. With a remote runner (svcgiven, FPT_REMOTE_RUNNER_URL set) the browser runs there, since Oracle's edge may refuse this host."""if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to read its screens", 409)if not _busy.acquire(blocking=False):raise ScreenError("CAPTURE_BUSY", "a screen capture is already running; one browser at a time", 409)try:out = Path(out_dir)out.mkdir(parents=True, exist_ok=True)plan_file = out / "_plan.json"remote = _remote(svc)if remote:from .remote_runner import RemoteRunnerError, run_screens_remotedef relay(raw: str) -> None:line = _scrub(raw, env).rstrip()if on_line and line.startswith("[explore]"):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, 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 Nonelines = [_scrub(line, env).rstrip() for line in raw_lines]else:plan_file.write_text(json.dumps(plan), encoding="utf-8")child_env = procs.child_env(**{k: env[k] for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA") if env.get(k)})for k in ("FPT_LIVE_VIEW_DIR", "PW_LOCATOR_OVERRIDES"):child_env.pop(k, None)p = _popen(["node", str(TSX_CLI), EXPLORE_SCRIPT, str(plan_file), "--out-dir", str(out)], cwd=str(AUTOMATION), env=child_env,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **procs.popen_kwargs())procs.register(p, "screen-explore")lines = []try:timer = threading.Timer(timeout_s, lambda: procs.kill_tree(p.pid))timer.start()for raw in p.stdout:line = _scrub(raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw), env).rstrip()lines.append(line)if on_line and line.startswith("[explore]"):on_line(line[len("[explore] "):])p.wait()timer.cancel()finally:procs.unregister(p)rc = p.returncodefound = next((l[len("EXPLORED "):] for l in reversed(lines) if l.startswith("EXPLORED ")), None)# each area is reported as it finishes ("AREA <json>"): a read cut off half-way keeps the areas it finisheddone = [json.loads(l[len("AREA "):]) for l in lines if l.startswith("AREA ")]if rc != 0 or not found:tail = " | ".join(lines[-4:])if not done:raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed (exit {rc}): {tail[:400]}", 502)result = {"areas": done, "incomplete": f"the read stopped before the end (exit {rc}); the areas it finished are kept"}else:result = json.loads(found)for a in result.get("areas") or []:kept = []choices: dict[str, list[str]] = {}for c in a.get("captured") or []:# the choices its lists offer the test user ("<slug>.values", next to the inventory): returned once to be# kept as the pod's test data, then removed (the inventory folder holds labels only)vf = out / f"{slug(c['task'])}.values"if vf.is_file():try:for label, vals in (json.loads(vf.read_text(encoding="utf-8")) or {}).items():if isinstance(vals, list):choices.setdefault(str(label)[:120], [str(v)[:200] for v in vals[:5] if str(v).strip()])except (OSError, ValueError):passvf.unlink(missing_ok=True)f = out / f"{slug(c['task'])}.json"try:validate(json.loads(f.read_text(encoding="utf-8")))kept.append({"task": c["task"], "slug": f.stem})except (OSError, ValueError, ScreenError) as e:f.unlink(missing_ok=True) # never keep a file that breaks the privacy rulea.setdefault("failed", []).append({"task": c["task"], "error": f"not kept: {e}"})a["captured"] = keptif choices:a["choices"] = choicesplan_file.unlink(missing_ok=True)return resultfinally:_busy.release()def list_screens(directory: Path | None = None) -> list[dict]:"""A summary of every stored inventory (no labels), newest task name order."""out = []for f in sorted(Path(directory or screens_dir()).glob("*.json")):try:inv = json.loads(f.read_text(encoding="utf-8"))except (OSError, ValueError):continueout.append({"slug": f.stem, "task": inv.get("task", ""), "captured_at": inv.get("captured_at"),"source": inv.get("source", "captured"), "pod_host": inv.get("pod_host"),"fields": len(inv.get("fields") or []), "line_fields": len(inv.get("line_fields") or []),"buttons": len(inv.get("buttons") or []), "menus": len(inv.get("menus") or {})})return outdef load_screen(task_or_slug: str, directory: Path | None = None) -> dict | None:"""The inventory of a task ("Payables > Invoices > Create Invoice") or slug; None when not captured yet."""s = slug(task_or_slug)if not s:return Nonef = Path(directory or screens_dir()) / f"{s}.json"if not f.is_file():return Nonereturn validate(json.loads(f.read_text(encoding="utf-8")))if __name__ == "__main__": # python -m coworker.adapters.screens "Payables > Invoices > Create Invoice"print(json.dumps(load_screen(" ".join(sys.argv[1:])), indent=2))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313"""Screen capture adapter: records a Fusion screen's inventory (field labels and kinds, buttons, menus, sections) byrunning automation/scripts/capture-fusion.ts against a pod, and reads the stored inventories in tests/screens/.The model step-writer reads these files to write steps with the screen's real labels. Contract (one file per task):tests/screens/<slug>.json, slug = task lower-cased with every run of non-alphanumerics turned into '-'.{"task", "captured_at", "source": "captured", "pod_host", "sections", "fields": [{label, kind, required, section}],"line_fields": [{label, kind, required}], "buttons", "menus": {menu: [entries]}, "tables": {section: [columns]}}Privacy: an inventory holds Oracle's labels only. A file carrying values, list options, URLs or the like is refused."""from __future__ import annotationsimport jsonimport loggingimport osimport reimport subprocessimport sysimport threadingfrom pathlib import Pathfrom ..config import ROOTfrom ..platform import procsAUTOMATION = ROOT / "automation"TSX_CLI = AUTOMATION / "node_modules" / "tsx" / "dist" / "cli.mjs"SCRIPT = "scripts/capture-fusion.ts"FORBIDDEN_KEYS = {"value", "values", "options", "option", "default", "selected", "url", "href", "user", "username"}FIELD_KINDS = {"text", "list", "lov", "date", "number", "checkbox", "textarea"}_popen = subprocess.Popen # replaced by tests (no browser, no network)_busy = threading.Lock() # one browser at a timelog = logging.getLogger("fpt.screens")class ScreenError(ValueError):def __init__(self, code: str, msg: str, status: int = 422):super().__init__(msg)self.code, self.status = code, statusdef screens_dir() -> Path:return Path(os.environ.get("FPT_SCREENS_DIR") or ROOT / "tests" / "screens")def slug(task: str) -> str:return re.sub(r"[^a-z0-9]+", "-", task.lower()).strip("-")def normalize_task(task: str) -> str:"""'Area > Page > Task' with single spaces around '>' (the form the step runner's open_task takes)."""parts = [p.strip() for p in (task or "").split(">") if p.strip()]if len(parts) != 3 or any(len(p) > 80 for p in parts):raise ScreenError("BAD_TASK", 'give the task as "Area > Page > Task", e.g. "Payables > Invoices > Create Invoice"')return " > ".join(parts)def check_no_data(inv, path: str = "$") -> None:"""Raise ScreenError when an inventory carries anything but labels (forbidden keys, URLs)."""if isinstance(inv, list):for i, v in enumerate(inv):check_no_data(v, f"{path}[{i}]")elif isinstance(inv, dict):for k, v in inv.items():if str(k).lower() in FORBIDDEN_KEYS:raise ScreenError("PRIVACY", f"screen inventory must not hold {k!r} (at {path})")check_no_data(v, f"{path}.{k}")elif isinstance(inv, str) and re.search(r"https?://|www\.", inv, re.I):raise ScreenError("PRIVACY", f"screen inventory must not hold a URL (at {path})")def validate(inv: dict) -> dict:check_no_data(inv)for k in ("task", "captured_at", "source", "sections", "fields", "buttons", "menus"):if k not in inv:raise ScreenError("BAD_INVENTORY", f"screen inventory has no {k!r}")for f in [*inv.get("fields", []), *inv.get("line_fields", [])]:if f.get("kind") not in FIELD_KINDS:raise ScreenError("BAD_INVENTORY", f"field {f.get('label')!r} has unknown kind {f.get('kind')!r}")inv.setdefault("line_fields", [])inv.setdefault("tables", {})return invdef command(task: str, out_dir: Path) -> list[str]:return ["node", str(TSX_CLI), SCRIPT, task, "--out-dir", str(out_dir)]def _scrub(text: str, env: dict) -> str:for k in ("FUSION_PASSWORD", "FUSION_USERNAME"):if env.get(k):text = text.replace(env[k], "***")return textdef _remote(svc):"""(runner address, token) when Fusion browsers run on the remote runner (FPT_REMOTE_RUNNER_URL), else None."""if svc is None:return Nonefrom .remote_runner import runner_forreturn 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_Stry:return 60.0 * float(svc.cfg.remote_runner_busy_wait_minutes)except (AttributeError, TypeError, ValueError):return BUSY_WAIT_Sdef 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 aremote runner (svc given, FPT_REMOTE_RUNNER_URL set) the browser runs there, since Oracle's edge may refuse this host."""task = normalize_task(task)if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to capture a screen", 409)if not _busy.acquire(blocking=False):raise ScreenError("CAPTURE_BUSY", "a screen capture is already running; one browser at a time", 409)try:out = Path(out_dir or screens_dir())out.mkdir(parents=True, exist_ok=True)remote = _remote(svc)if remote:from .remote_runner import RemoteRunnerError, run_screens_remotetry: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 Nonetext = _scrub("\n".join(lines), env)else:child_env = procs.child_env(**{k: env[k] for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")})for k in ("FPT_LIVE_VIEW_DIR", "PW_LOCATOR_OVERRIDES"):child_env.pop(k, None)p = _popen(command(task, out), cwd=str(AUTOMATION), env=child_env, stdout=subprocess.PIPE, stderr=subprocess.STDOUT,**procs.popen_kwargs())procs.register(p, f"screen-capture:{slug(task)}")try:stdout, _ = p.communicate(timeout=timeout_s)except subprocess.TimeoutExpired:procs.kill_tree(p.pid)raise ScreenError("CAPTURE_TIMEOUT", f"screen capture of {task} did not finish in {timeout_s}s", 504) from Nonefinally:procs.unregister(p)rc = p.returncodetext = _scrub((stdout or b"").decode("utf-8", "replace") if isinstance(stdout, bytes) else (stdout or ""), env)m = re.findall(r"^CAPTURED (.+)$", text, re.M)if rc != 0 or not m:tail = " | ".join(line for line in text.strip().splitlines()[-4:])raise ScreenError("CAPTURE_FAILED", f"screen capture of {task} failed (exit {rc}): {tail[:400]}", 502)f = out / f"{slug(task)}.json"try:inv = validate(json.loads(f.read_text(encoding="utf-8")))except ScreenError:f.unlink(missing_ok=True) # never keep a file that breaks the privacy ruleraisereturn invfinally:_busy.release()EXPLORE_SCRIPT = "scripts/explore-fusion.ts"def _area_line(line: str) -> dict | None:"""The area an "AREA <json>" line of the explorer reports, or None when the line is cut or not an area."""try:a = json.loads(line[len("AREA "):])except ValueError:return Nonereturn a if isinstance(a, dict) and a.get("code") else Nonedef _keep_area(a: dict, out: Path) -> dict:"""One area as the explorer reported it, with only the captured files that pass the privacy check (any other isdeleted) and the choices its lists offered ("<slug>.values", next to the inventory: returned once to be kept as thepod's test data, then removed, since the inventory folder holds labels only)."""kept = []choices: dict[str, list[str]] = {}for c in a.get("captured") or []:vf = out / f"{slug(c['task'])}.values"if vf.is_file():try:for label, vals in (json.loads(vf.read_text(encoding="utf-8")) or {}).items():if isinstance(vals, list):choices.setdefault(str(label)[:120], [str(v)[:200] for v in vals[:5] if str(v).strip()])except (OSError, ValueError):passvf.unlink(missing_ok=True)f = out / f"{slug(c['task'])}.json"try:validate(json.loads(f.read_text(encoding="utf-8")))kept.append({"task": c["task"], "slug": f.stem})except (OSError, ValueError, ScreenError) as e:f.unlink(missing_ok=True) # never keep a file that breaks the privacy rulea.setdefault("failed", []).append({"task": c["task"], "error": f"not kept: {e}"})a["captured"] = keptif choices:a["choices"] = choicesreturn adef explore(plan: dict, env: dict, out_dir: Path, *, timeout_s: int = 5400, on_line=None, on_area=None, svc=None) -> dict:"""Run the explorer (automation/scripts/explore-fusion.ts) on the pod in `env`: for each area of `plan`, list thetasks of its work areas and capture the chosen ones into `out_dir`. Returns {"areas": [...]} with only the capturedfiles that pass the privacy check (any other is deleted). Nothing is saved on the pod. With a remote runner (svcgiven, FPT_REMOTE_RUNNER_URL set) the browser runs there, since Oracle's edge may refuse this host.on_area(area) gets each area as soon as the explorer finishes it (its "AREA <json>" line), so the caller can keep itwhile the other areas are still read. Only a local read can: a remote one sends its files back when its job ends."""if not all(env.get(k) for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD")):raise ScreenError("NO_CREDENTIALS", "the pod's address and test user are needed to read its screens", 409)if not _busy.acquire(blocking=False):raise ScreenError("CAPTURE_BUSY", "a screen capture is already running; one browser at a time", 409)try:out = Path(out_dir)out.mkdir(parents=True, exist_ok=True)plan_file = out / "_plan.json"finished: dict[str, dict] = {} # areas already kept as their "AREA" line came (local reads)remote = _remote(svc)if remote:from .remote_runner import RemoteRunnerError, run_screens_remotedef relay(raw: str) -> None:line = _scrub(raw, env).rstrip()if on_line and line.startswith("[explore]"):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, 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 Nonelines = [_scrub(line, env).rstrip() for line in raw_lines]else:plan_file.write_text(json.dumps(plan), encoding="utf-8")child_env = procs.child_env(**{k: env[k] for k in ("FUSION_BASE_URL", "FUSION_USERNAME", "FUSION_PASSWORD", "FUSION_TESTDATA") if env.get(k)})for k in ("FPT_LIVE_VIEW_DIR", "PW_LOCATOR_OVERRIDES"):child_env.pop(k, None)p = _popen(["node", str(TSX_CLI), EXPLORE_SCRIPT, str(plan_file), "--out-dir", str(out)], cwd=str(AUTOMATION), env=child_env,stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **procs.popen_kwargs())procs.register(p, "screen-explore")lines = []try:timer = threading.Timer(timeout_s, lambda: procs.kill_tree(p.pid))timer.start()for raw in p.stdout:line = _scrub(raw.decode("utf-8", "replace") if isinstance(raw, bytes) else str(raw), env).rstrip()lines.append(line)if on_line and line.startswith("[explore]"):on_line(line[len("[explore] "):])elif line.startswith("AREA "):# the area's files are written before its line: kept now, not when the slowest area endsa = _area_line(line)if a:finished[a["code"]] = _keep_area(a, out)if on_area:try:on_area(finished[a["code"]])except Exception as e: # noqa: BLE001 - recording one area never stops the readlog.warning("area %s read but not recorded yet: %s", a["code"], e)p.wait()timer.cancel()finally:procs.unregister(p)rc = p.returncodefound = next((l[len("EXPLORED "):] for l in reversed(lines) if l.startswith("EXPLORED ")), None)# each area is reported as it finishes ("AREA <json>"): a read cut off half-way keeps the areas it finisheddone = [a for a in (_area_line(l) for l in lines if l.startswith("AREA ")) if a]if rc != 0 or not found:tail = " | ".join(lines[-4:])if not done:raise ScreenError("EXPLORE_FAILED", f"reading the pod's screens failed (exit {rc}): {tail[:400]}", 502)result = {"areas": done, "incomplete": f"the read stopped before the end (exit {rc}); the areas it finished are kept"}else:result = json.loads(found)# an area kept as it finished has had its list choices taken already (their files are gone): that copy is usedresult["areas"] = [finished.get(a.get("code")) or _keep_area(a, out) for a in result.get("areas") or []]plan_file.unlink(missing_ok=True)return resultfinally:_busy.release()def list_screens(directory: Path | None = None) -> list[dict]:"""A summary of every stored inventory (no labels), newest task name order."""out = []for f in sorted(Path(directory or screens_dir()).glob("*.json")):try:inv = json.loads(f.read_text(encoding="utf-8"))except (OSError, ValueError):continueout.append({"slug": f.stem, "task": inv.get("task", ""), "captured_at": inv.get("captured_at"),"source": inv.get("source", "captured"), "pod_host": inv.get("pod_host"),"fields": len(inv.get("fields") or []), "line_fields": len(inv.get("line_fields") or []),"buttons": len(inv.get("buttons") or []), "menus": len(inv.get("menus") or {})})return outdef load_screen(task_or_slug: str, directory: Path | None = None) -> dict | None:"""The inventory of a task ("Payables > Invoices > Create Invoice") or slug; None when not captured yet."""s = slug(task_or_slug)if not s:return Nonef = Path(directory or screens_dir()) / f"{s}.json"if not f.is_file():return Nonereturn validate(json.loads(f.read_text(encoding="utf-8")))if __name__ == "__main__": # python -m coworker.adapters.screens "Payables > Invoices > Create Invoice"print(json.dumps(load_screen(" ".join(sys.argv[1:])), indent=2))
123456789101112131415161718192021222324252627282930313233343536373839404142"""Wraps triage/classifier.py (the deterministic verdict). Review items follow the legacy rule exactly:failed and (needs_review or real_defect) -> confirm; flaky -> owner (QA C3)."""from __future__ import annotationsimport jsonfrom pathlib import Pathfrom .legacy import classifierdef triage(merged: Path, cases_dir: Path | None) -> dict:return classifier().triage(merged, cases_dir if cases_dir and Path(cases_dir).exists() else None)def review_items(tri: dict) -> list[dict]:items = []for r in tri["records"]:cid, cl = r.get("case_id") or r["full_title"], r.get("classification") or {}if r["outcome"] == "failed" and (cl.get("needs_review") or cl.get("category") == "real_defect"):items.append({"case_id": cid, "ask": "confirm", "category": cl.get("category"),"confidence": cl.get("confidence"), "evidence": cl.get("evidence"), "similar": []})elif r["outcome"] == "flaky":items.append({"case_id": cid, "ask": "owner", "category": None, "confidence": None, "evidence": None, "similar": []})return itemsdef verdicts(tri: dict) -> dict[str, dict]:out = {}for r in tri["records"]:if r["outcome"] not in ("failed", "flaky"):continuecid, cl = r.get("case_id") or r["full_title"], r.get("classification") or {}out[cid] = {"case_id": cid, "category": cl.get("category", "unclassified"), "confidence": float(cl.get("confidence") or 0),"needs_review": bool(cl.get("needs_review")), "evidence": cl.get("evidence") or [], "llm_hint": None,"similar": [], "outcome": r["outcome"], "message": (r.get("errors") or [{}])[0].get("message", "")[:2000]if r.get("errors") else ""}return outdef write(tri: dict, path: Path) -> Path:path.write_text(json.dumps(tri, indent=2, default=str), encoding="utf-8")return path1234567891011121314151617181920212223242526272829303132333435363738394041424344"""Wraps triage/classifier.py (the deterministic verdict). Review items follow the legacy rule exactly:failed and (needs_review or real_defect) -> confirm; flaky -> owner (QA C3)."""from __future__ import annotationsimport jsonfrom pathlib import Pathfrom .legacy import classifierdef triage(merged: Path, cases_dir: Path | None) -> dict:return classifier().triage(merged, cases_dir if cases_dir and Path(cases_dir).exists() else None)def review_items(tri: dict) -> list[dict]:items = []for r in tri["records"]:cid, cl = r.get("case_id") or r["full_title"], r.get("classification") or {}if r["outcome"] == "failed" and (cl.get("needs_review") or cl.get("category") == "real_defect"):items.append({"case_id": cid, "ask": "confirm", "category": cl.get("category"),"confidence": cl.get("confidence"), "evidence": cl.get("evidence"), "similar": []})elif r["outcome"] == "flaky":items.append({"case_id": cid, "ask": "owner", "category": None, "confidence": None, "evidence": None, "similar": []})return itemsdef verdicts(tri: dict) -> dict[str, dict]:out = {}for r in tri["records"]:if r["outcome"] not in ("failed", "flaky"):continuecid, cl = r.get("case_id") or r["full_title"], r.get("classification") or {}out[cid] = {"case_id": cid, "category": cl.get("category", "unclassified"), "confidence": float(cl.get("confidence") or 0),"needs_review": bool(cl.get("needs_review")), "evidence": cl.get("evidence") or [], "llm_hint": None,"similar": [], "outcome": r["outcome"], "message": (r.get("errors") or [{}])[0].get("message", "")[:2000]if r.get("errors") else ""}if r.get("blocked_by_canary"): # not run: the canary found these business actions broken (platform/canary.py)out[cid]["blocked_by_canary"] = list(r["blocked_by_canary"])return outdef write(tri: dict, path: Path) -> Path:path.write_text(json.dumps(tri, indent=2, default=str), encoding="utf-8")return path
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735"""/a2a: Astra as an A2A (Agent2Agent protocol v0.3) agent, JSON-RPC 2.0 over HTTP, with SSE streaming.Another agent (for example one that crawls a pod's modules and versions and Oracle's patch updates) finds Astra at/.well-known/agent-card.json and calls POST /a2a with a personal access token (`Authorization: Bearer pwt_...`, the sametokens, scopes, rate limit and code paths as /mcp, see api/mcp.py). Skills:- assess-readiness, get-report (scope "read")- design-tests, run-tests (scope "read,act" and run.start): a proposal first (task input-required); a follow-up message{"confirm": true} on the same task starts it through the same confirm path as Ask and MCP (role, gate and theemergency stop re-checked; a proposal is single use).- test-these-cases (scope "read,act" and run.start): parse + script + dry run (custom_cases.py). The task waits until aPERSON approves the cases in Astra; the caller can never approve. Then {"confirm": true} runs the approved ones.A task that leads to a test run follows it (working, input-required while a person reviews, completed with the report,failed). Never through A2A: approving custom cases, sign-off, failure verdicts, waivers, the emergency stop, admin.What the caller sends about its pod and patch is untrusted data: stored on the task and shown back, never given to anLLM as instructions and never fetched (URLs are only displayed). Text is routed with the deterministic Ask intent rules.Why not the a2a-sdk: its server app brings its own request handler, task store and auth model; binding tasks to ourtokens, RBAC and audit would mean adapters around all three. The subset below (message/send, message/stream,tasks/get, tasks/cancel, tasks/resubscribe) is the JSON-RPC binding of the spec, without push notifications."""from __future__ import annotationsimport asyncioimport jsonimport loggingimport reimport secretsimport timeimport uuidfrom fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse, Response, StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field, ValidationErrorfrom starlette.concurrency import run_in_threadpoolfrom ..config import VERSIONfrom ..platform import custom_cases as Cfrom ..platform.api_tokens import TokenStorefrom ..platform.pods import PodRegistryfrom . import mcpfrom .errors import ApiErrorfrom .mcp import Toolbox, ToolFailure, _module, _nowlog = logging.getLogger("fpt.a2a")router = APIRouter()PROTOCOL_VERSION = "0.3.0"MAX_BODY = 256 * 1024MAX_PARTS = 20MAX_TEXT = 8000MAX_HISTORY = 50STREAM_POLL_SECONDS = 1.0STREAM_MAX_SECONDS = 600TERMINAL = {"completed", "canceled", "failed", "rejected"}STOP = TERMINAL | {"input-required", "auth-required"} # a stream ends here (final: true)ACT_SKILLS = {"design-tests", "run-tests", "test-these-cases"}PATCH_RE = re.compile(r"^\d{2}[A-D]$", re.I) # the release names Astra's research knows (e.g. 26C)# JSON-RPC / A2A error codesTASK_NOT_FOUND, NOT_CANCELABLE, PUSH_UNSUPPORTED, UNSUPPORTED, CONTENT_TYPE, EXT_CARD = -32001, -32002, -32003, -32004, -32005, -32007IO = ["text/plain", "application/json"]SKILLS = [{"id": "assess-readiness", "name": "Assess patch readiness","description": "Readiness of each business area for the latest (or a given) Oracle patch: Ready / Not ready / Held / ""Not tested yet, with scenario counts. Input (optional): DataPart {area, patch}. Scope: read.","tags": ["oracle-fusion", "patch", "readiness"], "examples": ["Is Procure-to-Pay ready for 26C?"],"inputModes": IO, "outputModes": IO},{"id": "design-tests", "name": "Design tests for a patch","description": "Send what your agent found: DataPart {pod: {...}, patch: {id, changes: [{area, description, source_url?}]}, ""mode?: quick|browser, environment?}. Astra proposes a test run of the affected areas (its own ""generator chooses the scenarios; your facts are recorded as data). Reply {confirm: true} on the same ""task to start it. Scope: read,act.","tags": ["oracle-fusion", "patch", "test-design"], "inputModes": ["application/json"], "outputModes": IO},{"id": "test-these-cases", "name": "Test these cases","description": "Your own test cases: DataPart {cases: [{title, area, priority?, steps: [{action, expected?}], data?, ""preconditions?}], environment?} (at most 50). Astra writes the scripts and dry-runs them; a PERSON ""approves them in Astra (never the caller). Then reply {confirm: true} to run the approved ones. ""Scope: read,act.","tags": ["oracle-fusion", "custom-test-cases"], "inputModes": ["application/json"], "outputModes": IO},{"id": "run-tests", "name": "Run tests","description": "Propose a test run: DataPart {area or areas, mode?: quick|browser, environment?, patch?} or text ""('run a quick simulation of Procure-to-Pay'). Reply {confirm: true} on the same task to start it. ""The task then follows the run. Scope: read,act.","tags": ["oracle-fusion", "test-run"], "examples": ["Run a quick simulation of Procure-to-Pay"], "inputModes": IO, "outputModes": IO},{"id": "get-report", "name": "Get a test report","description": "A finished run's report: verdict and QA rule result per area, counts, exit criteria, links, and the ""PDF (opens for a signed-in person). Input: DataPart {run_id}. Scope: read.","tags": ["oracle-fusion", "report"], "inputModes": IO, "outputModes": IO + ["application/pdf"]},]SKILL_IDS = {s["id"] for s in SKILLS}HELP = ("I am Astra: I test Oracle Fusion patches. Skills: " + "; ".join(f"{s['id']} ({s['name']})" for s in SKILLS)+ ". Choose one with message.metadata.skill or a DataPart {\"skill\": ...}. Starting anything needs a confirm, and ""custom test cases need a person's approval in Astra.")class RpcError(Exception):def __init__(self, code: int, message: str):super().__init__(message)self.code = code# ------------------------------------------------------------------------------------------------ caller inputclass Change(BaseModel):model_config = ConfigDict(extra="forbid")area: str = Field(min_length=1, max_length=60)description: str = Field(min_length=1, max_length=2000)source_url: str | None = Field(default=None, max_length=500) # displayed only, never fetchedclass PatchFacts(BaseModel):model_config = ConfigDict(extra="forbid")id: str | None = Field(default=None, max_length=40)changes: list[Change] = Field(default_factory=list, max_length=200)class DesignIn(BaseModel):model_config = ConfigDict(extra="forbid")skill: str | None = Nonepod: dict = Field(default_factory=dict)patch: PatchFacts = Field(default_factory=PatchFacts)areas: list[str] = Field(default_factory=list, max_length=10)mode: str = Field(default="quick", pattern="^(quick|browser)$")environment: str | None = Field(default=None, max_length=60)class RunTestsIn(BaseModel):model_config = ConfigDict(extra="forbid")skill: str | None = Nonearea: str | None = Field(default=None, max_length=60)areas: list[str] = Field(default_factory=list, max_length=10)mode: str = Field(default="quick", pattern="^(quick|browser)$")environment: str | None = Field(default=None, max_length=60)patch: str | None = Field(default=None, max_length=40)def _bad(e: ValidationError) -> RpcError:return RpcError(-32602, "Invalid input: " + "; ".join(f"{'.'.join(str(p) for p in x['loc'])}: {x['msg']}" for x in e.errors()[:8]))def _parts(msg: dict) -> tuple[str, dict | None]:"""The message's text (joined) and its first DataPart. FileParts are accepted and ignored (nothing is fetched)."""texts, data = [], Nonefor p in msg["parts"]:kind = p.get("kind") if isinstance(p, dict) else Noneif kind == "text" and isinstance(p.get("text"), str):texts.append(p["text"])elif kind == "data" and isinstance(p.get("data"), dict):data = p["data"] if data is None else dataelif kind != "file":raise RpcError(-32602, "Each part needs kind text, data or file.")text = "\n".join(texts)if len(text) > MAX_TEXT:raise RpcError(-32602, f"The text is longer than {MAX_TEXT} characters.")return text, datadef _check_message(msg) -> dict:if not isinstance(msg, dict) or msg.get("role") != "user" or not isinstance(msg.get("parts"), list) or not msg["parts"]:raise RpcError(-32602, "params.message needs role 'user' and at least one part.")if len(msg["parts"]) > MAX_PARTS:raise RpcError(-32602, f"At most {MAX_PARTS} parts per message.")for k in ("messageId", "taskId", "contextId"):if msg.get(k) is not None and (not isinstance(msg[k], str) or len(msg[k]) > 100):raise RpcError(-32602, f"message.{k} must be a short string.")return msgdef _agent_message(task_id: str, context_id: str, text: str, data: dict | None = None) -> dict:parts: list[dict] = [{"kind": "text", "text": text}]if data is not None:parts.append({"kind": "data", "data": data})return {"kind": "message", "messageId": uuid.uuid4().hex, "role": "agent", "parts": parts, "taskId": task_id, "contextId": context_id}def _choose_skill(msg: dict, text: str, data: dict | None) -> str | None:named = (msg.get("metadata") or {}).get("skill") if isinstance(msg.get("metadata"), dict) else Nonenamed = named or (data or {}).get("skill")if named:return str(named) if str(named) in SKILL_IDS else Noneif data and "cases" in data:return "test-these-cases"if data and ("patch" in data or "pod" in data):return "design-tests"if data and "run_id" in data:return "get-report"if re.search(r"\breport\b", text or "", re.I):return "get-report"from ..chat.intent import routereturn {"readiness": "assess-readiness", "start_run": "run-tests"}.get(route(text or "").tool)# ------------------------------------------------------------------------------------------------ tasksclass A2AToolbox(Toolbox):VIA = "a2a"def task_out(row: dict, history_length: int | None = None) -> dict:hist = json.loads(row["history_json"] or "[]")status_msg = next((m for m in reversed(hist) if m.get("role") == "agent"), None)if history_length is not None:hist = hist[-history_length:] if history_length > 0 else []return {"kind": "task", "id": row["id"], "contextId": row["context_id"],"status": {"state": row["state"], **({"message": status_msg} if status_msg else {}), "timestamp": row["updated_at"]},"history": hist, "artifacts": json.loads(row["artifacts_json"] or "[]"),"metadata": {"skill": row["skill"], "run_id": row["run_id"], "batch_id": row["batch_id"]}}class Tasks:"""A2A tasks for one caller (token owner + token). Every method is blocking (database): call off the event loop."""def __init__(self, request: Request, user, token: dict):self.request, self.user, self.token = request, user, tokenself.svc, self.runs = request.app.state.svc, request.app.state.runsself.scopes = set(str(token["scopes"]).split(","))def box(self) -> A2AToolbox:return A2AToolbox(self.request, self.user, self.token)def link(self, path: str) -> str:from .mcp import _absreturn _abs(self.svc, path) or pathdef audit(self, kind: str, row: dict | None, summary: str, **payload) -> None:self.svc.audit.append(kind, actor=self.user.username, run_id=(row or {}).get("run_id"), summary=summary[:200],payload={"task": (row or {}).get("id"), "skill": (row or {}).get("skill"), "token_id": self.token["id"], **payload})# -- storagedef get(self, tid: str) -> dict | None:return self.svc.db.one("SELECT * FROM a2a_tasks WHERE id=?", (tid,))def own(self, tid, write: bool = False) -> dict:row = self.get(str(tid)[:100]) if isinstance(tid, str) else Nonemine = row and int(row["user_id"]) == int(self.user.id) and (not write or int(row["token_id"]) == int(self.token["id"]))if not row or not (mine or (not write and self.user.role == "admin")):raise RpcError(TASK_NOT_FOUND, "Task not found.")return rowdef create(self, skill: str, msg: dict, facts: dict | None = None) -> dict:tid = secrets.token_urlsafe(12)ctx = msg.get("contextId") or uuid.uuid4().hexnow = _now()user_msg = {**msg, "taskId": tid, "contextId": ctx, "kind": "message"}self.svc.db.insert("a2a_tasks", {"id": tid, "context_id": ctx, "user_id": self.user.id, "token_id": self.token["id"],"skill": skill, "state": "submitted", "facts_json": json.dumps(facts) if facts else None,"history_json": json.dumps([user_msg]), "artifacts_json": "[]","created_at": now, "updated_at": now})row = self.get(tid)self.audit("a2a.task", row, f"{skill} task from token '{self.token['name']}'")return rowdef update(self, row: dict, **cols) -> dict:cols["updated_at"] = _now()sets = ", ".join(f"{k}=?" for k in cols)self.svc.db.x(f"UPDATE a2a_tasks SET {sets} WHERE id=?", (*cols.values(), row["id"])) # noqa: S608 (column names are ours)return self.get(row["id"])def add_user_message(self, row: dict, msg: dict) -> dict:hist = json.loads(row["history_json"])[-(MAX_HISTORY - 1):] + [{**msg, "kind": "message", "taskId": row["id"], "contextId": row["context_id"]}]return self.update(row, history_json=json.dumps(hist))def state(self, row: dict, state: str, text: str, data: dict | None = None) -> dict:if row["state"] == state and row["status_text"] == text:return rowhist = json.loads(row["history_json"])[-(MAX_HISTORY - 1):] + [_agent_message(row["id"], row["context_id"], text, data)]if row["state"] != state:self.audit("a2a.state", row, f"{row['state']} -> {state}", **{"from": row["state"], "to": state})return self.update(row, state=state, status_text=text, history_json=json.dumps(hist))def artifact(self, row: dict, artifact_id: str, name: str, parts: list[dict], description: str | None = None) -> dict:arts = [a for a in json.loads(row["artifacts_json"]) if a["artifactId"] != artifact_id]arts.append({"artifactId": artifact_id, "name": name, **({"description": description} if description else {}), "parts": parts})return self.update(row, artifacts_json=json.dumps(arts))def claim(self, row: dict) -> bool:"""input-required -> working in one statement: a second confirm racing the first finds nothing to claim."""with self.svc.db.tx() as c:return c.execute("UPDATE a2a_tasks SET state='working', updated_at=? WHERE id=? AND state='input-required'",(_now(), row["id"])).rowcount == 1# -- permissiondef act_refusal(self, skill: str) -> str | None:if "act" not in self.scopes:return ("This token is read-only. Create a token with the 'read and act' scope in Astra ""(Account → Access tokens for AI assistants) to design or run tests.")if not self.user.can("run.start"):return f"Your role ({self.user.role}) can't start test runs in Astra."return None# -- message/senddef send(self, msg: dict) -> dict:_check_message(msg)text, data = _parts(msg)if msg.get("taskId"):row = self.own(msg["taskId"], write=True)if row["state"] in TERMINAL:raise RpcError(UNSUPPORTED, f"This task is {row['state']}. Start a new task (send without taskId).")return self.follow_up(self.add_user_message(row, msg), text, data)skill = _choose_skill(msg, text, data)if skill is None:row = self.create("help", msg)return self.state(row, "completed", HELP, {"skills": sorted(SKILL_IDS)})if skill in ACT_SKILLS:refusal = self.act_refusal(skill)if refusal:row = self.create(skill, msg)self.audit("a2a.refused", row, refusal[:120])return self.state(row, "rejected", refusal)return getattr(self, "skill_" + skill.replace("-", "_"))(msg, text, data or {})# -- read skillsdef skill_assess_readiness(self, msg: dict, text: str, data: dict) -> dict:from ..chat.intent import PATCH_ID, modules_inrow = self.create("assess-readiness", msg)area = data.get("area") if isinstance(data.get("area"), str) else (modules_in(text) or [None])[0]patch = data.get("patch") if isinstance(data.get("patch"), str) else (m.group(1).upper() if (m := PATCH_ID.search(text or "")) else None)try:res = self.box().readiness(area, patch)except ToolFailure as e:return self.state(row, "failed", str(e))text_out = res["content"][0]["text"]row = self.artifact(row, "readiness", "Patch readiness", [{"kind": "text", "text": text_out}, {"kind": "data", "data": res["structuredContent"]}])return self.state(row, "completed", text_out)def skill_get_report(self, msg: dict, text: str, data: dict) -> dict:rid = data.get("run_id") if isinstance(data.get("run_id"), str) else Noneif not rid:rid = next((w for w in re.findall(r"[A-Za-z0-9_-]{6,64}", text or "")[:20] if self.svc.db.get_run(w)), None)row = self.create("get-report", msg)if not rid or not self.svc.db.get_run(rid[:64]):return self.state(row, "rejected", "Say which test run: a DataPart {\"skill\": \"get-report\", \"run_id\": \"...\"}.")row = self.update(row, run_id=rid)return self.report(row, final=True)def report(self, row: dict, final: bool) -> dict:res = self.box().report_summary(row["run_id"])info = res["structuredContent"]parts = [{"kind": "text", "text": res["content"][0]["text"]}, {"kind": "data", "data": info}]parts += [{"kind": "file", "file": {"uri": a["pdf"], "mimeType": "application/pdf", "name": f"patchwise-{row['run_id']}-{a['area'].lower()}.pdf"}}for a in info.get("areas") or [] if a.get("pdf")]row = self.artifact(row, "report", "Test report", parts, "Verdict and QA rule result per area, counts, exit criteria and links. ""Sign-off happens in Astra.")if not final:return rowreturn self.state(row, "completed", res["content"][0]["text"])# -- act skills: propose, then confirm on the same taskdef skill_design_tests(self, msg: dict, text: str, data: dict) -> dict:try:d = DesignIn.model_validate(data)except ValidationError as e:raise _bad(e) from eif len(json.dumps(d.pod)) > 16 * 1024:raise RpcError(-32602, "pod details are larger than 16 KB.")facts = {"pod": d.pod, "patch": d.patch.model_dump()}row = self.create("design-tests", msg, facts)mods, unknown = [], []for a in d.areas + [c.area for c in d.patch.changes]:try:m = _module(a)except ToolFailure:unknown.append(a[:40])continueif m and m not in mods:mods.append(m)patch_id = d.patch.id.upper() if d.patch.id and PATCH_RE.match(d.patch.id) else Nonenote = (f" Your agent's facts are recorded on this task as data ({len(d.patch.changes)} change(s)"+ (f", patch {d.patch.id[:40]}" if d.patch.id else "") + "); Astra's own generator chooses the scenarios"+ (f" for patch {patch_id}" if patch_id else "") + "."+ (f" Areas not recognised: {', '.join(sorted(set(unknown)))}." if unknown else ""))if not mods:from ..chat.intent import MODULE_NAMESreturn self.state(row, "rejected", "None of the areas is a business area Astra tests. Known: "+ ", ".join(f"{k} ({v})" for k, v in MODULE_NAMES.items()) + "." + note)return self.propose(row, mods, d.mode, d.environment, patch_id, note)def skill_run_tests(self, msg: dict, text: str, data: dict) -> dict:if data:try:d = RunTestsIn.model_validate(data)except ValidationError as e:raise _bad(e) from erow = self.create("run-tests", msg)words = ([d.area] if d.area else []) + d.areasmods = []for a in words: # practice-app names here; an Oracle Fusion pod reads its own areas from the wordstry:mods.append(_module(a))except ToolFailure:passpatch = d.patch.upper() if d.patch and PATCH_RE.match(d.patch) else Nonereturn self.propose(row, list(dict.fromkeys(m for m in mods if m)), d.mode, d.environment, patch, "", " , ".join(words))from ..chat.intent import args_fora = args_for("start_run", text, {})row = self.create("run-tests", msg)return self.propose(row, a.get("modules") or [], "browser" if a.get("mode") == "live" else "quick", a.get("pod"), a.get("patch_id"), "", text)def propose(self, row: dict, mods: list[str], mode: str, environment: str | None, patch_id: str | None, note: str,area_text: str | None = None) -> dict:box = self.box()res = box._tools().start_run(modules=mods, mode="live" if mode == "browser" else "stub", pod=environment or None, patch_id=patch_id, # noqa: SLF001area_text=area_text)try:out = box._propose(row["skill"], res, None) # noqa: SLF001except ToolFailure as e:return self.state(row, "rejected", str(e))p = out["structuredContent"]row = self.update(row, proposal_id=p["proposal_id"])row = self.artifact(row, "proposal", "Proposed test run", [{"kind": "data", "data": {"summary": p["summary"], "items": p["items"], "expires_at": p["expires_at"], "facts_recorded": bool(row["facts_json"])}}])items = "\n".join(f"- {i['label']}: {i['value']}" for i in p["items"])return self.state(row, "input-required", f"{p['summary']}\n{items}\n{note.strip()}\n\nReply {{\"confirm\": true}} on this task "f"(taskId {row['id']}) to start it, or call tasks/cancel. The proposal expires {p['expires_at']}.".replace("\n\n\n", "\n\n"))def skill_test_these_cases(self, msg: dict, text: str, data: dict) -> dict:cases = data.get("cases")if not isinstance(cases, list):raise RpcError(-32602, "Send a DataPart {\"cases\": [...]}.")if len(cases) > C.MAX_CASES:raise RpcError(-32602, f"At most {C.MAX_CASES} cases per task ({len(cases)} given).")extra = set(data) - {"skill", "cases", "environment"}if extra:raise RpcError(-32602, f"Unknown fields: {', '.join(sorted(extra))[:200]}.")try: # the strict agent schema: an unknown field or a bad case rejects the whole setparsed = C.CustomCases.model_validate({"cases": cases}).model_dump()["cases"]except ValidationError as e:raise _bad(e) from erow = self.create("test-these-cases", msg)try:ok, warnings = C.validate(parsed, [])if not ok:return self.state(row, "rejected", "None of the cases can be used: " + "; ".join(warnings[:8]))env = data.get("environment")pods = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).list() # seeds the default podpod = next((p for p in pods if p["name"].lower() == str(env)[:60].lower()), None) if env else (pods[0] if pods else None)if env and not pod:return self.state(row, "rejected", f"There is no test environment called '{str(env)[:40]}'.")if not pod:return self.state(row, "rejected", "There is no test environment to dry-run on yet.")batch = C.create_batch(self.svc, self.user.username, "a2a", ok, warnings)row = self.update(row, batch_id=batch["batch_id"])self.audit("a2a.cases", row, f"{len(ok)} custom case(s) sent; build on pod {pod['id']}", batch=batch["batch_id"], cases=len(ok))C.start_build(self.svc, batch["batch_id"], int(pod["id"]), self.user.username)except C.CustomCaseError as e:return self.state(row, "failed", str(e))row = self.state(row, "working", "Writing scripts and dry-running your cases on the pod.")return self.sync(row)# -- follow-ups on an open taskdef follow_up(self, row: dict, text: str, data: dict | None) -> dict:row = self.sync(row)if row["state"] != "input-required":return rowd = data or {}if any(k in d for k in ("approve", "approved", "approve_cases", "sign_off", "signoff", "verdict")):self.audit("a2a.refused", row, "approval or sign-off asked through A2A")return self.state(row, "input-required", "Only a person can approve, decide or sign off, in Astra. "+ (row["status_text"] or ""))if not (d.get("confirm") is True or (text or "").strip().lower().rstrip(".!") == "confirm"):return self.state(row, "input-required", (row["status_text"] or "").split("\n\nReply")[0]+ "\n\nReply {\"confirm\": true} on this task to go on, or call tasks/cancel.")refusal = self.act_refusal(row["skill"])if refusal:return self.state(row, "input-required", refusal)if row["proposal_id"] and not row["run_id"]:return self.confirm_proposal(row)if row["batch_id"] and not row["run_id"]:return self.run_batch(row, d.get("mode") if d.get("mode") in ("quick", "browser") else "quick")return self.sync(row) # a run waiting for a person: a confirm here changes nothingdef confirm_proposal(self, row: dict) -> dict:if not self.claim(row):return self.get(row["id"])try:res = self.box().confirm(row["proposal_id"])["structuredContent"]except ToolFailure as e:row = self.get(row["id"])return self.state({**row, "state": "input-required"}, "failed", str(e))row = self.update(self.get(row["id"]), run_id=res.get("run_id"))self.audit("a2a.confirm", row, f"test run {res.get('run_id')} started")return self.sync(self.state({**row, "state": "input-required"}, "working", f"The test run has started: {res.get('link') or ''}".strip()))def run_batch(self, row: dict, mode: str) -> dict:v = C.view(self.svc, row["batch_id"])keys = [c["key"] for c in v["cases"] if c["state"] == "approved"]if not keys:return self.state(row, "input-required", "No case has been approved by a person yet. "+ f"Waiting for a person to approve the scenarios in Astra: {self.link('/scenarios/import?batch=' + row['batch_id'])}")if not self.claim(row):return self.get(row["id"])row = self.get(row["id"])try:rid = C.run(self.svc, self.runs, row["batch_id"], keys, mode, self.user.username)except C.CustomCaseError as e:return self.state({**row, "state": "input-required"}, "failed", str(e))except ApiError as e: # the emergency stopreturn self.state({**row, "state": "input-required"}, "failed", e.detail)row = self.update(row, run_id=rid)self.audit("a2a.run", row, f"test run {rid} of {len(keys)} approved custom case(s)", batch=row["batch_id"], keys=keys)return self.sync(self.state({**row, "state": "input-required"}, "working", f"Testing {len(keys)} approved case(s): {self.link(f'/runs/{rid}')}"))# -- following a run or a batchdef sync(self, row: dict) -> dict:if row["state"] in TERMINAL:return rowif row["run_id"]:return self.follow_run(row)if row["batch_id"]:return self.follow_batch(row)return rowdef follow_run(self, row: dict) -> dict:from ..chat.tools import STATUS_WORDSrid = row["run_id"]run = self.svc.db.get_run(rid)if not run:return self.state(row, "failed", "The test run no longer exists.")st, gate = run.get("status"), run.get("pending_gate")if gate == "approve_cases" or st == "waiting_approval":return self.state(row, "input-required", f"Waiting for a person to approve the scenarios in Astra: {self.link(f'/runs/{rid}/scenarios')}")if gate == "human_review" or st == "waiting_review":return self.state(row, "input-required", f"Waiting for a person to decide the failures in Astra: {self.link(f'/runs/{rid}/failures')}")if st == "completed":row = self.report(row, final=False)return self.state(row, "completed", f"The test run finished. Report: {self.link(f'/runs/{rid}/report')}")if st in ("failed", "killed"):return self.state(row, "failed", f"The test run {STATUS_WORDS.get(st, st)}." + (f" {str(run.get('error'))[:200]}" if run.get("error") else ""))if st == "cancelled":return self.state(row, "canceled", "The test run was cancelled.")step = f" ({run['current_node']})" if run.get("current_node") else ""return self.state(row, "working", f"Testing: {STATUS_WORDS.get(st, st)}{step}. Follow it in Astra: {self.link(f'/runs/{rid}')}")def follow_batch(self, row: dict) -> dict:try:v = C.view(self.svc, row["batch_id"])except C.CustomCaseError as e:return self.state(row, "failed", str(e))cases = [{k: c.get(k) for k in ("key", "title", "area", "state", "case_id", "failed_step", "message", "simulated", "decided_by")}for c in v["cases"]]row = self.artifact(row, "cases", "Your test cases", [{"kind": "data", "data": {"batch_id": row["batch_id"], "status": v["status"], "pod": v["pod"], "cases": cases}}])link = self.link(f"/scenarios/import?batch={row['batch_id']}")if v["status"] in ("parsed", "building"):return self.state(row, "working", "Writing scripts and dry-running your cases on the pod.")if v["status"] == "failed":return self.state(row, "failed", f"The scripts could not be built: {v.get('message') or 'see Astra'}.")by = lambda s: [c for c in cases if c["state"] == s] # noqa: E731approved, waiting = by("approved"), by("dry_run_passed")if waiting:return self.state(row, "input-required", f"{len(waiting)} case(s) passed their dry run. Waiting for a person to approve the "f"scenarios in Astra: {link}" + (f" ({len(approved)} already approved: reply {{\"confirm\": true}} to run those.)" if approved else ""))if approved:return self.state(row, "input-required", f"A person approved {len(approved)} case(s). Reply {{\"confirm\": true}} on this task ""to run them (optionally with \"mode\": \"quick\" or \"browser\").")return self.state(row, "completed", f"None of the cases can run: {len(by('not_scriptable'))} could not be scripted, "f"{len(by('dry_run_failed'))} failed their dry run, {len(by('rejected'))} rejected. Details are in the 'cases' artifact.")# -- tasks/canceldef cancel(self, tid) -> dict:row = self.own(tid, write=True)row = self.sync(row)if row["state"] in TERMINAL:raise RpcError(NOT_CANCELABLE, f"Task cannot be canceled: it is already {row['state']}.")if "act" not in self.scopes:raise RpcError(NOT_CANCELABLE, "This token is read-only.")if row["run_id"]:from . import actionsrun = self.svc.db.get_run(row["run_id"]) or {}if not (self.user.can("run.control") and (run.get("created_by") == self.user.username or self.user.role == "admin")):raise RpcError(NOT_CANCELABLE, "You can't cancel that test run (it isn't yours, or your role can't cancel runs).")try:actions.cancel_run(self.svc, self.runs, row["run_id"], self.user.username, "cancelled by an agent (A2A)", via="a2a")except ApiError as e:raise RpcError(NOT_CANCELABLE, e.detail) from eelif row["proposal_id"]:try:self.box().cancel(row["proposal_id"])except ToolFailure:pass # expired or already used: nothing to dropself.audit("a2a.cancel", row, "task canceled")return self.state(row, "canceled", "Canceled." + (" The test run was cancelled." if row["run_id"] else " Nothing was started."))# ------------------------------------------------------------------------------------------------ transportdef agent_card(request: Request) -> dict:svc = request.app.state.svcbase = (svc.cfg.public_url or str(request.base_url)).rstrip("/")return {"protocolVersion": PROTOCOL_VERSION, "name": "Astra","description": "Astra tests Oracle Fusion patches before they go live: readiness per business area, test design ""and runs on a test pod, your own test cases (a person approves them), and the report. Starting ""anything needs a confirm; approvals and sign-off stay with people in Astra.","url": f"{base}/a2a", "preferredTransport": "JSONRPC", "version": VERSION,"provider": {"organization": "Astra", "url": base},"capabilities": {"streaming": True, "pushNotifications": False, "stateTransitionHistory": True},"defaultInputModes": IO, "defaultOutputModes": IO,"securitySchemes": {"bearer": {"type": "http", "scheme": "bearer","description": "Astra access token (pwt_…) from Account → Access tokens for AI assistants"}},"security": [{"bearer": []}],"skills": SKILLS,"supportsAuthenticatedExtendedCard": False,}@router.get("/.well-known/agent-card.json", include_in_schema=False)def well_known_card(request: Request) -> JSONResponse:card = {k: v for k, v in agent_card(request).items() if v is not None}return JSONResponse(card, headers={"Cache-Control": "public, max-age=300"})def _ok(mid, result) -> dict:return {"jsonrpc": "2.0", "id": mid, "result": result}def _err(mid, code: int, message: str) -> dict:return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}}def _history_length(params: dict) -> int | None:h = params.get("historyLength", (params.get("configuration") or {}).get("historyLength") if isinstance(params.get("configuration"), dict) else None)return max(0, min(int(h), MAX_HISTORY)) if isinstance(h, int) and not isinstance(h, bool) else Nonedef _dispatch(tasks: Tasks, method: str, params: dict) -> dict:"""The task (as the protocol shows it) for a non-streaming method, or RpcError."""if method == "message/send":cfg = params.get("configuration") or {}if isinstance(cfg, dict) and cfg.get("pushNotificationConfig"):raise RpcError(PUSH_UNSUPPORTED, "Push notifications are not supported: poll tasks/get or use message/stream.")return task_out(tasks.send(params.get("message")), _history_length(params))if method == "tasks/get":return task_out(tasks.sync(tasks.own(params.get("id"))), _history_length(params))if method == "tasks/cancel":return task_out(tasks.cancel(params.get("id")))if method.startswith("tasks/pushNotificationConfig/"):raise RpcError(PUSH_UNSUPPORTED, "Push notifications are not supported.")if method == "agent/getAuthenticatedExtendedCard":raise RpcError(EXT_CARD, "There is no extended agent card.")raise RpcError(-32601, f"Method not found: {method[:60]}")def _handle(body, request: Request, user, token: dict) -> dict:if not isinstance(body, dict) or body.get("jsonrpc") != "2.0" or not isinstance(body.get("method"), str):return _err(body.get("id") if isinstance(body, dict) else None, -32600, "Invalid request")mid, params = body.get("id"), body.get("params") or {}if not isinstance(params, dict):return _err(mid, -32602, "params must be an object")try:return _ok(mid, _dispatch(Tasks(request, user, token), body["method"], params))except RpcError as e:return _err(mid, e.code, str(e))except Exception: # noqa: BLE001 (never a stack trace to the caller; the log has it)log.exception("a2a %s failed", body["method"][:40])return _err(mid, -32603, "Astra could not complete that. Try again, or open the app.")def _sse(obj: dict) -> bytes:return f"data: {json.dumps(obj, separators=(',', ':'))}\n\n".encode()async def _stream(request: Request, tasks: Tasks, mid, method: str, params: dict):"""message/stream and tasks/resubscribe: the Task, then status and artifact updates until input-required or a finalstate (final: true), or STREAM_MAX_SECONDS (then final: true while still working: resubscribe or poll tasks/get)."""def first():if method == "message/stream":return tasks.send(params.get("message"))return tasks.sync(tasks.own(params.get("id")))try:row = await run_in_threadpool(first)except RpcError as e:yield _sse(_err(mid, e.code, str(e)))returnexcept Exception: # noqa: BLE001log.exception("a2a %s failed", method)yield _sse(_err(mid, -32603, "Astra could not complete that."))returnprev = task_out(row, _history_length(params))yield _sse(_ok(mid, prev))status = {"kind": "status-update", "taskId": row["id"], "contextId": row["context_id"]}if row["state"] in STOP:yield _sse(_ok(mid, {**status, "status": prev["status"], "final": True}))returndeadline = time.monotonic() + STREAM_MAX_SECONDSwhile time.monotonic() < deadline:if await request.is_disconnected():returnawait asyncio.sleep(STREAM_POLL_SECONDS)row = await run_in_threadpool(lambda: tasks.sync(tasks.get(row["id"])))cur = task_out(row)old = {a["artifactId"]: a for a in prev["artifacts"]}for a in cur["artifacts"]:if old.get(a["artifactId"]) != a:yield _sse(_ok(mid, {"kind": "artifact-update", "taskId": row["id"], "contextId": row["context_id"], "artifact": a,"append": False, "lastChunk": True}))done = row["state"] in STOPif cur["status"]["state"] != prev["status"]["state"] or cur["status"].get("message") != prev["status"].get("message") or done:yield _sse(_ok(mid, {**status, "status": cur["status"], "final": done}))if done:returnprev = curyield _sse(_ok(mid, {**status, "status": prev["status"], "final": True}))@router.post("/a2a", include_in_schema=False)async def a2a_post(request: Request) -> Response:if not mcp._origin_ok(request): # noqa: SLF001return JSONResponse({"error": "forbidden", "detail": "origin not allowed"}, status_code=403)authz = request.headers.get("authorization", "")if not authz.lower().startswith("bearer "):return mcp._unauthorized("a personal access token is required: Authorization: Bearer pwt_...") # noqa: SLF001got = TokenStore(request.app.state.svc).resolve(authz[7:].strip())if not got:return mcp._unauthorized("the token is unknown, revoked or expired, or its owner is disabled") # noqa: SLF001user, token = gotrequest.state.user = userif not mcp._rate_ok(int(token["id"])): # noqa: SLF001 (one budget per token across /mcp and /a2a)return JSONResponse(_err(None, -32000, "Too many requests: at most 60 a minute per token"), status_code=429, headers={"Retry-After": "60"})if int(request.headers.get("content-length") or 0) > MAX_BODY:return JSONResponse(_err(None, -32600, "Request too large (256 KB at most)"), status_code=413)raw = await request.body()if len(raw) > MAX_BODY:return JSONResponse(_err(None, -32600, "Request too large (256 KB at most)"), status_code=413)try:body = json.loads(raw or b"null")except ValueError:return JSONResponse(_err(None, -32700, "Parse error"), status_code=400)token = dict(token)if isinstance(body, dict) and body.get("jsonrpc") == "2.0" and body.get("method") in ("message/stream", "tasks/resubscribe"):params = body.get("params") if isinstance(body.get("params"), dict) else {}return StreamingResponse(_stream(request, Tasks(request, user, token), body.get("id"), body["method"], params),media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})return JSONResponse(await run_in_threadpool(_handle, body, request, user, token))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737"""/a2a: Astra as an A2A (Agent2Agent protocol v0.3) agent, JSON-RPC 2.0 over HTTP, with SSE streaming.Another agent (for example one that crawls a pod's modules and versions and Oracle's patch updates) finds Astra at/.well-known/agent-card.json and calls POST /a2a with a personal access token (`Authorization: Bearer pwt_...`, the sametokens, scopes, rate limit and code paths as /mcp, see api/mcp.py). Skills:- assess-readiness, get-report (scope "read")- design-tests, run-tests (scope "read,act" and run.start): a proposal first (task input-required); a follow-up message{"confirm": true} on the same task starts it through the same confirm path as Ask and MCP (role, gate and theemergency stop re-checked; a proposal is single use).- test-these-cases (scope "read,act" and run.start): parse + script + dry run (custom_cases.py). The task waits until aPERSON approves the cases in Astra; the caller can never approve. Then {"confirm": true} runs the approved ones.A task that leads to a test run follows it (working, input-required while a person reviews, completed with the report,failed). Never through A2A: approving custom cases, sign-off, failure verdicts, waivers, the emergency stop, admin.What the caller sends about its pod and patch is untrusted data: stored on the task and shown back, never given to anLLM as instructions and never fetched (URLs are only displayed). Text is routed with the deterministic Ask intent rules.Why not the a2a-sdk: its server app brings its own request handler, task store and auth model; binding tasks to ourtokens, RBAC and audit would mean adapters around all three. The subset below (message/send, message/stream,tasks/get, tasks/cancel, tasks/resubscribe) is the JSON-RPC binding of the spec, without push notifications."""from __future__ import annotationsimport asyncioimport jsonimport loggingimport reimport secretsimport timeimport uuidfrom fastapi import APIRouter, Requestfrom fastapi.responses import JSONResponse, Response, StreamingResponsefrom pydantic import BaseModel, ConfigDict, Field, ValidationErrorfrom starlette.concurrency import run_in_threadpoolfrom ..config import VERSIONfrom ..platform import custom_cases as Cfrom ..platform.api_tokens import TokenStorefrom ..platform.pods import PodRegistryfrom . import mcpfrom .errors import ApiErrorfrom .mcp import Toolbox, ToolFailure, _module, _nowlog = logging.getLogger("fpt.a2a")router = APIRouter()PROTOCOL_VERSION = "0.3.0"MAX_BODY = 256 * 1024MAX_PARTS = 20MAX_TEXT = 8000MAX_HISTORY = 50STREAM_POLL_SECONDS = 1.0STREAM_MAX_SECONDS = 600TERMINAL = {"completed", "canceled", "failed", "rejected"}STOP = TERMINAL | {"input-required", "auth-required"} # a stream ends here (final: true)ACT_SKILLS = {"design-tests", "run-tests", "test-these-cases"}PATCH_RE = re.compile(r"^\d{2}[A-D]$", re.I) # the release names Astra's research knows (e.g. 26C)# JSON-RPC / A2A error codesTASK_NOT_FOUND, NOT_CANCELABLE, PUSH_UNSUPPORTED, UNSUPPORTED, CONTENT_TYPE, EXT_CARD = -32001, -32002, -32003, -32004, -32005, -32007IO = ["text/plain", "application/json"]SKILLS = [{"id": "assess-readiness", "name": "Assess patch readiness","description": "Readiness of each business area for the latest (or a given) Oracle patch: Ready / Not ready / Held / ""Not tested yet, with scenario counts. Input (optional): DataPart {area, patch}. Scope: read.","tags": ["oracle-fusion", "patch", "readiness"], "examples": ["Is Procure-to-Pay ready for 26C?"],"inputModes": IO, "outputModes": IO},{"id": "design-tests", "name": "Design tests for a patch","description": "Send what your agent found: DataPart {pod: {...}, patch: {id, changes: [{area, description, source_url?}]}, ""mode?: quick|browser, environment?}. Astra proposes a test run of the affected areas (its own ""generator chooses the scenarios; your facts are recorded as data). Reply {confirm: true} on the same ""task to start it. Scope: read,act.","tags": ["oracle-fusion", "patch", "test-design"], "inputModes": ["application/json"], "outputModes": IO},{"id": "test-these-cases", "name": "Test these cases","description": "Your own test cases: DataPart {cases: [{title, area, priority?, steps: [{action, expected?}], data?, ""preconditions?}], environment?} (at most 50). Astra writes the scripts and dry-runs them; a PERSON ""approves them in Astra (never the caller). Then reply {confirm: true} to run the approved ones. ""Scope: read,act.","tags": ["oracle-fusion", "custom-test-cases"], "inputModes": ["application/json"], "outputModes": IO},{"id": "run-tests", "name": "Run tests","description": "Propose a test run: DataPart {area or areas, mode?: quick|browser, environment?, patch?} or text ""('run a quick simulation of Procure-to-Pay'). Reply {confirm: true} on the same task to start it. ""The task then follows the run. Scope: read,act.","tags": ["oracle-fusion", "test-run"], "examples": ["Run a quick simulation of Procure-to-Pay"], "inputModes": IO, "outputModes": IO},{"id": "get-report", "name": "Get a test report","description": "A finished run's report: verdict and QA rule result per area, counts, exit criteria, links, and the ""PDF (opens for a signed-in person). Input: DataPart {run_id}. Scope: read.","tags": ["oracle-fusion", "report"], "inputModes": IO, "outputModes": IO + ["application/pdf"]},]SKILL_IDS = {s["id"] for s in SKILLS}HELP = ("I am Astra: I test Oracle Fusion patches. Skills: " + "; ".join(f"{s['id']} ({s['name']})" for s in SKILLS)+ ". Choose one with message.metadata.skill or a DataPart {\"skill\": ...}. Starting anything needs a confirm, and ""custom test cases need a person's approval in Astra.")class RpcError(Exception):def __init__(self, code: int, message: str):super().__init__(message)self.code = code# ------------------------------------------------------------------------------------------------ caller inputclass Change(BaseModel):model_config = ConfigDict(extra="forbid")area: str = Field(min_length=1, max_length=60)description: str = Field(min_length=1, max_length=2000)source_url: str | None = Field(default=None, max_length=500) # displayed only, never fetchedclass PatchFacts(BaseModel):model_config = ConfigDict(extra="forbid")id: str | None = Field(default=None, max_length=40)changes: list[Change] = Field(default_factory=list, max_length=200)class DesignIn(BaseModel):model_config = ConfigDict(extra="forbid")skill: str | None = Nonepod: dict = Field(default_factory=dict)patch: PatchFacts = Field(default_factory=PatchFacts)areas: list[str] = Field(default_factory=list, max_length=10)mode: str = Field(default="quick", pattern="^(quick|browser)$")environment: str | None = Field(default=None, max_length=60)class RunTestsIn(BaseModel):model_config = ConfigDict(extra="forbid")skill: str | None = Nonearea: str | None = Field(default=None, max_length=60)areas: list[str] = Field(default_factory=list, max_length=10)mode: str = Field(default="quick", pattern="^(quick|browser)$")environment: str | None = Field(default=None, max_length=60)patch: str | None = Field(default=None, max_length=40)def _bad(e: ValidationError) -> RpcError:return RpcError(-32602, "Invalid input: " + "; ".join(f"{'.'.join(str(p) for p in x['loc'])}: {x['msg']}" for x in e.errors()[:8]))def _parts(msg: dict) -> tuple[str, dict | None]:"""The message's text (joined) and its first DataPart. FileParts are accepted and ignored (nothing is fetched)."""texts, data = [], Nonefor p in msg["parts"]:kind = p.get("kind") if isinstance(p, dict) else Noneif kind == "text" and isinstance(p.get("text"), str):texts.append(p["text"])elif kind == "data" and isinstance(p.get("data"), dict):data = p["data"] if data is None else dataelif kind != "file":raise RpcError(-32602, "Each part needs kind text, data or file.")text = "\n".join(texts)if len(text) > MAX_TEXT:raise RpcError(-32602, f"The text is longer than {MAX_TEXT} characters.")return text, datadef _check_message(msg) -> dict:if not isinstance(msg, dict) or msg.get("role") != "user" or not isinstance(msg.get("parts"), list) or not msg["parts"]:raise RpcError(-32602, "params.message needs role 'user' and at least one part.")if len(msg["parts"]) > MAX_PARTS:raise RpcError(-32602, f"At most {MAX_PARTS} parts per message.")for k in ("messageId", "taskId", "contextId"):if msg.get(k) is not None and (not isinstance(msg[k], str) or len(msg[k]) > 100):raise RpcError(-32602, f"message.{k} must be a short string.")return msgdef _agent_message(task_id: str, context_id: str, text: str, data: dict | None = None) -> dict:parts: list[dict] = [{"kind": "text", "text": text}]if data is not None:parts.append({"kind": "data", "data": data})return {"kind": "message", "messageId": uuid.uuid4().hex, "role": "agent", "parts": parts, "taskId": task_id, "contextId": context_id}def _choose_skill(msg: dict, text: str, data: dict | None) -> str | None:named = (msg.get("metadata") or {}).get("skill") if isinstance(msg.get("metadata"), dict) else Nonenamed = named or (data or {}).get("skill")if named:return str(named) if str(named) in SKILL_IDS else Noneif data and "cases" in data:return "test-these-cases"if data and ("patch" in data or "pod" in data):return "design-tests"if data and "run_id" in data:return "get-report"if re.search(r"\breport\b", text or "", re.I):return "get-report"from ..chat.intent import routereturn {"readiness": "assess-readiness", "start_run": "run-tests"}.get(route(text or "").tool)# ------------------------------------------------------------------------------------------------ tasksclass A2AToolbox(Toolbox):VIA = "a2a"def task_out(row: dict, history_length: int | None = None) -> dict:hist = json.loads(row["history_json"] or "[]")status_msg = next((m for m in reversed(hist) if m.get("role") == "agent"), None)if history_length is not None:hist = hist[-history_length:] if history_length > 0 else []return {"kind": "task", "id": row["id"], "contextId": row["context_id"],"status": {"state": row["state"], **({"message": status_msg} if status_msg else {}), "timestamp": row["updated_at"]},"history": hist, "artifacts": json.loads(row["artifacts_json"] or "[]"),"metadata": {"skill": row["skill"], "run_id": row["run_id"], "batch_id": row["batch_id"]}}class Tasks:"""A2A tasks for one caller (token owner + token). Every method is blocking (database): call off the event loop."""def __init__(self, request: Request, user, token: dict):self.request, self.user, self.token = request, user, tokenself.svc, self.runs = request.app.state.svc, request.app.state.runsself.scopes = set(str(token["scopes"]).split(","))def box(self) -> A2AToolbox:return A2AToolbox(self.request, self.user, self.token)def link(self, path: str) -> str:from .mcp import _absreturn _abs(self.svc, path) or pathdef audit(self, kind: str, row: dict | None, summary: str, **payload) -> None:self.svc.audit.append(kind, actor=self.user.username, run_id=(row or {}).get("run_id"), summary=summary[:200],payload={"task": (row or {}).get("id"), "skill": (row or {}).get("skill"), "token_id": self.token["id"], **payload})# -- storagedef get(self, tid: str) -> dict | None:return self.svc.db.one("SELECT * FROM a2a_tasks WHERE id=?", (tid,))def own(self, tid, write: bool = False) -> dict:row = self.get(str(tid)[:100]) if isinstance(tid, str) else Nonemine = row and int(row["user_id"]) == int(self.user.id) and (not write or int(row["token_id"]) == int(self.token["id"]))if not row or not (mine or (not write and self.user.role == "admin")):raise RpcError(TASK_NOT_FOUND, "Task not found.")return rowdef create(self, skill: str, msg: dict, facts: dict | None = None) -> dict:tid = secrets.token_urlsafe(12)ctx = msg.get("contextId") or uuid.uuid4().hexnow = _now()user_msg = {**msg, "taskId": tid, "contextId": ctx, "kind": "message"}self.svc.db.insert("a2a_tasks", {"id": tid, "context_id": ctx, "user_id": self.user.id, "token_id": self.token["id"],"skill": skill, "state": "submitted", "facts_json": json.dumps(facts) if facts else None,"history_json": json.dumps([user_msg]), "artifacts_json": "[]","created_at": now, "updated_at": now})row = self.get(tid)self.audit("a2a.task", row, f"{skill} task from token '{self.token['name']}'")return rowdef update(self, row: dict, **cols) -> dict:cols["updated_at"] = _now()sets = ", ".join(f"{k}=?" for k in cols)self.svc.db.x(f"UPDATE a2a_tasks SET {sets} WHERE id=?", (*cols.values(), row["id"])) # noqa: S608 (column names are ours)return self.get(row["id"])def add_user_message(self, row: dict, msg: dict) -> dict:hist = json.loads(row["history_json"])[-(MAX_HISTORY - 1):] + [{**msg, "kind": "message", "taskId": row["id"], "contextId": row["context_id"]}]return self.update(row, history_json=json.dumps(hist))def state(self, row: dict, state: str, text: str, data: dict | None = None) -> dict:if row["state"] == state and row["status_text"] == text:return rowhist = json.loads(row["history_json"])[-(MAX_HISTORY - 1):] + [_agent_message(row["id"], row["context_id"], text, data)]if row["state"] != state:self.audit("a2a.state", row, f"{row['state']} -> {state}", **{"from": row["state"], "to": state})return self.update(row, state=state, status_text=text, history_json=json.dumps(hist))def artifact(self, row: dict, artifact_id: str, name: str, parts: list[dict], description: str | None = None) -> dict:arts = [a for a in json.loads(row["artifacts_json"]) if a["artifactId"] != artifact_id]arts.append({"artifactId": artifact_id, "name": name, **({"description": description} if description else {}), "parts": parts})return self.update(row, artifacts_json=json.dumps(arts))def claim(self, row: dict) -> bool:"""input-required -> working in one statement: a second confirm racing the first finds nothing to claim."""with self.svc.db.tx() as c:return c.execute("UPDATE a2a_tasks SET state='working', updated_at=? WHERE id=? AND state='input-required'",(_now(), row["id"])).rowcount == 1# -- permissiondef act_refusal(self, skill: str) -> str | None:if "act" not in self.scopes:return ("This token is read-only. Create a token with the 'read and act' scope in Astra ""(Account → Access tokens for AI assistants) to design or run tests.")if not self.user.can("run.start"):return f"Your role ({self.user.role}) can't start test runs in Astra."return None# -- message/senddef send(self, msg: dict) -> dict:_check_message(msg)text, data = _parts(msg)if msg.get("taskId"):row = self.own(msg["taskId"], write=True)if row["state"] in TERMINAL:raise RpcError(UNSUPPORTED, f"This task is {row['state']}. Start a new task (send without taskId).")return self.follow_up(self.add_user_message(row, msg), text, data)skill = _choose_skill(msg, text, data)if skill is None:row = self.create("help", msg)return self.state(row, "completed", HELP, {"skills": sorted(SKILL_IDS)})if skill in ACT_SKILLS:refusal = self.act_refusal(skill)if refusal:row = self.create(skill, msg)self.audit("a2a.refused", row, refusal[:120])return self.state(row, "rejected", refusal)return getattr(self, "skill_" + skill.replace("-", "_"))(msg, text, data or {})# -- read skillsdef skill_assess_readiness(self, msg: dict, text: str, data: dict) -> dict:from ..chat.intent import PATCH_ID, modules_inrow = self.create("assess-readiness", msg)area = data.get("area") if isinstance(data.get("area"), str) else (modules_in(text) or [None])[0]patch = data.get("patch") if isinstance(data.get("patch"), str) else (m.group(1).upper() if (m := PATCH_ID.search(text or "")) else None)try:res = self.box().readiness(area, patch)except ToolFailure as e:return self.state(row, "failed", str(e))text_out = res["content"][0]["text"]row = self.artifact(row, "readiness", "Patch readiness", [{"kind": "text", "text": text_out}, {"kind": "data", "data": res["structuredContent"]}])return self.state(row, "completed", text_out)def skill_get_report(self, msg: dict, text: str, data: dict) -> dict:rid = data.get("run_id") if isinstance(data.get("run_id"), str) else Noneif not rid:rid = next((w for w in re.findall(r"[A-Za-z0-9_-]{6,64}", text or "")[:20] if self.svc.db.get_run(w)), None)row = self.create("get-report", msg)if not rid or not self.svc.db.get_run(rid[:64]):return self.state(row, "rejected", "Say which test run: a DataPart {\"skill\": \"get-report\", \"run_id\": \"...\"}.")row = self.update(row, run_id=rid)return self.report(row, final=True)def report(self, row: dict, final: bool) -> dict:res = self.box().report_summary(row["run_id"])info = res["structuredContent"]parts = [{"kind": "text", "text": res["content"][0]["text"]}, {"kind": "data", "data": info}]parts += [{"kind": "file", "file": {"uri": a["pdf"], "mimeType": "application/pdf", "name": f"patchwise-{row['run_id']}-{a['area'].lower()}.pdf"}}for a in info.get("areas") or [] if a.get("pdf")]row = self.artifact(row, "report", "Test report", parts, "Verdict and QA rule result per area, counts, exit criteria and links. ""Sign-off happens in Astra.")if not final:return rowreturn self.state(row, "completed", res["content"][0]["text"])# -- act skills: propose, then confirm on the same taskdef skill_design_tests(self, msg: dict, text: str, data: dict) -> dict:try:d = DesignIn.model_validate(data)except ValidationError as e:raise _bad(e) from eif len(json.dumps(d.pod)) > 16 * 1024:raise RpcError(-32602, "pod details are larger than 16 KB.")facts = {"pod": d.pod, "patch": d.patch.model_dump()}row = self.create("design-tests", msg, facts)mods, unknown = [], []for a in d.areas + [c.area for c in d.patch.changes]:try:m = _module(a)except ToolFailure:unknown.append(a[:40])continueif m and m not in mods:mods.append(m)patch_id = d.patch.id.upper() if d.patch.id and PATCH_RE.match(d.patch.id) else Nonenote = (f" Your agent's facts are recorded on this task as data ({len(d.patch.changes)} change(s)"+ (f", patch {d.patch.id[:40]}" if d.patch.id else "") + "); Astra's own generator chooses the scenarios"+ (f" for patch {patch_id}" if patch_id else "") + "."+ (f" Areas not recognised: {', '.join(sorted(set(unknown)))}." if unknown else ""))if not mods:from ..chat.intent import MODULE_NAMESreturn self.state(row, "rejected", "None of the areas is a business area Astra tests. Known: "+ ", ".join(f"{k} ({v})" for k, v in MODULE_NAMES.items()) + "." + note)return self.propose(row, mods, d.mode, d.environment, patch_id, note)def skill_run_tests(self, msg: dict, text: str, data: dict) -> dict:if data:try:d = RunTestsIn.model_validate(data)except ValidationError as e:raise _bad(e) from erow = self.create("run-tests", msg)words = ([d.area] if d.area else []) + d.areasmods = []for a in words: # practice-app names here; an Oracle Fusion pod reads its own areas from the wordstry:mods.append(_module(a))except ToolFailure:passpatch = d.patch.upper() if d.patch and PATCH_RE.match(d.patch) else Nonereturn self.propose(row, list(dict.fromkeys(m for m in mods if m)), d.mode, d.environment, patch, "", " , ".join(words))from ..chat.intent import args_fora = args_for("start_run", text, {})row = self.create("run-tests", msg)return self.propose(row, a.get("modules") or [], "browser" if a.get("mode") == "live" else "quick", a.get("pod"), a.get("patch_id"), "", text)def propose(self, row: dict, mods: list[str], mode: str, environment: str | None, patch_id: str | None, note: str,area_text: str | None = None) -> dict:box = self.box()res = box._tools().start_run(modules=mods, mode="live" if mode == "browser" else "stub", pod=environment or None, patch_id=patch_id, # noqa: SLF001area_text=area_text)try:out = box._propose(row["skill"], res, None) # noqa: SLF001except ToolFailure as e:return self.state(row, "rejected", str(e))p = out["structuredContent"]row = self.update(row, proposal_id=p["proposal_id"])row = self.artifact(row, "proposal", "Proposed test run", [{"kind": "data", "data": {"summary": p["summary"], "items": p["items"], "expires_at": p["expires_at"], "facts_recorded": bool(row["facts_json"])}}])items = "\n".join(f"- {i['label']}: {i['value']}" for i in p["items"])return self.state(row, "input-required", f"{p['summary']}\n{items}\n{note.strip()}\n\nReply {{\"confirm\": true}} on this task "f"(taskId {row['id']}) to start it, or call tasks/cancel. The proposal expires {p['expires_at']}.".replace("\n\n\n", "\n\n"))def skill_test_these_cases(self, msg: dict, text: str, data: dict) -> dict:cases = data.get("cases")if not isinstance(cases, list):raise RpcError(-32602, "Send a DataPart {\"cases\": [...]}.")if len(cases) > C.MAX_CASES:raise RpcError(-32602, f"At most {C.MAX_CASES} cases per task ({len(cases)} given).")extra = set(data) - {"skill", "cases", "environment"}if extra:raise RpcError(-32602, f"Unknown fields: {', '.join(sorted(extra))[:200]}.")try: # the strict agent schema: an unknown field or a bad case rejects the whole setparsed = C.CustomCases.model_validate({"cases": cases}).model_dump()["cases"]except ValidationError as e:raise _bad(e) from erow = self.create("test-these-cases", msg)try:ok, warnings = C.validate(parsed, [])if not ok:return self.state(row, "rejected", "None of the cases can be used: " + "; ".join(warnings[:8]))env = data.get("environment")pods = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).list() # seeds the default podpod = next((p for p in pods if p["name"].lower() == str(env)[:60].lower()), None) if env else (pods[0] if pods else None)if env and not pod:return self.state(row, "rejected", f"There is no test environment called '{str(env)[:40]}'.")if not pod:return self.state(row, "rejected", "There is no test environment to dry-run on yet.")batch = C.create_batch(self.svc, self.user.username, "a2a", ok, warnings)row = self.update(row, batch_id=batch["batch_id"])self.audit("a2a.cases", row, f"{len(ok)} custom case(s) sent; build on pod {pod['id']}", batch=batch["batch_id"], cases=len(ok))C.start_build(self.svc, batch["batch_id"], int(pod["id"]), self.user.username)except C.CustomCaseError as e:return self.state(row, "failed", str(e))row = self.state(row, "working", "Writing scripts and dry-running your cases on the pod.")return self.sync(row)# -- follow-ups on an open taskdef follow_up(self, row: dict, text: str, data: dict | None) -> dict:row = self.sync(row)if row["state"] != "input-required":return rowd = data or {}if any(k in d for k in ("approve", "approved", "approve_cases", "sign_off", "signoff", "verdict")):self.audit("a2a.refused", row, "approval or sign-off asked through A2A")return self.state(row, "input-required", "Only a person can approve, decide or sign off, in Astra. "+ (row["status_text"] or ""))if not (d.get("confirm") is True or (text or "").strip().lower().rstrip(".!") == "confirm"):return self.state(row, "input-required", (row["status_text"] or "").split("\n\nReply")[0]+ "\n\nReply {\"confirm\": true} on this task to go on, or call tasks/cancel.")refusal = self.act_refusal(row["skill"])if refusal:return self.state(row, "input-required", refusal)if row["proposal_id"] and not row["run_id"]:return self.confirm_proposal(row)if row["batch_id"] and not row["run_id"]:return self.run_batch(row, d.get("mode") if d.get("mode") in ("quick", "browser") else "quick")return self.sync(row) # a run waiting for a person: a confirm here changes nothingdef confirm_proposal(self, row: dict) -> dict:if not self.claim(row):return self.get(row["id"])try:res = self.box().confirm(row["proposal_id"])["structuredContent"]except ToolFailure as e:row = self.get(row["id"])return self.state({**row, "state": "input-required"}, "failed", str(e))row = self.update(self.get(row["id"]), run_id=res.get("run_id"))self.audit("a2a.confirm", row, f"test run {res.get('run_id')} started")return self.sync(self.state({**row, "state": "input-required"}, "working", f"The test run has started: {res.get('link') or ''}".strip()))def run_batch(self, row: dict, mode: str) -> dict:v = C.view(self.svc, row["batch_id"])keys = [c["key"] for c in v["cases"] if c["state"] == "approved"]if not keys:return self.state(row, "input-required", "No case has been approved by a person yet. "+ f"Waiting for a person to approve the scenarios in Astra: {self.link('/scenarios/import?batch=' + row['batch_id'])}")if not self.claim(row):return self.get(row["id"])row = self.get(row["id"])try:rid = C.run(self.svc, self.runs, row["batch_id"], keys, mode, self.user.username)except C.CustomCaseError as e:return self.state({**row, "state": "input-required"}, "failed", str(e))except ApiError as e: # the emergency stopreturn self.state({**row, "state": "input-required"}, "failed", e.detail)row = self.update(row, run_id=rid)self.audit("a2a.run", row, f"test run {rid} of {len(keys)} approved custom case(s)", batch=row["batch_id"], keys=keys)return self.sync(self.state({**row, "state": "input-required"}, "working", f"Testing {len(keys)} approved case(s): {self.link(f'/runs/{rid}')}"))# -- following a run or a batchdef sync(self, row: dict) -> dict:if row["state"] in TERMINAL:return rowif row["run_id"]:return self.follow_run(row)if row["batch_id"]:return self.follow_batch(row)return rowdef follow_run(self, row: dict) -> dict:from ..chat.tools import STATUS_WORDSrid = row["run_id"]run = self.svc.db.get_run(rid)if not run:return self.state(row, "failed", "The test run no longer exists.")st, gate = run.get("status"), run.get("pending_gate")if gate == "approve_cases" or st == "waiting_approval":return self.state(row, "input-required", f"Waiting for a person to approve the scenarios in Astra: {self.link(f'/runs/{rid}/scenarios')}")if gate == "sign_in" or st == "waiting_sign_in":return self.state(row, "input-required", f"Waiting for a person to sign in to the pod in Astra: {self.link(f'/runs/{rid}')}")if gate == "human_review" or st == "waiting_review":return self.state(row, "input-required", f"Waiting for a person to decide the failures in Astra: {self.link(f'/runs/{rid}/failures')}")if st == "completed":row = self.report(row, final=False)return self.state(row, "completed", f"The test run finished. Report: {self.link(f'/runs/{rid}/report')}")if st in ("failed", "killed"):return self.state(row, "failed", f"The test run {STATUS_WORDS.get(st, st)}." + (f" {str(run.get('error'))[:200]}" if run.get("error") else ""))if st == "cancelled":return self.state(row, "canceled", "The test run was cancelled.")step = f" ({run['current_node']})" if run.get("current_node") else ""return self.state(row, "working", f"Testing: {STATUS_WORDS.get(st, st)}{step}. Follow it in Astra: {self.link(f'/runs/{rid}')}")def follow_batch(self, row: dict) -> dict:try:v = C.view(self.svc, row["batch_id"])except C.CustomCaseError as e:return self.state(row, "failed", str(e))cases = [{k: c.get(k) for k in ("key", "title", "area", "state", "case_id", "failed_step", "message", "simulated", "decided_by")}for c in v["cases"]]row = self.artifact(row, "cases", "Your test cases", [{"kind": "data", "data": {"batch_id": row["batch_id"], "status": v["status"], "pod": v["pod"], "cases": cases}}])link = self.link(f"/scenarios/import?batch={row['batch_id']}")if v["status"] in ("parsed", "building"):return self.state(row, "working", "Writing scripts and dry-running your cases on the pod.")if v["status"] == "failed":return self.state(row, "failed", f"The scripts could not be built: {v.get('message') or 'see Astra'}.")by = lambda s: [c for c in cases if c["state"] == s] # noqa: E731approved, waiting = by("approved"), by("dry_run_passed")if waiting:return self.state(row, "input-required", f"{len(waiting)} case(s) passed their dry run. Waiting for a person to approve the "f"scenarios in Astra: {link}" + (f" ({len(approved)} already approved: reply {{\"confirm\": true}} to run those.)" if approved else ""))if approved:return self.state(row, "input-required", f"A person approved {len(approved)} case(s). Reply {{\"confirm\": true}} on this task ""to run them (optionally with \"mode\": \"quick\" or \"browser\").")return self.state(row, "completed", f"None of the cases can run: {len(by('not_scriptable'))} could not be scripted, "f"{len(by('dry_run_failed'))} failed their dry run, {len(by('rejected'))} rejected. Details are in the 'cases' artifact.")# -- tasks/canceldef cancel(self, tid) -> dict:row = self.own(tid, write=True)row = self.sync(row)if row["state"] in TERMINAL:raise RpcError(NOT_CANCELABLE, f"Task cannot be canceled: it is already {row['state']}.")if "act" not in self.scopes:raise RpcError(NOT_CANCELABLE, "This token is read-only.")if row["run_id"]:from . import actionsrun = self.svc.db.get_run(row["run_id"]) or {}if not (self.user.can("run.control") and (run.get("created_by") == self.user.username or self.user.role == "admin")):raise RpcError(NOT_CANCELABLE, "You can't cancel that test run (it isn't yours, or your role can't cancel runs).")try:actions.cancel_run(self.svc, self.runs, row["run_id"], self.user.username, "cancelled by an agent (A2A)", via="a2a")except ApiError as e:raise RpcError(NOT_CANCELABLE, e.detail) from eelif row["proposal_id"]:try:self.box().cancel(row["proposal_id"])except ToolFailure:pass # expired or already used: nothing to dropself.audit("a2a.cancel", row, "task canceled")return self.state(row, "canceled", "Canceled." + (" The test run was cancelled." if row["run_id"] else " Nothing was started."))# ------------------------------------------------------------------------------------------------ transportdef agent_card(request: Request) -> dict:svc = request.app.state.svcbase = (svc.cfg.public_url or str(request.base_url)).rstrip("/")return {"protocolVersion": PROTOCOL_VERSION, "name": "Astra","description": "Astra tests Oracle Fusion patches before they go live: readiness per business area, test design ""and runs on a test pod, your own test cases (a person approves them), and the report. Starting ""anything needs a confirm; approvals and sign-off stay with people in Astra.","url": f"{base}/a2a", "preferredTransport": "JSONRPC", "version": VERSION,"provider": {"organization": "Astra", "url": base},"capabilities": {"streaming": True, "pushNotifications": False, "stateTransitionHistory": True},"defaultInputModes": IO, "defaultOutputModes": IO,"securitySchemes": {"bearer": {"type": "http", "scheme": "bearer","description": "Astra access token (pwt_…) from Account → Access tokens for AI assistants"}},"security": [{"bearer": []}],"skills": SKILLS,"supportsAuthenticatedExtendedCard": False,}@router.get("/.well-known/agent-card.json", include_in_schema=False)def well_known_card(request: Request) -> JSONResponse:card = {k: v for k, v in agent_card(request).items() if v is not None}return JSONResponse(card, headers={"Cache-Control": "public, max-age=300"})def _ok(mid, result) -> dict:return {"jsonrpc": "2.0", "id": mid, "result": result}def _err(mid, code: int, message: str) -> dict:return {"jsonrpc": "2.0", "id": mid, "error": {"code": code, "message": message}}def _history_length(params: dict) -> int | None:h = params.get("historyLength", (params.get("configuration") or {}).get("historyLength") if isinstance(params.get("configuration"), dict) else None)return max(0, min(int(h), MAX_HISTORY)) if isinstance(h, int) and not isinstance(h, bool) else Nonedef _dispatch(tasks: Tasks, method: str, params: dict) -> dict:"""The task (as the protocol shows it) for a non-streaming method, or RpcError."""if method == "message/send":cfg = params.get("configuration") or {}if isinstance(cfg, dict) and cfg.get("pushNotificationConfig"):raise RpcError(PUSH_UNSUPPORTED, "Push notifications are not supported: poll tasks/get or use message/stream.")return task_out(tasks.send(params.get("message")), _history_length(params))if method == "tasks/get":return task_out(tasks.sync(tasks.own(params.get("id"))), _history_length(params))if method == "tasks/cancel":return task_out(tasks.cancel(params.get("id")))if method.startswith("tasks/pushNotificationConfig/"):raise RpcError(PUSH_UNSUPPORTED, "Push notifications are not supported.")if method == "agent/getAuthenticatedExtendedCard":raise RpcError(EXT_CARD, "There is no extended agent card.")raise RpcError(-32601, f"Method not found: {method[:60]}")def _handle(body, request: Request, user, token: dict) -> dict:if not isinstance(body, dict) or body.get("jsonrpc") != "2.0" or not isinstance(body.get("method"), str):return _err(body.get("id") if isinstance(body, dict) else None, -32600, "Invalid request")mid, params = body.get("id"), body.get("params") or {}if not isinstance(params, dict):return _err(mid, -32602, "params must be an object")try:return _ok(mid, _dispatch(Tasks(request, user, token), body["method"], params))except RpcError as e:return _err(mid, e.code, str(e))except Exception: # noqa: BLE001 (never a stack trace to the caller; the log has it)log.exception("a2a %s failed", body["method"][:40])return _err(mid, -32603, "Astra could not complete that. Try again, or open the app.")def _sse(obj: dict) -> bytes:return f"data: {json.dumps(obj, separators=(',', ':'))}\n\n".encode()async def _stream(request: Request, tasks: Tasks, mid, method: str, params: dict):"""message/stream and tasks/resubscribe: the Task, then status and artifact updates until input-required or a finalstate (final: true), or STREAM_MAX_SECONDS (then final: true while still working: resubscribe or poll tasks/get)."""def first():if method == "message/stream":return tasks.send(params.get("message"))return tasks.sync(tasks.own(params.get("id")))try:row = await run_in_threadpool(first)except RpcError as e:yield _sse(_err(mid, e.code, str(e)))returnexcept Exception: # noqa: BLE001log.exception("a2a %s failed", method)yield _sse(_err(mid, -32603, "Astra could not complete that."))returnprev = task_out(row, _history_length(params))yield _sse(_ok(mid, prev))status = {"kind": "status-update", "taskId": row["id"], "contextId": row["context_id"]}if row["state"] in STOP:yield _sse(_ok(mid, {**status, "status": prev["status"], "final": True}))returndeadline = time.monotonic() + STREAM_MAX_SECONDSwhile time.monotonic() < deadline:if await request.is_disconnected():returnawait asyncio.sleep(STREAM_POLL_SECONDS)row = await run_in_threadpool(lambda: tasks.sync(tasks.get(row["id"])))cur = task_out(row)old = {a["artifactId"]: a for a in prev["artifacts"]}for a in cur["artifacts"]:if old.get(a["artifactId"]) != a:yield _sse(_ok(mid, {"kind": "artifact-update", "taskId": row["id"], "contextId": row["context_id"], "artifact": a,"append": False, "lastChunk": True}))done = row["state"] in STOPif cur["status"]["state"] != prev["status"]["state"] or cur["status"].get("message") != prev["status"].get("message") or done:yield _sse(_ok(mid, {**status, "status": cur["status"], "final": done}))if done:returnprev = curyield _sse(_ok(mid, {**status, "status": prev["status"], "final": True}))@router.post("/a2a", include_in_schema=False)async def a2a_post(request: Request) -> Response:if not mcp._origin_ok(request): # noqa: SLF001return JSONResponse({"error": "forbidden", "detail": "origin not allowed"}, status_code=403)authz = request.headers.get("authorization", "")if not authz.lower().startswith("bearer "):return mcp._unauthorized("a personal access token is required: Authorization: Bearer pwt_...") # noqa: SLF001got = TokenStore(request.app.state.svc).resolve(authz[7:].strip())if not got:return mcp._unauthorized("the token is unknown, revoked or expired, or its owner is disabled") # noqa: SLF001user, token = gotrequest.state.user = userif not mcp._rate_ok(int(token["id"])): # noqa: SLF001 (one budget per token across /mcp and /a2a)return JSONResponse(_err(None, -32000, "Too many requests: at most 60 a minute per token"), status_code=429, headers={"Retry-After": "60"})if int(request.headers.get("content-length") or 0) > MAX_BODY:return JSONResponse(_err(None, -32600, "Request too large (256 KB at most)"), status_code=413)raw = await request.body()if len(raw) > MAX_BODY:return JSONResponse(_err(None, -32600, "Request too large (256 KB at most)"), status_code=413)try:body = json.loads(raw or b"null")except ValueError:return JSONResponse(_err(None, -32700, "Parse error"), status_code=400)token = dict(token)if isinstance(body, dict) and body.get("jsonrpc") == "2.0" and body.get("method") in ("message/stream", "tasks/resubscribe"):params = body.get("params") if isinstance(body.get("params"), dict) else {}return StreamingResponse(_stream(request, Tasks(request, user, token), body.get("id"), body["method"], params),media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})return JSONResponse(await run_in_threadpool(_handle, body, request, user, token))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163"""FastAPI app factory. Same origin: `/` = built web app (web/dist), `/api` = API, `/api/docs` = OpenAPI UI.Lifespan starts the RunManager worker and the Scheduler; crash recovery marks running runs 'interrupted'."""from __future__ import annotationsimport loggingfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom fastapi import APIRouter, FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponsefrom ..config import VERSION, Settings, get_settingsfrom ..graph.services import Services, build_servicesfrom ..platform.scheduler import Schedulerfrom . import errorsfrom .middleware import RequestContext, setup_loggingfrom . import a2a, mcpfrom .routes import admin, agent_studio, ai_monitoring, assistant, auth, channels, chat, consultant, custom_cases, gates, integrations, live, llm, notifications, pods, review, runs, screens, tokensfrom .runner import RunManagerlog = logging.getLogger("fpt.api")def _orchestrator(svc: Services, cfg: Settings):"""FPT_ORCHESTRATOR=temporal (default): Temporal client + Temporal Schedules. Falls back to the in-process LangGraphRunManager + Scheduler when Temporal is unreachable (reported by /api/ready)."""if cfg.orchestrator == "temporal":try:from ..workflows.client import TemporalRunManager, TemporalSchedulerrm = TemporalRunManager(svc)if cfg.embedded_worker:from ..workflows.worker import start_embeddedstart_embedded(svc)return rm, TemporalScheduler(svc, rm)except Exception as e: # noqa: BLE001log.warning("Temporal unreachable at %s (%s): falling back to the in-process LangGraph orchestrator",cfg.temporal_address, type(e).__name__)rm = RunManager(svc)rm.fallback_reason = f"temporal unreachable at {cfg.temporal_address}"return rm, Scheduler(svc, rm, cfg.scheduler_tick_s)rm = RunManager(svc)return rm, Scheduler(svc, rm, cfg.scheduler_tick_s)def create_app(svc: Services | None = None, cfg: Settings | None = None, *, background: bool = True, transport=None) -> FastAPI:cfg = cfg or (svc.cfg if svc else get_settings())svc = svc or build_services(cfg, transport=transport)setup_logging(logfile=cfg.path("logs", "api.jsonl"))if svc.users.bootstrap_from_env():log.info("bootstrap admin created from FPT_BOOTSTRAP_ADMIN_USER")run_mgr, sched = _orchestrator(svc, cfg)@asynccontextmanagerasync def lifespan(app: FastAPI):_error_tracking()recovered = run_mgr.recover()from ..platform import liveviewliveview.sweep(svc) # live-view folders left behind by a crashif recovered:log.warning("marked %d run(s) interrupted after restart", len(recovered))from ..platform.pods import PodRegistrycut = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).recover_screens()if cut:log.warning("marked the screen reading of pod(s) %s interrupted after restart", cut)syncer = Noneif background:run_mgr.start_worker()sched.start()from ..platform import notifynotify.get(svc).start()from ..channels import telegram as tg_channeltg_channel.start(svc, run_mgr) # the two-way bot: listens only when the bot token is setfrom ..platform.agent_studio import AgentStudio, CourierAgentStudio(svc).ensure_from_env() # the Fusion tool's client survives a restart without saved statecourier = Courier(svc, run_mgr, watch_hours=cfg.agent_studio_watch_hours)courier.start() # callbacks to Oracle AI Agent Studio, and the release watchapp.state.courier = courierfrom ..platform import statesyncif statesync.enabled(svc):syncer = statesync.Syncer(svc, cfg.state_sync_interval_s)syncer.start()app.state.syncer = syncerlog.info("state is saved to Supabase Storage every %ss when it changes", syncer.interval)yield# Shutdown: stop taking new work, let a running run stop at its next step (bounded: the host does not wait long),# then the one last save, then everything else. Saving before the run stopped kept it as "running", so it came# back interrupted after the restart.if getattr(app.state, "courier", None):app.state.courier.stop()sched.stop()stop_runs = getattr(run_mgr, "stop_for_shutdown", None) # the Temporal orchestrator keeps its runs itselfif stop_runs and not stop_runs(cfg.shutdown_run_wait_s):log.warning("a run step was still going after %ss: saving without it (that run comes back interrupted)",cfg.shutdown_run_wait_s)if syncer:syncer.stop() # stops the saver and makes the last saverun_mgr.stop()from ..platform import notifynotify.get(svc).stop()from ..channels import telegram as tg_channeltg_channel.stop(svc)app = FastAPI(title="Astra API", version=VERSION, lifespan=lifespan,description="Pilot backend. Runs against the local mock app or a registered Oracle Fusion TEST pod (never production); ""every run and report names its target.",docs_url="/api/docs" if svc.cfg.api_docs else None, redoc_url=None,openapi_url="/api/openapi.json" if svc.cfg.api_docs else None)app.state.svc, app.state.runs, app.state.scheduler, app.state.inline_worker = svc, run_mgr, sched, not backgrounderrors.install(app)app.add_middleware(CORSMiddleware, allow_origins=cfg.cors_origins, allow_credentials=True,allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],allow_headers=["Authorization", "Content-Type", "X-CSRF-Token", "X-Request-ID", "Last-Event-ID"],expose_headers=["X-Request-ID"])app.add_middleware(RequestContext)api = APIRouter(prefix="/api")for r in (auth.router, runs.router, gates.router, review.router, admin.router, pods.router, screens.router, consultant.router, live.router, chat.router, assistant.router, llm.router, notifications.router, channels.router, integrations.router, tokens.router, custom_cases.router, agent_studio.router, ai_monitoring.router):api.include_router(r)app.include_router(api)app.include_router(agent_studio.oauth) # /oauth/token: the Oracle AI Agent Studio client (docs/AGENT_STUDIO.md)app.include_router(mcp.router) # /mcp: the MCP connector (personal access tokens only; docs/MCP.md)app.include_router(a2a.router) # /a2a + /.well-known/agent-card.json: the A2A agent (same tokens; docs/A2A.md)@app.api_route("/api/{rest:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"], include_in_schema=False)def api_404(rest: str, request: Request):return JSONResponse({"detail": f"no such endpoint /api/{rest}", "code": "NOT_FOUND","request_id": getattr(request.state, "request_id", None)}, status_code=404)dist = Path(cfg.web_dist)@app.get("/{path:path}", include_in_schema=False)def spa(path: str):if not (dist / "index.html").exists():return JSONResponse({"detail": "web app not built: run `fpt.cmd package` or `npm --prefix web run build`","code": "WEB_NOT_BUILT"}, status_code=404)f = (dist / path).resolve()if path and f.is_file() and f.is_relative_to(dist.resolve()):headers = {"Cache-Control": "public, max-age=31536000, immutable"} if path.startswith("assets/") else {}return FileResponse(f, headers=headers)return FileResponse(dist / "index.html", headers={"Cache-Control": "no-cache"})return appdef app_from_env() -> FastAPI: # uvicorn factory: `uvicorn coworker.api.app:app_from_env --factory`return create_app()def _error_tracking() -> None:"""Optional, Sentry-compatible error tracking: on when SENTRY_DSN is set and the sentry-sdk package is installed(not a dependency of the app). Request bodies and personal data are not sent."""import osdsn = os.environ.get("SENTRY_DSN", "")if not dsn:returntry:import sentry_sdkexcept ImportError:log.warning("SENTRY_DSN is set but sentry-sdk is not installed; error tracking is off")returnsentry_sdk.init(dsn=dsn, send_default_pii=False, max_request_body_size="never", traces_sample_rate=0.0,environment=os.environ.get("FPT_ENVIRONMENT", "production"))123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172"""FastAPI app factory. Same origin: `/` = built web app (web/dist), `/api` = API, `/api/docs` = OpenAPI UI.Lifespan starts the RunManager worker and the Scheduler; crash recovery marks running runs 'interrupted'."""from __future__ import annotationsimport loggingfrom contextlib import asynccontextmanagerfrom pathlib import Pathfrom fastapi import APIRouter, FastAPI, Requestfrom fastapi.middleware.cors import CORSMiddlewarefrom fastapi.responses import FileResponse, JSONResponsefrom ..config import VERSION, Settings, get_settingsfrom ..graph.services import Services, build_servicesfrom ..platform.scheduler import Schedulerfrom . import errorsfrom .middleware import RequestContext, setup_loggingfrom . import a2a, mcpfrom .routes import admin, agent_studio, ai_monitoring, assistant, auth, channels, chat, consultant, custom_cases, gates, heals, integrations, live, llm, notifications, pods, recordings, review, runs, screens, signin, tokensfrom .runner import RunManagerlog = logging.getLogger("fpt.api")def _orchestrator(svc: Services, cfg: Settings):"""FPT_ORCHESTRATOR=temporal (default): Temporal client + Temporal Schedules. Falls back to the in-process LangGraphRunManager + Scheduler when Temporal is unreachable (reported by /api/ready)."""if cfg.orchestrator == "temporal":try:from ..workflows.client import TemporalRunManager, TemporalSchedulerrm = TemporalRunManager(svc)if cfg.embedded_worker:from ..workflows.worker import start_embeddedstart_embedded(svc)return rm, TemporalScheduler(svc, rm)except Exception as e: # noqa: BLE001log.warning("Temporal unreachable at %s (%s): falling back to the in-process LangGraph orchestrator",cfg.temporal_address, type(e).__name__)rm = RunManager(svc)rm.fallback_reason = f"temporal unreachable at {cfg.temporal_address}"return rm, Scheduler(svc, rm, cfg.scheduler_tick_s)rm = RunManager(svc)return rm, Scheduler(svc, rm, cfg.scheduler_tick_s)def create_app(svc: Services | None = None, cfg: Settings | None = None, *, background: bool = True, transport=None) -> FastAPI:cfg = cfg or (svc.cfg if svc else get_settings())svc = svc or build_services(cfg, transport=transport)setup_logging(logfile=cfg.path("logs", "api.jsonl"))if svc.users.bootstrap_from_env():log.info("bootstrap admin created from FPT_BOOTSTRAP_ADMIN_USER")reset = svc.users.reset_admin_from_env()if reset: # audited, and loud: the secret should be deleted now that it has been usedsvc.audit.append("users.admin_password_reset", actor="server-secret", summary=f"{reset}: password reset from FPT_ADMIN_PASSWORD_RESET")log.warning("administrator %s password reset from FPT_ADMIN_PASSWORD_RESET: delete that secret now", reset)run_mgr, sched = _orchestrator(svc, cfg)@asynccontextmanagerasync def lifespan(app: FastAPI):_error_tracking()recovered = run_mgr.recover()from ..platform import assisted_signin, liveviewliveview.sweep(svc) # live-view folders left behind by a crashassisted_signin.sweep(svc) # captured sessions of runs that ended while the server was down, sign-in browser foldersif recovered:log.warning("marked %d run(s) interrupted after restart", len(recovered))from ..platform.pods import PodRegistrycut = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).recover_screens()if cut:log.warning("marked the screen reading of pod(s) %s interrupted after restart", cut)syncer = Noneif background:run_mgr.start_worker()sched.start()from ..platform import notifynotify.get(svc).start()from ..channels import telegram as tg_channeltg_channel.start(svc, run_mgr) # the two-way bot: listens only when the bot token is setfrom ..platform.agent_studio import AgentStudio, CourierAgentStudio(svc).ensure_from_env() # the Fusion tool's client survives a restart without saved statecourier = Courier(svc, run_mgr, watch_hours=cfg.agent_studio_watch_hours)courier.start() # callbacks to Oracle AI Agent Studio, and the release watchapp.state.courier = courierfrom ..platform import statesyncif statesync.enabled(svc):syncer = statesync.Syncer(svc, cfg.state_sync_interval_s)syncer.start()app.state.syncer = syncerlog.info("state is saved to Supabase Storage every %ss when it changes", syncer.interval)yield# Shutdown: stop taking new work, let a running run stop at its next step (bounded: the host does not wait long),# then the one last save, then everything else. Saving before the run stopped kept it as "running", so it came# back interrupted after the restart.if getattr(app.state, "courier", None):app.state.courier.stop()app.state.sign_in.close_all() # an open sign-in browser closes with the server (the run keeps waiting)sched.stop()stop_runs = getattr(run_mgr, "stop_for_shutdown", None) # the Temporal orchestrator keeps its runs itselfif stop_runs and not stop_runs(cfg.shutdown_run_wait_s):log.warning("a run step was still going after %ss: saving without it (that run comes back interrupted)",cfg.shutdown_run_wait_s)if syncer:syncer.stop() # stops the saver and makes the last saverun_mgr.stop()from ..platform import notifynotify.get(svc).stop()from ..channels import telegram as tg_channeltg_channel.stop(svc)app = FastAPI(title="Astra API", version=VERSION, lifespan=lifespan,description="Pilot backend. Runs against the local mock app or a registered Oracle Fusion TEST pod (never production); ""every run and report names its target.",docs_url="/api/docs" if svc.cfg.api_docs else None, redoc_url=None,openapi_url="/api/openapi.json" if svc.cfg.api_docs else None)app.state.svc, app.state.runs, app.state.scheduler, app.state.inline_worker = svc, run_mgr, sched, not backgroundfrom ..platform.assisted_signin import SignInSessionsapp.state.sign_in = SignInSessions(svc, run_mgr) # assisted sign-in browsers (routes/signin.py)run_mgr.sign_in = app.state.sign_in # a run that ends closes its own and drops its captured sessionerrors.install(app)app.add_middleware(CORSMiddleware, allow_origins=cfg.cors_origins, allow_credentials=True,allow_methods=["GET", "POST", "PUT", "PATCH", "DELETE"],allow_headers=["Authorization", "Content-Type", "X-CSRF-Token", "X-Request-ID", "Last-Event-ID"],expose_headers=["X-Request-ID"])app.add_middleware(RequestContext)api = APIRouter(prefix="/api")for r in (auth.router, runs.router, gates.router, review.router, admin.router, pods.router, screens.router, consultant.router, live.router, chat.router, assistant.router, llm.router, notifications.router, channels.router, integrations.router, tokens.router, custom_cases.router, recordings.router, heals.router, agent_studio.router, ai_monitoring.router, signin.router):api.include_router(r)app.include_router(api)app.include_router(agent_studio.oauth) # /oauth/token: the Oracle AI Agent Studio client (docs/AGENT_STUDIO.md)app.include_router(mcp.router) # /mcp: the MCP connector (personal access tokens only; docs/MCP.md)app.include_router(a2a.router) # /a2a + /.well-known/agent-card.json: the A2A agent (same tokens; docs/A2A.md)@app.api_route("/api/{rest:path}", methods=["GET", "POST", "PUT", "PATCH", "DELETE"], include_in_schema=False)def api_404(rest: str, request: Request):return JSONResponse({"detail": f"no such endpoint /api/{rest}", "code": "NOT_FOUND","request_id": getattr(request.state, "request_id", None)}, status_code=404)dist = Path(cfg.web_dist)@app.get("/{path:path}", include_in_schema=False)def spa(path: str):if not (dist / "index.html").exists():return JSONResponse({"detail": "web app not built: run `fpt.cmd package` or `npm --prefix web run build`","code": "WEB_NOT_BUILT"}, status_code=404)f = (dist / path).resolve()if path and f.is_file() and f.is_relative_to(dist.resolve()):headers = {"Cache-Control": "public, max-age=31536000, immutable"} if path.startswith("assets/") else {}return FileResponse(f, headers=headers)return FileResponse(dist / "index.html", headers={"Cache-Control": "no-cache"})return appdef app_from_env() -> FastAPI: # uvicorn factory: `uvicorn coworker.api.app:app_from_env --factory`return create_app()def _error_tracking() -> None:"""Optional, Sentry-compatible error tracking: on when SENTRY_DSN is set and the sentry-sdk package is installed(not a dependency of the app). Request bodies and personal data are not sent."""import osdsn = os.environ.get("SENTRY_DSN", "")if not dsn:returntry:import sentry_sdkexcept ImportError:log.warning("SENTRY_DSN is set but sentry-sdk is not installed; error tracking is off")returnsentry_sdk.init(dsn=dsn, send_default_pii=False, max_request_body_size="never", traces_sample_rate=0.0,environment=os.environ.get("FPT_ENVIRONMENT", "production"))
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287"""Functional-consultant read models over platform/readiness.py: patch readiness per business process, scenarios inplain language, failures in business words, the scenario library, and sign-off. Nothing here decides GO/NO-GO: thatstays the QA rule's result (reports/generate_report.py); sign-off is an audit entry and a run note.Rebuilt by the lead after the original route file was overwritten; the contract is coworker/tests/test_consultant.pyand the paths the web app calls (web/src/api/hooks.ts)."""from __future__ import annotationsimport refrom fastapi import APIRouter, Depends, Query, Requestfrom fastapi.responses import Responsefrom pydantic import BaseModel, ConfigDict, Fieldfrom ...config import ROOTfrom ...platform import readiness as Rfrom ...platform.rundb import now_isofrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom .live import MODULE_NAMESrouter = APIRouter(tags=["consultant"])_ID = re.compile(r"[A-Z][A-Z0-9]{1,5}(-[A-Z0-9]+)+")def _ctx(request: Request):return request.app.state.svc, request.app.state.runsdef _run(svc, run_id: str) -> dict:r = svc.db.get_run(run_id)if not r:raise ApiError(404, "NOT_FOUND", f"run {run_id} not found")return rdef _signoff(svc, run_id: str) -> dict | None:row = svc.db.one("SELECT ts, actor, payload FROM audit_log WHERE kind='run.signoff' AND run_id=? ORDER BY seq DESC LIMIT 1", (run_id,))if not row:return Nonep = row["payload"] if isinstance(row["payload"], dict) else {}return {"by": row["actor"], "role": p.get("role"), "at": row["ts"], "decisions": p.get("decisions") or {}, "comment": p.get("comment")}# ------------------------------------------------------------------ readiness@router.get("/readiness")def readiness(request: Request, pod_id: int | None = None, patch_id: str | None = None, modules: str | None = None,user: Principal = Depends(require("read"))):"""Patch readiness per business process for a pod (+ patch): latest test run per module, or the baseline(process steps + what the patch changes, labelled UNVERIFIED) when nothing has run yet."""svc, runs = _ctx(request)mods = [m.strip().upper() for m in modules.split(",") if m.strip()] if modules else Nonereturn R.readiness(svc, runs, pod_id, patch_id, mods)@router.get("/runs/{run_id}/readiness")def run_readiness(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = _ctx(request)_run(svc, run_id)return {**R.run_readiness(svc, runs, run_id), "signoff": _signoff(svc, run_id)}# ------------------------------------------------------------------ scenarios of a run / failuresdef _scenarios_view(svc, runs, run: dict) -> dict:"""Every scenario of a test run in plain language; shared by the screen and the Excel test script."""run_id = run["run_id"]state = runs.state(run_id)gate = runs.gate_payload(run_id) if run.get("pending_gate") else Nonepending = {p["id"]: p for p in (gate or {}).get("pending", [])} if (gate or {}).get("gate") == "approve_cases" else {}outcomes = (state.get("run_results") or {}).get("outcomes") or {}steps_cache: dict[str, list[dict]] = {}ai_by_id = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}out, seen = [], set()cases = list(state.get("test_cases") or []) + [p for p in pending.values() if p["id"] not in {c["id"] for c in state.get("test_cases") or []}]for c in cases:cid = c["id"]if cid in seen:continueseen.add(cid)module = c.get("module") or cid.split("-", 1)[0]steps = steps_cache.setdefault(module, R.module_steps(module))ai = ai_by_id.get(cid)d = R.scenario_detail(cid, steps, state, path=c.get("yaml_path") if ai else None)if d is not None and ai: # written by the AI model: say so, with its dry run on the podd["why"] = [f"Written by the AI model: {ai['why']}" if ai.get("why") else "Written by the AI model"] + d["why"]d.update(written_by="AI model", dry_run=ai.get("dry_run"), ai_status=ai.get("status"))if d is None: # a generated draft: no library entry yet, show what the generator proposedst = R.step_for_case({"id": cid, "map_ids": c.get("map_ids") or [], "process": c.get("process")}, steps)pr = str(c.get("priority") or "")[:2]d = {"id": cid, "title": c.get("title"), "module": module, "process": c.get("process"), "step": st["name"] if st else None,"priority": pr, "priority_words": R.PRIORITY_WORDS.get(pr, "Unrated"), "roles": [], "preconditions": [], "steps": [],"expected_result": "", "test_data": [], "why": ["New scenario drafted for a gap this patch touches"],"verification": "UNVERIFIED", "map_ids": c.get("map_ids") or [], "approval_status": "draft"}d.update(origin=c.get("origin") or "library", pending=cid in pending, outcome=outcomes.get(cid),diff=(pending.get(cid) or {}).get("diff"))out.append(d)out.sort(key=lambda s: (not s["pending"], s["priority"] or "P9", s["id"]))deferred = [{"id": d.get("id"), "reason": d.get("reason")} for d in state.get("deferred") or [] if isinstance(d, dict)]return {"run_id": run_id, "scenarios": out, "deferred": deferred, "pending": len(pending), "policy": (gate or {}).get("policy")}@router.get("/runs/{run_id}/scenarios")def run_scenarios(run_id: str, request: Request, user: Principal = Depends(require("read"))):"""Every scenario of the test run in plain language (steps, role, test data, expected result, why it is included)."""svc, runs = _ctx(request)return _scenarios_view(svc, runs, _run(svc, run_id))def test_script_xlsx(svc, runs, run_id: str, actor: str) -> Response:"""The test script as an Excel workbook for offline verification: one row per step (action, expected result),reviewer columns to fill in, and the results once the scenarios have run. Audited as an export."""from ...platform import test_scriptrun = _run(svc, run_id)view = _scenarios_view(svc, runs, run)gate = runs.gate_payload(run_id) if run.get("pending_gate") else Nonefailures = R.failures(svc, run_id, runs.state(run_id), gate)order: dict[str, int] = {}for m in sorted({s_.get("module") or "" for s_ in view["scenarios"]}):for i, st in enumerate(R.module_steps(m)):order.setdefault(st["name"], i)data = test_script.build(run, view["scenarios"], failures, area_names=MODULE_NAMES, signoff=_signoff(svc, run_id), step_order=order)svc.audit.append("export.test_script", actor=actor, run_id=run_id, summary=f"{len(view['scenarios'])} scenario(s) to Excel",payload={"scenarios": len(view["scenarios"]), "bytes": len(data)})return Response(content=data, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",headers={"Content-Disposition": f'attachment; filename="test-script-{run_id}.xlsx"', "Cache-Control": "no-store"})@router.get("/runs/{run_id}/test-script.xlsx")def run_test_script(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = _ctx(request)return test_script_xlsx(svc, runs, run_id, user.username)@router.get("/share/runs/{run_id}/test-script.xlsx")def shared_test_script(run_id: str, request: Request, exp: int = Query(...), sig: str = Query(..., max_length=80)):"""The same workbook from a signed link (platform/links.py) in an e-mail Oracle Fusion sends: no login, this run only,read-only, until the link expires."""from ...platform import linkssvc, runs = _ctx(request)if not links.verify(svc, run_id, "test-script.xlsx", exp, sig):raise ApiError(403, "LINK_EXPIRED", "This download link has expired or is not valid. Open the run in Astra, or ask for a new e-mail.")return test_script_xlsx(svc, runs, run_id, "signed link (e-mail)")@router.get("/runs/{run_id}/failures")def run_failures(run_id: str, request: Request, user: Principal = Depends(require("read"))):"""Failed or flaky scenarios in business words: process step, expected vs actual, screenshot ids, suggestion."""svc, runs = _ctx(request)run = _run(svc, run_id)gate = runs.gate_payload(run_id) if run.get("pending_gate") else Nonereturn R.failures(svc, run_id, runs.state(run_id), gate)# ------------------------------------------------------------------ sign-offclass SignOffIn(BaseModel):model_config = ConfigDict(extra="forbid")comment: str | None = Field(default=None, max_length=1000)@router.get("/runs/{run_id}/signoff")def get_signoff(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, _ = _ctx(request)_run(svc, run_id)return _signoff(svc, run_id)@router.post("/runs/{run_id}/signoff", status_code=201)def signoff(run_id: str, body: SignOffIn, request: Request, user: Principal = Depends(require("run.signoff"))):"""Records that a QA approver signed off the finished test run. It does NOT change the decision (that stays the QArule's result in generate_report.py); it is an audit entry and a run note."""svc, runs = _ctx(request)run = _run(svc, run_id)if run["status"] != "completed":raise ApiError(409, "NOT_FINISHED", "only a finished test run can be signed off")decisions = runs.state(run_id).get("decisions") or run.get("decisions") or {}comment = (body.comment or "").strip() or Nonewith svc.db.write_lock: # check and record in one step: a double click signs off onceif _signoff(svc, run_id):raise ApiError(409, "ALREADY_SIGNED", "this test run is already signed off")seq = svc.audit.append("run.signoff", actor=user.username, run_id=run_id, summary=f"signed off: {decisions}",payload={"decisions": decisions, "comment": comment, "role": user.role})text = f"Signed off by {user.username} ({user.role})." + (f" {comment}" if comment else "")svc.db.add_event(run_id, None, "note", {"text": text, "by": user.username, "role": user.role, "signoff": True, "audit_seq": seq})return {"by": user.username, "role": user.role, "at": now_iso(), "decisions": decisions, "comment": comment}# ------------------------------------------------------------------ scenario librarydef _automated(case_id: str) -> bool:return any((ROOT / "automation" / "tests" / "cases").rglob(f"{case_id}.spec.ts"))@router.get("/scenarios")def scenarios(request: Request, module: str | None = None, step: str | None = None, priority: str | None = None, q: str | None = None,limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0), user: Principal = Depends(require("read"))):"""The scenario library by business process: filter by module, process step, priority or text."""from ...adapters.cases import load_all, load_casescases = load_all(request.app.state.svc, [module.upper()] if module else None)steps_cache: dict[str, list[dict]] = {}items = []for c in cases:steps = steps_cache.setdefault(c["module"], R.module_steps(c["module"]))st = R.step_for_case(c, steps)pr = str(c["priority"] or "")[:2]items.append({"id": c["id"], "title": c["title"], "module": c["module"], "process": c["process"], "step": st["name"] if st else None,"priority": pr, "priority_words": R.PRIORITY_WORDS.get(pr, "Unrated"),"status": "approved" if c.get("already_approved") else (c.get("lifecycle") or "draft")})names = sorted({i["step"] for i in items if i["step"]})if step:items = [i for i in items if i["step"] == step]if priority:items = [i for i in items if i["priority"] == priority.upper()]if q:ql = q.lower()items = [i for i in items if ql in i["id"].lower() or ql in (i["title"] or "").lower()]page = items[offset: offset + limit]for i in page:i["automated"] = _automated(i["id"])return {"items": page, "total": len(items), "limit": limit, "offset": offset, "steps": names}@router.get("/scenarios/{case_id}")def scenario(case_id: str, request: Request, run_id: str | None = None, user: Principal = Depends(require("read"))):svc, runs = _ctx(request)if not _ID.fullmatch(case_id):raise ApiError(400, "BAD_ID", "invalid scenario id")state = Noneif run_id:_run(svc, run_id)state = runs.state(run_id)d = R.scenario_detail(case_id, None, state)if d is None:raise ApiError(404, "NOT_FOUND", f"no scenario {case_id} in the library")return dclass RetireIn(BaseModel):model_config = ConfigDict(extra="forbid")reason: str = Field(min_length=3, max_length=300, description="why it leaves the regression pack, kept in its history")def _library_case(svc, case_id: str):"""The YAML of a scenario added to this server's library (an approved AI or custom scenario). Built-in scenariosship with the code and change with a release, not here."""if not _ID.fullmatch(case_id):raise ApiError(400, "BAD_ID", "invalid scenario id")from ...graph.nodes.ai_scenarios import library_rootf = library_root(svc) / "tests" / "cases" / f"{case_id}.yaml"if not f.is_file():raise ApiError(404, "NOT_IN_LIBRARY", f"{case_id} is not a scenario added on this server (approved AI or custom ""scenarios only); built-in scenarios change with a release")return fdef _set_lifecycle(svc, f, case_id: str, user: Principal, retire_reason: str | None) -> dict:"""Retire (retire_reason) or reinstate (None) a library scenario: its lifecycle field, committed to the library'shistory, audited, and saved at once. A retired scenario is skipped by every run (qa case_class 'retired')."""import yamlfrom ...platform.statesync import save_soondoc = yaml.safe_load(f.read_text(encoding="utf-8")) or {}if retire_reason:doc["status"], doc["retired_reason"] = "retired", f"{retire_reason} ({user.username}, {now_iso()[:10]})"else:doc.pop("status", None)doc.pop("retired_reason", None)f.write_text(yaml.safe_dump(doc, sort_keys=False, allow_unicode=True), encoding="utf-8")verb = "retire" if retire_reason else "reinstate"commit = Noneif svc.library.exists():commit = svc.library.commit([f], f"{verb} {case_id}" + (f": {retire_reason}" if retire_reason else ""), author=user.username)svc.audit.append(f"scenario.{verb}d", actor=user.username, summary=f"{case_id}" + (f": {retire_reason}" if retire_reason else ""),payload={"case_id": case_id, "commit": commit})save_soon(f"scenario {verb}d")return {"case_id": case_id, "status": "retired" if retire_reason else "active", "commit": commit}@router.post("/scenarios/{case_id}/retire")def retire_scenario(case_id: str, body: RetireIn, request: Request, user: Principal = Depends(require("drafts.decide"))):"""Take an approved scenario out of the regression pack, with the reason (a person decides; runs skip it)."""svc, _ = _ctx(request)return _set_lifecycle(svc, _library_case(svc, case_id), case_id, user, body.reason.strip())@router.post("/scenarios/{case_id}/reinstate")def reinstate_scenario(case_id: str, request: Request, user: Principal = Depends(require("drafts.decide"))):"""Put a retired scenario back into the regression pack."""svc, _ = _ctx(request)return _set_lifecycle(svc, _library_case(svc, case_id), case_id, user, None)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295"""Functional-consultant read models over platform/readiness.py: patch readiness per business process, scenarios inplain language, failures in business words, the scenario library, and sign-off. Nothing here decides GO/NO-GO: thatstays the QA rule's result (reports/generate_report.py); sign-off is an audit entry and a run note.Rebuilt by the lead after the original route file was overwritten; the contract is coworker/tests/test_consultant.pyand the paths the web app calls (web/src/api/hooks.ts)."""from __future__ import annotationsimport refrom fastapi import APIRouter, Depends, Query, Requestfrom fastapi.responses import Responsefrom pydantic import BaseModel, ConfigDict, Fieldfrom ...config import ROOTfrom ...platform import readiness as Rfrom ...platform.rundb import now_isofrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom .live import MODULE_NAMESrouter = APIRouter(tags=["consultant"])_ID = re.compile(r"[A-Z][A-Z0-9]{1,5}(-[A-Z0-9]+)+")def _ctx(request: Request):return request.app.state.svc, request.app.state.runsdef _run(svc, run_id: str) -> dict:r = svc.db.get_run(run_id)if not r:raise ApiError(404, "NOT_FOUND", f"run {run_id} not found")return rdef _signoff(svc, run_id: str) -> dict | None:row = svc.db.one("SELECT ts, actor, payload FROM audit_log WHERE kind='run.signoff' AND run_id=? ORDER BY seq DESC LIMIT 1", (run_id,))if not row:return Nonep = row["payload"] if isinstance(row["payload"], dict) else {}return {"by": row["actor"], "role": p.get("role"), "at": row["ts"], "decisions": p.get("decisions") or {}, "comment": p.get("comment")}# ------------------------------------------------------------------ readiness@router.get("/readiness")def readiness(request: Request, pod_id: int | None = None, patch_id: str | None = None, modules: str | None = None,user: Principal = Depends(require("read"))):"""Patch readiness per business process for a pod (+ patch): latest test run per module, or the baseline(process steps + what the patch changes, labelled UNVERIFIED) when nothing has run yet."""svc, runs = _ctx(request)mods = [m.strip().upper() for m in modules.split(",") if m.strip()] if modules else Nonereturn R.readiness(svc, runs, pod_id, patch_id, mods)@router.get("/runs/{run_id}/readiness")def run_readiness(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = _ctx(request)_run(svc, run_id)return {**R.run_readiness(svc, runs, run_id), "signoff": _signoff(svc, run_id)}# ------------------------------------------------------------------ scenarios of a run / failuresdef _scenarios_view(svc, runs, run: dict) -> dict:"""Every scenario of a test run in plain language; shared by the screen and the Excel test script."""run_id = run["run_id"]state = runs.state(run_id)gate = runs.gate_payload(run_id) if run.get("pending_gate") else Nonepending = {p["id"]: p for p in (gate or {}).get("pending", [])} if (gate or {}).get("gate") == "approve_cases" else {}outcomes = (state.get("run_results") or {}).get("outcomes") or {}steps_cache: dict[str, list[dict]] = {}ai_by_id = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}out, seen = [], set()cases = list(state.get("test_cases") or []) + [p for p in pending.values() if p["id"] not in {c["id"] for c in state.get("test_cases") or []}]for c in cases:cid = c["id"]if cid in seen:continueseen.add(cid)module = c.get("module") or cid.split("-", 1)[0]steps = steps_cache.setdefault(module, R.module_steps(module))ai = ai_by_id.get(cid)d = R.scenario_detail(cid, steps, state, path=c.get("yaml_path") if ai else None)if d is not None and ai: # written by the AI model: say so, with its dry run on the podd["why"] = [f"Written by the AI model: {ai['why']}" if ai.get("why") else "Written by the AI model"] + d["why"]d.update(written_by="AI model", dry_run=ai.get("dry_run"), ai_status=ai.get("status"))if d is None: # a generated draft: no library entry yet, show what the generator proposedst = R.step_for_case({"id": cid, "map_ids": c.get("map_ids") or [], "process": c.get("process")}, steps)pr = str(c.get("priority") or "")[:2]d = {"id": cid, "title": c.get("title"), "module": module, "process": c.get("process"), "step": st["name"] if st else None,"priority": pr, "priority_words": R.PRIORITY_WORDS.get(pr, "Unrated"), "roles": [], "preconditions": [], "steps": [],"expected_result": "", "test_data": [], "why": ["New scenario drafted for a gap this patch touches"],"verification": "UNVERIFIED", "map_ids": c.get("map_ids") or [], "approval_status": "draft"}d.update(origin=c.get("origin") or "library", pending=cid in pending, outcome=outcomes.get(cid),diff=(pending.get(cid) or {}).get("diff"))out.append(d)out.sort(key=lambda s: (not s["pending"], s["priority"] or "P9", s["id"]))deferred = [{"id": d.get("id"), "reason": d.get("reason")} for d in state.get("deferred") or [] if isinstance(d, dict)]return {"run_id": run_id, "scenarios": out, "deferred": deferred, "pending": len(pending), "policy": (gate or {}).get("policy")}@router.get("/runs/{run_id}/scenarios")def run_scenarios(run_id: str, request: Request, user: Principal = Depends(require("read"))):"""Every scenario of the test run in plain language (steps, role, test data, expected result, why it is included)."""svc, runs = _ctx(request)return _scenarios_view(svc, runs, _run(svc, run_id))def test_script_xlsx(svc, runs, run_id: str, actor: str) -> Response:"""The test script as an Excel workbook for offline verification: one row per step (action, expected result),reviewer columns to fill in, and the results once the scenarios have run. Audited as an export."""from ...platform import test_scriptrun = _run(svc, run_id)view = _scenarios_view(svc, runs, run)gate = runs.gate_payload(run_id) if run.get("pending_gate") else Nonefailures = R.failures(svc, run_id, runs.state(run_id), gate)order: dict[str, int] = {}for m in sorted({s_.get("module") or "" for s_ in view["scenarios"]}):for i, st in enumerate(R.module_steps(m)):order.setdefault(st["name"], i)data = test_script.build(run, view["scenarios"], failures, area_names=MODULE_NAMES, signoff=_signoff(svc, run_id), step_order=order)svc.audit.append("export.test_script", actor=actor, run_id=run_id, summary=f"{len(view['scenarios'])} scenario(s) to Excel",payload={"scenarios": len(view["scenarios"]), "bytes": len(data)})return Response(content=data, media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",headers={"Content-Disposition": f'attachment; filename="test-script-{run_id}.xlsx"', "Cache-Control": "no-store"})@router.get("/runs/{run_id}/test-script.xlsx")def run_test_script(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = _ctx(request)return test_script_xlsx(svc, runs, run_id, user.username)@router.get("/share/runs/{run_id}/test-script.xlsx")def shared_test_script(run_id: str, request: Request, exp: int = Query(...), sig: str = Query(..., max_length=80)):"""The same workbook from a signed link (platform/links.py) in an e-mail Oracle Fusion sends: no login, this run only,read-only, until the link expires."""from ...platform import linkssvc, runs = _ctx(request)if not links.verify(svc, run_id, "test-script.xlsx", exp, sig):raise ApiError(403, "LINK_EXPIRED", "This download link has expired or is not valid. Open the run in Astra, or ask for a new e-mail.")return test_script_xlsx(svc, runs, run_id, "signed link (e-mail)")@router.get("/runs/{run_id}/failures")def run_failures(run_id: str, request: Request, user: Principal = Depends(require("read"))):"""Failed or flaky scenarios in business words: process step, expected vs actual, screenshot ids, suggestion."""svc, runs = _ctx(request)run = _run(svc, run_id)gate = runs.gate_payload(run_id) if run.get("pending_gate") else Nonereturn R.failures(svc, run_id, runs.state(run_id), gate)# ------------------------------------------------------------------ sign-offclass SignOffIn(BaseModel):model_config = ConfigDict(extra="forbid")comment: str | None = Field(default=None, max_length=1000)@router.get("/runs/{run_id}/signoff")def get_signoff(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, _ = _ctx(request)_run(svc, run_id)return _signoff(svc, run_id)@router.post("/runs/{run_id}/signoff", status_code=201)def signoff(run_id: str, body: SignOffIn, request: Request, user: Principal = Depends(require("run.signoff"))):"""Records that a QA approver signed off the finished test run. It does NOT change the decision (that stays the QArule's result in generate_report.py); it is an audit entry and a run note."""svc, runs = _ctx(request)run = _run(svc, run_id)if run["status"] != "completed":raise ApiError(409, "NOT_FINISHED", "only a finished test run can be signed off")decisions = runs.state(run_id).get("decisions") or run.get("decisions") or {}comment = (body.comment or "").strip() or Nonewith svc.db.write_lock: # check and record in one step: a double click signs off onceif _signoff(svc, run_id):raise ApiError(409, "ALREADY_SIGNED", "this test run is already signed off")seq = svc.audit.append("run.signoff", actor=user.username, run_id=run_id, summary=f"signed off: {decisions}",payload={"decisions": decisions, "comment": comment, "role": user.role})text = f"Signed off by {user.username} ({user.role})." + (f" {comment}" if comment else "")svc.db.add_event(run_id, None, "note", {"text": text, "by": user.username, "role": user.role, "signoff": True, "audit_seq": seq})return {"by": user.username, "role": user.role, "at": now_iso(), "decisions": decisions, "comment": comment}# ------------------------------------------------------------------ scenario librarydef _automated(case_id: str) -> bool:return any((ROOT / "automation" / "tests" / "cases").rglob(f"{case_id}.spec.ts"))@router.get("/scenarios")def scenarios(request: Request, module: str | None = None, step: str | None = None, priority: str | None = None, q: str | None = None,limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0), user: Principal = Depends(require("read"))):"""The scenario library by business process: filter by module, process step, priority or text."""from ...adapters.cases import load_all, load_casescases = load_all(request.app.state.svc, [module.upper()] if module else None)steps_cache: dict[str, list[dict]] = {}items = []for c in cases:steps = steps_cache.setdefault(c["module"], R.module_steps(c["module"]))st = R.step_for_case(c, steps)pr = str(c["priority"] or "")[:2]items.append({"id": c["id"], "title": c["title"], "module": c["module"], "process": c["process"], "step": st["name"] if st else None,"priority": pr, "priority_words": R.PRIORITY_WORDS.get(pr, "Unrated"),"status": "approved" if c.get("already_approved") else (c.get("lifecycle") or "draft")})names = sorted({i["step"] for i in items if i["step"]})if step:items = [i for i in items if i["step"] == step]if priority:items = [i for i in items if i["priority"] == priority.upper()]if q:ql = q.lower()items = [i for i in items if ql in i["id"].lower() or ql in (i["title"] or "").lower()]page = items[offset: offset + limit]for i in page:i["automated"] = _automated(i["id"])return {"items": page, "total": len(items), "limit": limit, "offset": offset, "steps": names}@router.get("/scenarios/{case_id}")def scenario(case_id: str, request: Request, run_id: str | None = None, user: Principal = Depends(require("read"))):svc, runs = _ctx(request)if not _ID.fullmatch(case_id):raise ApiError(400, "BAD_ID", "invalid scenario id")state = Noneif run_id:_run(svc, run_id)state = runs.state(run_id)d = R.scenario_detail(case_id, None, state)if d is None:raise ApiError(404, "NOT_FOUND", f"no scenario {case_id} in the library")return dclass RetireIn(BaseModel):model_config = ConfigDict(extra="forbid")reason: str = Field(min_length=3, max_length=300, description="why it leaves the regression pack, kept in its history")def _library_case(svc, case_id: str):"""The YAML of a scenario added to this server's library (an approved AI or custom scenario). Built-in scenariosship with the code and change with a release, not here."""if not _ID.fullmatch(case_id):raise ApiError(400, "BAD_ID", "invalid scenario id")from ...graph.nodes.ai_scenarios import library_rootf = library_root(svc) / "tests" / "cases" / f"{case_id}.yaml"if not f.is_file():raise ApiError(404, "NOT_IN_LIBRARY", f"{case_id} is not a scenario added on this server (approved AI or custom ""scenarios only); built-in scenarios change with a release")return fdef _set_lifecycle(svc, f, case_id: str, user: Principal, retire_reason: str | None) -> dict:"""Retire (retire_reason) or reinstate (None) a library scenario: its lifecycle field, committed to the library'shistory, audited, and saved at once. A retired scenario is skipped by every run (qa case_class 'retired')."""import yamlfrom ...platform.statesync import save_soondoc = yaml.safe_load(f.read_text(encoding="utf-8")) or {}if retire_reason:doc["status"], doc["retired_reason"] = "retired", f"{retire_reason} ({user.username}, {now_iso()[:10]})"else:doc.pop("status", None)doc.pop("retired_reason", None)f.write_text(yaml.safe_dump(doc, sort_keys=False, allow_unicode=True), encoding="utf-8")verb = "retire" if retire_reason else "reinstate"commit = None# the library's git history covers its own work tree only (the code folder on a deployed server, while approved# scenarios live in FPT_HOME/library): commit where it can, the audit entry records the change either wayfrom pathlib import Pathtree = getattr(svc.library, "work_tree", None)inside = tree is None or str(f.resolve()).startswith(str(Path(tree).resolve()))if inside and svc.library.exists():try:commit = svc.library.commit([f], f"{verb} {case_id}" + (f": {retire_reason}" if retire_reason else ""), author=user.username)except Exception as e: # noqa: BLE001 - the lifecycle change itself is made and auditedsvc.audit.append("library.error", actor=user.username, summary=str(e)[:300])svc.audit.append(f"scenario.{verb}d", actor=user.username, summary=f"{case_id}" + (f": {retire_reason}" if retire_reason else ""),payload={"case_id": case_id, "commit": commit})save_soon(f"scenario {verb}d")return {"case_id": case_id, "status": "retired" if retire_reason else "active", "commit": commit}@router.post("/scenarios/{case_id}/retire")def retire_scenario(case_id: str, body: RetireIn, request: Request, user: Principal = Depends(require("drafts.decide"))):"""Take an approved scenario out of the regression pack, with the reason (a person decides; runs skip it)."""svc, _ = _ctx(request)return _set_lifecycle(svc, _library_case(svc, case_id), case_id, user, body.reason.strip())@router.post("/scenarios/{case_id}/reinstate")def reinstate_scenario(case_id: str, request: Request, user: Principal = Depends(require("drafts.decide"))):"""Put a retired scenario back into the regression pack."""svc, _ = _ctx(request)return _set_lifecycle(svc, _library_case(svc, case_id), case_id, user, None)
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152"""Control-name heals: the names Oracle changed on screen that tests could not find, proposed for a person to approve."""from __future__ import annotations
import json
from fastapi import APIRouter, Depends, Query, Request
from ...platform import healingfrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom ..schemas import DecisionIn, Page, StatusOut
router = APIRouter(tags=["heals"])
@router.get("/heals", response_model=Page[dict])def heals_list(request: Request, status: str | None = None, pod_id: int | None = None, run_id: str | None = None, limit: int = Query(100, le=500), offset: int = 0, user: Principal = Depends(require("read"))): db = request.app.state.svc.db conds, args = [], [] for k, v in (("status", status), ("pod_id", pod_id), ("run_id", run_id)): if v is not None: conds.append(f"{k}=?") args.append(v) w = (" WHERE " + " AND ".join(conds)) if conds else "" rows = db.q(f"SELECT * FROM heal_rules{w} ORDER BY id DESC LIMIT ? OFFSET ?", args + [limit, offset]) for r in rows: r["names"] = json.loads(r["names"] or "[]") return {"items": rows, "total": db.one(f"SELECT COUNT(*) n FROM heal_rules{w}", args)["n"], "limit": limit, "offset": offset}
@router.post("/heals/{hid}/decision", response_model=StatusOut)def heal_decide(hid: int, body: DecisionIn, request: Request, user: Principal = Depends(require("heal.decide"))): try: return {"status": healing.decide(request.app.state.svc, hid, body.decision, user.username, body.note)} except healing.HealError as e: raise ApiError(e.status, e.code, str(e)) from e
@router.get("/runs/{run_id}/heals")def run_heals(run_id: str, request: Request, user: Principal = Depends(require("read"))): """What a run healed (steps that found their control under a new name) and the controls it could not find.""" svc = request.app.state.svc if not svc.db.get_run(run_id): raise ApiError(404, "NOT_FOUND", "run not found") steps = [] for e in svc.db.events(run_id): if e["kind"] == "heals": s = e["summary"] steps += (json.loads(s) if isinstance(s, str) else s or {}).get("steps") or [] proposals = svc.db.q("SELECT id, case_id, kind, wanted, proposed, place, confidence, status FROM heal_rules WHERE run_id=? ORDER BY id", (run_id,)) return {"healed": steps, "proposals": proposals}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106"""Pods: the test environments runs target. Everyone signed in can see them; admins add, edit and set credentials;anyone who can start a run can test a connection. Credential values are write-only (vault), never returned."""from __future__ import annotationsimport threadingfrom fastapi import APIRouter, Depends, Requestfrom ...platform.pods import PodError, PodRegistryfrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom ..schemas import PodCredentialIn, PodIn, PodRow, PodScreensIn, PodTestDataIn, PodTestResult, PodUpdaterouter = APIRouter(tags=["pods"])def _spawn(fn) -> None: # replaced by tests (runs inline there)threading.Thread(target=fn, daemon=True, name="pod-screens").start()def reg(request: Request) -> PodRegistry:svc = request.app.state.svcreturn PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)def _err(e: PodError) -> ApiError:return ApiError(e.status, e.code, str(e))@router.get("/pods", response_model=list[PodRow])def list_pods(request: Request, user: Principal = Depends(require("read"))):return reg(request).list()@router.post("/pods", response_model=PodRow, status_code=201)def create_pod(body: PodIn, request: Request, user: Principal = Depends(require("admin"))):try:return reg(request).create(body.model_dump(), user.username)except PodError as e:raise _err(e) from e@router.patch("/pods/{pod_id}", response_model=PodRow)def update_pod(pod_id: int, body: PodUpdate, request: Request, user: Principal = Depends(require("admin"))):try:return reg(request).update(pod_id, body.model_dump(exclude_none=True), user.username)except PodError as e:raise _err(e) from e@router.delete("/pods/{pod_id}", status_code=204)def delete_pod(pod_id: int, request: Request, user: Principal = Depends(require("admin"))):try:reg(request).delete(pod_id, user.username)except PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/credentials", response_model=PodRow)def set_credential(pod_id: int, body: PodCredentialIn, request: Request, user: Principal = Depends(require("admin"))):try:r = reg(request)pod = r.set_credential(pod_id, body.module, body.username, body.password, user.username)if pod["kind"] == "fusion": # prove the new sign-in straight away; the card shows the resultpod = r.test_connection(pod_id, user.username)["pod"]return podexcept PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/test", response_model=PodTestResult)def test_pod(pod_id: int, request: Request, user: Principal = Depends(require("run.start"))):try:return reg(request).test_connection(pod_id, user.username)except PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/discover", response_model=PodRow)def discover_pod(pod_id: int, request: Request, user: Principal = Depends(require("run.start"))):"""Read which business areas the Fusion pod uses and the test data its records offer (read-only GETs)."""try:return reg(request).discover(pod_id, user.username)except PodError as e:raise _err(e) from e@router.put("/pods/{pod_id}/test-data", response_model=PodRow)def set_test_data(pod_id: int, body: PodTestDataIn, request: Request, user: Principal = Depends(require("admin"))):try:return reg(request).set_test_data(pod_id, body.overrides, user.username)except PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/screens/read", response_model=PodRow, status_code=202)def read_screens(pod_id: int, body: PodScreensIn, request: Request, user: Principal = Depends(require("admin"))):"""Read the screens of the pod's business areas in a real browser (labels only, nothing saved on the pod). Runs in thebackground for many minutes; the pod's `screens` shows progress and the result."""r = reg(request)try:pod, job = r.start_screens(pod_id, user.username, body.areas, body.max_tasks or int(request.app.state.svc.cfg.fusion_screens_per_area or 8))except PodError as e:raise _err(e) from e_spawn(lambda: r.read_screens(pod_id, job, user.username))return pod123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135"""Pods: the test environments runs target. Everyone signed in can see them; admins add, edit and set credentials;anyone who can start a run can test a connection. Credential values are write-only (vault), never returned."""from __future__ import annotationsimport threadingfrom fastapi import APIRouter, Depends, Requestfrom ...platform.pods import PodError, PodRegistryfrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom ..schemas import (PodCoverage, PodCredentialIn, PodIn, PodRow, PodScreensIn, PodTestDataIn, PodTestResult, PodUpdate, PodUsage,PodUsageIn)router = APIRouter(tags=["pods"])def _spawn(fn) -> None: # replaced by tests (runs inline there)threading.Thread(target=fn, daemon=True, name="pod-screens").start()def reg(request: Request) -> PodRegistry:svc = request.app.state.svcreturn PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)def _err(e: PodError) -> ApiError:return ApiError(e.status, e.code, str(e))@router.get("/pods", response_model=list[PodRow])def list_pods(request: Request, user: Principal = Depends(require("read"))):return reg(request).list()@router.post("/pods", response_model=PodRow, status_code=201)def create_pod(body: PodIn, request: Request, user: Principal = Depends(require("admin"))):try:return reg(request).create(body.model_dump(), user.username)except PodError as e:raise _err(e) from e@router.patch("/pods/{pod_id}", response_model=PodRow)def update_pod(pod_id: int, body: PodUpdate, request: Request, user: Principal = Depends(require("admin"))):try:return reg(request).update(pod_id, body.model_dump(exclude_none=True), user.username)except PodError as e:raise _err(e) from e@router.delete("/pods/{pod_id}", status_code=204)def delete_pod(pod_id: int, request: Request, user: Principal = Depends(require("admin"))):try:reg(request).delete(pod_id, user.username)except PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/credentials", response_model=PodRow)def set_credential(pod_id: int, body: PodCredentialIn, request: Request, user: Principal = Depends(require("admin"))):try:r = reg(request)pod = r.set_credential(pod_id, body.module, body.username, body.password, user.username)if pod["kind"] == "fusion": # prove the new sign-in straight away; the card shows the resultpod = r.test_connection(pod_id, user.username)["pod"]return podexcept PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/test", response_model=PodTestResult)def test_pod(pod_id: int, request: Request, user: Principal = Depends(require("run.start"))):try:return reg(request).test_connection(pod_id, user.username)except PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/discover", response_model=PodRow)def discover_pod(pod_id: int, request: Request, user: Principal = Depends(require("run.start"))):"""Read which business areas the Fusion pod uses and the test data its records offer (read-only GETs)."""try:return reg(request).discover(pod_id, user.username)except PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/usage", response_model=PodUsage)def read_usage(pod_id: int, request: Request, body: PodUsageIn | None = None, user: Principal = Depends(require("run.start"))):"""Read how the client uses each business area of the Fusion pod: the records of the last `days` days counted byinvoice type, payment method, journal source ... (read-only GETs; platform/usage.py)."""try:return reg(request).read_usage(pod_id, user.username, (body or PodUsageIn()).days)except PodError as e:raise _err(e) from e@router.get("/pods/{pod_id}/usage", response_model=PodUsage)def get_usage(pod_id: int, request: Request, user: Principal = Depends(require("read"))):try:return {"pod_id": pod_id, **(reg(request).usage(pod_id) or {})}except PodError as e:raise _err(e) from e@router.get("/pods/{pod_id}/coverage", response_model=PodCoverage)def get_coverage(pod_id: int, request: Request, user: Principal = Depends(require("read"))):"""The variants the client uses against the scenario library: covered, practice only or not covered, by volume."""from ...adapters.cases import load_alltry:return reg(request).coverage(pod_id, load_all(request.app.state.svc))except PodError as e:raise _err(e) from e@router.put("/pods/{pod_id}/test-data", response_model=PodRow)def set_test_data(pod_id: int, body: PodTestDataIn, request: Request, user: Principal = Depends(require("admin"))):try:return reg(request).set_test_data(pod_id, body.overrides, user.username)except PodError as e:raise _err(e) from e@router.post("/pods/{pod_id}/screens/read", response_model=PodRow, status_code=202)def read_screens(pod_id: int, body: PodScreensIn, request: Request, user: Principal = Depends(require("admin"))):"""Read the screens of the pod's business areas in a real browser (labels only, nothing saved on the pod). Runs in thebackground for many minutes; the pod's `screens` shows progress and the result."""r = reg(request)try:pod, job = r.start_screens(pod_id, user.username, body.areas, body.max_tasks or int(request.app.state.svc.cfg.fusion_screens_per_area or 8))except PodError as e:raise _err(e) from e_spawn(lambda: r.read_screens(pod_id, job, user.username))return pod
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990"""Import a recording (backup path for odd, client-specific flows): a Playwright codegen recording is converted intobusiness-action steps and becomes a draft custom scenario (origin recording) that still needs its dry run and a person'sapproval (/api/custom-cases/{id}/build, /approve). docs/RECORDINGS.md."""from __future__ import annotations
from fastapi import APIRouter, Depends, Requestfrom pydantic import BaseModel, Field
from ...platform import custom_cases as Cfrom ...platform import recording as Rfrom ..auth import Principal, requirefrom ..errors import ApiError
router = APIRouter(tags=["recordings"])
class RecordingIn(BaseModel): module: str = Field(min_length=2, max_length=6, description="Business-area code of the draft: AP, PO, GL ...") title: str = Field(default="", max_length=200) text: str = Field(description="The recording: the .ts file `npx playwright codegen` saved (or its JSON-lines target); at most 200 KB.") pod_id: int | None = Field(default=None, description="Match recorded values to this pod's test data ({{pod.<area>.<key>}}).") ai_tidy: bool = Field(default=False, description="Let the AI model tidy the steps into business actions (masked values only).")
class StepOut(BaseModel): action: str field: str | None = None fields: list[str] | None = None value: str | None = None name: str | None = None lines: list[str] | None = None quantity: str | None = None price: str | None = None status: str | None = None expected: str | None = None
class Reported(BaseModel): line: int what: str why: str
class Unparsed(BaseModel): line: int why: str
class Converted(BaseModel): steps: list[StepOut] text: list[str] test_values: dict[str, str] = {} dropped: list[Reported] flagged: list[Reported] unparsed: list[Unparsed] ai: str | None = None
class DraftOut(Converted): draft_id: str key: str
def _read(body: RecordingIn, request: Request) -> None: # the size is checked before any parsing (413), whatever the JSON field limits say if int(request.headers.get("content-length") or 0) > R.MAX_BYTES + 8 * 1024 or len(body.text.encode("utf-8")) > R.MAX_BYTES: raise ApiError(413, "TOO_LARGE", "The recording is larger than 200 KB. Record a shorter flow.")
def _call(fn, *a, **kw): try: return fn(*a, **kw) except C.CustomCaseError as e: raise ApiError(e.status, e.code, str(e)) from e
@router.post("/recordings/preview", response_model=Converted)def preview(body: RecordingIn, request: Request, user: Principal = Depends(require("run.start"))): """What a recording converts to, with what was dropped and flagged. Nothing is created.""" _read(body, request) svc = request.app.state.svc return _call(R.run, svc, body.module, body.text, body.pod_id, body.ai_tidy)
@router.post("/recordings", response_model=DraftOut, status_code=201)def create(body: RecordingIn, request: Request, user: Principal = Depends(require("run.start"))): """Convert a recording and create a draft scenario from it: not approved, not in the script library. It then goes the normal custom scenario way (build = dry run on a pod, then a person approves).""" _read(body, request) return _call(R.create_draft, request.app.state.svc, user.username, body.module, body.title, body.text, body.pod_id, body.ai_tidy)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380"""/api/runs*: start/list/detail/events/SSE stream/resume/cancel/gate + per-phase views + report files + evidence."""from __future__ import annotationsimport asyncioimport jsonfrom pathlib import Pathfrom fastapi import APIRouter, Depends, Query, Requestfrom fastapi.responses import FileResponse, Response, StreamingResponsefrom ...graph.build import GRAPH_SPECfrom ...platform.killswitch import KillSwitchEngagedfrom .. import actionsfrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom ..runner import TERMINAL, RunErrorfrom ..schemas import CancelIn, Page, RunCreate, RunCreated, RunDetail, RunEvent, RunNoteIn, RunSummaryrouter = APIRouter(tags=["runs"])def ctx(request: Request):return request.app.state.svc, request.app.state.runsdef _run(svc, run_id: str) -> dict:r = svc.db.get_run(run_id)if not r:raise ApiError(404, "NOT_FOUND", f"run {run_id} not found")return rdef _summary(r: dict) -> dict:inp = r.get("inputs") if isinstance(r.get("inputs"), dict) else {}return {**r, "modules": r.get("modules") or [], "decisions": r.get("decisions") or {}, "pod_name": inp.get("pod_name")}def _run_error(e: RunError):return ApiError(e.status, e.code, str(e))@router.post("/runs", status_code=202, response_model=RunCreated)def start_run(body: RunCreate, request: Request, user: Principal = Depends(require("run.start"))):svc, runs = ctx(request)rid = actions.start_run(svc, runs, body.model_dump(exclude_none=True) | {"stub_knobs": body.stub_knobs.model_dump(exclude_none=True) if body.stub_knobs else {}},actor=user.username)return {"run_id": rid, "status": "queued"}@router.get("/runs", response_model=Page[RunSummary])def list_runs(request: Request, status: str | None = None, limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0),user: Principal = Depends(require("read"))):svc, _ = ctx(request)rows = svc.db.list_runs(status, limit, offset)counts = _counts(svc.db, [r["run_id"] for r in rows])return {"items": [{**_summary(r), "counts": counts.get(r["run_id"], {})} for r in rows], "total": svc.db.count_runs(status),"limit": limit, "offset": offset}_COUNTED = ("passed", "failed", "skipped", "flaky", "total")def _counts(db, run_ids: list[str]) -> dict[str, dict[str, int]]:"""Results of finished runs, all business areas of a run added up (one query for the whole page)."""if not run_ids:return {}out: dict[str, dict[str, int]] = {}marks = ",".join("?" * len(run_ids))for h in db.q(f"SELECT run_id, counts FROM run_history WHERE run_id IN ({marks})", tuple(run_ids)):c = h["counts"] if isinstance(h["counts"], dict) else json.loads(h["counts"] or "{}")acc = out.setdefault(h["run_id"], {k: 0 for k in _COUNTED})for k in _COUNTED:acc[k] += int(c.get(k) or 0)return out@router.get("/runs.csv")def export_runs(request: Request, status: str | None = None, user: Principal = Depends(require("read"))):"""Every test run as a CSV file (newest first) for spreadsheets and status reports. No evidence or credentials."""import csvimport iosvc, _ = ctx(request)buf = io.StringIO()w = csv.writer(buf)w.writerow(["run_id", "started_at", "started_by", "trigger", "test_environment", "patch", "business_areas", "run_type","status", "decision", "decisions_by_area", "last_updated_at", "error"])for r in (_summary(x) for x in svc.db.list_runs(status, 100_000, 0)):w.writerow([r["run_id"], r.get("created_at") or "", r.get("created_by") or "", r.get("trigger") or "", r.get("pod_name") or "",r.get("patch_id") or "", " ".join(r["modules"]), "full browser run" if r.get("playwright_mode") == "live" else "quick simulation",r.get("status") or "", r.get("decision") or "", "; ".join(f"{k}={v}" for k, v in r["decisions"].items()),r.get("updated_at") or "", _csv_safe(r.get("error") or "")])svc.audit.append("runs.exported", actor=user.username, summary=f"CSV, status={status or 'all'}")return Response(buf.getvalue(), media_type="text/csv; charset=utf-8",headers={"Content-Disposition": 'attachment; filename="trio-test-runs.csv"'})def _csv_safe(v: str) -> str:"""Spreadsheet apps run a cell that starts with = + - @ as a formula: neutralise it (CSV injection)."""return "'" + v if v[:1] in ("=", "+", "-", "@") else v@router.get("/runs/{run_id}", response_model=RunDetail)def run_detail(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)r = _summary(_run(svc, run_id))st = runs.state(run_id)calls = st.get("llm_calls") or []return {**r, "include_p2": bool(r.get("include_p2")), "live_view": bool(st["live_view"] if "live_view" in st else (r.get("inputs") or {}).get("live_view") if isinstance(r.get("inputs"), dict) else False), "counts": st.get("counts") or r.get("counts") or {},"report_paths": st.get("report_paths") or {}, "errors": st.get("errors") or [], "retry_count": st.get("retry_count", 0),"llm_calls_count": len(calls), "llm_calls": calls, "target": svc.target(run_id), "test_data": _test_data(svc, run_id),"decisions": st.get("decisions") or r["decisions"], "decision": st.get("decision", r.get("decision"))}def _test_data(svc, run_id: str) -> dict | None:"""Fusion test invoices this run created: what was cleaned up and what may be left on the pod (None for mock runs)."""if svc.fusion_pod_id(run_id) is None:return Nonefrom ...platform import cleanuprun_dir = svc.run_dir(run_id)entries = cleanup.ledger_entries(run_dir)swept = cleanup.result(run_dir) or {}left = [{"number": e["number"], "test": e.get("test"), "why": "not cleaned up yet"} for e in entries.values() if not e.get("cleaned")]if swept.get("left"):left = swept["left"]return {"created": len(entries), "cleaned": sum(1 for e in entries.values() if e.get("cleaned")), "left": left,"summary": swept.get("summary"), "swept_at": swept.get("at")}@router.get("/runs/{run_id}/events", response_model=list[RunEvent])def run_events(run_id: str, request: Request, after: int = 0, user: Principal = Depends(require("read"))):svc, _ = ctx(request)_run(svc, run_id)return svc.db.events(run_id, after)STREAM_END = TERMINAL + ("interrupted",) # an interrupted run waits for a person to resume it: nothing more will streamSTREAM_IDLE_S = 900 # a stream with no new event for 15 minutes ends (reason "idle")@router.get("/runs/{run_id}/stream")async def run_stream(run_id: str, request: Request, after: int = 0, user: Principal = Depends(require("read"))):"""Server-Sent Events: every run event (node started/finished/interrupted/error, status changes). Ends when the runreaches a terminal status. Clients fall back to polling /events."""svc, _ = ctx(request)_run(svc, run_id)last = int(request.headers.get("last-event-id") or after or 0)async def gen():nonlocal lastidle = 0yield "retry: 2000\n\n"while True:if await request.is_disconnected():returnevs = await asyncio.to_thread(svc.db.events, run_id, last)for e in evs:last = e["seq"]yield f"id: {e['seq']}\nevent: run_event\ndata: {json.dumps(e, default=str)}\n\n"r = await asyncio.to_thread(svc.db.get_run, run_id)if not evs and r and r["status"] in STREAM_END:yield f"event: end\ndata: {json.dumps({'status': r['status']})}\n\n"returnidle = 0 if evs else idle + 1if idle * 0.5 >= STREAM_IDLE_S: # e.g. a run waiting days at a gate: free the connection; the client pollsyield f"event: end\ndata: {json.dumps({'status': r['status'] if r else None, 'reason': 'idle'})}\n\n"returnif idle and idle % 30 == 0:yield ": keep-alive\n\n"await asyncio.sleep(0.5)return StreamingResponse(gen(), media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})@router.post("/runs/{run_id}/resume")def resume_run(run_id: str, request: Request, user: Principal = Depends(require("run.control"))):_, runs = ctx(request)try:runs.resume(run_id, user.username)except RunError as e:raise _run_error(e) from eexcept KillSwitchEngaged as e:raise ApiError(423, "KILL_SWITCH", str(e)) from ereturn {"status": "queued"}@router.post("/runs/{run_id}/cancel")def cancel_run(run_id: str, body: CancelIn, request: Request, user: Principal = Depends(require("run.control"))):svc, runs = ctx(request)return actions.cancel_run(svc, runs, run_id, user.username, body.reason)@router.post("/runs/{run_id}/notes", status_code=201)def run_note(run_id: str, body: RunNoteIn, request: Request, user: Principal = Depends(require("run.note"))):"""A human note on a run: stored in the append-only audit log and shown in the run's activity feed (run event)."""svc, _ = ctx(request)return actions.add_note(svc, run_id, body.text, user.username, user.role)@router.get("/runs/{run_id}/gate")def run_gate(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)r = _run(svc, run_id)if not r.get("pending_gate"):return Response(status_code=204)return runs.gate_payload(run_id) or Response(status_code=204)@router.get("/runs/{run_id}/research")def run_research(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)return {"pod_profile": st.get("pod_profile"), "research": st.get("research") or [], "coverage_map": st.get("coverage_map"),"research_modules": st.get("research_modules") or [], "target": svc.target(run_id)}@router.get("/runs/{run_id}/cases")def run_cases(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)approvals_rows = svc.db.q("SELECT case_id, gate, decision, actor, comment, ts, auto FROM approvals WHERE run_id=? ORDER BY id", (run_id,))return {"test_cases": st.get("test_cases") or [], "deferred": st.get("deferred") or [],"proposed_cases": st.get("proposed_cases") or [], "ai_drafts": st.get("ai_drafts") or [],"approvals": st.get("approvals") or {}, "approval_log": approvals_rows}@router.get("/runs/{run_id}/data-plan")def run_data(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)return {"data_plan": st.get("data_plan") or {}, "data_refs": st.get("data_refs") or {},"gaps": (st.get("approvals") or {}).get("data_gaps", [])}@router.get("/runs/{run_id}/scripts")def run_scripts(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)outs = (st.get("run_results") or {}).get("outcomes", {})return {cid: {**s, "last_outcome": outs.get(cid)} for cid, s in (st.get("scripts") or {}).items()}@router.get("/runs/{run_id}/results")def run_results(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)return {"run_results": st.get("run_results"), "verdicts": st.get("verdicts") or {}, "review_items": st.get("review_items") or [],"review": st.get("review") or {}, "heal_proposals": st.get("heal_proposals") or [], "tickets": st.get("tickets") or [],"retry_count": st.get("retry_count", 0)}@router.get("/runs/{run_id}/report")def run_report(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)paths = st.get("report_paths") or {}criteria, gaps, counts, summaries = {}, {}, {}, {}for m, p in paths.items():if p.get("summary") and Path(p["summary"]).exists():s = json.loads(Path(p["summary"]).read_text(encoding="utf-8"))criteria[m], gaps[m], counts[m], summaries[m] = s["criteria"], s["gaps"], s["counts"], s.get("executive_summary")files = {m: {k: bool(v and Path(v).exists()) for k, v in p.items()} for m, p in paths.items()}return {"decisions": st.get("decisions") or {}, "decision": st.get("decision"), "decision_source": "reports/generate_report.py","criteria": criteria, "gaps": gaps, "counts": counts, "executive_summary": summaries, "files": files,"run_mode": (st.get("run_results") or {}).get("mode"), "target": svc.target(run_id)}FMT = {"md": ("md", "text/markdown; charset=utf-8"), "html": ("html", "text/html; charset=utf-8"),"pdf": ("pdf", "application/pdf"), "bundle": ("bundle", "text/html; charset=utf-8"),"summary": ("summary", "application/json")}@router.get("/runs/{run_id}/report/{module}/{fmt}")def run_report_file(run_id: str, module: str, fmt: str, request: Request, download: bool = False,user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)if fmt not in FMT:raise ApiError(400, "BAD_FORMAT", f"fmt must be one of {sorted(FMT)}")paths = (runs.state(run_id).get("report_paths") or {}).get(module.upper())if not paths or not paths.get(FMT[fmt][0]) or not Path(paths[FMT[fmt][0]]).exists():from ...platform.statesync import not_kept_after_restartif paths and paths.get(FMT[fmt][0]) and not_kept_after_restart(svc.cfg.home, "run_folder", run_id=run_id):raise ApiError(410, "NOT_KEPT", f"The {fmt} report of run {run_id} was not kept after a restart: the saved copy of ""the data was over the size limit, so the folders of finished runs were left out. ""The run's results and decisions are still here.")raise ApiError(404, "NOT_FOUND", f"no {fmt} report for {module} in run {run_id}")p = Path(paths[FMT[fmt][0]]).resolve()if not p.is_relative_to(svc.cfg.runs_dir.resolve()):raise ApiError(403, "FORBIDDEN", "report path outside the run directory")name = f"{run_id}-{module.lower()}-go-no-go.{ {'summary': 'json', 'bundle': 'html'}.get(fmt, fmt) }"disp = "attachment" if download or fmt == "pdf" else "inline"return FileResponse(p, media_type=FMT[fmt][1], headers={"Content-Disposition": f'{disp}; filename="{name}"'})@router.get("/runs/{run_id}/evidence")def run_evidence(run_id: str, request: Request, case_id: str | None = None, user: Principal = Depends(require("read"))):svc, _ = ctx(request)_run(svc, run_id)return [e.to_dict() for e in svc.evidence.list(run_id, case_id)]@router.delete("/runs/{run_id}/evidence")def delete_run_evidence(run_id: str, request: Request, user: Principal = Depends(require("admin"))):"""Administrator: remove all screenshots, videos and traces of one run now. Cannot be undone."""svc, _ = ctx(request)_run(svc, run_id)return svc.evidence.delete_run(run_id, actor=user.username)@router.get("/evidence/{evidence_id}")def evidence_file(evidence_id: int, request: Request, user: Principal = Depends(require("evidence.read"))):svc, _ = ctx(request)from ...platform.evidence import EvidenceMissingfrom ...platform.statesync import not_kept_after_restarttry:data, ctype = svc.evidence.open(evidence_id, actor=user.username)except EvidenceMissing as e:if not_kept_after_restart(svc.cfg.home, "evidence", created_at=e.created_at):raise ApiError(410, "NOT_KEPT", f"Screenshot or recording {evidence_id} was not kept after a restart: the saved copy ""of the data was over the size limit, so screenshots, videos and traces were left ""out. The run's results are still here.") from eraise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the ""retention clean-up, or it is no longer stored on this server.") from eexcept FileNotFoundError as e: # a fixed sentence: the OS error text could show server pathsraise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the ""retention clean-up, or it is no longer stored on this server.") from ereturn Response(content=data, media_type=ctype, headers={"Content-Disposition": f'inline; filename="evidence-{evidence_id}"',"Cache-Control": "no-store"})@router.get("/pod/profile")def pod_profile(request: Request, refresh: bool = False, user: Principal = Depends(require("read"))):svc, _ = ctx(request)if refresh:if not user.can("run.start"):raise ApiError(403, "FORBIDDEN", "refresh needs a role that may start runs")pod = svc.pod()about = pod.about()mods = [{"module": m.get("idPrefix"), "pack_id": m["id"], "name": m.get("name"), "resources": m.get("resources", []),"processes": m.get("processes", []), "personas": m.get("personas", [])} for m in pod.modules()]prof = {"about": about, "modules": mods, "scanned_at": None, "refreshed": True}svc.db.kv_set("pod_profile_light", prof)return profreturn svc.db.kv_get("pod_profile") or svc.db.kv_get("pod_profile_light") or {"about": None, "modules": []}@router.get("/runs/{run_id}/temporal")def run_temporal(run_id: str, request: Request, user: Principal = Depends(require("admin"))):"""Admin: the run's Temporal workflow (status, query result, Temporal Web UI link)."""svc, runs = ctx(request)r = _run(svc, run_id)if r.get("orchestrator") != "temporal" or not hasattr(runs, "describe"):raise ApiError(404, "NOT_TEMPORAL", "this run was not orchestrated by Temporal")return runs.describe(run_id)@router.get("/graph")def graph_spec(user: Principal = Depends(require("read"))):return GRAPH_SPEC@router.get("/cases/{case_id}/yaml")def case_yaml(case_id: str, request: Request, user: Principal = Depends(require("read"))):"""Read-only YAML of a library case (tests/cases), for the approval screen's preview."""import re as _refrom ...adapters.cases import find_yamlif not _re.fullmatch(r"[A-Z][A-Z0-9]{1,5}(-[A-Z0-9]+)+", case_id):raise ApiError(400, "BAD_ID", "invalid case id")p = find_yaml(case_id)if not p:raise ApiError(404, "NOT_FOUND", f"no YAML for {case_id}")return {"case_id": case_id, "path": p.name,"yaml": p.read_text(encoding="utf-8")}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380"""/api/runs*: start/list/detail/events/SSE stream/resume/cancel/gate + per-phase views + report files + evidence."""from __future__ import annotationsimport asyncioimport jsonfrom pathlib import Pathfrom fastapi import APIRouter, Depends, Query, Requestfrom fastapi.responses import FileResponse, Response, StreamingResponsefrom ...graph.build import GRAPH_SPECfrom ...platform.killswitch import KillSwitchEngagedfrom .. import actionsfrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom ..runner import TERMINAL, RunErrorfrom ..schemas import CancelIn, Page, RunCreate, RunCreated, RunDetail, RunEvent, RunNoteIn, RunSummaryrouter = APIRouter(tags=["runs"])def ctx(request: Request):return request.app.state.svc, request.app.state.runsdef _run(svc, run_id: str) -> dict:r = svc.db.get_run(run_id)if not r:raise ApiError(404, "NOT_FOUND", f"run {run_id} not found")return rdef _summary(r: dict) -> dict:inp = r.get("inputs") if isinstance(r.get("inputs"), dict) else {}return {**r, "modules": r.get("modules") or [], "decisions": r.get("decisions") or {}, "pod_name": inp.get("pod_name")}def _run_error(e: RunError):return ApiError(e.status, e.code, str(e))@router.post("/runs", status_code=202, response_model=RunCreated)def start_run(body: RunCreate, request: Request, user: Principal = Depends(require("run.start"))):svc, runs = ctx(request)rid = actions.start_run(svc, runs, body.model_dump(exclude_none=True) | {"stub_knobs": body.stub_knobs.model_dump(exclude_none=True) if body.stub_knobs else {}},actor=user.username)return {"run_id": rid, "status": "queued"}@router.get("/runs", response_model=Page[RunSummary])def list_runs(request: Request, status: str | None = None, limit: int = Query(50, ge=1, le=500), offset: int = Query(0, ge=0),user: Principal = Depends(require("read"))):svc, _ = ctx(request)rows = svc.db.list_runs(status, limit, offset)counts = _counts(svc.db, [r["run_id"] for r in rows])return {"items": [{**_summary(r), "counts": counts.get(r["run_id"], {})} for r in rows], "total": svc.db.count_runs(status),"limit": limit, "offset": offset}_COUNTED = ("passed", "failed", "skipped", "flaky", "total")def _counts(db, run_ids: list[str]) -> dict[str, dict[str, int]]:"""Results of finished runs, all business areas of a run added up (one query for the whole page)."""if not run_ids:return {}out: dict[str, dict[str, int]] = {}marks = ",".join("?" * len(run_ids))for h in db.q(f"SELECT run_id, counts FROM run_history WHERE run_id IN ({marks})", tuple(run_ids)):c = h["counts"] if isinstance(h["counts"], dict) else json.loads(h["counts"] or "{}")acc = out.setdefault(h["run_id"], {k: 0 for k in _COUNTED})for k in _COUNTED:acc[k] += int(c.get(k) or 0)return out@router.get("/runs.csv")def export_runs(request: Request, status: str | None = None, user: Principal = Depends(require("read"))):"""Every test run as a CSV file (newest first) for spreadsheets and status reports. No evidence or credentials."""import csvimport iosvc, _ = ctx(request)buf = io.StringIO()w = csv.writer(buf)w.writerow(["run_id", "started_at", "started_by", "trigger", "test_environment", "patch", "business_areas", "run_type","status", "decision", "decisions_by_area", "last_updated_at", "error"])for r in (_summary(x) for x in svc.db.list_runs(status, 100_000, 0)):w.writerow([r["run_id"], r.get("created_at") or "", r.get("created_by") or "", r.get("trigger") or "", r.get("pod_name") or "",r.get("patch_id") or "", " ".join(r["modules"]), "full browser run" if r.get("playwright_mode") == "live" else "quick simulation",r.get("status") or "", r.get("decision") or "", "; ".join(f"{k}={v}" for k, v in r["decisions"].items()),r.get("updated_at") or "", _csv_safe(r.get("error") or "")])svc.audit.append("runs.exported", actor=user.username, summary=f"CSV, status={status or 'all'}")return Response(buf.getvalue(), media_type="text/csv; charset=utf-8",headers={"Content-Disposition": 'attachment; filename="trio-test-runs.csv"'})def _csv_safe(v: str) -> str:"""Spreadsheet apps run a cell that starts with = + - @ as a formula: neutralise it (CSV injection)."""return "'" + v if v[:1] in ("=", "+", "-", "@") else v@router.get("/runs/{run_id}", response_model=RunDetail)def run_detail(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)r = _summary(_run(svc, run_id))st = runs.state(run_id)calls = st.get("llm_calls") or []return {**r, "include_p2": bool(r.get("include_p2")), "live_view": bool(st["live_view"] if "live_view" in st else (r.get("inputs") or {}).get("live_view") if isinstance(r.get("inputs"), dict) else False), "counts": st.get("counts") or r.get("counts") or {},"report_paths": st.get("report_paths") or {}, "errors": st.get("errors") or [], "retry_count": st.get("retry_count", 0),"llm_calls_count": len(calls), "llm_calls": calls, "target": svc.target(run_id), "test_data": _test_data(svc, run_id),"decisions": st.get("decisions") or r["decisions"], "decision": st.get("decision", r.get("decision"))}def _test_data(svc, run_id: str) -> dict | None:"""Fusion test documents this run created: what was cleaned up and what may be left on the pod (None for mock runs)."""if svc.fusion_pod_id(run_id) is None:return Nonefrom ...platform import cleanuprun_dir = svc.run_dir(run_id)entries = cleanup.ledger_entries(run_dir)swept = cleanup.result(run_dir) or {}left = [{"number": e["number"], "test": e.get("test"), "why": "not cleaned up yet"} for e in entries.values() if not e.get("cleaned")]if swept.get("left"):left = swept["left"]return {"created": len(entries), "cleaned": sum(1 for e in entries.values() if e.get("cleaned")), "left": left,"summary": swept.get("summary"), "swept_at": swept.get("at")}@router.get("/runs/{run_id}/events", response_model=list[RunEvent])def run_events(run_id: str, request: Request, after: int = 0, user: Principal = Depends(require("read"))):svc, _ = ctx(request)_run(svc, run_id)return svc.db.events(run_id, after)STREAM_END = TERMINAL + ("interrupted",) # an interrupted run waits for a person to resume it: nothing more will streamSTREAM_IDLE_S = 900 # a stream with no new event for 15 minutes ends (reason "idle")@router.get("/runs/{run_id}/stream")async def run_stream(run_id: str, request: Request, after: int = 0, user: Principal = Depends(require("read"))):"""Server-Sent Events: every run event (node started/finished/interrupted/error, status changes). Ends when the runreaches a terminal status. Clients fall back to polling /events."""svc, _ = ctx(request)_run(svc, run_id)last = int(request.headers.get("last-event-id") or after or 0)async def gen():nonlocal lastidle = 0yield "retry: 2000\n\n"while True:if await request.is_disconnected():returnevs = await asyncio.to_thread(svc.db.events, run_id, last)for e in evs:last = e["seq"]yield f"id: {e['seq']}\nevent: run_event\ndata: {json.dumps(e, default=str)}\n\n"r = await asyncio.to_thread(svc.db.get_run, run_id)if not evs and r and r["status"] in STREAM_END:yield f"event: end\ndata: {json.dumps({'status': r['status']})}\n\n"returnidle = 0 if evs else idle + 1if idle * 0.5 >= STREAM_IDLE_S: # e.g. a run waiting days at a gate: free the connection; the client pollsyield f"event: end\ndata: {json.dumps({'status': r['status'] if r else None, 'reason': 'idle'})}\n\n"returnif idle and idle % 30 == 0:yield ": keep-alive\n\n"await asyncio.sleep(0.5)return StreamingResponse(gen(), media_type="text/event-stream", headers={"Cache-Control": "no-store", "X-Accel-Buffering": "no"})@router.post("/runs/{run_id}/resume")def resume_run(run_id: str, request: Request, user: Principal = Depends(require("run.control"))):_, runs = ctx(request)try:runs.resume(run_id, user.username)except RunError as e:raise _run_error(e) from eexcept KillSwitchEngaged as e:raise ApiError(423, "KILL_SWITCH", str(e)) from ereturn {"status": "queued"}@router.post("/runs/{run_id}/cancel")def cancel_run(run_id: str, body: CancelIn, request: Request, user: Principal = Depends(require("run.control"))):svc, runs = ctx(request)return actions.cancel_run(svc, runs, run_id, user.username, body.reason)@router.post("/runs/{run_id}/notes", status_code=201)def run_note(run_id: str, body: RunNoteIn, request: Request, user: Principal = Depends(require("run.note"))):"""A human note on a run: stored in the append-only audit log and shown in the run's activity feed (run event)."""svc, _ = ctx(request)return actions.add_note(svc, run_id, body.text, user.username, user.role)@router.get("/runs/{run_id}/gate")def run_gate(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)r = _run(svc, run_id)if not r.get("pending_gate"):return Response(status_code=204)return runs.gate_payload(run_id) or Response(status_code=204)@router.get("/runs/{run_id}/research")def run_research(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)return {"pod_profile": st.get("pod_profile"), "research": st.get("research") or [], "coverage_map": st.get("coverage_map"),"research_modules": st.get("research_modules") or [], "target": svc.target(run_id)}@router.get("/runs/{run_id}/cases")def run_cases(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)approvals_rows = svc.db.q("SELECT case_id, gate, decision, actor, comment, ts, auto FROM approvals WHERE run_id=? ORDER BY id", (run_id,))return {"test_cases": st.get("test_cases") or [], "deferred": st.get("deferred") or [],"proposed_cases": st.get("proposed_cases") or [], "ai_drafts": st.get("ai_drafts") or [],"approvals": st.get("approvals") or {}, "approval_log": approvals_rows}@router.get("/runs/{run_id}/data-plan")def run_data(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)return {"data_plan": st.get("data_plan") or {}, "data_refs": st.get("data_refs") or {},"gaps": (st.get("approvals") or {}).get("data_gaps", [])}@router.get("/runs/{run_id}/scripts")def run_scripts(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)outs = (st.get("run_results") or {}).get("outcomes", {})return {cid: {**s, "last_outcome": outs.get(cid)} for cid, s in (st.get("scripts") or {}).items()}@router.get("/runs/{run_id}/results")def run_results(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)return {"run_results": st.get("run_results"), "verdicts": st.get("verdicts") or {}, "review_items": st.get("review_items") or [],"review": st.get("review") or {}, "heal_proposals": st.get("heal_proposals") or [], "tickets": st.get("tickets") or [],"retry_count": st.get("retry_count", 0)}@router.get("/runs/{run_id}/report")def run_report(run_id: str, request: Request, user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)st = runs.state(run_id)paths = st.get("report_paths") or {}criteria, gaps, counts, summaries = {}, {}, {}, {}for m, p in paths.items():if p.get("summary") and Path(p["summary"]).exists():s = json.loads(Path(p["summary"]).read_text(encoding="utf-8"))criteria[m], gaps[m], counts[m], summaries[m] = s["criteria"], s["gaps"], s["counts"], s.get("executive_summary")files = {m: {k: bool(v and Path(v).exists()) for k, v in p.items()} for m, p in paths.items()}return {"decisions": st.get("decisions") or {}, "decision": st.get("decision"), "decision_source": "reports/generate_report.py","criteria": criteria, "gaps": gaps, "counts": counts, "executive_summary": summaries, "files": files,"run_mode": (st.get("run_results") or {}).get("mode"), "target": svc.target(run_id)}FMT = {"md": ("md", "text/markdown; charset=utf-8"), "html": ("html", "text/html; charset=utf-8"),"pdf": ("pdf", "application/pdf"), "bundle": ("bundle", "text/html; charset=utf-8"),"summary": ("summary", "application/json")}@router.get("/runs/{run_id}/report/{module}/{fmt}")def run_report_file(run_id: str, module: str, fmt: str, request: Request, download: bool = False,user: Principal = Depends(require("read"))):svc, runs = ctx(request)_run(svc, run_id)if fmt not in FMT:raise ApiError(400, "BAD_FORMAT", f"fmt must be one of {sorted(FMT)}")paths = (runs.state(run_id).get("report_paths") or {}).get(module.upper())if not paths or not paths.get(FMT[fmt][0]) or not Path(paths[FMT[fmt][0]]).exists():from ...platform.statesync import not_kept_after_restartif paths and paths.get(FMT[fmt][0]) and not_kept_after_restart(svc.cfg.home, "run_folder", run_id=run_id):raise ApiError(410, "NOT_KEPT", f"The {fmt} report of run {run_id} was not kept after a restart: the saved copy of ""the data was over the size limit, so the folders of finished runs were left out. ""The run's results and decisions are still here.")raise ApiError(404, "NOT_FOUND", f"no {fmt} report for {module} in run {run_id}")p = Path(paths[FMT[fmt][0]]).resolve()if not p.is_relative_to(svc.cfg.runs_dir.resolve()):raise ApiError(403, "FORBIDDEN", "report path outside the run directory")name = f"{run_id}-{module.lower()}-go-no-go.{ {'summary': 'json', 'bundle': 'html'}.get(fmt, fmt) }"disp = "attachment" if download or fmt == "pdf" else "inline"return FileResponse(p, media_type=FMT[fmt][1], headers={"Content-Disposition": f'{disp}; filename="{name}"'})@router.get("/runs/{run_id}/evidence")def run_evidence(run_id: str, request: Request, case_id: str | None = None, user: Principal = Depends(require("read"))):svc, _ = ctx(request)_run(svc, run_id)return [e.to_dict() for e in svc.evidence.list(run_id, case_id)]@router.delete("/runs/{run_id}/evidence")def delete_run_evidence(run_id: str, request: Request, user: Principal = Depends(require("admin"))):"""Administrator: remove all screenshots, videos and traces of one run now. Cannot be undone."""svc, _ = ctx(request)_run(svc, run_id)return svc.evidence.delete_run(run_id, actor=user.username)@router.get("/evidence/{evidence_id}")def evidence_file(evidence_id: int, request: Request, user: Principal = Depends(require("evidence.read"))):svc, _ = ctx(request)from ...platform.evidence import EvidenceMissingfrom ...platform.statesync import not_kept_after_restarttry:data, ctype = svc.evidence.open(evidence_id, actor=user.username)except EvidenceMissing as e:if not_kept_after_restart(svc.cfg.home, "evidence", created_at=e.created_at):raise ApiError(410, "NOT_KEPT", f"Screenshot or recording {evidence_id} was not kept after a restart: the saved copy ""of the data was over the size limit, so screenshots, videos and traces were left ""out. The run's results are still here.") from eraise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the ""retention clean-up, or it is no longer stored on this server.") from eexcept FileNotFoundError as e: # a fixed sentence: the OS error text could show server pathsraise ApiError(404, "NOT_FOUND", f"Screenshot or recording {evidence_id} is not available: it was removed by the ""retention clean-up, or it is no longer stored on this server.") from ereturn Response(content=data, media_type=ctype, headers={"Content-Disposition": f'inline; filename="evidence-{evidence_id}"',"Cache-Control": "no-store"})@router.get("/pod/profile")def pod_profile(request: Request, refresh: bool = False, user: Principal = Depends(require("read"))):svc, _ = ctx(request)if refresh:if not user.can("run.start"):raise ApiError(403, "FORBIDDEN", "refresh needs a role that may start runs")pod = svc.pod()about = pod.about()mods = [{"module": m.get("idPrefix"), "pack_id": m["id"], "name": m.get("name"), "resources": m.get("resources", []),"processes": m.get("processes", []), "personas": m.get("personas", [])} for m in pod.modules()]prof = {"about": about, "modules": mods, "scanned_at": None, "refreshed": True}svc.db.kv_set("pod_profile_light", prof)return profreturn svc.db.kv_get("pod_profile") or svc.db.kv_get("pod_profile_light") or {"about": None, "modules": []}@router.get("/runs/{run_id}/temporal")def run_temporal(run_id: str, request: Request, user: Principal = Depends(require("admin"))):"""Admin: the run's Temporal workflow (status, query result, Temporal Web UI link)."""svc, runs = ctx(request)r = _run(svc, run_id)if r.get("orchestrator") != "temporal" or not hasattr(runs, "describe"):raise ApiError(404, "NOT_TEMPORAL", "this run was not orchestrated by Temporal")return runs.describe(run_id)@router.get("/graph")def graph_spec(user: Principal = Depends(require("read"))):return GRAPH_SPEC@router.get("/cases/{case_id}/yaml")def case_yaml(case_id: str, request: Request, user: Principal = Depends(require("read"))):"""Read-only YAML of a library case (tests/cases), for the approval screen's preview."""import re as _refrom ...adapters.cases import find_yamlif not _re.fullmatch(r"[A-Z][A-Z0-9]{1,5}(-[A-Z0-9]+)+", case_id):raise ApiError(400, "BAD_ID", "invalid case id")p = find_yaml(case_id)if not p:raise ApiError(404, "NOT_FOUND", f"no YAML for {case_id}")return {"case_id": case_id, "path": p.name,"yaml": p.read_text(encoding="utf-8")}
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697"""/api/runs/{id}/sign-in/*: assisted sign-in (platform/assisted_signin.py). A run on a pod whose sign-in goes through thecompany's identity provider waits at the sign_in gate; here a person opens a browser on the pod, sees it, operates itwith clicks and keys, and the run goes on by itself once the pod's home page opens.
GET /runs/{id}/sign-in whether the run waits for a sign-in, and the session's state (anyone who can read runs)POST /runs/{id}/sign-in/session open a sign-in browser (gate.sign_in); its session id goes to the opener onlyGET /runs/{id}/sign-in/frame the browser's latest picture (JPEG), for the person who opened itPOST /runs/{id}/sign-in/input clicks, text, keys, scrolls: only with the session's id, only from its ownerPOST /runs/{id}/sign-in/finish "I have signed in": take the session now (when the home page is not recognised)POST /runs/{id}/sign-in/cancel close the browser; the run keeps waiting
Nothing typed here is logged or audited (the egress audit counts events by kind); frames are never stored."""from __future__ import annotations
from fastapi import APIRouter, Depends, Requestfrom fastapi.responses import Response
from ...platform.assisted_signin import STATUS, SignInError, SignInSessionsfrom ..auth import Principal, requirefrom ..errors import ApiErrorfrom ..schemas import SignInAccepted, SignInInputIn, SignInSessionIn, SignInStatusOut
router = APIRouter(tags=["sign-in"])
def _sessions(request: Request) -> SignInSessions: st = request.app.state if getattr(st, "sign_in", None) is None: st.sign_in = SignInSessions(st.svc, st.runs) if hasattr(st.runs, "sign_in"): st.runs.sign_in = st.sign_in return st.sign_in
def _err(e: SignInError) -> ApiError: return ApiError(e.status, e.code, str(e))
def _status(request: Request, run_id: str, user: Principal) -> dict: svc = request.app.state.svc run = svc.db.get_run(run_id) if not run: raise ApiError(404, "NOT_FOUND", f"run {run_id} not found") waiting = run.get("status") == STATUS and run.get("pending_gate") == "sign_in" gate = request.app.state.runs.gate_payload(run_id) if waiting else None return {"waiting": waiting, "gate": gate if isinstance(gate, dict) else None, **_sessions(request).status(run_id, user.username)}
@router.get("/runs/{run_id}/sign-in", response_model=SignInStatusOut)def sign_in_status(run_id: str, request: Request, user: Principal = Depends(require("read"))): return _status(request, run_id, user)
@router.post("/runs/{run_id}/sign-in/session", response_model=SignInStatusOut)def open_session(run_id: str, request: Request, user: Principal = Depends(require("gate.sign_in"))): try: opened = _sessions(request).start(run_id, user.username) except SignInError as e: raise _err(e) from e return {**_status(request, run_id, user), "session_id": opened["session_id"]}
@router.get("/runs/{run_id}/sign-in/frame")def session_frame(run_id: str, request: Request, user: Principal = Depends(require("gate.sign_in"))): try: fr = _sessions(request).frame(run_id, user.username) except SignInError as e: raise _err(e) from e if not fr: return Response(status_code=204, headers={"Cache-Control": "no-store"}) return Response(fr[0], media_type="image/jpeg", headers={"Cache-Control": "no-store"})
@router.post("/runs/{run_id}/sign-in/input", response_model=SignInAccepted)def session_input(run_id: str, body: SignInInputIn, request: Request, user: Principal = Depends(require("gate.sign_in"))): try: return _sessions(request).send(run_id, user.username, body.session_id, [e.model_dump(exclude_none=True) for e in body.events]) except SignInError as e: raise _err(e) from e
@router.post("/runs/{run_id}/sign-in/finish", response_model=SignInStatusOut)def session_finish(run_id: str, body: SignInSessionIn, request: Request, user: Principal = Depends(require("gate.sign_in"))): try: _sessions(request).finish(run_id, user.username, body.session_id) except SignInError as e: raise _err(e) from e return _status(request, run_id, user)
@router.post("/runs/{run_id}/sign-in/cancel", response_model=SignInStatusOut)def session_cancel(run_id: str, body: SignInSessionIn, request: Request, user: Principal = Depends(require("gate.sign_in"))): try: _sessions(request).cancel(run_id, user.username, body.session_id) except SignInError as e: raise _err(e) from e return _status(request, run_id, user)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420"""RunManager: ONE worker thread runs one graph run at a time (mock + Playwright are stateful, workers: 1).Jobs: start / resume (gate answer) / continue (crash recovery). Status: queued -> running -> waiting_approval |waiting_review -> running -> completed | failed | killed | cancelled | interrupted (backend restarted mid-run)."""from __future__ import annotationsimport jsonimport loggingimport queueimport secretsimport threadingfrom datetime import datetime, timezonefrom langgraph.errors import GraphRecursionErrorfrom langgraph.types import Commandfrom ..graph.build import build_graph, run_config, sqlite_checkpointerfrom ..graph.runtime import FatalNodeErrorfrom ..platform import procsfrom ..platform.failures import plain as plain_failurefrom ..platform.killswitch import KillSwitchEngagedfrom ..platform.rundb import now_isolog = logging.getLogger("fpt.runner")GATE_STATUS = {"approve_cases": "waiting_approval", "human_review": "waiting_review"}TERMINAL = ("completed", "failed", "killed", "cancelled")def sweep_test_data(svc, run_id: str, reason: str) -> dict | None:"""Cancel Fusion test invoices a run left behind (platform/cleanup.py); never raises."""from ..platform import cleanuptry:return cleanup.sweep(svc, run_id, reason)except Exception: # noqa: BLE001log.exception("test data clean-up of run %s failed", run_id)return Noneclass RunError(RuntimeError):def __init__(self, msg: str, code: str = "CONFLICT", status: int = 409):super().__init__(msg)self.code, self.status = code, statusdef new_run_id() -> str:return datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") + "-" + secrets.token_hex(3)def record_anchor(svc, run_id: str, status: str) -> dict:"""Write the audit chain head OUTSIDE the DB at run end (anchors file + structured log line) for truncation checks."""import time as _thead = svc.audit.head()anchor = {"run_id": run_id, "status": status, "audit_seq": head["seq"], "audit_hash": head["hash"],"ts": _t.strftime("%Y-%m-%dT%H:%M:%SZ", _t.gmtime())}f = svc.cfg.path("logs", "audit-anchors.jsonl")f.parent.mkdir(parents=True, exist_ok=True)with f.open("a", encoding="utf-8") as fh:fh.write(json.dumps(anchor) + "\n")logging.getLogger("fpt.audit").info("audit anchor %s", json.dumps(anchor))return anchorDUPLICATE_WINDOW_S = 600 # a second identical start within 10 minutes of one still going is refused_STATUS_WORDS = {"queued": "queued", "running": "running", "waiting_approval": "waiting for scenario approval","waiting_review": "waiting for QA review"}def _duplicate_run(svc, actor: str, pod_id: int, mods: list[str], patch: str | None) -> dict | None:"""A run by the same person on the same pod with the same business areas (and patch) that is still going and startedrecently: almost always a double click or a second tab."""from datetime import timedeltasince = (datetime.now(timezone.utc) - timedelta(seconds=DUPLICATE_WINDOW_S)).isoformat(timespec="seconds")rows = svc.db.q("SELECT run_id, status, modules, patch_id FROM runs WHERE created_by=? AND pod_id=? AND created_at>=? ""AND status IN ('queued','running','waiting_approval','waiting_review') ORDER BY created_at DESC",(actor, pod_id, since))return next((r for r in rows if sorted(r["modules"] or []) == sorted(mods) and (r["patch_id"] or None) == (patch or None)), None)def _refuse_duplicate(svc, actor: str, pod: dict, mods: list[str], patch: str | None) -> None:dup = _duplicate_run(svc, actor, pod["id"], mods, patch)if dup:raise RunError(f"Test run {dup['run_id']} with the same business areas on {pod['name']} is already "f"{_STATUS_WORDS.get(dup['status'], dup['status'])}. Open that run instead of starting another.", "DUPLICATE_RUN", 409)def _create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod) -> None:svc.db.create_run({"run_id": rid, "created_by": actor, "trigger": trigger, "patch_id": inputs.get("patch_id"),"modules": mods, "include_p2": int(state["include_p2"]), "playwright_mode": state["playwright_mode"],"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",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). `run_id`: an id the caller reservedbeforehand (an Agent Studio cycle records it before the run exists); a new one otherwise."""svc.kill.check("run.start")from ..platform.pods import PodError, PodRegistryreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)try:pod = reg.get(int(inputs["pod_id"])) if inputs.get("pod_id") else reg.default()except PodError as e:raise RunError(str(e), e.code, e.status) from eif not pod["runnable"]:raise RunError(pod["not_runnable_reason"] or "this pod cannot run tests", "POD_NOT_RUNNABLE", 409)_refuse_duplicate(svc, actor, pod, [m.upper() for m in inputs.get("modules") or []], inputs.get("patch_id")) # before signing in to Fusion againif pod["kind"] == "fusion": # only business areas this pod has (discovery; the run's scout discovers again)problem = reg.area_problem(pod, [m.upper() for m in inputs.get("modules") or []])if problem:raise RunError(problem, "AREA_NOT_ON_FUSION", 409)# prove the pod and its test user now, in seconds, instead of failing minutes into the runfailed = next((c for c in reg.fusion_checks(pod) if not c["ok"]), None)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 = 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 []],"depth": inputs.get("depth") if inputs.get("depth") in ("smoke", "standard", "full") else "standard","playwright_mode": inputs.get("playwright_mode") or svc.cfg.playwright_mode,"stub_knobs": {k: v for k, v in (inputs.get("stub_knobs") or {}).items() if k in ("STUB_FAIL", "STUB_DEFECT", "STUB_UI", "STUB_FLAKY") and v},"pod_id": pod["id"], "pod_name": pod["name"]}if state["playwright_mode"] == "live" and not svc.cfg.browser_runs_allowed:raise RunError("This server is too small to run a real browser. Start a quick simulation here, or use a server with at least 2 GB of memory.","BROWSER_RUNS_OFF", 409)state["live_view"] = state["playwright_mode"] == "live" and inputs.get("live_view") is not Falseif not state["patch_id"]:state.pop("patch_id")if state["playwright_mode"] != "stub":state["stub_knobs"] = {}with svc.db.write_lock: # the duplicate check and the insert are one step: a double click starts one run_refuse_duplicate(svc, actor, pod, mods, inputs.get("patch_id"))_create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod)if orchestrator == "temporal":from ..graph.statestore import StateStoreStateStore(svc.db).save(rid, dict(state))svc.db.add_event(rid, None, "status", {"status": "queued", "orchestrator": orchestrator})svc.audit.append("run.started", actor=actor, run_id=rid, summary=f"{trigger} {mods or 'all'} {state['playwright_mode']} via {orchestrator}",payload={**{k: v for k, v in state.items() if k != "run_id"}, **({"via": str(inputs["via"])} if inputs.get("via") else {})})return rid, stateclass RunManager:orchestrator = "langgraph"fallback_reason: str | None = Nonedef __init__(self, svc):self.svc = svcself.saver = sqlite_checkpointer(svc.cfg.checkpoint_path)self.graph = build_graph(svc, self.saver)self.q: queue.Queue = queue.Queue()self.current: str | None = Noneself._cancel: set[str] = set()self._stop = threading.Event()# the app is shutting down: no new run starts, no queued job is taken, a running run stops at its next stepself._shutting_down = threading.Event()self._thread: threading.Thread | None = Noneself.listeners: list = [] # callables(run_id, status) e.g. desktop notifications via SSE# ------------------------------------------------------------ lifecycledef recover(self) -> list[str]:"""After a restart: a run that was running is marked interrupted (resume it by hand); a run that was queued withits job saved (a start, a gate answer, a resume) is queued again, so an answered gate is not lost."""ids = []for r in self.svc.db.list_runs("running", 1000):self._interrupted(r["run_id"])ids.append(r["run_id"])for r in self.svc.db.list_runs("queued", 1000):job = self.svc.db.one("SELECT * FROM run_jobs WHERE run_id=? AND done_at IS NULL ORDER BY id DESC LIMIT 1", (r["run_id"],))if job and r.get("orchestrator", "langgraph") == "langgraph":self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE run_id=? AND done_at IS NULL AND id<?", (now_iso(), r["run_id"], job["id"]))self.q.put((job["kind"], r["run_id"], job["payload"], job["gate"], job["id"]))self.svc.db.add_event(r["run_id"], job["gate"], "status", {"status": "queued", "reason": "backend restarted; queued again"})continueself._interrupted(r["run_id"])ids.append(r["run_id"])return idsdef _interrupted(self, run_id: str) -> None:self.svc.db.update_run(run_id, status="interrupted")self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE run_id=? AND done_at IS NULL", (now_iso(), run_id))self.svc.db.add_event(run_id, None, "status", {"status": "interrupted", "reason": "backend restarted"})# the browser died with the old server: cancel the test invoices it had not cleaned up yet (in the background)threading.Thread(target=sweep_test_data, args=(self.svc, run_id, "interrupted by a restart"), daemon=True).start()def _enqueue(self, kind: str, run_id: str, payload, gate: str | None = None) -> None:jid = self.svc.db.insert("run_jobs", {"run_id": run_id, "kind": kind, "gate": gate, "payload": json.dumps(payload, default=str),"created_at": now_iso()})self.q.put((kind, run_id, payload, gate, jid))def start_worker(self) -> None:if self._thread and self._thread.is_alive():returnself._stop.clear()self._thread = threading.Thread(target=self._loop, name="fpt-run-worker", daemon=True)self._thread.start()def stop(self) -> None:self._stop.set()self.q.put(None)if self._thread:self._thread.join(timeout=10)def stop_for_shutdown(self, wait_s: float) -> bool:"""Shutdown, before the last save: take no new work, and let a running run stop at its next safe point (betweentwo graph steps, where its checkpoint is complete). That run is queued to continue after the restart instead ofcoming back interrupted. Waits at most wait_s; a step that takes longer (a browser attempt) is left to the oldbehaviour (interrupted after the restart), so shutdown is never held up. True when the worker stopped in time."""self._shutting_down.set()self._stop.set()self.q.put(None)t = self._threadif t is None or not t.is_alive():return Truet.join(timeout=max(0.0, float(wait_s)))return not t.is_alive()def drain(self, timeout: float = 600) -> None:"""Tests/CLI: process queued jobs synchronously in the calling thread."""import timeend = time.time() + timeoutwhile time.time() < end:try:job = self.q.get_nowait()except queue.Empty:returnif job:self._execute(*job)# ------------------------------------------------------------ APIdef start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str:if self._shutting_down.is_set():raise RunError("the server is restarting: start the run again in a minute", "SHUTTING_DOWN", 503)rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph", run_id=run_id)self._enqueue("start", rid, state)return riddef answer_gate(self, run_id: str, gate: str, answer: dict, actor: str) -> None:run = self._get(run_id)if run["pending_gate"] != gate or run["status"] != GATE_STATUS.get(gate):raise RunError(f"run {run_id} is not waiting at gate {gate} (status {run['status']}, gate {run['pending_gate']})", "NOT_AT_GATE")self.svc.kill.check("gate.answer")# check-and-write in one statement: a double click must not let the second answer resume the NEXT gateif not self.svc.db.claim_run(run_id, GATE_STATUS[gate], gate, status="queued", pending_gate=None):raise RunError(f"run {run_id} is no longer waiting at gate {gate}: this answer was already given", "NOT_AT_GATE")self.svc.db.add_event(run_id, gate, "status", {"status": "queued", "answered_by": actor})self._enqueue("resume", run_id, {**answer, "actor": actor}, gate)def resume(self, run_id: str, actor: str) -> None:run = self._get(run_id)if run["status"] not in ("interrupted", "failed"):raise RunError(f"run {run_id} is {run['status']}; only interrupted/failed runs can be resumed", "NOT_RESUMABLE")self.svc.kill.check("run.resume")self.svc.audit.append("run.resumed", actor=actor, run_id=run_id)snap = self.graph.get_state(run_config(run_id, self.svc.cfg))intr = self._interrupt(snap)if intr is not None:self._pause(run_id, intr)returnself.svc.db.update_run(run_id, status="queued", error=None)self._enqueue("continue", run_id, None)def cancel(self, run_id: str, actor: str, reason: str = "") -> None:run = self._get(run_id)if run["status"] in TERMINAL:raise RunError(f"run {run_id} is already {run['status']}", "ALREADY_FINISHED")self._cancel.add(run_id)if self.current == run_id:procs.kill_all(f"playwright:{run_id}")self.svc.db.update_run(run_id, status="cancelled", pending_gate=None, error=reason or None)self.svc.db.add_event(run_id, None, "status", {"status": "cancelled", "by": actor, "reason": reason})self.svc.audit.append("run.cancelled", actor=actor, run_id=run_id, summary=reason)from ..platform.statesync import save_soonsave_soon("run cancelled")if self.current != run_id: # a running one is swept by the worker once Playwright is gonethreading.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 itrunning): 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_jobrelease_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))return self._interrupt(snap)def state(self, run_id: str) -> dict:vals = dict(self.graph.get_state(run_config(run_id, self.svc.cfg)).values or {})if not vals: # an old finished run whose step checkpoints were pruned: its final state was kept in the run folderfrom ..platform.retention import final_statevals = final_state(self.svc.cfg.runs_dir / run_id) or {}return valsdef kill_active(self) -> None:if self.current:procs.kill_all(f"playwright:{self.current}")# ------------------------------------------------------------ workerdef _get(self, run_id: str) -> dict:r = self.svc.db.get_run(run_id)if not r:raise RunError(f"run {run_id} not found", "NOT_FOUND", 404)return r@staticmethoddef _interrupt(snap) -> dict | None:for t in snap.tasks or ():for i in t.interrupts or ():return i.valuereturn Nonedef _pause(self, run_id: str, payload: dict) -> None:gate = payload.get("gate")st = GATE_STATUS.get(gate, "waiting_approval")self.svc.db.update_run(run_id, status=st, pending_gate=gate)self.svc.db.add_event(run_id, gate, "status", {"status": st, "gate": gate})self._notify(run_id, st)def _notify(self, run_id: str, status: str) -> None:from ..platform.statesync import save_soonsave_soon(f"run {status}") # a run that waits for a person or has ended must survive a restartfor fn in list(self.listeners):try:fn(run_id, status)except Exception: # noqa: BLE001log.exception("listener failed")def _loop(self) -> None:while not self._stop.is_set():job = self.q.get()if job is None or self._stop.is_set(): # stopping: the job stays in run_jobs and runs after the restartcontinuetry:self._execute(*job)except Exception: # noqa: BLE001log.exception("run job crashed")def _execute(self, kind: str, run_id: str, payload, gate: str | None = None, job_id: int | None = None) -> None:try:self._work(kind, run_id, payload, gate)finally:r = self.svc.db.get_run(run_id)if r and r["status"] in TERMINAL:sweep_test_data(self.svc, run_id, r["status"])if job_id is not None:self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE id=?", (now_iso(), job_id))def _continue_after_restart(self, run_id: str) -> None:"""The app is shutting down between two steps of this run: queue it with a 'continue' job (kept in run_jobs, sorecover() picks it up at the next start) and let the last save hold it that way."""self.svc.db.update_run(run_id, status="queued")self.svc.db.insert("run_jobs", {"run_id": run_id, "kind": "continue", "gate": None, "payload": "null", "created_at": now_iso()})self.svc.db.add_event(run_id, None, "status", {"status": "queued", "reason": "the server is restarting; the run continues after the restart"})self.svc.audit.append("run.paused_for_restart", actor="system", run_id=run_id, summary="stopped between steps for a restart")log.info("run %s stopped between steps for the restart; it continues after it", run_id)def _work(self, kind: str, run_id: str, payload, gate: str | None = None) -> None:run = self.svc.db.get_run(run_id)if not run or run["status"] == "cancelled" or run_id in self._cancel:returncfg = run_config(run_id, self.svc.cfg)if kind == "resume":# a gate answer only resumes the gate it was given for; never a later pause of the same runintr = self._interrupt(self.graph.get_state(cfg))if intr is None or intr.get("gate") != gate:log.warning("run %s: answer for gate %s dropped, the run is at %s", run_id, gate, intr and intr.get("gate"))self.svc.db.add_event(run_id, gate, "gate_answer_dropped", {"gate": gate, "now_at": intr and intr.get("gate")})if intr is not None:self._pause(run_id, intr)returnpayload = Command(resume=payload)self.current = run_idself.svc.db.update_run(run_id, status="running")self.svc.db.add_event(run_id, None, "status", {"status": "running"})try:if self.svc.kill.engaged():raise KillSwitchEngaged("kill switch engaged before start")inp = payload if kind in ("start", "resume") else Nonefor _upd in self.graph.stream(inp, cfg, stream_mode="updates"):if run_id in self._cancel:returnif self.svc.kill.engaged():raise KillSwitchEngaged("kill switch engaged between steps")if self._shutting_down.is_set():self._continue_after_restart(run_id)returnsnap = self.graph.get_state(cfg)intr = self._interrupt(snap)if intr is not None:self._pause(run_id, intr)returnv = snap.valuesself.svc.db.update_run(run_id, status="completed", current_node=None, pending_gate=None,decisions=v.get("decisions") or {}, decision=v.get("decision"), counts=v.get("counts") or {},patch_id=v.get("patch_id"))self.svc.db.add_event(run_id, None, "status", {"status": "completed", "decisions": v.get("decisions")})self.svc.audit.append("run.completed", actor="system", run_id=run_id,summary=json.dumps(v.get("decisions")), payload={"decisions": v.get("decisions"), "counts": v.get("counts")})record_anchor(self.svc, run_id, "completed")self._notify(run_id, "completed")except KillSwitchEngaged as e:self.svc.db.update_run(run_id, status="killed", error=str(e), pending_gate=None)self.svc.db.add_event(run_id, None, "status", {"status": "killed", "error": str(e)})self._notify(run_id, "killed")except (FatalNodeError, GraphRecursionError, Exception) as e: # noqa: BLE001if run_id in self._cancel:returnraw = f"{type(e).__name__}: {e}"code, msg = plain_failure(e) # people see a sentence; the raw text stays in the audit log and the server logself.svc.db.update_run(run_id, status="failed", error=msg[:2000], pending_gate=None)self.svc.db.add_event(run_id, None, "status", {"status": "failed", "error": msg[:2000], "code": code,"fatal": isinstance(e, FatalNodeError)})self.svc.audit.append("run.failed", actor="system", run_id=run_id, summary=msg[:300], payload={"code": code, "raw": raw[:2000]})self._notify(run_id, "failed")log.warning("run %s failed: %s", run_id, raw)finally:self.current = Noneself._cancel.discard(run_id)123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433"""RunManager: ONE worker thread runs one graph run at a time (mock + Playwright are stateful, workers: 1).Jobs: start / resume (gate answer) / continue (crash recovery). Status: queued -> running -> waiting_approval |waiting_sign_in | waiting_review -> running -> completed | failed | killed | cancelled | interrupted (backend restartedmid-run). waiting_sign_in: a pod with assisted sign-in waits for a person to sign in (platform/assisted_signin.py)."""from __future__ import annotationsimport jsonimport loggingimport queueimport secretsimport threadingfrom datetime import datetime, timezonefrom langgraph.errors import GraphRecursionErrorfrom langgraph.types import Commandfrom ..graph.build import build_graph, run_config, sqlite_checkpointerfrom ..graph.runtime import FatalNodeErrorfrom ..platform import procsfrom ..platform.failures import plain as plain_failurefrom ..platform.killswitch import KillSwitchEngagedfrom ..platform.rundb import now_isolog = logging.getLogger("fpt.runner")GATE_STATUS = {"approve_cases": "waiting_approval", "sign_in": "waiting_sign_in", "human_review": "waiting_review"}TERMINAL = ("completed", "failed", "killed", "cancelled")def end_sign_in(svc, run_id: str, sessions=None) -> None:"""A run that ended keeps no captured session (assisted sign-in) and no sign-in browser open; never raises."""from ..platform import assisted_signinassisted_signin.at_end(svc, run_id, sessions)def sweep_test_data(svc, run_id: str, reason: str) -> dict | None:"""Cancel Fusion test invoices a run left behind (platform/cleanup.py); never raises."""from ..platform import cleanuptry:return cleanup.sweep(svc, run_id, reason)except Exception: # noqa: BLE001log.exception("test data clean-up of run %s failed", run_id)return Noneclass RunError(RuntimeError):def __init__(self, msg: str, code: str = "CONFLICT", status: int = 409):super().__init__(msg)self.code, self.status = code, statusdef new_run_id() -> str:return datetime.now(timezone.utc).strftime("%Y%m%d-%H%M%S") + "-" + secrets.token_hex(3)def record_anchor(svc, run_id: str, status: str) -> dict:"""Write the audit chain head OUTSIDE the DB at run end (anchors file + structured log line) for truncation checks."""import time as _thead = svc.audit.head()anchor = {"run_id": run_id, "status": status, "audit_seq": head["seq"], "audit_hash": head["hash"],"ts": _t.strftime("%Y-%m-%dT%H:%M:%SZ", _t.gmtime())}f = svc.cfg.path("logs", "audit-anchors.jsonl")f.parent.mkdir(parents=True, exist_ok=True)with f.open("a", encoding="utf-8") as fh:fh.write(json.dumps(anchor) + "\n")logging.getLogger("fpt.audit").info("audit anchor %s", json.dumps(anchor))return anchorDUPLICATE_WINDOW_S = 600 # a second identical start within 10 minutes of one still going is refused_STATUS_WORDS = {"queued": "queued", "running": "running", "waiting_approval": "waiting for scenario approval","waiting_sign_in": "waiting for a person to sign in to the pod", "waiting_review": "waiting for QA review"}def _duplicate_run(svc, actor: str, pod_id: int, mods: list[str], patch: str | None) -> dict | None:"""A run by the same person on the same pod with the same business areas (and patch) that is still going and startedrecently: almost always a double click or a second tab."""from datetime import timedeltasince = (datetime.now(timezone.utc) - timedelta(seconds=DUPLICATE_WINDOW_S)).isoformat(timespec="seconds")rows = svc.db.q("SELECT run_id, status, modules, patch_id FROM runs WHERE created_by=? AND pod_id=? AND created_at>=? ""AND status IN ('queued','running','waiting_approval','waiting_sign_in','waiting_review') ORDER BY created_at DESC",(actor, pod_id, since))return next((r for r in rows if sorted(r["modules"] or []) == sorted(mods) and (r["patch_id"] or None) == (patch or None)), None)def _refuse_duplicate(svc, actor: str, pod: dict, mods: list[str], patch: str | None) -> None:dup = _duplicate_run(svc, actor, pod["id"], mods, patch)if dup:raise RunError(f"Test run {dup['run_id']} with the same business areas on {pod['name']} is already "f"{_STATUS_WORDS.get(dup['status'], dup['status'])}. Open that run instead of starting another.", "DUPLICATE_RUN", 409)def _create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod) -> None:svc.db.create_run({"run_id": rid, "created_by": actor, "trigger": trigger, "patch_id": inputs.get("patch_id"),"modules": mods, "include_p2": int(state["include_p2"]), "playwright_mode": state["playwright_mode"],"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",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). `run_id`: an id the caller reservedbeforehand (an Agent Studio cycle records it before the run exists); a new one otherwise."""svc.kill.check("run.start")from ..platform.pods import PodError, PodRegistryreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)try:pod = reg.get(int(inputs["pod_id"])) if inputs.get("pod_id") else reg.default()except PodError as e:raise RunError(str(e), e.code, e.status) from eif not pod["runnable"]:raise RunError(pod["not_runnable_reason"] or "this pod cannot run tests", "POD_NOT_RUNNABLE", 409)if orchestrator == "temporal" and pod.get("sign_in_mode") == "assisted": # its sign_in gate exists in this graph onlyraise RunError(f"{pod['name']} uses assisted sign-in, which runs on the built-in orchestrator, not Temporal.","ASSISTED_NEEDS_LANGGRAPH", 409)_refuse_duplicate(svc, actor, pod, [m.upper() for m in inputs.get("modules") or []], inputs.get("patch_id")) # before signing in to Fusion againif pod["kind"] == "fusion": # only business areas this pod has (discovery; the run's scout discovers again)problem = reg.area_problem(pod, [m.upper() for m in inputs.get("modules") or []])if problem:raise RunError(problem, "AREA_NOT_ON_FUSION", 409)# prove the pod and its test user now, in seconds, instead of failing minutes into the runfailed = next((c for c in reg.fusion_checks(pod) if not c["ok"]), None)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 = 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 []],"depth": inputs.get("depth") if inputs.get("depth") in ("smoke", "standard", "full") else "standard","playwright_mode": inputs.get("playwright_mode") or svc.cfg.playwright_mode,"stub_knobs": {k: v for k, v in (inputs.get("stub_knobs") or {}).items() if k in ("STUB_FAIL", "STUB_DEFECT", "STUB_UI", "STUB_FLAKY") and v},"pod_id": pod["id"], "pod_name": pod["name"]}if state["playwright_mode"] == "live" and not svc.cfg.browser_runs_allowed:raise RunError("This server is too small to run a real browser. Start a quick simulation here, or use a server with at least 2 GB of memory.","BROWSER_RUNS_OFF", 409)state["live_view"] = state["playwright_mode"] == "live" and inputs.get("live_view") is not Falseif not state["patch_id"]:state.pop("patch_id")if state["playwright_mode"] != "stub":state["stub_knobs"] = {}with svc.db.write_lock: # the duplicate check and the insert are one step: a double click starts one run_refuse_duplicate(svc, actor, pod, mods, inputs.get("patch_id"))_create_row(svc, rid, actor, trigger, inputs, mods, state, orchestrator, pod)if orchestrator == "temporal":from ..graph.statestore import StateStoreStateStore(svc.db).save(rid, dict(state))svc.db.add_event(rid, None, "status", {"status": "queued", "orchestrator": orchestrator})svc.audit.append("run.started", actor=actor, run_id=rid, summary=f"{trigger} {mods or 'all'} {state['playwright_mode']} via {orchestrator}",payload={**{k: v for k, v in state.items() if k != "run_id"}, **({"via": str(inputs["via"])} if inputs.get("via") else {})})return rid, stateclass RunManager:orchestrator = "langgraph"fallback_reason: str | None = Nonedef __init__(self, svc):self.svc = svcself.saver = sqlite_checkpointer(svc.cfg.checkpoint_path)self.graph = build_graph(svc, self.saver)self.q: queue.Queue = queue.Queue()self.current: str | None = Noneself._cancel: set[str] = set()self._stop = threading.Event()# the app is shutting down: no new run starts, no queued job is taken, a running run stops at its next stepself._shutting_down = threading.Event()self._thread: threading.Thread | None = Noneself.listeners: list = [] # callables(run_id, status) e.g. desktop notifications via SSEself.sign_in = None # the app's SignInSessions (platform/assisted_signin.py), closed with a run that ends# ------------------------------------------------------------ lifecycledef recover(self) -> list[str]:"""After a restart: a run that was running is marked interrupted (resume it by hand); a run that was queued withits job saved (a start, a gate answer, a resume) is queued again, so an answered gate is not lost."""ids = []for r in self.svc.db.list_runs("running", 1000):self._interrupted(r["run_id"])ids.append(r["run_id"])for r in self.svc.db.list_runs("queued", 1000):job = self.svc.db.one("SELECT * FROM run_jobs WHERE run_id=? AND done_at IS NULL ORDER BY id DESC LIMIT 1", (r["run_id"],))if job and r.get("orchestrator", "langgraph") == "langgraph":self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE run_id=? AND done_at IS NULL AND id<?", (now_iso(), r["run_id"], job["id"]))self.q.put((job["kind"], r["run_id"], job["payload"], job["gate"], job["id"]))self.svc.db.add_event(r["run_id"], job["gate"], "status", {"status": "queued", "reason": "backend restarted; queued again"})continueself._interrupted(r["run_id"])ids.append(r["run_id"])return idsdef _interrupted(self, run_id: str) -> None:self.svc.db.update_run(run_id, status="interrupted")self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE run_id=? AND done_at IS NULL", (now_iso(), run_id))self.svc.db.add_event(run_id, None, "status", {"status": "interrupted", "reason": "backend restarted"})# the browser died with the old server: cancel the test invoices it had not cleaned up yet (in the background)threading.Thread(target=sweep_test_data, args=(self.svc, run_id, "interrupted by a restart"), daemon=True).start()def _enqueue(self, kind: str, run_id: str, payload, gate: str | None = None) -> None:jid = self.svc.db.insert("run_jobs", {"run_id": run_id, "kind": kind, "gate": gate, "payload": json.dumps(payload, default=str),"created_at": now_iso()})self.q.put((kind, run_id, payload, gate, jid))def start_worker(self) -> None:if self._thread and self._thread.is_alive():returnself._stop.clear()self._thread = threading.Thread(target=self._loop, name="fpt-run-worker", daemon=True)self._thread.start()def stop(self) -> None:self._stop.set()self.q.put(None)if self._thread:self._thread.join(timeout=10)def stop_for_shutdown(self, wait_s: float) -> bool:"""Shutdown, before the last save: take no new work, and let a running run stop at its next safe point (betweentwo graph steps, where its checkpoint is complete). That run is queued to continue after the restart instead ofcoming back interrupted. Waits at most wait_s; a step that takes longer (a browser attempt) is left to the oldbehaviour (interrupted after the restart), so shutdown is never held up. True when the worker stopped in time."""self._shutting_down.set()self._stop.set()self.q.put(None)t = self._threadif t is None or not t.is_alive():return Truet.join(timeout=max(0.0, float(wait_s)))return not t.is_alive()def drain(self, timeout: float = 600) -> None:"""Tests/CLI: process queued jobs synchronously in the calling thread."""import timeend = time.time() + timeoutwhile time.time() < end:try:job = self.q.get_nowait()except queue.Empty:returnif job:self._execute(*job)# ------------------------------------------------------------ APIdef start(self, inputs: dict, actor: str, trigger: str = "manual", run_id: str | None = None) -> str:if self._shutting_down.is_set():raise RunError("the server is restarting: start the run again in a minute", "SHUTTING_DOWN", 503)rid, state = create_run_record(self.svc, inputs, actor, trigger, orchestrator="langgraph", run_id=run_id)self._enqueue("start", rid, state)return riddef answer_gate(self, run_id: str, gate: str, answer: dict, actor: str) -> None:run = self._get(run_id)if run["pending_gate"] != gate or run["status"] != GATE_STATUS.get(gate):raise RunError(f"run {run_id} is not waiting at gate {gate} (status {run['status']}, gate {run['pending_gate']})", "NOT_AT_GATE")self.svc.kill.check("gate.answer")# check-and-write in one statement: a double click must not let the second answer resume the NEXT gateif not self.svc.db.claim_run(run_id, GATE_STATUS[gate], gate, status="queued", pending_gate=None):raise RunError(f"run {run_id} is no longer waiting at gate {gate}: this answer was already given", "NOT_AT_GATE")self.svc.db.add_event(run_id, gate, "status", {"status": "queued", "answered_by": actor})self._enqueue("resume", run_id, {**answer, "actor": actor}, gate)def resume(self, run_id: str, actor: str) -> None:run = self._get(run_id)if run["status"] not in ("interrupted", "failed"):raise RunError(f"run {run_id} is {run['status']}; only interrupted/failed runs can be resumed", "NOT_RESUMABLE")self.svc.kill.check("run.resume")self.svc.audit.append("run.resumed", actor=actor, run_id=run_id)snap = self.graph.get_state(run_config(run_id, self.svc.cfg))intr = self._interrupt(snap)if intr is not None:self._pause(run_id, intr)returnself.svc.db.update_run(run_id, status="queued", error=None)self._enqueue("continue", run_id, None)def cancel(self, run_id: str, actor: str, reason: str = "") -> None:run = self._get(run_id)if run["status"] in TERMINAL:raise RunError(f"run {run_id} is already {run['status']}", "ALREADY_FINISHED")self._cancel.add(run_id)if self.current == run_id:procs.kill_all(f"playwright:{run_id}")self.svc.db.update_run(run_id, status="cancelled", pending_gate=None, error=reason or None)self.svc.db.add_event(run_id, None, "status", {"status": "cancelled", "by": actor, "reason": reason})self.svc.audit.append("run.cancelled", actor=actor, run_id=run_id, summary=reason)end_sign_in(self.svc, run_id, self.sign_in)from ..platform.statesync import save_soonsave_soon("run cancelled")if self.current != run_id: # a running one is swept by the worker once Playwright is gonethreading.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 itrunning): 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_jobrelease_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))return self._interrupt(snap)def state(self, run_id: str) -> dict:vals = dict(self.graph.get_state(run_config(run_id, self.svc.cfg)).values or {})if not vals: # an old finished run whose step checkpoints were pruned: its final state was kept in the run folderfrom ..platform.retention import final_statevals = final_state(self.svc.cfg.runs_dir / run_id) or {}return valsdef kill_active(self) -> None:if self.current:procs.kill_all(f"playwright:{self.current}")# ------------------------------------------------------------ workerdef _get(self, run_id: str) -> dict:r = self.svc.db.get_run(run_id)if not r:raise RunError(f"run {run_id} not found", "NOT_FOUND", 404)return r@staticmethoddef _interrupt(snap) -> dict | None:for t in snap.tasks or ():for i in t.interrupts or ():return i.valuereturn Nonedef _pause(self, run_id: str, payload: dict) -> None:gate = payload.get("gate")st = GATE_STATUS.get(gate, "waiting_approval")self.svc.db.update_run(run_id, status=st, pending_gate=gate)self.svc.db.add_event(run_id, gate, "status", {"status": st, "gate": gate})self._notify(run_id, st)def _notify(self, run_id: str, status: str) -> None:from ..platform.statesync import save_soonsave_soon(f"run {status}") # a run that waits for a person or has ended must survive a restartfor fn in list(self.listeners):try:fn(run_id, status)except Exception: # noqa: BLE001log.exception("listener failed")def _loop(self) -> None:while not self._stop.is_set():job = self.q.get()if job is None or self._stop.is_set(): # stopping: the job stays in run_jobs and runs after the restartcontinuetry:self._execute(*job)except Exception: # noqa: BLE001log.exception("run job crashed")def _execute(self, kind: str, run_id: str, payload, gate: str | None = None, job_id: int | None = None) -> None:try:self._work(kind, run_id, payload, gate)finally:r = self.svc.db.get_run(run_id)if r and r["status"] in TERMINAL:end_sign_in(self.svc, run_id, self.sign_in)sweep_test_data(self.svc, run_id, r["status"])if job_id is not None:self.svc.db.x("UPDATE run_jobs SET done_at=? WHERE id=?", (now_iso(), job_id))def _continue_after_restart(self, run_id: str) -> None:"""The app is shutting down between two steps of this run: queue it with a 'continue' job (kept in run_jobs, sorecover() picks it up at the next start) and let the last save hold it that way."""self.svc.db.update_run(run_id, status="queued")self.svc.db.insert("run_jobs", {"run_id": run_id, "kind": "continue", "gate": None, "payload": "null", "created_at": now_iso()})self.svc.db.add_event(run_id, None, "status", {"status": "queued", "reason": "the server is restarting; the run continues after the restart"})self.svc.audit.append("run.paused_for_restart", actor="system", run_id=run_id, summary="stopped between steps for a restart")log.info("run %s stopped between steps for the restart; it continues after it", run_id)def _work(self, kind: str, run_id: str, payload, gate: str | None = None) -> None:run = self.svc.db.get_run(run_id)if not run or run["status"] == "cancelled" or run_id in self._cancel:returncfg = run_config(run_id, self.svc.cfg)if kind == "resume":# a gate answer only resumes the gate it was given for; never a later pause of the same runintr = self._interrupt(self.graph.get_state(cfg))if intr is None or intr.get("gate") != gate:log.warning("run %s: answer for gate %s dropped, the run is at %s", run_id, gate, intr and intr.get("gate"))self.svc.db.add_event(run_id, gate, "gate_answer_dropped", {"gate": gate, "now_at": intr and intr.get("gate")})if intr is not None:self._pause(run_id, intr)returnpayload = Command(resume=payload)self.current = run_idself.svc.db.update_run(run_id, status="running")self.svc.db.add_event(run_id, None, "status", {"status": "running"})try:if self.svc.kill.engaged():raise KillSwitchEngaged("kill switch engaged before start")inp = payload if kind in ("start", "resume") else Nonefor _upd in self.graph.stream(inp, cfg, stream_mode="updates"):if run_id in self._cancel:returnif self.svc.kill.engaged():raise KillSwitchEngaged("kill switch engaged between steps")if self._shutting_down.is_set():self._continue_after_restart(run_id)returnsnap = self.graph.get_state(cfg)intr = self._interrupt(snap)if intr is not None:self._pause(run_id, intr)returnv = snap.valuesself.svc.db.update_run(run_id, status="completed", current_node=None, pending_gate=None,decisions=v.get("decisions") or {}, decision=v.get("decision"), counts=v.get("counts") or {},patch_id=v.get("patch_id"))self.svc.db.add_event(run_id, None, "status", {"status": "completed", "decisions": v.get("decisions")})self.svc.audit.append("run.completed", actor="system", run_id=run_id,summary=json.dumps(v.get("decisions")), payload={"decisions": v.get("decisions"), "counts": v.get("counts")})record_anchor(self.svc, run_id, "completed")self._notify(run_id, "completed")except KillSwitchEngaged as e:self.svc.db.update_run(run_id, status="killed", error=str(e), pending_gate=None)self.svc.db.add_event(run_id, None, "status", {"status": "killed", "error": str(e)})self._notify(run_id, "killed")except (FatalNodeError, GraphRecursionError, Exception) as e: # noqa: BLE001if run_id in self._cancel:returnraw = f"{type(e).__name__}: {e}"code, msg = plain_failure(e) # people see a sentence; the raw text stays in the audit log and the server logself.svc.db.update_run(run_id, status="failed", error=msg[:2000], pending_gate=None)self.svc.db.add_event(run_id, None, "status", {"status": "failed", "error": msg[:2000], "code": code,"fatal": isinstance(e, FatalNodeError)})self.svc.audit.append("run.failed", actor="system", run_id=run_id, summary=msg[:300], payload={"code": code, "raw": raw[:2000]})self._notify(run_id, "failed")log.warning("run %s failed: %s", run_id, raw)finally:self.current = Noneself._cancel.discard(run_id)
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395"""Request/response models (OpenAPI source for the typed web client: web/src/api/schema.d.ts)."""from __future__ import annotationsfrom typing import Any, Generic, Literal, TypeVarfrom pydantic import BaseModel, ConfigDict, FieldT = TypeVar("T")class Strict(BaseModel):model_config = ConfigDict(extra="forbid")class Page(BaseModel, Generic[T]):items: list[T]total: intlimit: intoffset: intclass ErrorOut(BaseModel):detail: strcode: strrequest_id: str | None = None# ---------------------------------------------------------------- auth / usersclass LoginIn(Strict):username: str = Field(min_length=1, max_length=254) # a user name, or an e-mail addresspassword: str = Field(min_length=1, max_length=256)remember: bool = False # keep me signed in: a cookie that survives closing the browser, for up to 7 daysclass ForgotIn(Strict):email: str = Field(min_length=5, max_length=254)class FeatureIn(Strict):on: boolclass PasswordChangeIn(Strict):current_password: str = Field(min_length=1, max_length=256)new_password: str = Field(min_length=12, max_length=256)class SessionRow(BaseModel):id: str # a short fingerprint of the session, never the token itselfkind: str # cookie (browser) or bearer (API token)created_at: strexpires_at: strcurrent: boolclass ResetIn(Strict):access_token: str = Field(min_length=20, max_length=4096)password: str = Field(min_length=10, max_length=256)class RegisterIn(Strict):email: str = Field(min_length=5, max_length=254)password: str = Field(min_length=10, max_length=256)class UserOut(BaseModel):id: intusername: strrole: Literal["viewer", "consultant", "qa_approver", "admin"]via: str | None = Nonepermissions: list[str] = []class LoginOut(BaseModel):user: UserOutcsrf_token: strclass TokenOut(BaseModel):access_token: strtoken_type: Literal["bearer"] = "bearer"expires_in: intuser: UserOutclass UserRow(BaseModel):id: intusername: strrole: strdisabled: boolcreated_at: strcreated_by: str | None = Nonelast_login_at: str | None = Noneclass UserCreate(Strict):username: str = Field(min_length=2, max_length=64, pattern=r"^[A-Za-z0-9._-]+$")password: str = Field(min_length=12, max_length=256)role: Literal["viewer", "consultant", "qa_approver", "admin"]class UserUpdate(Strict):role: Literal["viewer", "consultant", "qa_approver", "admin"] | None = Nonedisabled: bool | None = Nonepassword: str | None = Field(default=None, min_length=12, max_length=256)# ---------------------------------------------------------------- runsclass StubKnobs(Strict):STUB_FAIL: str | None = NoneSTUB_DEFECT: str | None = NoneSTUB_UI: str | None = NoneSTUB_FLAKY: str | None = Noneclass RunCreate(Strict):patch_id: str | None = Field(default=None, max_length=40)modules: list[str] = Field(default_factory=list)include_p2: bool = False# how much of the script library a run re-tests: "smoke" = Critical only; "standard" = Critical, plus High where the# patch touches it (or every High with include_p2); "full" = every scenario of the areas, all prioritiesdepth: Literal["smoke", "standard", "full"] | None = Noneplaywright_mode: Literal["live", "stub"] = "live"stub_knobs: StubKnobs | None = Nonecase_ids: list[str] = Field(default_factory=list, max_length=500)pod_id: int | None = Nonelive_view: bool | None = None # "Watch the test"; default: on for full browser runs (ignored for quick simulations)class PodIn(Strict):name: str = Field(min_length=2, max_length=60)kind: Literal["mock", "fusion"] = "fusion"base_url: str = Field(min_length=8, max_length=300)environment: Literal["test", "uat", "dev", "sit"] = "test"modules: list[str] = Field(default_factory=list)notes: str | None = Field(default=None, max_length=500)class PodUpdate(Strict):name: str | None = Field(default=None, min_length=2, max_length=60)kind: Literal["mock", "fusion"] | None = Nonebase_url: str | None = Field(default=None, min_length=8, max_length=300)environment: Literal["test", "uat", "dev", "sit"] | None = Nonemodules: list[str] | None = Nonenotes: str | None = Field(default=None, max_length=500)enabled: bool | None = Nonerelease: str | None = Field(default=None, max_length=3) # the Oracle Fusion release the pod runs, for example 26Cclass PodScreensIn(Strict):areas: list[str] = Field(default_factory=list, max_length=20) # empty = the areas discovery found in usemax_tasks: int | None = Field(default=None, ge=1, le=12) # screens read per area (default: the server setting)class PodTestDataIn(Strict):overrides: dict[str, dict[str, str | None]] = Field(default_factory=dict) # {"AP": {"supplier": "..."}}; empty removesclass PodCredentialIn(Strict):module: str = Field(min_length=2, max_length=10)username: str = Field(min_length=1, max_length=120)password: str = Field(min_length=1, max_length=300)class PodCredentialRow(BaseModel):module: strset_by: strset_at: strclass PodRow(BaseModel):id: intname: strkind: strbase_url: strenvironment: strmodules: list[str]from_server_settings: bool = False # defined by FPT_FUSION_BASE_URL: re-created at every start, cannot be deleted in the appnotes: str | None = Noneenabled: boolis_default: boolrelease: str | None = Nonediscovery: dict | None = None # {"areas": [{code, name, status, counts, processes, detail?}]} (platform/discovery.py)discovered_at: str | None = Nonerun_areas: list[str] = Field(default_factory=list)screens: dict | None = None # {state, started_at, finished_at, progress, error, areas: {code: {work_areas, captured, failed}}} # Fusion: the business areas a run may target on this pod (discovery)test_data: dict[str, dict[str, str]] = Field(default_factory=dict) # per area: the values the test runner usestest_data_overrides: dict[str, dict[str, str]] = Field(default_factory=dict) # per area: values an admin set by handlast_check_at: str | None = Nonelast_check_ok: bool | None = Nonelast_check_detail: str | None = Nonecreated_by: str | None = Nonecredentials: list[PodCredentialRow]runnable: boolnot_runnable_reason: str | None = Noneclass PodCheck(BaseModel):name: Literal["address", "reachable", "sign_in"]ok: booldetail: strclass PodTestResult(BaseModel):ok: booldetail: strchecks: list[PodCheck] = Field(default_factory=list) # in order; a Fusion test stops at the first failed checkpod: PodRowclass RunCreated(BaseModel):run_id: strstatus: strclass RunSummary(BaseModel):run_id: strpod_id: int | None = Nonepod_name: str | None = Nonecreated_at: strcreated_by: str | None = Nonetrigger: strpatch_id: str | None = Nonemodules: list[str]playwright_mode: strstatus: strcurrent_node: str | None = Nonepending_gate: str | None = Nonedecisions: dict[str, str] = {}decision: str | None = Noneorchestrator: str = "langgraph"attention: str | None = Nonecounts: dict[str, int] = {} # finished runs: passed, failed, skipped, flaky, total (all business areas together)class LeftTestData(BaseModel):number: strtest: str | None = Nonewhy: str | None = Noneclass TestDataCleanup(BaseModel):created: int = 0 # test invoices the run registered before saving themcleaned: int = 0 # of those, cancelled (or found not saved / already cancelled)left: list[LeftTestData] = [] # may still be on the Fusion pod: cancel these by handsummary: str | None = None # the clean-up sweep's sentence after a cancelled / failed / interrupted runswept_at: str | None = Noneclass RunDetail(RunSummary):include_p2: bool = Falselive_view: bool = Falsecounts: dict = {}report_paths: dict = {}errors: list = []error: str | None = Noneretry_count: int = 0llm_calls_count: int = 0llm_calls: list = []target: str = "Mock app, not Oracle Fusion"test_data: TestDataCleanup | None = None # Fusion runs only: test invoices created, cleaned up, and left on the podclass RunEvent(BaseModel):seq: intts: strnode: str | None = Nonekind: strsummary: dict = {}class CancelIn(Strict):reason: str = Field(default="", max_length=500)class ApproveCasesIn(Strict):approved: list[str] = Field(default_factory=list)rejected: list[str] = Field(default_factory=list)comments: dict[str, str] = Field(default_factory=dict)class ReviewAnswer(Strict):confirmed: Literal["real_defect", "not_defect"] | None = Nonewaiver: str | None = Field(default=None, max_length=500)owner: str | None = Field(default=None, max_length=100)note: str | None = Field(default=None, max_length=1000)class HumanReviewIn(Strict):review: dict[str, ReviewAnswer]class StatusOut(BaseModel):status: strcommit_sha: str | None = Noneclass DecisionIn(Strict):decision: Literal["approve", "reject"]note: str | None = Field(default=None, max_length=1000)class SignOffIn(Strict):comment: str | None = Field(default=None, max_length=1000)class RunNoteIn(Strict):text: str = Field(min_length=1, max_length=2000)class NoteIn(Strict):note: str | None = Field(default=None, max_length=1000)class AutonomyIn(Strict):level: Literal["L0", "L1", "L2"]class KillIn(Strict):engaged: boolreason: str = Field(default="", max_length=500)class ScheduleIn(Strict):kind: Literal["interval", "daily", "monthly", "quarterly"]every_minutes: int | None = Field(default=None, ge=1, le=7 * 24 * 60)at: str | None = Field(default=None, pattern=r"^\d{2}:\d{2}$")day: int | None = Field(default=None, ge=1, le=28) # monthly / quarterly: day of the month (UTC)month: int | None = Field(default=None, ge=1, le=12) # quarterly: the first month of the cycle (runs again every third month)pod_id: int | None = None # the test environment to run on (default: the server's default pod)patch_id: str | None = Field(default=None, max_length=40) # the patch name to record, e.g. 26C or 2026-10modules: list[str] = Field(default_factory=list)include_p2: bool = Falseplaywright_mode: Literal["live", "stub"] = "live"enabled: bool = Truetimezone: str | None = Field(default=None, max_length=64) # IANA name, e.g. Asia/Kolkata; default FPT_TZ (Asia/Kolkata)class ScheduleUpdate(Strict):"""PATCH /api/schedules/{id}: only the fields given change. enabled=false pauses it, true turns it on again."""kind: Literal["interval", "daily", "monthly", "quarterly"] | None = Noneevery_minutes: int | None = Field(default=None, ge=1, le=7 * 24 * 60)at: str | None = Field(default=None, pattern=r"^\d{2}:\d{2}$")day: int | None = Field(default=None, ge=1, le=28)month: int | None = Field(default=None, ge=1, le=12)pod_id: int | None = Nonepatch_id: str | None = Field(default=None, max_length=40)modules: list[str] | None = Noneinclude_p2: bool | None = Noneplaywright_mode: Literal["live", "stub"] | None = Noneenabled: bool | None = Nonetimezone: str | None = Field(default=None, max_length=64)class ScheduleRow(BaseModel):id: intkind: strevery_minutes: int | None = Noneat: str | None = Noneday: int | None = Nonemonth: int | None = Nonepod_id: int | None = Nonepatch_id: str | None = Nonemodules: list[str] = []include_p2: bool = Falseplaywright_mode: strenabled: booltimezone: str # IANA name the clock time (at) is read in; UTC for schedules made before time zonesnext_run_at: str | None = None # UTC ISO time of the next startcreated_by: str | None = Nonecreated_at: strlast_attempt_at: str | None = None # when it last tried to start a run (UTC)last_run_id: str | None = None # the run it last startedlast_error: str | None = None # why the last start failed, in plain words (empty after a good start)fail_count: int = 0 # failed starts in a row; at 3 the schedule turns itself offclass PatchWatchIn(Strict):enabled: bool | None = Noneinterval_s: int | None = Field(default=None, ge=30, le=86400)autostart: bool | None = Nonemodules: list[str] | None = Noneclass Health(BaseModel):status: strmock_up: boolollama_up: boolfrontier_configured: boolkill_engaged: boolversion: strtarget: strAnyDict = dict[str, Any]123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470"""Request/response models (OpenAPI source for the typed web client: web/src/api/schema.d.ts)."""from __future__ import annotationsfrom typing import Any, Generic, Literal, TypeVarfrom pydantic import BaseModel, ConfigDict, FieldT = TypeVar("T")class Strict(BaseModel):model_config = ConfigDict(extra="forbid")class Page(BaseModel, Generic[T]):items: list[T]total: intlimit: intoffset: intclass ErrorOut(BaseModel):detail: strcode: strrequest_id: str | None = None# ---------------------------------------------------------------- auth / usersclass LoginIn(Strict):username: str = Field(min_length=1, max_length=254) # a user name, or an e-mail addresspassword: str = Field(min_length=1, max_length=256)remember: bool = False # keep me signed in: a cookie that survives closing the browser, for up to 7 daysclass ForgotIn(Strict):email: str = Field(min_length=5, max_length=254)class FeatureIn(Strict):on: boolclass PasswordChangeIn(Strict):current_password: str = Field(min_length=1, max_length=256)new_password: str = Field(min_length=12, max_length=256)class SessionRow(BaseModel):id: str # a short fingerprint of the session, never the token itselfkind: str # cookie (browser) or bearer (API token)created_at: strexpires_at: strcurrent: boolclass ResetIn(Strict):access_token: str = Field(min_length=20, max_length=4096)password: str = Field(min_length=10, max_length=256)class RegisterIn(Strict):email: str = Field(min_length=5, max_length=254)password: str = Field(min_length=10, max_length=256)class UserOut(BaseModel):id: intusername: strrole: Literal["viewer", "consultant", "qa_approver", "admin"]via: str | None = Nonepermissions: list[str] = []class LoginOut(BaseModel):user: UserOutcsrf_token: strclass TokenOut(BaseModel):access_token: strtoken_type: Literal["bearer"] = "bearer"expires_in: intuser: UserOutclass UserRow(BaseModel):id: intusername: strrole: strdisabled: boolcreated_at: strcreated_by: str | None = Nonelast_login_at: str | None = Noneclass UserCreate(Strict):username: str = Field(min_length=2, max_length=64, pattern=r"^[A-Za-z0-9._-]+$")password: str = Field(min_length=12, max_length=256)role: Literal["viewer", "consultant", "qa_approver", "admin"]class UserUpdate(Strict):role: Literal["viewer", "consultant", "qa_approver", "admin"] | None = Nonedisabled: bool | None = Nonepassword: str | None = Field(default=None, min_length=12, max_length=256)# ---------------------------------------------------------------- runsclass StubKnobs(Strict):STUB_FAIL: str | None = NoneSTUB_DEFECT: str | None = NoneSTUB_UI: str | None = NoneSTUB_FLAKY: str | None = Noneclass RunCreate(Strict):patch_id: str | None = Field(default=None, max_length=40)modules: list[str] = Field(default_factory=list)include_p2: bool = False# how much of the script library a run re-tests: "smoke" = Critical only; "standard" = Critical, plus High where the# patch touches it (or every High with include_p2); "full" = every scenario of the areas, all prioritiesdepth: Literal["smoke", "standard", "full"] | None = Noneplaywright_mode: Literal["live", "stub"] = "live"stub_knobs: StubKnobs | None = Nonecase_ids: list[str] = Field(default_factory=list, max_length=500)pod_id: int | None = Nonelive_view: bool | None = None # "Watch the test"; default: on for full browser runs (ignored for quick simulations)class PodIn(Strict):name: str = Field(min_length=2, max_length=60)kind: Literal["mock", "fusion"] = "fusion"base_url: str = Field(min_length=8, max_length=300)environment: Literal["test", "uat", "dev", "sit"] = "test"modules: list[str] = Field(default_factory=list)notes: str | None = Field(default=None, max_length=500)# "assisted": the pod sends every sign-in through the company's identity provider (with MFA), so a person signs in at# the start of each run and no test user password is stored (platform/assisted_signin.py)sign_in_mode: Literal["password", "assisted"] = "password"class PodUpdate(Strict):name: str | None = Field(default=None, min_length=2, max_length=60)kind: Literal["mock", "fusion"] | None = Nonebase_url: str | None = Field(default=None, min_length=8, max_length=300)environment: Literal["test", "uat", "dev", "sit"] | None = Nonemodules: list[str] | None = Nonenotes: str | None = Field(default=None, max_length=500)enabled: bool | None = Nonerelease: str | None = Field(default=None, max_length=3) # the Oracle Fusion release the pod runs, for example 26Csign_in_mode: Literal["password", "assisted"] | None = Noneclass PodScreensIn(Strict):areas: list[str] = Field(default_factory=list, max_length=20) # empty = the areas discovery found in usemax_tasks: int | None = Field(default=None, ge=1, le=12) # screens read per area (default: the server setting)class PodUsageIn(Strict):days: int = Field(default=90, ge=7, le=365) # the read window: records created in the last `days` daysclass PodUsage(BaseModel):"""How the client uses each business area of the pod (platform/usage.py). Category values are the client's own."""pod_id: intread_at: str | None = None # None: not read yetdays: int | None = Nonesince: str | None = Noneareas: list[dict] = Field(default_factory=list) # [{code, name, status, detail?, resources: [...], dimensions: [...]}]class PodCoverage(BaseModel):"""The used variants against the scenario library, weighted by volume (platform/usage.py coverage)."""pod_id: intread_at: str | None = Nonescenarios: int = 0covered_share: float | None = None # share of the read volume whose variant a Fusion scenario coversareas: list[dict] = Field(default_factory=list)variants: list[dict] = Field(default_factory=list) # [{area, dimension, label, value, share, volume, status, matches}]gaps: list[dict] = Field(default_factory=list) # variants not covered, most volume firstclass PodTestDataIn(Strict):overrides: dict[str, dict[str, str | None]] = Field(default_factory=dict) # {"AP": {"supplier": "..."}}; empty removesclass PodCredentialIn(Strict):module: str = Field(min_length=2, max_length=10)username: str = Field(min_length=1, max_length=120)password: str = Field(min_length=1, max_length=300)class PodCredentialRow(BaseModel):module: strset_by: strset_at: strclass PodRow(BaseModel):id: intname: strkind: strbase_url: strenvironment: strmodules: list[str]from_server_settings: bool = False # defined by FPT_FUSION_BASE_URL: re-created at every start, cannot be deleted in the appnotes: str | None = Noneenabled: boolis_default: boolrelease: str | None = Nonesign_in_mode: Literal["password", "assisted"] = "password" # assisted: a person signs in at the start of each rundiscovery: dict | None = None # {"areas": [{code, name, status, counts, processes, detail?}]} (platform/discovery.py)discovered_at: str | None = Noneusage_read_at: str | None = None # when the usage profile was read (GET /pods/{id}/usage)run_areas: list[str] = Field(default_factory=list)screens: dict | None = None # {state, started_at, finished_at, progress, error, areas: {code: {work_areas, captured, failed}}} # Fusion: the business areas a run may target on this pod (discovery)test_data: dict[str, dict[str, str]] = Field(default_factory=dict) # per area: the values the test runner usestest_data_overrides: dict[str, dict[str, str]] = Field(default_factory=dict) # per area: values an admin set by handlast_check_at: str | None = Nonelast_check_ok: bool | None = Nonelast_check_detail: str | None = Nonecreated_by: str | None = Nonecredentials: list[PodCredentialRow]runnable: boolnot_runnable_reason: str | None = Noneclass PodCheck(BaseModel):name: Literal["address", "reachable", "sign_in"]ok: booldetail: strclass PodTestResult(BaseModel):ok: booldetail: strchecks: list[PodCheck] = Field(default_factory=list) # in order; a Fusion test stops at the first failed checkpod: PodRowclass RunCreated(BaseModel):run_id: strstatus: strclass RunSummary(BaseModel):run_id: strpod_id: int | None = Nonepod_name: str | None = Nonecreated_at: strcreated_by: str | None = Nonetrigger: strpatch_id: str | None = Nonemodules: list[str]playwright_mode: strstatus: strcurrent_node: str | None = Nonepending_gate: str | None = Nonedecisions: dict[str, str] = {}decision: str | None = Noneorchestrator: str = "langgraph"attention: str | None = Nonecounts: dict[str, int] = {} # finished runs: passed, failed, skipped, flaky, total (all business areas together)class LeftTestData(BaseModel):number: strtest: str | None = Nonewhy: str | None = Noneclass TestDataCleanup(BaseModel):created: int = 0 # test invoices the run registered before saving themcleaned: int = 0 # of those, cancelled (or found not saved / already cancelled)left: list[LeftTestData] = [] # may still be on the Fusion pod: cancel these by handsummary: str | None = None # the clean-up sweep's sentence after a cancelled / failed / interrupted runswept_at: str | None = Noneclass RunDetail(RunSummary):include_p2: bool = Falselive_view: bool = Falsecounts: dict = {}report_paths: dict = {}errors: list = []error: str | None = Noneretry_count: int = 0llm_calls_count: int = 0llm_calls: list = []target: str = "Mock app, not Oracle Fusion"test_data: TestDataCleanup | None = None # Fusion runs only: test invoices created, cleaned up, and left on the podclass RunEvent(BaseModel):seq: intts: strnode: str | None = Nonekind: strsummary: dict = {}class CancelIn(Strict):reason: str = Field(default="", max_length=500)class ApproveCasesIn(Strict):approved: list[str] = Field(default_factory=list)rejected: list[str] = Field(default_factory=list)comments: dict[str, str] = Field(default_factory=dict)class ReviewAnswer(Strict):confirmed: Literal["real_defect", "not_defect"] | None = Nonewaiver: str | None = Field(default=None, max_length=500)owner: str | None = Field(default=None, max_length=100)note: str | None = Field(default=None, max_length=1000)class HumanReviewIn(Strict):review: dict[str, ReviewAnswer]class StatusOut(BaseModel):status: strcommit_sha: str | None = None# ---------------------------------------------------------------- assisted sign-in (platform/assisted_signin.py)class SignInEvent(Strict):"""One thing the person did in the sign-in browser: a click (in the browser's 1280x800 pixels), text, a key, a scroll."""type: Literal["click", "type", "press", "scroll"]x: float | None = Field(default=None, ge=0, le=1280)y: float | None = Field(default=None, ge=0, le=800)text: str | None = Field(default=None, min_length=1, max_length=500)key: str | None = Field(default=None, max_length=40)dy: float | None = Field(default=None, ge=-2000, le=2000)class SignInInputIn(Strict):session_id: str = Field(min_length=10, max_length=80)events: list[SignInEvent] = Field(min_length=1, max_length=50)class SignInSessionIn(Strict):session_id: str = Field(min_length=10, max_length=80)class SignInGate(BaseModel):pod: str | None = Nonebase_url: str | None = Nonereason: Literal["start", "expired"] = "start" # expired: the session ended mid-run; `remaining` scenarios wait for itremaining: int | None = Noneclass SignInStatusOut(BaseModel):waiting: bool # the run waits at the sign_in gategate: SignInGate | None = Noneactive: bool = False # a sign-in browser is open for this runstate: str | None = None # starting | open | signed_in | cancelled | expired | failed | closedowner: str | None = None # who opened it (only they may use it)mine: bool = Falsepage: str | None = None # pod | identity provider | blank (never the address)error: str | None = Noneidle_left_s: int | None = None # it closes after this many seconds without inputstarted_at: str | None = Nonesession_id: str | None = None # given only to its owner, when the session is openedclass SignInAccepted(BaseModel):accepted: intclass DecisionIn(Strict):decision: Literal["approve", "reject"]note: str | None = Field(default=None, max_length=1000)class SignOffIn(Strict):comment: str | None = Field(default=None, max_length=1000)class RunNoteIn(Strict):text: str = Field(min_length=1, max_length=2000)class NoteIn(Strict):note: str | None = Field(default=None, max_length=1000)class AutonomyIn(Strict):level: Literal["L0", "L1", "L2"]class KillIn(Strict):engaged: boolreason: str = Field(default="", max_length=500)class ScheduleIn(Strict):kind: Literal["interval", "daily", "monthly", "quarterly"]every_minutes: int | None = Field(default=None, ge=1, le=7 * 24 * 60)at: str | None = Field(default=None, pattern=r"^\d{2}:\d{2}$")day: int | None = Field(default=None, ge=1, le=28) # monthly / quarterly: day of the month (UTC)month: int | None = Field(default=None, ge=1, le=12) # quarterly: the first month of the cycle (runs again every third month)pod_id: int | None = None # the test environment to run on (default: the server's default pod)patch_id: str | None = Field(default=None, max_length=40) # the patch name to record, e.g. 26C or 2026-10modules: list[str] = Field(default_factory=list)include_p2: bool = Falseplaywright_mode: Literal["live", "stub"] = "live"enabled: bool = Truetimezone: str | None = Field(default=None, max_length=64) # IANA name, e.g. Asia/Kolkata; default FPT_TZ (Asia/Kolkata)class ScheduleUpdate(Strict):"""PATCH /api/schedules/{id}: only the fields given change. enabled=false pauses it, true turns it on again."""kind: Literal["interval", "daily", "monthly", "quarterly"] | None = Noneevery_minutes: int | None = Field(default=None, ge=1, le=7 * 24 * 60)at: str | None = Field(default=None, pattern=r"^\d{2}:\d{2}$")day: int | None = Field(default=None, ge=1, le=28)month: int | None = Field(default=None, ge=1, le=12)pod_id: int | None = Nonepatch_id: str | None = Field(default=None, max_length=40)modules: list[str] | None = Noneinclude_p2: bool | None = Noneplaywright_mode: Literal["live", "stub"] | None = Noneenabled: bool | None = Nonetimezone: str | None = Field(default=None, max_length=64)class ScheduleRow(BaseModel):id: intkind: strevery_minutes: int | None = Noneat: str | None = Noneday: int | None = Nonemonth: int | None = Nonepod_id: int | None = Nonepatch_id: str | None = Nonemodules: list[str] = []include_p2: bool = Falseplaywright_mode: strenabled: booltimezone: str # IANA name the clock time (at) is read in; UTC for schedules made before time zonesnext_run_at: str | None = None # UTC ISO time of the next startcreated_by: str | None = Nonecreated_at: strlast_attempt_at: str | None = None # when it last tried to start a run (UTC)last_run_id: str | None = None # the run it last startedlast_error: str | None = None # why the last start failed, in plain words (empty after a good start)fail_count: int = 0 # failed starts in a row; at 3 the schedule turns itself offclass PatchWatchIn(Strict):enabled: bool | None = Noneinterval_s: int | None = Field(default=None, ge=30, le=86400)autostart: bool | None = Nonemodules: list[str] | None = Noneclass Health(BaseModel):status: strmock_up: boolollama_up: boolfrontier_configured: boolkill_engaged: boolversion: strtarget: strAnyDict = dict[str, Any]
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396"""Two-way chat channels: the conversation core, the same for every channel (Telegram now, Microsoft Teams next).A channel adapter turns its platform's messages into `Inbound` and sends `OutMessage` back; everything else lives here:- Linking: a person links a chat to their Astra account with a one-time code made in the app (Account > Telegram).Only the code's hash is stored; it works once, for 10 minutes. From then on the bot acts as that user, with that user'srole: the same RBAC as the screens. An unlinked chat only gets help and "/link CODE".- Talking: any free text goes to the Ask service (coworker/chat/service.py) exactly as the Ask page does, as that user:one tool per message, read tools answer, action tools only propose. A proposal becomes two buttons, [Start test run][Cancel] (or the proposal's own verb), and nothing runs until the person presses it.- Buttons never carry what they do: the button holds a short random id; the action is stored server-side with the chat,the user, an expiry (24 h) and its group (pressing one button closes the others), so a button can't be forged,replayed, used in another chat or by another person.- Never in a chat: sign-off and failure verdicts (the bot links to the screens instead), the kill switch, administration.- Every action is audited as channel.<action>, with the linked user as the actor and the channel's name."""from __future__ import annotationsimport hashlibimport jsonimport secretsimport threadingimport timefrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom typing import Protocolfrom ..platform.rundb import now_isoCODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # no 0/O, 1/I: easy to type from a phoneCODE_LEN = 6CODE_TTL = timedelta(minutes=10)CALLBACK_TTL = timedelta(hours=24)LINK_TRIES = 5 # wrong codes per person per 10 minutes_tries_lock = threading.Lock()_tries: dict[str, list[float]] = {}@dataclassclass Button:label: strcallback: str | None = None # an opaque id from channel_callbacksurl: str | None = None # an absolute https link@dataclassclass OutMessage:text: str # plain text: the adapter escapes it for its platformbuttons: list[list[Button]] = field(default_factory=list)html: bool = False # the text is Telegram HTML already (a notification laid out by notify.telegram_text)@dataclassclass Inbound:channel: strexternal_user_id: strchat_id: strtext: str | None = Nonecallback_data: str | None = Nonecallback_id: str | None = None # the platform's id of the button press (to acknowledge it)username: str | None = Noneprivate: bool = Trueclass Adapter(Protocol):channel: strdef send(self, chat_id: str, msg: OutMessage) -> str | None: ...def answer_callback(self, callback_id: str, text: str | None = None) -> None: ...def _hash(code: str) -> str:return hashlib.sha256(code.strip().upper().encode("utf-8")).hexdigest()def _utc(ts: str) -> datetime:d = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))return d if d.tzinfo else d.replace(tzinfo=timezone.utc)def _later(delta: timedelta) -> str:return (datetime.now(timezone.utc) + delta).isoformat(timespec="seconds")def absolute(svc, path: str | None) -> str | None:"""A screen path as a link a chat can open: only an absolute https address (platforms refuse anything else)."""if not path:return Noneif path.startswith("https://"):return pathbase = (svc.cfg.public_url or "").rstrip("/")return f"{base}{path if path.startswith('/') else '/' + path}" if base.startswith("https://") else None# ------------------------------------------------------------ links (app side)def new_link_code(svc, user_id: int, channel: str) -> dict:"""A one-time code the person sends to the bot as "/link CODE". Only its hash is kept; it works once, for 10 minutes."""code = "".join(secrets.choice(CODE_ALPHABET) for _ in range(CODE_LEN))svc.db.insert("channel_link_codes", {"code_hash": _hash(code), "user_id": user_id, "channel": channel,"created_at": now_iso(), "expires_at": _later(CODE_TTL)})return {"code": code, "expires_at": _later(CODE_TTL)}def link_of_user(svc, user_id: int, channel: str) -> dict | None:return svc.db.one("SELECT * FROM channel_links WHERE user_id=? AND channel=? ORDER BY id DESC LIMIT 1", (user_id, channel))def unlink_user(svc, user_id: int, channel: str) -> int:return svc.db.x("DELETE FROM channel_links WHERE user_id=? AND channel=?", (user_id, channel))def linked_chats(svc, channel: str) -> list[dict]:return svc.db.q("SELECT * FROM channel_links WHERE channel=? ORDER BY id", (channel,))# ------------------------------------------------------------ the conversationclass Conversation:"""Handles one inbound message or button press and returns what to send back (the adapter sends it)."""def __init__(self, svc, runs):self.svc, self.runs, self.db = svc, runs, svc.db# -- who is talkingdef _link(self, inb: Inbound) -> dict | None:return self.db.one("SELECT * FROM channel_links WHERE channel=? AND external_user_id=?", (inb.channel, inb.external_user_id))def _principal(self, link: dict):from ..api.auth import Principalu = self.svc.users.get(int(link["user_id"]))if not u or u.get("disabled"):return Nonereturn Principal(u["id"], u["username"], u["role"], link["channel"])def _audit(self, kind: str, inb: Inbound, user=None, run_id: str | None = None, summary: str = "", **payload) -> None:self.svc.audit.append(f"channel.{kind}", actor=getattr(user, "username", None) or f"{inb.channel}:{inb.external_user_id}",run_id=run_id, summary=summary or kind, payload={"channel": inb.channel, **payload})# -- entry pointdef handle(self, inb: Inbound) -> list[OutMessage]:link = self._link(inb)if inb.callback_data is not None:if not link:return [OutMessage("This chat is not linked to a Astra account yet. " + LINK_HELP)]user = self._principal(link)if not user:return [OutMessage("This Astra account is switched off. Ask an administrator.")]return self._callback(inb, user, link)text = (inb.text or "").strip()cmd, _, rest = text.partition(" ")cmd = cmd.split("@", 1)[0].lower() # "/help@PatchwiseBot" in groupsif cmd == "/link":return [self._link_chat(inb, rest.strip())]if not link:return [OutMessage(WELCOME + "\n\n" + LINK_HELP)]user = self._principal(link)if not user:return [OutMessage("This Astra account is switched off. Ask an administrator.")]if cmd in ("/start", "/help"):return [OutMessage(HELP.format(name=user.username))]if cmd == "/unlink":self.db.x("DELETE FROM channel_links WHERE id=?", (link["id"],))self._audit("unlinked", inb, user, summary=f"{inb.channel} chat unlinked")return [OutMessage("This chat is no longer linked. You will not get Astra messages here. Link again with /link CODE.")]if cmd == "/status":return [self._status(user, inb)]if cmd == "/run":return self._ask(inb, user, link, _run_words(rest))if not text:return [OutMessage(HELP.format(name=user.username))]return self._ask(inb, user, link, text)# -- linkingdef _link_chat(self, inb: Inbound, code: str) -> OutMessage:if not inb.private:return OutMessage("Link in a private chat with the bot, not in a group.")key = f"{inb.channel}:{inb.external_user_id}"now = time.monotonic()with _tries_lock:recent = [t for t in _tries.get(key, []) if now - t < 600]if len(recent) >= LINK_TRIES:_tries[key] = recentreturn OutMessage("Too many tries. Wait 10 minutes, then make a new code in Astra.")_tries[key] = recent + [now]if not code:return OutMessage(LINK_HELP)row = self.db.one("SELECT * FROM channel_link_codes WHERE code_hash=? AND channel=?", (_hash(code), inb.channel))if not row or row["used_at"] or _utc(row["expires_at"]) <= datetime.now(timezone.utc):self._audit("link.refused", inb, summary="unknown, used or expired link code")return OutMessage("That code is not valid (codes work once, for 10 minutes). Make a new one in Astra: Account > Telegram.")if not self.db.x("UPDATE channel_link_codes SET used_at=? WHERE code_hash=? AND used_at IS NULL", (now_iso(), row["code_hash"])):return OutMessage("That code was just used. Make a new one in Astra.")u = self.svc.users.get(int(row["user_id"]))if not u or u.get("disabled"):return OutMessage("That Astra account is switched off. Ask an administrator.")with self.db.tx() as c:c.execute("DELETE FROM channel_links WHERE channel=? AND (external_user_id=? OR user_id=?)",(inb.channel, inb.external_user_id, u["id"]))c.execute("INSERT INTO channel_links (channel, external_user_id, chat_id, user_id, username, linked_at) VALUES (?,?,?,?,?,?)",(inb.channel, inb.external_user_id, inb.chat_id, u["id"], (inb.username or "")[:80], now_iso()))with _tries_lock:_tries.pop(key, None)self.svc.audit.append("channel.linked", actor=u["username"], summary=f"{inb.channel} chat linked",payload={"channel": inb.channel, "chat": inb.chat_id, "username": inb.username})return OutMessage(f"Linked. This chat now belongs to {u['username']} ({u['role']}). ""I will tell you here when a test run needs you, and you can ask me anything Ask can answer.\n\n"+ HELP_COMMANDS)# -- /statusdef _status(self, user, inb: Inbound) -> OutMessage:from ..chat.tools import STATUS_WORDS, run_nameruns = self.db.list_runs(None, 50)waiting = [r for r in runs if (r.get("pending_gate") == "approve_cases" and user.can("gate.approve_cases"))or (r.get("pending_gate") == "human_review" and user.can("gate.human_review"))]lines = []if waiting:lines.append(f"Waiting for you ({len(waiting)}):")lines += [f"• {run_name(r)}: {STATUS_WORDS.get(r['status'], r['status'])}" for r in waiting[:5]]else:lines.append("Nothing is waiting for you right now.")latest = runs[:3]if latest:lines.append("")lines.append("Latest test runs:")lines += [f"• {run_name(r)}: {STATUS_WORDS.get(r['status'], r['status'])}" for r in latest]buttons = []url = absolute(self.svc, "/runs")if url:buttons = [[Button("Open Test runs", url=url)]]self._audit("status", inb, user)return OutMessage("\n".join(lines), buttons)# -- free text: the Ask service, as this userdef _conversation_id(self, user, link: dict) -> str:from ..chat.service import ChatError, ChatServicechat = ChatService(self.svc, self.runs)cid = link.get("conv_id")if cid:try:chat.conversation(user, cid)return cidexcept ChatError:passcid = chat.create(user, None, None)["id"]self.db.x("UPDATE channel_links SET conv_id=? WHERE id=?", (cid, link["id"]))return ciddef _ask(self, inb: Inbound, user, link: dict, text: str) -> list[OutMessage]:from ..chat.service import ChatError, ChatServicechat = ChatService(self.svc, self.runs)cid = self._conversation_id(user, link)answer, links, sources, action = "", [], [], Nonetry:for ev, data in chat.turn(user, cid, text, {"tz_offset": 0}):if ev == "delta":answer += str(data.get("text") or "")elif ev == "result":links, sources = data.get("links") or [], data.get("sources") or []elif ev == "action":action = dataexcept ChatError as e:return [OutMessage(e.detail if e.code != "RATE_LIMITED" else "Too many questions in a short time. Try again in a minute.")]self._audit("message", inb, user, summary="ask", conversation=cid)if action:grp = secrets.token_hex(6)yes = self._callback_id(inb, user, grp, "chat.confirm", {"action_id": action["action_id"], "tool": action.get("tool")})no = self._callback_id(inb, user, grp, "chat.cancel", {"action_id": action["action_id"]})preview = action.get("preview")body = answer or action.get("title") or "Shall I do this?"if isinstance(preview, str) and preview and preview not in body:body += "\n" + previewbody += "\n\nNothing happens until you press the button."return [OutMessage(body, [[Button(_verb(action), callback=yes), Button("Cancel", callback=no)]])]text_out = answer or "I could not find an answer to that."if sources:text_out += "\n\nSource: " + "; ".join(str(s.get("label")) for s in sources if s.get("label"))row = [Button(str(lk.get("label") or "Open"), url=u) for lk in links[:3] if (u := absolute(self.svc, lk.get("to")))]return [OutMessage(text_out, [row] if row else [])]# -- buttonsdef _callback_id(self, inb: Inbound, user, grp: str, kind: str, payload: dict) -> str:cb = secrets.token_urlsafe(9) # 12 characters: well under Telegram's 64-byte limitself.db.insert("channel_callbacks", {"id": cb, "grp": grp, "channel": inb.channel, "chat_id": inb.chat_id, "user_id": user.id,"kind": kind, "payload_json": json.dumps(payload), "created_at": now_iso(),"expires_at": _later(CALLBACK_TTL)})return cbdef _callback(self, inb: Inbound, user, link: dict) -> list[OutMessage]:row = self.db.one("SELECT * FROM channel_callbacks WHERE id=?", (inb.callback_data,))if not row or row["channel"] != inb.channel or str(row["chat_id"]) != str(inb.chat_id) or int(row["user_id"]) != int(user.id):self._audit("callback.refused", inb, user, summary="unknown button or not this person's")return [OutMessage("This button is not valid here. Ask again.")]if row["used_at"] or _utc(row["expires_at"]) <= datetime.now(timezone.utc):return [OutMessage("This button has expired or was already used. Ask again to get a fresh one.")]if not self.db.x("UPDATE channel_callbacks SET used_at=? WHERE id=? AND used_at IS NULL", (now_iso(), row["id"])):return [OutMessage("This button was already used.")]self.db.x("UPDATE channel_callbacks SET used_at=? WHERE grp=? AND used_at IS NULL", (now_iso(), row["grp"]))payload = json.loads(row["payload_json"])kind = row["kind"]if kind == "chat.confirm":return [self._confirm(inb, user, payload)]if kind == "chat.cancel":return [self._cancel(inb, user, payload)]if kind == "approve.ask":return self._approve_ask(inb, user, link, payload)return [OutMessage("This button is not valid here. Ask again.")]def _confirm(self, inb: Inbound, user, payload: dict) -> OutMessage:from ..api.errors import ApiErrorfrom ..chat.service import ChatError, ChatServicetry:out = ChatService(self.svc, self.runs).confirm_action(user, payload["action_id"])except (ChatError, ApiError) as e:self._audit("action.failed", inb, user, summary=f"{payload.get('tool')}: {e.code}", action=payload["action_id"])return OutMessage(f"That did not work: {e.detail}")res = out.get("result") or {}rid = res.get("run_id")if payload.get("tool") == "start_run" and rid:self.db.x("INSERT OR IGNORE INTO channel_run_origins (run_id, channel, chat_id, user_id, created_at) VALUES (?,?,?,?,?)",(rid, inb.channel, inb.chat_id, user.id, now_iso()))self._audit("action.confirmed", inb, user, run_id=rid, summary=str(payload.get("tool")), action=payload["action_id"])words = {"start_run": "Done: the test run has started. I will tell you here when it needs you.","approve_scenarios": f"Done: {res.get('approved', 'the')} scenarios approved; testing starts now.","cancel_run": "Done: the test run was cancelled.", "add_note": "Done: the note is saved."}.get(str(payload.get("tool")), "Done.")url = absolute(self.svc, res.get("to"))return OutMessage(words, [[Button("Open in Astra", url=url)]] if url else [])def _cancel(self, inb: Inbound, user, payload: dict) -> OutMessage:from ..chat.service import ChatError, ChatServicetry:ChatService(self.svc, self.runs).cancel_action(user, payload["action_id"])except ChatError as e:return OutMessage(e.detail)self._audit("action.cancelled", inb, user, action=payload["action_id"])return OutMessage("Cancelled. Nothing was changed.")def _approve_ask(self, inb: Inbound, user, link: dict, payload: dict) -> list[OutMessage]:"""[Approve all] from a notification: the same proposal the Ask service makes for "approve all", then asecond press on [Yes, approve all] runs it through the same confirm path (RBAC and gate re-checked)."""from ..chat.service import ChatServicefrom ..chat.tools import Toolsif not user.can("gate.approve_cases"):self._audit("approve.refused", inb, user, run_id=payload.get("run_id"), summary="role may not approve scenarios")return [OutMessage(f"Your role ({user.role}) can't approve scenarios. Ask a consultant, or open the review to look.")]res = Tools(self.svc, self.runs, user, 0).approve_scenarios(run_id=payload.get("run_id"))if not res.proposal:return [OutMessage(res.text)]cid = self._conversation_id(user, link)action = ChatService(self.svc, self.runs)._propose(user, cid, res.proposal, payload.get("run_id")) # noqa: SLF001 (same path as Ask)n = len((res.proposal.get("payload") or {}).get("approved") or [])grp = secrets.token_hex(6)yes = self._callback_id(inb, user, grp, "chat.confirm", {"action_id": action["action_id"], "tool": "approve_scenarios"})no = self._callback_id(inb, user, grp, "chat.cancel", {"action_id": action["action_id"]})self._audit("approve.asked", inb, user, run_id=payload.get("run_id"), summary=f"{n} scenarios")return [OutMessage(f"{res.proposal['title']}\nApprove all {n} scenarios? Nothing is tested until you do.",[[Button("Yes, approve all", callback=yes), Button("Cancel", callback=no)]])]def notification_buttons(conv: Conversation, chat: Inbound, user, event: dict) -> list[list[Button]]:"""The buttons under a notification: [Approve all] when the run waits for this person's scenario review, and alink to the right screen. Sign-off and failure verdicts are links only: they stay in the app."""row: list[Button] = []if event.get("kind") == "run.waiting_approval" and event.get("run_id") and user.can("gate.approve_cases"):cb = conv._callback_id(chat, user, secrets.token_hex(6), "approve.ask", {"run_id": event["run_id"]}) # noqa: SLF001row.append(Button("Approve all", callback=cb))url = absolute(conv.svc, event.get("link"))if url:label = {"run.waiting_approval": "Open review", "run.waiting_decision": "Open failures", "run.finished": "Open report"}.get(str(event.get("kind")), "Open in Astra")row.append(Button(label, url=url))return [row] if row else []def _verb(action: dict) -> str:return {"start_run": "Start test run", "approve_scenarios": "Yes, approve", "cancel_run": "Cancel the test run","add_note": "Save the note"}.get(str(action.get("tool")), str(action.get("verb") or "Confirm"))def _run_words(rest: str) -> str:"""/run <area words> [quick|browser] -> the sentence the Ask router understands."""words = rest.split()mode = "quick simulation"if words and words[-1].lower() in ("browser", "live", "full"):mode, words = "browser run", words[:-1]elif words and words[-1].lower() in ("quick", "stub", "simulation"):words = words[:-1]what = " ".join(words) or "Procure-to-Pay"return f"start a {mode} of {what}"WELCOME = "Hello, I'm the Astra bot. I tell you when a test run needs you, and you can ask me about your patches."LINK_HELP = ("To link this chat to your Astra account: in Astra open Account > Telegram, press \"Get a link code\", ""then send me /link CODE here.")HELP_COMMANDS = ("/status: what is waiting for you\n/run Procure-to-Pay quick: start a test run (you confirm first)\n""/unlink: stop using this chat\nOr just ask, for example: Is Procure-to-Pay ready for 26C?")HELP = "Hi {name}. " + HELP_COMMANDS + "\n\nSign-off and failure decisions stay in the app: I send you the link."123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397"""Two-way chat channels: the conversation core, the same for every channel (Telegram now, Microsoft Teams next).A channel adapter turns its platform's messages into `Inbound` and sends `OutMessage` back; everything else lives here:- Linking: a person links a chat to their Astra account with a one-time code made in the app (Account > Telegram).Only the code's hash is stored; it works once, for 10 minutes. From then on the bot acts as that user, with that user'srole: the same RBAC as the screens. An unlinked chat only gets help and "/link CODE".- Talking: any free text goes to the Ask service (coworker/chat/service.py) exactly as the Ask page does, as that user:one tool per message, read tools answer, action tools only propose. A proposal becomes two buttons, [Start test run][Cancel] (or the proposal's own verb), and nothing runs until the person presses it.- Buttons never carry what they do: the button holds a short random id; the action is stored server-side with the chat,the user, an expiry (24 h) and its group (pressing one button closes the others), so a button can't be forged,replayed, used in another chat or by another person.- Never in a chat: sign-off and failure verdicts (the bot links to the screens instead), the kill switch, administration.- Every action is audited as channel.<action>, with the linked user as the actor and the channel's name."""from __future__ import annotationsimport hashlibimport jsonimport secretsimport threadingimport timefrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom typing import Protocolfrom ..platform.rundb import now_isoCODE_ALPHABET = "ABCDEFGHJKLMNPQRSTUVWXYZ23456789" # no 0/O, 1/I: easy to type from a phoneCODE_LEN = 6CODE_TTL = timedelta(minutes=10)CALLBACK_TTL = timedelta(hours=24)LINK_TRIES = 5 # wrong codes per person per 10 minutes_tries_lock = threading.Lock()_tries: dict[str, list[float]] = {}@dataclassclass Button:label: strcallback: str | None = None # an opaque id from channel_callbacksurl: str | None = None # an absolute https link@dataclassclass OutMessage:text: str # plain text: the adapter escapes it for its platformbuttons: list[list[Button]] = field(default_factory=list)html: bool = False # the text is Telegram HTML already (a notification laid out by notify.telegram_text)@dataclassclass Inbound:channel: strexternal_user_id: strchat_id: strtext: str | None = Nonecallback_data: str | None = Nonecallback_id: str | None = None # the platform's id of the button press (to acknowledge it)username: str | None = Noneprivate: bool = Trueclass Adapter(Protocol):channel: strdef send(self, chat_id: str, msg: OutMessage) -> str | None: ...def answer_callback(self, callback_id: str, text: str | None = None) -> None: ...def _hash(code: str) -> str:return hashlib.sha256(code.strip().upper().encode("utf-8")).hexdigest()def _utc(ts: str) -> datetime:d = datetime.fromisoformat(str(ts).replace("Z", "+00:00"))return d if d.tzinfo else d.replace(tzinfo=timezone.utc)def _later(delta: timedelta) -> str:return (datetime.now(timezone.utc) + delta).isoformat(timespec="seconds")def absolute(svc, path: str | None) -> str | None:"""A screen path as a link a chat can open: only an absolute https address (platforms refuse anything else)."""if not path:return Noneif path.startswith("https://"):return pathbase = (svc.cfg.public_url or "").rstrip("/")return f"{base}{path if path.startswith('/') else '/' + path}" if base.startswith("https://") else None# ------------------------------------------------------------ links (app side)def new_link_code(svc, user_id: int, channel: str) -> dict:"""A one-time code the person sends to the bot as "/link CODE". Only its hash is kept; it works once, for 10 minutes."""code = "".join(secrets.choice(CODE_ALPHABET) for _ in range(CODE_LEN))svc.db.insert("channel_link_codes", {"code_hash": _hash(code), "user_id": user_id, "channel": channel,"created_at": now_iso(), "expires_at": _later(CODE_TTL)})return {"code": code, "expires_at": _later(CODE_TTL)}def link_of_user(svc, user_id: int, channel: str) -> dict | None:return svc.db.one("SELECT * FROM channel_links WHERE user_id=? AND channel=? ORDER BY id DESC LIMIT 1", (user_id, channel))def unlink_user(svc, user_id: int, channel: str) -> int:return svc.db.x("DELETE FROM channel_links WHERE user_id=? AND channel=?", (user_id, channel))def linked_chats(svc, channel: str) -> list[dict]:return svc.db.q("SELECT * FROM channel_links WHERE channel=? ORDER BY id", (channel,))# ------------------------------------------------------------ the conversationclass Conversation:"""Handles one inbound message or button press and returns what to send back (the adapter sends it)."""def __init__(self, svc, runs):self.svc, self.runs, self.db = svc, runs, svc.db# -- who is talkingdef _link(self, inb: Inbound) -> dict | None:return self.db.one("SELECT * FROM channel_links WHERE channel=? AND external_user_id=?", (inb.channel, inb.external_user_id))def _principal(self, link: dict):from ..api.auth import Principalu = self.svc.users.get(int(link["user_id"]))if not u or u.get("disabled"):return Nonereturn Principal(u["id"], u["username"], u["role"], link["channel"])def _audit(self, kind: str, inb: Inbound, user=None, run_id: str | None = None, summary: str = "", **payload) -> None:self.svc.audit.append(f"channel.{kind}", actor=getattr(user, "username", None) or f"{inb.channel}:{inb.external_user_id}",run_id=run_id, summary=summary or kind, payload={"channel": inb.channel, **payload})# -- entry pointdef handle(self, inb: Inbound) -> list[OutMessage]:link = self._link(inb)if inb.callback_data is not None:if not link:return [OutMessage("This chat is not linked to a Astra account yet. " + LINK_HELP)]user = self._principal(link)if not user:return [OutMessage("This Astra account is switched off. Ask an administrator.")]return self._callback(inb, user, link)text = (inb.text or "").strip()cmd, _, rest = text.partition(" ")cmd = cmd.split("@", 1)[0].lower() # "/help@PatchwiseBot" in groupsif cmd == "/link":return [self._link_chat(inb, rest.strip())]if not link:return [OutMessage(WELCOME + "\n\n" + LINK_HELP)]user = self._principal(link)if not user:return [OutMessage("This Astra account is switched off. Ask an administrator.")]if cmd in ("/start", "/help"):return [OutMessage(HELP.format(name=user.username))]if cmd == "/unlink":self.db.x("DELETE FROM channel_links WHERE id=?", (link["id"],))self._audit("unlinked", inb, user, summary=f"{inb.channel} chat unlinked")return [OutMessage("This chat is no longer linked. You will not get Astra messages here. Link again with /link CODE.")]if cmd == "/status":return [self._status(user, inb)]if cmd == "/run":return self._ask(inb, user, link, _run_words(rest))if not text:return [OutMessage(HELP.format(name=user.username))]return self._ask(inb, user, link, text)# -- linkingdef _link_chat(self, inb: Inbound, code: str) -> OutMessage:if not inb.private:return OutMessage("Link in a private chat with the bot, not in a group.")key = f"{inb.channel}:{inb.external_user_id}"now = time.monotonic()with _tries_lock:recent = [t for t in _tries.get(key, []) if now - t < 600]if len(recent) >= LINK_TRIES:_tries[key] = recentreturn OutMessage("Too many tries. Wait 10 minutes, then make a new code in Astra.")_tries[key] = recent + [now]if not code:return OutMessage(LINK_HELP)row = self.db.one("SELECT * FROM channel_link_codes WHERE code_hash=? AND channel=?", (_hash(code), inb.channel))if not row or row["used_at"] or _utc(row["expires_at"]) <= datetime.now(timezone.utc):self._audit("link.refused", inb, summary="unknown, used or expired link code")return OutMessage("That code is not valid (codes work once, for 10 minutes). Make a new one in Astra: Account > Telegram.")if not self.db.x("UPDATE channel_link_codes SET used_at=? WHERE code_hash=? AND used_at IS NULL", (now_iso(), row["code_hash"])):return OutMessage("That code was just used. Make a new one in Astra.")u = self.svc.users.get(int(row["user_id"]))if not u or u.get("disabled"):return OutMessage("That Astra account is switched off. Ask an administrator.")with self.db.tx() as c:c.execute("DELETE FROM channel_links WHERE channel=? AND (external_user_id=? OR user_id=?)",(inb.channel, inb.external_user_id, u["id"]))c.execute("INSERT INTO channel_links (channel, external_user_id, chat_id, user_id, username, linked_at) VALUES (?,?,?,?,?,?)",(inb.channel, inb.external_user_id, inb.chat_id, u["id"], (inb.username or "")[:80], now_iso()))with _tries_lock:_tries.pop(key, None)self.svc.audit.append("channel.linked", actor=u["username"], summary=f"{inb.channel} chat linked",payload={"channel": inb.channel, "chat": inb.chat_id, "username": inb.username})return OutMessage(f"Linked. This chat now belongs to {u['username']} ({u['role']}). ""I will tell you here when a test run needs you, and you can ask me anything Ask can answer.\n\n"+ HELP_COMMANDS)# -- /statusdef _status(self, user, inb: Inbound) -> OutMessage:from ..chat.tools import STATUS_WORDS, run_nameruns = self.db.list_runs(None, 50)waiting = [r for r in runs if (r.get("pending_gate") == "approve_cases" and user.can("gate.approve_cases"))or (r.get("pending_gate") == "sign_in" and user.can("gate.sign_in"))or (r.get("pending_gate") == "human_review" and user.can("gate.human_review"))]lines = []if waiting:lines.append(f"Waiting for you ({len(waiting)}):")lines += [f"• {run_name(r)}: {STATUS_WORDS.get(r['status'], r['status'])}" for r in waiting[:5]]else:lines.append("Nothing is waiting for you right now.")latest = runs[:3]if latest:lines.append("")lines.append("Latest test runs:")lines += [f"• {run_name(r)}: {STATUS_WORDS.get(r['status'], r['status'])}" for r in latest]buttons = []url = absolute(self.svc, "/runs")if url:buttons = [[Button("Open Test runs", url=url)]]self._audit("status", inb, user)return OutMessage("\n".join(lines), buttons)# -- free text: the Ask service, as this userdef _conversation_id(self, user, link: dict) -> str:from ..chat.service import ChatError, ChatServicechat = ChatService(self.svc, self.runs)cid = link.get("conv_id")if cid:try:chat.conversation(user, cid)return cidexcept ChatError:passcid = chat.create(user, None, None)["id"]self.db.x("UPDATE channel_links SET conv_id=? WHERE id=?", (cid, link["id"]))return ciddef _ask(self, inb: Inbound, user, link: dict, text: str) -> list[OutMessage]:from ..chat.service import ChatError, ChatServicechat = ChatService(self.svc, self.runs)cid = self._conversation_id(user, link)answer, links, sources, action = "", [], [], Nonetry:for ev, data in chat.turn(user, cid, text, {"tz_offset": 0}):if ev == "delta":answer += str(data.get("text") or "")elif ev == "result":links, sources = data.get("links") or [], data.get("sources") or []elif ev == "action":action = dataexcept ChatError as e:return [OutMessage(e.detail if e.code != "RATE_LIMITED" else "Too many questions in a short time. Try again in a minute.")]self._audit("message", inb, user, summary="ask", conversation=cid)if action:grp = secrets.token_hex(6)yes = self._callback_id(inb, user, grp, "chat.confirm", {"action_id": action["action_id"], "tool": action.get("tool")})no = self._callback_id(inb, user, grp, "chat.cancel", {"action_id": action["action_id"]})preview = action.get("preview")body = answer or action.get("title") or "Shall I do this?"if isinstance(preview, str) and preview and preview not in body:body += "\n" + previewbody += "\n\nNothing happens until you press the button."return [OutMessage(body, [[Button(_verb(action), callback=yes), Button("Cancel", callback=no)]])]text_out = answer or "I could not find an answer to that."if sources:text_out += "\n\nSource: " + "; ".join(str(s.get("label")) for s in sources if s.get("label"))row = [Button(str(lk.get("label") or "Open"), url=u) for lk in links[:3] if (u := absolute(self.svc, lk.get("to")))]return [OutMessage(text_out, [row] if row else [])]# -- buttonsdef _callback_id(self, inb: Inbound, user, grp: str, kind: str, payload: dict) -> str:cb = secrets.token_urlsafe(9) # 12 characters: well under Telegram's 64-byte limitself.db.insert("channel_callbacks", {"id": cb, "grp": grp, "channel": inb.channel, "chat_id": inb.chat_id, "user_id": user.id,"kind": kind, "payload_json": json.dumps(payload), "created_at": now_iso(),"expires_at": _later(CALLBACK_TTL)})return cbdef _callback(self, inb: Inbound, user, link: dict) -> list[OutMessage]:row = self.db.one("SELECT * FROM channel_callbacks WHERE id=?", (inb.callback_data,))if not row or row["channel"] != inb.channel or str(row["chat_id"]) != str(inb.chat_id) or int(row["user_id"]) != int(user.id):self._audit("callback.refused", inb, user, summary="unknown button or not this person's")return [OutMessage("This button is not valid here. Ask again.")]if row["used_at"] or _utc(row["expires_at"]) <= datetime.now(timezone.utc):return [OutMessage("This button has expired or was already used. Ask again to get a fresh one.")]if not self.db.x("UPDATE channel_callbacks SET used_at=? WHERE id=? AND used_at IS NULL", (now_iso(), row["id"])):return [OutMessage("This button was already used.")]self.db.x("UPDATE channel_callbacks SET used_at=? WHERE grp=? AND used_at IS NULL", (now_iso(), row["grp"]))payload = json.loads(row["payload_json"])kind = row["kind"]if kind == "chat.confirm":return [self._confirm(inb, user, payload)]if kind == "chat.cancel":return [self._cancel(inb, user, payload)]if kind == "approve.ask":return self._approve_ask(inb, user, link, payload)return [OutMessage("This button is not valid here. Ask again.")]def _confirm(self, inb: Inbound, user, payload: dict) -> OutMessage:from ..api.errors import ApiErrorfrom ..chat.service import ChatError, ChatServicetry:out = ChatService(self.svc, self.runs).confirm_action(user, payload["action_id"])except (ChatError, ApiError) as e:self._audit("action.failed", inb, user, summary=f"{payload.get('tool')}: {e.code}", action=payload["action_id"])return OutMessage(f"That did not work: {e.detail}")res = out.get("result") or {}rid = res.get("run_id")if payload.get("tool") == "start_run" and rid:self.db.x("INSERT OR IGNORE INTO channel_run_origins (run_id, channel, chat_id, user_id, created_at) VALUES (?,?,?,?,?)",(rid, inb.channel, inb.chat_id, user.id, now_iso()))self._audit("action.confirmed", inb, user, run_id=rid, summary=str(payload.get("tool")), action=payload["action_id"])words = {"start_run": "Done: the test run has started. I will tell you here when it needs you.","approve_scenarios": f"Done: {res.get('approved', 'the')} scenarios approved; testing starts now.","cancel_run": "Done: the test run was cancelled.", "add_note": "Done: the note is saved."}.get(str(payload.get("tool")), "Done.")url = absolute(self.svc, res.get("to"))return OutMessage(words, [[Button("Open in Astra", url=url)]] if url else [])def _cancel(self, inb: Inbound, user, payload: dict) -> OutMessage:from ..chat.service import ChatError, ChatServicetry:ChatService(self.svc, self.runs).cancel_action(user, payload["action_id"])except ChatError as e:return OutMessage(e.detail)self._audit("action.cancelled", inb, user, action=payload["action_id"])return OutMessage("Cancelled. Nothing was changed.")def _approve_ask(self, inb: Inbound, user, link: dict, payload: dict) -> list[OutMessage]:"""[Approve all] from a notification: the same proposal the Ask service makes for "approve all", then asecond press on [Yes, approve all] runs it through the same confirm path (RBAC and gate re-checked)."""from ..chat.service import ChatServicefrom ..chat.tools import Toolsif not user.can("gate.approve_cases"):self._audit("approve.refused", inb, user, run_id=payload.get("run_id"), summary="role may not approve scenarios")return [OutMessage(f"Your role ({user.role}) can't approve scenarios. Ask a consultant, or open the review to look.")]res = Tools(self.svc, self.runs, user, 0).approve_scenarios(run_id=payload.get("run_id"))if not res.proposal:return [OutMessage(res.text)]cid = self._conversation_id(user, link)action = ChatService(self.svc, self.runs)._propose(user, cid, res.proposal, payload.get("run_id")) # noqa: SLF001 (same path as Ask)n = len((res.proposal.get("payload") or {}).get("approved") or [])grp = secrets.token_hex(6)yes = self._callback_id(inb, user, grp, "chat.confirm", {"action_id": action["action_id"], "tool": "approve_scenarios"})no = self._callback_id(inb, user, grp, "chat.cancel", {"action_id": action["action_id"]})self._audit("approve.asked", inb, user, run_id=payload.get("run_id"), summary=f"{n} scenarios")return [OutMessage(f"{res.proposal['title']}\nApprove all {n} scenarios? Nothing is tested until you do.",[[Button("Yes, approve all", callback=yes), Button("Cancel", callback=no)]])]def notification_buttons(conv: Conversation, chat: Inbound, user, event: dict) -> list[list[Button]]:"""The buttons under a notification: [Approve all] when the run waits for this person's scenario review, and alink to the right screen. Sign-off and failure verdicts are links only: they stay in the app."""row: list[Button] = []if event.get("kind") == "run.waiting_approval" and event.get("run_id") and user.can("gate.approve_cases"):cb = conv._callback_id(chat, user, secrets.token_hex(6), "approve.ask", {"run_id": event["run_id"]}) # noqa: SLF001row.append(Button("Approve all", callback=cb))url = absolute(conv.svc, event.get("link"))if url:label = {"run.waiting_approval": "Open review", "run.waiting_decision": "Open failures", "run.finished": "Open report"}.get(str(event.get("kind")), "Open in Astra")row.append(Button(label, url=url))return [row] if row else []def _verb(action: dict) -> str:return {"start_run": "Start test run", "approve_scenarios": "Yes, approve", "cancel_run": "Cancel the test run","add_note": "Save the note"}.get(str(action.get("tool")), str(action.get("verb") or "Confirm"))def _run_words(rest: str) -> str:"""/run <area words> [quick|browser] -> the sentence the Ask router understands."""words = rest.split()mode = "quick simulation"if words and words[-1].lower() in ("browser", "live", "full"):mode, words = "browser run", words[:-1]elif words and words[-1].lower() in ("quick", "stub", "simulation"):words = words[:-1]what = " ".join(words) or "Procure-to-Pay"return f"start a {mode} of {what}"WELCOME = "Hello, I'm the Astra bot. I tell you when a test run needs you, and you can ask me about your patches."LINK_HELP = ("To link this chat to your Astra account: in Astra open Account > Telegram, press \"Get a link code\", ""then send me /link CODE here.")HELP_COMMANDS = ("/status: what is waiting for you\n/run Procure-to-Pay quick: start a test run (you confirm first)\n""/unlink: stop using this chat\nOr just ask, for example: Is Procure-to-Pay ready for 26C?")HELP = "Hi {name}. " + HELP_COMMANDS + "\n\nSign-off and failure decisions stay in the app: I send you the link."
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470"""Chat tools: a closed list. Read tools answer from the existing read models (platform/readiness.py, the run DB) underthe asking user's own permissions. Action tools NEVER execute here: they resolve the exact payload and return a proposalthat the user confirms with a click (chat/service.py). Nothing here decides GO/NO-GO, signs off, or gives a verdict.Every tool returns a ToolResult: a template answer (plain text, three sentences at most), structured cards and links(the only place links come from), and source lines saying where the answer comes from."""from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom ..adapters.cases import load_all, load_casesfrom ..platform import readiness as Rfrom ..platform.pods import PodError, PodRegistryfrom ..platform.users import PERMISSIONSfrom .intent import MODULE_NAMES, fuzzyNO_EVIDENCE = "I can't find this in the test runs or the patch research, so I won't guess. Try the What changed tab."SRC_MAP = "analyst coverage map UNVERIFIED: not checked against Oracle's release notes"SRC_NOTES = "Oracle release notes"SRC_LIBRARY = "scenario library (descriptions not yet checked on a real Fusion pod)"STATUS_WORDS = {"queued": "starting", "running": "testing", "waiting_approval": "waiting for your scenario review","waiting_review": "waiting for your failure review", "completed": "finished", "failed": "stopped with an error","killed": "stopped (emergency stop)", "cancelled": "cancelled", "interrupted": "paused, can resume"}ROLE_WORDS = {"gate.approve_cases": "approve scenarios", "run.start": "start a test run", "run.control": "cancel a test run","run.note": "add a note"}TOOL_PERM = {"start_run": "run.start", "approve_scenarios": "gate.approve_cases", "cancel_run": "run.control", "add_note": "run.note"}TERMINAL = ("completed", "failed", "killed", "cancelled")_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]@dataclassclass ToolResult:ok: bool = Truetext: str = "" # template answer (plain text)summary: str = "" # one line for the SSE `tool` event and the stored digestcards: list[dict] = field(default_factory=list)links: list[dict] = field(default_factory=list) # [{label, to}] in-app routes onlysources: list[dict] = field(default_factory=list) # [{label, to?}]facts: str = "" # everything a rewritten answer may draw numbers fromproposal: dict | None = None # action tools onlydef area(m: str | None) -> str:return MODULE_NAMES.get(m or "", m or "All areas")def run_name(r: dict, tz_min: int = 0) -> str:""""Procure-to-Pay · 26C · 11 Oct 09:47", in the asking user's time zone (the same name the screens show)."""mods = r.get("modules") or []a = "All areas" if not mods else area(mods[0]) + (f" + {len(mods) - 1} more" if len(mods) > 1 else "")when = ""try:d = datetime.fromisoformat(str(r.get("created_at") or "").replace("Z", "+00:00"))if d.tzinfo is None:d = d.replace(tzinfo=timezone.utc)d = d.astimezone(timezone(timedelta(minutes=tz_min)))when = f"{d.day} {_MONTHS[d.month - 1]} {d.hour:02d}:{d.minute:02d}"except ValueError:when = ""return " · ".join(x for x in (a, r.get("patch_id"), when) if x)def _plural(n: int, word: str) -> str:return f"{n} {word}{'' if n == 1 else 's'}"class Tools:def __init__(self, svc, runs, user, tz_min: int = 0):self.svc, self.runs, self.user, self.tz = svc, runs, user, tz_mindef rn(self, r: dict) -> str:return run_name(r, self.tz)def src(self, r: dict) -> dict:return {"label": f"test run {self.rn(r)} (mock app)", "to": f"/runs/{r['run_id']}"}# ------------------------------------------------------------ helpersdef _run(self, run_id: str | None, *, waiting_gate: str | None = None, active: bool = False) -> dict | None:if run_id:return self.svc.db.get_run(run_id)rows = self.svc.db.list_runs(None, 50)if waiting_gate:rows = [r for r in rows if r.get("pending_gate") == waiting_gate]if active:rows = [r for r in rows if r.get("status") not in TERMINAL]return rows[0] if rows else Nonedef _gate(self, run: dict) -> dict | None:return self.runs.gate_payload(run["run_id"]) if run.get("pending_gate") else Nonedef _denied(self, tool: str) -> ToolResult | None:perm = TOOL_PERM[tool]if self.user.can(perm):return Nonewho = " or ".join(PERMISSIONS.get(perm, ())) or "another role"extra = " Ask a test lead, or open the scenario review to read them." if tool == "approve_scenarios" else f" It needs the {who} role."return ToolResult(ok=False, summary="no permission", text=f"Your role ({self.user.role}) can't {ROLE_WORDS[perm]}.{extra}")# ------------------------------------------------------------ read toolsdef readiness(self, module: str | None = None, pod_id: int | None = None, patch_id: str | None = None) -> ToolResult:data = R.readiness(self.svc, self.runs, pod_id, patch_id, [module] if module else None)mods = data["modules"]if not mods:return ToolResult(ok=False, text=NO_EVIDENCE, summary="no data")parts, sources, cards, facts = [], [], [], []for m in mods[:4]:c = m["counts"]name = area(m["module"])touched = [s["name"] for s in m["steps"] if s["touched"]]gaps = [s["name"] for s in m["steps"] if s["state"] == "gap"]if m["run_id"]:run = self.svc.db.get_run(m["run_id"]) or {"run_id": m["run_id"]}parts.append(f"{name}: {m['verdict']}. In the latest test run {c['passed'] + c['passed_on_retry']} of {_plural(c['scenarios'], 'scenario')} passed, "f"{c['failing']} failing, {c['waiting_for_you']} waiting for you.")sources.append(self.src(run))else:parts.append(f"{name} has not been tested yet{f' for {patch_id}' if patch_id else ''} on this test environment. "f"The patch research touches {_plural(len(touched), 'process step')} and {_plural(len(gaps), 'step')} "f"{'has' if len(gaps) == 1 else 'have'} no scenario yet.")sources.append({"label": SRC_MAP})cards.append({"type": "readiness", "module": m["module"], "name": name, "verdict": m["verdict"], "run_id": m["run_id"], "counts": c,"steps": [{k: s[k] for k in ("key", "name", "state", "scenarios", "passed", "failed", "flaky", "not_run", "library","touched", "cross_cutting", "group", "codes", "order") if k in s} for s in m["steps"]]})facts.append(str(c) + " " + " ".join(touched + gaps) + f" {len(touched)} {len(gaps)}")links = [{"label": "Open Patch readiness", "to": "/" + (f"?module={module}" if module else "")}]if mods[0]["run_id"]:links.append({"label": "Open the test run", "to": f"/runs/{mods[0]['run_id']}"})return ToolResult(text=" ".join(parts[:2]), summary=f"readiness for {len(mods)} area(s)", cards=cards, links=links,sources=_dedupe(sources), facts=" ".join(parts) + " " + " ".join(facts) + f" {patch_id or ''}")def run_status(self, run_id: str | None = None) -> ToolResult:run = self._run(run_id)if not run:return ToolResult(ok=False, summary="no test run", text="There is no test run yet. You can start one from Patch readiness.",links=[{"label": "Open Patch readiness", "to": "/"}])rid = run["run_id"]rd = R.run_readiness(self.svc, self.runs, rid)tot = {"scen": 0, "done": 0, "fail": 0, "wait": 0}for m in rd["modules"]:c = m["counts"]tot["scen"] += c["scenarios"]tot["done"] += c["passed"] + c["passed_on_retry"] + c["failing"]tot["fail"] += c["failing"]tot["wait"] += c["waiting_for_you"]st = run.get("status")name = self.rn(run)links = [{"label": "Open the test run", "to": f"/runs/{rid}"}]if st == "waiting_approval":text = f"Test run {name} is waiting for your scenario review: {_plural(tot['wait'], 'scenario')} to approve."links.insert(0, {"label": "Open scenario review", "to": f"/runs/{rid}/scenarios"})elif st == "waiting_review":text = f"Test run {name} is waiting for your failure review: {_plural(tot['wait'], 'failure')} to judge."links.insert(0, {"label": "Open failure review", "to": f"/runs/{rid}/failures"})elif st == "completed":verdicts = ", ".join(f"{area(m['module'])}: {m['verdict']}" for m in rd["modules"])text = f"Test run {name} has finished. {verdicts}. {tot['done']} of {_plural(tot['scen'], 'scenario')} tested, {tot['fail']} failing."links.insert(0, {"label": "Open Report & sign-off", "to": f"/runs/{rid}/report"})elif st in ("queued", "running"):text = f"Testing {name}: {tot['done']} of {_plural(tot['scen'], 'scenario')} tested, {tot['fail']} failing. Nothing is waiting for you."if run.get("playwright_mode") == "live":links.insert(0, {"label": "Watch live", "to": f"/runs/{rid}/live"})else:text = f"Test run {name} is {STATUS_WORDS.get(st, st)}." + (f" Reason: {str(run.get('error'))[:160]}" if run.get("error") else "")card = {"type": "run", "run_id": rid, "title": name, "status": st, "status_words": STATUS_WORDS.get(st, st), "pending_gate": run.get("pending_gate"),"mode": run.get("playwright_mode"), "counts": {"scenarios": tot["scen"], "tested": tot["done"], "failing": tot["fail"], "waiting": tot["wait"]}}return ToolResult(text=text, summary=f"status {st}", cards=[card], links=links, sources=[self.src(run)], facts=text + f" {tot}")def failures(self, run_id: str | None = None, scenario: str | None = None) -> ToolResult:run = self._run(run_id)if not run_id and run and not (self.runs.state(run["run_id"]).get("verdicts") or {}): # latest run with failures, if this one has nonefor r in self.svc.db.list_runs(None, 30):if self.runs.state(r["run_id"]).get("verdicts"):run = rbreakif not run:return ToolResult(ok=False, summary="no test run", text="There is no test run yet, so there are no failures to explain.")rid = run["run_id"]items = R.failures(self.svc, rid, self.runs.state(rid), self._gate(run))src = [self.src(run)]if not items:return ToolResult(text=f"No scenario failed in test run {self.rn(run)}.", summary="no failures", sources=src,links=[{"label": "Open the test run", "to": f"/runs/{rid}"}])picked = itemsif scenario:by_id = [f for f in items if f["case_id"].lower() == scenario.lower()]name = fuzzy(scenario, [f"{f['title'] or ''} {f['step'] or ''}" for f in items], 0.3)picked = by_id or [f for f in items if name and f"{f['title'] or ''} {f['step'] or ''}" == name] or (items if len(items) == 1 else [])if not picked:titles = "; ".join(str(f["title"] or f["case_id"]) for f in items[:3])return ToolResult(text=f"I can't find a failed scenario matching that in test run {self.rn(run)}. {_plural(len(items), 'scenario')} failed: {titles}.",summary="no matching failure", sources=src, links=[{"label": "Open failure review", "to": f"/runs/{rid}/failures"}],cards=[{"type": "failures", "run_id": rid, "items": [_failure_card(f) for f in items[:5]]}], facts=f"{len(items)} {titles}")f = picked[0]head = f"{_plural(len(items), 'scenario')} failed in test run {self.rn(run)}. " if len(picked) > 1 or not scenario else ""exp = f"expected {f['expected']}, but got {f['actual']}" if f.get("expected") and f.get("actual") else (f.get("actual") or "the test output does not say why")text = (f"{head}{f['title'] or f['case_id']} failed{f' at {f['step']}' if f.get('step') else ''}: {exp}. "f"Suggested cause: {f['suggestion']}. I can suggest a cause, but the verdict is yours.")return ToolResult(text=text, summary=f"{len(picked)} failure(s)", sources=src,cards=[{"type": "failures", "run_id": rid, "items": [_failure_card(x) for x in picked[:5]]}],links=[{"label": "Open failure review", "to": f"/runs/{rid}/failures"}], facts=text + f" {len(items)} {len(picked)}")def scenario(self, case_id: str | None = None, name: str | None = None, run_id: str | None = None) -> ToolResult:if not case_id and name:cases = load_all(self.svc, None)title = fuzzy(name, [c["title"] for c in cases if c.get("title")], 0.45)case_id = next((c["id"] for c in cases if c.get("title") == title), None) if title else Noned = R.scenario_detail(case_id, None, self.runs.state(run_id) if run_id and self.svc.db.get_run(run_id) else None) if case_id else Noneif not d:return ToolResult(ok=False, summary="scenario not found", text="I can't find that scenario in the library, so I won't guess. Open the Scenarios library to search for it.",links=[{"label": "Open Scenarios library", "to": "/scenarios"}])steps = len(d["steps"])text = (f"{d['title']} is a {d['priority_words']} scenario{f' in {d['step']}' if d.get('step') else ''} with {_plural(steps, 'step')}."+ (f" Expected result: {d['expected_result']}" if d.get("expected_result") else ""))return ToolResult(text=text[:600], summary=f"scenario {d['id']}", cards=[{"type": "scenario", "scenario": d}],links=[{"label": "Open Scenarios library", "to": f"/scenarios?q={d['id']}"}], sources=[{"label": SRC_LIBRARY}],facts=text + f" {steps} " + " ".join(s["text"] for s in d["steps"]))def patch_changes(self, module: str | None = None, step: str | None = None, gaps_only: bool = False, run_id: str | None = None) -> ToolResult:run = self.svc.db.get_run(run_id) if run_id else Nonestate = self.runs.state(run_id) if run else Nonemodule = module or ((run or {}).get("modules") or [None])[0] or "P2P"steps = R.module_steps(module)library = [c for c in load_all(self.svc, [module]) if not c["lifecycle"]]changes = R.patch_changes(module, state, steps, library)if not changes:return ToolResult(ok=False, text=NO_EVIDENCE, summary="no change information")picked, step_name = changes, Noneif step:step_name = fuzzy(step, [s["name"] for s in steps], 0.4)area_name = fuzzy(step, [c["area"] for c in changes if c.get("area")], 0.45)picked = [c for c in changes if (step_name and step_name in c["affected_steps"]) or (area_name and c["area"] == area_name)]if not picked:return ToolResult(ok=False, text=NO_EVIDENCE, summary="no matching change",links=[{"label": "Open What changed", "to": f"/runs/{run_id}/changes" if run else "/"}])if gaps_only:picked = [c for c in picked if c["gap"]]gap_steps = [s["name"] for s in R.module_readiness(module, run, state, None, self.svc)["steps"] if s["state"] == "gap"]if not picked and not gap_steps:text = f"Every change area the patch research lists for {area(module)} has at least one scenario."else:text = (f"In {area(module)}, {_plural(len(picked), 'change area')} of this patch {'has' if len(picked) == 1 else 'have'} no scenario yet"+ (f": {', '.join(c['area'] for c in picked[:4])}{' and more' if len(picked) > 4 else ''}." if picked else ".")+ (f" Process steps with no scenario at all: {', '.join(gap_steps[:5])}." if gap_steps else ""))facts = text + f" {len(gap_steps)}"else:where = f" in {step_name}" if step_name else ""n_gap = sum(1 for c in picked if c["gap"])text = (f"The patch research lists {_plural(len(picked), 'change area')} for {area(module)}{where}: "f"{', '.join(c['area'] for c in picked[:4])}{' and more' if len(picked) > 4 else ''}. "+ (f"{n_gap} of them {'has' if n_gap == 1 else 'have'} no scenario yet." if n_gap else "Each has at least one scenario."))facts = textunverified = any(str(c["verification"]).startswith("UNVERIFIED") for c in picked) or not pickedreturn ToolResult(text=text, summary=f"{len(picked)} change area(s)", facts=facts + " " + " ".join(str(len(c["covering_scenarios"])) for c in picked),cards=[{"type": "changes", "module": module, "items": [{"id": c["id"], "area": c["area"], "summary": c["summary"], "affected_steps": c["affected_steps"], "gap": c["gap"],"covering": len(c["covering_scenarios"]), "verification": c["verification"]} for c in picked[:6]]}] if picked else [],links=[{"label": "Open What changed", "to": f"/runs/{run_id}/changes" if run else "/"}],sources=[{"label": SRC_MAP if unverified else SRC_NOTES}])def list_runs(self, status: str | None = None) -> ToolResult:rows = self.svc.db.list_runs(None, 50)if status == "waiting":rows = [r for r in rows if r.get("pending_gate")]elif status:rows = [r for r in rows if r.get("status") == status]items = [{"run_id": r["run_id"], "title": self.rn(r), "status": r.get("status"), "status_words": STATUS_WORDS.get(r.get("status"), r.get("status")),"pending_gate": r.get("pending_gate")} for r in rows[:6]]if status == "waiting":if not rows:text = "Nothing is waiting for you right now."else:r = rows[0]what = "scenario review" if r.get("pending_gate") == "approve_cases" else "failure review"text = f"{_plural(len(rows), 'test run')} {'is' if len(rows) == 1 else 'are'} waiting for you. The latest is {self.rn(r)}: it needs your {what}."elif not rows:text = "There are no test runs" + (f" with status {STATUS_WORDS.get(status, status)}" if status else "") + " yet."else:text = f"There {'is' if len(rows) == 1 else 'are'} {_plural(len(rows), 'test run')}" + (f" {STATUS_WORDS.get(status, status)}" if status else "") + \f". The latest is {self.rn(rows[0])}, {STATUS_WORDS.get(rows[0].get('status'), rows[0].get('status'))}."links = [{"label": "Open Test runs", "to": "/runs" + ("?waiting=1" if status == "waiting" else "")}]if status == "waiting" and rows:links.insert(0, {"label": "Open the review", "to": f"/runs/{rows[0]['run_id']}/{'scenarios' if rows[0].get('pending_gate') == 'approve_cases' else 'failures'}"})return ToolResult(text=text, summary=f"{len(rows)} run(s)", cards=[{"type": "runs", "items": items}] if items else [], links=links,sources=[{"label": "test runs on this installation (mock app)", "to": "/runs"}], facts=text + f" {len(rows)}")def list_pods(self) -> ToolResult:pods = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).list()ok = [p for p in pods if p["runnable"]]text = (f"There {'is' if len(pods) == 1 else 'are'} {_plural(len(pods), 'test environment')}; {len(ok)} can run tests"+ (f": {', '.join(p['name'] for p in ok[:3])}." if ok else "."))return ToolResult(text=text, summary=f"{len(pods)} pod(s)", facts=text,cards=[{"type": "pods", "items": [{"id": p["id"], "name": p["name"], "kind": p["kind"], "runnable": p["runnable"],"reason": p["not_runnable_reason"]} for p in pods[:8]]}],links=[{"label": "Open Test environments", "to": "/pods"}], sources=[{"label": "test environments registered in this app", "to": "/pods"}])def help(self, topic: str | None = None, run_id: str | None = None) -> ToolResult:run = f"/runs/{run_id}" if run_id else Noneif topic == "signoff":return ToolResult(text="Sign-off is yours to give, on the report. Open Report & sign-off.", summary="sign-off stays with the user",links=[{"label": "Open Report & sign-off", "to": f"{run}/report" if run else "/reports"}])if topic == "verdict":return ToolResult(text="I can suggest a cause, but the verdict is yours. Open failure review.", summary="verdicts stay with the user",links=[{"label": "Open failure review", "to": f"{run}/failures" if run else "/runs?waiting=1"}])if topic == "admin":return ToolResult(text="That is an administration task, which I don't do from chat. An admin can do it under Admin & under the hood.",summary="admin tasks stay on the screens", links=[{"label": "Open Admin & under the hood", "to": "/admin"}])return ToolResult(summary="help", text="I answer from your test runs and the patch research, and I show where each answer comes from. ""Ask whether an area is ready, what the patch changes, why a scenario failed, or what is waiting for you. ""I can also prepare a test run, a scenario approval, a cancellation or a note for you to confirm.",links=[{"label": "Open Patch readiness", "to": "/"}])# ------------------------------------------------------------ action tools: proposals onlydef start_run(self, modules: list[str] | None = None, mode: str = "stub", include_p2: bool = False, pod: str | None = None,pod_id: int | None = None, patch_id: str | None = None, area_text: str | None = None) -> ToolResult:denied = self._denied("start_run")if denied:return deniedreg = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit)pods = reg.list()try:if pod:name = fuzzy(pod, [p["name"] for p in pods], 0.4)target = next((p for p in pods if p["name"] == name), None)if not target:return ToolResult(ok=False, summary="unknown pod", text=f"I don't know a test environment called '{pod[:40]}'. Open Test environments to see the list.",links=[{"label": "Open Test environments", "to": "/pods"}])else:target = reg.get(int(pod_id)) if pod_id else reg.default()except PodError:target = Noneif not target:return ToolResult(ok=False, summary="no pod", text="There is no test environment to run on yet. Open Test environments to add one.",links=[{"label": "Open Test environments", "to": "/pods"}])if not target["runnable"]:return ToolResult(ok=False, summary="pod not runnable",text=f"I can't start a run on {target['name']}: it isn't set up to run tests yet. You can run on Local mock pod, or open Test environments to see what's missing.",links=[{"label": "Open Test environments", "to": "/pods"}])fusion = target["kind"] == "fusion"if fusion: # an Oracle Fusion pod has its own business areas (discovery): read them from the words usedfrom ..platform import fusion_catalogknown = {a["code"]: a["name"] for a in fusion_catalog.areas(self.svc.cfg.home)}asked = list(dict.fromkeys([m for m in (modules or []) if m in known] + fusion_catalog.areas_in(area_text or "", self.svc.cfg.home)))offered = reg.run_areas(target)mods = [m for m in asked if m in offered]if not mods:names = ", ".join(known.get(m, m) for m in offered) or "none yet (Discover on Test environments)"missing = [known.get(m, m) for m in asked if m not in offered]return ToolResult(ok=False, summary="no business area",text=(f"{', '.join(missing)} is not available on {target['name']}. " if missing else "Which business area should I test? ")+ f"On {target['name']} I can test: {names}.", links=[{"label": "Open Test environments", "to": "/pods"}])else:mods = [m for m in (modules or []) if m in MODULE_NAMES]if not mods:return ToolResult(ok=False, summary="no business area", text="Which business area should I test? For example: start a quick simulation of Procure-to-Pay.")if self.svc.kill.engaged():return ToolResult(ok=False, summary="kill switch", text="The emergency stop is on, so new test runs are refused until an admin releases it.")mode = "live" if mode == "live" else "stub"body = {"modules": mods, "playwright_mode": mode, "include_p2": bool(include_p2), "pod_id": target["id"]}if patch_id:body["patch_id"] = patch_idkind = "a full browser run" if mode == "live" else "a quick simulation"names = ", ".join((known.get(m, m) if fusion else area(m)) for m in mods)return ToolResult(summary="proposed: start a test run", text="", proposal={"tool": "start_run", "payload": body, "verb": "Start test run","title": f"I will start {kind} of {names} on {target['name']}{' including High-priority scenarios' if include_p2 else ''}. Nothing changes until you confirm.","items": [{"label": "Business area", "value": names}, {"label": "Test environment", "value": f"{target['name']} (mock app, not Oracle Fusion)" if target["kind"] == "mock" else target["name"]},{"label": "Run type", "value": "Full browser run" if mode == "live" else "Quick simulation (no browser)"},{"label": "Priorities", "value": "Critical and High" if include_p2 else "Critical (High only where the patch touches it)"}],"review": {"label": "Choose the options yourself", "to": "/?new=1"},"preview": {"method": "POST", "path": "/api/runs", "body": body}})def approve_scenarios(self, run_id: str | None = None, filter: dict | None = None) -> ToolResult: # noqa: A002denied = self._denied("approve_scenarios")if denied:return deniedrun = self._run(run_id, waiting_gate=None if run_id else "approve_cases")gate = self._gate(run) if run else Noneif not run or not gate or gate.get("gate") != "approve_cases":return ToolResult(ok=False, summary="nothing to approve", text="No test run is waiting for a scenario review right now, so there is nothing to approve.",links=[{"label": "Open Test runs", "to": "/runs"}])rid = run["run_id"]f = filter or {}state = self.runs.state(rid)cases = {c["id"]: c for c in state.get("test_cases") or []}pending = gate.get("pending") or []steps_cache: dict[str, list[dict]] = {}def step_of(p: dict) -> str | None:steps = steps_cache.setdefault(p["module"], R.module_steps(p["module"]))st = R.step_for_case(cases.get(p["id"]) or {"id": p["id"], "map_ids": [], "process": ""}, steps)return st["name"] if st else Noneby_step = {p["id"]: step_of(p) for p in pending}picked = list(pending)scope = f.get("scope") or "all"if scope in ("changed", "unchanged"):is_ch = lambda p: bool(p.get("changed_by_patch") or p.get("new_or_changed") or p.get("origin") == "generated") # noqa: E731picked = [p for p in picked if is_ch(p) == (scope == "changed")]step_name = Noneif f.get("step"):step_name = fuzzy(str(f["step"]), sorted({s for s in by_step.values() if s}), 0.4)if not step_name:names = ", ".join(sorted({s for s in by_step.values() if s})[:6])return ToolResult(ok=False, summary="no matching step", text=f"I can't match that to a process step in this review. The steps waiting are: {names}.",links=[{"label": "Open scenario review", "to": f"/runs/{rid}/scenarios"}])picked = [p for p in picked if by_step[p["id"]] == step_name]if not picked:return ToolResult(ok=False, summary="nothing matches", text="No scenario waiting for review matches that.",links=[{"label": "Open scenario review", "to": f"/runs/{rid}/scenarios"}])approved = [p["id"] for p in picked]rest = [p["id"] for p in pending if p["id"] not in approved]what = f"{len(approved)} {step_name + ' ' if step_name else ''}{'new or changed ' if scope == 'changed' else 'unchanged ' if scope == 'unchanged' else ''}scenario{'' if len(approved) == 1 else 's'}"title = f"I will approve {what} in test run {self.rn(run)}."if rest: # the review is one answer: whatever is not approved is skipped for this patch (graph/nodes/design.approval_apply)title += f" The other {len(rest)} waiting for review will be skipped for this patch, because the review is submitted in one go."title += " Nothing changes until you confirm."payload = {"run_id": rid, "approved": approved, "rejected": rest, "comments": {}}return ToolResult(summary=f"proposed: approve {len(approved)} scenario(s)", text="", proposal={"tool": "approve_scenarios", "payload": payload, "verb": f"Approve {_plural(len(approved), 'scenario')}", "title": title,"items": [{"label": by_step[p["id"]] or "Other", "value": p["title"], "id": p["id"], "decision": "approve"} for p in picked]+ [{"label": by_step[i] or "Other", "value": next(p["title"] for p in pending if p["id"] == i), "id": i, "decision": "skip"} for i in rest],"counts": {"approve": len(approved), "skip": len(rest)},"review": {"label": "Review them first", "to": f"/runs/{rid}/scenarios"},"preview": {"method": "POST", "path": f"/api/runs/{rid}/gates/approve_cases", "body": {k: payload[k] for k in ("approved", "rejected", "comments")}}})def cancel_run(self, run_id: str | None = None) -> ToolResult:denied = self._denied("cancel_run")if denied:return deniedrun = self._run(run_id, active=not run_id)if not run or run.get("status") in TERMINAL:return ToolResult(ok=False, summary="nothing to cancel", text="There is no test run in progress to cancel.", links=[{"label": "Open Test runs", "to": "/runs"}])rid = run["run_id"]body = {"reason": "cancelled from chat"}return ToolResult(summary="proposed: cancel the test run", text="", proposal={"tool": "cancel_run", "payload": {"run_id": rid, **body}, "verb": "Cancel test run","title": f"I will cancel test run {self.rn(run)}, which is {STATUS_WORDS.get(run.get('status'), run.get('status'))}. It cannot be continued afterwards. Nothing changes until you confirm.","items": [{"label": "Test run", "value": self.rn(run)}, {"label": "Status", "value": STATUS_WORDS.get(run.get("status"), str(run.get("status")))}],"review": {"label": "Open the test run first", "to": f"/runs/{rid}"},"preview": {"method": "POST", "path": f"/api/runs/{rid}/cancel", "body": body}})def add_note(self, run_id: str | None = None, text: str = "") -> ToolResult:denied = self._denied("add_note")if denied:return deniedrun = self._run(run_id)text = (text or "").strip()if not run:return ToolResult(ok=False, summary="no test run", text="There is no test run to add a note to.")if len(text) < 2:return ToolResult(ok=False, summary="empty note", text="What should the note say? For example: add a note: release owner informed.")rid = run["run_id"]return ToolResult(summary="proposed: add a note", text="", proposal={"tool": "add_note", "payload": {"run_id": rid, "text": text}, "verb": "Add note","title": f"I will add this note to test run {self.rn(run)}. It is saved to the audit log and shown in the activity log. Nothing changes until you confirm.","items": [{"label": "Note", "value": text}], "review": {"label": "Open the test run first", "to": f"/runs/{rid}"},"preview": {"method": "POST", "path": f"/api/runs/{rid}/notes", "body": {"text": text}}})def _failure_card(f: dict) -> dict:return {k: f.get(k) for k in ("case_id", "title", "step", "outcome", "expected", "actual", "suggestion", "priority_words", "pending")}def _dedupe(items: list[dict]) -> list[dict]:seen, out = set(), []for i in items:if i["label"] not in seen:seen.add(i["label"])out.append(i)return out123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473"""Chat tools: a closed list. Read tools answer from the existing read models (platform/readiness.py, the run DB) underthe asking user's own permissions. Action tools NEVER execute here: they resolve the exact payload and return a proposalthat the user confirms with a click (chat/service.py). Nothing here decides GO/NO-GO, signs off, or gives a verdict.Every tool returns a ToolResult: a template answer (plain text, three sentences at most), structured cards and links(the only place links come from), and source lines saying where the answer comes from."""from __future__ import annotationsfrom dataclasses import dataclass, fieldfrom datetime import datetime, timedelta, timezonefrom ..adapters.cases import load_all, load_casesfrom ..platform import readiness as Rfrom ..platform.pods import PodError, PodRegistryfrom ..platform.users import PERMISSIONSfrom .intent import MODULE_NAMES, fuzzyNO_EVIDENCE = "I can't find this in the test runs or the patch research, so I won't guess. Try the What changed tab."SRC_MAP = "analyst coverage map UNVERIFIED: not checked against Oracle's release notes"SRC_NOTES = "Oracle release notes"SRC_LIBRARY = "scenario library (descriptions not yet checked on a real Fusion pod)"STATUS_WORDS = {"queued": "starting", "running": "testing", "waiting_approval": "waiting for your scenario review","waiting_sign_in": "waiting for someone to sign in to the pod", "waiting_review": "waiting for your failure review", "completed": "finished", "failed": "stopped with an error","killed": "stopped (emergency stop)", "cancelled": "cancelled", "interrupted": "paused, can resume"}ROLE_WORDS = {"gate.approve_cases": "approve scenarios", "run.start": "start a test run", "run.control": "cancel a test run","run.note": "add a note"}TOOL_PERM = {"start_run": "run.start", "approve_scenarios": "gate.approve_cases", "cancel_run": "run.control", "add_note": "run.note"}TERMINAL = ("completed", "failed", "killed", "cancelled")_MONTHS = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]@dataclassclass ToolResult:ok: bool = Truetext: str = "" # template answer (plain text)summary: str = "" # one line for the SSE `tool` event and the stored digestcards: list[dict] = field(default_factory=list)links: list[dict] = field(default_factory=list) # [{label, to}] in-app routes onlysources: list[dict] = field(default_factory=list) # [{label, to?}]facts: str = "" # everything a rewritten answer may draw numbers fromproposal: dict | None = None # action tools onlydef area(m: str | None) -> str:return MODULE_NAMES.get(m or "", m or "All areas")def run_name(r: dict, tz_min: int = 0) -> str:""""Procure-to-Pay · 26C · 11 Oct 09:47", in the asking user's time zone (the same name the screens show)."""mods = r.get("modules") or []a = "All areas" if not mods else area(mods[0]) + (f" + {len(mods) - 1} more" if len(mods) > 1 else "")when = ""try:d = datetime.fromisoformat(str(r.get("created_at") or "").replace("Z", "+00:00"))if d.tzinfo is None:d = d.replace(tzinfo=timezone.utc)d = d.astimezone(timezone(timedelta(minutes=tz_min)))when = f"{d.day} {_MONTHS[d.month - 1]} {d.hour:02d}:{d.minute:02d}"except ValueError:when = ""return " · ".join(x for x in (a, r.get("patch_id"), when) if x)def _plural(n: int, word: str) -> str:return f"{n} {word}{'' if n == 1 else 's'}"class Tools:def __init__(self, svc, runs, user, tz_min: int = 0):self.svc, self.runs, self.user, self.tz = svc, runs, user, tz_mindef rn(self, r: dict) -> str:return run_name(r, self.tz)def src(self, r: dict) -> dict:return {"label": f"test run {self.rn(r)} (mock app)", "to": f"/runs/{r['run_id']}"}# ------------------------------------------------------------ helpersdef _run(self, run_id: str | None, *, waiting_gate: str | None = None, active: bool = False) -> dict | None:if run_id:return self.svc.db.get_run(run_id)rows = self.svc.db.list_runs(None, 50)if waiting_gate:rows = [r for r in rows if r.get("pending_gate") == waiting_gate]if active:rows = [r for r in rows if r.get("status") not in TERMINAL]return rows[0] if rows else Nonedef _gate(self, run: dict) -> dict | None:return self.runs.gate_payload(run["run_id"]) if run.get("pending_gate") else Nonedef _denied(self, tool: str) -> ToolResult | None:perm = TOOL_PERM[tool]if self.user.can(perm):return Nonewho = " or ".join(PERMISSIONS.get(perm, ())) or "another role"extra = " Ask a test lead, or open the scenario review to read them." if tool == "approve_scenarios" else f" It needs the {who} role."return ToolResult(ok=False, summary="no permission", text=f"Your role ({self.user.role}) can't {ROLE_WORDS[perm]}.{extra}")# ------------------------------------------------------------ read toolsdef readiness(self, module: str | None = None, pod_id: int | None = None, patch_id: str | None = None) -> ToolResult:data = R.readiness(self.svc, self.runs, pod_id, patch_id, [module] if module else None)mods = data["modules"]if not mods:return ToolResult(ok=False, text=NO_EVIDENCE, summary="no data")parts, sources, cards, facts = [], [], [], []for m in mods[:4]:c = m["counts"]name = area(m["module"])touched = [s["name"] for s in m["steps"] if s["touched"]]gaps = [s["name"] for s in m["steps"] if s["state"] == "gap"]if m["run_id"]:run = self.svc.db.get_run(m["run_id"]) or {"run_id": m["run_id"]}parts.append(f"{name}: {m['verdict']}. In the latest test run {c['passed'] + c['passed_on_retry']} of {_plural(c['scenarios'], 'scenario')} passed, "f"{c['failing']} failing, {c['waiting_for_you']} waiting for you.")sources.append(self.src(run))else:parts.append(f"{name} has not been tested yet{f' for {patch_id}' if patch_id else ''} on this test environment. "f"The patch research touches {_plural(len(touched), 'process step')} and {_plural(len(gaps), 'step')} "f"{'has' if len(gaps) == 1 else 'have'} no scenario yet.")sources.append({"label": SRC_MAP})cards.append({"type": "readiness", "module": m["module"], "name": name, "verdict": m["verdict"], "run_id": m["run_id"], "counts": c,"steps": [{k: s[k] for k in ("key", "name", "state", "scenarios", "passed", "failed", "flaky", "not_run", "library","touched", "cross_cutting", "group", "codes", "order") if k in s} for s in m["steps"]]})facts.append(str(c) + " " + " ".join(touched + gaps) + f" {len(touched)} {len(gaps)}")links = [{"label": "Open Patch readiness", "to": "/" + (f"?module={module}" if module else "")}]if mods[0]["run_id"]:links.append({"label": "Open the test run", "to": f"/runs/{mods[0]['run_id']}"})return ToolResult(text=" ".join(parts[:2]), summary=f"readiness for {len(mods)} area(s)", cards=cards, links=links,sources=_dedupe(sources), facts=" ".join(parts) + " " + " ".join(facts) + f" {patch_id or ''}")def run_status(self, run_id: str | None = None) -> ToolResult:run = self._run(run_id)if not run:return ToolResult(ok=False, summary="no test run", text="There is no test run yet. You can start one from Patch readiness.",links=[{"label": "Open Patch readiness", "to": "/"}])rid = run["run_id"]rd = R.run_readiness(self.svc, self.runs, rid)tot = {"scen": 0, "done": 0, "fail": 0, "wait": 0}for m in rd["modules"]:c = m["counts"]tot["scen"] += c["scenarios"]tot["done"] += c["passed"] + c["passed_on_retry"] + c["failing"]tot["fail"] += c["failing"]tot["wait"] += c["waiting_for_you"]st = run.get("status")name = self.rn(run)links = [{"label": "Open the test run", "to": f"/runs/{rid}"}]if st == "waiting_approval":text = f"Test run {name} is waiting for your scenario review: {_plural(tot['wait'], 'scenario')} to approve."links.insert(0, {"label": "Open scenario review", "to": f"/runs/{rid}/scenarios"})elif st == "waiting_review":text = f"Test run {name} is waiting for your failure review: {_plural(tot['wait'], 'failure')} to judge."links.insert(0, {"label": "Open failure review", "to": f"/runs/{rid}/failures"})elif st == "waiting_sign_in":text = f"Test run {name} is waiting for someone to sign in to the pod (assisted sign-in) before its tests start."links.insert(0, {"label": "Open the run to sign in", "to": f"/runs/{rid}"})elif st == "completed":verdicts = ", ".join(f"{area(m['module'])}: {m['verdict']}" for m in rd["modules"])text = f"Test run {name} has finished. {verdicts}. {tot['done']} of {_plural(tot['scen'], 'scenario')} tested, {tot['fail']} failing."links.insert(0, {"label": "Open Report & sign-off", "to": f"/runs/{rid}/report"})elif st in ("queued", "running"):text = f"Testing {name}: {tot['done']} of {_plural(tot['scen'], 'scenario')} tested, {tot['fail']} failing. Nothing is waiting for you."if run.get("playwright_mode") == "live":links.insert(0, {"label": "Watch live", "to": f"/runs/{rid}/live"})else:text = f"Test run {name} is {STATUS_WORDS.get(st, st)}." + (f" Reason: {str(run.get('error'))[:160]}" if run.get("error") else "")card = {"type": "run", "run_id": rid, "title": name, "status": st, "status_words": STATUS_WORDS.get(st, st), "pending_gate": run.get("pending_gate"),"mode": run.get("playwright_mode"), "counts": {"scenarios": tot["scen"], "tested": tot["done"], "failing": tot["fail"], "waiting": tot["wait"]}}return ToolResult(text=text, summary=f"status {st}", cards=[card], links=links, sources=[self.src(run)], facts=text + f" {tot}")def failures(self, run_id: str | None = None, scenario: str | None = None) -> ToolResult:run = self._run(run_id)if not run_id and run and not (self.runs.state(run["run_id"]).get("verdicts") or {}): # latest run with failures, if this one has nonefor r in self.svc.db.list_runs(None, 30):if self.runs.state(r["run_id"]).get("verdicts"):run = rbreakif not run:return ToolResult(ok=False, summary="no test run", text="There is no test run yet, so there are no failures to explain.")rid = run["run_id"]items = R.failures(self.svc, rid, self.runs.state(rid), self._gate(run))src = [self.src(run)]if not items:return ToolResult(text=f"No scenario failed in test run {self.rn(run)}.", summary="no failures", sources=src,links=[{"label": "Open the test run", "to": f"/runs/{rid}"}])picked = itemsif scenario:by_id = [f for f in items if f["case_id"].lower() == scenario.lower()]name = fuzzy(scenario, [f"{f['title'] or ''} {f['step'] or ''}" for f in items], 0.3)picked = by_id or [f for f in items if name and f"{f['title'] or ''} {f['step'] or ''}" == name] or (items if len(items) == 1 else [])if not picked:titles = "; ".join(str(f["title"] or f["case_id"]) for f in items[:3])return ToolResult(text=f"I can't find a failed scenario matching that in test run {self.rn(run)}. {_plural(len(items), 'scenario')} failed: {titles}.",summary="no matching failure", sources=src, links=[{"label": "Open failure review", "to": f"/runs/{rid}/failures"}],cards=[{"type": "failures", "run_id": rid, "items": [_failure_card(f) for f in items[:5]]}], facts=f"{len(items)} {titles}")f = picked[0]head = f"{_plural(len(items), 'scenario')} failed in test run {self.rn(run)}. " if len(picked) > 1 or not scenario else ""exp = f"expected {f['expected']}, but got {f['actual']}" if f.get("expected") and f.get("actual") else (f.get("actual") or "the test output does not say why")text = (f"{head}{f['title'] or f['case_id']} failed{f' at {f['step']}' if f.get('step') else ''}: {exp}. "f"Suggested cause: {f['suggestion']}. I can suggest a cause, but the verdict is yours.")return ToolResult(text=text, summary=f"{len(picked)} failure(s)", sources=src,cards=[{"type": "failures", "run_id": rid, "items": [_failure_card(x) for x in picked[:5]]}],links=[{"label": "Open failure review", "to": f"/runs/{rid}/failures"}], facts=text + f" {len(items)} {len(picked)}")def scenario(self, case_id: str | None = None, name: str | None = None, run_id: str | None = None) -> ToolResult:if not case_id and name:cases = load_all(self.svc, None)title = fuzzy(name, [c["title"] for c in cases if c.get("title")], 0.45)case_id = next((c["id"] for c in cases if c.get("title") == title), None) if title else Noned = R.scenario_detail(case_id, None, self.runs.state(run_id) if run_id and self.svc.db.get_run(run_id) else None) if case_id else Noneif not d:return ToolResult(ok=False, summary="scenario not found", text="I can't find that scenario in the library, so I won't guess. Open the Scenarios library to search for it.",links=[{"label": "Open Scenarios library", "to": "/scenarios"}])steps = len(d["steps"])text = (f"{d['title']} is a {d['priority_words']} scenario{f' in {d['step']}' if d.get('step') else ''} with {_plural(steps, 'step')}."+ (f" Expected result: {d['expected_result']}" if d.get("expected_result") else ""))return ToolResult(text=text[:600], summary=f"scenario {d['id']}", cards=[{"type": "scenario", "scenario": d}],links=[{"label": "Open Scenarios library", "to": f"/scenarios?q={d['id']}"}], sources=[{"label": SRC_LIBRARY}],facts=text + f" {steps} " + " ".join(s["text"] for s in d["steps"]))def patch_changes(self, module: str | None = None, step: str | None = None, gaps_only: bool = False, run_id: str | None = None) -> ToolResult:run = self.svc.db.get_run(run_id) if run_id else Nonestate = self.runs.state(run_id) if run else Nonemodule = module or ((run or {}).get("modules") or [None])[0] or "P2P"steps = R.module_steps(module)library = [c for c in load_all(self.svc, [module]) if not c["lifecycle"]]changes = R.patch_changes(module, state, steps, library)if not changes:return ToolResult(ok=False, text=NO_EVIDENCE, summary="no change information")picked, step_name = changes, Noneif step:step_name = fuzzy(step, [s["name"] for s in steps], 0.4)area_name = fuzzy(step, [c["area"] for c in changes if c.get("area")], 0.45)picked = [c for c in changes if (step_name and step_name in c["affected_steps"]) or (area_name and c["area"] == area_name)]if not picked:return ToolResult(ok=False, text=NO_EVIDENCE, summary="no matching change",links=[{"label": "Open What changed", "to": f"/runs/{run_id}/changes" if run else "/"}])if gaps_only:picked = [c for c in picked if c["gap"]]gap_steps = [s["name"] for s in R.module_readiness(module, run, state, None, self.svc)["steps"] if s["state"] == "gap"]if not picked and not gap_steps:text = f"Every change area the patch research lists for {area(module)} has at least one scenario."else:text = (f"In {area(module)}, {_plural(len(picked), 'change area')} of this patch {'has' if len(picked) == 1 else 'have'} no scenario yet"+ (f": {', '.join(c['area'] for c in picked[:4])}{' and more' if len(picked) > 4 else ''}." if picked else ".")+ (f" Process steps with no scenario at all: {', '.join(gap_steps[:5])}." if gap_steps else ""))facts = text + f" {len(gap_steps)}"else:where = f" in {step_name}" if step_name else ""n_gap = sum(1 for c in picked if c["gap"])text = (f"The patch research lists {_plural(len(picked), 'change area')} for {area(module)}{where}: "f"{', '.join(c['area'] for c in picked[:4])}{' and more' if len(picked) > 4 else ''}. "+ (f"{n_gap} of them {'has' if n_gap == 1 else 'have'} no scenario yet." if n_gap else "Each has at least one scenario."))facts = textunverified = any(str(c["verification"]).startswith("UNVERIFIED") for c in picked) or not pickedreturn ToolResult(text=text, summary=f"{len(picked)} change area(s)", facts=facts + " " + " ".join(str(len(c["covering_scenarios"])) for c in picked),cards=[{"type": "changes", "module": module, "items": [{"id": c["id"], "area": c["area"], "summary": c["summary"], "affected_steps": c["affected_steps"], "gap": c["gap"],"covering": len(c["covering_scenarios"]), "verification": c["verification"]} for c in picked[:6]]}] if picked else [],links=[{"label": "Open What changed", "to": f"/runs/{run_id}/changes" if run else "/"}],sources=[{"label": SRC_MAP if unverified else SRC_NOTES}])def list_runs(self, status: str | None = None) -> ToolResult:rows = self.svc.db.list_runs(None, 50)if status == "waiting":rows = [r for r in rows if r.get("pending_gate")]elif status:rows = [r for r in rows if r.get("status") == status]items = [{"run_id": r["run_id"], "title": self.rn(r), "status": r.get("status"), "status_words": STATUS_WORDS.get(r.get("status"), r.get("status")),"pending_gate": r.get("pending_gate")} for r in rows[:6]]if status == "waiting":if not rows:text = "Nothing is waiting for you right now."else:r = rows[0]what = "scenario review" if r.get("pending_gate") == "approve_cases" else "failure review"text = f"{_plural(len(rows), 'test run')} {'is' if len(rows) == 1 else 'are'} waiting for you. The latest is {self.rn(r)}: it needs your {what}."elif not rows:text = "There are no test runs" + (f" with status {STATUS_WORDS.get(status, status)}" if status else "") + " yet."else:text = f"There {'is' if len(rows) == 1 else 'are'} {_plural(len(rows), 'test run')}" + (f" {STATUS_WORDS.get(status, status)}" if status else "") + \f". The latest is {self.rn(rows[0])}, {STATUS_WORDS.get(rows[0].get('status'), rows[0].get('status'))}."links = [{"label": "Open Test runs", "to": "/runs" + ("?waiting=1" if status == "waiting" else "")}]if status == "waiting" and rows:links.insert(0, {"label": "Open the review", "to": f"/runs/{rows[0]['run_id']}/{'scenarios' if rows[0].get('pending_gate') == 'approve_cases' else 'failures'}"})return ToolResult(text=text, summary=f"{len(rows)} run(s)", cards=[{"type": "runs", "items": items}] if items else [], links=links,sources=[{"label": "test runs on this installation (mock app)", "to": "/runs"}], facts=text + f" {len(rows)}")def list_pods(self) -> ToolResult:pods = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit).list()ok = [p for p in pods if p["runnable"]]text = (f"There {'is' if len(pods) == 1 else 'are'} {_plural(len(pods), 'test environment')}; {len(ok)} can run tests"+ (f": {', '.join(p['name'] for p in ok[:3])}." if ok else "."))return ToolResult(text=text, summary=f"{len(pods)} pod(s)", facts=text,cards=[{"type": "pods", "items": [{"id": p["id"], "name": p["name"], "kind": p["kind"], "runnable": p["runnable"],"reason": p["not_runnable_reason"]} for p in pods[:8]]}],links=[{"label": "Open Test environments", "to": "/pods"}], sources=[{"label": "test environments registered in this app", "to": "/pods"}])def help(self, topic: str | None = None, run_id: str | None = None) -> ToolResult:run = f"/runs/{run_id}" if run_id else Noneif topic == "signoff":return ToolResult(text="Sign-off is yours to give, on the report. Open Report & sign-off.", summary="sign-off stays with the user",links=[{"label": "Open Report & sign-off", "to": f"{run}/report" if run else "/reports"}])if topic == "verdict":return ToolResult(text="I can suggest a cause, but the verdict is yours. Open failure review.", summary="verdicts stay with the user",links=[{"label": "Open failure review", "to": f"{run}/failures" if run else "/runs?waiting=1"}])if topic == "admin":return ToolResult(text="That is an administration task, which I don't do from chat. An admin can do it under Admin & under the hood.",summary="admin tasks stay on the screens", links=[{"label": "Open Admin & under the hood", "to": "/admin"}])return ToolResult(summary="help", text="I answer from your test runs and the patch research, and I show where each answer comes from. ""Ask whether an area is ready, what the patch changes, why a scenario failed, or what is waiting for you. ""I can also prepare a test run, a scenario approval, a cancellation or a note for you to confirm.",links=[{"label": "Open Patch readiness", "to": "/"}])# ------------------------------------------------------------ action tools: proposals onlydef start_run(self, modules: list[str] | None = None, mode: str = "stub", include_p2: bool = False, pod: str | None = None,pod_id: int | None = None, patch_id: str | None = None, area_text: str | None = None) -> ToolResult:denied = self._denied("start_run")if denied:return deniedreg = PodRegistry(self.svc.db, self.svc.vault, self.svc.cfg, self.svc.egress, self.svc.audit)pods = reg.list()try:if pod:name = fuzzy(pod, [p["name"] for p in pods], 0.4)target = next((p for p in pods if p["name"] == name), None)if not target:return ToolResult(ok=False, summary="unknown pod", text=f"I don't know a test environment called '{pod[:40]}'. Open Test environments to see the list.",links=[{"label": "Open Test environments", "to": "/pods"}])else:target = reg.get(int(pod_id)) if pod_id else reg.default()except PodError:target = Noneif not target:return ToolResult(ok=False, summary="no pod", text="There is no test environment to run on yet. Open Test environments to add one.",links=[{"label": "Open Test environments", "to": "/pods"}])if not target["runnable"]:return ToolResult(ok=False, summary="pod not runnable",text=f"I can't start a run on {target['name']}: it isn't set up to run tests yet. You can run on Local mock pod, or open Test environments to see what's missing.",links=[{"label": "Open Test environments", "to": "/pods"}])fusion = target["kind"] == "fusion"if fusion: # an Oracle Fusion pod has its own business areas (discovery): read them from the words usedfrom ..platform import fusion_catalogknown = {a["code"]: a["name"] for a in fusion_catalog.areas(self.svc.cfg.home)}asked = list(dict.fromkeys([m for m in (modules or []) if m in known] + fusion_catalog.areas_in(area_text or "", self.svc.cfg.home)))offered = reg.run_areas(target)mods = [m for m in asked if m in offered]if not mods:names = ", ".join(known.get(m, m) for m in offered) or "none yet (Discover on Test environments)"missing = [known.get(m, m) for m in asked if m not in offered]return ToolResult(ok=False, summary="no business area",text=(f"{', '.join(missing)} is not available on {target['name']}. " if missing else "Which business area should I test? ")+ f"On {target['name']} I can test: {names}.", links=[{"label": "Open Test environments", "to": "/pods"}])else:mods = [m for m in (modules or []) if m in MODULE_NAMES]if not mods:return ToolResult(ok=False, summary="no business area", text="Which business area should I test? For example: start a quick simulation of Procure-to-Pay.")if self.svc.kill.engaged():return ToolResult(ok=False, summary="kill switch", text="The emergency stop is on, so new test runs are refused until an admin releases it.")mode = "live" if mode == "live" else "stub"body = {"modules": mods, "playwright_mode": mode, "include_p2": bool(include_p2), "pod_id": target["id"]}if patch_id:body["patch_id"] = patch_idkind = "a full browser run" if mode == "live" else "a quick simulation"names = ", ".join((known.get(m, m) if fusion else area(m)) for m in mods)return ToolResult(summary="proposed: start a test run", text="", proposal={"tool": "start_run", "payload": body, "verb": "Start test run","title": f"I will start {kind} of {names} on {target['name']}{' including High-priority scenarios' if include_p2 else ''}. Nothing changes until you confirm.","items": [{"label": "Business area", "value": names}, {"label": "Test environment", "value": f"{target['name']} (mock app, not Oracle Fusion)" if target["kind"] == "mock" else target["name"]},{"label": "Run type", "value": "Full browser run" if mode == "live" else "Quick simulation (no browser)"},{"label": "Priorities", "value": "Critical and High" if include_p2 else "Critical (High only where the patch touches it)"}],"review": {"label": "Choose the options yourself", "to": "/?new=1"},"preview": {"method": "POST", "path": "/api/runs", "body": body}})def approve_scenarios(self, run_id: str | None = None, filter: dict | None = None) -> ToolResult: # noqa: A002denied = self._denied("approve_scenarios")if denied:return deniedrun = self._run(run_id, waiting_gate=None if run_id else "approve_cases")gate = self._gate(run) if run else Noneif not run or not gate or gate.get("gate") != "approve_cases":return ToolResult(ok=False, summary="nothing to approve", text="No test run is waiting for a scenario review right now, so there is nothing to approve.",links=[{"label": "Open Test runs", "to": "/runs"}])rid = run["run_id"]f = filter or {}state = self.runs.state(rid)cases = {c["id"]: c for c in state.get("test_cases") or []}pending = gate.get("pending") or []steps_cache: dict[str, list[dict]] = {}def step_of(p: dict) -> str | None:steps = steps_cache.setdefault(p["module"], R.module_steps(p["module"]))st = R.step_for_case(cases.get(p["id"]) or {"id": p["id"], "map_ids": [], "process": ""}, steps)return st["name"] if st else Noneby_step = {p["id"]: step_of(p) for p in pending}picked = list(pending)scope = f.get("scope") or "all"if scope in ("changed", "unchanged"):is_ch = lambda p: bool(p.get("changed_by_patch") or p.get("new_or_changed") or p.get("origin") == "generated") # noqa: E731picked = [p for p in picked if is_ch(p) == (scope == "changed")]step_name = Noneif f.get("step"):step_name = fuzzy(str(f["step"]), sorted({s for s in by_step.values() if s}), 0.4)if not step_name:names = ", ".join(sorted({s for s in by_step.values() if s})[:6])return ToolResult(ok=False, summary="no matching step", text=f"I can't match that to a process step in this review. The steps waiting are: {names}.",links=[{"label": "Open scenario review", "to": f"/runs/{rid}/scenarios"}])picked = [p for p in picked if by_step[p["id"]] == step_name]if not picked:return ToolResult(ok=False, summary="nothing matches", text="No scenario waiting for review matches that.",links=[{"label": "Open scenario review", "to": f"/runs/{rid}/scenarios"}])approved = [p["id"] for p in picked]rest = [p["id"] for p in pending if p["id"] not in approved]what = f"{len(approved)} {step_name + ' ' if step_name else ''}{'new or changed ' if scope == 'changed' else 'unchanged ' if scope == 'unchanged' else ''}scenario{'' if len(approved) == 1 else 's'}"title = f"I will approve {what} in test run {self.rn(run)}."if rest: # the review is one answer: whatever is not approved is skipped for this patch (graph/nodes/design.approval_apply)title += f" The other {len(rest)} waiting for review will be skipped for this patch, because the review is submitted in one go."title += " Nothing changes until you confirm."payload = {"run_id": rid, "approved": approved, "rejected": rest, "comments": {}}return ToolResult(summary=f"proposed: approve {len(approved)} scenario(s)", text="", proposal={"tool": "approve_scenarios", "payload": payload, "verb": f"Approve {_plural(len(approved), 'scenario')}", "title": title,"items": [{"label": by_step[p["id"]] or "Other", "value": p["title"], "id": p["id"], "decision": "approve"} for p in picked]+ [{"label": by_step[i] or "Other", "value": next(p["title"] for p in pending if p["id"] == i), "id": i, "decision": "skip"} for i in rest],"counts": {"approve": len(approved), "skip": len(rest)},"review": {"label": "Review them first", "to": f"/runs/{rid}/scenarios"},"preview": {"method": "POST", "path": f"/api/runs/{rid}/gates/approve_cases", "body": {k: payload[k] for k in ("approved", "rejected", "comments")}}})def cancel_run(self, run_id: str | None = None) -> ToolResult:denied = self._denied("cancel_run")if denied:return deniedrun = self._run(run_id, active=not run_id)if not run or run.get("status") in TERMINAL:return ToolResult(ok=False, summary="nothing to cancel", text="There is no test run in progress to cancel.", links=[{"label": "Open Test runs", "to": "/runs"}])rid = run["run_id"]body = {"reason": "cancelled from chat"}return ToolResult(summary="proposed: cancel the test run", text="", proposal={"tool": "cancel_run", "payload": {"run_id": rid, **body}, "verb": "Cancel test run","title": f"I will cancel test run {self.rn(run)}, which is {STATUS_WORDS.get(run.get('status'), run.get('status'))}. It cannot be continued afterwards. Nothing changes until you confirm.","items": [{"label": "Test run", "value": self.rn(run)}, {"label": "Status", "value": STATUS_WORDS.get(run.get("status"), str(run.get("status")))}],"review": {"label": "Open the test run first", "to": f"/runs/{rid}"},"preview": {"method": "POST", "path": f"/api/runs/{rid}/cancel", "body": body}})def add_note(self, run_id: str | None = None, text: str = "") -> ToolResult:denied = self._denied("add_note")if denied:return deniedrun = self._run(run_id)text = (text or "").strip()if not run:return ToolResult(ok=False, summary="no test run", text="There is no test run to add a note to.")if len(text) < 2:return ToolResult(ok=False, summary="empty note", text="What should the note say? For example: add a note: release owner informed.")rid = run["run_id"]return ToolResult(summary="proposed: add a note", text="", proposal={"tool": "add_note", "payload": {"run_id": rid, "text": text}, "verb": "Add note","title": f"I will add this note to test run {self.rn(run)}. It is saved to the audit log and shown in the activity log. Nothing changes until you confirm.","items": [{"label": "Note", "value": text}], "review": {"label": "Open the test run first", "to": f"/runs/{rid}"},"preview": {"method": "POST", "path": f"/api/runs/{rid}/notes", "body": {"text": text}}})def _failure_card(f: dict) -> dict:return {k: f.get(k) for k in ("case_id", "title", "step", "outcome", "expected", "actual", "suggestion", "priority_words", "pending")}def _dedupe(items: list[dict]) -> list[dict]:seen, out = set(), []for i in items:if i["label"] not in seen:seen.add(i["label"])out.append(i)return out
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348"""Settings: config/coworker.yaml (non-secret) < .env < environment (env wins) < explicit kwargs (tests).Validated with pydantic-settings. Secrets are NOT settings: they come from the vault only."""from __future__ import annotationsimport osfrom functools import lru_cachefrom pathlib import Pathfrom typing import Annotated, Literalfrom pydantic import AliasChoices, Field, field_validatorfrom pydantic_settings import (BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict,YamlConfigSettingsSource, NoDecode)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 reporoot); "" when it cannot know, and then nothing compares against it."""import revals = [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:passfor v in vals:v = v.strip().lower()if re.fullmatch(r"[0-9a-f]{7,40}", v):return vreturn ""def _alias(*names: str):return AliasChoices(*names)class Settings(BaseSettings):model_config = SettingsConfigDict(env_file=str(ROOT / ".env"), env_file_encoding="utf-8", extra="ignore",yaml_file=str(CONFIG_YAML), case_sensitive=False, populate_by_name=True)fpt_home: Path = Field(default=ROOT / "var")api_host: str = Field("127.0.0.1", validation_alias=_alias("fpt_api_host", "api_host"))api_port: int = Field(8800, validation_alias=_alias("fpt_api_port", "api_port"))cors_origins: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["http://127.0.0.1:5173", "http://localhost:5173"],validation_alias=_alias("fpt_cors_origins", "cors_origins"))cookie_secure: Literal["auto", "always", "never"] = Field("auto", validation_alias=_alias("fpt_cookie_secure", "cookie_secure"))session_ttl_hours: int = 12login_max_attempts: int = 5login_window_s: int = 300web_dist: Path = Field(default=ROOT / "web" / "dist", validation_alias=_alias("fpt_web_dist", "web_dist"))oidc_issuer: str = ""# shown in the menu and on the sign-in page (a reseller or customer can set its own)product_name: str = Field("Astra", validation_alias=_alias("fpt_product_name", "product_name"))org_name: str = Field("", validation_alias=_alias("fpt_org_name", "org_name"))# ---- Supabase (optional): identity provider for sign-in / registration, and storage for the encrypted state archive.# The service key is NOT a setting (it would show in /api/config): it comes from SUPABASE_SERVICE_KEY or the vault.supabase_url: str = ""supabase_anon_key: str = "" # the public ("anon" / publishable) keysupabase_bucket: str = "patch-coworker"registration_enabled: bool = Field(True, validation_alias=_alias("fpt_registration", "registration_enabled"))register_role: Literal["viewer", "consultant", "qa_approver"] = Field("viewer", validation_alias=_alias("fpt_register_role", "register_role"))# blank, "a@x.com, b@x.com" or a JSON list are all accepted (a blank value must never stop the start-up)# the address people open the app at, used for links in e-mails (never taken from request headers when set)public_url: str = Field("", validation_alias=_alias("fpt_public_url", "public_url"))# behind a hosting proxy (Hugging Face, Render): read the visitor's address from X-Forwarded-For so sign-in limits# count per visitor, not per proxy. Only switch on where the app is reachable through that proxy alone.# the interactive API docs (/api/docs, /api/openapi.json): on for development, off on a public serverapi_docs: bool = Field(True, validation_alias=_alias("fpt_api_docs", "api_docs"))trust_proxy: bool = Field(False, validation_alias=_alias("fpt_trust_proxy", "trust_proxy"))admin_emails: Annotated[list[str], NoDecode] = Field(default_factory=list, validation_alias=_alias("fpt_admin_emails", "admin_emails"))@field_validator("browser_runs", "research_cache_dir", mode="before")@classmethoddef _blank_is_unset(cls, v):"""An empty value (FPT_BROWSER_RUNS= in a .env file) means "not set": use the automatic default."""return None if isinstance(v, str) and not v.strip() else v@field_validator("admin_emails", mode="before")@classmethoddef _emails(cls, v):if v is None:return []if isinstance(v, str):t = v.strip()if not t:return []if t.startswith("["):import jsontry:v = json.loads(t)except ValueError:v = t.strip("[]").split(",")else:v = t.split(",")cleaned = [str(x).strip().strip("\"'").lower() for x in v]return [x for x in cleaned if x]state_sync: bool = Field(True, validation_alias=_alias("fpt_state_sync", "state_sync"))state_sync_interval_s: int = Field(60, validation_alias=_alias("fpt_state_sync_interval", "state_sync_interval_s"))# how many earlier archives the bucket keeps as state/history/<time>.bin (0 = none), so a bad save can be undonestate_history_keep: int = Field(5, ge=0, le=50, validation_alias=_alias("fpt_state_history", "state_history_keep"))# at shutdown, how long a running test run may take to reach its next step (where it can stop cleanly and continue# after the restart) before the last save goes ahead without it. Keep it under the host's stop grace period.shutdown_run_wait_s: int = Field(20, ge=0, le=300, validation_alias=_alias("fpt_shutdown_run_wait_s", "shutdown_run_wait_s"))# A site allowed to show this application inside its own page (a private Hugging Face Space is only reachable that# way). Empty = never framed by another site. Setting it relaxes the session cookies to SameSite=None.embed_origin: str = Field("", validation_alias=_alias("fpt_embed_origin", "embed_origin"))@field_validator("embed_origin")@classmethoddef _embed_origin(cls, v: str) -> str:import rev = (v or "").strip().rstrip("/")if v and not re.fullmatch(r"https://[A-Za-z0-9.-]{1,200}(:\d{1,5})?", v):raise ValueError("FPT_EMBED_ORIGIN must look like https://host")return v# Full browser runs need about 1.5 GB for Chromium. Unset = decided from the container's memory limit.browser_runs: bool | None = Field(None, validation_alias=_alias("fpt_browser_runs", "browser_runs"))@propertydef browser_runs_allowed(self) -> bool:if self.browser_runs is not None:return self.browser_runsfor p in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):try:raw = Path(p).read_text().strip()except OSError:continuereturn not (raw.isdigit() and int(raw) < 1_400_000_000)return True# ---- orchestration (Temporal = durable outer workflow; LangGraph = agent engine / offline fallback)orchestrator: Literal["temporal", "langgraph"] = Field("temporal", validation_alias=_alias("fpt_orchestrator", "orchestrator"))temporal_address: str = "127.0.0.1:7233"temporal_namespace: str = "default"temporal_task_queue: str = "fpt-main"temporal_browser_queue: str = "fpt-browser"temporal_ui_url: str = "http://127.0.0.1:8233"embedded_worker: bool = Field(False, validation_alias=_alias("fpt_embedded_worker", "embedded_worker"))approval_remind_after_s: int = Field(24 * 3600, validation_alias=_alias("approval_remind_after", "approval_remind_after_s"))approval_escalate_after_s: int = Field(72 * 3600, validation_alias=_alias("approval_escalate_after", "approval_escalate_after_s"))exec_chunk_size: int = 10# Fusion pods with an AI model on: how many NEW scenarios the model writes per business area in each test run# (dry-run on the pod, then offered at the approval gate). 0 turns it off.fusion_ai_scenarios: int = Field(4, validation_alias=_alias("fpt_fusion_ai_scenarios", "fusion_ai_scenarios"))# dry-run the AI's scenarios on the pod BEFORE approval (they save there, then again in the test run). Off: nothing# runs on the pod until a person approves; every scenario that passes the checks against the pod's screens is offered# and the test run after approval shows where each one stops# Oracle AI Agent Studio: how often the release watch reads Oracle's What's New (hours; 0 = only when asked)agent_studio_watch_hours: float = Field(24.0, validation_alias=_alias("fpt_agent_studio_watch_hours", "agent_studio_watch_hours"))fusion_ai_dry_run: bool = Field(False, validation_alias=_alias("fpt_fusion_ai_dry_run", "fusion_ai_dry_run"))# screens the scout reads per business area (quick actions and work area tasks a test starts from)fusion_screens_per_area: int = Field(8, validation_alias=_alias("fpt_fusion_screens_per_area", "fusion_screens_per_area"))# per area, the AI designs fusion_ai_scenarios plus one per change the update switches on by itself, up to thisfusion_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 timefusion_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 resultsfusion_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 browsersfusion_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"))# before a live run's scenarios, each area's canary (tests/cases/CANARY-<AREA>.yaml) runs its business actions once;# the scenarios that use an action the canary found broken are reported as blocked, not run, not product defectsfusion_canary: bool = Field(True, validation_alias=_alias("fpt_fusion_canary", "fusion_canary"))# the remote runner drives one browser job at a time: a run or screen read that finds it busy waits this long for itremote_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 itselffusion_screens_on_setup: bool = Field(True, validation_alias=_alias("fpt_fusion_screens_on_setup", "fusion_screens_on_setup"))# one area's screen reading stops after this many minutes (a user without access to an area only meets timeouts)fusion_screens_area_minutes: int = Field(20, validation_alias=_alias("fpt_fusion_screens_area_minutes", "fusion_screens_area_minutes"))pod_kind: Literal["mock", "fusion"] = "mock"pod_base_url: str = "http://127.0.0.1:3100"pod_rest_base: str = "/fscmRestApi/resources/11.13.18.05"scout_personas: dict[str, str] = Field(default_factory=lambda: {"default": "auditor_ro", "p2p": "buyer"})playwright_mode: Literal["stub", "live"] = "live"# Browser attempts on an Oracle Fusion pod run on this remote runner (automation/remote_runner) when set: for a host# whose network Oracle's edge refuses. Its token: vault remote_runner.token (FPT_SECRET_REMOTE_RUNNER_TOKEN).remote_runner_url: str = Field("", validation_alias=_alias("fpt_remote_runner_url", "remote_runner_url"))executor_backend: Literal["local"] = "local" # "docker" is not implemented: rejected at startup, never mid-runllm_local: Literal["stub", "ollama"] = "stub"ollama_url: str = "http://127.0.0.1:11434"ollama_model: str = "llava-phi3:latest"llm_frontier: Literal["off", "stub", "frontier"] = "off"frontier_base_url: str = ""# With no model settings saved in the app, an https FRONTIER_BASE_URL plus a key in the secrets (FPT_SECRET_FRONTIER_API_KEY)# switches the external model on at start-up, so a restart or a lost snapshot cannot silently turn the AI off.frontier_auto: bool = Field(True, validation_alias=_alias("fpt_frontier_auto", "frontier_auto"))frontier_model: str = "mistral-large-2512"frontier_timeout_s: float = Field(120.0, validation_alias=_alias("fpt_frontier_timeout_s", "frontier_timeout_s"))frontier_max_tokens: int = Field(4096, validation_alias=_alias("fpt_frontier_max_tokens", "frontier_max_tokens"))# extra JSON merged into every external-model request body, e.g. NVIDIA: {"chat_template_kwargs": {"enable_thinking": false}}# (a key set to null removes that key from the body, e.g. {"response_format": null})frontier_extra_json: str = Field("", validation_alias=_alias("fpt_frontier_extra_json", "frontier_extra_json"))local_llm_hosts: Annotated[list[str], NoDecode] = Field(default_factory=list)research_live: bool = Falseresearch_allowed_domains: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["docs.oracle.com"])research_max_modules: int = 12research_max_workers: int = 4research_cache_dir: Path | None = Noneseed_allowed: bool = False# Approved library cases: rewrite the YAML approval_status line and commit to library.git (off in tests/selftest)case_writeback: bool = Field(True, validation_alias=_alias("fpt_case_writeback", "case_writeback"))library_git_dir: Path = Field(default=ROOT / "library.git", validation_alias=_alias("fpt_library_git", "library_git_dir"))review_threshold: float = 0.6autonomy_min_labels: int = 50autonomy_min_agreement: float = 0.95autonomy_min_recall: float = 0.98evidence_retention_days: int = 30evidence_plaintext_ttl_hours: int = 24# the daily purge keeps the saved state small (platform/retention.py): step-by-step checkpoints of finished runs,# then whole run folders (reports, logs); run rows, events and the audit log are keptcheckpoint_retention_days: int = 7run_files_retention_days: int = 90# Playwright's plaintext run dirs the purge may clean (only fpt-* subdirs, i.e. the co-worker's own runs)plaintext_runs_dir: Path = Field(default=ROOT / "automation" / "results" / "runs")ticket_sink: Literal["file", "jira", "servicenow"] = "file"# live view ("Watch the test"): Chromium screencast frames dropped by the Playwright fixture hook, served as MJPEGlive_view_enabled: bool = Truelive_view_block_modules: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["HCM", "CX"]) # never streamed (personal data)live_view_stale_s: int = 15live_view_max_viewers: int = 5# chat ("Ask the co-worker"): one tool per turn; action tools only propose; local-only LLM taskschat_retention_days: int = 30chat_rate_per_minute: int = 20chat_action_ttl_s: int = 600# Hermes assistant ("Ask a question" answered by the Hermes Agent Space, OpenAI-compatible /v1). Off by default: the# built-in chat stays in use. The API key is a secret (vault HERMES_API_KEY / env FPT_SECRET_HERMES_API_KEY), never here.hermes_url: str = Field("", validation_alias=_alias("fpt_hermes_url", "hermes_url"))hermes_enabled: bool = Field(False, validation_alias=_alias("fpt_hermes_enabled", "hermes_enabled"))hermes_timeout_s: float = Field(120.0, validation_alias=_alias("fpt_hermes_timeout_s", "hermes_timeout_s"))hermes_rate_per_minute: int = Field(6, validation_alias=_alias("fpt_hermes_rate_per_minute", "hermes_rate_per_minute"))# Notifications: moments that need a person are kept in an outbox and POSTed to this webhook (for example an n8n# workflow that forwards them to Telegram). Empty = not sent anywhere (the app still lists them). The signing secret# is a secret (vault NOTIFY_SECRET / env FPT_SECRET_NOTIFY_SECRET or FPT_NOTIFY_SECRET), never a setting.notify_webhook_url: str = Field("", validation_alias=_alias("fpt_notify_webhook_url", "notify_webhook_url"))notify_interval_s: float = Field(5.0, validation_alias=_alias("fpt_notify_interval_s", "notify_interval_s"))# An Oracle Fusion TEST pod that exists from the environment: created at start-up when the saved data has none, so a# restart or a lost snapshot never removes it. Its test user comes from the secrets FPT_SECRET_FUSION_USERNAME and# FPT_SECRET_FUSION_PASSWORD (never from a setting). Unset = pods are managed in the app only.fusion_base_url: str = Field("", validation_alias=_alias("fpt_fusion_base_url", "fusion_base_url"))fusion_name: str = Field("Oracle Fusion test pod", validation_alias=_alias("fpt_fusion_name", "fusion_name"))fusion_environment: str = Field("test", validation_alias=_alias("fpt_fusion_environment", "fusion_environment"))fusion_modules: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["AP"], validation_alias=_alias("fpt_fusion_modules", "fusion_modules"))# its quarterly update (e.g. 26D): the research step reads that release's What's New. Applied when the pod has none.fusion_release: str = Field("", validation_alias=_alias("fpt_fusion_release", "fusion_release"))# its test user per business area, as JSON {"PO": "prc_impl", "INV": "scm_impl"}: same password (the secret), and the# areas not named use the pod's test user. A user only sees the tasks of its own roles.fusion_area_users: str = Field("", validation_alias=_alias("fpt_fusion_area_users", "fusion_area_users"))patch_watch_enabled: bool = Truepatch_watch_interval_s: int = 300patch_watch_autostart: bool = Falsescheduler_tick_s: int = 30# the IANA time zone new schedules use for their clock times (each schedule can name its own)tz: str = Field("Asia/Kolkata", validation_alias=_alias("fpt_tz", "tz"))@field_validator("research_allowed_domains", "cors_origins", "local_llm_hosts", "live_view_block_modules", "fusion_modules", mode="before")@classmethoddef _csv(cls, v):if isinstance(v, str):v = v.strip()if v.startswith("["):import jsonreturn json.loads(v)return [x.strip() for x in v.split(",") if x.strip()]return v@classmethoddef settings_customise_sources(cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource,env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource,file_secret_settings: PydanticBaseSettingsSource):return (init_settings, env_settings, dotenv_settings, YamlConfigSettingsSource(settings_cls))# ---- derived paths (everything runtime lives under FPT_HOME: one deployment per client)@propertydef home(self) -> Path:return Path(self.fpt_home).resolve()def path(self, *parts: str) -> Path:return self.home.joinpath(*parts)@propertydef db_path(self) -> Path:return self.path("fpt.sqlite")@propertydef checkpoint_path(self) -> Path:return self.path("checkpoints.sqlite")@propertydef research_cache(self) -> Path:return Path(self.research_cache_dir) if self.research_cache_dir else self.path("research-cache")@propertydef runs_dir(self) -> Path:return self.path("runs")def persona_for(self, pack_id: str) -> str:return self.scout_personas.get(pack_id) or self.scout_personas.get("default", "auditor_ro")def public_dict(self) -> dict:d = self.model_dump(mode="json")d["frontier_configured"] = bool(self.frontier_base_url) and self.llm_frontier != "off"d["version"] = VERSIONd["target"] = MOCK_BANNERreturn ddef ensure_dirs(self) -> None:for p in ("runs", "evidence", "tickets", "research-cache", "staging/specs", "secrets", "logs"):self.path(p).mkdir(parents=True, exist_ok=True)@lru_cache(maxsize=1)def get_settings() -> Settings:return Settings()def reset_settings() -> None:get_settings.cache_clear()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351"""Settings: config/coworker.yaml (non-secret) < .env < environment (env wins) < explicit kwargs (tests).Validated with pydantic-settings. Secrets are NOT settings: they come from the vault only."""from __future__ import annotationsimport osfrom functools import lru_cachefrom pathlib import Pathfrom typing import Annotated, Literalfrom pydantic import AliasChoices, Field, field_validatorfrom pydantic_settings import (BaseSettings, PydanticBaseSettingsSource, SettingsConfigDict,YamlConfigSettingsSource, NoDecode)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 reporoot); "" when it cannot know, and then nothing compares against it."""import revals = [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:passfor v in vals:v = v.strip().lower()if re.fullmatch(r"[0-9a-f]{7,40}", v):return vreturn ""def _alias(*names: str):return AliasChoices(*names)class Settings(BaseSettings):model_config = SettingsConfigDict(env_file=str(ROOT / ".env"), env_file_encoding="utf-8", extra="ignore",yaml_file=str(CONFIG_YAML), case_sensitive=False, populate_by_name=True)fpt_home: Path = Field(default=ROOT / "var")api_host: str = Field("127.0.0.1", validation_alias=_alias("fpt_api_host", "api_host"))api_port: int = Field(8800, validation_alias=_alias("fpt_api_port", "api_port"))cors_origins: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["http://127.0.0.1:5173", "http://localhost:5173"],validation_alias=_alias("fpt_cors_origins", "cors_origins"))cookie_secure: Literal["auto", "always", "never"] = Field("auto", validation_alias=_alias("fpt_cookie_secure", "cookie_secure"))session_ttl_hours: int = 12login_max_attempts: int = 5login_window_s: int = 300web_dist: Path = Field(default=ROOT / "web" / "dist", validation_alias=_alias("fpt_web_dist", "web_dist"))oidc_issuer: str = ""# shown in the menu and on the sign-in page (a reseller or customer can set its own)product_name: str = Field("Astra", validation_alias=_alias("fpt_product_name", "product_name"))org_name: str = Field("", validation_alias=_alias("fpt_org_name", "org_name"))# ---- Supabase (optional): identity provider for sign-in / registration, and storage for the encrypted state archive.# The service key is NOT a setting (it would show in /api/config): it comes from SUPABASE_SERVICE_KEY or the vault.supabase_url: str = ""supabase_anon_key: str = "" # the public ("anon" / publishable) keysupabase_bucket: str = "patch-coworker"registration_enabled: bool = Field(True, validation_alias=_alias("fpt_registration", "registration_enabled"))register_role: Literal["viewer", "consultant", "qa_approver"] = Field("viewer", validation_alias=_alias("fpt_register_role", "register_role"))# blank, "a@x.com, b@x.com" or a JSON list are all accepted (a blank value must never stop the start-up)# the address people open the app at, used for links in e-mails (never taken from request headers when set)public_url: str = Field("", validation_alias=_alias("fpt_public_url", "public_url"))# behind a hosting proxy (Hugging Face, Render): read the visitor's address from X-Forwarded-For so sign-in limits# count per visitor, not per proxy. Only switch on where the app is reachable through that proxy alone.# the interactive API docs (/api/docs, /api/openapi.json): on for development, off on a public serverapi_docs: bool = Field(True, validation_alias=_alias("fpt_api_docs", "api_docs"))trust_proxy: bool = Field(False, validation_alias=_alias("fpt_trust_proxy", "trust_proxy"))admin_emails: Annotated[list[str], NoDecode] = Field(default_factory=list, validation_alias=_alias("fpt_admin_emails", "admin_emails"))@field_validator("browser_runs", "research_cache_dir", mode="before")@classmethoddef _blank_is_unset(cls, v):"""An empty value (FPT_BROWSER_RUNS= in a .env file) means "not set": use the automatic default."""return None if isinstance(v, str) and not v.strip() else v@field_validator("admin_emails", mode="before")@classmethoddef _emails(cls, v):if v is None:return []if isinstance(v, str):t = v.strip()if not t:return []if t.startswith("["):import jsontry:v = json.loads(t)except ValueError:v = t.strip("[]").split(",")else:v = t.split(",")cleaned = [str(x).strip().strip("\"'").lower() for x in v]return [x for x in cleaned if x]state_sync: bool = Field(True, validation_alias=_alias("fpt_state_sync", "state_sync"))state_sync_interval_s: int = Field(60, validation_alias=_alias("fpt_state_sync_interval", "state_sync_interval_s"))# how many earlier archives the bucket keeps as state/history/<time>.bin (0 = none), so a bad save can be undonestate_history_keep: int = Field(5, ge=0, le=50, validation_alias=_alias("fpt_state_history", "state_history_keep"))# at shutdown, how long a running test run may take to reach its next step (where it can stop cleanly and continue# after the restart) before the last save goes ahead without it. Keep it under the host's stop grace period.shutdown_run_wait_s: int = Field(20, ge=0, le=300, validation_alias=_alias("fpt_shutdown_run_wait_s", "shutdown_run_wait_s"))# A site allowed to show this application inside its own page (a private Hugging Face Space is only reachable that# way). Empty = never framed by another site. Setting it relaxes the session cookies to SameSite=None.embed_origin: str = Field("", validation_alias=_alias("fpt_embed_origin", "embed_origin"))@field_validator("embed_origin")@classmethoddef _embed_origin(cls, v: str) -> str:import rev = (v or "").strip().rstrip("/")if v and not re.fullmatch(r"https://[A-Za-z0-9.-]{1,200}(:\d{1,5})?", v):raise ValueError("FPT_EMBED_ORIGIN must look like https://host")return v# Full browser runs need about 1.5 GB for Chromium. Unset = decided from the container's memory limit.browser_runs: bool | None = Field(None, validation_alias=_alias("fpt_browser_runs", "browser_runs"))@propertydef browser_runs_allowed(self) -> bool:if self.browser_runs is not None:return self.browser_runsfor p in ("/sys/fs/cgroup/memory.max", "/sys/fs/cgroup/memory/memory.limit_in_bytes"):try:raw = Path(p).read_text().strip()except OSError:continuereturn not (raw.isdigit() and int(raw) < 1_400_000_000)return True# ---- orchestration (Temporal = durable outer workflow; LangGraph = agent engine / offline fallback)orchestrator: Literal["temporal", "langgraph"] = Field("temporal", validation_alias=_alias("fpt_orchestrator", "orchestrator"))temporal_address: str = "127.0.0.1:7233"temporal_namespace: str = "default"temporal_task_queue: str = "fpt-main"temporal_browser_queue: str = "fpt-browser"temporal_ui_url: str = "http://127.0.0.1:8233"embedded_worker: bool = Field(False, validation_alias=_alias("fpt_embedded_worker", "embedded_worker"))approval_remind_after_s: int = Field(24 * 3600, validation_alias=_alias("approval_remind_after", "approval_remind_after_s"))approval_escalate_after_s: int = Field(72 * 3600, validation_alias=_alias("approval_escalate_after", "approval_escalate_after_s"))exec_chunk_size: int = 10# Fusion pods with an AI model on: how many NEW scenarios the model writes per business area in each test run# (dry-run on the pod, then offered at the approval gate). 0 turns it off.fusion_ai_scenarios: int = Field(4, validation_alias=_alias("fpt_fusion_ai_scenarios", "fusion_ai_scenarios"))# dry-run the AI's scenarios on the pod BEFORE approval (they save there, then again in the test run). Off: nothing# runs on the pod until a person approves; every scenario that passes the checks against the pod's screens is offered# and the test run after approval shows where each one stops# Oracle AI Agent Studio: how often the release watch reads Oracle's What's New (hours; 0 = only when asked)agent_studio_watch_hours: float = Field(24.0, validation_alias=_alias("fpt_agent_studio_watch_hours", "agent_studio_watch_hours"))fusion_ai_dry_run: bool = Field(False, validation_alias=_alias("fpt_fusion_ai_dry_run", "fusion_ai_dry_run"))# screens the scout reads per business area (quick actions and work area tasks a test starts from)fusion_screens_per_area: int = Field(8, validation_alias=_alias("fpt_fusion_screens_per_area", "fusion_screens_per_area"))# per area, the AI designs fusion_ai_scenarios plus one per change the update switches on by itself, up to thisfusion_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 timefusion_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 resultsfusion_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 browsersfusion_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"))# before a live run's scenarios, each area's canary (tests/cases/CANARY-<AREA>.yaml) runs its business actions once;# the scenarios that use an action the canary found broken are reported as blocked, not run, not product defectsfusion_canary: bool = Field(True, validation_alias=_alias("fpt_fusion_canary", "fusion_canary"))# the remote runner drives one browser job at a time: a run or screen read that finds it busy waits this long for itremote_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 itselffusion_screens_on_setup: bool = Field(True, validation_alias=_alias("fpt_fusion_screens_on_setup", "fusion_screens_on_setup"))# one area's screen reading stops after this many minutes (a user without access to an area only meets timeouts)fusion_screens_area_minutes: int = Field(20, validation_alias=_alias("fpt_fusion_screens_area_minutes", "fusion_screens_area_minutes"))pod_kind: Literal["mock", "fusion"] = "mock"pod_base_url: str = "http://127.0.0.1:3100"pod_rest_base: str = "/fscmRestApi/resources/11.13.18.05"scout_personas: dict[str, str] = Field(default_factory=lambda: {"default": "auditor_ro", "p2p": "buyer"})playwright_mode: Literal["stub", "live"] = "live"# Browser attempts on an Oracle Fusion pod run on this remote runner (automation/remote_runner) when set: for a host# whose network Oracle's edge refuses. Its token: vault remote_runner.token (FPT_SECRET_REMOTE_RUNNER_TOKEN).remote_runner_url: str = Field("", validation_alias=_alias("fpt_remote_runner_url", "remote_runner_url"))executor_backend: Literal["local"] = "local" # "docker" is not implemented: rejected at startup, never mid-runllm_local: Literal["stub", "ollama"] = "stub"ollama_url: str = "http://127.0.0.1:11434"ollama_model: str = "llava-phi3:latest"llm_frontier: Literal["off", "stub", "frontier"] = "off"frontier_base_url: str = ""# With no model settings saved in the app, an https FRONTIER_BASE_URL plus a key in the secrets (FPT_SECRET_FRONTIER_API_KEY)# switches the external model on at start-up, so a restart or a lost snapshot cannot silently turn the AI off.frontier_auto: bool = Field(True, validation_alias=_alias("fpt_frontier_auto", "frontier_auto"))frontier_model: str = "mistral-large-2512"frontier_timeout_s: float = Field(120.0, validation_alias=_alias("fpt_frontier_timeout_s", "frontier_timeout_s"))frontier_max_tokens: int = Field(4096, validation_alias=_alias("fpt_frontier_max_tokens", "frontier_max_tokens"))# extra JSON merged into every external-model request body, e.g. NVIDIA: {"chat_template_kwargs": {"enable_thinking": false}}# (a key set to null removes that key from the body, e.g. {"response_format": null})frontier_extra_json: str = Field("", validation_alias=_alias("fpt_frontier_extra_json", "frontier_extra_json"))local_llm_hosts: Annotated[list[str], NoDecode] = Field(default_factory=list)research_live: bool = Falseresearch_allowed_domains: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["docs.oracle.com"])research_max_modules: int = 12research_max_workers: int = 4research_cache_dir: Path | None = Noneseed_allowed: bool = False# Approved library cases: rewrite the YAML approval_status line and commit to library.git (off in tests/selftest)case_writeback: bool = Field(True, validation_alias=_alias("fpt_case_writeback", "case_writeback"))library_git_dir: Path = Field(default=ROOT / "library.git", validation_alias=_alias("fpt_library_git", "library_git_dir"))review_threshold: float = 0.6autonomy_min_labels: int = 50autonomy_min_agreement: float = 0.95autonomy_min_recall: float = 0.98evidence_retention_days: int = 30evidence_plaintext_ttl_hours: int = 24# the daily purge keeps the saved state small (platform/retention.py): step-by-step checkpoints of finished runs,# then whole run folders (reports, logs); run rows, events and the audit log are keptcheckpoint_retention_days: int = 7run_files_retention_days: int = 90# Playwright's plaintext run dirs the purge may clean (only fpt-* subdirs, i.e. the co-worker's own runs)plaintext_runs_dir: Path = Field(default=ROOT / "automation" / "results" / "runs")ticket_sink: Literal["file", "jira", "servicenow"] = "file"# live view ("Watch the test"): Chromium screencast frames dropped by the Playwright fixture hook, served as MJPEGlive_view_enabled: bool = Truelive_view_block_modules: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["HCM", "CX"]) # never streamed (personal data)live_view_stale_s: int = 15live_view_max_viewers: int = 5# assisted sign-in (a pod whose sign-in goes through the company's identity provider): the browser a person signs in# with closes after this many minutes without input (platform/assisted_signin.py)sign_in_idle_minutes: int = Field(15, validation_alias=_alias("fpt_sign_in_idle_minutes", "sign_in_idle_minutes"))# chat ("Ask the co-worker"): one tool per turn; action tools only propose; local-only LLM taskschat_retention_days: int = 30chat_rate_per_minute: int = 20chat_action_ttl_s: int = 600# Hermes assistant ("Ask a question" answered by the Hermes Agent Space, OpenAI-compatible /v1). Off by default: the# built-in chat stays in use. The API key is a secret (vault HERMES_API_KEY / env FPT_SECRET_HERMES_API_KEY), never here.hermes_url: str = Field("", validation_alias=_alias("fpt_hermes_url", "hermes_url"))hermes_enabled: bool = Field(False, validation_alias=_alias("fpt_hermes_enabled", "hermes_enabled"))hermes_timeout_s: float = Field(120.0, validation_alias=_alias("fpt_hermes_timeout_s", "hermes_timeout_s"))hermes_rate_per_minute: int = Field(6, validation_alias=_alias("fpt_hermes_rate_per_minute", "hermes_rate_per_minute"))# Notifications: moments that need a person are kept in an outbox and POSTed to this webhook (for example an n8n# workflow that forwards them to Telegram). Empty = not sent anywhere (the app still lists them). The signing secret# is a secret (vault NOTIFY_SECRET / env FPT_SECRET_NOTIFY_SECRET or FPT_NOTIFY_SECRET), never a setting.notify_webhook_url: str = Field("", validation_alias=_alias("fpt_notify_webhook_url", "notify_webhook_url"))notify_interval_s: float = Field(5.0, validation_alias=_alias("fpt_notify_interval_s", "notify_interval_s"))# An Oracle Fusion TEST pod that exists from the environment: created at start-up when the saved data has none, so a# restart or a lost snapshot never removes it. Its test user comes from the secrets FPT_SECRET_FUSION_USERNAME and# FPT_SECRET_FUSION_PASSWORD (never from a setting). Unset = pods are managed in the app only.fusion_base_url: str = Field("", validation_alias=_alias("fpt_fusion_base_url", "fusion_base_url"))fusion_name: str = Field("Oracle Fusion test pod", validation_alias=_alias("fpt_fusion_name", "fusion_name"))fusion_environment: str = Field("test", validation_alias=_alias("fpt_fusion_environment", "fusion_environment"))fusion_modules: Annotated[list[str], NoDecode] = Field(default_factory=lambda: ["AP"], validation_alias=_alias("fpt_fusion_modules", "fusion_modules"))# its quarterly update (e.g. 26D): the research step reads that release's What's New. Applied when the pod has none.fusion_release: str = Field("", validation_alias=_alias("fpt_fusion_release", "fusion_release"))# its test user per business area, as JSON {"PO": "prc_impl", "INV": "scm_impl"}: same password (the secret), and the# areas not named use the pod's test user. A user only sees the tasks of its own roles.fusion_area_users: str = Field("", validation_alias=_alias("fpt_fusion_area_users", "fusion_area_users"))patch_watch_enabled: bool = Truepatch_watch_interval_s: int = 300patch_watch_autostart: bool = Falsescheduler_tick_s: int = 30# the IANA time zone new schedules use for their clock times (each schedule can name its own)tz: str = Field("Asia/Kolkata", validation_alias=_alias("fpt_tz", "tz"))@field_validator("research_allowed_domains", "cors_origins", "local_llm_hosts", "live_view_block_modules", "fusion_modules", mode="before")@classmethoddef _csv(cls, v):if isinstance(v, str):v = v.strip()if v.startswith("["):import jsonreturn json.loads(v)return [x.strip() for x in v.split(",") if x.strip()]return v@classmethoddef settings_customise_sources(cls, settings_cls: type[BaseSettings], init_settings: PydanticBaseSettingsSource,env_settings: PydanticBaseSettingsSource, dotenv_settings: PydanticBaseSettingsSource,file_secret_settings: PydanticBaseSettingsSource):return (init_settings, env_settings, dotenv_settings, YamlConfigSettingsSource(settings_cls))# ---- derived paths (everything runtime lives under FPT_HOME: one deployment per client)@propertydef home(self) -> Path:return Path(self.fpt_home).resolve()def path(self, *parts: str) -> Path:return self.home.joinpath(*parts)@propertydef db_path(self) -> Path:return self.path("fpt.sqlite")@propertydef checkpoint_path(self) -> Path:return self.path("checkpoints.sqlite")@propertydef research_cache(self) -> Path:return Path(self.research_cache_dir) if self.research_cache_dir else self.path("research-cache")@propertydef runs_dir(self) -> Path:return self.path("runs")def persona_for(self, pack_id: str) -> str:return self.scout_personas.get(pack_id) or self.scout_personas.get("default", "auditor_ro")def public_dict(self) -> dict:d = self.model_dump(mode="json")d["frontier_configured"] = bool(self.frontier_base_url) and self.llm_frontier != "off"d["version"] = VERSIONd["target"] = MOCK_BANNERreturn ddef ensure_dirs(self) -> None:for p in ("runs", "evidence", "tickets", "research-cache", "staging/specs", "secrets", "logs"):self.path(p).mkdir(parents=True, exist_ok=True)@lru_cache(maxsize=1)def get_settings() -> Settings:return Settings()def reset_settings() -> None:get_settings.cache_clear()
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677"""build_graph(services, checkpointer): the co-worker's LangGraph (15 work nodes + 4 routing functions, DESIGN.md section 4).Exactly one retry, owned by the graph; Playwright always --retries=0. GO/NO-GO only from reports/generate_report.py."""from __future__ import annotationsimport sqlite3from pathlib import Pathfrom langgraph.checkpoint.sqlite import SqliteSaverfrom langgraph.graph import END, START, StateGraphfrom ..state import CoworkerStatefrom .nodes import data, design, execute, report, research, triagefrom .runtime import wrapMAX_RETRIES = 1def after_execute(state) -> str:if state.get("retry_count", 0) >= MAX_RETRIES:return "triage"return "self_heal" if state.get("failures") else "reporter"def after_triage(state) -> str:return "human_review" if state.get("review_items") else "reporter"def after_review(state) -> str:review = state.get("review") or {}return "ticket" if any((v or {}).get("confirmed") == "real_defect" for v in review.values()) else "reporter"NODE_FUNCS = [("scout", research.scout), ("research_module", research.research_module), ("synthesizer", research.synthesizer),("test_generator", design.test_generator), ("approval_gate", design.approval_gate), ("data_planner", data.data_planner),("data_executor", data.data_executor), ("script_builder", design.script_builder), ("executor", execute.executor),("self_heal", execute.self_heal), ("triage", triage.triage), ("human_review", triage.human_review),("ticket", triage.ticket), ("reporter", report.reporter), ("learner", report.learner),]EDGES = [("research_module", "synthesizer"), ("synthesizer", "test_generator"), ("test_generator", "approval_gate"),("approval_gate", "data_planner"), ("data_planner", "data_executor"), ("data_executor", "script_builder"),("script_builder", "executor"), ("self_heal", "executor"), ("ticket", "reporter"), ("reporter", "learner")]def build_graph(svc, checkpointer=None):g = StateGraph(CoworkerState)for name, fn in NODE_FUNCS:g.add_node(name, wrap(name, fn, svc))g.add_edge(START, "scout")g.add_conditional_edges("scout", research.dispatch_research, ["research_module", "synthesizer"])for a, b in EDGES:g.add_edge(a, b)g.add_conditional_edges("executor", after_execute, ["reporter", "self_heal", "triage"])g.add_conditional_edges("triage", after_triage, ["human_review", "reporter"])g.add_conditional_edges("human_review", after_review, ["ticket", "reporter"])g.add_edge("learner", END)return g.compile(checkpointer=checkpointer)def sqlite_checkpointer(path: Path) -> SqliteSaver:Path(path).parent.mkdir(parents=True, exist_ok=True)conn = sqlite3.connect(str(path), check_same_thread=False)return SqliteSaver(conn)def run_config(run_id: str, cfg) -> dict:return {"configurable": {"thread_id": run_id}, "max_concurrency": cfg.research_max_workers, "recursion_limit": 60}GRAPH_SPEC = {"nodes": [n for n, _ in NODE_FUNCS],"edges": [["START", "scout"], ["scout", "research_module"], ["scout", "synthesizer"]] + [list(e) for e in EDGES]+ [["executor", "reporter"], ["executor", "self_heal"], ["executor", "triage"], ["triage", "human_review"],["triage", "reporter"], ["human_review", "ticket"], ["human_review", "reporter"], ["learner", "END"]],"routers": {"dispatch_research": "scout", "after_execute": "executor", "after_triage": "triage", "after_review": "human_review"},"gates": ["approval_gate", "human_review"]}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081"""build_graph(services, checkpointer): the co-worker's LangGraph (16 work nodes + 4 routing functions, DESIGN.md section 4).Exactly one retry, owned by the graph; Playwright always --retries=0. GO/NO-GO only from reports/generate_report.py."""from __future__ import annotationsimport sqlite3from pathlib import Pathfrom langgraph.checkpoint.sqlite import SqliteSaverfrom langgraph.graph import END, START, StateGraphfrom ..state import CoworkerStatefrom .nodes import data, design, execute, report, research, signin, triagefrom .runtime import wrapMAX_RETRIES = 1def after_execute(state) -> str:if state.get("sign_in_pending"): # assisted sign-in: the session expired mid-run, a person signs in againreturn "sign_in_gate"if state.get("retry_count", 0) >= MAX_RETRIES:return "triage"return "self_heal" if state.get("failures") else "reporter"def after_triage(state) -> str:return "human_review" if state.get("review_items") else "reporter"def after_review(state) -> str:review = state.get("review") or {}return "ticket" if any((v or {}).get("confirmed") == "real_defect" for v in review.values()) else "reporter"NODE_FUNCS = [("scout", research.scout), ("research_module", research.research_module), ("synthesizer", research.synthesizer),("test_generator", design.test_generator), ("approval_gate", design.approval_gate), ("data_planner", data.data_planner),("data_executor", data.data_executor), ("script_builder", design.script_builder), ("sign_in_gate", signin.sign_in_gate),("executor", execute.executor),("self_heal", execute.self_heal), ("triage", triage.triage), ("human_review", triage.human_review),("ticket", triage.ticket), ("reporter", report.reporter), ("learner", report.learner),]EDGES = [("research_module", "synthesizer"), ("synthesizer", "test_generator"), ("test_generator", "approval_gate"),("approval_gate", "data_planner"), ("data_planner", "data_executor"), ("data_executor", "script_builder"),("script_builder", "sign_in_gate"), ("sign_in_gate", "executor"), ("self_heal", "executor"), ("ticket", "reporter"), ("reporter", "learner")]def build_graph(svc, checkpointer=None):g = StateGraph(CoworkerState)for name, fn in NODE_FUNCS:g.add_node(name, wrap(name, fn, svc))g.add_edge(START, "scout")g.add_conditional_edges("scout", research.dispatch_research, ["research_module", "synthesizer"])for a, b in EDGES:g.add_edge(a, b)g.add_conditional_edges("executor", after_execute, ["reporter", "self_heal", "triage", "sign_in_gate"])g.add_conditional_edges("triage", after_triage, ["human_review", "reporter"])g.add_conditional_edges("human_review", after_review, ["ticket", "reporter"])g.add_edge("learner", END)return g.compile(checkpointer=checkpointer)def sqlite_checkpointer(path: Path) -> SqliteSaver:Path(path).parent.mkdir(parents=True, exist_ok=True)conn = sqlite3.connect(str(path), check_same_thread=False)return SqliteSaver(conn)def run_config(run_id: str, cfg) -> dict:return {"configurable": {"thread_id": run_id}, "max_concurrency": cfg.research_max_workers, "recursion_limit": 60}GRAPH_SPEC = {"nodes": [n for n, _ in NODE_FUNCS],"edges": [["START", "scout"], ["scout", "research_module"], ["scout", "synthesizer"]] + [list(e) for e in EDGES]+ [["executor", "reporter"], ["executor", "self_heal"], ["executor", "triage"], ["executor", "sign_in_gate"],["triage", "human_review"],["triage", "reporter"], ["human_review", "ticket"], ["human_review", "reporter"], ["learner", "END"]],"routers": {"dispatch_research": "scout", "after_execute": "executor", "after_triage": "triage", "after_review": "human_review"},"gates": ["approval_gate", "sign_in_gate", "human_review"]}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542"""AI-written scenarios for a real Oracle Fusion pod (part of the design phase).After test_generator has chosen the library cases, and only when the run targets a registered Fusion pod AND anexternal AI model is switched on, the step writer (platform/step_writer.py) designs a few NEW scenarios for each businessarea from the area's captured screens (public labels only; the data rule of the step writer is unchanged), writes theirsteps and checks them. Each accepted draft is staged under FPT_HOME/staging/steps/<run_id>/ with its Playwright entrypoint under FPT_HOME/staging/specs/<run_id>/, and offered at the approval gate (origin "ai") with its steps in plainlanguage. Nothing runs on the pod before a person approves: the test run after approval shows where each one stops.With FPT_FUSION_AI_DRY_RUN on, the drafts are first DRY-RUN on the pod with the step runner (saving there too):- dry run passed -> offered at the approval gate with the dry-run result;- dry run failed -> NOT offered as runnable; shown at the gate with the failing step and its message.Approving promotes the draft into the script library (tests/cases/<ID>.yaml + its entry spec, committed to library.git);rejected drafts stay in staging. Nothing here runs for the practice pod, or when no AI model is configured."""from __future__ import annotationsimport jsonimport reimport subprocessimport threadingfrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timezonefrom pathlib import Pathfrom urllib.parse import urlparseimport yamlfrom ...adapters import playwright as pwfrom ...config import ROOTfrom ...llm.base import Routefrom ...platform import procs, step_writerfrom ...platform.rundb import now_isoANSI = re.compile(r"\x1b\[[0-9;]*m")STEP_TITLE = re.compile(r"^\d+\.\s")PROMOTE_ROOT: Path | None = None # tests point it at a folder; otherwise the persistent library under FPT_HOMEdef library_root(svc) -> Path:"""Where approved scenarios (AI-written, or brought by the client) are kept: FPT_HOME/library, so they survive arestart and a new deployment (the app folder is rebuilt from the code; FPT_HOME is saved). Same layout as the repo:tests/cases/<ID>.yaml and automation/tests/fusion/steps/<ID>.spec.ts."""return Path(PROMOTE_ROOT) if PROMOTE_ROOT else svc.cfg.path("library")def write_library_entry(root: Path, case_id: str, priority: str | None) -> Path:"""The Playwright entry point of a library scenario: it reads its YAML from the library folder."""spec = Path(root) / "automation" / "tests" / "fusion" / "steps" / f"{case_id}.spec.ts"spec.parent.mkdir(parents=True, exist_ok=True)spec.write_text(step_writer.library_entry_spec(case_id, priority, Path(root) / "tests" / "cases"), encoding="utf-8")return specAI_ORIGIN = "ai"def _note(svc, run_id: str, message: str, **extra) -> None:svc.db.add_event(run_id, "test_generator", "ai_scenarios", {"message": message, **extra})svc.audit.append("ai_scenarios.note", actor="system", run_id=run_id, node="test_generator", summary=message[:200])def _pod_host(svc, pod_id: int) -> str:row = svc.db.one("SELECT base_url FROM pods WHERE id=?", (pod_id,))return urlparse((row or {}).get("base_url") or "").hostname or "the pod"def specs_dir(svc, run_id: str) -> Path:return svc.cfg.path("staging", "specs", run_id)# ====================================================================== dry rundef _failed_step(steps: list[dict]) -> tuple[str | None, str | None]:"""(title of the first scenario step that failed, its error message) from a Playwright JSON result's steps."""for s in steps or []:title = str(s.get("title") or "")inner_t, inner_m = _failed_step(s.get("steps") or [])if s.get("error") or inner_t:if STEP_TITLE.match(title):msg = (s.get("error") or {}).get("message") or inner_mreturn title, ANSI.sub("", str(msg or ""))[:1200] or Noneif inner_t:return inner_t, inner_mreturn None, Nonedef read_dry_run(report_file: Path, ids: list[str]) -> dict[str, dict]:"""{id: {status, failed_step, message}} from the dry run's Playwright JSON (stub or live)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out: dict[str, dict] = {}for spec in pw._walk_specs(data.get("suites")):tags = [t.lstrip("@") for t in spec.get("tags") or []]cid = next((i for i in ids if i in tags or spec.get("id") == i or str(spec.get("title", "")).startswith(i + " ")), None)if not cid:continuefor t in spec.get("tests") or []:res = (t.get("results") or [{}])[-1]status = res.get("status") or ("passed" if t.get("status") == "expected" else "failed")step, msg = _failed_step(res.get("steps") or [])if status != "passed" and not msg:msg = ANSI.sub("", "\n".join(e.get("message", "") for e in res.get("errors") or []))[:1200] or Noneout[cid] = {"status": "passed" if status == "passed" else "failed", "failed_step": step, "message": msg}for i in ids:out.setdefault(i, {"status": "failed", "failed_step": None, "message": "the dry run did not report this scenario"})return outdef dry_run(state, svc, pod_id: int, drafts: list[dict]) -> None:"""Runs the staged drafts once on the pod (step runner, playwright.fusion.config.ts, 'drafts' project) and attaches{status, failed_step, message, pod, at, simulated} to each draft. In a quick simulation (stub mode) nothing runs onthe pod: the result says so and is never presented as a pod result."""run_id = state["run_id"]mode = state.get("playwright_mode") or svc.cfg.playwright_modeids = [d["id"] for d in drafts]host = _pod_host(svc, pod_id)at = now_iso()run_dir = svc.run_dir(run_id)try:cred_env: dict = {}if mode == "live":from ...platform.pods import PodRegistryfor m in sorted({d["module"] for d in drafts}):cred_env.update(svc.vault.executor_env(m))cred_env.update(PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).executor_env(pod_id, run_id) or {})svc.db.add_event(run_id, "test_generator", "ai_scenarios",{"message": f"dry run of {len(ids)} AI-written scenario(s) on {host if mode == 'live' else 'the simulation'}","scenarios": ", ".join(ids)})# the same road as a test attempt: the remote browser runner when one is set (this server's network may be one# Oracle's edge refuses), else this serverfrom .execute import FUSION_CONFIG, attempt_timeout_s, run_passres = run_pass({"run_id": run_id, "attempt": 0, "tag": "-dryrun", "ids": ids, "mode": mode,"out_file": str(run_dir / "ai-dry-run.json"), "stub_knobs": state.get("stub_knobs"),"drafts_dir": str(specs_dir(svc, run_id)), "library_dir": None, "overrides": None, "cred_env": cred_env,"run_dir": str(run_dir), "config": FUSION_CONFIG, "timeout_s": attempt_timeout_s(svc.cfg, len(ids))}, svc)results = read_dry_run(Path(res["file"]), ids)if mode == "live": # the values Fusion accepted are tried first next time on this podPodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).learn_test_data(pod_id, pw.testdata_used_file(run_dir / "ai-dry-run.json"))if res.get("run_dir"):try: # the dry run's traces and screenshots go to the encrypted evidence store like any attempt'ssvc.evidence.ingest_dir(run_id, -1, Path(res["run_dir"]), pw.attachments_by_case(Path(res["file"])))except Exception as e: # noqa: BLE001svc.audit.append("evidence.error", actor="system", run_id=run_id, summary=str(e)[:300])except Exception as e: # noqa: BLE001 - a dry run that cannot start fails every draft, never the test runresults = {i: {"status": "failed", "failed_step": None, "message": f"the dry run could not run: {str(e)[:500]}"} for i in ids}for d in drafts:d["dry_run"] = {**results[d["id"]], "pod": host if mode == "live" else None, "at": at, "simulated": mode != "live"}d["runnable"] = results[d["id"]]["status"] == "passed"def scenario_count(base: int, switched_on: int, cap: int, screens: int) -> int:"""How many scenarios to ask for in one area: the base, plus one per change the update switches on by itself, atmost `cap`, and at most two per screen read (more would only repeat the same screen)."""return max(1, min(base + switched_on, cap, 2 * screens))def _read_missing_screens(state, svc, reg, pod_id: int, areas: list[str]) -> None:"""A full browser run reads, before designing, the screens of the areas it tests that have none on this pod yet orwere read on another release (one browser session, a few minutes per area). A quick simulation never opens the pod."""if state.get("playwright_mode") != "live":returnfrom ...platform.pods import PodErrorrun_id = state["run_id"]if reg.screens_busy(pod_id): # read in the background since the pod was set up: wait for it rather than read twice_note(svc, run_id, "The pod's screens are being read in the background (started when its areas were discovered); waiting for them.")reg.wait_for_screens(pod_id)missing = reg.areas_to_read(pod_id, areas)if not missing:return_note(svc, run_id, f"Reading the screens of {', '.join(missing)} on the pod before designing ({int(svc.cfg.fusion_workers or 1)} "f"at a time; nothing is saved).")try:_, job = reg.start_screens(pod_id, "scout", missing, max_tasks=int(svc.cfg.fusion_screens_per_area or 8))except PodError as e:_note(svc, run_id, f"The screens could not be read now: {e}")returnafter = reg.read_screens(pod_id, job, "scout").get("screens") or {}if after.get("state") == "failed":_note(svc, run_id, f"Reading the screens did not finish: {after.get('error')}")returngot = {a: len((after.get("areas") or {}).get(a, {}).get("captured") or []) for a in missing}_note(svc, run_id, "Screens read: " + ", ".join(f"{a} {n}" for a, n in got.items()) + ".")# end-to-end business processes that cross business areas: designed when a run tests every area of one of themCROSS_AREA_FLOWS = [{"name": "Procure-to-Pay", "areas": ["PO", "AP"], "id_area": "PO","steps": "requisition or purchase order, receipt, supplier invoice matched to the order, payment"},{"name": "Order-to-Cash", "areas": ["OM", "AR"], "id_area": "OM","steps": "sales order, shipment, customer invoice, receipt applied to the invoice"},{"name": "Record-to-Report", "areas": ["AP", "AR", "GL"], "id_area": "GL","steps": "subledger transactions accounted, journals posted to the ledger, period close checks"},]def _write_intents(svc, run_id: str, area: str, intents: list[dict], screens: list[dict], example: str, taken: set[str],drafts: list[dict], placeholders: list[str], lock=None) -> None:"""Steps for each designed intent (one screen, or a flow across several), checked, staged for the dry run. Areas arewritten at the same time (one thread each): `lock` keeps their scenario numbers and staged files apart."""lock = lock or threading.Lock()by_task = {step_writer.norm_task(s["task"]): s for s in screens}for it in intents:flow = [by_task[step_writer.norm_task(t)] for t in it.get("flow") or [] if step_writer.norm_task(t) in by_task]r = step_writer.write_steps(svc, it, by_task[step_writer.norm_task(it["task"])], example, run_id=run_id,placeholders=placeholders, flow_screens=flow if len(flow) > 1 else None)base = {"title": it["title"], "module": area, "priority": it.get("priority") or "P2", "type": it.get("type"),"why": it.get("why") or "", "task": it["task"], "model": r.get("model") or it.get("model"),"written_by": "AI model", "attempts": r.get("attempts"), "change_id": it.get("change_id") or "","flow": [s["task"] for s in flow] if len(flow) > 1 else []}if not r["ok"]:drafts.append({**base, "id": None, "status": "not written", "runnable": False, "problems": r["problems"][:10],"dry_run": None, "steps": []})continuewith lock:cid = step_writer.next_case_id(svc, area, taken)taken.add(cid)text = step_writer.to_case_yaml(it, r["steps"], cid, "model", area)yp = step_writer.save_draft(svc, cid, text, batch=run_id)sd = specs_dir(svc, run_id)sd.mkdir(parents=True, exist_ok=True)spec = sd / f"{cid}.spec.ts"spec.write_text(step_writer.staged_entry_spec(cid, base["priority"], yp.parent), encoding="utf-8")doc = yaml.safe_load(text)drafts.append({**base, "id": cid, "status": "staged", "yaml_path": str(yp), "spec_path": str(spec), "problems": [],"process": doc.get("process"), "steps": doc.get("steps") or [],"test_values": doc.get("test_values") or {}, "expected_result": doc.get("expected_result")})def _design_flows(svc, run_id: str, all_screens: dict[str, list[dict]], research: dict, library: list[dict], example: str,taken: set[str], drafts: list[dict], lock=None, keys_of=lambda area: []) -> None:"""End-to-end flows across business areas (Procure-to-Pay ...) for the processes whose areas this run tests andwhose screens were read: each flow goes through screens of several areas in business order, carrying thedocument's number or name from one screen to the next."""per_flow = max(1, min(3, int(svc.cfg.fusion_ai_scenarios or 2)))for f in CROSS_AREA_FLOWS:if not all(all_screens.get(a) for a in f["areas"]):continuescreens = [s for a in f["areas"] for s in all_screens[a]]changes = [c for a in f["areas"] for c in ((research.get(a) or {}).get("changes") or [])]changes = sorted(changes, key=lambda c: not c.get("on_by_default"))[:25]titles = [c["title"] for c in library if c.get("module") in f["areas"] and c.get("title")]try:intents = step_writer.design_scenarios(svc, f["name"], [f"{f['name']}: {f['steps']} (one end-to-end flow across these screens)"],changes, screens, count=per_flow, run_id=run_id, existing_titles=titles)except Exception as e: # noqa: BLE001_note(svc, run_id, f"{f['name']}: the AI model could not design end-to-end flows ({type(e).__name__}).")continueintents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value) and len(i.get("flow") or []) > 1]if not intents:_note(svc, run_id, f"{f['name']}: no end-to-end flow was designed across {', '.join(f['areas'])} this time.")continueplaceholders = sorted({p for a in f["areas"] for p in step_writer.area_placeholders(a, svc.cfg.home, keys_of(a))})_write_intents(svc, run_id, f["id_area"], intents, screens, example, taken, drafts, placeholders, lock)_note(svc, run_id, f"{f['name']}: {len(intents)} end-to-end flow(s) designed across {', '.join(f['areas'])}.")def _design_area_flows(svc, run_id: str, area: str, processes: list[str], changes: 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 end-to-end flow for each business process of the area, start to finish across itsscreens (create the document, then find it and act on it), so each process is tested whole, not one screen at a time."""n = max(0, min(int(svc.cfg.fusion_regression_flows or 0), len(processes)))if not n or len(screens) < 2:returnasks = [f"{p_}: one end-to-end flow through this process, start to finish, across these screens" for p_ in processes[:n]]try:intents = step_writer.design_scenarios(svc, area, asks, changes, 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 end-to-end flows for regression ({type(e).__name__}).", module=area)returnintents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value) and len(i.get("flow") or []) > 1]if not intents:_note(svc, run_id, f"{area}: no end-to-end flow was designed for regression this time.", module=area)return_write_intents(svc, run_id, area, intents, screens, example, taken, drafts, placeholders, lock)_note(svc, run_id, f"{area}: {len(intents)} end-to-end flow(s) for regression: " + "; ".join(i["title"] for i in intents)[:300] + ".",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: E731order = [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) + 1if per[k] <= PER_SCREEN:out.append(i)return outREGRESSION_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 oneprocess 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():continueif 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 outdef _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 isshown 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:returnseen, 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 themselvesintents = 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)returnintents = [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 += intentsif 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))# ====================================================================== writingdef 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 therun is not on a Fusion pod (silently) or no AI model is configured (with a note in the run's events)."""run_id = state["run_id"]pod_id = svc.fusion_pod_id(run_id)if pod_id is None:return {}count = int(svc.cfg.fusion_ai_scenarios or 0)if count <= 0:return {}if not svc.router.frontier_ready():_note(svc, run_id, "No AI model is configured, so no new scenarios were written for this pod (Settings > AI models).")return {}from ...platform import fusion_catalogfrom ...platform.pods import PodRegistryfrom .research import scope_modulesreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)areas = scope_modules(state)research = {r.get("module"): r for r in state.get("research") or []}taken: set[str] = set()example = step_writer.example_yaml()_read_missing_screens(state, svc, reg, pod_id, areas)all_screens: dict[str, list[dict]] = {}lock = threading.Lock()per_area: dict[str, list[dict]] = {a: [] for a in areas}def design_area(area: str) -> None:"""One area: its screens, the release's changes, the model's scenarios, their steps. Areas run side by side(the model's answers are the slow part); each keeps its own drafts, merged in area order afterwards."""drafts = per_area[area]# the screens read on this pod (by the run itself, or Test environments > Read screens), else the library'sscreens = reg.area_screens(pod_id, area)have = {step_writer.norm_task(s["task"]) for s in screens}screens += [inv for inv in (step_writer.load_inventory(t) for t in step_writer.AREA_SCREENS.get(area, [])) if invand step_writer.norm_task(inv["task"]) not in have]if not screens:_note(svc, run_id, f"{area}: no screens could be read on this pod, so no new scenarios were written"+ ("." if state.get("playwright_mode") == "live" else " (a quick simulation does not open the pod's screens)."),module=area)returncat = fusion_catalog.by_code(area, svc.cfg.home) or {}processes = step_writer.area_processes(area) + [p for p in cat.get("processes") or [] if p not in step_writer.area_processes(area)]changes = (research.get(area) or {}).get("changes") or step_writer.area_changes(svc, area)# the release's changes, the ones the update switches on by itself first; one scenario more for each of thosechanges = sorted(changes, key=lambda c: (not c.get("on_by_default"), str(c.get("impact") or "").lower() in ("", "none")))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 screenkey = key_screens(screens, cat.get("key_tasks") or [])try: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)returnwhy = next((i.get("fallback_reason") for i in intents if i.get("fallback_reason")), None)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."),module=area)returnwith lock:all_screens[area] = screensplaceholders = step_writer.area_placeholders(area, svc.cfg.home, reg.test_data_keys(pod_id, area, run_id))_write_intents(svc, run_id, area, intents, screens, example, taken, drafts, placeholders, lock)if state.get("depth") == "full": # the area's business processes first (Fusion's catalog), then the library'sflows = 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:for f in [ex.submit(design_area, a) for a in areas]:f.result()drafts = [d for a in areas for d in per_area[a]]all_screens = {a: all_screens[a] for a in areas if a in all_screens}_design_flows(svc, run_id, all_screens, research, library, example, taken, drafts, lock,keys_of=lambda a: reg.test_data_keys(pod_id, a, run_id))staged = [d for d in drafts if d["id"]]tried = bool(svc.cfg.fusion_ai_dry_run)if staged and tried:dry_run(state, svc, pod_id, staged)elif staged: # nothing runs on the pod before a person approves: the test run shows where each one stopsfor d in staged:d["dry_run"], d["runnable"] = None, Truepassed = [d for d in staged if d.get("runnable")]for area in dict.fromkeys(d["module"] for d in drafts): # one plain line per business area, in the order designedmine = [d for d in drafts if d["module"] == area]ok = [d for d in mine if d["id"]]good = [d for d in ok if d.get("runnable")]covered = len({d["change_id"] for d in good if d.get("change_id")})unwritten = f"; {len(mine) - len(ok)} could not be written with this screen's actions" if len(mine) > len(ok) else ""if tried:_note(svc, run_id, f"{area}: the AI model wrote {len(ok)} scenario(s), {len(good)} passed the dry run on the pod"+ (f", {len(ok) - len(good)} failed it" if len(ok) > len(good) else "") + unwritten+ (f"; {covered} release change(s) covered" if covered else "") + ".",module=area, written=len(ok), passed=len(good))else:_note(svc, run_id, f"{area}: the AI model wrote {len(ok)} scenario(s), offered for approval; they run on the pod "f"once approved" + unwritten + (f"; {covered} release change(s) covered" if covered else "") + ".",module=area, written=len(ok), offered=len(good))cases = [{"id": d["id"], "title": d["title"], "module": d["module"], "process": d.get("process") or "", "priority": d["priority"],"new_or_changed": True, "changed_by_patch": bool(d.get("change_id")), "origin": AI_ORIGIN, "yaml_path": d["yaml_path"],"map_ids": [d["change_id"]] if d.get("change_id") else [],"data_recipes": [], "learned": {"recent_failures": 0, "last_label": None}, "already_approved": False} for d in passed]return {"cases": cases, "drafts": drafts}# ====================================================================== approval gatedef plain_steps(steps: list[dict], test_values: dict | None = None) -> list[dict]:from ...platform.readiness import plain_fusion_stepreturn [{"n": s.get("n", i + 1), "action": s.get("action"), "field": s.get("field") or (", ".join(s.get("fields") or []) or None),"value": None if s.get("value") is None else str(s.get("value")), "expected": s.get("expected"),"text": plain_fusion_step(s, test_values)} for i, s in enumerate(steps or [])]def gate_view(d: dict) -> dict:"""What the consultant sees about one AI draft at the approval gate."""return {"id": d.get("id"), "title": d["title"], "module": d["module"], "priority": d["priority"], "written_by": "AI model","model": d.get("model"), "why": d.get("why"), "status": d.get("status"), "runnable": bool(d.get("runnable")),"dry_run": d.get("dry_run"), "problems": d.get("problems") or [], "steps": plain_steps(d.get("steps") or [], d.get("test_values")),"expected_result": d.get("expected_result")}def _gen_entry_specs(root: Path) -> tuple[bool, str]:cmd = ["node", str(ROOT / "automation" / "scripts" / "gen-fusion-steps.js"), "--cases", str(root / "tests" / "cases"),"--out", str(root / "automation" / "tests" / "fusion" / "steps")]p = subprocess.run(cmd, cwd=str(ROOT / "automation"), capture_output=True, text=True, encoding="utf-8", errors="replace",timeout=120, **procs.popen_kwargs())return p.returncode == 0, (p.stdout + p.stderr)[-1000:]def approve_drafts(state, svc, approved: list[str], actor: str) -> dict:"""Approved AI drafts: approval + verification lines set, then (case write-back on) promoted into the script libraryand committed; with write-back off they stay in staging, approved, and run from there. Returns {ai_drafts, cases}."""run_id = state["run_id"]drafts = [dict(d) for d in state.get("ai_drafts") or []]date = datetime.now(timezone.utc).strftime("%Y-%m-%d")root = library_root(svc)paths_to_commit: list[Path] = []moved: dict[str, str] = {}for d in drafts:if d.get("id") not in approved or not d.get("runnable"):continuedr = d.get("dry_run") or {}verification = ("UNVERIFIED until its first test run on the pod (approved without a dry run)" if not drelse f"dry run passed on {dr.get('pod')} {date}" if not dr.get("simulated")else f"dry run simulated (quick simulation, no browser, not on a pod) {date}")src = Path(d["yaml_path"])text = step_writer.approved_yaml(src.read_text(encoding="utf-8"), f"approved by {actor} on {date}", verification)d.update(status="approved", approved_by=actor, approved_at=date, verification=verification)if not svc.cfg.case_writeback:src.write_text(text, encoding="utf-8")continuedst = root / "tests" / "cases" / f"{d['id']}.yaml"if dst.exists():d.update(status="approved (kept in staging)", note=f"{dst.name} already exists in the library")src.write_text(text, encoding="utf-8")continuedst.parent.mkdir(parents=True, exist_ok=True)dst.write_text(text, encoding="utf-8", newline="")spec = write_library_entry(root, d["id"], d.get("priority"))Path(d["spec_path"]).unlink(missing_ok=True) # the library entry replaces the staged one (never both)d.update(status="promoted", yaml_path=str(dst), spec_path=str(spec))moved[d["id"]] = d["yaml_path"]paths_to_commit += [dst, spec]commit = None# the library's git history covers the files under its work tree; the persistent library is recorded in the audit loginside = [x for x in paths_to_commit if str(x.resolve()).startswith(str(Path(svc.library.work_tree).resolve()))] \if hasattr(svc.library, "work_tree") else paths_to_commitpaths_to_commit = insideif paths_to_commit and svc.library.exists():try:commit = svc.library.commit(paths_to_commit, f"add {len(moved)} AI-written scenario(s) approved in run {run_id}: "+ ", ".join(sorted(moved)), actor)except Exception as e: # noqa: BLE001svc.audit.append("library.error", actor="system", run_id=run_id, summary=str(e)[:300])for d in drafts:if d.get("id") in moved:d["library_commit"] = commitsvc.audit.append("ai_scenario.promoted", actor=actor, run_id=run_id, node="approval_gate", summary=d["id"],payload={"case_id": d["id"], "yaml": d["yaml_path"], "commit": commit})elif d.get("id") and d.get("runnable") and d["id"] not in approved and d.get("status") == "staged":d["status"] = "rejected (kept in staging)"cases = [{**c, "yaml_path": moved.get(c["id"], c.get("yaml_path")), "already_approved": c["id"] in approved}if c.get("origin") == AI_ORIGIN else c for c in state.get("test_cases") or []]return {"ai_drafts": drafts, "test_cases": cases, "commit": commit}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583"""AI-written scenarios for a real Oracle Fusion pod (part of the design phase).After test_generator has chosen the library cases, and only when the run targets a registered Fusion pod AND anexternal AI model is switched on, the step writer (platform/step_writer.py) designs a few NEW scenarios for each businessarea from the area's captured screens (public labels only; the data rule of the step writer is unchanged), writes theirsteps and checks them. Each accepted draft is staged under FPT_HOME/staging/steps/<run_id>/ with its Playwright entrypoint under FPT_HOME/staging/specs/<run_id>/, and offered at the approval gate (origin "ai") with its steps in plainlanguage. Nothing runs on the pod before a person approves: the test run after approval shows where each one stops.With FPT_FUSION_AI_DRY_RUN on, the drafts are first DRY-RUN on the pod with the step runner (saving there too):- dry run passed -> offered at the approval gate with the dry-run result;- dry run failed -> NOT offered as runnable; shown at the gate with the failing step and its message.Approving promotes the draft into the script library (tests/cases/<ID>.yaml + its entry spec, committed to library.git);rejected drafts stay in staging. Nothing here runs for the practice pod, or when no AI model is configured."""from __future__ import annotationsimport jsonimport reimport subprocessimport threadingimport timefrom concurrent.futures import ThreadPoolExecutorfrom datetime import datetime, timezonefrom pathlib import Pathfrom urllib.parse import urlparseimport yamlfrom ...adapters import playwright as pwfrom ...config import ROOTfrom ...llm.base import Routefrom ...platform import procs, step_writerfrom ...platform.rundb import now_isoANSI = re.compile(r"\x1b\[[0-9;]*m")STEP_TITLE = re.compile(r"^\d+\.\s")PROMOTE_ROOT: Path | None = None # tests point it at a folder; otherwise the persistent library under FPT_HOMEdef library_root(svc) -> Path:"""Where approved scenarios (AI-written, or brought by the client) are kept: FPT_HOME/library, so they survive arestart and a new deployment (the app folder is rebuilt from the code; FPT_HOME is saved). Same layout as the repo:tests/cases/<ID>.yaml and automation/tests/fusion/steps/<ID>.spec.ts."""return Path(PROMOTE_ROOT) if PROMOTE_ROOT else svc.cfg.path("library")def write_library_entry(root: Path, case_id: str, priority: str | None) -> Path:"""The Playwright entry point of a library scenario: it reads its YAML from the library folder."""spec = Path(root) / "automation" / "tests" / "fusion" / "steps" / f"{case_id}.spec.ts"spec.parent.mkdir(parents=True, exist_ok=True)spec.write_text(step_writer.library_entry_spec(case_id, priority, Path(root) / "tests" / "cases"), encoding="utf-8")return specAI_ORIGIN = "ai"def _note(svc, run_id: str, message: str, **extra) -> None:svc.db.add_event(run_id, "test_generator", "ai_scenarios", {"message": message, **extra})svc.audit.append("ai_scenarios.note", actor="system", run_id=run_id, node="test_generator", summary=message[:200])def _pod_host(svc, pod_id: int) -> str:row = svc.db.one("SELECT base_url FROM pods WHERE id=?", (pod_id,))return urlparse((row or {}).get("base_url") or "").hostname or "the pod"def specs_dir(svc, run_id: str) -> Path:return svc.cfg.path("staging", "specs", run_id)# ====================================================================== dry rundef _failed_step(steps: list[dict]) -> tuple[str | None, str | None]:"""(title of the first scenario step that failed, its error message) from a Playwright JSON result's steps."""for s in steps or []:title = str(s.get("title") or "")inner_t, inner_m = _failed_step(s.get("steps") or [])if s.get("error") or inner_t:if STEP_TITLE.match(title):msg = (s.get("error") or {}).get("message") or inner_mreturn title, ANSI.sub("", str(msg or ""))[:1200] or Noneif inner_t:return inner_t, inner_mreturn None, Nonedef read_dry_run(report_file: Path, ids: list[str]) -> dict[str, dict]:"""{id: {status, failed_step, message}} from the dry run's Playwright JSON (stub or live)."""data = json.loads(Path(report_file).read_text(encoding="utf-8"))out: dict[str, dict] = {}for spec in pw._walk_specs(data.get("suites")):tags = [t.lstrip("@") for t in spec.get("tags") or []]cid = next((i for i in ids if i in tags or spec.get("id") == i or str(spec.get("title", "")).startswith(i + " ")), None)if not cid:continuefor t in spec.get("tests") or []:res = (t.get("results") or [{}])[-1]status = res.get("status") or ("passed" if t.get("status") == "expected" else "failed")step, msg = _failed_step(res.get("steps") or [])if status != "passed" and not msg:msg = ANSI.sub("", "\n".join(e.get("message", "") for e in res.get("errors") or []))[:1200] or Noneout[cid] = {"status": "passed" if status == "passed" else "failed", "failed_step": step, "message": msg}for i in ids:out.setdefault(i, {"status": "failed", "failed_step": None, "message": "the dry run did not report this scenario"})return outdef dry_run(state, svc, pod_id: int, drafts: list[dict]) -> None:"""Runs the staged drafts once on the pod (step runner, playwright.fusion.config.ts, 'drafts' project) and attaches{status, failed_step, message, pod, at, simulated} to each draft. In a quick simulation (stub mode) nothing runs onthe pod: the result says so and is never presented as a pod result."""run_id = state["run_id"]mode = state.get("playwright_mode") or svc.cfg.playwright_modeids = [d["id"] for d in drafts]host = _pod_host(svc, pod_id)at = now_iso()run_dir = svc.run_dir(run_id)from ...platform.assisted_signin import assisted_podif mode == "live" and assisted_pod(svc, run_id): # nobody has signed in yet: a person signs in when the tests startwhy = ("not tried on the pod: it uses assisted sign-in, and a person signs in only when the run's tests start, so an ""AI-written scenario cannot have its dry run here")for d in drafts:d["dry_run"] = {"status": "failed", "failed_step": None, "message": why, "pod": host, "at": at, "simulated": False}d["runnable"] = Falsereturntry:cred_env: dict = {}if mode == "live":from ...platform.pods import PodRegistryfor m in sorted({d["module"] for d in drafts}):cred_env.update(svc.vault.executor_env(m))cred_env.update(PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).executor_env(pod_id, run_id) or {})svc.db.add_event(run_id, "test_generator", "ai_scenarios",{"message": f"dry run of {len(ids)} AI-written scenario(s) on {host if mode == 'live' else 'the simulation'}","scenarios": ", ".join(ids)})# the same road as a test attempt: the remote browser runner when one is set (this server's network may be one# Oracle's edge refuses), else this serverfrom .execute import FUSION_CONFIG, attempt_timeout_s, run_passres = run_pass({"run_id": run_id, "attempt": 0, "tag": "-dryrun", "ids": ids, "mode": mode,"out_file": str(run_dir / "ai-dry-run.json"), "stub_knobs": state.get("stub_knobs"),"drafts_dir": str(specs_dir(svc, run_id)), "library_dir": None, "overrides": None, "cred_env": cred_env,"run_dir": str(run_dir), "config": FUSION_CONFIG, "timeout_s": attempt_timeout_s(svc.cfg, len(ids))}, svc)results = read_dry_run(Path(res["file"]), ids)if mode == "live": # the values Fusion accepted are tried first next time on this podPodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).learn_test_data(pod_id, pw.testdata_used_file(run_dir / "ai-dry-run.json"))if res.get("run_dir"):try: # the dry run's traces and screenshots go to the encrypted evidence store like any attempt'ssvc.evidence.ingest_dir(run_id, -1, Path(res["run_dir"]), pw.attachments_by_case(Path(res["file"])))except Exception as e: # noqa: BLE001svc.audit.append("evidence.error", actor="system", run_id=run_id, summary=str(e)[:300])except Exception as e: # noqa: BLE001 - a dry run that cannot start fails every draft, never the test runresults = {i: {"status": "failed", "failed_step": None, "message": f"the dry run could not run: {str(e)[:500]}"} for i in ids}for d in drafts:d["dry_run"] = {**results[d["id"]], "pod": host if mode == "live" else None, "at": at, "simulated": mode != "live"}d["runnable"] = results[d["id"]]["status"] == "passed"def scenario_count(base: int, switched_on: int, cap: int, screens: int) -> int:"""How many scenarios to ask for in one area: the base, plus one per change the update switches on by itself, atmost `cap`, and at most two per screen read (more would only repeat the same screen)."""return max(1, min(base + switched_on, cap, 2 * screens))def _read_missing_screens(state, svc, reg, pod_id: int, areas: list[str]) -> None:"""A full browser run reads, before designing, the screens of the areas it tests that have none on this pod yet orwere read on another release (one browser session, a few minutes per area). A quick simulation never opens the pod."""if state.get("playwright_mode") != "live":returnfrom ...platform.pods import PodErrorrun_id = state["run_id"]late = "The background read of the pod's screens did not finish in time; the run designs with the screens it has."end = time.monotonic() + 5400 # the explorer itself stops after 90 minutes# read in the background since the pod was set up: wait for this run's own areas rather than read them twice, not# for the pod's other areas (each area is on the pod's record as soon as it is read)ahead = reg.areas_being_read(pod_id, areas)if ahead:_note(svc, run_id, f"The pod's screens are being read in the background (started when its areas were discovered); "f"waiting for {', '.join(ahead)}.")if not reg.wait_for_screens(pod_id, timeout_s=end - time.monotonic(), areas=ahead):_note(svc, run_id, late)returnmissing = reg.areas_to_read(pod_id, areas)if missing and reg.screens_busy(pod_id): # one browser reads at a time: an area the background read skips waits for it_note(svc, run_id, f"The background read of the pod's other areas is still going; reading {', '.join(missing)} waits for it.")if not reg.wait_for_screens(pod_id, timeout_s=end - time.monotonic()):_note(svc, run_id, late)returnmissing = reg.areas_to_read(pod_id, areas)if not missing:return_note(svc, run_id, f"Reading the screens of {', '.join(missing)} on the pod before designing ({int(svc.cfg.fusion_workers or 1)} "f"at a time; nothing is saved).")try:_, job = reg.start_screens(pod_id, "scout", missing, max_tasks=int(svc.cfg.fusion_screens_per_area or 8))except PodError as e:_note(svc, run_id, f"The screens could not be read now: {e}")returnafter = reg.read_screens(pod_id, job, "scout").get("screens") or {}if after.get("state") == "failed":_note(svc, run_id, f"Reading the screens did not finish: {after.get('error')}")returngot = {a: len((after.get("areas") or {}).get(a, {}).get("captured") or []) for a in missing}_note(svc, run_id, "Screens read: " + ", ".join(f"{a} {n}" for a, n in got.items()) + ".")# end-to-end business processes that cross business areas: designed when a run tests every area of one of themCROSS_AREA_FLOWS = [{"name": "Procure-to-Pay", "areas": ["PO", "AP"], "id_area": "PO","steps": "requisition or purchase order, receipt, supplier invoice matched to the order, payment"},{"name": "Order-to-Cash", "areas": ["OM", "AR"], "id_area": "OM","steps": "sales order, shipment, customer invoice, receipt applied to the invoice"},{"name": "Record-to-Report", "areas": ["AP", "AR", "GL"], "id_area": "GL","steps": "subledger transactions accounted, journals posted to the ledger, period close checks"},]def _write_intents(svc, run_id: str, area: str, intents: list[dict], screens: list[dict], example: str, taken: set[str],drafts: list[dict], placeholders: list[str], lock=None) -> None:"""Steps for each designed intent (one screen, or a flow across several), checked, staged for the dry run. Areas arewritten at the same time (one thread each): `lock` keeps their scenario numbers and staged files apart."""lock = lock or threading.Lock()by_task = {step_writer.norm_task(s["task"]): s for s in screens}for it in intents:flow = [by_task[step_writer.norm_task(t)] for t in it.get("flow") or [] if step_writer.norm_task(t) in by_task]r = step_writer.write_steps(svc, it, by_task[step_writer.norm_task(it["task"])], example, run_id=run_id,placeholders=placeholders, flow_screens=flow if len(flow) > 1 else None)base = {"title": it["title"], "module": area, "priority": it.get("priority") or "P2", "type": it.get("type"),"why": it.get("why") or "", "task": it["task"], "model": r.get("model") or it.get("model"),"written_by": "AI model", "attempts": r.get("attempts"), "change_id": it.get("change_id") or "","flow": [s["task"] for s in flow] if len(flow) > 1 else []}if not r["ok"]:drafts.append({**base, "id": None, "status": "not written", "runnable": False, "problems": r["problems"][:10],"dry_run": None, "steps": []})continuewith lock:cid = step_writer.next_case_id(svc, area, taken)taken.add(cid)text = step_writer.to_case_yaml(it, r["steps"], cid, "model", area)yp = step_writer.save_draft(svc, cid, text, batch=run_id)sd = specs_dir(svc, run_id)sd.mkdir(parents=True, exist_ok=True)spec = sd / f"{cid}.spec.ts"spec.write_text(step_writer.staged_entry_spec(cid, base["priority"], yp.parent), encoding="utf-8")doc = yaml.safe_load(text)drafts.append({**base, "id": cid, "status": "staged", "yaml_path": str(yp), "spec_path": str(spec), "problems": [],"process": doc.get("process"), "steps": doc.get("steps") or [],"test_values": doc.get("test_values") or {}, "expected_result": doc.get("expected_result")})def _design_flows(svc, run_id: str, all_screens: dict[str, list[dict]], research: dict, library: list[dict], example: str,taken: set[str], drafts: list[dict], lock=None, keys_of=lambda area: []) -> None:"""End-to-end flows across business areas (Procure-to-Pay ...) for the processes whose areas this run tests andwhose screens were read: each flow goes through screens of several areas in business order, carrying thedocument's number or name from one screen to the next."""per_flow = max(1, min(3, int(svc.cfg.fusion_ai_scenarios or 2)))for f in CROSS_AREA_FLOWS:if not all(all_screens.get(a) for a in f["areas"]):continuescreens = [s for a in f["areas"] for s in all_screens[a]]changes = [c for a in f["areas"] for c in ((research.get(a) or {}).get("changes") or [])]changes = sorted(changes, key=lambda c: not c.get("on_by_default"))[:25]titles = [c["title"] for c in library if c.get("module") in f["areas"] and c.get("title")]try:intents = step_writer.design_scenarios(svc, f["name"], [f"{f['name']}: {f['steps']} (one end-to-end flow across these screens)"],changes, screens, count=per_flow, run_id=run_id, existing_titles=titles)except Exception as e: # noqa: BLE001_note(svc, run_id, f"{f['name']}: the AI model could not design end-to-end flows ({type(e).__name__}).")continueintents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value) and len(i.get("flow") or []) > 1]if not intents:_note(svc, run_id, f"{f['name']}: no end-to-end flow was designed across {', '.join(f['areas'])} this time.")continueplaceholders = sorted({p for a in f["areas"] for p in step_writer.area_placeholders(a, svc.cfg.home, keys_of(a))})_write_intents(svc, run_id, f["id_area"], intents, screens, example, taken, drafts, placeholders, lock)_note(svc, run_id, f"{f['name']}: {len(intents)} end-to-end flow(s) designed across {', '.join(f['areas'])}.")def _design_area_flows(svc, run_id: str, area: str, processes: list[str], changes: 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 end-to-end flow for each business process of the area, start to finish across itsscreens (create the document, then find it and act on it), so each process is tested whole, not one screen at a time."""n = max(0, min(int(svc.cfg.fusion_regression_flows or 0), len(processes)))if not n or len(screens) < 2:returnasks = [f"{p_}: one end-to-end flow through this process, start to finish, across these screens" for p_ in processes[:n]]try:intents = step_writer.design_scenarios(svc, area, asks, changes, 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 end-to-end flows for regression ({type(e).__name__}).", module=area)returnintents = [i for i in intents if i.get("designed_by") in (Route.FRONTIER.value, Route.LOCAL.value) and len(i.get("flow") or []) > 1]if not intents:_note(svc, run_id, f"{area}: no end-to-end flow was designed for regression this time.", module=area)return_write_intents(svc, run_id, area, intents, screens, example, taken, drafts, placeholders, lock)_note(svc, run_id, f"{area}: {len(intents)} end-to-end flow(s) for regression: " + "; ".join(i["title"] for i in intents)[:300] + ".",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: E731order = [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) + 1if per[k] <= PER_SCREEN:out.append(i)return outREGRESSION_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 oneprocess 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():continueif 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 outdef _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 isshown 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:returnseen, 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 themselvesintents = 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)returnintents = [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 += intentsif 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))# ====================================================================== writingdef 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 therun is not on a Fusion pod (silently) or no AI model is configured (with a note in the run's events)."""run_id = state["run_id"]pod_id = svc.fusion_pod_id(run_id)if pod_id is None:return {}count = int(svc.cfg.fusion_ai_scenarios or 0)if count <= 0:return {}if not svc.router.frontier_ready():_note(svc, run_id, "No AI model is configured, so no new scenarios were written for this pod (Settings > AI models).")return {}from ...platform import fusion_catalogfrom ...platform.pods import PodRegistryfrom .research import scope_modulesreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)areas = scope_modules(state)research = {r.get("module"): r for r in state.get("research") or []}taken: set[str] = set()example = step_writer.example_yaml()_read_missing_screens(state, svc, reg, pod_id, areas)# how the client uses each area (Test environments > Read usage): the designer is told the standard variants and their# shares, the changes touching them come first and the scenarios on them rank first (platform/usage.py)from ...platform import usagetry:prof = reg.usage(pod_id)cov = usage.coverage(prof, library, svc.cfg.home) if prof else Noneexcept Exception as e: # noqa: BLE001 - a damaged profile designs as before, never stops the design_note(svc, run_id, f"The pod's usage profile could not be used ({type(e).__name__}); designing without it.")cov = Noneall_screens: dict[str, list[dict]] = {}lock = threading.Lock()per_area: dict[str, list[dict]] = {a: [] for a in areas}def design_area(area: str) -> None:"""One area: its screens, the release's changes, the model's scenarios, their steps. Areas run side by side(the model's answers are the slow part); each keeps its own drafts, merged in area order afterwards."""drafts = per_area[area]# the screens read on this pod (by the run itself, or Test environments > Read screens), else the library'sscreens = reg.area_screens(pod_id, area)have = {step_writer.norm_task(s["task"]) for s in screens}screens += [inv for inv in (step_writer.load_inventory(t) for t in step_writer.AREA_SCREENS.get(area, [])) if invand step_writer.norm_task(inv["task"]) not in have]if not screens:_note(svc, run_id, f"{area}: no screens could be read on this pod, so no new scenarios were written"+ ("." if state.get("playwright_mode") == "live" else " (a quick simulation does not open the pod's screens)."),module=area)returncat = fusion_catalog.by_code(area, svc.cfg.home) or {}processes = step_writer.area_processes(area) + [p for p in cat.get("processes") or [] if p not in step_writer.area_processes(area)]changes = (research.get(area) or {}).get("changes") or step_writer.area_changes(svc, area)# the release's changes, the ones the update switches on by itself first; one scenario more for each of thosechanges = sorted(changes, key=lambda c: (not c.get("on_by_default"), str(c.get("impact") or "").lower() in ("", "none")))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 screenkey = key_screens(screens, cat.get("key_tasks") or [])view = usage.prompt_view(cov, area, cat.get("name")) if cov else Noneif view:gaps = sum(1 for v in view["variants"] if not v["covered_by_library"] and v["value"] != "other values")_note(svc, run_id, f"{area}: designed with this pod's usage ({len(view['variants'])} variant(s) in use, {gaps} not covered "f"by the library yet).", module=area)try:intents = step_writer.design_scenarios(svc, area, processes, changes, key or screens, count=n,run_id=run_id, existing_titles=titles, usage_view=view,usage_variants=usage.area_variants(cov, area) if view else None)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)returnwhy = next((i.get("fallback_reason") for i in intents if i.get("fallback_reason")), None)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."),module=area)returnwith lock:all_screens[area] = screensplaceholders = step_writer.area_placeholders(area, svc.cfg.home, reg.test_data_keys(pod_id, area, run_id))_write_intents(svc, run_id, area, intents, screens, example, taken, drafts, placeholders, lock)if state.get("depth") == "full": # the area's business processes first (Fusion's catalog), then the library'sflows = list(dict.fromkeys(list(cat.get("processes") or []) + step_writer.area_processes(area)))# a business process flows through the area's key screens (create, then find and act on it): given every# screen read, the model built both AP flows on a bank-file screen; all screens only when too few key ones_design_area_flows(svc, run_id, area, flows, changes, key if len(key) >= 2 else 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:for f in [ex.submit(design_area, a) for a in areas]:f.result()drafts = [d for a in areas for d in per_area[a]]all_screens = {a: all_screens[a] for a in areas if a in all_screens}_design_flows(svc, run_id, all_screens, research, library, example, taken, drafts, lock,keys_of=lambda a: reg.test_data_keys(pod_id, a, run_id))staged = [d for d in drafts if d["id"]]tried = bool(svc.cfg.fusion_ai_dry_run)if staged and tried:dry_run(state, svc, pod_id, staged)elif staged: # nothing runs on the pod before a person approves: the test run shows where each one stopsfor d in staged:d["dry_run"], d["runnable"] = None, Truepassed = [d for d in staged if d.get("runnable")]for area in dict.fromkeys(d["module"] for d in drafts): # one plain line per business area, in the order designedmine = [d for d in drafts if d["module"] == area]ok = [d for d in mine if d["id"]]good = [d for d in ok if d.get("runnable")]covered = len({d["change_id"] for d in good if d.get("change_id")})unwritten = f"; {len(mine) - len(ok)} could not be written with this screen's actions" if len(mine) > len(ok) else ""if tried:_note(svc, run_id, f"{area}: the AI model wrote {len(ok)} scenario(s), {len(good)} passed the dry run on the pod"+ (f", {len(ok) - len(good)} failed it" if len(ok) > len(good) else "") + unwritten+ (f"; {covered} release change(s) covered" if covered else "") + ".",module=area, written=len(ok), passed=len(good))else:_note(svc, run_id, f"{area}: the AI model wrote {len(ok)} scenario(s), offered for approval; they run on the pod "f"once approved" + unwritten + (f"; {covered} release change(s) covered" if covered else "") + ".",module=area, written=len(ok), offered=len(good))cases = [{"id": d["id"], "title": d["title"], "module": d["module"], "process": d.get("process") or "", "priority": d["priority"],"new_or_changed": True, "changed_by_patch": bool(d.get("change_id")), "origin": AI_ORIGIN, "yaml_path": d["yaml_path"],"map_ids": [d["change_id"]] if d.get("change_id") else [],"data_recipes": [], "learned": {"recent_failures": 0, "last_label": None}, "already_approved": False} for d in passed]return {"cases": cases, "drafts": drafts}# ====================================================================== approval gatedef plain_steps(steps: list[dict], test_values: dict | None = None) -> list[dict]:from ...platform.readiness import plain_fusion_stepreturn [{"n": s.get("n", i + 1), "action": s.get("action"), "field": s.get("field") or (", ".join(s.get("fields") or []) or None),"value": None if s.get("value") is None else str(s.get("value")), "expected": s.get("expected"),"text": plain_fusion_step(s, test_values)} for i, s in enumerate(steps or [])]def gate_view(d: dict) -> dict:"""What the consultant sees about one AI draft at the approval gate."""return {"id": d.get("id"), "title": d["title"], "module": d["module"], "priority": d["priority"], "written_by": "AI model","model": d.get("model"), "why": d.get("why"), "status": d.get("status"), "runnable": bool(d.get("runnable")),"dry_run": d.get("dry_run"), "problems": d.get("problems") or [], "steps": plain_steps(d.get("steps") or [], d.get("test_values")),"expected_result": d.get("expected_result")}def _gen_entry_specs(root: Path) -> tuple[bool, str]:cmd = ["node", str(ROOT / "automation" / "scripts" / "gen-fusion-steps.js"), "--cases", str(root / "tests" / "cases"),"--out", str(root / "automation" / "tests" / "fusion" / "steps")]p = subprocess.run(cmd, cwd=str(ROOT / "automation"), capture_output=True, text=True, encoding="utf-8", errors="replace",timeout=120, **procs.popen_kwargs())return p.returncode == 0, (p.stdout + p.stderr)[-1000:]def approve_drafts(state, svc, approved: list[str], actor: str) -> dict:"""Approved AI drafts: approval + verification lines set, then (case write-back on) promoted into the script libraryand committed; with write-back off they stay in staging, approved, and run from there. Returns {ai_drafts, cases}."""run_id = state["run_id"]drafts = [dict(d) for d in state.get("ai_drafts") or []]date = datetime.now(timezone.utc).strftime("%Y-%m-%d")root = library_root(svc)paths_to_commit: list[Path] = []moved: dict[str, str] = {}for d in drafts:if d.get("id") not in approved or not d.get("runnable"):continuedr = d.get("dry_run") or {}verification = ("UNVERIFIED until its first test run on the pod (approved without a dry run)" if not drelse f"dry run passed on {dr.get('pod')} {date}" if not dr.get("simulated")else f"dry run simulated (quick simulation, no browser, not on a pod) {date}")src = Path(d["yaml_path"])text = step_writer.approved_yaml(src.read_text(encoding="utf-8"), f"approved by {actor} on {date}", verification)d.update(status="approved", approved_by=actor, approved_at=date, verification=verification)if not svc.cfg.case_writeback:src.write_text(text, encoding="utf-8")continuedst = root / "tests" / "cases" / f"{d['id']}.yaml"if dst.exists():d.update(status="approved (kept in staging)", note=f"{dst.name} already exists in the library")src.write_text(text, encoding="utf-8")continuedst.parent.mkdir(parents=True, exist_ok=True)dst.write_text(text, encoding="utf-8", newline="")spec = write_library_entry(root, d["id"], d.get("priority"))Path(d["spec_path"]).unlink(missing_ok=True) # the library entry replaces the staged one (never both)d.update(status="promoted", yaml_path=str(dst), spec_path=str(spec))moved[d["id"]] = d["yaml_path"]paths_to_commit += [dst, spec]commit = None# the library's git history covers the files under its work tree; the persistent library is recorded in the audit loginside = [x for x in paths_to_commit if str(x.resolve()).startswith(str(Path(svc.library.work_tree).resolve()))] \if hasattr(svc.library, "work_tree") else paths_to_commitpaths_to_commit = insideif paths_to_commit and svc.library.exists():try:commit = svc.library.commit(paths_to_commit, f"add {len(moved)} AI-written scenario(s) approved in run {run_id}: "+ ", ".join(sorted(moved)), actor)except Exception as e: # noqa: BLE001svc.audit.append("library.error", actor="system", run_id=run_id, summary=str(e)[:300])for d in drafts:if d.get("id") in moved:d["library_commit"] = commitsvc.audit.append("ai_scenario.promoted", actor=actor, run_id=run_id, node="approval_gate", summary=d["id"],payload={"case_id": d["id"], "yaml": d["yaml_path"], "commit": commit})elif d.get("id") and d.get("runnable") and d["id"] not in approved and d.get("status") == "staged":d["status"] = "rejected (kept in staging)"cases = [{**c, "yaml_path": moved.get(c["id"], c.get("yaml_path")), "already_approved": c["id"] in approved}if c.get("origin") == AI_ORIGIN else c for c in state.get("test_cases") or []]return {"ai_drafts": drafts, "test_cases": cases, "commit": commit}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442"""Design phase: test_generator -> approval_gate (human interrupt / earned autonomy) -> (data) -> script_builder.Library cases are reused; drafts are proposed for patch-touched gap rows; generated specs are staged OUTSIDE automation/until a human promotes them."""from __future__ import annotationsimport jsonimport reimport subprocessfrom datetime import datetime, timezonefrom pathlib import Pathimport yamlfrom langgraph.types import interruptfrom ...adapters import cases as case_libfrom ...adapters.legacy import select_scopefrom ...config import ROOTfrom ...llm.base import LLMRequest, Sensitivityfrom ...llm.schemas import CaseProposals, ScriptDraftfrom ...platform import procsfrom ...platform.rundb import now_isofrom . import ai_scenariosfrom .research import scope_modulesAUTOMATION = ROOT / "automation"SPEC_DIR = AUTOMATION / "tests" / "cases"PRIO_ORDER = {"P1": 0, "P2": 1, "P3": 2, "P4": 3}# ====================================================================== test_generatordef gen_id(module: str, row_id: str) -> str:return f"{module}-GEN-{re.sub(r'[^A-Z0-9]', '', row_id.upper())}-001"def stub_generate_tests(payload: dict) -> CaseProposals:out = []for r in payload.get("rows", []):out.append({"id": gen_id(r["module"], r["row_id"]), "title": f"Generated smoke for {r['row_id']}: {r['process'][:80]}","module": r["module"], "process": r["process"][:120], "priority": r["tier"], "map_ids": [r["row_id"]],"steps": [{"action": "login_as", "value": r.get("persona") or "auditor_ro","expected": "Home page loads for the persona; no error banner."},{"action": "verify", "target": {"testid": "page-title"}, "value": "Home","expected": "Home page title shown."}],"rationale": "Row touched by the patch (research) and no designed case cites it (gap)."})return CaseProposals.model_validate({"cases": out})def test_generator(state, config, svc) -> dict:run_id = state["run_id"]mods = scope_modules(state)include_p2 = bool(state.get("include_p2"))cmap = state.get("coverage_map") or {"rows": []}touched = {(r["module"], r["row_id"]) for r in cmap["rows"] if r["touched_by_patch"]}library = case_lib.load_all(svc, mods) if mods else [] # with the approved scenarios of the persistent library# a real Fusion pod runs only Fusion scenarios (steps or Fusion scripts), the practice pod only its ownfusion = svc.fusion_pod_id(run_id) is not Nonelibrary = [c for c in library if c.get("target", "practice") == ("fusion" if fusion else "practice")]only = set(state.get("case_filter") or [])if only:library = [c for c in library if c["id"] in only]active, deferred = [], []for c in library:c["changed_by_patch"] = any((c["module"], rid) in touched for rid in c["map_ids"])hist = svc.memory.case_history(c["id"], 10)c["learned"] = {"recent_failures": sum(1 for h in hist if h["category"]), "last_label": next((h["human_label"] for h in hist if h["human_label"]), None)}if c["lifecycle"]:deferred.append({"id": c["id"], "priority": c["priority"], "reason": f"{c['lifecycle']} (tests/README.md lifecycle, qa/audit.py case_flags)"})else:active.append(c)depth = state.get("depth") or "standard"if depth == "full": # the whole regression pack of the areas: every priority, every approved scenariokeep, out_of_scope = list(active), []else:keep, out_of_scope = select_scope(active, include_p2 and depth != "smoke")pulled = []for d in list(out_of_scope):c = next(x for x in active if x["id"] == d["id"])if depth == "standard" and c["priority"] == "P2" and c["changed_by_patch"] and not include_p2 and not only:keep.append(c)pulled.append(c["id"])out_of_scope.remove(d)deferred += out_of_scopekeep.sort(key=lambda c: (PRIO_ORDER.get(c["priority"], 9), -c["learned"]["recent_failures"], c["id"]))# proposals for gap rows touched by the patchon_pod = {m["module"]: m for m in (state.get("pod_profile") or {}).get("modules", [])}gap_rows = [] if only or fusion else [r for r in cmap["rows"] if r["gap"] and r["touched_by_patch"] and r["module"] in mods]uniq = {}for r in gap_rows:uniq.setdefault((r["module"], r["row_id"]), r)rows_payload = [{"module": r["module"], "row_id": r["row_id"], "process": r["process"], "tier": r["tier"],"persona": on_pod.get(r["module"], {}).get("scout_persona")} for r in uniq.values()]baseline = stub_generate_tests({"rows": rows_payload})red, mapping = svc.redactor.redact({"rows": rows_payload, "row_ids": [r["row_id"] for r in rows_payload]})req = LLMRequest("generate_tests", Sensitivity.REDACTED, red, CaseProposals, "test_generator", run_id, baseline)resp = svc.router.call(req)out = svc.redactor.restore(resp.output.model_dump(), mapping)proposals = []existing = {c["id"] for c in library}for d in out["cases"]:if d["id"] in existing:continued.update({"origin": "generated", "approval_status": "draft - generated by co-worker, pending approval","verification": "UNVERIFIED", "notes": ["Generated draft. Runs against the mock prove only the mock, never Oracle Fusion."]})proposals.append(d)gen_cases = [{"id": d["id"], "title": d["title"], "module": d["module"], "process": d["process"], "priority": d["priority"],"new_or_changed": True, "changed_by_patch": True, "origin": "generated", "yaml_path": "", "map_ids": d["map_ids"],"data_recipes": [], "learned": {"recent_failures": 0, "last_label": None}} for d in proposals]slim = [{k: c[k] for k in ("id", "title", "module", "process", "priority", "new_or_changed", "changed_by_patch", "origin","yaml_path", "map_ids", "data_recipes", "learned")} | {"already_approved": c.get("already_approved", False)}for c in keep]# Fusion pods with an AI model on: new scenarios written by the model, dry-run on the pod before the gateai = ai_scenarios.write_ai_scenarios(state, svc, case_lib.load_all(svc, mods) if only and mods else library)out = {"test_cases": slim + gen_cases + ai.get("cases", []), "deferred": deferred, "proposed_cases": proposals,"approvals": {"pulled_in_changed_by_patch": pulled}, "llm_calls": [resp.record]}if ai:out["ai_drafts"] = ai["drafts"]if fusion and cmap.get("rows"): # the release changes a scenario of this run covers are no longer gapsby_row: dict[tuple[str, str], list[str]] = {}for c in out["test_cases"]:for rid in c.get("map_ids") or []:by_row.setdefault((c["module"], rid), []).append(c["id"])rows = [{**r, "gap": False, "gap_reason": None, "covered_by": by_row[(r["module"], r["row_id"])]} if (r["module"], r["row_id"]) in by_rowelse r for r in cmap["rows"]]out["coverage_map"] = {**cmap, "rows": rows}return out# ====================================================================== approval_gatedef _diff_for(svc, c: dict, proposals: dict) -> str | None:if c["origin"] == "generated":return yaml.safe_dump(proposals.get(c["id"], {}), sort_keys=False)if c["origin"] == ai_scenarios.AI_ORIGIN: # the draft's YAML as the model wrote itp = Path(c.get("yaml_path") or "")return p.read_text(encoding="utf-8") if p.is_file() else Noneif c.get("yaml_path"):try:d = svc.library.diff_worktree(ROOT / c["yaml_path"]) if svc.library.exists() else ""except Exception: # noqa: BLE001d = ""return d or Nonereturn Nonedef approval_gate(state, config, svc) -> dict:"""LangGraph node: prepare -> interrupt (human) -> apply. The Temporal workflow calls the same two halves around a signal."""payload, update = approval_prepare(state, svc)if payload is None:return updatereturn approval_apply(state, svc, payload, interrupt(payload))def approval_prepare(state, svc) -> tuple[dict | None, dict | None]:"""(gate payload, None) when a human must decide; (None, state update) when nothing is pending."""run_id = state["run_id"]cases = state.get("test_cases") or []proposals = {p["id"]: p for p in state.get("proposed_cases") or []}need = [c for c in cases if c["new_or_changed"] or c["origin"] in ("generated", ai_scenarios.AI_ORIGIN) or c.get("changed_by_patch")]auto: list[str] = []for m in sorted({c["module"] for c in need}): # scenarios written by the AI model always wait for a personauto += svc.autonomy.auto_approvals(m, [c for c in need if c["module"] == m and c["origin"] != ai_scenarios.AI_ORIGIN])pending = [c for c in need if c["id"] not in auto]levels = {m: svc.autonomy.level(m) for m in sorted({c["module"] for c in cases})}policy = max(levels.values(), default="L0")if not pending:for cid in auto:svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid, "decision": "approved","actor": "autonomy", "ts": now_iso(), "auto": 1}, ('run_id', 'gate', 'case_id'))return None, {"approvals": {"cases": {"auto": auto or "no new, changed or generated cases", "policy": policy}}}ai = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}payload = {"gate": "approve_cases", "policy": policy, "levels": levels, "auto_approved": auto,"pending": [{"id": c["id"], "title": c["title"], "module": c["module"], "priority": c["priority"],"origin": c["origin"], "changed_by_patch": c.get("changed_by_patch", False),"new_or_changed": c["new_or_changed"], "yaml_path": c.get("yaml_path") or None,"diff": _diff_for(svc, c, proposals)}| ({"ai": ai_scenarios.gate_view(ai[c["id"]])} if c["origin"] == ai_scenarios.AI_ORIGIN and c["id"] in ai else {})for c in pending]}not_runnable = [ai_scenarios.gate_view(d) for d in state.get("ai_drafts") or [] if not d.get("runnable")]if not_runnable: # written by the model but failed the dry run (or the checks): shown with the failure, not offeredpayload["ai_not_runnable"] = not_runnablereturn payload, Nonedef approval_apply(state, svc, payload: dict, answer) -> dict:run_id = state["run_id"]cases = state.get("test_cases") or []proposals = {p["id"]: p for p in state.get("proposed_cases") or []}pending = payload["pending"]auto = list(payload.get("auto_approved") or [])policy = payload.get("policy", "L0")answer = answer if isinstance(answer, dict) else {}actor = str(answer.get("actor") or "unknown")pend_ids = [c["id"] for c in pending]approved = [i for i in pend_ids if i in set(answer.get("approved") or [])]rejected = [i for i in pend_ids if i not in approved]comments = answer.get("comments") or {}for cid in approved + rejected:svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid,"decision": "approved" if cid in approved else "rejected", "actor": actor,"comment": comments.get(cid), "ts": now_iso(), "auto": 0}, ('run_id', 'gate', 'case_id'))for cid in auto:svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid, "decision": "approved","actor": "autonomy", "ts": now_iso(), "auto": 1}, ('run_id', 'gate', 'case_id'))svc.audit.append("gate.approve_cases", actor=actor, run_id=run_id, node="approval_gate",summary=f"{len(approved)} approved, {len(rejected)} rejected, {len(auto)} auto",payload={"approved": approved, "rejected": rejected, "auto": auto, "comments": comments})# write-back: library YAML approval line + library commit; generated drafts -> var/runs/<id>/proposed-cases/date = datetime.now(timezone.utc).strftime("%Y-%m-%d")by_id = {c["id"]: c for c in cases}changed_paths = []if svc.cfg.case_writeback:for cid in approved:c = by_id[cid]if c["origin"] == "library" and c.get("yaml_path") and not c.get("already_approved"):p = ROOT / c["yaml_path"]text = p.read_text(encoding="utf-8")new = case_lib.rewrite_approval_line(text, f"approved {date} by {actor} (run {run_id})")if new != text:p.write_text(new, encoding="utf-8", newline="")changed_paths.append(p)commit = Noneif changed_paths and svc.library.exists():try:commit = svc.library.commit(changed_paths, f"approve {len(changed_paths)} case(s) in run {run_id}", actor)except Exception as e: # noqa: BLE001svc.audit.append("library.error", actor="system", run_id=run_id, summary=str(e)[:300])pdir = svc.run_dir(run_id) / "proposed-cases"for cid in approved:if cid in proposals:pdir.mkdir(parents=True, exist_ok=True)d = {k: v for k, v in proposals[cid].items() if k != "origin"}d["approval_status"] = f"approved {date} by {actor} (run {run_id}) - generated draft, not yet promoted"(pdir / f"{cid}.yaml").write_text(f"# Generated draft (co-worker). UNVERIFIED. Target: {svc.target(run_id)}.\n"+ yaml.safe_dump(d, sort_keys=False), encoding="utf-8")ai_upd: dict = {}if state.get("ai_drafts"): # approved AI drafts join the script library; rejected ones stay in stagingai_upd = ai_scenarios.approve_drafts(state, svc, [i for i in approved if by_id.get(i, {}).get("origin") == ai_scenarios.AI_ORIGIN], actor)cases = ai_upd["test_cases"]keep = [c for c in cases if c["id"] not in rejected]deferred = list(state.get("deferred") or []) + [{"id": i, "priority": by_id[i]["priority"], "reason": "rejected at approval gate"}for i in rejected]out = {"test_cases": keep, "deferred": deferred,"approvals": {"cases": {"approved": approved, "rejected": rejected, "auto": auto, "comments": comments,"actor": actor, "policy": policy, "library_commit": commit}}}if ai_upd:out["ai_drafts"] = ai_upd["ai_drafts"]out["approvals"]["cases"]["ai_library_commit"] = ai_upd["commit"]return out# ====================================================================== script_builderdef existing_spec(case_id: str) -> Path | None:"""The case's spec in the script library: practice cases (tests/cases), smoke, and real-Fusion ones (tests/fusion)."""for p in SPEC_DIR.rglob(f"{case_id}.spec.ts"):return pfor p in (AUTOMATION / "tests" / "fusion").rglob(f"{case_id}.spec.ts"):return preturn Nonedef _nav_keys() -> set[str]:src = (AUTOMATION / "src" / "ui.ts").read_text(encoding="utf-8")m = re.search(r"export const NAV = \{(.*?)\} as const", src, re.S)return set(re.findall(r"(\w+)\s*:", m.group(1))) if m else set()PH = re.compile(r"\{\{\s*([\w.]+)\s*\}\}")def render_spec(case: dict, steps: list[dict]) -> str:"""YAML steps -> Playwright spec (deterministic template). Unresolved {{placeholders}} -> test.fixme."""fixtures = (AUTOMATION / "src" / "fixtures").as_posix()ui_mod = (AUTOMATION / "src" / "ui").as_posix()nav = _nav_keys()lines, unresolved = [], []q = json.dumpsfor s in steps:act = str(s.get("action", "")).lower()val = s.get("value")tgt = s.get("target") or {}if act == "login_as":v = str(val or "")m = PH.fullmatch(v.strip())persona = m.group(1).split(".", 1)[1] if m and m.group(1).startswith("users.") else (None if m else v)if persona:lines.append(f" await ui.login({q(persona)} as never);")else:unresolved.append(v)elif act == "navigate":v = str(val or "")m = PH.fullmatch(v.strip())key = m.group(1).split(".", 1)[1] if m and m.group(1).startswith("nav.") else Noneif key and key in nav:lines.append(f" await page.goto(NAV.{key});")else:unresolved.append(v)elif act in ("click", "fill", "select", "verify", "check"):role, name = tgt.get("role"), tgt.get("name")texts = [str(x) for x in (name, val) if x is not None]bad = [t for t in texts if PH.search(t)]if bad:unresolved += badcontinueif tgt.get("testid"):loc = f"page.getByTestId({q(tgt['testid'])})"elif tgt.get("label"):loc = f"page.getByLabel({q(tgt['label'])}, {{ exact: true }})"elif role:loc = f"page.getByRole({q(role)} as never, {{ name: {q(str(name))}, exact: true }})" if name else f"page.getByRole({q(role)} as never)"else:loc = Noneif act == "click" and loc:lines.append(f" await {loc}.click();")elif act == "fill" and loc:lines.append(f" await {loc}.fill({q(str(val or ''))});")elif act == "select" and loc:lines.append(f" await {loc}.selectOption({q(str(val or ''))});")elif act == "check" and loc:lines.append(f" await {loc}.check();")elif act == "verify":if loc and val is not None:lines.append(f" await expect({loc}).toHaveText({q(str(val))});")elif val is not None:lines.append(f" await expect(page.getByText({q(str(val))})).toBeVisible();")else:lines.append(f" // step {s.get('n', '?')} '{act}' has no template; expected: {str(s.get('expected', ''))[:100]!r}")fixme = ""if unresolved:fixme = f" test.fixme(true, {q('unresolved placeholder(s): ' + ', '.join(sorted(set(unresolved)))[:300])});\n"cid = case["id"]title = f"{cid} {case.get('title', '')}".strip()return (f"// GENERATED DRAFT for {cid} by the co-worker script_builder (deterministic template). NOT promoted.\n"f"// Runs only against the local MOCK app, never Oracle Fusion. Review before promoting.\n"f"import {{ test, expect }} from {q(fixtures)};\n"f"import {{ NAV }} from {q(ui_mod)};\n\n"f"test({q(title)}, {{ tag: [{q('@' + cid)}, '@generated'] }}, async ({{ page, ui }}) => {{\n"f"{fixme} void NAV; void expect;\n" + "\n".join(lines) + "\n});\n")def stub_build_script(payload: dict) -> ScriptDraft:return ScriptDraft(code=render_spec(payload["case"], payload.get("steps", [])))def _node(*args, cwd: Path, timeout: int = 300) -> tuple[int, str]:p = subprocess.Popen(["node", *args], cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **procs.popen_kwargs())procs.register(p, "script_builder")try:out, _ = p.communicate(timeout=timeout)except subprocess.TimeoutExpired:procs.kill_tree(p.pid)out = b"timeout"finally:procs.unregister(p)return p.returncode if p.returncode is not None else -9, out.decode("utf-8", "replace")def lint_specs(files: list[Path]) -> tuple[bool, str]:tsc = AUTOMATION / "node_modules" / "typescript" / "bin" / "tsc"args = [str(tsc), "--ignoreConfig", "--noEmit", "--strict", "--skipLibCheck", "--esModuleInterop", "--target", "ES2022", "--module", "commonjs","--types", "node", "--typeRoots", str(AUTOMATION / "node_modules" / "@types"), *[str(f) for f in files]]code, out = _node(*args, cwd=AUTOMATION)return code == 0, out[-4000:]def dry_run(drafts_dir: Path, ids: list[str]) -> tuple[bool, str]:import oscli = AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"grep = "(?:" + "|".join("@" + re.escape(i) for i in ids) + ")(?![\\w-])"env_backup = {k: os.environ.get(k) for k in ("FPT_DRAFTS_DIR", "PLAYWRIGHT_MODE")}os.environ["FPT_DRAFTS_DIR"], os.environ["PLAYWRIGHT_MODE"] = str(drafts_dir), "live"try:code, out = _node(str(cli), "test", "--config", "playwright.agent.config.ts", "--list", "--project", "drafts","--grep", grep, cwd=AUTOMATION)finally:for k, v in env_backup.items():if v is None:os.environ.pop(k, None)else:os.environ[k] = vreturn code == 0 and all(i in out for i in ids), out[-4000:]def script_builder(state, config, svc) -> dict:run_id = state["run_id"]proposals = {p["id"]: p for p in state.get("proposed_cases") or []}scripts: dict = {}to_build = []ai = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}for c in state.get("test_cases") or []:if c["origin"] == ai_scenarios.AI_ORIGIN: # written by the model, dry-run on the pod, approved at the gated = ai.get(c["id"], {})sp = Path(d.get("spec_path") or "")scripts[c["id"]] = {"case_id": c["id"], "path": str(sp), "status": "existing" if d.get("status") == "promoted" else "generated","lint_ok": None, "dry_run_ok": bool(d.get("runnable")) and sp.is_file(), "draft_id": None}continuesp = existing_spec(c["id"])if sp:scripts[c["id"]] = {"case_id": c["id"], "path": sp.relative_to(ROOT).as_posix(), "status": "existing","lint_ok": None, "dry_run_ok": None, "draft_id": None}continueif c["origin"] == "generated":steps = proposals.get(c["id"], {}).get("steps", [])else:p = case_lib.find_yaml(c["id"])steps = (case_lib.load_doc(p) or {}).get("steps", []) if p else []to_build.append((c, steps))if not to_build:return {"scripts": scripts}if state.get("playwright_mode") == "stub":for c, _ in to_build:scripts[c["id"]] = {"case_id": c["id"], "path": "", "status": "missing", "lint_ok": None, "dry_run_ok": None,"draft_id": None, "note": "stub mode: no draft generated (no browser run)"}return {"scripts": scripts}out_dir = svc.cfg.path("staging", "specs", run_id)out_dir.mkdir(parents=True, exist_ok=True)calls, files = [], {}for c, steps in to_build:req = LLMRequest("build_script", Sensitivity.CLIENT, {"case": {"id": c["id"], "title": c["title"]}, "steps": steps},ScriptDraft, "script_builder", run_id, stub_build_script({"case": c, "steps": steps}))resp = svc.router.call(req)calls.append(resp.record)f = out_dir / f"{c['id']}.spec.ts"f.write_text(resp.output.code, encoding="utf-8") # type: ignore[attr-defined]files[c["id"]] = flint_ok, lint_log = lint_specs(list(files.values()))dry_ok, dry_log = dry_run(out_dir, list(files))for cid, f in files.items():c = next(x for x, _ in to_build if x["id"] == cid)yaml_path = ""if c["origin"] == "generated":yp = svc.run_dir(run_id) / "proposed-cases" / f"{cid}.yaml"yaml_path = str(yp) if yp.exists() else ""else:yaml_path = c.get("yaml_path", "")did = svc.db.insert("drafts", {"run_id": run_id, "case_id": cid, "module": c["module"], "yaml_path": yaml_path,"spec_path": str(f), "lint_ok": int(lint_ok), "dry_run_ok": int(dry_ok and cid in dry_log),"lint_log": (lint_log + "\n---\n" + dry_log)[-6000:], "status": "staged", "created_at": now_iso()})scripts[cid] = {"case_id": cid, "path": str(f), "status": "generated", "lint_ok": lint_ok,"dry_run_ok": dry_ok and cid in dry_log, "draft_id": did}return {"scripts": scripts, "llm_calls": calls}STUB_TASKS = {"generate_tests": stub_generate_tests, "build_script": stub_build_script}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450"""Design phase: test_generator -> approval_gate (human interrupt / earned autonomy) -> (data) -> script_builder.Library cases are reused; drafts are proposed for patch-touched gap rows; generated specs are staged OUTSIDE automation/until a human promotes them."""from __future__ import annotationsimport jsonimport reimport subprocessfrom datetime import datetime, timezonefrom pathlib import Pathimport yamlfrom langgraph.types import interruptfrom ...adapters import cases as case_libfrom ...adapters.legacy import select_scopefrom ...config import ROOTfrom ...llm.base import LLMRequest, Sensitivityfrom ...llm.schemas import CaseProposals, ScriptDraftfrom ...platform import procsfrom ...platform.rundb import now_isofrom . import ai_scenariosfrom .research import scope_modulesAUTOMATION = ROOT / "automation"SPEC_DIR = AUTOMATION / "tests" / "cases"PRIO_ORDER = {"P1": 0, "P2": 1, "P3": 2, "P4": 3}# ====================================================================== test_generatordef gen_id(module: str, row_id: str) -> str:return f"{module}-GEN-{re.sub(r'[^A-Z0-9]', '', row_id.upper())}-001"def stub_generate_tests(payload: dict) -> CaseProposals:out = []for r in payload.get("rows", []):out.append({"id": gen_id(r["module"], r["row_id"]), "title": f"Generated smoke for {r['row_id']}: {r['process'][:80]}","module": r["module"], "process": r["process"][:120], "priority": r["tier"], "map_ids": [r["row_id"]],"steps": [{"action": "login_as", "value": r.get("persona") or "auditor_ro","expected": "Home page loads for the persona; no error banner."},{"action": "verify", "target": {"testid": "page-title"}, "value": "Home","expected": "Home page title shown."}],"rationale": "Row touched by the patch (research) and no designed case cites it (gap)."})return CaseProposals.model_validate({"cases": out})def test_generator(state, config, svc) -> dict:run_id = state["run_id"]mods = scope_modules(state)include_p2 = bool(state.get("include_p2"))cmap = state.get("coverage_map") or {"rows": []}touched = {(r["module"], r["row_id"]) for r in cmap["rows"] if r["touched_by_patch"]}library = case_lib.load_all(svc, mods) if mods else [] # with the approved scenarios of the persistent library# a real Fusion pod runs only Fusion scenarios (steps or Fusion scripts), the practice pod only its ownfusion = svc.fusion_pod_id(run_id) is not Nonelibrary = [c for c in library if c.get("target", "practice") == ("fusion" if fusion else "practice")]only = set(state.get("case_filter") or [])if only:library = [c for c in library if c["id"] in only]active, deferred = [], []for c in library:c["changed_by_patch"] = any((c["module"], rid) in touched for rid in c["map_ids"])hist = svc.memory.case_history(c["id"], 10)c["learned"] = {"recent_failures": sum(1 for h in hist if h["category"]), "last_label": next((h["human_label"] for h in hist if h["human_label"]), None)}if c["lifecycle"]:deferred.append({"id": c["id"], "priority": c["priority"], "reason": f"{c['lifecycle']} (tests/README.md lifecycle, qa/audit.py case_flags)"})else:active.append(c)depth = state.get("depth") or "standard"if depth == "full": # the whole regression pack of the areas: every priority, every approved scenariokeep, out_of_scope = list(active), []else:keep, out_of_scope = select_scope(active, include_p2 and depth != "smoke")pulled = []for d in list(out_of_scope):c = next(x for x in active if x["id"] == d["id"])if depth == "standard" and c["priority"] == "P2" and c["changed_by_patch"] and not include_p2 and not only:keep.append(c)pulled.append(c["id"])out_of_scope.remove(d)deferred += out_of_scopekeep.sort(key=lambda c: (PRIO_ORDER.get(c["priority"], 9), -c["learned"]["recent_failures"], c["id"]))# proposals for gap rows touched by the patchon_pod = {m["module"]: m for m in (state.get("pod_profile") or {}).get("modules", [])}gap_rows = [] if only or fusion else [r for r in cmap["rows"] if r["gap"] and r["touched_by_patch"] and r["module"] in mods]uniq = {}for r in gap_rows:uniq.setdefault((r["module"], r["row_id"]), r)rows_payload = [{"module": r["module"], "row_id": r["row_id"], "process": r["process"], "tier": r["tier"],"persona": on_pod.get(r["module"], {}).get("scout_persona")} for r in uniq.values()]baseline = stub_generate_tests({"rows": rows_payload})red, mapping = svc.redactor.redact({"rows": rows_payload, "row_ids": [r["row_id"] for r in rows_payload]})req = LLMRequest("generate_tests", Sensitivity.REDACTED, red, CaseProposals, "test_generator", run_id, baseline)resp = svc.router.call(req)out = svc.redactor.restore(resp.output.model_dump(), mapping)proposals = []existing = {c["id"] for c in library}for d in out["cases"]:if d["id"] in existing:continued.update({"origin": "generated", "approval_status": "draft - generated by co-worker, pending approval","verification": "UNVERIFIED", "notes": ["Generated draft. Runs against the mock prove only the mock, never Oracle Fusion."]})proposals.append(d)gen_cases = [{"id": d["id"], "title": d["title"], "module": d["module"], "process": d["process"], "priority": d["priority"],"new_or_changed": True, "changed_by_patch": True, "origin": "generated", "yaml_path": "", "map_ids": d["map_ids"],"data_recipes": [], "learned": {"recent_failures": 0, "last_label": None}} for d in proposals]slim = [{k: c[k] for k in ("id", "title", "module", "process", "priority", "new_or_changed", "changed_by_patch", "origin","yaml_path", "map_ids", "data_recipes", "learned")} | {"already_approved": c.get("already_approved", False)}for c in keep]# Fusion pods with an AI model on: new scenarios written by the model, dry-run on the pod before the gateai = ai_scenarios.write_ai_scenarios(state, svc, case_lib.load_all(svc, mods) if only and mods else library)out = {"test_cases": slim + gen_cases + ai.get("cases", []), "deferred": deferred, "proposed_cases": proposals,"approvals": {"pulled_in_changed_by_patch": pulled}, "llm_calls": [resp.record]}if ai:out["ai_drafts"] = ai["drafts"]if fusion and cmap.get("rows"): # the release changes a scenario of this run covers are no longer gapsby_row: dict[tuple[str, str], list[str]] = {}for c in out["test_cases"]:for rid in c.get("map_ids") or []:by_row.setdefault((c["module"], rid), []).append(c["id"])rows = [{**r, "gap": False, "gap_reason": None, "covered_by": by_row[(r["module"], r["row_id"])]} if (r["module"], r["row_id"]) in by_rowelse r for r in cmap["rows"]]out["coverage_map"] = {**cmap, "rows": rows}return out# ====================================================================== approval_gatedef _diff_for(svc, c: dict, proposals: dict) -> str | None:if c["origin"] == "generated":return yaml.safe_dump(proposals.get(c["id"], {}), sort_keys=False)if c["origin"] == ai_scenarios.AI_ORIGIN: # the draft's YAML as the model wrote itp = Path(c.get("yaml_path") or "")return p.read_text(encoding="utf-8") if p.is_file() else Noneif c.get("yaml_path"):try:d = svc.library.diff_worktree(ROOT / c["yaml_path"]) if svc.library.exists() else ""except Exception: # noqa: BLE001d = ""return d or Nonereturn Nonedef approval_gate(state, config, svc) -> dict:"""LangGraph node: prepare -> interrupt (human) -> apply. The Temporal workflow calls the same two halves around a signal."""payload, update = approval_prepare(state, svc)if payload is None:return updatereturn approval_apply(state, svc, payload, interrupt(payload))def approval_prepare(state, svc) -> tuple[dict | None, dict | None]:"""(gate payload, None) when a human must decide; (None, state update) when nothing is pending."""run_id = state["run_id"]cases = state.get("test_cases") or []proposals = {p["id"]: p for p in state.get("proposed_cases") or []}need = [c for c in cases if c["new_or_changed"] or c["origin"] in ("generated", ai_scenarios.AI_ORIGIN) or c.get("changed_by_patch")]auto: list[str] = []for m in sorted({c["module"] for c in need}): # scenarios written by the AI model always wait for a personauto += svc.autonomy.auto_approvals(m, [c for c in need if c["module"] == m and c["origin"] != ai_scenarios.AI_ORIGIN])pending = [c for c in need if c["id"] not in auto]levels = {m: svc.autonomy.level(m) for m in sorted({c["module"] for c in cases})}policy = max(levels.values(), default="L0")if not pending:for cid in auto:svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid, "decision": "approved","actor": "autonomy", "ts": now_iso(), "auto": 1}, ('run_id', 'gate', 'case_id'))return None, {"approvals": {"cases": {"auto": auto or "no new, changed or generated cases", "policy": policy}}}ai = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}payload = {"gate": "approve_cases", "policy": policy, "levels": levels, "auto_approved": auto,"pending": [{"id": c["id"], "title": c["title"], "module": c["module"], "priority": c["priority"],"origin": c["origin"], "changed_by_patch": c.get("changed_by_patch", False),"new_or_changed": c["new_or_changed"], "yaml_path": c.get("yaml_path") or None,"diff": _diff_for(svc, c, proposals)}| ({"ai": ai_scenarios.gate_view(ai[c["id"]])} if c["origin"] == ai_scenarios.AI_ORIGIN and c["id"] in ai else {})for c in pending]}not_runnable = [ai_scenarios.gate_view(d) for d in state.get("ai_drafts") or [] if not d.get("runnable")]if not_runnable: # written by the model but failed the dry run (or the checks): shown with the failure, not offeredpayload["ai_not_runnable"] = not_runnablereturn payload, Nonedef approval_apply(state, svc, payload: dict, answer) -> dict:run_id = state["run_id"]cases = state.get("test_cases") or []proposals = {p["id"]: p for p in state.get("proposed_cases") or []}pending = payload["pending"]auto = list(payload.get("auto_approved") or [])policy = payload.get("policy", "L0")answer = answer if isinstance(answer, dict) else {}actor = str(answer.get("actor") or "unknown")pend_ids = [c["id"] for c in pending]approved = [i for i in pend_ids if i in set(answer.get("approved") or [])]rejected = [i for i in pend_ids if i not in approved]comments = answer.get("comments") or {}for cid in approved + rejected:svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid,"decision": "approved" if cid in approved else "rejected", "actor": actor,"comment": comments.get(cid), "ts": now_iso(), "auto": 0}, ('run_id', 'gate', 'case_id'))for cid in auto:svc.db.insert_once("approvals", {"run_id": run_id, "gate": "approve_cases", "case_id": cid, "decision": "approved","actor": "autonomy", "ts": now_iso(), "auto": 1}, ('run_id', 'gate', 'case_id'))svc.audit.append("gate.approve_cases", actor=actor, run_id=run_id, node="approval_gate",summary=f"{len(approved)} approved, {len(rejected)} rejected, {len(auto)} auto",payload={"approved": approved, "rejected": rejected, "auto": auto, "comments": comments})# write-back: library YAML approval line + library commit; generated drafts -> var/runs/<id>/proposed-cases/date = datetime.now(timezone.utc).strftime("%Y-%m-%d")by_id = {c["id"]: c for c in cases}changed_paths = []if svc.cfg.case_writeback:for cid in approved:c = by_id[cid]if c["origin"] == "library" and c.get("yaml_path") and not c.get("already_approved"):p = ROOT / c["yaml_path"]text = p.read_text(encoding="utf-8")new = case_lib.rewrite_approval_line(text, f"approved {date} by {actor} (run {run_id})")if new != text:p.write_text(new, encoding="utf-8", newline="")changed_paths.append(p)commit = Noneif changed_paths and svc.library.exists():try:commit = svc.library.commit(changed_paths, f"approve {len(changed_paths)} case(s) in run {run_id}", actor)except Exception as e: # noqa: BLE001svc.audit.append("library.error", actor="system", run_id=run_id, summary=str(e)[:300])pdir = svc.run_dir(run_id) / "proposed-cases"for cid in approved:if cid in proposals:pdir.mkdir(parents=True, exist_ok=True)d = {k: v for k, v in proposals[cid].items() if k != "origin"}d["approval_status"] = f"approved {date} by {actor} (run {run_id}) - generated draft, not yet promoted"(pdir / f"{cid}.yaml").write_text(f"# Generated draft (co-worker). UNVERIFIED. Target: {svc.target(run_id)}.\n"+ yaml.safe_dump(d, sort_keys=False), encoding="utf-8")ai_upd: dict = {}if state.get("ai_drafts"): # approved AI drafts join the script library; rejected ones stay in stagingai_upd = ai_scenarios.approve_drafts(state, svc, [i for i in approved if by_id.get(i, {}).get("origin") == ai_scenarios.AI_ORIGIN], actor)cases = ai_upd["test_cases"]keep = [c for c in cases if c["id"] not in rejected]deferred = list(state.get("deferred") or []) + [{"id": i, "priority": by_id[i]["priority"], "reason": "rejected at approval gate"}for i in rejected]out = {"test_cases": keep, "deferred": deferred,"approvals": {"cases": {"approved": approved, "rejected": rejected, "auto": auto, "comments": comments,"actor": actor, "policy": policy, "library_commit": commit}}}if ai_upd:out["ai_drafts"] = ai_upd["ai_drafts"]out["approvals"]["cases"]["ai_library_commit"] = ai_upd["commit"]return out# ====================================================================== script_builderdef existing_spec(case_id: str) -> Path | None:"""The case's spec in the script library: practice cases (tests/cases), smoke, and real-Fusion ones (tests/fusion)."""for p in SPEC_DIR.rglob(f"{case_id}.spec.ts"):return pfor p in (AUTOMATION / "tests" / "fusion").rglob(f"{case_id}.spec.ts"):return preturn Nonedef _nav_keys() -> set[str]:src = (AUTOMATION / "src" / "ui.ts").read_text(encoding="utf-8")m = re.search(r"export const NAV = \{(.*?)\} as const", src, re.S)return set(re.findall(r"(\w+)\s*:", m.group(1))) if m else set()PH = re.compile(r"\{\{\s*([\w.]+)\s*\}\}")def render_spec(case: dict, steps: list[dict]) -> str:"""YAML steps -> Playwright spec (deterministic template). Unresolved {{placeholders}} -> test.fixme."""fixtures = (AUTOMATION / "src" / "fixtures").as_posix()ui_mod = (AUTOMATION / "src" / "ui").as_posix()nav = _nav_keys()lines, unresolved = [], []q = json.dumpsfor s in steps:act = str(s.get("action", "")).lower()val = s.get("value")tgt = s.get("target") or {}if act == "login_as":v = str(val or "")m = PH.fullmatch(v.strip())persona = m.group(1).split(".", 1)[1] if m and m.group(1).startswith("users.") else (None if m else v)if persona:lines.append(f" await ui.login({q(persona)} as never);")else:unresolved.append(v)elif act == "navigate":v = str(val or "")m = PH.fullmatch(v.strip())key = m.group(1).split(".", 1)[1] if m and m.group(1).startswith("nav.") else Noneif key and key in nav:lines.append(f" await page.goto(NAV.{key});")else:unresolved.append(v)elif act in ("click", "fill", "select", "verify", "check"):role, name = tgt.get("role"), tgt.get("name")texts = [str(x) for x in (name, val) if x is not None]bad = [t for t in texts if PH.search(t)]if bad:unresolved += badcontinueif tgt.get("testid"):loc = f"page.getByTestId({q(tgt['testid'])})"elif tgt.get("label"):loc = f"page.getByLabel({q(tgt['label'])}, {{ exact: true }})"elif role:loc = f"page.getByRole({q(role)} as never, {{ name: {q(str(name))}, exact: true }})" if name else f"page.getByRole({q(role)} as never)"else:loc = Noneif act == "click" and loc:lines.append(f" await {loc}.click();")elif act == "fill" and loc:lines.append(f" await {loc}.fill({q(str(val or ''))});")elif act == "select" and loc:lines.append(f" await {loc}.selectOption({q(str(val or ''))});")elif act == "check" and loc:lines.append(f" await {loc}.check();")elif act == "verify":if loc and val is not None:lines.append(f" await expect({loc}).toHaveText({q(str(val))});")elif val is not None:lines.append(f" await expect(page.getByText({q(str(val))})).toBeVisible();")else:lines.append(f" // step {s.get('n', '?')} '{act}' has no template; expected: {str(s.get('expected', ''))[:100]!r}")fixme = ""if unresolved:fixme = f" test.fixme(true, {q('unresolved placeholder(s): ' + ', '.join(sorted(set(unresolved)))[:300])});\n"cid = case["id"]title = f"{cid} {case.get('title', '')}".strip()return (f"// GENERATED DRAFT for {cid} by the co-worker script_builder (deterministic template). NOT promoted.\n"f"// Runs only against the local MOCK app, never Oracle Fusion. Review before promoting.\n"f"import {{ test, expect }} from {q(fixtures)};\n"f"import {{ NAV }} from {q(ui_mod)};\n\n"f"test({q(title)}, {{ tag: [{q('@' + cid)}, '@generated'] }}, async ({{ page, ui }}) => {{\n"f"{fixme} void NAV; void expect;\n" + "\n".join(lines) + "\n});\n")def stub_build_script(payload: dict) -> ScriptDraft:return ScriptDraft(code=render_spec(payload["case"], payload.get("steps", [])))def _node(*args, cwd: Path, timeout: int = 300) -> tuple[int, str]:p = subprocess.Popen(["node", *args], cwd=str(cwd), stdout=subprocess.PIPE, stderr=subprocess.STDOUT, **procs.popen_kwargs())procs.register(p, "script_builder")try:out, _ = p.communicate(timeout=timeout)except subprocess.TimeoutExpired:procs.kill_tree(p.pid)out = b"timeout"finally:procs.unregister(p)return p.returncode if p.returncode is not None else -9, out.decode("utf-8", "replace")def lint_specs(files: list[Path]) -> tuple[bool, str]:tsc = AUTOMATION / "node_modules" / "typescript" / "bin" / "tsc"args = [str(tsc), "--ignoreConfig", "--noEmit", "--strict", "--skipLibCheck", "--esModuleInterop", "--target", "ES2022", "--module", "commonjs","--types", "node", "--typeRoots", str(AUTOMATION / "node_modules" / "@types"), *[str(f) for f in files]]code, out = _node(*args, cwd=AUTOMATION)return code == 0, out[-4000:]def dry_run(drafts_dir: Path, ids: list[str]) -> tuple[bool, str]:import oscli = AUTOMATION / "node_modules" / "@playwright" / "test" / "cli.js"grep = "(?:" + "|".join("@" + re.escape(i) for i in ids) + ")(?![\\w-])"env_backup = {k: os.environ.get(k) for k in ("FPT_DRAFTS_DIR", "PLAYWRIGHT_MODE")}os.environ["FPT_DRAFTS_DIR"], os.environ["PLAYWRIGHT_MODE"] = str(drafts_dir), "live"try:code, out = _node(str(cli), "test", "--config", "playwright.agent.config.ts", "--list", "--project", "drafts","--grep", grep, cwd=AUTOMATION)finally:for k, v in env_backup.items():if v is None:os.environ.pop(k, None)else:os.environ[k] = vreturn code == 0 and all(i in out for i in ids), out[-4000:]def script_builder(state, config, svc) -> dict:run_id = state["run_id"]proposals = {p["id"]: p for p in state.get("proposed_cases") or []}scripts: dict = {}to_build = []ai = {d["id"]: d for d in state.get("ai_drafts") or [] if d.get("id")}for c in state.get("test_cases") or []:if c["origin"] == ai_scenarios.AI_ORIGIN: # written by the model, dry-run on the pod, approved at the gated = ai.get(c["id"], {})sp = Path(d.get("spec_path") or "")scripts[c["id"]] = {"case_id": c["id"], "path": str(sp), "status": "existing" if d.get("status") == "promoted" else "generated","lint_ok": None, "dry_run_ok": bool(d.get("runnable")) and sp.is_file(), "draft_id": None}continuesp = existing_spec(c["id"])if sp:scripts[c["id"]] = {"case_id": c["id"], "path": sp.relative_to(ROOT).as_posix(), "status": "existing","lint_ok": None, "dry_run_ok": None, "draft_id": None}continue# a scenario a person approved earlier lives in the server's library (FPT_HOME/library), not in the code: it# has its spec there and runs from the library project. Building it again wrote a practice-app template into# the run's drafts, which on a Fusion pod failed at once and ran the scenario twice (seen live)lib = ai_scenarios.library_root(svc) / "automation" / "tests" / "fusion" / "steps" / f"{c['id']}.spec.ts"if lib.is_file():scripts[c["id"]] = {"case_id": c["id"], "path": str(lib), "status": "existing","lint_ok": None, "dry_run_ok": None, "draft_id": None}continueif c["origin"] == "generated":steps = proposals.get(c["id"], {}).get("steps", [])else:p = case_lib.find_yaml(c["id"])steps = (case_lib.load_doc(p) or {}).get("steps", []) if p else []to_build.append((c, steps))if not to_build:return {"scripts": scripts}if state.get("playwright_mode") == "stub":for c, _ in to_build:scripts[c["id"]] = {"case_id": c["id"], "path": "", "status": "missing", "lint_ok": None, "dry_run_ok": None,"draft_id": None, "note": "stub mode: no draft generated (no browser run)"}return {"scripts": scripts}out_dir = svc.cfg.path("staging", "specs", run_id)out_dir.mkdir(parents=True, exist_ok=True)calls, files = [], {}for c, steps in to_build:req = LLMRequest("build_script", Sensitivity.CLIENT, {"case": {"id": c["id"], "title": c["title"]}, "steps": steps},ScriptDraft, "script_builder", run_id, stub_build_script({"case": c, "steps": steps}))resp = svc.router.call(req)calls.append(resp.record)f = out_dir / f"{c['id']}.spec.ts"f.write_text(resp.output.code, encoding="utf-8") # type: ignore[attr-defined]files[c["id"]] = flint_ok, lint_log = lint_specs(list(files.values()))dry_ok, dry_log = dry_run(out_dir, list(files))for cid, f in files.items():c = next(x for x, _ in to_build if x["id"] == cid)yaml_path = ""if c["origin"] == "generated":yp = svc.run_dir(run_id) / "proposed-cases" / f"{cid}.yaml"yaml_path = str(yp) if yp.exists() else ""else:yaml_path = c.get("yaml_path", "")did = svc.db.insert("drafts", {"run_id": run_id, "case_id": cid, "module": c["module"], "yaml_path": yaml_path,"spec_path": str(f), "lint_ok": int(lint_ok), "dry_run_ok": int(dry_ok and cid in dry_log),"lint_log": (lint_log + "\n---\n" + dry_log)[-6000:], "status": "staged", "created_at": now_iso()})scripts[cid] = {"case_id": cid, "path": str(f), "status": "generated", "lint_ok": lint_ok,"dry_run_ok": dry_ok and cid in dry_log, "draft_id": did}return {"scripts": scripts, "llm_calls": calls}STUB_TASKS = {"generate_tests": stub_generate_tests, "build_script": stub_build_script}
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594"""Execute phase: executor (Playwright attempt, --retries=0) and self_heal (locator rename proposal from the failure'sARIA snapshot; applied only as a retry override; the permanent fix needs human approval)."""from __future__ import annotationsimport difflibimport jsonimport refrom pathlib import Pathfrom ...adapters import playwright as pwfrom ...adapters.legacy import classifier, merge_attemptsfrom ...config import ROOTfrom ...llm.base import LLMRequest, Sensitivityfrom ...llm.schemas import HealProposalfrom . import ai_scenariosfrom ...platform import canary, liveviewfrom ...platform.killswitch import KillSwitchEngagedfrom ...platform.rundb import now_isoLOCATOR_RE = re.compile(r"getBy(Role|Label)\(\s*'([^']+)'(?:\s*,\s*\{\s*name:\s*'([^']+)')?")LOCATOR_FAIL_RE = re.compile(r"strict mode violation|waiting for getBy(Role|Label)|not found|element\(s\) not found|Timeout \d+ms exceeded", re.I)ARIA_RE = re.compile(r"^\s*-\s+([a-z]+)\s+\"([^\"]+)\"", re.M)def smoke_ids(modules: list[str]) -> list[str]:"""Tag ids of automation/tests/smoke/*.spec.ts for these modules (scripts with no YAML case, e.g. P2P-SMOKE-001)."""out = []for p in sorted((ROOT / "automation" / "tests" / "smoke").glob("*.spec.ts")):for tag in re.findall(r"['\"`]@([A-Z][A-Z0-9]{1,5}-[A-Z0-9-]+)['\"`]", p.read_text(encoding="utf-8")):if tag.split("-", 1)[0] in modules and tag not in out:out.append(tag)return outdef failing_ids(report_file: str) -> list[str]:clf = classifier()recs = clf.parse_report(clf.load_report(report_file))return [r.case_id or r.title for r in recs if r.outcome == "failed"]def outcomes(merged: str) -> tuple[dict, dict]:clf = classifier()recs = clf.parse_report(clf.load_report(merged))out = {}for r in recs:cid = r.case_id or r.titleout[cid] = r.outcomecounts = {"total": len(recs), **{k: sum(1 for r in recs if r.outcome == k) for k in ("passed", "failed", "flaky", "skipped")}}return out, countsdef browser_failure(out_file: str | Path, res: dict | None) -> str | None:"""A failure of the browser run as a whole: Playwright reported top-level errors (it could not start, a browser orworker crashed, the config failed) or exited non-zero, AND no scenario result was recorded. Then the attempt saysnothing about the scenarios and must not be read as 'all passed'. Returns the reason in words, or None."""f = Path(out_file)try:rep = json.loads(f.read_text(encoding="utf-8"))except (OSError, ValueError):return "Playwright's report could not be read, so no scenario result was recorded."_, counts = outcomes(str(f))errs = [str((e or {}).get("message") or "").strip().splitlines()[0][:200] for e in rep.get("errors") or [] if isinstance(e, dict)]code = (res or {}).get("exit_code") or 0if counts["total"] or not (errs or code):return Nonewhy = f"Playwright stopped before any scenario ran (exit {code})" if code else "Playwright stopped before any scenario ran"return why + (f": {errs[0]}" if errs and errs[0] else "") + "."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_modeif 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()scripts = state.get("scripts") or {}ids = [c["id"] for c in state.get("test_cases") or []if c["origin"] == "library" or (scripts.get(c["id"], {}).get("dry_run_ok"))]if not state.get("case_filter") and mode == "live": # full-module live runs also execute the module's smoke specs (QA C1 counts them)ids += smoke_ids(sorted({c["module"] for c in state.get("test_cases") or []}))else:ids = list(state.get("failures") or [])mods = sorted({c["module"] for c in state.get("test_cases") or []})cred_env: dict = {}for m in mods:cred_env.update(svc.vault.executor_env(m))live_on, _why = liveview.availability(svc.cfg, mode=mode, wanted=bool(state.get("live_view")), modules=mods)fusion_pod = svc.fusion_pod_id(run_id)config, groups = None, Noneif fusion_pod is not None and mode == "live": # a real Fusion pod: its own test set, its test user from the vaultfrom ...platform.pods import PodRegistryreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)cred_env.update(reg.executor_env(fusion_pod, run_id) or {})config = "playwright.fusion.config.ts"groups = user_groups(reg, fusion_pod, run_id, ids, {c["id"]: c["module"] for c in state.get("test_cases") or []}, cred_env)return {"run_id": run_id, "attempt": attempt, "ids": ids, "mode": mode, "files": files, "run_dir": str(run_dir), "config": config,"live_dir": str(liveview.live_dir(svc.cfg, run_id)) if live_on and ids else None,"out_file": str(run_dir / f"attempt-{attempt}.json"), "stub_knobs": state.get("stub_knobs"),"drafts_dir": str(svc.cfg.path("staging", "specs", run_id)),"library_dir": str(ai_scenarios.library_root(svc) / "automation" / "tests" / "fusion" / "steps"),"overrides": str(run_dir / "heal-overrides.json") if attempt == 1 else None, "cred_env": cred_env, "groups": groups,"run_dirs": list((state.get("run_results") or {}).get("run_dirs") or [])}def user_groups(reg, pod_id: int, run_id: str, ids: list[str], module_of: dict[str, str], base_env: dict) -> list[dict] | None:"""Each area's scenarios signed in as that area's test user (FPT_FUSION_AREA_USERS): one Playwright pass per user,in the order the areas come. None when every scenario uses the same user (one pass, as before)."""envs: dict[str, dict] = {}groups: dict[str, dict] = {}for cid in ids:area = (module_of.get(cid) or cid.split("-", 1)[0]).upper()if area not in envs:envs[area] = reg.executor_env(pod_id, run_id, area=area) or {}user = envs[area].get("FUSION_USERNAME") or ""g = groups.setdefault(user, {"user": user, "areas": [], "ids": [], "cred_env": {**base_env, **envs[area]}})if area not in g["areas"]:g["areas"].append(area)g["ids"].append(cid)return list(groups.values()) if len(groups) > 1 else NoneFUSION_CONFIG = "playwright.fusion.config.ts"STARTUP_MINUTES = 10 # a pass's own start-up: Playwright, the browser and the test user's one sign-indef 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 thatrun 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):passdef _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 thesame 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 ofthem, or the runner job it was following, is still in the run folder. A first entry finds neither."""from ...adapters.remote_runner import saved_jobjob = 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 (LangGraph path): one Playwright invocation for the attempt; one per test user when the areas signin as different users (plan["groups"]), merged into the attempt's one report. On a Fusion pod an attempt runs inpasses 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, asunder Temporal), each with its own time budget and report, merged into the attempt's one report. A pass that runsout of time loses only its own scenarios (recorded as timed out, so the retry runs them), and the finished passes arelisted 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] = fif run_dir:dirs[k] = run_dirtmp = 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") == FUSION_CONFIG:from ...adapters.remote_runner import run_attempt_remote # Oracle's edge refuses this host: the browser runs theretoken = svc.vault.get("remote_runner.token") or ""if token:svc.redactor.add_secrets([token])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: _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"))if plan.get("config"):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,overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, cred_env=plan["cred_env"],backend=svc.cfg.executor_backend, log_dir=Path(plan["run_dir"]),live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, **extra)def run_groups(plan: dict, svc, **extra) -> dict:out = Path(plan["out_file"])used = pw.testdata_used_file(out)files, dirs, lines, code, timed_out = [], [], [], 0, Falsefor k, g in enumerate(plan["groups"]):svc.db.add_event(plan["run_id"], "executor", "progress", {"attempt": plan["attempt"], "user": g["user"], "areas": g["areas"],"scenarios": len(g["ids"]), "pass": k + 1, "of": len(plan["groups"])})sub = {**plan, "ids": g["ids"], "cred_env": g["cred_env"], "groups": None, "tag": f"-u{k}","out_file": str(out.with_name(f"{out.stem}.u{k}.json"))}res = run_planned(sub, svc, **extra) or {}f = Path(sub["out_file"])if f.exists():files.append(f)dirs += res.get("run_dirs") or ([res["run_dir"]] if res.get("run_dir") else [])code, timed_out = code or res.get("exit_code") or 0, timed_out or bool(res.get("timed_out"))if used.exists(): # each pass writes the values it tried to the same file: keep them all for learn_test_datalines.append(used.read_text(encoding="utf-8"))used.unlink()pw.merge_chunk_reports(files, out)if lines:used.write_text("".join(x if x.endswith("\n") else x + "\n" for x in lines if x), encoding="utf-8")return {"file": str(out), "run_dirs": dirs, "run_dir": dirs[-1] if dirs else None, "exit_code": code, "timed_out": timed_out,"mode": plan["mode"]}def finish_attempt(state, svc, plan: dict, res: dict | None) -> dict:"""Merge attempts (Playwright-shaped; failed-then-passed = flaky), ingest evidence, compute failures. Scenarios thecanary blocked (run_canaries) join attempt 0's report as failed with the reason, and are never retried."""run_id, attempt, out_file = plan["run_id"], plan["attempt"], Path(plan["out_file"])liveview.cleanup(plan.get("live_dir")) # the latest frame lives only while the attempt runsrun_dirs = list(plan["run_dirs"])if not plan["ids"]:out_file.write_text(json.dumps({"config": {"projects": []}, "suites": [], "errors": [], "stats": {},"_note": "no cases in scope"}), encoding="utf-8")can = plan.get("canary") or (state.get("run_results") or {}).get("canary") or {}blocked = can.get("blocked") or {}if blocked and attempt == 0:titles = {c["id"]: c.get("title") or "" for c in state.get("test_cases") or []}extra = canary.blocked_report(blocked, titles, out_file.with_name(f"{out_file.stem}.blocked.json"))pw.merge_chunk_reports([f for f in (out_file, extra) if f.exists()], out_file)new_dirs = list((res or {}).get("run_dirs") or ([res["run_dir"]] if res and res.get("run_dir") else []))run_dirs += new_dirsif new_dirs: # every Playwright run dir of this attempt (one per chunk under Temporal), each with its own attachmentsamap = pw.attachments_by_case(out_file)for rd in new_dirs:root = Path(rd).resolve()sub = {p_: c for p_, c in amap.items() if Path(p_).resolve().is_relative_to(root)}try:svc.evidence.ingest_dir(run_id, attempt, Path(rd), sub)except Exception as e: # noqa: BLE001svc.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 resultpw.adopt_no_result(files)merged = merge_attempts(files, Path(plan["run_dir"]) / "merged-results.json")outs, counts = outcomes(str(merged))fails = [f for f in failing_ids(str(out_file)) if f not in blocked] if plan["ids"] else []return {"attempt_files": files, "failures": fails, "retry_count": attempt,"run_results": {"merged_path": str(merged), "attempt_files": files, "counts": counts, "outcomes": outs,"run_dirs": run_dirs, "mode": plan["mode"], **({"canary": can} if can else {})}}def executor(state, config, svc) -> dict:plan = plan_attempt(state, svc)preflight_or_stop(state, svc, plan)plan["canary"] = run_canaries(state, svc, plan)for tries in (1, 2): # a browser-level failure (nothing ran) is tried once more, then fails the run clearlytry:res = run_planned(plan, svc) if plan["ids"] else Noneexcept BaseException:liveview.cleanup(plan.get("live_dir")) # a crashed or cancelled attempt leaves no frame behindraisepid = svc.fusion_pod_id(plan["run_id"]) if plan["ids"] and plan["mode"] == "live" else Noneif pid is not None: # the pod values Fusion accepted in this attempt are tried first next timefrom ...platform.pods import PodRegistryPodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).learn_test_data(pid, pw.testdata_used_file(Path(plan["out_file"])))why = browser_failure(plan["out_file"], res) if plan["ids"] else Noneif why is None:breaksvc.db.add_event(plan["run_id"], "executor", "execution_error", {"error": why, "attempt": plan["attempt"], "try": tries,"retrying": tries == 1})svc.audit.append("run.execution_error", actor="system", run_id=plan["run_id"], node="executor", summary=why[:300],payload={"attempt": plan["attempt"], "try": tries, "exit_code": (res or {}).get("exit_code")})if tries == 2:liveview.cleanup(plan.get("live_dir"))from ...platform.failures import ExecutionErrorraise 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 anythingreturn finish_attempt(state, svc, plan, res)def run_canaries(state, svc, plan: dict) -> dict:"""Attempt 0 of a live run on a Fusion pod: the canary of each of the run's areas (platform/canary.py) runs first, asits own pass, and a "canary" event records how each business action did. The scenarios that use an action thecanary found broken are taken out of the attempt (finish_attempt reports them as blocked by the canary: a script/UIchange to maintain, not a product defect); the others run as usual. {} when no canary runs: fusion_canary is off,another attempt or mode, or none of the run's areas has a canary file. A resumed attempt 0 keeps the canary'searlier answer (canary.json in the run folder) instead of running it again."""if (plan["attempt"] != 0 or plan["mode"] != "live" or plan.get("config") != FUSION_CONFIG or not plan["ids"]or not svc.cfg.fusion_canary):return {}saved = Path(plan["run_dir"]) / "canary.json"try:info = json.loads(saved.read_text(encoding="utf-8"))except (OSError, ValueError):info = Noneif not isinstance(info, dict):info = canary_passes(state, svc, plan)if not info:return {}info["learned"] = learn_from_canary(svc, plan)saved.write_text(json.dumps(info, indent=1), encoding="utf-8")svc.db.add_event(plan["run_id"], "executor", "canary", {**info, "message": canary_words(info)})blocked = info.get("blocked") or {}if blocked:plan["ids"] = [i for i in plan["ids"] if i not in blocked]if plan.get("groups"):groups = [{**g, "ids": [i for i in g["ids"] if i not in blocked]} for g in plan["groups"]]plan["groups"] = [g for g in groups if g["ids"]] or Nonereturn infodef canary_passes(state, svc, plan: dict) -> dict:"""Run the canaries of the attempt's areas (one pass per test user when the areas sign in as different users) andread each business action's result from their reports. A canary that cannot run blocks nothing (error says why)."""module_of = {c["id"]: c["module"] for c in state.get("test_cases") or []}areas = list(dict.fromkeys((module_of.get(i) or i.split("-", 1)[0]).upper() for i in plan["ids"]))ids = [canary.canary_id(a) for a in areas if canary.canary_file(a)]if not ids:return {}passes = [([canary.canary_id(a) for a in g["areas"] if canary.canary_id(a) in ids], g["cred_env"]) for g in plan.get("groups") or []]files, error = [], Nonefor k, (cids, env) in enumerate(x for x in (passes or [(ids, plan["cred_env"])]) if x[0]):out = Path(plan["run_dir"]) / f"canary-{k}.json"sub = {**plan, "ids": cids, "cred_env": env, "groups": None, "out_file": str(out), "tag": "-canary" if k == 0 else f"-canary{k}","timeout_s": attempt_timeout_s(svc.cfg, len(cids), (env or {}).get("FPT_FUSION_WORKERS"))}try:run_pass(sub, svc)except (RunCancelled, KillSwitchEngaged):raiseexcept Exception as e: # noqa: BLE001 (the run goes on as it would without a canary)error = f"{type(e).__name__}: {e}"[:300]if out.exists():files.append(out)results = canary.action_results(files, ids)failed = canary.failed_actions(results)from ...platform import step_writerdirs = [canary.CASES_DIR, ai_scenarios.library_root(svc) / "tests" / "cases", step_writer.staging_dir(svc)]return {"canaries": ids, "actions": results, "failed_actions": failed,"blocked": canary.blocked_scenarios(plan["ids"], failed, dirs), "error": error}def learn_from_canary(svc, plan: dict) -> int:"""The pod values the canary found working (its create_invoice tries the pod's data sets in turn and records the setthat saves and validates, FPT_TESTDATA_USED) are learned for the pod at once: the next run tries them first, and sodo this run's scenarios (their test data is refreshed). Returns how many values were learned."""pid = svc.fusion_pod_id(plan["run_id"])if pid is None:return 0from ...platform.pods import PodRegistryreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)n = reg.learn_test_data(pid, pw.testdata_used_file(Path(plan["out_file"])))if n:env = reg.executor_env(pid, plan["run_id"]) or {}fresh = {k: env[k] for k in ("FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES") if k in env}plan["cred_env"].update(fresh)for g in plan.get("groups") or []:g["cred_env"].update(fresh)return ndef canary_words(info: dict) -> str:"""The canary event in one sentence for the run's timeline."""ok = sorted({a for r in (info.get("actions") or {}).values() if r for a, s in r.items() if s == "passed"})silent = [c for c, r in (info.get("actions") or {}).items() if r is None]parts = [f"{len(ok)} business action(s) work on the pod"]if info.get("failed_actions"):parts.append(f"broken: {', '.join(info['failed_actions'])}; {len(info.get('blocked') or {})} scenario(s) that use them ""are blocked (a script/UI change to maintain, not a product defect)")if silent:parts.append(f"no result from {', '.join(silent)}" + (f" ({info['error']})" if info.get("error") else ""))if info.get("learned"):parts.append(f"{info['learned']} pod test data value(s) that work were learned and are tried first")return "Canary: " + "; ".join(parts) + "."def preflight_or_stop(state, svc, plan: dict) -> None:"""The first attempt of a browser run on a Fusion pod checks its runner, sign-in and test data before any browserstarts (platform/preflight.py): a run that cannot work stops in seconds with the reason."""pid = svc.fusion_pod_id(plan["run_id"]) if plan["ids"] and plan["mode"] == "live" and plan["attempt"] == 0 else Noneif pid is None:returnfrom ...platform import preflightids = set(plan["ids"]) # the areas this attempt runs, not every area the run designed forareas = 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})if bad:from ...platform.failures import ExecutionErrorraise ExecutionError("Pre-flight check failed, no browser was started: " + " ".join(bad))# ====================================================================== self_healdef parse_locator(message: str) -> tuple[str, str] | None:for m in LOCATOR_RE.finditer(message or ""):kind, a, b = m.groups()if kind == "Role" and b:return a, bif kind == "Label":return "label", areturn Nonedef snapshot_candidates(snapshot: str, role: str) -> list[str]:names = [n for r, n in ARIA_RE.findall(snapshot or "") if role == "label" or r == role]return list(dict.fromkeys(names))def stub_self_heal(payload: dict) -> HealProposal:old, role = payload["old_name"], payload["role"]cands = [c for c in payload.get("candidates", []) if c != old]best, ratio = None, 0.0for c in cands:r = difflib.SequenceMatcher(None, old.lower(), c.lower()).ratio()if old.lower() in c.lower() or c.lower() in old.lower():r = max(r, 0.75)if r > ratio:best, ratio = c, rif best is None or ratio < 0.6:return HealProposal(role=role, old_name=old, new_name=old, confidence=0.0, reason="no candidate with similarity >= 0.6")return HealProposal(role=role, old_name=old, new_name=best, confidence=round(ratio, 3), reason=f"difflib ratio {ratio:.2f} (stub)")STACK_RE = re.compile(r"([A-Za-z]:[\\/][^\s():]+?\.ts|/[^\s():]+?\.ts):(\d+)")def find_literal(old: str, case_id: str, stack: str = "") -> tuple[str | None, int | None, str | None]:"""Source literal for the permanent fix: (1) the failing frames in the error stack (automation/ only), then(2) the case spec, then automation/src/** skipping other modules' packs."""pat = re.compile(r"(['\"`])" + re.escape(old) + r"\1")auto = (ROOT / "automation").resolve()for m in STACK_RE.finditer(stack or ""):f, ln = Path(m.group(1)), int(m.group(2))try:f = f.resolve()if not f.is_relative_to(auto) or "node_modules" in f.parts or not f.exists():continuelines = f.read_text(encoding="utf-8").splitlines()except (OSError, ValueError):continueif 1 <= ln <= len(lines) and pat.search(lines[ln - 1]):return f.relative_to(ROOT.resolve()).as_posix(), ln, lines[ln - 1].strip()spec = next((p for p in (ROOT / "automation" / "tests").rglob(f"{case_id}.spec.ts")), None)mod = case_id.split("-", 1)[0].lower()src = [p for p in sorted((ROOT / "automation" / "src").rglob("*.ts"))if "modules" not in p.relative_to(ROOT / "automation" / "src").parts or f"modules/{mod}/" in p.as_posix()]for f in ([spec] if spec else []) + src:for i, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):if pat.search(line):return f.relative_to(ROOT).as_posix(), i, line.strip()return None, None, Nonedef self_heal(state, config, svc) -> dict:run_id = state["run_id"]a0 = Path(state["attempt_files"][0])errs = pw.errors_by_case(a0)ctxs = pw.error_contexts(a0)stacks = pw.stacks_by_case(a0)overrides, refs, calls = {}, [], []for cid in state.get("failures") or []:msg = errs.get(cid, "")if not LOCATOR_FAIL_RE.search(msg):continueloc = parse_locator(msg)if not loc:continuerole, old = locsnap = ctxs.get(cid)file, line, src = find_literal(old, cid, stacks.get(cid, ""))if not snap:pid = svc.db.insert_once("heal_proposals", {"run_id": run_id, "case_id": cid, "role": role, "old_name": old, "new_name": None,"confidence": 0.0, "reason": "no error-context ARIA snapshot attached: plain retry","file": file, "line": line, "status": "no_snapshot", "created_at": now_iso()}, ('run_id', 'case_id', 'role', 'old_name'))refs.append({"proposal_id": pid, "case_id": cid, "role": role, "old_name": old, "new_name": "", "confidence": 0.0,"file": file, "line": line, "applied_in_retry": False})continuecands = snapshot_candidates(snap, role)payload = {"case_id": cid, "role": role, "old_name": old, "error": msg[:1500], "candidates": cands}req = LLMRequest("self_heal", Sensitivity.CLIENT, payload, HealProposal, "self_heal", run_id, stub_self_heal(payload))resp = svc.router.call(req)calls.append(resp.record)hp = resp.outputusable = hp.new_name != old and hp.new_name in cands and hp.confidence >= 0.6 # type: ignore[attr-defined]diff = Noneif usable and file:diff = f"--- a/{file}\n+++ b/{file}\n@@ line {line} @@\n-{src}\n+{src.replace(old, hp.new_name)}" # type: ignore[union-attr,attr-defined]pid = svc.db.insert_once("heal_proposals", {"run_id": run_id, "case_id": cid, "role": role, "old_name": old,"new_name": hp.new_name if usable else None, "confidence": hp.confidence, # type: ignore[attr-defined]"reason": hp.reason, "file": file, "line": line, "diff": diff, # type: ignore[attr-defined]"status": "pending" if usable else "no_candidate", "created_at": now_iso()}, ('run_id', 'case_id', 'role', 'old_name'))if usable:overrides[f"{role}|{old}"] = hp.new_name # type: ignore[attr-defined]refs.append({"proposal_id": pid, "case_id": cid, "role": role, "old_name": old, "new_name": hp.new_name if usable else "", # type: ignore[attr-defined]"confidence": hp.confidence, "file": file, "line": line, "applied_in_retry": usable}) # type: ignore[attr-defined]run_dir = svc.run_dir(run_id)(run_dir / "heal-overrides.json").write_text(json.dumps(overrides), encoding="utf-8")return {"heal_proposals": refs, "llm_calls": calls}STUB_TASKS = {"self_heal": stub_self_heal}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674"""Execute phase: executor (Playwright attempt, --retries=0) and self_heal (locator rename proposal from the failure'sARIA snapshot; applied only as a retry override; the permanent fix needs human approval)."""from __future__ import annotationsimport difflibimport jsonimport refrom pathlib import Pathfrom ...adapters import playwright as pwfrom ...adapters.legacy import classifier, merge_attemptsfrom ...config import ROOTfrom ...llm.base import LLMRequest, Sensitivityfrom ...llm.schemas import HealProposalfrom . import ai_scenariosfrom ...platform import assisted_signin, canary, healing, liveviewfrom ...platform.killswitch import KillSwitchEngagedfrom ...platform.rundb import now_isoLOCATOR_RE = re.compile(r"getBy(Role|Label)\(\s*'([^']+)'(?:\s*,\s*\{\s*name:\s*'([^']+)')?")LOCATOR_FAIL_RE = re.compile(r"strict mode violation|waiting for getBy(Role|Label)|not found|element\(s\) not found|Timeout \d+ms exceeded", re.I)ARIA_RE = re.compile(r"^\s*-\s+([a-z]+)\s+\"([^\"]+)\"", re.M)def smoke_ids(modules: list[str]) -> list[str]:"""Tag ids of automation/tests/smoke/*.spec.ts for these modules (scripts with no YAML case, e.g. P2P-SMOKE-001)."""out = []for p in sorted((ROOT / "automation" / "tests" / "smoke").glob("*.spec.ts")):for tag in re.findall(r"['\"`]@([A-Z][A-Z0-9]{1,5}-[A-Z0-9-]+)['\"`]", p.read_text(encoding="utf-8")):if tag.split("-", 1)[0] in modules and tag not in out:out.append(tag)return outdef failing_ids(report_file: str) -> list[str]:clf = classifier()recs = clf.parse_report(clf.load_report(report_file))return [r.case_id or r.title for r in recs if r.outcome == "failed"]def outcomes(merged: str) -> tuple[dict, dict]:clf = classifier()recs = clf.parse_report(clf.load_report(merged))out = {}for r in recs:cid = r.case_id or r.titleout[cid] = r.outcomecounts = {"total": len(recs), **{k: sum(1 for r in recs if r.outcome == k) for k in ("passed", "failed", "flaky", "skipped")}}return out, countsdef browser_failure(out_file: str | Path, res: dict | None) -> str | None:"""A failure of the browser run as a whole: Playwright reported top-level errors (it could not start, a browser orworker crashed, the config failed) or exited non-zero, AND no scenario result was recorded. Then the attempt saysnothing about the scenarios and must not be read as 'all passed'. Returns the reason in words, or None."""f = Path(out_file)try:rep = json.loads(f.read_text(encoding="utf-8"))except (OSError, ValueError):return "Playwright's report could not be read, so no scenario result was recorded."_, counts = outcomes(str(f))errs = [str((e or {}).get("message") or "").strip().splitlines()[0][:200] for e in rep.get("errors") or [] if isinstance(e, dict)]code = (res or {}).get("exit_code") or 0if counts["total"] or not (errs or code):return Nonewhy = f"Playwright stopped before any scenario ran (exit {code})" if code else "Playwright stopped before any scenario ran"return why + (f": {errs[0]}" if errs and errs[0] else "") + "."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_modeif 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()scripts = state.get("scripts") or {}ids = [c["id"] for c in state.get("test_cases") or []if c["origin"] == "library" or (scripts.get(c["id"], {}).get("dry_run_ok"))]if not state.get("case_filter") and mode == "live": # full-module live runs also execute the module's smoke specs (QA C1 counts them)ids += smoke_ids(sorted({c["module"] for c in state.get("test_cases") or []}))else:ids = list(state.get("failures") or [])mods = sorted({c["module"] for c in state.get("test_cases") or []})cred_env: dict = {}for m in mods:cred_env.update(svc.vault.executor_env(m))live_on, _why = liveview.availability(svc.cfg, mode=mode, wanted=bool(state.get("live_view")), modules=mods)fusion_pod = svc.fusion_pod_id(run_id)config, groups = None, Noneif fusion_pod is not None and mode == "live": # a real Fusion pod: its own test set, its test user from the vaultfrom ...platform.pods import PodRegistryreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)cred_env.update(reg.executor_env(fusion_pod, run_id) or {})config = "playwright.fusion.config.ts"groups = user_groups(reg, fusion_pod, run_id, ids, {c["id"]: c["module"] for c in state.get("test_cases") or []}, cred_env)# assisted sign-in: the tests start from the session a person signed in at the sign_in gate (run_pass hands it over)assisted = config == FUSION_CONFIG and assisted_signin.assisted_pod(svc, run_id)return {"run_id": run_id, "attempt": attempt, "ids": ids, "mode": mode, "files": files, "run_dir": str(run_dir), "config": config,"assisted": assisted,"live_dir": str(liveview.live_dir(svc.cfg, run_id)) if live_on and ids else None,"out_file": str(run_dir / f"attempt-{attempt}.json"), "stub_knobs": state.get("stub_knobs"),"drafts_dir": str(svc.cfg.path("staging", "specs", run_id)),"library_dir": str(ai_scenarios.library_root(svc) / "automation" / "tests" / "fusion" / "steps"),"overrides": str(run_dir / "heal-overrides.json") if attempt == 1 else None, "cred_env": cred_env, "groups": groups,"run_dirs": list((state.get("run_results") or {}).get("run_dirs") or [])}def user_groups(reg, pod_id: int, run_id: str, ids: list[str], module_of: dict[str, str], base_env: dict) -> list[dict] | None:"""Each area's scenarios signed in as that area's test user (FPT_FUSION_AREA_USERS): one Playwright pass per user,in the order the areas come. None when every scenario uses the same user (one pass, as before)."""envs: dict[str, dict] = {}groups: dict[str, dict] = {}for cid in ids:area = (module_of.get(cid) or cid.split("-", 1)[0]).upper()if area not in envs:envs[area] = reg.executor_env(pod_id, run_id, area=area) or {}user = envs[area].get("FUSION_USERNAME") or ""g = groups.setdefault(user, {"user": user, "areas": [], "ids": [], "cred_env": {**base_env, **envs[area]}})if area not in g["areas"]:g["areas"].append(area)g["ids"].append(cid)return list(groups.values()) if len(groups) > 1 else NoneFUSION_CONFIG = "playwright.fusion.config.ts"STARTUP_MINUTES = 10 # a pass's own start-up: Playwright, the browser and the test user's one sign-indef 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 thatrun 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):passdef _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 thesame 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 ofthem, or the runner job it was following, is still in the run folder. A first entry finds neither."""from ...adapters.remote_runner import saved_jobjob = 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 (LangGraph path): one Playwright invocation for the attempt; one per test user when the areas signin as different users (plan["groups"]), merged into the attempt's one report. On a Fusion pod an attempt runs inpasses 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, asunder Temporal), each with its own time budget and report, merged into the attempt's one report. A pass that runsout of time loses only its own scenarios (recorded as timed out, so the retry runs them), and the finished passes arelisted 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] = fif run_dir:dirs[k] = run_dirtmp = 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()session = assisted_signin.SessionStore(svc).load(plan["run_id"]) if plan.get("assisted") else Noneif 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 theretoken = svc.vault.get("remote_runner.token") or ""if token:svc.redactor.add_secrets([token])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: _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 "",storage_state=session)if plan["mode"] == "live" and not plan.get("config"):pw.ensure_mock(svc.egress, svc.cfg.pod_base_url, svc.cfg.path("logs"))if plan.get("config"):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"])if session is not None:extra.setdefault("storage_state", session)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,overrides_file=Path(plan["overrides"]) if plan["overrides"] else None, cred_env=plan["cred_env"],backend=svc.cfg.executor_backend, log_dir=Path(plan["run_dir"]),live_dir=Path(plan["live_dir"]) if plan.get("live_dir") else None, **extra)def run_groups(plan: dict, svc, **extra) -> dict:out = Path(plan["out_file"])used = pw.testdata_used_file(out)files, dirs, lines, code, timed_out = [], [], [], 0, Falsefor k, g in enumerate(plan["groups"]):svc.db.add_event(plan["run_id"], "executor", "progress", {"attempt": plan["attempt"], "user": g["user"], "areas": g["areas"],"scenarios": len(g["ids"]), "pass": k + 1, "of": len(plan["groups"])})sub = {**plan, "ids": g["ids"], "cred_env": g["cred_env"], "groups": None, "tag": f"{plan.get('tag') or ''}-u{k}","out_file": str(out.with_name(f"{out.stem}.u{k}.json"))}res = run_planned(sub, svc, **extra) or {}f = Path(sub["out_file"])if f.exists():files.append(f)dirs += res.get("run_dirs") or ([res["run_dir"]] if res.get("run_dir") else [])code, timed_out = code or res.get("exit_code") or 0, timed_out or bool(res.get("timed_out"))if used.exists(): # each pass writes the values it tried to the same file: keep them all for learn_test_datalines.append(used.read_text(encoding="utf-8"))used.unlink()pw.merge_chunk_reports(files, out)if lines:used.write_text("".join(x if x.endswith("\n") else x + "\n" for x in lines if x), encoding="utf-8")return {"file": str(out), "run_dirs": dirs, "run_dir": dirs[-1] if dirs else None, "exit_code": code, "timed_out": timed_out,"mode": plan["mode"]}def finish_attempt(state, svc, plan: dict, res: dict | None) -> dict:"""Merge attempts (Playwright-shaped; failed-then-passed = flaky), ingest evidence, compute failures. Scenarios thecanary blocked (run_canaries) join attempt 0's report as failed with the reason, and are never retried."""run_id, attempt, out_file = plan["run_id"], plan["attempt"], Path(plan["out_file"])liveview.cleanup(plan.get("live_dir")) # the latest frame lives only while the attempt runsrun_dirs = list(plan["run_dirs"])if not plan["ids"]:out_file.write_text(json.dumps({"config": {"projects": []}, "suites": [], "errors": [], "stats": {},"_note": "no cases in scope"}), encoding="utf-8")can = plan.get("canary") or (state.get("run_results") or {}).get("canary") or {}blocked = can.get("blocked") or {}if blocked and attempt == 0:titles = {c["id"]: c.get("title") or "" for c in state.get("test_cases") or []}extra = canary.blocked_report(blocked, titles, out_file.with_name(f"{out_file.stem}.blocked.json"))pw.merge_chunk_reports([f for f in (out_file, extra) if f.exists()], out_file)new_dirs = list((res or {}).get("run_dirs") or ([res["run_dir"]] if res and res.get("run_dir") else []))run_dirs += new_dirsif new_dirs: # every Playwright run dir of this attempt (one per chunk under Temporal), each with its own attachmentsamap = pw.attachments_by_case(out_file)for rd in new_dirs:root = Path(rd).resolve()sub = {p_: c for p_, c in amap.items() if Path(p_).resolve().is_relative_to(root)}try:svc.evidence.ingest_dir(run_id, attempt, Path(rd), sub)except Exception as e: # noqa: BLE001svc.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 resultpw.adopt_no_result(files)merged = merge_attempts(files, Path(plan["run_dir"]) / "merged-results.json")outs, counts = outcomes(str(merged))fails = [f for f in failing_ids(str(out_file)) if f not in blocked] if plan["ids"] else []if plan["ids"] and plan["mode"] == "live": # healed steps and controls not found (platform/healing.py); never fails the runhealing.after_attempt(svc, run_id, out_file)return {"attempt_files": files, "failures": fails, "retry_count": attempt,"run_results": {"merged_path": str(merged), "attempt_files": files, "counts": counts, "outcomes": outs,"run_dirs": run_dirs, "mode": plan["mode"], **({"canary": can} if can else {})}}def executor(state, config, svc) -> dict:plan = plan_attempt(state, svc)pending = sign_in_resume(state, plan)if pending: # after a new sign-in: the scenarios the expired session left, in a pass of their ownplan["ids"] = list(pending["ids"])plan["tag"] = f"-s{int(pending.get('round') or 1)}"plan["canary"] = saved_canary(plan)if plan.get("assisted") and plan["ids"] and not assisted_signin.SessionStore(svc).has(plan["run_id"]):return park_for_sign_in(svc, plan, None, list(plan["ids"]), pending, "no signed-in session is kept for this run")if not pending:preflight_or_stop(state, svc, plan)plan["canary"] = run_canaries(state, svc, plan)for tries in (1, 2): # a browser-level failure (nothing ran) is tried once more, then fails the run clearlytry:res = run_planned(plan, svc) if plan["ids"] else Noneexcept BaseException:liveview.cleanup(plan.get("live_dir")) # a crashed or cancelled attempt leaves no frame behindraisepid = svc.fusion_pod_id(plan["run_id"]) if plan["ids"] and plan["mode"] == "live" else Noneif pid is not None: # the pod values Fusion accepted in this attempt are tried first next timefrom ...platform.pods import PodRegistryPodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit).learn_test_data(pid, pw.testdata_used_file(Path(plan["out_file"])))why = browser_failure(plan["out_file"], res) if plan["ids"] else Noneif why is None:breaksvc.db.add_event(plan["run_id"], "executor", "execution_error", {"error": why, "attempt": plan["attempt"], "try": tries,"retrying": tries == 1})svc.audit.append("run.execution_error", actor="system", run_id=plan["run_id"], node="executor", summary=why[:300],payload={"attempt": plan["attempt"], "try": tries, "exit_code": (res or {}).get("exit_code")})if tries == 2:liveview.cleanup(plan.get("live_dir"))from ...platform.failures import ExecutionErrorraise 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 anythingif plan.get("assisted") and plan["ids"]:expired = pw.sign_in_expired_ids(Path(plan["out_file"]))if expired:return park_for_sign_in(svc, plan, res, expired, pending, "the pod no longer accepted the signed-in session")rest_note(svc, plan)if pending: # what ran before the session expired joins this pass's results: one report for the attemptout = Path(plan["out_file"])pw.merge_chunk_reports([Path(p) for p in pending.get("parts") or [] if Path(p).exists()] + [out], out)new = list((res or {}).get("run_dirs") or ([res["run_dir"]] if res and res.get("run_dir") else []))res = {**(res or {}), "run_dirs": list(pending.get("run_dirs") or []) + new, "run_dir": None}return {**finish_attempt(state, svc, plan, res), **({"sign_in_pending": None} if pending else {})}# ====================================================================== assisted sign-in (platform/assisted_signin.py)def sign_in_resume(state, plan: dict) -> dict | None:"""The scenarios an expired session left for after a new sign-in, when this is the attempt they belong to."""p = state.get("sign_in_pending")return p if isinstance(p, dict) and p.get("attempt") == plan["attempt"] and p.get("ids") else Nonedef saved_canary(plan: dict) -> dict:"""The canary's answer from earlier in this attempt (it is not run again after a new sign-in)."""try:info = json.loads((Path(plan["run_dir"]) / "canary.json").read_text(encoding="utf-8"))except (OSError, ValueError):return {}return info if isinstance(info, dict) else {}def park_for_sign_in(svc, plan: dict, res: dict | None, expired: list[str], pending: dict | None, why: str) -> dict:"""The run cannot go on with its session (it expired mid-attempt, or there is none): what ran is kept (its reportwithout the scenarios that met the sign-in page, and its evidence folders), the session is deleted, and the run goesback to the sign_in gate. After a new sign-in the executor runs only the scenarios listed here."""run_id, out = plan["run_id"], Path(plan["out_file"])n = int((pending or {}).get("round") or 0) + 1parts = [p for p in (pending or {}).get("parts") or [] if Path(p).exists()]if out.exists():part = Path(plan["run_dir"]) / f"sign-in-a{plan['attempt']}-p{n}.json" # not attempt-*: a fresh attempt 0 keeps itpw.drop_cases(out, expired, part)parts.append(str(part))out.unlink(missing_ok=True)forget_passes(out)new = list((res or {}).get("run_dirs") or ([res["run_dir"]] if res and res.get("run_dir") else []))dirs = list((pending or {}).get("run_dirs") or []) + newliveview.cleanup(plan.get("live_dir"))assisted_signin.SessionStore(svc).delete(run_id)left = sorted(set(expired))words = (f"Sign-in expired: {why}. {len(left)} scenario(s) did not run "f"({', '.join(left[:10])}{', ...' if len(left) > 10 else ''}); the run waits for a person to sign in again, then runs them.")svc.db.add_event(run_id, "executor", "sign_in_expired", {"message": words, "remaining": len(left), "attempt": plan["attempt"]})svc.audit.append("sign_in.expired", actor="system", run_id=run_id, node="executor", summary=words[:300],payload={"attempt": plan["attempt"], "remaining": left, "round": n})return {"sign_in_pending": {"attempt": plan["attempt"], "ids": left, "parts": parts, "run_dirs": dirs, "round": n}}def rest_note(svc, plan: dict) -> None:"""Scenarios whose Fusion REST checks were skipped (an assisted sign-in pod has no password for REST): one line in therun's timeline. Their screen results stand."""skipped = pw.annotated(Path(plan["out_file"]), "rest-skipped")if skipped:svc.db.add_event(plan["run_id"], "executor", "message", {"message": (f"Fusion REST checks were skipped in {len(skipped)} scenario(s) ({', '.join(sorted(skipped)[:10])}): this pod uses ""assisted sign-in, so there is no password for REST. Their screen results stand; test records they created are ""not cancelled automatically."), "rest_skipped": sorted(skipped)})def run_canaries(state, svc, plan: dict) -> dict:"""Attempt 0 of a live run on a Fusion pod: the canary of each of the run's areas (platform/canary.py) runs first, asits own pass, and a "canary" event records how each business action did. The scenarios that use an action thecanary found broken are taken out of the attempt (finish_attempt reports them as blocked by the canary: a script/UIchange to maintain, not a product defect); the others run as usual. {} when no canary runs: fusion_canary is off,another attempt or mode, or none of the run's areas has a canary file. A resumed attempt 0 keeps the canary'searlier answer (canary.json in the run folder) instead of running it again."""if (plan["attempt"] != 0 or plan["mode"] != "live" or plan.get("config") != FUSION_CONFIG or not plan["ids"]or not svc.cfg.fusion_canary):return {}saved = Path(plan["run_dir"]) / "canary.json"try:info = json.loads(saved.read_text(encoding="utf-8"))except (OSError, ValueError):info = Noneif not isinstance(info, dict):info = canary_passes(state, svc, plan)if not info:return {}info["learned"] = learn_from_canary(svc, plan)saved.write_text(json.dumps(info, indent=1), encoding="utf-8")svc.db.add_event(plan["run_id"], "executor", "canary", {**info, "message": canary_words(info)})blocked = info.get("blocked") or {}if blocked:plan["ids"] = [i for i in plan["ids"] if i not in blocked]if plan.get("groups"):groups = [{**g, "ids": [i for i in g["ids"] if i not in blocked]} for g in plan["groups"]]plan["groups"] = [g for g in groups if g["ids"]] or Nonereturn infodef canary_passes(state, svc, plan: dict) -> dict:"""Run the canaries of the attempt's areas (one pass per test user when the areas sign in as different users) andread each business action's result from their reports. A canary that cannot run blocks nothing (error says why)."""module_of = {c["id"]: c["module"] for c in state.get("test_cases") or []}areas = list(dict.fromkeys((module_of.get(i) or i.split("-", 1)[0]).upper() for i in plan["ids"]))ids = [canary.canary_id(a) for a in areas if canary.canary_file(a)]if not ids:return {}passes = [([canary.canary_id(a) for a in g["areas"] if canary.canary_id(a) in ids], g["cred_env"]) for g in plan.get("groups") or []]files, error = [], Nonefor k, (cids, env) in enumerate(x for x in (passes or [(ids, plan["cred_env"])]) if x[0]):out = Path(plan["run_dir"]) / f"canary-{k}.json"sub = {**plan, "ids": cids, "cred_env": env, "groups": None, "out_file": str(out), "tag": "-canary" if k == 0 else f"-canary{k}","timeout_s": attempt_timeout_s(svc.cfg, len(cids), (env or {}).get("FPT_FUSION_WORKERS"))}try:run_pass(sub, svc)except (RunCancelled, KillSwitchEngaged):raiseexcept Exception as e: # noqa: BLE001 (the run goes on as it would without a canary)error = f"{type(e).__name__}: {e}"[:300]if out.exists():files.append(out)results = canary.action_results(files, ids)failed = canary.failed_actions(results)from ...platform import step_writerdirs = [canary.CASES_DIR, ai_scenarios.library_root(svc) / "tests" / "cases", step_writer.staging_dir(svc)]return {"canaries": ids, "actions": results, "failed_actions": failed,"blocked": canary.blocked_scenarios(plan["ids"], failed, dirs), "error": error}def learn_from_canary(svc, plan: dict) -> int:"""The pod values the canary found working (its create_invoice tries the pod's data sets in turn and records the setthat saves and validates, FPT_TESTDATA_USED) are learned for the pod at once: the next run tries them first, and sodo this run's scenarios (their test data is refreshed). Returns how many values were learned."""pid = svc.fusion_pod_id(plan["run_id"])if pid is None:return 0from ...platform.pods import PodRegistryreg = PodRegistry(svc.db, svc.vault, svc.cfg, svc.egress, svc.audit)n = reg.learn_test_data(pid, pw.testdata_used_file(Path(plan["out_file"])))if n:env = reg.executor_env(pid, plan["run_id"]) or {}fresh = {k: env[k] for k in ("FUSION_TESTDATA", "FUSION_TESTDATA_CANDIDATES") if k in env}plan["cred_env"].update(fresh)for g in plan.get("groups") or []:g["cred_env"].update(fresh)return ndef canary_words(info: dict) -> str:"""The canary event in one sentence for the run's timeline."""ok = sorted({a for r in (info.get("actions") or {}).values() if r for a, s in r.items() if s == "passed"})silent = [c for c, r in (info.get("actions") or {}).items() if r is None]parts = [f"{len(ok)} business action(s) work on the pod"]if info.get("failed_actions"):parts.append(f"broken: {', '.join(info['failed_actions'])}; {len(info.get('blocked') or {})} scenario(s) that use them ""are blocked (a script/UI change to maintain, not a product defect)")if silent:parts.append(f"no result from {', '.join(silent)}" + (f" ({info['error']})" if info.get("error") else ""))if info.get("learned"):parts.append(f"{info['learned']} pod test data value(s) that work were learned and are tried first")return "Canary: " + "; ".join(parts) + "."def preflight_or_stop(state, svc, plan: dict) -> None:"""The first attempt of a browser run on a Fusion pod checks its runner, sign-in and test data before any browserstarts (platform/preflight.py): a run that cannot work stops in seconds with the reason."""pid = svc.fusion_pod_id(plan["run_id"]) if plan["ids"] and plan["mode"] == "live" and plan["attempt"] == 0 else Noneif pid is None:returnfrom ...platform import preflightids = set(plan["ids"]) # the areas this attempt runs, not every area the run designed forareas = 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})if bad:from ...platform.failures import ExecutionErrorraise ExecutionError("Pre-flight check failed, no browser was started: " + " ".join(bad))# ====================================================================== self_healdef parse_locator(message: str) -> tuple[str, str] | None:for m in LOCATOR_RE.finditer(message or ""):kind, a, b = m.groups()if kind == "Role" and b:return a, bif kind == "Label":return "label", areturn Nonedef snapshot_candidates(snapshot: str, role: str) -> list[str]:names = [n for r, n in ARIA_RE.findall(snapshot or "") if role == "label" or r == role]return list(dict.fromkeys(names))def stub_self_heal(payload: dict) -> HealProposal:old, role = payload["old_name"], payload["role"]cands = [c for c in payload.get("candidates", []) if c != old]best, ratio = None, 0.0for c in cands:r = difflib.SequenceMatcher(None, old.lower(), c.lower()).ratio()if old.lower() in c.lower() or c.lower() in old.lower():r = max(r, 0.75)if r > ratio:best, ratio = c, rif best is None or ratio < 0.6:return HealProposal(role=role, old_name=old, new_name=old, confidence=0.0, reason="no candidate with similarity >= 0.6")return HealProposal(role=role, old_name=old, new_name=best, confidence=round(ratio, 3), reason=f"difflib ratio {ratio:.2f} (stub)")STACK_RE = re.compile(r"([A-Za-z]:[\\/][^\s():]+?\.ts|/[^\s():]+?\.ts):(\d+)")def find_literal(old: str, case_id: str, stack: str = "") -> tuple[str | None, int | None, str | None]:"""Source literal for the permanent fix: (1) the failing frames in the error stack (automation/ only), then(2) the case spec, then automation/src/** skipping other modules' packs."""pat = re.compile(r"(['\"`])" + re.escape(old) + r"\1")auto = (ROOT / "automation").resolve()for m in STACK_RE.finditer(stack or ""):f, ln = Path(m.group(1)), int(m.group(2))try:f = f.resolve()if not f.is_relative_to(auto) or "node_modules" in f.parts or not f.exists():continuelines = f.read_text(encoding="utf-8").splitlines()except (OSError, ValueError):continueif 1 <= ln <= len(lines) and pat.search(lines[ln - 1]):return f.relative_to(ROOT.resolve()).as_posix(), ln, lines[ln - 1].strip()spec = next((p for p in (ROOT / "automation" / "tests").rglob(f"{case_id}.spec.ts")), None)mod = case_id.split("-", 1)[0].lower()src = [p for p in sorted((ROOT / "automation" / "src").rglob("*.ts"))if "modules" not in p.relative_to(ROOT / "automation" / "src").parts or f"modules/{mod}/" in p.as_posix()]for f in ([spec] if spec else []) + src:for i, line in enumerate(f.read_text(encoding="utf-8").splitlines(), 1):if pat.search(line):return f.relative_to(ROOT).as_posix(), i, line.strip()return None, None, Nonedef self_heal(state, config, svc) -> dict:run_id = state["run_id"]a0 = Path(state["attempt_files"][0])errs = pw.errors_by_case(a0)ctxs = pw.error_contexts(a0)stacks = pw.stacks_by_case(a0)overrides, refs, calls = {}, [], []for cid in state.get("failures") or []:msg = errs.get(cid, "")if not LOCATOR_FAIL_RE.search(msg):continueloc = parse_locator(msg)if not loc:continuerole, old = locsnap = ctxs.get(cid)file, line, src = find_literal(old, cid, stacks.get(cid, ""))if not snap:pid = svc.db.insert_once("heal_proposals", {"run_id": run_id, "case_id": cid, "role": role, "old_name": old, "new_name": None,"confidence": 0.0, "reason": "no error-context ARIA snapshot attached: plain retry","file": file, "line": line, "status": "no_snapshot", "created_at": now_iso()}, ('run_id', 'case_id', 'role', 'old_name'))refs.append({"proposal_id": pid, "case_id": cid, "role": role, "old_name": old, "new_name": "", "confidence": 0.0,"file": file, "line": line, "applied_in_retry": False})continuecands = snapshot_candidates(snap, role)payload = {"case_id": cid, "role": role, "old_name": old, "error": msg[:1500], "candidates": cands}req = LLMRequest("self_heal", Sensitivity.CLIENT, payload, HealProposal, "self_heal", run_id, stub_self_heal(payload))resp = svc.router.call(req)calls.append(resp.record)hp = resp.outputusable = hp.new_name != old and hp.new_name in cands and hp.confidence >= 0.6 # type: ignore[attr-defined]diff = Noneif usable and file:diff = f"--- a/{file}\n+++ b/{file}\n@@ line {line} @@\n-{src}\n+{src.replace(old, hp.new_name)}" # type: ignore[union-attr,attr-defined]pid = svc.db.insert_once("heal_proposals", {"run_id": run_id, "case_id": cid, "role": role, "old_name": old,"new_name": hp.new_name if usable else None, "confidence": hp.confidence, # type: ignore[attr-defined]"reason": hp.reason, "file": file, "line": line, "diff": diff, # type: ignore[attr-defined]"status": "pending" if usable else "no_candidate", "created_at": now_iso()}, ('run_id', 'case_id', 'role', 'old_name'))if usable:overrides[f"{role}|{old}"] = hp.new_name # type: ignore[attr-defined]refs.append({"proposal_id": pid, "case_id": cid, "role": role, "old_name": old, "new_name": hp.new_name if usable else "", # type: ignore[attr-defined]"confidence": hp.confidence, "file": file, "line": line, "applied_in_retry": usable}) # type: ignore[attr-defined]run_dir = svc.run_dir(run_id)(run_dir / "heal-overrides.json").write_text(json.dumps(overrides), encoding="utf-8")return {"heal_proposals": refs, "llm_calls": calls}STUB_TASKS = {"self_heal": stub_self_heal}
automation/playwright.fusion.config.ts+62-59
automation/remote_runner/server.py+710-457
automation/scripts/check-heal.tsAdded+33
automation/scripts/sign-in-session.tsAdded+127
automation/src/fusion/fixtures.ts+142-64
automation/src/fusion/heal.tsAdded+103
automation/src/fusion/rest.ts+329-113
automation/src/fusion/session.ts+73-42
automation/src/fusion/steps.ts+511-295
automation/src/fusion/ui.ts
automation/tests/fusion/AP-FUS-002.spec.ts+37-35
automation/tests/fusion/AP-FUS-003.spec.ts+36-36
automation/tests/fusion/AP-FUS-004.spec.ts+36-36
automation/tests/fusion/AP-FUS-005.spec.ts+35-35
automation/tests/fusion/steps/CANARY-GL.spec.tsAdded+4
automation/tests/fusion/steps/CANARY-PO.spec.tsAdded+4
coworker/adapters/playwright.py+466-372
coworker/adapters/remote_runner.py+488-484
coworker/adapters/screens.py+313-282
coworker/adapters/triage_rule.py+44-42
coworker/api/a2a.py+737-735
coworker/api/app.py+172-163
coworker/api/routes/consultant.py+295-287
coworker/api/routes/heals.pyAdded+52
coworker/api/routes/pods.py+135-106
coworker/api/routes/recordings.pyAdded+90
coworker/api/routes/runs.py+380-380
coworker/api/routes/signin.pyAdded+97
coworker/api/runner.py+433-420
coworker/api/schemas.py+470-395
coworker/channels/core.py+397-396
coworker/chat/tools.py+473-470
coworker/config.py+351-348
coworker/graph/build.py+81-77
coworker/graph/nodes/ai_scenarios.py+583-542
coworker/graph/nodes/design.py+450-442
coworker/graph/nodes/execute.py+674-594
coworker/graph/nodes/report.py
coworker/graph/nodes/research.py
coworker/graph/nodes/signin.pyAdded
coworker/graph/services.py
coworker/llm/prompts/design_scenarios.md
coworker/llm/prompts/tidy_recording.mdAdded
coworker/llm/prompts/triage.md
coworker/llm/prompts/write_steps.md
coworker/llm/schemas.py
coworker/platform/agent_studio.py
coworker/platform/assisted_signin.pyAdded
coworker/platform/canary.py
coworker/platform/cleanup.py