diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 462d157c9d..1cfcd8d21e 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -361,6 +361,7 @@ improvising or retrying when something is off. | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](packages/flow/docs/WRITE_RECEIPTS.md) | +| Per-run accounting ledger for any executor (an OpenAdapt agent, a compiled program, another agent, a person): one value-free row per run with the outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN) and a closed reason, a person's minutes from approval, question, exception and second-factor intervals, model calls and cost (unknown is null, never zero), field names with their checks, and the read-back tier; values only in a local 0600 sidecar; collected from the files guard, verify-run, compiled runs, wrap, item approvals and compile-agent already write, plus readiness shadow runs, guard ledger rows, P7 fallback results and P6 exception answers; a person's decline is ESCALATED, not a caught error | On main | Unit tests with synthetic data: the outcome rule as a table over every engine outcome enum, fixtures for each source (copies of the shadow, guarded-save, fallback and exception files from a synthetic MockMed end-to-end run), the real commit guard against MockMed's fault server end to end, exports scanned for every fixture value and checked with the real Presidio scrubber, push payloads validated against the JSON Schema, push refused with no key | `openadapt-flow ledger add`, `list`, `show`, `summary`, `export`, `push`; [RUN_LEDGER.md](packages/flow/docs/RUN_LEDGER.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own. One screen: map left, Seal and verdict top right, Summary, Steps, Evidence and Raw tabs; light and dark | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests; a link to one step, keyboard tabs and steps, theme switch, phone layout); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](packages/seal-view/README.md) | | Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](packages/flow/openadapt_flow/browser_login.py) | | Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing every public field and the full path to each file; `--show` prints the exact upload | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | @@ -458,6 +459,7 @@ A test fails when a command has no file or this list is out of date. - `attach-seal` - `countersign` - `encrypt` +- `ledger`: Per-run accounting rows for any executor: outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN), a person's minutes, model cost, fields checked; no record values - `local-seal`: Offline Seals: customer-held keys, pinned verification, Rekor anchoring, run authorizations, operator profiles, public cards. - `receipt`: Signed write receipts (COSE, SCITT shape): check one offline against pinned keys and print what it did not check; export the public keys; anchor in Rekor. - `redact-report`: Strip session tokens from an existing run's report so it can be sealed again; the original stays local diff --git a/llms-full.txt b/llms-full.txt index 5d3446e884..05b86b3bc2 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -821,6 +821,7 @@ improvising or retrying when something is off. | Offline Seals signed with a key the customer holds: a key file, the OS keychain, or a PKCS#11 token or HSM; pinned keys with rotation and revocation; no fallback to a generated key | On main ([#1392](https://github.com/OpenAdaptAI/OpenAdapt/pull/1392)) | Unit tests with synthetic data (keychain and PKCS#11 through stand-ins) | `openadapt-flow local-seal --key`, `local-seal key create`, `pin`, `revoke`; `openadapt seal verify FOLDER` checks every sealed run in a folder; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#customer-held-keys) | | Anchor an offline Seal in the public Sigstore Rekor transparency log (opt-in; sends one digest and the public key), and verify the anchor offline from the stored inclusion proof | Released ([#1394](https://github.com/OpenAdaptAI/OpenAdapt/pull/1394)) | Unit tests against a simulated Rekor log; real public Rekor entries and Sigstore TSA tokens for the landing demo's referral runs, verified offline in tests; Ed25519ph matches the RFC 8032 test vector | `openadapt-flow local-seal anchor`, `local-seal verify --require-anchor`; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#optional-anchor-a-seal-in-a-public-transparency-log) | | Signed write receipts: a verifier verdict with its scope (stores read, window, strength) and a plain not-checked list, signed as a COSE_Sign1 (IETF SCITT shape) and logged in a local Merkle transparency log; checked offline against pinned keys; a receipt that claims more than its scope is neither issued nor accepted; optional Rekor anchor | On main | Unit tests on the real verifier (SQLite) and shadow proxy; COSE checked through python-cwt | `openadapt-flow receipt verify`, `receipt keys export`, `receipt anchor`; `verify_write(..., write_receipt=True)`; `shadow --receipts`; [WRITE_RECEIPTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRITE_RECEIPTS.md) | +| Per-run accounting ledger for any executor (an OpenAdapt agent, a compiled program, another agent, a person): one value-free row per run with the outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN) and a closed reason, a person's minutes from approval, question, exception and second-factor intervals, model calls and cost (unknown is null, never zero), field names with their checks, and the read-back tier; values only in a local 0600 sidecar; collected from the files guard, verify-run, compiled runs, wrap, item approvals and compile-agent already write, plus readiness shadow runs, guard ledger rows, P7 fallback results and P6 exception answers; a person's decline is ESCALATED, not a caught error | On main | Unit tests with synthetic data: the outcome rule as a table over every engine outcome enum, fixtures for each source (copies of the shadow, guarded-save, fallback and exception files from a synthetic MockMed end-to-end run), the real commit guard against MockMed's fault server end to end, exports scanned for every fixture value and checked with the real Presidio scrubber, push payloads validated against the JSON Schema, push refused with no key | `openadapt-flow ledger add`, `list`, `show`, `summary`, `export`, `push`; [RUN_LEDGER.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/RUN_LEDGER.md) | | See a run's Seal offline: one HTML page that checks the Ed25519 signature over the run's exact report in the browser, draws the Seal from it, replays the run over its program map, and lets the reader tamper with a copy; no network requests; the quickstart ends on the person's own. One screen: map left, Seal and verdict top right, Summary, Steps, Evidence and Raw tabs; light and dark | On main ([#1566](https://github.com/OpenAdaptAI/OpenAdapt/pull/1566)) | A real quickstart run's Seal opened from `file://` in Chromium (valid, tampered, no requests; a link to one step, keyboard tabs and steps, theme switch, phone layout); RFC 8032 test vectors; a published OpenEMR Seal's Rekor entry and timestamp | `openadapt seal view RUN_DIR`; `openadapt quickstart`; [`@openadapt/seal-view`](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/seal-view/README.md) | | Sign in to OpenAdapt Cloud from the terminal: `openadapt login` with no token prints a sign-in link (opened only with `--open`), listens on 127.0.0.1 for the browser's redirect, and redeems Cloud's one-use code with an S256 PKCE verifier that never leaves the process. A first-time user gets a workspace on the way. The credential goes to the OS keychain entry `push` and `report-run` read; a stored token is re-validated as before, and `--token` and `--no-browser` keep the token path | On main | Unit tests with a real loopback listener (state mismatch, refusal, malformed code, timeout, browser opened only on request); end to end against Cloud's `/auth/loopback` and pairing routes in mock mode, both Connect and Cancel | `openadapt login`; [browser_login.py](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/openadapt_flow/browser_login.py) | | Publish a run's Seal online: a signed public card (counts, outcomes, each step's check, digests; the program name only with `--names` or for the tutorial; never inputs, intents, screenshots, URLs or halt text) shown in full and uploaded only after a yes, with a delete token; check a hosted link here. The quickstart offers its checked and its stopped run's Seals in one question, showing every public field and the full path to each file; `--show` prints the exact upload | On main ([#2266](https://github.com/OpenAdaptAI/OpenAdapt/pull/2266)) | Unit tests with synthetic reports: planted values absent from the file, 64-step card within 4,096 bytes, stopped runs, mock uploads with real sockets blocked; 29 golden vectors shared with Cloud's verifier | `openadapt-flow local-seal public`; `openadapt seal publish`, `unpublish`, `seal verify `; [OFFLINE_SEALS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/OFFLINE_SEALS.md#public-seals-a-summary-you-can-post) | @@ -918,6 +919,7 @@ A test fails when a command has no file or this list is out of date. - `attach-seal` - `countersign` - `encrypt` +- `ledger`: Per-run accounting rows for any executor: outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN), a person's minutes, model cost, fields checked; no record values - `local-seal`: Offline Seals: customer-held keys, pinned verification, Rekor anchoring, run authorizations, operator profiles, public cards. - `receipt`: Signed write receipts (COSE, SCITT shape): check one offline against pinned keys and print what it did not check; export the public keys; anchor in Rekor. - `redact-report`: Strip session tokens from an existing run's report so it can be sealed again; the original stays local diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 298ac8056b..7ab4efba1f 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -72,6 +72,7 @@ "jit": "compile --jit", "known-ids": "verify known-ids", "learn": "teach --learn", + "ledger": "inspect ledger", "lint": "inspect lint", "local-seal": "verify local-seal", "login": "setup login", diff --git a/packages/flow/docs/RUN_LEDGER.md b/packages/flow/docs/RUN_LEDGER.md new file mode 100644 index 0000000000..f2064fbd97 --- /dev/null +++ b/packages/flow/docs/RUN_LEDGER.md @@ -0,0 +1,353 @@ +# Run ledger + +`openadapt-flow ledger` keeps one accounting row per run, whatever did the +work: an OpenAdapt agent, a compiled program, another vendor's agent, or a +person. A row says how the run ended, why, how long it took, what its model +calls cost, how many minutes a person spent on it, which fields it wrote and +whether each one checked out. It holds no record values. + +```bash +openadapt-flow ledger add RUN_DIR --task-type intake +openadapt-flow ledger summary --since 2026-11-01 +openadapt-flow ledger export --out rows.jsonl +OPENADAPT_API_KEY=... openadapt-flow ledger push +``` + +`add` reads files that other commands already wrote. It never changes them, +calls a model, or uses the network. + +## The row + +Schema `openadapt.run-ledger/v1`, defined in +`openadapt_types.run_ledger.RunLedgerRowV1`: + +| Field | Meaning | +| --- | --- | +| `row_id` | A new UUID per row. | +| `task_id` | The task id a source names (guard task, flight, shadow write). Without one, `run-` and a digest of the run's path. | +| `task_type` | The operator's label from `--task-type` (default `unspecified`). Lower-case words only, so it can't carry a name. | +| `executor_kind`, `executor_label` | `agent`, `program`, `human` or `unknown`, and a short label such as `browser-use`. | +| `inputs_commitment` | `sha256:` of a random salt plus the run's inputs. The salt is only in the private sidecar. `null` when no source names the inputs. | +| `started_at`, `ended_at`, `duration_s` | From a source that keeps the run's own start and end (wrap, compiled runs, flight, compile-agent). Otherwise from the wall-clock moments the run's files record (an approval asked and answered, a shadow hold, the egress timeline's first and last model call, a read-back issued, an exception card): `ended_at` is the latest, and `started_at` is `ended_at` minus the run's own duration, or the earliest moment if that is earlier. `null` only when no source records a moment. A guard run is placed exactly when it held a save for a person: the approval request's `created_at` minus the guard's own `t` for that hold. A dispatcher envelope takes its start and finish from wrap's run store record `runs/.json` near it. `duration_s` is always a source's own measure; a guard run that ended by timeout after its last save decision is measured to that decision, not through the wait for the agent to exit. | +| `model` | `calls`, `input_tokens`, `output_tokens`, `cost_usd`, and `cost_source` (`metered`, `reported` or `unknown`). A value a source doesn't give is `null`, never `0`. | +| `human` | `intervals` (`approval`, `question`, `exception`, `second_factor`, each with `opened_at` and `decided_at`) and `intervention_s`, their sum. If any interval has no `decided_at`, `intervention_s` is `null`. With no intervals it is `0` only when a source shows no person was asked (a shadow hold, which never asks; an agent-guard run with approval `not_gated`; a flight with no gate events), and `null` (unknown) otherwise. A shadow run's person did the real save in a separate recorded run, so the shadow row itself is `0`. | +| `outcome`, `outcome_reason` | See below. | +| `fields_written`, `fields_differing` | Field names with `matched`, `differs` or `not_checked`, and how many differ. Names only. A shadow run writes nothing, so its row has none; its comparison stays in `case.json` and the values in the private sidecar. | +| `readback_tier` | The weakest read: `independent_readback`, `screen_readback` or `unchecked`. | +| `receipt_digest` | The run receipt's digest, when there is one. | +| `sources` | The files the row came from, relative to the run directory. | + +Every string field is a closed pattern or enum, and the models forbid +unknown keys, so a value has no field to travel in. + +## The private sidecar + +`add` writes `$OPENADAPT_HOME/ledger/private//ledger.private.json` +(mode 0600, directory 0700). It holds the inputs salt and, for each field a +source gave values for, what was meant to be saved, what was saved, and a +diff. Only `ledger show ROW_ID --show-values` prints it. `export` and `push` +look for every sidecar value in what they would send and refuse on a match. + +## The outcome rule + +Five buckets. Each `outcome_reason` belongs to exactly one, and a row whose +reason names another bucket is refused. + +| Bucket | When | Reasons | +| --- | --- | --- | +| VERIFIED | An independent read-back verified the save and no hold is pending. | `readback_verified` | +| ESCALATED | The run stopped for a person, a person declined it, or a person did the step. | `approval_held`, `person_declined`, `values_unread`, `approval_declined`, `question_asked`, `exception_card`, `second_factor`, `halted_before_effect`, `gate_held`, `shadow_matched` | +| CAUGHT_ERROR | A check caught a wrong save. A person declining is not a catch on its own. | `readback_refuted`, `save_blocked_wrong_record`, `save_blocked_other_origin`, `save_blocked_double_save`, `save_blocked_out_of_scope`, `gate_refused`, `shadow_wrong_record`, `shadow_field_mismatch` | +| FAILED | Crashed, timed out, canceled or gave up, with no evidence of a write. | `crashed_no_write`, `timed_out_no_write`, `agent_gave_up`, `shadow_no_proposal`, `shadow_timed_out`, `platform_failed`, `canceled_no_write`, `policy_rejected_no_write` | +| UNKNOWN | Nothing settles it. Never folded into another bucket. | `shadow_write_landed`, `completed_unverified`, `shadow_not_compared`, `shadow_extra_target`, `shadow_agent_error`, `egress_refused`, `reconciliation_required`, `screen_readback_only`, `lost_reply`, `write_unconfirmed`, `saved_awaiting_check`, `rolled_back`, `self_approved`, `observe_only_would_block`, `schema_unrecognised`, `source_unreadable`, `task_id_conflict`, `unmapped_outcome`, `no_sources` | + +When sources disagree, the stronger finding wins: +CAUGHT_ERROR > UNKNOWN > ESCALATED > FAILED > VERIFIED. A run in which the +guard blocked a save on the wrong record and the agent then saved the right +one is CAUGHT_ERROR: the row records the catch. + +Two more rules: + +- **A model never verifies.** An agent's own "finished" (compile-agent's + `finished`, a model's judgement) counts only when no deterministic source + says anything. Then it gives UNKNOWN (`completed_unverified`), or FAILED + when the agent says it gave up. It can't change a read-back, a guard + decision, a receipt or a person's answer. +- **VERIFIED needs an independent read-back.** A VERIFIED outcome resting on + a screen read-back is UNKNOWN (`screen_readback_only`). +- **A decline is not a catch.** A person declining an approval (a guard + `declined` block, an item-approval answer that isn't `approve`, a + compile-agent gate `refused_by_hold`, a P7 `GATE_REFUSED` with a record + check that shows no write) is ESCALATED (`person_declined`). It is + CAUGHT_ERROR only when deterministic evidence shows an actual error: a + refuted read-back, a differing field, a blocked wrong record. Those + outrank ESCALATED anyway. `approval_declined` is an approval nobody gave + in time (`request_expired`, `approval_wait_timed_out`). +- **A person who helped, then a verified save, is VERIFIED.** An approval + the person approved, a P7 gate the person approved, and a P6 exception the + person cleared (`continue` or `done_by_person`, decided) let the run go on: + none is a bucket source. The person's time is recorded in `human` (the + interval's `kind` keeps which: `approval`, `exception`, `second_factor`), + and the run's own result decides, so a save read back independently is + VERIFIED. An approval declined, an exception stopped (`skip`, `abort`, + `decline`), expired or not yet answered is ESCALATED, and ESCALATED + outranks VERIFIED. A task-ledger or item-approval question stays ESCALATED + (`question_asked`) even once answered: the ledger never reads the answer + text, so it can't tell whether the answer let the run go on or stopped it, + and a person's answer was part of the work either way. Approvals and + exceptions carry a closed decision (`approve`, `continue`, + `done_by_person`), which is why they can be cleared. +- **A field that differs is a caught error.** A field any source marks + `differs` (a guard row's `fields_differing`, a read-back) makes the run + CAUGHT_ERROR (`readback_field_differs`, or `readback_refuted` when the guard + says so), whatever else says VERIFIED, and the schema refuses a VERIFIED row + with `fields_differing` above 0. +- **"No write" needs evidence.** A crash, failure or timeout can come after a + request went out. `crashed_no_write` and `timed_out_no_write` are used only + where the source also shows nothing was sent (the agent guard's own save + events, the shadow guard's landed-write count). A bare status is UNKNOWN + (`write_unconfirmed`). + +### Engine outcomes on main + +| Source value | Bucket | +| --- | --- | +| `TransactionOutcome` VERIFIED | VERIFIED (with an independent read-back) | +| HALTED_BEFORE_EFFECT | ESCALATED | +| RECONCILIATION_REQUIRED, COMPLETED_UNVERIFIED, ROLLED_BACK, SAVED_AWAITING_CHECK | UNKNOWN | +| FAILED_PLATFORM, CANCELED, REJECTED_POLICY | FAILED | +| `ExecutionOutcome` (when no transaction outcome) VERIFIED / COMPLETED_UNVERIFIED / HALTED / FAILED / ROLLED_BACK | VERIFIED / UNKNOWN / UNKNOWN / UNKNOWN (`write_unconfirmed`) / UNKNOWN | +| verify-run receipt `outcome` verified / halted_before_effect / reconciliation_required / failed_platform / rolled_back_verified | VERIFIED / ESCALATED / UNKNOWN / FAILED / UNKNOWN | +| verify-run receipt `outcome` rejected_policy (the executor approved its own write, which landed) | UNKNOWN (`self_approved`) | +| verify-run `effect_verdict` REFUTED, with an effect row the store shows (`observed_effect` `present` or `conflicting`) | CAUGHT_ERROR | +| verify-run `effect_verdict` REFUTED with the effect `absent` (a halt before the save, a save that never landed) | the receipt `outcome` decides | +| `GuardVerdict` VERIFIED / REFUTED / RECONCILIATION_REQUIRED | VERIFIED / CAUGHT_ERROR / UNKNOWN | +| Guard block code `values_unread` (P5: the card couldn't show the values, so no one was asked) | ESCALATED (`values_unread`) | +| Guard block code `declined` / `request_expired`, `approval_wait_timed_out`, `approval_required` / P5's could-not-check codes (`baseline_unreadable`, `answer_malformed` ...) | ESCALATED (`person_declined`) / ESCALATED (`approval_declined`) / FAILED (`policy_rejected_no_write`; the save was blocked before it was sent) | +| Agent runner `RunOutcome.status` success / halt / refused / timeout / error | UNKNOWN / UNKNOWN / FAILED / UNKNOWN / UNKNOWN | +| Any other value | UNKNOWN (`unmapped_outcome`) | + +`tests/test_run_ledger_outcome.py` imports each enum and fails when a member +has no row in these tables. + +## Sources + +The ledger reads only an allowlist of file names +(`openadapt_flow.run_ledger.collect.ALLOWED_NAMES`): the producer files below, +`item-approval/request-*.json` and `answer-*.json`, `jobs/job-*.json`, +`runs/run-*.json`, `egress/timeline.jsonl`, and the run's own `task.json`, +`guard_task.json` and `verify.yaml`. A file named directly with `ledger add +FILE` may also be a `run-*.json` record or a `*result*.json` / +`*envelope*.json` dispatcher result. Every other file in a run directory is +never opened, hashed into the run digest, copied into a sidecar, exported or +pushed. That covers P3's `egress/pseudonyms.json`, which holds real values, +as well as screenshots, logs and stray files. `--config` takes only a guard +task or a `verify.yaml`; any other file is ignored. + +The collectors are in `openadapt_flow/run_ledger/collect.py`, one function +per source. Each reads files only and refuses a schema version it doesn't +know: the row is then UNKNOWN with `schema_unrecognised`. + +### Written by commands on main + +| File | Reads | Can't tell | +| --- | --- | --- | +| `summary.json` (`openadapt.agent-guard-run/v1`) and `guard_events.jsonl` | Verdict, blocked and would-block codes, holds, whether a save was sent, `ended`, `seconds`, `requests.save`. With no `guard_events.jsonl` and no `requests.save` of 0, nothing shows that no save went out: UNKNOWN (`write_unconfirmed`), never a no-write FAILED. | Wall-clock times, field names, the guarded agent's model usage | +| `effect-receipt.json` (verify-run, `openadapt.effect-receipt/v1`) | `outcome`, `effect_verdict`, `verification_tier`, `executor_kind` | Field names (effects are contract hashes) | +| `report.json` (compiled run; no schema field, recognised by shape) | `transaction_outcome` (else `execution_outcome`), `readback.checked_how`, `model_calls`, `est_model_cost_usd`, `started_at`, `total_ms`, `params` (committed only) | Tokens; field names | +| `receipt.json` (`openadapt.run-receipt/v2`) | `effect_assurance` (else `effect_tier_reached`), `receipt_digest`, `model_calls`, `est_cost_usd`, `duration_ms` | Anything about a halted run (only VERIFIED runs get one) | +| `openadapt-agent/runs/.json` (`openadapt-agent.run/v1`, wrap's run store) | `state`, `started_at`, `finished_at`, result `path`, `status`, `verified`, `receipt_outcome`, `model_calls`, `cost_usd`, `seconds` | Tokens, field names; a `running` record is a lost reply | +| `item-approval/request-*.json`, `answer-*.json` | `created_at`, `answered_at`, `decision`, `workflow_name` | An unanswered request's end (time is unknown) | +| `jobs/.json` (`openadapt.task-ledger/v1`) | Each question's `asked_at`, `answered_at`, `request_id` | Question text is never read | +| `run1.json` (compile-agent; `agent` is `AgentLedger.to_dict()`) or `agent_ledger.json` | `model_calls`, tokens, `cost_usd` and `usage_known`, `finished`, wall-clock `started_at`/`finished_at` when they are epochs, `gates` refusals (`refused_by_hold` is a person declining: `person_declined`; other refusals are `gate_refused`) | `summary`, `final_text` and per-call `actions` are never read | + +Wall-clock times come only from fields that hold them. The guard's `t` and +`seconds` and compile-agent's monotonic readings give durations, not times. +File modification times are never used. + +### Agent-control-plane sources + +The pieces of a control-plane pilot write these. The tests read committed +copies of their real (synthetic) files from the 2026-11-21 end-to-end run; +`tests/test_run_ledger_joins.py` is the join check. + +| Source | Keys read | Outcome | +| --- | --- | --- | +| Readiness run directory (P1): a folder with `run.json` (`openadapt.readiness-task-run/v1`) | `run.json` `task_id`, `status`, `agent_wall_s`, `landed_writes`, `usage`, `model_cost_usd`; `case.json` (`openadapt.readiness-case/v1`) `task_id`, `status`, `landed_writes`, `fields[].name`, `kind`, `human`, `proposed`; `proposed_write.json` `fields[].name`, `value`; `usage.json` `calls`, tokens, `model`, `cost_usd`; `egress.json` `model_calls`, `cost_usd`, `cost_source` | See the shadow table. Nothing else in the folder is read: a `guard_ledger_row.json` or `guard_events.jsonl` there belongs to the shadow hold. | +| `guard_ledger_row.json` (`openadapt.guard-ledger-row/v1`, P5) | `task_id`, `fields_checked[]`, `fields_differing[]` (names), `approval_opened_at`, `approval_decided_at`, `readback_tier` | None: the row is never a bucket source (`verdict`, `guard_verdict` and `verdict_reason` aren't read). The guard's `summary.json` and the read-back decide. A differing field shows as `differs`. | +| P7 fallback `result.json` (`/fallback///`, with `replay`) or a `wrap-dispatch --result` envelope (with `outcome` and `fallback`); no schema field, recognised by `path`, `status`, `verified` and those keys | `status`, `verified`, `path`, `seconds`, `model_calls`, `cost_usd`, `usage_known`, the policy record (`replay.fallback`, or the envelope's `fallback`) `task_record_check`, `replay.program.receipt_outcome`, `compile.run1.gates[].at` / `decision`, `compile.task_key`, `request_id` | See the fallback table. The envelope's `outcome` is not read. The agent attempt under `run/` is not read again. | +| `$OPENADAPT_HOME/exceptions//` (P6): `card-.json` (`openadapt.exception-card/v1`), `answer-.json` (`openadapt.exception-answer/v1`) | card `task_id`, `kind`, `opened_at`, `card_id`; answer `card_id`, `kind`, `opened_at`, `decided_at` | ESCALATED: `second_factor` for that kind, else `exception_card`. An expired card (`decided_at: null`) or one not answered yet makes the person's time unknown. A card for another task id makes the row `task_id_conflict`. | +| `flight.json` (`openadapt.flight-run/v1`, P3) | `task_id`, `executor_label`, `started_at`, `ended_at`, `model`, `gate_events[].kind` | A `held` with no later `allowed` or `refused`: ESCALATED (`gate_held`). A `refused`: CAUGHT_ERROR (`gate_refused`). | +| A lone `proposed_write.json` (outside a readiness folder) | `task_id`, `fields[].name`, `value` | UNKNOWN (`shadow_not_compared`): nothing compared it. | + +P6's run reference is the operator's `exceptions serve --run-ref` (or a +random `mcp-...`); no run directory names it. `ledger add --run-ref REF` +reads `exceptions/REF/`. Without it no exception folder is read: nothing +in a run directory says which folder is its own. + +`answer` and signatures in exception files, card summaries, `approver_kind`, +`hold_ms` and `diff_path` in a guard row, and `timeline_path` in a flight file +are not read. + +#### Shadow runs (J1) + +A shadow run holds every save, so it is never VERIFIED. The person's own +save is the real one. + +| Case | Bucket (reason) | +| --- | --- | +| `landed_writes` > 0 or `FAILED_SCOPE` (a write reached the app) | UNKNOWN (`shadow_write_landed`) | +| Run `EXTRA_TARGET` (a write from, or a target outside, the guarded tab) | UNKNOWN (`shadow_extra_target`) | +| Run `EGRESS_REFUSED`, or `run.json` `egress.refused: true` | UNKNOWN (`egress_refused`). A healthy `--egress blocked` run also writes `mode: blocked`; only `refused` tells them apart. | +| `WRONG_RECORD` | CAUGHT_ERROR (`shadow_wrong_record`) | +| `MISMATCHED` | CAUGHT_ERROR (`shadow_field_mismatch`) | +| `MATCHED` | ESCALATED (`shadow_matched`): a person did the step; not a catch | +| `NOT_COMPARABLE`, `NOT_CHECKED`, no `case.json` | UNKNOWN (`shadow_not_compared`) | +| No proposal, run `TIMEOUT` / `NO_WRITE_HELD`, `landed_writes: 0` | FAILED (`shadow_timed_out` / `shadow_no_proposal`) | +| No proposal, run `AGENT_ERROR` (set before the guard counted anything) | UNKNOWN (`shadow_agent_error`) | + +Every shadow reason is a `shadow_*` one (or `egress_refused`), so a readiness +trial never shows as a production failure. + +Fields come from `case.json`: `matched` is matched; `mismatched`, `missing`, +`extra` and `wrong_record` differ; `uncompared` is not checked. A proposed +field the case doesn't list (an expected-record field that matched, or an +ignored one) is `not_checked`. Values go to the sidecar only. Duration is +`agent_wall_s`. Model usage is `run.json` `usage` (else `usage.json`), +`reported`; an `egress.json` (else the copy in `run.json` `egress`, unless +refused) replaces calls and cost with the proxy's count (`metered` when its +`cost_source` says so). + +#### Fallback runs (J5) + +| `status` (`path: agent_fallback`) | Bucket (reason) | +| --- | --- | +| VERIFIED with P7's `verified` and a record check that is `readable: true` and passed | VERIFIED (`readback_verified`, independent: the record check read the system of record before and after) | +| VERIFIED, but the record check isn't `readable: true` (a failed read, or an older check without the flag) | UNKNOWN (`reconciliation_required`) | +| GATE_REFUSED, record check `readable: true` with no write | ESCALATED (`person_declined`) | +| GATE_REFUSED or COST_CAP_EXCEEDED, record check missing, not `readable: true`, or showing a write | UNKNOWN (`write_unconfirmed`). An unreadable store also reports zero counts, so zeros alone prove nothing. | +| COST_CAP_EXCEEDED, no write | FAILED (`policy_rejected_no_write`) | +| GATE_NOT_PROVED | UNKNOWN (`self_approved`) | +| RECONCILIATION_REQUIRED | UNKNOWN (`reconciliation_required`) | +| FALLBACK_GATE_UNATTENDED, FALLBACK_NO_AGENT, FALLBACK_COST_UNBOUNDED, FALLBACK_REQUEST_REUSED (agent not started) | ESCALATED (`halted_before_effect`) when the program halted before effect, else UNKNOWN (`write_unconfirmed`) | +| Anything else | UNKNOWN (`unmapped_outcome`), or CAUGHT_ERROR (`readback_refuted`) when the record check shows an unverified write | + +An item-approval gate records `fallback.gate_answers` (request ids, decisions, +signer) but no times; its request and answer files sit in +`//item-approval/` (`wrap-dispatch +--fallback-approvals`). `ledger add --approvals DIR` reads them there: the +person's time runs from the request's `created_at` to the answer's +`answered_at`. Without `--approvals`, a folder named exactly the fallback's +request id near the envelope or result (bounded search) is used, and only +the requests `gate_answers` names with the same `request_sha256` are read; +an answer bound to another request is UNKNOWN (`source_unreadable`). With +none found the time is unknown. A `result.json`'s +record check names the fields of the new record; the row keeps those the +run's config (`--config verify.yaml`) declares, `matched` when the check is +readable and passed. For an envelope, which carries no field names, the +fallback's own `result.json` (a folder named the fallback request id, with a +matching `replay.fallback.request_id`) gives them, and the task's confirmed +`//compiled/verify.yaml` declares which to keep. + +On `path: program` or `held` the envelope is read like a wrap result; +`NO_ADMITTED_PROGRAM` is FAILED (`policy_rejected_no_write`, nothing ran). +A fallback gate in `result.json` keeps one time, not an opened/decided pair, +so a person's time on it is unknown (`null`), not zero. The envelope keeps +no gate times at all, so its row's time is unknown too. A wrap run record +(`openadapt-agent.run/v1`) whose result `path` is `agent_fallback` is read +like an agent's first run, but `verified: true` counts only with P7's final +read, `result.fallback.task_record_check` (`result.record_check` on older +records), being `readable: true` and passed; without one it is UNKNOWN +(`reconciliation_required`). + +### Merging sources + +- **Model usage:** metered beats reported beats unknown; the first source + wins within a rank. Usage is never added across sources, because two files + often describe the same calls. +- **Times:** the earliest `started_at` and the latest `ended_at`. Without + both, the first source's duration. +- **Intervals:** one per approval request, even when several files mention it. +- **Fields:** by name, the worst check wins (`differs`, then `not_checked`, + then `matched`). +- **Read-back tier:** the weakest one. +- **Task id:** two different task ids make the row UNKNOWN + (`task_id_conflict`). + +## The store + +`$OPENADAPT_HOME/ledger/rows.jsonl` (default `~/.openadapt/ledger`), mode +0600. Each line is `{"row": ..., "run_digest": ..., "run_ref": ..., +"added_at": ..., "declared_fields": [...]}`. `declared_fields` are the field +names the run's own config declares (see `export` below); they stay beside +the row, not in it. `run_digest` hashes the source files' paths and bytes, and +`run_ref` hashes the run's path. A second `add` of an unchanged run does +nothing (dedupe on task id and run digest). A run whose files changed (an +approval answered after the first `add`) gets a new row; `summary`, `export` +and `push` use the newest row per run. Writes go through a temporary file and +a rename under an exclusive lock (`flock` on POSIX, `msvcrt.locking` on +Windows). On Windows the files rely on the user profile's ACL, since there is +no POSIX mode to set. + +## Commands + +| Command | Does | +| --- | --- | +| `ledger add RUN_DIR [--task-type T] [--task-id ID] [--run-ref REF] [--config FILE ...]` | Reads the run and appends its row. `RUN_DIR` can also be one wrap run record or one `wrap-dispatch` envelope. `--run-ref` names the run's P6 exception folder. `--config` names the run's guard task JSON or `verify.yaml` when they aren't in `RUN_DIR`. | +| `ledger list [--json]` | Every row. | +| `ledger show ROW_ID [--show-values]` | One row; with `--show-values`, also the sidecar's values. | +| `ledger summary [--since ISO] [--task-type T] [--json]` | Runs per outcome, a person's minutes, model cost, median duration. Rows whose time or cost is unknown are counted as unknown, not as zero. | +| `ledger export --out FILE` | Value-free JSONL, written owner-only (0600). Always requires openadapt-privacy's text scrubber (`--require-scrubber` is kept for old scripts). Export keeps `sources`; each path part gets the same scrubber check as the labels, and a part the scrubber would rewrite leaves as an opaque `src-<16 hex>` (the same keyed digest as task ids). The local row keeps the real paths. | +| `ledger push [--host URL] [--dry-run]` | POSTs each row without `sources`, as `openadapt.agent-run-summary/v1`, to `/api/runs/ingest-agent-run` with `OPENADAPT_API_KEY`. | + +`export` and `push` screen each row and refuse a row when: + +- a value from any local sidecar appears in what they would send; +- a row has a key outside its schema, or fails validation; +- openadapt-privacy's text scrubber is installed and would rewrite a label + (task id, task type, executor label or field name), or can't run (for + example, its spaCy model is missing). Without a working scrubber, `export` + and `push` refuse everything; only `push --dry-run` warns and prints. + One exemption: a field name the run's own config declared at `add` time. + Presidio rewrites the name `patient_id` to ``; a declared + name is a form's identifier, not a value. Declared means: a guard task's + `expected_record` and `intended_fields` keys (`openadapt.guard-task/v1`, + `task.json` or `guard_task.json` in the run, or `--config`; only a task + whose `task_id` is the run's), a + `verify.yaml`'s effect `match` keys (a `verify.proposed.yaml` doesn't + count), and a readiness `case.json`'s reference fields (not its `extra` + ones; and for `FAILED_SCOPE` or a case with no proposal, whose field rows + compare never built, nothing). Any other name the scrubber would rewrite still refuses, and an + entry added before this rule exempts nothing. + A task id is never exempt: a caller can choose one (a wrap-dispatch + request id is the calling agent's). When the scrubber would rewrite it, the + row leaves with an opaque `tid-<16 hex>` instead: HMAC-SHA256 of the id + under a per-install key in `$OPENADAPT_HOME/ledger/task-id.key` (0600), so + the same task still groups together in Cloud and the text stays on this + computer. The local row keeps the real id. + +Cloud receives `null` for every value the sources don't give +(`started_at`, `ended_at`, `duration_s`, the `model` counts and cost, +`readback_tier`, `intervention_s`). Real `push --dry-run` output over the +synthetic fixtures is committed at +`packages/types/tests/fixtures/agent_run_summary_v1_examples.jsonl`; a test +validates it against `AgentRunSummaryV1`'s JSON Schema. + +A refused row stays local and the rest still go: each refused row is listed +on stderr with its reason, and the command exits 2. A scrubber that can't run +refuses everything. + +`push` also refuses before anything else when `OPENADAPT_API_KEY` isn't set +or openadapt-privacy's text scrubber isn't available or can't run (rows +leave this computer, so it always runs the label check; `push --dry-run`, +which sends nothing, only warns), +and sends only to a destination the hosted destination policy accepts (the +same check `ingest-report` uses). + +The task view also lists the verb as `openadapt inspect ledger` +(`openadapt verify ledger` is the protected-write ledger, a different thing). + +The verb needs an openadapt-types release that has +`openadapt_types.run_ledger`. Building the parser doesn't import it, so an +install with an older openadapt-types still starts; `ledger` itself then +says to upgrade openadapt-types. diff --git a/packages/flow/docs/commands/07-proof/ledger.md b/packages/flow/docs/commands/07-proof/ledger.md new file mode 100644 index 0000000000..30ae02be0b --- /dev/null +++ b/packages/flow/docs/commands/07-proof/ledger.md @@ -0,0 +1 @@ +Per-run accounting rows for any executor: outcome (VERIFIED, ESCALATED, CAUGHT_ERROR, FAILED, UNKNOWN), a person's minutes, model cost, fields checked; no record values diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 7e74f59283..1067753f66 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13157,14 +13157,14 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: from openadapt_flow.cli_admit import register_admit_parser from openadapt_flow.cli_api import register_api_parser from openadapt_flow.cli_check import register_check_parser + from openadapt_flow.cli_deferred import register_deferred_parser + from openadapt_flow.run_ledger.cli import register as _register_ledger register_admit_parser(sub) register_check_parser(sub) register_api_parser(sub) - - from openadapt_flow.cli_deferred import register_deferred_parser - register_deferred_parser(sub) + _register_ledger(sub) from openadapt_flow.cli_undo import register as _register_undo diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index a0bac30176..ec2466072d 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -71,6 +71,7 @@ "jit": "compile --jit", "known-ids": "verify known-ids", "learn": "teach --learn", + "ledger": "inspect ledger", "lint": "inspect lint", "local-seal": "verify local-seal", "login": "setup login", diff --git a/packages/flow/openadapt_flow/run_ledger/__init__.py b/packages/flow/openadapt_flow/run_ledger/__init__.py new file mode 100644 index 0000000000..31af2127b2 --- /dev/null +++ b/packages/flow/openadapt_flow/run_ledger/__init__.py @@ -0,0 +1,70 @@ +"""Per-run accounting ledger for any executor. + +``openadapt-flow ledger add RUN_DIR`` reads the files a run already left +behind (agent guard, verify-run, a compiled run's report and receipt, wrap's +run store, item approvals, task-ledger questions, compile-agent's agent +ledger, and the contract files of the shadow, flight, gate and exception +pieces) and appends one value-free ``openadapt.run-ledger/v1`` row to +``$OPENADAPT_HOME/ledger/rows.jsonl``. The values a person may need to see +(what was meant to be saved, what was saved, the difference, and the inputs +salt) go to a 0600 sidecar beside the store, never into the row. + +* :mod:`.outcome`: the VERIFIED / ESCALATED / CAUGHT_ERROR / FAILED / UNKNOWN + rule. +* :mod:`.collect`: one reader per source; files only. +* :mod:`.store`: the append-only store, its private sidecars, and + :func:`build_row`. +* :mod:`.cli`: ``openadapt-flow ledger``. + +See ``docs/RUN_LEDGER.md``. Nothing here edits a producer's files, calls a +model, or uses the network except ``ledger push``. +""" + +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + +if TYPE_CHECKING: + from openadapt_flow.run_ledger.collect import Collected, collect + from openadapt_flow.run_ledger.outcome import Signal, decide + from openadapt_flow.run_ledger.store import ( + LedgerStore, + PrivateSidecar, + build_row, + ledger_home, + ) + +# Loaded on first use so that ``openadapt-flow``'s parser can register the +# ``ledger`` verb (``from openadapt_flow.run_ledger.cli import register``) +# without importing the schema in openadapt-types. +_EXPORTS = { + "Collected": "collect", + "collect": "collect", + "Signal": "outcome", + "decide": "outcome", + "LedgerStore": "store", + "PrivateSidecar": "store", + "build_row": "store", + "ledger_home": "store", +} + + +def __getattr__(name: str) -> Any: + module = _EXPORTS.get(name) + if module is None: + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + from importlib import import_module + + return getattr(import_module(f"{__name__}.{module}"), name) + + +__all__ = [ + "Collected", + "LedgerStore", + "PrivateSidecar", + "Signal", + "build_row", + "collect", + "decide", + "ledger_home", +] diff --git a/packages/flow/openadapt_flow/run_ledger/cli.py b/packages/flow/openadapt_flow/run_ledger/cli.py new file mode 100644 index 0000000000..f43ee12fbe --- /dev/null +++ b/packages/flow/openadapt_flow/run_ledger/cli.py @@ -0,0 +1,649 @@ +"""``openadapt-flow ledger``: one accounting row per run, for any executor. + + openadapt-flow ledger add RUN_DIR [--task-type T] [--task-id ID] [--run-ref REF] [--approvals DIR] + [--config TASK_OR_VERIFY_FILE ...] + openadapt-flow ledger list [--json] + openadapt-flow ledger show ROW_ID [--show-values] + openadapt-flow ledger summary [--since ISO] [--task-type T] [--json] + openadapt-flow ledger export --out FILE + openadapt-flow ledger push [--host URL] [--dry-run] + +``add`` reads the run's files and appends a value-free row. ``show +--show-values`` is the only command that prints values, and only from the +local private sidecar. ``export`` and ``push`` send the newest row per run, +value-free, and refuse if any value from a private sidecar appears in what +would leave. See ``docs/RUN_LEDGER.md``. +""" + +from __future__ import annotations + +import argparse +import json +import os +import statistics +import sys +from dataclasses import dataclass +from datetime import datetime +from pathlib import Path +from typing import TYPE_CHECKING, Any, Callable, Optional, Sequence + +if TYPE_CHECKING: + from openadapt_flow.run_ledger.store import LedgerStore + +API_KEY_ENV = "OPENADAPT_API_KEY" +INGEST_PATH = "/api/runs/ingest-agent-run" +_OUTCOMES = ("VERIFIED", "ESCALATED", "CAUGHT_ERROR", "FAILED", "UNKNOWN") + + +class LedgerRefused(Exception): + """An export or push that would let a value leave. Nothing was written.""" + + +def register(sub: argparse._SubParsersAction) -> None: + parser = sub.add_parser( + "ledger", + help="Per-run accounting rows (outcome, time, cost, fields) for any executor", + allow_abbrev=False, + ) + parser.add_argument( + "--home", + default=None, + help="OpenAdapt home (default: $OPENADAPT_HOME, else ~/.openadapt)", + ) + verbs = parser.add_subparsers(dest="ledger_cmd", required=True) + + add = verbs.add_parser( + "add", help="Read a run's files and append its row", allow_abbrev=False + ) + add.add_argument("run", help="Run directory (or one run record file)") + add.add_argument("--task-type", default=None, help="Operator label, e.g. intake") + add.add_argument("--task-id", default=None, help="Override the task id") + add.add_argument( + "--run-ref", + default=None, + help="The run's exception-queue reference (exceptions serve --run-ref); " + "its cards and answers are read from $OPENADAPT_HOME/exceptions/REF", + ) + add.add_argument( + "--approvals", + default=None, + help="A P7 fallback's item-approval folder root " + "(wrap-dispatch --fallback-approvals); each gate's request and answer " + "times are read from DIR//item-approval", + ) + add.add_argument( + "--config", + action="append", + default=[], + help="The run's guard task JSON or verify.yaml, when not in RUN_DIR; " + "its field names may leave in export and push (repeatable)", + ) + add.set_defaults(func=cmd_add) + + lst = verbs.add_parser("list", help="List rows", allow_abbrev=False) + lst.add_argument("--json", action="store_true", help="One JSON row per line") + lst.set_defaults(func=cmd_list) + + show = verbs.add_parser("show", help="Show one row", allow_abbrev=False) + show.add_argument("row_id") + show.add_argument( + "--show-values", + action="store_true", + help="Also print the field values from the local private sidecar", + ) + show.set_defaults(func=cmd_show) + + summary = verbs.add_parser( + "summary", + help="Counts per outcome, minutes, cost, duration", + allow_abbrev=False, + ) + summary.add_argument("--since", default=None, help="ISO date or time") + summary.add_argument("--task-type", default=None) + summary.add_argument("--json", action="store_true") + summary.set_defaults(func=cmd_summary) + + export = verbs.add_parser( + "export", help="Write value-free rows as JSONL", allow_abbrev=False + ) + export.add_argument("--out", required=True, help="Output file") + export.add_argument( + "--require-scrubber", + action="store_true", + help="Kept for old scripts: export always requires openadapt-privacy's " + "text scrubber", + ) + export.set_defaults(func=cmd_export) + + push = verbs.add_parser( + "push", + help=f"Send value-free run summaries to OpenAdapt Cloud ({API_KEY_ENV})", + allow_abbrev=False, + ) + push.add_argument("--host", default=None, help="Cloud origin") + push.add_argument( + "--dry-run", action="store_true", help="Print what would be sent; send nothing" + ) + push.set_defaults(func=cmd_push) + + +# -- add / list / show ------------------------------------------------------------------ + + +def _store(args: argparse.Namespace) -> LedgerStore: + # Imported here so that building the parser (``--version``, ``--help``) + # never needs the ledger schema: an install whose openadapt-types predates + # it still starts, and only ``ledger`` itself refuses. + try: + from openadapt_flow.run_ledger.store import LedgerStore + except ImportError as exc: + raise SystemExit( + "ledger: this install's openadapt-types has no run ledger schema " + f"({exc}); upgrade openadapt-types" + ) from None + return LedgerStore(args.home) + + +def cmd_add(args: argparse.Namespace) -> int: + from pydantic import ValidationError + + run = Path(args.run) + if not run.exists(): + print(f"ledger add: {run} does not exist", file=sys.stderr) + return 2 + try: + result = _store(args).add( + run, + task_type=args.task_type, + task_id=args.task_id, + run_ref=args.run_ref, + config=tuple(args.config), + approvals=args.approvals, + ) + except ValidationError as exc: + bad = sorted({str(e["loc"][0]) for e in exc.errors() if e.get("loc")}) + print( + "ledger add: refused a value that isn't a closed label: " + + ", ".join(bad or ["row"]), + file=sys.stderr, + ) + return 2 + except ValueError as exc: # a --run-ref that isn't a run reference + print(f"ledger add: {exc}", file=sys.stderr) + return 2 + row = result.row + state = "added" if result.added else "already in the ledger" + print( + f"{row.row_id} {row.outcome.value} ({row.outcome_reason}) " + f"task {row.task_id} {state}" + ) + return 0 + + +def _money(value: Optional[float]) -> str: + return "-" if value is None else f"${value:.4f}" + + +def _secs(value: Optional[float]) -> str: + return "-" if value is None else f"{value:.1f}s" + + +def cmd_list(args: argparse.Namespace) -> int: + rows = _store(args).rows() + if args.json: + for row in rows: + print(json.dumps(row.to_json(), sort_keys=True)) + return 0 + if not rows: + print("No rows yet. Add one with: openadapt-flow ledger add RUN_DIR") + return 0 + for row in rows: + print( + f"{row.row_id} {row.outcome.value:<12} {row.outcome_reason:<26} " + f"{row.task_type:<12} {row.task_id:<24} {_secs(row.duration_s):>8} " + f"{_money(row.model.cost_usd):>10}" + ) + return 0 + + +def cmd_show(args: argparse.Namespace) -> int: + store = _store(args) + try: + row = store.find(args.row_id) + except ValueError: + row = None + if row is None: + print(f"ledger show: no row {args.row_id}", file=sys.stderr) + return 2 + doc: dict[str, Any] = {"row": row.to_json()} + if args.show_values: + sidecar = store.sidecar(row.row_id) + doc["values"] = (sidecar or {}).get("fields") or {} + print(json.dumps(doc, indent=2, sort_keys=True)) + return 0 + + +# -- summary ---------------------------------------------------------------------------- + + +def _since(text: Optional[str]) -> Optional[datetime]: + if not text: + return None + moment = datetime.fromisoformat(text.replace("Z", "+00:00")) + if moment.tzinfo is None: + from datetime import timezone + + moment = moment.replace(tzinfo=timezone.utc) + return moment + + +def summarize( + rows: Sequence[Any], + *, + since: Optional[datetime] = None, + task_type: Optional[str] = None, +) -> dict[str, Any]: + """Counts per outcome, a person's minutes, model cost, median duration. + + A row whose time or cost is unknown is counted as unknown, never as 0. + A row with no ``started_at`` is kept by ``since`` only if it has none to + compare (it is reported in ``undated``). + """ + + picked = [] + undated = 0 + for row in rows: + if task_type is not None and row.task_type != task_type: + continue + if since is not None: + if row.started_at is None: + undated += 1 + continue + if datetime.fromisoformat(row.started_at.replace("Z", "+00:00")) < since: + continue + picked.append(row) + counts = {name: 0 for name in _OUTCOMES} + for row in picked: + counts[row.outcome.value] += 1 + minutes = [ + r.human.intervention_s for r in picked if r.human.intervention_s is not None + ] + costs = [r.model.cost_usd for r in picked if r.model.cost_usd is not None] + durations = [r.duration_s for r in picked if r.duration_s is not None] + return { + "rows": len(picked), + "outcomes": counts, + "intervention_minutes": round(sum(minutes) / 60.0, 2), + "intervention_unknown_rows": len(picked) - len(minutes), + "model_cost_usd": round(sum(costs), 6), + "model_cost_unknown_rows": len(picked) - len(costs), + "median_duration_s": round(statistics.median(durations), 3) + if durations + else None, + "duration_unknown_rows": len(picked) - len(durations), + "fields_differing": sum(r.fields_differing for r in picked), + "undated_rows_skipped": undated, + } + + +def cmd_summary(args: argparse.Namespace) -> int: + try: + since = _since(args.since) + except ValueError: + print("ledger summary: --since must be an ISO date or time", file=sys.stderr) + return 2 + report = summarize(_store(args).latest(), since=since, task_type=args.task_type) + if args.json: + print(json.dumps(report, indent=2, sort_keys=True)) + return 0 + counts = report["outcomes"] + print(f"{report['rows']} runs") + for name in _OUTCOMES: + print(f" {name:<13}{counts[name]}") + unknown_m = report["intervention_unknown_rows"] + print( + f"A person's time: {report['intervention_minutes']} min" + + (f" (unknown for {unknown_m} runs)" if unknown_m else "") + ) + unknown_c = report["model_cost_unknown_rows"] + print( + f"Model cost: ${report['model_cost_usd']:.4f}" + + (f" (unknown for {unknown_c} runs)" if unknown_c else "") + ) + median = report["median_duration_s"] + print("Median duration: " + ("-" if median is None else f"{median}s")) + return 0 + + +# -- leaving this computer ---------------------------------------------------------------- + + +def _label_values(doc: dict[str, Any]) -> list[tuple[str, str]]: + labels = [ + ("task_id", doc["task_id"]), + ("task_type", doc["task_type"]), + ("executor_label", doc["executor_label"]), + ] + labels += [ + ("fields_written.name", f["name"]) for f in doc.get("fields_written", []) + ] + return labels + + +@dataclass +class Screened: + """What may leave, and each row that may not (with why).""" + + lines: list[str] + refused: list[tuple[str, str]] + + +def screen_rows( + store: LedgerStore, + *, + summary: bool, + scrubber: Optional[Any] = None, +) -> Screened: + """The newest row per run, serialised, each after both guards. + + 1. Every value in every local sidecar is looked for in the row; a hit + refuses that row. + 2. When a text scrubber is given, each label (task id, task type, + executor label, field names) must come back from it unchanged; a label + the scrubber would rewrite looks like personal data and refuses that + row. The exemption is a field name the run's own task, verify or + readiness files declared (kept beside the row at ``add`` time): + Presidio rewrites the name ``patient_id``, but a declared name is a + form's identifier, not a value. A task id the scrubber would rewrite + leaves as an opaque ``tid-<16 hex>`` instead (:func:`_screen_one`). + + A refused row is left out; the others still go. A scrubber that can't + run at all refuses everything (:class:`LedgerRefused`). + """ + + from openadapt_types.run_ledger import AgentRunSummaryV1, RunLedgerRowV1 + + values = store.sidecar_values() + out = Screened([], []) + for entry in store.latest_entries(): + row = RunLedgerRowV1.model_validate(entry["row"]) + reason = _screen_one( + entry, + row, + opaque=store.opaque_task_id, + summary=summary, + scrubber=scrubber, + values=values, + models=(AgentRunSummaryV1, RunLedgerRowV1), + ) + if isinstance(reason, str): + out.refused.append((row.row_id, reason)) + else: + out.lines.append(reason[0]) + return out + + +def _screen_one( + entry: dict[str, Any], + row: Any, + *, + opaque: Callable[[str], str], + summary: bool, + scrubber: Optional[Any], + values: list[str], + models: tuple[Any, Any], +) -> str | tuple[str]: + """``(line,)`` for a row that may leave, else the reason it may not. + + A task id the scrubber would rewrite is replaced by an opaque + ``tid-<16 hex>`` (:meth:`LedgerStore.opaque_task_id`): a caller can + choose a task id (a wrap-dispatch request id, say), so its text never + leaves, while the same task still groups together. Every other label + the scrubber would rewrite refuses the row, except a field name the + run's own config declared. + """ + + declared = set(entry.get("declared_fields") or []) + doc = row.summary().to_json() if summary else row.to_json() + model = models[0] if summary else models[1] + allowed = {f.alias or name for name, f in model.model_fields.items()} + if set(doc) - allowed: + return "a key outside the contract" + model.model_validate(doc) + if scrubber is not None: + for where, label in _label_values(doc): + if where == "fields_written.name" and label in declared: + continue # a declared field name (patient_id): not a value + try: + scrubbed = scrubber.scrub_text(label) + except Exception as exc: # a scrubber that can't run refuses all + raise LedgerRefused( + f"the text scrubber could not run ({type(exc).__name__}); " + "nothing was written" + ) from exc + if scrubbed != label and where == "task_id": + doc["task_id"] = opaque(label) + elif scrubbed != label: + return f"the scrubber would rewrite its {where}" + if "sources" in doc: + # Export keeps the source paths: each path part gets the same + # check, and a part the scrubber would rewrite leaves as an + # opaque ``src-<16 hex>`` (the same keyed digest as task ids). + doc["sources"] = [ + "/".join( + _opaque_part(part, scrubber, opaque) for part in path.split("/") + ) + for path in doc["sources"] + ] + line = json.dumps(doc, sort_keys=True) + if any(value in line for value in values): + return "it contains a value from a private sidecar" + return (line,) + + +def _opaque_part(part: str, scrubber: Any, opaque: Callable[[str], str]) -> str: + try: + scrubbed = scrubber.scrub_text(part) + except Exception as exc: # a scrubber that can't run refuses all + raise LedgerRefused( + f"the text scrubber could not run ({type(exc).__name__}); " + "nothing was written" + ) from exc + if scrubbed == part: + return part + return "src-" + opaque(part)[len("tid-") :] + + +def outbound_lines( + store: LedgerStore, + *, + summary: bool, + scrubber: Optional[Any] = None, +) -> list[str]: + """:func:`screen_rows`, strict: the first refused row refuses all.""" + + screened = screen_rows(store, summary=summary, scrubber=scrubber) + if screened.refused: + row_id, reason = screened.refused[0] + raise LedgerRefused(f"row {row_id}: {reason}") + return screened.lines + + +def _print_refused(verb: str, refused: list[tuple[str, str]]) -> None: + for row_id, reason in refused: + print(f"ledger {verb}: refused row {row_id}: {reason}", file=sys.stderr) + + +def _scrubber(require: bool) -> Optional[Any]: + from openadapt_flow.privacy import PrivacyNotAvailable, get_text_scrubber + + try: + scrubber = get_text_scrubber() + except PrivacyNotAvailable as exc: + raise LedgerRefused(str(exc)) from exc + if scrubber is None and require: + raise LedgerRefused( + "openadapt-privacy's text scrubber isn't available (--require-scrubber)" + ) + if scrubber is None: + print( + "ledger: openadapt-privacy's text scrubber isn't available; rows were " + "checked against the local value sidecars only", + file=sys.stderr, + ) + return scrubber + + +def _write_0600(path: Path, data: bytes) -> None: + """Write ``path`` owner-only (0600), through a temporary file.""" + + import tempfile + + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-") + try: + if hasattr(os, "fchmod"): + os.fchmod(fd, 0o600) + with os.fdopen(fd, "wb") as handle: + handle.write(data) + os.replace(tmp, path) + finally: + if os.path.exists(tmp): + os.unlink(tmp) + + +def cmd_export(args: argparse.Namespace) -> int: + try: + # Rows leave the ledger: a working text scrubber is always required. + scrubber = _scrubber(True) + screened = screen_rows(_store(args), summary=False, scrubber=scrubber) + except LedgerRefused as exc: + print(f"ledger export: refused: {exc}", file=sys.stderr) + return 2 + out = Path(args.out) + out.parent.mkdir(parents=True, exist_ok=True) + lines = screened.lines + _write_0600(out, "".join(line + "\n" for line in lines).encode("utf-8")) + print(f"Wrote {len(lines)} rows to {out}") + _print_refused("export", screened.refused) + # A refused row stays local; the exit status says some didn't go. + return 2 if screened.refused else 0 + + +Poster = Callable[[str, dict[str, str], dict[str, Any]], int] + + +def _post(url: str, headers: dict[str, str], payload: dict[str, Any]) -> int: + import httpx + + response = httpx.post( + url, headers=headers, json=payload, timeout=30.0, follow_redirects=False + ) + return response.status_code + + +def push( + store: LedgerStore, + *, + host: Optional[str] = None, + dry_run: bool = False, + poster: Poster = _post, + environ: Optional[dict[str, str]] = None, + scrubber: Optional[Any] = None, + refused: Optional[list[tuple[str, str]]] = None, +) -> list[dict[str, Any]]: + """POST each newest row (minus ``sources``) to ``/api/runs/ingest-agent-run``. + + Refused, before anything else, when ``OPENADAPT_API_KEY`` isn't set. + The destination must pass the same policy ``ingest-report`` uses. A row + :func:`screen_rows` refuses isn't sent; it is appended to ``refused`` + (``(row_id, reason)``) when a list is given. + """ + + env = os.environ if environ is None else environ + key = env.get(API_KEY_ENV, "").strip() + if not key and not dry_run: + raise LedgerRefused(f"{API_KEY_ENV} isn't set; nothing was sent") + if scrubber is None and not dry_run: + # Fail closed: without openadapt-privacy's scrubber no label check + # ran, so nothing is sent. + raise LedgerRefused( + "openadapt-privacy's text scrubber isn't available; nothing was sent" + ) + screened = screen_rows(store, summary=True, scrubber=scrubber) + if refused is not None: + refused.extend(screened.refused) + payloads = [json.loads(line) for line in screened.lines] + if dry_run: + return payloads + from openadapt_flow.hosted import ( + HostedError, + resolve_destination_policy, + resolve_host, + ) + + try: + origin = resolve_host(host) + resolve_destination_policy(origin) + except HostedError as exc: + raise LedgerRefused(f"destination refused: {exc}") from exc + url = origin + INGEST_PATH + headers = {"Authorization": f"Bearer {key}"} + results = [] + for payload in payloads: + try: + status = poster(url, headers, payload) + except Exception: # noqa: BLE001 - a transport error never echoes the key + status = 0 + results.append({"row_id": payload["row_id"], "status": status}) + return results + + +def cmd_push(args: argparse.Namespace) -> int: + try: + if not args.dry_run and not os.environ.get(API_KEY_ENV, "").strip(): + raise LedgerRefused(f"{API_KEY_ENV} isn't set; nothing was sent") + refused: list[tuple[str, str]] = [] + results = push( + _store(args), + host=args.host, + dry_run=args.dry_run, + # Rows leave this computer: a working text scrubber is required, + # as with ``export --require-scrubber``. A dry run sends nothing. + scrubber=_scrubber(not args.dry_run), + refused=refused, + ) + except LedgerRefused as exc: + print(f"ledger push: refused: {exc}", file=sys.stderr) + return 2 + if args.dry_run: + for payload in results: + print(json.dumps(payload, sort_keys=True)) + _print_refused("push", refused) + return 2 if refused else 0 + failed = [r for r in results if r["status"] not in (200, 201, 202)] + total = len(results) + len(refused) + print(f"Sent {len(results) - len(failed)} of {total} rows") + for item in failed: + print(f" {item['row_id']}: HTTP {item['status']}", file=sys.stderr) + _print_refused("push", refused) + return 2 if refused else 1 if failed else 0 + + +def main(argv: Optional[Sequence[str]] = None) -> int: + parser = argparse.ArgumentParser(prog="openadapt-flow", allow_abbrev=False) + register(parser.add_subparsers(dest="command", required=True)) + args = parser.parse_args(argv) + return int(args.func(args)) + + +__all__ = [ + "API_KEY_ENV", + "INGEST_PATH", + "LedgerRefused", + "main", + "outbound_lines", + "screen_rows", + "push", + "register", + "summarize", +] diff --git a/packages/flow/openadapt_flow/run_ledger/collect.py b/packages/flow/openadapt_flow/run_ledger/collect.py new file mode 100644 index 0000000000..197c4b7274 --- /dev/null +++ b/packages/flow/openadapt_flow/run_ledger/collect.py @@ -0,0 +1,1418 @@ +"""Collectors: read the files other commands already write, one function each. + +A collector never edits its source, never calls a model and never touches +the network. Each takes the file it recognises (and its siblings) and returns +a :class:`Contribution`: outcome signals, task ids, timestamps, model usage, +intervals a person spent, field names and verdicts, and (kept apart) the +values the private sidecar holds. + +Each collector refuses a schema version it doesn't know. The contribution is +then a single ``schema_unrecognised`` signal and nothing else, so the row is +UNKNOWN rather than half-read. :func:`collect` walks a run directory (or one +file), dispatches each file by name, and merges the contributions. + +Main-branch sources and what each one can't tell (also in +``docs/RUN_LEDGER.md``): + +* ``summary.json`` + ``guard_events.jsonl`` (agent guard, + ``openadapt.agent-guard-run/v1``): the guard's verdict, blocked saves, holds + and run seconds. No wall-clock times, no field names, no agent model usage. +* ``effect-receipt.json`` (verify-run, ``openadapt.effect-receipt/v1``): the + receipt outcome, the effect verdict, the read-back tier and the executor + kind. No field names (effect rows are contract hashes). +* ``report.json`` (a compiled run's ``RunReport``, no schema field, recognised + by shape) and ``receipt.json`` (``openadapt.run-receipt/v2``): the + transaction outcome, the read-back level, model calls, estimated cost, start + time and duration, the run's inputs (committed, never copied). +* ``openadapt-agent.run/v1`` records (wrap's run store): status, verified, + receipt outcome, model calls and cost when known, start and finish times. +* ``item-approval/request-*.json`` and ``answer-*.json``: approval and + question intervals from ``created_at`` to ``answered_at`` (the times inside + the files, never file mtimes). +* ``jobs/*.json`` (task ledger, ``openadapt.task-ledger/v1``): question + intervals from ``asked_at`` to ``answered_at``. Question text is never read. +* ``run1.json`` (compile-agent, ``agent`` = ``AgentLedger.to_dict()``) and + ``agent_ledger.json`` (the launch demo's agent ledger): metered calls, + tokens and cost, whether the agent finished, gate refusals. + ``summary``, ``final_text`` and per-call ``actions`` are never read. + +Sources produced by the agent-control-plane pieces: ``flight.json`` +(``openadapt.flight-run/v1``), ``guard_ledger_row.json`` +(``openadapt.guard-ledger-row/v1``), a lone ``proposed_write.json``, and, +in :mod:`openadapt_flow.run_ledger.readers`, readiness shadow run +directories, P7 fallback results and P6's exception folders. Their +collectors read exactly the keys ``docs/RUN_LEDGER.md`` lists. +""" + +from __future__ import annotations + +import hashlib +import json +import math +import re +from dataclasses import dataclass, field +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Callable, Iterable, Mapping, Optional, cast + +from openadapt_types.approval import CHECKED_HOW_TIER + +from openadapt_flow.run_ledger.outcome import ( + AGENT_RUN_STATUS_REASON, + EFFECT_VERDICT_REASON, + EXECUTE_OUTCOME_REASON, + EXECUTION_OUTCOME_REASON, + GUARD_VERDICT_REASON, + TRANSACTION_OUTCOME_REASON, + WRAP_STATUS_REASON, + Signal, + guard_block_reason, + outcome_reason, + verified_or_tier, +) + +GUARD_SUMMARY_SCHEMA = "openadapt.agent-guard-run/v1" +EFFECT_RECEIPT_SCHEMA = "openadapt.effect-receipt/v1" +RUN_RECEIPT_SCHEMA = "openadapt.run-receipt/v2" +AGENT_RUN_RECORD_SCHEMA = "openadapt-agent.run/v1" +ITEM_APPROVAL_REQUEST_SCHEMA = "openadapt.item-approval-request/v1" +ITEM_APPROVAL_ANSWER_SCHEMA = "openadapt.item-approval-answer/v1" +TASK_LEDGER_SCHEMA = "openadapt.task-ledger/v1" +PROPOSED_WRITE_SCHEMA = "openadapt.proposed-write/v1" +FLIGHT_SCHEMA = "openadapt.flight-run/v1" +GUARD_LEDGER_ROW_SCHEMA = "openadapt.guard-ledger-row/v1" +EXCEPTION_ANSWER_SCHEMA = "openadapt.exception-answer/v1" + +#: ``openadapt_flow.agent.ledger.ASK_WORKFLOW_NAME``: an item-approval request +#: that is a ledger question, not a save approval. +_ASK_WORKFLOW = "openadapt.task-ledger.question" + +_TASK_ID = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$") +_LABEL = re.compile(r"^[a-z0-9][a-z0-9._-]{0,63}$") +_FIELD_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.-]{0,63}$") +_HEX64 = re.compile(r"^[0-9a-f]{64}$") +_STAMP = re.compile( + r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,9})?(Z|[+-]\d{2}:\d{2})$" +) + +#: How far the walk goes, so a recording folder can't make ``add`` slow. +MAX_DEPTH = 5 +MAX_FILES = 5000 +MAX_BYTES = 16 * 1024 * 1024 + +#: The executor kinds verify-run names, as ledger kinds. +_EXECUTOR_KIND = { + "flow_replay": "program", + "script": "program", + "agent": "agent", + "human": "human", + "unknown": "unknown", +} +_CHECK_RANK = {"matched": 0, "not_checked": 1, "differs": 2} +_TIER_RANK = {"independent_readback": 0, "screen_readback": 1, "unchecked": 2} + + +@dataclass +class Usage: + """Model usage one source reports. ``None`` means it doesn't say.""" + + calls: Optional[int] = None + input_tokens: Optional[int] = None + output_tokens: Optional[int] = None + cost_usd: Optional[float] = None + cost_source: str = "unknown" + + +@dataclass +class Interval: + kind: str + opened_at: str + decided_at: Optional[str] + #: Two sources describing one wait (an approval request and the guard + #: row that mentions it) share a key and are counted once. + key: str = "" + + +@dataclass +class Contribution: + """What one source says about the run.""" + + collector: str + files: list[Path] = field(default_factory=list) + signals: list[Signal] = field(default_factory=list) + task_ids: list[str] = field(default_factory=list) + executor_kind: Optional[str] = None + executor_label: Optional[str] = None + usage: Optional[Usage] = None + intervals: list[Interval] = field(default_factory=list) + #: name -> matched | differs | not_checked + fields: dict[str, str] = field(default_factory=dict) + fields_differing: int = 0 + #: name -> {"intended": ..., "saved": ...}; private sidecar only. + private_fields: dict[str, dict[str, Any]] = field(default_factory=dict) + inputs: Optional[dict[str, Any]] = None + readback_tiers: list[str] = field(default_factory=list) + receipt_digest: Optional[str] = None + #: Field names the run's own task, verify or readiness reference config + #: declares (``ledger export`` lets only these past the scrubber check). + declared_fields: set[str] = field(default_factory=set) + #: Wall-clock moments the source records (an approval asked, a hold, a + #: read-back issued). They bound the run when it keeps no start time. + moments: list[str] = field(default_factory=list) + #: P7: the fallback request id whose item-approval folder holds the + #: gate's requests and answers (``ledger add --approvals``). + approvals_key: Optional[str] = None + #: Config files a source points at (P7's confirmed verify.yaml). + config_paths: list[Path] = field(default_factory=list) + #: A dispatcher envelope's ``run_id``: wrap's run store record + #: (``runs/.json``) keeps its start and finish times. + run_record_id: Optional[str] = None + #: P7: what a field the record check names counts as (confirmed or not). + fields_check: Optional[str] = None + #: P7 ``gate_answers``: request id -> request_sha256. + gate_requests: dict[str, Optional[str]] = field(default_factory=dict) + #: ``fields`` are names a read-back saw in the new record, not names + #: the run declared it would write. + readback_fields: bool = False + #: The guard's relative clock (``guard_events.jsonl`` ``t``) when the save + #: was held for a person: with the approval's created_at it names the + #: run's start. + anchor_t: Optional[float] = None + #: True when the source shows no person was asked during the run (a + #: shadow hold, a guard run with approval ``not_gated``): the row's + #: ``intervention_s`` is then 0 rather than unknown. + no_person: bool = False + started_at: Optional[str] = None + ended_at: Optional[str] = None + duration_s: Optional[float] = None + + def signal(self, reason: str, basis: str = "deterministic") -> None: + self.signals.append(Signal(reason, basis, self.collector)) # type: ignore[arg-type] + + +# -- reading ------------------------------------------------------------------------ + + +class _Unreadable(Exception): + pass + + +def _read_json(path: Path) -> Any: + try: + if path.is_symlink() or path.stat().st_size > MAX_BYTES: + raise _Unreadable(str(path)) + return json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError, UnicodeDecodeError) as exc: + raise _Unreadable(str(path)) from exc + + +def _refused(collector: str, path: Path, reason: str) -> Contribution: + out = Contribution(collector, files=[path]) + out.signal(reason) + return out + + +def _schema_check( + doc: Any, key: str, expected: str, collector: str, path: Path +) -> Optional[Contribution]: + """None when ``doc[key]`` is the version this collector reads.""" + + if not isinstance(doc, dict): + return _refused(collector, path, "source_unreadable") + if doc.get(key) != expected: + return _refused(collector, path, "schema_unrecognised") + return None + + +def _int(value: Any) -> Optional[int]: + if isinstance(value, bool) or not isinstance(value, int) or value < 0: + return None + return value + + +def _float(value: Any) -> Optional[float]: + if isinstance(value, bool) or not isinstance(value, (int, float)): + return None + value = float(value) + if not math.isfinite(value) or value < 0: + return None + return value + + +def _stamp(value: Any) -> Optional[str]: + """An RFC 3339 instant with an offset, normalised to microseconds.""" + + if not isinstance(value, str) or not _STAMP.match(value): + return None + try: + parsed = datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + return _iso(parsed) + + +def _iso(moment: datetime) -> str: + return ( + moment.astimezone(timezone.utc) + .isoformat(timespec="microseconds") + .replace("+00:00", "Z") + ) + + +def _epoch(value: Any) -> Optional[str]: + """A wall-clock epoch in seconds. Monotonic clock readings (small numbers) + are refused: they don't name a time.""" + + number = _float(value) + if number is None or not (1_000_000_000 < number < 4_000_000_000): + return None + return _iso(datetime.fromtimestamp(number, tz=timezone.utc)) + + +def _task_id(value: Any) -> Optional[str]: + return value if isinstance(value, str) and _TASK_ID.match(value) else None + + +def _label(value: Any) -> Optional[str]: + if not isinstance(value, str): + return None + lowered = value.strip().lower().replace(" ", "-") + return lowered if _LABEL.match(lowered) else None + + +def _field_name(value: Any) -> Optional[str]: + return value if isinstance(value, str) and _FIELD_NAME.match(value) else None + + +# -- agent guard ---------------------------------------------------------------------- + + +def collect_agent_guard(path: Path) -> Contribution: + """``summary.json`` (``openadapt.agent-guard-run/v1``) and the + ``guard_events.jsonl`` beside it. + + Limits: the guard keeps relative times only, so the row gets + ``duration_s`` but no ``started_at``. It names no fields and no model + usage of the agent it guards (its own ``model_calls`` are the guard's). + """ + + name = "agent_guard" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema", GUARD_SUMMARY_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path], executor_kind="agent") + out.executor_label = "agent-guard" + # ``not_gated``: the guard never asks a person (no approval card). + out.no_person = doc.get("approval") == "not_gated" + if (tid := _task_id(doc.get("task_id"))) is not None: + out.task_ids.append(tid) + out.duration_s = _float(doc.get("seconds")) + events: list[dict[str, Any]] = [] + events_path = path.parent / "guard_events.jsonl" + if events_path.is_file() and not events_path.is_symlink(): + out.files.append(events_path) + try: + for line in events_path.read_text(encoding="utf-8").splitlines(): + if line.strip(): + event = json.loads(line) + if isinstance(event, dict): + events.append(event) + except (OSError, ValueError): + out.signal("source_unreadable") + times = [t for t in (_float(e.get("t")) for e in events) if t is not None] + if doc.get("ended") == "timeout" and times: + # After its last save decision the guard only waited for the agent + # to exit; the run's own span ends at that decision. + out.duration_s = round(max(times), 3) + held = [ + t + for e in events + if e.get("decision") == "held_for_person" + and (t := _float(e.get("t"))) is not None + ] + # Where the save was held for a person: lines the approval request's own + # created_at up with the guard's relative clock (see ``collect``). + out.anchor_t = held[0] if held else None + if events and not held: + # The guard's own events show no save was held for a person: a save + # blocked before any card opened asked nobody. + out.no_person = True + meta = path.parent / "recording" / "meta.json" + if meta.is_file() and not meta.is_symlink(): + try: + created = _read_json(meta).get("created_at") + except (_Unreadable, AttributeError): + created = None + if (moment := _stamp(created)) is not None: + # The recording is written when the guarded run ends. + out.files.append(meta) + out.moments.append(moment) + scope_codes = { + str(item.get("code")) + for item in doc.get("scope_blocked") or [] + if isinstance(item, dict) + } + blocked = [b for b in doc.get("blocked") or [] if isinstance(b, dict)] + for item in blocked: + code = str(item.get("code") or "") + out.signal(guard_block_reason(code, scope=code in scope_codes)) + verdict = doc.get("verdict") + would_block = [w for w in doc.get("would_block") or [] if isinstance(w, dict)] + save_events = [e for e in events if e.get("kind") == "save"] + sent = bool(doc.get("hold_ms")) or any( + e.get("decision") == "continued" for e in save_events + ) + if verdict is not None: + reason = outcome_reason(GUARD_VERDICT_REASON, verdict) + if reason == "readback_verified": + # A guard VERIFIED is verify-run's: an independent read-back. + out.readback_tiers.append("independent_readback") + if would_block: + # Observe-only let a save through that it would have blocked. + reason = "observe_only_would_block" + out.signal(reason) + else: + last_save = save_events[-1] if save_events else None + if last_save is not None and last_save.get("decision") == "held_for_person": + out.signal("approval_held") + elif sent: + out.signal("write_unconfirmed") + elif not blocked and not ( + events_path.is_file() or _int((doc.get("requests") or {}).get("save")) == 0 + ): + # No events file and no count of zero saves: nothing shows that + # no save request went out. + out.signal("write_unconfirmed") + elif not blocked: + ended = doc.get("ended") + out.signal( + "timed_out_no_write" + if ended == "timeout" + else "crashed_no_write" + if ended == "tab_closed" + else "agent_gave_up" + ) + return out + + +# -- verify-run --------------------------------------------------------------------- + + +def collect_effect_receipt(path: Path) -> Contribution: + """``effect-receipt.json`` (verify-run, ``openadapt.effect-receipt/v1``). + + Limits: effect rows carry contract hashes, not field names, so the row + gets no ``fields_written`` from here. + """ + + name = "verify_run" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema_version", EFFECT_RECEIPT_SCHEMA, name, path) + if refused is not None: + return refused + receipt = doc.get("receipt") + if not isinstance(receipt, dict) or ( + receipt.get("schema_version") != EFFECT_RECEIPT_SCHEMA + ): + return _refused(name, path, "schema_unrecognised") + out = Contribution(name, files=[path]) + out.executor_kind = _EXECUTOR_KIND.get(str(receipt.get("executor_kind")), "unknown") + evidence = doc.get("evidence") if isinstance(doc.get("evidence"), dict) else {} + readback = evidence.get("readback") if isinstance(evidence, dict) else None + readback = readback if isinstance(readback, dict) else {} + for value in ( + readback.get("baseline_read_at"), + readback.get("read_at"), + receipt.get("issued_at"), + ): + if (moment := _stamp(value)) is not None: + out.moments.append(moment) + tier = receipt.get("verification_tier") + if tier in _TIER_RANK: + out.readback_tiers.append(str(tier)) + reason = outcome_reason(EXECUTE_OUTCOME_REASON, receipt.get("outcome")) + if reason == "readback_verified": + reason = verified_or_tier(tier if isinstance(tier, str) else None) + out.signal(reason) + effect = outcome_reason(EFFECT_VERDICT_REASON, receipt.get("effect_verdict")) + if effect == "readback_refuted" and _store_shows_a_write(doc): + # The guard's rule (``guard._verdict``): REFUTED only when the store + # shows a write. An absent effect after a halt before the effect, or + # a save that never landed, is the outcome's call, not a catch. + out.signal(effect) + return out + + +def _store_shows_a_write(doc: Mapping[str, Any]) -> bool: + evidence = doc.get("evidence") + readback = evidence.get("readback") if isinstance(evidence, dict) else None + rows = readback.get("effects") if isinstance(readback, dict) else None + return any( + isinstance(row, dict) + and row.get("observed_effect") in ("present", "conflicting") + for row in rows or [] + ) + + +# -- compiled runs ------------------------------------------------------------------ + + +def _is_run_report(doc: Any) -> bool: + return ( + isinstance(doc, dict) + and isinstance(doc.get("workflow_name"), str) + and "started_at" in doc + and "results" in doc + ) + + +def collect_run_report(path: Path) -> Contribution: + """A compiled run's ``report.json`` (``RunReport``) and ``receipt.json`` + (``openadapt.run-receipt/v2``) beside it. + + ``report.json`` has no schema field, so it is recognised by shape. A + VERIFIED transaction counts as VERIFIED only when the report's read-back + level or the receipt's assurance is an independent read-back. + """ + + name = "compiled_run" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + if not _is_run_report(doc): + return _refused(name, path, "schema_unrecognised") + out = Contribution(name, files=[path], executor_kind="program") + out.executor_label = "openadapt-flow" + out.started_at = _stamp(doc.get("started_at")) + total_ms = _float(doc.get("total_ms")) + if total_ms is not None: + out.duration_s = round(total_ms / 1000.0, 3) + if out.started_at is not None: + start = datetime.fromisoformat(out.started_at.replace("Z", "+00:00")) + out.ended_at = _iso(start + timedelta(milliseconds=total_ms)) + out.usage = Usage( + calls=_int(doc.get("model_calls")), + cost_usd=_float(doc.get("est_model_cost_usd")), + ) + if out.usage.cost_usd is not None: + out.usage.cost_source = "reported" + params = doc.get("params") + if isinstance(params, dict): + out.inputs = dict(params) + tier: Optional[str] = None + readback = doc.get("readback") + if isinstance(readback, dict): + tiers = cast("Mapping[str, str]", CHECKED_HOW_TIER) + tier = tiers.get(str(readback.get("checked_how"))) + receipt_path = path.parent / "receipt.json" + if receipt_path.is_file(): + receipt = collect_run_receipt(receipt_path) + out.files.extend(receipt.files) + out.signals.extend( + s for s in receipt.signals if s.reason != "readback_verified" + ) + out.receipt_digest = receipt.receipt_digest + if tier is None and receipt.readback_tiers: + tier = receipt.readback_tiers[0] + if tier is not None: + out.readback_tiers.append(tier) + outcome = doc.get("transaction_outcome") + table = TRANSACTION_OUTCOME_REASON + if outcome is None: + outcome, table = doc.get("execution_outcome"), EXECUTION_OUTCOME_REASON + reason = outcome_reason(table, outcome) + if reason == "readback_verified": + reason = verified_or_tier(tier) + out.signal(reason) + return out + + +def collect_run_receipt(path: Path) -> Contribution: + """``receipt.json`` (``openadapt.run-receipt/v2``), the success receipt. + + It exists only for a VERIFIED run; its ``effect_assurance`` (or, on an + older receipt, ``effect_tier_reached``) says whether the read-back was + independent. + """ + + name = "run_receipt" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema_version", RUN_RECEIPT_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path], executor_kind="program") + out.executor_label = "openadapt-flow" + assurance = doc.get("effect_assurance") + if assurance is None: + assurance = { + "independent_system": "independent_readback", + "independent_session": "screen_readback", + "persisted_state_reacquisition": "screen_readback", + }.get(str(doc.get("effect_tier_reached"))) + if assurance in _TIER_RANK: + out.readback_tiers.append(str(assurance)) + digest = doc.get("receipt_digest") + if isinstance(digest, str) and _HEX64.match(digest): + out.receipt_digest = digest + out.usage = Usage( + calls=_int(doc.get("model_calls")), + cost_usd=_float(doc.get("est_cost_usd")), + ) + if out.usage.cost_usd is not None: + out.usage.cost_source = "reported" + duration = _int(doc.get("duration_ms")) + out.duration_s = round(duration / 1000.0, 3) if duration is not None else None + reason = outcome_reason(TRANSACTION_OUTCOME_REASON, doc.get("outcome")) + if reason == "readback_verified": + reason = verified_or_tier(assurance if isinstance(assurance, str) else None) + out.signal(reason) + return out + + +# -- wrap --------------------------------------------------------------------------- + + +def collect_agent_run_record(path: Path) -> Contribution: + """A wrap / agent run record (``openadapt-agent.run/v1``) from + ``openadapt-agent/runs/.json``. + + Limits: a wrap result names no fields and no tokens; ``model_calls`` and + ``cost_usd`` are ``null`` when the agent's usage is unknown. A record still + ``running`` is a lost reply. + """ + + name = "wrap" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema", AGENT_RUN_RECORD_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path], executor_label="openadapt-wrap") + if (tid := _task_id(doc.get("request_id"))) is not None: + out.task_ids.append(tid) + out.started_at = _stamp(doc.get("started_at")) + out.ended_at = _stamp(doc.get("finished_at")) + result = doc.get("result") + if doc.get("state") != "finished" or not isinstance(result, dict): + out.signal("lost_reply") + return out + path_kind = result.get("path") + fallback_unproved = False + if path_kind == "agent_fallback": + # P7: an agent run after a program's drift. Its ``verified`` counts + # only with the record check that proves it: readable and passed + # (P7's ``confirmed``). A record without one proves nothing. + path_kind = "agent" + # P7 keeps the policy's record in the result's ``fallback``; its + # task_record_check is the final read (``record_check`` on older ones). + policy = result.get("fallback") + check = ( + policy.get("task_record_check") + if isinstance(policy, dict) and "task_record_check" in policy + else result.get("record_check") + ) + fallback_unproved = not ( + isinstance(check, dict) + and check.get("readable") is True + and check.get("passed") is True + ) + out.executor_kind = ( + "program" if path_kind == "skill" else "agent" if path_kind == "agent" else None + ) + out.duration_s = _float(result.get("seconds")) + out.usage = Usage( + calls=_int(result.get("model_calls")), cost_usd=_float(result.get("cost_usd")) + ) + if out.usage.cost_usd is not None: + out.usage.cost_source = "reported" + status = result.get("status") + receipt_outcome = result.get("receipt_outcome") + if isinstance(status, str) and status in WRAP_STATUS_REASON: + out.signal(WRAP_STATUS_REASON[status]) + elif result.get("verified") is True and fallback_unproved: + out.signal("reconciliation_required") + elif result.get("verified") is True and ( + receipt_outcome == "VERIFIED" or path_kind == "agent" + ): + # A compiled run: verify-run's VERIFIED. An agent's first run: the + # record check read the system of record before and after. + out.readback_tiers.append("independent_readback") + out.signal("readback_verified") + elif isinstance(receipt_outcome, str): + reason = outcome_reason(EXECUTE_OUTCOME_REASON, receipt_outcome) + out.signal("completed_unverified" if reason == "readback_verified" else reason) + elif isinstance(status, str) and status.lower() in AGENT_RUN_STATUS_REASON: + out.signal(AGENT_RUN_STATUS_REASON[status.lower()]) + else: + out.signal("write_unconfirmed") + return out + + +# -- a person's time ---------------------------------------------------------------- + + +def collect_item_approvals( + folder: Path, only: Optional[Mapping[str, Optional[str]]] = None +) -> Contribution: + """``item-approval/request-.json`` and ``answer-.json``. + + One interval per request, from the request's ``created_at`` to the + answer's ``answered_at``. A request with no answer is still open: the row's + intervention time is then unknown, and the run is ESCALATED + (``approval_held``). A declined save is ``person_declined`` (ESCALATED, + not a catch). A ledger + question (``workflow_name`` ``openadapt.task-ledger.question``) is a + ``question`` interval. + """ + + name = "item_approval" + out = Contribution(name) + for request_path in sorted(folder.glob("request-*.json")): + request_id = request_path.name[len("request-") : -len(".json")] + if only is not None and request_id not in only: + continue # not one of the requests the run's gate recorded + try: + request = _read_json(request_path) + except _Unreadable: + out.files.append(request_path) + out.signal("source_unreadable") + continue + out.files.append(request_path) + if not isinstance(request, dict) or ( + request.get("schema_version") != ITEM_APPROVAL_REQUEST_SCHEMA + ): + out.signal("schema_unrecognised") + continue + opened = _stamp(request.get("created_at")) + if opened is None: + out.signal("source_unreadable") + continue + question = request.get("workflow_name") == _ASK_WORKFLOW + decided: Optional[str] = None + decision: Optional[str] = None + answer_path = folder / f"answer-{request_id}.json" + if answer_path.is_file(): + out.files.append(answer_path) + try: + answer = _read_json(answer_path) + except _Unreadable: + answer = None + if not isinstance(answer, dict) or ( + answer.get("schema_version") != ITEM_APPROVAL_ANSWER_SCHEMA + ): + out.signal("schema_unrecognised") + continue + if only is not None and only.get(request_id) not in ( + None, + answer.get("request_sha256"), + ): + # The gate recorded another request under this id. + out.signal("source_unreadable") + continue + decided = _stamp(answer.get("answered_at")) + decision = answer.get("decision") + out.moments += [m for m in (opened, decided) if m is not None] + out.intervals.append( + Interval( + "question" if question else "approval", + opened, + decided, + key=f"approval:{request_id}", + ) + ) + if question: + out.signal("question_asked") + elif decided is None: + out.signal("approval_held") + elif decision != "approve": + # A signed answer that isn't "approve": a person said no. + out.signal("person_declined") + return out + + +def collect_task_ledger(path: Path) -> Contribution: + """A task-ledger job (``openadapt.task-ledger/v1``): its questions. + + Only ``asked_at``, ``answered_at`` and ``request_id`` are read. A question + without ``answered_at`` (waiting, expired or refused) is an open interval. + """ + + name = "task_ledger" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema_version", TASK_LEDGER_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path]) + questions = doc.get("questions") + for question in (questions or {}).values() if isinstance(questions, dict) else []: + if not isinstance(question, dict): + continue + opened = _stamp(question.get("asked_at")) + if opened is None: + out.signal("source_unreadable") + continue + request_id = question.get("request_id") + out.intervals.append( + Interval( + "question", + opened, + _stamp(question.get("answered_at")), + key=f"approval:{request_id}" if isinstance(request_id, str) else "", + ) + ) + out.signal("question_asked") + return out + + +# -- compile-agent ---------------------------------------------------------------- + + +def _agent_usage(agent: Mapping[str, Any]) -> Usage: + calls = _int(agent.get("model_calls")) + tokens_in = _int(agent.get("input_tokens")) + tokens_out = _int(agent.get("output_tokens")) + per_call = agent.get("calls") + if (tokens_in is None or tokens_out is None) and isinstance(per_call, list): + ins = [_int(c.get("input_tokens")) for c in per_call if isinstance(c, dict)] + outs = [_int(c.get("output_tokens")) for c in per_call if isinstance(c, dict)] + if per_call and len(ins) == len(per_call) and None not in ins + outs: + tokens_in = sum(i for i in ins if i is not None) + tokens_out = sum(o for o in outs if o is not None) + cost = _float(agent.get("cost_usd")) + if agent.get("usage_known") is False: + cost = None + return Usage( + calls=calls, + input_tokens=tokens_in, + output_tokens=tokens_out, + cost_usd=cost, + cost_source="metered" if cost is not None else "unknown", + ) + + +def collect_compile_agent(path: Path) -> Contribution: + """compile-agent's ``run1.json`` (``agent`` is ``AgentLedger.to_dict()``) + or a bare ``agent_ledger.json``. + + The agent's ``finished`` flag is its own judgement (``basis="model"``): it + never verifies anything and is ignored when any deterministic source + speaks. A gate refusal in ``gates`` is a catch. + """ + + name = "compile_agent" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + if not isinstance(doc, dict): + return _refused(name, path, "source_unreadable") + if "schema" in doc or "schema_version" in doc: + return _refused(name, path, "schema_unrecognised") + agent = doc.get("agent") if path.name == "run1.json" else doc + if not isinstance(agent, dict) or "model_calls" not in agent: + return _refused(name, path, "schema_unrecognised") + out = Contribution(name, files=[path], executor_kind="agent") + out.executor_label = _label(agent.get("agent")) or _label(agent.get("model")) + out.usage = _agent_usage(agent) + out.started_at = _epoch(agent.get("started_at")) + out.ended_at = _epoch(agent.get("finished_at")) + out.duration_s = _float(agent.get("wall_seconds")) or _float(doc.get("seconds")) + for gate in doc.get("gates") or []: + decision = str(gate.get("decision", "")) if isinstance(gate, dict) else "" + if decision == "refused_by_hold": + # The person at the gate said no: a decline, not a catch. + out.signal("person_declined") + elif decision.startswith("refused"): + out.signal("gate_refused") + if agent.get("finished") is True: + out.signal("readback_verified", "model") + elif agent.get("finished") is False: + out.signal("agent_gave_up", "model") + return out + + +# -- contract-only sources (sibling pieces) ----------------------------------------- + + +def collect_proposed_write(path: Path) -> Contribution: + """A lone ``proposed_write.json`` (``openadapt.proposed-write/v1``), read + outside a readiness run directory. + + Reads ``task_id`` and ``fields[].name`` / ``value``. Nothing compared it + with what the person saved (that is ``case.json``, read with the run + directory), so every field is ``not_checked`` and the run is + ``shadow_not_compared``. Values go to the private sidecar only. + """ + + name = "proposed_write" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema", PROPOSED_WRITE_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path], executor_kind="agent") + if (tid := _task_id(doc.get("task_id"))) is not None: + out.task_ids.append(tid) + for item in doc.get("fields") or []: + if ( + not isinstance(item, dict) + or (fname := _field_name(item.get("name"))) is None + ): + out.signal("source_unreadable") + continue + out.fields[fname] = "not_checked" + out.private_fields[fname] = {"intended": item.get("value"), "saved": None} + out.signal("shadow_not_compared") + return out + + +def collect_flight(path: Path) -> Contribution: + """``flight.json`` (``openadapt.flight-run/v1``): one recorded agent run. + + Reads ``task_id``, ``executor_label``, ``started_at``, ``ended_at``, + ``model`` and ``gate_events``. A ``held`` gate event with no later + ``allowed`` or ``refused`` is a pending hold (``gate_held``); a ``refused`` + one is a catch (``gate_refused``). ``timeline_path`` isn't read. + """ + + name = "flight" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema", FLIGHT_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path], executor_kind="agent") + if (tid := _task_id(doc.get("task_id"))) is not None: + out.task_ids.append(tid) + out.executor_label = _label(doc.get("executor_label")) + out.started_at = _stamp(doc.get("started_at")) + out.ended_at = _stamp(doc.get("ended_at")) + model = doc.get("model") + if isinstance(model, dict): + cost = _float(model.get("cost_usd")) + source = model.get("cost_source") + out.usage = Usage( + calls=_int(model.get("calls")), + input_tokens=_int(model.get("input_tokens")), + output_tokens=_int(model.get("output_tokens")), + cost_usd=cost, + cost_source=( + str(source) + if cost is not None and source in ("metered", "reported") + else "reported" + if cost is not None + else "unknown" + ), + ) + pending = False + # A flight with no gate events never stopped for a person. + out.no_person = doc.get("gate_events") == [] + for event in doc.get("gate_events") or []: + kind = event.get("kind") if isinstance(event, dict) else None + if kind == "held": + pending = True + elif kind == "allowed": + pending = False + elif kind == "refused": + pending = False + out.signal("gate_refused") + if pending: + out.signal("gate_held") + return out + + +def collect_guard_ledger_row(path: Path) -> Contribution: + """``guard_ledger_row.json`` (``openadapt.guard-ledger-row/v1``, P5, J3). + + Reads ``task_id``, ``fields_checked`` and ``fields_differing`` (lists of + names), ``approval_opened_at``, ``approval_decided_at`` and + ``readback_tier``. ``verdict`` is a bucket name P5 chose and is never a + bucket source here, and neither is anything else in the row: the guard's + ``summary.json`` and the read-back decide (J3). A differing field shows + as ``differs``. + ``approver_kind``, ``hold_ms`` and ``diff_path`` have no place in the row + and aren't read. + """ + + name = "guard_ledger_row" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema", GUARD_LEDGER_ROW_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path]) + if (tid := _task_id(doc.get("task_id"))) is not None: + out.task_ids.append(tid) + differing_raw = doc.get("fields_differing") + differing = ( + {n for n in map(_field_name, differing_raw or []) if n} + if isinstance(differing_raw, list) + else set() + ) + checked = doc.get("fields_checked") + for fname in ( + [n for n in map(_field_name, checked or []) if n] + if isinstance(checked, list) + else [] + ): + out.fields[fname] = "differs" if fname in differing else "matched" + for fname in differing: + out.fields[fname] = "differs" + out.fields_differing = len(differing) + tier = doc.get("readback_tier") + if tier in _TIER_RANK: + out.readback_tiers.append(str(tier)) + opened = _stamp(doc.get("approval_opened_at")) + if opened is not None: + decided = _stamp(doc.get("approval_decided_at")) + out.moments += [m for m in (opened, decided) if m is not None] + out.intervals.append(Interval("approval", opened, decided, key="")) + # No signal: J3 makes the row a source of names, times and the tier only. + # The guard's summary.json says REFUTED when its read-back differs. + return out + + +def collect_exception_answer(path: Path) -> Contribution: + """``answer-.json`` (``openadapt.exception-answer/v1``) from P6's + ``$OPENADAPT_HOME/exceptions//`` (read through + :func:`openadapt_flow.run_ledger.readers.collect_exception_folder`). + + Reads ``kind``, ``opened_at``, ``decided_at``, ``answer`` and + ``approver_kind``. A ``second_factor`` kind is a second-factor interval, + anything else an exception interval; the person's time counts either way. + + The bucket: a person who cleared the exception (``continue`` or + ``done_by_person``, decided) let the run go on, as an approved approval + does, so the answer is no bucket source: the run's own result decides + (a save read back independently is VERIFIED). An exception the person + stopped (``skip``, ``abort``, ``decline``), one that expired, or one not + answered yet is ESCALATED (``second_factor`` / ``exception_card``). + """ + + name = "exception" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + refused = _schema_check(doc, "schema", EXCEPTION_ANSWER_SCHEMA, name, path) + if refused is not None: + return refused + out = Contribution(name, files=[path]) + opened = _stamp(doc.get("opened_at")) + if opened is None: + out.signal("source_unreadable") + return out + decided_at = _stamp(doc.get("decided_at")) + out.moments += [m for m in (opened, decided_at) if m is not None] + second = doc.get("kind") == "second_factor" + card = doc.get("card_id") + out.intervals.append( + Interval( + "second_factor" if second else "exception", + opened, + _stamp(doc.get("decided_at")), + key=f"exception:{card}" if isinstance(card, str) else "", + ) + ) + cleared = ( + doc.get("answer") in ("continue", "done_by_person") + and doc.get("approver_kind") == "person" + and decided_at is not None + ) + if not cleared: + out.signal("second_factor" if second else "exception_card") + return out + + +# -- the walk ----------------------------------------------------------------------- + + +def _worse(current: Optional[str], new: str) -> str: + if current is None: + return new + return new if _CHECK_RANK[new] > _CHECK_RANK[current] else current + + +#: The only files the ledger reads, by name: what the producers it knows +#: write. Anything else in a run directory (P3's ``egress/pseudonyms.json``, +#: which holds real values; screenshots; logs; a stray file) is never +#: opened, digested, copied to a sidecar or sent. +ALLOWED_NAMES = frozenset( + { + "summary.json", + "guard_events.jsonl", + "effect-receipt.json", + "report.json", + "receipt.json", + "run1.json", + "agent_ledger.json", + "proposed_write.json", + "flight.json", + "guard_ledger_row.json", + "result.json", + # P1 readiness run directory + "run.json", + "case.json", + "usage.json", + "egress.json", + # the run's own config (declared field names and task ids) + "task.json", + "guard_task.json", + "verify.yaml", + } +) +#: Allowed by folder and name pattern: (parent folder name, prefix, suffix). +_ALLOWED_PATTERNS = ( + ("item-approval", "request-", ".json"), + ("item-approval", "answer-", ".json"), + ("jobs", "job-", ".json"), # task ledger: job-.json + ("runs", "run-", ".json"), # wrap's run store: run-.json + ("egress", "timeline", ".jsonl"), + # Only created_at is read (the guard's recording metadata). + ("recording", "meta", ".json"), + # The shadow hold's held proposals: only held_at is read. + ("held", "", ".json"), +) +#: A file named directly (``ledger add FILE``) may also be a wrap run record +#: (``run-.json``) or a ``wrap-dispatch --result`` envelope. +_DIRECT_FILE = re.compile( + r"^(run-[A-Za-z0-9._-]+|[A-Za-z0-9._-]*(result|envelope)[A-Za-z0-9._-]*)\.json$" +) + + +def allowed_file(path: Path, *, direct: bool = False) -> bool: + """Whether the ledger may read ``path`` at all (see :data:`ALLOWED_NAMES`).""" + + name, parent = path.name, path.parent.name + if name == "timeline.jsonl": + return parent == "egress" + if name in ALLOWED_NAMES: + return True + for folder, prefix, suffix in _ALLOWED_PATTERNS: + if parent == folder and name.startswith(prefix) and name.endswith(suffix): + return True + return direct and bool(_DIRECT_FILE.match(name)) + + +def _files(root: Path) -> list[Path]: + if root.is_file(): + return [root] if allowed_file(root, direct=True) else [] + found: list[Path] = [] + stack = [(root, 0)] + while stack and len(found) < MAX_FILES: + folder, depth = stack.pop() + try: + entries = sorted(folder.iterdir()) + except OSError: + continue + for entry in entries: + if entry.is_symlink(): + continue + if entry.is_dir(): + if depth < MAX_DEPTH: + stack.append((entry, depth + 1)) + elif entry.is_file() and allowed_file(entry): + found.append(entry) + return sorted(found) + + +def _has_schema(path: Path, key: str, family: str) -> bool: + """Cheap test that a JSON file claims a schema of ``family`` (any version).""" + + try: + doc = _read_json(path) + except _Unreadable: + return False + value = doc.get(key) if isinstance(doc, dict) else None + return isinstance(value, str) and value.startswith(family) + + +Dispatch = Callable[[Path], Optional[Contribution]] + + +def _dispatch(path: Path) -> Optional[Contribution]: + name = path.name + parent = path.parent.name + if name == "summary.json": + if _has_schema(path, "schema", "openadapt.agent-guard-run/"): + return collect_agent_guard(path) + return None + if name == "effect-receipt.json": + return collect_effect_receipt(path) + if name == "report.json": + return collect_run_report(path) + if name == "receipt.json": + if (path.parent / "report.json").is_file(): + return None # read with its report + if _has_schema(path, "schema_version", "openadapt.run-receipt/"): + return collect_run_receipt(path) + return None + if name == "run1.json" or name == "agent_ledger.json": + return collect_compile_agent(path) + if name == "proposed_write.json": + return collect_proposed_write(path) + if name == "flight.json": + return collect_flight(path) + if name == "guard_ledger_row.json": + return collect_guard_ledger_row(path) + if name == "result.json": + from openadapt_flow.run_ledger.readers import ( + collect_fallback_result, + is_dispatch_result, + ) + + try: + doc = _read_json(path) + except _Unreadable: + return None + return collect_fallback_result(path) if is_dispatch_result(doc) else None + if parent == "jobs" and name.endswith(".json"): + if _has_schema(path, "schema_version", "openadapt.task-ledger/"): + return collect_task_ledger(path) + return None + if name.endswith(".json") and parent == "runs": + if _has_schema(path, "schema", "openadapt-agent.run/"): + return collect_agent_run_record(path) + return None + + +@dataclass +class Collected: + """Every contribution for one run, plus the files they came from.""" + + root: Path + contributions: list[Contribution] + #: Field names the run's guard task or verify.yaml declares. + config_fields: set[str] = field(default_factory=set) + #: Config files named with ``ledger add --config``, outside the run. + config_paths: list[Path] = field(default_factory=list) + + @property + def declared_fields(self) -> set[str]: + """Every field name the run's own config declares (finding a).""" + + names = set(self.config_fields) + for contribution in self.contributions: + names |= contribution.declared_fields + return names + + @property + def files(self) -> list[Path]: + seen: dict[Path, None] = dict.fromkeys(self.config_paths) + for contribution in self.contributions: + for path in contribution.files: + seen.setdefault(path, None) + return sorted(seen) + + def relative(self, path: Path) -> str: + base = self.root if self.root.is_dir() else self.root.parent + try: + return path.resolve().relative_to(base.resolve()).as_posix() + except ValueError: + return path.name + + def digest(self) -> str: + """sha256 over each source file's relative path and bytes. The private + sidecar never lives in the run, so a second ``add`` gets the same one.""" + + outer = hashlib.sha256() + for path in self.files: + try: + data = path.read_bytes() + except OSError: + data = b"" + outer.update(self.relative(path).encode("utf-8") + b"\0") + outer.update(hashlib.sha256(data).digest()) + return outer.hexdigest() + + +def _skipped(files: list[Path], run: Path) -> tuple[list[Path], list[Path]]: + """Files no collector reads on their own, and readiness shadow run dirs. + + A readiness run directory is read as one source (J1); nothing else in it + is dispatched. A P7 fallback ``result.json`` speaks for the agent run + under its ``run/`` folder (J5), so those files aren't read again. + """ + + from openadapt_flow.run_ledger.readers import is_dispatch_result, is_shadow_run + + shadows = sorted( + {p.parent for p in files if p.name == "run.json" and is_shadow_run(p.parent)} + ) + covered = list(shadows) + for path in files: + if path.name == "result.json" and (path.parent / "run").is_dir(): + try: + doc = _read_json(path) + except _Unreadable: + continue + if is_dispatch_result(doc): + covered.append(path.parent / "run") + kept = [p for p in files if not any(p.is_relative_to(folder) for folder in covered)] + return kept, shadows + + +def collect( + run: Path, + *, + exceptions: Optional[Path] = None, + config: Iterable[Path] = (), + approvals: Optional[Path] = None, +) -> Collected: + """Every source in ``run`` (a run directory or one file), plus P6's + exception folder for the run when ``exceptions`` names one. ``config`` + names the run's guard task or ``verify.yaml`` when they live outside the + run directory (their field names are the ones ``ledger export`` may + let through).""" + + from openadapt_flow.run_ledger.readers import ( + collect_exception_folder, + collect_shadow_run, + config_files, + declared_fields, + ) + + run = Path(run) + # Only a guard task (task.json, guard_task.json) or a verify.yaml. + config = [Path(c) for c in config if allowed_file(Path(c)) and Path(c).is_file()] + contributions: list[Contribution] = [] + approval_folders: set[Path] = set() + found = _files(run) + files, shadows = _skipped(found, run) + for folder in shadows: + contributions.append(collect_shadow_run(folder)) + for path in files: + if path.parent.name == "item-approval" and path.name.startswith("request-"): + approval_folders.add(path.parent) + continue + contribution = _dispatch(path) + if contribution is None and path == run: + from openadapt_flow.run_ledger.readers import ( + collect_fallback_result, + is_dispatch_result, + ) + + try: + doc = _read_json(path) + except _Unreadable: + doc = None + if isinstance(doc, dict) and str(doc.get("schema", "")).startswith( + "openadapt-agent.run/" + ): + # One wrap run record named directly, wherever it was copied. + contribution = collect_agent_run_record(path) + elif is_dispatch_result(doc): + # A wrap-dispatch envelope saved with --result FILE. + contribution = collect_fallback_result(path) + if contribution is not None: + contributions.append(contribution) + for folder in sorted(approval_folders): + contribution = collect_item_approvals(folder) + if contribution.files: + contributions.append(contribution) + if exceptions is not None: + contribution = collect_exception_folder(exceptions) + if contribution is not None: + contributions.append(contribution) + from openadapt_flow.run_ledger.readers import fallback_neighbours, record_times + + for contribution in contributions: + if contribution.run_record_id and contribution.started_at is None: + contribution.started_at, contribution.ended_at, record = record_times( + contribution, run + ) + if record is not None: + contribution.files.append(record) + + for fallback in [c for c in contributions if c.approvals_key]: + # P7's item-approval gate: //item-approval, + # given with --approvals or found near the run by that exact id. + approval_dir, result_extra = fallback_neighbours( + fallback, run, Path(approvals) if approvals is not None else None + ) + if approval_dir is not None: + contribution = collect_item_approvals( + approval_dir, only=fallback.gate_requests or None + ) + if contribution.files: + contributions.append(contribution) + if result_extra is not None: + contributions.append(result_extra) + config = [*config, *result_extra.config_paths] + opened = sorted( + i.opened_at + for c in contributions + if c.collector in ("item_approval", "guard_ledger_row") + for i in c.intervals + if i.kind == "approval" + ) + for contribution in contributions: + if contribution.anchor_t is not None and opened: + start = datetime.fromisoformat(opened[0].replace("Z", "+00:00")) + begin = start - timedelta(seconds=contribution.anchor_t) + contribution.started_at = _iso(begin) + if contribution.duration_s is not None: + contribution.ended_at = _iso( + begin + timedelta(seconds=contribution.duration_s) + ) + collected = Collected( + root=run, + contributions=contributions, + config_fields=declared_fields( + [*config_files(files), *config], + [tid for c in contributions for tid in c.task_ids], + ), + config_paths=[p for p in config if p.is_file()], + ) + declared = collected.declared_fields + for contribution in contributions: + if contribution.readback_fields and declared: + # A read-back lists every field of the new record (id, key ...); + # keep the ones the run's own config says it writes. + contribution.fields = { + n: c for n, c in contribution.fields.items() if n in declared + } + return collected + + +__all__ = [ + "Collected", + "Contribution", + "Interval", + "Usage", + "collect", + "collect_agent_guard", + "collect_agent_run_record", + "collect_compile_agent", + "collect_effect_receipt", + "collect_exception_answer", + "collect_flight", + "collect_guard_ledger_row", + "collect_item_approvals", + "collect_proposed_write", + "collect_run_receipt", + "collect_run_report", + "collect_task_ledger", +] diff --git a/packages/flow/openadapt_flow/run_ledger/outcome.py b/packages/flow/openadapt_flow/run_ledger/outcome.py new file mode 100644 index 0000000000..1a837728f2 --- /dev/null +++ b/packages/flow/openadapt_flow/run_ledger/outcome.py @@ -0,0 +1,428 @@ +"""The outcome rule: which of five buckets a run lands in, and why. + +Each collector turns what its files say into :class:`Signal` values. A signal +names a bucket through a closed reason code +(:data:`openadapt_types.run_ledger.RUN_LEDGER_REASON_OUTCOME`) and says what it +rests on (``basis``): + +* ``deterministic``: a read of the system of record, a guard decision, a + receipt, a person's recorded answer. +* ``model``: a model's or an agent's own judgement ("looks fine", "done"). + +:func:`decide` picks the run's bucket. The stronger finding wins, in the order +CAUGHT_ERROR > UNKNOWN > ESCALATED > FAILED > VERIFIED. Two rules keep a +model from upgrading anything: + +1. A ``model`` signal can never yield VERIFIED. An agent that says it is done, + with nothing that read the save back, is UNKNOWN (``completed_unverified``). +2. Because CAUGHT_ERROR outranks everything, a model's VERIFIED can't + override a deterministic refutation either way. + +The mapping tables below translate every terminal outcome the engine writes +on main into a reason. An outcome missing from a table is UNKNOWN +(``unmapped_outcome``), never another bucket. ``docs/RUN_LEDGER.md`` is the +written-down version of this module, and +``tests/test_run_ledger_outcome.py`` checks it as a table. +""" + +from __future__ import annotations + +from dataclasses import dataclass +from typing import Iterable, Literal, Optional + +from openadapt_types.run_ledger import ( + RUN_LEDGER_OUTCOME_PRECEDENCE, + RUN_LEDGER_REASON_OUTCOME, + RunLedgerOutcome, +) + +Basis = Literal["deterministic", "model"] + + +@dataclass(frozen=True) +class Signal: + """One finding from one source: a reason code and what it rests on.""" + + reason: str + basis: Basis = "deterministic" + source: str = "" + + def __post_init__(self) -> None: + if self.reason not in RUN_LEDGER_REASON_OUTCOME: + raise ValueError(f"unknown ledger reason {self.reason!r}") + + @property + def outcome(self) -> RunLedgerOutcome: + return RUN_LEDGER_REASON_OUTCOME[self.reason] + + +_RANK = {outcome: rank for rank, outcome in enumerate(RUN_LEDGER_OUTCOME_PRECEDENCE)} + +#: Within one bucket, the reason that explains it best comes first. +_REASON_ORDER = tuple(RUN_LEDGER_REASON_OUTCOME) + + +def decide(signals: Iterable[Signal]) -> tuple[RunLedgerOutcome, str]: + """The run's bucket and reason. No signal at all is UNKNOWN (``no_sources``).""" + + effective: list[Signal] = [] + for signal in signals: + if signal.basis == "model" and signal.outcome is RunLedgerOutcome.VERIFIED: + # A model's judgement can't verify a save. + signal = Signal("completed_unverified", "model", signal.source) + effective.append(signal) + if not effective: + return RunLedgerOutcome.UNKNOWN, "no_sources" + best = min( + effective, + key=lambda s: (_RANK[s.outcome], _REASON_ORDER.index(s.reason)), + ) + return best.outcome, best.reason + + +# -- the engine's terminal outcomes on main --------------------------------------- + +#: ``openadapt_flow.transaction.TransactionOutcome`` (``report.json`` +#: ``transaction_outcome``). VERIFIED still needs an independent read-back: +#: see :func:`verified_or_tier`. +TRANSACTION_OUTCOME_REASON: dict[str, str] = { + "VERIFIED": "readback_verified", + "HALTED_BEFORE_EFFECT": "halted_before_effect", + "RECONCILIATION_REQUIRED": "reconciliation_required", + "FAILED_PLATFORM": "platform_failed", + "CANCELED": "canceled_no_write", + "REJECTED_POLICY": "policy_rejected_no_write", + "COMPLETED_UNVERIFIED": "completed_unverified", + "ROLLED_BACK": "rolled_back", + "SAVED_AWAITING_CHECK": "saved_awaiting_check", +} + +#: ``openadapt_flow.execution_profiles.ExecutionOutcome`` (``report.json`` +#: ``execution_outcome``), used only when ``transaction_outcome`` is absent. +EXECUTION_OUTCOME_REASON: dict[str, str] = { + "VERIFIED": "readback_verified", + "COMPLETED_UNVERIFIED": "completed_unverified", + # A halt or a failure says the run stopped; neither says whether before + # the write, so neither is "no write" without more evidence. + "HALTED": "write_unconfirmed", + "FAILED": "write_unconfirmed", + "ROLLED_BACK": "rolled_back", +} + +#: ``openadapt_types.execute.ExecuteTerminalOutcomeV1`` (the verify-run effect +#: receipt's ``outcome``, and wrap's upper-cased ``receipt_outcome``). +#: ``REJECTED_POLICY`` from verify-run means the write landed but the executor +#: approved it itself: not a clean stop, so UNKNOWN. +EXECUTE_OUTCOME_REASON: dict[str, str] = { + "VERIFIED": "readback_verified", + "HALTED_BEFORE_EFFECT": "halted_before_effect", + "RECONCILIATION_REQUIRED": "reconciliation_required", + "REJECTED_POLICY": "self_approved", + "FAILED_PLATFORM": "platform_failed", + "ROLLED_BACK_VERIFIED": "rolled_back", +} + +#: ``openadapt_flow.guard.GuardVerdict`` (agent-guard ``summary.json``). +GUARD_VERDICT_REASON: dict[str, str] = { + "VERIFIED": "readback_verified", + "REFUTED": "readback_refuted", + "RECONCILIATION_REQUIRED": "reconciliation_required", +} + +#: ``effect_verdict`` on a verify-run effect receipt. +EFFECT_VERDICT_REASON: dict[str, str] = { + "CONFIRMED": "readback_verified", + "REFUTED": "readback_refuted", + "INDETERMINATE": "reconciliation_required", +} + +#: ``openadapt_flow.agent.runner.RunOutcome.status``. A timeout or an error +#: can come after a request went out, and the status alone doesn't say it +#: didn't: UNKNOWN, not FAILED. The ``*_no_write`` reasons are only for a +#: source that also shows nothing was sent (the agent guard's own events). +AGENT_RUN_STATUS_REASON: dict[str, str] = { + "success": "completed_unverified", + "halt": "write_unconfirmed", + "refused": "policy_rejected_no_write", + "timeout": "write_unconfirmed", + "error": "write_unconfirmed", +} + +#: Wrap / SkillCache ``status`` codes that decide on their own +#: (``openadapt_flow.integrations.agents.skills``). Others defer to +#: ``receipt_outcome`` and the record check. +WRAP_STATUS_REASON: dict[str, str] = { + "CACHE_HALTED": "reconciliation_required", + "RECONCILIATION_REQUIRED": "reconciliation_required", + "RECEIPT_NOT_VERIFIED": "completed_unverified", + "MODEL_CALLS_NOT_ZERO": "completed_unverified", + "RECORD_CHECK_FAILED": "readback_refuted", + "BASELINE_UNAVAILABLE": "write_unconfirmed", + "TOOL_ERROR": "write_unconfirmed", + "REQUEST_ID_CONFLICT": "policy_rejected_no_write", +} + + +#: Guard refusal codes (``summary.json`` ``blocked[].code``) where the +#: approval was not given and no person said no: nobody answered in time. +#: The save was blocked, so nothing was written; a person still has to act. +_APPROVAL_NOT_GIVEN = frozenset( + {"request_expired", "approval_wait_timed_out", "approval_required"} +) +#: Guard refusal codes where the guard itself could not do its job (P5's +#: ``agent_guard.ledger_row._FAILED_CODES`` and the approval plumbing). The +#: save was blocked before it was sent. +_GUARD_COULD_NOT_CHECK = frozenset( + { + "baseline_unreadable", + "screenshot_required", + "wrong_state", + "task_invalid", + "task_unreadable", + "readback_provider_failed", + "already_answered", + "answer_fields_invalid", + "answer_malformed", + "answer_unreadable", + "approver_root_changed", + "frame_digest_mismatch", + "frame_unreadable", + "initiator_changed", + "request_unknown", + "store_unsafe", + "approval_not_authenticated_person", + "approval_request_unwritable", + } +) + + +def _guard_block_reason(code: str) -> Optional[str]: + """A save the guard blocked (``summary.json`` ``blocked[].code``).""" + + if code.startswith("identity_"): + return "save_blocked_wrong_record" + if code == "other_origin": + return "save_blocked_other_origin" + if code in ( + "already_committed", + "already_saved", + "needs_reconciliation", + "save_waiting_for_person", + "approval_already_used", + ): + return "save_blocked_double_save" + if code == "values_unread": + # P5: the card couldn't show the values to approve, so the guard asked + # no one and blocked the save. Nothing was written; a person acts. + return "values_unread" + if code == "declined": + # P5 writes ``declined`` only for a readable answer that isn't + # "approve": a person said no. Not a catch (skeptic #16). + return "person_declined" + if code in _APPROVAL_NOT_GIVEN: + return "approval_declined" + if code in _GUARD_COULD_NOT_CHECK: + return "policy_rejected_no_write" + return None + + +def guard_block_reason(code: str, *, scope: bool = False) -> str: + """The reason for one blocked save. A scope refusal (another record, field + or value than the task's teach scope) is out of scope. An unknown code is + UNKNOWN: a block the ledger can't name isn't counted as a catch.""" + + if scope: + return "save_blocked_out_of_scope" + return _guard_block_reason(code) or "unmapped_outcome" + + +def tier_reason(tier: Optional[str]) -> Optional[str]: + """What a weaker-than-independent read-back does to a VERIFIED claim.""" + + if tier == "independent_readback": + return None + if tier == "screen_readback": + return "screen_readback_only" + return "completed_unverified" + + +def verified_or_tier(tier: Optional[str]) -> str: + """``readback_verified`` when the read-back was independent, else the + reason it isn't.""" + + return tier_reason(tier) or "readback_verified" + + +def outcome_reason(table: dict[str, str], value: object) -> str: + """Look ``value`` up in a mapping table; anything else is unmapped.""" + + if not isinstance(value, str): + return "unmapped_outcome" + return table.get(value.upper(), table.get(value, "unmapped_outcome")) + + +#: P1 readiness ``case.json`` ``status`` (``openadapt.readiness-case/v1``, +#: ``readiness/compare.py CASE_STATUSES``). A shadow run holds every save, +#: so nothing it proposed was written: never VERIFIED. A person's save is the +#: real one, so a match is ESCALATED (a person did the step), and a mismatch +#: or a wrong record is the error the shadow caught. ``FAILED_SCOPE`` means a +#: write reached the app anyway: UNKNOWN, since nothing read it back. +#: ``NOT_CHECKED`` is refined by :func:`shadow_reason`. +READINESS_CASE_REASON: dict[str, str] = { + "MATCHED": "shadow_matched", + "MISMATCHED": "shadow_field_mismatch", + "WRONG_RECORD": "shadow_wrong_record", + "NOT_COMPARABLE": "shadow_not_compared", + "NOT_CHECKED": "shadow_not_compared", + "FAILED_SCOPE": "shadow_write_landed", +} + +#: P1 ``run.json`` ``status`` for a run that proposed nothing +#: (``readiness/runner.py``). ``TIMEOUT`` and ``NO_WRITE_HELD`` are set only +#: after the shadow guard counted the saves that reached the app, so with +#: ``landed_writes == 0`` they are failures with evidence that nothing was +#: written. ``AGENT_ERROR`` is the default before the guard counted anything: +#: its ``landed_writes: 0`` is not evidence, so it is UNKNOWN. Every reason +#: for a shadow run is a ``shadow_*`` one (or ``egress_refused``), so Cloud +#: never counts a readiness trial as a production failure. +READINESS_RUN_NO_WRITE_REASON: dict[str, str] = { + "TIMEOUT": "shadow_timed_out", + "NO_WRITE_HELD": "shadow_no_proposal", + "AGENT_ERROR": "shadow_agent_error", +} + + +def shadow_reason( + case_status: Optional[str], + run_status: Optional[str], + landed_writes: Optional[int], + *, + egress_refused: bool = False, +) -> str: + """The reason for one shadow run (J1). + + ``landed_writes`` is P1's count of saves that reached the app (``None`` + when unknown). A landed write wins: something was saved and nothing read + it back. A missing ``case.json`` is never a match. + + ``EXTRA_TARGET``: a write came from, or could have come from, a tab, + popup or worker the hold didn't guard; the hold can't vouch that nothing + was written there. ``EGRESS_REFUSED`` (or ``run.json`` ``egress.refused``): + the run's model traffic wasn't scrubbed or metered as required, so P1 + keeps no scorecard for it. Both are UNKNOWN, never a match. A healthy + ``--egress blocked`` run also says ``mode: blocked``; only ``refused`` + tells the two apart. + """ + + if case_status == "FAILED_SCOPE" or (landed_writes or 0) > 0: + return "shadow_write_landed" + if run_status == "EXTRA_TARGET": + return "shadow_extra_target" + if run_status == "EGRESS_REFUSED" or egress_refused: + return "egress_refused" + if case_status in ("MISMATCHED", "WRONG_RECORD"): + # The proposal was held, so the error the shadow caught stands even + # when the landed count is unknown. + return READINESS_CASE_REASON[case_status] + if landed_writes is None: + return "shadow_not_compared" + if ( + case_status in (None, "NOT_CHECKED") + and run_status in READINESS_RUN_NO_WRITE_REASON + ): + return READINESS_RUN_NO_WRITE_REASON[str(run_status)] + if case_status is None or case_status not in READINESS_CASE_REASON: + return "shadow_not_compared" + return READINESS_CASE_REASON[case_status] + + +#: P7 fallback ``status`` (``wrap/fallback.py``) on ``path: agent_fallback``. +#: ``None`` means the reason depends on the record check (see +#: :func:`fallback_reason`). +FALLBACK_STATUS_REASON: dict[str, Optional[str]] = { + "VERIFIED": None, + "GATE_REFUSED": None, + "COST_CAP_EXCEEDED": None, + # A save went through without the gate's approval. + "GATE_NOT_PROVED": "self_approved", + "RECONCILIATION_REQUIRED": "reconciliation_required", + # The agent was never started; the program's proved pre-effect halt + # stands and a person picks the task up. + "FALLBACK_GATE_UNATTENDED": None, + "FALLBACK_NO_AGENT": None, + "FALLBACK_COST_UNBOUNDED": None, + "FALLBACK_REQUEST_REUSED": None, +} +_FALLBACK_NOT_STARTED = ( + "FALLBACK_GATE_UNATTENDED", + "FALLBACK_NO_AGENT", + "FALLBACK_COST_UNBOUNDED", + "FALLBACK_REQUEST_REUSED", +) + + +def fallback_reason( + status: object, + *, + verified: bool, + confirmed: bool = False, + nothing_written: bool, + something_written: bool, + program_halted_before_effect: bool, +) -> str: + """The reason for one P7 fallback run (J5). ``verified`` is P7's own + flag (every gate approved by the person and a passed record check); + ``confirmed`` is the record check itself: readable and passed. + ``nothing_written`` needs a readable check with zero changes; + ``something_written`` is a check that counted a change.""" + + if not isinstance(status, str) or status not in FALLBACK_STATUS_REASON: + return ( + "readback_refuted" + if something_written and not confirmed + else ("unmapped_outcome") + ) + fixed = FALLBACK_STATUS_REASON[status] + if fixed is not None: + return fixed + if status == "VERIFIED": + if not verified: + return "self_approved" + # A record check that isn't readable (or predates ``readable``) + # doesn't confirm the save; P7 itself now says RECONCILIATION_REQUIRED. + return "readback_verified" if confirmed else "reconciliation_required" + if status == "GATE_REFUSED": + # The person at the gate said no. With the record check showing no + # write, it is a decline, not a catch (skeptic #16). + return "person_declined" if nothing_written else "write_unconfirmed" + if status == "COST_CAP_EXCEEDED": + return "policy_rejected_no_write" if nothing_written else "write_unconfirmed" + if status in _FALLBACK_NOT_STARTED: + return ( + "halted_before_effect" + if program_halted_before_effect + else "write_unconfirmed" + ) + return "unmapped_outcome" + + +__all__ = [ + "AGENT_RUN_STATUS_REASON", + "EFFECT_VERDICT_REASON", + "EXECUTE_OUTCOME_REASON", + "EXECUTION_OUTCOME_REASON", + "FALLBACK_STATUS_REASON", + "GUARD_VERDICT_REASON", + "READINESS_CASE_REASON", + "READINESS_RUN_NO_WRITE_REASON", + "Signal", + "TRANSACTION_OUTCOME_REASON", + "WRAP_STATUS_REASON", + "decide", + "fallback_reason", + "guard_block_reason", + "shadow_reason", + "outcome_reason", + "tier_reason", + "verified_or_tier", +] diff --git a/packages/flow/openadapt_flow/run_ledger/readers.py b/packages/flow/openadapt_flow/run_ledger/readers.py new file mode 100644 index 0000000000..28aef4b324 --- /dev/null +++ b/packages/flow/openadapt_flow/run_ledger/readers.py @@ -0,0 +1,753 @@ +"""Readers for the agent-control-plane pieces' files (joins J1, J4 and J5). + +Each reads exactly what its producer writes (synthetic copies are under +``tests/fixtures/run_ledger``) and returns a :class:`Contribution`. The bucket +is decided only in :mod:`openadapt_flow.run_ledger.outcome`. + +* :func:`collect_shadow_run`: a readiness task run directory (P1): ``run.json`` + (``openadapt.readiness-task-run/v1``), ``proposed_write.json``, + ``case.json`` (``openadapt.readiness-case/v1``), ``usage.json`` + (``openadapt.agent-usage/v1``) and ``egress.json`` (P3's egress summary) + when the agent ran behind the flight proxy. Nothing else in the directory + is read: a ``guard_ledger_row.json`` or ``guard_events.jsonl`` there is the + shadow hold's, not a save's. +* :func:`collect_fallback_result`: P7's fallback ``result.json`` and the + ``wrap-dispatch`` result envelope. The envelope's ``outcome`` (a bucket + name) is not read; the bucket comes from ``status``, ``verified`` and the + record check. +* :func:`collect_exception_folder`: P6's + ``$OPENADAPT_HOME/exceptions//`` (``card-*.json`` and + ``answer-*.json``). +* :func:`declared_fields`: the field names the run's own task or verify + config declares, which ``ledger export`` lets through the scrubber check. +""" + +from __future__ import annotations + +import json +import re +from pathlib import Path +from typing import Any, Iterable, Mapping, Optional + +from openadapt_flow.run_ledger.collect import ( + Contribution, + Interval, + Usage, + _epoch, + _field_name, + _float, + _int, + _label, + _read_json, + _refused, + _stamp, + _task_id, + _Unreadable, + _worse, + collect_exception_answer, +) +from openadapt_flow.run_ledger.outcome import ( + EXECUTE_OUTCOME_REASON, + WRAP_STATUS_REASON, + fallback_reason, + outcome_reason, + shadow_reason, +) + +READINESS_RUN_SCHEMA = "openadapt.readiness-task-run/v1" +READINESS_CASE_SCHEMA = "openadapt.readiness-case/v1" +AGENT_USAGE_SCHEMA = "openadapt.agent-usage/v1" +PROPOSED_WRITE_SCHEMA = "openadapt.proposed-write/v1" +EXCEPTION_CARD_SCHEMA = "openadapt.exception-card/v1" +GUARD_TASK_SCHEMA = "openadapt.guard-task/v1" +VERIFY_SCHEMA = "openadapt.verify/v1" + +#: P7's ``FALLBACK_PATH`` and the dispatcher's other ``path`` values. +_DISPATCH_PATHS = ("agent_fallback", "program", "held") +#: ``readiness/compare.py`` field kinds, as ledger field checks. +_CASE_KIND_CHECK = { + "matched": "matched", + "mismatched": "differs", + "missing": "differs", + "extra": "differs", + "wrong_record": "differs", + "uncompared": "not_checked", +} + + +def is_shadow_run(folder: Path) -> bool: + """A directory with a readiness ``run.json`` is a shadow run (J1).""" + + path = folder / "run.json" + if not path.is_file() or path.is_symlink(): + return False + try: + doc = _read_json(path) + except _Unreadable: + return False + return isinstance(doc, dict) and str(doc.get("schema", "")).startswith( + "openadapt.readiness-task-run/" + ) + + +def _optional(folder: Path, name: str, schema: str, out: Contribution) -> Any: + """``folder/name`` when present and of ``schema``; ``None`` when absent. + A present file that can't be read or claims another version is a + ``schema_unrecognised`` / ``source_unreadable`` signal.""" + + path = folder / name + if not path.is_file() or path.is_symlink(): + return None + out.files.append(path) + try: + doc = _read_json(path) + except _Unreadable: + out.signal("source_unreadable") + return None + if not isinstance(doc, dict) or doc.get("schema") != schema: + out.signal("schema_unrecognised") + return None + return doc + + +def _timeline_moments(path: Path, out: Contribution) -> list[str]: + """The first and last ``at`` in P3's egress ``timeline.jsonl``: when the + proxy saw the agent's first and last model traffic. Nothing else in the + timeline is read.""" + + if not path.is_file() or path.is_symlink() or path.name != "timeline.jsonl": + return [] + try: + if path.stat().st_size > 16 * 1024 * 1024: + return [] + lines = path.read_text(encoding="utf-8").splitlines() + except (OSError, UnicodeDecodeError): + return [] + found: list[str] = [] + for line in lines: + try: + event = json.loads(line) + except ValueError: + continue + if isinstance(event, dict) and (moment := _stamp(event.get("at"))): + found.append(moment) + if not found: + return [] + out.files.append(path) + ordered = sorted(found) + return [ordered[0], ordered[-1]] + + +def _usage_from(doc: Mapping[str, Any]) -> Usage: + cost = _float(doc.get("cost_usd")) + return Usage( + calls=_int(doc.get("calls")), + input_tokens=_int(doc.get("input_tokens")), + output_tokens=_int(doc.get("output_tokens")), + cost_usd=cost, + cost_source="reported" if cost is not None else "unknown", + ) + + +def _egress_usage(doc: Mapping[str, Any], base: Optional[Usage]) -> Usage: + """P3's egress summary (J7): the proxy's own count of model calls and + cost. Metered cost beats the agent's report; tokens stay the agent's.""" + + out = Usage(**vars(base)) if base is not None else Usage() + calls = _int(doc.get("model_calls")) + if calls is not None: + out.calls = calls + cost = _float(doc.get("cost_usd")) + if cost is not None: + out.cost_usd = cost + out.cost_source = ( + "metered" if doc.get("cost_source") == "metered" else "reported" + ) + return out + + +def collect_shadow_run(folder: Path) -> Contribution: + """One readiness task run directory (P1, J1). See the module docstring. + + Duration is ``agent_wall_s``. Model usage comes from ``run.json`` + ``usage`` (P1's copy, which carries the priced cost), else + ``usage.json``; both are the agent's own report (``reported``). An + ``egress.json`` replaces calls and cost with the proxy's metered count. + Field checks and the private values come from ``case.json``; without it + every proposed field is ``not_checked`` and the run is + ``shadow_not_compared``. + """ + + name = "readiness_shadow" + run_path = folder / "run.json" + try: + run = _read_json(run_path) + except _Unreadable: + return _refused(name, run_path, "source_unreadable") + if not isinstance(run, dict) or run.get("schema") != READINESS_RUN_SCHEMA: + return _refused(name, run_path, "schema_unrecognised") + out = Contribution(name, files=[run_path], executor_kind="agent") + if (tid := _task_id(run.get("task_id"))) is not None: + out.task_ids.append(tid) + out.duration_s = _float(run.get("agent_wall_s")) + + usage_doc = _optional(folder, "usage.json", AGENT_USAGE_SCHEMA, out) + run_usage = run.get("usage") + usage: Optional[Usage] = None + if isinstance(run_usage, dict): + usage = _usage_from(run_usage) + if usage.cost_usd is None and _float(run.get("model_cost_usd")) is not None: + usage.cost_usd = _float(run.get("model_cost_usd")) + usage.cost_source = "reported" + elif usage_doc is not None: + usage = _usage_from(usage_doc) + model = (run_usage if isinstance(run_usage, dict) else usage_doc or {}).get("model") + out.executor_label = _label(model) or "readiness-shadow" + egress_path = folder / "egress.json" + if egress_path.is_file() and not egress_path.is_symlink(): + out.files.append(egress_path) + try: + egress = _read_json(egress_path) + except _Unreadable: + egress = None + out.signal("source_unreadable") + if isinstance(egress, dict) and "mode" in egress: + usage = _egress_usage(egress, usage) + elif egress is not None: + out.signal("schema_unrecognised") + else: + # P1 also copies the egress summary into run.json (``egress``); a + # refused session there has no ``mode`` and no counts. + copy = run.get("egress") + if ( + isinstance(copy, dict) + and "mode" in copy + and copy.get("refused") is not True + ): + usage = _egress_usage(copy, usage) + out.usage = usage + + proposed = _optional(folder, "proposed_write.json", PROPOSED_WRITE_SCHEMA, out) + case = _optional(folder, "case.json", READINESS_CASE_SCHEMA, out) + proposed_names: list[str] = [] + proposed_values: dict[str, Any] = {} + if (held := _stamp((proposed or {}).get("held_at"))) is not None: + out.moments.append(held) # when the shadow hold stopped the save + for held_path in sorted((folder / "held").glob("*.json"))[:64]: + # The hold's own record of each save it stopped (an extra target's + # too). Only ``held_at`` is read; the file holds the values. + if held_path.is_symlink() or not held_path.name[:-5].isdigit(): + continue + try: + held_doc = _read_json(held_path) + except _Unreadable: + continue + if isinstance(held_doc, dict) and (moment := _stamp(held_doc.get("held_at"))): + out.moments.append(moment) + out.files.append(held_path) + out.moments += _timeline_moments(folder / "egress" / "timeline.jsonl", out) + for item in (proposed or {}).get("fields") or []: + if isinstance(item, dict) and (fname := _field_name(item.get("name"))): + proposed_names.append(fname) + proposed_values[fname] = item.get("value") + case_names: set[str] = set() + compared: dict[str, str] = {} + # compare.py returns before it builds the field rows for FAILED_SCOPE, + # a task that didn't run and a run with no proposal; then the case + # declares nothing about the proposed names. + rows_built = case is not None and ( + case.get("status") + in ("MATCHED", "MISMATCHED", "WRONG_RECORD", "NOT_COMPARABLE") + or ( + case.get("status") == "NOT_CHECKED" + and case.get("reason") in ("uncompared_fields", "no_reference_fields") + ) + ) + if case is not None: + if (tid := _task_id(case.get("task_id"))) is not None: + out.task_ids.append(tid) + for row in case.get("fields") or []: + if ( + not isinstance(row, dict) + or (fname := _field_name(row.get("name"))) is None + ): + continue + kind = row.get("kind") + check = _CASE_KIND_CHECK.get(str(kind), "not_checked") + compared[fname] = _worse(compared.get(fname), check) + out.private_fields[fname] = { + "intended": row.get("proposed"), + "saved": row.get("human"), + } + case_names.add(fname) + # compare.py lists every proposed name the reference doesn't + # declare as ``extra`` (or ``uncompared`` with no human value). + undeclared = kind == "extra" or ( + kind == "uncompared" and row.get("human") is None + ) + if not undeclared: + out.declared_fields.add(fname) + for fname in proposed_names: + if fname in case_names: + continue + compared[fname] = _worse(compared.get(fname), "not_checked") + out.private_fields.setdefault( + fname, {"intended": proposed_values.get(fname), "saved": None} + ) + if rows_built: + # Once compare.py built the rows it lists every proposed field + # the reference doesn't declare; one it leaves out is an + # expected-record or ignored field the task declared. + out.declared_fields.add(fname) + # A shadow run writes nothing, so the row has no fields_written and no + # fields_differing: the comparison is in case.json (and the values in + # the private sidecar), and the reason says whether it matched. + del compared + + landed = _int(run.get("landed_writes")) + if case is not None and _int(case.get("landed_writes")): + landed = max(landed or 0, _int(case.get("landed_writes")) or 0) + status = case.get("status") if case is not None else None + run_egress = run.get("egress") + out.signal( + shadow_reason( + status if isinstance(status, str) else None, + run.get("status") if isinstance(run.get("status"), str) else None, + landed, + egress_refused=isinstance(run_egress, dict) + and run_egress.get("refused") is True, + ) + ) + # The shadow hold never asks a person: the person's own save is a + # separate recorded run. Nobody spent time on this one. + out.no_person = True + return out + + +# -- P7 fallback (J5) --------------------------------------------------------------- + + +def is_dispatch_result(doc: Any) -> bool: + """P7's fallback ``result.json`` (``SkillRun.to_dict()``, with + ``replay``) or the ``wrap-dispatch`` envelope (``WrappedTask.call``'s + result plus ``outcome`` and ``fallback``). Neither has a schema field, so + both are recognised by shape; compile-agent's ``compiled/result.json`` + has no ``path`` and isn't one.""" + + return ( + isinstance(doc, dict) + and doc.get("path") in _DISPATCH_PATHS + and isinstance(doc.get("status"), str) + and "verified" in doc + and ("replay" in doc or ("outcome" in doc and "fallback" in doc)) + ) + + +def _nothing_written(check: Any) -> bool: + """P7's ``_nothing_written``: both reads of the record check succeeded + (``readable: true``) and saw no change. An unreadable store also reports + zero counts, so a check without ``readable: true`` (an older one, or a + failed read) proves nothing.""" + + return ( + isinstance(check, Mapping) + and check.get("readable") is True + and all( + _int(check.get(key)) == 0 and not isinstance(check.get(key), bool) + for key in ("created", "changed", "removed") + ) + ) + + +def _something_written(check: Any) -> bool: + return isinstance(check, Mapping) and any( + (_int(check.get(key)) or 0) > 0 for key in ("created", "changed", "removed") + ) + + +def collect_fallback_result(path: Path) -> Contribution: + """P7's ``/fallback///result.json`` or a dispatcher + envelope (J5). + + On ``path: agent_fallback`` the reason comes from + :func:`~openadapt_flow.run_ledger.outcome.fallback_reason`: ``status``, + P7's ``verified`` (a passed record check of the task's record and every + gate approved by the person) and the record check + (``replay.fallback.task_record_check``). A VERIFIED fallback's record + check read the system of record before and after, an independent + read-back. ``replay.program`` (the program's earlier halt) is never read + for a signal: it is what the fallback answered. Gates carry one time + each, not an opened/decided pair, so a person's time on them is unknown. + + On ``path: program`` / ``held`` the envelope is read like a wrap result. + """ + + name = "wrap_fallback" + try: + doc = _read_json(path) + except _Unreadable: + return _refused(name, path, "source_unreadable") + if not is_dispatch_result(doc): + return _refused(name, path, "schema_unrecognised") + out = Contribution(name, files=[path], executor_label="openadapt-wrap") + run_id = doc.get("run_id") + if isinstance(run_id, str) and re.fullmatch(r"run-[0-9a-f]{8,64}", run_id): + out.run_record_id = run_id + + def _dict(value: Any) -> dict[str, Any]: + return value if isinstance(value, dict) else {} + + compile_doc = _dict(doc.get("compile")) + replay = _dict(doc.get("replay")) + # result.json keeps the policy's record in replay.fallback; the + # dispatcher envelope carries the same object as its top-level fallback. + fallback = _dict(replay.get("fallback")) or _dict(doc.get("fallback")) + program = _dict(replay.get("program")) + tid = _task_id(doc.get("request_id")) or _task_id(compile_doc.get("task_key")) + if tid is not None: + out.task_ids.append(tid) + out.duration_s = _float(doc.get("seconds")) + cost = _float(doc.get("cost_usd")) if doc.get("usage_known") is True else None + out.usage = Usage( + calls=_int(doc.get("model_calls")), + cost_usd=cost, + cost_source="reported" if cost is not None else "unknown", + ) + status = doc.get("status") + if doc.get("path") != "agent_fallback": + out.executor_kind = "program" + if status in WRAP_STATUS_REASON: + out.signal(WRAP_STATUS_REASON[str(status)]) + elif status == "NO_ADMITTED_PROGRAM": + out.signal("policy_rejected_no_write") # nothing ran + elif doc.get("verified") is True and doc.get("receipt_outcome") == "VERIFIED": + out.readback_tiers.append("independent_readback") + out.signal("readback_verified") + elif isinstance(doc.get("receipt_outcome"), str): + reason = outcome_reason(EXECUTE_OUTCOME_REASON, doc["receipt_outcome"]) + out.signal( + "completed_unverified" if reason == "readback_verified" else reason + ) + else: + out.signal("unmapped_outcome") + return out + + out.executor_kind = "agent" + run1 = _dict(compile_doc.get("run1")) + # An item-approval gate (P7's ``gate_answers``) keeps each save's + # request in ``//item-approval/``, with + # the times a person was asked and answered; ``ledger add --approvals`` + # reads it there. A terminal gate keeps one time per save, not a pair. + answers = fallback.get("gate_answers") + key = fallback.get("request_id") + if isinstance(key, str) and _task_id(key) is not None: + # The fallback's own request id names its folders: the item-approval + # requests and, for an envelope, the result.json with field names. + out.approvals_key = key + if isinstance(answers, list): + for answer in answers: + rid = answer.get("request_id") if isinstance(answer, dict) else None + if isinstance(rid, str) and re.fullmatch(r"[0-9a-f]{32}", rid): + sha = answer.get("request_sha256") + out.gate_requests[rid] = sha if isinstance(sha, str) else None + for gate in run1.get("gates") or []: + if not isinstance(gate, dict): + continue + at = _epoch(gate.get("at")) + if at is not None: + out.moments.append(at) + if ( + at is not None + and not out.gate_requests + and str(gate.get("decision", "")).endswith("_by_hold") + ): + out.intervals.append(Interval("approval", at, None, key=f"gate:{at}")) + check = fallback.get("task_record_check") + if check is None: + check = doc.get("record_check") + # P7's ``confirmed``: the final read was readable and passed. + confirmed = ( + isinstance(check, Mapping) + and check.get("readable") is True + and check.get("passed") is True + ) + reason = fallback_reason( + status, + verified=doc.get("verified") is True, + confirmed=confirmed, + nothing_written=_nothing_written(check), + something_written=_something_written(check), + program_halted_before_effect=program.get("receipt_outcome") + == "HALTED_BEFORE_EFFECT", + ) + if reason == "readback_verified": + out.readback_tiers.append("independent_readback") + out.signal(reason) + out.fields_check = "matched" if confirmed else "not_checked" + # The names the record check read back in the task's new record + # (``result.json`` only; the envelope doesn't carry them). ``collect`` + # keeps only the ones the run's config declares when it declares any. + record = _dict(doc.get("record_check")) or _dict(run1.get("record_check")) + names = record.get("fields") + if isinstance(names, list) and record.get("created") == 1: + for fname in [n for n in map(_field_name, names) if n]: + out.fields[fname] = "matched" if confirmed else "not_checked" + out.readback_fields = True + return out + + +def _named_dirs(base: Path, name: str, *, depth: int = 5) -> list[Path]: + """Folders called exactly ``name`` under ``base`` (no links, bounded).""" + + found: list[Path] = [] + stack = [(base, 0)] + seen = 0 + while stack and seen < 5000: + folder, level = stack.pop() + try: + entries = sorted(folder.iterdir()) + except OSError: + continue + for entry in entries: + seen += 1 + if entry.is_symlink() or not entry.is_dir(): + continue + if entry.name == name: + found.append(entry) + if level < depth: + stack.append((entry, level + 1)) + return sorted(found) + + +def record_times( + contribution: Contribution, run: Path +) -> tuple[Optional[str], Optional[str], Optional[Path]]: + """A dispatcher envelope's start and finish, from wrap's run store record + ``runs/.json`` near it (``openadapt-agent.run/v1`` with the same + ``request_id``). Only ``started_at`` and ``finished_at`` are read; the + envelope is already the record's result.""" + + run_id = contribution.run_record_id + base = run.parent if run.is_file() else run + for folder in _named_dirs(base, "runs", depth=6): + path = folder / f"{run_id}.json" + if not path.is_file() or path.is_symlink(): + continue + try: + doc = _read_json(path) + except _Unreadable: + continue + if ( + isinstance(doc, dict) + and doc.get("schema") == "openadapt-agent.run/v1" + and doc.get("run_id") == run_id + and doc.get("request_id") in contribution.task_ids + ): + return _stamp(doc.get("started_at")), _stamp(doc.get("finished_at")), path + return None, None, None + + +def fallback_neighbours( + fallback: Contribution, run: Path, approvals: Optional[Path] +) -> tuple[Optional[Path], Optional[Contribution]]: + """P7's files beside a fallback run, found by its own request id. + + * The item-approval folder: ``//item-approval`` with + ``--approvals``, else a folder named exactly ```` near the run + (under the directory holding the result or envelope) that has an + ``item-approval`` folder. Only the requests the run's ``gate_answers`` + name, with the same ``request_sha256``, are read. + * For an envelope (no field names of its own): the fallback's own + ``result.json`` (a folder named ```` holding one whose + ``replay.fallback.request_id`` is ````), for the record check's + field names, and the task's confirmed ``compiled/verify.yaml`` beside + the cache (``/fallback///`` -> ``/``). + """ + + key = fallback.approvals_key + assert key is not None + base = run.parent if run.is_file() else run + approval_dir: Optional[Path] = None + if approvals is not None: + candidate = approvals / key / "item-approval" + approval_dir = candidate if candidate.is_dir() else None + named = _named_dirs(base, key) + if approval_dir is None and fallback.gate_requests: + for folder in named: + if (folder / "item-approval").is_dir(): + approval_dir = folder / "item-approval" + break + extra: Optional[Contribution] = None + result_dir = None + if run.is_file() or (run / "result.json") not in fallback.files: + for folder in named: + result = folder / "result.json" + if result in fallback.files or not result.is_file(): + continue + try: + doc = _read_json(result) + except _Unreadable: + continue + replay = doc.get("replay") if isinstance(doc, dict) else None + mine = ( + isinstance(replay, dict) + and isinstance(replay.get("fallback"), dict) + and replay["fallback"].get("request_id") == key + ) + if mine and is_dispatch_result(doc): + result_dir = folder + record = doc.get("record_check") + names = record.get("fields") if isinstance(record, dict) else None + extra = Contribution("wrap_fallback_fields", files=[result]) + if isinstance(names, list) and record.get("created") == 1: + check = fallback.fields_check or "not_checked" + for fname in [n for n in map(_field_name, names) if n]: + extra.fields[fname] = check + extra.readback_fields = True + break + else: + result_dir = run + if result_dir is not None: + task_dir = result_dir.parent + verify = task_dir.parent.parent / task_dir.name / "compiled" / "verify.yaml" + if verify.is_file() and not verify.is_symlink(): + extra = extra or Contribution("wrap_fallback_fields") + extra.config_paths.append(verify) + return approval_dir, extra + + +# -- P6 exceptions (J4) ------------------------------------------------------------- + + +def collect_exception_folder(folder: Path) -> Optional[Contribution]: + """``$OPENADAPT_HOME/exceptions//`` (P6's registry). + + One interval per card, from the card's ``opened_at`` to the answer's + ``decided_at``; a card with no answer yet, or an expired one + (``decided_at: null``), is an open interval. The card's ``task_id`` is a + task id source, so a card from another task makes the row + ``task_id_conflict``. Card summaries and answers' signatures aren't read. + """ + + if not folder.is_dir() or folder.is_symlink(): + return None + out = Contribution("exception") + answered: set[str] = set() + for answer_path in sorted(folder.glob("answer-*.json")): + part = collect_exception_answer(answer_path) + out.files.extend(part.files) + out.signals.extend(part.signals) + out.intervals.extend(part.intervals) + answered.add(answer_path.name[len("answer-") : -len(".json")]) + for card_path in sorted(folder.glob("card-*.json")): + out.files.append(card_path) + try: + card = _read_json(card_path) + except _Unreadable: + out.signal("source_unreadable") + continue + if not isinstance(card, dict) or card.get("schema") != EXCEPTION_CARD_SCHEMA: + out.signal("schema_unrecognised") + continue + if (tid := _task_id(card.get("task_id"))) is not None: + out.task_ids.append(tid) + if card_path.name[len("card-") : -len(".json")] in answered: + continue + opened = _stamp(card.get("opened_at")) + if opened is None: + out.signal("source_unreadable") + continue + second = card.get("kind") == "second_factor" + card_id = card.get("card_id") + out.intervals.append( + Interval( + "second_factor" if second else "exception", + opened, + None, + key=f"exception:{card_id}" if isinstance(card_id, str) else "", + ) + ) + out.signal("second_factor" if second else "exception_card") + return out if out.files else None + + +# -- declared field names (finding a) ------------------------------------------------- + + +def _guard_task_fields(path: Path, task_ids: set[str]) -> set[str]: + try: + doc = _read_json(path) + except _Unreadable: + return set() + if not isinstance(doc, dict) or doc.get("schema_version") != GUARD_TASK_SCHEMA: + return set() + if doc.get("task_id") not in task_ids: + return set() # another task's config declares nothing for this run + names: set[str] = set() + for key in ("expected_record", "intended_fields"): + value = doc.get(key) + if isinstance(value, dict): + names.update(n for n in map(_field_name, value) if n) + return names + + +def _verify_fields(path: Path) -> set[str]: + try: + import yaml + + doc = yaml.safe_load(path.read_text(encoding="utf-8")) + except Exception: # noqa: BLE001 - an unreadable config declares nothing + return set() + if not isinstance(doc, dict) or doc.get("schema_version", VERIFY_SCHEMA) != ( + VERIFY_SCHEMA + ): + # A compile-agent verify.yaml has no schema_version; one that names + # another version declares nothing. + return set() + names: set[str] = set() + for effect in doc.get("effects") or []: + match = effect.get("match") if isinstance(effect, dict) else None + if isinstance(match, dict): + names.update(n for n in map(_field_name, match) if n) + return names + + +#: File names a run's own config goes by: the guard task (``task.json``, +#: readiness episodes' ``guard_task.json``) and a confirmed ``verify.yaml``. +#: A ``verify.proposed.yaml`` is a proposal, not a declaration. +_CONFIG_NAMES = ("task.json", "guard_task.json", "verify.yaml") + + +def declared_fields(files: Iterable[Path], task_ids: Iterable[str]) -> set[str]: + """Field names declared by a guard task (``openadapt.guard-task/v1``: + ``expected_record`` and ``intended_fields``) whose ``task_id`` is one of + the run's, or a ``verify.yaml`` (``openadapt.verify/v1``: each effect's + ``match``) among ``files``. + Readiness reference fields come from ``case.json`` through + :func:`collect_shadow_run`. Anything else declares nothing.""" + + ids = set(task_ids) + names: set[str] = set() + for path in files: + if path.suffix in (".yaml", ".yml"): + names |= _verify_fields(path) + elif path.suffix == ".json": + names |= _guard_task_fields(path, ids) + return names + + +def config_files(files: Iterable[Path]) -> list[Path]: + """The run's own config files among the files found in it.""" + + return [p for p in files if p.name in _CONFIG_NAMES] + + +__all__ = [ + "collect_exception_folder", + "collect_fallback_result", + "collect_shadow_run", + "config_files", + "declared_fields", + "is_dispatch_result", + "is_shadow_run", +] diff --git a/packages/flow/openadapt_flow/run_ledger/store.py b/packages/flow/openadapt_flow/run_ledger/store.py new file mode 100644 index 0000000000..2222c6c2e1 --- /dev/null +++ b/packages/flow/openadapt_flow/run_ledger/store.py @@ -0,0 +1,563 @@ +"""The ledger store: one row per run, append-only, plus a private sidecar. + +Layout under ``$OPENADAPT_HOME/ledger`` (default ``~/.openadapt/ledger``):: + + rows.jsonl one entry per line (mode 0600) + ../exceptions// P6's exception cards and answers (read) + private//ledger.private.json that row's values (mode 0600) + .lock serialises add + +Each ``rows.jsonl`` line is ``{"row": , "run_digest": +..., "run_ref": ..., "added_at": ..., "declared_fields": [...]}``. +``declared_fields`` lists the field names the run's own task, verify or +readiness reference config declares; ``ledger export`` and ``push`` let only +those field names past the scrubber check (an entry without the key exempts +nothing). +A task id the scrubber would rewrite (a caller may choose it) leaves as an +opaque ``tid-<16 hex>``: an HMAC-SHA256 of the id under a per-install key in +``task-id.key`` (mode 0600), so the same task still groups together and the +text stays here. ``run_digest`` hashes the source +files (paths and bytes); ``run_ref`` hashes the run's resolved path, so a run +whose files change later (an approval answered after the first ``add``) gets +a new row and :meth:`LedgerStore.latest` keeps the newest one per run. A +second ``add`` of an unchanged run is a no-op: the store dedupes on +``(task_id, run_digest)``. + +The file is rewritten through a temporary file and ``os.replace`` under an +exclusive lock, so a reader never sees half a line and two sessions on one +machine can't interleave. +""" + +from __future__ import annotations + +import contextlib +import hashlib +import json +import os +import re +import secrets +import tempfile +import uuid +from dataclasses import dataclass +from datetime import datetime, timedelta, timezone +from pathlib import Path +from typing import Any, Iterator, Optional + +from openadapt_types.run_ledger import ( + RunLedgerFieldV1, + RunLedgerHumanV1, + RunLedgerIntervalV1, + RunLedgerModelUsageV1, + RunLedgerOutcome, + RunLedgerRowV1, +) + +from openadapt_flow.fleet._lock import exclusive_lock +from openadapt_flow.run_ledger.collect import ( + _TIER_RANK, + Collected, + Interval, + Usage, + _worse, + collect, +) +from openadapt_flow.run_ledger.outcome import Signal, decide + +PRIVATE_SCHEMA = "openadapt.run-ledger-private/v1" +#: P6's run reference (``openadapt_types.exception_card.RUN_REF_PATTERN``). +_RUN_REF = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") +_LABEL_DEFAULT = "unspecified" + + +def ledger_home(home: Optional[Path | str] = None) -> Path: + base = ( + Path(home) + if home + else Path(os.environ.get("OPENADAPT_HOME") or Path.home() / ".openadapt") + ) + return base.expanduser() / "ledger" + + +def _now() -> str: + return ( + datetime.now(timezone.utc) + .isoformat(timespec="microseconds") + .replace("+00:00", "Z") + ) + + +def _canonical(value: Any) -> bytes: + return json.dumps( + value, sort_keys=True, separators=(",", ":"), ensure_ascii=True, default=str + ).encode("utf-8") + + +def _parse(stamp: str) -> datetime: + return datetime.fromisoformat(stamp.replace("Z", "+00:00")) + + +# -- building a row ------------------------------------------------------------------- + + +@dataclass +class PrivateSidecar: + """What stays on this computer: field values and the inputs salt.""" + + row_id: str + inputs_salt: Optional[str] + fields: dict[str, dict[str, Any]] + + def to_dict(self) -> dict[str, Any]: + return { + "schema": PRIVATE_SCHEMA, + "row_id": self.row_id, + "inputs_salt": self.inputs_salt, + "fields": self.fields, + } + + def values(self) -> list[str]: + """Every value string, so an export can be scanned for them.""" + + found: list[str] = [] + for entry in self.fields.values(): + for key in ("intended", "saved"): + value = entry.get(key) + if value is not None and not isinstance(value, bool): + text = str(value) + if len(text) >= 3: + found.append(text) + return found + + +def _diff(intended: Any, saved: Any) -> Optional[str]: + if intended == saved or saved is None: + return None + import difflib + + return "\n".join( + difflib.unified_diff( + str(intended).splitlines(), + str(saved).splitlines(), + "intended", + "saved", + lineterm="", + ) + ) + + +def _usage(collected: Collected) -> RunLedgerModelUsageV1: + """Metered usage beats reported usage beats unknown; first source wins + within a rank. Usage is never summed across sources: two files often + describe the same calls.""" + + rank = {"metered": 0, "reported": 1, "unknown": 2} + usages: list[Usage] = [c.usage for c in collected.contributions if c.usage] + if not usages: + return RunLedgerModelUsageV1() + best = min(usages, key=lambda u: rank[u.cost_source]) + return RunLedgerModelUsageV1( + calls=best.calls, + input_tokens=best.input_tokens, + output_tokens=best.output_tokens, + cost_usd=float(best.cost_usd) if best.cost_usd is not None else None, + cost_source=best.cost_source, # type: ignore[arg-type] + ) + + +def _human(collected: Collected) -> RunLedgerHumanV1: + seen: dict[str, Interval] = {} + loose: list[Interval] = [] + for contribution in collected.contributions: + for interval in contribution.intervals: + if not interval.key: + loose.append(interval) + continue + known = seen.get(interval.key) + # The first reader wins; one that has the decision fills it in. + if known is None or (known.decided_at is None and interval.decided_at): + seen[interval.key] = interval + intervals: list[RunLedgerIntervalV1] = [] + dedupe: set[tuple[str, str, Optional[str]]] = set() + for interval in list(seen.values()) + loose: + key = (interval.kind, interval.opened_at, interval.decided_at) + if key in dedupe: + continue + dedupe.add(key) + decided = interval.decided_at + if decided is not None and _parse(decided) < _parse(interval.opened_at): + decided = None # a clock that runs backwards names no span + intervals.append( + RunLedgerIntervalV1( + kind=interval.kind, # type: ignore[arg-type] + opened_at=interval.opened_at, + decided_at=decided, + ) + ) + intervals.sort(key=lambda i: i.opened_at) + if not intervals: + # No interval in the run's files is not proof nobody spent time on + # it: 0 only when a source shows no person was asked, else unknown. + nobody = any(c.no_person for c in collected.contributions) + return RunLedgerHumanV1(intervention_s=0.0 if nobody else None) + spans = [i.seconds() for i in intervals] + total: Optional[float] = ( + None + if any(s is None for s in spans) + else round(sum(s or 0.0 for s in spans), 3) + ) + return RunLedgerHumanV1(intervention_s=total, intervals=tuple(intervals)) + + +def _times( + collected: Collected, +) -> tuple[Optional[str], Optional[str], Optional[float]]: + """``started_at``, ``ended_at`` and ``duration_s``. + + A source that keeps the run's own start and end (wrap, compiled runs, + flight, compile-agent) wins. Otherwise the run is bounded by the + wall-clock moments its files record (an approval asked and answered, a + shadow hold, a read-back issued, an exception card): ``ended_at`` is the + latest one, and ``started_at`` is ``ended_at`` minus the run's own + duration, or the earliest moment if that is earlier. No moment at all: + both stay ``null``. ``duration_s`` is a source's own measure, never a + span of moments. + """ + + starts = [c.started_at for c in collected.contributions if c.started_at] + ends = [c.ended_at for c in collected.contributions if c.ended_at] + started = min(starts, key=_parse) if starts else None + ended = max(ends, key=_parse) if ends else None + if started is not None and ended is not None and _parse(ended) < _parse(started): + ended = None + durations = [ + c.duration_s for c in collected.contributions if c.duration_s is not None + ] + if started is not None and ended is not None: + duration: Optional[float] = round( + (_parse(ended) - _parse(started)).total_seconds(), 3 + ) + return started, ended, duration + duration = durations[0] if durations else None + moments = [m for c in collected.contributions for m in c.moments] + for contribution in collected.contributions: + for interval in contribution.intervals: + moments += [m for m in (interval.opened_at, interval.decided_at) if m] + moments += [m for m in (started, ended) if m] + if not moments: + return started, ended, duration + times = [_parse(m) for m in moments] + last = max(times) + first = min(times) + if started is None: + begin = last - timedelta(seconds=duration) if duration is not None else first + started_dt = min(begin, first) + started = _iso(started_dt) + if ended is None: + ended = _iso(last) + return started, ended, duration + + +def _iso(moment: datetime) -> str: + return ( + moment.astimezone(timezone.utc) + .isoformat(timespec="microseconds") + .replace("+00:00", "Z") + ) + + +def _first(values: list[Optional[str]]) -> Optional[str]: + return next((v for v in values if v), None) + + +def build_row( + run: Path | str, + *, + task_type: Optional[str] = None, + task_id: Optional[str] = None, + collected: Optional[Collected] = None, + exceptions: Optional[Path] = None, +) -> tuple[RunLedgerRowV1, PrivateSidecar, str]: + """One row for ``run``, its private sidecar, and the run digest. + + ``exceptions`` is the run's P6 folder (``$OPENADAPT_HOME/exceptions/ + ``), read beside the run.""" + + collected = ( + collected + if collected is not None + else collect(Path(run), exceptions=exceptions) + ) + contributions = collected.contributions + signals: list[Signal] = [s for c in contributions for s in c.signals] + ids = list(dict.fromkeys(t for c in contributions for t in c.task_ids)) + digest = collected.digest() + if task_id is None: + # No source names the task: name it after the run's place on disk, so + # a run whose files change later keeps its task id. + where = hashlib.sha256(str(collected.root.resolve()).encode("utf-8")) + task_id = ids[0] if ids else f"run-{where.hexdigest()[:16]}" + if len(ids) > 1: + signals.append(Signal("task_id_conflict", source="ledger")) + if contributions and not signals: + # Sources were read but none decides (a flight log alone, say). + signals.append(Signal("completed_unverified", source="ledger")) + if any(s.basis == "deterministic" for s in signals): + # A model's or agent's own judgement only counts when nothing else + # speaks: it can't upgrade or downgrade a deterministic finding. + signals = [s for s in signals if s.basis == "deterministic"] + outcome, reason = decide(signals) + + fields: dict[str, str] = {} + private_fields: dict[str, dict[str, Any]] = {} + differing = 0 + for contribution in contributions: + for name, check in contribution.fields.items(): + fields[name] = _worse(fields.get(name), check) + for name, values in contribution.private_fields.items(): + intended, saved = values.get("intended"), values.get("saved") + private_fields[name] = { + "intended": intended, + "saved": saved, + "diff": _diff(intended, saved), + } + differing = max(differing, contribution.fields_differing) + differing = max(differing, sum(1 for c in fields.values() if c == "differs")) + if differing: + # A field that differs, from any source (a guard row, a read-back), + # is a caught error: it outranks a VERIFIED from anywhere else. + signals = signals + [Signal("readback_field_differs", source="ledger")] + outcome, reason = decide(signals) + + tiers = [t for c in contributions for t in c.readback_tiers if t in _TIER_RANK] + tier = max(tiers, key=lambda t: _TIER_RANK[t]) if tiers else None + if outcome is RunLedgerOutcome.VERIFIED and tier != "independent_readback": + # The weakest read decides; a VERIFIED resting on a weaker one isn't. + outcome, reason = decide( + signals + + [ + Signal( + "screen_readback_only" + if tier == "screen_readback" + else "completed_unverified", + source="ledger", + ) + ] + ) + + inputs = next((c.inputs for c in contributions if c.inputs is not None), None) + salt: Optional[str] = None + commitment: Optional[str] = None + if inputs is not None: + salt = secrets.token_hex(32) + commitment = ( + "sha256:" + + hashlib.sha256(bytes.fromhex(salt) + _canonical(inputs)).hexdigest() + ) + started, ended, duration = _times(collected) + row_id = str(uuid.uuid4()) + kinds = [c.executor_kind for c in contributions if c.executor_kind] + row = RunLedgerRowV1( + row_id=row_id, + task_id=task_id, + task_type=task_type or _LABEL_DEFAULT, + executor_kind=(kinds[0] if kinds else "unknown"), # type: ignore[arg-type] + executor_label=_first([c.executor_label for c in contributions]) + or "unlabelled", + inputs_commitment=commitment, + started_at=started, + ended_at=ended, + duration_s=duration, + model=_usage(collected), + human=_human(collected), + outcome=outcome, + outcome_reason=reason, # type: ignore[arg-type] + fields_written=tuple( + RunLedgerFieldV1(name=name, check=check) # type: ignore[arg-type] + for name, check in sorted(fields.items()) + ), + fields_differing=differing, + readback_tier=tier, # type: ignore[arg-type] + receipt_digest=_first([c.receipt_digest for c in contributions]), + sources=tuple(collected.relative(path) for path in collected.files), + ) + return row, PrivateSidecar(row_id, salt, private_fields), digest + + +# -- the store ------------------------------------------------------------------------ + + +def _write_private(path: Path, data: bytes) -> None: + path.parent.mkdir(parents=True, exist_ok=True) + os.chmod(path.parent, 0o700) + fd, tmp = tempfile.mkstemp(dir=path.parent, prefix=".tmp-") + try: + # mkstemp already creates 0600 on POSIX; Windows has no fchmod and + # keeps the file under the user's profile ACL. + if hasattr(os, "fchmod"): + os.fchmod(fd, 0o600) + with os.fdopen(fd, "wb") as handle: + handle.write(data) + handle.flush() + os.fsync(handle.fileno()) + os.replace(tmp, path) + finally: + with contextlib.suppress(FileNotFoundError): + os.unlink(tmp) + + +@dataclass +class AddResult: + row: RunLedgerRowV1 + added: bool + + +class LedgerStore: + """``$OPENADAPT_HOME/ledger``: rows, sidecars, a lock.""" + + def __init__(self, home: Optional[Path | str] = None) -> None: + self.root = ledger_home(home) + self.rows_path = self.root / "rows.jsonl" + self.private_root = self.root / "private" + + @contextlib.contextmanager + def _locked(self) -> Iterator[None]: + self.root.mkdir(parents=True, exist_ok=True) + os.chmod(self.root, 0o700) + # flock on POSIX, msvcrt.locking on Windows. + with exclusive_lock(self.root / ".lock"): + yield + + def entries(self) -> list[dict[str, Any]]: + if not self.rows_path.is_file(): + return [] + out: list[dict[str, Any]] = [] + for line in self.rows_path.read_text(encoding="utf-8").splitlines(): + if line.strip(): + out.append(json.loads(line)) + return out + + def rows(self) -> list[RunLedgerRowV1]: + return [RunLedgerRowV1.model_validate(e["row"]) for e in self.entries()] + + def latest_entries(self) -> list[dict[str, Any]]: + """The newest entry per (task_id, run), in the order they were added.""" + + keep: dict[tuple[str, str], dict[str, Any]] = {} + for entry in self.entries(): + keep[(entry["row"]["task_id"], entry.get("run_ref", ""))] = entry + return list(keep.values()) + + def latest(self) -> list[RunLedgerRowV1]: + """The newest row per (task_id, run), in the order they were added.""" + + return [RunLedgerRowV1.model_validate(e["row"]) for e in self.latest_entries()] + + def opaque_task_id(self, task_id: str) -> str: + """``tid-`` and 16 hex of HMAC-SHA256(task id) under this install's + key (created once, mode 0600): stable per task, not reversible + without the key, which never leaves this computer.""" + + import hmac + + key_path = self.root / "task-id.key" + with self._locked(): + if not key_path.is_file(): + _write_private(key_path, secrets.token_bytes(32)) + key = key_path.read_bytes() + digest = hmac.new(key, task_id.encode("utf-8"), hashlib.sha256) + return "tid-" + digest.hexdigest()[:16] + + def exceptions_dir(self, run_ref: Optional[str]) -> Optional[Path]: + """P6's folder for a run: ``exceptions/`` beside the ledger. + P6's run reference is the operator's ``exceptions serve --run-ref`` + (or a random ``mcp-...``); no run directory names it, so it is only + ever given explicitly.""" + + if run_ref is None: + return None + if not _RUN_REF.match(run_ref): + raise ValueError("a run reference is letters, digits, '.', '_' or '-'") + return self.root.parent / "exceptions" / run_ref + + def find(self, row_id: str) -> Optional[RunLedgerRowV1]: + for entry in self.entries(): + if entry["row"]["row_id"] == row_id: + return RunLedgerRowV1.model_validate(entry["row"]) + return None + + def sidecar_path(self, row_id: str) -> Path: + uuid.UUID(row_id) # refuses a path in place of an id + return self.private_root / row_id / "ledger.private.json" + + def sidecar(self, row_id: str) -> Optional[dict[str, Any]]: + path = self.sidecar_path(row_id) + if not path.is_file(): + return None + return json.loads(path.read_text(encoding="utf-8")) + + def sidecar_values(self) -> list[str]: + values: list[str] = [] + for entry in self.entries(): + doc = self.sidecar(entry["row"]["row_id"]) or {} + values.extend( + PrivateSidecar( + entry["row"]["row_id"], None, doc.get("fields") or {} + ).values() + ) + return values + + def add( + self, + run: Path | str, + *, + task_type: Optional[str] = None, + task_id: Optional[str] = None, + run_ref: Optional[str] = None, + config: tuple[Path | str, ...] = (), + approvals: Optional[Path | str] = None, + ) -> AddResult: + run = Path(run) + collected = collect( + run, + exceptions=self.exceptions_dir(run_ref), + config=tuple(Path(c) for c in config), + approvals=Path(approvals) if approvals is not None else None, + ) + row, sidecar, digest = build_row( + run, task_type=task_type, task_id=task_id, collected=collected + ) + run_ref = hashlib.sha256(str(run.resolve()).encode("utf-8")).hexdigest() + with self._locked(): + entries = self.entries() + for entry in entries: + if ( + entry["row"]["task_id"] == row.task_id + and entry.get("run_digest") == digest + ): + return AddResult(RunLedgerRowV1.model_validate(entry["row"]), False) + _write_private( + self.sidecar_path(row.row_id), + json.dumps(sidecar.to_dict(), indent=2, sort_keys=True).encode("utf-8"), + ) + entries.append( + { + "row": row.to_json(), + "run_digest": digest, + "run_ref": run_ref, + "added_at": _now(), + "declared_fields": sorted(collected.declared_fields), + } + ) + body = "".join(json.dumps(e, sort_keys=True) + "\n" for e in entries) + _write_private(self.rows_path, body.encode("utf-8")) + return AddResult(row, True) + + +__all__ = [ + "AddResult", + "LedgerStore", + "PRIVATE_SCHEMA", + "PrivateSidecar", + "build_row", + "ledger_home", +] diff --git a/packages/flow/tests/fixtures/run_ledger/agent_only_finished/agent_ledger.json b/packages/flow/tests/fixtures/run_ledger/agent_only_finished/agent_ledger.json new file mode 100644 index 0000000000..28c2aabe76 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/agent_only_finished/agent_ledger.json @@ -0,0 +1,21 @@ +{ + "calls": [ + { + "actions": [ + { + "name": "left_click" + } + ], + "input_tokens": 4, + "output_tokens": 122, + "turn": 1 + } + ], + "cost_usd": 0.1032, + "final_text": "Synthetic final text that must never be copied", + "finished": true, + "finished_at": 1792344093.0, + "model": "synthetic-model", + "model_calls": 7, + "started_at": 1792344051.0 +} diff --git a/packages/flow/tests/fixtures/run_ledger/agent_only_gave_up/agent_ledger.json b/packages/flow/tests/fixtures/run_ledger/agent_only_gave_up/agent_ledger.json new file mode 100644 index 0000000000..26692e4357 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/agent_only_gave_up/agent_ledger.json @@ -0,0 +1,11 @@ +{ + "agent": "scripted", + "cost_usd": null, + "finished": false, + "input_tokens": 10, + "model_calls": 3, + "output_tokens": 20, + "summary": "Synthetic summary", + "usage_known": false, + "wall_seconds": 12.5 +} diff --git a/packages/flow/tests/fixtures/run_ledger/compiled_halted/report.json b/packages/flow/tests/fixtures/run_ledger/compiled_halted/report.json new file mode 100644 index 0000000000..056e9d942b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/compiled_halted/report.json @@ -0,0 +1,16 @@ +{ + "est_model_cost_usd": 0.0, + "execution_outcome": "HALTED", + "model_calls": 0, + "params": { + "patient_ref": "SYN-PATIENT-0042" + }, + "production_eligible": true, + "readback": null, + "results": [], + "started_at": "2026-11-20T09:00:00.000000+00:00", + "success": false, + "total_ms": 1800.0, + "transaction_outcome": "HALTED_BEFORE_EFFECT", + "workflow_name": "synthetic-intake" +} diff --git a/packages/flow/tests/fixtures/run_ledger/compiled_halted_receipt/effect-receipt.json b/packages/flow/tests/fixtures/run_ledger/compiled_halted_receipt/effect-receipt.json new file mode 100644 index 0000000000..4fb44d7b97 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/compiled_halted_receipt/effect-receipt.json @@ -0,0 +1,117 @@ +{ + "evidence": { + "authorization": { + "approver": null, + "evaluated_by_verifier": false, + "reference_sha256": "hmac-sha256:855f7b145cb980e174d5a835017fd6bf48b510a1392a357b4bf47da4d29418ea", + "self_approved": null + }, + "checked": { + "delta": "refuted", + "frame": "held", + "source": "instruction" + }, + "contract": { + "contract_sha256": "sha256:9943a9f55e6df4c2847a4984d491569672d90c2d73edf3cf3b7f0a2cb364f276", + "minimum_effect_strength": "independent_system_of_record" + }, + "effect_verdict": "REFUTED", + "executor": { + "build_sha256": "sha256:90e62d1a7c44c73051994bd294827aa1d761aeae0fc8c4449b8a581991bc6163", + "claims_counted_as_evidence": false, + "kind": "flow_replay", + "ref_sha256": "sha256:ccefc610d2f146fd8084dd3c02c474f03f5851f894e889f38a13367a9a3ce43e", + "run_record_sha256": "hmac-sha256:6adcd940eecd0441f1dbfc568c6c4bcd7b3310c0cc4a9789cf4e36048ffd9ec1" + }, + "frame": { + "attribution": "none", + "collateral_count": 0, + "collateral_fields": [], + "collateral_kinds": [], + "concurrent_count": 0, + "frame_sha256": "sha256:d61a1174c92e1599fdba954140c5bbe6b26d3918c2eb7523bdd46bca4179c2e0", + "records_compared": 0, + "status": "held", + "target_changed_by_other": 0, + "unattributed_count": 0 + }, + "readback": { + "baseline_read_at": "2026-11-22T02:36:16Z", + "baseline_sha256": "hmac-sha256:a3c25099bee12411f0ed90e6dbc767de612d7b4fc1624136e248ba8a7864f9d9", + "checked_how": "system_of_record", + "effects": [ + { + "collateral_change_checked": true, + "effect_contract_hash": "sha256:d59db9d7fc02c90dfe9d6dcb5edd5d3ef3a8283b233c3312273ada33f733b0f3", + "expected_count": 1, + "flow_verification_tier": 1, + "kind": "record_written", + "observed_count": 0, + "observed_effect": "absent", + "stale": false, + "substrate": "rest", + "unavailable": false, + "verdict": "REFUTED" + } + ], + "max_execution_window_s": 3600, + "read_at": "2026-11-22T02:36:25Z", + "verification_tier": "independent_readback", + "verifier_identity": "sha256:dfa56efc976a24437efbe556dd8bfb410c4df27f13f45e98102b087261149956" + }, + "salting": { + "salt_commitment": "sha256:33bfa7416f08539fdba4b16bdac10bdbff85a0d2eebe137b114d09188f8b0a5a", + "scheme": "openadapt.run-salt/v1" + }, + "schema_version": "openadapt.effect-evidence/v1", + "source": { + "status": "instruction" + }, + "verifier": { + "model_calls": 0, + "name": "openadapt-flow verify-run" + }, + "write_attribution": { + "purpose": "observation", + "status": "observed" + } + }, + "receipt": { + "checked": { + "delta": "refuted", + "frame": "held", + "source": "instruction" + }, + "checked_how": "system_of_record", + "compensation_effect_verified": false, + "contracts": { + "authorization_passed": false, + "effect_passed": false, + "external_network_used": false, + "identity_passed": false, + "minimum_effect_strength": "independent_system_of_record", + "model_used": false, + "observed_effect_strength": "independent_system_of_record", + "postcondition_passed": false + }, + "delivery_uncertain": false, + "effect_verdict": "REFUTED", + "environment_id": "unnamed-environment", + "evidence_digest": "sha256:f293e4f7020164f827ab9fd1e79ea87b476bd0d3dffdd1b96b77cea0387c5e1e", + "execution_id": "verify-7f3fbe1e2ea848ca85662fc2b58b4865", + "executor_kind": "flow_replay", + "executor_ref_sha256": "sha256:ccefc610d2f146fd8084dd3c02c474f03f5851f894e889f38a13367a9a3ce43e", + "issued_at": "2026-11-22T02:36:30Z", + "nonce": "nonce-bd3405afdec74bdb8234d830cd44559e", + "oracle_tier": 2, + "outcome": "halted_before_effect", + "qualification_id": "unqualified-verify-run", + "receipt_id": "receipt-42810a47107c4487ba09fe9b4ef0add0", + "runner_id": "executor-ccefc610d2f146fd", + "schema_version": "openadapt.effect-receipt/v1", + "verification_tier": "independent_readback", + "workflow_digest": "sha256:9943a9f55e6df4c2847a4984d491569672d90c2d73edf3cf3b7f0a2cb364f276", + "workflow_version": "contract-9943a9f55e6df4c2" + }, + "schema_version": "openadapt.effect-receipt/v1" +} diff --git a/packages/flow/tests/fixtures/run_ledger/compiled_screen/report.json b/packages/flow/tests/fixtures/run_ledger/compiled_screen/report.json new file mode 100644 index 0000000000..87b2a279d4 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/compiled_screen/report.json @@ -0,0 +1,20 @@ +{ + "est_model_cost_usd": 0.0, + "execution_outcome": "VERIFIED", + "model_calls": 0, + "params": { + "patient_ref": "SYN-PATIENT-0042" + }, + "production_eligible": true, + "readback": { + "checked_how": "separate_session", + "label": "Checked in a separate session", + "minimum": "separate_session" + }, + "results": [], + "started_at": "2026-11-20T09:00:00.000000+00:00", + "success": true, + "total_ms": 1800.0, + "transaction_outcome": "VERIFIED", + "workflow_name": "synthetic-intake" +} diff --git a/packages/flow/tests/fixtures/run_ledger/compiled_verified/report.json b/packages/flow/tests/fixtures/run_ledger/compiled_verified/report.json new file mode 100644 index 0000000000..49d32b108e --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/compiled_verified/report.json @@ -0,0 +1,20 @@ +{ + "est_model_cost_usd": 0.0, + "execution_outcome": "VERIFIED", + "model_calls": 0, + "params": { + "patient_ref": "SYN-PATIENT-0042" + }, + "production_eligible": true, + "readback": { + "checked_how": "system_of_record", + "label": "Checked in the system of record", + "minimum": "system_of_record" + }, + "results": [], + "started_at": "2026-11-20T09:00:00.000000+00:00", + "success": true, + "total_ms": 1800.0, + "transaction_outcome": "VERIFIED", + "workflow_name": "synthetic-intake" +} diff --git a/packages/flow/tests/fixtures/run_ledger/dispatch_envelope_refused.json b/packages/flow/tests/fixtures/run_ledger/dispatch_envelope_refused.json new file mode 100644 index 0000000000..bb588ee485 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/dispatch_envelope_refused.json @@ -0,0 +1,52 @@ +{ + "cost_usd": 0.0, + "fallback": { + "admitted": false, + "approvals": 0, + "decisions": [ + "refused_by_gate" + ], + "fallback": true, + "gates": [ + "refused_by_hold" + ], + "repair": null, + "request_id": "fallback-084420b471744764a6e39508abc32eff", + "status": "GATE_REFUSED", + "task_record_check": { + "changed": 0, + "created": 0, + "outside_run": { + "changed": 0, + "created": 0, + "removed": 0 + }, + "passed": false, + "readable": true, + "reasons": [ + "0 new records of the task's record appeared; the task makes one (wrong record, or not saved)" + ], + "removed": 0 + } + }, + "model_calls": 0, + "outcome": "ESCALATED", + "path": "agent_fallback", + "reason": "cached_tool_result", + "receipt": null, + "receipt_binding": { + "reason": "NO_RECEIPT", + "schema": "openadapt.receipt-binding/1", + "status": "UNBOUND" + }, + "receipt_outcome": null, + "replayed": false, + "request_id": "r-119", + "run_id": "run-0002", + "seconds": 6.025, + "status": "GATE_REFUSED", + "usage": [], + "usage_known": true, + "verified": false, + "wire_checked": false +} diff --git a/packages/flow/tests/fixtures/run_ledger/dispatch_envelope_verified.json b/packages/flow/tests/fixtures/run_ledger/dispatch_envelope_verified.json new file mode 100644 index 0000000000..ba1a969387 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/dispatch_envelope_verified.json @@ -0,0 +1,54 @@ +{ + "cost_usd": 0.0, + "fallback": { + "admitted": false, + "approvals": 1, + "decisions": [ + "approved" + ], + "fallback": true, + "gates": [ + "approved_by_hold" + ], + "repair": { + "file": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/repair.json", + "opened": true, + "step_id": "step_005" + }, + "request_id": "fallback-dcd8fb13286d4db693bcdbb5d22f6ba2", + "status": "VERIFIED", + "task_record_check": { + "changed": 0, + "created": 1, + "outside_run": { + "changed": 0, + "created": 0, + "removed": 0 + }, + "passed": true, + "readable": true, + "reasons": [], + "removed": 0 + } + }, + "model_calls": 0, + "outcome": "VERIFIED", + "path": "agent_fallback", + "reason": "cached_tool_result", + "receipt": null, + "receipt_binding": { + "reason": "NO_RECEIPT", + "schema": "openadapt.receipt-binding/1", + "status": "UNBOUND" + }, + "receipt_outcome": null, + "replayed": false, + "request_id": "r-118", + "run_id": "run-0001", + "seconds": 7.976, + "status": "VERIFIED", + "usage": [], + "usage_known": true, + "verified": true, + "wire_checked": false +} diff --git a/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-answered/answer-cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9.json b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-answered/answer-cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9.json new file mode 100644 index 0000000000..0b6139a0e2 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-answered/answer-cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9.json @@ -0,0 +1,13 @@ +{ + "answer": "abort", + "approver_kind": "person", + "card_id": "sha256:cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9", + "decided_at": "2026-11-22T02:41:45.721610Z", + "kind": "second_factor", + "opened_at": "2026-11-22T02:41:42.899700Z", + "public_key": "40476c738e37f4a0e3012c097a42c379bc297f4cd49bbce3df4550e12fdef58d", + "reason": null, + "route": "cli", + "schema": "openadapt.exception-answer/v1", + "signature": "ed25519:736bf9ba41e9ad48e8f0913ed65b66ee9725738364a17e26fc17959a3a51dced9fc61bf56d0810a572e9c8488253bdf9184cf8ae51f8f6c97a0c8b54f5d27a00" +} diff --git a/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-answered/card-cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9.json b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-answered/card-cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9.json new file mode 100644 index 0000000000..38f3c5d5c3 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-answered/card-cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9.json @@ -0,0 +1,28 @@ +{ + "card_id": "sha256:cf9bd5690ea2c5a3912d15d3b120a5f9f7239cc38c26543a7df1beb40051cec9", + "choices": [ + { + "consequence": "You type the code in the live browser yourself. The run then goes on from the same screen. OpenAdapt never sees the code.", + "id": "done_by_person", + "label": "I entered the code in the browser" + }, + { + "consequence": "Nothing is saved. The run moves to the next item.", + "id": "skip", + "label": "Skip this item" + }, + { + "consequence": "Nothing more is saved. The whole run stops.", + "id": "abort", + "label": "Stop the run" + } + ], + "deadline_at": "2026-11-22T02:43:42.899700Z", + "kind": "second_factor", + "opened_at": "2026-11-22T02:41:42.899700Z", + "run_ref": "e2e-run", + "schema": "openadapt.exception-card/v1", + "screenshot_ref": null, + "summary": "The sign-in for (, MRN ) wants a code", + "task_id": "note-intake" +} diff --git a/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-expired/answer-14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40.json b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-expired/answer-14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40.json new file mode 100644 index 0000000000..a3b96181a3 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-expired/answer-14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40.json @@ -0,0 +1,13 @@ +{ + "answer": "decline", + "approver_kind": "expiry", + "card_id": "sha256:14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40", + "decided_at": null, + "kind": "second_factor", + "opened_at": "2026-11-22T02:41:59.700707Z", + "public_key": null, + "reason": "expired", + "route": "registry", + "schema": "openadapt.exception-answer/v1", + "signature": null +} diff --git a/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-expired/card-14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40.json b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-expired/card-14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40.json new file mode 100644 index 0000000000..70d497446b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/exceptions_home/exceptions/e2e-expired/card-14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40.json @@ -0,0 +1,28 @@ +{ + "card_id": "sha256:14f96152fe836e5777795a069b35df054608625cb077460726dc280e2f417b40", + "choices": [ + { + "consequence": "You type the code in the live browser yourself. The run then goes on from the same screen. OpenAdapt never sees the code.", + "id": "done_by_person", + "label": "I entered the code in the browser" + }, + { + "consequence": "Nothing is saved. The run moves to the next item.", + "id": "skip", + "label": "Skip this item" + }, + { + "consequence": "Nothing more is saved. The whole run stops.", + "id": "abort", + "label": "Stop the run" + } + ], + "deadline_at": "2026-11-22T02:42:02.700707Z", + "kind": "second_factor", + "opened_at": "2026-11-22T02:41:59.700707Z", + "run_ref": "e2e-run", + "schema": "openadapt.exception-card/v1", + "screenshot_ref": null, + "summary": "The sign-in for (, MRN ) wants a code", + "task_id": "note-intake" +} diff --git a/packages/flow/tests/fixtures/run_ledger/fallback_refused/result.json b/packages/flow/tests/fixtures/run_ledger/fallback_refused/result.json new file mode 100644 index 0000000000..89558886bd --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/fallback_refused/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "the hold did not approve 'Submit to chart'", "dir": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2", "emitted": {}, "proposed_checks": null, "record_check": null, "run1": {"agent": null, "agent_error": "GateRefused: the hold did not approve 'Submit to chart'", "attempt": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0", "gates": [{"at": 1795315002.1357582, "control": "Submit to chart", "decision": "refused_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0/gates/gate-01.png", "url": "http://127.0.0.1:54032/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 5, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 1, "observations": 5, "readbacks": 0, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "capture_failed", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [], "seconds": 6.02}, "status": "refused_by_hold", "task_key": "wrap.fallback-2e89a8e2928331ef-42b4692268c2"}, "cost_usd": 0.0, "detail": "The person at the gate refused the save.", "model_calls": 0, "path": "agent_fallback", "record_check": {}, "replay": {"fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gates": ["refused_by_hold"], "repair": null, "request_id": "fallback-084420b471744764a6e39508abc32eff", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": false, "reasons": ["0 new records of the task's record appeared; the task makes one (wrong record, or not saved)"], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/4-fallback/kept/cache/inbox/20261122T023625677474000-91a89e00.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/receipts/run-20261122T023616-6c9381/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/runs/20261122T023616590495000-5dbe8c17", "seconds": 14.152, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 6.025, "status": "GATE_REFUSED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": false, "wire_checked": false} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/fallback_refused/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0/run1.json b/packages/flow/tests/fixtures/run_ledger/fallback_refused/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0/run1.json new file mode 100644 index 0000000000..f0b63b4263 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/fallback_refused/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0/run1.json @@ -0,0 +1,43 @@ +{ + "agent": null, + "agent_error": "GateRefused: the hold did not approve 'Submit to chart'", + "attempt": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0", + "gates": [ + { + "at": 1795315002.1357582, + "control": "Submit to chart", + "decision": "refused_by_hold", + "identity": [ + "Jane Sample", + "MRN P1" + ], + "missing": [], + "screenshot": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0/gates/gate-01.png", + "url": "http://127.0.0.1:54032/?fault=ok&idempotency=demo#encounter" + } + ], + "harness": { + "actions": 5, + "gate_checks": 1, + "gate_evidence_screenshots": 1, + "gate_refusals": 1, + "observations": 5, + "readbacks": 0, + "screenshots_at_gate": 0, + "screenshots_every_turn": 0, + "screenshots_requested": 0 + }, + "jit_status": "capture_failed", + "network_metadata": { + "api_binding": "UNAVAILABLE", + "capture_closed": true, + "causal_attribution": "UNAVAILABLE", + "events": [], + "losses": [], + "mode": "metadata_only", + "records_complete": null, + "schema": "openadapt.network-metadata/v1" + }, + "readbacks": [], + "seconds": 6.02 +} diff --git a/packages/flow/tests/fixtures/run_ledger/fallback_refused_readable/result.json b/packages/flow/tests/fixtures/run_ledger/fallback_refused_readable/result.json new file mode 100644 index 0000000000..6a707b5c54 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/fallback_refused_readable/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "the hold did not approve 'Submit to chart'", "dir": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2", "emitted": {}, "proposed_checks": null, "record_check": null, "run1": {"agent": null, "agent_error": "GateRefused: the hold did not approve 'Submit to chart'", "attempt": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0", "gates": [{"at": 1795315002.1357582, "control": "Submit to chart", "decision": "refused_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0/gates/gate-01.png", "url": "http://127.0.0.1:54032/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 5, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 1, "observations": 5, "readbacks": 0, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "capture_failed", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [], "seconds": 6.02}, "status": "refused_by_hold", "task_key": "wrap.fallback-2e89a8e2928331ef-42b4692268c2"}, "cost_usd": 0.0, "detail": "The person at the gate refused the save.", "model_calls": 0, "path": "agent_fallback", "record_check": {}, "replay": {"fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gates": ["refused_by_hold"], "repair": null, "request_id": "fallback-084420b471744764a6e39508abc32eff", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": false, "readable": true, "reasons": ["0 new records of the task's record appeared; the task makes one (wrong record, or not saved)"], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/4-fallback/kept/cache/inbox/20261122T023625677474000-91a89e00.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/receipts/run-20261122T023616-6c9381/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/runs/20261122T023616590495000-5dbe8c17", "seconds": 14.152, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 6.025, "status": "GATE_REFUSED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": false, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/fallback_refused_unreadable/result.json b/packages/flow/tests/fixtures/run_ledger/fallback_refused_unreadable/result.json new file mode 100644 index 0000000000..7fb8e10779 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/fallback_refused_unreadable/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "the hold did not approve 'Submit to chart'", "dir": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2", "emitted": {}, "proposed_checks": null, "record_check": null, "run1": {"agent": null, "agent_error": "GateRefused: the hold did not approve 'Submit to chart'", "attempt": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0", "gates": [{"at": 1795315002.1357582, "control": "Submit to chart", "decision": "refused_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-084420b471744764a6e39508abc32eff/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023638-b67aa0/gates/gate-01.png", "url": "http://127.0.0.1:54032/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 5, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 1, "observations": 5, "readbacks": 0, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "capture_failed", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [], "seconds": 6.02}, "status": "refused_by_hold", "task_key": "wrap.fallback-2e89a8e2928331ef-42b4692268c2"}, "cost_usd": 0.0, "detail": "The person at the gate refused the save.", "model_calls": 0, "path": "agent_fallback", "record_check": {}, "replay": {"fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gates": ["refused_by_hold"], "repair": null, "request_id": "fallback-084420b471744764a6e39508abc32eff", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {}, "passed": false, "readable": false, "reasons": ["the system of record could not be read"], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/4-fallback/kept/cache/inbox/20261122T023625677474000-91a89e00.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/receipts/run-20261122T023616-6c9381/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/runs/20261122T023616590495000-5dbe8c17", "seconds": 14.152, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 6.025, "status": "GATE_REFUSED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": false, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/fallback_verified/result.json b/packages/flow/tests/fixtures/run_ledger/fallback_verified/result.json new file mode 100644 index 0000000000..ac75cdacc8 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/fallback_verified/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "run 1 passed its record check; a person confirms the proposed checks", "dir": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2", "emitted": {}, "proposed_checks": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/compiled/verify.proposed.yaml", "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "run1": {"agent": {"agent": "scripted", "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "calls": [], "cost_usd": 0.0, "finished": true, "images_in_requests": 0, "input_tokens": 0, "model": null, "model_calls": 0, "model_requests_started": 0, "model_seconds": 0.0, "output_tokens": 0, "prompt_tokens": 0, "summary": null, "tool_errors": 0, "tool_invocations": [], "usage_known": true, "vision": null, "wall_seconds": 3.586}, "agent_error": null, "attempt": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34", "gates": [{"at": 1795314994.656737, "control": "Submit to chart", "decision": "approved_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34/gates/gate-01.png", "url": "http://127.0.0.1:54032/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 6, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 0, "observations": 5, "readbacks": 1, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "needs_human_admit", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [{"method": "POST", "origin": null, "path": null, "phase": "request", "status": null}, {"method": "POST", "origin": null, "path": null, "phase": "response", "status": 200}], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [{"control": "Submit to chart", "detail": "1 record saved for patient_id=p1, type=Triage, with every input", "fields": ["id", "key", "note", "patient_id", "source", "type"], "outcome": "landed"}], "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "seconds": 7.799}, "status": "draft", "task_key": "wrap.fallback-2e89a8e2928331ef-42b4692268c2"}, "cost_usd": 0.0, "detail": "The agent's save was read back.", "model_calls": 0, "path": "agent_fallback", "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "replay": {"fallback": {"admitted": false, "approvals": 1, "decisions": ["approved"], "fallback": true, "gates": ["approved_by_hold"], "repair": {"file": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/repair.json", "opened": true, "step_id": "step_005"}, "request_id": "fallback-dcd8fb13286d4db693bcdbb5d22f6ba2", "status": "VERIFIED", "task_record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "reasons": [], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/4-fallback/kept/cache/inbox/20261122T023625677474000-91a89e00.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/receipts/run-20261122T023616-6c9381/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/runs/20261122T023616590495000-5dbe8c17", "seconds": 14.152, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 7.976, "status": "VERIFIED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": true, "wire_checked": false} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/fallback_verified/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34/run1.json b/packages/flow/tests/fixtures/run_ledger/fallback_verified/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34/run1.json new file mode 100644 index 0000000000..8d1c8b40f1 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/fallback_verified/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34/run1.json @@ -0,0 +1,108 @@ +{ + "agent": { + "agent": "scripted", + "cache_creation_input_tokens": 0, + "cache_read_input_tokens": 0, + "calls": [], + "cost_usd": 0.0, + "finished": true, + "images_in_requests": 0, + "input_tokens": 0, + "model": null, + "model_calls": 0, + "model_requests_started": 0, + "model_seconds": 0.0, + "output_tokens": 0, + "prompt_tokens": 0, + "summary": null, + "tool_errors": 0, + "tool_invocations": [], + "usage_known": true, + "vision": null, + "wall_seconds": 3.586 + }, + "agent_error": null, + "attempt": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34", + "gates": [ + { + "at": 1795314994.656737, + "control": "Submit to chart", + "decision": "approved_by_hold", + "identity": [ + "Jane Sample", + "MRN P1" + ], + "missing": [], + "screenshot": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34/gates/gate-01.png", + "url": "http://127.0.0.1:54032/?fault=ok&idempotency=demo#encounter" + } + ], + "harness": { + "actions": 6, + "gate_checks": 1, + "gate_evidence_screenshots": 1, + "gate_refusals": 0, + "observations": 5, + "readbacks": 1, + "screenshots_at_gate": 0, + "screenshots_every_turn": 0, + "screenshots_requested": 0 + }, + "jit_status": "needs_human_admit", + "network_metadata": { + "api_binding": "UNAVAILABLE", + "capture_closed": true, + "causal_attribution": "UNAVAILABLE", + "events": [ + { + "method": "POST", + "origin": null, + "path": null, + "phase": "request", + "status": null + }, + { + "method": "POST", + "origin": null, + "path": null, + "phase": "response", + "status": 200 + } + ], + "losses": [], + "mode": "metadata_only", + "records_complete": null, + "schema": "openadapt.network-metadata/v1" + }, + "readbacks": [ + { + "control": "Submit to chart", + "detail": "1 record saved for patient_id=p1, type=Triage, with every input", + "fields": [ + "id", + "key", + "note", + "patient_id", + "source", + "type" + ], + "outcome": "landed" + } + ], + "record_check": { + "changed": 0, + "created": 1, + "fields": [ + "id", + "key", + "note", + "patient_id", + "source", + "type" + ], + "passed": true, + "reasons": [], + "removed": 0 + }, + "seconds": 7.799 +} diff --git a/packages/flow/tests/fixtures/run_ledger/fallback_verified_readable/result.json b/packages/flow/tests/fixtures/run_ledger/fallback_verified_readable/result.json new file mode 100644 index 0000000000..27abf33b57 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/fallback_verified_readable/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "run 1 passed its record check; a person confirms the proposed checks", "dir": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2", "emitted": {}, "proposed_checks": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/compiled/verify.proposed.yaml", "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "run1": {"agent": {"agent": "scripted", "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "calls": [], "cost_usd": 0.0, "finished": true, "images_in_requests": 0, "input_tokens": 0, "model": null, "model_calls": 0, "model_requests_started": 0, "model_seconds": 0.0, "output_tokens": 0, "prompt_tokens": 0, "summary": null, "tool_errors": 0, "tool_invocations": [], "usage_known": true, "vision": null, "wall_seconds": 3.586}, "agent_error": null, "attempt": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34", "gates": [{"at": 1795314994.656737, "control": "Submit to chart", "decision": "approved_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/run/wrap.fallback-2e89a8e2928331ef-42b4692268c2/attempts/20261122T023630-fbcf34/gates/gate-01.png", "url": "http://127.0.0.1:54032/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 6, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 0, "observations": 5, "readbacks": 1, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "needs_human_admit", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [{"method": "POST", "origin": null, "path": null, "phase": "request", "status": null}, {"method": "POST", "origin": null, "path": null, "phase": "response", "status": 200}], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [{"control": "Submit to chart", "detail": "1 record saved for patient_id=p1, type=Triage, with every input", "fields": ["id", "key", "note", "patient_id", "source", "type"], "outcome": "landed"}], "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "seconds": 7.799}, "status": "draft", "task_key": "wrap.fallback-2e89a8e2928331ef-42b4692268c2"}, "cost_usd": 0.0, "detail": "The agent's save was read back.", "model_calls": 0, "path": "agent_fallback", "record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "readable": true, "reasons": [], "removed": 0}, "replay": {"fallback": {"admitted": false, "approvals": 1, "decisions": ["approved"], "fallback": true, "gates": ["approved_by_hold"], "repair": {"file": "/tmp/acp-demo-out/4-fallback/kept/cache/fallback/wrap.fallback-2e89a8e2928331ef-42b4692268c2/fallback-dcd8fb13286d4db693bcdbb5d22f6ba2/repair.json", "opened": true, "step_id": "step_005"}, "request_id": "fallback-dcd8fb13286d4db693bcdbb5d22f6ba2", "status": "VERIFIED", "task_record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "readable": true, "reasons": [], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/4-fallback/kept/cache/inbox/20261122T023625677474000-91a89e00.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/receipts/run-20261122T023616-6c9381/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/4-fallback/kept/cache/wrap.fallback-2e89a8e2928331ef-42b4692268c2/runs/20261122T023616590495000-5dbe8c17", "seconds": 14.152, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 7.976, "status": "VERIFIED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": true, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/flight_held/flight.json b/packages/flow/tests/fixtures/run_ledger/flight_held/flight.json new file mode 100644 index 0000000000..0096fd9ece --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/flight_held/flight.json @@ -0,0 +1,23 @@ +{ + "actions_count": 41, + "ended_at": "2026-11-20T10:02:30Z", + "executor_label": "browser-use", + "gate_events": [ + { + "at": "2026-11-20T10:02:00Z", + "kind": "held", + "reason": "consequential_click" + } + ], + "model": { + "calls": 12, + "cost_source": "metered", + "cost_usd": 0.231, + "input_tokens": 48000, + "output_tokens": 2100 + }, + "schema": "openadapt.flight-run/v1", + "started_at": "2026-11-20T10:00:00Z", + "task_id": "flight-task-0001", + "timeline_path": "timeline.jsonl" +} diff --git a/packages/flow/tests/fixtures/run_ledger/flight_refused/flight.json b/packages/flow/tests/fixtures/run_ledger/flight_refused/flight.json new file mode 100644 index 0000000000..3b74662638 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/flight_refused/flight.json @@ -0,0 +1,28 @@ +{ + "actions_count": 9, + "ended_at": "2026-11-20T11:01:00Z", + "executor_label": "openai-cua", + "gate_events": [ + { + "at": "2026-11-20T11:00:40Z", + "kind": "held", + "reason": "consequential_click" + }, + { + "at": "2026-11-20T11:00:41Z", + "kind": "refused", + "reason": "wrong_record" + } + ], + "model": { + "calls": 5, + "cost_source": "unknown", + "cost_usd": null, + "input_tokens": 9000, + "output_tokens": 400 + }, + "schema": "openadapt.flight-run/v1", + "started_at": "2026-11-20T11:00:00Z", + "task_id": "flight-task-0002", + "timeline_path": "timeline.jsonl" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/effect-receipt.json b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/effect-receipt.json new file mode 100644 index 0000000000..f369a40d77 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/effect-receipt.json @@ -0,0 +1,122 @@ +{ + "evidence": { + "authorization": { + "approver": { + "id": "front-desk", + "kind": "person", + "policy_ref": "sha256:9f876b763f1186b30da7c8b84d763fa03e315cf082f93a274446c31d3b9e7e07" + }, + "evaluated_by_verifier": false, + "reference_sha256": "hmac-sha256:ab12659bdd05543eba9595e1590eee6e1e4d0add28598f4479d814c008c31556", + "self_approved": false + }, + "checked": { + "delta": "held", + "frame": "held", + "source": "instruction" + }, + "contract": { + "contract_sha256": "sha256:e18a4d06277349b7bc7f5b367b5339d4e9c90f7c93636183f9a0a2b89f6fd184", + "minimum_effect_strength": "independent_system_of_record" + }, + "effect_verdict": "CONFIRMED", + "executor": { + "build_sha256": null, + "claims_counted_as_evidence": false, + "kind": "agent", + "ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "run_record_sha256": "hmac-sha256:ac9855147ed283aaf33b882760831f38cabaa8b1d7d5c9888aedc4091f19946b" + }, + "frame": { + "attribution": "none", + "collateral_count": 0, + "collateral_fields": [], + "collateral_kinds": [], + "concurrent_count": 0, + "frame_sha256": "sha256:d61a1174c92e1599fdba954140c5bbe6b26d3918c2eb7523bdd46bca4179c2e0", + "records_compared": 1, + "status": "held", + "target_changed_by_other": 0, + "unattributed_count": 0 + }, + "readback": { + "baseline_read_at": "2026-11-22T02:31:07Z", + "baseline_sha256": "hmac-sha256:d1b8d13656c037e6cc864651ce14f83128fdd854c97df292218f6449c5318ea0", + "checked_how": "system_of_record", + "effects": [ + { + "collateral_change_checked": true, + "effect_contract_hash": "sha256:d4d08070d4462269dd3d5aadbc792ff4dea9aceacc4397799619310026d2e423", + "expected_count": 1, + "flow_verification_tier": 1, + "kind": "record_written", + "observed_count": 1, + "observed_effect": "present", + "stale": false, + "substrate": "rest", + "unavailable": false, + "verdict": "CONFIRMED" + } + ], + "max_execution_window_s": 3600, + "read_at": "2026-11-22T02:31:10Z", + "verification_tier": "independent_readback", + "verifier_identity": "sha256:52c211557c4d93231d7859160f3df14b4002d720531604a6e0cfe2d9cb88b772" + }, + "salting": { + "salt_commitment": "sha256:38c4492a57721cb35be1244f578f1ca76603b51141e4a272d1b55b6fee3c71f4", + "scheme": "openadapt.run-salt/v1" + }, + "schema_version": "openadapt.effect-evidence/v1", + "source": { + "status": "instruction" + }, + "verifier": { + "model_calls": 0, + "name": "openadapt-flow verify-run" + }, + "write_attribution": { + "purpose": "observation", + "status": "observed" + } + }, + "receipt": { + "checked": { + "delta": "held", + "frame": "held", + "source": "instruction" + }, + "checked_how": "system_of_record", + "compensation_effect_verified": false, + "contracts": { + "authorization_passed": true, + "effect_passed": true, + "external_network_used": true, + "identity_passed": true, + "minimum_effect_strength": "independent_system_of_record", + "model_used": true, + "observed_effect_strength": "independent_system_of_record", + "postcondition_passed": true + }, + "correlation_id": "guard-41eb7c4087463e7ca88e09419bd35ea9", + "delivery_uncertain": false, + "effect_verdict": "CONFIRMED", + "environment_id": "unnamed-environment", + "evidence_digest": "sha256:0f4bb26e231b07bb06f9c2e9594b7dffe580b1a24188103b2e27dfcd45c75245", + "execution_id": "verify-8e44a38323d945ac807d40252c47a50f", + "executor_kind": "agent", + "executor_ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "issued_at": "2026-11-22T02:31:10Z", + "nonce": "nonce-26978d8e7165497f8c387361eed129aa", + "oracle_tier": 2, + "outcome": "verified", + "qualification_id": "unqualified-verify-run", + "receipt_id": "receipt-5aebb8ed64e34a13866a220f478d763d", + "runner_id": "executor-14dace72889585b0", + "schema_version": "openadapt.effect-receipt/v1", + "verification_tier": "independent_readback", + "workflow_digest": "sha256:e18a4d06277349b7bc7f5b367b5339d4e9c90f7c93636183f9a0a2b89f6fd184", + "workflow_version": "contract-e18a4d06277349b7" + }, + "schema_version": "openadapt.effect-receipt/v1" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/item-approval/answer-0d1212b6e74747b79cd591955a343fae.json b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/item-approval/answer-0d1212b6e74747b79cd591955a343fae.json new file mode 100644 index 0000000000..0a3bc3714c --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/item-approval/answer-0d1212b6e74747b79cd591955a343fae.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T02:31:10.463176+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:efd71edfa00508f61af4843ffdcdc80bd3286573cf8ac6186405307da91d3323a1a0045408e95ef42c7389b487d8261da69ddb5abb99f2f30e1c4508f6bd6f08","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"approve","decline_reason":null,"request_id":"0d1212b6e74747b79cd591955a343fae","request_sha256":"sha256:f9b56b472d9ad320808975f6ba60b78c60d56bfac044b729a1602975ccbfe906","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/item-approval/request-0d1212b6e74747b79cd591955a343fae.json b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/item-approval/request-0d1212b6e74747b79cd591955a343fae.json new file mode 100644 index 0000000000..f143aa2326 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/item-approval/request-0d1212b6e74747b79cd591955a343fae.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T02:31:07.223859+00:00","expires_at":"2026-11-22T06:31:07.223859+00:00","fields":[{"after":"Agent guard benchmark triage note","before":null,"label":"note"},{"after":"Triage","before":null,"label":"type"}],"form_state_kind":"dom","form_state_sha256":"sha256:d5cfd5c5b0ed635ddad7b4678e5813260157f5ab4f6b52c6adb6992aba11741e","mode":"each_item","provenance":{"actor":"agent:attached-agent","instruction_like":[],"reason":null,"seen_text":"Jane Sample — MRN P1 — DOB 1980-01-01","task_scope":"record name, patient_id; fields note, type"},"qualification_case_kind":null,"request_id":"0d1212b6e74747b79cd591955a343fae","run_id":"guard-41eb7c4087463e7ca88e09419bd35ea9","runtime_inputs_digest":"d5cfd5c5b0ed635ddad7b4678e5813260157f5ab4f6b52c6adb6992aba11741e","schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/0d1212b6e74747b79cd591955a343fae.png","screenshot_sha256":"22b513fcd843d664833328f2f05466d809982286943f9e5bf55cd15ea474580a","step_id":"save","step_index":0,"step_intent":"Save note, type","workflow_name":"guarded-save"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard_events.jsonl new file mode 100644 index 0000000000..c9737dcaf6 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard_events.jsonl @@ -0,0 +1,3 @@ +{"decision": "held_for_person", "event": "request", "guard_id": "guard-41eb7c4087463e7ca88e09419bd35ea9", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:52247", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 3.178} +{"decision": "continued", "event": "request", "hold_ms": 3315.1, "kind": "save", "method": "POST", "origin": "http://127.0.0.1:52247", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 6.434} +{"event": "read_back", "t": 6.542, "verdict": "VERIFIED"} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard_ledger_row.json new file mode 100644 index 0000000000..dc1346bd17 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/guard_ledger_row.json @@ -0,0 +1,18 @@ +{ + "approval_decided_at": "2026-11-22T02:31:10.463176+00:00", + "approval_opened_at": "2026-11-22T02:31:07.223859+00:00", + "approver_kind": "person", + "diff_path": "guard_diff.private.json", + "fields_checked": [ + "note", + "type" + ], + "fields_differing": [], + "guard_verdict": "VERIFIED", + "hold_ms": 3315.1, + "readback_tier": "independent_readback", + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-approval-approve-ok", + "verdict": "VERIFIED", + "verdict_reason": "readback_verified" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/summary.json b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/summary.json new file mode 100644 index 0000000000..3ac52eaf1f --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok/summary.json @@ -0,0 +1,24 @@ +{ + "approval": "each_item", + "blocked": [], + "ended": "read_back", + "hold_ms": [ + 3315.1 + ], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": 45.3, + "receipt_path": "/tmp/acp-demo-out/2-gated/runs/prod-approval-approve-ok/guard/guard-41eb7c4087463e7ca88e09419bd35ea9/effect-receipt.json", + "recording": "/tmp/acp-demo-out/2-gated/runs/prod-approval-approve-ok/recording", + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 7.933, + "task_id": "prod-approval-approve-ok", + "verdict": "VERIFIED", + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok_config/task.json b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok_config/task.json new file mode 100644 index 0000000000..023b9e13d7 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok_config/task.json @@ -0,0 +1 @@ +{"schema_version": "openadapt.guard-task/v1", "task_id": "prod-approval-approve-ok", "expected_record": {"patient_id": "p1", "name": "Jane Sample"}, "intended_fields": {"type": "Triage", "note": "Agent guard benchmark triage note"}} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_approved_ok_config/verify.yaml b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok_config/verify.yaml new file mode 100644 index 0000000000..bcf0263712 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_approved_ok_config/verify.yaml @@ -0,0 +1,17 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: rest + base_url: http://127.0.0.1:52247 + records_path: /api/records + records_key: records + records_complete: true +effects: + - kind: record_written + match: + patient_id: {param: patient_id} + type: {param: type} + note: {param: note} + expected_count: 1 + count_new_only: true + forbid_collateral_loss: true + timeout_s: 1.0 diff --git a/packages/flow/tests/fixtures/run_ledger/guard_declined/guard/guard-bc505242bd9f9cf1ed434c85fc65e7ad/item-approval/answer-251327afe07e4cf8bbc25ce037f1600f.json b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard/guard-bc505242bd9f9cf1ed434c85fc65e7ad/item-approval/answer-251327afe07e4cf8bbc25ce037f1600f.json new file mode 100644 index 0000000000..4ce99eb886 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard/guard-bc505242bd9f9cf1ed434c85fc65e7ad/item-approval/answer-251327afe07e4cf8bbc25ce037f1600f.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T02:31:19.941436+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:2335346b545f82ee1f3d7be89730fba375d2738eb33834a2e795a74a9bf70ad78751d9fdeab60a5b8345488fd5233694ae775e00b879e3a38e0ec5833f344000","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"decline","decline_reason":"wrong_values","request_id":"251327afe07e4cf8bbc25ce037f1600f","request_sha256":"sha256:a438b361eb9f0cbf5124d1488b34521c23aa3e006f6e2208f43866a002284162","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_declined/guard/guard-bc505242bd9f9cf1ed434c85fc65e7ad/item-approval/request-251327afe07e4cf8bbc25ce037f1600f.json b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard/guard-bc505242bd9f9cf1ed434c85fc65e7ad/item-approval/request-251327afe07e4cf8bbc25ce037f1600f.json new file mode 100644 index 0000000000..6ca65e58fd --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard/guard-bc505242bd9f9cf1ed434c85fc65e7ad/item-approval/request-251327afe07e4cf8bbc25ce037f1600f.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T02:31:16.760172+00:00","expires_at":"2026-11-22T06:31:16.760172+00:00","fields":[{"after":"Agent guard benchmark triage note","before":null,"label":"note"},{"after":"Triage","before":null,"label":"type"}],"form_state_kind":"dom","form_state_sha256":"sha256:d5cfd5c5b0ed635ddad7b4678e5813260157f5ab4f6b52c6adb6992aba11741e","mode":"each_item","provenance":{"actor":"agent:attached-agent","instruction_like":[],"reason":null,"seen_text":"Jane Sample — MRN P1 — DOB 1980-01-01","task_scope":"record name, patient_id; fields note, type"},"qualification_case_kind":null,"request_id":"251327afe07e4cf8bbc25ce037f1600f","run_id":"guard-bc505242bd9f9cf1ed434c85fc65e7ad","runtime_inputs_digest":"d5cfd5c5b0ed635ddad7b4678e5813260157f5ab4f6b52c6adb6992aba11741e","schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/251327afe07e4cf8bbc25ce037f1600f.png","screenshot_sha256":"22b513fcd843d664833328f2f05466d809982286943f9e5bf55cd15ea474580a","step_id":"save","step_index":0,"step_intent":"Save note, type","workflow_name":"guarded-save"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_declined/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard_events.jsonl new file mode 100644 index 0000000000..c602003a39 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard_events.jsonl @@ -0,0 +1,2 @@ +{"decision": "held_for_person", "event": "request", "guard_id": "guard-bc505242bd9f9cf1ed434c85fc65e7ad", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:52247", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.705} +{"code": "declined", "decision": "blocked", "event": "request", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:52247", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 5.909} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_declined/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard_ledger_row.json new file mode 100644 index 0000000000..8ed4e69f06 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_declined/guard_ledger_row.json @@ -0,0 +1,15 @@ +{ + "approval_decided_at": "2026-11-22T02:31:19.941436+00:00", + "approval_opened_at": "2026-11-22T02:31:16.760172+00:00", + "approver_kind": "none", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "guard_verdict": null, + "hold_ms": 3271.7, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-approval-decline-ok", + "verdict": "ESCALATED", + "verdict_reason": "person_declined" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_declined/summary.json b/packages/flow/tests/fixtures/run_ledger/guard_declined/summary.json new file mode 100644 index 0000000000..e4e8372996 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_declined/summary.json @@ -0,0 +1,27 @@ +{ + "approval": "each_item", + "blocked": [ + { + "code": "declined", + "hold_ms": 3271.7 + } + ], + "ended": "stopped", + "hold_ms": [], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": null, + "receipt_path": null, + "recording": "/tmp/acp-demo-out/2-gated/runs/prod-approval-decline-ok/recording", + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 14.389, + "task_id": "prod-approval-decline-ok", + "verdict": null, + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_declined_config/task.json b/packages/flow/tests/fixtures/run_ledger/guard_declined_config/task.json new file mode 100644 index 0000000000..37d7f0db10 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_declined_config/task.json @@ -0,0 +1 @@ +{"schema_version": "openadapt.guard-task/v1", "task_id": "prod-approval-decline-ok", "expected_record": {"patient_id": "p1", "name": "Jane Sample"}, "intended_fields": {"type": "Triage", "note": "Agent guard benchmark triage note"}} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_declined_config/verify.yaml b/packages/flow/tests/fixtures/run_ledger/guard_declined_config/verify.yaml new file mode 100644 index 0000000000..bcf0263712 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_declined_config/verify.yaml @@ -0,0 +1,17 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: rest + base_url: http://127.0.0.1:52247 + records_path: /api/records + records_key: records + records_complete: true +effects: + - kind: record_written + match: + patient_id: {param: patient_id} + type: {param: type} + note: {param: note} + expected_count: 1 + count_new_only: true + forbid_collateral_loss: true + timeout_s: 1.0 diff --git a/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard/guard-0b3b10d4c20d4051103b00eb2fe338c1/effect-receipt.json b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard/guard-0b3b10d4c20d4051103b00eb2fe338c1/effect-receipt.json new file mode 100644 index 0000000000..ed2d08249c --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard/guard-0b3b10d4c20d4051103b00eb2fe338c1/effect-receipt.json @@ -0,0 +1,118 @@ +{ + "evidence": { + "authorization": { + "approver": null, + "evaluated_by_verifier": false, + "reference_sha256": "hmac-sha256:fc899f00f4692bc97b79a90d1ef8894eef56cfc2194f6241400b6f87f1e7e67c", + "self_approved": null + }, + "checked": { + "delta": "refuted", + "frame": "held", + "source": "instruction" + }, + "contract": { + "contract_sha256": "sha256:677870cc4c1fb067c74c55ad355f2277b2635efc1c6c53f00a3ff447ca01572d", + "minimum_effect_strength": "independent_system_of_record" + }, + "effect_verdict": "REFUTED", + "executor": { + "build_sha256": null, + "claims_counted_as_evidence": false, + "kind": "agent", + "ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "run_record_sha256": "hmac-sha256:0d823b21e50d0390fd279cda1c27a40834a4bc13c0fa135f9f4f5b08fb8e57e0" + }, + "frame": { + "attribution": "none", + "collateral_count": 0, + "collateral_fields": [], + "collateral_kinds": [], + "concurrent_count": 0, + "frame_sha256": "sha256:d61a1174c92e1599fdba954140c5bbe6b26d3918c2eb7523bdd46bca4179c2e0", + "records_compared": 0, + "status": "held", + "target_changed_by_other": 0, + "unattributed_count": 0 + }, + "readback": { + "baseline_read_at": "2026-11-22T02:08:30Z", + "baseline_sha256": "hmac-sha256:e4c3864bdc783f5f8be695be2be2ac5cd4c126c1fb8eaf95bc7c7400be88bf1e", + "checked_how": "system_of_record", + "effects": [ + { + "collateral_change_checked": true, + "effect_contract_hash": "sha256:d986dc1c458b4105da6e05534f42ac3007de725c52dcc4474095030082e9220f", + "expected_count": 1, + "flow_verification_tier": 1, + "kind": "record_written", + "observed_count": 0, + "observed_effect": "absent", + "stale": false, + "substrate": "rest", + "unavailable": false, + "verdict": "REFUTED" + } + ], + "max_execution_window_s": 3600, + "read_at": "2026-11-22T02:08:30Z", + "verification_tier": "independent_readback", + "verifier_identity": "sha256:605844092a1ba2e76b6a8527aad9551df8a96edcfa16db4e31186e495346279f" + }, + "salting": { + "salt_commitment": "sha256:1168fa63c7fe3519552e273b757a3581fb769d095a8f6a5273829b077f7fecf3", + "scheme": "openadapt.run-salt/v1" + }, + "schema_version": "openadapt.effect-evidence/v1", + "source": { + "status": "instruction" + }, + "verifier": { + "model_calls": 0, + "name": "openadapt-flow verify-run" + }, + "write_attribution": { + "purpose": "observation", + "status": "observed" + } + }, + "receipt": { + "checked": { + "delta": "refuted", + "frame": "held", + "source": "instruction" + }, + "checked_how": "system_of_record", + "compensation_effect_verified": false, + "contracts": { + "authorization_passed": false, + "effect_passed": false, + "external_network_used": true, + "identity_passed": false, + "minimum_effect_strength": "independent_system_of_record", + "model_used": true, + "observed_effect_strength": "independent_system_of_record", + "postcondition_passed": false + }, + "correlation_id": "guard-0b3b10d4c20d4051103b00eb2fe338c1", + "delivery_uncertain": true, + "effect_verdict": "REFUTED", + "environment_id": "unnamed-environment", + "evidence_digest": "sha256:15c457bfe1fcc15b5f5abe1f91268f2f1a2e3fae2fffe60777890be2955effa2", + "execution_id": "verify-7c236e4bca174f80b5bbe197783ad7c8", + "executor_kind": "agent", + "executor_ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "issued_at": "2026-11-22T02:08:31Z", + "nonce": "nonce-b53591ae151d49bb8174a0a0cb815834", + "oracle_tier": 2, + "outcome": "reconciliation_required", + "qualification_id": "unqualified-verify-run", + "receipt_id": "receipt-1c8ba2a34d304b52823014396668a395", + "runner_id": "executor-14dace72889585b0", + "schema_version": "openadapt.effect-receipt/v1", + "verification_tier": "independent_readback", + "workflow_digest": "sha256:677870cc4c1fb067c74c55ad355f2277b2635efc1c6c53f00a3ff447ca01572d", + "workflow_version": "contract-677870cc4c1fb067" + }, + "schema_version": "openadapt.effect-receipt/v1" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard_events.jsonl new file mode 100644 index 0000000000..c37036c5bd --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard_events.jsonl @@ -0,0 +1,2 @@ +{"decision": "continued", "event": "request", "hold_ms": 14.5, "kind": "save", "method": "POST", "origin": "http://127.0.0.1:55300", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.731} +{"event": "read_back", "t": 3.917, "verdict": "RECONCILIATION_REQUIRED"} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard_ledger_row.json new file mode 100644 index 0000000000..559942e7df --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/guard_ledger_row.json @@ -0,0 +1,15 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": "guard_diff.private.json", + "fields_checked": [], + "fields_differing": [], + "guard_verdict": "RECONCILIATION_REQUIRED", + "hold_ms": 14.5, + "readback_tier": "independent_readback", + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-no-persist-00", + "verdict": "UNKNOWN", + "verdict_reason": "reconciliation_required" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_no_persist/summary.json b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/summary.json new file mode 100644 index 0000000000..8a867845c4 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_no_persist/summary.json @@ -0,0 +1,24 @@ +{ + "approval": "not_gated", + "blocked": [], + "ended": "read_back", + "hold_ms": [ + 14.5 + ], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": 1094.6, + "receipt_path": "/tmp/acp-demo-out/2-gated/runs/prod-no-persist-00/guard/guard-0b3b10d4c20d4051103b00eb2fe338c1/effect-receipt.json", + "recording": "/tmp/acp-demo-out/2-gated/runs/prod-no-persist-00/recording", + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 5.396, + "task_id": "prod-no-persist-00", + "verdict": "RECONCILIATION_REQUIRED", + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_no_persist_config/task.json b/packages/flow/tests/fixtures/run_ledger/guard_no_persist_config/task.json new file mode 100644 index 0000000000..efffe78b8a --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_no_persist_config/task.json @@ -0,0 +1 @@ +{"schema_version": "openadapt.guard-task/v1", "task_id": "prod-no-persist-00", "expected_record": {"patient_id": "p1", "name": "Jane Sample"}, "intended_fields": {"type": "Triage", "note": "Agent guard benchmark triage note"}} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_no_persist_config/verify.yaml b/packages/flow/tests/fixtures/run_ledger/guard_no_persist_config/verify.yaml new file mode 100644 index 0000000000..929a063bb3 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_no_persist_config/verify.yaml @@ -0,0 +1,17 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: rest + base_url: http://127.0.0.1:55300 + records_path: /api/records + records_key: records + records_complete: true +effects: + - kind: record_written + match: + patient_id: {param: patient_id} + type: {param: type} + note: {param: note} + expected_count: 1 + count_new_only: true + forbid_collateral_loss: true + timeout_s: 1.0 diff --git a/packages/flow/tests/fixtures/run_ledger/guard_row_p5_declined/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_row_p5_declined/guard_ledger_row.json new file mode 100644 index 0000000000..a8f49c77c1 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_row_p5_declined/guard_ledger_row.json @@ -0,0 +1,15 @@ +{ + "approval_decided_at": "2026-11-22T04:52:15.690409+00:00", + "approval_opened_at": "2026-11-22T04:52:15.686471+00:00", + "approver_kind": "none", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "guard_verdict": null, + "hold_ms": 15.8, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "task-ledger-0001", + "verdict": "ESCALATED", + "verdict_reason": "person_declined" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_row_p5_verified/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_row_p5_verified/guard_ledger_row.json new file mode 100644 index 0000000000..2a40218337 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_row_p5_verified/guard_ledger_row.json @@ -0,0 +1,17 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": "guard_diff.private.json", + "fields_checked": [ + "note" + ], + "fields_differing": [], + "guard_verdict": "VERIFIED", + "hold_ms": 69.3, + "readback_tier": "independent_readback", + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "task-ledger-0001", + "verdict": "VERIFIED", + "verdict_reason": "readback_verified" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_values_unread/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/guard_values_unread/guard_events.jsonl new file mode 100644 index 0000000000..984e0567ce --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_values_unread/guard_events.jsonl @@ -0,0 +1 @@ +{"code": "values_unread", "decision": "blocked", "event": "request", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:54672", "path_sha256": "a01c22910e2962c5", "resource_type": "Fetch", "t": 0.061} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_values_unread/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_values_unread/guard_ledger_row.json new file mode 100644 index 0000000000..3b3c3973ba --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_values_unread/guard_ledger_row.json @@ -0,0 +1,15 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "guard_verdict": null, + "hold_ms": 60.4, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "task-ledger-0001", + "verdict": "ESCALATED", + "verdict_reason": "values_unread" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_values_unread/summary.json b/packages/flow/tests/fixtures/run_ledger/guard_values_unread/summary.json new file mode 100644 index 0000000000..796330584d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_values_unread/summary.json @@ -0,0 +1,27 @@ +{ + "approval": "each_item", + "blocked": [ + { + "code": "values_unread", + "hold_ms": 60.4 + } + ], + "ended": "stopped", + "hold_ms": [], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": null, + "receipt_path": null, + "recording": null, + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": null, + "task_id": "task-ledger-0001", + "verdict": null, + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/guard_events.jsonl new file mode 100644 index 0000000000..997c21b611 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/guard_events.jsonl @@ -0,0 +1 @@ +{"code": "identity_mismatch", "decision": "blocked", "event": "request", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:55300", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.718} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/guard_ledger_row.json new file mode 100644 index 0000000000..d230c3e6c3 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/guard_ledger_row.json @@ -0,0 +1,15 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "guard_verdict": null, + "hold_ms": 13.3, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-agent-wrong-patient-00", + "verdict": "CAUGHT_ERROR", + "verdict_reason": "save_blocked_wrong_record" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/summary.json b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/summary.json new file mode 100644 index 0000000000..75c0725d51 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient/summary.json @@ -0,0 +1,27 @@ +{ + "approval": "not_gated", + "blocked": [ + { + "code": "identity_mismatch", + "hold_ms": 13.3 + } + ], + "ended": "stopped", + "hold_ms": [], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": null, + "receipt_path": null, + "recording": "/tmp/acp-demo-out/2-gated/runs/prod-agent-wrong-patient-00/recording", + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 11.179, + "task_id": "prod-agent-wrong-patient-00", + "verdict": null, + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient_config/task.json b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient_config/task.json new file mode 100644 index 0000000000..ae1e5216bd --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient_config/task.json @@ -0,0 +1 @@ +{"schema_version": "openadapt.guard-task/v1", "task_id": "prod-agent-wrong-patient-00", "expected_record": {"patient_id": "p1", "name": "Jane Sample"}, "intended_fields": {"type": "Triage", "note": "Agent guard benchmark triage note"}} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient_config/verify.yaml b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient_config/verify.yaml new file mode 100644 index 0000000000..929a063bb3 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_patient_config/verify.yaml @@ -0,0 +1,17 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: rest + base_url: http://127.0.0.1:55300 + records_path: /api/records + records_key: records + records_complete: true +effects: + - kind: record_written + match: + patient_id: {param: patient_id} + type: {param: type} + note: {param: note} + expected_count: 1 + count_new_only: true + forbid_collateral_loss: true + timeout_s: 1.0 diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard/guard-fddd1fab2045226572814c5406cf33ff/effect-receipt.json b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard/guard-fddd1fab2045226572814c5406cf33ff/effect-receipt.json new file mode 100644 index 0000000000..7344ee6bd4 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard/guard-fddd1fab2045226572814c5406cf33ff/effect-receipt.json @@ -0,0 +1,134 @@ +{ + "evidence": { + "authorization": { + "approver": null, + "evaluated_by_verifier": false, + "reference_sha256": "hmac-sha256:b3f4506e5b66fd0c9831c1221b99a59a3bbd5a840732f56c8b3976941c3b1032", + "self_approved": null + }, + "checked": { + "delta": "refuted", + "frame": "refuted", + "source": "instruction" + }, + "contract": { + "contract_sha256": "sha256:677870cc4c1fb067c74c55ad355f2277b2635efc1c6c53f00a3ff447ca01572d", + "minimum_effect_strength": "independent_system_of_record" + }, + "effect_verdict": "REFUTED", + "executor": { + "build_sha256": null, + "claims_counted_as_evidence": false, + "kind": "agent", + "ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "run_record_sha256": "hmac-sha256:d6c92ca2e5fc619aaae45903c46dc0c61fbf97ab651ce73164a00f91c0118a18" + }, + "frame": { + "attribution": "none", + "collateral_count": 1, + "collateral_fields": [ + "id", + "key", + "note", + "patient_id", + "source", + "type" + ], + "collateral_kinds": [ + "added" + ], + "concurrent_count": 0, + "frame_sha256": "sha256:d61a1174c92e1599fdba954140c5bbe6b26d3918c2eb7523bdd46bca4179c2e0", + "moves": [ + { + "change": "added", + "row": false, + "table": "" + } + ], + "records_compared": 1, + "status": "refuted", + "target_changed_by_other": 0, + "unattributed_count": 1 + }, + "readback": { + "baseline_read_at": "2026-11-22T02:08:01Z", + "baseline_sha256": "hmac-sha256:d11d1437ff66a1a4ddab08aca5eb8501c600bacb3692c9f9939fdd99b3df0c29", + "checked_how": "system_of_record", + "effects": [ + { + "collateral_change_checked": true, + "effect_contract_hash": "sha256:e3490284dae29ea9928378e2507db89493eaeb8c393e52982f535aedd1418ece", + "expected_count": 1, + "flow_verification_tier": 1, + "kind": "record_written", + "observed_count": 0, + "observed_effect": "absent", + "stale": false, + "substrate": "rest", + "unavailable": false, + "verdict": "REFUTED" + } + ], + "max_execution_window_s": 3600, + "read_at": "2026-11-22T02:08:01Z", + "verification_tier": "independent_readback", + "verifier_identity": "sha256:605844092a1ba2e76b6a8527aad9551df8a96edcfa16db4e31186e495346279f" + }, + "salting": { + "salt_commitment": "sha256:91d1e3f9340710ecbab99a3619d22774ef1736ad00f55bbb8b5ef9b75a171913", + "scheme": "openadapt.run-salt/v1" + }, + "schema_version": "openadapt.effect-evidence/v1", + "source": { + "status": "instruction" + }, + "verifier": { + "model_calls": 0, + "name": "openadapt-flow verify-run" + }, + "write_attribution": { + "purpose": "observation", + "status": "observed" + } + }, + "receipt": { + "checked": { + "delta": "refuted", + "frame": "refuted", + "source": "instruction" + }, + "checked_how": "system_of_record", + "compensation_effect_verified": false, + "contracts": { + "authorization_passed": false, + "effect_passed": false, + "external_network_used": true, + "identity_passed": false, + "minimum_effect_strength": "independent_system_of_record", + "model_used": true, + "observed_effect_strength": "independent_system_of_record", + "postcondition_passed": false + }, + "correlation_id": "guard-fddd1fab2045226572814c5406cf33ff", + "delivery_uncertain": true, + "effect_verdict": "REFUTED", + "environment_id": "unnamed-environment", + "evidence_digest": "sha256:55c5493a71b12f215349ab74f57352662cf2242de841de6590dda368aa6caf05", + "execution_id": "verify-ed6cf58cdadd4b6bbd06ca3ed8771be7", + "executor_kind": "agent", + "executor_ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "issued_at": "2026-11-22T02:08:02Z", + "nonce": "nonce-323cfdaa79ba413f98cdbc04c81385e4", + "oracle_tier": 2, + "outcome": "reconciliation_required", + "qualification_id": "unqualified-verify-run", + "receipt_id": "receipt-53956456949846748ddd0e9a73e033fe", + "runner_id": "executor-14dace72889585b0", + "schema_version": "openadapt.effect-receipt/v1", + "verification_tier": "independent_readback", + "workflow_digest": "sha256:677870cc4c1fb067c74c55ad355f2277b2635efc1c6c53f00a3ff447ca01572d", + "workflow_version": "contract-677870cc4c1fb067" + }, + "schema_version": "openadapt.effect-receipt/v1" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard_events.jsonl new file mode 100644 index 0000000000..13a9eb389b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard_events.jsonl @@ -0,0 +1,2 @@ +{"decision": "continued", "event": "request", "hold_ms": 12.0, "kind": "save", "method": "POST", "origin": "http://127.0.0.1:55300", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.66} +{"event": "read_back", "t": 3.802, "verdict": "REFUTED"} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard_ledger_row.json new file mode 100644 index 0000000000..b389dfcff1 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/guard_ledger_row.json @@ -0,0 +1,20 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": "guard_diff.private.json", + "fields_checked": [ + "note", + "type" + ], + "fields_differing": [ + "note" + ], + "guard_verdict": "REFUTED", + "hold_ms": 12.0, + "readback_tier": "independent_readback", + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-agent-wrong-value-00", + "verdict": "CAUGHT_ERROR", + "verdict_reason": "readback_refuted" +} diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/summary.json b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/summary.json new file mode 100644 index 0000000000..c70ad9dc9a --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value/summary.json @@ -0,0 +1,24 @@ +{ + "approval": "not_gated", + "blocked": [], + "ended": "read_back", + "hold_ms": [ + 12.0 + ], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": 1075.7, + "receipt_path": "/tmp/acp-demo-out/2-gated/runs/prod-agent-wrong-value-00/guard/guard-fddd1fab2045226572814c5406cf33ff/effect-receipt.json", + "recording": "/tmp/acp-demo-out/2-gated/runs/prod-agent-wrong-value-00/recording", + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 5.158, + "task_id": "prod-agent-wrong-value-00", + "verdict": "REFUTED", + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_value_config/task.json b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value_config/task.json new file mode 100644 index 0000000000..ef3c73c52c --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value_config/task.json @@ -0,0 +1 @@ +{"schema_version": "openadapt.guard-task/v1", "task_id": "prod-agent-wrong-value-00", "expected_record": {"patient_id": "p1", "name": "Jane Sample"}, "intended_fields": {"type": "Triage", "note": "Agent guard benchmark triage note"}} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/guard_wrong_value_config/verify.yaml b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value_config/verify.yaml new file mode 100644 index 0000000000..929a063bb3 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/guard_wrong_value_config/verify.yaml @@ -0,0 +1,17 @@ +schema_version: openadapt.verify/v1 +verifier: + kind: rest + base_url: http://127.0.0.1:55300 + records_path: /api/records + records_key: records + records_complete: true +effects: + - kind: record_written + match: + patient_id: {param: patient_id} + type: {param: type} + note: {param: note} + expected_count: 1 + count_new_only: true + forbid_collateral_loss: true + timeout_s: 1.0 diff --git a/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/answer-4c7c5947e9484d4f9be73a395e124523.json b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/answer-4c7c5947e9484d4f9be73a395e124523.json new file mode 100644 index 0000000000..f6cd07045b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/answer-4c7c5947e9484d4f9be73a395e124523.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T05:15:04.841678+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:cf55610e70f49426816a060397b41f706850e7fc7d91cb5b62cb8825a51e8c294430b3e5b0eb4f7e92578c924b4fea4f8f996a43c1773679769b2f9f174e1107","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"decline","decline_reason":"wrong_values","request_id":"4c7c5947e9484d4f9be73a395e124523","request_sha256":"sha256:2f66bd073f6ab8f9bd9313dc50fd54edb0d5f2bb61ec7f94c3adaf81411ce543","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/request-4c7c5947e9484d4f9be73a395e124523.json b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/request-4c7c5947e9484d4f9be73a395e124523.json new file mode 100644 index 0000000000..7cb36567d7 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/request-4c7c5947e9484d4f9be73a395e124523.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T05:15:04.821481+00:00","expires_at":"2026-11-22T05:15:34.821481+00:00","form_state_kind":"screen_text","form_state_sha256":"sha256:7a8837891b7d8fef53fc3a9675a0290ce159dd7f9147a631c17e73c5e603b76d","mode":"each_item","provenance":{"actor":"agent:wrap-fallback","instruction_like":[],"reason":null,"seen_text":null,"task_scope":"the task's own record, after the compiled program stopped before saving"},"qualification_case_kind":null,"request_id":"4c7c5947e9484d4f9be73a395e124523","run_id":"fallback-26d212a3c6483cd967c68cb19948794c25abc33d","runtime_inputs_digest":null,"schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/4c7c5947e9484d4f9be73a395e124523.png","screenshot_sha256":"9b4f544a921325282282835b2e6b3b4a362a4961c6137902425861773f34f707","step_id":"save-1","step_index":0,"step_intent":"Press 'Submit to chart' on the record showing Jane Sample, MRN P1","workflow_name":"wrap-fallback"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/answer-c60a0ed817be4254b1ec377418c5d91d.json b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/answer-c60a0ed817be4254b1ec377418c5d91d.json new file mode 100644 index 0000000000..ce28138d8e --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/answer-c60a0ed817be4254b1ec377418c5d91d.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T05:14:52.372891+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:d56c77798923e77f761a87fbaba5e12fdd54a352d083f8287ae7e3646f476fc3044ad7d8d9c1eed08336440d7a66e85a945999f22b92fac8b31310cff0533702","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"approve","decline_reason":null,"request_id":"c60a0ed817be4254b1ec377418c5d91d","request_sha256":"sha256:1459ab8c22cd004e09c6624be0dd8e6ec129d6ad71adbc4894ed69e7163349c7","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/request-c60a0ed817be4254b1ec377418c5d91d.json b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/request-c60a0ed817be4254b1ec377418c5d91d.json new file mode 100644 index 0000000000..156ca2b0fc --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_approvals/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/request-c60a0ed817be4254b1ec377418c5d91d.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T05:14:52.311278+00:00","expires_at":"2026-11-22T05:15:22.311278+00:00","form_state_kind":"screen_text","form_state_sha256":"sha256:7a8837891b7d8fef53fc3a9675a0290ce159dd7f9147a631c17e73c5e603b76d","mode":"each_item","provenance":{"actor":"agent:wrap-fallback","instruction_like":[],"reason":null,"seen_text":null,"task_scope":"the task's own record, after the compiled program stopped before saving"},"qualification_case_kind":null,"request_id":"c60a0ed817be4254b1ec377418c5d91d","run_id":"fallback-ca9527beac76e04f400612a30e06cb3373c2914b","runtime_inputs_digest":null,"schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/c60a0ed817be4254b1ec377418c5d91d.png","screenshot_sha256":"9b4f544a921325282282835b2e6b3b4a362a4961c6137902425861773f34f707","step_id":"save-1","step_index":0,"step_intent":"Press 'Submit to chart' on the record showing Jane Sample, MRN P1","workflow_name":"wrap-fallback"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/case.json b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/case.json new file mode 100644 index 0000000000..55d6ec49c0 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/case.json @@ -0,0 +1,19 @@ +{ + "agent_time_s": 7.603, + "contamination": null, + "double_save": false, + "extra_held_writes": 0, + "fields": [], + "human_time_s": 0.963, + "identity": null, + "landed_writes": 0, + "model_calls_metered": 2, + "model_cost_source": "metered", + "model_cost_usd": 0.023775, + "out_of_scope_requests": 0, + "reason": "no_write_held", + "schema": "openadapt.readiness-case/v1", + "status": "NOT_CHECKED", + "task_id": "readiness-mockmed-0000", + "undeclared_fields": 0 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/egress.json b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/egress.json new file mode 100644 index 0000000000..30ce059121 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/egress.json @@ -0,0 +1,8 @@ +{ + "cost_source": "metered", + "cost_usd": 0.023775, + "enforced": true, + "mode": "scrubbed", + "model_calls": 2, + "refused_requests": 0 +} diff --git a/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/egress/timeline.jsonl b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/egress/timeline.jsonl new file mode 100644 index 0000000000..e3d4f99c6d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/egress/timeline.jsonl @@ -0,0 +1,4 @@ +{"at": "2026-11-22T05:10:58.080Z", "frame": "frames/41c1a26769ffa3154207.png", "kind": "frame", "provider": "anthropic", "source": "request", "t": 2.438} +{"at": "2026-11-22T05:11:00.219Z", "cost_usd": 0.016548, "kind": "model_call", "model": "claude-sonnet-5-5", "provider": "anthropic", "seconds": 2.133, "status": 200, "streamed": false, "t": 4.577, "usage": {"cache_creation_input_tokens": 6092, "input_tokens": 4, "output_tokens": 131}} +{"action": {"action": "screenshot"}, "at": "2026-11-22T05:11:00.219Z", "dialect": "anthropic", "kind": "model_action", "note": null, "ops": [{"dx": 0, "dy": 0, "fill": false, "kind": "observe", "seconds": 0.0}], "provider": "anthropic", "t": 4.577} +{"at": "2026-11-22T05:11:03.073Z", "cost_usd": 0.0072274, "kind": "model_call", "model": "claude-sonnet-5-5", "provider": "anthropic", "seconds": 2.778, "status": 200, "streamed": false, "t": 7.431, "usage": {"cache_creation_input_tokens": 1506, "cache_read_input_tokens": 6092, "input_tokens": 2, "output_tokens": 224}} diff --git a/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/run.json b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/run.json new file mode 100644 index 0000000000..3c774db00f --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/run.json @@ -0,0 +1,43 @@ +{ + "agent_wall_s": 7.603, + "before_screen": false, + "double_save": false, + "egress": { + "cost_source": "metered", + "cost_usd": 0.023775, + "enforced": true, + "mode": "scrubbed", + "model_calls": 2, + "reason": null, + "refused": false, + "refused_requests": 0 + }, + "ended": "agent_exited", + "exit_code": 0, + "extra_target_writes": 0, + "held": 0, + "landed_writes": 0, + "model_cost_source": "metered", + "model_cost_usd": 0.023775, + "notes": [], + "other_origin_refused": 0, + "proposed": false, + "requests": {}, + "schema": "openadapt.readiness-task-run/v1", + "session": "fresh", + "status": "NO_WRITE_HELD", + "target_gate": { + "errors": [], + "extra_targets": {}, + "gate_lost": false, + "ungated_targets": {} + }, + "task_id": "readiness-mockmed-0000", + "usage": { + "calls": 2, + "cost_usd": 0.023775, + "input_tokens": 13696, + "model": "claude-sonnet-5-5", + "output_tokens": 355 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/usage.json b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/usage.json new file mode 100644 index 0000000000..f98a6a4efd --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_claude_no_write/usage.json @@ -0,0 +1,10 @@ +{ + "calls": 2, + "cost_usd": 0.023775, + "final_line": "RESULT: NOT DONE The patient name and MRN were not given (only placeholders), so I couldn't identify which referral to open.", + "input_tokens": 13696, + "model": "claude-sonnet-5-5", + "output_tokens": 355, + "schema": "openadapt.agent-usage/v1", + "stopped": null +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_envelope_approved.json b/packages/flow/tests/fixtures/run_ledger/run2_envelope_approved.json new file mode 100644 index 0000000000..0a09140ff0 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_envelope_approved.json @@ -0,0 +1 @@ +{"cost_usd": 0.0, "fallback": {"admitted": false, "approvals": 1, "decisions": ["approved"], "fallback": true, "gate_answers": [{"answer_sha256": "sha256:107c100bf3091a1d27e0ec38fe52299675dc1013ae8860be52decfdd8d2651bd", "decision": "approved", "request_id": "c60a0ed817be4254b1ec377418c5d91d", "request_sha256": "sha256:1459ab8c22cd004e09c6624be0dd8e6ec129d6ad71adbc4894ed69e7163349c7", "route": "desktop_run_it", "signer": "front-desk"}], "gates": ["approved_by_hold"], "parent_request_id": "dispatch-drift-approved", "readings_agree": true, "repair": {"file": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/repair.json", "opened": true, "step_id": "step_005"}, "request_id": "fallback-ca9527beac76e04f400612a30e06cb3373c2914b", "run_status": "VERIFIED", "status": "VERIFIED", "task_record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "readable": true, "reasons": [], "removed": 0}}, "model_calls": 0, "outcome": "VERIFIED", "path": "agent_fallback", "reason": "cached_tool_result", "receipt": null, "receipt_binding": {"reason": "NO_RECEIPT", "schema": "openadapt.receipt-binding/1", "status": "UNBOUND"}, "receipt_outcome": null, "replayed": false, "request_id": "dispatch-drift-approved", "run_id": "run-4bb6828905cd4c91a781a40a", "seconds": 12.497, "status": "VERIFIED", "usage": [], "usage_known": true, "verified": true, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/run2_envelope_declined.json b/packages/flow/tests/fixtures/run_ledger/run2_envelope_declined.json new file mode 100644 index 0000000000..10b40e148c --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_envelope_declined.json @@ -0,0 +1 @@ +{"cost_usd": 0.0, "fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gate_answers": [{"code": "declined", "decision": "refused", "request_id": "4c7c5947e9484d4f9be73a395e124523", "request_sha256": "sha256:2f66bd073f6ab8f9bd9313dc50fd54edb0d5f2bb61ec7f94c3adaf81411ce543"}], "gates": ["refused_by_hold"], "parent_request_id": "dispatch-drift-declined", "readings_agree": true, "repair": null, "request_id": "fallback-26d212a3c6483cd967c68cb19948794c25abc33d", "run_status": "GATE_REFUSED", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": false, "readable": true, "reasons": ["0 new records of the task's record appeared; the task makes one (wrong record, or not saved)"], "removed": 0}}, "model_calls": 0, "outcome": "ESCALATED", "path": "agent_fallback", "reason": "cached_tool_result", "receipt": null, "receipt_binding": {"reason": "NO_RECEIPT", "schema": "openadapt.receipt-binding/1", "status": "UNBOUND"}, "receipt_outcome": null, "replayed": false, "request_id": "dispatch-drift-declined", "run_id": "run-6e12e085b9df4c01bc4ef228", "seconds": 5.673, "status": "GATE_REFUSED", "usage": [], "usage_known": true, "verified": false, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/run2_envelope_happy.json b/packages/flow/tests/fixtures/run_ledger/run2_envelope_happy.json new file mode 100644 index 0000000000..7f853ae2ec --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_envelope_happy.json @@ -0,0 +1 @@ +{"cost_usd": 0.0, "fallback": null, "model_calls": 0, "outcome": "VERIFIED", "path": "program", "reason": "cached_tool_result", "receipt": "/tmp/acp-demo-out/run2/4-fallback/cache/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/receipts/run-20261122T051431-627903/effect-receipt.json", "receipt_binding": {"receipt_bytes": 5139, "receipt_sha256": "ec0cf70565e0ebb2320561b76112c2c2e77d642483790c4fd1646711b0f1fd10", "request_context": {"fingerprint": "f96ab3453468c11dee44c50bfa1e4fe821a46b13a227b85c783261655f7f729b", "request_ref": "sha256:b85916bf3f09cc19d4ac57046706bf955a13b3a263d315602b931e7507ef1aad", "run_id": "run-7c338e1ee00f45699ccc1c58", "schema": "openadapt.request-context/1", "workflow": "wrap:bf88195d8940299c6ded6fad3061c86539280e66aafdf6dbc83a18564254f02f"}, "schema": "openadapt.receipt-binding/1", "status": "BOUND"}, "receipt_outcome": "VERIFIED", "replayed": false, "request_id": "dispatch-happy", "run_id": "run-7c338e1ee00f45699ccc1c58", "seconds": 5.774, "status": "VERIFIED", "usage": [], "usage_known": true, "verified": true, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/run2_fallback_approved/result.json b/packages/flow/tests/fixtures/run_ledger/run2_fallback_approved/result.json new file mode 100644 index 0000000000..42bb4f93bd --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_fallback_approved/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "run 1 passed its record check; a person confirms the proposed checks", "dir": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8", "emitted": {}, "proposed_checks": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/compiled/verify.proposed.yaml", "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "run1": {"agent": {"agent": "scripted", "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "calls": [], "cost_usd": 0.0, "finished": true, "images_in_requests": 0, "input_tokens": 0, "model": null, "model_calls": 0, "model_requests_started": 0, "model_seconds": 0.0, "output_tokens": 0, "prompt_tokens": 0, "summary": null, "tool_errors": 0, "tool_invocations": [], "usage_known": true, "vision": null, "wall_seconds": 3.891}, "agent_error": null, "attempt": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/attempts/20261122T051448-e5dd71", "gates": [{"at": 1795324492.30799, "control": "Submit to chart", "decision": "approved_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/attempts/20261122T051448-e5dd71/gates/gate-01.png", "url": "http://127.0.0.1:53906/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 6, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 0, "observations": 5, "readbacks": 1, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "needs_human_admit", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [{"method": "POST", "origin": null, "path": null, "phase": "request", "status": null}, {"method": "POST", "origin": null, "path": null, "phase": "response", "status": 200}], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [{"control": "Submit to chart", "detail": "1 record saved for patient_id=p1, type=Triage, with every input", "fields": ["id", "key", "note", "patient_id", "source", "type"], "outcome": "landed"}], "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "seconds": 12.435}, "status": "draft", "task_key": "wrap.fallback-bf88195d8940299c-4e5d12f4c2c8"}, "cost_usd": 0.0, "detail": "The agent's save was read back.", "model_calls": 0, "path": "agent_fallback", "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "replay": {"fallback": {"admitted": false, "approvals": 1, "decisions": ["approved"], "fallback": true, "gate_answers": [{"answer_sha256": "sha256:107c100bf3091a1d27e0ec38fe52299675dc1013ae8860be52decfdd8d2651bd", "decision": "approved", "request_id": "c60a0ed817be4254b1ec377418c5d91d", "request_sha256": "sha256:1459ab8c22cd004e09c6624be0dd8e6ec129d6ad71adbc4894ed69e7163349c7", "route": "desktop_run_it", "signer": "front-desk"}], "gates": ["approved_by_hold"], "parent_request_id": "dispatch-drift-approved", "readings_agree": true, "repair": {"file": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/repair.json", "opened": true, "step_id": "step_005"}, "request_id": "fallback-ca9527beac76e04f400612a30e06cb3373c2914b", "run_status": "VERIFIED", "status": "VERIFIED", "task_record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "readable": true, "reasons": [], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/run2/4-fallback/cache/inbox/20261122T051443663358000-31881f7b.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/run2/4-fallback/cache/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/receipts/run-20261122T051437-49cea8/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/run2/4-fallback/cache/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/runs/20261122T051437784684000-69fa6f6b", "seconds": 10.93, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 12.497, "status": "VERIFIED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": true, "wire_checked": false} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_fallback_approved_config/verify.yaml b/packages/flow/tests/fixtures/run_ledger/run2_fallback_approved_config/verify.yaml new file mode 100644 index 0000000000..c44153ef08 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_fallback_approved_config/verify.yaml @@ -0,0 +1,29 @@ +# Confirmed by dana.reviewer at 2026-11-22T05:14:25Z from verify.proposed.yaml. +schema_version: openadapt.verify/v1 +verifier: + kind: rest + records_path: /api/db + records_key: records + records_complete: true + base_url: http://127.0.0.1:53906 + timeout_s: 2.0 + poll_interval_s: 0.05 +effects: +- kind: record_written + match: + note: + param: note + patient_id: + literal: p1 + type: + literal: Triage + composite_key: + note: + param: note + patient_id: + literal: p1 + type: + literal: Triage + count_new_only: true + probe: exactly one new record with note=parameter 'note', patient_id='p1', type='Triage' + (confirmed by dana.reviewer) diff --git a/packages/flow/tests/fixtures/run_ledger/run2_fallback_declined/result.json b/packages/flow/tests/fixtures/run_ledger/run2_fallback_declined/result.json new file mode 100644 index 0000000000..97f2b81e83 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_fallback_declined/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "the hold did not approve 'Submit to chart'", "dir": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/run/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8", "emitted": {}, "proposed_checks": null, "record_check": null, "run1": {"agent": null, "agent_error": "GateRefused: the hold did not approve 'Submit to chart'", "attempt": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/run/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/attempts/20261122T051501-0c25ee", "gates": [{"at": 1795324504.818132, "control": "Submit to chart", "decision": "refused_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/run2/4-fallback/cache/fallback/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/run/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/attempts/20261122T051501-0c25ee/gates/gate-01.png", "url": "http://127.0.0.1:53906/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 5, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 1, "observations": 5, "readbacks": 0, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "capture_failed", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [], "seconds": 5.669}, "status": "refused_by_hold", "task_key": "wrap.fallback-bf88195d8940299c-4e5d12f4c2c8"}, "cost_usd": 0.0, "detail": "The person at the gate refused the save.", "model_calls": 0, "path": "agent_fallback", "record_check": {}, "replay": {"fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gate_answers": [{"code": "declined", "decision": "refused", "request_id": "4c7c5947e9484d4f9be73a395e124523", "request_sha256": "sha256:2f66bd073f6ab8f9bd9313dc50fd54edb0d5f2bb61ec7f94c3adaf81411ce543"}], "gates": ["refused_by_hold"], "parent_request_id": "dispatch-drift-declined", "readings_agree": true, "repair": null, "request_id": "fallback-26d212a3c6483cd967c68cb19948794c25abc33d", "run_status": "GATE_REFUSED", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": false, "readable": true, "reasons": ["0 new records of the task's record appeared; the task makes one (wrong record, or not saved)"], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/run2/4-fallback/cache/inbox/20261122T051443663358000-31881f7b.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/run2/4-fallback/cache/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/receipts/run-20261122T051437-49cea8/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/run2/4-fallback/cache/wrap.fallback-bf88195d8940299c-4e5d12f4c2c8/runs/20261122T051437784684000-69fa6f6b", "seconds": 10.93, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 5.673, "status": "GATE_REFUSED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": false, "wire_checked": false} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/effect-receipt.json b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/effect-receipt.json new file mode 100644 index 0000000000..87777744bf --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/effect-receipt.json @@ -0,0 +1,122 @@ +{ + "evidence": { + "authorization": { + "approver": { + "id": "front-desk", + "kind": "person", + "policy_ref": "sha256:9f876b763f1186b30da7c8b84d763fa03e315cf082f93a274446c31d3b9e7e07" + }, + "evaluated_by_verifier": false, + "reference_sha256": "hmac-sha256:3f3a78a7a79ad71fecb3d218e6de1cfce4765129551ac26df830f8055db24734", + "self_approved": false + }, + "checked": { + "delta": "held", + "frame": "held", + "source": "instruction" + }, + "contract": { + "contract_sha256": "sha256:54ce4864d68e01f7d260b58aba8b9da11c18bf01457d22af0a8dbb84c65d4ee8", + "minimum_effect_strength": "independent_system_of_record" + }, + "effect_verdict": "CONFIRMED", + "executor": { + "build_sha256": null, + "claims_counted_as_evidence": false, + "kind": "agent", + "ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "run_record_sha256": "hmac-sha256:c9cd9e6681d19ae60bf9ca3f0ed686cb00d8faf6da71ca151bae45d95662d0bf" + }, + "frame": { + "attribution": "none", + "collateral_count": 0, + "collateral_fields": [], + "collateral_kinds": [], + "concurrent_count": 0, + "frame_sha256": "sha256:d61a1174c92e1599fdba954140c5bbe6b26d3918c2eb7523bdd46bca4179c2e0", + "records_compared": 1, + "status": "held", + "target_changed_by_other": 0, + "unattributed_count": 0 + }, + "readback": { + "baseline_read_at": "2026-11-22T05:02:08Z", + "baseline_sha256": "hmac-sha256:8e60d4add1ea706f800aefcd796cb61fccce922287aa98e0a03d26285f2ff719", + "checked_how": "system_of_record", + "effects": [ + { + "collateral_change_checked": true, + "effect_contract_hash": "sha256:c1937a89e848f4dd558643170b7d03c3497d97a7d135f69b8546541edb1e58a7", + "expected_count": 1, + "flow_verification_tier": 1, + "kind": "record_written", + "observed_count": 1, + "observed_effect": "present", + "stale": false, + "substrate": "rest", + "unavailable": false, + "verdict": "CONFIRMED" + } + ], + "max_execution_window_s": 3600, + "read_at": "2026-11-22T05:02:12Z", + "verification_tier": "independent_readback", + "verifier_identity": "sha256:18aba2210968ad15308a15cc3cbb6b58076ba126075b59585a0fb1889330fdb1" + }, + "salting": { + "salt_commitment": "sha256:62b2e61e923c90c8c7beb232d8429c2cb41d5c1a858ccabe67ec69769bc5401f", + "scheme": "openadapt.run-salt/v1" + }, + "schema_version": "openadapt.effect-evidence/v1", + "source": { + "status": "instruction" + }, + "verifier": { + "model_calls": 0, + "name": "openadapt-flow verify-run" + }, + "write_attribution": { + "purpose": "observation", + "status": "observed" + } + }, + "receipt": { + "checked": { + "delta": "held", + "frame": "held", + "source": "instruction" + }, + "checked_how": "system_of_record", + "compensation_effect_verified": false, + "contracts": { + "authorization_passed": true, + "effect_passed": true, + "external_network_used": true, + "identity_passed": true, + "minimum_effect_strength": "independent_system_of_record", + "model_used": true, + "observed_effect_strength": "independent_system_of_record", + "postcondition_passed": true + }, + "correlation_id": "guard-b6ca7b52f361c50713836050eca7c7f7", + "delivery_uncertain": false, + "effect_verdict": "CONFIRMED", + "environment_id": "unnamed-environment", + "evidence_digest": "sha256:9298d8c9085958064691986988dfced69e2801caf0c5b9621d06a900ce4e41c8", + "execution_id": "verify-4835969cb17c4b0abf6a7b9fd02575bb", + "executor_kind": "agent", + "executor_ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "issued_at": "2026-11-22T05:02:12Z", + "nonce": "nonce-0c6e32f341084778848e646887783c7d", + "oracle_tier": 2, + "outcome": "verified", + "qualification_id": "unqualified-verify-run", + "receipt_id": "receipt-a1ba75a70f4c45c2b0372b149f47f1bc", + "runner_id": "executor-14dace72889585b0", + "schema_version": "openadapt.effect-receipt/v1", + "verification_tier": "independent_readback", + "workflow_digest": "sha256:54ce4864d68e01f7d260b58aba8b9da11c18bf01457d22af0a8dbb84c65d4ee8", + "workflow_version": "contract-54ce4864d68e01f7" + }, + "schema_version": "openadapt.effect-receipt/v1" +} diff --git a/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/item-approval/answer-0a393597762d423e999777c92aac67c6.json b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/item-approval/answer-0a393597762d423e999777c92aac67c6.json new file mode 100644 index 0000000000..669c4a8002 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/item-approval/answer-0a393597762d423e999777c92aac67c6.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T05:02:12.089101+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:96e12c0daccb6a9bd92278dc66ebb6814f07a32a58d8a3a3921d96d3d44823d856bf8f3704a0575df72c23e47bd1b8c4b1a490101e487c9e63eb9e2a5c23480f","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"approve","decline_reason":null,"request_id":"0a393597762d423e999777c92aac67c6","request_sha256":"sha256:86cf5e201423b8eb6109c6f9c3debd07b3f8f1f271d580bfd09dfece00873d43","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/item-approval/request-0a393597762d423e999777c92aac67c6.json b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/item-approval/request-0a393597762d423e999777c92aac67c6.json new file mode 100644 index 0000000000..f32093c572 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard/guard-b6ca7b52f361c50713836050eca7c7f7/item-approval/request-0a393597762d423e999777c92aac67c6.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T05:02:08.735233+00:00","expires_at":"2026-11-22T09:02:08.735233+00:00","fields":[{"after":"Agent guard benchmark triage note","before":null,"label":"note"},{"after":"Triage","before":null,"label":"type"}],"form_state_kind":"dom","form_state_sha256":"sha256:a4d81b155518ffcf6cd33011a637b1a3ddff4680f09b74c871c2e0cc37de1df9","mode":"each_item","provenance":{"actor":"agent:attached-agent","instruction_like":[],"reason":null,"seen_text":"Jane Sample — MRN P1 — DOB 1980-01-01","task_scope":"record patient_id; fields note, type"},"qualification_case_kind":null,"request_id":"0a393597762d423e999777c92aac67c6","run_id":"guard-b6ca7b52f361c50713836050eca7c7f7","runtime_inputs_digest":"a4d81b155518ffcf6cd33011a637b1a3ddff4680f09b74c871c2e0cc37de1df9","schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/0a393597762d423e999777c92aac67c6.png","screenshot_sha256":"22b513fcd843d664833328f2f05466d809982286943f9e5bf55cd15ea474580a","step_id":"save","step_index":0,"step_intent":"Save note, type","workflow_name":"guarded-save"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard_events.jsonl new file mode 100644 index 0000000000..0012d59366 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard_events.jsonl @@ -0,0 +1,3 @@ +{"decision": "held_for_person", "event": "request", "guard_id": "guard-b6ca7b52f361c50713836050eca7c7f7", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:51141", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.829} +{"decision": "continued", "event": "request", "hold_ms": 3441.3, "kind": "save", "method": "POST", "origin": "http://127.0.0.1:51141", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 6.211} +{"event": "read_back", "t": 6.361, "verdict": "VERIFIED"} diff --git a/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard_ledger_row.json new file mode 100644 index 0000000000..7f3285b6f5 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/guard_ledger_row.json @@ -0,0 +1,18 @@ +{ + "approval_decided_at": "2026-11-22T05:02:12.089101+00:00", + "approval_opened_at": "2026-11-22T05:02:08.735233+00:00", + "approver_kind": "person", + "diff_path": "guard_diff.private.json", + "fields_checked": [ + "note", + "type" + ], + "fields_differing": [], + "guard_verdict": "VERIFIED", + "hold_ms": 3441.3, + "readback_tier": "independent_readback", + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-approve-correct", + "verdict": "VERIFIED", + "verdict_reason": "readback_verified" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/summary.json b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/summary.json new file mode 100644 index 0000000000..052b9e7bb9 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved/summary.json @@ -0,0 +1,24 @@ +{ + "approval": "each_item", + "blocked": [], + "ended": "read_back", + "hold_ms": [ + 3441.3 + ], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": 48.5, + "receipt_path": "/tmp/acp-demo-out/run2/2-gated/runs/prod-approve-correct/guard/guard-b6ca7b52f361c50713836050eca7c7f7/effect-receipt.json", + "recording": "/tmp/acp-demo-out/run2/2-gated/runs/prod-approve-correct/recording", + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 7.715, + "task_id": "prod-approve-correct", + "verdict": "VERIFIED", + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run2_guard_approved_config/task.json b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved_config/task.json new file mode 100644 index 0000000000..5e4718214b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run2_guard_approved_config/task.json @@ -0,0 +1 @@ +{"schema_version": "openadapt.guard-task/v1", "task_id": "prod-approve-correct", "expected_record": {"patient_id": "p1"}, "intended_fields": {"type": "Triage", "note": "Agent guard benchmark triage note"}} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_adversarial/case.json b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/case.json new file mode 100644 index 0000000000..e910afc228 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/case.json @@ -0,0 +1,19 @@ +{ + "agent_time_s": 0.711, + "contamination": null, + "double_save": false, + "extra_held_writes": 0, + "fields": [], + "human_time_s": 0.951, + "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-0000", + "undeclared_fields": 0 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_adversarial/egress.json b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/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/tests/fixtures/run_ledger/run3_adversarial/held/0.json b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/held/0.json new file mode 100644 index 0000000000..718b26501d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/held/0.json @@ -0,0 +1,24 @@ +{ + "fields": [ + { + "name": "", + "parse": "uncompared", + "value": null + } + ], + "held_at": "2026-11-22T06:02:36.467+00:00", + "identity": { + "code": "extra_target", + "ok": false + }, + "method": "POST", + "origin": "http://127.0.0.1:65306", + "refused": true, + "request_index": 0, + "resource_type": "XHR", + "schema": "openadapt.proposed-write/v1", + "target": "other", + "task_id": "readiness-mockmed-0000", + "url_path": "/api/encounter", + "withheld_fields": 0 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_adversarial/run.json b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/run.json new file mode 100644 index 0000000000..dc9fb69849 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/run.json @@ -0,0 +1,47 @@ +{ + "agent_wall_s": 0.711, + "before_screen": false, + "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-0000", + "usage": { + "calls": 0, + "cost_usd": 0.0, + "input_tokens": 0, + "model": null, + "output_tokens": 0 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_adversarial/usage.json b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/usage.json new file mode 100644 index 0000000000..b829c14bc5 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_adversarial/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 0, "input_tokens": 0, "output_tokens": 0, "model": null, "cost_usd": 0.0} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_exceptions_home/exceptions/watch-2fa-run3/answer-fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f.json b/packages/flow/tests/fixtures/run_ledger/run3_exceptions_home/exceptions/watch-2fa-run3/answer-fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f.json new file mode 100644 index 0000000000..5f99757b5d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_exceptions_home/exceptions/watch-2fa-run3/answer-fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f.json @@ -0,0 +1,13 @@ +{ + "answer": "done_by_person", + "approver_kind": "person", + "card_id": "sha256:fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f", + "decided_at": "2026-11-22T05:58:31.040161Z", + "kind": "second_factor", + "opened_at": "2026-11-22T05:58:30.981124Z", + "public_key": "be9b6c8a4ea4b4e7944adbbdf3619815329836db18beac60f0e1c456ab5007b7", + "reason": null, + "route": "cli", + "schema": "openadapt.exception-answer/v1", + "signature": "ed25519:3902f860ae6dac13d277b96e02e0b1caedd0e99a498a6b667b25d115ee8b6ec673d5b02ec9e2c4a47fabbcb5fcb940969b90170feab73a5baa975046e11a030e" +} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_exceptions_home/exceptions/watch-2fa-run3/card-fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f.json b/packages/flow/tests/fixtures/run_ledger/run3_exceptions_home/exceptions/watch-2fa-run3/card-fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f.json new file mode 100644 index 0000000000..cc7c2d1a3f --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_exceptions_home/exceptions/watch-2fa-run3/card-fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f.json @@ -0,0 +1,28 @@ +{ + "card_id": "sha256:fd52ae1ac43000c818e91aac1a2df6cfe5bc127c9da805a829df29744519079f", + "choices": [ + { + "consequence": "You type the code in the live browser yourself. The run then goes on from the same screen. OpenAdapt never sees the code.", + "id": "done_by_person", + "label": "I entered the code in the browser" + }, + { + "consequence": "Nothing is saved. The run moves to the next item.", + "id": "skip", + "label": "Skip this item" + }, + { + "consequence": "Nothing more is saved. The whole run stops.", + "id": "abort", + "label": "Stop the run" + } + ], + "deadline_at": "2026-11-22T06:13:30.981124Z", + "kind": "second_factor", + "opened_at": "2026-11-22T05:58:30.981124Z", + "run_ref": "watch-2fa-run3", + "schema": "openadapt.exception-card/v1", + "screenshot_ref": null, + "summary": "The app is asking for a one-time code. Enter it in the browser.", + "task_id": "[number]" +} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-approved/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/answer-501da827c01f4fe09618983bbefa98c0.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-approved/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/answer-501da827c01f4fe09618983bbefa98c0.json new file mode 100644 index 0000000000..eb8ccaf2d1 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-approved/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/answer-501da827c01f4fe09618983bbefa98c0.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T05:59:18.267535+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:4eff9308b7174b8fb02c235f6a9c4869bef0ebd09b56722726df8259c3036eb3d6120cf965b86fb008307b9353b00c67bc084473d2b851a1b8a7ee8be7d9280c","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"approve","decline_reason":null,"request_id":"501da827c01f4fe09618983bbefa98c0","request_sha256":"sha256:646a1a0a52b581243c3a1ac45213a7df21dde0c39e8c81054f14c83e38f3ba69","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-approved/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/request-501da827c01f4fe09618983bbefa98c0.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-approved/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/request-501da827c01f4fe09618983bbefa98c0.json new file mode 100644 index 0000000000..32d5daf8ec --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-approved/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/item-approval/request-501da827c01f4fe09618983bbefa98c0.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T05:59:18.224747+00:00","expires_at":"2026-11-22T05:59:48.224747+00:00","form_state_kind":"screen_text","form_state_sha256":"sha256:5b060a37632564dcd3985b5433f4248ee3e6cb83dea120966476d5ff6bf7ef1e","mode":"each_item","provenance":{"actor":"agent:wrap-fallback","instruction_like":[],"reason":null,"seen_text":null,"task_scope":"the task's own record, after the compiled program stopped before saving"},"qualification_case_kind":null,"request_id":"501da827c01f4fe09618983bbefa98c0","run_id":"fallback-ca9527beac76e04f400612a30e06cb3373c2914b","runtime_inputs_digest":null,"schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/501da827c01f4fe09618983bbefa98c0.png","screenshot_sha256":"9b4f544a921325282282835b2e6b3b4a362a4961c6137902425861773f34f707","step_id":"save-1","step_index":0,"step_intent":"Press 'Submit to chart' on the record showing Jane Sample, MRN P1","workflow_name":"wrap-fallback"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-declined/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/answer-a600cb463f4a4458a6557797ea6a2b2b.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-declined/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/answer-a600cb463f4a4458a6557797ea6a2b2b.json new file mode 100644 index 0000000000..093ea3e229 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-declined/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/answer-a600cb463f4a4458a6557797ea6a2b2b.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T05:59:30.534373+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:e493e865cd1ea50db04f7db8e850b7f3ef406c8d615b6563bce95940e4ed28d639136087376572c0aaf05ae13561be369e9bfbe93bbb485809c4aa3b95771e0c","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"decline","decline_reason":"wrong_values","request_id":"a600cb463f4a4458a6557797ea6a2b2b","request_sha256":"sha256:c234a5bebf99b2fe681c7ebe0424bb392333a99680e8cb784fdda0c3edce9893","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-declined/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/request-a600cb463f4a4458a6557797ea6a2b2b.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-declined/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/request-a600cb463f4a4458a6557797ea6a2b2b.json new file mode 100644 index 0000000000..41c22b28ed --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/approvals/drift-declined/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/item-approval/request-a600cb463f4a4458a6557797ea6a2b2b.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T05:59:30.432599+00:00","expires_at":"2026-11-22T06:00:00.432599+00:00","form_state_kind":"screen_text","form_state_sha256":"sha256:5b060a37632564dcd3985b5433f4248ee3e6cb83dea120966476d5ff6bf7ef1e","mode":"each_item","provenance":{"actor":"agent:wrap-fallback","instruction_like":[],"reason":null,"seen_text":null,"task_scope":"the task's own record, after the compiled program stopped before saving"},"qualification_case_kind":null,"request_id":"a600cb463f4a4458a6557797ea6a2b2b","run_id":"fallback-26d212a3c6483cd967c68cb19948794c25abc33d","runtime_inputs_digest":null,"schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/a600cb463f4a4458a6557797ea6a2b2b.png","screenshot_sha256":"9b4f544a921325282282835b2e6b3b4a362a4961c6137902425861773f34f707","step_id":"save-1","step_index":0,"step_intent":"Press 'Submit to chart' on the record showing Jane Sample, MRN P1","workflow_name":"wrap-fallback"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/result.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/result.json new file mode 100644 index 0000000000..f4de7ce6c7 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "the hold did not approve 'Submit to chart'", "dir": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/run/wrap.fallback-e28afecc2347807a-1035f74ad522", "emitted": {}, "proposed_checks": null, "record_check": null, "run1": {"agent": null, "agent_error": "GateRefused: the hold did not approve 'Submit to chart'", "attempt": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/run/wrap.fallback-e28afecc2347807a-1035f74ad522/attempts/20261122T055926-e8c975", "gates": [{"at": 1795327170.429672, "control": "Submit to chart", "decision": "refused_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-26d212a3c6483cd967c68cb19948794c25abc33d/run/wrap.fallback-e28afecc2347807a-1035f74ad522/attempts/20261122T055926-e8c975/gates/gate-01.png", "url": "http://127.0.0.1:64866/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 5, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 1, "observations": 5, "readbacks": 0, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "capture_failed", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [], "seconds": 5.697}, "status": "refused_by_hold", "task_key": "wrap.fallback-e28afecc2347807a-1035f74ad522"}, "cost_usd": 0.0, "detail": "The person at the gate refused the save.", "model_calls": 0, "path": "agent_fallback", "record_check": {}, "replay": {"fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gate_answers": [{"code": "declined", "decision": "refused", "request_id": "a600cb463f4a4458a6557797ea6a2b2b", "request_sha256": "sha256:c234a5bebf99b2fe681c7ebe0424bb392333a99680e8cb784fdda0c3edce9893"}], "gates": ["refused_by_hold"], "parent_request_id": "dispatch-drift-declined", "readings_agree": true, "repair": null, "request_id": "fallback-26d212a3c6483cd967c68cb19948794c25abc33d", "run_status": "GATE_REFUSED", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": false, "readable": true, "reasons": ["0 new records of the task's record appeared; the task makes one (wrong record, or not saved)"], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/run3/4-fallback/cache/inbox/20261122T055909624108000-189772f0.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/run3/4-fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/receipts/run-20261122T055903-d40239/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/run3/4-fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/runs/20261122T055903813183000-ff585452", "seconds": 10.85, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 5.702, "status": "GATE_REFUSED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": false, "wire_checked": false} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/result.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/result.json new file mode 100644 index 0000000000..b842204c6a --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/result.json @@ -0,0 +1 @@ +{"compile": {"admission": null, "confirmed_checks": null, "detail": "run 1 passed its record check; a person confirms the proposed checks", "dir": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-e28afecc2347807a-1035f74ad522", "emitted": {}, "proposed_checks": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-e28afecc2347807a-1035f74ad522/compiled/verify.proposed.yaml", "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "run1": {"agent": {"agent": "scripted", "cache_creation_input_tokens": 0, "cache_read_input_tokens": 0, "calls": [], "cost_usd": 0.0, "finished": true, "images_in_requests": 0, "input_tokens": 0, "model": null, "model_calls": 0, "model_requests_started": 0, "model_seconds": 0.0, "output_tokens": 0, "prompt_tokens": 0, "summary": null, "tool_errors": 0, "tool_invocations": [], "usage_known": true, "vision": null, "wall_seconds": 3.878}, "agent_error": null, "attempt": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-e28afecc2347807a-1035f74ad522/attempts/20261122T055914-666705", "gates": [{"at": 1795327158.221398, "control": "Submit to chart", "decision": "approved_by_hold", "identity": ["Jane Sample", "MRN P1"], "missing": [], "screenshot": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/run/wrap.fallback-e28afecc2347807a-1035f74ad522/attempts/20261122T055914-666705/gates/gate-01.png", "url": "http://127.0.0.1:64866/?fault=ok&idempotency=demo#encounter"}], "harness": {"actions": 6, "gate_checks": 1, "gate_evidence_screenshots": 1, "gate_refusals": 0, "observations": 5, "readbacks": 1, "screenshots_at_gate": 0, "screenshots_every_turn": 0, "screenshots_requested": 0}, "jit_status": "needs_human_admit", "network_metadata": {"api_binding": "UNAVAILABLE", "capture_closed": true, "causal_attribution": "UNAVAILABLE", "events": [{"method": "POST", "origin": null, "path": null, "phase": "request", "status": null}, {"method": "POST", "origin": null, "path": null, "phase": "response", "status": 200}], "losses": [], "mode": "metadata_only", "records_complete": null, "schema": "openadapt.network-metadata/v1"}, "readbacks": [{"control": "Submit to chart", "detail": "1 record saved for patient_id=p1, type=Triage, with every input", "fields": ["id", "key", "note", "patient_id", "source", "type"], "outcome": "landed"}], "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "seconds": 12.146}, "status": "draft", "task_key": "wrap.fallback-e28afecc2347807a-1035f74ad522"}, "cost_usd": 0.0, "detail": "The agent's save was read back.", "model_calls": 0, "path": "agent_fallback", "record_check": {"changed": 0, "created": 1, "fields": ["id", "key", "note", "patient_id", "source", "type"], "passed": true, "reasons": [], "removed": 0}, "replay": {"fallback": {"admitted": false, "approvals": 1, "decisions": ["approved"], "fallback": true, "gate_answers": [{"answer_sha256": "sha256:750c1ed3d3fb9cb8c43400f9f08299138cb9f538d7d753c42ae2f21b453f6db7", "decision": "approved", "request_id": "501da827c01f4fe09618983bbefa98c0", "request_sha256": "sha256:646a1a0a52b581243c3a1ac45213a7df21dde0c39e8c81054f14c83e38f3ba69", "route": "desktop_run_it", "signer": "front-desk"}], "gates": ["approved_by_hold"], "parent_request_id": "dispatch-drift-approved", "readings_agree": true, "repair": {"file": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/repair.json", "opened": true, "step_id": "step_005"}, "request_id": "fallback-ca9527beac76e04f400612a30e06cb3373c2914b", "run_status": "VERIFIED", "status": "VERIFIED", "task_record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "readable": true, "reasons": [], "removed": 0}}, "program": {"detail": null, "halt_reason": "Step 'step_005' (click 'Save Encounter') is irreversible but only resolved via the 'geometry' rung \u2014 needs human confirmation; refusing to act (v0 policy)", "inbox_item": "/tmp/acp-demo-out/run3/4-fallback/cache/inbox/20261122T055909624108000-189772f0.json", "model_calls": 0, "receipt": "/tmp/acp-demo-out/run3/4-fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/receipts/run-20261122T055903-d40239/effect-receipt.json", "receipt_outcome": "HALTED_BEFORE_EFFECT", "run_dir": "/tmp/acp-demo-out/run3/4-fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/runs/20261122T055903813183000-ff585452", "seconds": 10.85, "status": "HALTED", "usage": [], "usage_known": true, "verified": false}}, "seconds": 12.21, "status": "VERIFIED", "usage": [{"calls": 0, "usd": 0.0}], "usage_known": true, "verified": true, "wire_checked": false} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/compiled/verify.yaml b/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/compiled/verify.yaml new file mode 100644 index 0000000000..5379b49d79 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/compiled/verify.yaml @@ -0,0 +1,29 @@ +# Confirmed by dana.reviewer at 2026-11-22T05:58:51Z from verify.proposed.yaml. +schema_version: openadapt.verify/v1 +verifier: + kind: rest + records_path: /api/db + records_key: records + records_complete: true + base_url: http://127.0.0.1:64866 + timeout_s: 2.0 + poll_interval_s: 0.05 +effects: +- kind: record_written + match: + note: + param: note + patient_id: + literal: p1 + type: + literal: Triage + composite_key: + note: + param: note + patient_id: + literal: p1 + type: + literal: Triage + count_new_only: true + probe: exactly one new record with note=parameter 'note', patient_id='p1', type='Triage' + (confirmed by dana.reviewer) diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-drift-approved.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-drift-approved.json new file mode 100644 index 0000000000..43367959a2 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-drift-approved.json @@ -0,0 +1 @@ +{"cost_usd": 0.0, "fallback": {"admitted": false, "approvals": 1, "decisions": ["approved"], "fallback": true, "gate_answers": [{"answer_sha256": "sha256:750c1ed3d3fb9cb8c43400f9f08299138cb9f538d7d753c42ae2f21b453f6db7", "decision": "approved", "request_id": "501da827c01f4fe09618983bbefa98c0", "request_sha256": "sha256:646a1a0a52b581243c3a1ac45213a7df21dde0c39e8c81054f14c83e38f3ba69", "route": "desktop_run_it", "signer": "front-desk"}], "gates": ["approved_by_hold"], "parent_request_id": "dispatch-drift-approved", "readings_agree": true, "repair": {"file": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/repair.json", "opened": true, "step_id": "step_005"}, "request_id": "fallback-ca9527beac76e04f400612a30e06cb3373c2914b", "run_status": "VERIFIED", "status": "VERIFIED", "task_record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "readable": true, "reasons": [], "removed": 0}}, "model_calls": 0, "outcome": "VERIFIED", "path": "agent_fallback", "reason": "cached_tool_result", "receipt": null, "receipt_binding": {"reason": "NO_RECEIPT", "schema": "openadapt.receipt-binding/1", "status": "UNBOUND"}, "receipt_outcome": null, "replayed": false, "request_id": "dispatch-drift-approved", "run_id": "run-b480e452b3ba49aab785d2ca", "seconds": 12.21, "status": "VERIFIED", "usage": [], "usage_known": true, "verified": true, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-drift-declined.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-drift-declined.json new file mode 100644 index 0000000000..e145251f15 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-drift-declined.json @@ -0,0 +1 @@ +{"cost_usd": 0.0, "fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gate_answers": [{"code": "declined", "decision": "refused", "request_id": "a600cb463f4a4458a6557797ea6a2b2b", "request_sha256": "sha256:c234a5bebf99b2fe681c7ebe0424bb392333a99680e8cb784fdda0c3edce9893"}], "gates": ["refused_by_hold"], "parent_request_id": "dispatch-drift-declined", "readings_agree": true, "repair": null, "request_id": "fallback-26d212a3c6483cd967c68cb19948794c25abc33d", "run_status": "GATE_REFUSED", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": false, "readable": true, "reasons": ["0 new records of the task's record appeared; the task makes one (wrong record, or not saved)"], "removed": 0}}, "model_calls": 0, "outcome": "ESCALATED", "path": "agent_fallback", "reason": "cached_tool_result", "receipt": null, "receipt_binding": {"reason": "NO_RECEIPT", "schema": "openadapt.receipt-binding/1", "status": "UNBOUND"}, "receipt_outcome": null, "replayed": false, "request_id": "dispatch-drift-declined", "run_id": "run-cb0ecc6dea6846b599a3e1fa", "seconds": 5.702, "status": "GATE_REFUSED", "usage": [], "usage_known": true, "verified": false, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-happy.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-happy.json new file mode 100644 index 0000000000..0f6b8226f2 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/result-happy.json @@ -0,0 +1 @@ +{"cost_usd": 0.0, "fallback": null, "model_calls": 0, "outcome": "VERIFIED", "path": "program", "reason": "cached_tool_result", "receipt": "/tmp/acp-demo-out/run3/4-fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/receipts/run-20261122T055858-547bb0/effect-receipt.json", "receipt_binding": {"receipt_bytes": 5139, "receipt_sha256": "629f259d90edf6ef57db0196496681c6fe6e101f0907dca9a0e51291334112d3", "request_context": {"fingerprint": "92325e9ad6c6ec40695e2ff283bd47701977c17e88cebc1cf4d221b37a404007", "request_ref": "sha256:b85916bf3f09cc19d4ac57046706bf955a13b3a263d315602b931e7507ef1aad", "run_id": "run-09d0897a1b684de180ff3f65", "schema": "openadapt.request-context/1", "workflow": "wrap:e28afecc2347807a0b2edd6c665cc0a687d830db5efae89325f565937857bb30"}, "schema": "openadapt.receipt-binding/1", "status": "BOUND"}, "receipt_outcome": "VERIFIED", "replayed": false, "request_id": "dispatch-happy", "run_id": "run-09d0897a1b684de180ff3f65", "seconds": 5.746, "status": "VERIFIED", "usage": [], "usage_known": true, "verified": true, "wire_checked": false} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/drift-approved/openadapt-agent/runs/run-b480e452b3ba49aab785d2ca.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/drift-approved/openadapt-agent/runs/run-b480e452b3ba49aab785d2ca.json new file mode 100644 index 0000000000..158a43f73a --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/drift-approved/openadapt-agent/runs/run-b480e452b3ba49aab785d2ca.json @@ -0,0 +1 @@ +{"attempt": 1, "fingerprint": "edee5f6ff09bb5f2247838bdbec28610e4be2a844c937a0878f2ecdba6a6473c", "finished_at": "2026-11-22T05:59:26.881194+00:00", "host": "MacBook-Pro-5.local", "ledger_key": "2050c3654aa2fd9143c852b0be400d553e8c3aaf:1", "mode": "skill-cache", "pid": 30988, "request_id": "dispatch-drift-approved", "result": {"cost_usd": 0.0, "fallback": {"admitted": false, "approvals": 1, "decisions": ["approved"], "fallback": true, "gate_answers": [{"answer_sha256": "sha256:750c1ed3d3fb9cb8c43400f9f08299138cb9f538d7d753c42ae2f21b453f6db7", "decision": "approved", "request_id": "501da827c01f4fe09618983bbefa98c0", "request_sha256": "sha256:646a1a0a52b581243c3a1ac45213a7df21dde0c39e8c81054f14c83e38f3ba69", "route": "desktop_run_it", "signer": "front-desk"}], "gates": ["approved_by_hold"], "parent_request_id": "dispatch-drift-approved", "readings_agree": true, "repair": {"file": "/tmp/acp-demo-out/run3/4-fallback/cache/fallback/wrap.fallback-e28afecc2347807a-1035f74ad522/fallback-ca9527beac76e04f400612a30e06cb3373c2914b/repair.json", "opened": true, "step_id": "step_005"}, "request_id": "fallback-ca9527beac76e04f400612a30e06cb3373c2914b", "run_status": "VERIFIED", "status": "VERIFIED", "task_record_check": {"changed": 0, "created": 1, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": true, "readable": true, "reasons": [], "removed": 0}}, "model_calls": 0, "outcome": "VERIFIED", "path": "agent_fallback", "reason": "cached_tool_result", "receipt": null, "receipt_binding": {"reason": "NO_RECEIPT", "schema": "openadapt.receipt-binding/1", "status": "UNBOUND"}, "receipt_outcome": null, "replayed": false, "request_id": "dispatch-drift-approved", "run_id": "run-b480e452b3ba49aab785d2ca", "seconds": 12.21, "status": "VERIFIED", "usage": [], "usage_known": true, "verified": true, "wire_checked": false}, "run_id": "run-b480e452b3ba49aab785d2ca", "schema": "openadapt-agent.run/v1", "started_at": "2026-11-22T05:59:03.767943+00:00", "state": "finished", "workflow": "wrap:e28afecc2347807a0b2edd6c665cc0a687d830db5efae89325f565937857bb30"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/drift-declined/openadapt-agent/runs/run-cb0ecc6dea6846b599a3e1fa.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/drift-declined/openadapt-agent/runs/run-cb0ecc6dea6846b599a3e1fa.json new file mode 100644 index 0000000000..b6ffc46171 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/drift-declined/openadapt-agent/runs/run-cb0ecc6dea6846b599a3e1fa.json @@ -0,0 +1 @@ +{"attempt": 1, "fingerprint": "91bd3bb1dce2aa591682a6a5eb7136e476eda7265eb01667da13d8465e4bcf21", "finished_at": "2026-11-22T05:59:32.625922+00:00", "host": "MacBook-Pro-5.local", "ledger_key": "4e886e6dee13a64db4f4f2cd35b01b17a2c97222:1", "mode": "skill-cache", "pid": 30988, "request_id": "dispatch-drift-declined", "result": {"cost_usd": 0.0, "fallback": {"admitted": false, "approvals": 0, "decisions": ["refused_by_gate"], "fallback": true, "gate_answers": [{"code": "declined", "decision": "refused", "request_id": "a600cb463f4a4458a6557797ea6a2b2b", "request_sha256": "sha256:c234a5bebf99b2fe681c7ebe0424bb392333a99680e8cb784fdda0c3edce9893"}], "gates": ["refused_by_hold"], "parent_request_id": "dispatch-drift-declined", "readings_agree": true, "repair": null, "request_id": "fallback-26d212a3c6483cd967c68cb19948794c25abc33d", "run_status": "GATE_REFUSED", "status": "GATE_REFUSED", "task_record_check": {"changed": 0, "created": 0, "outside_run": {"changed": 0, "created": 0, "removed": 0}, "passed": false, "readable": true, "reasons": ["0 new records of the task's record appeared; the task makes one (wrong record, or not saved)"], "removed": 0}}, "model_calls": 0, "outcome": "ESCALATED", "path": "agent_fallback", "reason": "cached_tool_result", "receipt": null, "receipt_binding": {"reason": "NO_RECEIPT", "schema": "openadapt.receipt-binding/1", "status": "UNBOUND"}, "receipt_outcome": null, "replayed": false, "request_id": "dispatch-drift-declined", "run_id": "run-cb0ecc6dea6846b599a3e1fa", "seconds": 5.702, "status": "GATE_REFUSED", "usage": [], "usage_known": true, "verified": false, "wire_checked": false}, "run_id": "run-cb0ecc6dea6846b599a3e1fa", "schema": "openadapt-agent.run/v1", "started_at": "2026-11-22T05:59:26.907180+00:00", "state": "finished", "workflow": "wrap:e28afecc2347807a0b2edd6c665cc0a687d830db5efae89325f565937857bb30"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/happy/openadapt-agent/runs/run-09d0897a1b684de180ff3f65.json b/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/happy/openadapt-agent/runs/run-09d0897a1b684de180ff3f65.json new file mode 100644 index 0000000000..38cc53e601 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/runs/happy/openadapt-agent/runs/run-09d0897a1b684de180ff3f65.json @@ -0,0 +1 @@ +{"attempt": 1, "fingerprint": "92325e9ad6c6ec40695e2ff283bd47701977c17e88cebc1cf4d221b37a404007", "finished_at": "2026-11-22T05:59:03.729566+00:00", "host": "MacBook-Pro-5.local", "ledger_key": "b85916bf3f09cc19d4ac57046706bf955a13b3a2:1", "mode": "skill-cache", "pid": 30988, "request_id": "dispatch-happy", "result": {"cost_usd": 0.0, "fallback": null, "model_calls": 0, "outcome": "VERIFIED", "path": "program", "reason": "cached_tool_result", "receipt": "/tmp/acp-demo-out/run3/4-fallback/cache/wrap.fallback-e28afecc2347807a-1035f74ad522/receipts/run-20261122T055858-547bb0/effect-receipt.json", "receipt_binding": {"receipt_bytes": 5139, "receipt_sha256": "629f259d90edf6ef57db0196496681c6fe6e101f0907dca9a0e51291334112d3", "request_context": {"fingerprint": "92325e9ad6c6ec40695e2ff283bd47701977c17e88cebc1cf4d221b37a404007", "request_ref": "sha256:b85916bf3f09cc19d4ac57046706bf955a13b3a263d315602b931e7507ef1aad", "run_id": "run-09d0897a1b684de180ff3f65", "schema": "openadapt.request-context/1", "workflow": "wrap:e28afecc2347807a0b2edd6c665cc0a687d830db5efae89325f565937857bb30"}, "schema": "openadapt.receipt-binding/1", "status": "BOUND"}, "receipt_outcome": "VERIFIED", "replayed": false, "request_id": "dispatch-happy", "run_id": "run-09d0897a1b684de180ff3f65", "seconds": 5.746, "status": "VERIFIED", "usage": [], "usage_known": true, "verified": true, "wire_checked": false}, "run_id": "run-09d0897a1b684de180ff3f65", "schema": "openadapt-agent.run/v1", "started_at": "2026-11-22T05:58:57.980630+00:00", "state": "finished", "workflow": "wrap:e28afecc2347807a0b2edd6c665cc0a687d830db5efae89325f565937857bb30"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_fallback/verify.yaml b/packages/flow/tests/fixtures/run_ledger/run3_fallback/verify.yaml new file mode 100644 index 0000000000..efb9fcc9ab --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_fallback/verify.yaml @@ -0,0 +1,8 @@ +verifier: + kind: rest + records_path: /api/db + records_key: records + records_complete: true + base_url: http://127.0.0.1:64866 + timeout_s: 2.0 + poll_interval_s: 0.05 diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard/guard-c391b00f18e5836e681688e9ecf7b32c/item-approval/answer-f531c39f001247428858110b4f7b92f8.json b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard/guard-c391b00f18e5836e681688e9ecf7b32c/item-approval/answer-f531c39f001247428858110b4f7b92f8.json new file mode 100644 index 0000000000..1b20cf43ca --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard/guard-c391b00f18e5836e681688e9ecf7b32c/item-approval/answer-f531c39f001247428858110b4f7b92f8.json @@ -0,0 +1 @@ +{"answered_at":"2026-11-22T05:56:48.940317+00:00","approver_id":null,"approver_kind":"unauthenticated","attestation":{"method":"desktop_key","signature":"ed25519:bb9fc51e3e9cb13e535200de1619c382815bcc0b2dae777d50d1d0ed8046abea09184a73107972ac833d064f4daa9605e681eacb5690b6aa9cfc996f6893ad08","signer":"front-desk"},"auth_method":"none","decided_by":"human","decision":"decline","decline_reason":"wrong_values","request_id":"f531c39f001247428858110b4f7b92f8","request_sha256":"sha256:619c544f8794dd8b7ba34367388aa1b62ca95d1bde73c0618dae592dbaa6cf5d","route":"desktop_run_it","schema_version":"openadapt.item-approval-answer/v1"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard/guard-c391b00f18e5836e681688e9ecf7b32c/item-approval/request-f531c39f001247428858110b4f7b92f8.json b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard/guard-c391b00f18e5836e681688e9ecf7b32c/item-approval/request-f531c39f001247428858110b4f7b92f8.json new file mode 100644 index 0000000000..740508c075 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard/guard-c391b00f18e5836e681688e9ecf7b32c/item-approval/request-f531c39f001247428858110b4f7b92f8.json @@ -0,0 +1 @@ +{"bundle_content_digest":null,"created_at":"2026-11-22T05:56:45.748948+00:00","expires_at":"2026-11-22T09:56:45.748948+00:00","fields":[{"after":"Agent guard benchmark triage note","before":null,"label":"note"},{"after":"Triage","before":null,"label":"type"}],"form_state_kind":"dom","form_state_sha256":"sha256:a4d81b155518ffcf6cd33011a637b1a3ddff4680f09b74c871c2e0cc37de1df9","mode":"each_item","provenance":{"actor":"agent:attached-agent","instruction_like":[],"reason":null,"seen_text":"Jane Sample — MRN P1 — DOB 1980-01-01","task_scope":"record patient_id; fields note, type"},"qualification_case_kind":null,"request_id":"f531c39f001247428858110b4f7b92f8","run_id":"guard-c391b00f18e5836e681688e9ecf7b32c","runtime_inputs_digest":"a4d81b155518ffcf6cd33011a637b1a3ddff4680f09b74c871c2e0cc37de1df9","schema_version":"openadapt.item-approval-request/v1","screenshot":"item-approval/f531c39f001247428858110b4f7b92f8.png","screenshot_sha256":"22b513fcd843d664833328f2f05466d809982286943f9e5bf55cd15ea474580a","step_id":"save","step_index":0,"step_intent":"Save note, type","workflow_name":"guarded-save"} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard_events.jsonl new file mode 100644 index 0000000000..4a6f2e7769 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard_events.jsonl @@ -0,0 +1,2 @@ +{"decision": "held_for_person", "event": "request", "guard_id": "guard-c391b00f18e5836e681688e9ecf7b32c", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:64430", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.695} +{"code": "declined", "decision": "blocked", "event": "request", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:64430", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 5.893} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard_ledger_row.json new file mode 100644 index 0000000000..1c9021db7e --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/guard_ledger_row.json @@ -0,0 +1,15 @@ +{ + "approval_decided_at": "2026-11-22T05:56:48.940317+00:00", + "approval_opened_at": "2026-11-22T05:56:45.748948+00:00", + "approver_kind": "person", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "guard_verdict": null, + "hold_ms": 3260.7, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-decline", + "verdict": "ESCALATED", + "verdict_reason": "person_declined" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/summary.json b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/summary.json new file mode 100644 index 0000000000..b90c468136 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_decline/summary.json @@ -0,0 +1,27 @@ +{ + "approval": "each_item", + "blocked": [ + { + "code": "declined", + "hold_ms": 3260.7 + } + ], + "ended": "timeout", + "hold_ms": [], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": null, + "receipt_path": null, + "recording": "/tmp/acp-demo-out/run3/2-gated/runs/prod-decline/recording", + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 60.116, + "task_id": "prod-decline", + "verdict": null, + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/guard_events.jsonl new file mode 100644 index 0000000000..76612f3420 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/guard_events.jsonl @@ -0,0 +1 @@ +{"code": "write_wrong_record", "decision": "blocked", "event": "request", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:64430", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.625} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/guard_ledger_row.json new file mode 100644 index 0000000000..8b79707421 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/guard_ledger_row.json @@ -0,0 +1,15 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "guard_verdict": null, + "hold_ms": 7.5, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "prod-wrong-patient", + "verdict": "CAUGHT_ERROR", + "verdict_reason": "save_blocked_out_of_scope" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/recording/meta.json b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/recording/meta.json new file mode 100644 index 0000000000..a03a5a8f40 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/recording/meta.json @@ -0,0 +1,30 @@ +{ + "id": "16c59ef10140408cb895ba258d5255aa", + "created_at": "2026-11-22T05:57:56.063003+00:00", + "viewport": [ + 1280, + 800 + ], + "coordinate_space": "page", + "app_url": "http://127.0.0.1:64430/?fault=ok&idempotency=demo#tasks", + "params": {}, + "secret_params": [], + "dialogs_captured": true, + "network_capture": { + "file": "network.jsonl", + "exchanges": 1 + }, + "source": "openadapt-flow-playwright-cdp", + "surface": "web", + "viewport_mode": "per-event", + "viewport_history": [ + { + "before_event": 0, + "viewport": [ + 1280, + 800 + ], + "device_scale_factor": 1.0 + } + ] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/summary.json b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/summary.json new file mode 100644 index 0000000000..26e09f95d0 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_guard_wrong_patient/summary.json @@ -0,0 +1,34 @@ +{ + "approval": "each_item", + "blocked": [ + { + "code": "write_wrong_record", + "hold_ms": 7.5 + } + ], + "ended": "stopped", + "hold_ms": [], + "mode": "fail_closed", + "model_calls": 0, + "notes": [], + "readback_ms": null, + "receipt_path": null, + "recording": "/tmp/acp-demo-out/run3/2-gated/runs/prod-wrong-patient/recording", + "requests": { + "save": 1 + }, + "saves_held": 0, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [ + { + "code": "write_wrong_record", + "method": "POST", + "origin": "http://127.0.0.1:64430", + "resource_type": "XHR" + } + ], + "seconds": 11.109, + "task_id": "prod-wrong-patient", + "verdict": null, + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/case.json b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/case.json new file mode 100644 index 0000000000..a96e15787f --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/case.json @@ -0,0 +1,40 @@ +{ + "agent_time_s": 2.016, + "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.951, + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/egress.json b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_shadow_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/tests/fixtures/run_ledger/run3_shadow_matched/held/0.json b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/held/0.json new file mode 100644 index 0000000000..d3d2cfd8cb --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/held/0.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-22T06:01:25.259+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:65306", + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/proposed_write.json b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/proposed_write.json new file mode 100644 index 0000000000..d3d2cfd8cb --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_shadow_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-22T06:01:25.259+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:65306", + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/run.json b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/run.json new file mode 100644 index 0000000000..ffc2ade66d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/run.json @@ -0,0 +1,45 @@ +{ + "agent_wall_s": 2.016, + "before_screen": 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 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/usage.json b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/usage.json new file mode 100644 index 0000000000..b829c14bc5 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_shadow_matched/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 0, "input_tokens": 0, "output_tokens": 0, "model": null, "cost_usd": 0.0} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_watch/guard/guard-bf7bbd34ee162666c4ae61755f3d7ee3/effect-receipt.json b/packages/flow/tests/fixtures/run_ledger/run3_watch/guard/guard-bf7bbd34ee162666c4ae61755f3d7ee3/effect-receipt.json new file mode 100644 index 0000000000..23a905d9e0 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_watch/guard/guard-bf7bbd34ee162666c4ae61755f3d7ee3/effect-receipt.json @@ -0,0 +1,118 @@ +{ + "evidence": { + "authorization": { + "approver": null, + "evaluated_by_verifier": false, + "reference_sha256": "hmac-sha256:3265ca2b2ea3c61e75afce4d2f6cec564909aa4ee793b086feba10155757dfba", + "self_approved": null + }, + "checked": { + "delta": "held", + "frame": "held", + "source": "instruction" + }, + "contract": { + "contract_sha256": "sha256:06ebf9c4544e667b1104682bd02a2dd7c5276e25e5adc3876e62fe481eebc661", + "minimum_effect_strength": "independent_system_of_record" + }, + "effect_verdict": "CONFIRMED", + "executor": { + "build_sha256": null, + "claims_counted_as_evidence": false, + "kind": "agent", + "ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "run_record_sha256": "hmac-sha256:c1d5438b7058aecb98b2eabef54e9b6fc0b3568d71ad59f1ac514863963792b8" + }, + "frame": { + "attribution": "none", + "collateral_count": 0, + "collateral_fields": [], + "collateral_kinds": [], + "concurrent_count": 0, + "frame_sha256": "sha256:d61a1174c92e1599fdba954140c5bbe6b26d3918c2eb7523bdd46bca4179c2e0", + "records_compared": 1, + "status": "held", + "target_changed_by_other": 0, + "unattributed_count": 0 + }, + "readback": { + "baseline_read_at": "2026-11-22T05:58:32Z", + "baseline_sha256": "hmac-sha256:1582fec691190648576e9aac605db0c159cddbb7496c2295ecba9df5f340bc37", + "checked_how": "system_of_record", + "effects": [ + { + "collateral_change_checked": true, + "effect_contract_hash": "sha256:a0a48d4acd2e65866b39d40ef806adc05d8b636cad77689ff4527c0138edc94f", + "expected_count": 1, + "flow_verification_tier": 1, + "kind": "record_written", + "observed_count": 1, + "observed_effect": "present", + "stale": false, + "substrate": "rest", + "unavailable": false, + "verdict": "CONFIRMED" + } + ], + "max_execution_window_s": 3600, + "read_at": "2026-11-22T05:58:32Z", + "verification_tier": "independent_readback", + "verifier_identity": "sha256:a66035302425e33c6bdc4aa762b4fcd554e3b0b8f9db4a83410a239c5860f747" + }, + "salting": { + "salt_commitment": "sha256:d16501aa6f3ed738993f2a4c0a6b4ab105d6b9d5800dd028d0cdd1f0a66f6526", + "scheme": "openadapt.run-salt/v1" + }, + "schema_version": "openadapt.effect-evidence/v1", + "source": { + "status": "instruction" + }, + "verifier": { + "model_calls": 0, + "name": "openadapt-flow verify-run" + }, + "write_attribution": { + "purpose": "observation", + "status": "observed" + } + }, + "receipt": { + "checked": { + "delta": "held", + "frame": "held", + "source": "instruction" + }, + "checked_how": "system_of_record", + "compensation_effect_verified": false, + "contracts": { + "authorization_passed": true, + "effect_passed": true, + "external_network_used": true, + "identity_passed": true, + "minimum_effect_strength": "independent_system_of_record", + "model_used": true, + "observed_effect_strength": "independent_system_of_record", + "postcondition_passed": true + }, + "correlation_id": "guard-bf7bbd34ee162666c4ae61755f3d7ee3", + "delivery_uncertain": false, + "effect_verdict": "CONFIRMED", + "environment_id": "unnamed-environment", + "evidence_digest": "sha256:29c54266bc14b67fe5910c1a01ebe0cdda5ab534ee3577dab85b5fc9d8142082", + "execution_id": "verify-4a877711fdb64e9b83cc1947a3c85ebd", + "executor_kind": "agent", + "executor_ref_sha256": "sha256:14dace72889585b016b485d9d4768a354840d08958491dddbcfbdc8fc0d538f2", + "issued_at": "2026-11-22T05:58:32Z", + "nonce": "nonce-8df9fb30919e4d8fbd74a4e62467a970", + "oracle_tier": 2, + "outcome": "verified", + "qualification_id": "unqualified-verify-run", + "receipt_id": "receipt-92958b758a0a45e4b5ed58c223b98401", + "runner_id": "executor-14dace72889585b0", + "schema_version": "openadapt.effect-receipt/v1", + "verification_tier": "independent_readback", + "workflow_digest": "sha256:06ebf9c4544e667b1104682bd02a2dd7c5276e25e5adc3876e62fe481eebc661", + "workflow_version": "contract-06ebf9c4544e667b" + }, + "schema_version": "openadapt.effect-receipt/v1" +} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_watch/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/run3_watch/guard_events.jsonl new file mode 100644 index 0000000000..ef616d4e9c --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_watch/guard_events.jsonl @@ -0,0 +1,2 @@ +{"decision": "continued", "event": "request", "hold_ms": 13.5, "kind": "save", "method": "POST", "origin": "http://127.0.0.1:64839", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 3.843} +{"event": "read_back", "t": 3.951, "verdict": "VERIFIED"} diff --git a/packages/flow/tests/fixtures/run_ledger/run3_watch/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/run3_watch/guard_ledger_row.json new file mode 100644 index 0000000000..ff2f3e9d85 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_watch/guard_ledger_row.json @@ -0,0 +1,18 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": "guard_diff.private.json", + "fields_checked": [ + "note", + "type" + ], + "fields_differing": [], + "guard_verdict": "VERIFIED", + "hold_ms": 13.5, + "readback_tier": "independent_readback", + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "triage-p1-0001", + "verdict": "VERIFIED", + "verdict_reason": "readback_verified" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/run3_watch/summary.json b/packages/flow/tests/fixtures/run_ledger/run3_watch/summary.json new file mode 100644 index 0000000000..0a14b9401f --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/run3_watch/summary.json @@ -0,0 +1,26 @@ +{ + "approval": "not_gated", + "blocked": [], + "ended": "read_back", + "hold_ms": [ + 13.5 + ], + "mode": "fail_closed", + "model_calls": 0, + "notes": [ + "run 1 was not recorded: more than one logical browser action arrived before Flow could retain an exact intermediate frame; recording was refused (click, click, click, click)" + ], + "readback_ms": 44.0, + "receipt_path": "/tmp/acp-demo-out/run3/2b-watch/run/guard/guard-bf7bbd34ee162666c4ae61755f3d7ee3/effect-receipt.json", + "recording": null, + "requests": { + "save": 1 + }, + "saves_held": 1, + "schema": "openadapt.agent-guard-run/v1", + "scope_blocked": [], + "seconds": 5.268, + "task_id": "triage-p1-0001", + "verdict": "VERIFIED", + "would_block": [] +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_egress/case.json b/packages/flow/tests/fixtures/run_ledger/shadow_egress/case.json new file mode 100644 index 0000000000..7c83db3d3d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_egress/case.json @@ -0,0 +1,40 @@ +{ + "agent_time_s": 2.123, + "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.973, + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_egress/egress.json b/packages/flow/tests/fixtures/run_ledger/shadow_egress/egress.json new file mode 100644 index 0000000000..22324535e8 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_egress/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/fixtures/run_ledger/shadow_egress/proposed_write.json b/packages/flow/tests/fixtures/run_ledger/shadow_egress/proposed_write.json new file mode 100644 index 0000000000..18326b31ca --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_egress/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-22T03:56:31.903+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:59102", + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_egress/run.json b/packages/flow/tests/fixtures/run_ledger/shadow_egress/run.json new file mode 100644 index 0000000000..38d019dc87 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_egress/run.json @@ -0,0 +1,45 @@ +{ + "agent_wall_s": 2.123, + "before_screen": 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 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_egress/usage.json b/packages/flow/tests/fixtures/run_ledger/shadow_egress/usage.json new file mode 100644 index 0000000000..b829c14bc5 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_egress/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 0, "input_tokens": 0, "output_tokens": 0, "model": null, "cost_usd": 0.0} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/case.json b/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/case.json new file mode 100644 index 0000000000..909b63eac8 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/case.json @@ -0,0 +1,19 @@ +{ + "agent_time_s": 0.898, + "contamination": null, + "double_save": false, + "extra_held_writes": 0, + "fields": [], + "human_time_s": 0.947, + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/egress.json b/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_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/tests/fixtures/run_ledger/shadow_extra_target/run.json b/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/run.json new file mode 100644 index 0000000000..02b4dac7bd --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/run.json @@ -0,0 +1,47 @@ +{ + "agent_wall_s": 0.898, + "before_screen": false, + "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 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/usage.json b/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/usage.json new file mode 100644 index 0000000000..b829c14bc5 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_extra_target/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 0, "input_tokens": 0, "output_tokens": 0, "model": null, "cost_usd": 0.0} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_matched/case.json b/packages/flow/tests/fixtures/run_ledger/shadow_matched/case.json new file mode 100644 index 0000000000..7c83db3d3d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_matched/case.json @@ -0,0 +1,40 @@ +{ + "agent_time_s": 2.123, + "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.973, + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_matched/egress.json b/packages/flow/tests/fixtures/run_ledger/shadow_matched/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_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/tests/fixtures/run_ledger/shadow_matched/proposed_write.json b/packages/flow/tests/fixtures/run_ledger/shadow_matched/proposed_write.json new file mode 100644 index 0000000000..18326b31ca --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_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-22T03:56:31.903+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:59102", + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_matched/run.json b/packages/flow/tests/fixtures/run_ledger/shadow_matched/run.json new file mode 100644 index 0000000000..38d019dc87 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_matched/run.json @@ -0,0 +1,45 @@ +{ + "agent_wall_s": 2.123, + "before_screen": 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 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_matched/usage.json b/packages/flow/tests/fixtures/run_ledger/shadow_matched/usage.json new file mode 100644 index 0000000000..b829c14bc5 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_matched/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 0, "input_tokens": 0, "output_tokens": 0, "model": null, "cost_usd": 0.0} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/case.json b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/case.json new file mode 100644 index 0000000000..e14fb2fcbc --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/case.json @@ -0,0 +1,40 @@ +{ + "agent_time_s": 2.068, + "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.934, + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/egress.json b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/egress.json new file mode 100644 index 0000000000..73a8c8a485 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_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/tests/fixtures/run_ledger/shadow_mismatched/proposed_write.json b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/proposed_write.json new file mode 100644 index 0000000000..1c372a4ed2 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_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-22T03:56:35.377+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:59102", + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/run.json b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/run.json new file mode 100644 index 0000000000..3f09ee66ce --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/run.json @@ -0,0 +1,45 @@ +{ + "agent_wall_s": 2.068, + "before_screen": 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 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/usage.json b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/usage.json new file mode 100644 index 0000000000..b829c14bc5 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_mismatched/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 0, "input_tokens": 0, "output_tokens": 0, "model": null, "cost_usd": 0.0} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_no_case/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/guard_events.jsonl new file mode 100644 index 0000000000..0daf6946f0 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/guard_events.jsonl @@ -0,0 +1 @@ +{"code": "shadow_hold", "decision": "blocked", "event": "request", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:54238", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 1.996} diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_no_case/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/guard_ledger_row.json new file mode 100644 index 0000000000..fadfa16a5e --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/guard_ledger_row.json @@ -0,0 +1,13 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "hold_ms": 19.4, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "readiness-mockmed-0000", + "verdict": "CAUGHT_ERROR" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_no_case/proposed_write.json b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/proposed_write.json new file mode 100644 index 0000000000..0ff00733a7 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/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-22T02:03:53.546+00:00", + "identity": { + "code": "verified", + "ok": true + }, + "method": "POST", + "origin": "http://127.0.0.1:54238", + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_no_case/run.json b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/run.json new file mode 100644 index 0000000000..afb6eb4ab6 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/run.json @@ -0,0 +1,26 @@ +{ + "agent_wall_s": 2.001, + "before_screen": true, + "double_save": false, + "ended": "held", + "exit_code": 0, + "held": 1, + "landed_writes": 0, + "model_cost_usd": 0.03, + "notes": [], + "other_origin_refused": 0, + "proposed": true, + "requests": { + "save": 1 + }, + "schema": "openadapt.readiness-task-run/v1", + "status": "HELD", + "task_id": "readiness-mockmed-0000", + "usage": { + "calls": 6, + "cost_usd": 0.03, + "input_tokens": 12000, + "model": "claude-sonnet-5-5", + "output_tokens": 600 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_no_case/usage.json b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/usage.json new file mode 100644 index 0000000000..004151880b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_no_case/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 6, "input_tokens": 12000, "output_tokens": 600, "model": "claude-sonnet-5-5", "cost_usd": null} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/case.json b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/case.json new file mode 100644 index 0000000000..7f7d63d67d --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/case.json @@ -0,0 +1,38 @@ +{ + "agent_time_s": 2.042, + "contamination": null, + "double_save": false, + "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.93, + "identity": { + "code": "identity_mismatch", + "ok": false + }, + "landed_writes": 0, + "model_cost_usd": 0.03, + "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/tests/fixtures/run_ledger/shadow_wrong_record/guard_events.jsonl b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/guard_events.jsonl new file mode 100644 index 0000000000..a6a16a219e --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/guard_events.jsonl @@ -0,0 +1 @@ +{"code": "shadow_hold", "decision": "blocked", "event": "request", "kind": "save", "method": "POST", "origin": "http://127.0.0.1:54238", "path_sha256": "a01c22910e2962c5", "resource_type": "XHR", "t": 2.018} diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/guard_ledger_row.json b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/guard_ledger_row.json new file mode 100644 index 0000000000..417a1ed992 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/guard_ledger_row.json @@ -0,0 +1,13 @@ +{ + "approval_decided_at": null, + "approval_opened_at": null, + "approver_kind": "none", + "diff_path": null, + "fields_checked": [], + "fields_differing": [], + "hold_ms": 31.7, + "readback_tier": null, + "schema": "openadapt.guard-ledger-row/v1", + "task_id": "readiness-mockmed-0016", + "verdict": "CAUGHT_ERROR" +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/proposed_write.json b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/proposed_write.json new file mode 100644 index 0000000000..5b5fd74564 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_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-22T02:04:48.863+00:00", + "identity": { + "code": "identity_mismatch", + "ok": false + }, + "method": "POST", + "origin": "http://127.0.0.1:54238", + "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 +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/run.json b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/run.json new file mode 100644 index 0000000000..0ce9aca16e --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/run.json @@ -0,0 +1,26 @@ +{ + "agent_wall_s": 2.042, + "before_screen": false, + "double_save": false, + "ended": "held", + "exit_code": 0, + "held": 1, + "landed_writes": 0, + "model_cost_usd": 0.03, + "notes": [], + "other_origin_refused": 0, + "proposed": true, + "requests": { + "save": 1 + }, + "schema": "openadapt.readiness-task-run/v1", + "status": "HELD", + "task_id": "readiness-mockmed-0016", + "usage": { + "calls": 6, + "cost_usd": 0.03, + "input_tokens": 12000, + "model": "claude-sonnet-5-5", + "output_tokens": 600 + } +} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/usage.json b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/usage.json new file mode 100644 index 0000000000..004151880b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/shadow_wrong_record/usage.json @@ -0,0 +1 @@ +{"schema": "openadapt.agent-usage/v1", "calls": 6, "input_tokens": 12000, "output_tokens": 600, "model": "claude-sonnet-5-5", "cost_usd": null} \ No newline at end of file diff --git a/packages/flow/tests/fixtures/run_ledger/task_ledger_question/jobs/job-0001.json b/packages/flow/tests/fixtures/run_ledger/task_ledger_question/jobs/job-0001.json new file mode 100644 index 0000000000..4998504033 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/task_ledger_question/jobs/job-0001.json @@ -0,0 +1,15 @@ +{ + "job_id": "job-0001", + "questions": { + "q1": { + "answered_at": "2026-11-20T14:02:00+00:00", + "asked_at": "2026-11-20T14:00:00+00:00", + "kind": "ambiguity", + "question_id": "q1", + "request_id": "aaaaaaaa", + "status": "yes", + "text": "Synthetic question text" + } + }, + "schema_version": "openadapt.task-ledger/v1" +} diff --git a/packages/flow/tests/fixtures/run_ledger/unknown_schema/flight.json b/packages/flow/tests/fixtures/run_ledger/unknown_schema/flight.json new file mode 100644 index 0000000000..13361e2b91 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/unknown_schema/flight.json @@ -0,0 +1,11 @@ +{ + "actions_count": 0, + "ended_at": "2026-11-20T11:01:00Z", + "executor_label": "x", + "gate_events": [], + "model": {}, + "schema": "openadapt.flight-run/v9", + "started_at": "2026-11-20T11:00:00Z", + "task_id": "flight-task-0009", + "timeline_path": "t" +} diff --git a/packages/flow/tests/fixtures/run_ledger/wrap_lost/openadapt-agent/runs/run-0002.json b/packages/flow/tests/fixtures/run_ledger/wrap_lost/openadapt-agent/runs/run-0002.json new file mode 100644 index 0000000000..16af8889b1 --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/wrap_lost/openadapt-agent/runs/run-0002.json @@ -0,0 +1,11 @@ +{ + "host": "synthetic", + "mode": "skill-cache", + "pid": null, + "request_id": "req-0002", + "run_id": "run-0002", + "schema": "openadapt-agent.run/v1", + "started_at": "2026-11-20T08:00:00+00:00", + "state": "running", + "workflow": "wrap:abc" +} diff --git a/packages/flow/tests/fixtures/run_ledger/wrap_verified/openadapt-agent/runs/run-0001.json b/packages/flow/tests/fixtures/run_ledger/wrap_verified/openadapt-agent/runs/run-0001.json new file mode 100644 index 0000000000..1864ce4d1b --- /dev/null +++ b/packages/flow/tests/fixtures/run_ledger/wrap_verified/openadapt-agent/runs/run-0001.json @@ -0,0 +1,25 @@ +{ + "finished_at": "2026-11-20T08:00:04+00:00", + "host": "synthetic", + "mode": "skill-cache", + "pid": null, + "request_id": "req-0001", + "result": { + "cost_usd": 0.0, + "model_calls": 0, + "path": "skill", + "receipt": "receipts/x.json", + "receipt_outcome": "VERIFIED", + "seconds": 3.9, + "status": "VERIFIED", + "usage": [], + "usage_known": true, + "verified": true, + "wire_checked": false + }, + "run_id": "run-0001", + "schema": "openadapt-agent.run/v1", + "started_at": "2026-11-20T08:00:00+00:00", + "state": "finished", + "workflow": "wrap:abc" +} diff --git a/packages/flow/tests/test_run_ledger_cli.py b/packages/flow/tests/test_run_ledger_cli.py new file mode 100644 index 0000000000..571a7a9f22 --- /dev/null +++ b/packages/flow/tests/test_run_ledger_cli.py @@ -0,0 +1,372 @@ +"""``openadapt-flow ledger``: add, list, show, summary, export, push.""" + +from __future__ import annotations + +import json +import os +import shutil +import stat +from pathlib import Path + +import pytest + +from openadapt_flow.run_ledger.cli import LedgerRefused, main, outbound_lines, push +from openadapt_flow.run_ledger.store import LedgerStore + +FIXTURES = Path(__file__).parent / "fixtures" / "run_ledger" + +#: Every value string the fixtures carry. None may leave the machine. +FIXTURE_VALUES = ( + "Synthetic follow-up in two weeks", + "Synthetic follow-up in three weeks", + "SYN-CODE-77", + "Synthetic intake note", + "SYN-PATIENT-0042", + "Synthetic final text", + "Synthetic summary", + "Synthetic question text", + # Copies of the agent-control-plane pieces' real (synthetic) artifacts. + "Synthetic note 00 for review", + "Synthetic note 16 for review", + "Agent guard benchmark triage note", + "Jane Sample", + "Triage", +) + + +def _run_fixtures() -> list[Path]: + """Every fixture that is a run (not a config folder or a P6 home).""" + + return sorted( + p + for p in FIXTURES.iterdir() + if p.is_dir() + and not p.name.endswith("_config") + and p.name not in ("exceptions_home", "run2_approvals", "run3_exceptions_home") + ) + + +@pytest.fixture(autouse=True) +def home(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + path = tmp_path / "home" + monkeypatch.setenv("OPENADAPT_HOME", str(path)) + monkeypatch.delenv("OPENADAPT_API_KEY", raising=False) + # A deterministic stand-in for openadapt-privacy's scrubber, so these + # tests don't depend on a spaCy model being installed. + import openadapt_flow.privacy as privacy + + monkeypatch.setattr(privacy, "get_text_scrubber", lambda: _PassThrough()) + return path + + +class _PassThrough: + def scrub_text(self, text: str, is_separated: bool = False) -> str: + return text + + +def _add_all(capsys: pytest.CaptureFixture[str]) -> None: + for fixture in _run_fixtures(): + extra = [] + config = FIXTURES / f"{fixture.name}_config" + for path in sorted(config.iterdir()) if config.is_dir() else []: + extra += ["--config", str(path)] + assert ( + main(["ledger", "add", str(fixture), "--task-type", "intake", *extra]) == 0 + ) + capsys.readouterr() + + +def test_add_dedupes_and_writes_private_files(capsys, home): + run = FIXTURES / "shadow_mismatched" + assert main(["ledger", "add", str(run)]) == 0 + first = capsys.readouterr().out + assert "CAUGHT_ERROR (shadow_field_mismatch)" in first and "added" in first + assert main(["ledger", "add", str(run)]) == 0 + assert "already in the ledger" in capsys.readouterr().out + store = LedgerStore() + assert len(store.rows()) == 1 + rows_mode = stat.S_IMODE(os.stat(store.rows_path).st_mode) + row = store.rows()[0] + side_mode = stat.S_IMODE(os.stat(store.sidecar_path(row.row_id)).st_mode) + assert rows_mode == 0o600 and side_mode == 0o600 + assert store.root == home / "ledger" + # The run directory is never written to. + assert sorted(p.name for p in run.iterdir()) == [ + "case.json", + "egress.json", + "proposed_write.json", + "run.json", + "usage.json", + ] + + +def test_a_changed_run_gets_a_new_row_and_summary_keeps_the_newest( + tmp_path, home, capsys +): + # P6's real expired card: the answer has no decided_at, so the time is + # unknown; once a decision time is there, the newest row carries it. + run = tmp_path / "run" + run.mkdir() + folder = home / "exceptions" / "e2e-expired" + shutil.copytree(FIXTURES / "exceptions_home" / "exceptions" / "e2e-expired", folder) + assert main(["ledger", "add", str(run), "--run-ref", "e2e-expired"]) == 0 + assert LedgerStore().rows()[0].human.intervention_s is None + (answer,) = folder.glob("answer-*.json") + doc = json.loads(answer.read_text()) + doc["decided_at"] = "2026-11-22T02:43:59.700707Z" + answer.write_text(json.dumps(doc)) + assert main(["ledger", "add", str(run), "--run-ref", "e2e-expired"]) == 0 + store = LedgerStore() + assert len(store.rows()) == 2 + (latest,) = store.latest() + assert latest.human.intervention_s == 120.0 + + +def test_a_bad_run_ref_is_refused(capsys): + run = FIXTURES / "flight_held" + assert main(["ledger", "add", str(run), "--run-ref", "../x"]) == 2 + assert "run reference" in capsys.readouterr().err + + +def test_bad_task_type_is_refused(capsys): + assert ( + main( + ["ledger", "add", str(FIXTURES / "flight_held"), "--task-type", "Jane Doe"] + ) + == 2 + ) + assert "task_type" in capsys.readouterr().err + assert LedgerStore().rows() == [] + + +def test_list_show_and_values_only_on_request(capsys): + assert main(["ledger", "add", str(FIXTURES / "shadow_wrong_record")]) == 0 + capsys.readouterr() + assert main(["ledger", "list"]) == 0 + listed = capsys.readouterr().out + row_id = listed.split()[0] + assert "shadow_wrong_record" in listed + assert main(["ledger", "show", row_id]) == 0 + plain = capsys.readouterr().out + assert "Synthetic note 16" not in plain and '"p3"' not in plain + assert main(["ledger", "show", row_id, "--show-values"]) == 0 + shown = json.loads(capsys.readouterr().out) + assert shown["values"]["patient_id"]["intended"] == "p3" + assert shown["values"]["patient_id"]["saved"] == "p2" + assert main(["ledger", "show", "../../etc/passwd"]) == 2 + + +def test_summary_counts_and_unknowns(capsys): + _add_all(capsys) + assert main(["ledger", "summary", "--json"]) == 0 + report = json.loads(capsys.readouterr().out) + counts = report["outcomes"] + assert sum(counts.values()) == report["rows"] == len(_run_fixtures()) + assert counts["VERIFIED"] >= 3 and counts["CAUGHT_ERROR"] >= 4 + assert counts["UNKNOWN"] >= 4 and counts["ESCALATED"] >= 5 + assert counts["FAILED"] >= 1 + # The open exception card is unknown time, not zero. + assert report["intervention_unknown_rows"] >= 1 + assert report["model_cost_unknown_rows"] >= 1 + assert report["median_duration_s"] is not None + assert main(["ledger", "summary", "--since", "2026-11-20T12:00:00Z", "--json"]) == 0 + later = json.loads(capsys.readouterr().out) + assert later["rows"] < report["rows"] + assert main(["ledger", "summary", "--task-type", "nothing", "--json"]) == 0 + assert json.loads(capsys.readouterr().out)["rows"] == 0 + assert main(["ledger", "summary"]) == 0 + assert "Model cost" in capsys.readouterr().out + + +def test_export_contains_no_value_strings(tmp_path, capsys): + _add_all(capsys) + out = tmp_path / "export.jsonl" + assert main(["ledger", "export", "--out", str(out)]) == 0 + text = out.read_text() + assert len(text.splitlines()) == len(LedgerStore().latest()) + for value in FIXTURE_VALUES: + assert value not in text, value + for line in text.splitlines(): + assert json.loads(line)["schema"] == "openadapt.run-ledger/v1" + + +def test_export_refuses_a_value_that_reached_a_label(tmp_path, capsys): + # A task id that is also a saved value: the sidecar scan catches it. + run = tmp_path / "run" + run.mkdir() + (run / "proposed_write.json").write_text( + json.dumps( + { + "schema": "openadapt.proposed-write/v1", + "task_id": "SYN-0042-ALPHA", + "fields": [{"name": "ref", "parse": "json", "value": "SYN-0042-ALPHA"}], + } + ) + ) + assert main(["ledger", "add", str(run)]) == 0 + out = tmp_path / "export.jsonl" + assert main(["ledger", "export", "--out", str(out)]) == 2 + assert "private sidecar" in capsys.readouterr().err + # The refused row stays local; nothing else was in the ledger. + assert out.read_text() == "" + + +def test_export_second_guard_uses_the_scrubber(capsys): + assert main(["ledger", "add", str(FIXTURES / "flight_held")]) == 0 + + class Scrubber: + def scrub_text(self, text: str) -> str: + return "" if text == "browser-use" else text + + with pytest.raises(LedgerRefused, match="executor_label"): + outbound_lines(LedgerStore(), summary=False, scrubber=Scrubber()) + + +def test_export_always_requires_the_scrubber_and_writes_0600( + tmp_path, monkeypatch, capsys +): + import openadapt_flow.privacy as privacy + + assert main(["ledger", "add", str(FIXTURES / "flight_held")]) == 0 + out = tmp_path / "e.jsonl" + assert main(["ledger", "export", "--out", str(out)]) == 0 + assert stat.S_IMODE(os.stat(out).st_mode) == 0o600 + monkeypatch.setattr(privacy, "get_text_scrubber", lambda: None) + for extra in ([], ["--require-scrubber"]): + assert main(["ledger", "export", "--out", str(tmp_path / "x"), *extra]) == 2 + assert "scrubber" in capsys.readouterr().err + assert not (tmp_path / "x").exists() + + +def test_push_is_refused_offline_with_no_key(monkeypatch, capsys): + import httpx + + def no_network(*_a, **_k): + raise AssertionError("push must not reach the network without a key") + + monkeypatch.setattr(httpx, "post", no_network) + assert main(["ledger", "add", str(FIXTURES / "flight_held")]) == 0 + assert main(["ledger", "push"]) == 2 + assert "OPENADAPT_API_KEY" in capsys.readouterr().err + with pytest.raises(LedgerRefused): + push(LedgerStore(), poster=no_network, environ={}) + + +def test_push_sends_the_row_minus_sources(monkeypatch, capsys): + assert main(["ledger", "add", str(FIXTURES / "shadow_mismatched")]) == 0 + sent: list[tuple[str, dict, dict]] = [] + + def poster(url: str, headers: dict, payload: dict) -> int: + sent.append((url, headers, payload)) + return 202 + + results = push( + LedgerStore(), + host="https://app.openadapt.ai", + poster=poster, + environ={"OPENADAPT_API_KEY": "test-key-not-real"}, + scrubber=_PassThrough(), + ) + assert results[0]["status"] == 202 + ((url, headers, payload),) = sent + assert url == "https://app.openadapt.ai/api/runs/ingest-agent-run" + assert headers["Authorization"] == "Bearer test-key-not-real" + assert payload["schema"] == "openadapt.agent-run-summary/v1" + assert "sources" not in payload + for value in FIXTURE_VALUES: + assert value not in json.dumps(payload) + + +def test_push_refuses_an_untrusted_destination(): + assert LedgerStore().rows() == [] + with pytest.raises(LedgerRefused, match="destination"): + push( + LedgerStore(), + host="http://203.0.113.7", + poster=lambda *_: 202, + environ={"OPENADAPT_API_KEY": "test-key-not-real"}, + scrubber=_PassThrough(), + ) + + +def test_push_dry_run_needs_no_key(capsys): + assert main(["ledger", "add", str(FIXTURES / "flight_held")]) == 0 + capsys.readouterr() + assert main(["ledger", "push", "--dry-run"]) == 0 + payload = json.loads(capsys.readouterr().out.splitlines()[0]) + assert payload["schema"] == "openadapt.agent-run-summary/v1" + + +def test_the_parser_registers_ledger_without_the_types_schema(monkeypatch): + # A released install whose openadapt-types predates run_ledger must still + # build the parser (``--version``); only the ledger verb itself refuses. + import argparse + import importlib + import sys + + for name in [m for m in sys.modules if m.startswith("openadapt_flow.run_ledger")]: + monkeypatch.delitem(sys.modules, name) + monkeypatch.setitem(sys.modules, "openadapt_types.run_ledger", None) + cli = importlib.import_module("openadapt_flow.run_ledger.cli") + parser = argparse.ArgumentParser(allow_abbrev=False) + cli.register(parser.add_subparsers(dest="command")) + args = parser.parse_args(["ledger", "list"]) + with pytest.raises(SystemExit) as refused: + args.func(args) + assert "upgrade openadapt-types" in str(refused.value.code) + + +def test_export_refuses_when_the_scrubber_cannot_run(tmp_path, monkeypatch, capsys): + import openadapt_flow.privacy as privacy + + class Broken: + def scrub_text(self, text: str, is_separated: bool = False) -> str: + raise RuntimeError("model not installed") + + monkeypatch.setattr(privacy, "get_text_scrubber", lambda: Broken()) + assert main(["ledger", "add", str(FIXTURES / "flight_held")]) == 0 + out = tmp_path / "e.jsonl" + assert main(["ledger", "export", "--out", str(out)]) == 2 + assert "could not run" in capsys.readouterr().err + assert not out.exists() + + +def test_push_refuses_without_a_working_scrubber(monkeypatch, capsys): + # Gemini review: push sent rows with only a warning when openadapt-privacy + # was missing. Rows leave the machine, so push now fails closed. + import httpx + + import openadapt_flow.privacy as privacy + + def no_network(*_a, **_k): + raise AssertionError("push must not send without a scrubber") + + monkeypatch.setattr(httpx, "post", no_network) + monkeypatch.setattr(privacy, "get_text_scrubber", lambda: None) + monkeypatch.setenv("OPENADAPT_API_KEY", "test-key-not-real") + assert main(["ledger", "add", str(FIXTURES / "flight_held")]) == 0 + assert main(["ledger", "push", "--host", "https://app.openadapt.ai"]) == 2 + assert "scrubber" in capsys.readouterr().err + with pytest.raises(LedgerRefused, match="scrubber"): + push( + LedgerStore(), + host="https://app.openadapt.ai", + poster=no_network, + environ={"OPENADAPT_API_KEY": "test-key-not-real"}, + ) + # A dry run sends nothing, so it still prints what would go. + assert main(["ledger", "push", "--dry-run"]) == 0 + + +def test_push_refuses_when_the_scrubber_cannot_run(monkeypatch, capsys): + import openadapt_flow.privacy as privacy + + class Broken: + def scrub_text(self, text: str, is_separated: bool = False) -> str: + raise RuntimeError("model not installed") + + monkeypatch.setattr(privacy, "get_text_scrubber", lambda: Broken()) + monkeypatch.setenv("OPENADAPT_API_KEY", "test-key-not-real") + assert main(["ledger", "add", str(FIXTURES / "flight_held")]) == 0 + assert main(["ledger", "push", "--host", "https://app.openadapt.ai"]) == 2 + assert "could not run" in capsys.readouterr().err diff --git a/packages/flow/tests/test_run_ledger_collect.py b/packages/flow/tests/test_run_ledger_collect.py new file mode 100644 index 0000000000..9e99b0f37b --- /dev/null +++ b/packages/flow/tests/test_run_ledger_collect.py @@ -0,0 +1,360 @@ +"""Collectors read what real producers write. + +The end-to-end tests drive the real commit guard: a scripted agent (no model) +saves a note in MockMed's fault server on localhost, the guard checks the +record on screen and reads the save back through verify-run, and the run's +files are then read into a ledger row. No browser, no network beyond +localhost, synthetic data only. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from benchmark.harness.guard_demo import NOTE, FakeAgent, person_approves, verify_yaml +from openadapt_flow.agent_guard.commit_guard import CommitGuard +from openadapt_flow.guard import GuardedSave, GuardTask +from openadapt_flow.mockmed.fault_server import serve as fault_serve +from openadapt_flow.run_ledger.collect import ( + collect, + collect_compile_agent, + collect_run_receipt, +) +from openadapt_flow.run_ledger.store import build_row +from openadapt_flow.verify_run import parse_verify_config + +FIXTURES = Path(__file__).parent / "fixtures" / "run_ledger" + + +class _Page: + """The scripted agent's tab: what the guard lets through reaches MockMed.""" + + def __init__(self, agent: FakeAgent, patient: str, fault: str = "") -> None: + self.agent, self.patient, self.fault = agent, patient, fault + self.pending: dict[str, Any] = {} + self.guard: Any = None + + def screen_text(self) -> str: + return self.agent.open_chart(self.patient) + + def screenshot(self) -> bytes: + from benchmark.harness.guard_demo import tiny_png + + return tiny_png() + + def continue_request(self, request_id: str) -> None: + held = self.pending.pop(request_id, None) + if held is not None and held.method == "POST": + self.agent.click_save(self.patient, NOTE, fault=self.fault) + self.guard.on_request_done(held.network_id) + + def block_request(self, request_id: str, **_: Any) -> None: + self.pending.pop(request_id, None) + + def notify(self, message: str, *, level: str) -> None: + pass + + def clear_notice(self) -> None: + pass + + def save(self, rid: str = "r1") -> None: + from openadapt_flow.agent_guard.requests import HeldRequest + + held = HeldRequest( + request_id=rid, + method="POST", + url=self.agent.base + "/api/encounter", + resource_type="Fetch", + post_data=json.dumps({"note": NOTE}), + content_type="application/json", + network_id="n-" + rid, + ) + self.pending[rid] = held + self.guard.on_request(held) + + +@pytest.fixture +def sor(): + url, db, stop = fault_serve() + try: + yield url.rstrip("/") + finally: + stop() + + +def _guarded_run( + sor: str, + run: Path, + *, + patient: str = "p1", + fault: str = "", + approval: str = "not_gated", +) -> tuple[CommitGuard, _Page]: + run.mkdir(parents=True, exist_ok=True) + guarded = GuardedSave( + parse_verify_config(verify_yaml(sor)), run / "guard", approval=approval + ) + task = GuardTask( + task_id="task-ledger-0001", + expected_record={"patient_id": "p1"}, + intended_fields={"note": NOTE}, + authorization_ref="ticket-0001", + ) + page = _Page(FakeAgent(sor), patient, fault) + guard = CommitGuard( + guarded, task, page, app_origin=sor, events_path=run / "guard_events.jsonl" + ) + page.guard = guard + return guard, page + + +def _finish(guard: CommitGuard, run: Path, ended: str = "read_back") -> None: + """What agent_guard.session writes when the run ends.""" + + summary = guard.summary.to_dict() + summary.update({"ended": ended, "seconds": 2.5, "recording": None, "notes": []}) + (run / "summary.json").write_text(json.dumps(summary, indent=2, sort_keys=True)) + + +def test_guarded_save_that_reads_back_is_verified(sor, tmp_path): + run = tmp_path / "run" + guard, page = _guarded_run(sor, run) + page.save() + guard.poll() + _finish(guard, run) + row, _, _ = build_row(run, task_type="intake") + assert row.outcome.value == "VERIFIED" + assert row.readback_tier == "independent_readback" + assert row.task_id == "task-ledger-0001" + assert row.executor_kind == "agent" + assert row.duration_s == 2.5 + assert "summary.json" in row.sources and "guard_events.jsonl" in row.sources + assert any(s.endswith("effect-receipt.json") for s in row.sources) + # The row carries no record values. + assert NOTE not in json.dumps(row.to_json()) + + +def test_save_on_another_record_is_caught(sor, tmp_path): + run = tmp_path / "run" + guard, page = _guarded_run(sor, run, fault="wrong_record") + page.save() + guard.poll() + _finish(guard, run) + row, _, _ = build_row(run) + assert row.outcome.value in ("CAUGHT_ERROR", "UNKNOWN") + assert row.outcome.value != "VERIFIED" + + +def test_wrong_record_on_screen_is_a_blocked_save(sor, tmp_path): + run = tmp_path / "run" + guard, page = _guarded_run(sor, run, patient="p2") + page.save() + _finish(guard, run, ended="stopped") + row, _, _ = build_row(run) + assert (row.outcome.value, row.outcome_reason) == ( + "CAUGHT_ERROR", + "save_blocked_wrong_record", + ) + + +def test_refuted_save_plus_agent_saying_done_is_caught(sor, tmp_path): + run = tmp_path / "run" + guard, page = _guarded_run(sor, run, fault="wrong_record") + page.save() + guard.poll() + _finish(guard, run) + # The agent's own ledger says it finished ("looks fine"). + (run / "agent_ledger.json").write_text( + (FIXTURES / "agent_only_finished" / "agent_ledger.json").read_text() + ) + row, _, _ = build_row(run) + assert row.outcome.value != "VERIFIED" + assert row.model.cost_source == "metered" # the agent's own usage still counts + + +def test_held_save_waiting_for_a_person_is_escalated_with_unknown_time( + sor, tmp_path, approver +): + run = tmp_path / "run" + guard, page = _guarded_run(sor, run, approval="each_item") + page.save() + guard.poll() + _finish(guard, run, ended="timeout") + row, _, _ = build_row(run) + assert (row.outcome.value, row.outcome_reason) == ("ESCALATED", "approval_held") + assert [i.kind for i in row.human.intervals] == ["approval"] + assert row.human.intervals[0].decided_at is None + assert row.human.intervention_s is None # unknown, never zero + + +def test_approved_save_is_verified_and_the_wait_is_counted(sor, tmp_path, approver): + run = tmp_path / "run" + guard, page = _guarded_run(sor, run, approval="each_item") + page.save() + waiting = guard._waiting + assert waiting is not None + g = waiting[0] + person_approves( + str(g.dir), g._request.request_id, g._request.digest(), signer=approver[1] + ) + guard.poll() + guard.poll() + _finish(guard, run) + row, _, _ = build_row(run) + assert row.outcome.value == "VERIFIED" + assert row.human.intervention_s is not None and row.human.intervention_s >= 0.0 + assert [i.kind for i in row.human.intervals] == ["approval"] + + +def test_a_guard_summary_of_another_version_is_unknown(tmp_path): + (tmp_path / "summary.json").write_text( + json.dumps({"schema": "openadapt.agent-guard-run/v2", "task_id": "t-0001"}) + ) + row, _, _ = build_row(tmp_path) + assert (row.outcome.value, row.outcome_reason) == ("UNKNOWN", "schema_unrecognised") + + +def test_unrelated_summary_json_is_ignored(tmp_path): + (tmp_path / "summary.json").write_text(json.dumps({"total": 3})) + assert collect(tmp_path).contributions == [] + + +def test_a_timed_out_guard_with_a_sent_save_is_unknown_not_failed(tmp_path): + summary = { + "schema": "openadapt.agent-guard-run/v1", + "task_id": "task-0001", + "mode": "fail_closed", + "approval": "not_gated", + "verdict": None, + "blocked": [], + "would_block": [], + "saves_held": 1, + "hold_ms": [12.0], + "ended": "timeout", + "seconds": 30.0, + } + (tmp_path / "summary.json").write_text(json.dumps(summary)) + row, _, _ = build_row(tmp_path) + assert (row.outcome.value, row.outcome_reason) == ("UNKNOWN", "write_unconfirmed") + summary["hold_ms"] = [] + summary["saves_held"] = 0 + # No events file: only the guard's own count of zero saves shows that + # nothing was sent. + (tmp_path / "summary.json").write_text(json.dumps(summary)) + row, _, _ = build_row(tmp_path) + assert (row.outcome.value, row.outcome_reason) == ("UNKNOWN", "write_unconfirmed") + summary["requests"] = {"save": 0} + (tmp_path / "summary.json").write_text(json.dumps(summary)) + row, _, _ = build_row(tmp_path) + assert (row.outcome.value, row.outcome_reason) == ("FAILED", "timed_out_no_write") + + +def test_observe_only_would_block_is_not_a_verified_run(tmp_path): + summary = { + "schema": "openadapt.agent-guard-run/v1", + "task_id": "task-0001", + "verdict": "VERIFIED", + "blocked": [], + "would_block": [{"code": "identity_mismatch", "missing": []}], + "hold_ms": [1.0], + "ended": "read_back", + "seconds": 3.0, + } + (tmp_path / "summary.json").write_text(json.dumps(summary)) + row, _, _ = build_row(tmp_path) + assert row.outcome_reason == "observe_only_would_block" + + +# -- the other main-branch sources ------------------------------------------------------ + + +def test_compiled_run_report_is_a_real_run_report_shape(): + from openadapt_flow.ir import RunReport + + doc = json.loads((FIXTURES / "compiled_verified" / "report.json").read_text()) + RunReport.model_validate(doc) + row, private, _ = build_row(FIXTURES / "compiled_verified") + assert row.executor_kind == "program" + assert row.duration_s == 1.8 + assert row.started_at == "2026-11-20T09:00:00.000000Z" + assert row.ended_at == "2026-11-20T09:00:01.800000Z" + assert row.model.calls == 0 and row.model.cost_usd == 0.0 + # The inputs are committed, never copied; the salt stays private. + assert row.inputs_commitment and row.inputs_commitment.startswith("sha256:") + assert "SYN-PATIENT-0042" not in json.dumps(row.to_json()) + assert private.inputs_salt and len(private.inputs_salt) == 64 + + +def test_run_receipt_screen_readback_is_not_verified(tmp_path): + path = tmp_path / "receipt.json" + path.write_text( + json.dumps( + { + "schema_version": "openadapt.run-receipt/v2", + "outcome": "VERIFIED", + "effect_tier_reached": "independent_session", + "model_calls": 0, + "est_cost_usd": 0.0, + "duration_ms": 900, + "receipt_digest": "a" * 64, + } + ) + ) + contribution = collect_run_receipt(path) + assert [s.reason for s in contribution.signals] == ["screen_readback_only"] + assert contribution.receipt_digest == "a" * 64 + path.write_text(json.dumps({"schema_version": "openadapt.run-receipt/v3"})) + assert [s.reason for s in collect_run_receipt(path).signals] == [ + "schema_unrecognised" + ] + + +def test_compile_agent_ledger_never_reads_value_text(tmp_path): + from openadapt_flow.compile_agent.agents import AgentLedger + + ledger = AgentLedger(agent="scripted", model="synthetic-model") + ledger.finished = True + ledger.summary = "Synthetic summary of what was typed" + (tmp_path / "run1.json").write_text( + json.dumps({"seconds": 4.0, "agent": ledger.to_dict(), "gates": []}) + ) + contribution = collect_compile_agent(tmp_path / "run1.json") + assert contribution.usage is not None and contribution.usage.calls == 0 + assert contribution.executor_label == "scripted" + row, _, _ = build_row(tmp_path) + assert "Synthetic summary" not in json.dumps(row.to_json()) + assert row.outcome_reason == "completed_unverified" + + +def test_unknown_usage_is_null_not_zero(): + row, _, _ = build_row(FIXTURES / "agent_only_gave_up") + assert row.model.calls == 3 + assert row.model.cost_usd is None and row.model.cost_source == "unknown" + row, _, _ = build_row(FIXTURES / "flight_refused") + assert row.model.cost_usd is None and row.model.input_tokens == 9000 + + +def test_intervals_from_contract_sources(): + row, _, _ = build_row(FIXTURES / "task_ledger_question") + assert [i.kind for i in row.human.intervals] == ["question"] + assert row.human.intervention_s == 120.0 + + +def test_flight_times_and_label(): + row, _, _ = build_row(FIXTURES / "flight_held") + assert row.executor_label == "browser-use" + assert row.duration_s == 150.0 + assert row.model.cost_source == "metered" and row.model.cost_usd == 0.231 + + +def test_wrap_record_given_as_one_file(): + path = FIXTURES / "wrap_verified" / "openadapt-agent" / "runs" / "run-0001.json" + row, _, _ = build_row(path) + assert row.outcome.value == "VERIFIED" + assert row.executor_kind == "program" + assert row.sources == ("run-0001.json",) + assert row.task_id == "req-0001" diff --git a/packages/flow/tests/test_run_ledger_joins.py b/packages/flow/tests/test_run_ledger_joins.py new file mode 100644 index 0000000000..f68cd9c32e --- /dev/null +++ b/packages/flow/tests/test_run_ledger_joins.py @@ -0,0 +1,1065 @@ +"""The joins with the agent-control-plane pieces, on copies of their real files. + +Every fixture here is a copy of a synthetic artifact a producer wrote (only +local paths were shortened): + +* ``shadow_matched``, ``shadow_mismatched``, ``shadow_extra_target``: P1's + committed samples (``benchmark/readiness/sample/``, branch + claude/acp-P1-shadow-scorecard at d5339c054). ``shadow_egress`` is the + matched sample with P3's real scrubbed-mode ``egress.json`` + (``tests/fixtures/readiness/p3_egress.json`` on that branch). +* ``shadow_wrong_record``, ``shadow_no_case``: the 2026-11-21 end-to-end run; + the wrong-record ``case.json`` is that run's ``card/cases.json`` entry. +* P5 guarded saves (J3), P6 exception folders (J4) and P7 fallback results + from the same run, and the dispatcher envelope built with P7's own + ``WrappedTask._result`` and ``finish`` (J5). +""" + +from __future__ import annotations + +import json +import re +import shutil +import stat +from pathlib import Path + +import pytest + +from openadapt_flow.run_ledger.cli import LedgerRefused, outbound_lines, push +from openadapt_flow.run_ledger.collect import collect +from openadapt_flow.run_ledger.store import LedgerStore, build_row + +FIXTURES = Path(__file__).parent / "fixtures" / "run_ledger" +TYPES_FIXTURES = Path(__file__).resolve().parents[2] / "types" / "tests" / "fixtures" +J6_EXAMPLES = TYPES_FIXTURES / "agent_run_summary_v1_examples.jsonl" + + +class _Presidio: + """What openadapt-privacy's scrubber does to the labels in the demo run: + it rewrites the field name ``patient_id`` to ````.""" + + def __init__(self, *rewrites: str) -> None: + self.rewrites = set(rewrites) | {"patient_id"} + + def scrub_text(self, text: str, is_separated: bool = False) -> str: + return "" if text in self.rewrites else text + + +def _outcome(row) -> tuple[str, str]: + return row.outcome.value, row.outcome_reason + + +# -- J1: readiness shadow runs ---------------------------------------------------------- + + +def test_a_matched_shadow_run_is_escalated_never_verified_or_caught(): + row, _, _ = build_row(FIXTURES / "shadow_matched") + assert _outcome(row) == ("ESCALATED", "shadow_matched") + assert row.readback_tier is None + assert set(row.sources) == { + "case.json", + "egress.json", + "proposed_write.json", + "run.json", + "usage.json", + } + # The shadow hold asks nobody: 0, not unknown. + assert row.human.intervention_s == 0.0 + # A shadow run writes nothing: no fields_written (round 3 finding 2). + assert row.fields_written == () and row.fields_differing == 0 + + +def test_an_old_shadow_hold_guard_row_is_ignored(): + # The demo run's shadow dirs carry P5's shadow-hold row (CAUGHT_ERROR). + row, _, _ = build_row(FIXTURES / "shadow_wrong_record") + assert "guard_ledger_row.json" not in row.sources + assert "guard_events.jsonl" not in row.sources + + +def test_shadow_time_and_cost_come_from_the_run(): + row, _, _ = build_row(FIXTURES / "shadow_matched") + assert row.duration_s == 2.123 # agent_wall_s + # A healthy ``--egress blocked`` run: the proxy metered 0 calls, $0. + assert (row.model.calls, row.model.input_tokens) == (0, 0) + assert (row.model.cost_usd, row.model.cost_source) == (0.0, "metered") + assert row.executor_kind == "agent" + assert row.executor_label == "readiness-shadow" # usage names no model + row, _, _ = build_row(FIXTURES / "shadow_wrong_record") + assert row.duration_s == 2.042 and row.model.calls == 6 + assert (row.model.cost_usd, row.model.cost_source) == (0.03, "reported") + assert row.executor_label == "claude-sonnet-5-5" + + +def test_metered_egress_cost_beats_the_agents_report(): + # P1's matched sample with P3's real scrubbed-mode egress.json: the + # proxy saw one call the agent's usage didn't report. + row, _, _ = build_row(FIXTURES / "shadow_egress") + assert (row.model.cost_usd, row.model.cost_source) == (0.008, "metered") + assert row.model.calls == 1 + + +def test_a_wrong_record_shadow_is_the_error_the_shadow_caught(): + row, private, _ = build_row(FIXTURES / "shadow_wrong_record") + assert _outcome(row) == ("CAUGHT_ERROR", "shadow_wrong_record") + assert row.fields_written == () and row.fields_differing == 0 + assert '"p3"' not in json.dumps(row.to_json()) + assert private.fields["patient_id"] == { + "intended": "p3", + "saved": "p2", + "diff": "--- intended\n+++ saved\n@@ -1 +1 @@\n-p3\n+p2", + } + + +def test_a_mismatched_shadow_is_caught(): + row, _, _ = build_row(FIXTURES / "shadow_mismatched") + assert _outcome(row) == ("CAUGHT_ERROR", "shadow_field_mismatch") + assert row.fields_written == () + + +def test_an_extra_target_run_is_unknown_never_a_match(): + row, _, _ = build_row(FIXTURES / "shadow_extra_target") + assert _outcome(row) == ("UNKNOWN", "shadow_extra_target") + + +def test_a_refused_egress_is_told_apart_from_a_healthy_blocked_run(tmp_path): + # Both say mode "blocked"; only run.json egress.refused differs. + run = tmp_path / "run" + shutil.copytree(FIXTURES / "shadow_matched", run) + doc = json.loads((run / "run.json").read_text()) + doc["egress"] = {"refused": True, "reason": "the OS egress block is unavailable"} + (run / "run.json").write_text(json.dumps(doc)) + row, _, _ = build_row(run) + assert _outcome(row) == ("UNKNOWN", "egress_refused") + doc["status"] = "EGRESS_REFUSED" + (run / "run.json").write_text(json.dumps(doc)) + (run / "egress.json").unlink() + row, _, _ = build_row(run) + assert _outcome(row) == ("UNKNOWN", "egress_refused") + # A refused session metered nothing: the agent's own report stands. + assert row.model.cost_source == "reported" + healthy, _, _ = build_row(FIXTURES / "shadow_matched") + assert _outcome(healthy) == ("ESCALATED", "shadow_matched") + + +def test_a_shadow_run_without_its_case_is_not_a_match(): + row, _, _ = build_row(FIXTURES / "shadow_no_case") + assert _outcome(row) == ("UNKNOWN", "shadow_not_compared") + assert row.fields_written == () + + +def test_a_write_that_reached_the_app_in_shadow_mode_is_unknown(tmp_path): + run = tmp_path / "run" + shutil.copytree(FIXTURES / "shadow_matched", run) + doc = json.loads((run / "run.json").read_text()) + doc["landed_writes"] = 1 + (run / "run.json").write_text(json.dumps(doc)) + row, _, _ = build_row(run) + assert _outcome(row) == ("UNKNOWN", "shadow_write_landed") + + +@pytest.mark.parametrize( + ("status", "expected"), + [ + ("TIMEOUT", ("FAILED", "shadow_timed_out")), + ("NO_WRITE_HELD", ("FAILED", "shadow_no_proposal")), + # P1 sets AGENT_ERROR before its guard counted anything: no evidence. + ("AGENT_ERROR", ("UNKNOWN", "shadow_agent_error")), + ], +) +def test_a_shadow_run_that_proposed_nothing(tmp_path, status, expected): + run = tmp_path / "run" + shutil.copytree(FIXTURES / "shadow_no_case", run) + (run / "proposed_write.json").unlink() + doc = json.loads((run / "run.json").read_text()) + doc.update(status=status, proposed=False) + (run / "run.json").write_text(json.dumps(doc)) + row, _, _ = build_row(run) + assert _outcome(row) == expected + + +# -- J3: guarded saves ---------------------------------------------------------------- + + +def test_a_declined_approval_is_escalated_not_unknown_or_caught(): + row, _, _ = build_row(FIXTURES / "guard_declined") + assert _outcome(row) == ("ESCALATED", "person_declined") + # The row's approval times and the item-approval files describe one wait. + assert len(row.human.intervals) == 1 + assert row.human.intervention_s == 3.181 + + +def test_the_guard_rows_verdict_is_never_a_bucket_source(tmp_path): + for fixture, expected in ( + ("guard_declined", ("ESCALATED", "person_declined")), + ("guard_no_persist", ("UNKNOWN", "reconciliation_required")), + ("guard_approved_ok", ("VERIFIED", "readback_verified")), + ): + run = tmp_path / fixture + shutil.copytree(FIXTURES / fixture, run) + for verdict in ("CAUGHT_ERROR", "VERIFIED", "ESCALATED", "FAILED"): + doc = json.loads((run / "guard_ledger_row.json").read_text()) + doc["verdict"] = verdict + (run / "guard_ledger_row.json").write_text(json.dumps(doc)) + row, _, _ = build_row(run) + assert _outcome(row) == expected, (fixture, verdict) + + +def test_one_guarded_run_is_one_row_with_one_bucket(): + # The not-saved run: the guard says RECONCILIATION_REQUIRED, P5's row + # said ESCALATED and the effect receipt says REFUTED with the effect + # absent. The guard's rule (REFUTED only when the store shows a write) + # gives one answer: UNKNOWN. + row, _, _ = build_row(FIXTURES / "guard_no_persist") + assert _outcome(row) == ("UNKNOWN", "reconciliation_required") + assert row.readback_tier == "independent_readback" + + +def test_a_field_diff_keeps_caught_error_even_with_a_person_in_the_loop(): + row, _, _ = build_row(FIXTURES / "guard_wrong_value") + assert _outcome(row) == ("CAUGHT_ERROR", "readback_refuted") + assert {f.name: f.check for f in row.fields_written} == { + "note": "differs", + "type": "matched", + } + assert row.fields_differing == 1 + + +def test_an_approved_guarded_save_is_verified_with_the_persons_time(): + row, _, _ = build_row(FIXTURES / "guard_approved_ok") + assert _outcome(row) == ("VERIFIED", "readback_verified") + assert len(row.human.intervals) == 1 + assert row.human.intervention_s is not None and row.human.intervention_s > 0 + + +# -- J4: P6 exception answers ---------------------------------------------------------- + + +def _home_with_exceptions(tmp_path: Path) -> Path: + home = tmp_path / "home" + shutil.copytree(FIXTURES / "exceptions_home", home) + return home + + +def test_exception_answers_are_read_from_the_registry(tmp_path): + home = _home_with_exceptions(tmp_path) + run = tmp_path / "run" + run.mkdir() + result = LedgerStore(home).add(run, run_ref="e2e-answered") + row = result.row + assert _outcome(row) == ("ESCALATED", "second_factor") + assert [i.kind for i in row.human.intervals] == ["second_factor"] + assert row.human.intervention_s == 2.822 + assert row.task_id == "note-intake" # the card's task id + + +def test_an_expired_exception_is_unknown_time_not_zero(tmp_path): + home = _home_with_exceptions(tmp_path) + run = tmp_path / "run" + run.mkdir() + row = LedgerStore(home).add(run, run_ref="e2e-expired").row + assert row.outcome.value == "ESCALATED" + assert row.human.intervention_s is None + + +def test_without_a_run_ref_no_exception_folder_is_read(tmp_path): + # P6's run reference is the operator's --run-ref; nothing derives it + # from a run directory, so a folder named like the run isn't guessed. + home = _home_with_exceptions(tmp_path) + run = tmp_path / "e2e-answered" + run.mkdir() + row = LedgerStore(home).add(run).row + assert row.outcome_reason == "no_sources" + + +def test_a_card_from_another_task_is_a_conflict(tmp_path): + home = _home_with_exceptions(tmp_path) + run = tmp_path / "run" + shutil.copytree(FIXTURES / "guard_declined", run) + row = LedgerStore(home).add(run, run_ref="e2e-answered").row + assert _outcome(row) == ("UNKNOWN", "task_id_conflict") + + +def test_run_dir_exceptions_folder_is_not_p6s_location(tmp_path): + run = tmp_path / "run" + shutil.copytree( + FIXTURES / "exceptions_home" / "exceptions" / "e2e-answered", run / "exceptions" + ) + row, _, _ = build_row(run) + assert _outcome(row) == ("UNKNOWN", "no_sources") + + +# -- J5: P7 fallback -------------------------------------------------------------------- + + +def test_an_approved_verified_fallback_is_verified(): + row, _, _ = build_row(FIXTURES / "fallback_verified_readable") + assert _outcome(row) == ("VERIFIED", "readback_verified") + assert row.readback_tier == "independent_readback" + assert row.executor_kind == "agent" + assert (row.model.calls, row.model.cost_usd) == (0, 0.0) + # A person approved at the gate; the gate records one time, so the + # person's time is unknown, not zero. + assert row.human.intervention_s is None + assert row.sources == ("result.json",) + + +def test_a_refused_gate_is_a_decline_not_schema_unrecognised(): + row, _, _ = build_row(FIXTURES / "fallback_refused_readable") + assert _outcome(row) == ("ESCALATED", "person_declined") + # The agent attempt's own run1.json (agent: null) isn't read again. + row, _, _ = build_row(FIXTURES / "fallback_refused") + assert row.outcome_reason != "schema_unrecognised" + assert row.sources == ("result.json",) + + +def test_a_record_check_without_readable_true_proves_nothing(): + # P7's TaskRecordCheck says readable: false when a read failed; the zero + # counts then prove nothing. An older check has no flag at all. + for fixture, verified_or_not in ( + ("fallback_refused_unreadable", ("UNKNOWN", "write_unconfirmed")), + ("fallback_refused", ("UNKNOWN", "write_unconfirmed")), + ("fallback_verified", ("UNKNOWN", "reconciliation_required")), + ): + row, _, _ = build_row(FIXTURES / fixture) + assert _outcome(row) == verified_or_not, fixture + + +def test_the_dispatcher_envelope_is_wrapped_tasks_result_plus_dispatch_fields(): + # Built with P7's own WrappedTask._result and dispatch_cli.finish over + # the real result.json: no replay or compile, a top-level fallback. + doc = json.loads((FIXTURES / "dispatch_envelope_refused.json").read_text()) + assert "replay" not in doc and "compile" not in doc + assert doc["fallback"]["task_record_check"]["created"] == 0 + row, _, _ = build_row(FIXTURES / "dispatch_envelope_refused.json") + assert row.task_id == "r-119" + + +def test_the_dispatcher_envelopes_outcome_is_not_read(tmp_path): + for name, expected in ( + ("dispatch_envelope_verified.json", ("VERIFIED", "readback_verified")), + ("dispatch_envelope_refused.json", ("ESCALATED", "person_declined")), + ): + doc = json.loads((FIXTURES / name).read_text()) + doc["outcome"] = "CAUGHT_ERROR" + path = tmp_path / name + path.write_text(json.dumps(doc)) + row, _, _ = build_row(path) + assert _outcome(row) == expected + + +def test_a_wrap_record_of_a_verified_fallback_reads_p7s_record_check(tmp_path): + # Review on 0a886f1df: P7's run store record keeps the policy record in + # result.fallback (task_record_check), not result.record_check. + record = ( + RUN3_FALLBACK + / "runs" + / "drift-approved" + / "openadapt-agent" + / "runs" + / "run-b480e452b3ba49aab785d2ca.json" + ) + row, _, _ = build_row(record) + assert _outcome(row) == ("VERIFIED", "readback_verified") + assert row.executor_kind == "agent" + # Without a readable task_record_check, verified: true proves nothing. + doc = json.loads(record.read_text()) + doc["result"]["fallback"]["task_record_check"]["readable"] = False + path = tmp_path / "run-b480e452b3ba49aab785d2ca.json" + path.write_text(json.dumps(doc)) + row, _, _ = build_row(path) + assert _outcome(row) == ("UNKNOWN", "reconciliation_required") + del doc["result"]["fallback"] + path.write_text(json.dumps(doc)) + row, _, _ = build_row(path) + assert _outcome(row) == ("UNKNOWN", "reconciliation_required") + + +def test_a_refused_gate_with_a_write_on_record_is_not_a_clean_decline(tmp_path): + run = tmp_path / "run" + shutil.copytree(FIXTURES / "fallback_refused_readable", run) + doc = json.loads((run / "result.json").read_text()) + doc["replay"]["fallback"]["task_record_check"]["created"] = 1 + (run / "result.json").write_text(json.dumps(doc)) + row, _, _ = build_row(run) + assert _outcome(row) == ("UNKNOWN", "write_unconfirmed") + + +# -- skeptic #13: crash and timeout without evidence ----------------------------------- + + +def test_a_failed_compiled_run_with_no_transaction_outcome_is_unknown(tmp_path): + run = tmp_path / "run" + shutil.copytree(FIXTURES / "compiled_halted", run) + doc = json.loads((run / "report.json").read_text()) + doc.pop("transaction_outcome", None) + doc["execution_outcome"] = "FAILED" + (run / "report.json").write_text(json.dumps(doc)) + row, _, _ = build_row(run) + assert _outcome(row) == ("UNKNOWN", "write_unconfirmed") + + +# -- (a): declared field names may leave ---------------------------------------------- + + +def _store(tmp_path: Path) -> LedgerStore: + return LedgerStore(tmp_path / "home") + + +def test_declared_patient_id_passes_the_scrubber_check(tmp_path): + store = _store(tmp_path) + store.add( + FIXTURES / "run2_fallback_approved", + config=(RUN2_VERIFY,), + approvals=RUN2_APPROVALS, + ) + (line,) = outbound_lines(store, summary=False, scrubber=_Presidio()) + assert '"patient_id"' in line + + +def test_an_undeclared_rewritable_name_still_refuses(tmp_path): + store = _store(tmp_path) + # A lone proposed write: no task, verify or reference config declares + # its fields. + run = tmp_path / "run" + run.mkdir() + shutil.copy(FIXTURES / "shadow_matched" / "proposed_write.json", run) + store.add(run) + with pytest.raises(LedgerRefused, match="fields_written.name"): + outbound_lines(store, summary=False, scrubber=_Presidio()) + + +def test_an_extra_field_the_reference_does_not_declare_refuses(tmp_path): + run = tmp_path / "run" + shutil.copytree(FIXTURES / "shadow_matched", run) + case = json.loads((run / "case.json").read_text()) + case["fields"].append( + {"name": "ssn", "kind": "extra", "human": None, "proposed": "x"} + ) + (run / "case.json").write_text(json.dumps(case)) + store = _store(tmp_path) + store.add(run) + # A shadow row carries no field names at all, so none can leave. + (line,) = outbound_lines(store, summary=False, scrubber=_Presidio("ssn")) + assert "ssn" not in line + + +def test_a_failed_scope_case_declares_none_of_the_proposed_names(tmp_path): + # compare.py returns before it builds the rows for FAILED_SCOPE, so the + # empty field list says nothing about the agent's own names. + run = tmp_path / "run" + shutil.copytree(FIXTURES / "shadow_matched", run) + case = json.loads((run / "case.json").read_text()) + case.update(status="FAILED_SCOPE", reason="a write reached the app", fields=[]) + (run / "case.json").write_text(json.dumps(case)) + store = _store(tmp_path) + assert store.add(run).row.outcome_reason == "shadow_write_landed" + assert store.entries()[0]["declared_fields"] == [] + + +def test_another_tasks_guard_task_declares_nothing(tmp_path): + task = json.loads((FIXTURES / "guard_approved_ok_config" / "task.json").read_text()) + task["task_id"] = "another-task" + other = tmp_path / "task.json" + other.write_text(json.dumps(task)) + store = _store(tmp_path) + store.add(FIXTURES / "guard_approved_ok", config=(other,)) + assert store.entries()[0]["declared_fields"] == [] + + +def test_guard_task_fields_are_declared_through_config(tmp_path): + config = sorted((FIXTURES / "guard_approved_ok_config").iterdir()) + plain = LedgerStore(tmp_path / "a") + plain.add(FIXTURES / "guard_approved_ok") + with pytest.raises(LedgerRefused, match="fields_written.name"): + outbound_lines(plain, summary=False, scrubber=_Presidio("note")) + declared = LedgerStore(tmp_path / "b") + declared.add(FIXTURES / "guard_approved_ok", config=tuple(config)) + (entry,) = declared.entries() + assert entry["declared_fields"] == ["name", "note", "patient_id", "type"] + assert outbound_lines(declared, summary=False, scrubber=_Presidio("note")) + + +def test_an_entry_from_before_declared_fields_exempts_nothing(tmp_path): + store = _store(tmp_path) + store.add( + FIXTURES / "run2_fallback_approved", + config=(RUN2_VERIFY,), + approvals=RUN2_APPROVALS, + ) + body = "".join( + json.dumps({k: v for k, v in e.items() if k != "declared_fields"}) + "\n" + for e in store.entries() + ) + store.rows_path.write_text(body) + with pytest.raises(LedgerRefused): + outbound_lines(store, summary=False, scrubber=_Presidio()) + + +def test_the_real_scrubber_lets_every_demo_run_out(tmp_path): + """openadapt-privacy's own scrubber over the shadow and guard copies.""" + + from openadapt_flow.privacy import PrivacyNotAvailable, get_text_scrubber + + try: + scrubber = get_text_scrubber() + if scrubber is not None: + scrubber.scrub_text("probe") # the spaCy model may be missing + except (PrivacyNotAvailable, Exception): # noqa: BLE001 + scrubber = None + if scrubber is None: + pytest.skip("openadapt-privacy's text scrubber can't run here") + store = _store(tmp_path) + for path in sorted(FIXTURES.iterdir()): + if path.name == "shadow_no_case": + continue # added at the end + if path.name.startswith("fallback_"): + continue # no config declares their read-back field names + if path.name.startswith(("shadow_", "run2_claude")): + store.add(path) + elif path.name == "run2_fallback_approved": + config = FIXTURES / "run2_fallback_approved_config" / "verify.yaml" + store.add(path, config=(config,), approvals=FIXTURES / "run2_approvals") + elif path.name.startswith("guard_") and not path.name.endswith("_config"): + config = FIXTURES / f"{path.name}_config" + files = tuple(sorted(config.iterdir())) if config.is_dir() else () + store.add(path, config=files) + lines = outbound_lines(store, summary=True, scrubber=scrubber) + assert len(lines) == len(store.latest()) + # A shadow run with no case.json: no field names, so it goes too. + store.add(FIXTURES / "shadow_no_case") + assert len(outbound_lines(store, summary=True, scrubber=scrubber)) == len( + store.latest() + ) + + +# -- J6: the push payload ------------------------------------------------------------- + + +def _schema() -> dict: + from openadapt_types.run_ledger import AgentRunSummaryV1 + + return AgentRunSummaryV1.model_json_schema(by_alias=True) + + +def test_push_payloads_validate_against_the_json_schema(tmp_path): + import jsonschema + + store = _store(tmp_path) + for name in ( + "shadow_matched", + "guard_declined", + "guard_no_persist", + "fallback_refused", + "compiled_halted_receipt", + ): + store.add(FIXTURES / name) + payloads = push(store, dry_run=True, environ={}, scrubber=_Presidio()) + validator = jsonschema.Draft202012Validator(_schema()) + for payload in payloads: + validator.validate(payload) + # Unknown values stay null, never 0. + halted = next(p for p in payloads if p["outcome_reason"] == "halted_before_effect") + # The receipt's own read-back times bound the run; no duration is kept. + assert halted["started_at"] is not None and halted["duration_s"] is None + assert halted["model"]["calls"] is None and halted["model"]["cost_usd"] is None + + +def test_the_committed_j6_examples_validate_against_the_json_schema(): + import jsonschema + + validator = jsonschema.Draft202012Validator(_schema()) + lines = J6_EXAMPLES.read_text().splitlines() + assert len(lines) >= 4 + seen_null = False + for line in lines: + payload = json.loads(line) + validator.validate(payload) + seen_null |= payload["model"]["calls"] is None + assert seen_null + reasons = {json.loads(line)["outcome_reason"] for line in lines} + assert {"shadow_wrong_record", "person_declined", "readback_verified"} <= reasons + + +def test_collect_reads_a_shadow_run_as_one_source(): + collected = collect(FIXTURES / "shadow_wrong_record") + assert [c.collector for c in collected.contributions] == ["readiness_shadow"] + assert collected.declared_fields == {"note", "patient_id", "type"} + + +def test_a_field_that_differs_from_any_source_is_a_caught_error(tmp_path): + # Review on b4e63aa2d: a row could be VERIFIED while a field differed. + # The guard row's differing field now makes the run CAUGHT_ERROR even + # when summary.json says VERIFIED. + run = tmp_path / "run" + shutil.copytree(FIXTURES / "guard_approved_ok", run) + doc = json.loads((run / "guard_ledger_row.json").read_text()) + doc.update(fields_differing=["note"]) + (run / "guard_ledger_row.json").write_text(json.dumps(doc)) + row, _, _ = build_row(run) + assert _outcome(row) == ("CAUGHT_ERROR", "readback_field_differs") + assert ("note", "differs") in [(f.name, f.check) for f in row.fields_written] + + +def test_the_schema_refuses_verified_with_a_differing_field(): + from openadapt_types.run_ledger import RunLedgerRowV1 + + row, _, _ = build_row(FIXTURES / "guard_approved_ok") + doc = row.to_json() + doc["fields_differing"] = 1 + with pytest.raises(ValueError, match="differs"): + RunLedgerRowV1.model_validate(doc) + + +# -- a person's time: unknown unless a source shows nobody was asked ---------------- + + +@pytest.mark.parametrize( + ("fixture", "expected"), + [ + ("shadow_matched", 0.0), # the shadow hold asks nobody + ("guard_no_persist", 0.0), # approval not_gated + ("compiled_verified", None), # a compiled run's report doesn't say + ("compiled_halted_receipt", None), + ("fallback_verified", None), # a person approved at a gate + ("dispatch_envelope_refused.json", None), # no gate times at all + ], +) +def test_no_intervals_is_unknown_unless_nobody_was_asked(fixture, expected): + row, _, _ = build_row(FIXTURES / fixture) + assert row.human.intervention_s == expected + + +# -- task ids: a rewritten one leaves as an opaque id, never as text -------------- + + +class _ReadsTaskIdAsOrg(_Presidio): + """What Presidio does to P1's extra-target sample's task id.""" + + def __init__(self, *more: str) -> None: + super().__init__("readiness-mockmed-0002", *more) + + +def test_a_task_id_the_scrubber_rewrites_leaves_as_an_opaque_id(tmp_path): + store = _store(tmp_path) + store.add(FIXTURES / "shadow_extra_target") + (line,) = outbound_lines(store, summary=True, scrubber=_ReadsTaskIdAsOrg()) + sent = json.loads(line)["task_id"] + assert re.fullmatch(r"tid-[0-9a-f]{16}", sent) + assert "readiness-mockmed-0002" not in line + # Stable per task, and the key stays here, owner-only. + assert store.opaque_task_id("readiness-mockmed-0002") == sent + key = store.root / "task-id.key" + assert stat.S_IMODE(key.stat().st_mode) == 0o600 + # Kept locally as it was. + assert store.rows()[0].task_id == "readiness-mockmed-0002" + + +def test_a_caller_chosen_request_id_never_leaves_as_text(tmp_path): + # A wrap-dispatch request id is chosen by the agent that calls it. + store = _store(tmp_path) + store.add(FIXTURES / "run2_envelope_happy.json") + store.add(FIXTURES / "run2_envelope_declined.json") + lines = outbound_lines( + store, + summary=True, + scrubber=_ReadsTaskIdAsOrg("dispatch-happy", "dispatch-drift-declined"), + ) + ids = {json.loads(line)["task_id"] for line in lines} + assert len(ids) == 2 and all(i.startswith("tid-") for i in ids) + assert not any("dispatch-" in line for line in lines) + + +def test_another_install_gets_another_opaque_id(tmp_path): + a, b = LedgerStore(tmp_path / "a"), LedgerStore(tmp_path / "b") + assert a.opaque_task_id("x") != b.opaque_task_id("x") + + +# -- P5's current row (guard_verdict, verdict_reason) --------------------------------- + + +@pytest.mark.parametrize("fixture", ["guard_row_p5_verified", "guard_row_p5_declined"]) +def test_p5s_current_row_alone_decides_no_bucket(fixture): + # Real rows from P5's d0a1e92f3 (its own tests against MockMed's fault + # server): verdict VERIFIED / ESCALATED, guard_verdict, verdict_reason. + doc = json.loads((FIXTURES / fixture / "guard_ledger_row.json").read_text()) + assert {"guard_verdict", "verdict_reason"} <= set(doc) + row, _, _ = build_row(FIXTURES / fixture) + assert _outcome(row) == ("UNKNOWN", "completed_unverified") + assert row.readback_tier == doc["readback_tier"] + + +def test_p5s_row_times_still_count(): + row, _, _ = build_row(FIXTURES / "guard_row_p5_declined") + assert len(row.human.intervals) == 1 + assert row.human.intervention_s is not None + + +# -- round 3: the integrated run2 (2026-11-22) --------------------------------------- +# +# run2_* are copies of /tmp/acp-demo-out/run2: 5-claude's real Claude readiness +# run, 4-fallback's results, envelopes and item-approval folders (request and +# answer JSON only), the compiled verify.yaml a person confirmed, and a +# 2-gated approved save. + +RUN2_APPROVALS = FIXTURES / "run2_approvals" +RUN2_VERIFY = FIXTURES / "run2_fallback_approved_config" / "verify.yaml" + + +def test_a_real_claude_readiness_run_with_no_proposal_is_a_shadow_reason(): + # NO_WRITE_HELD: the agent said it wasn't done and proposed nothing. + row, _, _ = build_row(FIXTURES / "run2_claude_no_write") + assert _outcome(row) == ("FAILED", "shadow_no_proposal") + assert row.outcome_reason.startswith("shadow_") + assert (row.model.calls, row.model.cost_source) == (2, "metered") + # The proxy's timeline names the run's first and last model traffic. + assert row.started_at == "2026-11-22T05:10:55.470000Z" + assert row.ended_at is not None and row.duration_s == 7.603 + + +@pytest.mark.parametrize( + "fixture", + [ + "shadow_matched", + "shadow_mismatched", + "shadow_extra_target", + "shadow_egress", + "shadow_wrong_record", + "shadow_no_case", + "run2_claude_no_write", + ], +) +def test_every_shadow_row_has_a_shadow_reason(fixture): + row, _, _ = build_row(FIXTURES / fixture) + assert row.outcome_reason.startswith("shadow_") or ( + row.outcome_reason == "egress_refused" + ) + + +def test_the_approved_fallback_has_the_persons_time_and_its_fields(tmp_path): + row = ( + _store(tmp_path) + .add( + FIXTURES / "run2_fallback_approved", + config=(RUN2_VERIFY,), + approvals=RUN2_APPROVALS, + ) + .row + ) + assert _outcome(row) == ("VERIFIED", "readback_verified") + # The signed approval: request created_at to answer answered_at. + assert [i.kind for i in row.human.intervals] == ["approval"] + assert row.human.intervention_s == 0.062 + # The record check's names that the confirmed verify.yaml declares. + assert [(f.name, f.check) for f in row.fields_written] == [ + ("note", "matched"), + ("patient_id", "matched"), + ("type", "matched"), + ] + assert row.started_at is not None and row.ended_at is not None + + +def test_without_the_approvals_folder_the_persons_time_is_unknown(tmp_path): + alone = tmp_path / "result-drift-approved.json" + shutil.copy(FIXTURES / "run2_envelope_approved.json", alone) + row, _, _ = build_row(alone) + assert _outcome(row) == ("VERIFIED", "readback_verified") + assert row.human.intervention_s is None + + +def test_the_envelope_finds_its_own_approvals_folder_by_request_id(): + # The fixtures folder holds run2_approvals//: the + # gate_answers' request id and sha256 bind it to this envelope. + row, _, _ = build_row(FIXTURES / "run2_envelope_approved.json") + assert row.human.intervention_s == 0.062 + + +def test_the_envelope_with_its_approvals_folder(tmp_path): + row = ( + _store(tmp_path) + .add(FIXTURES / "run2_envelope_declined.json", approvals=RUN2_APPROVALS) + .row + ) + assert _outcome(row) == ("ESCALATED", "person_declined") + assert row.human.intervention_s == 0.02 + assert row.task_id == "dispatch-drift-declined" + + +def test_times_come_from_the_runs_own_files(): + row, _, _ = build_row(FIXTURES / "run2_guard_approved") + # The guard held the save at t=2.829 s; the approval request was created + # then (05:02:08.735233), so the run started 2.829 s before that. + assert row.started_at == "2026-11-22T05:02:05.906233Z" + assert row.ended_at == "2026-11-22T05:02:13.621233Z" + assert row.duration_s == 7.715 + row, _, _ = build_row(FIXTURES / "run2_envelope_happy.json") + assert row.started_at is None and row.ended_at is None # no source has one + + +# -- round 3: one bad row refuses itself, not the ledger ---------------------------- + + +def _two_rows(tmp_path: Path) -> LedgerStore: + store = _store(tmp_path) + store.add(FIXTURES / "shadow_matched") + run = tmp_path / "run" + run.mkdir() + shutil.copy(FIXTURES / "shadow_matched" / "proposed_write.json", run) + store.add(run) # a lone proposed write: patient_id undeclared + return store + + +def test_screen_rows_refuses_only_the_bad_row(tmp_path): + from openadapt_flow.run_ledger.cli import screen_rows + + store = _two_rows(tmp_path) + screened = screen_rows(store, summary=True, scrubber=_Presidio()) + assert len(screened.lines) == 1 + ((row_id, reason),) = screened.refused + assert reason == "the scrubber would rewrite its fields_written.name" + assert row_id not in screened.lines[0] + + +def test_push_sends_the_good_rows_and_lists_the_refused_ones(tmp_path): + store = _two_rows(tmp_path) + sent: list[dict] = [] + refused: list[tuple[str, str]] = [] + results = push( + store, + host="https://app.openadapt.ai", + poster=lambda url, headers, payload: sent.append(payload) or 202, + environ={"OPENADAPT_API_KEY": "test-key-not-real"}, + scrubber=_Presidio(), + refused=refused, + ) + assert len(sent) == len(results) == 1 and len(refused) == 1 + + +def test_export_writes_the_good_rows_and_exits_non_zero(tmp_path, monkeypatch, capsys): + import openadapt_flow.privacy as privacy + from openadapt_flow.run_ledger.cli import main + + home = tmp_path / "home" + monkeypatch.setenv("OPENADAPT_HOME", str(home)) + monkeypatch.setattr(privacy, "get_text_scrubber", lambda: _Presidio()) + _two_rows(tmp_path) + out = tmp_path / "export.jsonl" + assert main(["ledger", "export", "--out", str(out)]) == 2 + assert len(out.read_text().splitlines()) == 1 + assert "refused row" in capsys.readouterr().err + + +# -- round 4: an allowlist of files, nothing else is read --------------------------- + +PLANTED = ("Zelda Quintanilla-Hart", "MRN-PLANTED-7731") + + +def _planted_run(tmp_path: Path) -> Path: + """A real readiness run plus P3's pseudonym map (real values, 0600) and a + stray file, both unreadable so any attempt to open them would show.""" + + run = tmp_path / "run" + shutil.copytree(FIXTURES / "run2_claude_no_write", run) + pseudonyms = run / "egress" / "pseudonyms.json" + pseudonyms.write_text( + json.dumps({"": PLANTED[0], "": PLANTED[1]}), encoding="utf-8" + ) + stray = run / "notes.json" + stray.write_text( + json.dumps( + { + "schema": "openadapt.flight-run/v1", + "task_id": PLANTED[1], + "note": PLANTED[0], + } + ) + ) + for path in (pseudonyms, stray): + path.chmod(0o000) + return run + + +def test_files_off_the_allowlist_never_leave(tmp_path): + run = _planted_run(tmp_path) + clean, _, _ = build_row(FIXTURES / "run2_claude_no_write") + try: + store = _store(tmp_path) + row = store.add(run, task_type="intake").row + assert _outcome(row) == _outcome(clean) + assert "egress/pseudonyms.json" not in row.sources + assert "notes.json" not in row.sources + payloads = push(store, dry_run=True, environ={}, scrubber=_Presidio()) + exported = outbound_lines(store, summary=False, scrubber=_Presidio()) + stored = store.rows_path.read_text() + sidecars = "".join(p.read_text() for p in store.private_root.rglob("*.json")) + for text in (json.dumps(payloads), "".join(exported), stored, sidecars): + for value in PLANTED: + assert value not in text + finally: + for path in (run / "egress" / "pseudonyms.json", run / "notes.json"): + path.chmod(0o600) + + +def test_a_file_off_the_allowlist_named_directly_or_as_config_is_ignored(tmp_path): + run = _planted_run(tmp_path) + pseudonyms = run / "egress" / "pseudonyms.json" + try: + row, _, _ = build_row(pseudonyms) + assert _outcome(row) == ("UNKNOWN", "no_sources") and row.sources == () + collected = collect(run, config=(pseudonyms, run / "notes.json")) + assert collected.config_paths == [] + assert all( + p.name not in ("pseudonyms.json", "notes.json") for p in collected.files + ) + finally: + for path in (pseudonyms, run / "notes.json"): + path.chmod(0o600) + + +@pytest.mark.parametrize( + ("name", "direct", "allowed"), + [ + ("egress/pseudonyms.json", False, False), + ("egress/pseudonyms.json", True, False), + ("egress/timeline.jsonl", False, True), + ("timeline.jsonl", False, False), + ("notes.json", False, False), + ("run.json", False, True), + ("item-approval/request-abc.json", False, True), + ("item-approval/consumed-abc", False, False), + ("runs/run-0001.json", False, True), + ("runs/pseudonyms.json", False, False), + ("result-drift-approved.json", True, True), + ("verify.proposed.yaml", False, False), + ], +) +def test_the_allowlist(name, direct, allowed): + from openadapt_flow.run_ledger.collect import allowed_file + + assert allowed_file(Path("/x") / name, direct=direct) is allowed + + +# -- round 5: run3 (2026-11-22) accuracy findings ----------------------------------- +# +# run3_* are copies of /tmp/acp-demo-out/run3 (allowlisted files only). + +RUN3_FALLBACK = FIXTURES / "run3_fallback" + + +def test_a_cleared_exception_then_a_verified_save_is_verified(): + # P6: the person typed the code (done_by_person); the guard then read the + # save back independently. VERIFIED, with the person's time recorded. + exceptions = FIXTURES / "run3_exceptions_home" / "exceptions" / "watch-2fa-run3" + row, _, _ = build_row(FIXTURES / "run3_watch", exceptions=exceptions) + assert _outcome(row) == ("VERIFIED", "readback_verified") + assert [i.kind for i in row.human.intervals] == ["second_factor"] + assert row.human.intervention_s == 0.059 + + +def test_a_stopped_exception_stays_escalated_even_after_a_verified_save(tmp_path): + folder = tmp_path / "watch-2fa-run3" + shutil.copytree( + FIXTURES / "run3_exceptions_home" / "exceptions" / "watch-2fa-run3", folder + ) + (answer,) = folder.glob("answer-*.json") + doc = json.loads(answer.read_text()) + doc["answer"] = "abort" # the person stopped the run + answer.write_text(json.dumps(doc)) + row, _, _ = build_row(FIXTURES / "run3_watch", exceptions=folder) + assert _outcome(row) == ("ESCALATED", "second_factor") + + +def test_run3_shadow_rows_write_no_fields(): + row, _, _ = build_row(FIXTURES / "run3_shadow_matched") + assert _outcome(row) == ("ESCALATED", "shadow_matched") + assert row.fields_written == () + + +@pytest.mark.parametrize( + "fixture", + [ + "run3_adversarial", # the hold's held/0.json held_at + "run3_guard_wrong_patient", # recording/meta.json created_at + "run3_fallback/result-happy.json", # wrap's run store record + "run3_fallback/result-drift-approved.json", + "run3_fallback/result-drift-declined.json", + ], +) +def test_run3_rows_have_start_times(fixture): + row, _, _ = build_row(FIXTURES / fixture) + assert row.started_at is not None and row.ended_at is not None + + +def test_the_approved_fallback_envelope_finds_its_approval_and_fields(): + row, _, _ = build_row(RUN3_FALLBACK / "result-drift-approved.json") + assert _outcome(row) == ("VERIFIED", "readback_verified") + assert [i.kind for i in row.human.intervals] == ["approval"] + assert row.human.intervention_s == 0.043 + # From the fallback's own result.json record check, kept to the names + # the task's confirmed compiled/verify.yaml declares. + assert [(f.name, f.check) for f in row.fields_written] == [ + ("note", "matched"), + ("patient_id", "matched"), + ("type", "matched"), + ] + + +def test_a_gate_answer_for_another_request_is_not_read(tmp_path): + copy = tmp_path / "fb" + shutil.copytree(RUN3_FALLBACK, copy) + envelope = copy / "result-drift-approved.json" + doc = json.loads(envelope.read_text()) + doc["fallback"]["gate_answers"][0]["request_sha256"] = "sha256:" + "0" * 64 + envelope.write_text(json.dumps(doc)) + row, _, _ = build_row(envelope) + # The folder's answer belongs to another request: fail closed. + assert _outcome(row) == ("UNKNOWN", "source_unreadable") + + +def test_the_decline_rows_duration_is_the_runs_own_span(): + # The guard idled 54 s after the decline until its timeout; the run ends + # at its last save decision (t=5.893). The person answered 3.191 s after + # the card opened. + row, _, _ = build_row(FIXTURES / "run3_guard_decline") + assert _outcome(row) == ("ESCALATED", "person_declined") + assert row.duration_s == 5.893 + assert row.human.intervention_s == 3.191 + assert row.started_at == "2026-11-22T05:56:43.053948Z" + + +# -- review fixes --------------------------------------------------------------------- + + +def test_p5s_values_unread_block_is_escalated_values_unread(): + # P5 6fa9c3a36: the card couldn't show the values, so the guard asked no + # one and blocked the save. summary.json and the row are P5's own output + # (its unit test; summary.json is CommitGuard.summary.to_dict() as + # agent_guard/session.py writes it). + row, _, _ = build_row(FIXTURES / "guard_values_unread") + assert _outcome(row) == ("ESCALATED", "values_unread") + assert row.human.intervention_s == 0.0 # nobody was asked + + +def test_an_answered_question_stays_escalated(): + # The ledger never reads a question's answer text, so it can't tell + # whether the answer let the run go on: an answered question is still + # a person's step (ESCALATED question_asked), unlike a cleared exception. + row, _, _ = build_row(FIXTURES / "task_ledger_question") + assert _outcome(row) == ("ESCALATED", "question_asked") + assert row.human.intervention_s == 120.0 + + +def test_export_checks_source_paths_like_labels(tmp_path): + # Review on 0a886f1df: export carries sources; a path part the scrubber + # would rewrite leaves as an opaque src-, never as text. + store = _store(tmp_path) + run = tmp_path / "Zelda-Quintanilla" + shutil.copytree(FIXTURES / "run3_fallback", run) + store.add(run / "result-drift-approved.json") + scrubber = _Presidio("result-drift-approved.json", "drift-approved") + (line,) = outbound_lines(store, summary=False, scrubber=scrubber) + sources = json.loads(line)["sources"] + assert "result-drift-approved.json" not in sources + assert not any("drift-approved" in part for s in sources for part in s.split("/")) + assert any(part.startswith("src-") for s in sources for part in s.split("/")) + # The real paths stay in the local row. + assert "result-drift-approved.json" in store.rows()[0].sources diff --git a/packages/flow/tests/test_run_ledger_outcome.py b/packages/flow/tests/test_run_ledger_outcome.py new file mode 100644 index 0000000000..3789c0ce26 --- /dev/null +++ b/packages/flow/tests/test_run_ledger_outcome.py @@ -0,0 +1,234 @@ +"""The outcome rule, as a table (docs/RUN_LEDGER.md). + +Every terminal outcome the engine writes on main maps to exactly one bucket, +each contract source lands where the doc says, and a model's judgement never +upgrades a deterministic refutation. +""" + +from __future__ import annotations + +import shutil +from pathlib import Path + +import pytest +from openadapt_types.execute import ExecuteTerminalOutcomeV1 +from openadapt_types.run_ledger import RUN_LEDGER_REASON_OUTCOME + +from openadapt_flow.execution_profiles import ExecutionOutcome +from openadapt_flow.guard import GuardVerdict +from openadapt_flow.run_ledger.outcome import ( + AGENT_RUN_STATUS_REASON, + EXECUTE_OUTCOME_REASON, + EXECUTION_OUTCOME_REASON, + GUARD_VERDICT_REASON, + TRANSACTION_OUTCOME_REASON, + Signal, + decide, + guard_block_reason, + outcome_reason, +) +from openadapt_flow.run_ledger.store import build_row +from openadapt_flow.transaction import TransactionOutcome + +FIXTURES = Path(__file__).parent / "fixtures" / "run_ledger" + +V, E, C, F, U = "VERIFIED", "ESCALATED", "CAUGHT_ERROR", "FAILED", "UNKNOWN" + +TRANSACTION = { + "VERIFIED": V, + "HALTED_BEFORE_EFFECT": E, + "RECONCILIATION_REQUIRED": U, + "FAILED_PLATFORM": F, + "CANCELED": F, + "REJECTED_POLICY": F, + "COMPLETED_UNVERIFIED": U, + "ROLLED_BACK": U, + "SAVED_AWAITING_CHECK": U, +} +EXECUTE = { + "verified": V, + "halted_before_effect": E, + "reconciliation_required": U, + # verify-run's REJECTED_POLICY: the write landed but was self-approved. + "rejected_policy": U, + "failed_platform": F, + "rolled_back_verified": U, +} +EXECUTION = { + "VERIFIED": V, + "COMPLETED_UNVERIFIED": U, + "HALTED": U, + "FAILED": F, + "ROLLED_BACK": U, +} +# A failure, a timeout or an error can come after a request went out: with +# no evidence that nothing was sent they are UNKNOWN, not FAILED (skeptic #13). +EXECUTION["FAILED"] = U +GUARD = {"VERIFIED": V, "REFUTED": C, "RECONCILIATION_REQUIRED": U} +AGENT_STATUS = {"success": U, "halt": U, "refused": F, "timeout": U, "error": U} + + +def _bucket(reason: str) -> str: + return RUN_LEDGER_REASON_OUTCOME[reason].value + + +@pytest.mark.parametrize("member", list(TransactionOutcome)) +def test_every_transaction_outcome_has_one_bucket(member: TransactionOutcome) -> None: + assert member.value in TRANSACTION_OUTCOME_REASON, "add it to the table and doc" + assert ( + _bucket(TRANSACTION_OUTCOME_REASON[member.value]) == TRANSACTION[member.value] + ) + + +@pytest.mark.parametrize("member", list(ExecuteTerminalOutcomeV1)) +def test_every_execute_outcome_has_one_bucket(member: ExecuteTerminalOutcomeV1) -> None: + reason = outcome_reason(EXECUTE_OUTCOME_REASON, member.value) + assert reason != "unmapped_outcome", "add it to the table and doc" + assert _bucket(reason) == EXECUTE[member.value] + + +@pytest.mark.parametrize("member", list(ExecutionOutcome)) +def test_every_execution_outcome_has_one_bucket(member: ExecutionOutcome) -> None: + assert _bucket(EXECUTION_OUTCOME_REASON[member.value]) == EXECUTION[member.value] + + +@pytest.mark.parametrize("member", list(GuardVerdict)) +def test_every_guard_verdict_has_one_bucket(member: GuardVerdict) -> None: + assert _bucket(GUARD_VERDICT_REASON[member.value]) == GUARD[member.value] + + +@pytest.mark.parametrize("status", sorted(AGENT_STATUS)) +def test_every_agent_run_status_has_one_bucket(status: str) -> None: + assert _bucket(AGENT_RUN_STATUS_REASON[status]) == AGENT_STATUS[status] + + +def test_an_unmapped_outcome_is_unknown_never_another_bucket() -> None: + assert outcome_reason(TRANSACTION_OUTCOME_REASON, "SOMETHING_NEW") == ( + "unmapped_outcome" + ) + assert outcome_reason(TRANSACTION_OUTCOME_REASON, None) == "unmapped_outcome" + assert _bucket("unmapped_outcome") == U + + +@pytest.mark.parametrize( + ("code", "reason"), + [ + ("identity_mismatch", "save_blocked_wrong_record"), + ("identity_missing", "save_blocked_wrong_record"), + ("other_origin", "save_blocked_other_origin"), + ("already_committed", "save_blocked_double_save"), + ("needs_reconciliation", "save_blocked_double_save"), + ("save_waiting_for_person", "save_blocked_double_save"), + # A person said no: ESCALATED, not a catch (skeptic #16). + ("declined", "person_declined"), + ("values_unread", "values_unread"), + ("request_expired", "approval_declined"), + ("approval_wait_timed_out", "approval_declined"), + ("baseline_unreadable", "policy_rejected_no_write"), + ("answer_malformed", "policy_rejected_no_write"), + ("approval_something_new", "unmapped_outcome"), + ], +) +def test_guard_block_codes(code: str, reason: str) -> None: + assert guard_block_reason(code) == reason + assert guard_block_reason(code, scope=True) == "save_blocked_out_of_scope" + + +# -- precedence ------------------------------------------------------------------------ + + +@pytest.mark.parametrize( + ("reasons", "expected"), + [ + (["readback_verified", "readback_refuted"], C), + (["readback_verified", "reconciliation_required"], U), + (["approval_held", "reconciliation_required"], U), + (["approval_held", "timed_out_no_write"], E), + (["agent_gave_up", "readback_verified"], F), + (["readback_verified"], V), + (["shadow_field_mismatch", "halted_before_effect"], C), + ([], U), + ], +) +def test_precedence(reasons: list[str], expected: str) -> None: + outcome, _ = decide(Signal(r) for r in reasons) + assert outcome.value == expected + + +def test_a_model_never_verifies() -> None: + outcome, reason = decide([Signal("readback_verified", "model")]) + assert (outcome.value, reason) == (U, "completed_unverified") + + +def test_refuted_readback_plus_model_looks_fine_is_caught_error(tmp_path: Path) -> None: + """A deterministic refutation and an agent that says it's done.""" + + run = tmp_path / "run" + shutil.copytree(FIXTURES / "guard_wrong_value", run) + (run / "agent_ledger.json").write_text( + (FIXTURES / "agent_only_finished" / "agent_ledger.json").read_text() + ) + row, _, _ = build_row(run) + assert (row.outcome.value, row.outcome_reason) == (C, "readback_refuted") + + +# -- each contract source, as a table ------------------------------------------------ + + +@pytest.mark.parametrize( + ("fixture", "outcome", "reason"), + [ + # J1: P1 readiness run directories. Never VERIFIED. + ("shadow_matched", E, "shadow_matched"), + ("shadow_mismatched", C, "shadow_field_mismatch"), + ("shadow_wrong_record", C, "shadow_wrong_record"), + ("shadow_no_case", U, "shadow_not_compared"), + ("shadow_egress", E, "shadow_matched"), + ("flight_held", E, "gate_held"), + ("flight_refused", C, "gate_refused"), + # J3: P5 guarded saves; summary.json and the read-back decide. + ("guard_approved_ok", V, "readback_verified"), + ("guard_declined", E, "person_declined"), + ("guard_no_persist", U, "reconciliation_required"), + ("guard_wrong_value", C, "readback_refuted"), + ("guard_wrong_patient", C, "save_blocked_wrong_record"), + # J5: P7 fallback results. + # P7's current record check says readable: true. + ("fallback_verified_readable", V, "readback_verified"), + ("fallback_refused_readable", E, "person_declined"), + # Missing (older P7) or false readable proves nothing. + ("fallback_verified", U, "reconciliation_required"), + ("fallback_refused", U, "write_unconfirmed"), + ("fallback_refused_unreadable", U, "write_unconfirmed"), + ("dispatch_envelope_verified.json", V, "readback_verified"), + ("dispatch_envelope_refused.json", E, "person_declined"), + # A program's halt before the save: the absent effect isn't a catch. + ("compiled_halted_receipt", E, "halted_before_effect"), + ("unknown_schema", U, "schema_unrecognised"), + ("compiled_verified", V, "readback_verified"), + ("compiled_screen", U, "screen_readback_only"), + ("compiled_halted", E, "halted_before_effect"), + ("wrap_verified", V, "readback_verified"), + ("wrap_lost", U, "lost_reply"), + ("task_ledger_question", E, "question_asked"), + ("agent_only_finished", U, "completed_unverified"), + ("agent_only_gave_up", F, "agent_gave_up"), + ], +) +def test_fixture_outcomes(fixture: str, outcome: str, reason: str) -> None: + row, _, _ = build_row(FIXTURES / fixture) + assert (row.outcome.value, row.outcome_reason) == (outcome, reason) + + +def test_an_empty_run_is_unknown_no_sources(tmp_path: Path) -> None: + row, _, _ = build_row(tmp_path) + assert (row.outcome.value, row.outcome_reason) == (U, "no_sources") + assert row.sources == () + + +def test_conflicting_task_ids_are_unknown(tmp_path: Path) -> None: + for name in ("guard_declined", "flight_held"): + for src in (FIXTURES / name).glob("*.json"): + (tmp_path / src.name).write_text(src.read_text()) + row, _, _ = build_row(tmp_path) + assert row.outcome_reason == "task_id_conflict" diff --git a/packages/types/openadapt_types/__init__.py b/packages/types/openadapt_types/__init__.py index 87e79dde54..c930f36df6 100644 --- a/packages/types/openadapt_types/__init__.py +++ b/packages/types/openadapt_types/__init__.py @@ -439,6 +439,25 @@ refuse_development_certification, score, ) + from openadapt_types.run_ledger import ( + AGENT_RUN_SUMMARY_SCHEMA, + RUN_LEDGER_OUTCOME_PRECEDENCE, + RUN_LEDGER_REASON_OUTCOME, + RUN_LEDGER_SCHEMA, + AgentRunSummaryV1, + RunLedgerCostSource, + RunLedgerExecutorKind, + RunLedgerFieldCheck, + RunLedgerFieldV1, + RunLedgerHumanV1, + RunLedgerIntervalV1, + RunLedgerInterventionKind, + RunLedgerModelUsageV1, + RunLedgerOutcome, + RunLedgerOutcomeReason, + RunLedgerReadbackTier, + RunLedgerRowV1, + ) from openadapt_types.runner_capability import ( RUNNER_CAPABILITY_MANIFEST_SCHEMA, EffectVerificationTier, @@ -828,6 +847,23 @@ "certificate_state": "reward", "refuse_development_certification": "reward", "score": "reward", + "AGENT_RUN_SUMMARY_SCHEMA": "run_ledger", + "RUN_LEDGER_OUTCOME_PRECEDENCE": "run_ledger", + "RUN_LEDGER_REASON_OUTCOME": "run_ledger", + "RUN_LEDGER_SCHEMA": "run_ledger", + "AgentRunSummaryV1": "run_ledger", + "RunLedgerCostSource": "run_ledger", + "RunLedgerExecutorKind": "run_ledger", + "RunLedgerFieldCheck": "run_ledger", + "RunLedgerFieldV1": "run_ledger", + "RunLedgerHumanV1": "run_ledger", + "RunLedgerIntervalV1": "run_ledger", + "RunLedgerInterventionKind": "run_ledger", + "RunLedgerModelUsageV1": "run_ledger", + "RunLedgerOutcome": "run_ledger", + "RunLedgerOutcomeReason": "run_ledger", + "RunLedgerReadbackTier": "run_ledger", + "RunLedgerRowV1": "run_ledger", "RUNNER_CAPABILITY_MANIFEST_SCHEMA": "runner_capability", "EffectVerificationTier": "runner_capability", "ExecutionMode": "runner_capability", @@ -1273,6 +1309,24 @@ def __dir__() -> list[str]: "sign_human_decision_receipt_hmac", "sign_human_decision_task_hmac", "sign_human_decision_task_v2_hmac", + # run_ledger + "AGENT_RUN_SUMMARY_SCHEMA", + "RUN_LEDGER_OUTCOME_PRECEDENCE", + "RUN_LEDGER_REASON_OUTCOME", + "RUN_LEDGER_SCHEMA", + "AgentRunSummaryV1", + "RunLedgerCostSource", + "RunLedgerExecutorKind", + "RunLedgerFieldCheck", + "RunLedgerFieldV1", + "RunLedgerHumanV1", + "RunLedgerIntervalV1", + "RunLedgerInterventionKind", + "RunLedgerModelUsageV1", + "RunLedgerOutcome", + "RunLedgerOutcomeReason", + "RunLedgerReadbackTier", + "RunLedgerRowV1", # parsing "PARSE_ERROR_KEY", "from_benchmark_action", diff --git a/packages/types/openadapt_types/run_ledger.py b/packages/types/openadapt_types/run_ledger.py new file mode 100644 index 0000000000..70c102888f --- /dev/null +++ b/packages/types/openadapt_types/run_ledger.py @@ -0,0 +1,410 @@ +"""Per-run accounting rows that carry no record values. + +One :class:`RunLedgerRowV1` describes one run of one task, whatever did it: +an OpenAdapt agent, a compiled program, a third-party agent or a person. It +answers the questions an operations dashboard asks: did the case finish, was +the save checked, how long did it take, what did the model calls cost, and +how many minutes did a person spend on it. + +:class:`AgentRunSummaryV1` is the same row without ``sources`` (local paths), +the shape a runner sends to OpenAdapt Cloud. + +No values, by construction +-------------------------- +Every string field is a ``Literal``, an ``Enum`` member, or carries an +explicit ``pattern``, and every model forbids unknown fields. A field value, +an OCR string, a screenshot or operator prose has no field to travel in, and a +new field can't quietly open one: ``tests/test_run_ledger.py`` walks both JSON +Schemas and fails on any string that isn't closed. Values the person needs to +see (what was meant to be saved, what was saved, the difference) live only in +a local private sidecar the producer writes beside its store, never here. + +The outcome +----------- +``outcome`` is one of five buckets and ``outcome_reason`` is a closed code +that belongs to exactly one bucket (:data:`RUN_LEDGER_REASON_OUTCOME`); a row +whose reason names another bucket is refused. ``UNKNOWN`` is a bucket of its +own and is never folded into another. When a producer's sources disagree, the +stronger finding wins in this order (:data:`RUN_LEDGER_OUTCOME_PRECEDENCE`): +``CAUGHT_ERROR`` > ``UNKNOWN`` > ``ESCALATED`` > ``FAILED`` > ``VERIFIED``. + +Unknown is never zero +--------------------- +Model calls, tokens, cost and intervention time are ``null`` when a source +doesn't say, never ``0``. ``human.intervention_s`` is ``null`` whenever any +interval has no ``decided_at``, and with no intervals unless a source shows no +person was asked. +""" + +from __future__ import annotations + +from datetime import datetime +from enum import Enum +from typing import Annotated, Literal, Mapping, Optional + +from pydantic import ( + BaseModel, + ConfigDict, + Field, + StrictFloat, + StrictInt, + StrictStr, + model_validator, +) + +RUN_LEDGER_SCHEMA = "openadapt.run-ledger/v1" +AGENT_RUN_SUMMARY_SCHEMA = "openadapt.agent-run-summary/v1" + +_UUID_PATTERN = r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$" +#: An opaque task id, as the guard and the run store already use. +_TASK_ID_PATTERN = r"^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$" +#: An operator label: lower-case words, no spaces, no record identity. +_LABEL_PATTERN = r"^[a-z0-9][a-z0-9._-]{0,63}$" +#: A field name as a form or an API names it: an identifier, not a value. +_FIELD_NAME_PATTERN = r"^[A-Za-z_][A-Za-z0-9_.-]{0,63}$" +_SHA256_PATTERN = r"^sha256:[0-9a-f]{64}$" +_HEX64_PATTERN = r"^[0-9a-f]{64}$" +#: A path relative to the run directory: no leading slash, and no part that +#: starts with a dot (so no ``..``). +_SOURCE_PATTERN = r"^[A-Za-z0-9_-][A-Za-z0-9._-]*(/[A-Za-z0-9_-][A-Za-z0-9._-]*)*$" +_TIMESTAMP_PATTERN = ( + r"^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}(\.\d{1,6})?(Z|[+-]\d{2}:\d{2})$" +) + + +class RunLedgerOutcome(str, Enum): + """The five accounting buckets (``docs/RUN_LEDGER.md`` in openadapt-flow).""" + + #: An independent read-back verified the save and no hold is pending. + VERIFIED = "VERIFIED" + #: The run stopped for a person, a person declined it, or a person did + #: the step (a shadow run: the person's own save is the real one). + ESCALATED = "ESCALATED" + #: A check caught a wrong save: refuted read-back, blocked save, or a + #: shadow-mode field mismatch or wrong record. A person declining an + #: approval is not a catch on its own. + CAUGHT_ERROR = "CAUGHT_ERROR" + #: Crashed, timed out or gave up, with no evidence of a write. + FAILED = "FAILED" + #: Nothing settles it. Never folded into another bucket. + UNKNOWN = "UNKNOWN" + + +#: Strongest first. When sources disagree the earliest bucket wins. +RUN_LEDGER_OUTCOME_PRECEDENCE: tuple[RunLedgerOutcome, ...] = ( + RunLedgerOutcome.CAUGHT_ERROR, + RunLedgerOutcome.UNKNOWN, + RunLedgerOutcome.ESCALATED, + RunLedgerOutcome.FAILED, + RunLedgerOutcome.VERIFIED, +) + +RunLedgerOutcomeReason = Literal[ + # VERIFIED + "readback_verified", + # ESCALATED + "approval_held", + "person_declined", + "approval_declined", + "question_asked", + "exception_card", + "second_factor", + "halted_before_effect", + "gate_held", + "shadow_matched", + # P5: the approval card couldn't read the values back, so a person + # decides with what's on screen. + "values_unread", + # CAUGHT_ERROR + "readback_refuted", + "save_blocked_wrong_record", + "save_blocked_other_origin", + "save_blocked_double_save", + "save_blocked_out_of_scope", + "gate_refused", + "readback_field_differs", + "shadow_wrong_record", + "shadow_field_mismatch", + # FAILED + "crashed_no_write", + "timed_out_no_write", + "agent_gave_up", + "shadow_no_proposal", + "shadow_timed_out", + "platform_failed", + "canceled_no_write", + "policy_rejected_no_write", + # UNKNOWN + "shadow_write_landed", + "completed_unverified", + "shadow_not_compared", + "shadow_extra_target", + "shadow_agent_error", + "egress_refused", + "reconciliation_required", + "screen_readback_only", + "lost_reply", + "write_unconfirmed", + "saved_awaiting_check", + "rolled_back", + "self_approved", + "observe_only_would_block", + "schema_unrecognised", + "source_unreadable", + "task_id_conflict", + "unmapped_outcome", + "no_sources", +] + +_V = RunLedgerOutcome.VERIFIED +_E = RunLedgerOutcome.ESCALATED +_C = RunLedgerOutcome.CAUGHT_ERROR +_F = RunLedgerOutcome.FAILED +_U = RunLedgerOutcome.UNKNOWN + +#: The one bucket each reason belongs to. +RUN_LEDGER_REASON_OUTCOME: Mapping[str, RunLedgerOutcome] = { + "readback_verified": _V, + "approval_held": _E, + "person_declined": _E, + "approval_declined": _E, + "question_asked": _E, + "exception_card": _E, + "second_factor": _E, + "halted_before_effect": _E, + "gate_held": _E, + "shadow_matched": _E, + "values_unread": _E, + "readback_refuted": _C, + "save_blocked_wrong_record": _C, + "save_blocked_other_origin": _C, + "save_blocked_double_save": _C, + "save_blocked_out_of_scope": _C, + "gate_refused": _C, + "readback_field_differs": _C, + "shadow_wrong_record": _C, + "shadow_field_mismatch": _C, + "crashed_no_write": _F, + "timed_out_no_write": _F, + "agent_gave_up": _F, + "shadow_no_proposal": _F, + "shadow_timed_out": _F, + "platform_failed": _F, + "canceled_no_write": _F, + "policy_rejected_no_write": _F, + "shadow_write_landed": _U, + "completed_unverified": _U, + "shadow_not_compared": _U, + "shadow_extra_target": _U, + "shadow_agent_error": _U, + "egress_refused": _U, + "reconciliation_required": _U, + "screen_readback_only": _U, + "lost_reply": _U, + "write_unconfirmed": _U, + "saved_awaiting_check": _U, + "rolled_back": _U, + "self_approved": _U, + "observe_only_would_block": _U, + "schema_unrecognised": _U, + "source_unreadable": _U, + "task_id_conflict": _U, + "unmapped_outcome": _U, + "no_sources": _U, +} + +RunLedgerExecutorKind = Literal["agent", "program", "human", "unknown"] +RunLedgerCostSource = Literal["metered", "reported", "unknown"] +RunLedgerInterventionKind = Literal[ + "approval", "question", "exception", "second_factor" +] +RunLedgerFieldCheck = Literal["matched", "differs", "not_checked"] +RunLedgerReadbackTier = Literal["independent_readback", "screen_readback", "unchecked"] + +Count = StrictInt +_Source = Annotated[StrictStr, Field(pattern=_SOURCE_PATTERN, max_length=256)] + + +class _Strict(BaseModel): + model_config = ConfigDict(extra="forbid", frozen=True) + + +def _parse(stamp: str) -> datetime: + return datetime.fromisoformat(stamp.replace("Z", "+00:00")) + + +class RunLedgerModelUsageV1(_Strict): + """What the run's model calls cost. ``null`` means the source didn't say.""" + + calls: Optional[Count] = Field(default=None, ge=0) + input_tokens: Optional[Count] = Field(default=None, ge=0) + output_tokens: Optional[Count] = Field(default=None, ge=0) + cost_usd: Optional[StrictFloat] = Field(default=None, ge=0.0, le=1_000_000.0) + cost_source: RunLedgerCostSource = "unknown" + + @model_validator(mode="after") + def _source_matches_cost(self) -> "RunLedgerModelUsageV1": + if self.cost_usd is None and self.cost_source != "unknown": + raise ValueError("a null cost_usd has cost_source unknown") + if self.cost_usd is not None and self.cost_source == "unknown": + raise ValueError("a known cost_usd names its cost_source") + return self + + +class RunLedgerIntervalV1(_Strict): + """One stretch a person spent on the run: opened, then decided.""" + + kind: RunLedgerInterventionKind + opened_at: StrictStr = Field(pattern=_TIMESTAMP_PATTERN, max_length=40) + decided_at: Optional[StrictStr] = Field( + default=None, pattern=_TIMESTAMP_PATTERN, max_length=40 + ) + + @model_validator(mode="after") + def _ordered(self) -> "RunLedgerIntervalV1": + if self.decided_at is not None and _parse(self.decided_at) < _parse( + self.opened_at + ): + raise ValueError("decided_at is before opened_at") + return self + + def seconds(self) -> Optional[float]: + if self.decided_at is None: + return None + return (_parse(self.decided_at) - _parse(self.opened_at)).total_seconds() + + +class RunLedgerHumanV1(_Strict): + """A person's time on the run. ``intervention_s`` is the sum of the + intervals, and ``null`` when any interval is still open (never ``0``). + With no intervals it is ``0`` only when a source shows no person was + asked, else ``null`` (unknown).""" + + intervention_s: Optional[StrictFloat] = Field(default=None, ge=0.0) + intervals: tuple[RunLedgerIntervalV1, ...] = () + + @model_validator(mode="after") + def _sum(self) -> "RunLedgerHumanV1": + if not self.intervals: + if self.intervention_s not in (None, 0.0): + raise ValueError("intervention_s is the sum of the intervals") + return self + spans = [interval.seconds() for interval in self.intervals] + if any(span is None for span in spans): + if self.intervention_s is not None: + raise ValueError("an open interval makes intervention_s null") + return self + total = round(sum(span for span in spans if span is not None), 3) + if self.intervention_s is None or abs(self.intervention_s - total) > 0.002: + raise ValueError("intervention_s is the sum of the intervals") + return self + + +class RunLedgerFieldV1(_Strict): + """A field the run wrote: its name and how its check came out. No value.""" + + name: StrictStr = Field(pattern=_FIELD_NAME_PATTERN) + check: RunLedgerFieldCheck + + +class _RowBody(_Strict): + row_id: StrictStr = Field(pattern=_UUID_PATTERN) + task_id: StrictStr = Field(pattern=_TASK_ID_PATTERN) + task_type: StrictStr = Field(pattern=_LABEL_PATTERN) + executor_kind: RunLedgerExecutorKind + executor_label: StrictStr = Field(pattern=_LABEL_PATTERN) + #: ``sha256:`` of the salted inputs; the salt is in the private sidecar. + #: ``null`` when no source names the run's inputs. + inputs_commitment: Optional[StrictStr] = Field( + default=None, pattern=_SHA256_PATTERN + ) + started_at: Optional[StrictStr] = Field( + default=None, pattern=_TIMESTAMP_PATTERN, max_length=40 + ) + ended_at: Optional[StrictStr] = Field( + default=None, pattern=_TIMESTAMP_PATTERN, max_length=40 + ) + duration_s: Optional[StrictFloat] = Field(default=None, ge=0.0) + model: RunLedgerModelUsageV1 = Field(default_factory=RunLedgerModelUsageV1) + human: RunLedgerHumanV1 = Field(default_factory=RunLedgerHumanV1) + outcome: RunLedgerOutcome + outcome_reason: RunLedgerOutcomeReason + fields_written: tuple[RunLedgerFieldV1, ...] = () + fields_differing: Count = Field(default=0, ge=0) + readback_tier: Optional[RunLedgerReadbackTier] = None + receipt_digest: Optional[StrictStr] = Field(default=None, pattern=_HEX64_PATTERN) + + @model_validator(mode="after") + def _consistent(self) -> "_RowBody": + if RUN_LEDGER_REASON_OUTCOME[self.outcome_reason] is not self.outcome: + raise ValueError( + f"outcome_reason {self.outcome_reason} is not a {self.outcome.value} reason" + ) + if self.outcome is RunLedgerOutcome.VERIFIED and ( + self.readback_tier != "independent_readback" + ): + raise ValueError("VERIFIED needs an independent read-back") + if self.outcome is RunLedgerOutcome.VERIFIED and self.fields_differing: + raise ValueError("VERIFIED can't have a field that differs") + if self.started_at is not None and self.ended_at is not None: + if _parse(self.ended_at) < _parse(self.started_at): + raise ValueError("ended_at is before started_at") + differing = sum(1 for f in self.fields_written if f.check == "differs") + if self.fields_differing < differing: + raise ValueError("fields_differing counts every field that differs") + return self + + +class RunLedgerRowV1(_RowBody): + """One run, value-free. Local: ``sources`` names the files it came from.""" + + schema_: Literal["openadapt.run-ledger/v1"] = Field( + default=RUN_LEDGER_SCHEMA, alias="schema" + ) + sources: tuple[_Source, ...] = Field(default=(), max_length=256) + + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + def to_json(self) -> dict[str, object]: + return self.model_dump(mode="json", by_alias=True) + + def summary(self) -> "AgentRunSummaryV1": + """The Cloud shape: this row without ``sources``.""" + + body = self.model_dump(mode="json", by_alias=True, exclude={"sources"}) + body["schema"] = AGENT_RUN_SUMMARY_SCHEMA + return AgentRunSummaryV1.model_validate(body) + + +class AgentRunSummaryV1(_RowBody): + """What ``openadapt-flow ledger push`` sends: the row minus ``sources``.""" + + schema_: Literal["openadapt.agent-run-summary/v1"] = Field( + default=AGENT_RUN_SUMMARY_SCHEMA, alias="schema" + ) + + model_config = ConfigDict(extra="forbid", frozen=True, populate_by_name=True) + + def to_json(self) -> dict[str, object]: + return self.model_dump(mode="json", by_alias=True) + + +__all__ = [ + "AGENT_RUN_SUMMARY_SCHEMA", + "RUN_LEDGER_OUTCOME_PRECEDENCE", + "RUN_LEDGER_REASON_OUTCOME", + "RUN_LEDGER_SCHEMA", + "AgentRunSummaryV1", + "RunLedgerCostSource", + "RunLedgerExecutorKind", + "RunLedgerFieldCheck", + "RunLedgerFieldV1", + "RunLedgerHumanV1", + "RunLedgerIntervalV1", + "RunLedgerInterventionKind", + "RunLedgerModelUsageV1", + "RunLedgerOutcome", + "RunLedgerOutcomeReason", + "RunLedgerReadbackTier", + "RunLedgerRowV1", +] diff --git a/packages/types/openadapt_types/vocabulary/outcomes.json b/packages/types/openadapt_types/vocabulary/outcomes.json index 15ce4758e5..e68c4be2b5 100644 --- a/packages/types/openadapt_types/vocabulary/outcomes.json +++ b/packages/types/openadapt_types/vocabulary/outcomes.json @@ -108,6 +108,10 @@ } ], "not_run_outcomes": [ + { + "symbol": "openadapt_types/run_ledger.py RunLedgerOutcome (verified, escalated, caught_error, failed, unknown)", + "reason": "An accounting bucket that openadapt_flow/run_ledger/outcome.py derives from the run's own outcome and evidence. It sums runs for a ledger and never replaces the run's outcome." + }, { "symbol": "openadapt_flow/runtime/effects/effect.py Verdict (confirmed, refuted, indeterminate)", "reason": "One effect check inside a step. The run's outcome already accounts for it." diff --git a/packages/types/tests/fixtures/agent_run_summary_v1_examples.jsonl b/packages/types/tests/fixtures/agent_run_summary_v1_examples.jsonl new file mode 100644 index 0000000000..5341505b54 --- /dev/null +++ b/packages/types/tests/fixtures/agent_run_summary_v1_examples.jsonl @@ -0,0 +1,14 @@ +{"duration_s": 2.016, "ended_at": "2026-11-22T06:01:25.259000Z", "executor_kind": "agent", "executor_label": "readiness-shadow", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": 0.0}, "inputs_commitment": null, "model": {"calls": 0, "cost_source": "metered", "cost_usd": 0.0, "input_tokens": 0, "output_tokens": 0}, "outcome": "ESCALATED", "outcome_reason": "shadow_matched", "readback_tier": null, "receipt_digest": null, "row_id": "69b513f0-6907-4e76-82f6-eb24ed41c70d", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T06:01:23.243000Z", "task_id": "readiness-mockmed-0000", "task_type": "intake"} +{"duration_s": 2.068, "ended_at": "2026-11-22T03:56:35.377000Z", "executor_kind": "agent", "executor_label": "readiness-shadow", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": 0.0}, "inputs_commitment": null, "model": {"calls": 0, "cost_source": "metered", "cost_usd": 0.0, "input_tokens": 0, "output_tokens": 0}, "outcome": "CAUGHT_ERROR", "outcome_reason": "shadow_field_mismatch", "readback_tier": null, "receipt_digest": null, "row_id": "63561428-67a3-4908-a657-a65ad6fc9e5f", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T03:56:33.309000Z", "task_id": "readiness-mockmed-0001", "task_type": "intake"} +{"duration_s": 0.711, "ended_at": "2026-11-22T06:02:36.467000Z", "executor_kind": "agent", "executor_label": "readiness-shadow", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": 0.0}, "inputs_commitment": null, "model": {"calls": 0, "cost_source": "metered", "cost_usd": 0.0, "input_tokens": 0, "output_tokens": 0}, "outcome": "UNKNOWN", "outcome_reason": "shadow_extra_target", "readback_tier": null, "receipt_digest": null, "row_id": "9e9cfbda-817c-4217-ab2e-77aaacdc1473", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T06:02:35.756000Z", "task_id": "readiness-mockmed-0000", "task_type": "intake"} +{"duration_s": 2.042, "ended_at": "2026-11-22T02:04:48.863000Z", "executor_kind": "agent", "executor_label": "claude-sonnet-5-5", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": 0.0}, "inputs_commitment": null, "model": {"calls": 6, "cost_source": "reported", "cost_usd": 0.03, "input_tokens": 12000, "output_tokens": 600}, "outcome": "CAUGHT_ERROR", "outcome_reason": "shadow_wrong_record", "readback_tier": null, "receipt_digest": null, "row_id": "6c59332c-9bd1-4a43-9ad2-e59f1d0c7a82", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T02:04:46.821000Z", "task_id": "readiness-mockmed-0016", "task_type": "intake"} +{"duration_s": 7.603, "ended_at": "2026-11-22T05:11:03.073000Z", "executor_kind": "agent", "executor_label": "claude-sonnet-5-5", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": 0.0}, "inputs_commitment": null, "model": {"calls": 2, "cost_source": "metered", "cost_usd": 0.023775, "input_tokens": 13696, "output_tokens": 355}, "outcome": "FAILED", "outcome_reason": "shadow_no_proposal", "readback_tier": null, "receipt_digest": null, "row_id": "a2ef34a5-3f3d-4f57-8d10-0dcfa8e855f7", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:10:55.470000Z", "task_id": "readiness-mockmed-0000", "task_type": "intake"} +{"duration_s": 7.715, "ended_at": "2026-11-22T05:02:13.621233Z", "executor_kind": "agent", "executor_label": "agent-guard", "fields_differing": 0, "fields_written": [{"check": "matched", "name": "note"}, {"check": "matched", "name": "type"}], "human": {"intervals": [{"decided_at": "2026-11-22T05:02:12.089101Z", "kind": "approval", "opened_at": "2026-11-22T05:02:08.735233Z"}], "intervention_s": 3.354}, "inputs_commitment": null, "model": {"calls": null, "cost_source": "unknown", "cost_usd": null, "input_tokens": null, "output_tokens": null}, "outcome": "VERIFIED", "outcome_reason": "readback_verified", "readback_tier": "independent_readback", "receipt_digest": null, "row_id": "2774e5ba-e774-4ad4-bea2-89ecce823f94", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:02:05.906233Z", "task_id": "prod-approve-correct", "task_type": "intake"} +{"duration_s": 5.893, "ended_at": "2026-11-22T05:56:48.946948Z", "executor_kind": "agent", "executor_label": "agent-guard", "fields_differing": 0, "fields_written": [], "human": {"intervals": [{"decided_at": "2026-11-22T05:56:48.940317Z", "kind": "approval", "opened_at": "2026-11-22T05:56:45.748948Z"}], "intervention_s": 3.191}, "inputs_commitment": null, "model": {"calls": null, "cost_source": "unknown", "cost_usd": null, "input_tokens": null, "output_tokens": null}, "outcome": "ESCALATED", "outcome_reason": "person_declined", "readback_tier": null, "receipt_digest": null, "row_id": "9088175a-00b4-4393-8213-20495b4169f1", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:56:43.053948Z", "task_id": "prod-decline", "task_type": "intake"} +{"duration_s": 11.109, "ended_at": "2026-11-22T05:57:56.063003Z", "executor_kind": "agent", "executor_label": "agent-guard", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": 0.0}, "inputs_commitment": null, "model": {"calls": null, "cost_source": "unknown", "cost_usd": null, "input_tokens": null, "output_tokens": null}, "outcome": "CAUGHT_ERROR", "outcome_reason": "save_blocked_out_of_scope", "readback_tier": null, "receipt_digest": null, "row_id": "9caa1eac-b58f-42e2-afb3-de27fc9e1f65", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:57:44.954003Z", "task_id": "prod-wrong-patient", "task_type": "intake"} +{"duration_s": 5.396, "ended_at": "2026-11-22T02:08:31.000000Z", "executor_kind": "agent", "executor_label": "agent-guard", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": 0.0}, "inputs_commitment": null, "model": {"calls": null, "cost_source": "unknown", "cost_usd": null, "input_tokens": null, "output_tokens": null}, "outcome": "UNKNOWN", "outcome_reason": "reconciliation_required", "readback_tier": "independent_readback", "receipt_digest": null, "row_id": "e9f94668-399f-48c3-9e46-b2cfd4a00ec0", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T02:08:25.604000Z", "task_id": "prod-no-persist-00", "task_type": "intake"} +{"duration_s": 5.268, "ended_at": "2026-11-22T05:58:32.000000Z", "executor_kind": "agent", "executor_label": "agent-guard", "fields_differing": 0, "fields_written": [{"check": "matched", "name": "note"}, {"check": "matched", "name": "type"}], "human": {"intervals": [{"decided_at": "2026-11-22T05:58:31.040161Z", "kind": "second_factor", "opened_at": "2026-11-22T05:58:30.981124Z"}], "intervention_s": 0.059}, "inputs_commitment": null, "model": {"calls": null, "cost_source": "unknown", "cost_usd": null, "input_tokens": null, "output_tokens": null}, "outcome": "VERIFIED", "outcome_reason": "readback_verified", "readback_tier": "independent_readback", "receipt_digest": null, "row_id": "5530bd6d-89b5-4a3b-afc3-7fc996fff338", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:58:26.732000Z", "task_id": "triage-p1-0001", "task_type": "intake"} +{"duration_s": 23.113, "ended_at": "2026-11-22T05:59:26.881194Z", "executor_kind": "agent", "executor_label": "openadapt-wrap", "fields_differing": 0, "fields_written": [{"check": "matched", "name": "note"}, {"check": "matched", "name": "patient_id"}, {"check": "matched", "name": "type"}], "human": {"intervals": [{"decided_at": "2026-11-22T05:59:18.267535Z", "kind": "approval", "opened_at": "2026-11-22T05:59:18.224747Z"}], "intervention_s": 0.043}, "inputs_commitment": null, "model": {"calls": 0, "cost_source": "reported", "cost_usd": 0.0, "input_tokens": null, "output_tokens": null}, "outcome": "VERIFIED", "outcome_reason": "readback_verified", "readback_tier": "independent_readback", "receipt_digest": null, "row_id": "f85bfe7b-68dd-42e2-958a-46ebec3117ed", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:59:03.767943Z", "task_id": "dispatch-drift-approved", "task_type": "intake"} +{"duration_s": 5.719, "ended_at": "2026-11-22T05:59:32.625922Z", "executor_kind": "agent", "executor_label": "openadapt-wrap", "fields_differing": 0, "fields_written": [], "human": {"intervals": [{"decided_at": "2026-11-22T05:59:30.534373Z", "kind": "approval", "opened_at": "2026-11-22T05:59:30.432599Z"}], "intervention_s": 0.102}, "inputs_commitment": null, "model": {"calls": 0, "cost_source": "reported", "cost_usd": 0.0, "input_tokens": null, "output_tokens": null}, "outcome": "ESCALATED", "outcome_reason": "person_declined", "readback_tier": null, "receipt_digest": null, "row_id": "2487c82f-4537-4cd7-9607-87f3862c5291", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:59:26.907180Z", "task_id": "dispatch-drift-declined", "task_type": "intake"} +{"duration_s": 5.749, "ended_at": "2026-11-22T05:59:03.729566Z", "executor_kind": "program", "executor_label": "openadapt-wrap", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": null}, "inputs_commitment": null, "model": {"calls": 0, "cost_source": "reported", "cost_usd": 0.0, "input_tokens": null, "output_tokens": null}, "outcome": "VERIFIED", "outcome_reason": "readback_verified", "readback_tier": "independent_readback", "receipt_digest": null, "row_id": "6f5222fc-94e8-4e23-9ea6-e3e945af26f4", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T05:58:57.980630Z", "task_id": "dispatch-happy", "task_type": "intake"} +{"duration_s": null, "ended_at": "2026-11-22T02:36:30.000000Z", "executor_kind": "program", "executor_label": "unlabelled", "fields_differing": 0, "fields_written": [], "human": {"intervals": [], "intervention_s": null}, "inputs_commitment": null, "model": {"calls": null, "cost_source": "unknown", "cost_usd": null, "input_tokens": null, "output_tokens": null}, "outcome": "ESCALATED", "outcome_reason": "halted_before_effect", "readback_tier": "independent_readback", "receipt_digest": null, "row_id": "2b62a5be-7110-464d-b5ef-50ead1034d38", "schema": "openadapt.agent-run-summary/v1", "started_at": "2026-11-22T02:36:16.000000Z", "task_id": "run-7eaa419f42bfdc9a", "task_type": "intake"} diff --git a/packages/types/tests/test_run_ledger.py b/packages/types/tests/test_run_ledger.py new file mode 100644 index 0000000000..4ea4abb8bd --- /dev/null +++ b/packages/types/tests/test_run_ledger.py @@ -0,0 +1,211 @@ +"""The run-ledger row is closed, value-free, and self-consistent.""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any, get_args + +import pytest +from pydantic import ValidationError + +from openadapt_types.run_ledger import ( + AGENT_RUN_SUMMARY_SCHEMA, + RUN_LEDGER_OUTCOME_PRECEDENCE, + RUN_LEDGER_REASON_OUTCOME, + RUN_LEDGER_SCHEMA, + AgentRunSummaryV1, + RunLedgerHumanV1, + RunLedgerIntervalV1, + RunLedgerModelUsageV1, + RunLedgerOutcome, + RunLedgerOutcomeReason, + RunLedgerRowV1, +) + +ROW_ID = "0b6f3f9e-6a43-4c63-9f6e-1d2a3b4c5d6e" + + +def _row(**overrides: Any) -> RunLedgerRowV1: + body: dict[str, Any] = { + "row_id": ROW_ID, + "task_id": "task-0001", + "task_type": "intake", + "executor_kind": "agent", + "executor_label": "browser-use", + "outcome": "VERIFIED", + "outcome_reason": "readback_verified", + "readback_tier": "independent_readback", + "sources": ["summary.json"], + } + body.update(overrides) + return RunLedgerRowV1.model_validate(body) + + +def _strings(schema: dict[str, Any], defs: dict[str, Any], path: str = "") -> list[str]: + """Every string-typed node with no pattern, const or enum.""" + + open_: list[str] = [] + if "$ref" in schema: + name = schema["$ref"].split("/")[-1] + return _strings(defs[name], defs, path + "->" + name) + if schema.get("type") == "string" and not ( + "pattern" in schema or "const" in schema or "enum" in schema + ): + open_.append(path or "") + for key in ("anyOf", "allOf", "oneOf", "prefixItems"): + for i, sub in enumerate(schema.get(key, [])): + open_ += _strings(sub, defs, f"{path}[{key}{i}]") + if isinstance(schema.get("items"), dict): + open_ += _strings(schema["items"], defs, path + "[]") + for name, sub in (schema.get("properties") or {}).items(): + open_ += _strings(sub, defs, f"{path}.{name}") + return open_ + + +@pytest.mark.parametrize("model", [RunLedgerRowV1, AgentRunSummaryV1]) +def test_no_string_field_accepts_free_text(model: Any) -> None: + schema = model.model_json_schema(by_alias=True) + assert _strings(schema, schema.get("$defs", {})) == [] + + +def test_every_reason_names_exactly_one_bucket() -> None: + assert set(get_args(RunLedgerOutcomeReason)) == set(RUN_LEDGER_REASON_OUTCOME) + for outcome in RunLedgerOutcome: + assert outcome in RUN_LEDGER_REASON_OUTCOME.values(), outcome + assert RUN_LEDGER_OUTCOME_PRECEDENCE == ( + RunLedgerOutcome.CAUGHT_ERROR, + RunLedgerOutcome.UNKNOWN, + RunLedgerOutcome.ESCALATED, + RunLedgerOutcome.FAILED, + RunLedgerOutcome.VERIFIED, + ) + + +def test_a_reason_from_another_bucket_is_refused() -> None: + with pytest.raises(ValidationError, match="not a VERIFIED reason"): + _row(outcome_reason="readback_refuted") + + +def test_verified_needs_an_independent_readback() -> None: + with pytest.raises(ValidationError, match="independent"): + _row(readback_tier="screen_readback") + with pytest.raises(ValidationError, match="independent"): + _row(readback_tier=None) + + +def test_unknown_time_is_null_never_zero() -> None: + open_interval = RunLedgerIntervalV1( + kind="approval", opened_at="2026-11-20T10:00:00Z" + ) + with pytest.raises(ValidationError, match="null"): + RunLedgerHumanV1(intervention_s=0.0, intervals=(open_interval,)) + human = RunLedgerHumanV1(intervention_s=None, intervals=(open_interval,)) + assert human.intervention_s is None + closed = RunLedgerIntervalV1( + kind="question", + opened_at="2026-11-20T10:00:00Z", + decided_at="2026-11-20T10:01:30Z", + ) + assert ( + RunLedgerHumanV1(intervention_s=90.0, intervals=(closed,)).intervention_s + == 90.0 + ) + with pytest.raises(ValidationError, match="sum"): + RunLedgerHumanV1(intervention_s=10.0, intervals=(closed,)) + with pytest.raises(ValidationError, match="before"): + RunLedgerIntervalV1( + kind="question", + opened_at="2026-11-20T10:01:00Z", + decided_at="2026-11-20T10:00:00Z", + ) + + +def test_cost_source_matches_cost() -> None: + assert RunLedgerModelUsageV1().cost_source == "unknown" + with pytest.raises(ValidationError): + RunLedgerModelUsageV1(cost_usd=0.1) + with pytest.raises(ValidationError): + RunLedgerModelUsageV1(cost_source="metered") + usage = RunLedgerModelUsageV1(calls=3, cost_usd=0.12, cost_source="metered") + assert usage.input_tokens is None # unknown, not zero + + +@pytest.mark.parametrize( + ("field", "value"), + [ + ("task_type", "Patient Jane Doe"), + ("executor_label", "agent with spaces"), + ("task_id", "has space"), + ("sources", ["/etc/passwd"]), + ("sources", ["../outside.json"]), + ("fields_written", [{"name": "note value!", "check": "matched"}]), + ("unknown_key", "x"), + ], +) +def test_values_have_no_field_to_travel_in(field: str, value: Any) -> None: + with pytest.raises(ValidationError): + _row(**{field: value}) + + +def test_summary_is_the_row_minus_sources() -> None: + row = _row() + assert row.to_json()["schema"] == RUN_LEDGER_SCHEMA + summary = row.summary().to_json() + assert summary["schema"] == AGENT_RUN_SUMMARY_SCHEMA + assert "sources" not in summary + assert { + k: v for k, v in row.to_json().items() if k not in ("schema", "sources") + } == {k: v for k, v in summary.items() if k != "schema"} + with pytest.raises(ValidationError): + AgentRunSummaryV1.model_validate(dict(summary, sources=["a.json"])) + + +def test_fields_differing_counts_every_differing_field() -> None: + with pytest.raises(ValidationError, match="fields_differing"): + _row( + outcome="CAUGHT_ERROR", + outcome_reason="shadow_field_mismatch", + fields_written=[{"name": "note", "check": "differs"}], + fields_differing=0, + ) + + +# -- J6: the push payload Cloud ingests ------------------------------------------------ + +#: Real ``openadapt-flow ledger push --dry-run`` output over synthetic runs +#: (shadow, guarded, declined, not-saved, refused fallback, halted program). +#: The Cloud dashboard (openadapt-cloud#551) copies this file as its fixture. +J6_EXAMPLES = Path(__file__).parent / "fixtures" / "agent_run_summary_v1_examples.jsonl" + + +def test_the_j6_examples_validate_against_the_model_and_its_json_schema() -> None: + jsonschema = pytest.importorskip("jsonschema") + schema = AgentRunSummaryV1.model_json_schema(by_alias=True) + validator = jsonschema.Draft202012Validator(schema) + lines = J6_EXAMPLES.read_text(encoding="utf-8").splitlines() + assert lines + nulls = 0 + for line in lines: + payload = json.loads(line) + validator.validate(payload) + AgentRunSummaryV1.model_validate(payload) + assert payload["schema"] == "openadapt.agent-run-summary/v1" + assert "sources" not in payload + nulls += payload["model"]["calls"] is None + # Unknown values travel as null. + assert nulls >= 1 + + +def test_no_intervals_is_zero_or_unknown_never_another_number() -> None: + from openadapt_types.run_ledger import RunLedgerHumanV1 + + assert RunLedgerHumanV1().intervention_s is None + assert RunLedgerHumanV1(intervention_s=0.0).intervention_s == 0.0 + with pytest.raises(ValidationError): + RunLedgerHumanV1(intervention_s=5.0) + + +def test_verified_with_a_differing_field_is_refused() -> None: + with pytest.raises(ValidationError, match="differs"): + _row(fields_differing=1)