diff --git a/.gitleaksignore b/.gitleaksignore index 5d6bacc640..767366646f 100644 --- a/.gitleaksignore +++ b/.gitleaksignore @@ -228,3 +228,7 @@ cc5fba3e0b69646430c7e11ae0c181aaaad82d7f:packages/flow/tests/test_sanitized_arti 075417ff50b15d443f31be4fc591ec07be9ced49:packages/flow/benchmark/hooks_live/runs/hk-5e9e2f18db8db211/report.json:generic-api-key:14 075417ff50b15d443f31be4fc591ec07be9ced49:packages/flow/benchmark/hooks_live/runs/hk-93a7facdefde72e6/report.json:generic-api-key:8 075417ff50b15d443f31be4fc591ec07be9ced49:packages/flow/benchmark/hooks_live/runs/hk-bdb55e83345cda8b/report.json:generic-api-key:8 +# PR #2498: the RFC 6455 sample WebSocket nonce sent as Sec-WebSocket-Key by a +# relay test in one commit; not a credential. The test now draws a nonce from +# os.urandom at runtime. +e09ebaec9b380b8217471cccb4031511ac7c966e:packages/flow/tests/test_readiness_devtools_relay.py:generic-api-key:44 diff --git a/CAPABILITIES.md b/CAPABILITIES.md index b4f438e37c..03d4905a48 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -329,6 +329,7 @@ improvising or retrying when something is off. | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | | See what your own agent gets wrong, with no risk: `openadapt shadow` is a loopback pass-through proxy beside the agent. It checks each write against the system of record (FHIR through `ensure_record`; SQL through the verifier's whole-database frame), checks each `CONFIRMED` again later, and writes `report.html` and `report.json`. It never blocks, changes or resends a write; the only delay is the read before a write (at most `hold_ms`) | [#1678](https://github.com/OpenAdaptAI/OpenAdapt/pull/1678) | Real app (Medplum 5.2.8, 37 cases through a fault proxy: scripted agent 18 of 18 harms caught, 0 correct writes refuted; Claude Sonnet 5.5 9 of 9 caught, 4 correct but corrected writes refuted; 0 writes by the shadow; 15 to 25 ms median added per write; setup 76.5 s machine time, 3 decisions); real app, SQL mode (Dolibarr 21 on MariaDB 11.4, 13 cases: 8 of 8 harms caught, 5 of 5 correct writes confirmed, 292 ms median added); synthetic (SQLite) | `openadapt shadow`, [SHADOW_MODE.md](packages/flow/docs/SHADOW_MODE.md), [SHADOW_RESULTS.md](packages/flow/benchmark/fhir_medplum/public/SHADOW_RESULTS.md) | +| Score a candidate before it saves anything: `openadapt-flow readiness` imports 20 to 50 tasks a person did (the save from the browser recording's network capture, else a read-back through the verify config's reader, else refused), runs the candidate agent (`--agent-cmd`) or compiled program (`--program`) on each task in its own headless browser (DevTools on a pipe only, reached through a loopback relay that refuses any request without the run's random token; the page can reach only the app's origins) where the shadow hold refuses every non-GET request to the app origin (autosaves, drafts and locks included) after recording the write it would have made, and a browser-level hold hands every request of every other tab, popup, browser context and worker to the same hold (a write from one of them makes the case `NOT_CHECKED`, reason `extra_target`, and `scope_ok` false). It compares the write field by field with the person's save (identifiers such as `02134` compare as exact text; any extra held write fails the match; uncompared never counts as matched; a prefilled form or other contamination makes a case not comparable), and writes a one-page `scorecard.html` and an aggregates-only `scorecard.json` (matched N of M, risks, field errors, agent and human time, model cost and its source, estimated savings with its formula). Each candidate runs under the flight recorder's egress (`--egress scrubbed` by default, `blocked` or `unscrubbed`) with the OS egress block, and cost is metered by the proxy; a candidate that reports model calls the proxy didn't see is refused for that task. Each imported task names its target record in the candidate's inputs (`record_`). `--keep-session` carries a signed-in session across tasks. A card whose scope failed states what failed in place of the claim. What is checked: no non-GET request to the app origin left any tab, popup, browser context or worker except listed sign-in requests; not covered: GET requests with side effects, WebSocket writes, writes before attach | On main ([#2498](https://github.com/OpenAdaptAI/OpenAdapt/pull/2498)) | Synthetic (MockMed, 20 recorded tasks; scripted agent with 5 planted field errors and 2 wrong-record cases: precision and recall 1.0, 0 writes in the app's own store; an adversarial agent's six routes around the tab (popup form, `window.open`, `Target.createTarget`, a new browser context, a shared worker, a dedicated worker) land 0 writes in the store) | `openadapt-flow readiness`, [READINESS.md](packages/flow/docs/READINESS.md), [benchmark/readiness](packages/flow/benchmark/readiness/README.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | @@ -511,6 +512,7 @@ A test fails when a command has no file or this list is out of date. - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. - `proxy`: Holds the database credentials, and with `--api` the API credentials, and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof; each API write is sent once under a task-derived key, read back, and checked against the system's own event or audit log. +- `readiness`: Shadow a candidate agent or compiled program on tasks a person did, stopped before every save, and write a one-page Readiness Scorecard (matched N of M, risks, field errors, time and cost). - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/llms-full.txt b/llms-full.txt index e0a8430d3a..da96443d1f 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -789,6 +789,7 @@ improvising or retrying when something is off. | Turn a read-only browser task into a tool for the coding agent you already use: `openadapt setup` registers the MCP server and a skill in Claude Code, Cursor, Codex and Gemini CLI (idempotent, `--dry-run`, `--undo`); `openadapt setup --app deploy.yaml --verify verify.yaml` sets the agent up to teach saves in one web, desktop, RDP or Citrix app instead, each read back from the system of record. Read-only teaching runs only where a guard stops writes before they leave (the browser); `serve --teach-browser --config` naming a desktop, RDP or Citrix app is refused; the agent does the task once through `teach_start`/`teach_act`/`teach_finish`, the task must end in a download, the file is checked (columns, a column between two inputs or equal to one, fewest rows), the compiled steps are replayed once with no model, and the agent gets a `taught_` tool that downloads a checked file with new inputs. The browser sends no POST, PUT, PATCH or DELETE and stays on one site; a compiled run stops when a control is missing, matches more than one element, or is relabelled | Released ([#1502](https://github.com/OpenAdaptAI/OpenAdapt/pull/1502)) | Real headless Chromium on the local example portal (scripted MCP client, in CI); a real Claude Code agent taught the export from the guide's prompt and called the tool with new dates (2026-10-24, one run) | `openadapt setup`, `openadapt-agent serve --teach-browser`, [FIRST_TOOL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FIRST_TOOL.md) | | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | | See what your own agent gets wrong, with no risk: `openadapt shadow` is a loopback pass-through proxy beside the agent. It checks each write against the system of record (FHIR through `ensure_record`; SQL through the verifier's whole-database frame), checks each `CONFIRMED` again later, and writes `report.html` and `report.json`. It never blocks, changes or resends a write; the only delay is the read before a write (at most `hold_ms`) | [#1678](https://github.com/OpenAdaptAI/OpenAdapt/pull/1678) | Real app (Medplum 5.2.8, 37 cases through a fault proxy: scripted agent 18 of 18 harms caught, 0 correct writes refuted; Claude Sonnet 5.5 9 of 9 caught, 4 correct but corrected writes refuted; 0 writes by the shadow; 15 to 25 ms median added per write; setup 76.5 s machine time, 3 decisions); real app, SQL mode (Dolibarr 21 on MariaDB 11.4, 13 cases: 8 of 8 harms caught, 5 of 5 correct writes confirmed, 292 ms median added); synthetic (SQLite) | `openadapt shadow`, [SHADOW_MODE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SHADOW_MODE.md), [SHADOW_RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/SHADOW_RESULTS.md) | +| Score a candidate before it saves anything: `openadapt-flow readiness` imports 20 to 50 tasks a person did (the save from the browser recording's network capture, else a read-back through the verify config's reader, else refused), runs the candidate agent (`--agent-cmd`) or compiled program (`--program`) on each task in its own headless browser (DevTools on a pipe only, reached through a loopback relay that refuses any request without the run's random token; the page can reach only the app's origins) where the shadow hold refuses every non-GET request to the app origin (autosaves, drafts and locks included) after recording the write it would have made, and a browser-level hold hands every request of every other tab, popup, browser context and worker to the same hold (a write from one of them makes the case `NOT_CHECKED`, reason `extra_target`, and `scope_ok` false). It compares the write field by field with the person's save (identifiers such as `02134` compare as exact text; any extra held write fails the match; uncompared never counts as matched; a prefilled form or other contamination makes a case not comparable), and writes a one-page `scorecard.html` and an aggregates-only `scorecard.json` (matched N of M, risks, field errors, agent and human time, model cost and its source, estimated savings with its formula). Each candidate runs under the flight recorder's egress (`--egress scrubbed` by default, `blocked` or `unscrubbed`) with the OS egress block, and cost is metered by the proxy; a candidate that reports model calls the proxy didn't see is refused for that task. Each imported task names its target record in the candidate's inputs (`record_`). `--keep-session` carries a signed-in session across tasks. A card whose scope failed states what failed in place of the claim. What is checked: no non-GET request to the app origin left any tab, popup, browser context or worker except listed sign-in requests; not covered: GET requests with side effects, WebSocket writes, writes before attach | On main ([#2498](https://github.com/OpenAdaptAI/OpenAdapt/pull/2498)) | Synthetic (MockMed, 20 recorded tasks; scripted agent with 5 planted field errors and 2 wrong-record cases: precision and recall 1.0, 0 writes in the app's own store; an adversarial agent's six routes around the tab (popup form, `window.open`, `Target.createTarget`, a new browser context, a shared worker, a dedicated worker) land 0 writes in the store) | `openadapt-flow readiness`, [READINESS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/READINESS.md), [benchmark/readiness](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/readiness/README.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/skill_cache/README.md) | | Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | @@ -971,6 +972,7 @@ A test fails when a command has no file or this list is out of date. - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. - `proxy`: Holds the database credentials, and with `--api` the API credentials, and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof; each API write is sent once under a task-derived key, read back, and checked against the system's own event or audit log. +- `readiness`: Shadow a candidate agent or compiled program on tasks a person did, stopped before every save, and write a one-page Readiness Scorecard (matched N of M, risks, field errors, time and cost). - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 5d58e70507..4e923f1586 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -88,6 +88,7 @@ "pull": "workflow pull", "push": "workflow push", "qualify": "qualify", + "readiness": "qualify readiness", "receipt": "verify receipt", "handoff": "verify handoff", "reconcile": "verify reconcile", diff --git a/packages/flow/benchmark/readiness/README.md b/packages/flow/benchmark/readiness/README.md new file mode 100644 index 0000000000..78dc5993de --- /dev/null +++ b/packages/flow/benchmark/readiness/README.md @@ -0,0 +1,64 @@ +# Readiness: synthetic evidence + +What `tests/e2e/test_readiness_e2e.py` checks, in headless Chromium on +synthetic MockMed in front of the `effect_e2e` SQLite store (localhost only): + +1. A scripted person does 20 tasks (open a patient, add a Triage or Consult + encounter with a note, save) with the network capture on. Their saves + land in the store. +2. `readiness import` turns the 20 recordings into reference episodes; none + is refused. +3. The store is reset to its "before" state before each agent task. +4. A scripted agent, run as a subprocess through `SubprocessLauncher`, does + the same tasks on the guarded tab. It has 5 planted field errors (two + wrong encounter types, a letter O for a zero, an empty note, an extra + letter) and 2 planted wrong-record cases (it opens the next patient). +5. The shadow hold stops every save. The comparator and the scorecard must + find exactly the planted errors. + +Asserted: + +- the app's own store and write counter show no write after the run + (`landed_writes == 0`); +- precision and recall 1.0 on the planted field errors and on the planted + wrong-record cases; 13 of 20 matched; +- no case with an uncompared field is counted as matched; +- `scorecard.json` holds none of the notes or patient names. + +`results.json` is written by the test with `OPENADAPT_WRITE_EVIDENCE=1`, as +is `sample/`: one matched, one mismatched, one wrong-record and one +`extra_target` task's +`run.json`, `case.json`, `egress.json`, `usage.json` (and +`proposed_write.json`) with that run's `scorecard.json`, for the consumers' +join tests (J1, J2). All values in them are synthetic. + +`tests/e2e/test_readiness_adversarial_e2e.py` runs an adversarial agent +on the same app, one route per task, each trying to POST an encounter from +outside the guarded tab: a `target=_blank` form, `window.open` then `fetch` +from the popup, `Target.createTarget` on the browser endpoint then +`Runtime.evaluate` at once (the race against the hold attaching), a page in +a new browser context, a shared worker and a dedicated worker. Asserted, in +the app's own write counter and store: no write landed; every route reached +the hold (a held record per task); every route outside the tab is +`NOT_CHECKED` with reason `extra_target`; `scope_ok` is false. With the +browser-level hold turned off and auto-attach left on, 5 of the 6 routes +landed a write. The same file covers a service worker in a context the +agent made (held, on a small test app with its own POST counter), a session +carried across tasks with `keep_session`, and form values read from a real +page. + +Both e2e tests run their scripted agents with `--egress blocked` (the OS +egress block; no model calls), so each task's cost is metered as 0 and its +`egress.json` is checked; they skip where the block is unavailable (it is +macOS only). + +`claude_cu_agent.py` is a real-agent candidate for `readiness run +--agent-cmd`: the leaderboard's Claude computer-use loop on the guarded tab, +capped at 25 model calls and $1.00 per task by default. Its unit tests +(`tests/test_readiness_claude_cu_agent.py`) use a stub upstream only. + +Not shown here: contamination on a live screen (MockMed's record header +doesn't show saved encounters; the unit tests cover a form that opens +prefilled), out-of-process iframes, the compiled-program path (unit tests +only), and any real model. Running a real computer-use agent through +`readiness run` is the next evidence step. diff --git a/packages/flow/benchmark/readiness/claude_cu_agent.py b/packages/flow/benchmark/readiness/claude_cu_agent.py new file mode 100644 index 0000000000..eb2b02f261 --- /dev/null +++ b/packages/flow/benchmark/readiness/claude_cu_agent.py @@ -0,0 +1,200 @@ +"""A Claude computer-use candidate for ``openadapt-flow readiness run``. + +Use it as the agent command:: + + openadapt-flow readiness run --episodes episodes --out runs \\ + --app-url "$APP_URL" --egress scrubbed --spend-cap 1.00 \\ + --agent-cmd "python benchmark/readiness/claude_cu_agent.py" + +It reads ``OPENADAPT_GUARD_CDP_URL``, ``OPENADAPT_GUARD_PAGE_URL`` and +``OPENADAPT_TASK`` (the readiness launcher sets them), attaches to the +guarded tab over CDP, and runs the leaderboard's Claude computer-use loop +(``benchmark/fhir_medplum/leaderboard/agents/claude_cu.py``, reused as is) +with a preamble that names no app. The Anthropic SDK reads +``ANTHROPIC_API_KEY`` and ``ANTHROPIC_BASE_URL`` from the environment, so +under ``--egress scrubbed`` every call goes through the flight proxy. It +writes ``usage.json`` (``openadapt.agent-usage/v1``) after every model call +(the runner stops the process once the save is held, so a file written only +at the end would be lost); the proxy's metered count and cost are what the +scorecard uses, and this file is the cross-check. + +Hard caps per task (environment, never raised past the maximum): + +``OPENADAPT_CU_MAX_STEPS`` + model calls, default 25, at most 50; +``OPENADAPT_CU_MAX_USD`` + list-price spend, default 1.00, at most 5.00; +``OPENADAPT_CU_MAX_S`` + seconds, default 600, at most 1800. + +``OPENADAPT_CU_MODEL`` picks the model (default ``claude-sonnet-5-5``; it +must have a price in the loop's table, so the spend cap can hold). The +loop's own run ledger (the leaderboard's total spend file) is not touched. +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path +from typing import Any, Optional + +PREAMBLE = """\ +You are a staff member using your organisation's web application in a web \ +browser. The screen is 1280x800 pixels and you are already signed in. Use \ +only this app, and change nothing the task doesn't ask for. Do the task and \ +save it once. + +When you have finished, or if you can't finish, stop acting and end your \ +reply with one final line in exactly one of these two forms: +RESULT: DONE +RESULT: NOT DONE + +The task: +""" + +DEFAULT_MODEL = "claude-sonnet-5-5" +CAPS = { + # name: (environment variable, default, maximum) + "steps": ("OPENADAPT_CU_MAX_STEPS", 25, 50), + "usd": ("OPENADAPT_CU_MAX_USD", 1.0, 5.0), + "seconds": ("OPENADAPT_CU_MAX_S", 600, 1800), +} + + +def caps(env: Optional[dict[str, str]] = None) -> dict[str, float]: + """The task's caps: the environment's values, clamped to the maximums.""" + + env = dict(os.environ if env is None else env) + out: dict[str, float] = {} + for name, (var, default, ceiling) in CAPS.items(): + try: + value = float(env.get(var, default)) + except ValueError: + value = float(default) + out[name] = min(max(value, 0.0), float(ceiling)) + return out + + +def _loop_modules() -> tuple[Any, Any]: + root = Path(__file__).resolve().parents[2] + if str(root) not in sys.path: + sys.path.insert(0, str(root)) + from benchmark.fhir_medplum.leaderboard import common + from benchmark.fhir_medplum.leaderboard.agents import claude_cu + + return claude_cu, common + + +def _usage(meter: Any, model: str, **extra: Any) -> dict[str, Any]: + return { + "schema": "openadapt.agent-usage/v1", + "calls": meter.calls, + "input_tokens": meter.tokens_in, + "output_tokens": meter.tokens_out, + "model": model, + "cost_usd": round(meter.usd, 6), + **extra, + } + + +def _write_usage(path: Optional[Path], usage: dict[str, Any]) -> None: + if path is None: + return + tmp = path.with_name(path.name + ".tmp") + tmp.write_text(json.dumps(usage, indent=2, sort_keys=True)) + os.replace(tmp, path) + + +def make_meter( + label: str, + limits: dict[str, float], + *, + model: str = DEFAULT_MODEL, + usage_path: Optional[Path] = None, +) -> Any: + """The loop's ``Meter`` with this task's caps, no shared ledger, and + ``usage.json`` rewritten after every call.""" + + _, common = _loop_modules() + + class TaskMeter(common.Meter): + def before_call(self) -> None: + if self.calls >= int(limits["steps"]): + raise common.RunLimit(f"step cap: {int(limits['steps'])} model calls") + if self.usd >= limits["usd"]: + raise common.RunLimit(f"spend cap: ${self.usd:.2f} of ${limits['usd']:.2f}") + if time.monotonic() - self.started > limits["seconds"]: + raise common.RunLimit(f"time cap: {int(limits['seconds'])} s") + + def record(self, usd: float, tokens_in: int, tokens_out: int, **extra: Any) -> None: + self.calls += 1 + self.usd += usd + self.tokens_in += tokens_in + self.tokens_out += tokens_out + self.usage.append({"in": tokens_in, "out": tokens_out, "usd": round(usd, 6)}) + _write_usage(usage_path, _usage(self, model)) + + return TaskMeter(label=label) + + +def run_task( + instruction: str, + screen: Any, + *, + model: str = DEFAULT_MODEL, + limits: Optional[dict[str, float]] = None, + usage_path: Optional[Path] = None, +) -> dict[str, Any]: + """One task through the reused loop; returns ``usage.json``'s content + (also written to ``usage_path`` after every call and at the end).""" + + claude_cu, _ = _loop_modules() + if model not in claude_cu.PRICES: + raise SystemExit(f"model {model!r} has no price in the loop's table; the spend cap can't hold") + limits = limits or caps() + meter = make_meter(f"claude {model}", limits, model=model, usage_path=usage_path) + _write_usage(usage_path, _usage(meter, model)) + claude_cu.PREAMBLE = PREAMBLE # the loop prepends it; this one names no app + try: + result = claude_cu.run(instruction, screen, meter, model=model) + stopped, final = result.stopped, (result.final_text or "").strip().splitlines()[-1:] + except Exception as exc: # noqa: BLE001 - the calls made so far are still reported + stopped, final = f"error: {type(exc).__name__}", [] + usage = _usage( + meter, model, stopped=stopped, final_line=final[0][:300] if final else None + ) + _write_usage(usage_path, usage) + return usage + + +def main() -> int: + from playwright.sync_api import sync_playwright + + _, _ = _loop_modules() + from benchmark.fhir_medplum.leaderboard.browser import Screen + + cdp_url = os.environ["OPENADAPT_GUARD_CDP_URL"] + page_url = os.environ["OPENADAPT_GUARD_PAGE_URL"] + instruction = os.environ["OPENADAPT_TASK"] + usage_path = Path(os.environ["OPENADAPT_USAGE_PATH"]) + model = os.environ.get("OPENADAPT_CU_MODEL", DEFAULT_MODEL) + base = page_url.split("#", 1)[0].split("?", 1)[0] + with sync_playwright() as pw: + browser = pw.chromium.connect_over_cdp(cdp_url) + page = next( + (p for c in browser.contexts for p in c.pages if p.url.startswith(base)), + None, + ) + if page is None: + print("the guarded tab was not found", file=sys.stderr) + return 3 + usage = run_task(instruction, Screen(page), model=model, usage_path=usage_path) + print(json.dumps({k: usage.get(k) for k in ("calls", "cost_usd", "stopped")})) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/flow/benchmark/readiness/results.json b/packages/flow/benchmark/readiness/results.json new file mode 100644 index 0000000000..2976fe0814 --- /dev/null +++ b/packages/flow/benchmark/readiness/results.json @@ -0,0 +1,168 @@ +{ + "app_store_unchanged": true, + "app_writes_after_run": 0, + "episodes": 20, + "field_error_precision_recall": [ + 1.0, + 1.0 + ], + "fixture": "MockMed (synthetic) in front of the effect_e2e SQLite store", + "found": { + "field_errors": [ + [ + "readiness-mockmed-0001", + "type" + ], + [ + "readiness-mockmed-0004", + "note" + ], + [ + "readiness-mockmed-0007", + "note" + ], + [ + "readiness-mockmed-0010", + "type" + ], + [ + "readiness-mockmed-0013", + "note" + ] + ], + "wrong_record": [ + "readiness-mockmed-0016", + "readiness-mockmed-0019" + ] + }, + "planted": { + "field_errors": [ + [ + "readiness-mockmed-0001", + "type" + ], + [ + "readiness-mockmed-0004", + "note" + ], + [ + "readiness-mockmed-0007", + "note" + ], + [ + "readiness-mockmed-0010", + "type" + ], + [ + "readiness-mockmed-0013", + "note" + ] + ], + "wrong_record": [ + "readiness-mockmed-0016", + "readiness-mockmed-0019" + ] + }, + "run_seconds": 69.5, + "run_statuses": [ + "HELD" + ], + "schema": "openadapt.readiness-evidence/v1", + "scorecard": { + "agent_label": "scripted-agent", + "agent_time_s": { + "mean": 2.054, + "median": 2.055 + }, + "cases_total": 20, + "egress": { + "enforced": true, + "mode": "blocked", + "model_calls": 0 + }, + "failed_scope": 0, + "field_errors": [ + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0001" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0004" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0007" + }, + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0010" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0013" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0016" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0019" + } + ], + "generated_at": "2026-11-22T07:41:24+00:00", + "human_time_s": { + "mean": 0.932, + "median": 0.933 + }, + "landed_writes": 0, + "matched": 13, + "mismatched": 7, + "mode": "sandbox", + "model_cost_usd": { + "per_task": 0.0, + "source": "metered", + "total": 0.0, + "unknown_count": 0 + }, + "not_checked": 0, + "not_comparable": 0, + "replay_state": "Sandbox: each task ran on a sandbox or test tenant reset to synthetic \"before\" state; the person's saved values are the reference.", + "risks": { + "double_save": 0, + "out_of_scope_request": 0, + "undeclared_field": 0, + "wrong_record": 2 + }, + "savings": { + "est_value_usd": -0.16, + "estimate": true, + "formula": "(human_median_s - agent_median_s) / 60 = minutes saved per task; x matched cases / 60 x hourly cost - model cost = estimated value", + "inputs": { + "agent_median_s": 2.055, + "hourly_cost_usd": 40.0, + "human_median_s": 0.933, + "matched_cases": 13, + "model_cost_usd": 0.0, + "why_no_value": null + }, + "minutes_saved_per_task": -0.019 + }, + "schema": "openadapt.readiness-scorecard/v1", + "scope_ok": true, + "scope_statement": "No non-GET request to the app origin left any tab, popup, browser context or worker, except listed sign-in requests. Not covered: GET side effects, WebSocket writes, writes before attach.", + "task_type": "unspecified" + }, + "wrong_record_precision_recall": [ + 1.0, + 1.0 + ] +} diff --git a/packages/flow/benchmark/readiness/sample/extra-target/case.json b/packages/flow/benchmark/readiness/sample/extra-target/case.json new file mode 100644 index 0000000000..0ccfa0a7ab --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/extra-target/case.json @@ -0,0 +1,19 @@ +{ + "agent_time_s": 0.694, + "contamination": null, + "double_save": false, + "extra_held_writes": 0, + "fields": [], + "human_time_s": 0.935, + "identity": null, + "landed_writes": 0, + "model_calls_metered": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "out_of_scope_requests": 0, + "reason": "extra_target", + "schema": "openadapt.readiness-case/v1", + "status": "NOT_CHECKED", + "task_id": "readiness-mockmed-0002", + "undeclared_fields": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/extra-target/egress.json b/packages/flow/benchmark/readiness/sample/extra-target/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/extra-target/egress.json @@ -0,0 +1,8 @@ +{ + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "refused_requests": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/extra-target/run.json b/packages/flow/benchmark/readiness/sample/extra-target/run.json new file mode 100644 index 0000000000..3f48f08eb6 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/extra-target/run.json @@ -0,0 +1,53 @@ +{ + "agent_wall_s": 0.694, + "before_screen": false, + "browser_network": { + "allowed_origins": [ + "http://127.0.0.1:61962" + ], + "limited": true + }, + "double_save": false, + "egress": { + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "reason": null, + "refused": false, + "refused_requests": 0 + }, + "ended": "agent_exited", + "exit_code": 0, + "extra_target_writes": 1, + "held": 1, + "landed_writes": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "notes": [], + "other_origin_refused": 0, + "proposed": false, + "requests": { + "save": 1 + }, + "schema": "openadapt.readiness-task-run/v1", + "session": "fresh", + "status": "EXTRA_TARGET", + "target_gate": { + "errors": [], + "extra_targets": { + "page": 1 + }, + "gate_lost": false, + "ungated_targets": {} + }, + "task_id": "readiness-mockmed-0002", + "usage": { + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0 + } +} diff --git a/packages/flow/benchmark/readiness/sample/extra-target/scorecard.json b/packages/flow/benchmark/readiness/sample/extra-target/scorecard.json new file mode 100644 index 0000000000..2c575ed833 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/extra-target/scorecard.json @@ -0,0 +1,63 @@ +{ + "agent_label": "adversarial-agent", + "agent_time_s": { + "mean": 1.053, + "median": 0.698 + }, + "cases_total": 6, + "egress": { + "enforced": true, + "mode": "blocked", + "model_calls": 0 + }, + "failed_scope": 5, + "field_errors": [ + { + "field": "", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0005" + } + ], + "generated_at": "2026-11-22T07:41:43+00:00", + "human_time_s": { + "mean": 0.938, + "median": 0.936 + }, + "landed_writes": 0, + "matched": 0, + "mismatched": 1, + "mode": "sandbox", + "model_cost_usd": { + "per_task": 0.0, + "source": "metered", + "total": 0.0, + "unknown_count": 0 + }, + "not_checked": 5, + "not_comparable": 0, + "replay_state": "Sandbox: each task ran on a sandbox or test tenant reset to synthetic \"before\" state; the person's saved values are the reference.", + "risks": { + "double_save": 0, + "out_of_scope_request": 0, + "undeclared_field": 0, + "wrong_record": 1 + }, + "savings": { + "est_value_usd": null, + "estimate": true, + "formula": "(human_median_s - agent_median_s) / 60 = minutes saved per task; x matched cases / 60 x hourly cost - model cost = estimated value", + "inputs": { + "agent_median_s": 0.698, + "hourly_cost_usd": null, + "human_median_s": 0.936, + "matched_cases": 0, + "model_cost_usd": 0.0, + "why_no_value": "no --hourly-cost given" + }, + "minutes_saved_per_task": 0.004 + }, + "schema": "openadapt.readiness-scorecard/v1", + "scope_ok": false, + "scope_statement": "Scope failed in 5 of 6 case(s): 5 case(s) had a tab, popup, context or worker the hold couldn't vouch for. Not a clean shadow run.", + "task_type": "unspecified" +} diff --git a/packages/flow/benchmark/readiness/sample/extra-target/usage.json b/packages/flow/benchmark/readiness/sample/extra-target/usage.json new file mode 100644 index 0000000000..beb2fa7089 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/extra-target/usage.json @@ -0,0 +1,8 @@ +{ + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0, + "schema": "openadapt.agent-usage/v1" +} diff --git a/packages/flow/benchmark/readiness/sample/matched/case.json b/packages/flow/benchmark/readiness/sample/matched/case.json new file mode 100644 index 0000000000..399dcf8d40 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/matched/case.json @@ -0,0 +1,40 @@ +{ + "agent_time_s": 2.021, + "contamination": { + "compared": 2, + "not_comparable": false, + "reason": null, + "shown": 0 + }, + "double_save": false, + "extra_held_writes": 0, + "fields": [ + { + "human": "Triage", + "kind": "matched", + "name": "type", + "proposed": "Triage" + }, + { + "human": "Synthetic note 00 for review", + "kind": "matched", + "name": "note", + "proposed": "Synthetic note 00 for review" + } + ], + "human_time_s": 0.969, + "identity": { + "code": "verified", + "ok": true + }, + "landed_writes": 0, + "model_calls_metered": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "out_of_scope_requests": 0, + "reason": null, + "schema": "openadapt.readiness-case/v1", + "status": "MATCHED", + "task_id": "readiness-mockmed-0000", + "undeclared_fields": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/matched/egress.json b/packages/flow/benchmark/readiness/sample/matched/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/matched/egress.json @@ -0,0 +1,8 @@ +{ + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "refused_requests": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/matched/proposed_write.json b/packages/flow/benchmark/readiness/sample/matched/proposed_write.json new file mode 100644 index 0000000000..4c4353f450 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/matched/proposed_write.json @@ -0,0 +1,35 @@ +{ + "fields": [ + { + "name": "patient_id", + "parse": "json", + "value": "p1" + }, + { + "name": "type", + "parse": "json", + "value": "Triage" + }, + { + "name": "note", + "parse": "json", + "value": "Synthetic note 00 for review" + } + ], + "held_at": "2026-11-22T07:40:17.020+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:61403", + "refused": true, + "request_index": 0, + "resource_type": "XHR", + "schema": "openadapt.proposed-write/v1", + "screen_text": "held/0.screen.txt", + "screenshot": "held/0.png", + "task_id": "readiness-mockmed-0000", + "url_path": "/api/encounter", + "withheld_fields": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/matched/run.json b/packages/flow/benchmark/readiness/sample/matched/run.json new file mode 100644 index 0000000000..0b46db5bb7 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/matched/run.json @@ -0,0 +1,51 @@ +{ + "agent_wall_s": 2.021, + "before_screen": true, + "browser_network": { + "allowed_origins": [ + "http://127.0.0.1:61403" + ], + "limited": true + }, + "double_save": false, + "egress": { + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "reason": null, + "refused": false, + "refused_requests": 0 + }, + "ended": "held", + "exit_code": 0, + "extra_target_writes": 0, + "held": 1, + "landed_writes": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "notes": [], + "other_origin_refused": 0, + "proposed": true, + "requests": { + "save": 1 + }, + "schema": "openadapt.readiness-task-run/v1", + "session": "fresh", + "status": "HELD", + "target_gate": { + "errors": [], + "extra_targets": {}, + "gate_lost": false, + "ungated_targets": {} + }, + "task_id": "readiness-mockmed-0000", + "usage": { + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0 + } +} diff --git a/packages/flow/benchmark/readiness/sample/matched/scorecard.json b/packages/flow/benchmark/readiness/sample/matched/scorecard.json new file mode 100644 index 0000000000..5761035e45 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/matched/scorecard.json @@ -0,0 +1,93 @@ +{ + "agent_label": "scripted-agent", + "agent_time_s": { + "mean": 2.054, + "median": 2.055 + }, + "cases_total": 20, + "egress": { + "enforced": true, + "mode": "blocked", + "model_calls": 0 + }, + "failed_scope": 0, + "field_errors": [ + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0001" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0004" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0007" + }, + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0010" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0013" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0016" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0019" + } + ], + "generated_at": "2026-11-22T07:41:24+00:00", + "human_time_s": { + "mean": 0.932, + "median": 0.933 + }, + "landed_writes": 0, + "matched": 13, + "mismatched": 7, + "mode": "sandbox", + "model_cost_usd": { + "per_task": 0.0, + "source": "metered", + "total": 0.0, + "unknown_count": 0 + }, + "not_checked": 0, + "not_comparable": 0, + "replay_state": "Sandbox: each task ran on a sandbox or test tenant reset to synthetic \"before\" state; the person's saved values are the reference.", + "risks": { + "double_save": 0, + "out_of_scope_request": 0, + "undeclared_field": 0, + "wrong_record": 2 + }, + "savings": { + "est_value_usd": -0.16, + "estimate": true, + "formula": "(human_median_s - agent_median_s) / 60 = minutes saved per task; x matched cases / 60 x hourly cost - model cost = estimated value", + "inputs": { + "agent_median_s": 2.055, + "hourly_cost_usd": 40.0, + "human_median_s": 0.933, + "matched_cases": 13, + "model_cost_usd": 0.0, + "why_no_value": null + }, + "minutes_saved_per_task": -0.019 + }, + "schema": "openadapt.readiness-scorecard/v1", + "scope_ok": true, + "scope_statement": "No non-GET request to the app origin left any tab, popup, browser context or worker, except listed sign-in requests. Not covered: GET side effects, WebSocket writes, writes before attach.", + "task_type": "unspecified" +} diff --git a/packages/flow/benchmark/readiness/sample/matched/usage.json b/packages/flow/benchmark/readiness/sample/matched/usage.json new file mode 100644 index 0000000000..beb2fa7089 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/matched/usage.json @@ -0,0 +1,8 @@ +{ + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0, + "schema": "openadapt.agent-usage/v1" +} diff --git a/packages/flow/benchmark/readiness/sample/mismatched/case.json b/packages/flow/benchmark/readiness/sample/mismatched/case.json new file mode 100644 index 0000000000..1069b77036 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/mismatched/case.json @@ -0,0 +1,40 @@ +{ + "agent_time_s": 2.046, + "contamination": { + "compared": 2, + "not_comparable": false, + "reason": null, + "shown": 0 + }, + "double_save": false, + "extra_held_writes": 0, + "fields": [ + { + "human": "Consult", + "kind": "mismatched", + "name": "type", + "proposed": "Triage" + }, + { + "human": "Synthetic note 01 for review", + "kind": "matched", + "name": "note", + "proposed": "Synthetic note 01 for review" + } + ], + "human_time_s": 0.932, + "identity": { + "code": "verified", + "ok": true + }, + "landed_writes": 0, + "model_calls_metered": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "out_of_scope_requests": 0, + "reason": null, + "schema": "openadapt.readiness-case/v1", + "status": "MISMATCHED", + "task_id": "readiness-mockmed-0001", + "undeclared_fields": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/mismatched/egress.json b/packages/flow/benchmark/readiness/sample/mismatched/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/mismatched/egress.json @@ -0,0 +1,8 @@ +{ + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "refused_requests": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/mismatched/proposed_write.json b/packages/flow/benchmark/readiness/sample/mismatched/proposed_write.json new file mode 100644 index 0000000000..59ed389c99 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/mismatched/proposed_write.json @@ -0,0 +1,35 @@ +{ + "fields": [ + { + "name": "patient_id", + "parse": "json", + "value": "p2" + }, + { + "name": "type", + "parse": "json", + "value": "Triage" + }, + { + "name": "note", + "parse": "json", + "value": "Synthetic note 01 for review" + } + ], + "held_at": "2026-11-22T07:40:20.453+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:61403", + "refused": true, + "request_index": 0, + "resource_type": "XHR", + "schema": "openadapt.proposed-write/v1", + "screen_text": "held/0.screen.txt", + "screenshot": "held/0.png", + "task_id": "readiness-mockmed-0001", + "url_path": "/api/encounter", + "withheld_fields": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/mismatched/run.json b/packages/flow/benchmark/readiness/sample/mismatched/run.json new file mode 100644 index 0000000000..03cbe7a2d5 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/mismatched/run.json @@ -0,0 +1,51 @@ +{ + "agent_wall_s": 2.046, + "before_screen": true, + "browser_network": { + "allowed_origins": [ + "http://127.0.0.1:61403" + ], + "limited": true + }, + "double_save": false, + "egress": { + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "reason": null, + "refused": false, + "refused_requests": 0 + }, + "ended": "held", + "exit_code": 0, + "extra_target_writes": 0, + "held": 1, + "landed_writes": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "notes": [], + "other_origin_refused": 0, + "proposed": true, + "requests": { + "save": 1 + }, + "schema": "openadapt.readiness-task-run/v1", + "session": "fresh", + "status": "HELD", + "target_gate": { + "errors": [], + "extra_targets": {}, + "gate_lost": false, + "ungated_targets": {} + }, + "task_id": "readiness-mockmed-0001", + "usage": { + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0 + } +} diff --git a/packages/flow/benchmark/readiness/sample/mismatched/scorecard.json b/packages/flow/benchmark/readiness/sample/mismatched/scorecard.json new file mode 100644 index 0000000000..5761035e45 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/mismatched/scorecard.json @@ -0,0 +1,93 @@ +{ + "agent_label": "scripted-agent", + "agent_time_s": { + "mean": 2.054, + "median": 2.055 + }, + "cases_total": 20, + "egress": { + "enforced": true, + "mode": "blocked", + "model_calls": 0 + }, + "failed_scope": 0, + "field_errors": [ + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0001" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0004" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0007" + }, + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0010" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0013" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0016" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0019" + } + ], + "generated_at": "2026-11-22T07:41:24+00:00", + "human_time_s": { + "mean": 0.932, + "median": 0.933 + }, + "landed_writes": 0, + "matched": 13, + "mismatched": 7, + "mode": "sandbox", + "model_cost_usd": { + "per_task": 0.0, + "source": "metered", + "total": 0.0, + "unknown_count": 0 + }, + "not_checked": 0, + "not_comparable": 0, + "replay_state": "Sandbox: each task ran on a sandbox or test tenant reset to synthetic \"before\" state; the person's saved values are the reference.", + "risks": { + "double_save": 0, + "out_of_scope_request": 0, + "undeclared_field": 0, + "wrong_record": 2 + }, + "savings": { + "est_value_usd": -0.16, + "estimate": true, + "formula": "(human_median_s - agent_median_s) / 60 = minutes saved per task; x matched cases / 60 x hourly cost - model cost = estimated value", + "inputs": { + "agent_median_s": 2.055, + "hourly_cost_usd": 40.0, + "human_median_s": 0.933, + "matched_cases": 13, + "model_cost_usd": 0.0, + "why_no_value": null + }, + "minutes_saved_per_task": -0.019 + }, + "schema": "openadapt.readiness-scorecard/v1", + "scope_ok": true, + "scope_statement": "No non-GET request to the app origin left any tab, popup, browser context or worker, except listed sign-in requests. Not covered: GET side effects, WebSocket writes, writes before attach.", + "task_type": "unspecified" +} diff --git a/packages/flow/benchmark/readiness/sample/mismatched/usage.json b/packages/flow/benchmark/readiness/sample/mismatched/usage.json new file mode 100644 index 0000000000..beb2fa7089 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/mismatched/usage.json @@ -0,0 +1,8 @@ +{ + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0, + "schema": "openadapt.agent-usage/v1" +} diff --git a/packages/flow/benchmark/readiness/sample/wrong-record/case.json b/packages/flow/benchmark/readiness/sample/wrong-record/case.json new file mode 100644 index 0000000000..6a0187f4c6 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/wrong-record/case.json @@ -0,0 +1,41 @@ +{ + "agent_time_s": 2.073, + "contamination": null, + "double_save": false, + "extra_held_writes": 0, + "fields": [ + { + "human": "p2", + "kind": "wrong_record", + "name": "patient_id", + "proposed": "p3" + }, + { + "human": "Triage", + "kind": "matched", + "name": "type", + "proposed": "Triage" + }, + { + "human": "Synthetic note 16 for review", + "kind": "matched", + "name": "note", + "proposed": "Synthetic note 16 for review" + } + ], + "human_time_s": 0.948, + "identity": { + "code": "identity_mismatch", + "ok": false + }, + "landed_writes": 0, + "model_calls_metered": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "out_of_scope_requests": 0, + "reason": "identity_mismatch", + "schema": "openadapt.readiness-case/v1", + "status": "WRONG_RECORD", + "task_id": "readiness-mockmed-0016", + "undeclared_fields": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/wrong-record/egress.json b/packages/flow/benchmark/readiness/sample/wrong-record/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/wrong-record/egress.json @@ -0,0 +1,8 @@ +{ + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "refused_requests": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/wrong-record/proposed_write.json b/packages/flow/benchmark/readiness/sample/wrong-record/proposed_write.json new file mode 100644 index 0000000000..9a09026f91 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/wrong-record/proposed_write.json @@ -0,0 +1,35 @@ +{ + "fields": [ + { + "name": "patient_id", + "parse": "json", + "value": "p3" + }, + { + "name": "type", + "parse": "json", + "value": "Triage" + }, + { + "name": "note", + "parse": "json", + "value": "Synthetic note 16 for review" + } + ], + "held_at": "2026-11-22T07:41:12.536+00:00", + "identity": { + "code": "identity_mismatch", + "ok": false + }, + "method": "POST", + "origin": "http://127.0.0.1:61403", + "refused": true, + "request_index": 0, + "resource_type": "XHR", + "schema": "openadapt.proposed-write/v1", + "screen_text": "held/0.screen.txt", + "screenshot": "held/0.png", + "task_id": "readiness-mockmed-0016", + "url_path": "/api/encounter", + "withheld_fields": 0 +} diff --git a/packages/flow/benchmark/readiness/sample/wrong-record/run.json b/packages/flow/benchmark/readiness/sample/wrong-record/run.json new file mode 100644 index 0000000000..664452e91b --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/wrong-record/run.json @@ -0,0 +1,51 @@ +{ + "agent_wall_s": 2.073, + "before_screen": false, + "browser_network": { + "allowed_origins": [ + "http://127.0.0.1:61403" + ], + "limited": true + }, + "double_save": false, + "egress": { + "cost_source": "metered", + "cost_usd": 0.0, + "enforced": true, + "mode": "blocked", + "model_calls": 0, + "reason": null, + "refused": false, + "refused_requests": 0 + }, + "ended": "held", + "exit_code": 0, + "extra_target_writes": 0, + "held": 1, + "landed_writes": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.0, + "notes": [], + "other_origin_refused": 0, + "proposed": true, + "requests": { + "save": 1 + }, + "schema": "openadapt.readiness-task-run/v1", + "session": "fresh", + "status": "HELD", + "target_gate": { + "errors": [], + "extra_targets": {}, + "gate_lost": false, + "ungated_targets": {} + }, + "task_id": "readiness-mockmed-0016", + "usage": { + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0 + } +} diff --git a/packages/flow/benchmark/readiness/sample/wrong-record/scorecard.json b/packages/flow/benchmark/readiness/sample/wrong-record/scorecard.json new file mode 100644 index 0000000000..5761035e45 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/wrong-record/scorecard.json @@ -0,0 +1,93 @@ +{ + "agent_label": "scripted-agent", + "agent_time_s": { + "mean": 2.054, + "median": 2.055 + }, + "cases_total": 20, + "egress": { + "enforced": true, + "mode": "blocked", + "model_calls": 0 + }, + "failed_scope": 0, + "field_errors": [ + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0001" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0004" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0007" + }, + { + "field": "type", + "kind": "mismatched", + "task_id": "readiness-mockmed-0010" + }, + { + "field": "note", + "kind": "mismatched", + "task_id": "readiness-mockmed-0013" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0016" + }, + { + "field": "patient_id", + "kind": "wrong_record", + "task_id": "readiness-mockmed-0019" + } + ], + "generated_at": "2026-11-22T07:41:24+00:00", + "human_time_s": { + "mean": 0.932, + "median": 0.933 + }, + "landed_writes": 0, + "matched": 13, + "mismatched": 7, + "mode": "sandbox", + "model_cost_usd": { + "per_task": 0.0, + "source": "metered", + "total": 0.0, + "unknown_count": 0 + }, + "not_checked": 0, + "not_comparable": 0, + "replay_state": "Sandbox: each task ran on a sandbox or test tenant reset to synthetic \"before\" state; the person's saved values are the reference.", + "risks": { + "double_save": 0, + "out_of_scope_request": 0, + "undeclared_field": 0, + "wrong_record": 2 + }, + "savings": { + "est_value_usd": -0.16, + "estimate": true, + "formula": "(human_median_s - agent_median_s) / 60 = minutes saved per task; x matched cases / 60 x hourly cost - model cost = estimated value", + "inputs": { + "agent_median_s": 2.055, + "hourly_cost_usd": 40.0, + "human_median_s": 0.933, + "matched_cases": 13, + "model_cost_usd": 0.0, + "why_no_value": null + }, + "minutes_saved_per_task": -0.019 + }, + "schema": "openadapt.readiness-scorecard/v1", + "scope_ok": true, + "scope_statement": "No non-GET request to the app origin left any tab, popup, browser context or worker, except listed sign-in requests. Not covered: GET side effects, WebSocket writes, writes before attach.", + "task_type": "unspecified" +} diff --git a/packages/flow/benchmark/readiness/sample/wrong-record/usage.json b/packages/flow/benchmark/readiness/sample/wrong-record/usage.json new file mode 100644 index 0000000000..beb2fa7089 --- /dev/null +++ b/packages/flow/benchmark/readiness/sample/wrong-record/usage.json @@ -0,0 +1,8 @@ +{ + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0, + "schema": "openadapt.agent-usage/v1" +} diff --git a/packages/flow/docs/BACKEND_PARITY.md b/packages/flow/docs/BACKEND_PARITY.md index 52ad243df6..095cb658c8 100644 --- a/packages/flow/docs/BACKEND_PARITY.md +++ b/packages/flow/docs/BACKEND_PARITY.md @@ -340,6 +340,8 @@ and `--log-url`, the transparency log) are not app URLs. | Command | URL flag | Why it has no backend-neutral alternative | | --- | --- | --- | +| `openadapt-flow readiness import` | `--app-url` | It filters a recorded network capture to the app's origin: a browser recording is the only reference source that has request origins. | +| `openadapt-flow readiness run` | `--app-url` | The shadow hold works on the browser's own requests (CDP `Fetch`), so it is web-only; a candidate on another surface has no request to hold. | | `openadapt-flow validate-hosted` | `--target-url` | The surface comes from the signed run report. A non-web report refuses a target URL ("Target URL is web-only and must be omitted"). | | `openadapt-agent authoring connect` | `--url` | `--url` opens a fresh browser. Without it the command pins the local app window (one macOS or Linux window). Windows, RDP and Citrix are coach-only on the mailbox: the person drives and Capture records (`COACH_ONLY_BACKENDS` in `agent/mailbox.py`). | | `openadapt-agent seal keys pin` | `--url` | The seal key server's address, not an app. | diff --git a/packages/flow/docs/READINESS.md b/packages/flow/docs/READINESS.md new file mode 100644 index 0000000000..19a88c1829 --- /dev/null +++ b/packages/flow/docs/READINESS.md @@ -0,0 +1,484 @@ +# Readiness: shadow a candidate on tasks a person did + +`openadapt-flow readiness` answers one question before a candidate agent, or +a compiled program, is allowed to save anything: on the tasks your people +already do, how often would it have saved exactly what they saved? + +1. A person does 20 to 50 real tasks with the browser recording's network + capture on (`record --backend web --capture-network`, see + [BROWSER_RECORDING.md](BROWSER_RECORDING.md) and + [NETWORK_CAPTURE.md](NETWORK_CAPTURE.md)). +2. `readiness import` turns each recorded task into a reference episode. +3. `readiness run` gives the candidate the same tasks on a guarded browser + tab. It navigates and fills every field; the shadow hold stops it before + Save, Submit or Send and records the write it would have made. +4. `readiness compare` compares each proposed write with the person's save, + field by field. +5. `readiness report` writes `scorecard.html` (one page) and + `scorecard.json` (aggregates only). + +Scope of the hold, as the scorecard states it: + +> No non-GET request to the app origin left any tab, popup, browser context +> or worker, except listed sign-in requests. Not covered: GET side effects, +> WebSocket writes, writes before attach. + +That is the statement of a clean run. When `scope_ok` is false, the +scorecard's `scope_statement` (and the page) says what failed instead, for +example "Scope failed in 2 of 20 case(s): 1 write(s) reached the app; 1 +case(s) had a tab, popup, context or worker the hold couldn't vouch for. +Not a clean shadow run." Both stay under 200 characters. + +That is what is checked; it is not a claim that the run had no effect on +the app. A case the hold can't vouch for outside the guarded tab is +`NOT_CHECKED` with reason `extra_target` and turns `scope_ok` false (see +[Other tabs, popups, contexts and workers](#other-tabs-popups-contexts-and-workers)). + +## Commands + +```bash +openadapt-flow readiness import --from human-tasks --out episodes \ + --app-url https://sandbox.example.test/ +openadapt-flow readiness run --episodes episodes --out runs \ + --app-url "https://sandbox.example.test/" \ + --agent-cmd "python my_agent.py" \ + --reset-cmd "./reset-sandbox.sh" \ + --screen-selector "#record-header" \ + --not-save POST:/login +openadapt-flow readiness compare --episodes episodes --runs runs --out card +openadapt-flow readiness report --cases card/cases.json --out card \ + --hourly-cost 38 --task-type encounter-note +``` + +`run` takes `--program BUNDLE` instead of `--agent-cmd` for a compiled +program. + +A signed-in session across tasks: `--storage-state FILE` loads a Playwright +storage state (cookies and local storage, for example saved once with +`context.storage_state(path=...)` after a person signed in) into every +task's browser context, and `--keep-session` carries the state at the end of +each task into the next one, so a person signs in and passes 2FA once, not +once per task. The carried state lives in `RUNS/.session/` (mode 0600) and +is removed when the run ends. Each task still gets its own browser, hold, +target gate and run folder. Local storage is carried too: an app that keeps +drafts there can carry one task's draft into the next, which the +contamination check reads like any prefilled form. + +## Reference episodes (`import`) + +One folder per task. `task.json` (`openadapt.readiness-task/v1`): + +```json +{"schema": "openadapt.readiness-task/v1", + "task_id": "intake-000123", + "instruction": "Add the triage note from the referral.", + "inputs": {"note": "..."}, + "expected_record": {"patient_id": "p1", "name": "Jane Sample"}, + "save": {"method": "POST", "path": "/api/encounter"}, + "not_saves": [{"method": "POST", "path": "/login"}], + "fields": ["type", "note"], + "readback": {"verify": "verify.yaml", "match": {}}} +``` + +`save`, `not_saves`, `fields` and `readback` are optional. The recording sits +in `recording/` (or in the task folder itself). + +The person's saved values come from, in this order: + +1. **The network capture of the save** (`human_source: "network_capture"`). + The save is the last successful write to the app's origin; `save` names + it when the recording holds more than one kind of write (a lock and a + save), and two kinds without `save` are refused as ambiguous. The body is + parsed with the shadow hold's own parser, so both sides are read the same + way. +2. **A read-back of the saved record** (`human_source: "readback"`) through + the system-of-record verifier in `readback.verify` (the reader + `verify-run` uses). Exactly one record must carry every `expected_record` + and `readback.match` value; `fields` names what is compared. +3. Otherwise the episode is **refused**. A reference is never made up. + +Refusal codes: `task_invalid`, `task_unreadable`, `no_save_in_capture`, +`ambiguous_save`, `save_not_confirmed` (the save failed or returned an +error), `save_unreadable` (the capture did not keep the body), +`readback_invalid`, `readback_unavailable`, `readback_ambiguous`, +`no_source`, `no_fields`, `duplicate_task_id`. + +The person's time is first recorded event to the save request +(`human_duration_s`), from the recording's own clock. + +Output per episode, under `EPISODES//`: + +- `reference_episode.json`, `openadapt.reference-episode/v1`, mode 0600: + `{schema, task_id, inputs_digest, inputs_path, expected_record, + human_fields: [{name, value}], human_source, human_started_at, + human_saved_at, human_duration_s, withheld_fields, save}`. +- `inputs.json` (0600): the instruction and the inputs the candidate gets. + The record the guard checks (`expected_record`) is added to the inputs as + plain fields, `record_` (for example `record_patient_id` and + `record_name`), unless the task's inputs already have that key, and the + instruction ends with "Work on the record identified by the inputs + record_patient_id, record_name." Without it, a candidate on an app that + lists several records can't know which one to open. `"record_in_inputs": + false` in `task.json` turns it off. `record_keys` lists the added keys; + a compiled program gets no `--param` for them. A proxy that pseudonymizes + text sees these values like any other input. +- `guard_task.json`, `openadapt.guard-task/v1`, with the intended fields by + name only, so the commit guard reads it unchanged. + +Session tokens and password-like fields (the network capture's name rules) +are withheld on both sides: never stored, never compared, counted in +`withheld_fields`. + +## The shadow hold (`run`) + +`ShadowHoldGuard` (`openadapt_flow/agent_guard/shadow_hold.py`) is a +`CommitGuard` that holds every request to the app's origin that is not a +plain `GET` (including `HEAD`, `OPTIONS` and a GraphQL query sent with +`POST`), and every GraphQL mutation sent with `GET`, unless the operator +listed it with `--not-save`. Autosaves, drafts and locks are held like the +Save button. Writes to other origins are refused. Before refusing, it +records a proposed write (`held/.json`, schema +`openadapt.proposed-write/v1`, mode 0600) with a screenshot and the screen +text: + +```json +{"schema": "openadapt.proposed-write/v1", "task_id": "...", + "request_index": 1, "method": "POST", "url_path": "/api/encounter", + "origin": "https://sandbox.example.test", "held_at": "...", + "identity": {"ok": true, "code": "verified"}, + "fields": [{"name": "note", "value": "...", "parse": "json"}], + "withheld_fields": 0, "refused": true} +``` + +The request is then refused with the commit guard's 409 and the +`X-OpenAdapt-Guard: blocked; code=shadow_hold` header, with the notice +"stopped before save (shadow mode)", and the task ends. `proposed_write.json` +is the held request whose method and path are the person's save (the first +held request when the reference names none). + +`identity` is the commit guard's right-record check on the screen text +(`--screen-selector` narrows it to the record header). With `--verify`, it +goes through `GuardedSave.begin`; only an `identity_*` refusal from it counts +as the wrong record. + +Field parsing, the same for every app: an entity lens's endpoint +(`--lens`, an `openadapt.entity-lens/v1` file, or `import --har` to induce +one with `tx.induce.induce_lens_from_har`) gives `parse: "lens"` and its +field codecs; otherwise URL-encoded or multipart form bodies (`"form"`) and +JSON object bodies (`"json"`, nested names dotted). Anything else, a +repeated form name, a file part, or a body the browser didn't expose is +`"uncompared"` and has no value. + +The runner, per episode: runs `--reset-cmd`, starts a headless Chromium with +DevTools on a pipe only (no TCP port, which any local user could use against +the signed-in session; the candidate's `OPENADAPT_GUARD_CDP_URL` is a +loopback relay that refuses every HTTP and WebSocket request without the +run's random token, `readiness/devtools_relay.py`), opens one tab at `--app-url` (service workers blocked in its +context), attaches the hold over CDP (every request of that tab is paused), +turns on the target gate, and starts the candidate. It stops the candidate, +then closes the browser, every target with it, while both holds are still +on, so a page timer can't send after a hold lets go. One task, one browser, one guard session. + +### Other tabs, popups, contexts and workers + +The candidate gets the browser-wide DevTools endpoint, so it can open a +second tab or popup (`window.open`, a `target=_blank` form, +`Target.createTarget`), a page in a new browser context, or a worker, and +send a write from there. The target gate (`readiness/targets.py`) covers +them: + +- **A browser-level request hold.** `Fetch.enable` on the browser target + pauses every request of every target other than the guarded tab (new tabs + and popups, pages in new browser contexts, service workers, shared + workers) and hands it to the same shadow hold: reads to the app go on, + other origins are refused, writes are held and refused. It is on before + the candidate starts. Dedicated workers of the guarded tab are paused by + the tab's own session. +- **Auto-attach.** `Target.setAutoAttach` with `waitForDebuggerOnStart` and + `flatten` on the browser target pauses each new target until the gate has + seen it. The gate keeps a count of new targets by type (no URLs) and does + not resume a type it hasn't shown to be held (anything but a page, an + iframe, a worker, a service worker or a shared worker). + +Auto-attach alone does not stop a write: a candidate that calls +`Target.createTarget` and then `Runtime.evaluate` on the new target over its +own DevTools session runs the page's `fetch` before the gate resumes it. In +the adversarial test's negative control (auto-attach on, browser-level hold +off), 5 of the 6 routes landed a write in the app's store (all but the +dedicated worker, which the tab's own session holds); with the hold, none +did. + +The case is `NOT_CHECKED` with reason `extra_target` (counted in +`failed_scope`, `scope_ok` false) when a write came from any target other +than the guarded tab (it was held, but the identity check reads the guarded +tab, so the write can't be checked), a target was left paused because its +type isn't covered, the gate lost its DevTools connection (Chromium then +lets paused requests go on), or no gate ran (a run folder from before the +gate existed). A second tab that only read is not a failure. `run.json` +records `target_gate: {extra_targets, ungated_targets, gate_lost, errors}` +and `extra_target_writes`; the task's status is `EXTRA_TARGET`. + +Service workers: Playwright's `service_workers="block"` on the guarded +context makes `navigator.serviceWorker.register` a no-op; it is a page +script, so the browser-level hold is what holds a service worker's requests +(tested in a context the candidate made). The candidate's own `Fetch` +interception runs before the gate's: a candidate that rewrites a request +(for example a `GET` into a `POST`) is seen rewritten by the hold, which +then refuses it. + +Defence in depth: the page the hold acts through counts every non-GET +request to the app's origin that still went on. One such request makes that +run `FAILED_SCOPE` and flags the whole scorecard; `run` exits 2. + +### The candidate + +`--agent-cmd` runs once per task (`SubprocessLauncher`) with: + +| Variable | Meaning | +| --- | --- | +| `OPENADAPT_GUARD_CDP_URL` | the DevTools endpoint of the guarded browser: the token-gated relay, `http://127.0.0.1:/` (use it as given) | +| `OPENADAPT_GUARD_PAGE_URL` | the URL the guarded tab was opened at | +| `OPENADAPT_TASK` | the instruction, then the inputs as JSON | +| `OPENADAPT_TASK_ID` | the task id | +| `OPENADAPT_USAGE_PATH` | where the command may write `usage.json` | +| `OPENADAPT_RUN_DIR` | its own folder for this task | + +`usage.json` (`openadapt.agent-usage/v1`): `{calls, input_tokens, +output_tokens, cost_usd, model}`. It is a cross-check only: the cost on the +scorecard is metered by the flight proxy (`model_cost_usd.source: +metered`; see [Model traffic](#model-traffic)). A cost the proxy +can't price is unknown and shown as "unknown", never as zero. + +`benchmark/readiness/claude_cu_agent.py` is a ready candidate: it attaches +to the guarded tab and runs the leaderboard's Claude computer-use loop +(reused, with a preamble that names no app), capped per task at 25 model +calls, $1.00 and 600 s by default (`OPENADAPT_CU_MAX_STEPS`, +`OPENADAPT_CU_MAX_USD`, `OPENADAPT_CU_MAX_S`; never above 50, $5.00 and +1800 s). Its unit tests use a stub upstream only; no real model has been run +through it yet. + +### Model traffic + +Every task's candidate process runs under the flight recorder's +`ScrubbedEgress` (`openadapt_flow.flight.egress`, the J7 API), through +`readiness/egress.py`: + +- `--egress scrubbed` (default): the candidate's model base URLs + (`ANTHROPIC_BASE_URL`, `OPENAI_BASE_URL`) point at the flight proxy on + loopback, which scrubs every text and image before forwarding and meters + the cost. The process runs under the OS egress block (macOS + `sandbox-exec`) and can reach only the guarded browser's DevTools port and + the proxy. `run` refuses to start (exit 2) when the scrubber or the block + is unavailable. +- `--egress blocked`: no model calls at all, for a scripted or local + candidate. The same OS block, with the DevTools port the only address it + can reach. The cost is 0, known because nothing could pass. +- `--egress unscrubbed`: the proxy and the block without the scrubber. An + explicit opt-in for synthetic data only; the scorecard's `egress.mode` + says so. + +`--spend-cap USD` caps each task's model spend at the proxy (429 past it, +and at once for a model with no price); `--upstream anthropic=URL` points +the proxy elsewhere. + +A task is refused (`EGRESS_REFUSED`; its case `NOT_CHECKED`, reason +`egress_refused`, counted in `failed_scope`) when its `usage.json` reports +more model calls than the proxy saw, or a direct connection outside the +proxy was trapped; `run` then exits 2. Each task's run folder gets +`egress.json` (`mode, enforced, model_calls, cost_usd, cost_source, +refused_requests`, the flight recorder's summary) and the proxy's scrubbed +record in `egress/`; `run.json` gets `egress` (that summary with the +session's mode, `refused` and `reason`). + +The shadow browser's network is limited too: it starts with +`--proxy-server` at a loopback port that refuses every connection and +`--proxy-bypass-list` naming only the app's origin, the origins of +`--not-save` rules that name one, and `--browser-allow ORIGIN` (a sign-in +host, a CDN), with `<-loopback>` so other loopback ports aren't exempt. A +page can reach nothing else, by `GET`, image, navigation or WebSocket. +`run.json` records `browser_network: {limited, allowed_origins}`. The +scorecard's `egress.enforced` is true only when the candidate's process ran +under the OS block and the browser was limited, for every task. + +The limit holds against the candidate too. The relay refuses a +`Target.createBrowserContext` that carries anything but `disposeOnDetach` +(so no `proxyServer: "direct://"`, `proxyBypassList` or +`originsWithUniversalNetworkAccess`, nor a key it doesn't know), and +refuses `Network.loadNetworkResource`, `Target.exposeDevToolsProtocol` and +`Browser.executeBrowserCommand`. The shadow hold refuses every request, +`GET` included, to an origin outside the same list, in every tab and +context. WebRTC may not send UDP around the proxy +(`--force-webrtc-ip-handling-policy=disable_non_proxied_udp`); a test with a +local STUN listener receives a packet without the flag and none with it. + +A compiled program (`--program`) gets its arguments (the relay URL with the +run's token, the task's inputs) through a 0600 file the child reads once +and deletes (`readiness/program_child.py`), never on its command line, +which every local user can read with `ps`. + +The proxy replaces each personal value with a run token (`[PERSON_1]`, the +same token in text and on screenshots) and turns the token back into the +real value in the candidate's tool inputs, so the candidate types the real +value. The map lives in `egress/pseudonyms.json` in the task's run folder +(0600, real values in plaintext) and never leaves it: nothing readiness +writes (cases, scorecard) reads `egress/`, and `readiness/export.py` copies +files out of a run folder only by allowlist (`run.json`, `egress.json`, +`usage.json`, the scorecard, and with `include_values` the case and the +proposed write, each checked against its allowed keys). An unknown file, a +directory or an unexpected key is left behind; the committed samples are +written through it. + +The OS block exists on macOS only, so outside macOS every `--egress` mode +refuses to run. The scrubber also hides personal data from the candidate +(the model can't read a name it must check); task success with scrubbing on +has not been measured. + +`--program BUNDLE` (`ProgramLauncher`) runs `openadapt-flow run` on the +guarded browser with `--approval-mode each_item` and a one-second approval +wait. No person answers, so the run stops before its save, as a declined +item does, and nothing is sent. The approval request holds the form's +values, which become the proposed write (`parse: "form"`, named by the form's +labels; a label that is not the person's field name shows as `extra`). The +program's cost is 0 only when its run report says it made no model calls. + +## Replay state + +Primary mode, `--mode sandbox`: a sandbox or test tenant seeded with +synthetic "before" state, restored by `--reset-cmd` before each task. + +Supported alternative, `--mode run-ahead`: the candidate works a live queue +item first and stops before save; the person then does the item, and +`import` pairs the two by `task_id`. Nothing the candidate does is saved. + +Always on, in both modes, **contamination detection**: if the screen that +showed the task's record, read before any write was held, already shows the +person's saved values for at least half of the compared fields, the case is +`NOT_COMPARABLE` and is never counted as matched. When no such screen was +read, the case is `NOT_COMPARABLE` too. + +What the check reads (`before_screen.txt`, mode 0600): the first screen text +on which the task's record showed, plus the first value seen in each form +control (``, `" + ) + page = CdpGuardPage(tab) + values = dict(page.form_values() or []) + text = page.screen_text() or "" + page.release() + browser.close() + assert "02134" not in text and "Cough, 3 days" not in text # innerText misses them + joined = "\n".join(values.values()) + for expected in ("02134", "Triage", "b Beta", "Cough, 3 days"): + assert expected in joined, (expected, values) + assert "hunter2" not in joined and "Consult" not in joined + + +def test_negative_control_auto_attach_alone_loses_the_race( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The same agent with the browser-level hold turned off (auto-attach + left on): writes land in the app's store. This is why the browser-level + hold, not auto-attach, is the gate.""" + + _chromium_or_skip() + from benchmark.agent_guard.app import serve + from openadapt_flow.readiness import targets + from openadapt_flow.readiness.cdp_wire import CdpWire, browser_ws_url + from openadapt_flow.readiness.runner import RunnerConfig, run_episodes + from tests.e2e.test_readiness_e2e import _episode + + def start_without_the_hold(self: Any) -> Any: + self.wire = CdpWire(browser_ws_url(self.endpoint), self._on_event) + existing = self.wire.send("Target.getTargets", {}).get("targetInfos") or [] + self._baseline = {str(t.get("targetId")) for t in existing} + self.wire.send( + "Target.setAutoAttach", + {"autoAttach": True, "waitForDebuggerOnStart": True, "flatten": True}, + ) + self._started = True + return self + + monkeypatch.setattr(targets.TargetGate, "start", start_without_the_hold) + app = serve(tmp_path / "app.sqlite") + landed: list[int] = [] + try: + app_url, episodes = _episodes(tmp_path, app, len(ROUTES)) + + def reset() -> None: + landed.append(app.writes) + app.writes = 0 + app.store.reset() + + plan = { + _episode(i)["task_id"]: {**_episode(i), "route": route} + for i, route in enumerate(ROUTES) + } + (tmp_path / "plan.json").write_text(json.dumps(plan)) + monkeypatch.setenv("READINESS_ADV_PLAN", str(tmp_path / "plan.json")) + cfg = RunnerConfig( + app_url=app_url, + screen_selector="#patient-banner", + timeout_s=60.0, + linger_s=0.5, + reset=reset, + ) + run_episodes(episodes, tmp_path / "runs", _launcher(), cfg) + landed.append(app.writes) + finally: + app.stop() + by_route = dict(zip(ROUTES, landed[1:])) + print("negative control, writes landed per route:", by_route) + assert by_route["create_target"] >= 1 and by_route["new_context"] >= 1, by_route + assert by_route["worker"] == 0 # held by the tab's own session either way + + +def test_a_real_claude_loop_under_scrubbed_egress_on_mockmed( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """``claude_cu_agent.py`` on MockMed under ``--egress scrubbed``, with the + real scrubber and a loopback stand-in for the Anthropic API. The proxy + meters the calls, the task is not refused, and the planted patient name + in the instruction never reaches the stand-in.""" + + _chromium_or_skip() + from openadapt_flow.flight.egress import egress_block_available + from openadapt_flow.flight.scrub import ScrubberUnavailable, require_scrubber + + if not egress_block_available()[0]: + pytest.skip("scrubbed egress needs the OS egress block (macOS)") + try: + require_scrubber() + except ScrubberUnavailable as exc: + pytest.skip(f"the scrubber can't run here: {exc}") + from benchmark.agent_guard.app import serve + from openadapt_flow.readiness.compare import compare_runs + from openadapt_flow.readiness.launcher import EgressOptions, SubprocessLauncher + from openadapt_flow.readiness.runner import RunnerConfig, run_episodes + from openadapt_flow.readiness.scorecard import build_scorecard + from tests.fixtures.flight.fake_provider import FakeProvider, anthropic_click + + fake = FakeProvider(model="claude-sonnet-5-5").start() + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key-not-real") + fake.anthropic_turns = [ + [anthropic_click(200, 200)], + [{"type": "text", "text": "RESULT: NOT DONE stub upstream"}], + ] + app = serve(tmp_path / "app.sqlite") + try: + app_url, episodes = _episodes(tmp_path, app, 1) + inputs_path = next(episodes.glob("*/inputs.json")) + inputs = json.loads(inputs_path.read_text()) + inputs["instruction"] = "For Jane Sample: " + inputs["instruction"] + inputs_path.write_text(json.dumps(inputs)) + agent = ( + Path(__file__).resolve().parents[2] + / "benchmark" + / "readiness" + / "claude_cu_agent.py" + ) + launcher = SubprocessLauncher( + [sys.executable, str(agent)], + label="claude-cu-stub", + egress=EgressOptions( + mode="scrubbed", spend_cap_usd=0.5, upstreams={"anthropic": fake.url} + ), + ) + cfg = RunnerConfig( + app_url=app_url, + screen_selector="#patient-banner", + timeout_s=120.0, + linger_s=0.5, + reset=app.store.reset, + ) + manifest = run_episodes(episodes, tmp_path / "runs", launcher, cfg) + assert app.writes == 0 + finally: + app.stop() + fake.stop() + task_id = manifest["tasks"][0]["task_id"] + run_dir = tmp_path / "runs" / task_id + run = json.loads((run_dir / "run.json").read_text()) + egress = json.loads((run_dir / "egress.json").read_text()) + log = (run_dir / "agent.log").read_text() + assert egress["mode"] == "scrubbed" and egress["enforced"] is True, (egress, log) + assert egress["model_calls"] == 2, (egress, log) + assert egress["cost_source"] == "metered" and egress["cost_usd"] > 0 + assert run["egress"]["refused"] is False, run["egress"] + assert run["model_cost_source"] == "metered" + assert run["usage"]["calls"] == 2 # the agent's own count agrees + assert len(fake.requests) == 2 + card = build_scorecard(compare_runs(episodes, tmp_path / "runs")) + assert card["egress"] == {"mode": "scrubbed", "enforced": True, "model_calls": 2} + assert card["model_cost_usd"]["source"] == "metered" + sent = fake.received_bytes() + assert b"Jane Sample" not in sent, [ + sent[max(0, i - 80) : i + 40] for i in [sent.find(b"Jane Sample")] + ] + assert b"Jane" not in sent # not even the first name diff --git a/packages/flow/tests/e2e/test_readiness_e2e.py b/packages/flow/tests/e2e/test_readiness_e2e.py new file mode 100644 index 0000000000..c73152238b --- /dev/null +++ b/packages/flow/tests/e2e/test_readiness_e2e.py @@ -0,0 +1,414 @@ +"""Shadow mode to a Readiness Scorecard, end to end in headless Chromium. + +A scripted "person" does 20 synthetic MockMed tasks with the network capture +on; ``readiness import`` turns the recordings into reference episodes. The +store is reset to its "before" state, and a scripted agent (this file, run as +a subprocess through ``SubprocessLauncher``) does the same tasks on the +guarded tab. It has 5 planted field errors and 2 planted wrong-record cases. +The shadow hold stops every save; the comparator must find exactly the +planted errors, and the app's own store must show no write. + +Synthetic MockMed in front of the ``effect_e2e`` record store; localhost only. + +Set ``OPENADAPT_WRITE_EVIDENCE=1`` to rewrite ``benchmark/readiness/results.json``. +""" + +from __future__ import annotations + +import json +import os +import sys +import time +from pathlib import Path +from typing import Any + +PATIENTS = { + "p1": "Jane Sample", + "p2": "Alex Testcase", + "p3": "Sam Specimen", +} +#: Planted agent errors: episode index -> what the agent does differently. +FIELD_ERRORS = { + 1: {"type": "flip"}, + 4: {"note": "Synthetic note O4 for review"}, # letter O for zero + 7: {"note": ""}, + 10: {"type": "flip"}, + 13: {"note": "Synthetic note 13 for reviews"}, +} +WRONG_RECORD = {16: "next", 19: "next"} +EVIDENCE = ( + Path(__file__).resolve().parents[2] / "benchmark" / "readiness" / "results.json" +) +#: One task's run folder and the scorecard, for the join tests of the +#: consumers (J1, J2); written with OPENADAPT_WRITE_EVIDENCE=1. +SAMPLE = EVIDENCE.parent / "sample" + + +def write_sample(runs: Path, task_id: str, card_dir: Path, name: str) -> None: + """Export one task's run files and the scorecard into ``sample//`` + through the allowlist (synthetic run, so values are included).""" + + import shutil + + from openadapt_flow.readiness.export import export_task + + target = SAMPLE / name + shutil.rmtree(target, ignore_errors=True) + export_task( + runs / task_id, + target, + include_values=True, + extra={"scorecard.json": card_dir / "scorecard.json"}, + ) + + +def _episode(i: int) -> dict[str, Any]: + pid = list(PATIENTS)[i % 3] + return { + "task_id": f"readiness-mockmed-{i:04d}", + "patient": pid, + "type": "Triage" if i % 2 == 0 else "Consult", + "note": f"Synthetic note {i:02d} for review", + } + + +def _agent_plan(i: int) -> dict[str, Any]: + plan = dict(_episode(i)) + errors = FIELD_ERRORS.get(i, {}) + if errors.get("type") == "flip": + plan["type"] = "Consult" if plan["type"] == "Triage" else "Triage" + if "note" in errors: + plan["note"] = errors["note"] + if i in WRONG_RECORD: + ids = list(PATIENTS) + plan["patient"] = ids[(ids.index(plan["patient"]) + 1) % 3] + return plan + + +def _do_task(page: Any, plan: dict[str, Any], think_s: float, log: Any = None) -> None: + def act(kind: str, fn: Any) -> None: + time.sleep(think_s) + if log is not None: + log(kind) + fn() + + act("click", lambda: page.click(f"#open-{plan['patient']}")) + act("click", lambda: page.click("#new-encounter")) + act("click", lambda: page.click(f"#type-{plan['type'].lower()}")) + act("click", lambda: page.click("#note")) + act("type", lambda: page.fill("#note", plan["note"])) + act("click", lambda: page.click("#save-encounter")) + + +# -- the scripted agent (run as a subprocess) --------------------------------------- + + +def agent_main() -> int: + from playwright.sync_api import sync_playwright + + plan = json.loads(Path(os.environ["READINESS_E2E_PLAN"]).read_text())[ + os.environ["OPENADAPT_TASK_ID"] + ] + task = os.environ["OPENADAPT_TASK"] + # The task names its record (``readiness import`` adds it), so the agent + # can tell which of the listed patients to open. + named = [pid for pid, name in PATIENTS.items() if name in task and pid in task] + assert named == [plan["true_patient"]], (named, task) + with sync_playwright() as pw: + browser = pw.chromium.connect_over_cdp(os.environ["OPENADAPT_GUARD_CDP_URL"]) + base = os.environ["OPENADAPT_GUARD_PAGE_URL"].split("?")[0].split("#")[0] + page = next( + p for c in browser.contexts for p in c.pages if p.url.startswith(base) + ) + page.wait_for_selector("#tasks-table") + _do_task(page, plan, think_s=0.25) + page.wait_for_timeout(800) + Path(os.environ["OPENADAPT_USAGE_PATH"]).write_text( + json.dumps( + { + "schema": "openadapt.agent-usage/v1", + # A scripted agent: no model calls (it runs with --egress + # blocked, so a claimed call would refuse the task). + "calls": 0, + "input_tokens": 0, + "output_tokens": 0, + "model": None, + "cost_usd": 0.0, + } + ) + ) + return 0 + + +if __name__ == "__main__": + sys.path.insert(0, str(Path(__file__).resolve().parents[2])) + raise SystemExit(agent_main()) + + +# -- the test ------------------------------------------------------------------------------- + +import pytest # noqa: E402 + +pytestmark = pytest.mark.timeout(1200) + + +def egress_options() -> Any: + """``--egress blocked`` where the OS egress block exists (macOS); else + None, so the hold is still tested where the block isn't (Linux CI). The + egress checks run only with the block.""" + + from openadapt_flow.flight.egress import egress_block_available + from openadapt_flow.readiness.launcher import EgressOptions + + return EgressOptions(mode="blocked") if egress_block_available()[0] else None + + +def _chromium_or_skip() -> None: + pytest.importorskip("playwright") + from playwright.sync_api import sync_playwright + + try: + with sync_playwright() as pw: + pw.chromium.launch(headless=True).close() + except Exception as exc: # noqa: BLE001 + pytest.skip(f"chromium unavailable: {exc}") + + +def _record_people(app_url: str, src: Path, n: int) -> None: + """The person does each task in a headless browser with network capture.""" + + from playwright.sync_api import sync_playwright + + from openadapt_flow.network_capture import NetworkCapture + + with sync_playwright() as pw: + browser = pw.chromium.launch(headless=True) + for i in range(n): + ep = _episode(i) + folder = src / f"task-{i:02d}" + rec = folder / "recording" + rec.mkdir(parents=True) + context = browser.new_context(viewport={"width": 1280, "height": 800}) + capture = NetworkCapture(context).start() + t0 = time.monotonic() + events: list[dict[str, Any]] = [] + page = context.new_page() + page.goto(app_url) + page.wait_for_selector("#tasks-table") + _do_task( + page, + ep, + think_s=0.15, + log=lambda kind: events.append( + {"t": round(time.monotonic() - t0, 3), "kind": kind} + ), + ) + page.wait_for_selector("#saved-banner", timeout=10000) + # The save's requestfinished callback runs on the event loop; + # pump it until the write is in the capture, then detach. + deadline = time.monotonic() + 10 + while time.monotonic() < deadline and ( + capture.pending_writes() + or not any( + str(line.get("method", "GET")).upper() != "GET" + for line in list(capture._lines) # noqa: SLF001 - test drain + ) + ): + page.wait_for_timeout(20) + capture.stop() + capture.write(rec, t0) + (rec / "events.jsonl").write_text( + "".join(json.dumps(e) + "\n" for e in events) + ) + context.close() + (folder / "task.json").write_text( + json.dumps( + { + "schema": "openadapt.readiness-task/v1", + "task_id": ep["task_id"], + "instruction": "Open the patient, add an encounter of the " + "given type with the note, and save.", + "inputs": {"type": ep["type"], "note": ep["note"]}, + "expected_record": { + "patient_id": ep["patient"], + "name": PATIENTS[ep["patient"]], + }, + "save": {"method": "POST", "path": "/api/encounter"}, + } + ) + ) + browser.close() + + +def test_shadow_run_to_scorecard( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + _chromium_or_skip() + from benchmark.agent_guard.app import serve + from openadapt_flow.readiness.compare import compare_runs, write_case_files + from openadapt_flow.readiness.launcher import SubprocessLauncher + from openadapt_flow.readiness.reference import import_episodes + from openadapt_flow.readiness.runner import RunnerConfig, run_episodes + from openadapt_flow.readiness.scorecard import write_scorecard + + n = 20 + app = serve(tmp_path / "app.sqlite") + try: + app_url = f"{app.base_url}/?fault=ok#tasks" + _record_people(app_url, tmp_path / "people", n) + assert app.writes == n # the person's saves landed + imported = import_episodes( + tmp_path / "people", tmp_path / "episodes", app_url=app_url + ) + assert imported.refused == [], imported.refused + assert len(imported.imported) == n + + # The sandbox's "before" state, restored before every agent task. + app.store.reset() + app.writes = 0 + before = app.store.read_encounters() + + def reset() -> None: + app.store.reset() + app.writes = 0 + + plan = tmp_path / "plan.json" + plan.write_text( + json.dumps( + { + _episode(i)["task_id"]: { + **_agent_plan(i), + "true_patient": _episode(i)["patient"], + } + for i in range(n) + } + ) + ) + for i in range(n): + given = json.loads( + ( + tmp_path / "episodes" / _episode(i)["task_id"] / "inputs.json" + ).read_text() + ) + assert given["inputs"]["record_name"] == PATIENTS[_episode(i)["patient"]] + assert given["inputs"]["record_patient_id"] == _episode(i)["patient"] + assert "record_name" in given["instruction"] + monkeypatch.setenv("READINESS_E2E_PLAN", str(plan)) + launcher = SubprocessLauncher( + [sys.executable, str(Path(__file__).resolve())], + label="scripted-agent", + egress=(egress := egress_options()), + ) + cfg = RunnerConfig( + app_url=app_url, + screen_selector="#patient-banner", + timeout_s=90.0, + linger_s=1.0, + reset=reset, + ) + started = time.monotonic() + manifest = run_episodes(tmp_path / "episodes", tmp_path / "runs", launcher, cfg) + run_seconds = round(time.monotonic() - started, 1) + + # No write reached the app: read the app's own state. + assert app.writes == 0 + assert app.store.read_encounters() == before + assert manifest["landed_writes"] == 0 + statuses = {t["task_id"]: t["status"] for t in manifest["tasks"]} + assert set(statuses.values()) == {"HELD"}, statuses + + cases = compare_runs(tmp_path / "episodes", tmp_path / "runs") + assert write_case_files(cases, tmp_path / "runs") == n + card = write_scorecard(cases, tmp_path / "card", hourly_cost=40.0) + finally: + app.stop() + + planted_fields = set() + for i, errors in FIELD_ERRORS.items(): + planted_fields |= {(_episode(i)["task_id"], name) for name in errors} + planted_wrong = {_episode(i)["task_id"] for i in WRONG_RECORD} + found_fields = { + (e["task_id"], e["field"]) + for e in card["field_errors"] + if e["kind"] in ("mismatched", "missing", "extra") + } + found_wrong = { + c["task_id"] for c in cases["cases"] if c["status"] == "WRONG_RECORD" + } + + def pr(found: set, planted: set) -> tuple[float, float]: + hit = len(found & planted) + return (hit / len(found) if found else 1.0, hit / len(planted)) + + field_pr, wrong_pr = ( + pr(found_fields, planted_fields), + pr(found_wrong, planted_wrong), + ) + assert field_pr == (1.0, 1.0), (found_fields, planted_fields) + assert wrong_pr == (1.0, 1.0), (found_wrong, planted_wrong) + assert card["matched"] == n - len(FIELD_ERRORS) - len(WRONG_RECORD) + assert card["risks"]["wrong_record"] == len(WRONG_RECORD) + assert card["landed_writes"] == 0 and card["scope_ok"] + # Uncompared never counts as matched. + for case in cases["cases"]: + if any(r["kind"] == "uncompared" for r in case["fields"]): + assert case["status"] != "MATCHED" + # The JSON carries no values. + text = (tmp_path / "card" / "scorecard.json").read_text() + for i in range(n): + assert _episode(i)["note"] not in text + assert _agent_plan(i)["note"] not in text or not _agent_plan(i)["note"] + for name in PATIENTS.values(): + assert name not in text + assert card["model_cost_usd"]["unknown_count"] == 0 + assert card["model_cost_usd"]["total"] == 0.0 + assert card["task_type"] == "unspecified" + assert card["savings"]["est_value_usd"] is not None + if egress is not None: + assert card["model_cost_usd"]["source"] == "metered" + assert card["egress"] == {"mode": "blocked", "enforced": True, "model_calls": 0} + for i in range(n): + run_dir = tmp_path / "runs" / _episode(i)["task_id"] + summary = json.loads((run_dir / "egress.json").read_text()) + assert summary["model_calls"] == 0 and summary["enforced"] is True + else: + assert card["egress"]["mode"] == "unscrubbed" # no proxy ran: said so + + if os.environ.get("OPENADAPT_WRITE_EVIDENCE") == "1": + write_sample( + tmp_path / "runs", _episode(0)["task_id"], tmp_path / "card", "matched" + ) + write_sample( + tmp_path / "runs", _episode(1)["task_id"], tmp_path / "card", "mismatched" + ) + wrong = _episode(min(WRONG_RECORD))["task_id"] + write_sample(tmp_path / "runs", wrong, tmp_path / "card", "wrong-record") + EVIDENCE.parent.mkdir(parents=True, exist_ok=True) + EVIDENCE.write_text( + json.dumps( + { + "schema": "openadapt.readiness-evidence/v1", + "fixture": "MockMed (synthetic) in front of the effect_e2e SQLite store", + "episodes": n, + "planted": { + "field_errors": sorted(map(list, planted_fields)), + "wrong_record": sorted(planted_wrong), + }, + "found": { + "field_errors": sorted(map(list, found_fields)), + "wrong_record": sorted(found_wrong), + }, + "field_error_precision_recall": list(field_pr), + "wrong_record_precision_recall": list(wrong_pr), + "app_writes_after_run": 0, + "app_store_unchanged": True, + "run_seconds": run_seconds, + "run_statuses": sorted(set(statuses.values())), + "scorecard": card, + }, + indent=2, + sort_keys=True, + ) + + "\n", + encoding="utf-8", + ) diff --git a/packages/flow/tests/fixtures/readiness/p3_egress.json b/packages/flow/tests/fixtures/readiness/p3_egress.json new file mode 100644 index 0000000000..22324535e8 --- /dev/null +++ b/packages/flow/tests/fixtures/readiness/p3_egress.json @@ -0,0 +1,8 @@ +{ + "cost_source": "metered", + "cost_usd": 0.008, + "enforced": true, + "mode": "scrubbed", + "model_calls": 1, + "refused_requests": 0 +} diff --git a/packages/flow/tests/test_browser_readiness.py b/packages/flow/tests/test_browser_readiness.py index 1fc92a5a2b..1f4f600471 100644 --- a/packages/flow/tests/test_browser_readiness.py +++ b/packages/flow/tests/test_browser_readiness.py @@ -321,6 +321,7 @@ def test_all_cdp_acquisitions_check_their_selected_page() -> None: "cli_worklist_pool.py": "_open", "agent_guard/session.py": "_connect", "copilot_runtime.py": "main", + "readiness/runner.py": "run_one", "exceptions/watch.py": "watch_browser", } observed = {} diff --git a/packages/flow/tests/test_readiness_claude_cu_agent.py b/packages/flow/tests/test_readiness_claude_cu_agent.py new file mode 100644 index 0000000000..073e6aa99e --- /dev/null +++ b/packages/flow/tests/test_readiness_claude_cu_agent.py @@ -0,0 +1,215 @@ +"""The Claude computer-use readiness candidate, against a stub upstream only. + +``FakeProvider`` (loopback) answers the Anthropic Messages API; a fake +screen stands in for the guarded tab. No model is called and no key is real. +""" + +from __future__ import annotations + +import importlib.util +from pathlib import Path +from typing import Any + +import pytest + +from tests.fixtures.flight.fake_provider import FakeProvider, anthropic_click + +pytest.importorskip("anthropic") +AGENT = ( + Path(__file__).resolve().parents[1] + / "benchmark" + / "readiness" + / "claude_cu_agent.py" +) + + +def _agent() -> Any: + spec = importlib.util.spec_from_file_location("readiness_claude_cu_agent", AGENT) + assert spec and spec.loader + module = importlib.util.module_from_spec(spec) + spec.loader.exec_module(module) + return module + + +class FakeScreen: + def __init__(self) -> None: + self.clicks: list[tuple[float, float]] = [] + + def screenshot(self) -> bytes: + return b"\x89PNG\r\n\x1a\n fake" + + def click(self, x: float, y: float, **_kw: Any) -> None: + self.clicks.append((x, y)) + + def move(self, x: float, y: float) -> None: ... + def drag(self, path: Any) -> None: ... + def type(self, text: str) -> None: ... + def key(self, keys: Any) -> None: ... + def scroll(self, *a: Any) -> None: ... + def wait(self, seconds: float = 1.0) -> None: ... + + +@pytest.fixture +def upstream(monkeypatch: pytest.MonkeyPatch): + fake = FakeProvider(model="claude-sonnet-5-5").start() + monkeypatch.setenv("ANTHROPIC_BASE_URL", fake.url) + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key-not-real") + yield fake + fake.stop() + + +def test_the_loop_acts_and_reports_usage(upstream: FakeProvider) -> None: + upstream.anthropic_turns = [ + [anthropic_click(640, 400)], + [{"type": "text", "text": "RESULT: DONE"}], + ] + screen = FakeScreen() + usage = _agent().run_task("Add the note and save.", screen) + assert screen.clicks == [(640, 400)] + assert usage["calls"] == 2 and usage["cost_usd"] > 0 + assert usage["schema"] == "openadapt.agent-usage/v1" + assert usage["final_line"] == "RESULT: DONE" + first = upstream.requests[0]["body"].decode() + assert "Medplum" not in first and "Add the note and save." in first + + +def test_usage_json_is_written_after_every_call( + upstream: FakeProvider, tmp_path: Path +) -> None: + import json + + upstream.anthropic_turns = [[anthropic_click(10, 10, f"t{i}")] for i in range(5)] + agent = _agent() + path = tmp_path / "usage.json" + seen: list[int] = [] + + class Watching(FakeScreen): + def click(self, x: float, y: float, **kw: Any) -> None: + seen.append(json.loads(path.read_text())["calls"]) + + agent.run_task( + "x", + Watching(), + limits=agent.caps({"OPENADAPT_CU_MAX_STEPS": "3"}), + usage_path=path, + ) + assert seen == [1, 2, 3] # on disk before each action, so a stop loses nothing + assert json.loads(path.read_text())["calls"] == 3 + + +def test_the_step_cap_holds(upstream: FakeProvider) -> None: + upstream.anthropic_turns = [[anthropic_click(10, 10, f"t{i}")] for i in range(40)] + agent = _agent() + limits = agent.caps({"OPENADAPT_CU_MAX_STEPS": "3"}) + usage = agent.run_task("x", FakeScreen(), limits=limits) + assert usage["calls"] == 3 and usage["stopped"].startswith("step cap") + assert len(upstream.requests) == 3 + + +def test_the_spend_cap_holds(upstream: FakeProvider) -> None: + upstream.anthropic_turns = [[anthropic_click(10, 10, f"t{i}")] for i in range(40)] + agent = _agent() + usage = agent.run_task( + "x", FakeScreen(), limits=agent.caps({"OPENADAPT_CU_MAX_USD": "0.0001"}) + ) + assert usage["calls"] == 1 and usage["stopped"].startswith("spend cap") + + +def test_caps_never_pass_the_maximums() -> None: + agent = _agent() + assert agent.caps({}) == {"steps": 25, "usd": 1.0, "seconds": 600} + assert agent.caps( + { + "OPENADAPT_CU_MAX_STEPS": "500", + "OPENADAPT_CU_MAX_USD": "90", + "OPENADAPT_CU_MAX_S": "1e9", + } + ) == {"steps": 50, "usd": 5.0, "seconds": 1800} + + +def test_an_unpriced_model_is_refused() -> None: + with pytest.raises(SystemExit, match="no price"): + _agent().run_task("x", FakeScreen(), model="claude-unknown") + + +def test_the_shared_leaderboard_ledger_is_not_touched( + upstream: FakeProvider, tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + from benchmark.fhir_medplum.leaderboard import common + + monkeypatch.setattr(common, "LEDGER", tmp_path / "spend.json") + upstream.anthropic_turns = [[{"type": "text", "text": "RESULT: NOT DONE stub"}]] + _agent().run_task("x", FakeScreen()) + assert not (tmp_path / "spend.json").exists() + + +def _png() -> bytes: + import io + + from PIL import Image + + buf = io.BytesIO() + Image.new("RGB", (64, 48), "white").save(buf, format="PNG") + return buf.getvalue() + + +def test_the_loop_works_with_run_tokens_through_the_flight_proxy( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + """The flight proxy (real scrubber, pseudonyms on) between the loop and a + stub upstream: the upstream sees ``[PERSON_1]`` for the name in the task, + answers with a ``type`` of ``[PERSON_1]``, and the loop types the real + name, because the proxy de-tokenizes tool inputs on the way back.""" + + from openadapt_flow.flight.egress import ScrubbedEgress + from openadapt_flow.flight.scrub import ScrubberUnavailable, require_scrubber + + try: + scrubber = require_scrubber() + except ScrubberUnavailable as exc: + pytest.skip(f"the scrubber can't run here: {exc}") + fake = FakeProvider(model="claude-sonnet-5-5").start() + typed: list[str] = [] + + class TypingScreen(FakeScreen): + def screenshot(self) -> bytes: + return _png() + + def type(self, text: str) -> None: + typed.append(text) + + fake.anthropic_turns = [ + [ + { + "type": "tool_use", + "id": "toolu_1", + "name": "computer", + "input": {"action": "type", "text": "[PERSON_1]"}, + } + ], + [{"type": "text", "text": "RESULT: DONE"}], + ] + monkeypatch.setenv("ANTHROPIC_API_KEY", "test-key-not-real") + run_dir = tmp_path / "task-0001" + try: + with ScrubbedEgress( + run_dir, + spend_cap_usd=1.0, + allow_unenforced=True, + use_block=False, + upstreams={"anthropic": fake.url}, + scrubber=scrubber, + ) as egress: + monkeypatch.setenv("ANTHROPIC_BASE_URL", egress.env["ANTHROPIC_BASE_URL"]) + usage = _agent().run_task( + "Open the chart of Jane Sample and type the patient's name in the note.", + TypingScreen(), + usage_path=run_dir / "usage.json", + ) + finally: + fake.stop() + sent = fake.received_bytes() + assert b"[PERSON_1]" in sent and b"Jane Sample" not in sent and b"Jane" not in sent + assert typed == ["Jane Sample"], typed + assert usage["calls"] == 2 and usage["final_line"] == "RESULT: DONE" + assert (run_dir / "egress" / "pseudonyms.json").is_file() # local only diff --git a/packages/flow/tests/test_readiness_compare.py b/packages/flow/tests/test_readiness_compare.py new file mode 100644 index 0000000000..9b65607563 --- /dev/null +++ b/packages/flow/tests/test_readiness_compare.py @@ -0,0 +1,305 @@ +"""The readiness comparator and scorecard, on planted synthetic cases.""" + +from __future__ import annotations + +import json +from typing import Any, Optional + +import pytest + +from openadapt_flow.readiness.compare import compare_case, contamination, values_equal +from openadapt_flow.readiness.runner import SCOPE_STATEMENT +from openadapt_flow.readiness.scorecard import build_scorecard, render_html + +RECORD = {"patient_id": "p1", "name": "Jane Sample"} + + +def _ref(**fields: Any) -> dict[str, Any]: + return { + "schema": "openadapt.reference-episode/v1", + "task_id": "case-000001", + "expected_record": RECORD, + "human_fields": [{"name": "patient_id", "value": "p1"}] + + [{"name": k, "value": v} for k, v in fields.items()], + "human_duration_s": 60.0, + } + + +#: A run whose target gate saw nothing outside the guarded tab. +CLEAN_GATE = { + "extra_targets": {}, + "ungated_targets": {}, + "gate_lost": False, + "errors": [], +} + + +def _run(**kw: Any) -> dict[str, Any]: + return { + "status": "HELD", + "agent_wall_s": 20.0, + "landed_writes": 0, + "target_gate": CLEAN_GATE, + **kw, + } + + +def _proposed(ok: bool = True, parse: str = "json", **fields: Any) -> dict[str, Any]: + return { + "identity": {"ok": ok, "code": "verified" if ok else "identity_mismatch"}, + "fields": [{"name": "patient_id", "value": "p1", "parse": parse}] + + [{"name": k, "value": v, "parse": parse} for k, v in fields.items()], + } + + +SCREEN = "Jane Sample — MRN P1 — DOB 1980-01-01" + + +def _case(ref: dict, proposed: Optional[dict], run: Optional[dict] = None, **kw: Any): + return compare_case( + ref, + run if run is not None else _run(), + proposed, + before_screen=kw.pop("before_screen", SCREEN), + **kw, + ) + + +@pytest.mark.parametrize( + ("human", "proposed", "same"), + [ + (None, "", True), + ("", None, True), + (" a b ", "a b", True), + ("1.50", "1.5", True), + ("10", "10.0", True), + ("10", "11", False), + ("2026-01-05", "2026-01-05T00:00:00Z", True), + ("2026-01-05", "2026-01-06", False), + ("Jane", "jane", False), + ("x", None, False), + ], +) +def test_values_equal(human: Any, proposed: Any, same: bool) -> None: + assert values_equal(human, proposed) is same + + +def test_codec_applies() -> None: + from openadapt_flow.tx.types import FieldCodec + + assert values_equal("Jane", "jane", FieldCodec(kind="casefold")) + + +def test_matched() -> None: + case = _case( + _ref(type="Triage", note="Cough, 3 days"), + _proposed(type="Triage", note=" Cough, 3 days"), + ) + assert case["status"] == "MATCHED" + assert {r["kind"] for r in case["fields"]} == {"matched"} + + +def test_planted_errors() -> None: + ref = _ref(type="Triage", note="n", dose="5") + mism = _case(ref, _proposed(type="Consult", note="n", dose="5")) + assert mism["status"] == "MISMATCHED" + assert [ + (r["name"], r["kind"], r["human"], r["proposed"]) + for r in mism["fields"] + if r["kind"] != "matched" + ] == [("type", "mismatched", "Triage", "Consult")] + missing = _case(ref, _proposed(type="Triage", dose="5")) + assert [ + (r["name"], r["kind"]) for r in missing["fields"] if r["kind"] != "matched" + ] == [("note", "missing")] + extra = _case(ref, _proposed(type="Triage", note="n", dose="5", billing="999")) + assert extra["status"] == "MISMATCHED" + assert extra["undeclared_fields"] == 1 + ignored = _case( + ref, + _proposed(type="Triage", note="n", dose="5", billing="999"), + ignore_fields=["billing"], + ) + assert ignored["status"] == "MATCHED" + + +def test_wrong_record() -> None: + ref = _ref(type="Triage") + by_screen = _case(ref, _proposed(ok=False, type="Triage")) + assert by_screen["status"] == "WRONG_RECORD" + body = _proposed(type="Triage") + body["fields"][0]["value"] = "p2" + by_body = _case(ref, body) + assert by_body["status"] == "WRONG_RECORD" + assert [r["kind"] for r in by_body["fields"]][0] == "wrong_record" + + +def test_uncompared_is_never_matched() -> None: + ref = _ref(type="Triage", note="n") + unreadable = { + "identity": {"ok": True, "code": "verified"}, + "fields": [{"name": "", "value": None, "parse": "uncompared"}], + } + case = _case(ref, unreadable) + assert case["status"] == "NOT_CHECKED" + assert {r["kind"] for r in case["fields"]} == {"uncompared"} + one = _proposed(type="Triage", note="n") + one["fields"][2] = {"name": "note", "value": None, "parse": "uncompared"} + assert _case(ref, one)["status"] == "NOT_CHECKED" + human_unreadable = _ref(type="Triage") + human_unreadable["human_fields"].append( + {"name": "file", "value": None, "parse": "uncompared"} + ) + assert ( + _case(human_unreadable, _proposed(type="Triage", file="x"))["status"] + == "NOT_CHECKED" + ) + + +def test_contamination() -> None: + ref = _ref(type="Triage", note="Cough for three days") + shown = SCREEN + "\nPrevious: Triage — Cough for three days" + case = _case( + ref, _proposed(type="Triage", note="Cough for three days"), before_screen=shown + ) + assert case["status"] == "NOT_COMPARABLE" + half = _case( + ref, + _proposed(type="Triage", note="Cough for three days"), + before_screen=SCREEN + " Triage", + ) + assert half["status"] == "NOT_COMPARABLE" # one of two is at least half + assert ( + contamination(SCREEN, [{"name": "note", "value": "Cough"}])["not_comparable"] + is False + ) + no_screen = _case( + ref, _proposed(type="Triage", note="Cough for three days"), before_screen=None + ) + assert no_screen["status"] == "NOT_COMPARABLE" + + +def test_not_run_and_failed_scope() -> None: + ref = _ref(type="Triage") + assert compare_case(ref, None, None)["status"] == "NOT_CHECKED" + assert _case(ref, None, run=_run(status="TIMEOUT"))["reason"] == "timeout" + assert ( + _case(ref, _proposed(type="Triage"), run=_run(landed_writes=1))["status"] + == "FAILED_SCOPE" + ) + + +def _cases() -> dict[str, Any]: + ref = _ref(type="Triage", note="secret-ish value 123") + cases = [ + _case( + ref, + _proposed(type="Triage", note="secret-ish value 123"), + run=_run(model_cost_usd=0.02), + ), + _case( + ref, + _proposed(type="Consult", note="secret-ish value 123"), + run=_run(model_cost_usd=0.04, agent_wall_s=30.0), + ), + _case( + ref, + _proposed(ok=False, type="Triage", note="x"), + run=_run(model_cost_usd=0.0), + ), + ] + for i, c in enumerate(cases): + c["task_id"] = f"case-00000{i}" + return {"agent_label": "scripted", "mode": "sandbox", "cases": cases} + + +def test_scorecard_json_has_no_values() -> None: + doc = _cases() + card = build_scorecard(doc, hourly_cost=60.0) + assert card["schema"] == "openadapt.readiness-scorecard/v1" + assert card["scope_statement"] == SCOPE_STATEMENT + assert (card["cases_total"], card["matched"], card["mismatched"]) == (3, 1, 2) + assert card["risks"]["wrong_record"] == 1 + assert {(e["task_id"], e["field"], e["kind"]) for e in card["field_errors"]} == { + ("case-000001", "type", "mismatched"), + ("case-000002", "", "wrong_record"), + } + assert card["model_cost_usd"] == { + "total": 0.06, + "per_task": 0.02, + "unknown_count": 0, + "source": "reported", + } + assert card["agent_time_s"]["median"] == 20.0 + assert card["savings"]["minutes_saved_per_task"] == round(40 / 60, 3) + assert card["savings"]["est_value_usd"] == round(40 / 60 * 1 / 60 * 60 - 0.06, 2) + text = json.dumps(card) + for value in ("secret-ish", "Triage", "Consult", "Jane", "p1"): + assert value not in text + page = render_html(card, doc) + assert "Consult" in page and "zero write risk" not in page.lower() + + +def test_savings_unknown_cost_is_not_estimated() -> None: + doc = _cases() + doc["cases"][0]["model_cost_usd"] = None + card = build_scorecard(doc, hourly_cost=60.0) + assert card["savings"]["est_value_usd"] is None + assert card["model_cost_usd"]["unknown_count"] == 1 + assert build_scorecard(_cases())["savings"]["est_value_usd"] is None + + +def test_usage_pricing_and_program_launcher(tmp_path) -> None: + from pathlib import Path + + from openadapt_flow.readiness.launcher import ( + LaunchJob, + ProgramLauncher, + approval_fields, + price_usage, + read_usage, + ) + + assert price_usage({"cost_usd": 0.5}) == 0.5 + assert ( + price_usage( + { + "model": "claude-sonnet-5-5", + "input_tokens": 1_000_000, + "output_tokens": 100_000, + } + ) + == 3.0 + ) + assert ( + price_usage({"model": "unknown-model", "input_tokens": 1, "output_tokens": 1}) + is None + ) + assert price_usage({"calls": 3}) is None + assert read_usage(Path(tmp_path) / "none.json") is None + + job = LaunchJob( + task_id="t-00000001", + instruction="do it", + inputs={"note": "n"}, + cdp_url="http://127.0.0.1:9", + page_url="http://127.0.0.1:1/", + run_dir=Path(tmp_path), + ) + argv = ProgramLauncher(Path(tmp_path) / "bundle").flow_args(job) + assert argv[:2] == ["run", str(Path(tmp_path) / "bundle")] + assert argv[argv.index("--approval-mode") + 1] == "each_item" + assert "note=n" in argv + folder = Path(tmp_path) / "program-run" / "item-approval" + folder.mkdir(parents=True) + (folder / "r.json").write_text( + json.dumps( + { + "schema_version": "openadapt.item-approval-request/v1", + "fields": [{"label": "note", "before": None, "after": "n"}], + } + ) + ) + assert approval_fields(Path(tmp_path) / "program-run") == [ + {"name": "note", "value": "n", "parse": "form"} + ] diff --git a/packages/flow/tests/test_readiness_devtools_relay.py b/packages/flow/tests/test_readiness_devtools_relay.py new file mode 100644 index 0000000000..5ac1660390 --- /dev/null +++ b/packages/flow/tests/test_readiness_devtools_relay.py @@ -0,0 +1,304 @@ +"""The shadow browser's DevTools: a pipe only, reached through a relay that +refuses anything without the run's token. Headless; localhost only.""" + +from __future__ import annotations + +import json +import socket +import urllib.error +import urllib.request + +import pytest + +from openadapt_flow.readiness.cdp_wire import CdpError, CdpWire, browser_ws_url +from openadapt_flow.readiness.devtools_relay import DevToolsRelay, headless_shell + + +@pytest.fixture(scope="module") +def relay(): + pytest.importorskip("playwright") + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + exe = headless_shell(pw.chromium.executable_path) + try: + started = DevToolsRelay(exe).start() + except OSError as exc: + pytest.skip(f"chromium unavailable: {exc}") + yield started + started.close() + + +def _status(url: str) -> int: + try: + with urllib.request.urlopen(url, timeout=5) as resp: # noqa: S310 - loopback + return resp.status + except urllib.error.HTTPError as exc: + return exc.code + + +def _upgrade(relay: DevToolsRelay, path: str) -> bytes: + import base64 + import os + + nonce = base64.b64encode(os.urandom(16)).decode() # a fresh WebSocket nonce + with socket.create_connection(("127.0.0.1", relay.port), timeout=5) as sock: + sock.sendall( + f"GET {path} HTTP/1.1\r\nHost: 127.0.0.1\r\nUpgrade: websocket\r\n" + f"Connection: Upgrade\r\nSec-WebSocket-Key: {nonce}\r\n" + "Sec-WebSocket-Version: 13\r\n\r\n".encode() + ) + return sock.recv(200) + + +def test_the_browser_has_no_tcp_debugging_port(relay: DevToolsRelay) -> None: + args = " ".join(relay.proc.args) + assert "--remote-debugging-pipe" in args and "--remote-debugging-port" not in args + + +def test_without_the_token_everything_is_refused(relay: DevToolsRelay) -> None: + base = f"http://127.0.0.1:{relay.port}" + assert _status(base + "/json/version") == 403 + assert _status(base + "/wrong/json/version") == 403 + assert _status(base + f"/{relay.token}x/json/version") == 403 # a longer token + assert _status(base + f"/{relay.token[:-1]}/json/version") == 403 + assert b" 403 " in _upgrade(relay, "/devtools/browser") + assert b" 403 " in _upgrade(relay, "/nottoken/devtools/browser") + assert _status(relay.http_url + "/json/version") == 200 + assert b" 101 " in _upgrade(relay, f"/{relay.token}/devtools/browser") + + +def test_with_the_token_a_client_drives_the_browser(relay: DevToolsRelay) -> None: + ws = browser_ws_url(relay.http_url) + assert relay.token in ws + events: list[str] = [] + wire = CdpWire(ws, lambda method, params, session: events.append(method)) + try: + target = wire.send("Target.createTarget", {"url": "about:blank"})["targetId"] + session = wire.send( + "Target.attachToTarget", {"targetId": target, "flatten": True} + )["sessionId"] + out = wire.send("Runtime.evaluate", {"expression": "6*7"}, session_id=session) + assert out["result"]["value"] == 42 + # Another client can't use this client's session. + other = CdpWire(ws, lambda *a: None) + try: + with pytest.raises(CdpError): + other.send("Runtime.evaluate", {"expression": "1"}, session_id=session) + finally: + other.close() + finally: + wire.close() + + +def test_playwright_connects_with_the_token(relay: DevToolsRelay) -> None: + from playwright.sync_api import sync_playwright + + with sync_playwright() as pw: + browser = pw.chromium.connect_over_cdp(relay.http_url) + context = browser.new_context() + page = context.new_page() + page.set_content("

ok

") + assert page.text_content("#x") == "ok" + context.close() + browser.close() + with sync_playwright() as pw: + with pytest.raises(Exception): # noqa: B017 - any refusal + pw.chromium.connect_over_cdp(f"http://127.0.0.1:{relay.port}", timeout=5000) + assert ( + json.loads( + urllib.request.urlopen( # noqa: S310 + relay.http_url + "/json/version", timeout=5 + ).read() + )["webSocketDebuggerUrl"] + == relay.ws_url + ) + + +def _server(body: bytes): + import threading + from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + + hits: list[str] = [] + + class Handler(BaseHTTPRequestHandler): + def log_message(self, *a) -> None: + pass + + def do_GET(self) -> None: # noqa: N802 + hits.append(self.path) + self.send_response(200) + self.send_header("Content-Type", "text/html") + self.send_header("Access-Control-Allow-Origin", "*") + self.end_headers() + self.wfile.write(body) + + httpd = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + threading.Thread(target=httpd.serve_forever, daemon=True).start() + return httpd, hits + + +def test_the_browser_reaches_the_app_and_nothing_else() -> None: + pytest.importorskip("playwright") + from playwright.sync_api import sync_playwright + + app, app_hits = _server(b"

app

") + other, other_hits = _server(b"other") + app_origin = f"http://127.0.0.1:{app.server_address[1]}" + other_origin = f"http://127.0.0.1:{other.server_address[1]}" + with sync_playwright() as pw: + exe = headless_shell(pw.chromium.executable_path) + relay = DevToolsRelay(exe, allowed_origins=(app_origin,)).start() + try: + assert relay.network_limited + browser = pw.chromium.connect_over_cdp(relay.http_url) + page = browser.new_context().new_page() + page.goto(app_origin + "/") + assert page.text_content("#app") == "app" + assert ( + page.evaluate( + f"fetch({json.dumps(app_origin + '/again')}).then(r => r.status, e => 'failed')" + ) + == 200 + ) + got = page.evaluate( + f"fetch({json.dumps(other_origin + '/leak?d=1')}, {{mode: 'no-cors'}})" + ".then(() => 'answered', () => 'failed')" + ) + public = page.evaluate( + "fetch('http://192.0.2.1/leak', {mode: 'no-cors'})" + ".then(() => 'answered', () => 'failed')" + ) + ws = page.evaluate( + f"""new Promise(done => {{ + const s = new WebSocket({json.dumps("ws://127.0.0.1:" + str(other.server_address[1]) + "/ws")}); + s.onopen = () => done('open'); s.onerror = () => done('failed'); + setTimeout(() => done('timeout'), 20000); + }})""" + ) + image = page.evaluate( + f"""new Promise(done => {{ + const i = new Image(); i.onload = () => done('loaded'); + i.onerror = () => done('failed'); + i.src = {json.dumps(other_origin + "/pixel?d=1")}; + }})""" + ) + browser.close() + finally: + relay.close() + app.shutdown() + other.shutdown() + assert other_hits == [], other_hits + assert (got, public, ws, image) == ("failed", "failed", "failed", "failed") + assert "/again" in app_hits + + +def test_a_new_context_cannot_take_its_own_proxy() -> None: + """Reviewer probe: ``Target.createBrowserContext`` with ``proxyServer: + "direct://"`` through the relay escaped the browser's proxy limit.""" + + pytest.importorskip("playwright") + from playwright.sync_api import sync_playwright + + app, _ = _server(b"

app

") + other, other_hits = _server(b"other") + app_origin = f"http://127.0.0.1:{app.server_address[1]}" + other_origin = f"http://127.0.0.1:{other.server_address[1]}" + with sync_playwright() as pw: + relay = DevToolsRelay( + headless_shell(pw.chromium.executable_path), allowed_origins=(app_origin,) + ).start() + try: + wire = CdpWire(browser_ws_url(relay.http_url), lambda *a: None) + for params in ( + {"proxyServer": "direct://"}, + {"proxyBypassList": "*"}, + {"originsWithUniversalNetworkAccess": [other_origin]}, + {"someFutureKey": True}, + ): + with pytest.raises(CdpError, match="refused"): + wire.send("Target.createBrowserContext", params) + for method in ( + "Network.loadNetworkResource", + "Target.exposeDevToolsProtocol", + "Browser.executeBrowserCommand", + ): + with pytest.raises(CdpError, match="refused"): + wire.send(method, {}) + ctx = wire.send("Target.createBrowserContext", {"disposeOnDetach": True}) + wire.send( + "Target.createTarget", + { + "url": other_origin + "/exfil?d=1", + "browserContextId": ctx["browserContextId"], + }, + ) + import time + + time.sleep(2) + wire.close() + finally: + relay.close() + app.shutdown() + other.shutdown() + assert other_hits == [] + + +def _lan_ip() -> str: + with socket.socket(socket.AF_INET, socket.SOCK_DGRAM) as s: + try: + s.connect(("192.0.2.1", 9)) # no packet is sent for a UDP connect + return s.getsockname()[0] + except OSError: + return "127.0.0.1" + + +def _stun_probe(block_webrtc: bool) -> bool: + """Whether a page's WebRTC ICE gathering sends a UDP packet to a local + STUN listener.""" + + from playwright.sync_api import sync_playwright + + app, _ = _server(b"

app

") + app_origin = f"http://127.0.0.1:{app.server_address[1]}" + udp = socket.socket(socket.AF_INET, socket.SOCK_DGRAM) + udp.bind(("0.0.0.0", 0)) + udp.settimeout(6) + try: + with sync_playwright() as pw: + relay = DevToolsRelay( + headless_shell(pw.chromium.executable_path), + allowed_origins=(app_origin,), + block_webrtc=block_webrtc, + ).start() + try: + browser = pw.chromium.connect_over_cdp(relay.http_url) + page = browser.new_context().new_page() + page.goto(app_origin + "/") + page.evaluate( + """(u) => { const pc = new RTCPeerConnection({iceServers: [{urls: u}]}); + pc.createDataChannel('x'); + pc.createOffer().then(o => pc.setLocalDescription(o)); window._pc = pc; }""", + f"stun:{_lan_ip()}:{udp.getsockname()[1]}", + ) + try: + udp.recvfrom(2048) + return True + except socket.timeout: + return False + finally: + browser.close() + finally: + relay.close() + finally: + udp.close() + app.shutdown() + + +def test_webrtc_sends_no_udp_past_the_proxy() -> None: + """Reviewer probe: WebRTC's STUN packets went around the HTTP proxy.""" + + pytest.importorskip("playwright") + if not _stun_probe(block_webrtc=False): + pytest.skip("no STUN packet arrives here even without the block") + assert _stun_probe(block_webrtc=True) is False diff --git a/packages/flow/tests/test_readiness_egress.py b/packages/flow/tests/test_readiness_egress.py new file mode 100644 index 0000000000..6164b5eb97 --- /dev/null +++ b/packages/flow/tests/test_readiness_egress.py @@ -0,0 +1,352 @@ +"""Readiness runs every candidate under the flight recorder's egress (J7). + +The sandbox parts run for real on macOS (``sandbox-exec``). Model calls go to +a loopback stand-in for the provider API (``FakeProvider``); nothing leaves +this machine. The join test reads ``fixtures/readiness/p3_egress.json``, an +``egress.json`` written by the flight recorder's own ``ScrubbedEgress`` (one +scrubbed call to the stand-in, usage.json agreeing). +""" + +from __future__ import annotations + +import json +import socket +import sys +import threading +import time +from pathlib import Path +from typing import Any + +import pytest + +from openadapt_flow.readiness.compare import compare_case +from openadapt_flow.readiness.egress import ( + EgressRefused, + EgressSession, + metered_cost, + preflight, +) +from openadapt_flow.readiness.launcher import ( + EgressOptions, + LaunchJob, + SubprocessLauncher, +) +from openadapt_flow.readiness.scorecard import build_scorecard +from tests.fixtures.flight.fake_provider import FakeProvider + +FIXTURE = Path(__file__).parent / "fixtures" / "readiness" / "p3_egress.json" +J7_KEYS = { + "mode", + "enforced", + "model_calls", + "cost_usd", + "cost_source", + "refused_requests", +} +CLEAN_GATE = { + "extra_targets": {}, + "ungated_targets": {}, + "gate_lost": False, + "errors": [], +} + + +def _block_or_skip() -> None: + from openadapt_flow.flight.egress import egress_block_available + + ok, why = egress_block_available() + if not ok: + pytest.skip(why) + + +class FakeScrubber: + def scrub_text(self, text: str, is_separated: bool = False) -> str: + return text.replace("Zyxwv Qtest", "") + + def scrub_image(self, image: Any, fill_color: Any = None) -> Any: + return image + + +@pytest.fixture +def provider(): + fake = FakeProvider().start() + yield fake + fake.stop() + + +@pytest.fixture +def cdp_port(): + """A loopback listener standing in for the browser's DevTools port.""" + + server = socket.socket() + server.bind(("127.0.0.1", 0)) + server.listen(8) + + def accept() -> None: + while True: + try: + conn, _ = server.accept() + except OSError: + return + conn.close() + + threading.Thread(target=accept, daemon=True).start() + yield server.getsockname()[1] + server.close() + + +#: The candidate: one model call through ANTHROPIC_BASE_URL, then a connect +#: to a public (TEST-NET) address, the DevTools port and another loopback +#: port; then it writes the call count it claims to usage.json. +AGENT = """ +import json, os, socket, sys, urllib.request +calls, claim, cdp, other = sys.argv[1], int(sys.argv[2]), int(sys.argv[3]), int(sys.argv[4]) +out = [] +if calls == "1": + req = urllib.request.Request( + os.environ["ANTHROPIC_BASE_URL"] + "/v1/messages", + data=json.dumps({"model": "claude-opus-5-5", "max_tokens": 8, + "messages": [{"role": "user", "content": "hi Zyxwv Qtest"}]}).encode(), + headers={"content-type": "application/json"}, method="POST") + try: + out.append(str(urllib.request.build_opener(urllib.request.ProxyHandler({})) + .open(req, timeout=30).status)) + except Exception as exc: + out.append("call failed " + type(exc).__name__) +for host, port in (("192.0.2.1", 443), ("127.0.0.1", cdp), ("127.0.0.1", other)): + s = socket.socket(); s.settimeout(3) + try: + s.connect((host, port)); out.append("connected") + except PermissionError: + out.append("EPERM") + except OSError as exc: + out.append("error " + type(exc).__name__) +print(" ".join(out)) +with open(os.environ["OPENADAPT_USAGE_PATH"], "w") as fh: + json.dump({"schema": "openadapt.agent-usage/v1", "calls": claim}, fh) +""" + + +def _run_agent( + tmp_path: Path, + options: EgressOptions, + cdp_port: int, + calls: str, + claim: int, + other: int, +) -> tuple[str, Any]: + run_dir = tmp_path / "task-0001" + run_dir.mkdir(parents=True, exist_ok=True) + job = LaunchJob( + task_id="task-0001", + instruction="x", + inputs={}, + cdp_url=f"http://127.0.0.1:{cdp_port}", + page_url="http://127.0.0.1/", + run_dir=run_dir, + ) + launcher = SubprocessLauncher( + [sys.executable, "-c", AGENT, calls, str(claim), str(cdp_port), str(other)], + egress=options, + ) + agent = launcher.start(job) + deadline = time.monotonic() + 60 + while agent.poll() is None and time.monotonic() < deadline: + time.sleep(0.05) + agent.stop() + result = agent.result() + return (run_dir / "agent.log").read_text().strip().splitlines()[-1], result + + +def test_scrubbed_calls_are_metered_and_the_agent_reaches_only_its_ports( + tmp_path: Path, provider: FakeProvider, cdp_port: int +) -> None: + _block_or_skip() + with socket.socket() as spare: + spare.bind(("127.0.0.1", 0)) + other = spare.getsockname()[1] + options = EgressOptions( + mode="scrubbed", + spend_cap_usd=1.0, + upstreams={"anthropic": provider.url}, + scrubber=FakeScrubber(), + ) + out, result = _run_agent(tmp_path, options, cdp_port, "1", 1, other) + assert out == "200 EPERM connected EPERM" + assert b"Zyxwv Qtest" not in provider.received_bytes() + egress = result.egress + assert egress["mode"] == "scrubbed" and egress["enforced"] is True + assert egress["model_calls"] == 1 and egress["refused"] is False + assert ( + metered_cost(egress) == (egress["cost_usd"], "metered") + and egress["cost_usd"] > 0 + ) + on_disk = json.loads((tmp_path / "task-0001" / "egress.json").read_text()) + assert set(on_disk) == J7_KEYS + + +def test_an_agent_that_claims_calls_the_proxy_didnt_see_is_refused( + tmp_path: Path, provider: FakeProvider, cdp_port: int +) -> None: + _block_or_skip() + options = EgressOptions( + mode="scrubbed", upstreams={"anthropic": provider.url}, scrubber=FakeScrubber() + ) + _, result = _run_agent(tmp_path, options, cdp_port, "1", 3, cdp_port) + assert result.egress["refused"] is True + assert "reports 3 model calls" in result.egress["reason"] + + +def test_blocked_mode_allows_no_model_call(tmp_path: Path, cdp_port: int) -> None: + _block_or_skip() + out, result = _run_agent( + tmp_path, + EgressOptions(mode="blocked"), + cdp_port, + "1", + 0, + cdp_port + 1 if cdp_port < 65535 else cdp_port - 1, + ) + words = out.split() + assert words[0] == "call" and words[1] == "failed" # no model reachable + assert words[-3:] == ["EPERM", "connected", "EPERM"] + egress = result.egress + assert egress == { + "mode": "blocked", + "enforced": True, + "model_calls": 0, + "cost_usd": 0.0, + "cost_source": "metered", + "refused_requests": 0, + "refused": False, + "reason": None, + } + assert ( + set(json.loads((tmp_path / "task-0001" / "egress.json").read_text())) == J7_KEYS + ) + + +def test_blocked_mode_refuses_a_claimed_call(tmp_path: Path, cdp_port: int) -> None: + _block_or_skip() + _, result = _run_agent( + tmp_path, EgressOptions(mode="blocked"), cdp_port, "0", 2, cdp_port + ) + assert result.egress["refused"] is True + assert "reports 2 model calls" in result.egress["reason"] + + +def test_unscrubbed_is_recorded( + tmp_path: Path, provider: FakeProvider, cdp_port: int +) -> None: + _block_or_skip() + options = EgressOptions(mode="unscrubbed", upstreams={"anthropic": provider.url}) + _, result = _run_agent(tmp_path, options, cdp_port, "1", 1, cdp_port) + assert result.egress["mode"] == "unscrubbed" and result.egress["model_calls"] == 1 + assert b"Zyxwv Qtest" in provider.received_bytes() # the opt-in is real + + +def test_no_block_refuses_before_anything_runs( + monkeypatch: pytest.MonkeyPatch, tmp_path: Path +) -> None: + from openadapt_flow.flight import egress as flight + + monkeypatch.setattr( + flight, "egress_block_available", lambda: (False, "test: no block") + ) + for mode in ("scrubbed", "blocked", "unscrubbed"): + with pytest.raises(EgressRefused, match="no block"): + preflight(mode, scrubber=FakeScrubber()) + with pytest.raises(EgressRefused): + EgressSession( + mode, tmp_path, cdp_port=9222, scrubber=FakeScrubber() + ).start() + with pytest.raises(EgressRefused): + preflight("open") + + +def test_a_missing_scrubber_refuses_the_run(monkeypatch: pytest.MonkeyPatch) -> None: + from openadapt_flow.flight import egress as flight + from openadapt_flow.flight import scrub + + monkeypatch.setattr(flight, "egress_block_available", lambda: (True, "")) + + def missing(**_kw: Any) -> Any: + raise scrub.ScrubberUnavailable("the tesseract binary is not on PATH") + + monkeypatch.setattr(scrub, "require_scrubber", missing) + with pytest.raises(EgressRefused, match="tesseract"): + preflight("scrubbed") + + +# -- the J7 join, on the flight recorder's own egress.json ------------------------------ + + +def test_the_flight_recorders_egress_json_is_read_as_metered_cost() -> None: + summary = json.loads(FIXTURE.read_text()) + assert set(summary) == J7_KEYS + cost, source = metered_cost(summary) + assert source == "metered" and cost == summary["cost_usd"] + assert metered_cost({**summary, "cost_source": "unknown", "cost_usd": None}) == ( + None, + None, + ) + + +def _ref() -> dict[str, Any]: + return { + "task_id": "case-0001", + "expected_record": {"patient_id": "p1"}, + "human_fields": [{"name": "type", "value": "Triage"}], + "human_duration_s": 60.0, + } + + +def _proposed() -> dict[str, Any]: + return { + "request_index": 0, + "identity": {"ok": True, "code": "verified"}, + "fields": [{"name": "type", "value": "Triage", "parse": "json"}], + } + + +def test_scorecard_cost_and_egress_come_from_the_proxy() -> None: + summary = json.loads(FIXTURE.read_text()) + cost, source = metered_cost(summary) + run = { + "status": "HELD", + "agent_wall_s": 20.0, + "landed_writes": 0, + "target_gate": CLEAN_GATE, + "model_cost_usd": cost, + "model_cost_source": source, + "egress": {**summary, "refused": False, "reason": None}, + "usage": {"calls": 1, "cost_usd": 99.0}, + } # the agent's own claim is ignored + case = compare_case( + _ref(), run, _proposed(), before_screen="p1", held=[{"request_index": 0}] + ) + assert case["status"] == "MATCHED" + card = build_scorecard( + {"cases": [case], "egress": {"mode": "scrubbed", "enforced": True}} + ) + assert card["model_cost_usd"]["total"] == summary["cost_usd"] + assert card["model_cost_usd"]["source"] == "metered" + assert card["egress"] == {"mode": "scrubbed", "enforced": True, "model_calls": 1} + + +def test_a_refused_egress_fails_the_case_closed() -> None: + run = { + "status": "EGRESS_REFUSED", + "agent_wall_s": 20.0, + "landed_writes": 0, + "target_gate": CLEAN_GATE, + "egress": {"mode": "scrubbed", "refused": True, "reason": "reports 3 calls"}, + } + case = compare_case( + _ref(), run, _proposed(), before_screen="p1", held=[{"request_index": 0}] + ) + assert (case["status"], case["reason"]) == ("NOT_CHECKED", "egress_refused") + card = build_scorecard( + {"cases": [case], "egress": {"mode": "scrubbed", "enforced": True}} + ) + assert card["failed_scope"] == 1 and card["scope_ok"] is False diff --git a/packages/flow/tests/test_readiness_hardening.py b/packages/flow/tests/test_readiness_hardening.py new file mode 100644 index 0000000000..2c53410442 --- /dev/null +++ b/packages/flow/tests/test_readiness_hardening.py @@ -0,0 +1,779 @@ +"""Readiness fixes: identifiers, extra held writes, other targets, form +values, the joins (case.json, scorecard keys) and the page's money format. + +No browser: fake pages and planted synthetic cases. Each test here fails on +the code before the fix it names. +""" + +from __future__ import annotations + +import json +import stat +from pathlib import Path +from typing import Any, Optional + +import pytest + +from openadapt_flow.agent_guard.requests import HeldRequest +from openadapt_flow.agent_guard.shadow_hold import ShadowHoldGuard +from openadapt_flow.guard import GuardTask +from openadapt_flow.readiness.compare import ( + compare_case, + contamination, + identifier_like, + values_equal, + write_case_files, +) +from openadapt_flow.readiness.scorecard import build_scorecard, render_html +from openadapt_flow.readiness.targets import EXTRA_PREFIX, RoutedPage + +APP = "http://127.0.0.1:9999" +RECORD = {"patient_id": "p1", "name": "Jane Sample"} +CLEAN_GATE = { + "extra_targets": {}, + "ungated_targets": {}, + "gate_lost": False, + "errors": [], +} +SCREEN = "Jane Sample — MRN P1" + + +# -- 3. identifiers never compare as numbers --------------------------------------- + + +@pytest.mark.parametrize( + ("human", "proposed", "name", "same"), + [ + ("02134", "2134", "zip", False), + ("02134", "2134", None, False), # a leading zero is an identifier + ("007", "7", "note", False), + ("1e3", "1000", "amount", False), + ("+15551234", "15551234", "contact", False), + ("1234567890", "1234567890.0", "amount", False), # a long digit run + ("5", "5.0", "patient_id", False), + ("12", "12.0", "accountNumber", False), + ("12", "12.0", "zipCode", False), + ("12.50", "12.5", "amount", True), + ("10", "10.0", "quantity", True), + ("-3.10", "-3.1", "balance", True), + ("0.50", "0.5", "copay", True), + (" 02134 ", "02134", "zip", True), # trimmed exact text still matches + ], +) +def test_identifier_like_values_compare_as_text( + human: str, proposed: str, name: Optional[str], same: bool +) -> None: + assert values_equal(human, proposed, name=name) is same + + +def test_identifier_names() -> None: + for name in ( + "patient_id", + "patientId", + "MRN", + "zip", + "postal_code", + "phone", + "account_no", + "member.number", + "npi", + "ref", + ): + assert identifier_like(name), name + for name in ("note", "amount", "type", "quantity", "notes", "identity_note"): + assert not identifier_like(name), name + + +def _ref(**fields: Any) -> dict[str, Any]: + return { + "task_id": "case-0001", + "expected_record": dict(RECORD), + "human_fields": [{"name": k, "value": v} for k, v in fields.items()], + "human_duration_s": 60.0, + } + + +def _run(**kw: Any) -> dict[str, Any]: + return { + "status": "HELD", + "agent_wall_s": 20.0, + "landed_writes": 0, + "target_gate": CLEAN_GATE, + **kw, + } + + +def _proposed(index: Optional[int] = 0, **fields: Any) -> dict[str, Any]: + return { + "request_index": index, + "method": "POST", + "url_path": "/api/encounter", + "identity": {"ok": True, "code": "verified"}, + "fields": [{"name": k, "value": v, "parse": "json"} for k, v in fields.items()], + } + + +def test_a_leading_zero_record_id_is_another_record() -> None: + ref = _ref(type="Triage") + ref["expected_record"] = {"patient_id": "0012", "name": "Jane Sample"} + case = compare_case( + ref, _run(), _proposed(patient_id="12", type="Triage"), before_screen=SCREEN + ) + assert case["status"] == "WRONG_RECORD" + + +def test_a_record_date_still_matches_at_midnight() -> None: + ref = _ref(type="Triage") + ref["expected_record"] = {"patient_id": "p1", "dob": "1980-01-01"} + case = compare_case( + ref, + _run(), + _proposed(patient_id="p1", dob="1980-01-01T00:00:00Z", type="Triage"), + before_screen=SCREEN, + ) + assert case["status"] == "MATCHED", case + ref["expected_record"] = {"patient_id": "p1", "visits": "10"} + case = compare_case( + ref, + _run(), + _proposed(patient_id="p1", visits="10.0", type="Triage"), + before_screen=SCREEN, + ) + assert case["status"] == "WRONG_RECORD" # a record field is never a number + + +def test_a_leading_zero_field_is_a_field_error() -> None: + case = compare_case( + _ref(zip="02134"), _run(), _proposed(zip="2134"), before_screen=SCREEN + ) + assert case["status"] == "MISMATCHED" + assert [r["kind"] for r in case["fields"]] == ["mismatched"] + + +# -- 4. any other held write fails the match ----------------------------------------- + + +def _held(index: int, method: str = "POST", path: str = "/api/encounter") -> dict: + return {"request_index": index, "method": method, "url_path": path} + + +@pytest.mark.parametrize( + ("target_index", "held"), + [ + (0, [_held(0), _held(1, "PATCH")]), # a second PATCH + (0, [_held(0), _held(1, "DELETE", "/api/encounter/7")]), # a delete + (0, [_held(0), _held(1, "POST", "/api/patient/p2")]), # another record + (0, [_held(0), _held(1)]), # the save twice + (1, [_held(0, "POST", "/api/lock"), _held(1)]), # a write before it + ], +) +def test_extra_held_writes_are_never_matched(target_index: int, held: list) -> None: + case = compare_case( + _ref(type="Triage"), + _run(), + _proposed(target_index, type="Triage"), + before_screen=SCREEN, + held=held, + ) + assert case["status"] == "MISMATCHED" + assert case["reason"] == "extra_held_writes" + assert case["extra_held_writes"] == 1 + + +def test_one_held_write_still_matches() -> None: + case = compare_case( + _ref(type="Triage"), + _run(), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + assert case["status"] == "MATCHED" + assert case["extra_held_writes"] == 0 + + +# -- 1. other targets fail the case closed -------------------------------------------- + + +@pytest.mark.parametrize( + "run", + [ + _run(target_gate=None), # no gate ran + _run(target_gate={**CLEAN_GATE, "gate_lost": True}), + _run(target_gate={**CLEAN_GATE, "ungated_targets": {"other": 1}}), + _run(extra_target_writes=1), + ], +) +def test_a_run_that_cant_vouch_for_other_targets_is_not_checked(run: dict) -> None: + case = compare_case( + _ref(type="Triage"), + run, + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + assert (case["status"], case["reason"]) == ("NOT_CHECKED", "extra_target") + card = build_scorecard({"cases": [case]}) + assert card["failed_scope"] == 1 + assert card["scope_ok"] is False + assert card["not_checked"] == 1 + + +def test_a_gated_popup_that_only_read_is_fine() -> None: + gate = {**CLEAN_GATE, "extra_targets": {"page": 1}} + case = compare_case( + _ref(type="Triage"), + _run(target_gate=gate), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + assert case["status"] == "MATCHED" + assert build_scorecard({"cases": [case]})["scope_ok"] is True + + +class FakePage: + def __init__(self, screen: Optional[str] = SCREEN) -> None: + self.screen = screen + self.values: list[tuple[str, str]] = [] + self.continued: list[str] = [] + self.blocked: list[str] = [] + + def continue_request(self, request_id: str) -> None: + self.continued.append(request_id) + + def block_request(self, request_id: str, **kw: Any) -> None: + self.blocked.append(request_id) + + def screen_text(self) -> Optional[str]: + return self.screen + + def form_values(self) -> list[tuple[str, str]]: + return list(self.values) + + def screenshot(self) -> Optional[bytes]: + return b"\x89PNG fake" + + def notify(self, message: str, *, level: str) -> None: + pass + + def clear_notice(self) -> None: + pass + + +class FakeGate: + def __init__(self) -> None: + self.continued: list[str] = [] + self.blocked: list[str] = [] + + def continue_request(self, request_id: str) -> None: + self.continued.append(request_id) + + def block_request(self, request_id: str, **kw: Any) -> None: + self.blocked.append(request_id) + + +def _task() -> GuardTask: + return GuardTask( + task_id="shadow-0001", + expected_record=dict(RECORD), + intended_fields={"type": None}, + ) + + +def _guard(tmp_path: Path, page: Any, **kw: Any) -> ShadowHoldGuard: + return ShadowHoldGuard( + None, + _task(), + page, + app_origin=APP + "/", + run_dir=tmp_path, + save_target=("POST", "/api/encounter"), + **kw, + ) + + +def _req(rid: str, method: str, path: str, body: Optional[str] = None) -> HeldRequest: + return HeldRequest( + request_id=rid, + method=method, + url=APP + path, + resource_type="Fetch", + post_data=body, + content_type="application/json", + ) + + +def test_a_write_from_another_target_is_held_and_never_the_proposal( + tmp_path: Path, +) -> None: + page, gate = FakePage(), FakeGate() + guard = _guard(tmp_path, RoutedPage(page, gate)) # type: ignore[arg-type] + guard.on_request(_req(EXTRA_PREFIX + "1", "GET", "/api/records")) + guard.on_request( + _req( + EXTRA_PREFIX + "2", + "POST", + "/api/encounter", + '{"patient_id": "p1", "type": "Triage"}', + ) + ) + assert gate.continued == [EXTRA_PREFIX + "1"] + assert gate.blocked == [EXTRA_PREFIX + "2"] + assert page.blocked == [] and page.continued == [] + assert guard.proposed is None + outcome = guard.outcome() + assert outcome["extra_target_writes"] == 1 and outcome["landed_writes"] == 0 + held = json.loads((tmp_path / "held" / "0.json").read_text()) + assert held["target"] == "other" + assert stat.S_IMODE((tmp_path / "held" / "0.json").stat().st_mode) == 0o600 + # The tab's own save is still the proposal. + guard.on_request(_req("t1", "POST", "/api/encounter", '{"patient_id": "p1"}')) + assert page.blocked == ["t1"] and guard.proposed["request_index"] == 1 + + +# -- 2. contamination sees values already in the form ------------------------------------- + + +def test_contamination_sees_a_prefilled_form(tmp_path: Path) -> None: + page = FakePage(screen="Jane Sample — MRN P1\nNew encounter\nType\nNote") + guard = _guard(tmp_path, page) + guard.observe_screen() # the record shows; the form is not open yet + page.values = [("input:type:1", "Triage"), ("textarea:note:1", "Cough, 3 days")] + guard.observe_screen() # the edit form opens, already filled in + human = [ + {"name": "type", "value": "Triage"}, + {"name": "note", "value": "Cough, 3 days"}, + ] + assert contamination(guard.before_screen, human)["not_comparable"] is False + check = contamination(guard.contamination_screen, human) + assert check["not_comparable"] is True and check["shown"] == 2 + + +def test_contamination_keeps_the_first_value_not_what_the_agent_typed( + tmp_path: Path, +) -> None: + page = FakePage() + guard = _guard(tmp_path, page) + page.values = [("textarea:note:1", "")] + guard.observe_screen() + page.values = [("textarea:note:1", "Cough, 3 days")] # the agent typed + guard.observe_screen() + human = [{"name": "note", "value": "Cough, 3 days"}] + assert contamination(guard.contamination_screen, human)["not_comparable"] is False + + +def test_form_values_never_decide_identity(tmp_path: Path) -> None: + page = FakePage(screen="Search patients") + page.values = [("input:q:1", "Jane Sample p1")] # typed into a search box + guard = _guard(tmp_path, page) + guard.observe_screen() + assert guard.before_screen is None and guard.contamination_screen is None + + +# -- 6. joins ----------------------------------------------------------------------------- + + +def test_shadow_hold_writes_no_ledger_row_and_has_no_store(tmp_path: Path) -> None: + guard = _guard(tmp_path, FakePage()) + assert guard.ledger_dir is None + assert getattr(guard.guarded, "state_dir", "missing") is None + + +def test_case_json_is_the_cases_entry(tmp_path: Path) -> None: + runs = tmp_path / "runs" + (runs / "case-0001").mkdir(parents=True) + case = compare_case( + _ref(type="Triage"), + _run(), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + doc = {"cases": [case, {**case, "task_id": "not-run-here"}]} + assert write_case_files(doc, runs) == 1 + path = runs / "case-0001" / "case.json" + assert json.loads(path.read_text()) == json.loads(json.dumps(case)) + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + for key in ( + "task_id", + "status", + "reason", + "fields", + "identity", + "contamination", + "double_save", + "landed_writes", + "undeclared_fields", + "out_of_scope_requests", + "agent_time_s", + "human_time_s", + "model_cost_usd", + ): + assert key in case, key + + +def test_scorecard_carries_task_type_cost_source_and_egress() -> None: + case = compare_case( + _ref(type="Triage"), + _run(model_cost_usd=0.02, model_cost_source="reported"), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + card = build_scorecard({"cases": [case]}) + assert card["task_type"] == "unspecified" + assert card["model_cost_usd"]["source"] == "reported" + assert card["egress"] == { + "mode": "unscrubbed", + "enforced": False, + "model_calls": None, + } + card = build_scorecard({"cases": [case]}, task_type="encounter-note") + assert card["task_type"] == "encounter-note" + with pytest.raises(ValueError): + build_scorecard({"cases": [case]}, task_type="Encounter Note!") + unknown = compare_case( + _ref(type="Triage"), + _run(), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + assert ( + build_scorecard({"cases": [unknown]})["model_cost_usd"]["source"] == "unknown" + ) + metered = compare_case( + _ref(type="Triage"), + _run( + model_cost_usd=0.02, model_cost_source="metered", egress={"model_calls": 3} + ), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + card = build_scorecard( + {"cases": [metered], "egress": {"mode": "scrubbed", "enforced": True}} + ) + assert card["model_cost_usd"]["source"] == "metered" + assert card["egress"] == {"mode": "scrubbed", "enforced": True, "model_calls": 3} + + +def test_a_negative_estimate_reads_minus_dollars() -> None: + case = compare_case( + _ref(type="Triage"), + _run(agent_wall_s=105.0, model_cost_usd=0.0, model_cost_source="reported"), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + doc = {"cases": [case]} + card = build_scorecard(doc, hourly_cost=60.0) + assert card["savings"]["est_value_usd"] == -0.75 + page = render_html(card, doc) + assert "-$0.75 (estimate)" in page and "$-0.75" not in page + + +# -- round 3: the scope line and the target record -------------------------------------- + + +def test_a_failed_scope_card_says_what_failed_not_the_claim() -> None: + from openadapt_flow.readiness.runner import SCOPE_STATEMENT, SCOPE_STATEMENT_MAX + + assert len(SCOPE_STATEMENT) <= SCOPE_STATEMENT_MAX + clean = compare_case( + _ref(type="Triage"), + _run(), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + extra = compare_case( + _ref(type="Triage"), + _run(extra_target_writes=1), + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + landed = compare_case( + _ref(type="Triage"), + _run(landed_writes=1), + _proposed(type="Triage"), + before_screen=SCREEN, + ) + assert build_scorecard({"cases": [clean]})["scope_statement"] == SCOPE_STATEMENT + doc = {"cases": [clean, extra, landed]} + card = build_scorecard(doc) + statement = card["scope_statement"] + assert card["scope_ok"] is False + assert statement != SCOPE_STATEMENT and "left any tab" not in statement + assert statement.startswith("Scope failed in 2 of 3 case(s)") + assert "1 write(s) reached the app" in statement and "couldn't vouch" in statement + assert len(statement) <= SCOPE_STATEMENT_MAX + page = render_html(card, doc) + assert "left any tab" not in page and statement.replace("'", "'") in page + many = build_scorecard({"cases": [landed] * 30 + [extra] * 30}) + assert len(many["scope_statement"]) <= SCOPE_STATEMENT_MAX + + +def test_import_names_the_target_record_in_the_inputs() -> None: + from openadapt_flow.readiness.reference import task_inputs + + raw = {"instruction": "Add the note and save.", "inputs": {"note": "n"}} + got = task_inputs(raw, {"patient_id": "p1", "name": "Jane Sample"}) + assert got["inputs"] == { + "note": "n", + "record_patient_id": "p1", + "record_name": "Jane Sample", + } + assert got["instruction"].startswith("Add the note and save.") + assert got["instruction"].endswith( + "Work on the record identified by the inputs record_patient_id, record_name." + ) + assert got["record_keys"] == ["record_patient_id", "record_name"] + # The person's own input of that name wins; it is not a program parameter to drop. + own = task_inputs( + {**raw, "inputs": {"record_name": "Jane S."}}, {"name": "Jane Sample"} + ) + assert own["inputs"] == {"record_name": "Jane S."} and own["record_keys"] == [] + off = task_inputs({**raw, "record_in_inputs": False}, {"name": "Jane Sample"}) + assert off == {"instruction": "Add the note and save.", "inputs": {"note": "n"}} + + +def test_a_program_gets_no_parameter_for_the_record_inputs(tmp_path: Path) -> None: + from openadapt_flow.readiness.launcher import LaunchJob, ProgramLauncher + + job = LaunchJob( + task_id="t-00000001", + instruction="x", + inputs={"note": "n", "record_name": "Jane Sample"}, + cdp_url="http://127.0.0.1:9", + page_url="http://127.0.0.1/", + run_dir=tmp_path, + record_keys=("record_name",), + ) + argv = ProgramLauncher(tmp_path / "bundle", egress=None).flow_args(job) + assert "note=n" in argv and not any("Jane" in a for a in argv) + + +# -- round 4: nothing outside the allowlist leaves the run folder ------------------------- + +PLANTED = "Zyxwv Qtest" +SAMPLES = Path(__file__).resolve().parents[1] / "benchmark" / "readiness" + + +def test_export_copies_only_the_allowlist(tmp_path: Path) -> None: + from openadapt_flow.readiness.export import export_task + + runs = tmp_path / "runs" + task = runs / "case-0001" + (task / "egress").mkdir(parents=True) + (task / "egress" / "pseudonyms.json").write_text( + json.dumps({"[PERSON_1]": PLANTED}) + ) + (task / "pseudonyms.json").write_text(json.dumps({"[PERSON_1]": PLANTED})) + (task / "stray.txt").write_text(PLANTED) + (task / "agent.log").write_text(PLANTED) + (task / "before_screen.txt").write_text(PLANTED) + (task / "usage.json").write_text(json.dumps({"calls": 1, "note": PLANTED})) + run = _run( + model_cost_usd=0.0, + model_cost_source="metered", + usage={"calls": 1, "cost_usd": 0.0, "extra": PLANTED}, + ) + (task / "run.json").write_text( + json.dumps( + {"schema": "openadapt.readiness-task-run/v1", "task_id": "case-0001", **run} + ) + ) + (task / "egress.json").write_text( + json.dumps( + { + "mode": "scrubbed", + "enforced": True, + "model_calls": 1, + "cost_usd": 0.0, + "cost_source": "metered", + "refused_requests": 0, + } + ) + ) + case = compare_case( + _ref(type="Triage"), + run, + _proposed(type="Triage"), + before_screen=SCREEN, + held=[_held(0)], + ) + doc = {"cases": [case]} + write_case_files(doc, runs) + card_dir = tmp_path / "card" + card_dir.mkdir() + (card_dir / "scorecard.json").write_text(json.dumps(build_scorecard(doc))) + out = tmp_path / "export" + result = export_task( + task, + out, + include_values=True, + extra={"scorecard.json": card_dir / "scorecard.json"}, + ) + assert sorted(result["copied"]) == [ + "case.json", + "egress.json", + "run.json", + "scorecard.json", + ] + left = " ".join(result["left"]) + for name in ( + "egress", + "pseudonyms.json", + "stray.txt", + "agent.log", + "before_screen.txt", + "usage.json", + ): + assert name in left, (name, left) + for path in out.rglob("*"): + assert PLANTED not in path.read_text(), path + assert PLANTED not in json.dumps(doc) + # Without values, case files stay behind too. + bare = export_task(task, tmp_path / "bare") + assert "case.json" not in bare["copied"] + + +def test_committed_samples_hold_no_patient_names_or_pseudonym_maps() -> None: + from tests.e2e.test_readiness_e2e import PATIENTS + + files = [p for p in SAMPLES.rglob("*.json")] + assert files + for path in files: + text = path.read_text() + assert "pseudonyms" not in path.name, path + for name in [*PATIENTS.values(), PLANTED]: + assert name not in text, (path, name) + + +# -- review: undeclared names stay local; no name is exempt ------------------------------ + + +def test_undeclared_field_names_never_reach_the_scorecard() -> None: + import json as _json + + name_like = "Jane_Sample_DOB_1980-01-01" + case = compare_case( + _ref(type="Triage"), + _run(), + _proposed(type="Triage", **{name_like: "x"}), + before_screen=SCREEN, + held=[_held(0)], + ) + assert case["status"] == "MISMATCHED" and case["undeclared_fields"] == 1 + card = build_scorecard({"cases": [case]}) + assert {e["field"] for e in card["field_errors"]} == {"undeclared_field"} + assert card["risks"]["undeclared_field"] == 1 + assert name_like not in _json.dumps(card) + assert "Jane" not in _json.dumps(card) + + +def test_a_field_named_body_is_not_exempt() -> None: + case = compare_case( + _ref(type="Triage"), + _run(), + _proposed(type="Triage", **{"": "anything"}), + before_screen=SCREEN, + held=[_held(0)], + ) + assert case["status"] == "MISMATCHED", case + assert [r["kind"] for r in case["fields"] if r["name"] == ""] == ["extra"] + unparsed = _proposed(type="Triage") + unparsed["fields"].append({"name": "", "value": None, "parse": "uncompared"}) + case = compare_case( + _ref(type="Triage"), _run(), unparsed, before_screen=SCREEN, held=[_held(0)] + ) + assert case["status"] != "MATCHED", case + + +# -- review: no secret or input on a command line ------------------------------------------- + + +def test_a_programs_command_line_holds_no_token_or_input(tmp_path: Path) -> None: + from openadapt_flow.readiness.launcher import LaunchJob, ProgramLauncher + + token = "tok_" + "s3cr3t" * 4 + job = LaunchJob( + task_id="t-00000001", + instruction="x", + inputs={"note": "Synthetic note 07", "record_name": "Jane Sample"}, + cdp_url=f"http://127.0.0.1:9/{token}", + page_url="http://127.0.0.1:1/", + run_dir=tmp_path, + record_keys=("record_name",), + ) + agent = ProgramLauncher(tmp_path / "no-bundle", egress=None).start(job) + try: + args = " ".join(agent._process.proc.args) # what ps shows + finally: + agent.stop() + assert token not in args and "Synthetic note 07" not in args and "Jane" not in args + assert "openadapt_flow.readiness.program_child" in args + + +def test_the_program_child_reads_its_args_once_and_only_private( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch +) -> None: + import os + + import openadapt_flow.__main__ as flow + from openadapt_flow.readiness import program_child + + seen: list[list[str]] = [] + monkeypatch.setattr(flow, "main", lambda argv: seen.append(list(argv)) or 0) + path = program_child.write_args( + tmp_path / "a.json", ["run", "b", "--browser-cdp-endpoint", "http://x/tok"] + ) + assert oct(os.stat(path).st_mode & 0o777) == "0o600" + assert program_child.main([str(path)]) == 0 + assert seen == [["run", "b", "--browser-cdp-endpoint", "http://x/tok"]] + assert not path.exists() # read once + loose = program_child.write_args(tmp_path / "b.json", ["run", "b"]) + os.chmod(loose, 0o644) + with pytest.raises(SystemExit, match="readable by others"): + program_child.main([str(loose)]) + other = program_child.write_args(tmp_path / "c.json", ["guard", "x"]) + with pytest.raises(SystemExit, match="not a readiness program run"): + program_child.main([str(other)]) + + +def test_the_hold_refuses_reads_to_origins_outside_the_allowlist( + tmp_path: Path, +) -> None: + page = FakePage() + guard = _guard(tmp_path, page, allowed_origins=(APP, "https://login.example.test")) + guard.on_request(_req("r1", "GET", "/api/records")) + guard.on_request( + HeldRequest( + request_id="r2", + method="GET", + url="http://127.0.0.1:1234/leak?d=Jane", + resource_type="Image", + ) + ) + guard.on_request( + HeldRequest( + request_id="r3", + method="GET", + url="https://login.example.test/start", + resource_type="Document", + ) + ) + guard.on_request( + HeldRequest( + request_id="r4", + method="GET", + url=f"blob:{APP}/0b1c", + resource_type="Script", + ) + ) + assert page.continued == ["r1", "r3", "r4"] + assert page.blocked == ["r2"] + assert guard.outcome()["other_origin_refused"] == 1 diff --git a/packages/flow/tests/test_readiness_reference.py b/packages/flow/tests/test_readiness_reference.py new file mode 100644 index 0000000000..4e35d30fcd --- /dev/null +++ b/packages/flow/tests/test_readiness_reference.py @@ -0,0 +1,263 @@ +"""Reference episodes from a person's recorded tasks. Synthetic data only.""" + +from __future__ import annotations + +import json +import stat +from pathlib import Path +from typing import Any, Optional + +import pytest + +from openadapt_flow.readiness.reference import ( + REFERENCE_SCHEMA, + import_episodes, + load_episodes, +) + +APP = "http://127.0.0.1:9811" +RECORD = {"patient_id": "p1", "name": "Jane Sample"} + + +def _task(folder: Path, task_id: str = "ref-task-0001", **extra: Any) -> Path: + folder.mkdir(parents=True, exist_ok=True) + doc = { + "schema": "openadapt.readiness-task/v1", + "task_id": task_id, + "instruction": "Add the triage note.", + "inputs": {"note": "Cough, 3 days"}, + "expected_record": RECORD, + **extra, + } + (folder / "task.json").write_text(json.dumps(doc)) + return folder + + +def _capture( + folder: Path, lines: list[dict[str, Any]], events: Optional[list[float]] = None +): + rec = folder / "recording" + rec.mkdir(parents=True, exist_ok=True) + rows = [{"schema": "openadapt.network-capture/1", "exchanges": len(lines)}] + rows += [ + {"seq": i, "resource_type": "fetch", "frame_url": None, **line} + for i, line in enumerate(lines) + ] + (rec / "network.jsonl").write_text("\n".join(json.dumps(r) for r in rows) + "\n") + if events is not None: + (rec / "events.jsonl").write_text( + "\n".join(json.dumps({"t": t, "kind": "click"}) for t in events) + "\n" + ) + + +def _save(t: float = 42.5, status: int = 200, **kw: Any) -> dict[str, Any]: + return { + "t": t, + "method": "POST", + "url": APP + "/api/encounter?fault=ok", + "status": status, + "request_type": "application/json", + "body": json.dumps( + { + "patient_id": "p1", + "type": "Triage", + "note": "Cough, 3 days", + "csrf_token": "", + } + ), + **kw, + } + + +def test_import_from_network_capture(tmp_path: Path) -> None: + folder = _task(tmp_path / "src" / "a") + _capture( + folder, + [{"t": 0.1, "method": "GET", "url": APP + "/", "status": 200}, _save()], + events=[2.5, 10.0, 40.0], + ) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP + "/") + assert result.imported == ["ref-task-0001"] and result.refused == [] + out = tmp_path / "eps" / "ref-task-0001" + ep = json.loads((out / "reference_episode.json").read_text()) + assert ep["schema"] == REFERENCE_SCHEMA + assert ep["human_source"] == "network_capture" + assert ep["human_fields"] == [ + {"name": "patient_id", "value": "p1"}, + {"name": "type", "value": "Triage"}, + {"name": "note", "value": "Cough, 3 days"}, + ] + assert ep["human_duration_s"] == 40.0 + assert ep["save"] == {"method": "POST", "url_path": "/api/encounter"} + assert ep["withheld_fields"] == 1 + assert ep["inputs_digest"].startswith("sha256:") + for name in ("reference_episode.json", "inputs.json", "guard_task.json"): + assert stat.S_IMODE((out / name).stat().st_mode) == 0o600 + guard_task = json.loads((out / "guard_task.json").read_text()) + assert guard_task["schema_version"] == "openadapt.guard-task/v1" + assert guard_task["intended_fields"] == {"type": None, "note": None} + from openadapt_flow.guard import load_task + + assert load_task(out / "guard_task.json").expected_record == RECORD + assert [doc["task_id"] for _p, doc in load_episodes(tmp_path / "eps")] == [ + "ref-task-0001" + ] + + +@pytest.mark.parametrize( + ("lines", "extra", "code"), + [ + ( + [{"t": 1, "method": "GET", "url": APP + "/", "status": 200}], + {}, + "no_save_in_capture", + ), + ([_save(status=500)], {}, "save_not_confirmed"), + ([_save(failed=True, status=None)], {}, "save_not_confirmed"), + ([_save(body=None, body_omitted="multipart")], {}, "save_unreadable"), + ([_save(request_truncated=True)], {}, "save_unreadable"), + ( + [{**_save(), "url": APP + "/api/lock", "t": 1}, _save()], + {}, + "ambiguous_save", + ), + ], +) +def test_refusals(tmp_path: Path, lines: list, extra: dict, code: str) -> None: + folder = _task(tmp_path / "src" / "a", **extra) + _capture(folder, lines) + result = import_episodes(tmp_path / "src", tmp_path / "eps", app_url=APP) + assert result.imported == [] + assert [r["code"] for r in result.refused] == [code] + assert not (tmp_path / "eps" / "ref-task-0001").exists() + + +def test_named_save_resolves_ambiguity_and_skips_not_saves(tmp_path: Path) -> None: + folder = _task( + tmp_path / "src" / "a", + save={"method": "POST", "path": "/api/encounter"}, + not_saves=[{"method": "POST", "path": "/login"}], + ) + _capture( + folder, + [ + {**_save(), "url": APP + "/login", "t": 0.5}, + {**_save(), "url": APP + "/api/lock", "t": 1}, + _save(), + ], + ) + assert import_episodes(tmp_path / "src", tmp_path / "eps").imported == [ + "ref-task-0001" + ] + + +def test_no_source_and_bad_task(tmp_path: Path) -> None: + _task(tmp_path / "src" / "a") + _task(tmp_path / "src" / "b", task_id="short") + result = import_episodes(tmp_path / "src", tmp_path / "eps") + assert sorted(r["code"] for r in result.refused) == ["no_source", "task_invalid"] + + +def test_readback_source(tmp_path: Path) -> None: + records = [ + { + "id": 1, + "patient_id": "p1", + "name": "Jane Sample", + "type": "Triage", + "note": "old", + }, + {"id": 2, "patient_id": "p2", "name": "Alex", "type": "Consult", "note": "x"}, + ] + _task( + tmp_path / "src" / "a", + fields=["type", "note"], + readback={"verify": "verify.yaml", "match": {"id": 1}}, + ) + _task( + tmp_path / "src" / "b", + task_id="ref-task-0002", + fields=["type"], + readback={"verify": "verify.yaml"}, + expected_record={"patient_id": "p9", "name": "Nobody"}, + ) + result = import_episodes( + tmp_path / "src", tmp_path / "eps", reader=lambda rb, folder, expected: records + ) + assert result.imported == ["ref-task-0001"] + assert [r["code"] for r in result.refused] == ["readback_ambiguous"] + ep = json.loads( + (tmp_path / "eps" / "ref-task-0001" / "reference_episode.json").read_text() + ) + assert ep["human_source"] == "readback" + assert ep["human_fields"] == [ + {"name": "type", "value": "Triage"}, + {"name": "note", "value": "old"}, + ] + + +def test_readback_needs_field_names_and_a_reachable_store(tmp_path: Path) -> None: + _task(tmp_path / "src" / "a", readback={"verify": "verify.yaml"}) + _task( + tmp_path / "src" / "b", + task_id="ref-task-0002", + fields=["note"], + readback={"verify": "missing.yaml"}, + ) + result = import_episodes(tmp_path / "src", tmp_path / "eps") + assert sorted(r["code"] for r in result.refused) == [ + "readback_invalid", + "readback_unavailable", + ] + + +def test_readback_through_the_verify_config(tmp_path: Path) -> None: + pytest.importorskip("yaml") + from benchmark.agent_guard.app import serve + from benchmark.effect_e2e.record_service import ENCOUNTERS_READ_CONTRACT + + app = serve(tmp_path / "app.sqlite") + try: + app.store.apply_write( + "ok", + patient_id="p3", + enc_type="Consult", + note="Synthetic readback note", + key=None, + ) + import yaml + + folder = _task( + tmp_path / "src" / "a", + expected_record={"patient_id": "p3"}, + fields=["type", "note"], + readback={ + "verify": "verify.yaml", + "match": {"note": "Synthetic readback note"}, + }, + ) + (folder / "verify.yaml").write_text( + "schema_version: openadapt.verify/v1\n" + + yaml.safe_dump( + { + "verifier": { + "kind": "rest", + "base_url": app.base_url, + **ENCOUNTERS_READ_CONTRACT, + } + } + ) + + "effects:\n - kind: record_written\n match:\n" + " patient_id: {param: patient_id}\n expected_count: 1\n" + ) + result = import_episodes(tmp_path / "src", tmp_path / "eps") + assert result.refused == [] and result.imported == ["ref-task-0001"] + ep = json.loads( + (tmp_path / "eps" / "ref-task-0001" / "reference_episode.json").read_text() + ) + assert ep["human_fields"] == [ + {"name": "type", "value": "Consult"}, + {"name": "note", "value": "Synthetic readback note"}, + ] + finally: + app.stop() diff --git a/packages/flow/tests/test_shadow_hold.py b/packages/flow/tests/test_shadow_hold.py new file mode 100644 index 0000000000..698de0a0ed --- /dev/null +++ b/packages/flow/tests/test_shadow_hold.py @@ -0,0 +1,262 @@ +"""The shadow hold captures every write of a task and refuses it. + +A fake page stands in for the CDP adapter; no browser. Synthetic values. +""" + +from __future__ import annotations + +import json +import stat +from pathlib import Path +from typing import Any, Optional + +import pytest + +from openadapt_flow.agent_guard.commit_guard import BLOCK_STATUS, GUARD_HEADER +from openadapt_flow.agent_guard.requests import HeldRequest, NotASave +from openadapt_flow.agent_guard.shadow_hold import ( + PROPOSED_WRITE_SCHEMA, + ShadowHoldGuard, + parse_body_fields, +) +from openadapt_flow.guard import GuardTask + +APP = "http://127.0.0.1:9999" + + +class FakePage: + def __init__(self, screen: Optional[str] = "Jane Sample — MRN P1") -> None: + self.screen = screen + self.continued: list[str] = [] + self.blocked: list[tuple[str, int, dict[str, str], str]] = [] + self.notices: list[str] = [] + + def continue_request(self, request_id: str) -> None: + self.continued.append(request_id) + + def block_request(self, request_id: str, *, status, body, content_type, headers): + self.blocked.append((request_id, status, headers, body)) + + def screen_text(self) -> Optional[str]: + return self.screen + + def screenshot(self) -> Optional[bytes]: + return b"\x89PNG fake" + + def notify(self, message: str, *, level: str) -> None: + self.notices.append(message) + + def clear_notice(self) -> None: + pass + + +def _task() -> GuardTask: + return GuardTask( + task_id="shadow-task-0001", + expected_record={"patient_id": "p1", "name": "Jane Sample"}, + intended_fields={"type": None, "note": None}, + ) + + +def _guard(tmp_path: Path, page: FakePage, **kw: Any) -> ShadowHoldGuard: + return ShadowHoldGuard( + None, _task(), page, app_origin=APP + "/", run_dir=tmp_path, **kw + ) + + +def _req( + rid: str, + method: str, + path: str, + body: Optional[str] = None, + ctype: str = "application/json", + origin: str = APP, +) -> HeldRequest: + return HeldRequest( + request_id=rid, + method=method, + url=origin + path, + resource_type="Fetch", + post_data=body, + content_type=ctype, + ) + + +def test_every_non_get_to_the_app_is_held_and_refused(tmp_path: Path) -> None: + page = FakePage() + guard = _guard(tmp_path, page) + guard.on_request(_req("r0", "GET", "/api/records")) + for i, method in enumerate(("POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS")): + guard.on_request(_req(f"w{i}", method, "/api/encounter", '{"note": "x"}')) + assert page.continued == ["r0"] + assert [b[0] for b in page.blocked] == [f"w{i}" for i in range(6)] + for _rid, status, headers, body in page.blocked: + assert status == BLOCK_STATUS + assert headers[GUARD_HEADER] == "blocked; code=shadow_hold" + assert "stopped before save (shadow mode)" in body + assert guard.outcome()["held"] == 6 + assert guard.landed_writes == 0 + assert guard.finished # the first hold ends the task + + +def test_graphql_query_post_and_get_mutation_are_held(tmp_path: Path) -> None: + page = FakePage() + guard = _guard(tmp_path, page) + guard.on_request(_req("q", "POST", "/graphql", '{"query": "query { a }"}')) + guard.on_request( + HeldRequest("m", "GET", APP + "/graphql?query=mutation%20%7B%20b%20%7D") + ) + assert page.continued == [] + assert [b[0] for b in page.blocked] == ["q", "m"] + + +def test_not_saves_go_on_and_other_origins_are_refused(tmp_path: Path) -> None: + page = FakePage() + guard = _guard(tmp_path, page, not_saves=[NotASave("POST", "/login")]) + guard.on_request( + _req("s", "POST", "/login", "user=a", "application/x-www-form-urlencoded") + ) + guard.on_request(_req("o", "POST", "/beacon", "{}", origin="http://127.0.0.1:1")) + assert page.continued == ["s"] + assert [b[0] for b in page.blocked] == ["o"] + assert guard.landed_writes == 0 + assert guard.other_origin_refused == 1 + assert guard.proposed is None + + +def test_proposed_write_file(tmp_path: Path) -> None: + page = FakePage() + guard = _guard(tmp_path, page, save_target=("POST", "/api/encounter")) + guard.on_request(_req("lock", "POST", "/api/lock", '{"id": 1}')) + assert guard.proposed is None # a lock is held, but it isn't the save + guard.on_request( + _req( + "s", + "POST", + "/api/encounter", + json.dumps( + { + "patient_id": "p1", + "type": "Triage", + "note": "n", + "csrf_token": "abcdefghijkl", + } + ), + ) + ) + path = tmp_path / "proposed_write.json" + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + doc = json.loads(path.read_text()) + assert doc["schema"] == PROPOSED_WRITE_SCHEMA + assert doc["request_index"] == 1 + assert doc["method"] == "POST" and doc["url_path"] == "/api/encounter" + assert doc["origin"] == APP + assert doc["identity"] == {"ok": True, "code": "verified"} + assert doc["refused"] is True + assert doc["withheld_fields"] == 1 + assert {f["name"]: f["value"] for f in doc["fields"]} == { + "patient_id": "p1", + "type": "Triage", + "note": "n", + } + assert "abcdefghijkl" not in path.read_text() + assert (tmp_path / "held" / "1.png").is_file() + assert (tmp_path / "held" / "0.json").is_file() + + +def test_wrong_record_is_recorded(tmp_path: Path) -> None: + page = FakePage(screen="Alex Testcase — MRN P2") + guard = _guard(tmp_path, page) + guard.on_request(_req("s", "POST", "/api/encounter", '{"note": "n"}')) + assert guard.proposed["identity"] == {"ok": False, "code": "identity_mismatch"} + + +def test_a_forwarded_write_is_counted(tmp_path: Path) -> None: + # Defence in depth: the counting page sees a write go on whatever decided it. + page = FakePage() + guard = _guard(tmp_path, page) + request = _req("x", "POST", "/api/encounter", "{}") + guard._seen["x"] = request + guard.page.continue_request("x") + assert guard.landed_writes == 1 + assert guard.outcome()["landed"] == [ + {"method": "POST", "url_path": "/api/encounter"} + ] + + +def test_double_save_and_before_screen(tmp_path: Path) -> None: + page = FakePage(screen="Referral Tasks") + guard = _guard(tmp_path, page) + guard.observe_screen() + assert guard.before_screen is None # the record isn't open yet + page.screen = "Jane Sample — MRN P1 — DOB 1980-01-01" + guard.observe_screen() + assert guard.before_screen == page.screen + for rid in ("a", "b"): + guard.on_request(_req(rid, "POST", "/api/encounter", '{"note": "n"}')) + assert guard.outcome()["double_save"] is True + + +@pytest.mark.parametrize( + ("ctype", "body", "expected"), + [ + ( + "application/x-www-form-urlencoded", + "a=1&b=&a=2&c=x", + [("a", None, "uncompared"), ("b", "", "form"), ("c", "x", "form")], + ), + ( + "application/json", + '{"a": {"b": 1}, "c": null, "d": true}', + [("a.b", "1", "json"), ("c", None, "json"), ("d", "true", "json")], + ), + ("text/plain", "free text", [("", None, "uncompared")]), + ("application/json", "[1, 2]", [("", None, "uncompared")]), + ("application/json", "{not json", [("", None, "uncompared")]), + ], +) +def test_parse_body_fields(ctype: str, body: str, expected: list) -> None: + fields, _ = parse_body_fields( + method="POST", url=APP + "/x", content_type=ctype, body=body + ) + assert [(f.name, f.value, f.parse) for f in fields] == expected + + +def test_a_write_with_no_body_seen_is_uncompared() -> None: + fields, _ = parse_body_fields( + method="POST", url=APP + "/x", content_type="", body=None + ) + assert [(f.name, f.parse) for f in fields] == [("", "uncompared")] + + +def test_multipart_and_lens() -> None: + from openadapt_flow.tx.types import EndpointTemplate, EntityLensSpec + + boundary = "XyZ" + body = ( + f'--{boundary}\r\nContent-Disposition: form-data; name="note"\r\n\r\nhello\r\n' + f"--{boundary}--\r\n" + ) + fields, _ = parse_body_fields( + method="POST", + url=APP + "/x", + content_type=f"multipart/form-data; boundary={boundary}", + body=body, + ) + assert [(f.name, f.value, f.parse) for f in fields] == [("note", "hello", "form")] + lens = EntityLensSpec( + entity_name="encounter", + base_url=APP, + get_one=EndpointTemplate(method="GET", path_template="/api/encounter/{id}"), + write_endpoint=EndpointTemplate( + method="PATCH", path_template="/api/encounter/{id}" + ), + ) + fields, _ = parse_body_fields( + method="PATCH", + url=APP + "/api/encounter/7", + content_type="application/json", + body='{"note": "n"}', + lens=lens, + ) + assert fields[0].parse == "lens"