From b22d64812ab31f80d0f852ee8f9de0a50920f872 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 12:18:55 -0500 Subject: [PATCH 01/15] feat(guard): approval card values beside the source, ReadbackProvider seam, per-save ledger row --- CAPABILITIES.md | 4 +- llms-full.txt | 4 +- .../openadapt_desktop/portal/shell/app.js | 45 ++- .../openadapt_desktop/portal/shell/index.html | 1 + .../tests/test_guard_request_pickup.py | 206 ++++++++++ packages/flow/docs/GUARD_AN_AGENT.md | 68 ++++ .../guard.md | 2 +- .../agent_guard/approval_fields.py | 337 ++++++++++++++++ .../flow/openadapt_flow/agent_guard/cli.py | 12 +- .../agent_guard/commit_guard.py | 47 ++- .../flow/openadapt_flow/agent_guard/config.py | 23 ++ .../openadapt_flow/agent_guard/ledger_row.py | 371 ++++++++++++++++++ .../openadapt_flow/agent_guard/readback.py | 303 ++++++++++++++ .../openadapt_flow/agent_guard/session.py | 13 +- .../flow/openadapt_flow/cli_redact_report.py | 7 + .../openadapt_flow/console/save_approvals.py | 7 + packages/flow/openadapt_flow/guard.py | 19 + .../tests/e2e/test_agent_guard_fields_e2e.py | 108 +++++ .../flow/tests/test_guard_approval_fields.py | 191 +++++++++ packages/flow/tests/test_guard_ledger_row.py | 281 +++++++++++++ .../tests/test_guard_readback_provider.py | 235 +++++++++++ 21 files changed, 2267 insertions(+), 17 deletions(-) create mode 100644 packages/desktop/tests/test_guard_request_pickup.py create mode 100644 packages/flow/openadapt_flow/agent_guard/approval_fields.py create mode 100644 packages/flow/openadapt_flow/agent_guard/ledger_row.py create mode 100644 packages/flow/openadapt_flow/agent_guard/readback.py create mode 100644 packages/flow/tests/e2e/test_agent_guard_fields_e2e.py create mode 100644 packages/flow/tests/test_guard_approval_fields.py create mode 100644 packages/flow/tests/test_guard_ledger_row.py create mode 100644 packages/flow/tests/test_guard_readback_provider.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 77cb5b857c..ab9cb9c1b4 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -323,7 +323,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 saved and its source; each save gets a ledger row with no values and a 0600 diff, and 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)) | Synthetic (MockMed, scripted Playwright agent, `effect_e2e` faults) | `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) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](packages/flow/docs/THREAT_MODEL.md) | @@ -486,7 +486,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. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/llms-full.txt b/llms-full.txt index cfb52865db..19df5c745a 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -763,7 +763,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 saved and its source; each save gets a ledger row with no values and a 0600 diff, and 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)) | 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) | | 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) | | Task ledger per job: rules locked when the job opens and enforced on every run, item status set only from OpenAdapt's own results, and yes-or-no questions a person answers on the phone or in Desktop, including when a run stops | Released ([#1332](https://github.com/OpenAdaptAI/OpenAdapt/pull/1332)) | Synthetic (30-item MockMed worklist, scripted agent, no model calls) | MCP tools `open_job`, `get_job`, `add_items`, `record_evidence`, `ask_user`, `get_answer`, `change_constraint`, `close_job`; [Track a long job](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/agent/README.md#track-a-long-job) | | Limit a teaching agent to the declared task on every teach path (`compile_agent`, `compile-agent`, teach over MCP, the airbag guard): typed text must be a declared value, links and browser requests to other origins are refused, writes are checked before they are sent, and the record is read back before a draft exists. Injected instructions in record notes, banners, tooltips, alt text and server responses are blocked or caught on MockMed through each path (scripted agent; a live-model mode is off by default). Self-repair refuses a control that leaves the app | Released ([#1359](https://github.com/OpenAdaptAI/OpenAdapt/pull/1359), [#1386](https://github.com/OpenAdaptAI/OpenAdapt/pull/1386)) | Synthetic | `openadapt_flow.teach_scope`, [THREAT_MODEL.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/THREAT_MODEL.md) | @@ -926,7 +926,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. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/packages/desktop/openadapt_desktop/portal/shell/app.js b/packages/desktop/openadapt_desktop/portal/shell/app.js index 36fc233c0c..62f3aa19c6 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/app.js +++ b/packages/desktop/openadapt_desktop/portal/shell/app.js @@ -971,6 +971,25 @@ function saveFields(presentation) { })); } +// `presentation.sources`: a guarded save's source column, `{label, source, +// status, differs}` per field, kept by Flow beside the request and bound to its digest. +// 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", + ); + if (!ok) return null; + return new Map(raw.map((row) => [row.label, { source: row.source, differs: row.differs }])); +} + // `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 @@ -1032,6 +1051,7 @@ async function openSave(item) { presentation.explanation || "Before it saves, OpenAdapt reads the form again. If anything changed, it stops and asks again.", fields: saveFields(presentation), + sources: saveSources(presentation), provenance: saveProvenance(presentation), frameUrl: null, frameOk: false, @@ -1183,17 +1203,32 @@ 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. + return `${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("")}${ + unread ? '

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

' : "" + }`; } function provenanceMarkup(card) { 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/tests/test_guard_request_pickup.py b/packages/desktop/tests/test_guard_request_pickup.py new file mode 100644 index 0000000000..5373b6e25b --- /dev/null +++ b/packages/desktop/tests/test_guard_request_pickup.py @@ -0,0 +1,206 @@ +"""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, from the guard's request. + assert presentation["fields"] == [{"label": "note", "before": None, "after": NOTE}] + + +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/flow/docs/GUARD_AN_AGENT.md b/packages/flow/docs/GUARD_AN_AGENT.md index 77b78b0d7d..dae8bd22ed 100644 --- a/packages/flow/docs/GUARD_AN_AGENT.md +++ b/packages/flow/docs/GUARD_AN_AGENT.md @@ -139,6 +139,66 @@ 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. The card they answer (Desktop +or the paired phone) lists every field the task writes: + +| 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 task's `intended_fields` value, or, with `write_adapter`, the value the held request carries. | +| 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 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. +None of these values leave the computer: 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`, `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` is `VERIFIED`, `CAUGHT_ERROR` (a blocked save, a declined approval, +or a read-back that shows another value or another write), `ESCALATED` (the +save went through and couldn't be confirmed) or `FAILED` (the guard couldn't +do its job, for example the system of record couldn't be read before the +save). + +`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. + +`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`. + ## Run 2: a program from run 1 With a `teach:` section, a run that reads back `VERIFIED` is handed to the @@ -264,6 +324,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. 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..c119910bc5 --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/approval_fields.py @@ -0,0 +1,337 @@ +"""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 task says to write, or, when the app's write + adapter is configured, the value the held request actually carries. +* ``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. + +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", + "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 + + def to_dict(self) -> dict[str, Any]: + return { + "label": self.label, + "source": self.source, + "status": self.status, + "differs": self.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) + + def intent_note(self) -> str: + """The sentence the card's intent carries when something is unread.""" + + if not self.not_covered: + return "" + return ". Not read, so this approval does not cover: " + ", ".join( + sorted(self.not_covered) + ) + + +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, +) -> 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. ``records`` is a read the caller + already made; otherwise one is made now when ``read``. + """ + + 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) + if claim_fields is not None: + if name in claim_fields and claim_fields[name] is not None: + after = _text(claim_fields[name]) + else: + after = NOT_READ + if name not in not_covered: + not_covered.append(name) + else: + after = _text(task.intended_fields[name]) + rows.append(SaveField(label=name[:128], before=before, after=after)) + row = sources.get(name) or SourceRow(name, None, "no_source") + row = replace(row, differs=_source_differs(row, after)) + 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:]) + return ApprovalCard(fields=rows, sources=source_rows, not_covered=not_covered) + + +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), + }, + ) + 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 + 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, + } + ) + return rows + + +def card_for_request(guard: Any, request: Any, scope: Any) -> Any: + """The commit guard's card for a held save, with the values the request + carries when the app's write adapter can read them. None: let the guard + build the task's card itself (or none, when the card is turned off).""" + + owner = guard.owner + asked = owner.approval == "each_item" or guard.source_check == "hold" + adapter = getattr(scope, "write_adapter", None) if scope is not None else None + if not owner.approval_fields or not asked or adapter is None: + return None + try: + body = request.post_data.encode("utf-8") if request.post_data else None + claim = adapter.claim(request.method, request.url, body) + claimed = dict(claim.fields) if claim is not None else {} + except Exception: # noqa: BLE001 - unread: every value shows not read + claimed = {} + return build_card(guard.task, owner.verify, claim_fields=claimed) 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..e1f1f476d2 100644 --- a/packages/flow/openadapt_flow/agent_guard/commit_guard.py +++ b/packages/flow/openadapt_flow/agent_guard/commit_guard.py @@ -153,7 +153,20 @@ 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. + self.ledger_dir = ( + (ledger_dir or (events_path.parent if events_path else guarded.state_dir)) + 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,6 +275,9 @@ def _commit( held_at: float, screen: Optional[str], ) -> None: + from openadapt_flow.agent_guard.approval_fields import card_for_request + + guard.approval_card = card_for_request(guard, request, self.scope) shot = self.page.screenshot() if self.guarded.approval == "each_item" else None commit = guard.commit(screenshot_png=shot, screen_text=screen, wait_s=0.0) if commit.status == "waiting_for_approval": @@ -285,6 +301,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 +364,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 +379,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 +393,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. @@ -465,6 +496,7 @@ def _refuse( held_at: float, code: str, message: str, + guard: Optional[Guard] = None, ) -> None: if self.observe_only: self.summary.would_block.append({"code": code}) @@ -504,9 +536,14 @@ 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 + ) 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..d2f9041343 --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/ledger_row.py @@ -0,0 +1,371 @@ +"""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: + +* ``VERIFIED``: an independent read-back shows exactly the intended write. +* ``CAUGHT_ERROR``: the guard stopped or caught a wrong save: a wrong record + on screen, a second save, a declined approval, or a read-back that shows + another value or another write (``REFUTED``). +* ``ESCALATED``: the save went through and could not be confirmed + (``RECONCILIATION_REQUIRED``), or nobody answered its approval before it + expired; a person checks the record. +* ``FAILED``: the guard could not do its job (the store couldn't be read + before the save, the approval couldn't be asked, or its answer was + unusable). + +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", + "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", + "fields_checked", + "fields_differing", + "hold_ms", + "approver_kind", + "approval_opened_at", + "approval_decided_at", + "readback_tier", + "diff_path", +) + +#: 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", + } +) +#: Refusals where nobody decided in time: nothing was written, a person acts. +_ESCALATED_CODES = frozenset({"request_expired"}) + + +def ledger_verdict( + verdict: Optional[GuardVerdict], + *, + differing: bool = False, + refusal: Optional[str] = None, +) -> str: + """The ledger outcome for a read-back verdict or a refusal code.""" + + if refusal is not None: + if refusal in _ESCALATED_CODES: + return "ESCALATED" + if refusal in _FAILED_CODES or refusal.startswith(("approval_", "policy_")): + return "FAILED" + return "CAUGHT_ERROR" + if differing or verdict is GuardVerdict.REFUTED: + return "CAUGHT_ERROR" + if verdict is GuardVerdict.VERIFIED: + return "VERIFIED" + return "ESCALATED" + + +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 + decided = None + try: + from openadapt_flow.approval_mode.item_approval import ItemApprovalStore + + answer = ItemApprovalStore(guard.dir, key_dir=guard.owner.key_dir).read_answer( + request.request_id + ) + decided = answer.answered_at if answer is not None else None + 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: 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, + "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=ledger_verdict(verdict, differing=bool(differing)), + 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], +) -> 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=ledger_verdict(None, refusal=code), + 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..947c361a9a --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/readback.py @@ -0,0 +1,303 @@ +"""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 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, + ) + + +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) + 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") + final = GuardResult( + verdict=verdict, + guard_id=guard.guard_id, + task_id=guard.task.task_id, + outcome=prior.outcome if prior is not None else evidence.get("outcome"), + receipt_path=( + prior.receipt_path if prior is not None else evidence.get("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/session.py b/packages/flow/openadapt_flow/agent_guard/session.py index ab96c2bd09..6a4d46ed85 100644 --- a/packages/flow/openadapt_flow/agent_guard/session.py +++ b/packages/flow/openadapt_flow/agent_guard/session.py @@ -223,6 +223,7 @@ def guard_task( on_attached: Optional[Callable[[], None]] = None, on_recorded: Optional[Callable[[int], None]] = None, stop: Optional[Callable[[], bool]] = None, + readback: Optional[Any] = None, ) -> GuardRun: """Guard one task's save in the agent's own browser and record the run. @@ -253,9 +254,16 @@ def guard_task( # The save is still read back by verify-run; only the # recording's record snapshots are missing. notes.append(f"no record snapshots in the recording: {exc}") + from openadapt_flow.agent_guard.readback import load_provider + guarded = GuardedSave( - load_verify_config(cfg.verify), out / "guard", approval=cfg.approval + load_verify_config(cfg.verify), + out / "guard", + approval=cfg.approval, + approval_fields=cfg.approval_fields, ) + if readback is None: + readback = load_provider(cfg.readback_provider, task.params) started = time.monotonic() pw, browser, tab = _connect( cfg, cdp_endpoint=cdp_endpoint, page_url=page_url, attach_wait_s=attach_wait_s @@ -279,6 +287,9 @@ def guard_task( response_wait_s=cfg.response_wait_s, events_path=out / "guard_events.jsonl", scope=scope, + readback=readback, + ledger_dir=out, + ledger_row=cfg.ledger_row, ) if record: recorder = _RecorderThread( diff --git a/packages/flow/openadapt_flow/cli_redact_report.py b/packages/flow/openadapt_flow/cli_redact_report.py index 1b64f952ca..afaaff3bfd 100644 --- a/packages/flow/openadapt_flow/cli_redact_report.py +++ b/packages/flow/openadapt_flow/cli_redact_report.py @@ -10,6 +10,7 @@ def _cmd_redact_report(args: argparse.Namespace) -> int: + from openadapt_flow.agent_guard.ledger_row import export_scrubbed from openadapt_flow.report_redaction import ( RedactionPolicyError, RedactRunError, @@ -17,6 +18,12 @@ def _cmd_redact_report(args: argparse.Namespace) -> int: redact_run, ) + # A guarded run's private diff: a scrubbed copy, written next to it. + scrubbed = export_scrubbed(Path(args.run_dir)) + if scrubbed is not None: + print(f"scrubbed guard diff: {scrubbed}", file=sys.stderr) + if not (Path(args.run_dir) / "report.json").is_file(): + return 0 try: policy = load_policy(Path(args.policy) if args.policy else None) result = redact_run(Path(args.run_dir), policy) diff --git a/packages/flow/openadapt_flow/console/save_approvals.py b/packages/flow/openadapt_flow/console/save_approvals.py index 624fe77d5c..9499d65276 100644 --- a/packages/flow/openadapt_flow/console/save_approvals.py +++ b/packages/flow/openadapt_flow/console/save_approvals.py @@ -293,6 +293,13 @@ def save_approval_detail(root: Path, request_id: str) -> dict[str, Any]: presentation["fields"] = [ field.model_dump(mode="json") for field in request.fields ] + # A guarded save's source column, kept beside the request and bound + # to its digest (agent_guard/approval_fields.py). Local only. + from openadapt_flow.agent_guard.approval_fields import read_sources_for + + sources = read_sources_for(run_dir, request) + if sources: + presentation["sources"] = sources if request.workflow_name == LEDGER_QUESTION_WORKFLOW: # An agent's question from its task ledger, not a save. Approve is # yes and decline is no; the answer saves nothing in any app. diff --git a/packages/flow/openadapt_flow/guard.py b/packages/flow/openadapt_flow/guard.py index 4fd94303da..08724a801d 100644 --- a/packages/flow/openadapt_flow/guard.py +++ b/packages/flow/openadapt_flow/guard.py @@ -317,6 +317,9 @@ class GuardedSave: config_only: bool = False #: A roster head from the deployment config the roster must extend. config_head: Optional[tuple[int, str]] = None + #: Show each field's value now, the value saved and its source on the + #: approval card (:mod:`openadapt_flow.agent_guard.approval_fields`). + approval_fields: bool = True def __post_init__(self) -> None: if self.approval not in APPROVAL_MODES: @@ -422,6 +425,9 @@ class Guard: source_check: Optional[str] = None source_held_fields: list[str] = field(default_factory=list) result: Optional[GuardResult] = None + #: The approval card's rows (``approval_fields.ApprovalCard``); built at + #: the first approval request when unset. + approval_card: Any = field(default=None, repr=False) _request: Any = field(default=None, repr=False) _approver: Optional[dict[str, str]] = field(default=None, repr=False) _policy_ref: str = field(default="", repr=False) @@ -518,6 +524,7 @@ def _await_approval( reason: Optional[str] = None, screen_text: Optional[str] = None, ) -> Optional[CommitResult]: + from openadapt_flow.agent_guard.approval_fields import write_sources from openadapt_flow.approval_mode.approver import DEFAULT_APPROVER_POLICY from openadapt_flow.approval_mode.item_approval import ( ItemApprovalRefused, @@ -544,6 +551,7 @@ def _await_approval( "a person approves this save; commit needs the screenshot " "they will be shown", ) + card = self._card() try: # Person-only, pinned before anything is asked; the agent that # started this guard is recorded so it can never answer it. @@ -566,6 +574,7 @@ def _await_approval( if self.source_check == "hold" else "" ) + + (card.intent_note() if card is not None else "") ), mode=ApprovalMode.EACH_ITEM, bundle_content_digest=None, @@ -573,7 +582,10 @@ def _await_approval( frame_png=screenshot_png, form_state=("dom", "sha256:" + _sha256_hex(self.task.params)), provenance=self._provenance(reason, screen_text), + fields=card.fields if card is not None else None, ) + if card is not None: + write_sources(self.dir, self._request, card) except ItemApprovalRefused as exc: self._save("refused_approval", reason=exc.code) raise GuardRefused(exc.code, str(exc)) from exc @@ -620,6 +632,13 @@ def _await_approval( } return None + def _card(self) -> Any: + if self.approval_card is None and self.owner.approval_fields: + from openadapt_flow.agent_guard.approval_fields import build_card + + self.approval_card = build_card(self.task, self.owner.verify) + return self.approval_card + def _provenance( self, reason: Optional[str], screen_text: Optional[str] ) -> dict[str, Any]: diff --git a/packages/flow/tests/e2e/test_agent_guard_fields_e2e.py b/packages/flow/tests/e2e/test_agent_guard_fields_e2e.py new file mode 100644 index 0000000000..066e4a9e41 --- /dev/null +++ b/packages/flow/tests/e2e/test_agent_guard_fields_e2e.py @@ -0,0 +1,108 @@ +"""The guard's ledger row and private diff, end to end in a real Chromium. + +A scripted Playwright agent (``benchmark/agent_guard/agent.py``) drives its +own headless browser; ``openadapt-flow guard`` runs in another process, +attached over CDP. A clean save is read back VERIFIED with a row that holds +no values; a save the agent makes with another note than the task's shows +that field as differing in the 0600 diff and is caught, not verified. + +Synthetic MockMed in front of the ``effect_e2e`` record store; localhost only. +""" + +from __future__ import annotations + +import json +import socket +from pathlib import Path + +import pytest + +pytest.importorskip("playwright") + +from benchmark.agent_guard import run as bench # noqa: E402 +from benchmark.agent_guard.app import serve # noqa: E402 + +pytestmark = pytest.mark.timeout(600) + + +def _port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def _scenario(name: str) -> bench.Scenario: + return next(s for s in bench.SCENARIOS if s.name == name) + + +def _chromium_or_skip() -> None: + from playwright.sync_api import sync_playwright + + try: + with sync_playwright() as pw: + pw.chromium.launch(headless=True).close() + except Exception as exc: # noqa: BLE001 + pytest.skip(f"chromium unavailable: {exc}") + + +def _no_values(path: Path) -> None: + data = path.read_bytes() + for value in (bench.NOTE, bench.OTHER_NOTE, "Jane Sample", "Triage"): + assert value.encode("utf-8") not in data, value + + +def test_the_ledger_row_and_diff_from_a_real_browser(tmp_path: Path) -> None: + _chromium_or_skip() + app = serve(tmp_path / "app.sqlite") + try: + files = bench.write_setup(tmp_path / "setup", app.base_url, teach_dir=None) + + ok = bench.run_one( + app, + _scenario("ok"), + "guard", + tmp_path / "run-ok", + _port(), + think_s=0.5, + files=files, + teach=False, + ) + assert ok["verdict"] == "VERIFIED", ok + row_path = tmp_path / "run-ok" / "guard_ledger_row.json" + row = json.loads(row_path.read_text()) + assert row["schema"] == "openadapt.guard-ledger-row/v1" + assert row["verdict"] == "VERIFIED" + assert row["fields_checked"] == ["note", "type"] + assert row["fields_differing"] == [] + assert row["readback_tier"] == "independent_readback" + _no_values(row_path) + diff = tmp_path / "run-ok" / "guard_diff.private.json" + assert diff.stat().st_mode & 0o777 == 0o600 + + wrong = bench.run_one( + app, + _scenario("agent_wrong_value"), + "guard", + tmp_path / "run-wrong", + _port(), + think_s=0.5, + files=files, + teach=False, + ) + assert wrong["verdict"] != "VERIFIED", wrong + assert wrong["verdict"] == "REFUTED" + assert wrong["guard_exit"] == 4 + row_path = tmp_path / "run-wrong" / "guard_ledger_row.json" + row = json.loads(row_path.read_text()) + assert row["verdict"] == "CAUGHT_ERROR" + assert row["fields_differing"] == ["note"] + _no_values(row_path) + diff = tmp_path / "run-wrong" / "guard_diff.private.json" + assert diff.stat().st_mode & 0o777 == 0o600 + by_field = {f["field"]: f for f in json.loads(diff.read_text())["fields"]} + assert by_field["note"]["intended"] == bench.NOTE + assert by_field["note"]["saved"] == bench.OTHER_NOTE + assert by_field["note"]["status"] == "differs" + assert by_field["type"]["status"] == "same" + finally: + app.stop() diff --git a/packages/flow/tests/test_guard_approval_fields.py b/packages/flow/tests/test_guard_approval_fields.py new file mode 100644 index 0000000000..54d82d30fa --- /dev/null +++ b/packages/flow/tests/test_guard_approval_fields.py @@ -0,0 +1,191 @@ +"""The guarded save's approval card: each field's value now, the value saved, +and its source, bound to the request the person answers. + +Synthetic MockMed fault server on localhost; no browser, no model calls. +""" + +from __future__ import annotations + +import json +from pathlib import Path + +import pytest + +from benchmark.harness.guard_demo import NOTE, FakeAgent, tiny_png, verify_yaml +from openadapt_flow.agent_guard.approval_fields import ( + NOT_READ, + SOURCES_FILENAME, + build_card, + read_sources_for, +) +from openadapt_flow.guard import GuardedSave, GuardTask, load_task +from openadapt_flow.mockmed.fault_server import serve as fault_serve +from openadapt_flow.verify_run import parse_verify_config + +MISREAD = "Referral to orthopaedics for knee pain" + + +@pytest.fixture +def sor(): + url, db, stop = fault_serve() + try: + yield url.rstrip("/"), db + finally: + stop() + + +def _task(task_id: str = "card-task-0001") -> GuardTask: + return GuardTask( + task_id=task_id, + expected_record={"patient_id": "p1"}, + intended_fields={"note": NOTE}, + ) + + +def _source_task(tmp_path: Path, note: str, cited: str) -> GuardTask: + """A task whose note cites a referral letter (``cited`` is the letter's).""" + + from openadapt_flow.provenance import ( + ParamProvenance, + ProvenanceFile, + SourceRef, + document_sha256, + ) + + letter = tmp_path / "referral.txt" + letter.write_text(f"Referral\nPatient: p1\nNote: {cited}\n") + prov = ProvenanceFile( + params={ + "note": ParamProvenance( + value=note, + source=SourceRef( + kind="document", + sha256=document_sha256(letter), + line=3, + label="Note", + ), + extractor="model:first-reader", + ) + } + ) + path = tmp_path / "task.json" + path.write_text( + json.dumps( + { + "schema_version": "openadapt.guard-task/v1", + "task_id": "card-source-0001", + "expected_record": {"patient_id": "p1"}, + "intended_fields": {"note": note}, + "provenance": json.loads(prov.model_dump_json()), + "sources": [letter.name], + } + ) + ) + return load_task(path) + + +def test_the_request_carries_before_after_and_source_for_each_field( + sor, tmp_path: Path +) -> None: + from openadapt_flow.console.save_approvals import ( + list_save_approvals, + save_approval_detail, + ) + + task = _source_task(tmp_path, NOTE, NOTE) + guarded = GuardedSave(parse_verify_config(verify_yaml(sor[0])), tmp_path / "g") + guard = guarded.begin(task, screen_text=FakeAgent(sor[0]).open_chart("p1")) + guard.commit(screenshot_png=tiny_png()) + request = guard._request + # A create: nothing was there before, the value saved is the task's. + assert [f.model_dump() for f in request.fields] == [ + {"label": "note", "before": None, "after": NOTE} + ] + sources = read_sources_for(guard.dir, request) + assert sources == [ + {"label": "note", "source": NOTE, "status": "agree", "differs": False} + ] + assert (guard.dir / SOURCES_FILENAME).stat().st_mode & 0o777 == 0o600 + # The phone's presentation shows both, from the console that serves it. + [row] = list_save_approvals(tmp_path) + shown = save_approval_detail(tmp_path, row.request_id)["presentation"] + assert shown["fields"] == [{"label": "note", "before": None, "after": NOTE}] + assert shown["sources"] == sources + # The signed task the phone answers is PHI-free; the values stay local. + task_doc = save_approval_detail(tmp_path, row.request_id)["task"] + assert NOTE not in json.dumps(task_doc) + + +def test_a_source_that_disagrees_shows_what_the_document_says( + sor, tmp_path: Path +) -> None: + # The task cites the letter for the note, but the letter says another one. + task = _source_task(tmp_path, MISREAD, NOTE) + card = build_card(task, parse_verify_config(verify_yaml(sor[0]))) + [source] = card.sources + assert (source.source, source.status, source.differs) == (NOTE, "disagree", True) + assert card.fields[0].after == MISREAD + + +def test_a_value_that_cant_be_read_is_not_read_never_blank(tmp_path: Path) -> None: + from openadapt_flow.verify_run import parse_verify_config as parse + + # Nothing listens here: the current values can't be read. + data = verify_yaml("http://127.0.0.1:9") + data["effects"][0]["count_new_only"] = False + cfg = parse(data) + card = build_card(_task(), cfg) + [row] = card.fields + assert row.before == NOT_READ and row.after == NOTE + assert card.not_covered == ["note"] + assert "does not cover: note" in card.intent_note() + + +def test_a_write_adapter_claim_is_what_the_card_shows(sor) -> None: + cfg = parse_verify_config(verify_yaml(sor[0])) + card = build_card(_task(), cfg, claim_fields={"note": "what the request sends"}) + assert card.fields[0].after == "what the request sends" + unread = build_card(_task(), cfg, claim_fields={}) + assert unread.fields[0].after == NOT_READ + assert unread.not_covered == ["note"] + + +def test_the_card_can_be_turned_off(sor, tmp_path: Path) -> None: + guarded = GuardedSave( + parse_verify_config(verify_yaml(sor[0])), + tmp_path / "g", + approval_fields=False, + ) + guard = guarded.begin(_task(), screen_text=FakeAgent(sor[0]).open_chart("p1")) + guard.commit(screenshot_png=tiny_png()) + assert guard._request.fields is None + assert not (guard.dir / SOURCES_FILENAME).exists() + + +def test_a_sources_file_for_another_request_is_not_shown(sor, tmp_path: Path) -> None: + task = _source_task(tmp_path, NOTE, NOTE) + guarded = GuardedSave(parse_verify_config(verify_yaml(sor[0])), tmp_path / "g") + guard = guarded.begin(task, screen_text=FakeAgent(sor[0]).open_chart("p1")) + guard.commit(screenshot_png=tiny_png()) + path = guard.dir / SOURCES_FILENAME + doc = json.loads(path.read_text()) + doc["request_sha256"] = "0" * 64 + path.write_text(json.dumps(doc)) + assert read_sources_for(guard.dir, guard._request) is None + + +def test_the_differs_flag_uses_the_value_comparison(sor, tmp_path: Path) -> None: + from dataclasses import replace + + from openadapt_flow.agent_guard.approval_fields import SourceRow, _source_differs + + agree = SourceRow("dob", "1990-01-25", "agree") + assert not _source_differs(agree, "01/25/1990") + assert _source_differs(agree, "1991-01-25") + assert not _source_differs(replace(agree, source=NOT_READ), "x") + assert not _source_differs(agree, NOT_READ) + # The request sends another note than the letter cites: flagged. + task = _source_task(tmp_path, NOTE, NOTE) + cfg = parse_verify_config(verify_yaml(sor[0])) + card = build_card(task, cfg, claim_fields={"note": MISREAD}) + assert card.sources[0].differs is True diff --git a/packages/flow/tests/test_guard_ledger_row.py b/packages/flow/tests/test_guard_ledger_row.py new file mode 100644 index 0000000000..76c26fd12f --- /dev/null +++ b/packages/flow/tests/test_guard_ledger_row.py @@ -0,0 +1,281 @@ +"""The guard's per-save ledger row holds no values; its private diff does. + +Synthetic MockMed fault server on localhost; no browser, no model calls. +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from typing import Any + +import pytest + +from benchmark.harness.guard_demo import NOTE, FakeAgent, person_approves, verify_yaml +from openadapt_flow.agent_guard.commit_guard import CommitGuard +from openadapt_flow.agent_guard.ledger_row import ( + DIFF_FILENAME, + ROW_FILENAME, + ROW_KEYS, + ROW_SCHEMA, + SCRUBBED_FILENAME, + export_scrubbed, + ledger_verdict, +) +from openadapt_flow.guard import GuardedSave, GuardTask, GuardVerdict +from openadapt_flow.mockmed.fault_server import serve as fault_serve +from openadapt_flow.verify_run import parse_verify_config +from tests.test_agent_guard import FakePage + +OTHER = "Referral to cardiology for chest pain" +#: Every value the fixture puts in a record or a task. +FIXTURE_VALUES = (NOTE, OTHER, "Referral to orthopedics", "cardiology") + + +@pytest.fixture +def sor(): + url, db, stop = fault_serve() + try: + yield url.rstrip("/"), db + finally: + stop() + + +def _task() -> GuardTask: + return GuardTask( + task_id="task-ledger-0001", + expected_record={"patient_id": "p1"}, + intended_fields={"note": NOTE}, + ) + + +class _Page(FakePage): + """Saves ``note`` instead of the task's when it is set.""" + + note: str = NOTE + + def continue_request(self, request_id: str) -> None: + self.sent.append(request_id) + held = self.pending.pop(request_id, None) + if held is not None and held.method == "POST": + self.agent.click_save(self.patient, self.note, fault=self.fault) + assert self.guard is not None + self.guard.on_request_done(held.network_id) + + +def _guard(sor, tmp_path: Path, page: FakePage, **kw: Any) -> CommitGuard: + approval = kw.pop("approval", "not_gated") + guarded = GuardedSave( + parse_verify_config(verify_yaml(sor[0])), tmp_path / "state", approval=approval + ) + guard = CommitGuard( + guarded, + _task(), + page, + app_origin=sor[0], + events_path=tmp_path / "events.jsonl", + **kw, + ) + page.guard = guard + return guard + + +def _no_values(path: Path) -> None: + data = path.read_bytes() + for value in FIXTURE_VALUES: + assert value.encode("utf-8") not in data, value + assert b"p1" not in data + + +def test_a_verified_save_writes_a_row_without_values(sor, tmp_path: Path) -> None: + page = _Page(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page) + page.save() + guard.poll() + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert set(row) == set(ROW_KEYS) and row["schema"] == ROW_SCHEMA + assert row["verdict"] == "VERIFIED" + assert row["fields_checked"] == ["note"] and row["fields_differing"] == [] + assert row["readback_tier"] == "independent_readback" + assert row["approver_kind"] == "none" and row["approval_opened_at"] is None + assert row["diff_path"] == DIFF_FILENAME and row["hold_ms"] is not None + _no_values(tmp_path / ROW_FILENAME) + diff = tmp_path / DIFF_FILENAME + assert diff.stat().st_mode & 0o777 == 0o600 + [field] = json.loads(diff.read_text())["fields"] + assert field == { + "field": "note", + "intended": NOTE, + "before": None, + "saved": NOTE, + "status": "same", + } + + +def test_a_planted_wrong_value_differs_and_is_caught(sor, tmp_path: Path) -> None: + page = _Page(FakeAgent(sor[0]), "p1") + page.note = OTHER + guard = _guard(sor, tmp_path, page) + page.save() + guard.poll() + assert guard.summary.verdict == "REFUTED" + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["verdict"] == "CAUGHT_ERROR" + assert row["fields_differing"] == ["note"] + _no_values(tmp_path / ROW_FILENAME) + [field] = json.loads((tmp_path / DIFF_FILENAME).read_text())["fields"] + assert (field["intended"], field["saved"], field["status"]) == ( + NOTE, + OTHER, + "differs", + ) + assert (tmp_path / DIFF_FILENAME).stat().st_mode & 0o777 == 0o600 + + +def test_a_refusal_writes_a_row_with_no_diff(sor, tmp_path: Path) -> None: + page = _Page(FakeAgent(sor[0]), "p2") + _guard(sor, tmp_path, page) + page.save() + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["verdict"] == "CAUGHT_ERROR" + assert row["readback_tier"] is None and row["diff_path"] is None + assert row["fields_checked"] == [] + assert not (tmp_path / DIFF_FILENAME).exists() + _no_values(tmp_path / ROW_FILENAME) + + +def test_an_approved_save_records_who_and_when(sor, tmp_path: Path, approver) -> None: + page = _Page(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, approval="each_item") + page.save() + waiting = guard._waiting + assert waiting is not None + g = waiting[0] + person_approves( + str(g.dir), g._request.request_id, g._request.digest(), signer=approver[1] + ) + guard.poll() + guard.poll() + assert guard.summary.verdict == "VERIFIED" + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["approver_kind"] == "person" + assert row["approval_opened_at"] == g._request.created_at + assert row["approval_decided_at"] is not None + _no_values(tmp_path / ROW_FILENAME) + + +def test_no_ledger_row_when_turned_off(sor, tmp_path: Path) -> None: + page = _Page(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, ledger_row=False) + page.save() + guard.poll() + assert guard.summary.verdict == "VERIFIED" + assert not (tmp_path / ROW_FILENAME).exists() + assert not (tmp_path / DIFF_FILENAME).exists() + + +def test_redact_report_exports_a_scrubbed_diff(sor, tmp_path: Path) -> None: + from openadapt_flow.cli_redact_report import _cmd_redact_report + + page = _Page(FakeAgent(sor[0]), "p1") + page.note = OTHER + guard = _guard(sor, tmp_path, page) + page.save() + guard.poll() + code = _cmd_redact_report( + argparse.Namespace(run_dir=str(tmp_path), policy=None, json=False) + ) + assert code == 0 + scrubbed = tmp_path / SCRUBBED_FILENAME + _no_values(scrubbed) + [field] = json.loads(scrubbed.read_text())["fields"] + assert field["status"] == "differs" + assert field["intended"] != field["saved"] + assert field["intended"].startswith("salted:") + assert export_scrubbed(tmp_path / "nowhere") is None + + +@pytest.mark.parametrize( + ("verdict", "kw", "expected"), + [ + (GuardVerdict.VERIFIED, {}, "VERIFIED"), + (GuardVerdict.VERIFIED, {"differing": True}, "CAUGHT_ERROR"), + (GuardVerdict.REFUTED, {}, "CAUGHT_ERROR"), + (GuardVerdict.RECONCILIATION_REQUIRED, {}, "ESCALATED"), + (None, {"refusal": "identity_mismatch"}, "CAUGHT_ERROR"), + (None, {"refusal": "declined"}, "CAUGHT_ERROR"), + (None, {"refusal": "baseline_unreadable"}, "FAILED"), + (None, {"refusal": "request_expired"}, "ESCALATED"), + (None, {"refusal": "answer_malformed"}, "FAILED"), + (None, {"refusal": "approval_already_used"}, "FAILED"), + (None, {"refusal": "save_waiting_for_person"}, "CAUGHT_ERROR"), + (None, {"refusal": "already_saved"}, "CAUGHT_ERROR"), + (None, {"refusal": "other_origin"}, "CAUGHT_ERROR"), + ], +) +def test_ledger_verdicts(verdict: Any, kw: dict, expected: str) -> None: + assert ledger_verdict(verdict, **kw) == expected + + +def test_a_declined_approval_is_caught(sor, tmp_path: Path, approver) -> None: + from openadapt_flow.approval_mode.item_approval import ( + ItemApprovalStore, + make_answer, + ) + from openadapt_flow.approval_mode.model import ITEM_APPROVAL_ROUTE + + page = _Page(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, approval="each_item") + page.save() + assert guard._waiting is not None + g = guard._waiting[0] + store = ItemApprovalStore(g.dir) + store.write_answer( + make_answer( + store.read_request(g._request.request_id), + decision="decline", + decline_reason="wrong_values", + decided_by="human", + route=ITEM_APPROVAL_ROUTE, + approver_id=None, + auth_method="none", + policy=store.context(), + signer=approver[1], + ) + ) + guard.poll() + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["verdict"] == "CAUGHT_ERROR" + assert row["approver_kind"] == "none" + assert row["approval_opened_at"] == g._request.created_at + assert row["approval_decided_at"] is not None + assert not (tmp_path / DIFF_FILENAME).exists() + _no_values(tmp_path / ROW_FILENAME) + + +def test_blocked_then_saved_right_keeps_the_read_back(sor, tmp_path: Path) -> None: + page = _Page(FakeAgent(sor[0]), "p2") + guard = _guard(sor, tmp_path, page) + page.save() # the wrong record on screen: blocked + assert json.loads((tmp_path / ROW_FILENAME).read_text())["verdict"] == ( + "CAUGHT_ERROR" + ) + page.patient = "p1" + page.save() + guard.poll() + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["verdict"] == "VERIFIED" and row["diff_path"] == DIFF_FILENAME + + +def test_a_refused_second_save_keeps_the_verified_row(sor, tmp_path: Path) -> None: + page = _Page(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page) + page.save() + guard.poll() + assert guard.summary.verdict == "VERIFIED" + page.save() # a second save of a verified task: blocked + assert guard.summary.blocked + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["verdict"] == "VERIFIED" and row["diff_path"] == DIFF_FILENAME + assert (tmp_path / DIFF_FILENAME).exists() diff --git a/packages/flow/tests/test_guard_readback_provider.py b/packages/flow/tests/test_guard_readback_provider.py new file mode 100644 index 0000000000..a83b21b7eb --- /dev/null +++ b/packages/flow/tests/test_guard_readback_provider.py @@ -0,0 +1,235 @@ +"""The commit guard's read-back seam: :mod:`openadapt_flow.agent_guard.readback`. + +The default provider is today's ``Guard.confirm`` (verify-run). Whatever a +provider says, only an independent read-back is VERIFIED, and a field the +read shows with another value is refuted. Synthetic MockMed, localhost. +""" + +from __future__ import annotations + +import json +from pathlib import Path +from typing import Any + +import pytest + +from benchmark.harness.guard_demo import NOTE, FakeAgent, verify_yaml +from openadapt_flow.agent_guard.commit_guard import CommitGuard +from openadapt_flow.agent_guard.config import ConfigError, parse_config +from openadapt_flow.agent_guard.readback import ( + KIND_PREFIX, + ReadbackResult, + VerifyRunReadback, + load_provider, + rule, +) +from openadapt_flow.guard import GuardedSave, GuardTask, GuardVerdict +from openadapt_flow.mockmed.fault_server import serve as fault_serve +from openadapt_flow.verify_run import parse_verify_config +from tests.test_agent_guard import FakePage + +OTHER = "Referral to cardiology for chest pain" + + +@pytest.fixture +def sor(): + url, db, stop = fault_serve() + try: + yield url.rstrip("/"), db + finally: + stop() + + +def _task() -> GuardTask: + return GuardTask( + task_id="task-readback-0001", + expected_record={"patient_id": "p1"}, + intended_fields={"note": NOTE}, + ) + + +class ScreenOnly: + """A provider that read the saved record off a second screen session.""" + + def __init__(self, note: str = NOTE) -> None: + self.note = note + + def read(self, task: Any, guard: Any) -> ReadbackResult: + return ReadbackResult( + tier="screen_readback", + fields={"note": self.note}, + verdict=GuardVerdict.VERIFIED, + ) + + +def _guard(sor, tmp_path: Path, page: FakePage, **kw: Any) -> CommitGuard: + guarded = GuardedSave( + parse_verify_config(verify_yaml(sor[0])), + tmp_path / "state", + approval="not_gated", + ) + guard = CommitGuard( + guarded, + _task(), + page, + app_origin=sor[0], + events_path=tmp_path / "events.jsonl", + **kw, + ) + page.guard = guard + return guard + + +def test_the_default_provider_is_verify_run_unchanged(sor, tmp_path: Path) -> None: + page = FakePage(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page) + assert isinstance(guard.readback, VerifyRunReadback) + page.save() + guard.poll() + assert guard.summary.verdict == "VERIFIED" + assert guard.result is not None and guard.result.receipt_path + ledger = json.loads( + (tmp_path / "state" / "tasks" / "task-readback-0001.json").read_text() + ) + assert ledger["verdict"] == "VERIFIED" + + +def test_a_screen_only_provider_never_yields_verified(sor, tmp_path: Path) -> None: + page = FakePage(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, readback=ScreenOnly()) + page.save() + guard.poll() + assert guard.summary.verdict == "RECONCILIATION_REQUIRED" + # The task's own ledger says so too: the next attempt goes to a person. + ledger = json.loads( + (tmp_path / "state" / "tasks" / "task-readback-0001.json").read_text() + ) + assert ledger["verdict"] == "RECONCILIATION_REQUIRED" + row = json.loads((tmp_path / "guard_ledger_row.json").read_text()) + assert row["readback_tier"] == "screen_readback" + assert row["verdict"] == "ESCALATED" + + +@pytest.mark.parametrize("tier", ["screen_readback", "unchecked", "anything"]) +def test_the_tier_rule(tier: str) -> None: + result = ReadbackResult(tier=tier, fields={}, verdict=GuardVerdict.VERIFIED) + assert rule(_task(), result) is GuardVerdict.RECONCILIATION_REQUIRED + independent = ReadbackResult( + tier="independent_readback", + fields={"note": NOTE}, + verdict=GuardVerdict.VERIFIED, + ) + assert rule(_task(), independent) is GuardVerdict.VERIFIED + + +def test_a_differing_field_is_refuted_whatever_the_provider_says() -> None: + result = ReadbackResult( + tier="independent_readback", + fields={"note": OTHER}, + verdict=GuardVerdict.VERIFIED, + ) + assert rule(_task(), result) is GuardVerdict.REFUTED + # A field the read didn't reach is not a refutation (and not a match). + unread = ReadbackResult( + tier="independent_readback", + fields={"note": None}, + verdict=GuardVerdict.VERIFIED, + ) + assert rule(_task(), unread) is GuardVerdict.VERIFIED + + +def test_a_provider_that_fails_is_reconciliation_required(sor, tmp_path: Path) -> None: + class Broken: + def read(self, task: Any, guard: Any) -> ReadbackResult: + raise TimeoutError("api down") + + page = FakePage(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, readback=Broken()) + page.save() + guard.poll() + assert guard.summary.verdict == "RECONCILIATION_REQUIRED" + assert guard.result is not None + assert guard.result.reason == "readback_provider_failed:TimeoutError" + + +def test_a_provider_that_fails_after_verify_run_keeps_the_tier_rule( + sor, tmp_path: Path +) -> None: + class ConfirmsThenFails: + def read(self, task: Any, guard: Any) -> ReadbackResult: + guard.confirm() + raise RuntimeError("the extra read broke") + + page = FakePage(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, readback=ConfirmsThenFails()) + page.save() + guard.poll() + # verify-run's own independent read stands; nothing upgrades it. + assert guard.summary.verdict == "VERIFIED" + row = json.loads((tmp_path / "guard_ledger_row.json").read_text()) + assert row["readback_tier"] == "independent_readback" + assert row["fields_checked"] == [] + + +def test_a_planted_wrong_value_is_caught_by_the_default_read( + sor, tmp_path: Path +) -> None: + class WrongNote(FakePage): + def continue_request(self, request_id: str) -> None: + self.sent.append(request_id) + held = self.pending.pop(request_id, None) + if held is not None and held.method == "POST": + self.agent.click_save(self.patient, OTHER) + assert self.guard is not None + self.guard.on_request_done(held.network_id) + + page = WrongNote(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page) + page.save() + guard.poll() + assert guard.summary.verdict == "REFUTED" + assert guard.result is not None and guard.result.reason == "readback:fields_differ" + + +def test_a_provider_is_named_through_the_verifier_factory_registry( + tmp_path: Path, +) -> None: + from openadapt_flow.runtime.effects.adapter import ( + _REGISTRY, + register_verifier_factory, + ) + + built: list[Any] = [] + + def factory(config: Any, params: Any) -> ScreenOnly: + built.append((dict(config), dict(params))) + return ScreenOnly() + + register_verifier_factory(KIND_PREFIX + "test_second_session", factory) + try: + provider = load_provider( + {"kind": "test_second_session", "base_url": "http://127.0.0.1:1"}, + {"patient_id": "p1"}, + ) + assert isinstance(provider, ScreenOnly) + assert built[0][0]["base_url"] == "http://127.0.0.1:1" + assert isinstance(load_provider(None, {}), VerifyRunReadback) + assert isinstance(load_provider("verify_run", {}), VerifyRunReadback) + with pytest.raises(ValueError, match="no readback provider"): + load_provider("not_registered_anywhere", {}) + finally: + _REGISTRY.pop(KIND_PREFIX + "test_second_session", None) + + verify = tmp_path / "verify.yaml" + verify.write_text("x: 1\n") + base = { + "schema_version": "openadapt.agent-guard/v1", + "app_url": "http://127.0.0.1:8765/", + "verify": str(verify), + } + cfg = parse_config({**base, "readback_provider": "api"}, base=tmp_path) + assert cfg.readback_provider == "api" and cfg.approval_fields is True + off = parse_config({**base, "approval_fields": False}, base=tmp_path) + assert off.approval_fields is False and off.readback_provider is None + with pytest.raises(ConfigError, match="readback_provider"): + parse_config({**base, "readback_provider": {"base_url": "x"}}, base=tmp_path) From b39f84fbf1ae7243261696c24bb0216d579d8936 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 18:29:07 -0500 Subject: [PATCH 02/15] chore(desktop): prepare 0.31.0 for the guard approval card's source column --- packages/desktop/CHANGELOG.md | 12 ++++++++++++ packages/desktop/openadapt_desktop/__init__.py | 2 +- packages/desktop/package-lock.json | 4 ++-- packages/desktop/package.json | 2 +- packages/desktop/pyproject.toml | 2 +- packages/desktop/src-tauri/Cargo.lock | 2 +- packages/desktop/src-tauri/Cargo.toml | 2 +- packages/desktop/src-tauri/tauri.conf.json | 2 +- packages/desktop/uv.lock | 2 +- 9 files changed, 21 insertions(+), 9 deletions(-) diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 9916a41b8d..c8eafe0fd2 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -1,6 +1,18 @@ # CHANGELOG +## v0.31.0 (2026-11-21) + +### Features + +- **guard**: approval card values beside the source, ReadbackProvider seam, per-save ledger row + +### Bug Fixes + +- **ci**: qualify owned deadlines and pin helper outside subject checkout (#2333) + + + ## 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/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/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" }, From 401f896a8cca18e7762511b1a00531ac5fc84faf Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 18:45:18 -0500 Subject: [PATCH 03/15] docs(guard): one ledger row per run; expired approvals escalate --- packages/flow/docs/GUARD_AN_AGENT.md | 12 ++++++++---- 1 file changed, 8 insertions(+), 4 deletions(-) diff --git a/packages/flow/docs/GUARD_AN_AGENT.md b/packages/flow/docs/GUARD_AN_AGENT.md index dae8bd22ed..05b0398f37 100644 --- a/packages/flow/docs/GUARD_AN_AGENT.md +++ b/packages/flow/docs/GUARD_AN_AGENT.md @@ -177,9 +177,13 @@ After each read-back or blocked save, the guard writes two files in `--out`: `verdict` is `VERIFIED`, `CAUGHT_ERROR` (a blocked save, a declined approval, or a read-back that shows another value or another write), `ESCALATED` (the -save went through and couldn't be confirmed) or `FAILED` (the guard couldn't -do its job, for example the system of record couldn't be read before the -save). +save went through and couldn't be confirmed, or nobody answered the approval +before it expired) or `FAILED` (the guard couldn't do its job, for example the +system of record couldn't be read before the save, or the approval's answer +was unusable). + +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` @@ -325,7 +329,7 @@ GUI steps, and the run-2 times are GUI times. 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. When the task's record can't be told apart in that read (no + 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 From 97c27fb00ac51cee748789942b295fb9b4c1c743 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:07:46 -0500 Subject: [PATCH 04/15] feat(desktop): list exception cards from any run in the stop queue Moved here from #2494 so only one pull request bumps Desktop to 0.31.0. The stop queue reads Flow's exception registry under OPENADAPT_HOME and answers each card on its own, signed with the stop queue's approver key. The card fixture the tests read is committed here too, byte for byte the file #2494's Flow test writes. --- packages/desktop/CHANGELOG.md | 10 +- .../desktop/openadapt_desktop/dispatch.py | 71 +++- .../openadapt_desktop/exception_queue.py | 304 ++++++++++++++ .../openadapt_desktop/portal/shell/stops.js | 10 +- .../desktop/openadapt_desktop/stop_queue.py | 197 ++++++++- packages/desktop/tests/conftest.py | 3 + .../test_engine/test_stop_queue_exceptions.py | 384 ++++++++++++++++++ .../exception_card_second_factor.json | 28 ++ 8 files changed, 997 insertions(+), 10 deletions(-) create mode 100644 packages/desktop/openadapt_desktop/exception_queue.py create mode 100644 packages/desktop/tests/test_engine/test_stop_queue_exceptions.py create mode 100644 packages/flow/tests/fixtures/exception_card_second_factor.json diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index c8eafe0fd2..71513fa9a1 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -6,10 +6,12 @@ ### Features - **guard**: approval card values beside the source, ReadbackProvider seam, per-save ledger row - -### Bug Fixes - -- **ci**: qualify owned deadlines and pin helper outside subject checkout (#2333) +- **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. diff --git a/packages/desktop/openadapt_desktop/dispatch.py b/packages/desktop/openadapt_desktop/dispatch.py index 2c72ea20d8..e11168d63c 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" @@ -4519,6 +4519,14 @@ def _stop_cards(self) -> list[dict]: card = stop_queue.card_for_rearm(switch) if card is not None: cards.append(card) + # Any run on this computer that asked a person (CLI guard, wrap, + # flight, hooks), not only Desktop's own runs. + from openadapt_desktop import exception_queue + + for raw in exception_queue.open_cards(): + card = stop_queue.card_for_exception(raw) + if card is not None: + cards.append(card) return stop_queue.sort_cards(cards) def _rearm_offer(self, workflow_id: str) -> dict | None: @@ -4841,6 +4849,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 self._answer_exception(cards, choice_id, sign=sign, device=device) if any(card["kind"] == "rearm_problems_only" for card in cards): if len(cards) != 1 or device is not None: return { @@ -4911,6 +4921,65 @@ def _answer_stop_cards( ), } + def _answer_exception( + self, + cards: list[dict], + choice_id: str, + *, + sign: Callable[..., dict], + device: dict[str, str] | None, + ) -> dict: + """Answer one exception card: sign it and write the run's answer file.""" + + from openadapt_desktop import exception_queue, 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 = exception_queue.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.", + } + self._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 {}), + } + ) + self.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, + } + def _answer_rearm(self, card: dict, *, shown_ms: Any) -> dict: """Turn a task's switch back on with one Touch ID. diff --git a/packages/desktop/openadapt_desktop/exception_queue.py b/packages/desktop/openadapt_desktop/exception_queue.py new file mode 100644 index 0000000000..020203307b --- /dev/null +++ b/packages/desktop/openadapt_desktop/exception_queue.py @@ -0,0 +1,304 @@ +"""Exception cards from any agent's run, in the stop queue. + +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), a regular 0600-style file 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 + 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 + 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", +] 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/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..0049a812ca --- /dev/null +++ b/packages/desktop/tests/test_engine/test_stop_queue_exceptions.py @@ -0,0 +1,384 @@ +"""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)) + + (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})) + + (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})) + 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()) + 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"] diff --git a/packages/flow/tests/fixtures/exception_card_second_factor.json b/packages/flow/tests/fixtures/exception_card_second_factor.json new file mode 100644 index 0000000000..2cd32341c9 --- /dev/null +++ b/packages/flow/tests/fixtures/exception_card_second_factor.json @@ -0,0 +1,28 @@ +{ + "card_id": "sha256:789e54fd7198a18087709380c8db637b843b28fb2d1d04f1247e5ac8026097ce", + "choices": [ + { + "consequence": "You type the code in the live browser yourself. The run then goes on from the same screen. OpenAdapt never sees the code.", + "id": "done_by_person", + "label": "I entered the code in the browser" + }, + { + "consequence": "Nothing is saved. The run moves to the next item.", + "id": "skip", + "label": "Skip this item" + }, + { + "consequence": "Nothing more is saved. The whole run stops.", + "id": "abort", + "label": "Stop the run" + } + ], + "deadline_at": "2026-11-21T12:15:00Z", + "kind": "second_factor", + "opened_at": "2026-11-21T12:00:00Z", + "run_ref": "fixture-run", + "schema": "openadapt.exception-card/v1", + "screenshot_ref": null, + "summary": "The sign-in page asks for a six-digit code", + "task_id": "intake" +} From fcd5b1da4c9e0a52cefc814b8f03efd1df9da415 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:20:01 -0500 Subject: [PATCH 05/15] fix(guard): ledger row follows the guard's verdict; build with no store The row's verdict now comes only from the GuardVerdict that summary.json carries, or from the block code when the save never went out, using the run ledger's reason names. The row adds guard_verdict and verdict_reason, so a save the guard calls RECONCILIATION_REQUIRED is UNKNOWN with that reason instead of a bare ESCALATED, a declined approval is ESCALATED (person_declined), and a VERIFIED verdict that the field diff contradicts is UNKNOWN. An unnamed block code is UNKNOWN, not a caught error. CommitGuard reads guarded.state_dir with getattr, so a guard stand-in with no store (the shadow hold's) builds and writes no row (J3). A test drives the phone card's decline through Flow's console: the card always sends a closed reason, and a reject without one changes nothing. --- .../agent_guard/commit_guard.py | 22 ++- .../openadapt_flow/agent_guard/ledger_row.py | 143 +++++++++++++--- packages/flow/tests/test_guard_ledger_row.py | 157 +++++++++++++++++- .../tests/test_guard_readback_provider.py | 5 +- 4 files changed, 290 insertions(+), 37 deletions(-) diff --git a/packages/flow/openadapt_flow/agent_guard/commit_guard.py b/packages/flow/openadapt_flow/agent_guard/commit_guard.py index e1f1f476d2..def9f7b328 100644 --- a/packages/flow/openadapt_flow/agent_guard/commit_guard.py +++ b/packages/flow/openadapt_flow/agent_guard/commit_guard.py @@ -161,9 +161,17 @@ def __init__( #: 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. + #: 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 guarded.state_dir)) + ( + ledger_dir + or ( + events_path.parent + if events_path + else getattr(guarded, "state_dir", None) + ) + ) if ledger_row else None ) @@ -473,6 +481,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: @@ -497,6 +506,8 @@ def _refuse( code: str, message: str, guard: Optional[Guard] = None, + *, + scope: bool = False, ) -> None: if self.observe_only: self.summary.would_block.append({"code": code}) @@ -542,7 +553,12 @@ def _refuse( 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 + 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( diff --git a/packages/flow/openadapt_flow/agent_guard/ledger_row.py b/packages/flow/openadapt_flow/agent_guard/ledger_row.py index d2f9041343..d87032afdb 100644 --- a/packages/flow/openadapt_flow/agent_guard/ledger_row.py +++ b/packages/flow/openadapt_flow/agent_guard/ledger_row.py @@ -16,18 +16,41 @@ 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: - -* ``VERIFIED``: an independent read-back shows exactly the intended write. -* ``CAUGHT_ERROR``: the guard stopped or caught a wrong save: a wrong record - on screen, a second save, a declined approval, or a read-back that shows - another value or another write (``REFUTED``). -* ``ESCALATED``: the save went through and could not be confirmed - (``RECONCILIATION_REQUIRED``), or nobody answered its approval before it - expired; a person checks the record. -* ``FAILED``: the guard could not do its job (the store couldn't be read - before the save, the approval couldn't be asked, or its answer was - unusable). +``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: 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; @@ -53,6 +76,8 @@ "SCRUBBED_FILENAME", "export_scrubbed", "ledger_verdict", + "readback_outcome", + "refusal_outcome", "row_after_read_back", "write_readback_row", "write_refusal_row", @@ -68,6 +93,8 @@ "schema", "task_id", "verdict", + "guard_verdict", + "verdict_reason", "fields_checked", "fields_differing", "hold_ms", @@ -78,6 +105,12 @@ "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( { @@ -98,10 +131,66 @@ "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. -_ESCALATED_CODES = frozenset({"request_expired"}) +_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 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( @@ -109,20 +198,14 @@ def ledger_verdict( *, 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: - if refusal in _ESCALATED_CODES: - return "ESCALATED" - if refusal in _FAILED_CODES or refusal.startswith(("approval_", "policy_")): - return "FAILED" - return "CAUGHT_ERROR" - if differing or verdict is GuardVerdict.REFUTED: - return "CAUGHT_ERROR" - if verdict is GuardVerdict.VERIFIED: - return "VERIFIED" - return "ESCALATED" + 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]]: @@ -152,7 +235,8 @@ def _approver_kind(guard: Any) -> str: def _row( *, task_id: str, - verdict: str, + verdict: tuple[str, str], + guard_verdict: Optional[str], checked: list[str], differing: list[str], hold_ms: Optional[float], @@ -164,7 +248,9 @@ def _row( row = { "schema": ROW_SCHEMA, "task_id": task_id, - "verdict": verdict, + "verdict": verdict[0], + "guard_verdict": guard_verdict, + "verdict_reason": verdict[1], "fields_checked": sorted(checked), "fields_differing": sorted(differing), "hold_ms": hold_ms, @@ -223,7 +309,8 @@ def write_readback_row( ) row = _row( task_id=task.task_id, - verdict=ledger_verdict(verdict, differing=bool(differing)), + 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, @@ -281,6 +368,7 @@ def write_refusal_row( 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. @@ -291,7 +379,8 @@ def write_refusal_row( return None row = _row( task_id=task.task_id, - verdict=ledger_verdict(None, refusal=code), + verdict=refusal_outcome(code, scope=scope), + guard_verdict=None, checked=[], differing=[], hold_ms=hold_ms, diff --git a/packages/flow/tests/test_guard_ledger_row.py b/packages/flow/tests/test_guard_ledger_row.py index 76c26fd12f..8294573a9b 100644 --- a/packages/flow/tests/test_guard_ledger_row.py +++ b/packages/flow/tests/test_guard_ledger_row.py @@ -96,6 +96,8 @@ def test_a_verified_save_writes_a_row_without_values(sor, tmp_path: Path) -> Non row = json.loads((tmp_path / ROW_FILENAME).read_text()) assert set(row) == set(ROW_KEYS) and row["schema"] == ROW_SCHEMA assert row["verdict"] == "VERIFIED" + assert row["guard_verdict"] == "VERIFIED" + assert row["verdict_reason"] == "readback_verified" assert row["fields_checked"] == ["note"] and row["fields_differing"] == [] assert row["readback_tier"] == "independent_readback" assert row["approver_kind"] == "none" and row["approval_opened_at"] is None @@ -122,6 +124,8 @@ def test_a_planted_wrong_value_differs_and_is_caught(sor, tmp_path: Path) -> Non assert guard.summary.verdict == "REFUTED" row = json.loads((tmp_path / ROW_FILENAME).read_text()) assert row["verdict"] == "CAUGHT_ERROR" + assert row["guard_verdict"] == "REFUTED" + assert row["verdict_reason"] == "readback_refuted" assert row["fields_differing"] == ["note"] _no_values(tmp_path / ROW_FILENAME) [field] = json.loads((tmp_path / DIFF_FILENAME).read_text())["fields"] @@ -200,25 +204,112 @@ def test_redact_report_exports_a_scrubbed_diff(sor, tmp_path: Path) -> None: ("verdict", "kw", "expected"), [ (GuardVerdict.VERIFIED, {}, "VERIFIED"), - (GuardVerdict.VERIFIED, {"differing": True}, "CAUGHT_ERROR"), + # The guard says VERIFIED and the diff says a field differs: neither + # is trusted (it was CAUGHT_ERROR, against summary.json's VERIFIED). + (GuardVerdict.VERIFIED, {"differing": True}, "UNKNOWN"), + (GuardVerdict.VERIFIED, {"tier": "screen_readback"}, "UNKNOWN"), + (GuardVerdict.VERIFIED, {"tier": None}, "UNKNOWN"), (GuardVerdict.REFUTED, {}, "CAUGHT_ERROR"), - (GuardVerdict.RECONCILIATION_REQUIRED, {}, "ESCALATED"), + # Sent, and not confirmed either way: not a person's escalation. + (GuardVerdict.RECONCILIATION_REQUIRED, {}, "UNKNOWN"), + (GuardVerdict.RECONCILIATION_REQUIRED, {"differing": True}, "UNKNOWN"), (None, {"refusal": "identity_mismatch"}, "CAUGHT_ERROR"), - (None, {"refusal": "declined"}, "CAUGHT_ERROR"), + # A person said no: escalated, not a caught error (skeptic #16). + (None, {"refusal": "declined"}, "ESCALATED"), (None, {"refusal": "baseline_unreadable"}, "FAILED"), (None, {"refusal": "request_expired"}, "ESCALATED"), (None, {"refusal": "answer_malformed"}, "FAILED"), - (None, {"refusal": "approval_already_used"}, "FAILED"), + (None, {"refusal": "approval_already_used"}, "CAUGHT_ERROR"), + (None, {"refusal": "approval_not_authenticated_person"}, "FAILED"), (None, {"refusal": "save_waiting_for_person"}, "CAUGHT_ERROR"), (None, {"refusal": "already_saved"}, "CAUGHT_ERROR"), (None, {"refusal": "other_origin"}, "CAUGHT_ERROR"), + (None, {"refusal": "value_not_declared", "scope": True}, "CAUGHT_ERROR"), + # A code the row can't name is not counted as a catch. + (None, {"refusal": "something_new"}, "UNKNOWN"), ], ) def test_ledger_verdicts(verdict: Any, kw: dict, expected: str) -> None: assert ledger_verdict(verdict, **kw) == expected -def test_a_declined_approval_is_caught(sor, tmp_path: Path, approver) -> None: +def test_the_mapping_matches_the_run_ledger_reasons() -> None: + """Every reason the row names is the run ledger's word for that bucket, + except the one contradiction only the row can see.""" + + from openadapt_flow.agent_guard.ledger_row import readback_outcome, refusal_outcome + + expected = { + "readback_verified": "VERIFIED", + "readback_refuted": "CAUGHT_ERROR", + "reconciliation_required": "UNKNOWN", + "screen_readback_only": "UNKNOWN", + "completed_unverified": "UNKNOWN", + "save_blocked_wrong_record": "CAUGHT_ERROR", + "save_blocked_other_origin": "CAUGHT_ERROR", + "save_blocked_double_save": "CAUGHT_ERROR", + "save_blocked_out_of_scope": "CAUGHT_ERROR", + "person_declined": "ESCALATED", + "approval_declined": "ESCALATED", + "policy_rejected_no_write": "FAILED", + "unmapped_outcome": "UNKNOWN", + "readback_fields_disagree": "UNKNOWN", + } + seen = [ + readback_outcome(v, tier=t, differing=d) + for v in GuardVerdict + for t in ("independent_readback", "screen_readback", None) + for d in (False, True) + ] + [ + refusal_outcome(c, scope=sc) + for c in ( + "identity_mismatch", + "other_origin", + "already_saved", + "declined", + "request_expired", + "baseline_unreadable", + "x", + ) + for sc in (False, True) + ] + for bucket, reason in seen: + assert expected[reason] == bucket, reason + + +def test_a_save_that_did_not_land_is_unknown_and_says_why(sor, tmp_path: Path) -> None: + """The not-saved run: the guard says RECONCILIATION_REQUIRED and the row + says the same thing in the ledger's words, never a bare ESCALATED.""" + + page = _Page(FakeAgent(sor[0]), "p1", fault="no_persist") + guard = _guard(sor, tmp_path, page) + page.save() + guard.poll() + assert guard.summary.verdict == "RECONCILIATION_REQUIRED" + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["verdict"] == "UNKNOWN" + assert row["guard_verdict"] == "RECONCILIATION_REQUIRED" + assert row["verdict_reason"] == "reconciliation_required" + + +def test_a_guard_with_no_store_and_no_events_file_builds(sor, tmp_path: Path) -> None: + """J3: a guard stand-in with no ``state_dir`` (P1's shadow hold) builds + and writes no row; it crashed with AttributeError before.""" + + class _NoStore: + approval = "not_gated" + approval_fields = False + + guard = CommitGuard( + _NoStore(), # type: ignore[arg-type] + _task(), + _Page(FakeAgent(sor[0]), "p1"), + app_origin=sor[0], + ) + assert guard.ledger_dir is None + + +def test_a_declined_approval_is_escalated(sor, tmp_path: Path, approver) -> None: from openadapt_flow.approval_mode.item_approval import ( ItemApprovalStore, make_answer, @@ -246,7 +337,9 @@ def test_a_declined_approval_is_caught(sor, tmp_path: Path, approver) -> None: ) guard.poll() row = json.loads((tmp_path / ROW_FILENAME).read_text()) - assert row["verdict"] == "CAUGHT_ERROR" + assert row["verdict"] == "ESCALATED" + assert row["guard_verdict"] is None + assert row["verdict_reason"] == "person_declined" assert row["approver_kind"] == "none" assert row["approval_opened_at"] == g._request.created_at assert row["approval_decided_at"] is not None @@ -279,3 +372,55 @@ def test_a_refused_second_save_keeps_the_verified_row(sor, tmp_path: Path) -> No row = json.loads((tmp_path / ROW_FILENAME).read_text()) assert row["verdict"] == "VERIFIED" and row["diff_path"] == DIFF_FILENAME assert (tmp_path / DIFF_FILENAME).exists() + + +def test_a_decline_from_the_phone_card_carries_a_reason( + sor, tmp_path: Path, approver +) -> None: + """Item 4 of the e2e findings: ``make_answer`` refuses a decline with no + ``decline_reason``. The phone card always sends one: it asks why before a + decline (``openReasons`` in Desktop's ``portal/shell/app.js``) and offers + only the reasons Flow lists for the save. This drives that path through + Flow's console with a real guard on MockMed.""" + + from openadapt_flow.console import save_approvals + + page = _Page(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, approval="each_item") + page.save() + assert guard._waiting is not None + g = guard._waiting[0] + rid = g._request.request_id + detail = save_approvals.save_approval_detail(g.dir.parent, rid) + reasons = detail["presentation"]["decline_reasons"] + # The card has a reason to send for Don't save, from the closed list. + assert reasons and set(reasons) <= { + "wrong_values", + "wrong_record", + "screen_problem", + } + + def payload(**kw: Any) -> Any: + return save_approvals.SaveApprovalActionRequest( + action="reject", + task_digest=detail["task_digest"], + task_signature=detail["task"]["signature"], + **kw, + ) + + # A reject with no reason (which the card never sends) changes nothing. + with pytest.raises(save_approvals.SaveApprovalRefused) as refused: + save_approvals.decide_save_approval(g.dir.parent, rid, payload()) + assert refused.value.code == "decline_reason_required" + guard.poll() + assert guard._waiting is not None + + # What the card sends: reject plus the reason the person tapped. + save_approvals.decide_save_approval( + g.dir.parent, rid, payload(decline_reason=reasons[0]) + ) + guard.poll() + assert guard._waiting is None + assert [b["code"] for b in guard.summary.blocked] == ["declined"] + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert (row["verdict"], row["verdict_reason"]) == ("ESCALATED", "person_declined") diff --git a/packages/flow/tests/test_guard_readback_provider.py b/packages/flow/tests/test_guard_readback_provider.py index a83b21b7eb..698b9cc79c 100644 --- a/packages/flow/tests/test_guard_readback_provider.py +++ b/packages/flow/tests/test_guard_readback_provider.py @@ -107,7 +107,10 @@ def test_a_screen_only_provider_never_yields_verified(sor, tmp_path: Path) -> No assert ledger["verdict"] == "RECONCILIATION_REQUIRED" row = json.loads((tmp_path / "guard_ledger_row.json").read_text()) assert row["readback_tier"] == "screen_readback" - assert row["verdict"] == "ESCALATED" + # Unconfirmed, as summary.json says: the row doesn't call it escalated. + assert row["verdict"] == "UNKNOWN" + assert row["guard_verdict"] == "RECONCILIATION_REQUIRED" + assert row["verdict_reason"] == "reconciliation_required" @pytest.mark.parametrize("tier", ["screen_readback", "unchecked", "anything"]) From 2953d4e0002a7e90835ad1bed4e774cfbd352904 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:20:01 -0500 Subject: [PATCH 06/15] fix(guard): approval card shows what the held save sends, or says it can't In the end-to-end run, the card for an agent's save showed the task's intended note and said "This is exactly what OpenAdapt will save", while the agent had typed another note; it was approved and the wrong note landed. The card's value saved now comes only from the held request, read by the app's write adapter (the same reader the guard checks writes with). Without an adapter, or with a body it can't read, every sent value is "not read", the card says the values were not read and not checked before saving, and the phone never says "exactly". The task's value is shown beside each sent value, with a difference flagged. Tested in headless Chromium on MockMed: no adapter and a wrong note gives the unchecked wording; the adapter and the right note shows the held values as checked; the adapter and a wrong note is blocked before any card. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/desktop/CHANGELOG.md | 7 + .../openadapt_desktop/portal/shell/app.js | 55 ++++- .../tests/test_guard_request_pickup.py | 11 +- packages/flow/docs/GUARD_AN_AGENT.md | 47 +++- .../agent_guard/approval_fields.py | 134 ++++++++--- .../openadapt_flow/console/save_approvals.py | 30 +++ .../e2e/test_agent_guard_card_values_e2e.py | 217 ++++++++++++++++++ .../flow/tests/test_guard_approval_fields.py | 47 +++- 10 files changed, 493 insertions(+), 59 deletions(-) create mode 100644 packages/flow/tests/e2e/test_agent_guard_card_values_e2e.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 1c0e9164b4..cafe63a5df 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -323,7 +323,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. The approval card shows each field's value now, the value saved and its source; each save gets a ledger row with no values and a 0600 diff, and 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)) | 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), 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) | diff --git a/llms-full.txt b/llms-full.txt index 5a28066566..7ef88abca7 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -763,7 +763,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. The approval card shows each field's value now, the value saved and its source; each save gets a ledger row with no values and a 0600 diff, and 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)) | 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), 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) | diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 71513fa9a1..4ff42cefb2 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -13,6 +13,13 @@ answered on its own, here or on a paired phone, and the answer is signed with the same approver key as other stop answers. +### 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. + ## v0.30.6 (2026-11-19) diff --git a/packages/desktop/openadapt_desktop/portal/shell/app.js b/packages/desktop/openadapt_desktop/portal/shell/app.js index 62f3aa19c6..614d6e17e7 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/app.js +++ b/packages/desktop/openadapt_desktop/portal/shell/app.js @@ -972,7 +972,9 @@ function saveFields(presentation) { } // `presentation.sources`: a guarded save's source column, `{label, source, -// status, differs}` per field, kept by Flow beside the request and bound to its digest. +// 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) { @@ -984,10 +986,22 @@ function saveSources(presentation) { typeof row.label === "string" && (row.source === null || typeof row.source === "string") && typeof row.status === "string" && - typeof row.differs === "boolean", + typeof row.differs === "boolean" && + (row.intended === undefined || row.intended === null || typeof row.intended === "string") && + (row.held_differs === undefined || typeof row.held_differs === "boolean"), ); if (!ok) return null; - return new Map(raw.map((row) => [row.label, { source: row.source, differs: row.differs }])); + 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, + }, + ]), + ); } // `presentation.provenance`: why an agent asked for this save. The agent's @@ -1052,6 +1066,9 @@ async function openSave(item) { "Before it saves, OpenAdapt reads the form again. If anything changed, it stops and asks again.", fields: saveFields(presentation), sources: saveSources(presentation), + // Flow sets this false for an agent's save whose values it couldn't read + // from the held request; the card then never says "exactly". + exact: presentation.values_checked !== false, provenance: saveProvenance(presentation), frameUrl: null, frameOk: false, @@ -1184,7 +1201,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"; @@ -1210,7 +1232,11 @@ function sourceMarkup(card, field) { 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. - return `${row.differs ? 'Differs ' : ""}Source: ${esc(text)}`; + const intended = + row.intended === null + ? "" + : `${row.heldDiffers ? 'Differs ' : ""}Task says: ${esc(row.intended === "" ? "empty" : row.intended)}`; + return `${intended}${row.differs ? 'Differs ' : ""}Source: ${esc(text)}`; } function fieldsMarkup(card) { @@ -1227,7 +1253,11 @@ function fieldsMarkup(card) { }${field.after === "" ? '(empty)' : esc(field.after)}${sourceMarkup(card, field)}
`, ) .join("")}${ - unread ? '

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

' : "" + 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.

' + : "" }`; } @@ -2128,7 +2158,11 @@ function openMore() { ? `` : ""; const closes = @@ -2171,11 +2205,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/tests/test_guard_request_pickup.py b/packages/desktop/tests/test_guard_request_pickup.py index 5373b6e25b..db84cc8e4c 100644 --- a/packages/desktop/tests/test_guard_request_pickup.py +++ b/packages/desktop/tests/test_guard_request_pickup.py @@ -182,8 +182,15 @@ def test_desktop_shows_a_guard_request_from_a_state_dir_in_its_runs_folder( ) assert status == 200 presentation = json.loads(body)["presentation"] - # The card carries the field the save writes, from the guard's request. - assert presentation["fields"] == [{"label": "note", "before": None, "after": NOTE}] + # 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( diff --git a/packages/flow/docs/GUARD_AN_AGENT.md b/packages/flow/docs/GUARD_AN_AGENT.md index 05b0398f37..12d6f7a3fd 100644 --- a/packages/flow/docs/GUARD_AN_AGENT.md +++ b/packages/flow/docs/GUARD_AN_AGENT.md @@ -148,11 +148,19 @@ or the paired phone) lists every field the task writes: | 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 task's `intended_fields` value, or, with `write_adapter`, the value the held request carries. | +| 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`. | +| 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. +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, and asks the person to compare the screen with the +task's values. It says "exactly what will be saved" only when every value came +from the held request. 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 @@ -168,19 +176,36 @@ screenshot only. 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`, `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. + `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` is `VERIFIED`, `CAUGHT_ERROR` (a blocked save, a declined approval, -or a read-back that shows another value or another write), `ESCALATED` (the -save went through and couldn't be confirmed, or nobody answered the approval -before it expired) or `FAILED` (the guard couldn't do its job, for example the -system of record couldn't be read before the save, or the approval's answer -was unusable). +`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: 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. diff --git a/packages/flow/openadapt_flow/agent_guard/approval_fields.py b/packages/flow/openadapt_flow/agent_guard/approval_fields.py index c119910bc5..4e5a0238f0 100644 --- a/packages/flow/openadapt_flow/agent_guard/approval_fields.py +++ b/packages/flow/openadapt_flow/agent_guard/approval_fields.py @@ -8,13 +8,23 @@ 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 task says to write, or, when the app's write - adapter is configured, the value the held request actually carries. +* ``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. * ``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. +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 @@ -66,6 +76,11 @@ class SourceRow: #: 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 def to_dict(self) -> dict[str, Any]: return { @@ -73,6 +88,8 @@ def to_dict(self) -> dict[str, Any]: "source": self.source, "status": self.status, "differs": self.differs, + "intended": self.intended, + "held_differs": self.held_differs, } @@ -84,15 +101,26 @@ class ApprovalCard: 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" def intent_note(self) -> str: """The sentence the card's intent carries when something is unread.""" - if not self.not_covered: - return "" - return ". Not read, so this approval does not cover: " + ", ".join( - sorted(self.not_covered) - ) + 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.not_covered: + note += ". Not read, so this approval does not cover: " + ", ".join( + sorted(self.not_covered) + ) + return note def _text(value: Any) -> str: @@ -209,12 +237,15 @@ def build_card( claim_fields: Optional[Mapping[str, Any]] = None, records: Optional[Sequence[Mapping[str, Any]]] = None, read: bool = True, + values_how: Optional[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. ``records`` is a read the caller - already made; otherwise one is made now when ``read``. + 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. """ from openadapt_flow.approval_mode.item_approval import MAX_SAVE_FIELDS, SaveField @@ -239,24 +270,56 @@ def build_card( # Which record, or its value, isn't known: shown, not hidden. before = NOT_READ not_covered.append(name) - if claim_fields is not None: - if name in claim_fields and claim_fields[name] is not None: - after = _text(claim_fields[name]) - else: - after = NOT_READ - if name not in not_covered: - 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: - after = _text(task.intended_fields[name]) + # 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") - row = replace(row, differs=_source_differs(row, after)) + 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), + ) 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:]) - return ApprovalCard(fields=rows, sources=source_rows, not_covered=not_covered) + 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, + ) + + +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: @@ -273,6 +336,7 @@ def write_sources(run_dir: Path, request: Any, card: ApprovalCard) -> Path: "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}, }, ) return path @@ -307,31 +371,45 @@ def read_sources_for(run_dir: Path, request: Any) -> Optional[list[dict[str, Any 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 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, } ) return rows def card_for_request(guard: Any, request: Any, scope: Any) -> Any: - """The commit guard's card for a held save, with the values the request - carries when the app's write adapter can read them. None: let the guard - build the task's card itself (or none, when the card is turned off).""" + """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. 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" - adapter = getattr(scope, "write_adapter", None) if scope is not None else None - if not owner.approval_fields or not asked or adapter is None: + 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: + return build_card( + guard.task, owner.verify, claim_fields=None, values_how="no_write_adapter" + ) try: body = request.post_data.encode("utf-8") if request.post_data else None claim = adapter.claim(request.method, request.url, body) - claimed = dict(claim.fields) if claim is not None else {} except Exception: # noqa: BLE001 - unread: every value shows not read - claimed = {} - return build_card(guard.task, owner.verify, claim_fields=claimed) + 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/console/save_approvals.py b/packages/flow/openadapt_flow/console/save_approvals.py index 9499d65276..3227a13ac3 100644 --- a/packages/flow/openadapt_flow/console/save_approvals.py +++ b/packages/flow/openadapt_flow/console/save_approvals.py @@ -257,6 +257,31 @@ def save_approval_task( return sign_human_decision_task_hmac(key=_task_key(store), fields=fields) +#: ``openadapt_flow.guard.Guard``'s item-approval workflow name. +GUARDED_SAVE_WORKFLOW = "guarded-save" + + +def _guarded_wording(presentation: dict[str, Any], request: Any) -> None: + from openadapt_flow.agent_guard.approval_fields import NOT_READ + + fields = list(request.fields or []) + checked = bool(fields) and all(f.after != NOT_READ for f in fields) + presentation["values_checked"] = checked + if checked: + presentation["explanation"] = ( + "These are the values in the save the agent is sending, read from " + "the held request before it goes out. After it saves, OpenAdapt " + "reads the record back and reports any difference." + ) + else: + presentation["explanation"] = ( + "OpenAdapt could not read the values this save will send, so they " + "were not checked before saving. Compare the screen with the " + "task's values before you approve. After it saves, OpenAdapt " + "reads the record back and reports any difference." + ) + + def save_approval_detail(root: Path, request_id: str) -> dict[str, Any]: """The portal's view of one waiting save: signed task + local presentation. @@ -300,6 +325,11 @@ def save_approval_detail(root: Path, request_id: str) -> dict[str, Any]: sources = read_sources_for(run_dir, request) if sources: presentation["sources"] = sources + if request.workflow_name == GUARDED_SAVE_WORKFLOW: + # An agent's save the guard holds. The card says "exactly" only when + # every value came from the held request (request.fields, inside the + # digest); otherwise it says plainly they were not read or checked. + _guarded_wording(presentation, request) if request.workflow_name == LEDGER_QUESTION_WORKFLOW: # An agent's question from its task ledger, not a save. Approve is # yes and decline is no; the answer saves nothing in any app. diff --git a/packages/flow/tests/e2e/test_agent_guard_card_values_e2e.py b/packages/flow/tests/e2e/test_agent_guard_card_values_e2e.py new file mode 100644 index 0000000000..00b6ca0cc5 --- /dev/null +++ b/packages/flow/tests/e2e/test_agent_guard_card_values_e2e.py @@ -0,0 +1,217 @@ +"""The approval card shows what the held save sends, or says it can't. + +The end-to-end finding this pins: with ``approval: each_item`` and no write +adapter, the card showed the task's intended note as the value saved and said +"This is exactly what OpenAdapt will save", while the agent had typed another +note. The person approved and the wrong note landed. + +A scripted Playwright agent (``benchmark/agent_guard/agent.py``) drives its +own headless browser; ``openadapt-flow guard`` runs in another process, +attached over CDP, and holds the save for a person. The person here reads the +card through Flow's console (``save_approval_detail``, what the phone shows) +and answers with a registered test approver key. + +* No write adapter, the agent types another note: the card says the values + were not read and not checked, shows the task's note beside ``not read``, + and never says "exactly". Approved anyway, the read-back catches it. +* MockMed's write adapter, the right note: the card shows the note read from + the held request, marks it checked, and flags no difference. +* MockMed's write adapter, the agent types another note: the guard blocks the + save before any card is shown. + +Synthetic MockMed in front of the ``effect_e2e`` record store; localhost only. +""" + +from __future__ import annotations + +import json +import socket +import threading +import time +from pathlib import Path +from typing import Any, Optional + +import pytest + +pytest.importorskip("playwright") + +from benchmark.agent_guard import run as bench # noqa: E402 +from benchmark.agent_guard.app import serve # noqa: E402 +from tests import _approver_keys as ak # noqa: E402 + +pytestmark = pytest.mark.timeout(600) + +ADAPTER = "tests._teach_scope:EncounterWrites" + + +def _port() -> int: + with socket.socket() as sock: + sock.bind(("127.0.0.1", 0)) + return int(sock.getsockname()[1]) + + +def _scenario(name: str) -> bench.Scenario: + return next(s for s in bench.SCENARIOS if s.name == name) + + +def _chromium_or_skip() -> None: + from playwright.sync_api import sync_playwright + + try: + with sync_playwright() as pw: + pw.chromium.launch(headless=True).close() + except Exception as exc: # noqa: BLE001 + pytest.skip(f"chromium unavailable: {exc}") + + +@pytest.fixture +def signer(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Any: + from openadapt_flow.approval_mode.approver_roster import ROOT_ENV + from openadapt_flow.jit.authority import KEY_PASSPHRASE_ENV + from openadapt_flow.jit.lifecycle import KEY_DIR_ENV + + key_dir = tmp_path / "approver-keys" + monkeypatch.setenv(KEY_DIR_ENV, str(key_dir)) + monkeypatch.setenv(KEY_PASSPHRASE_ENV, ak.PASSPHRASE) + _, sign = ak.provision(key_dir) + monkeypatch.setenv(ROOT_ENV, ak.root_of(key_dir)) + return sign + + +def _files(app: Any, work: Path, *, adapter: Optional[str]) -> dict[str, Path]: + files = bench.write_setup(work, app.base_url, teach_dir=None) + extra = "approval: each_item\n" + if adapter: + extra += f"write_adapter: {adapter}\n" + # The adapter attributes a write to ``patient_id`` only. + task = json.loads(files["task"].read_text()) + task["expected_record"] = {"patient_id": "p1"} + files["task"].write_text(json.dumps(task)) + files["guard"].write_text(files["guard"].read_text() + extra) + return files + + +class _Person(threading.Thread): + """Waits for the held save, reads its card as the phone would, answers.""" + + def __init__(self, work: Path, decision: str, signer: Any) -> None: + super().__init__(daemon=True) + self.work = work + self.decision = decision + self.signer = signer + self.stop = threading.Event() + self.shown: Optional[dict[str, Any]] = None + self.error: Optional[str] = None + + def run(self) -> None: + from openadapt_flow.approval_mode.item_approval import ( + ItemApprovalStore, + make_answer, + ) + from openadapt_flow.approval_mode.model import ITEM_APPROVAL_ROUTE + from openadapt_flow.console.save_approvals import save_approval_detail + + requests: list[Path] = [] + while not self.stop.is_set(): + requests = list(self.work.rglob("item-approval/request-*.json")) + if requests: + break + time.sleep(0.1) + if not requests: + return + run_dir = requests[0].parent.parent + request_id = requests[0].stem.split("request-", 1)[1] + try: + self.shown = save_approval_detail(run_dir.parent, request_id)[ + "presentation" + ] + store = ItemApprovalStore(run_dir) + store.write_answer( + make_answer( + store.read_request(request_id), + decision=self.decision, + decided_by="human", + route=ITEM_APPROVAL_ROUTE, + approver_id=None, + auth_method="none", + policy=store.context(), + signer=self.signer, + ) + ) + except Exception as exc: # noqa: BLE001 - reported by the test + self.error = repr(exc) + + +def _run(app: Any, scenario: str, work: Path, files: dict, person: _Person) -> dict: + person.start() + try: + return bench.run_one( + app, + _scenario(scenario), + "guard", + work, + _port(), + think_s=0.3, + files=files, + teach=False, + ) + finally: + person.stop.set() + person.join(timeout=60) + + +def test_the_card_never_says_exactly_when_it_could_not_read_the_values( + tmp_path: Path, signer: Any +) -> None: + _chromium_or_skip() + app = serve(tmp_path / "app.sqlite") + try: + # 1. No write adapter, the agent types another note. + work = tmp_path / "no-adapter-wrong" + files = _files(app, tmp_path / "setup-a", adapter=None) + person = _Person(work, "approve", signer) + result = _run(app, "agent_wrong_value", work, files, person) + assert person.error is None, person.error + shown = person.shown + assert shown is not None, result + assert shown["values_checked"] is False + assert "exactly" not in shown["explanation"].lower() + assert "not checked before saving" in shown["explanation"] + by_label = {f["label"]: f for f in shown["fields"]} + # Never the task's note standing in for the one the agent typed. + assert by_label["note"]["after"] == "not read" + assert bench.NOTE not in json.dumps(shown["fields"]) + sources = {r["label"]: r for r in shown["sources"]} + assert sources["note"]["intended"] == bench.NOTE + assert "values this save sends could not be read" in shown["step_intent"] + # Approved anyway: the read-back still catches the other note. + assert result["verdict"] == "REFUTED", result + + # 2. MockMed's write adapter, the right note: read from the request. + work = tmp_path / "adapter-ok" + files = _files(app, tmp_path / "setup-b", adapter=ADAPTER) + person = _Person(work, "approve", signer) + result = _run(app, "ok", work, files, person) + assert person.error is None, person.error + shown = person.shown + assert shown is not None, result + assert shown["values_checked"] is True + by_label = {f["label"]: f for f in shown["fields"]} + assert by_label["note"]["after"] == bench.NOTE + assert by_label["type"]["after"] == "Triage" + sources = {r["label"]: r for r in shown["sources"]} + assert sources["note"]["intended"] == bench.NOTE + assert sources["note"]["held_differs"] is False + assert result["verdict"] == "VERIFIED", result + + # 3. MockMed's write adapter, another note: blocked before any card. + work = tmp_path / "adapter-wrong" + files = _files(app, tmp_path / "setup-c", adapter=ADAPTER) + person = _Person(work, "approve", signer) + result = _run(app, "agent_wrong_value", work, files, person) + assert person.shown is None + assert not list(work.rglob("item-approval/request-*.json")) + assert result["verdict"] is None, result + assert result["blocked"] == ["write_value_not_declared"], result + finally: + app.stop() diff --git a/packages/flow/tests/test_guard_approval_fields.py b/packages/flow/tests/test_guard_approval_fields.py index 54d82d30fa..6fbc981d4e 100644 --- a/packages/flow/tests/test_guard_approval_fields.py +++ b/packages/flow/tests/test_guard_approval_fields.py @@ -97,20 +97,32 @@ def test_the_request_carries_before_after_and_source_for_each_field( guard = guarded.begin(task, screen_text=FakeAgent(sor[0]).open_chart("p1")) guard.commit(screenshot_png=tiny_png()) request = guard._request - # A create: nothing was there before, the value saved is the task's. + # A create: nothing was there before. No request is held here (the + # caller sends the save itself), so what it sends is not read: the task's + # value is shown beside it, never in its place. assert [f.model_dump() for f in request.fields] == [ - {"label": "note", "before": None, "after": NOTE} + {"label": "note", "before": None, "after": NOT_READ} ] sources = read_sources_for(guard.dir, request) assert sources == [ - {"label": "note", "source": NOTE, "status": "agree", "differs": False} + { + "label": "note", + "source": NOTE, + "status": "agree", + "differs": False, + "intended": NOTE, + "held_differs": False, + } ] assert (guard.dir / SOURCES_FILENAME).stat().st_mode & 0o777 == 0o600 # The phone's presentation shows both, from the console that serves it. [row] = list_save_approvals(tmp_path) shown = save_approval_detail(tmp_path, row.request_id)["presentation"] - assert shown["fields"] == [{"label": "note", "before": None, "after": NOTE}] + assert shown["fields"] == [{"label": "note", "before": None, "after": NOT_READ}] assert shown["sources"] == sources + assert shown["values_checked"] is False + assert "exactly" not in shown["explanation"].lower() + assert "not checked before saving" in shown["explanation"] # The signed task the phone answers is PHI-free; the values stay local. task_doc = save_approval_detail(tmp_path, row.request_id)["task"] assert NOTE not in json.dumps(task_doc) @@ -124,7 +136,8 @@ def test_a_source_that_disagrees_shows_what_the_document_says( card = build_card(task, parse_verify_config(verify_yaml(sor[0]))) [source] = card.sources assert (source.source, source.status, source.differs) == (NOTE, "disagree", True) - assert card.fields[0].after == MISREAD + assert source.intended == MISREAD + assert card.fields[0].after == NOT_READ def test_a_value_that_cant_be_read_is_not_read_never_blank(tmp_path: Path) -> None: @@ -134,7 +147,7 @@ def test_a_value_that_cant_be_read_is_not_read_never_blank(tmp_path: Path) -> No data = verify_yaml("http://127.0.0.1:9") data["effects"][0]["count_new_only"] = False cfg = parse(data) - card = build_card(_task(), cfg) + card = build_card(_task(), cfg, claim_fields={"note": NOTE}) [row] = card.fields assert row.before == NOT_READ and row.after == NOTE assert card.not_covered == ["note"] @@ -145,9 +158,31 @@ def test_a_write_adapter_claim_is_what_the_card_shows(sor) -> None: cfg = parse_verify_config(verify_yaml(sor[0])) card = build_card(_task(), cfg, claim_fields={"note": "what the request sends"}) assert card.fields[0].after == "what the request sends" + # Beside the task's value, flagged: the request sends another note. + assert card.sources[0].intended == NOTE + assert card.sources[0].held_differs is True + assert card.values_read is True and card.values_how == "write_adapter" + assert "not checked" not in card.intent_note() + same = build_card(_task(), cfg, claim_fields={"note": NOTE}) + assert same.sources[0].held_differs is False and same.values_read is True unread = build_card(_task(), cfg, claim_fields={}) assert unread.fields[0].after == NOT_READ assert unread.not_covered == ["note"] + assert unread.values_read is False + assert "could not be read, so they were not checked" in unread.intent_note() + + +def test_no_held_values_never_shows_the_task_value_as_what_is_sent(sor) -> None: + """The e2e finding: with no write adapter the card showed the task's note + as the value saved, under "exactly what OpenAdapt will save", while the + agent had typed another one.""" + + cfg = parse_verify_config(verify_yaml(sor[0])) + card = build_card(_task(), cfg, claim_fields=None, values_how="no_write_adapter") + assert card.fields[0].after == NOT_READ + assert card.sources[0].intended == NOTE + assert card.values_read is False and card.values_how == "no_write_adapter" + assert "could not be read, so they were not checked" in card.intent_note() def test_the_card_can_be_turned_off(sor, tmp_path: Path) -> None: From 9d374a7a1c4b78a7932fe732ceec23533c67f535 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:29:12 -0500 Subject: [PATCH 07/15] fix(guard): annotate the read-back reason as optional for mypy --- packages/flow/openadapt_flow/agent_guard/readback.py | 1 + 1 file changed, 1 insertion(+) diff --git a/packages/flow/openadapt_flow/agent_guard/readback.py b/packages/flow/openadapt_flow/agent_guard/readback.py index 947c361a9a..fde3c05ab9 100644 --- a/packages/flow/openadapt_flow/agent_guard/readback.py +++ b/packages/flow/openadapt_flow/agent_guard/readback.py @@ -212,6 +212,7 @@ def settle(guard: Guard, result: ReadbackResult, verdict: GuardVerdict) -> Guard 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: From f8f617311593151aae4d2ca647b0bf1ee06eaa6b Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:38:39 -0500 Subject: [PATCH 08/15] test(desktop): the phone card's unchecked wording and the task's value --- packages/desktop/src/portalShell.test.ts | 39 ++++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/packages/desktop/src/portalShell.test.ts b/packages/desktop/src/portalShell.test.ts index 91db714762..76c8b296cf 100644 --- a/packages/desktop/src/portalShell.test.ts +++ b/packages/desktop/src/portalShell.test.ts @@ -375,6 +375,45 @@ describe("the card shows what will be saved", () => { expect(q("#evidence")!.classList).toContain("big"); }); + 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("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(); From d0a1e92f3c3955a644fd5c224f6fe58fa507419e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:39:05 -0500 Subject: [PATCH 09/15] test(guard): an observed verified save is VERIFIED in the ledger row --- packages/flow/tests/test_guard_ledger_row.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/packages/flow/tests/test_guard_ledger_row.py b/packages/flow/tests/test_guard_ledger_row.py index 8294573a9b..f562c7aa63 100644 --- a/packages/flow/tests/test_guard_ledger_row.py +++ b/packages/flow/tests/test_guard_ledger_row.py @@ -424,3 +424,23 @@ def payload(**kw: Any) -> Any: assert [b["code"] for b in guard.summary.blocked] == ["declined"] row = json.loads((tmp_path / ROW_FILENAME).read_text()) assert (row["verdict"], row["verdict_reason"]) == ("ESCALATED", "person_declined") + + +def test_an_observe_only_verified_save_is_verified_in_the_row( + sor, tmp_path: Path +) -> None: + """Observe-only takes the tier from the verify-run receipt; its words are + the same, so a verified observed save is VERIFIED in the row too.""" + + page = _Page(FakeAgent(sor[0]), "p1") + guard = _guard(sor, tmp_path, page, observe_only=True) + page.save() + guard.poll() + assert guard.summary.verdict == "VERIFIED" + row = json.loads((tmp_path / ROW_FILENAME).read_text()) + assert row["readback_tier"] == "independent_readback" + assert (row["verdict"], row["guard_verdict"], row["verdict_reason"]) == ( + "VERIFIED", + "VERIFIED", + "readback_verified", + ) From 40d4e9b142474234610e1e50e0a8e6030dfbc2c1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 00:28:41 -0500 Subject: [PATCH 10/15] fix(guard): a signed decline records who declined The ledger row of a declined save said approver_kind none although a person had signed the decline: the guard kept the approver only for an approval. It now records the approver from any verified answer, approve or decline. --- packages/flow/openadapt_flow/guard.py | 17 ++++++++++------- packages/flow/tests/test_guard_ledger_row.py | 5 ++++- 2 files changed, 14 insertions(+), 8 deletions(-) diff --git a/packages/flow/openadapt_flow/guard.py b/packages/flow/openadapt_flow/guard.py index 08724a801d..d717363758 100644 --- a/packages/flow/openadapt_flow/guard.py +++ b/packages/flow/openadapt_flow/guard.py @@ -606,6 +606,16 @@ def _await_approval( approval_request_sha256=request.digest(), approval_run_dir=str(self.dir), ) + if answer is not None: + # A verified answer, either way: who decided goes on the record + # (and the ledger row), a decline as much as an approval. + self._approver = { + "kind": "person", + "id": answer.approver_id + or (answer.attestation.signer if answer.attestation else None) + or "unauthenticated-person", + "policy_ref": self._policy_ref, + } if answer is None or answer.decision != "approve": reason = code or "declined" self._save("declined", reason=reason) @@ -623,13 +633,6 @@ def _await_approval( "decided_by": answer.decided_by, "route": answer.route, } - self._approver = { - "kind": "person", - "id": answer.approver_id - or (answer.attestation.signer if answer.attestation else None) - or "unauthenticated-person", - "policy_ref": self._policy_ref, - } return None def _card(self) -> Any: diff --git a/packages/flow/tests/test_guard_ledger_row.py b/packages/flow/tests/test_guard_ledger_row.py index f562c7aa63..27e1e3dca5 100644 --- a/packages/flow/tests/test_guard_ledger_row.py +++ b/packages/flow/tests/test_guard_ledger_row.py @@ -340,7 +340,9 @@ def test_a_declined_approval_is_escalated(sor, tmp_path: Path, approver) -> None assert row["verdict"] == "ESCALATED" assert row["guard_verdict"] is None assert row["verdict_reason"] == "person_declined" - assert row["approver_kind"] == "none" + # A person signed the decline: the row says so (it said "none" before). + assert row["approver_kind"] == "person" + assert g._approver is not None and g._approver["id"] == "front-desk" assert row["approval_opened_at"] == g._request.created_at assert row["approval_decided_at"] is not None assert not (tmp_path / DIFF_FILENAME).exists() @@ -424,6 +426,7 @@ def payload(**kw: Any) -> Any: assert [b["code"] for b in guard.summary.blocked] == ["declined"] row = json.loads((tmp_path / ROW_FILENAME).read_text()) assert (row["verdict"], row["verdict_reason"]) == ("ESCALATED", "person_declined") + assert row["approver_kind"] == "person" def test_an_observe_only_verified_save_is_verified_in_the_row( From 6fa9c3a36c45e4a689c8bd013a1d58a63fb54bef Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 01:19:52 -0500 Subject: [PATCH 11/15] fix(guard): with no write adapter, show the screen at the save or ask no one With no write adapter the card said the sent values were not read but still offered approve over nothing a person could check. The guard now takes the screenshot and reads the form's values (input, select, textarea and contenteditable, matched to a field by id, name or label, in the new agent_guard/screen_values.py, mirroring the readiness form read) at the moment the save is held. The card shows them as "on screen at the save" beside the task's values, with a difference flagged. When no value was read from the request or the screen and there is no readable screenshot, no approval request is opened, so no surface can approve: the guard blocks the save with values_unread and the ledger row is ESCALATED with reason values_unread. Tested in headless Chromium on MockMed with the real guard and no adapter: the agent's wrong note is read from the screen and flagged, with a readable screenshot; with the screenshot and form read failing in the guard's process, no request is opened, the save is blocked and nothing is written. --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/desktop/CHANGELOG.md | 2 + .../openadapt_desktop/portal/shell/app.js | 13 +- packages/desktop/src/portalShell.test.ts | 28 ++++ packages/flow/docs/GUARD_AN_AGENT.md | 10 +- .../agent_guard/approval_fields.py | 69 ++++++++- .../flow/openadapt_flow/agent_guard/cdp.py | 22 +++ .../agent_guard/commit_guard.py | 11 +- .../openadapt_flow/agent_guard/ledger_row.py | 4 + .../agent_guard/screen_values.py | 142 ++++++++++++++++++ .../openadapt_flow/console/save_approvals.py | 11 ++ packages/flow/openadapt_flow/guard.py | 11 +- .../e2e/test_agent_guard_card_values_e2e.py | 59 +++++++- .../flow/tests/test_guard_approval_fields.py | 44 ++++++ packages/flow/tests/test_guard_ledger_row.py | 21 +++ packages/flow/tests/test_guarded_save.py | 4 +- packages/flow/tests/test_provenance.py | 3 +- 18 files changed, 442 insertions(+), 16 deletions(-) create mode 100644 packages/flow/openadapt_flow/agent_guard/screen_values.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 3c7a8e923d..ecaa67fa54 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -325,7 +325,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. 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), 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) | +| 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) | diff --git a/llms-full.txt b/llms-full.txt index 72f7379e86..88f5cb415e 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -785,7 +785,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. 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), 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) | +| 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) | diff --git a/packages/desktop/CHANGELOG.md b/packages/desktop/CHANGELOG.md index 4ff42cefb2..59d5a064d0 100644 --- a/packages/desktop/CHANGELOG.md +++ b/packages/desktop/CHANGELOG.md @@ -19,6 +19,8 @@ "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. diff --git a/packages/desktop/openadapt_desktop/portal/shell/app.js b/packages/desktop/openadapt_desktop/portal/shell/app.js index 614d6e17e7..1c875ebff1 100644 --- a/packages/desktop/openadapt_desktop/portal/shell/app.js +++ b/packages/desktop/openadapt_desktop/portal/shell/app.js @@ -988,7 +988,9 @@ function saveSources(presentation) { 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.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( @@ -999,6 +1001,8 @@ function saveSources(presentation) { 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, }, ]), ); @@ -1236,7 +1240,12 @@ function sourceMarkup(card, field) { row.intended === null ? "" : `${row.heldDiffers ? 'Differs ' : ""}Task says: ${esc(row.intended === "" ? "empty" : row.intended)}`; - return `${intended}${row.differs ? 'Differs ' : ""}Source: ${esc(text)}`; + // 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) { diff --git a/packages/desktop/src/portalShell.test.ts b/packages/desktop/src/portalShell.test.ts index 76c8b296cf..48503cea43 100644 --- a/packages/desktop/src/portalShell.test.ts +++ b/packages/desktop/src/portalShell.test.ts @@ -395,6 +395,34 @@ describe("the card shows what will be saved", () => { 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({ diff --git a/packages/flow/docs/GUARD_AN_AGENT.md b/packages/flow/docs/GUARD_AN_AGENT.md index 12d6f7a3fd..2da994ae91 100644 --- a/packages/flow/docs/GUARD_AN_AGENT.md +++ b/packages/flow/docs/GUARD_AN_AGENT.md @@ -149,6 +149,7 @@ or the paired phone) lists every field the task writes: |---|---| | 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. | @@ -156,8 +157,12 @@ 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, and asks the person to compare the screen with the -task's values. It says "exactly what will be saved" only when every value came +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. 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. @@ -199,6 +204,7 @@ ledger's words: | 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` | diff --git a/packages/flow/openadapt_flow/agent_guard/approval_fields.py b/packages/flow/openadapt_flow/agent_guard/approval_fields.py index 4e5a0238f0..32813a0db3 100644 --- a/packages/flow/openadapt_flow/agent_guard/approval_fields.py +++ b/packages/flow/openadapt_flow/agent_guard/approval_fields.py @@ -17,6 +17,11 @@ * ``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`). @@ -81,6 +86,10 @@ class SourceRow: #: 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 { @@ -90,6 +99,8 @@ def to_dict(self) -> dict[str, Any]: "differs": self.differs, "intended": self.intended, "held_differs": self.held_differs, + "screen": self.screen, + "screen_differs": self.screen_differs, } @@ -106,6 +117,21 @@ class ApprovalCard: #: 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.""" @@ -116,6 +142,8 @@ def intent_note(self) -> str: ". 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) @@ -238,6 +266,7 @@ def build_card( 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. @@ -246,6 +275,8 @@ def build_card( (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 @@ -284,11 +315,15 @@ def build_card( 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: @@ -313,6 +348,7 @@ def build_card( not_covered=not_covered, values_read=values_read, values_how=how, + screen_read=any(r.screen is not None for r in source_rows), ) @@ -336,7 +372,11 @@ def write_sources(run_dir: Path, request: Any, card: ApprovalCard) -> Path: "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}, + "values": { + "read": card.values_read, + "how": card.values_how, + "screen_read": card.screen_read, + }, }, ) return path @@ -374,6 +414,9 @@ def read_sources_for(run_dir: Path, request: Any) -> Optional[list[dict[str, Any 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], @@ -382,17 +425,27 @@ def read_sources_for(run_dir: Path, request: Any) -> Optional[list[dict[str, Any "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 card_for_request(guard: Any, request: Any, scope: Any) -> Any: +def card_for_request( + guard: Any, + request: Any, + scope: Any, + *, + controls: Optional[Sequence[Mapping[str, str]]] = 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. None when no card is asked for (or it is turned off).""" + 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" @@ -400,8 +453,16 @@ def card_for_request(guard: Any, request: Any, scope: Any) -> Any: 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" + 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 diff --git a/packages/flow/openadapt_flow/agent_guard/cdp.py b/packages/flow/openadapt_flow/agent_guard/cdp.py index 7a2ec055d0..539921123d 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, str]]]: + """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/commit_guard.py b/packages/flow/openadapt_flow/agent_guard/commit_guard.py index def9f7b328..663c8b0249 100644 --- a/packages/flow/openadapt_flow/agent_guard/commit_guard.py +++ b/packages/flow/openadapt_flow/agent_guard/commit_guard.py @@ -285,8 +285,15 @@ def _commit( ) -> None: from openadapt_flow.agent_guard.approval_fields import card_for_request - guard.approval_card = card_for_request(guard, request, self.scope) - shot = self.page.screenshot() if self.guarded.approval == "each_item" else None + 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) diff --git a/packages/flow/openadapt_flow/agent_guard/ledger_row.py b/packages/flow/openadapt_flow/agent_guard/ledger_row.py index d87032afdb..3b955ae9dd 100644 --- a/packages/flow/openadapt_flow/agent_guard/ledger_row.py +++ b/packages/flow/openadapt_flow/agent_guard/ledger_row.py @@ -40,6 +40,7 @@ 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 ============================= ================ ========================== @@ -186,6 +187,9 @@ def refusal_outcome(code: str, *, scope: bool = False) -> tuple[str, str]: 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_")): 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..c4e312da85 --- /dev/null +++ b/packages/flow/openadapt_flow/agent_guard/screen_values.py @@ -0,0 +1,142 @@ +"""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 ``