diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 462d157c9d..315271d5d2 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -213,6 +213,7 @@ improvising or retrying when something is off. | Person-signed grants let named agents or systems answer saves | Released | Unit tests | `openadapt-flow approver-grant` | | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | +| Answer exception cards from any run on this computer in Desktop's stop queue and on a paired phone: each card (a one-time code prompt, an unexpected dialog, a sign-in partway through, a stall, a possible duplicate, an ambiguous record, a task it can't finish) offers only the run's own closed choices, is answered one at a time, and the answer is signed with the stop queue's approver key. Desktop reads only card files that are regular, owned by this user and readable by no one else, and lists at most 200. The cards come from Flow's exception registry ([#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494)); the Flow 2.4.1 that Desktop runs has none, so cards appear only from runs of a newer Flow | In PR [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492) (openadapt-desktop 0.31.0) | Unit tests with Flow's card fixture and answer contract; synthetic | openadapt-desktop `exception_queue.py`, `stop_queue.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | ## Branching work, not one linear path @@ -326,7 +327,7 @@ improvising or retrying when something is off. | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | -| Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](packages/flow/docs/GUARD_AN_AGENT.md) | +| Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks. The approval card shows each field's value now, the value the held save sends (read by the app's `write_adapter`; without one the card says the values were not read and not checked before saving, and shows a screenshot and the form's values on screen taken when the save is held; with neither a value nor a readable screenshot no approval is offered and the run ends `ESCALATED` `values_unread`), the task's value beside it and its source; each save gets a ledger row with no values whose outcome follows the guard's own verdict, and a 0600 diff; the read-back goes through a `ReadbackProvider` where only an independent read can verify | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)); card values, ledger row and `ReadbackProvider` in PR [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults; the approval card in headless Chromium with and without MockMed's write adapter) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](packages/flow/docs/GUARD_AN_AGENT.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, PR [#2411](https://github.com/OpenAdaptAI/OpenAdapt/pull/2411) | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command; one run of live headless Claude Code 2.1.305 and Codex CLI 0.144.4 sessions, both against a local SQLite file and HTTP API: declared writes VERIFIED, an out-of-scope delete blocked, a broken read-back UNCERTAIN, and a Python write that builds the path at run time not seen, [hooks_live](packages/flow/benchmark/hooks_live/README.md)) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](packages/flow/docs/HOOKS.md) | | Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-12 s from empty venv to first diff; one real MCP SDK session; one live headless Claude Code session (held, then applied and undone) | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](packages/flow/docs/TRANSACTIONS.md) | | Dry-run, apply, undo and release a batch of writes to external systems: `openadapt plan create/approve/apply/undo/release/cancel` over an `openadapt.tx.yaml` of REST collections, SQL tables and mail. The diff comes from a staged transaction (SQL), a computed shadow with declared server-set and derived fields (REST) or the holdback queue (email). Approval is single-use and bound to the plan digest, a stale plan is refused, each write's idempotency key comes from the task and the record slot (never the payload), and a retry with a different payload is refused (the ACRFence action-replay attack). The undo is verified by reading back each record and the whole frame. Irreversible writes wait in a cancelable holdback queue | Experimental, this PR | Lab: Vikunja 2.7.1, Dolibarr 21.0.4 on MariaDB, Mailpit; 100 writes each; 0 missed effects, 0 false diffs, 200/200 verified undos (REST, SQL), 50/50 cancelled emails never sent, 50/50 released exactly once, 0/60 regenerated retries through (control 60/60 doubled), 0/10 after a crash after send; seeded faults caught 20/20 | `openadapt plan`, `openadapt_flow/txplan/`, [TRANSACTIONS.md](packages/flow/docs/TRANSACTIONS.md) | @@ -492,7 +493,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** -- `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. +- `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, writes a ledger row and a private diff, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. diff --git a/llms-full.txt b/llms-full.txt index 5d3446e884..955ca9703d 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -673,6 +673,7 @@ improvising or retrying when something is off. | Person-signed grants let named agents or systems answer saves | Released | Unit tests | `openadapt-flow approver-grant` | | Admit once, then stop only on problems | Released ([#1212](https://github.com/OpenAdaptAI/OpenAdapt/pull/1212)), behind a readiness gate | Synthetic | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md) | | Show the field values a save writes on the phone | Released ([#1257](https://github.com/OpenAdaptAI/OpenAdapt/pull/1257)) | Unit tests | `console/save_approvals.py` | +| Answer exception cards from any run on this computer in Desktop's stop queue and on a paired phone: each card (a one-time code prompt, an unexpected dialog, a sign-in partway through, a stall, a possible duplicate, an ambiguous record, a task it can't finish) offers only the run's own closed choices, is answered one at a time, and the answer is signed with the stop queue's approver key. Desktop reads only card files that are regular, owned by this user and readable by no one else, and lists at most 200. The cards come from Flow's exception registry ([#2494](https://github.com/OpenAdaptAI/OpenAdapt/pull/2494)); the Flow 2.4.1 that Desktop runs has none, so cards appear only from runs of a newer Flow | In PR [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492) (openadapt-desktop 0.31.0) | Unit tests with Flow's card fixture and answer contract; synthetic | openadapt-desktop `exception_queue.py`, `stop_queue.py` | | Show why an agent asked for a save: who asked, its own reason (as a quote), the screen text it saw, and any of that text that reads like an instruction to an agent | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359)) | Unit tests, synthetic | `ApprovalProvenance` in `approval_mode/item_approval.py`; the phone card in openadapt-desktop `portal/shell` | ## Branching work, not one linear path @@ -786,7 +787,7 @@ improvising or retrying when something is off. | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | -| Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | +| Guard an agent you already run: attach to its own Chromium over CDP (one added line), hold each save until the record on screen is the one the task names, block it and tell the agent why when it isn't, read the save back; a run that reads back correctly becomes a draft program with a record check from scaffold-verifier, which a person confirms and admits, then a `taught_*` tool with no model calls. `--observe-only` never blocks. The approval card shows each field's value now, the value the held save sends (read by the app's `write_adapter`; without one the card says the values were not read and not checked before saving, and shows a screenshot and the form's values on screen taken when the save is held; with neither a value nor a readable screenshot no approval is offered and the run ends `ESCALATED` `values_unread`), the task's value beside it and its source; each save gets a ledger row with no values whose outcome follows the guard's own verdict, and a 0600 diff; the read-back goes through a `ReadbackProvider` where only an independent read can verify | Released ([#1357](https://github.com/OpenAdaptAI/OpenAdapt/pull/1357), stacked on [#1335](https://github.com/OpenAdaptAI/OpenAdapt/pull/1335)); card values, ledger row and `ReadbackProvider` in PR [#2492](https://github.com/OpenAdaptAI/OpenAdapt/pull/2492) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults; the approval card in headless Chromium with and without MockMed's write adapter) | `openadapt-flow guard`, [GUARD_AN_AGENT.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/GUARD_AN_AGENT.md) | | Check a coding agent's writes to declared systems of record: `openadapt hooks install --agent claude-code` (or `codex`) writes project-local hooks (Claude Code `PreToolUse`/`PostToolUse`/`PostToolUseFailure`/`Stop`, Codex `PreToolUse`/`PostToolUse`/`Stop`). For a call that writes to a database, HTTP API or MCP tool declared in `openadapt.systems.yaml`, the pre-check allows, asks or blocks it by the write's approval mode (Codex can't ask from a hook, so `ask` is a deny until `openadapt hooks approve`); an undeclared write to a declared system is blocked or asked about; the read-back uses the verifier's contract (`openadapt.verify/v1`), a failed read-back is `UNCERTAIN` and the same call is then held; every outcome gets a signed `record/run/v1` receipt. Advisory: hooks see tool calls, so an agent with its own credentials and shell can bypass them; `--strict` (credential broker) is refused until a broker exists for these systems | Experimental, PR [#2411](https://github.com/OpenAdaptAI/OpenAdapt/pull/2411) | Synthetic (a scripted harness sends each agent's documented hook input to the installed hook command; one run of live headless Claude Code 2.1.305 and Codex CLI 0.144.4 sessions, both against a local SQLite file and HTTP API: declared writes VERIFIED, an out-of-scope delete blocked, a broken read-back UNCERTAIN, and a Python write that builds the path at run time not seen, [hooks_live](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/hooks_live/README.md)) | `openadapt hooks`, `openadapt_flow/hooks/`, [HOOKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/HOOKS.md) | | Hold the database credentials and give the agent scoped tools: `openadapt proxy --postgres URL -- claude` (or `--sqlite`) serves an MCP endpoint on loopback with a per-run token and takes the credentials out of the agent's environment. Each SQL write is dry-run in a rolled-back transaction with its exact row-level diff (triggers and cascades included), approved by policy (`--auto-approve-max-rows`) or by a person (`y`, `openadapt plan approve`) against the plan digest, used once, committed only if its diff matches the plan, read back, and undone from its row images with a read-back proof. A regenerated statement over rows already written in the task is held for a person (`possible_replay`). Each stage gets a signed `record/run/v1` receipt with the approval block. The dry run covers effects inside the database only | Experimental, this PR | Lab: PostgreSQL 16, 120 statements of 8 kinds, 0 missed effects, 0 false diffs, 120/120 verified undos, 0/20 regenerated statements applied (control 20/20 doubled), the independent `capture_database` read-back agreed on 120/120, 8-12 s from empty venv to first diff; one real MCP SDK session; one live headless Claude Code session (held, then applied and undone) | `openadapt proxy`, `openadapt_flow/txplan/proxy.py`, [TRANSACTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TRANSACTIONS.md) | | Dry-run, apply, undo and release a batch of writes to external systems: `openadapt plan create/approve/apply/undo/release/cancel` over an `openadapt.tx.yaml` of REST collections, SQL tables and mail. The diff comes from a staged transaction (SQL), a computed shadow with declared server-set and derived fields (REST) or the holdback queue (email). Approval is single-use and bound to the plan digest, a stale plan is refused, each write's idempotency key comes from the task and the record slot (never the payload), and a retry with a different payload is refused (the ACRFence action-replay attack). The undo is verified by reading back each record and the whole frame. Irreversible writes wait in a cancelable holdback queue | Experimental, this PR | Lab: Vikunja 2.7.1, Dolibarr 21.0.4 on MariaDB, Mailpit; 100 writes each; 0 missed effects, 0 false diffs, 200/200 verified undos (REST, SQL), 50/50 cancelled emails never sent, 50/50 released exactly once, 0/60 regenerated retries through (control 60/60 doubled), 0/10 after a crash after send; seeded faults caught 20/20 | `openadapt plan`, `openadapt_flow/txplan/`, [TRANSACTIONS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/TRANSACTIONS.md) | @@ -952,7 +953,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** -- `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. +- `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, writes a ledger row and a private diff, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). - `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 9916a41b8d..d70a1592b4 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,36 @@ # CHANGELOG +## v0.31.0 (2026-11-21) + +### Features + +- **guard**: approval card values beside the source, ReadbackProvider seam, per-save ledger row +- **desktop**: The stop queue now lists exception cards from any run on this + computer that asked a person (a one-time code prompt, an unexpected dialog, + a sign-in partway through, a stall, a possible duplicate, an ambiguous + record, a task it can't finish), not only Desktop's own runs. Each card is + answered on its own, here or on a paired phone, and the answer is signed + with the same approver key as other stop answers. Requires Flow with the + exception registry (#2494). The Flow 2.4.1 that Desktop runs has no + registry yet, so the queue shows exception cards only from runs of a newer + Flow on this computer. + +### Bug Fixes + +- **guard**: The phone's approval card for an agent's save no longer says + "exactly what will be saved" when OpenAdapt could not read the values the + save sends. It shows the task's value beside each sent value, flags a + difference, and says plainly when the sent values were not read or checked. + With no write adapter it shows the value on screen when the agent asked, + beside the task's, with a difference flagged. The on-screen values and the + source and task columns need a Flow release that includes #2492. Desktop + still runs Flow 2.4.1: until then an agent's save says its values were not + checked and never "exactly", and a compiled program's save keeps its + wording. + + + ## v0.30.6 (2026-11-19) ### Bug Fixes diff --git a/packages/desktop/openadapt_desktop/__init__.py b/packages/desktop/openadapt_desktop/__init__.py index c5dd5310f4..f30ef439c1 100644 --- a/packages/desktop/openadapt_desktop/__init__.py +++ b/packages/desktop/openadapt_desktop/__init__.py @@ -21,4 +21,4 @@ +-- backends/ Storage backend plugins """ -__version__ = "0.30.6" +__version__ = "0.31.0" diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 2c72ea20d8..50262cba8f 100644 --- a/packages/desktop/openadapt_desktop/dispatch.py +++ b/packages/desktop/openadapt_desktop/dispatch.py @@ -81,7 +81,7 @@ #: Stop cards a paired phone may answer through Desktop. A waiting save is #: answered through the portal's own save approval; turning "only ask about #: problems" back on is answered on the computer. -PHONE_ANSWERABLE_KINDS = frozenset({"same_record", "confirm_save", "halted"}) +PHONE_ANSWERABLE_KINDS = frozenset({"same_record", "confirm_save", "halted", "exception"}) _TEACH_CORRECTION_SCHEMA = "openadapt.desktop-teach-correction/v1" _TEACH_CORRECTION_META_KEY = "teach_correction" @@ -4490,7 +4490,7 @@ def _approver_key_setup_route(self, code: str) -> str | None: def _stop_cards(self) -> list[dict]: """Every card the queue shows now, rebuilt from the stores.""" - from openadapt_desktop import stop_queue + from openadapt_desktop import exception_queue, stop_queue from openadapt_desktop.work_items import OPEN, TEACHING, public_item names = { @@ -4519,7 +4519,7 @@ def _stop_cards(self) -> list[dict]: card = stop_queue.card_for_rearm(switch) if card is not None: cards.append(card) - return stop_queue.sort_cards(cards) + return stop_queue.sort_cards(cards + exception_queue.stop_cards()) def _rearm_offer(self, workflow_id: str) -> dict | None: """Flow's re-arm offer for a task's switch, with the clean items named.""" @@ -4819,7 +4819,7 @@ def _answer_stop_cards( ) -> dict: from datetime import datetime, timezone - from openadapt_desktop import stop_queue + from openadapt_desktop import exception_queue, stop_queue from openadapt_desktop.approver_keychain import ApproverKeychainError params = {"shown_ms": shown_ms} @@ -4841,6 +4841,8 @@ def _answer_stop_cards( } if choice_id == "leave": return {"ok": True, "results": [], "changed": 0} + if any(card["kind"] == stop_queue.EXCEPTION_KIND for card in cards): + return exception_queue.answer_stop_cards(self, cards, choice_id, sign, device) if any(card["kind"] == "rearm_problems_only" for card in cards): if len(cards) != 1 or device is not None: return { diff --git a/packages/desktop/openadapt_desktop/exception_queue.py b/packages/desktop/openadapt_desktop/exception_queue.py new file mode 100644 index 0000000000..087715aa6b --- /dev/null +++ b/packages/desktop/openadapt_desktop/exception_queue.py @@ -0,0 +1,384 @@ +"""Exception cards from any agent's run, in the stop queue. + +Requires Flow with the exception registry (#2494): Flow's exception registry +(``openadapt-flow exceptions``) keeps one folder per +run under ``$OPENADAPT_HOME/exceptions`` (``~/.openadapt/exceptions`` by +default). A run that hits a second-factor prompt, an unexpected dialog, a +sign-in page mid-task, a stall, a possible duplicate, a record it can't tell +apart, or a task it can't finish writes a ``card-.json`` and waits for an +``answer-.json``. Cards come from any run on this computer: a CLI guard, +``openadapt wrap``, a flight recorder, a hook, a Desktop-launched run. + +Desktop pins an exact Flow release, so this module reads the files as plain +JSON and checks them itself: the schema id, the closed kind and answer sets, +the card id (the digest of the card), and a regular file, not a link, owned by +this user, readable by no one else (no group or other permission bits), under +the size cap. A card that fails any check isn't shown. + +An answer is the closed answer signed with the approver key Desktop already +uses for the stop queue (Touch ID on a Mac, the portal's key for a phone). +The waiting run checks the signature against its pinned approver roster, so +an answer Desktop writes counts only when that key is on the roster. The +answer file records ``opened_at`` and ``decided_at``: how long a person held +the run. + +Nothing here is sent anywhere. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import re +import stat +import uuid +from collections.abc import Callable +from datetime import datetime, timezone +from pathlib import Path +from typing import Any + +CARD_SCHEMA = "openadapt.exception-card/v1" +ANSWER_SCHEMA = "openadapt.exception-answer/v1" +#: The bytes an approver key signs before the canonical answer. Flow's +#: ``openadapt_types.exception_card.EXCEPTION_ANSWER_DOMAIN``. +ANSWER_DOMAIN = b"openadapt.exception-answer/v1\x00" +KINDS = frozenset( + { + "second_factor", + "unexpected_dialog", + "session_expired", + "timeout_or_stall", + "possible_duplicate", + "ambiguous_record", + "cannot_complete", + } +) +ANSWERS = frozenset({"continue", "skip", "decline", "done_by_person", "abort"}) +#: How many cards one scan reads at most. +MAX_CARDS = 200 +_MAX_BYTES = 256 * 1024 +_RUN_REF = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$") +_CARD_FILE = re.compile(r"^card-([0-9a-f]{64})\.json$") +_SUMMARY_MAX = 200 + + +def _canonical(value: Any) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode("utf-8") + + +def registry_root() -> Path: + home = os.environ.get("OPENADAPT_HOME") + return (Path(home) if home else Path.home() / ".openadapt") / "exceptions" + + +def _read(path: Path) -> bytes | None: + flags = os.O_RDONLY | getattr(os, "O_NOFOLLOW", 0) | getattr(os, "O_CLOEXEC", 0) + try: + fd = os.open(path, flags) + except OSError: + return None + try: + info = os.fstat(fd) + if not stat.S_ISREG(info.st_mode) or info.st_size > _MAX_BYTES: + return None + if hasattr(os, "getuid") and info.st_uid != os.getuid(): + return None + if os.name == "posix" and info.st_mode & 0o077: + return None # another user could read or change it + return os.read(fd, _MAX_BYTES + 1)[:_MAX_BYTES] + finally: + os.close(fd) + + +def _time(value: Any) -> bool: + try: + parsed = datetime.fromisoformat(str(value).replace("Z", "+00:00")) + except ValueError: + return False + return parsed.tzinfo is not None + + +def valid_card(raw: Any, *, run_ref: str, file_hex: str) -> dict[str, Any] | None: + """The card when every field checks out, else ``None``.""" + + if not isinstance(raw, dict) or raw.get("schema") != CARD_SCHEMA: + return None + if raw.get("kind") not in KINDS or raw.get("run_ref") != run_ref: + return None + body = {k: v for k, v in raw.items() if k != "card_id"} + digest = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() + if raw.get("card_id") != digest or digest != f"sha256:{file_hex}": + return None + if not (_time(raw.get("opened_at")) and _time(raw.get("deadline_at"))): + return None + summary = raw.get("summary") + if not isinstance(summary, str) or not summary or len(summary) > _SUMMARY_MAX: + return None + choices = raw.get("choices") + if not isinstance(choices, list) or not choices: + return None + ids = [c.get("id") if isinstance(c, dict) else None for c in choices] + if any(i not in ANSWERS for i in ids) or len(set(ids)) != len(ids): + return None + task_id = raw.get("task_id") + if task_id is not None and (not isinstance(task_id, str) or len(task_id) > 128): + return None + return raw + + +def open_cards(root: Path | None = None) -> list[dict[str, Any]]: + """Every valid card with no answer yet, oldest first.""" + + base = root if root is not None else registry_root() + try: + folders = sorted(p for p in base.iterdir() if _RUN_REF.fullmatch(p.name)) + except OSError: + return [] + cards: list[dict[str, Any]] = [] + for folder in folders: + try: + if stat.S_ISLNK(os.lstat(folder).st_mode) or not folder.is_dir(): + continue + names = sorted(os.listdir(folder)) + except OSError: + continue + for name in names: + match = _CARD_FILE.fullmatch(name) + if match is None: + continue + if (folder / f"answer-{match.group(1)}.json").exists(): + continue + data = _read(folder / name) + if data is None: + continue + try: + raw = json.loads(data) + except ValueError: + continue + card = valid_card(raw, run_ref=folder.name, file_hex=match.group(1)) + if card is not None: + cards.append(card) + if len(cards) >= MAX_CARDS: + break + if len(cards) >= MAX_CARDS: + break + return sorted(cards, key=lambda c: str(c.get("opened_at"))) + + +def find_card(card_id: str, run_ref: str, root: Path | None = None) -> dict[str, Any] | None: + """The card, still unanswered and unchanged, or ``None``.""" + + return next( + ( + c + for c in open_cards(root) + if c.get("card_id") == card_id and c.get("run_ref") == run_ref + ), + None, + ) + + +def unsigned_answer(card: dict[str, Any], answer: str, *, route: str, decided_at: str) -> dict: + """The answer the approver key signs (Flow's ``ExceptionAnswerV1`` fields).""" + + if answer not in ANSWERS or route not in {"desktop", "portal"}: + raise ValueError("not an answer") + return { + "schema": ANSWER_SCHEMA, + "card_id": card["card_id"], + "kind": card["kind"], + "opened_at": card["opened_at"], + "decided_at": decided_at, + "answer": answer, + "approver_kind": "person", + "route": route, + "reason": None, + } + + +def message(unsigned: dict[str, Any]) -> bytes: + """The exact bytes the approver key signs.""" + + return ANSWER_DOMAIN + _canonical(unsigned) + + +def _write_exclusive(path: Path, payload: bytes) -> None: + tmp = path.with_name(f".{path.name}.{uuid.uuid4().hex}.tmp") + flags = os.O_WRONLY | os.O_CREAT | os.O_EXCL | getattr(os, "O_NOFOLLOW", 0) + fd = os.open(tmp, flags, 0o600) + try: + view = memoryview(payload) + while view: + view = view[os.write(fd, view) :] + os.fsync(fd) + finally: + os.close(fd) + try: + os.link(tmp, path) + finally: + try: + os.unlink(tmp) + except OSError: + pass + + +def answer( + source: dict[str, Any], + choice: str, + *, + sign: Callable[..., dict], + route: str, + root: Path | None = None, + now: Callable[[], datetime] = lambda: datetime.now(timezone.utc), +) -> dict[str, Any]: + """Sign and write one card's answer. Returns ``{"ok", ...}``. + + ``source`` is the queue card's ``source`` (the Flow card id and run). + The Flow card is read again before signing and again before writing: one + answered, changed or gone in between changes nothing. Raises the + signer's own error (``ApproverKeychainError``) for the caller to report. + """ + + base = root if root is not None else registry_root() + card_id, run_ref = str(source.get("id") or ""), str(source.get("run_ref") or "") + card = find_card(card_id, run_ref, base) + if card is None: + return {"ok": False, "code": "card_changed", "error": "The stop was answered or is gone."} + if choice not in {c.get("id") for c in card["choices"]}: + return { + "ok": False, + "code": "choice_not_offered", + "error": "That choice isn't on this stop.", + } + decided = now().astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + if _after(decided, card["deadline_at"]): + return {"ok": False, "code": "card_expired", "error": "The stop expired."} + unsigned = unsigned_answer(card, choice, route=route, decided_at=decided) + signature = sign(message(unsigned), count=1) + if find_card(card_id, run_ref, base) is None: + return {"ok": False, "code": "card_changed", "error": "The stop was answered or is gone."} + record = { + **unsigned, + "public_key": signature["public_key"], + "signature": signature["signature"], + } + path = base / run_ref / f"answer-{card_id.removeprefix('sha256:')}.json" + try: + _write_exclusive(path, (json.dumps(record, sort_keys=True, indent=2) + "\n").encode()) + except FileExistsError: + return {"ok": False, "code": "card_changed", "error": "The stop was answered first."} + except OSError: + return { + "ok": False, + "code": "registry_unwritable", + "error": "Desktop couldn't save the answer.", + } + return { + "ok": True, + "answer": choice, + "decided_at": decided, + "opened_at": card["opened_at"], + "key": signature.get("key"), + "public_key": signature["public_key"], + "signature": signature["signature"], + } + + +def _after(a: str, b: str) -> bool: + try: + return datetime.fromisoformat(a.replace("Z", "+00:00")) > datetime.fromisoformat( + str(b).replace("Z", "+00:00") + ) + except ValueError: + return True + + +__all__ = [ + "ANSWERS", + "ANSWER_DOMAIN", + "ANSWER_SCHEMA", + "CARD_SCHEMA", + "KINDS", + "answer", + "find_card", + "message", + "open_cards", + "registry_root", + "unsigned_answer", + "valid_card", +] + + +# -- the stop queue's side ------------------------------------------------------ + + +def stop_cards(root: Path | None = None) -> list[dict[str, Any]]: + """The stop queue's cards for every open exception card on this computer: + any run that asked a person (CLI guard, wrap, flight, hooks), not only + Desktop's own.""" + + from openadapt_desktop import stop_queue + + cards = (stop_queue.card_for_exception(raw) for raw in open_cards(root)) + return [card for card in cards if card is not None] + + +def answer_stop_cards( + dispatcher: Any, + cards: list[dict], + choice_id: str, + sign: Callable[..., dict], + device: dict[str, str] | None, +) -> dict: + """Answer one exception card from the stop queue: sign it, write the run's + answer file, and record the decision the way the queue records others.""" + + from openadapt_desktop import stop_queue + from openadapt_desktop.approver_keychain import ApproverKeychainError + + if len(cards) != 1: + return { + "ok": False, + "code": "answer_one_by_one", + "error": "Each of these stops is answered on its own. Nothing changed.", + } + card = cards[0] + try: + outcome = answer( + card["source"], + choice_id, + sign=sign, + route="desktop" if device is None else "portal", + ) + except ApproverKeychainError as exc: + return {"ok": False, "code": exc.code, "error": str(exc)} + if not outcome.get("ok"): + return { + "ok": False, + "code": outcome.get("code"), + "error": f"{outcome.get('error')} Nothing changed.", + } + dispatcher._record_stop_decision( + { + "schema": stop_queue.DECISION_SCHEMA, + "card_ids": [card["card_id"]], + "kinds": [stop_queue.EXCEPTION_KIND], + "choice": choice_id, + "decided_at": outcome["decided_at"], + "opened_at": outcome["opened_at"], + "public_key": outcome["public_key"], + "signature": outcome["signature"], + "key": outcome.get("key"), + "results": [{"card_id": card["card_id"], "ok": True}], + **({"device": device} if device is not None else {}), + } + ) + dispatcher.services.audit.log( + "exception_answered", kind=card.get("exception_kind"), choice=choice_id + ) + return { + "ok": True, + "results": [{"card_id": card["card_id"], "ok": True, "error": None}], + "changed": 1, + } diff --git a/packages/desktop/openadapt_desktop/portal/shell/app.js b/packages/desktop/openadapt_desktop/portal/shell/app.js index 36fc233c0c..857ed694e5 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/app.js +++ b/packages/desktop/openadapt_desktop/portal/shell/app.js @@ -971,6 +971,73 @@ function saveFields(presentation) { })); } +// `presentation.sources`: a guarded save's source column, `{label, source, +// status, differs, intended, held_differs}` per field, kept by Flow beside the +// request and bound to its digest. `intended` is the task's value, shown beside +// the value the held request sends; `held_differs` flags them differing. +// Anything malformed drops the column; the fields still show. +const NOT_READ = "not read"; +function saveSources(presentation) { + const raw = presentation && presentation.sources; + if (!Array.isArray(raw) || raw.length === 0 || raw.length > MAX_FIELDS) return null; + const ok = raw.every( + (row) => + row && + typeof row.label === "string" && + (row.source === null || typeof row.source === "string") && + typeof row.status === "string" && + typeof row.differs === "boolean" && + (row.intended === undefined || row.intended === null || typeof row.intended === "string") && + (row.held_differs === undefined || typeof row.held_differs === "boolean") && + (row.screen === undefined || row.screen === null || typeof row.screen === "string") && + (row.screen_differs === undefined || typeof row.screen_differs === "boolean"), + ); + if (!ok) return null; + return new Map( + raw.map((row) => [ + row.label, + { + source: row.source, + differs: row.differs, + intended: typeof row.intended === "string" ? row.intended : null, + heldDiffers: row.held_differs === true, + screen: typeof row.screen === "string" ? row.screen : null, + screenDiffers: row.screen_differs === true, + }, + ]), + ); +} + +const UNCHECKED_EXPLANATION = + "OpenAdapt didn't confirm that these are the values this save will send, so they were not checked before saving. Compare the screen with what the task says before you approve."; + +// A save an agent asked for: it carries the agent's provenance, or a value +// Flow couldn't read. An older Flow (Desktop pins 2.4.1) sends both for every +// guarded save and neither for a compiled program's own save. +function agentSave(presentation) { + if (presentation.provenance) return true; + const fields = Array.isArray(presentation.fields) ? presentation.fields : []; + return fields.some((f) => f && (f.after === NOT_READ || f.before === NOT_READ)); +} + +// Whether the card may say "exactly what will be saved". Flow says so with +// `values_checked`. An older Flow sends no flag: a compiled program's save +// keeps its wording, and an agent's save is not checked (fail closed). A +// ledger question saves nothing, so the flag doesn't apply. +function valuesChecked(presentation) { + if (presentation.kind === "question") return true; + if (presentation.values_checked === true) return true; + if (presentation.values_checked === false) return false; + return !agentSave(presentation); +} + +// Without checked values, any "exactly" in Flow's wording is replaced. +function saveExplanation(presentation) { + const text = typeof presentation.explanation === "string" ? presentation.explanation : ""; + if (!valuesChecked(presentation) && (!text || /exactly/i.test(text))) return UNCHECKED_EXPLANATION; + return text || "Before it saves, OpenAdapt reads the form again. If anything changed, it stops and asks again."; +} + // `presentation.provenance`: why an agent asked for this save. The agent's // reason is its own account and is shown as a quote, never as a finding. // Lines of what it saw that read like an instruction to an agent are shown @@ -1028,10 +1095,12 @@ async function openSave(item) { step, question: presentation.question || "Save this?", why: String(presentation.step_intent || "").trim() || "OpenAdapt filled the form and stopped before saving.", - then: - presentation.explanation || - "Before it saves, OpenAdapt reads the form again. If anything changed, it stops and asks again.", + then: saveExplanation(presentation), fields: saveFields(presentation), + sources: saveSources(presentation), + // "Exactly what will be saved" only when the values were checked + // (valuesChecked: an agent's save from an older Flow never is). + exact: valuesChecked(presentation), provenance: saveProvenance(presentation), frameUrl: null, frameOk: false, @@ -1164,7 +1233,12 @@ function expire(card) { function evidenceMarkup(card) { if (card.frameState === "none") return ""; const big = card.kind === "save" && !card.fields; - const title = card.kind === "save" ? "Exactly what will be saved" : "Screen when it stopped"; + const title = + card.kind === "save" + ? card.exact === false + ? "The screen when the agent asked" + : "Exactly what will be saved" + : "Screen when it stopped"; let sub; if (card.frameState === "loading") sub = "Loading the picture"; else if (card.frameState === "missing") sub = card.kind === "save" ? "Couldn't be shown" : "Not available"; @@ -1183,17 +1257,45 @@ function evidenceMarkup(card) { return ``; } +// The source line reuses the stop queue's side-by-side classes (stops.css). +function sourceMarkup(card, field) { + if (!card.sources) return ""; + const row = card.sources.get(field.label); + if (!row) return ""; + const text = row.source === null ? "none given" : row.source === "" ? "empty" : row.source; + // Flow compares the values (dates, numbers) and sends the result. + const intended = + row.intended === null + ? "" + : `${row.heldDiffers ? 'Differs ' : ""}Task says: ${esc(row.intended === "" ? "empty" : row.intended)}`; + // With no write adapter: the value the form showed when the agent asked. + const onScreen = + row.screen === null + ? "" + : `${row.screenDiffers ? 'Differs ' : ""}On screen at the save: ${esc(row.screen === "" ? "empty" : row.screen)}`; + return `${onScreen}${intended}${row.differs ? 'Differs ' : ""}Source: ${esc(text)}`; +} + function fieldsMarkup(card) { if (!card.fields) return ""; + const unread = card.fields.some((field) => field.after === NOT_READ || field.before === NOT_READ); return `
${card.fields .map( (field) => `
${esc(field.label)}
${ - field.before != null && field.before !== field.after - ? `Was ${esc(field.before)}` - : "" - }${field.after === "" ? '(empty)' : esc(field.after)}
`, + field.before === NOT_READ + ? 'Now: not read' + : field.before != null && field.before !== field.after + ? `Was ${esc(field.before)}` + : "" + }${field.after === "" ? '(empty)' : esc(field.after)}${sourceMarkup(card, field)}`, ) - .join("")}
`; + .join("")}${ + card.exact === false + ? '

OpenAdapt could not read the values this save will send, so they were not checked before saving. Compare the screen with what the task says.

' + : unread + ? '

A value marked not read was not checked; this approval does not cover it.

' + : "" + }`; } function provenanceMarkup(card) { @@ -2093,7 +2195,11 @@ function openMore() { ? `` : ""; const closes = @@ -2136,11 +2242,12 @@ function openScreen() { const card = deck.card; if (!card || !card.frameOk) return; const save = card.kind === "save"; + const exact = card.exact !== false; openSheet( - `

${save ? "Exactly what will be saved" : "The screen it kept"}

-

${save ? "The form as OpenAdapt will save it." : "Kept when it stopped. Not live, so check the application."} Drag to pan. Tap the picture to fit it.

+ `

${save ? (exact ? "Exactly what will be saved" : "The screen when the agent asked") : "The screen it kept"}

+

${save ? (exact ? "The form as OpenAdapt will save it." : "The agent's screen when it asked. OpenAdapt did not read the values it will send.") : "Kept when it stopped. Not live, so check the application."} Drag to pan. Tap the picture to fit it.

${save ?
+ alt="${save ? (exact ? "The filled form, exactly as OpenAdapt will save it." : "The agent's screen when it asked to save.") : "The screen OpenAdapt kept when it stopped."}"> `, () => { const wrap = $("screen-wrap"); diff --git a/packages/desktop/openadapt_desktop/portal/shell/index.html b/packages/desktop/openadapt_desktop/portal/shell/index.html index 2853739ae7..e976bc24c0 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/index.html +++ b/packages/desktop/openadapt_desktop/portal/shell/index.html @@ -11,6 +11,7 @@ OpenAdapt decisions +
diff --git a/packages/desktop/openadapt_desktop/portal/shell/stops.js b/packages/desktop/openadapt_desktop/portal/shell/stops.js index a916569954..725e4d2ed6 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/stops.js +++ b/packages/desktop/openadapt_desktop/portal/shell/stops.js @@ -8,6 +8,12 @@ // choice the stop doesn't offer, changes nothing, and this page shows the // refusal as it came. // +// An exception card is any agent's run asking a person (a one-time code +// prompt, a dialog in the way, a sign-in partway through, a stall, a +// possible duplicate, an ambiguous record, a task it can't finish). It shows +// the run's scrubbed summary and its closed choices, and is answered on its +// own. A one-time code is typed in the live browser, never here. +// // Answers are signed on the computer with the decision portal's approver // key. Two kinds of stop are view-only here: a waiting save is answered on // the Decisions page (the portal's own save approval), and turning "only ask @@ -19,7 +25,7 @@ const POLL_MS = 10000; const MAX_BATCH = 25; -const PHONE_KINDS = new Set(["same_record", "confirm_save", "halted"]); +const PHONE_KINDS = new Set(["same_record", "confirm_save", "halted", "exception"]); const store = window.sessionStorage; const state = { @@ -437,7 +443,7 @@ function render() { className: "stops-warn", text: "Answers from this phone need the decision portal's approver key. Set it up on the computer. Until then, nothing here changes.", }), - evidence(card), + card.kind === "exception" ? null : evidence(card), choices(card), batchBlock(card), ]), diff --git a/packages/desktop/openadapt_desktop/stop_queue.py b/packages/desktop/openadapt_desktop/stop_queue.py index f51438331f..5606f05bbb 100644 --- a/packages/desktop/openadapt_desktop/stop_queue.py +++ b/packages/desktop/openadapt_desktop/stop_queue.py @@ -24,6 +24,12 @@ first, so every answer names a registered approver. * ``rearm_problems_only``: a task whose "only ask about problems" switch went off, when a signed re-arm is available. +* ``exception``: a card any agent's run opened in Flow's exception registry + (a one-time code prompt, an unexpected dialog, a sign-in mid-task, a stall, + a possible duplicate, an ambiguous record, a task it can't finish). The + answer is the closed answer, signed with the approver key and written as + the card's answer file (:mod:`openadapt_desktop.exception_queue`); the + waiting run checks the signature itself. Similar cards share a ``batch_key``. A batch is answered with one choice and one signature, and each card in it is still checked on its own. @@ -489,6 +495,179 @@ def card_for_rearm(switch: dict) -> dict[str, Any] | None: return _seal(card) +# -- exception cards ------------------------------------------------------------- + +#: Per kind: the question, and the closed answers with what each one does. +#: Desktop shows its own words for each answer, and only answers the run's +#: own card offers. +_EXCEPTION_QUESTIONS = { + "second_factor": "The app wants a one-time code", + "unexpected_dialog": "A dialog is in the way", + "session_expired": "The app signed out partway through", + "timeout_or_stall": "The run has stalled", + "possible_duplicate": "Is this record already in the app?", + "ambiguous_record": "Which record is it?", + "cannot_complete": "The run can't finish this item", +} + +_EXCEPTION_SKIP = Choice( + "skip", "Skip this item", "Nothing is saved. The run moves to the next item.", "exception:skip" +) +_EXCEPTION_ABORT = Choice( + "abort", "Stop the run", "Nothing more is saved. The whole run stops.", "exception:abort" +) + +_EXCEPTION_CHOICES: dict[str, tuple[Choice, ...]] = { + "second_factor": ( + Choice( + "done_by_person", + "I entered the code in the browser", + "You type the code in the live browser yourself, then the run goes on. " + "OpenAdapt never sees the code.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "unexpected_dialog": ( + Choice( + "done_by_person", + "I dealt with the dialog", + "You close or answer it yourself, then the run goes on.", + "exception:done_by_person", + ), + Choice( + "continue", + "It's harmless, go on", + "The run goes on with the dialog as it is. Every check still runs.", + "exception:continue", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "session_expired": ( + Choice( + "done_by_person", + "I signed in again", + "You sign in yourself in the live browser, then the run goes on. " + "OpenAdapt never sees the password.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "timeout_or_stall": ( + Choice( + "continue", + "Keep waiting", + "The run tries the step again, with every check.", + "exception:continue", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), + "possible_duplicate": ( + Choice( + "skip", + "Same record: don't add it", + "Nothing is saved. The item closes as skipped.", + "exception:skip", + ), + Choice( + "continue", + "Different record: go on", + "The run goes on to fill the form. The save still needs every check.", + "exception:continue", + ), + Choice( + "done_by_person", + "I'll do this one by hand", + "OpenAdapt saves nothing. The item closes as done by a person.", + "exception:done_by_person", + ), + _EXCEPTION_ABORT, + ), + "ambiguous_record": ( + Choice( + "done_by_person", + "I opened the right record", + "You open the right record yourself, then the run goes on from there.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + Choice( + "decline", + "This item shouldn't be done", + "Nothing is saved. The item closes as declined.", + "exception:decline", + ), + ), + "cannot_complete": ( + Choice( + "done_by_person", + "I did it by hand", + "OpenAdapt saves nothing. The item closes as done by a person.", + "exception:done_by_person", + ), + _EXCEPTION_SKIP, + _EXCEPTION_ABORT, + ), +} + +#: Card kinds that are exception cards (one card kind, many exception kinds). +EXCEPTION_KIND = "exception" + + +def card_for_exception(raw: dict) -> dict[str, Any] | None: + """A card from Flow's exception registry as a queue card, or None. + + ``raw`` is a card :func:`openadapt_desktop.exception_queue.open_cards` + already checked. Its summary was scrubbed by the run before it was + written. Each exception is answered on its own: no batch. + """ + + kind = raw.get("kind") if isinstance(raw, dict) else None + table = _EXCEPTION_CHOICES.get(str(kind)) + if table is None: + return None + offered = {c.get("id") for c in raw.get("choices") or [] if isinstance(c, dict)} + choices = [c for c in table if c.id in offered] + if not choices: + return None + card = { + "schema": CARD_SCHEMA, + "kind": EXCEPTION_KIND, + "exception_kind": kind, + "source": { + "type": "exception", + "id": raw["card_id"], + "run_ref": raw["run_ref"], + }, + "workflow_id": "", + "task_name": str(raw.get("task_id") or raw["run_ref"]), + "label": "", + "question": _EXCEPTION_QUESTIONS[str(kind)], + "summary": str(raw.get("summary") or ""), + "evidence": { + "source": [], + "record": [], + "differences": [], + "candidates": [], + "reason": "", + "step": "", + "expected": "", + "observed": "", + "screenshot": None, + }, + "choices": [c.public() for c in [*choices, _LEAVE]], + "expires_at": raw.get("deadline_at"), + "created_at": raw.get("opened_at"), + "batch_key": None, + "status": "waiting", + } + return _seal(card) + + def choice_for(card: dict, choice_id: str) -> Choice | None: """The full choice behind a card's button, or None if it doesn't offer it.""" @@ -500,6 +679,9 @@ def choice_for(card: dict, choice_id: str) -> Choice | None: return next((c for c in _APPROVAL_CHOICES if c.id == choice_id), None) if card["kind"] == "rearm_problems_only": return Choice("rearm", "", "", "rearm") if choice_id == "rearm" else None + if card["kind"] == EXCEPTION_KIND: + table = _EXCEPTION_CHOICES.get(str(card.get("exception_kind")), ()) + return next((c for c in table if c.id == choice_id), None) table = _ITEM_CHOICES.get(card["kind"], {}) return next((c for c in table.values() if c.id == choice_id), None) @@ -531,9 +713,16 @@ def decision_message(card_ids: Iterable[str], choice_id: str, *, decided_at: str def sort_cards(cards: list[dict]) -> list[dict]: - """Waiting saves first (they expire), then the oldest stop first.""" - - order = {"approve_save": 0, "confirm_save": 1, "same_record": 2, "halted": 3} + """Waiting saves and exceptions first (they expire), then the oldest stop.""" + + # A run holding on an exception waits with a deadline, like a save. + order = { + "approve_save": 0, + EXCEPTION_KIND: 0, + "confirm_save": 1, + "same_record": 2, + "halted": 3, + } return sorted( cards, key=lambda c: (order.get(c["kind"], 4), str(c.get("created_at") or "")), @@ -544,10 +733,12 @@ def sort_cards(cards: list[dict]) -> list[dict]: "CARD_SCHEMA", "DECISION_DOMAIN", "DECISION_SCHEMA", + "EXCEPTION_KIND", "MAX_BATCH", "RECORD_CHECK_ACTIONS", "Choice", "card_for_approval", + "card_for_exception", "card_for_item", "card_for_rearm", "choice_for", diff --git a/packages/desktop/package-lock.json b/packages/desktop/package-lock.json index 3fa77186e8..88c85f2015 100644 --- a/packages/desktop/package-lock.json +++ b/packages/desktop/package-lock.json @@ -1,12 +1,12 @@ { "name": "openadapt-desktop", - "version": "0.30.6", + "version": "0.31.0", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "openadapt-desktop", - "version": "0.30.6", + "version": "0.31.0", "dependencies": { "@tauri-apps/api": "^2", "@tauri-apps/plugin-notification": "^2", diff --git a/packages/desktop/package.json b/packages/desktop/package.json index 2922cf9315..1b92b8568c 100644 --- a/packages/desktop/package.json +++ b/packages/desktop/package.json @@ -1,6 +1,6 @@ { "name": "openadapt-desktop", - "version": "0.30.6", + "version": "0.31.0", "description": "Installed companion for OpenAdapt authoring, teaching, and local pairing", "private": true, "type": "module", diff --git a/packages/desktop/pyproject.toml b/packages/desktop/pyproject.toml index bd1d994ee7..84d122859c 100644 --- a/packages/desktop/pyproject.toml +++ b/packages/desktop/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" description = "The OpenAdapt desktop app and local engine: record a data-entry task, run it on a list, and check each saved record" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/desktop/src-tauri/Cargo.lock b/packages/desktop/src-tauri/Cargo.lock index 111ec12503..98cf6ea65f 100644 --- a/packages/desktop/src-tauri/Cargo.lock +++ b/packages/desktop/src-tauri/Cargo.lock @@ -2513,7 +2513,7 @@ dependencies = [ [[package]] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" dependencies = [ "hex", "reqwest", diff --git a/packages/desktop/src-tauri/Cargo.toml b/packages/desktop/src-tauri/Cargo.toml index 80279fdaab..e8c03f006a 100644 --- a/packages/desktop/src-tauri/Cargo.toml +++ b/packages/desktop/src-tauri/Cargo.toml @@ -1,6 +1,6 @@ [package] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" description = "Installed companion for OpenAdapt authoring, teaching, and local pairing" authors = ["OpenAdapt AI"] license = "MIT" diff --git a/packages/desktop/src-tauri/tauri.conf.json b/packages/desktop/src-tauri/tauri.conf.json index ede2e28594..aa17f4b35d 100644 --- a/packages/desktop/src-tauri/tauri.conf.json +++ b/packages/desktop/src-tauri/tauri.conf.json @@ -1,7 +1,7 @@ { "$schema": "https://raw.githubusercontent.com/nicoverbruggen/tauri-v2-schema/main/schema.json", "productName": "OpenAdapt Desktop", - "version": "0.30.6", + "version": "0.31.0", "identifier": "ai.openadapt.desktop", "build": { "frontendDist": "../dist", diff --git a/packages/desktop/src/lib/types.ts b/packages/desktop/src/lib/types.ts index 1743b68536..295dce888a 100644 --- a/packages/desktop/src/lib/types.ts +++ b/packages/desktop/src/lib/types.ts @@ -1243,8 +1243,17 @@ export interface ApproverKeyStatus { export interface StopCard { schema: "openadapt.desktop-stop-card/v1"; card_id: string; - kind: "approve_save" | "same_record" | "confirm_save" | "halted" | "rearm_problems_only"; - source: { type: "item" | "approval" | "switch"; id: string; [key: string]: unknown }; + kind: "approve_save" | "same_record" | "confirm_save" | "halted" | "rearm_problems_only" | "exception"; + /** With kind "exception": the run's closed exception kind (second_factor, ...). */ + exception_kind?: + | "second_factor" + | "unexpected_dialog" + | "session_expired" + | "timeout_or_stall" + | "possible_duplicate" + | "ambiguous_record" + | "cannot_complete"; + source: { type: "item" | "approval" | "switch" | "exception"; id: string; [key: string]: unknown }; workflow_id: string; task_name: string; label: string; diff --git a/packages/desktop/src/portalShell.test.ts b/packages/desktop/src/portalShell.test.ts index 91db714762..d9c610c943 100644 --- a/packages/desktop/src/portalShell.test.ts +++ b/packages/desktop/src/portalShell.test.ts @@ -375,6 +375,136 @@ describe("the card shows what will be saved", () => { expect(q("#evidence")!.classList).toContain("big"); }); + // The shapes Flow 2.4.1's console sends (Desktop 0.31.0 pins it): no + // values_checked, no sources, and its own "exactly" explanation. + const OLD_EXPLANATION = + "This is exactly what OpenAdapt will save. Before it saves, it reads the form again; if anything changed, it stops and asks again."; + + it("an older Flow's compiled-program save keeps its wording", async () => { + onlySave(saveDetail({ presentation: { explanation: OLD_EXPLANATION } })); + await boot(); + const card = q("#card")!.textContent!; + expect(card).toContain("This is exactly what OpenAdapt will save"); + expect(card).toContain("Exactly what will be saved"); + expect(card).not.toContain("The screen when the agent asked"); + expect(card).not.toContain("were not checked before saving"); + }); + + it("an older Flow's guarded save never gets an exactly", async () => { + // 2.4.1 guarded saves carry the agent's provenance and unread values. + onlySave( + saveDetail({ + presentation: { + explanation: OLD_EXPLANATION, + fields: [{ label: "note", before: null, after: "not read" }], + provenance: { + actor: "agent:attached-agent", + reason: null, + screen_text: "Chart: patient p1", + instruction_like: [], + task_scope: "record patient_id; fields note", + }, + }, + }), + ); + await boot(); + const card = q("#card")!.textContent!; + expect(card).not.toMatch(/exactly/i); + expect(card).toContain("were not checked before saving"); + expect(card).toContain("The screen when the agent asked"); + }); + + it("a ledger question never gets the agent-asked title", async () => { + onlySave( + saveDetail({ + presentation: { + kind: "question", + question: "Is this the right patient?", + explanation: "Your agent asks you this. Save means yes, Don't save means no.", + provenance: { + actor: "agent:attached-agent", + reason: null, + screen_text: "", + instruction_like: [], + task_scope: "", + }, + }, + }), + ); + await boot(); + const card = q("#card")!.textContent!; + expect(card).not.toContain("The screen when the agent asked"); + expect(card).not.toContain("were not checked before saving"); + expect(card).toContain("Your agent asks you this."); + }); + + it("an agent's save whose values Flow couldn't read never says exactly", async () => { + onlySave( + saveDetail({ + presentation: { + fields: [{ label: "note", before: null, after: "not read" }], + sources: [ + { label: "note", source: null, status: "no_source", differs: false, intended: "Triage note", held_differs: false }, + ], + values_checked: false, + explanation: "OpenAdapt could not read the values this save will send, so they were not checked before saving.", + }, + }), + ); + await boot(); + const card = q("#card")!.textContent!; + expect(card).not.toMatch(/exactly/i); + expect(card).toContain("Task says: Triage note"); + expect(card).toContain("were not checked before saving"); + }); + + it("shows the value on screen at the save beside the task's, flagged", async () => { + onlySave( + saveDetail({ + presentation: { + fields: [{ label: "note", before: null, after: "not read" }], + sources: [ + { + label: "note", + source: null, + status: "no_source", + differs: false, + intended: "Triage note", + held_differs: false, + screen: "Another note", + screen_differs: true, + }, + ], + values_checked: false, + }, + }), + ); + await boot(); + const dd = q(".fields dd")!.textContent!; + expect(dd).toContain("On screen at the save: Another note"); + expect(dd).toContain("Differs"); + expect(dd).toContain("Task says: Triage note"); + }); + + it("flags a held value that differs from the task's", async () => { + onlySave( + saveDetail({ + presentation: { + fields: [{ label: "note", before: null, after: "Another note" }], + sources: [ + { label: "note", source: null, status: "no_source", differs: false, intended: "Triage note", held_differs: true }, + ], + values_checked: true, + }, + }), + ); + await boot(); + const dd = q(".fields dd")!.textContent!; + expect(dd).toContain("Another note"); + expect(dd).toContain("Differs"); + expect(dd).toContain("Task says: Triage note"); + }); + it("drops a malformed field list as a whole rather than show part of it", async () => { onlySave(saveDetail({ presentation: { fields: [...FIELDS, { label: "Amount", after: 142 }] } })); await boot(); diff --git a/packages/desktop/tests/conftest.py b/packages/desktop/tests/conftest.py index cdfb7ce65c..e8a4208cd3 100644 --- a/packages/desktop/tests/conftest.py +++ b/packages/desktop/tests/conftest.py @@ -151,6 +151,9 @@ def _isolated_flow_at_rest(tmp_path_factory, monkeypatch): monkeypatch.setenv("OPENADAPT_FLOW_AT_REST_HOME", str(tmp_path_factory.mktemp("at-rest-home"))) monkeypatch.setenv("OPENADAPT_FLOW_PLAINTEXT_AT_REST", "test suite: synthetic data") monkeypatch.delenv("OPENADAPT_FLOW_AT_REST", raising=False) + # The stop queue also lists Flow's exception registry under + # OPENADAPT_HOME; keep a developer's real cards out of every test. + monkeypatch.setenv("OPENADAPT_HOME", str(tmp_path_factory.mktemp("openadapt-home"))) @pytest.fixture(autouse=True) diff --git a/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py new file mode 100644 index 0000000000..ce88aedccb --- /dev/null +++ b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py @@ -0,0 +1,405 @@ +"""Exception cards from any agent's run, in the stop queue and on the phone. + +The cards are files in a temporary OPENADAPT_HOME, written as Flow's +exception registry writes them (the committed Flow fixture is the contract). +Answers are signed with the fake Secure Enclave's approver key, or the +portal's key for the phone. Synthetic data only. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import stat +import threading +from datetime import datetime, timedelta, timezone +from pathlib import Path + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PublicKey + +from openadapt_desktop import exception_queue, stop_queue +from openadapt_desktop.portal.stops import DispatcherStopQueue +from tests.test_engine.test_stop_queue import ( # noqa: F401 (fixtures) + enclave, + queue, +) +from tests.test_engine.test_stop_queue_portal import ( # noqa: F401 (fixtures) + _app, + _paired, + portal_key, +) + +FLOW_FIXTURE = ( + Path(__file__).resolve().parents[3] + / "flow" + / "tests" + / "fixtures" + / "exception_card_second_factor.json" +) +CHOICES = { + "second_factor": ["done_by_person", "skip", "abort"], + "unexpected_dialog": ["done_by_person", "continue", "skip", "abort"], + "session_expired": ["done_by_person", "skip", "abort"], + "timeout_or_stall": ["continue", "skip", "abort"], + "possible_duplicate": ["skip", "continue", "done_by_person", "abort"], + "ambiguous_record": ["done_by_person", "skip", "decline"], + "cannot_complete": ["done_by_person", "skip", "abort"], +} + + +def _canonical(value) -> bytes: + return json.dumps(value, sort_keys=True, separators=(",", ":")).encode() + + +def _iso(value: datetime) -> str: + return value.astimezone(timezone.utc).isoformat().replace("+00:00", "Z") + + +def _write_card( + kind: str = "second_factor", + *, + run_ref: str = "guard-run", + minutes: int = 15, + summary: str = "The app is asking for a one-time code.", +) -> dict: + opened = datetime.now(timezone.utc) + body = { + "schema": "openadapt.exception-card/v1", + "run_ref": run_ref, + "task_id": "intake", + "kind": kind, + "opened_at": _iso(opened), + "deadline_at": _iso(opened + timedelta(minutes=minutes)), + "screenshot_ref": None, + "summary": summary, + "choices": [ + {"id": answer, "label": answer.replace("_", " "), "consequence": "As the run says."} + for answer in CHOICES[kind] + ], + } + card = {**body, "card_id": "sha256:" + hashlib.sha256(_canonical(body)).hexdigest()} + folder = exception_queue.registry_root() / run_ref + folder.mkdir(parents=True, exist_ok=True) + path = folder / f"card-{card['card_id'][7:]}.json" + path.write_text(json.dumps(card, indent=2)) + path.chmod(0o600) + return card + + +def _cards(disp) -> list[dict]: + listed = disp.dispatch("list_stop_cards", {}) + assert listed["ok"] is True + return [c for c in listed["cards"] if c["kind"] == stop_queue.EXCEPTION_KIND] + + +def _answer_file(card: dict) -> Path: + return ( + exception_queue.registry_root() + / card["run_ref"] + / f"answer-{card['card_id'][7:]}.json" + ) + + +# -- the cards ------------------------------------------------------------------------ + + +def test_flows_own_card_file_is_listed(): + if not FLOW_FIXTURE.is_file(): + pytest.skip("Flow's fixture isn't in this checkout") + raw = json.loads(FLOW_FIXTURE.read_text()) + folder = exception_queue.registry_root() / raw["run_ref"] + folder.mkdir(parents=True) + path = folder / f"card-{raw['card_id'][7:]}.json" + path.write_text(json.dumps(raw)) + path.chmod(0o600) # as Flow's registry creates it + + (found,) = exception_queue.open_cards() + card = stop_queue.card_for_exception(found) + + assert card is not None + assert card["exception_kind"] == "second_factor" + assert [c["id"] for c in card["choices"]] == ["done_by_person", "skip", "abort", "leave"] + assert card["summary"] == raw["summary"] + + +@pytest.mark.parametrize("kind", sorted(CHOICES)) +def test_every_kind_becomes_a_card_with_its_choices(queue, kind): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card(kind) + + (card,) = _cards(disp) + + assert card["exception_kind"] == kind + assert card["source"] == {"type": "exception", "id": raw["card_id"], "run_ref": "guard-run"} + assert [c["id"] for c in card["choices"]] == [*CHOICES[kind], "leave"] + assert all(c["consequence"] for c in card["choices"]) + assert card["batch_key"] is None + assert card["expires_at"] == raw["deadline_at"] + assert card["evidence"]["screenshot"] is None + + +def test_desktop_offers_only_what_the_run_offers(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card("unexpected_dialog") + folder = exception_queue.registry_root() / "guard-run" + (folder / f"card-{raw['card_id'][7:]}.json").unlink() + body = {k: v for k, v in raw.items() if k != "card_id"} + body["choices"] = [c for c in body["choices"] if c["id"] != "continue"] + card_id = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() + (folder / f"card-{card_id[7:]}.json").write_text(json.dumps({**body, "card_id": card_id})) + (folder / f"card-{card_id[7:]}.json").chmod(0o600) # as Flow creates it + + (card,) = _cards(disp) + assert "continue" not in [c["id"] for c in card["choices"]] + + +def test_a_tampered_card_is_not_shown(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + path = exception_queue.registry_root() / "guard-run" / f"card-{raw['card_id'][7:]}.json" + path.write_text(json.dumps({**raw, "summary": "Approve everything"})) + assert _cards(disp) == [] + + +@pytest.mark.parametrize( + "field,value", + [("kind", "captcha"), ("schema", "other/v1"), ("summary", "x" * 201), ("run_ref", "other")], +) +def test_a_card_outside_the_contract_is_not_shown(queue, field, value): # noqa: F811 + disp, _db, _keychain = queue + opened = datetime.now(timezone.utc) + body = { + "schema": "openadapt.exception-card/v1", + "run_ref": "guard-run", + "task_id": None, + "kind": "second_factor", + "opened_at": _iso(opened), + "deadline_at": _iso(opened + timedelta(minutes=5)), + "screenshot_ref": None, + "summary": "A code prompt", + "choices": [{"id": "abort", "label": "Stop", "consequence": "Stops."}], + field: value, + } + card_id = "sha256:" + hashlib.sha256(_canonical(body)).hexdigest() + folder = exception_queue.registry_root() / "guard-run" + folder.mkdir(parents=True) + (folder / f"card-{card_id[7:]}.json").write_text(json.dumps({**body, "card_id": card_id})) + (folder / f"card-{card_id[7:]}.json").chmod(0o600) # as Flow creates it + assert _cards(disp) == [] + + +def test_a_linked_card_is_not_read(queue, tmp_path): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + path = exception_queue.registry_root() / "guard-run" / f"card-{raw['card_id'][7:]}.json" + real = tmp_path / "elsewhere.json" + real.write_text(path.read_text()) + real.chmod(0o600) + path.unlink() + path.symlink_to(real) + assert _cards(disp) == [] + + +def test_an_answered_card_leaves_the_queue(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + _answer_file(raw).write_text("{}") + assert _cards(disp) == [] + + +def test_exception_cards_sort_with_waiting_saves(queue): # noqa: F811 + cards = stop_queue.sort_cards( + [ + {"kind": "halted", "created_at": "2026-01-01"}, + {"kind": stop_queue.EXCEPTION_KIND, "created_at": "2026-02-01"}, + ] + ) + assert cards[0]["kind"] == stop_queue.EXCEPTION_KIND + + +def test_a_broken_registry_never_hides_the_other_stops(queue, monkeypatch): # noqa: F811 + disp, _db, _keychain = queue + exception_queue.registry_root().mkdir(parents=True) + (exception_queue.registry_root() / "guard-run").write_text("not a folder") + assert disp.dispatch("list_stop_cards", {})["ok"] is True + + +# -- answers from the window -------------------------------------------------------- + + +def test_the_window_signs_and_writes_the_runs_answer(queue, enclave): # noqa: F811 + disp, _db, keychain = queue + raw = _write_card() + (card,) = _cards(disp) + + result = disp.dispatch( + "answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "done_by_person"} + ) + + assert result["ok"] is True and result["changed"] == 1 + assert len(enclave.prompts) == 1 + path = _answer_file(raw) + assert stat.S_IMODE(path.stat().st_mode) == 0o600 + answer = json.loads(path.read_text()) + assert answer["answer"] == "done_by_person" + assert answer["approver_kind"] == "person" and answer["route"] == "desktop" + assert answer["opened_at"] == raw["opened_at"] and answer["decided_at"] + assert answer["public_key"] == keychain.stored().public_key + unsigned = {k: v for k, v in answer.items() if k not in {"signature", "public_key"}} + Ed25519PublicKey.from_public_bytes(bytes.fromhex(answer["public_key"])).verify( + bytes.fromhex(answer["signature"].removeprefix("ed25519:")), + exception_queue.ANSWER_DOMAIN + _canonical(unsigned), + ) + assert _cards(disp) == [] + (receipt,) = [ + json.loads(line) + for line in (disp.config.data_dir / "stop_decisions.jsonl").read_text().splitlines() + ] + assert receipt["kinds"] == ["exception"] + assert receipt["opened_at"] == raw["opened_at"] and receipt["decided_at"] + + +def test_the_answer_file_matches_flows_answer_contract(queue, enclave): # noqa: F811 + """Flow's ExceptionAnswerV1 accepts what Desktop writes, when it's importable.""" + + types = pytest.importorskip("openadapt_types.exception_card") + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "skip"}) + answer = types.ExceptionAnswerV1.model_validate(json.loads(_answer_file(raw).read_text())) + assert types.answer_message(answer.wire()) == exception_queue.message( + {k: v for k, v in answer.wire().items() if k not in {"signature", "public_key"}} + ) + + +def test_a_choice_the_card_doesnt_offer_changes_nothing(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card("second_factor") + (card,) = _cards(disp) + result = disp.dispatch( + "answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "continue"} + ) + assert result["ok"] is False and result["code"] == "choice_not_offered" + assert not _answer_file(raw).exists() + + +def test_leave_changes_nothing(queue, enclave): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "leave"}) + assert result["ok"] is True and result["changed"] == 0 + assert not _answer_file(raw).exists() and enclave.prompts == [] + + +def test_an_expired_card_changes_nothing(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card(minutes=-1) + (card,) = _cards(disp) + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) + assert result["ok"] is False + assert not _answer_file(raw).exists() + + +def test_a_cancelled_prompt_writes_nothing(queue, enclave): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + enclave.answer = "cancel" + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) + assert result["ok"] is False and result["code"] == "approver_presence_refused" + assert not _answer_file(raw).exists() + + +def test_a_card_answered_elsewhere_during_the_prompt_is_not_overwritten( + queue, # noqa: F811 + enclave, # noqa: F811 + monkeypatch, +): + disp, _db, _keychain = queue + raw = _write_card() + (card,) = _cards(disp) + original = disp._sign_stop_decision + + def sign_while_the_cli_answers(message, *, count): + _answer_file(raw).write_text('{"answered": "elsewhere"}') + return original(message, count=count) + + monkeypatch.setattr(disp, "_sign_stop_decision", sign_while_the_cli_answers) + result = disp.dispatch("answer_stop_cards", {"card_ids": [card["card_id"]], "choice": "abort"}) + assert result["ok"] is False and result["code"] == "card_changed" + assert json.loads(_answer_file(raw).read_text()) == {"answered": "elsewhere"} + + +def test_two_exception_cards_are_never_one_batch(queue): # noqa: F811 + disp, _db, _keychain = queue + _write_card(run_ref="run-a") + _write_card(run_ref="run-b") + ids = [c["card_id"] for c in _cards(disp)] + result = disp.dispatch("answer_stop_cards", {"card_ids": ids, "choice": "abort"}) + assert result["ok"] is False + assert not list(exception_queue.registry_root().rglob("answer-*.json")) + + +# -- answers from the paired phone --------------------------------------------------- + + +def test_the_phone_answers_with_the_portal_key(queue, portal_key, enclave): # noqa: F811 + disp, _db, _keychain = queue + disp.serial_lock = threading.RLock() + raw = _write_card("possible_duplicate") + app, pairings = _app(DispatcherStopQueue(disp)) + headers = _paired(pairings) + + status, _h, body = app.handle("GET", "/api/portal/stops", headers, b"") + (card,) = [c for c in json.loads(body)["cards"] if c["kind"] == "exception"] + status, _h, body = app.handle( + "POST", + f"/api/portal/stops/{card['card_id'].removeprefix('sha256:')}/answer", + headers, + json.dumps({"choice": "skip", "shown_ms": 900}).encode(), + ) + + assert status == 200 and json.loads(body)["ok"] is True + assert enclave.prompts == [] + answer = json.loads(_answer_file(raw).read_text()) + assert answer["route"] == "portal" and answer["answer"] == "skip" + assert answer["public_key"] == portal_key.public_key + + +def test_the_phone_page_knows_the_exception_cards(): + script = ( + Path(__file__).resolve().parents[2] + / "openadapt_desktop" + / "portal" + / "shell" + / "stops.js" + ).read_text() + assert '"exception"' in script + assert "const MAX_BATCH = 25;" in script + assert stop_queue.MAX_BATCH == 25 + + +def test_no_registry_folder_is_an_empty_list(tmp_path): + assert exception_queue.open_cards(tmp_path / "missing") == [] + assert os.environ["OPENADAPT_HOME"] + + +def test_a_card_other_users_can_read_is_not_shown(queue): # noqa: F811 + disp, _db, _keychain = queue + raw = _write_card() + path = exception_queue.registry_root() / raw["run_ref"] / f"card-{raw['card_id'][7:]}.json" + path.chmod(0o644) + assert _cards(disp) == [] + path.chmod(0o600) + assert [c["source"]["id"] for c in _cards(disp)] == [raw["card_id"]] + + +def test_the_scan_stops_at_the_cap_across_runs(monkeypatch): + monkeypatch.setattr(exception_queue, "MAX_CARDS", 2) + for run in ("run-a", "run-b", "run-c"): + _write_card(run_ref=run) + assert len(exception_queue.open_cards()) == 2 diff --git a/packages/desktop/tests/test_guard_request_pickup.py b/packages/desktop/tests/test_guard_request_pickup.py new file mode 100644 index 0000000000..db84cc8e4c --- /dev/null +++ b/packages/desktop/tests/test_guard_request_pickup.py @@ -0,0 +1,213 @@ +"""Desktop shows a guarded agent's save approval when its state is in the runs folder. + +``openadapt_flow.guard.GuardedSave`` says that when its ``state_dir`` is the +runs folder the console watches, or a folder directly inside it, the phone +portal shows its approval requests. This test holds Desktop to that with its +own code: the ``--runs`` folder Desktop starts the Flow console with, and the +portal's relay of ``/api/portal/save-approvals``. The relay is answered by +Flow's own console functions over that folder, so nothing is canned. + +Synthetic MockMed fault server on localhost; no browser, no model calls. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +pytest.importorskip("openadapt_flow") + +from openadapt_desktop.portal.flow_client import FlowResponse # noqa: E402 +from openadapt_desktop.portal.ingress import resolve_ingress # noqa: E402 +from openadapt_desktop.portal.pairing import DevicePairingStore # noqa: E402 +from openadapt_desktop.portal.server import PortalApp # noqa: E402 +from openadapt_desktop.portal.service import PortalError, PortalService # noqa: E402 + +ORIGIN = "https://openadapt.clinic.example" +NOTE = "Synthetic referral note for the pickup test" +#: The open record's text, as an agent's harness reads it. +SCREEN = "Chart: patient p1 (synthetic)" + + +class _Config: + portal_ingress_mode = "customer_ingress" + portal_public_origin = ORIGIN + portal_bind_host = "" + portal_ingress_acknowledged = True + portal_port = 8443 + portal_console_port = 7863 + + def __init__(self, data_dir: Path) -> None: + self.data_dir = data_dir + + +class _Spawned(Exception): + pass + + +def _console_runs_folder(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """The ``--runs`` folder Desktop gives the Flow console it starts.""" + + import openadapt_desktop.approver_key as approver_key + + monkeypatch.setattr(approver_key, "portal_approver_environment", lambda: {}) + seen: list[list[str]] = [] + + def popen(command: list[str], **_kw: Any) -> Any: + seen.append(list(command)) + raise _Spawned() + + service = PortalService(_Config(tmp_path / "desktop-data"), popen=popen) + with pytest.raises((_Spawned, PortalError)): + service._spawn_console(["openadapt-flow"], tmp_path / "flow.yaml") + [command] = seen + return Path(command[command.index("--runs") + 1]) + + +class _FlowConsole: + """Answers the portal's relay with Flow's console functions over ``root``.""" + + def __init__(self, root: Path) -> None: + self.root = root + + def request(self, route: str, **kwargs: Any) -> FlowResponse: + from openadapt_flow.console.save_approvals import ( + list_save_approvals, + save_approval_detail, + ) + + if route == "save_approvals": + rows = [r.model_dump(mode="json") for r in list_save_approvals(self.root)] + return FlowResponse(200, {"save_approvals": rows}, None, "application/json") + if route == "save_approval_detail": + detail = save_approval_detail(self.root, kwargs["request_id"]) + return FlowResponse(200, detail, None, "application/json") + raise AssertionError(route) + + +def _paired(app: PortalApp, pairings: DevicePairingStore) -> dict[str, str]: + pairing = pairings.create(ORIGIN, reachable_from_phone=True) + claim = pairings.claim(pairing.secret, "Phone") + pairings.approve(claim["pairing_id"], claim["confirm_code"]) + return { + "authorization": f"Bearer {claim['session_token']}", + "origin": ORIGIN, + "content-type": "application/json", + "x-openadapt-portal-csrf": claim["csrf_token"], + } + + +def _verify(base_url: str) -> Any: + from openadapt_flow.mockmed.fault_server import MOCKMED_RECORDS_READ_CONTRACT + from openadapt_flow.verify_run import parse_verify_config + + return parse_verify_config( + { + "schema_version": "openadapt.verify/v1", + "verifier": {"base_url": base_url, **MOCKMED_RECORDS_READ_CONTRACT}, + "effects": [ + { + "kind": "record_written", + "match": { + "patient_id": {"param": "patient_id"}, + "type": "Referral", + "note": {"param": "note"}, + }, + "expected_count": 1, + "count_new_only": True, + "timeout_s": 1.0, + } + ], + } + ) + + +def _png() -> bytes: + import struct + import zlib + + def chunk(kind: bytes, data: bytes) -> bytes: + body = kind + data + return struct.pack(">I", len(data)) + body + struct.pack(">I", zlib.crc32(body)) + + return ( + b"\x89PNG\r\n\x1a\n" + + chunk(b"IHDR", struct.pack(">IIBBBBB", 1, 1, 8, 2, 0, 0, 0)) + + chunk(b"IDAT", zlib.compress(b"\x00\xf0\xf0\xf0")) + + chunk(b"IEND", b"") + ) + + +@pytest.fixture +def mockmed(): + from openadapt_flow.mockmed.fault_server import serve + + url, _db, stop = serve() + try: + yield url.rstrip("/") + finally: + stop() + + +@pytest.mark.parametrize("state", ["folder_inside", "runs_folder"]) +def test_desktop_shows_a_guard_request_from_a_state_dir_in_its_runs_folder( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mockmed: str, state: str +) -> None: + from openadapt_flow.guard import GuardedSave, GuardTask + + runs = _console_runs_folder(tmp_path, monkeypatch) + state_dir = runs / "guarded-agent" if state == "folder_inside" else runs + guarded = GuardedSave(_verify(mockmed), state_dir, approval="each_item") + task = GuardTask( + task_id="pickup-task-0001", + expected_record={"patient_id": "p1"}, + intended_fields={"note": NOTE}, + ) + guard = guarded.begin(task, screen_text=SCREEN, agent_id="cua-pickup") + waiting = guard.commit(screenshot_png=_png()) + assert waiting.status == "waiting_for_approval" + + pairings = DevicePairingStore(runner_id="runner_test") + app = PortalApp(resolve_ingress(_Config(tmp_path)), pairings, _FlowConsole(runs)) + headers = _paired(app, pairings) + status, _, body = app.handle("GET", "/api/portal/save-approvals", headers, b"") + assert status == 200 + [row] = json.loads(body)["save_approvals"] + assert row["request_id"] == waiting.approval_request_id + status, _, body = app.handle( + "GET", f"/api/portal/save-approvals/{row['request_id']}", headers, b"" + ) + assert status == 200 + presentation = json.loads(body)["presentation"] + # The card carries the field the save writes. No request is held here + # (the harness sends the save itself), so the value sent is not read and + # the card says so; the task's value is shown beside it, never in its place. + assert presentation["fields"] == [ + {"label": "note", "before": None, "after": "not read"} + ] + assert presentation["sources"][0]["intended"] == NOTE + assert presentation["values_checked"] is False + assert "exactly" not in presentation["explanation"].lower() + + +def test_a_state_dir_two_folders_down_is_not_shown( + tmp_path: Path, monkeypatch: pytest.MonkeyPatch, mockmed: str +) -> None: + """The console looks two levels deep: a guard folder under + ``runs//guard`` (``openadapt-flow guard --out runs/``) is + deeper than that, and the phone doesn't see it.""" + + from openadapt_flow.guard import GuardedSave, GuardTask + + runs = _console_runs_folder(tmp_path, monkeypatch) + guarded = GuardedSave(_verify(mockmed), runs / "task-0001" / "guard") + task = GuardTask( + task_id="pickup-task-0002", + expected_record={"patient_id": "p1"}, + intended_fields={"note": NOTE}, + ) + guarded.begin(task, screen_text=SCREEN).commit(screenshot_png=_png()) + assert _FlowConsole(runs).request("save_approvals").json == {"save_approvals": []} diff --git a/packages/desktop/uv.lock b/packages/desktop/uv.lock index 2f82f650e6..97ac5c27f7 100644 --- a/packages/desktop/uv.lock +++ b/packages/desktop/uv.lock @@ -1172,7 +1172,7 @@ wheels = [ [[package]] name = "openadapt-desktop" -version = "0.30.6" +version = "0.31.0" source = { editable = "." } dependencies = [ { name = "cryptography" }, diff --git a/packages/flow/docs/GUARD_AN_AGENT.md b/packages/flow/docs/GUARD_AN_AGENT.md index 77b78b0d7d..e26dbce979 100644 --- a/packages/flow/docs/GUARD_AN_AGENT.md +++ b/packages/flow/docs/GUARD_AN_AGENT.md @@ -139,6 +139,110 @@ If the guard stops while a save is paused, it blocks that save before it lets go of the tab, because Chromium sends paused requests on when the session that paused them goes away. +## The approval card + +With `approval: each_item`, or when a second reading of the source doesn't +confirm a value, the save waits for a person. They answer it in Desktop or on +the paired phone. The phone card lists every field the task writes, in these +columns; Desktop's own window shows the screenshot and the step's +description (which says when values were not read or checked): + +| Column | Where it comes from | +|---|---| +| Now | The record's value before the save, read through `verify.yaml`. Empty for a save that adds a record. | +| Saved | The value the held request carries, read by the app's `write_adapter`, the same reader the guard checks the write with. Without a `write_adapter`, or when the adapter can't read the body, it is `not read`. | +| On screen at the save | Without a `write_adapter`: the value the agent's form shows when the save is held (its `input`, `select`, `textarea` and `contenteditable` controls, matched to a field by id, name or label). Marked `Differs` when it isn't the task's value. A field with no matching control, or two controls that disagree, is not read on screen. | +| Task says | The task's `intended_fields` value, beside Saved. Marked `Differs` when the held request sends another value. | +| Source | The value the task's `provenance` cites, checked a second time against the source document. A value the document doesn't confirm is marked `Differs` and shows what the document says. | + +A value the guard can't read shows `not read`, never a blank, and the card +says the approval doesn't cover it. The guard doesn't parse request bodies +itself, so without a `write_adapter` it can't say what the save sends. The +card then says that the values this save sends could not be read and were not +checked before saving. It shows what a careful person would check instead: a +screenshot of the filled form and the values on screen, both taken when the +save is held, beside the task's values. If no value could be read and there +is no readable screenshot, no card is offered at all, so nobody can approve +what nobody could see: the guard blocks the save with `values_unread` and the +run ends `ESCALATED` for a person to check the record. It says "exactly what will be saved" only when every value came +from the held request and the card left no field out (a task with more fields +than the card holds is never "checked"). With a `write_adapter`, a save whose values differ +from the task's is blocked before any card is shown. Either way, the read-back +after the save still catches a value that differs. + +The Now and Saved values are in the approval request and its digest, so the +person's answer covers exactly them. The source column is kept beside the +request in `approval_sources.json` (mode 0600), bound to the request's digest. +The values go to the paired phone that shows the card, through the decision +portal on this computer, and nowhere else: they aren't in a notification, the +run report, or anything Cloud receives. + +Turn the values off with `approval_fields: false`; the card then shows the +screenshot only. + +## The ledger row + +After each read-back or blocked save, the guard writes two files in `--out`: + +- `guard_ledger_row.json` (`openadapt.guard-ledger-row/v1`): `task_id`, + `verdict`, `guard_verdict`, `verdict_reason`, `fields_checked`, + `fields_differing` (field names), `hold_ms`, `approver_kind`, + `approval_opened_at`, `approval_decided_at`, `readback_tier` and + `diff_path`. It holds no record values. +- `guard_diff.private.json` (mode 0600): for each field, the value intended, + the value before, the value the read-back found, and `same`, `differs` or + `not_read`. + +`verdict` comes only from the guard's own verdict, the `verdict` in +`summary.json` (repeated as `guard_verdict`), or, for a save blocked before it +was sent, from the block's code. `verdict_reason` names the rule, in the run +ledger's words: + +| Guard verdict or block | `verdict` | `verdict_reason` | +|---|---|---| +| `VERIFIED`, independent read-back | `VERIFIED` | `readback_verified` | +| `VERIFIED`, screen read-back | `UNKNOWN` | `screen_readback_only` | +| `VERIFIED`, a field differs in the diff | `UNKNOWN` | `readback_fields_disagree` | +| `REFUTED` | `CAUGHT_ERROR` | `readback_refuted` | +| `RECONCILIATION_REQUIRED` | `UNKNOWN` | `reconciliation_required` | +| Blocked: wrong record, another origin, a second save, outside the teach scope | `CAUGHT_ERROR` | `save_blocked_*` | +| Blocked: a person declined | `ESCALATED` | `person_declined` | +| Blocked: nobody answered in time | `ESCALATED` | `approval_declined` | +| Blocked: no value read and no screenshot, so no card was offered | `ESCALATED` | `values_unread` | +| Blocked: the guard couldn't check (store unreadable, unusable answer) | `FAILED` | `policy_rejected_no_write` | +| Blocked: any other code | `UNKNOWN` | `unmapped_outcome` | + +A save the guard calls `RECONCILIATION_REQUIRED` (sent, and the read-back +couldn't confirm it, for example because it never landed) is `UNKNOWN`, not +`ESCALATED`. The run ledger decides its own bucket from `summary.json` and +reads only the row's field names, times and tier. + +There is one row per run. A blocked second save after a read-back keeps the +read-back's row; a read-back after a blocked save replaces the blocked row. + +`openadapt-flow redact-report RUN_DIR` writes `guard_diff.scrubbed.json`: the +same rows with each value replaced by a salted digest. `--no-ledger-row` +writes neither file. + +### How a save is read back + +By default the guard reads the save back through `verify-run`, then reads the +record once more through the same reader to fill the diff. A field the +read-back shows with another value than the task's makes the verdict +`REFUTED`, whatever else the read-back found. When that overrides a +`verify-run` receipt that says verified, the receipt keeps the outcome it +signed, `effect-receipt.override.json` beside it records the guard's verdict +and the receipt's digest, and `guard.json` says `outcome: overridden`. + +`readback_provider: ` in `guard.yaml` names another reader, registered +with `register_verifier_factory("readback:", factory)`. Only a reader +that doesn't use the app's screen (`independent_readback`) can make a save +`VERIFIED`. A reader that reads the app's screen in a second session +(`screen_readback`) gives `RECONCILIATION_REQUIRED` at best. A reader that +fails gives `RECONCILIATION_REQUIRED`. The reader declares its own tier, so +registering one is trusting its code: the guard can't check that a reader +calling itself `independent_readback` doesn't read the screen. + ## Run 2: a program from run 1 With a `teach:` section, a run that reads back `VERIFIED` is handed to the @@ -264,6 +368,14 @@ GUI steps, and the run-2 times are GUI times. - Compiling run 1 needs the recording. The recorder refuses a run it can't keep exactly (an agent that acts faster than a frame can be kept). The guard keeps guarding; only run 2 is missing. +- The card's Now column and the diff's saved value come from one more read + of the record (the guard's baseline holds keyed digests, not values). When the task's record can't be told apart in that read (no + `expected_record` field is in the effect contract), or two records changed, + they show `not read`. +- The phone portal shows a guard's approval only when the guard's state is + at most two folders below the runs folder the console watches. `--out + runs/` puts it three folders down (`runs//guard/`), so + answer those with `openadapt-flow item-approval approve` or Desktop. - API steps are proposed only for form posts (`application/x-www-form-urlencoded`). A save built by script as JSON, like MockMed's, stays on GUI steps. Programs from the teach dir run as durable diff --git a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/guard.md b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/guard.md index 6bc864889c..149b06c40c 100644 --- a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/guard.md +++ b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/guard.md @@ -1 +1 @@ -Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. +Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, writes a ledger row and a private diff, and hands a verified run to the teach dir. diff --git a/packages/flow/openadapt_flow/agent_guard/approval_fields.py b/packages/flow/openadapt_flow/agent_guard/approval_fields.py new file mode 100644 index 0000000000..cfe5ca993a --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/approval_fields.py @@ -0,0 +1,504 @@ +"""The values a guarded save's approval card shows, next to their source. + +A person approving an agent's save should see, for every field the task +writes, what the record holds now, what the save writes, and what the source +document says. :func:`build_card` makes those rows for one guarded save: + +* ``before``: the record's value now, read from the system of record through + the same ``verify.yaml`` reader the guard's baseline uses, before anything + is written. ``None`` when the save creates a record (nothing was there) or + the current value can't be read. +* ``after``: the value the held request actually carries, read by the app's + write adapter, the same parser the guard checks the write with + (:meth:`openadapt_flow.teach_scope.TeachScope.request_refusal`). With no + write adapter, or a body the adapter can't read, it is ``not read``: the + guard does not parse request bodies itself, so it can't say what the save + sends. It is never the task's intended value standing in for it. +* ``intended``: the value the task says to write, beside ``after``, with + ``held_differs`` set when the two differ by the read-back's value + comparison. +* ``screen``: with no write adapter, the value the agent's form shows at the + moment the save is held (:mod:`.screen_values`), with ``screen_differs`` + set when it differs from ``intended``. The card's screenshot is taken at + the same moment. With neither a value read nor a readable screenshot, no + card is offered: the guard refuses the save with ``values_unread``. +* ``source``: the value the task's provenance cites, checked a second way + against the source document (:func:`openadapt_flow.provenance.cross_check`). + +A value that can't be resolved is shown as ``not read``, never blank, and the +card's intent says that the approval does not cover it. When any value the +save sends is not read, the card says that the values were not read and were +not checked before saving (``values_read`` false), never that it shows exactly +what will be saved. + +The ``before`` and ``after`` rows go into the item-approval request as its +``fields`` (inside the request digest, local only, never sent to Cloud). The +source column is kept beside the request in ``approval_sources.json`` (0600), +bound to the request's digest; the console shows it only for that request. +""" + +from __future__ import annotations + +import json +from dataclasses import dataclass, field, replace +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +from openadapt_flow.runtime.identity import normalize_structured + +__all__ = [ + "NOT_READ", + "SOURCES_FILENAME", + "SOURCES_SCHEMA", + "ApprovalCard", + "SourceRow", + "build_card", + "bound_fields", + "card_for_request", + "matching_records", + "read_records", + "read_sources_for", + "read_values_for", + "write_sources", +] + +NOT_READ = "not read" +SOURCES_FILENAME = "approval_sources.json" +SOURCES_SCHEMA = "openadapt.guard-approval-sources/v1" +_MAX_VALUE = 512 + + +@dataclass(frozen=True) +class SourceRow: + """One field's source column: the cited value and how it was checked.""" + + label: str + #: The source's value, ``not read`` when it can't be, or None when the + #: task gives no source for this field. + source: Optional[str] + #: ``agree`` | ``disagree`` | ``missing`` | ``no_document`` | + #: ``not_independent`` | ``instruction`` | ``no_source`` + status: str + #: The source disagrees with the value saved, by the same value + #: comparison the read-back uses. The phone only renders this. + differs: bool = False + #: The task's intended value for this field. + intended: Optional[str] = None + #: The value the held request sends differs from ``intended``. False when + #: the sent value was not read (the card then says it wasn't checked). + held_differs: bool = False + #: The value the form showed when the save was held; None: not read. + screen: Optional[str] = None + #: ``screen`` differs from ``intended``. + screen_differs: bool = False + + def to_dict(self) -> dict[str, Any]: + return { + "label": self.label, + "source": self.source, + "status": self.status, + "differs": self.differs, + "intended": self.intended, + "held_differs": self.held_differs, + "screen": self.screen, + "screen_differs": self.screen_differs, + } + + +@dataclass +class ApprovalCard: + """What :func:`build_card` resolved for one save.""" + + fields: list[Any] + sources: list[SourceRow] + #: Field names whose value the card can't show (``not read``). + not_covered: list[str] = field(default_factory=list) + #: Every value the save sends was read from the held request. + values_read: bool = False + #: How the sent values were read: ``write_adapter``, or why not + #: (``no_held_request``, ``no_write_adapter``, ``unreadable``). + values_how: str = "no_held_request" + #: At least one field's value was read from the screen at the hold. + screen_read: bool = False + + def nothing_visible(self, screenshot: Optional[bytes]) -> bool: + """No value was read (not from the request, not from the screen) and + there is no screenshot a person could look at: nobody could see what + would be approved.""" + + from openadapt_flow.agent_guard.screen_values import readable_png + + return ( + not self.values_read + and not self.screen_read + and not readable_png(screenshot) + ) + + def intent_note(self) -> str: + """The sentence the card's intent carries when something is unread.""" + + note = "" + if not self.values_read: + note += ( + ". The values this save sends could not be read, so they were " + "not checked before saving" + ) + if self.screen_read: + note += "; compare what was on screen at the save with the task" + if self.not_covered: + note += ". Not read, so this approval does not cover: " + ", ".join( + sorted(self.not_covered) + ) + return note + + +def _text(value: Any) -> str: + return ("" if value is None else str(value))[:_MAX_VALUE] + + +def bound_fields(verify: Any) -> dict[str, str]: + """Task parameter -> record field, from the effect contract.""" + + from openadapt_flow.provenance import bound_fields as _bound + + try: + return dict(_bound(verify.effects)) + except Exception: # noqa: BLE001 - an unusual contract: nothing is bound + return {} + + +def _creates(verify: Any) -> bool: + """Every effect adds a record (so nothing was there before).""" + + effects = list(getattr(verify, "effects", []) or []) + return bool(effects) and all( + getattr(e, "kind", "") == "record_written" + and bool(getattr(e, "count_new_only", False)) + for e in effects + ) + + +def read_records(verify: Any, params: Mapping[str, Any]) -> Optional[list[dict]]: + """The records the ``verify.yaml`` reader returns now, or None. + + A fresh read of the system of record, independent of the screen. Raw + values: kept in memory and in 0600 files only. + """ + + from openadapt_flow.deployment import build_effect_verifier + + try: + verifier = build_effect_verifier(verify.verifier, dict(params)) + state = verifier.capture_pre_state() if verifier is not None else None + except Exception: # noqa: BLE001 - unreadable: the card says not read + return None + if state is None or state.reachable is not True: + return None + return [dict(r) for r in state.records if isinstance(r, Mapping)] + + +def matching_records( + records: Optional[Sequence[Mapping[str, Any]]], + expected_record: Mapping[str, str], + bound: Mapping[str, str], +) -> Optional[list[Mapping[str, Any]]]: + """The records whose bound identity fields equal the task's record. + + None when no identity field of the task is bound in the contract (the + record can't be told apart) or the records weren't read. + """ + + keys = {bound[p]: v for p, v in expected_record.items() if p in bound} + if records is None or not keys: + return None + return [ + r + for r in records + if all( + normalize_structured(_text(r.get(f))) == normalize_structured(str(v)) + for f, v in keys.items() + ) + ] + + +def _sources(task: Any) -> dict[str, SourceRow]: + provenance = getattr(task, "provenance", None) + if provenance is None: + return {} + from openadapt_flow.provenance import cross_check, default_extractor + + try: + check = cross_check(provenance, task.documents, default_extractor(provenance)) + except Exception: # noqa: BLE001 - the card shows the source as not read + return { + name: SourceRow(name, NOT_READ, "missing") for name in provenance.params + } + out: dict[str, SourceRow] = {} + for item in check.fields: + cited = provenance.params[item.name].value + if item.result == "agree": + value: Optional[str] = cited + elif item.result == "disagree": + # The second reading: what the document says, not what was cited. + value = item.second if item.second is not None else NOT_READ + elif item.result == "instruction": + value = cited + else: + value = NOT_READ + out[item.name] = SourceRow(item.name, _text(value), item.result) + return out + + +def _source_differs(row: SourceRow, after: str) -> bool: + if row.status == "disagree": + return True + if row.source is None or row.source == NOT_READ or after == NOT_READ: + return False + from openadapt_flow.agent_guard.readback import same_value + + return not same_value(row.source, after) + + +def build_card( + task: Any, + verify: Any, + *, + claim_fields: Optional[Mapping[str, Any]] = None, + records: Optional[Sequence[Mapping[str, Any]]] = None, + read: bool = True, + values_how: Optional[str] = None, + screen_fields: Optional[Mapping[str, str]] = None, +) -> ApprovalCard: + """The approval card's rows for one guarded save. Never raises. + + ``claim_fields`` are the values the held request carries, per the app's + write adapter, keyed by task field name; None when they weren't read + (every ``after`` is then ``not read``). ``records`` is a read the caller + already made; otherwise one is made now when ``read``. ``values_how`` + says why the values weren't read, for the card's sources file. + ``screen_fields`` are the values the form showed at the hold, keyed by + task field name (:func:`.screen_values.match_fields`). + """ + + from openadapt_flow.approval_mode.item_approval import MAX_SAVE_FIELDS, SaveField + + bound = bound_fields(verify) + if records is None and read: + records = read_records(verify, task.params) + current = matching_records(records, task.expected_record, bound) + creates = _creates(verify) + sources = _sources(task) + rows: list[Any] = [] + source_rows: list[SourceRow] = [] + not_covered: list[str] = [] + for name in sorted(task.intended_fields)[:MAX_SAVE_FIELDS]: + before: Optional[str] = None + if not creates: + record_field = bound.get(name) + if current is not None and len(current) == 1 and record_field: + value = current[0].get(record_field) + before = None if value is None else _text(value) + else: + # Which record, or its value, isn't known: shown, not hidden. + before = NOT_READ + not_covered.append(name) + intended = _text(task.intended_fields[name]) + if ( + claim_fields is not None + and name in claim_fields + and claim_fields[name] is not None + ): + after = _text(claim_fields[name]) + else: + # Never the task's value in its place: what is sent is unknown. + after = NOT_READ + if name not in not_covered: + not_covered.append(name) + rows.append(SaveField(label=name[:128], before=before, after=after)) + row = sources.get(name) or SourceRow(name, None, "no_source") + on_screen = (screen_fields or {}).get(name) + on_screen = None if on_screen is None else _text(on_screen) + row = replace( + row, + differs=_source_differs(row, intended if after == NOT_READ else after), + intended=intended, + held_differs=after != NOT_READ and _differs(intended, after), + screen=on_screen, + screen_differs=on_screen is not None and _differs(intended, on_screen), + ) + source_rows.append(row) + if row.source == NOT_READ and name not in not_covered: + not_covered.append(name) + if len(task.intended_fields) > MAX_SAVE_FIELDS: + not_covered.extend(sorted(task.intended_fields)[MAX_SAVE_FIELDS:]) + values_read = ( + claim_fields is not None + and bool(rows) + and all(r.after != NOT_READ for r in rows) + and len(task.intended_fields) <= MAX_SAVE_FIELDS + ) + if values_read: + how = "write_adapter" + elif values_how is not None: + how = values_how + else: + how = "no_held_request" if claim_fields is None else "unreadable" + return ApprovalCard( + fields=rows, + sources=source_rows, + not_covered=not_covered, + values_read=values_read, + values_how=how, + screen_read=any(r.screen is not None for r in source_rows), + ) + + +def _differs(intended: str, sent: str) -> bool: + from openadapt_flow.agent_guard.readback import same_value + + return not same_value(intended, sent) + + +def write_sources(run_dir: Path, request: Any, card: ApprovalCard) -> Path: + """Keep the card's source column next to the request, bound to its digest.""" + + from openadapt_flow.guard import _write_json + + path = Path(run_dir) / SOURCES_FILENAME + _write_json( + path, + { + "schema": SOURCES_SCHEMA, + "request_id": request.request_id, + "request_sha256": request.digest(), + "rows": [row.to_dict() for row in card.sources], + "not_covered": sorted(card.not_covered), + "values": { + "read": card.values_read, + "how": card.values_how, + "screen_read": card.screen_read, + }, + }, + ) + return path + + +def read_sources_for(run_dir: Path, request: Any) -> Optional[list[dict[str, Any]]]: + """The source rows kept for exactly this request, or None. + + Anything else (another request's file, an edited request, a malformed + file) shows no source column rather than a wrong one. + """ + + path = Path(run_dir) / SOURCES_FILENAME + try: + if path.is_symlink() or not path.is_file(): + return None + raw = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if ( + not isinstance(raw, dict) + or raw.get("schema") != SOURCES_SCHEMA + or raw.get("request_id") != request.request_id + or raw.get("request_sha256") != request.digest() + or not isinstance(raw.get("rows"), list) + ): + return None + rows = [] + for row in raw["rows"]: + if not isinstance(row, dict) or not isinstance(row.get("label"), str): + return None + source = row.get("source") + if source is not None and not isinstance(source, str): + return None + intended = row.get("intended") + if intended is not None and not isinstance(intended, str): + return None + screen = row.get("screen") + if screen is not None and not isinstance(screen, str): + return None + rows.append( + { + "label": row["label"][:128], + "source": None if source is None else source[:_MAX_VALUE], + "status": str(row.get("status") or "")[:32], + "differs": row.get("differs") is True, + "intended": None if intended is None else intended[:_MAX_VALUE], + "held_differs": row.get("held_differs") is True, + "screen": None if screen is None else screen[:_MAX_VALUE], + "screen_differs": row.get("screen_differs") is True, + } + ) + return rows + + +def read_values_for(run_dir: Path, request: Any) -> Optional[dict[str, Any]]: + """The card's ``values`` summary kept for exactly this request + (``read``, ``how``, ``screen_read``), or None.""" + + path = Path(run_dir) / SOURCES_FILENAME + try: + if path.is_symlink() or not path.is_file(): + return None + raw = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if ( + not isinstance(raw, dict) + or raw.get("schema") != SOURCES_SCHEMA + or raw.get("request_id") != request.request_id + or raw.get("request_sha256") != request.digest() + or not isinstance(raw.get("values"), dict) + ): + return None + values = raw["values"] + return { + "read": values.get("read") is True, + "how": str(values.get("how") or "")[:32], + "screen_read": values.get("screen_read") is True, + } + + +def card_for_request( + guard: Any, + request: Any, + scope: Any, + *, + controls: Optional[Sequence[Mapping[str, Any]]] = None, +) -> Any: + """The commit guard's card for a held save: the values the held request + carries, read by the app's write adapter (the parser the guard checks + writes with), beside the task's values. With no adapter, or a body it + can't read, every sent value is ``not read`` and the card says they were + not checked. Without an adapter, ``controls`` (the form at the hold, + :meth:`~.cdp.CdpGuardPage.form_controls`) give each field's value on + screen. None when no card is asked for (or it is turned off).""" + + owner = guard.owner + asked = owner.approval == "each_item" or guard.source_check == "hold" + if not owner.approval_fields or not asked: + return None + adapter = getattr(scope, "write_adapter", None) if scope is not None else None + if adapter is None: + from openadapt_flow.agent_guard.screen_values import match_fields + + return build_card( + guard.task, + owner.verify, + claim_fields=None, + values_how="no_write_adapter", + screen_fields=match_fields( + controls, sorted(guard.task.intended_fields), bound_fields(owner.verify) + ), + ) + try: + body = request.post_data.encode("utf-8") if request.post_data else None + claim = adapter.claim(request.method, request.url, body) + except Exception: # noqa: BLE001 - unread: every value shows not read + claim = None + if claim is None: + return build_card( + guard.task, owner.verify, claim_fields=None, values_how="unreadable" + ) + return build_card(guard.task, owner.verify, claim_fields=dict(claim.fields)) diff --git a/packages/flow/openadapt_flow/agent_guard/cdp.py b/packages/flow/openadapt_flow/agent_guard/cdp.py index 7a2ec055d0..734f74cb4f 100644 --- a/packages/flow/openadapt_flow/agent_guard/cdp.py +++ b/packages/flow/openadapt_flow/agent_guard/cdp.py @@ -226,6 +226,28 @@ def screen_text(self) -> Optional[str]: value = (out.get("result") or {}).get("value") return value if isinstance(value, str) else None + def form_controls(self) -> Optional[list[dict[str, Any]]]: + """The form controls' values and labels at this moment + (:data:`~.screen_values.READ_CONTROLS_JS`), or None when unreadable.""" + + from openadapt_flow.agent_guard.screen_values import ( + READ_CONTROLS_JS, + controls_from, + ) + + try: + out = self.cdp.send( + "Runtime.callFunctionOn", + { + "functionDeclaration": _call(READ_CONTROLS_JS), + "executionContextId": self._context_id(), + "returnByValue": True, + }, + ) + except Exception: # noqa: BLE001 - unreadable: the card says so + return None + return controls_from((out.get("result") or {}).get("value")) + def screenshot(self) -> Optional[bytes]: try: out = self.cdp.send("Page.captureScreenshot", {"format": "png"}) diff --git a/packages/flow/openadapt_flow/agent_guard/cli.py b/packages/flow/openadapt_flow/agent_guard/cli.py index 7afc73b77a..a5cdc3516a 100644 --- a/packages/flow/openadapt_flow/agent_guard/cli.py +++ b/packages/flow/openadapt_flow/agent_guard/cli.py @@ -89,6 +89,12 @@ def add_parser(sub: argparse._SubParsersAction) -> None: action="store_true", help="don't hand a verified run to the teach dir", ) + p.add_argument( + "--ledger-row", + action=argparse.BooleanOptionalAction, + default=True, + help="write guard_ledger_row.json and guard_diff.private.json (default on)", + ) p.add_argument("--json", action="store_true", help="print the result as JSON") p.set_defaults(func=cmd_guard) @@ -98,6 +104,7 @@ def cmd_guard(args: argparse.Namespace) -> int: from openadapt_flow.agent_guard.config import ConfigError, load_config from openadapt_flow.agent_guard.handoff import HandoffError, handoff + from openadapt_flow.agent_guard.readback import load_provider from openadapt_flow.agent_guard.session import guard_task from openadapt_flow.guard import GuardRefused, load_task from openadapt_flow.interactive_recorder import ( @@ -112,8 +119,10 @@ def cmd_guard(args: argparse.Namespace) -> int: if args.approval: cfg = replace(cfg, approval=args.approval) task = load_task(args.task) + cfg = replace(cfg, ledger_row=args.ledger_row) + readback = load_provider(cfg.readback_provider, task.params) validate_browser_cdp_endpoint(args.cdp) - except (ConfigError, GuardRefused, BrowserAttachError) as exc: + except (ConfigError, GuardRefused, BrowserAttachError, ValueError) as exc: print(f"guard: {getattr(exc, 'message', exc)}", file=sys.stderr) return 2 out = Path(args.out) @@ -149,6 +158,7 @@ def _stop(signum: int, _frame: Any) -> None: timeout_s=args.timeout, attach_wait_s=args.attach_wait, secret_fields=tuple(args.secret), + readback=readback, on_attached=lambda: print( "guard: attached; saves are held until the right record is on screen", file=sys.stderr, diff --git a/packages/flow/openadapt_flow/agent_guard/commit_guard.py b/packages/flow/openadapt_flow/agent_guard/commit_guard.py index 05b59e7a74..663c8b0249 100644 --- a/packages/flow/openadapt_flow/agent_guard/commit_guard.py +++ b/packages/flow/openadapt_flow/agent_guard/commit_guard.py @@ -153,7 +153,28 @@ def __init__( events_path: Optional[Path] = None, clock: Callable[[], float] = time.monotonic, scope: Optional[Any] = None, + readback: Optional[Any] = None, + ledger_dir: Optional[Path] = None, + ledger_row: bool = True, ) -> None: + from openadapt_flow.agent_guard.readback import VerifyRunReadback + + #: How a save is read back (:class:`~.readback.ReadbackProvider`). + self.readback = readback if readback is not None else VerifyRunReadback() + #: Where ``guard_ledger_row.json`` goes; None: no row. A guard with no + #: store of its own (no ``state_dir``) and no events file writes none. + self.ledger_dir = ( + ( + ledger_dir + or ( + events_path.parent + if events_path + else getattr(guarded, "state_dir", None) + ) + ) + if ledger_row + else None + ) self.guarded = guarded #: The task's :class:`~openadapt_flow.teach_scope.TeachScope`: reads #: to an undeclared origin are blocked, and a save is read against @@ -262,7 +283,17 @@ def _commit( held_at: float, screen: Optional[str], ) -> None: - shot = self.page.screenshot() if self.guarded.approval == "each_item" else None + from openadapt_flow.agent_guard.approval_fields import card_for_request + + asked = self.guarded.approval == "each_item" or guard.source_check == "hold" + # What a person checks with no write adapter: the form as it is at + # the hold, its picture and its values, read at the same moment. + shot = self.page.screenshot() if asked else None + read_controls = getattr(self.page, "form_controls", None) + controls = read_controls() if asked and callable(read_controls) else None + guard.approval_card = card_for_request( + guard, request, self.scope, controls=controls + ) commit = guard.commit(screenshot_png=shot, screen_text=screen, wait_s=0.0) if commit.status == "waiting_for_approval": self._waiting = (guard, request, held_at) @@ -285,6 +316,8 @@ def _send( self.summary.hold_ms.append(hold_ms) if guard is not None and guard.approval is not None: self.page.clear_notice() # the "waiting for a person" notice + if guard is not None and hasattr(self.readback, "before_send"): + self.readback.before_send(self.task, guard) self.page.continue_request(request.request_id) self._log(request, "save", "continued", hold_ms=hold_ms) @@ -346,7 +379,7 @@ def poll(self) -> None: commit = guard.commit(wait_s=0.0) except GuardRefused as exc: self._waiting = None - self._refuse(request, "save", held_at, exc.code, exc.message) + self._refuse(request, "save", held_at, exc.code, exc.message, guard) return if commit.status == "go": self._waiting = None @@ -361,9 +394,13 @@ def poll(self) -> None: self._read_back(save) def _read_back(self, save: _Save) -> None: + from openadapt_flow.agent_guard import readback + from openadapt_flow.agent_guard.ledger_row import row_after_read_back + started = self._clock() + read = None if save.guard is not None: - self.result = save.guard.confirm() + self.result, read = readback.confirm(self.readback, self.task, save.guard) verdict = self.result.verdict self.summary.receipt_path = self.result.receipt_path message = self.result.what_to_do @@ -371,6 +408,15 @@ def _read_back(self, save: _Save) -> None: verdict, message = self._observe_read_back(save) self.summary.readback_ms = round((self._clock() - started) * 1000.0, 1) self.summary.verdict = verdict.value + row_after_read_back( + self.ledger_dir, + task=self.task, + guard=save.guard, + read=read, + verdict=verdict, + hold_ms=self.summary.hold_ms[-1] if self.summary.hold_ms else None, + receipt=self.observed, + ) if verdict is GuardVerdict.VERIFIED: # Nothing on the page: a verified run 1 is recorded as the app # drew it, so run 2 never expects the guard's notice. @@ -442,6 +488,7 @@ def _scope_refuse(self, request: HeldRequest, kind: str, code: str) -> None: code, "the save is not the one the task declared (another record, " "field or value)", + scope=True, ) return if self.observe_only: @@ -465,6 +512,9 @@ def _refuse( held_at: float, code: str, message: str, + guard: Optional[Guard] = None, + *, + scope: bool = False, ) -> None: if self.observe_only: self.summary.would_block.append({"code": code}) @@ -504,9 +554,19 @@ def _refuse( content_type=content_type, headers={GUARD_HEADER: f"blocked; code={code}"}, ) - self.summary.blocked.append( - {"code": code, "hold_ms": round((self._clock() - held_at) * 1000.0, 1)} - ) + hold_ms = round((self._clock() - held_at) * 1000.0, 1) + self.summary.blocked.append({"code": code, "hold_ms": hold_ms}) + if self.ledger_dir is not None: + from openadapt_flow.agent_guard.ledger_row import write_refusal_row + + write_refusal_row( + self.ledger_dir, + task=self.task, + guard=guard, + code=code, + hold_ms=hold_ms, + scope=scope, + ) self._log(request, kind, "blocked", code=code) self.page.notify( f"OpenAdapt blocked this save: {message}. {what}", level="error" diff --git a/packages/flow/openadapt_flow/agent_guard/config.py b/packages/flow/openadapt_flow/agent_guard/config.py index 895b20ca70..eabaf9b64f 100644 --- a/packages/flow/openadapt_flow/agent_guard/config.py +++ b/packages/flow/openadapt_flow/agent_guard/config.py @@ -9,6 +9,8 @@ not_saves: # optional: writes that aren't the save - {method: POST, path: /chart/signin} approval: not_gated # or each_item: a person approves each save + approval_fields: true # the card shows values beside the source + readback_provider: verify_run # optional: how a save is read back teach: # optional: compile run 1 for run 2 dir: .openadapt-teach name: triage_note @@ -51,6 +53,8 @@ "allow_origins", "allow_text", "write_adapter", + "readback_provider", + "approval_fields", } _TEACH_KEYS = { "dir", @@ -108,6 +112,15 @@ class GuardConfig: #: Values a save may carry besides the task's own (a fixed encounter #: type), for the write adapter's check. allow_text: tuple[str, ...] = () + #: How a save is read back: a kind registered as ``readback:`` + #: (:mod:`openadapt_flow.agent_guard.readback`), or a mapping with + #: ``kind``. None: ``verify_run``. + readback_provider: Optional[Any] = None + #: The approval card shows each field's value now, the value saved and + #: its source (:mod:`openadapt_flow.agent_guard.approval_fields`). + approval_fields: bool = True + #: Write ``guard_ledger_row.json`` after each read-back or refusal. + ledger_row: bool = True def __post_init__(self) -> None: if not origin_of(self.app_url).startswith(("http://", "https://")): @@ -183,9 +196,19 @@ def parse_config(raw: Mapping[str, Any], *, base: Path) -> GuardConfig: ), write_adapter=raw.get("write_adapter") or None, allow_text=tuple(str(t) for t in (raw.get("allow_text") or []) if str(t)), + readback_provider=_provider(raw.get("readback_provider")), + approval_fields=bool(raw.get("approval_fields", True)), ) +def _provider(value: Any) -> Any: + if value is None or (isinstance(value, str) and value.strip()): + return value + if isinstance(value, Mapping) and str(value.get("kind") or "").strip(): + return dict(value) + raise ConfigError("readback_provider is a kind, or a mapping with kind") + + def load_config(path: str | Path) -> GuardConfig: import yaml diff --git a/packages/flow/openadapt_flow/agent_guard/ledger_row.py b/packages/flow/openadapt_flow/agent_guard/ledger_row.py new file mode 100644 index 0000000000..59abf1d730 --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/ledger_row.py @@ -0,0 +1,473 @@ +"""One accounting row per guarded save, and the private diff behind it. + +After every read-back or refusal the commit guard writes, in the run folder: + +``guard_ledger_row.json`` (``openadapt.guard-ledger-row/v1``) + What happened to the save, with no record values: the outcome, the + names of the fields checked and of those that differ, how long the save + was held, who approved it and when, and how independent the read-back + was. An ops collector sums these rows. + +``guard_diff.private.json`` (``openadapt.guard-diff/v1``, mode 0600) + Per field: the value the task intended, the value the record held + before, the value the read-back found, and whether they differ. Raw + values, so it stays on this machine. ``openadapt-flow redact-report`` + on the run folder writes ``guard_diff.scrubbed.json`` (:func:`export_scrubbed`): + the same rows with each value replaced by a salted digest, so two copies + can still be compared without the values. + +``verdict`` is the run's outcome in the ledger's words. It is derived only +from the guard's own verdict, the one ``summary.json`` carries, or, when the +save was blocked before it was sent (``summary.json`` ``verdict`` is null), +from the refusal code in ``blocked[].code``. ``guard_verdict`` repeats the +``summary.json`` value and ``verdict_reason`` says which rule applied. The +rules (:data:`READBACK_OUTCOMES` and :func:`refusal_outcome`) use the run +ledger's reason names (``openadapt_flow.run_ledger.outcome``), so the row and +the ledger never put one run in two buckets: + +============================= ================ ========================== +Guard verdict or refusal ``verdict`` ``verdict_reason`` +============================= ================ ========================== +VERIFIED, independent tier VERIFIED readback_verified +VERIFIED, screen tier UNKNOWN screen_readback_only +VERIFIED, any other tier UNKNOWN completed_unverified +VERIFIED, but a field differs UNKNOWN readback_fields_disagree +REFUTED CAUGHT_ERROR readback_refuted +RECONCILIATION_REQUIRED UNKNOWN reconciliation_required +blocked: wrong record CAUGHT_ERROR save_blocked_wrong_record +blocked: another origin CAUGHT_ERROR save_blocked_other_origin +blocked: a second save CAUGHT_ERROR save_blocked_double_save +blocked: outside teach scope CAUGHT_ERROR save_blocked_out_of_scope +blocked: a person declined ESCALATED person_declined +blocked: nobody answered ESCALATED approval_declined +blocked: nothing to see ESCALATED values_unread +blocked: guard couldn't check FAILED policy_rejected_no_write +blocked: any other code UNKNOWN unmapped_outcome +============================= ================ ========================== + +RECONCILIATION_REQUIRED is UNKNOWN, not ESCALATED: the save was sent and +the guard can't say whether it landed, so the row doesn't claim a person +took it over. A declined approval is ESCALATED, not a caught error: a +person said no, and the row can't tell whether the save was wrong. The run +ledger decides its bucket from ``summary.json`` itself and reads only the +row's names, times and tier (contract J3); these rules only keep the row +from contradicting it. + +One row per run. A refusal after a read-back (a second save the guard +blocked) keeps the read-back's row, since that is the save that happened; +a read-back after a refusal (blocked, then saved right) replaces it. +""" + +from __future__ import annotations + +import hashlib +import json +import os +import secrets +from pathlib import Path +from typing import Any, Mapping, Optional + +from openadapt_flow.guard import GuardVerdict, _write_json + +__all__ = [ + "DIFF_FILENAME", + "DIFF_SCHEMA", + "ROW_FILENAME", + "ROW_SCHEMA", + "SCRUBBED_FILENAME", + "export_scrubbed", + "ledger_verdict", + "readback_outcome", + "refusal_outcome", + "row_after_read_back", + "write_readback_row", + "write_refusal_row", +] + +ROW_SCHEMA = "openadapt.guard-ledger-row/v1" +DIFF_SCHEMA = "openadapt.guard-diff/v1" +SCRUBBED_SCHEMA = "openadapt.guard-diff-scrubbed/v1" +ROW_FILENAME = "guard_ledger_row.json" +DIFF_FILENAME = "guard_diff.private.json" +SCRUBBED_FILENAME = "guard_diff.scrubbed.json" +ROW_KEYS = ( + "schema", + "task_id", + "verdict", + "guard_verdict", + "verdict_reason", + "fields_checked", + "fields_differing", + "hold_ms", + "approver_kind", + "approval_opened_at", + "approval_decided_at", + "readback_tier", + "diff_path", +) + +#: The guard's read-back verdict -> (ledger outcome, reason). VERIFIED is +#: decided with the read-back tier in :func:`readback_outcome`. +READBACK_OUTCOMES: dict[str, tuple[str, str]] = { + "REFUTED": ("CAUGHT_ERROR", "readback_refuted"), + "RECONCILIATION_REQUIRED": ("UNKNOWN", "reconciliation_required"), +} +#: Refusals where the guard itself could not do its job. +_FAILED_CODES = frozenset( + { + "baseline_unreadable", + "screenshot_required", + "wrong_state", + "task_invalid", + "task_unreadable", + "readback_provider_failed", + # The approval itself could not be used: a broken or replayed answer. + "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", + } +) +#: Refusals where nobody decided in time: nothing was written, a person acts. +_NOT_ANSWERED_CODES = frozenset( + {"request_expired", "approval_wait_timed_out", "approval_required"} +) +#: Refusals of a second save of the same task. +_DOUBLE_SAVE_CODES = frozenset( + { + "already_committed", + "already_saved", + "needs_reconciliation", + "save_waiting_for_person", + "approval_already_used", + } +) + + +def readback_outcome( + verdict: Optional[GuardVerdict], + *, + tier: Optional[str] = None, + differing: bool = False, +) -> tuple[str, str]: + """``(verdict, verdict_reason)`` for the guard's read-back verdict.""" + + if verdict is GuardVerdict.VERIFIED: + if differing: + # The guard and the field diff disagree: neither is trusted. + return "UNKNOWN", "readback_fields_disagree" + if tier == "independent_readback": + return "VERIFIED", "readback_verified" + if tier == "screen_readback": + return "UNKNOWN", "screen_readback_only" + return "UNKNOWN", "completed_unverified" + if verdict is None: + return "UNKNOWN", "unmapped_outcome" + return READBACK_OUTCOMES.get(verdict.value, ("UNKNOWN", "unmapped_outcome")) + + +def refusal_outcome(code: str, *, scope: bool = False) -> tuple[str, str]: + """``(verdict, verdict_reason)`` for a save the guard blocked.""" + + if scope: + return "CAUGHT_ERROR", "save_blocked_out_of_scope" + if code.startswith("identity_"): + return "CAUGHT_ERROR", "save_blocked_wrong_record" + if code == "other_origin": + return "CAUGHT_ERROR", "save_blocked_other_origin" + if code in _DOUBLE_SAVE_CODES: + return "CAUGHT_ERROR", "save_blocked_double_save" + if code == "declined": + return "ESCALATED", "person_declined" + if code == "values_unread": + # No card was offered: nobody could see the values. A person acts. + return "ESCALATED", "values_unread" + if code in _NOT_ANSWERED_CODES: + return "ESCALATED", "approval_declined" + if code in _FAILED_CODES or code.startswith(("approval_", "policy_")): + return "FAILED", "policy_rejected_no_write" + return "UNKNOWN", "unmapped_outcome" + + +def ledger_verdict( + verdict: Optional[GuardVerdict], + *, + differing: bool = False, + refusal: Optional[str] = None, + tier: Optional[str] = "independent_readback", + scope: bool = False, +) -> str: + """The ledger outcome for a read-back verdict or a refusal code.""" + + if refusal is not None: + return refusal_outcome(refusal, scope=scope)[0] + return readback_outcome(verdict, tier=tier, differing=differing)[0] + + +def _approval_times(guard: Any) -> tuple[Optional[str], Optional[str]]: + request = getattr(guard, "_request", None) if guard is not None else None + if request is None: + return None, None + if getattr(guard, "_approver", None) is None: + # The guard accepted no answer (none came, or it was refused): the + # row has no decision time, whatever file is on disk. + return request.created_at, None + decided = None + try: + from openadapt_flow.approval_mode.item_approval import ( + ItemApprovalStore, + answer_refusal, + ) + + store = ItemApprovalStore(guard.dir, key_dir=guard.owner.key_dir) + answer = store.read_answer(request.request_id) + if answer is not None and ( + answer_refusal(request, answer, policy=store.context()) is None + ): + decided = answer.answered_at + except Exception: # noqa: BLE001 - an unreadable answer: time unknown + decided = None + return request.created_at, decided + + +def _approver_kind(guard: Any) -> str: + approver = getattr(guard, "_approver", None) if guard is not None else None + if approver: + return str(approver.get("kind") or "person") + return "none" + + +def _row( + *, + task_id: str, + verdict: tuple[str, str], + guard_verdict: Optional[str], + checked: list[str], + differing: list[str], + hold_ms: Optional[float], + guard: Any, + tier: Optional[str], + diff_path: Optional[str], +) -> dict[str, Any]: + opened, decided = _approval_times(guard) + row = { + "schema": ROW_SCHEMA, + "task_id": task_id, + "verdict": verdict[0], + "guard_verdict": guard_verdict, + "verdict_reason": verdict[1], + "fields_checked": sorted(checked), + "fields_differing": sorted(differing), + "hold_ms": hold_ms, + "approver_kind": _approver_kind(guard), + "approval_opened_at": opened, + "approval_decided_at": decided, + "readback_tier": tier, + "diff_path": diff_path, + } + return row + + +def write_readback_row( + out_dir: Path, + *, + task: Any, + guard: Any, + saved: Mapping[str, Optional[str]], + differing: list[str], + verdict: GuardVerdict, + tier: Optional[str], + hold_ms: Optional[float], +) -> dict[str, Any]: + """Write the diff (0600) and the row after a read-back. Returns the row.""" + + before: dict[str, Optional[str]] = {} + card = getattr(guard, "approval_card", None) if guard is not None else None + for item in getattr(card, "fields", None) or []: + before[item.label] = item.before + rows = [] + for name in sorted(task.intended_fields): + found = saved.get(name) + rows.append( + { + "field": name, + "intended": str(task.intended_fields[name]), + "before": before.get(name), + "saved": found, + "status": ( + "not_read" + if found is None + else ("differs" if name in differing else "same") + ), + } + ) + out = Path(out_dir) + _write_json( + out / DIFF_FILENAME, + { + "schema": DIFF_SCHEMA, + "task_id": task.task_id, + "guard_id": getattr(guard, "guard_id", None), + "readback_tier": tier, + "fields": rows, + }, + ) + row = _row( + task_id=task.task_id, + verdict=readback_outcome(verdict, tier=tier, differing=bool(differing)), + guard_verdict=verdict.value, + checked=[r["field"] for r in rows if r["status"] != "not_read"], + differing=differing, + hold_ms=hold_ms, + guard=guard, + tier=tier, + diff_path=DIFF_FILENAME, + ) + _write_json(out / ROW_FILENAME, row) + return row + + +def row_after_read_back( + out_dir: Optional[Path], + *, + task: Any, + guard: Any, + read: Any, + verdict: GuardVerdict, + hold_ms: Optional[float], + receipt: Optional[Mapping[str, Any]] = None, +) -> Optional[dict[str, Any]]: + """The commit guard's one call after a read-back. ``read`` is the + provider's :class:`~openadapt_flow.agent_guard.readback.ReadbackResult`, + or None (observe-only: ``receipt`` is the verify-run document).""" + + if out_dir is None: + return None + from openadapt_flow.agent_guard.readback import differing_fields + + if read is not None: + saved, tier = dict(read.fields), read.tier + else: + saved = {name: None for name in task.intended_fields} + tier = ((receipt or {}).get("receipt") or {}).get("verification_tier") + try: + return write_readback_row( + out_dir, + task=task, + guard=guard, + saved=saved, + differing=differing_fields(task, saved), + verdict=verdict, + tier=tier, + hold_ms=hold_ms, + ) + except OSError: + # The accounting row is lost, never the guard's verdict or notice. + return None + + +def write_refusal_row( + out_dir: Path, + *, + task: Any, + guard: Any, + code: str, + hold_ms: Optional[float], + scope: bool = False, +) -> Optional[dict[str, Any]]: + """Write the row for a save the guard refused. Nothing was written. + + A row a read-back already wrote in this run is kept (returns None). + """ + + if _has_read_back(Path(out_dir) / ROW_FILENAME): + return None + row = _row( + task_id=task.task_id, + verdict=refusal_outcome(code, scope=scope), + guard_verdict=None, + checked=[], + differing=[], + hold_ms=hold_ms, + guard=guard, + tier=None, + diff_path=None, + ) + try: + _write_json(Path(out_dir) / ROW_FILENAME, row) + except OSError: + return None + return row + + +def _has_read_back(path: Path) -> bool: + try: + if path.is_symlink() or not path.is_file(): + return False + row = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return False + return isinstance(row, dict) and row.get("diff_path") is not None + + +def export_scrubbed(run_dir: Path) -> Optional[Path]: + """Write ``guard_diff.scrubbed.json`` next to the private diff, or None. + + Each value becomes a digest salted once per export (the salt is not + kept), so equal values still look equal within the copy and nothing can + be looked up. Field names and statuses stay. The copy then goes through + the report redaction (:func:`openadapt_flow.report_redaction.redact_report`) + so a credential-like name is scrubbed as in a report. + """ + + from openadapt_flow.report_redaction import load_policy, redact_report + + run = Path(run_dir) + source = run / DIFF_FILENAME + if source.is_symlink() or not source.is_file(): + return None + try: + diff = json.loads(source.read_text(encoding="utf-8")) + except (OSError, ValueError): + return None + if not isinstance(diff, dict) or diff.get("schema") != DIFF_SCHEMA: + return None + salt = secrets.token_bytes(16) + + def digest(value: Any) -> Optional[str]: + if value is None: + return None + mac = hashlib.sha256(salt + str(value).encode("utf-8")).hexdigest()[:16] + return "salted:" + mac + + rows = [ + { + "field": str(item.get("field")), + "status": str(item.get("status")), + **{k: digest(item.get(k)) for k in ("intended", "before", "saved")}, + } + for item in diff.get("fields") or [] + if isinstance(item, dict) + ] + copy = { + "schema": SCRUBBED_SCHEMA, + "task_id": diff.get("task_id"), + "readback_tier": diff.get("readback_tier"), + "fields": rows, + } + redacted, _found = redact_report(copy, load_policy(), by="redact-report") + out = run / SCRUBBED_FILENAME + tmp = out.with_name(out.name + ".tmp") + fd = os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600) + with os.fdopen(fd, "w", encoding="utf-8") as fh: + json.dump(redacted, fh, indent=2, sort_keys=True) + os.replace(tmp, out) + return out diff --git a/packages/flow/openadapt_flow/agent_guard/readback.py b/packages/flow/openadapt_flow/agent_guard/readback.py new file mode 100644 index 0000000000..9529886e2e --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/readback.py @@ -0,0 +1,343 @@ +"""How the commit guard reads a save back: the :class:`ReadbackProvider` seam. + +After the agent's save goes through, the commit guard asks a provider what +the system of record now holds. A provider returns a :class:`ReadbackResult`: +its ``tier`` (how independent the read was), the saved value of each task +field it could read (``None``: not read), its verdict and its evidence. + +:class:`VerifyRunReadback`, the default, is today's path unchanged: +:meth:`Guard.confirm ` runs +``verify-run`` and its receipt decides. It also reads the record once more +through the same ``verify.yaml`` reader, so the ledger can show which fields +differ from what the task intended. + +:func:`rule` makes the final verdict, and no provider can get past it: + +* only an ``independent_readback`` may be ``VERIFIED``; a ``screen_readback`` + (or anything weaker) that says verified is ``RECONCILIATION_REQUIRED``; +* a field the read shows with a value other than the task's is a refutation, + and nothing (a provider, a model) turns that back into ``VERIFIED``. + +Another provider (an app's own API, a second session) is named in +``guard.yaml`` as ``readback_provider: `` and registered through +:func:`openadapt_flow.runtime.effects.register_verifier_factory` under the +kind ``readback:``. The factory is called with the ``readback_provider`` +mapping and the task's parameters and must return a provider. +""" + +from __future__ import annotations + +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Literal, Mapping, Optional, Protocol, Sequence + +from openadapt_flow.guard import ( + Guard, + GuardResult, + GuardTask, + GuardVerdict, + _write_json, +) + +__all__ = [ + "KIND_PREFIX", + "ReadbackProvider", + "ReadbackResult", + "VerifyRunReadback", + "confirm", + "differing_fields", + "load_provider", + "rule", + "same_value", +] + +Tier = Literal["independent_readback", "screen_readback", "unchecked"] +TIERS = ("independent_readback", "screen_readback", "unchecked") +#: The registry kind a readback provider factory is registered under. +KIND_PREFIX = "readback:" + + +@dataclass(frozen=True) +class ReadbackResult: + """What one read-back of one save found.""" + + tier: str + #: Task field name -> the value the read shows, or None when not read. + fields: Mapping[str, Optional[str]] + #: Ids, codes and paths only (a receipt path, a reason). No values. + evidence: Mapping[str, Any] = field(default_factory=dict) + #: The provider's own verdict, before :func:`rule`. + verdict: GuardVerdict = GuardVerdict.RECONCILIATION_REQUIRED + #: Set by :class:`VerifyRunReadback`: the guard's own result. + guard_result: Optional[GuardResult] = None + + +class ReadbackProvider(Protocol): + """Reads one committed save back from the system of record.""" + + def read(self, task: GuardTask, guard: Guard) -> ReadbackResult: ... + + +def same_value(intended: Any, saved: str) -> bool: + """Whether two values are the same by the provenance value comparison.""" + + from openadapt_flow.runtime.effects.readback_values import infer_value_kind + + a = "" if intended is None else str(intended) + try: + from openadapt_flow.provenance import same_value as _provenance_same + + return _provenance_same(a, saved, infer_value_kind(a)) + except Exception: # noqa: BLE001 - an unusual value: compare exactly + return a.strip() == saved.strip() + + +def differing_fields(task: GuardTask, saved: Mapping[str, Optional[str]]) -> list[str]: + """Task fields the read shows with another value. Unread ones don't count.""" + + return sorted( + name + for name, value in saved.items() + if name in task.intended_fields + and value is not None + and not same_value(task.intended_fields[name], value) + ) + + +def rule(task: GuardTask, result: ReadbackResult) -> GuardVerdict: + """The final verdict. Fail closed; see the module docstring.""" + + if differing_fields(task, result.fields): + return GuardVerdict.REFUTED + verdict = result.verdict + if verdict is GuardVerdict.VERIFIED and result.tier != "independent_readback": + return GuardVerdict.RECONCILIATION_REQUIRED + return verdict + + +def _saved_fields( + task: GuardTask, + verify: Any, + before: Optional[Sequence[Mapping[str, Any]]], +) -> dict[str, Optional[str]]: + """The saved value of each task field, read again from the record reader. + + The saved record is the one record of the task's record that is new or + changed since ``before``. Anything else (no read, no change, two + candidates) leaves every field unread. + """ + + from openadapt_flow.agent_guard.approval_fields import ( + bound_fields, + matching_records, + read_records, + ) + + unread: dict[str, Optional[str]] = {n: None for n in task.intended_fields} + bound = bound_fields(verify) + after = matching_records( + read_records(verify, task.params), task.expected_record, bound + ) + prior = matching_records(before, task.expected_record, bound) + if after is None or prior is None: + return unread + import json + + def key(row: Mapping[str, Any]) -> str: + return json.dumps(row, sort_keys=True, default=str) + + left = [key(r) for r in prior] + changed = [] + for row in after: + k = key(row) + if k in left: + left.remove(k) + else: + changed.append(row) + if len(changed) != 1: + return unread + row = changed[0] + return { + name: ( + None + if bound.get(name) not in row or row.get(bound[name]) is None + else str(row.get(bound[name])) + ) + for name in task.intended_fields + } + + +class VerifyRunReadback: + """The default provider: ``Guard.confirm`` (verify-run), unchanged.""" + + def __init__(self) -> None: + self._before: dict[str, Optional[list[dict]]] = {} + + def before_send(self, task: GuardTask, guard: Guard) -> None: + """Read the task's record just before the save goes on.""" + + from openadapt_flow.agent_guard.approval_fields import read_records + + self._before[guard.guard_id] = read_records(guard.owner.verify, task.params) + + def read(self, task: GuardTask, guard: Guard) -> ReadbackResult: + result = guard.confirm() + receipt = (result.receipt or {}).get("receipt") or {} + tier = str(receipt.get("verification_tier") or "unchecked") + saved = ( + _saved_fields(task, guard.owner.verify, self._before.pop(guard.guard_id)) + if guard.guard_id in self._before + else {n: None for n in task.intended_fields} + ) + return ReadbackResult( + tier=tier if tier in TIERS else "unchecked", + fields=saved, + evidence={ + "receipt_path": result.receipt_path, + "outcome": result.outcome, + "reason": result.reason, + }, + verdict=result.verdict, + guard_result=result, + ) + + +#: ``GuardResult.outcome`` (and ``guard.json``'s ``outcome``) when the guard's +#: verdict overrides the verify-run receipt's. +OVERRIDDEN = "overridden" +#: Written next to a receipt the guard overrode: ``.override.json``. +OVERRIDE_SCHEMA = "openadapt.guard-receipt-override/v1" + + +def _mark_overridden( + receipt: Path, receipt_outcome: str, verdict: GuardVerdict, reason: Optional[str] +) -> None: + import hashlib + + try: + digest = "sha256:" + hashlib.sha256(receipt.read_bytes()).hexdigest() + except OSError: + digest = None + _write_json( + receipt.with_name(receipt.stem + ".override.json"), + { + "schema": OVERRIDE_SCHEMA, + "receipt": receipt.name, + "receipt_sha256": digest, + "receipt_outcome": receipt_outcome, + "guard_verdict": verdict.value, + "reason": reason, + }, + ) + + +def settle(guard: Guard, result: ReadbackResult, verdict: GuardVerdict) -> GuardResult: + """Record the final verdict on the guard and its task ledger. + + The default provider already confirmed the guard; it is rewritten only + when :func:`rule` made the verdict stricter. + """ + + prior = result.guard_result + if prior is not None and prior.verdict is verdict: + return prior + evidence = dict(result.evidence) + reason: Optional[str] + if differing_fields(guard.task, result.fields): + reason = "readback:fields_differ" + elif prior is not None or verdict is not result.verdict: + reason = f"readback:tier_{result.tier}" + else: + reason = evidence.get("reason") + receipt_path = ( + prior.receipt_path if prior is not None else evidence.get("receipt_path") + ) + outcome = prior.outcome if prior is not None else evidence.get("outcome") + overridden = prior is not None or verdict is not result.verdict + if overridden and receipt_path and outcome is not None: + # The receipt on disk keeps the outcome verify-run signed; the guard's + # stricter verdict is written beside it, and the guard's own record + # says the receipt was overridden, so no file reads as verified alone. + _mark_overridden(Path(receipt_path), outcome, verdict, reason) + outcome = OVERRIDDEN + final = GuardResult( + verdict=verdict, + guard_id=guard.guard_id, + task_id=guard.task.task_id, + outcome=outcome, + receipt_path=receipt_path, + receipt=prior.receipt if prior is not None else None, + reason=reason, + ) + guard.result = final + _write_json( + guard.owner._ledger(guard.task.task_id), + {"guard_id": guard.guard_id, "state": "confirmed", "verdict": verdict.value}, + ) + guard._save("confirmed", reason) + return final + + +def load_provider(spec: Any, params: Mapping[str, Any]) -> ReadbackProvider: + """The provider ``guard.yaml`` names. Raises ValueError (fail closed).""" + + if spec is None: + return VerifyRunReadback() + config: Mapping[str, Any] = spec if isinstance(spec, Mapping) else {"kind": spec} + kind = str(config.get("kind") or "").strip().lower() + if kind in ("", "verify_run"): + return VerifyRunReadback() + from openadapt_flow.runtime.effects.adapter import resolve_verifier_factory + + factory = resolve_verifier_factory(KIND_PREFIX + kind) + if factory is None: + raise ValueError( + f"no readback provider is registered as {KIND_PREFIX}{kind} " + "(register_verifier_factory)" + ) + provider = factory(dict(config), dict(params)) + if not callable(getattr(provider, "read", None)): + raise ValueError(f"{KIND_PREFIX}{kind} did not build a readback provider") + return provider # type: ignore[no-any-return] + + +def confirm( + provider: ReadbackProvider, task: GuardTask, guard: Guard +) -> tuple[GuardResult, Optional[ReadbackResult]]: + """Read the save back through ``provider`` and settle the final verdict. + + A provider that fails is a read that didn't happen: the save may have + landed, so the verdict is ``RECONCILIATION_REQUIRED``, never a retry. + """ + + try: + result = provider.read(task, guard) + if not isinstance(result, ReadbackResult): + raise TypeError("a readback provider returns a ReadbackResult") + except Exception as exc: # noqa: BLE001 - fail closed + unread = {n: None for n in task.intended_fields} + prior = guard.result + if prior is not None: + # verify-run already ran; the provider failed after it. Its + # verdict stands only under the same tier rule. + receipt = (prior.receipt or {}).get("receipt") or {} + tier = str(receipt.get("verification_tier") or "unchecked") + kept = ReadbackResult( + tier=tier if tier in TIERS else "unchecked", + fields=unread, + evidence={ + "receipt_path": prior.receipt_path, + "outcome": prior.outcome, + "reason": prior.reason, + }, + verdict=prior.verdict, + guard_result=prior, + ) + return settle(guard, kept, rule(task, kept)), kept + failed = ReadbackResult( + tier="unchecked", + fields=unread, + evidence={"reason": "readback_provider_failed:" + type(exc).__name__}, + ) + return settle(guard, failed, GuardVerdict.RECONCILIATION_REQUIRED), failed + return settle(guard, result, rule(task, result)), result diff --git a/packages/flow/openadapt_flow/agent_guard/screen_values.py b/packages/flow/openadapt_flow/agent_guard/screen_values.py new file mode 100644 index 0000000000..6dbf431c0e --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/screen_values.py @@ -0,0 +1,164 @@ +"""What the agent's form shows at the moment its save is held. + +With no write adapter the guard can't read the values a save sends. A +careful person then checks the screen: the filled form, and each field's +value on it. :data:`READ_CONTROLS_JS` reads the page's form controls the way +the readiness check reads them (``agent_guard/cdp.py`` on the shadow-hold +branch, ``_READ_FORM_VALUES``): ``input``, ``select``, ``textarea`` and +``contenteditable`` values in document order, leaving out password, hidden, +file and button inputs. It also keeps each control's label (its ``