From b779bcc6ae5a00a84f4c769864def29ca11ea212 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 18:26:33 -0500 Subject: [PATCH 1/9] feat(flow): opt-in governed fallback from a compiled program to the agent on drift FallbackPolicy hands a wrapped task to the agent only when the compiled run halted before any effect (proved from the hold, the bound report and the cache's record check), behind a pre-commit gate and its own spend cap. The default stays the hold. Adds openadapt-flow wrap-dispatch (run, status, release, evict), docs, a MockMed drift benchmark, and fixes stale rows in AGENT_FRAMEWORKS.md and CAPABILITIES.md. --- CAPABILITIES.md | 6 +- llms-full.txt | 6 +- .../flow/benchmark/wrap_fallback/README.md | 39 ++ .../flow/benchmark/wrap_fallback/measure.py | 167 +++++ .../flow/benchmark/wrap_fallback/results.json | 105 +++ packages/flow/docs/AGENT_FRAMEWORKS.md | 12 +- packages/flow/docs/WRAP_FALLBACK.md | 133 ++++ .../wrap-dispatch.md | 1 + packages/flow/openadapt_flow/__main__.py | 2 +- .../flow/openadapt_flow/wrap/dispatch_cli.py | 474 ++++++++++++++ packages/flow/openadapt_flow/wrap/fallback.py | 609 ++++++++++++++++++ .../flow/tests/e2e/test_wrap_fallback_e2e.py | 252 ++++++++ packages/flow/tests/test_wrap_dispatch_cli.py | 215 +++++++ packages/flow/tests/test_wrap_fallback.py | 552 ++++++++++++++++ 14 files changed, 2565 insertions(+), 8 deletions(-) create mode 100644 packages/flow/benchmark/wrap_fallback/README.md create mode 100644 packages/flow/benchmark/wrap_fallback/measure.py create mode 100644 packages/flow/benchmark/wrap_fallback/results.json create mode 100644 packages/flow/docs/WRAP_FALLBACK.md create mode 100644 packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md create mode 100644 packages/flow/openadapt_flow/wrap/dispatch_cli.py create mode 100644 packages/flow/openadapt_flow/wrap/fallback.py create mode 100644 packages/flow/tests/e2e/test_wrap_fallback_e2e.py create mode 100644 packages/flow/tests/test_wrap_dispatch_cli.py create mode 100644 packages/flow/tests/test_wrap_fallback.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 77cb5b857c..ad8d36ff9d 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -304,6 +304,7 @@ improvising or retrying when something is off. | A duplicate check that asks the system of record (generic FHIR R4 `Patient` search; OpenEMR REST and SQL adapters): every page read, stop on an exact match, send a close match to a person, proceed otherwise, fail closed on any read problem. Close matching is heuristic and misses some duplicates; it is not patient identity resolution. One source for qualification, runs and resume; a program can pin it | On main | Synthetic: unit and HTTP tests; live OpenEMR 8.0.0.3 search decided 6 of 6 known referrals right through FHIR | [DUPLICATE_CHECK.md](packages/flow/docs/DUPLICATE_CHECK.md) | | A switched-off `problems_only` gate asks a person before the save instead of stopping the item | Released | Synthetic; real app in [#1513](https://github.com/OpenAdaptAI/OpenAdapt/pull/1513) | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md#when-the-mode-turns-itself-off) | | Fleet drift patches: a verified fix with no patient data, shared across sites under policy, moved as files or through a local reference hub | Released, local reference hub | Simulator | `openadapt-flow fleet`, [FLEET_DRIFT_PATCHES.md](packages/flow/docs/FLEET_DRIFT_PATCHES.md) | +| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check that found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED` or a receipt that is not `VERIFIED`. The agent runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate and its own spend cap; its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs the admitted program first and exposes the hold (`status`, `release`, `evict`) | On main | Synthetic: unit tests on the real cache, hold and report checks; MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](packages/flow/benchmark/wrap_fallback/README.md)) | `openadapt-flow wrap-dispatch`, `openadapt_flow.wrap.fallback`, [WRAP_FALLBACK.md](packages/flow/docs/WRAP_FALLBACK.md) | ## Computer-use agents @@ -319,8 +320,8 @@ improvising or retrying when something is off. | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md) | | See what your own agent gets wrong, with no risk: `openadapt shadow` is a loopback pass-through proxy beside the agent. It checks each write against the system of record (FHIR through `ensure_record`; SQL through the verifier's whole-database frame), checks each `CONFIRMED` again later, and writes `report.html` and `report.json`. It never blocks, changes or resends a write; the only delay is the read before a write (at most `hold_ms`) | [#1678](https://github.com/OpenAdaptAI/OpenAdapt/pull/1678) | Real app (Medplum 5.2.8, 37 cases through a fault proxy: scripted agent 18 of 18 harms caught, 0 correct writes refuted; Claude Sonnet 5.5 9 of 9 caught, 4 correct but corrected writes refuted; 0 writes by the shadow; 15 to 25 ms median added per write; setup 76.5 s machine time, 3 decisions); real app, SQL mode (Dolibarr 21 on MariaDB 11.4, 13 cases: 8 of 8 harms caught, 5 of 5 correct writes confirmed, 292 ms median added); synthetic (SQLite) | `openadapt shadow`, [SHADOW_MODE.md](packages/flow/docs/SHADOW_MODE.md), [SHADOW_RESULTS.md](packages/flow/benchmark/fhir_medplum/public/SHADOW_RESULTS.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](packages/flow/benchmark/skill_cache/README.md) | -| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (draft), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | -| Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | 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` | +| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | 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) | @@ -446,6 +447,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. +- `wrap-dispatch`: Run a wrapped task's admitted program. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate; `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). **Proof:** diff --git a/llms-full.txt b/llms-full.txt index cfb52865db..cb95cee0b2 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -744,6 +744,7 @@ improvising or retrying when something is off. | A duplicate check that asks the system of record (generic FHIR R4 `Patient` search; OpenEMR REST and SQL adapters): every page read, stop on an exact match, send a close match to a person, proceed otherwise, fail closed on any read problem. Close matching is heuristic and misses some duplicates; it is not patient identity resolution. One source for qualification, runs and resume; a program can pin it | On main | Synthetic: unit and HTTP tests; live OpenEMR 8.0.0.3 search decided 6 of 6 known referrals right through FHIR | [DUPLICATE_CHECK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/DUPLICATE_CHECK.md) | | A switched-off `problems_only` gate asks a person before the save instead of stopping the item | Released | Synthetic; real app in [#1513](https://github.com/OpenAdaptAI/OpenAdapt/pull/1513) | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md#when-the-mode-turns-itself-off) | | Fleet drift patches: a verified fix with no patient data, shared across sites under policy, moved as files or through a local reference hub | Released, local reference hub | Simulator | `openadapt-flow fleet`, [FLEET_DRIFT_PATCHES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FLEET_DRIFT_PATCHES.md) | +| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check that found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED` or a receipt that is not `VERIFIED`. The agent runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate and its own spend cap; its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs the admitted program first and exposes the hold (`status`, `release`, `evict`) | On main | Synthetic: unit tests on the real cache, hold and report checks; MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/wrap_fallback/README.md)) | `openadapt-flow wrap-dispatch`, `openadapt_flow.wrap.fallback`, [WRAP_FALLBACK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_FALLBACK.md) | ## Computer-use agents @@ -759,8 +760,8 @@ improvising or retrying when something is off. | Verify any agent's own writes: `openadapt verify` reads the system of record before and after a write, against a contract the operator owns (REST, FHIR, SQL, GraphQL), and returns a verified receipt (`openadapt.effect-receipt/v1`) or a refusal (`REFUTED`, `UNCERTAIN`), never an unverified success. Python SDK (`openadapt.verify`, which is `openadapt_flow.verifier`: `begin_write`, `verify_write`, `verified_write`) wraps a write in any agent framework; the MCP server (`openadapt verify serve`) offers `verify_begin`, `verify_check` and `verify_recheck` to any MCP client | Released ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589)) | Synthetic (MockMed's fault server over real HTTP: correct write, wrong record, not saved, saved twice, unreadable store) | `openadapt verify`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md) | | See what your own agent gets wrong, with no risk: `openadapt shadow` is a loopback pass-through proxy beside the agent. It checks each write against the system of record (FHIR through `ensure_record`; SQL through the verifier's whole-database frame), checks each `CONFIRMED` again later, and writes `report.html` and `report.json`. It never blocks, changes or resends a write; the only delay is the read before a write (at most `hold_ms`) | [#1678](https://github.com/OpenAdaptAI/OpenAdapt/pull/1678) | Real app (Medplum 5.2.8, 37 cases through a fault proxy: scripted agent 18 of 18 harms caught, 0 correct writes refuted; Claude Sonnet 5.5 9 of 9 caught, 4 correct but corrected writes refuted; 0 writes by the shadow; 15 to 25 ms median added per write; setup 76.5 s machine time, 3 decisions); real app, SQL mode (Dolibarr 21 on MariaDB 11.4, 13 cases: 8 of 8 harms caught, 5 of 5 correct writes confirmed, 292 ms median added); synthetic (SQLite) | `openadapt shadow`, [SHADOW_MODE.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/SHADOW_MODE.md), [SHADOW_RESULTS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/fhir_medplum/public/SHADOW_RESULTS.md) | | Skill cache for framework agents: an agent in any framework does a browser task through compile-agent's harness as plain tools (`BrowserTools`); when the system of record shows exactly the task's record and the operator confirms the checks, the run is canaried, admitted and emitted as an MCP server. A repeat of the same task (instruction, record, app, contract, environment) calls that tool instead of the agent: no model calls, the program's checks and this task's record check on every run, eviction after a failed run | Released | Synthetic (MockMed, LangGraph on `claude-sonnet-5-5`, 3 trials, repeats on the same record: run 1 6 model calls and $0.022; runs 2 to 10 27/27 VERIFIED, 0 model calls, 7.8 s median); Trac 1.6: run 1 verified, not admitted | `openadapt_flow.integrations.agents.skills`, [benchmark/skill_cache](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/skill_cache/README.md) | -| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (draft), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | -| Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | 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` | +| Publish a wrapped task as a hosted endpoint with one credential: `openadapt wrap publish --task TASK` uses only `OPENADAPT_API_KEY`. It finds the task's admitted program, re-verifies its admission signature, refuses a held task, a program without a read-back check (no saving step, a save with no effect contract, or no confirmed `verify.yaml`), symbolic links and a non-public app URL, and stages the bundle with its read-back configuration. It sanitizes the bundle and the recording it was compiled from (the generated wrap files declare each field as content, always scrubbed, or structural, kept only with its machine shape, so schema ids, step ids, digests and the signed admission survive the scrub byte-for-byte), shows one summary and asks once (`--yes` for scripts), finds the key's organization (`GET /api/v1/whoami`, or `--org`), registers the local admission public key with it once, attests the program from the wrap run's own signed recording and attended canary (strict lint with no warn or error finding, certification, VERIFIED replay) against a challenge from the organization's API-key route, uploads it through the governed bundle push to `POST /api/v1/org/{org}/workflow` (or `PUT .../workflow/{id}/definition`), then reads the Cloud workflow definition and prints the endpoint URL and `curl` examples from the acknowledged `execute_path` and `qualification_id`. Each refusal is one line with a code. The upload carries the program's value-free Standard run shape. A managed run of the program rests on its signed admission: `openadapt-flow run --managed-dispatch-file` checks the admission against the registered admission key, requires the authorization to name that admission and match the shape, and reads back through the bundled `verify.yaml`. The CLI, public runtime and deployment API carry one-use verification bound to that dispatch's admission, bundle, inputs, policy, run, session and current trust registry; resume verifies a fresh proof. Each input checks that scope again after preparation and requires a signed v3 permit with a receiver-checked exclusive start deadline. API sequences acknowledge every request separately. Missing receipts or late completion evidence halt further input and require reconciliation. Publish refuses, before anything is uploaded, an admission mode a hosted run cannot verify (only a person's admission or a registered CI admitter key), and an admitter-key admission whose key the organization has not registered (`GET /api/v1/org/{org}/admitter-keys`). The recording stays on the machine; only its sanitized hash is attested. Regulated is refused (`openadapt_flow.jit.hosted_authority`) | On main | Unit tests (real bundle, record check, staging, local sanitization and signed wrap evidence; the attestation's recording binding checked on real derivatives; the whoami, admission-key, challenge, workflow upload and definition routes mocked at the HTTP boundary); no run against a live Cloud deployment. Relies on the API-key workflow routes in openadapt-cloud#430 (merged 2026-11-14), which accept this v2 attestation only behind a flag that is off by default; the whoami route is not in #430 yet | `openadapt_flow.wrap.publish`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md), `packages/flow/tests/test_wrap_publish.py`, `packages/flow/tests/test_jit_hosted_authority.py`, `packages/flow/tests/test_jit_hosted_managed_replay.py` | +| Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | On main ([#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294), merged 2026-11-20) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | 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) | @@ -886,6 +887,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. +- `wrap-dispatch`: Run a wrapped task's admitted program. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate; `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). **Proof:** diff --git a/packages/flow/benchmark/wrap_fallback/README.md b/packages/flow/benchmark/wrap_fallback/README.md new file mode 100644 index 0000000000..15510f707c --- /dev/null +++ b/packages/flow/benchmark/wrap_fallback/README.md @@ -0,0 +1,39 @@ +# Opt-in fallback on drift (MockMed) + +What happens when a wrapped task's compiled program meets a changed app and +the task has opted in to `FallbackPolicy` ([WRAP_FALLBACK.md](../../docs/WRAP_FALLBACK.md)). + +```bash +cd packages/flow +python benchmark/wrap_fallback/measure.py --out benchmark/wrap_fallback/results.json +``` + +For each MockMed drift mode, a scripted agent's run 1 is compiled and +admitted on the unchanged app (a registered key admits it after two +canaries). Then the app drifts, and the task runs once through the policy. +The fallback agent is scripted: it knows the drifted labels, and it makes no +model calls. A scripted gate stands in for the person and approves every +save that reaches it; a second trial per mode has it refuse. After each +trial the script reads MockMed's own store: `correct` is exactly one record +for the task's patient with the typed note, `none` is nothing saved, and +`wrong` is anything else. + +| Mode | What changed | Program | Gate approves | Gate refuses | +| --- | --- | --- | --- | --- | +| redesign | The save is renamed, given a new id and moved; a decoy "Submit feedback" is added | HALTED | agent_fallback: VERIFIED, saved correct, 1 approval | agent_fallback: GATE_REFUSED, saved none, 1 approval | +| relink | The control that opens the form is renamed and moved | HALTED | agent_fallback: VERIFIED, saved correct, 1 approval | agent_fallback: GATE_REFUSED, saved none, 1 approval | +| rename | Labels renamed (`Submit Encounter`, `View`) | VERIFIED | not reached (program verified) | not reached (program verified) | + +Summary: 3 drift modes, 6 trials. The program halted before the save on 2 modes and verified on 1 (the compiled program found the renamed labels). Fallbacks: 4, of which 2 verified (every approved one). Wrong saves: 0. Saves after a refusal: 0. Approvals asked for: 4. Model calls: 0. + +## Limits + +- Synthetic app, scripted agent, scripted gate, three drift modes. It shows + the policy's routing and safety on real browser runs; it does not measure + how often a model-driven agent finishes a drifted task. +- The compiled program runs in process on a thread, not over MCP, until the + MCP worker-thread fix in #2406 lands. +- `repair_opened` is false when the halted step is not a one-step target + replacement, so `SkillCache.open_repair` offers no candidate. + +Results: [results.json](results.json). diff --git a/packages/flow/benchmark/wrap_fallback/measure.py b/packages/flow/benchmark/wrap_fallback/measure.py new file mode 100644 index 0000000000..23ebff2c7e --- /dev/null +++ b/packages/flow/benchmark/wrap_fallback/measure.py @@ -0,0 +1,167 @@ +"""Measure the opt-in fallback on MockMed drifts, headless, synthetic data. + + python benchmark/wrap_fallback/measure.py --out benchmark/wrap_fallback/results.json + +For each drift mode: a scripted agent's run 1 is compiled and admitted on the +undrifted app, MockMed drifts, and the task runs once through +``FallbackPolicy`` with a scripted fallback agent that knows the drifted +labels and a gate that approves every save that reaches it (it stands in for +the person). One more trial per mode has the gate refuse. After every trial +the script reads MockMed's own store and classifies the outcome: ``correct`` +(exactly one record, for the task's patient, with the typed note), ``none`` +(nothing saved) or ``wrong`` (anything else). + +The compiled program runs in process on a thread (the MCP worker-thread fix +is #2406). No model is called. +""" + +from __future__ import annotations + +import argparse +import json +import platform +import sys +import tempfile +import time +from pathlib import Path +from typing import Any + +HERE = Path(__file__).resolve().parent +FLOW = HERE.parents[1] +sys.path.insert(0, str(FLOW)) + +from tests.e2e.test_wrap_fallback_e2e import ( # noqa: E402 + NOTE, + PROMPT, + DriftableMockMed, + Gate, + admitted, + saved, + steps, +) + +#: Drift modes, and the steps the scripted fallback agent takes on each. +MODES: dict[str, list] = { + "rename": steps(save="Submit Encounter", new="New Encounter"), + "redesign": steps(save="Submit to chart"), + "relink": steps(new="Start visit"), +} + + +class Env: + """The two monkeypatch calls the shared helpers make, outside pytest.""" + + def __init__(self) -> None: + self.undo: list = [] + + def setenv(self, name: str, value: str) -> None: + import os + + self.undo.append(("env", name, os.environ.get(name))) + os.environ[name] = value + + def setattr(self, target: Any, name: str, value: Any) -> None: + self.undo.append(("attr", target, name, getattr(target, name))) + setattr(target, name, value) + + def close(self) -> None: + import os + + for item in reversed(self.undo): + if item[0] == "env": + if item[2] is None: + os.environ.pop(item[1], None) + else: + os.environ[item[1]] = item[2] + else: + setattr(item[1], item[2], item[3]) + + +def classify(rows: list) -> str: + if not rows: + return "none" + return "correct" if rows == [("p1", "Triage", NOTE)] else "wrong" + + +def trial(mode: str, approve: bool) -> dict[str, Any]: + from openadapt_flow.agent.repair import RepairAccessPolicy, RepairDesk + from openadapt_flow.compile_agent import ScriptedAgent + from openadapt_flow.wrap.fallback import FallbackPolicy + + env = Env() + with tempfile.TemporaryDirectory(prefix="wrap-fallback-") as raw: + tmp = Path(raw) + app = DriftableMockMed(tmp / "app") + try: + cache = admitted(tmp, app, env) + app.drift(mode) + gate = Gate(approve=approve) + policy = FallbackPolicy( + cache, + max_cost_usd=0.5, + gate=gate, + repair_desk=RepairDesk(tmp / "repairs", RepairAccessPolicy(None)), + ) + started = time.monotonic() + run = policy.run(PROMPT, {"note": NOTE}, ScriptedAgent(steps=MODES[mode])) + seconds = round(time.monotonic() - started, 2) + rows = saved(app) + finally: + app.stop() + env.close() + last = policy.last or {} + program = run.replay if run.path == "skill" else run.replay.get("program") + return { + "mode": mode, + "gate": "approve" if approve else "refuse", + "program_status": program.get("status") if isinstance(program, dict) else None, + "path": run.path, + "status": run.status, + "verified": run.verified, + "fallback_reason": last.get("reason"), + "approvals_needed": len(gate.requests), + "model_calls": run.model_calls, + "seconds": seconds, + "saved": classify(rows), + "repair_opened": bool((last.get("repair") or {}).get("opened")), + } + + +def main() -> int: + parser = argparse.ArgumentParser() + parser.add_argument("--out", required=True) + parser.add_argument("--modes", nargs="*", default=sorted(MODES)) + args = parser.parse_args() + trials = [trial(m, approve) for m in args.modes for approve in (True, False)] + fell_back = [t for t in trials if t["path"] == "agent_fallback"] + summary = { + "drifts": len(args.modes), + "trials": len(trials), + "program_verified": sum(t["path"] == "skill" and t["verified"] for t in trials), + "fallbacks": len(fell_back), + "fallback_verified": sum(t["verified"] for t in fell_back), + "wrong_saves": sum(t["saved"] == "wrong" for t in trials), + "saves_after_refusal": sum( + t["gate"] == "refuse" and t["saved"] != "none" and t["path"] != "skill" + for t in trials + ), + "approvals_needed": sum(t["approvals_needed"] for t in trials), + "model_calls": sum(t["model_calls"] or 0 for t in trials), + } + result = { + "schema": "openadapt.wrap-fallback-benchmark/v1", + "app": "MockMed (synthetic), headless Chromium", + "agent": "scripted (no model)", + "gate": "scripted: approves or refuses every save that reaches it", + "measured_at": time.strftime("%Y-%m-%d"), + "python": platform.python_version(), + "summary": summary, + "trials": trials, + } + Path(args.out).write_text(json.dumps(result, indent=2) + "\n", encoding="utf-8") + print(json.dumps(summary, indent=2)) + return 0 if summary["wrong_saves"] == 0 else 1 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/flow/benchmark/wrap_fallback/results.json b/packages/flow/benchmark/wrap_fallback/results.json new file mode 100644 index 0000000000..84eee52007 --- /dev/null +++ b/packages/flow/benchmark/wrap_fallback/results.json @@ -0,0 +1,105 @@ +{ + "schema": "openadapt.wrap-fallback-benchmark/v1", + "app": "MockMed (synthetic), headless Chromium", + "agent": "scripted (no model)", + "gate": "scripted: approves or refuses every save that reaches it", + "measured_at": "2026-11-21", + "python": "3.12.13", + "summary": { + "drifts": 3, + "trials": 6, + "program_verified": 2, + "fallbacks": 4, + "fallback_verified": 2, + "wrong_saves": 0, + "saves_after_refusal": 0, + "approvals_needed": 4, + "model_calls": 0 + }, + "trials": [ + { + "mode": "redesign", + "gate": "approve", + "program_status": "HALTED", + "path": "agent_fallback", + "status": "VERIFIED", + "verified": true, + "fallback_reason": null, + "approvals_needed": 1, + "model_calls": 0, + "seconds": 24.2, + "saved": "correct", + "repair_opened": true + }, + { + "mode": "redesign", + "gate": "refuse", + "program_status": "HALTED", + "path": "agent_fallback", + "status": "GATE_REFUSED", + "verified": false, + "fallback_reason": null, + "approvals_needed": 1, + "model_calls": 0, + "seconds": 17.08, + "saved": "none", + "repair_opened": false + }, + { + "mode": "relink", + "gate": "approve", + "program_status": "HALTED", + "path": "agent_fallback", + "status": "VERIFIED", + "verified": true, + "fallback_reason": null, + "approvals_needed": 1, + "model_calls": 0, + "seconds": 17.3, + "saved": "correct", + "repair_opened": true + }, + { + "mode": "relink", + "gate": "refuse", + "program_status": "HALTED", + "path": "agent_fallback", + "status": "GATE_REFUSED", + "verified": false, + "fallback_reason": null, + "approvals_needed": 1, + "model_calls": 0, + "seconds": 19.21, + "saved": "none", + "repair_opened": false + }, + { + "mode": "rename", + "gate": "approve", + "program_status": "VERIFIED", + "path": "skill", + "status": "VERIFIED", + "verified": true, + "fallback_reason": null, + "approvals_needed": 0, + "model_calls": 0, + "seconds": 6.08, + "saved": "correct", + "repair_opened": false + }, + { + "mode": "rename", + "gate": "refuse", + "program_status": "VERIFIED", + "path": "skill", + "status": "VERIFIED", + "verified": true, + "fallback_reason": null, + "approvals_needed": 0, + "model_calls": 0, + "seconds": 6.1, + "saved": "correct", + "repair_opened": false + } + ] +} diff --git a/packages/flow/docs/AGENT_FRAMEWORKS.md b/packages/flow/docs/AGENT_FRAMEWORKS.md index 43ac7e98ef..ed06c8bcdf 100644 --- a/packages/flow/docs/AGENT_FRAMEWORKS.md +++ b/packages/flow/docs/AGENT_FRAMEWORKS.md @@ -239,7 +239,13 @@ What each skill run has: record check fails, the result is `RECORD_CHECK_FAILED` with the check's reasons, for a person to look at the record. -A skill that fails a run is evicted: it moves to `/evicted/`, and -the next run of the task goes to the agent and compiles afresh. -`cache.evict(prompt, params)` does the same by hand. Skills live in +A skill that fails a run is held, not rerun by the agent: the next run of the +task returns `CACHE_HALTED` with the stop's reason, makes no model calls, and +keeps the halt as evidence until a person reconciles, repairs or releases it. +`cache.evict(prompt, params)` sets the skill aside by hand (it moves to +`/evicted/`), and the next run goes to the agent and compiles +afresh. To send a proved pre-effect drift to the agent behind a pre-commit +gate instead, opt in per task with `FallbackPolicy` or +`openadapt-flow wrap-dispatch --fallback agent` +([WRAP_FALLBACK.md](WRAP_FALLBACK.md)). Skills live in `~/.openadapt/skills` unless you pass `cache_dir=`. diff --git a/packages/flow/docs/WRAP_FALLBACK.md b/packages/flow/docs/WRAP_FALLBACK.md new file mode 100644 index 0000000000..e4bdccb9a0 --- /dev/null +++ b/packages/flow/docs/WRAP_FALLBACK.md @@ -0,0 +1,133 @@ +# Fall back to the agent when a wrapped program drifts + +A wrapped task runs its compiled program with no model calls. When the +program stops, the default is to hold the task: every later call returns +`CACHE_HALTED`, the agent is not run again, and a person reconciles, repairs +or releases the hold. That stays the default. + +For a task where a person would rather have the agent finish the work than +wait, the fallback is an opt-in per task. It hands the task back to the agent +only when the program's stop is proved to have written nothing, and the agent +runs with a person approving each save. + +```bash +openadapt-flow wrap-dispatch --task task.json --request-id r-118 \ + --param note="Synthetic follow-up" \ + --fallback agent --fallback-max-cost-usd 0.50 +``` + +In Python, wrap the task's `SkillCache`: + +```python +from openadapt_flow.wrap.fallback import FallbackPolicy + +policy = FallbackPolicy(cache, max_cost_usd=0.50) # gate: the terminal confirm +run = policy.run(prompt, params, agent) +``` + +## When the agent gets the task + +All of these must hold. Each is read from files on disk, not from the reply's +status text: + +- The cache's hold is a terminal halt (`phase: halted`). A hold left in + `running` means a reply was lost and a save may exist. +- The halted run's `report.json` belongs to the admitted bundle: its workflow + name, its bundle digest, the digest in the hold and the digest in the + verified admission all match. +- The report says `HALTED` and `HALTED_BEFORE_EFFECT`, and + `steps_requiring_reconciliation` (from `openadapt_flow.transaction`) lists + no step. +- The halted reply recorded exactly zero model calls. +- The cache's own record check of the halted run found no new, changed or + removed record of the task's record. The policy keeps that check beside the + halt, so a later call that finds the task held can fall back on the same + halt. + +It never falls back on `RECONCILIATION_REQUIRED`, a lost reply, +`RECORD_CHECK_FAILED`, `RECEIPT_NOT_VERIFIED`, `MODEL_CALLS_NOT_ZERO`, a +missing baseline, or a halt the policy did not see with a clean record check. +Those stay held, exactly as without the policy. + +These are the checks `SkillCache.open_repair` makes before it offers a +repair, without its extra rule that the fix is a one-step target +replacement. A drift that needs more than one new step can fall back; it +then gets no repair candidate. + +## What the fallback run is + +The fallback is a run 1 through compile-agent's harness, in its own +directory beside the task's cache (`/fallback///`): + +- the right-record check before every save; +- a pre-commit gate before every save. The default `TerminalGate` is + compile-agent's terminal confirmation; with no terminal it refuses, and the + agent is not started (`FALLBACK_GATE_UNATTENDED`). Any object with + `__call__(request) -> bool` can be the gate; +- the app's origin fence; +- a read-back of every save from the system of record, and the record check + of run 1; +- its own spend cap, `--fallback-max-cost-usd` (no default). The policy sets + the agent's own cap to the lower of the two for the run, and the gate + refuses a save when the spend so far is over the cap or unknown. An agent + with model calls and no settable cap is not started + (`FALLBACK_COST_UNBOUNDED`); +- its own request ID (default `.fallback`), which runs once. + +The run's draft program is never confirmed or admitted. A verified fallback +leaves the task held and opens a repair candidate with +`SkillCache.open_repair` when the halt is a one-step target replacement. The +repair token is kept in `repair.json` in the run directory (mode 0600). A +person demonstrates and approves the repair, and +`SkillCache.complete_repair` runs its canaries and selects it. Nothing in the +fallback path does either step. + +A fallback that raises, or ends without proving what it wrote, leaves an +in-flight marker. Every later fallback of the task then returns +`RECONCILIATION_REQUIRED` until a person checks the record and runs +`wrap-dispatch release TASK --person NAME --after-reconciling`. + +## The dispatcher + +`openadapt-flow wrap-dispatch` runs only the admitted program: + +| Situation | Result `path` | `status` | +| --- | --- | --- | +| The program ran | `program` | its status (`VERIFIED`, `HALTED` ...) | +| No admitted program | `held` | `NO_ADMITTED_PROGRAM` (nothing runs; `openadapt wrap` makes the first run) | +| The task is held, no fallback | `held` | `CACHE_HALTED` | +| The fallback ran or was refused | `agent_fallback` | `VERIFIED`, `GATE_REFUSED`, `COST_CAP_EXCEEDED` ... | + +Each run prints one JSON object with `openadapt wrap`'s per-run fields +(`request_id`, `run_id`, `status`, `verified`, `model_calls`, `cost_usd`, +`usage`, `usage_known`, `seconds`, `wire_checked`, `receipt`, +`receipt_outcome`, `receipt_binding`), with `path` as in the table, plus +`outcome` (`VERIFIED`, `ESCALATED`, `CAUGHT_ERROR` or `FAILED`) and +`fallback` (what the policy did, or null). `--result FILE` also writes it to +a file. Requests go through the same run store as `openadapt wrap`, so a +retried request ID returns its first result. + +The hold verbs: + +- `wrap-dispatch status TASK`: the hold's phase and reason, whether an + admitted program is served, whether the hold may fall back and why, and + the task's fallback runs. +- `wrap-dispatch release TASK --person NAME`: a person at a terminal types + `release`. The hold file is archived next to a record of who released it. + A hold that may have written (`running`, unreadable) or a stuck fallback + needs `--after-reconciling`. +- `wrap-dispatch evict TASK`: sets the program aside as evidence; the next + `openadapt wrap` run compiles afresh. + +## Not covered yet + +- Compiled browser runs over MCP need the worker-thread fix in + [#2406](https://github.com/OpenAdaptAI/OpenAdapt/pull/2406) under mcp + 1.30.0. The end-to-end test runs the program in-process until then. +- `openadapt wrap run` does not dispatch through this policy yet (#2407). +- The gate is the terminal confirmation. The guard approval card and the + flight gate are the next gates. +- Fallback runs have no receipt of their own (#2394); the evidence is the + harness's gate log, read-backs and record check. + +Measured on MockMed: [benchmark/wrap_fallback](../benchmark/wrap_fallback/README.md). diff --git a/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md b/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md new file mode 100644 index 0000000000..a26a48dd35 --- /dev/null +++ b/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md @@ -0,0 +1 @@ +Run a wrapped task's admitted program. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate; `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 5de90f3d77..f471558f43 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -10178,7 +10178,7 @@ def build_parser() -> argparse.ArgumentParser: q.add_argument("variant_set", help="Variant-set directory") q.set_defaults(func=_cmd_variants) p.set_defaults(func=_cmd_variants) - + __import__("openadapt_flow.wrap.dispatch_cli", fromlist=["_"]).register(sub) p = sub.add_parser( "route", help=( diff --git a/packages/flow/openadapt_flow/wrap/dispatch_cli.py b/packages/flow/openadapt_flow/wrap/dispatch_cli.py new file mode 100644 index 0000000000..a95f4c3153 --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/dispatch_cli.py @@ -0,0 +1,474 @@ +"""``openadapt-flow wrap-dispatch``: run a wrapped task's admitted program. + + openadapt-flow wrap-dispatch --task TASK --request-id ID --param NAME=VALUE + openadapt-flow wrap-dispatch --task TASK --request-id ID --param NAME=VALUE \\ + --fallback agent --fallback-max-cost-usd 0.50 + openadapt-flow wrap-dispatch status TASK + openadapt-flow wrap-dispatch release TASK --person NAME + openadapt-flow wrap-dispatch evict TASK + +A run uses only the task's admitted program. With no admitted program it +reports ``NO_ADMITTED_PROGRAM`` and runs nothing (``openadapt wrap`` makes the +first run). When the program stops, the task is held, as ``openadapt wrap`` +holds it, unless ``--fallback agent`` is given: then +:class:`~openadapt_flow.wrap.fallback.FallbackPolicy` may hand a proved +pre-effect drift to the agent behind a pre-commit gate at this terminal. + +Each run prints one result JSON with ``openadapt wrap``'s per-run fields +(``path``, ``status``, ``verified``, ``model_calls``, ``cost_usd``, +``seconds`` ...), where ``path`` is ``program``, ``agent_fallback`` or +``held``, plus ``outcome``: ``VERIFIED``, ``ESCALATED``, ``CAUGHT_ERROR`` +or ``FAILED``. See docs/WRAP_FALLBACK.md. +""" + +from __future__ import annotations + +import argparse +import json +import math +import sys +import time +from collections.abc import Mapping, Sequence +from pathlib import Path +from typing import Any, Optional + +#: The program, or the agent, needs a person to look before the task goes on. +_ESCALATED = frozenset( + { + "CACHE_HALTED", + "HALTED", + "NO_ADMITTED_PROGRAM", + "RECONCILIATION_REQUIRED", + "REQUEST_ID_CONFLICT", + "GATE_REFUSED", + "FALLBACK_GATE_UNATTENDED", + "FALLBACK_NO_AGENT", + "FALLBACK_COST_UNBOUNDED", + "FALLBACK_REQUEST_REUSED", + "refused_by_hold", + } +) +#: A check stopped something wrong from passing as done. +_CAUGHT = frozenset( + { + "RECORD_CHECK_FAILED", + "RECEIPT_NOT_VERIFIED", + "MODEL_CALLS_NOT_ZERO", + "COST_CAP_EXCEEDED", + "GATE_NOT_PROVED", + "BASELINE_UNAVAILABLE", + "refused_wrong_record", + "readback_wrong_record", + "readback_refused", + "record_check_failed", + } +) +_HOLD_VERBS = ("status", "release", "evict") + + +def outcome(result: Mapping[str, Any]) -> str: + """The run's accounting outcome, from its status alone.""" + if result.get("verified") is True: + return "VERIFIED" + status = str(result.get("status")) + if status in _ESCALATED: + return "ESCALATED" + if status in _CAUGHT: + return "CAUGHT_ERROR" + return "FAILED" + + +def dispatch_path(result: Mapping[str, Any]) -> str: + """``program``, ``agent_fallback`` or ``held`` for one run's result.""" + from openadapt_flow.wrap.fallback import FALLBACK_PATH + + if result.get("path") == FALLBACK_PATH: + return FALLBACK_PATH + if result.get("status") in ("CACHE_HALTED", "NO_ADMITTED_PROGRAM"): + return "held" + return "program" + + +def finish( + result: dict[str, Any], fallback: Optional[Mapping[str, Any]] +) -> dict[str, Any]: + """Add the dispatch fields to a WrappedTask per-run result.""" + out = dict(result) + out["path"] = dispatch_path(result) + out["outcome"] = outcome(result) + out["fallback"] = dict(fallback) if fallback is not None else None + return out + + +# -- parser ------------------------------------------------------------------------ + + +def _add_task(p: argparse.ArgumentParser) -> None: + p.add_argument("task", help="Generated task and read-back configuration") + p.add_argument("--key-dir", help="Existing admission key directory") + + +def register(sub: argparse._SubParsersAction) -> None: + """Add ``wrap-dispatch`` to ``openadapt-flow``.""" + p = sub.add_parser( + "wrap-dispatch", + help=( + "Run a wrapped task's admitted program; on a proved pre-effect " + "drift, optionally hand it to the agent behind a pre-commit gate" + ), + allow_abbrev=False, + ) + add_run_arguments(p) + verbs = p.add_subparsers(dest="dispatch_verb") + q = verbs.add_parser( + "status", help="Show the task's hold and fallback runs", allow_abbrev=False + ) + _add_task(q) + q = verbs.add_parser( + "release", + help="A person releases the task's hold (the evidence is kept)", + allow_abbrev=False, + ) + _add_task(q) + q.add_argument("--person", required=True, help="Who checked and releases it") + q.add_argument( + "--after-reconciling", + action="store_true", + help="Also release a hold or fallback that may have written, after " + "the person checked the record", + ) + q = verbs.add_parser( + "evict", + help="Set the task's program aside (kept as evidence)", + allow_abbrev=False, + ) + _add_task(q) + p.set_defaults(func=cmd_wrap_dispatch) + + +def add_run_arguments(p: argparse.ArgumentParser) -> None: + p.add_argument("--task", help="Generated task and read-back configuration") + p.add_argument("--request-id", help="This request's ID (reused on a retry)") + p.add_argument( + "--param", + action="append", + default=[], + metavar="NAME=VALUE", + help="A task input (a sign-in input may come from " + "OPENADAPT_FLOW_SECRET_)", + ) + p.add_argument("--runs-dir", default="~/.openadapt/wrap/runs") + p.add_argument("--key-dir", help="Existing admission key directory") + p.add_argument("--teach-authorization", help="Signed teaching authorization") + p.add_argument("--approver-root", help="Pinned approver root for it") + p.add_argument( + "--fallback", + choices=("none", "agent"), + default="none", + help="On a proved pre-effect drift: hold (none, the default) or hand " + "the task to the agent behind a pre-commit gate (agent)", + ) + p.add_argument( + "--fallback-max-cost-usd", + type=float, + help="Model spend cap for the fallback run (required with --fallback agent)", + ) + p.add_argument( + "--fallback-request-id", + help="The fallback run's own ID (default: derived from --request-id)", + ) + p.add_argument("--provider", choices=("claude", "openai"), default="claude") + p.add_argument("--model") + p.add_argument( + "--price", + action="append", + default=[], + metavar="KIND=USD_PER_MTOK", + help="Explicit input, output, cache_write and cache_read model prices", + ) + p.add_argument("--price-model", help="Exact model covered by supplied prices") + p.add_argument("--pricing-source-url", help="Primary source for model prices") + p.add_argument("--pricing-verified-at", help="Date prices were verified") + p.add_argument("--max-turns", type=int, default=40) + p.add_argument("--max-run-seconds", type=float, default=110) + p.add_argument("--request-timeout-seconds", type=float, default=25) + p.add_argument("--max-input-bytes", type=int) + p.add_argument("--result", help="Also write the result JSON to this file") + + +# -- commands ---------------------------------------------------------------------- + + +class _NoAgent: + """Stands in when no fallback is configured: it never drives anything.""" + + requires_model_key = False + dialect = "generic" + principal_id = None + + def drive(self, request: Any, harness: Any) -> Any: + raise RuntimeError("wrap-dispatch has no agent for this run") + + +def _setup(task: str, key_dir: Optional[str], teach: Any = None) -> Any: + from openadapt_flow.integrations.agents.recording import load_task + + options: dict[str, Any] = {} + if key_dir: + options["key_dir"] = key_dir + if teach is not None: + options["teach_authorization"] = teach + return load_task(task, **options) + + +def _names(setup: Any) -> dict[str, str]: + # The cache key depends on parameter names, not their values. + return dict.fromkeys(setup.parameters, "") + + +def _emit(result: Mapping[str, Any], path: Optional[str]) -> None: + text = json.dumps(result, sort_keys=True, default=str) + if path: + Path(path).expanduser().write_text(text + "\n", encoding="utf-8") + print(text) + + +def _fallback_agent(args: argparse.Namespace, setup: Any) -> Any: + from openadapt_flow.integrations.agents.providers import build_agent + from openadapt_flow.jit.keys import load_customer_model_key + from openadapt_flow.wrap.cli import _prices + + agent = build_agent( + args.provider, + model=args.model, + max_turns=args.max_turns, + max_cost_usd=args.fallback_max_cost_usd, + prices=_prices(args.price), + max_run_seconds=args.max_run_seconds, + request_timeout_seconds=args.request_timeout_seconds, + max_input_bytes=args.max_input_bytes, + price_model=args.price_model, + pricing_source_url=args.pricing_source_url, + pricing_verified_at=args.pricing_verified_at, + ) + if getattr(agent, "requires_model_key", True): + provider = getattr(agent, "model_key_provider", None) + expected = "anthropic" if args.provider == "claude" else "openai" + if provider != expected: + raise SystemExit("provider adapter has no matching model-key provenance") + setup.cache.model_key = load_customer_model_key(provider) + return agent + + +def run( + args: argparse.Namespace, + *, + agent: Any = None, + gate: Any = None, + repair_desk: Any = None, +) -> dict[str, Any]: + """One dispatch. ``agent``, ``gate`` and ``repair_desk`` are for tests and + embedding; the CLI builds the provider agent and the terminal gate.""" + from openadapt_flow.wrap import WrappedTask + from openadapt_flow.wrap.cli import _params, _with_secret_env + + if not args.task or not args.request_id: + raise SystemExit("wrap-dispatch needs --task and --request-id") + fallback_on = args.fallback == "agent" + cap = args.fallback_max_cost_usd + if fallback_on and (cap is None or not math.isfinite(cap) or cap <= 0): + raise SystemExit("--fallback agent requires a positive --fallback-max-cost-usd") + if not fallback_on and (cap is not None or args.fallback_request_id): + raise SystemExit("--fallback-max-cost-usd needs --fallback agent") + from openadapt_flow.compile_agent.cli import _teach_authority + + setup = _setup(args.task, args.key_dir, _teach_authority(args)) + names = _names(setup) + started = time.monotonic() + if not setup.cache.held(setup.instruction, names) and ( + setup.cache.server(setup.instruction, names) is None + ): + # Never a first run: that is openadapt wrap's, with its own review. + result = { + "request_id": args.request_id, + "path": "held", + "status": "NO_ADMITTED_PROGRAM", + "verified": False, + "model_calls": 0, + "cost_usd": 0.0, + "usage": [], + "usage_known": True, + "seconds": round(time.monotonic() - started, 3), + "wire_checked": False, + "receipt": None, + "receipt_outcome": None, + } + return finish(result, None) + cache: Any = setup.cache + policy = None + if fallback_on: + from openadapt_flow.wrap.fallback import ( + FallbackPolicy, + TerminalGate, + fallback_root, + ) + + if repair_desk is None: + from openadapt_flow.agent.repair import RepairAccessPolicy, RepairDesk + + root = fallback_root(setup.cache, setup.instruction, names) + repair_desk = RepairDesk(root / "repairs", RepairAccessPolicy(None)) + if agent is None: + agent = _fallback_agent(args, setup) + policy = FallbackPolicy( + setup.cache, + max_cost_usd=cap, + gate=gate if gate is not None else TerminalGate(), + request_id=args.fallback_request_id or f"{args.request_id}.fallback", + repair_desk=repair_desk, + ) + cache = policy + task = WrappedTask( + cache=cache, + agent=agent if agent is not None else _NoAgent(), + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=args.runs_dir, + ) + values = _with_secret_env(_params(args.param), task.parameters) + result = task.call(args.request_id, values) + return finish(result, policy.last if policy is not None else None) + + +def _hold_file(setup: Any) -> Path: + from openadapt_flow.integrations.agents.skills import _STOP_FILE + + return Path(setup.cache.receipt_root(setup.instruction, _names(setup))) / _STOP_FILE + + +def status(args: argparse.Namespace) -> dict[str, Any]: + from openadapt_flow.privacy import scrub_text + from openadapt_flow.wrap.fallback import fallback_runs, proved_before_effect + + setup = _setup(args.task, args.key_dir) + names = _names(setup) + cache = setup.cache + hold: Optional[dict[str, Any]] = None + path = _hold_file(setup) + if path.exists() or path.is_symlink(): + try: + stopped = json.loads(path.read_text(encoding="utf-8")) + replay = stopped.get("replay") or {} + reason = replay.get("halt_reason") or stopped.get("reason") + hold = { + "phase": stopped.get("phase"), + "status": replay.get("status"), + "halt_reason": scrub_text(str(reason)) if reason else None, + "bundle_digest": stopped.get("bundle_digest"), + } + except (OSError, ValueError, AttributeError): + hold = {"phase": "unreadable"} + found = proved_before_effect(cache, setup.instruction, names) + return { + "task_id": cache.task_id(setup.instruction, names), + "held": cache.held(setup.instruction, names), + "hold": hold, + "admitted_program": cache.admitted_program(setup.instruction, names) + is not None, + "fallback_eligible": found.eligible, + "fallback_reason": found.reason, + "fallback": fallback_runs(cache, setup.instruction, names), + } + + +def release(args: argparse.Namespace, ask: Any = input) -> dict[str, Any]: + """A person releases a hold at a terminal; the hold file is archived.""" + from openadapt_flow.compile_agent.cli import _interactive + from openadapt_flow.wrap.fallback import clear_in_flight, fallback_runs + + person = (args.person or "").strip() + if not person: + raise SystemExit("release needs --person") + if not _interactive(): + raise SystemExit("release needs a person at an interactive terminal") + setup = _setup(args.task, args.key_dir) + names = _names(setup) + path = _hold_file(setup) + stuck = fallback_runs(setup.cache, setup.instruction, names)["in_flight"] + phase = None + if path.exists() or path.is_symlink(): + try: + phase = json.loads(path.read_text(encoding="utf-8")).get("phase") + except (OSError, ValueError, AttributeError): + phase = "unreadable" + elif not stuck: + return {"released": False, "reason": "NOT_HELD"} + if (stuck or phase not in (None, "halted")) and not args.after_reconciling: + return { + "released": False, + "reason": "RECONCILE_FIRST", + "detail": "A write may exist. Check the record, then pass " + "--after-reconciling.", + } + if ask("Type release to release this hold: ").strip().lower() != "release": + return {"released": False, "reason": "NOT_CONFIRMED"} + archived = None + if phase is not None: + archived = path.with_name(f"skill-stop-released-{time.time_ns()}.json") + path.rename(archived) + from openadapt_flow.wrap.fallback import _write + + _write( + archived.with_suffix(".by.json"), + {"person": person, "at": time.time(), "phase": phase}, + ) + cleared = clear_in_flight(setup.cache, setup.instruction, names) if stuck else False + return { + "released": True, + "person": person, + "archived": str(archived) if archived else None, + "fallback_cleared": cleared, + } + + +def evict(args: argparse.Namespace) -> dict[str, Any]: + setup = _setup(args.task, args.key_dir) + kept = setup.cache.evict(setup.instruction, _names(setup)) + return {"evicted": kept is not None, "kept_at": str(kept) if kept else None} + + +def cmd_wrap_dispatch(args: argparse.Namespace) -> int: + from openadapt_flow.integrations.agents.recording import TaskSetupError + from openadapt_flow.wrap import TaskArgumentsError + + verb = getattr(args, "dispatch_verb", None) + try: + if verb == "status": + _emit(status(args), None) + return 0 + if verb == "release": + result = release(args) + _emit(result, None) + return 0 if result.get("released") else 1 + if verb == "evict": + _emit(evict(args), None) + return 0 + result = run(args) + except (TaskArgumentsError, TaskSetupError) as exc: + print(f"openadapt-flow wrap-dispatch: {exc}", file=sys.stderr) + return 2 + _emit(result, args.result) + return 0 if result.get("verified") is True else 1 + + +def main(argv: Sequence[str] | None = None) -> int: + """Run as ``python -m openadapt_flow.wrap.dispatch_cli``.""" + parser = argparse.ArgumentParser(prog="openadapt-flow") + register(parser.add_subparsers(dest="command", required=True)) + rows = list(sys.argv[1:] if argv is None else argv) + args = parser.parse_args(["wrap-dispatch", *rows]) + return int(args.func(args)) + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/flow/openadapt_flow/wrap/fallback.py b/packages/flow/openadapt_flow/wrap/fallback.py new file mode 100644 index 0000000000..6618c40886 --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/fallback.py @@ -0,0 +1,609 @@ +"""Opt-in governed fallback from a compiled program to the agent. + +By default a compiled program that stops is held: the agent task is never +rerun (see :class:`~openadapt_flow.integrations.agents.skills.SkillCache`). +:class:`FallbackPolicy` is the opt-in alternative for one task. It wraps the +cache and hands the task back to the agent only when the program's stop is +proved to have written nothing: + +* the cache's hold is a terminal halt whose report says ``HALTED`` and + ``HALTED_BEFORE_EFFECT``, with no step that needs reconciliation + (:func:`openadapt_flow.transaction.steps_requiring_reconciliation`), bound + to the admitted bundle's digest; +* the halted reply proved zero model calls; +* the cache's own record check of the halted run saw no new, changed or + removed record of the task's record. + +It never falls back on ``RECONCILIATION_REQUIRED``, a lost reply (the hold +stays ``running``), ``RECORD_CHECK_FAILED``, a receipt that is not +``VERIFIED``, or a model call during replay. + +The fallback run is a run 1 through compile-agent's harness in its own +directory: the right-record check and a mandatory :class:`PreCommitGate` +before every save, the app's origin fence, and a read-back of every save +from the system of record. Its draft is never confirmed or admitted. A +verified fallback opens a repair candidate through +:meth:`SkillCache.open_repair` when a repair desk is configured; a person +still approves the repair, and :meth:`SkillCache.complete_repair` runs its +canaries afterwards. Nothing here admits a program or clears a hold. +""" + +from __future__ import annotations + +import json +import math +import os +import time +import uuid +from collections.abc import Callable, Mapping +from dataclasses import dataclass +from pathlib import Path +from typing import Any, Optional, Protocol + +from openadapt_flow.compile_agent.harness import GateRequest +from openadapt_flow.integrations.agents.skills import SkillRun + +#: ``SkillRun.path`` of a run the agent did after a program's drift. +FALLBACK_PATH = "agent_fallback" + +#: Program outcomes that never fall back, whatever their evidence says. +NEVER_FALL_BACK = frozenset( + { + "VERIFIED", + "RECONCILIATION_REQUIRED", + "RECORD_CHECK_FAILED", + "RECEIPT_NOT_VERIFIED", + "MODEL_CALLS_NOT_ZERO", + "BASELINE_UNAVAILABLE", + } +) + +_ACTIVE = "in-flight.json" +_HALT = "halt-evidence.json" +_RESULT = "result.json" +_REQUEST_CHARS = frozenset( + "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789._-" +) + + +class PreCommitGate(Protocol): + """Asked before every save in a fallback run; True lets that save through. + + It sees compile-agent's :class:`GateRequest` (the control, the record's + identity on screen, the URL and the gate screenshot) after the harness's + right-record check passed. + """ + + def __call__(self, request: GateRequest) -> bool: ... + + +class TerminalGate: + """The default gate: compile-agent's terminal confirmation. + + A person at the terminal types ``y`` for each save. With no terminal it + refuses every save, and :class:`FallbackPolicy` does not start the agent. + """ + + def __init__( + self, + ask: Callable[[str], str] = input, + attended: Optional[Callable[[], bool]] = None, + ) -> None: + from openadapt_flow.compile_agent.cli import _interactive, _terminal_hold + + self._hold = _terminal_hold(ask) + self._attended = attended or _interactive + + @property + def attended(self) -> bool: + return bool(self._attended()) + + def __call__(self, request: GateRequest) -> bool: + if not self.attended: + return False + return bool(self._hold(request)) + + +@dataclass(frozen=True) +class Eligibility: + """Whether a held program may hand this task to the agent, and why.""" + + eligible: bool + reason: str + run_dir: Optional[Path] = None + bundle_digest: Optional[str] = None + + +def _int_zero(value: Any) -> bool: + return type(value) is int and value == 0 + + +def _nothing_written(check: Any) -> bool: + """The cache's record check saw no change to the task's record.""" + return ( + isinstance(check, Mapping) + and _int_zero(check.get("created")) + and _int_zero(check.get("changed")) + and _int_zero(check.get("removed")) + ) + + +def proved_before_effect( + cache: Any, prompt: str, params: Mapping[str, Any] +) -> Eligibility: + """Read the cache's hold and the halted run's report from disk. + + The checks are those :meth:`SkillCache.open_repair` applies before it + offers a repair, without its extra one-step-replacement requirement. It + reads only; a cache that is not a SkillCache is never eligible. + """ + from openadapt_flow.integrations.agents.skills import _STOP_FILE + from openadapt_flow.ir import RunReport, Workflow + from openadapt_flow.jit import lifecycle + from openadapt_flow.transaction import steps_requiring_reconciliation + + compiler_for = getattr(cache, "_compiler", None) + if not callable(compiler_for): + return Eligibility(False, "not_a_skill_cache") + try: + compiler, _key = compiler_for(prompt, params) + stop = compiler.dir / _STOP_FILE + if stop.is_symlink() or not stop.is_file(): + return Eligibility(False, "no_hold") + stopped = json.loads(stop.read_text(encoding="utf-8")) + if not isinstance(stopped, dict) or stopped.get("phase") != "halted": + # A ``running`` hold is a lost reply: a write may exist. + return Eligibility(False, "hold_not_terminal") + replay = stopped.get("replay") + if not isinstance(replay, dict): + return Eligibility(False, "no_halted_run") + if replay.get("status") in NEVER_FALL_BACK or replay.get("verified"): + return Eligibility(False, "outcome_never_falls_back") + if not _int_zero(replay.get("model_calls")): + return Eligibility(False, "model_calls_not_zero") + jit = compiler._jit() + run_dir = Path(replay["run_dir"]).resolve(strict=True) + if run_dir.parent != Path(jit.runs_dir).resolve(strict=True): + return Eligibility(False, "foreign_run") + report_path = run_dir / "report.json" + if report_path.is_symlink(): + return Eligibility(False, "foreign_report") + workflow = Workflow.load(jit.bundle_dir) + admission = lifecycle.verify_admission(jit.bundle_dir, key_dir=compiler.key_dir) + report = RunReport.model_validate_json(report_path.read_text(encoding="utf-8")) + except (OSError, ValueError, KeyError, TypeError, lifecycle.AdmissionError): + return Eligibility(False, "unreadable_evidence") + if not ( + report.workflow_name == workflow.name + and report.bundle_content_digest == stopped.get("bundle_digest") + and report.bundle_content_digest == admission.get("digest") + ): + return Eligibility(False, "evidence_not_bound_to_admission") + if report.execution_outcome != "HALTED": + return Eligibility(False, "not_halted") + if report.transaction_outcome != "HALTED_BEFORE_EFFECT": + return Eligibility(False, "not_before_effect") + if steps_requiring_reconciliation(report): + return Eligibility(False, "steps_require_reconciliation") + return Eligibility( + True, "halted_before_effect", run_dir, report.bundle_content_digest + ) + + +def _cap(value: Any) -> float: + if ( + isinstance(value, bool) + or not isinstance(value, (int, float)) + or not math.isfinite(float(value)) + or value <= 0 + ): + raise ValueError("the fallback needs a positive, finite max_cost_usd") + return float(value) + + +def _spent(agent: Any) -> Optional[float]: + """What the agent has spent so far, or None when it is not known.""" + ledger = getattr(agent, "last_ledger", None) + if ledger is None: + return 0.0 if not getattr(agent, "requires_model_key", True) else None + if not ledger.model_calls: + return 0.0 + if not getattr(ledger, "usage_known", False): + return None + try: + spent = float(ledger.cost_usd()) + except Exception: # noqa: BLE001 - an unpriceable run is an unknown spend + return None + return spent if math.isfinite(spent) and spent >= 0 else None + + +def _write(path: Path, data: Mapping[str, Any], *, exclusive: bool = False) -> None: + flags = os.O_WRONLY | os.O_CREAT | (os.O_EXCL if exclusive else os.O_TRUNC) + descriptor = os.open(path, flags, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(data, stream, sort_keys=True, default=str) + stream.flush() + os.fsync(stream.fileno()) + + +def fallback_root(cache: Any, prompt: str, params: Mapping[str, Any]) -> Path: + """Where this task's fallback runs are kept. + + Beside the task's cache directory, not inside it, so an eviction (which + moves the task directory aside) keeps the fallback evidence in place. + """ + task_dir = Path(cache.receipt_root(prompt, params)) + return task_dir.parent / "fallback" / task_dir.name + + +class FallbackPolicy: + """A TaskCache that may hand a proved pre-effect drift to the agent. + + Args: + cache: The task's cache (normally a SkillCache). Everything other + than :meth:`run` is the cache's own. + max_cost_usd: The fallback run's model spend cap. Required; it is + separate from any cap on a first run. + gate: Asked before every save in the fallback run. Default: a + :class:`TerminalGate`. + request_id: The fallback run's own id. Default: a new one per run. + repair_desk: When given, a verified fallback opens a repair + candidate with :meth:`SkillCache.open_repair`. + """ + + def __init__( + self, + cache: Any, + *, + max_cost_usd: float, + gate: Optional[PreCommitGate] = None, + request_id: Optional[str] = None, + repair_desk: Any = None, + ) -> None: + self.cache = cache + self.max_cost_usd = _cap(max_cost_usd) + self.gate: PreCommitGate = gate if gate is not None else TerminalGate() + if request_id is not None and ( + not isinstance(request_id, str) + or not 0 < len(request_id) <= 128 + or not set(request_id) <= _REQUEST_CHARS + or request_id.startswith(".") + ): + raise ValueError("a fallback request id is 1 to 128 of [A-Za-z0-9._-]") + self.request_id = request_id + self.repair_desk = repair_desk + #: What the last :meth:`run` did about a fallback (None: not tried). + self.last: Optional[dict[str, Any]] = None + + def __getattr__(self, name: str) -> Any: + # Only called for names this object lacks: the cache's own surface + # (key, held, server, receipt_root, evict, open_repair ...). + return getattr(self.__dict__["cache"], name) + + def key(self, prompt: str, params: Mapping[str, Any]) -> dict[str, Any]: + return self.cache.key(prompt, params) + + # -- the policy ------------------------------------------------------------ + + def run(self, prompt: str, params: Mapping[str, Any], agent: Any) -> SkillRun: + self.last = None + # A lost reply raises here and stays held; it never falls back. + first = self.cache.run(prompt, params, agent) + if first.path != "skill" or first.verified or first.status in NEVER_FALL_BACK: + return first + root = fallback_root(self.cache, prompt, params) + found = proved_before_effect(self.cache, prompt, params) + if first.status != "CACHE_HALTED": + # The run that just halted: keep its record check with the halt, + # so a later held call can rely on it too. + if ( + found.eligible + and _int_zero(first.model_calls) + and _nothing_written(first.record_check) + ): + root.mkdir(parents=True, exist_ok=True) + _write( + root / _HALT, + { + "run_dir": str(found.run_dir), + "bundle_digest": found.bundle_digest, + "record_check": first.record_check, + }, + ) + elif found.eligible: + found = Eligibility(False, "record_changed_or_unproved") + if found.eligible: + try: + halt = json.loads((root / _HALT).read_text(encoding="utf-8")) + except (OSError, ValueError): + halt = None + if not ( + isinstance(halt, dict) + and halt.get("run_dir") == str(found.run_dir) + and halt.get("bundle_digest") == found.bundle_digest + and _nothing_written(halt.get("record_check")) + ): + found = Eligibility(False, "no_record_check_for_halt") + if not found.eligible: + self.last = {"fallback": False, "reason": found.reason} + return first + return self._fallback(prompt, params, agent, first, root) + + def _refused( + self, first: SkillRun, status: str, detail: str, started: float, **last: Any + ) -> SkillRun: + self.last = {"fallback": False, "reason": status.lower(), **last} + return SkillRun( + path=FALLBACK_PATH, + status=status, + verified=False, + model_calls=0, + cost_usd=0.0, + usage=[], + usage_known=True, + seconds=round(time.monotonic() - started, 3), + detail=detail, + replay={"program": first.replay, "fallback": self.last}, + ) + + def _fallback( + self, + prompt: str, + params: Mapping[str, Any], + agent: Any, + first: SkillRun, + root: Path, + ) -> SkillRun: + started = time.monotonic() + if agent is None: + return self._refused( + first, "FALLBACK_NO_AGENT", "No fallback agent was given.", started + ) + model_free = not getattr(agent, "requires_model_key", True) + own_cap = getattr(agent, "max_cost_usd", None) + if not model_free and ( + isinstance(own_cap, bool) or not isinstance(own_cap, (int, float)) + ): + return self._refused( + first, + "FALLBACK_COST_UNBOUNDED", + "The fallback agent has no spend cap this policy can set.", + started, + ) + if getattr(self.gate, "attended", True) is False: + return self._refused( + first, + "FALLBACK_GATE_UNATTENDED", + "No person is at the pre-commit gate; the agent was not started.", + started, + ) + request_id = self.request_id or f"fallback-{uuid.uuid4().hex}" + root.mkdir(parents=True, exist_ok=True) + active = root / _ACTIVE + try: + _write( + active, {"request_id": request_id, "at": time.time()}, exclusive=True + ) + except FileExistsError: + # Another fallback is running, or one ended without proving what + # it wrote. A person reconciles it before another one starts. + return self._refused( + first, + "RECONCILIATION_REQUIRED", + "An earlier fallback of this task has not been reconciled.", + started, + ) + run_root = root / request_id + try: + run_root.mkdir() + except FileExistsError: + active.unlink() + return self._refused( + first, + "FALLBACK_REQUEST_REUSED", + "This fallback request id already ran.", + started, + request_id=request_id, + ) + # Any exception from here keeps the in-flight marker: a save may exist. + return self._run_agent(prompt, params, agent, first, root, run_root, started) + + def _run_agent( + self, + prompt: str, + params: Mapping[str, Any], + agent: Any, + first: SkillRun, + root: Path, + run_root: Path, + started: float, + ) -> SkillRun: + from openadapt_flow.compile_agent import FirstRunCompiler + + request_id = run_root.name + cap = self.max_cost_usd + decisions: list[str] = [] + + def hold(request: GateRequest) -> bool: + spent = _spent(agent) + if spent is None or spent > cap: + decisions.append("refused_cost_cap") + return False + approved = bool(self.gate(request)) + decisions.append("approved" if approved else "refused_by_gate") + return approved + + common = { + k: v + for k, v in self.cache.common.items() + if k not in ("reset", "task_id", "review", "hold", "cache_dir") + } + compiler = FirstRunCompiler( + prompt, + params=list(params), + task_id=self.cache.task_id(prompt, params), + cache_dir=run_root / "run", + model_key=getattr(self.cache, "model_key", None), + before_capture=getattr(self.cache, "before_capture", None), + **common, + ) + restore = getattr(agent, "max_cost_usd", None) + capped = isinstance(restore, (int, float)) and not isinstance(restore, bool) + if isinstance(restore, (int, float)) and capped: + agent.max_cost_usd = min(float(restore), cap) + try: + result = compiler.record(agent, dict(params), hold=hold) + finally: + if capped: + agent.max_cost_usd = restore + # The cache's own record check, on reads independent of the run's + # report: the baseline taken as the run started, and a fresh read. + from openadapt_flow.integrations.agents.skills import task_record_check + + try: + # A sign-in value is never saved in the record. + withheld = set(compiler._secret_params()) + except Exception: # noqa: BLE001 - no bundle: no input is known secret + withheld = set() + written = task_record_check( + compiler._baseline, + compiler.observer.system_of_record, + expect=self.cache.common["expect"], + values={k: str(v) for k, v in params.items() if k not in withheld}, + ).to_dict() + run1 = result.run1 or {} + ledger = run1.get("agent") or {} + model_calls = ledger.get("model_calls") + if isinstance(model_calls, bool) or not isinstance(model_calls, int): + # A run that stopped at the gate may return no ledger; an agent + # with no model behind it still made no calls. + model_calls = None if getattr(agent, "requires_model_key", True) else 0 + raw_cost = ledger.get("cost_usd") + cost: Optional[float] = ( + float(raw_cost) + if isinstance(raw_cost, (int, float)) + and not isinstance(raw_cost, bool) + and math.isfinite(float(raw_cost)) + and raw_cost >= 0 + else None + ) + if model_calls == 0: + cost = 0.0 + usage_known = model_calls is not None and cost is not None + gates = [g.get("decision") for g in run1.get("gates") or []] + check = result.record_check or {} + passed = bool(check.get("passed")) + status, detail = result.status, result.detail + if result.status == "draft" and passed: + status, detail = "VERIFIED", "The agent's save was read back." + if ( + "refused_cost_cap" in decisions + or (cost is not None and cost > cap) + or (model_calls and cost is None) + ): + status = "COST_CAP_EXCEEDED" + detail = ( + f"The fallback's model spend passed or could not be held to ${cap:.2f}." + ) + elif "refused_by_gate" in decisions: + status, detail = "GATE_REFUSED", "The person at the gate refused the save." + verified = ( + status == "VERIFIED" + and bool(gates) + and all(g == "approved_by_hold" for g in gates) + ) + if status == "VERIFIED" and not verified: + status, detail = "GATE_NOT_PROVED", "A save did not pass the gate." + repair = self._open_repair(prompt, params, run_root) if verified else None + self.last = { + "fallback": True, + "request_id": request_id, + "status": status, + "gates": gates, + "decisions": decisions, + "approvals": decisions.count("approved"), + "repair": repair, + "admitted": False, + "task_record_check": written, + } + run = SkillRun( + path=FALLBACK_PATH, + status=status, + verified=verified, + model_calls=model_calls, + cost_usd=cost, + seconds=round(time.monotonic() - started, 3), + detail=detail, + wire_checked=self.cache.common.get("write_adapter") is not None, + compile=result.to_dict(), + replay={"program": first.replay, "fallback": self.last}, + record_check=check, + usage=[{"calls": model_calls, "usd": cost}] + if model_calls is not None + else None, + usage_known=usage_known, + ) + _write(run_root / _RESULT, run.to_dict()) + # The marker goes only when what the run did is known: a verified + # save, or an independent read that found the task's record unchanged. + if verified or _nothing_written(written): + (root / _ACTIVE).unlink(missing_ok=True) + return run + + def _open_repair( + self, prompt: str, params: Mapping[str, Any], run_root: Path + ) -> dict[str, Any]: + if self.repair_desk is None: + return {"opened": False, "reason": "no_repair_desk"} + from openadapt_flow.agent.repair import RepairError + + try: + reply = self.cache.open_repair(prompt, params, repair_desk=self.repair_desk) + except RepairError: + return {"opened": False, "reason": "no_one_step_repair"} + # The repair token is a one-use capability for the person who + # demonstrates the fix; it stays in a private local file. + _write(run_root / "repair.json", reply) + return { + "opened": True, + "step_id": reply.get("step_id"), + "file": str(run_root / "repair.json"), + } + + +def fallback_runs(cache: Any, prompt: str, params: Mapping[str, Any]) -> dict[str, Any]: + """This task's fallback runs and whether one is unreconciled.""" + root = fallback_root(cache, prompt, params) + runs: list[dict[str, Any]] = [] + if root.is_dir(): + for path in sorted(root.iterdir()): + result = path / _RESULT + if not path.is_dir() or path.is_symlink(): + continue + try: + data = json.loads(result.read_text(encoding="utf-8")) + except (OSError, ValueError): + data = {} + fallback = (data.get("replay") or {}).get("fallback") or {} + runs.append( + { + "request_id": path.name, + "status": data.get("status", "UNFINISHED"), + "verified": data.get("verified") is True, + "repair": fallback.get("repair"), + } + ) + return { + "dir": str(root), + "in_flight": (root / _ACTIVE).exists(), + "runs": runs, + } + + +def clear_in_flight(cache: Any, prompt: str, params: Mapping[str, Any]) -> bool: + """A person reconciled a stuck fallback: drop its marker (evidence stays).""" + marker = fallback_root(cache, prompt, params) / _ACTIVE + if not marker.exists(): + return False + marker.rename(marker.with_name(f"reconciled-{time.time_ns()}.json")) + return True diff --git a/packages/flow/tests/e2e/test_wrap_fallback_e2e.py b/packages/flow/tests/e2e/test_wrap_fallback_e2e.py new file mode 100644 index 0000000000..21bc93b2c1 --- /dev/null +++ b/packages/flow/tests/e2e/test_wrap_fallback_e2e.py @@ -0,0 +1,252 @@ +"""Opt-in fallback end to end on MockMed, headless. + +A scripted agent's run 1 is compiled and admitted with a registered key. +Then MockMed drifts (a vendor release relabels and moves a control). The +compiled program halts before the save; with the opt-in policy the task goes +to a scripted fallback agent that drives the drifted screens through the +compile-agent harness, a gate stands in for the person, and the saved record +is read from MockMed's own store. Until #2406 moves the MCP tool onto a +worker thread (needed under mcp 1.30.0), the compiled program runs in +process, on a thread, instead of over MCP. +""" + +from __future__ import annotations + +import json +import shutil +import threading +from http.server import ThreadingHTTPServer +from pathlib import Path +from typing import Any, Iterator + +import pytest + +from openadapt_flow.compile_agent import ScriptedAgent +from openadapt_flow.integrations.agents import skills +from openadapt_flow.integrations.agents.skills import SkillCache +from openadapt_flow.jit.keys import CustomerModelKey +from openadapt_flow.tutorial import _http_json, _records +from tests._rest_read_contract_fixtures import mockmed_effects_yaml +from tests._teach_authorization_support import mockmed_note + +pytest.importorskip("playwright") + +PROMPT = ( + "Open the referral for Jane Sample, start a Triage encounter, and save " + "this note: {note}" +) +NOTE = "Synthetic follow-up in two weeks" +EXPECT = {"patient_id": "p1", "type": "Triage"} +ON_SCREEN = ["Jane Sample", "MRN P1"] +TEST_KEY = CustomerModelKey("anthropic", "env:TEST_ONLY", "not-a-real-key") +DRIFT_HOOK = "(new URLSearchParams(location.search).get('drift') || '')" + + +class DriftableMockMed: + """MockMed's fault server over a copy of its static files. + + The app reads ``?drift=`` from its own URL, and the URL is part of the + task's key, so the drift is switched in the served script instead. + """ + + def __init__(self, root: Path) -> None: + from openadapt_flow.mockmed import fault_server + from openadapt_flow.mockmed.chart_pages import ChartPages + + self.static = root / "static" + shutil.copytree(fault_server.STATIC_DIR, self.static) + self.app_js = (self.static / "app.js").read_text(encoding="utf-8") + assert DRIFT_HOOK in self.app_js + db = fault_server.FaultDB() + chart = ChartPages(rows_for=db.rows_for_patient) + db.chart = chart + handler = fault_server._make_handler(db, str(self.static), chart) + self.httpd = ThreadingHTTPServer(("127.0.0.1", 0), handler) + self.thread = threading.Thread(target=self.httpd.serve_forever, daemon=True) + self.thread.start() + self.base = f"http://127.0.0.1:{self.httpd.server_address[1]}" + + def drift(self, mode: str) -> None: + text = self.app_js.replace(DRIFT_HOOK, f"({json.dumps(mode)} || '')") + (self.static / "app.js").write_text(text, encoding="utf-8") + + def reset(self) -> None: + _http_json(f"{self.base}/api/reset", method="POST", body={}) + + def stop(self) -> None: + self.httpd.shutdown() + self.httpd.server_close() + self.thread.join(timeout=5) + + +@pytest.fixture +def app(tmp_path: Path) -> Iterator[DriftableMockMed]: + server = DriftableMockMed(tmp_path / "app") + yield server + server.stop() + + +def steps(save: str = "Save Encounter", new: str = "New Encounter") -> list: + return [ + {"click": "Open", "near": "Jane Sample"}, + {"click": new}, + {"click": "Triage"}, + {"type": "{note}", "into": "Note"}, + {"click": save}, + ] + + +def make_cache(tmp_path: Path, app: DriftableMockMed, env: Any) -> SkillCache: + from openadapt_flow.jit import authority + + env.setenv(authority.KEY_PASSPHRASE_ENV, "e2e passphrase") + key_dir = tmp_path / "keys" + pem = tmp_path / "keyfiles" / "ci.pem" + authority.register_principal( + key_dir, + role="admitter_key", + principal_id="ci:wrap-fallback", + public_key_hex=authority.generate_encrypted_key(pem), + ) + admitter = authority.principal_from_key(authority.load_encrypted_key(pem), key_dir) + verify = tmp_path / "verify.yaml" + verify.write_text( + "verifier:\n" + f"{mockmed_effects_yaml(app.base)}" + " timeout_s: 2.0\n" + " poll_interval_s: 0.05\n" + ) + cache = SkillCache( + url=f"{app.base}/?fault=ok&idempotency=demo#tasks", + verify=verify, + expect=EXPECT, + on_screen=ON_SCREEN, + offer=lambda proposal: "dana.reviewer", + admitter=admitter, + canary_params=[{"note": "Canary test note"}], + drop_fields=["key", "source"], + task_id="wrap.fallback", + cache_dir=tmp_path / "cache", + key_dir=key_dir, + model_key=TEST_KEY, + reset=app.reset, + on_warning=lambda text: None, + ) + task_id = cache.task_id(PROMPT, {"note": NOTE}) + cache.common["teach_authorization"] = mockmed_note( + key_dir, + tmp_path / f"teach-authorization-{task_id}", + task_id, + cache.common["url"], + note=NOTE, + record=EXPECT, + constants=ON_SCREEN, + ) + return cache + + +def in_process(patch: Any, cache: SkillCache) -> None: + from openadapt_flow.compile_agent import run_compiled_params + + async def call(_python, _server, params): + import asyncio + + task_dir = cache.receipt_root(PROMPT, params) + # Playwright's sync API refuses a running event loop (#2406 moves the + # MCP tool to a worker thread the same way). + result = await asyncio.to_thread(run_compiled_params, task_dir, params) + return result.to_dict() + + patch.setattr(skills, "_call_skill", call) + + +#: What the scripted fallback agent clicks on each drifted release. +DRIFTED_STEPS = { + "redesign": steps(save="Submit to chart"), + "relink": steps(new="Start visit"), +} + + +class Gate: + """Stands in for the person at the pre-commit gate.""" + + def __init__(self, approve: bool) -> None: + self.approve = approve + self.requests: list = [] + + def __call__(self, request: Any) -> bool: + self.requests.append(request) + return self.approve + + +def admitted(tmp_path: Path, app: DriftableMockMed, patch: Any) -> SkillCache: + cache = make_cache(tmp_path, app, patch) + in_process(patch, cache) + app.reset() + first = cache.run(PROMPT, {"note": NOTE}, ScriptedAgent(steps=steps())) + assert first.status == "admitted", first.to_dict() + app.reset() + return cache + + +def saved(app: DriftableMockMed) -> list[tuple[str, str, str]]: + return [(r["patient_id"], r["type"], r["note"]) for r in _records(app.base)] + + +@pytest.mark.parametrize("mode", sorted(DRIFTED_STEPS)) +def test_drift_falls_back_and_the_save_is_read_back( + app, tmp_path, monkeypatch, mode +) -> None: + from openadapt_flow.agent.repair import RepairAccessPolicy, RepairDesk + from openadapt_flow.wrap.fallback import FALLBACK_PATH, FallbackPolicy + + cache = admitted(tmp_path, app, monkeypatch) + app.drift(mode) + gate = Gate(approve=True) + agent = ScriptedAgent(steps=DRIFTED_STEPS[mode]) + policy = FallbackPolicy( + cache, + max_cost_usd=0.5, + gate=gate, + request_id=f"e2e-{mode}.fallback", + repair_desk=RepairDesk(tmp_path / "repairs", RepairAccessPolicy(None)), + ) + run = policy.run(PROMPT, {"note": NOTE}, agent) + assert run.path == FALLBACK_PATH and run.verified, run.to_dict() + assert run.status == "VERIFIED" and run.model_calls == 0 + # The program halted before the save; the agent saved once, approved once. + assert run.replay["program"]["status"] == "HALTED" + assert len(gate.requests) == 1 and policy.last["approvals"] == 1 + assert saved(app) == [("p1", "Triage", NOTE)] + # Nothing was admitted: the task is still held and serves no program. + assert policy.last["admitted"] is False + assert cache.held(PROMPT, {"note": ""}) + assert cache.server(PROMPT, {"note": ""}) is None + repair = policy.last["repair"] + assert repair["opened"] is True and Path(repair["file"]).is_file(), repair + + +def test_gate_refusal_saves_nothing(app, tmp_path, monkeypatch) -> None: + from openadapt_flow.wrap.fallback import FallbackPolicy + + cache = admitted(tmp_path, app, monkeypatch) + app.drift("redesign") + gate = Gate(approve=False) + policy = FallbackPolicy(cache, max_cost_usd=0.5, gate=gate) + run = policy.run( + PROMPT, {"note": NOTE}, ScriptedAgent(steps=DRIFTED_STEPS["redesign"]) + ) + assert run.status == "GATE_REFUSED" and not run.verified + assert len(gate.requests) == 1 + assert saved(app) == [] # read from MockMed's store + + +def test_without_the_policy_the_drift_is_held(app, tmp_path, monkeypatch) -> None: + cache = admitted(tmp_path, app, monkeypatch) + app.drift("redesign") + agent = ScriptedAgent(steps=DRIFTED_STEPS["redesign"]) + first = cache.run(PROMPT, {"note": NOTE}, agent) + again = cache.run(PROMPT, {"note": NOTE}, agent) + assert first.status == "HALTED" and again.status == "CACHE_HALTED" + assert not first.verified and not again.verified + assert saved(app) == [] diff --git a/packages/flow/tests/test_wrap_dispatch_cli.py b/packages/flow/tests/test_wrap_dispatch_cli.py new file mode 100644 index 0000000000..5040311d16 --- /dev/null +++ b/packages/flow/tests/test_wrap_dispatch_cli.py @@ -0,0 +1,215 @@ +"""wrap-dispatch: program first, the default hold, the opt-in fallback, hold verbs. + +The task setup is the same modelled SkillCache as tests/test_wrap_fallback.py +(real cache, hold and report checks; the MCP reply and run 1 modelled). +""" + +from __future__ import annotations + +import argparse +import json +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openadapt_flow.compile_agent import cli as compile_cli +from openadapt_flow.wrap import WrappedTask +from openadapt_flow.wrap import dispatch_cli as dc +from tests.test_wrap_fallback import ( # noqa: F401 - fixtures + PARAMS, + PROMPT, + Agent, + build_model, + install_reply, + model, + run1, +) + +RUN_KEYS = { + "path", + "status", + "verified", + "model_calls", + "cost_usd", + "usage", + "usage_known", + "seconds", + "wire_checked", + "receipt", + "receipt_outcome", +} + + +def parse(*argv: str) -> argparse.Namespace: + parser = argparse.ArgumentParser(prog="openadapt-flow") + dc.register(parser.add_subparsers(dest="command", required=True)) + return parser.parse_args(["wrap-dispatch", *argv]) + + +@pytest.fixture +def task(model, monkeypatch, tmp_path) -> SimpleNamespace: # noqa: F811 + setup = SimpleNamespace( + cache=model.cache, instruction=PROMPT, parameters=("value",) + ) + monkeypatch.setattr(dc, "_setup", lambda *_a, **_k: setup) + runs = tmp_path / "runs" + return SimpleNamespace(setup=setup, runs=str(runs), model=model) + + +def run_args(task: SimpleNamespace, request: str, value: str, *extra: str): + return parse( + "--task", + "task.json", + "--request-id", + request, + "--param", + f"value={value}", + "--runs-dir", + task.runs, + *extra, + ) + + +def test_the_verb_is_registered_in_openadapt_flow() -> None: + from openadapt_flow.__main__ import build_parser + + args = build_parser().parse_args(["wrap-dispatch", "status", "task.json"]) + assert args.func is dc.cmd_wrap_dispatch and args.dispatch_verb == "status" + + +def test_no_admitted_program_runs_nothing(task, monkeypatch) -> None: + monkeypatch.setattr(task.setup.cache, "server", lambda *_: None) + result = dc.run(run_args(task, "r1", "one")) + assert result["status"] == "NO_ADMITTED_PROGRAM" and result["path"] == "held" + assert result["outcome"] == "ESCALATED" and result["model_calls"] == 0 + assert task.model.sent == [] and set(result) >= RUN_KEYS + + +def test_default_dispatch_is_the_wrap_hold(task, monkeypatch, tmp_path) -> None: + install_reply(task.model, monkeypatch) + first = dc.run(run_args(task, "r1", "one")) + assert first["status"] == "HALTED" and first["path"] == "program" + assert first["outcome"] == "ESCALATED" and first["fallback"] is None + second = dc.run(run_args(task, "r2", "two")) + assert second["status"] == "CACHE_HALTED" and second["path"] == "held" + assert task.model.sent == [{"value": "one"}] + + # The same requests through openadapt wrap's WrappedTask on a fresh copy. + (tmp_path / "plain").mkdir() + other = build_model(tmp_path / "plain", monkeypatch) + install_reply(other, monkeypatch) + wrapped = WrappedTask( + cache=other.cache, + agent=dc._NoAgent(), + instruction=PROMPT, + parameters=("value",), + runs_dir=tmp_path / "plain-runs", + ) + plain = [ + wrapped.call("r1", {"value": "one"}), + wrapped.call("r2", {"value": "two"}), + ] + for ours, theirs in zip((first, second), plain): + mine = {k: v for k, v in ours.items() if k not in ("outcome", "fallback")} + assert set(mine) == set(theirs) + # ``path`` keeps wrap's field name; its value is the dispatch route. + for key in set(theirs) - {"run_id", "seconds", "halt_reason", "path"}: + assert mine[key] == theirs[key], key + + +def test_fallback_needs_its_own_cap(task) -> None: + with pytest.raises(SystemExit): + dc.run(run_args(task, "r1", "one", "--fallback", "agent")) + with pytest.raises(SystemExit): + dc.run(run_args(task, "r1", "one", "--fallback-max-cost-usd", "1")) + with pytest.raises(SystemExit): + dc.run( + run_args( + task, "r1", "one", "--fallback", "agent", "--fallback-max-cost-usd", "0" + ) + ) + + +def test_opt_in_fallback_result(task, monkeypatch, run1, tmp_path) -> None: # noqa: F811 + install_reply(task.model, monkeypatch) + out = tmp_path / "result.json" + args = run_args( + task, + "r1", + "one", + "--fallback", + "agent", + "--fallback-max-cost-usd", + "0.25", + "--result", + str(out), + ) + approvals: list = [] + result = dc.run(args, agent=Agent(), gate=lambda r: approvals.append(r) or True) + assert result["path"] == "agent_fallback" and result["outcome"] == "VERIFIED" + assert result["verified"] and result["model_calls"] == 0 and len(approvals) == 1 + assert result["fallback"]["request_id"] == "r1.fallback" + assert result["fallback"]["admitted"] is False + assert result["fallback"]["repair"]["opened"] is True + assert set(result) >= RUN_KEYS + # The CLI prints and writes the same JSON. + monkeypatch.setattr(dc, "run", lambda _args: result) + assert dc.cmd_wrap_dispatch(args) == 0 + assert json.loads(out.read_text())["path"] == "agent_fallback" + + +def test_status_evict_and_release(task, monkeypatch, run1, capsys) -> None: # noqa: F811 + install_reply(task.model, monkeypatch) + dc.run(run_args(task, "r1", "one")) + shown = dc.status(parse("status", "task.json")) + assert shown["held"] and shown["hold"]["phase"] == "halted" + assert shown["fallback_eligible"] and shown["fallback"]["runs"] == [] + + # Release needs a person at a terminal, and their typed confirmation. + monkeypatch.setattr(compile_cli, "_interactive", lambda: False) + with pytest.raises(SystemExit): + dc.release(parse("release", "task.json", "--person", "dana")) + monkeypatch.setattr(compile_cli, "_interactive", lambda: True) + args = parse("release", "task.json", "--person", "dana") + assert dc.release(args, ask=lambda _: "no")["reason"] == "NOT_CONFIRMED" + done = dc.release(args, ask=lambda _: "release") + assert done["released"] and Path(done["archived"]).is_file() + assert not task.model.stop.exists() + by = json.loads(Path(done["archived"]).with_suffix(".by.json").read_text()) + assert by["person"] == "dana" and by["phase"] == "halted" + + kept = dc.evict(parse("evict", "task.json")) + assert kept["evicted"] and Path(kept["kept_at"]).is_dir() + + +def test_release_of_a_possible_write_needs_reconciling(task, monkeypatch) -> None: + async def hit(*_): + raise RuntimeError("lost") + + from openadapt_flow.integrations.agents import skills + + monkeypatch.setattr(skills, "_call_skill", hit) + result = dc.run(run_args(task, "r1", "one")) + assert result["status"] == "RECONCILIATION_REQUIRED" + assert result["outcome"] == "ESCALATED" + monkeypatch.setattr(compile_cli, "_interactive", lambda: True) + args = parse("release", "task.json", "--person", "dana") + assert dc.release(args, ask=lambda _: "release")["reason"] == "RECONCILE_FIRST" + args = parse("release", "task.json", "--person", "dana", "--after-reconciling") + assert dc.release(args, ask=lambda _: "release")["released"] + + +@pytest.mark.parametrize( + ("status", "verified", "expected"), + [ + ("VERIFIED", True, "VERIFIED"), + ("CACHE_HALTED", False, "ESCALATED"), + ("GATE_REFUSED", False, "ESCALATED"), + ("RECORD_CHECK_FAILED", False, "CAUGHT_ERROR"), + ("COST_CAP_EXCEEDED", False, "CAUGHT_ERROR"), + ("SOMETHING_ELSE", False, "FAILED"), + ], +) +def test_outcomes(status: str, verified: bool, expected: str) -> None: + assert dc.outcome({"status": status, "verified": verified}) == expected diff --git a/packages/flow/tests/test_wrap_fallback.py b/packages/flow/tests/test_wrap_fallback.py new file mode 100644 index 0000000000..abd7131c6c --- /dev/null +++ b/packages/flow/tests/test_wrap_fallback.py @@ -0,0 +1,552 @@ +"""FallbackPolicy: the real cache, hold and report checks; MCP and run 1 modelled. + +The compiled program's reply is the MCP boundary (as in +test_skill_cache_runtime.py). The fallback's run 1 is a small stand-in for +FirstRunCompiler that calls the real gate wrapper before its one save. The +browser path is in tests/e2e/test_wrap_fallback_e2e.py. +""" + +from __future__ import annotations + +import copy +import json +from pathlib import Path +from types import SimpleNamespace +from typing import Any, Optional + +import pytest + +from openadapt_flow import compile_agent +from openadapt_flow.integrations.agents import skills +from openadapt_flow.ir import ( + ActionKind, + Anchor, + HaltObservation, + RunReport, + Step, + StepResult, + Workflow, +) +from openadapt_flow.wrap import fallback as fb +from openadapt_flow.wrap.fallback import FallbackPolicy, TerminalGate + +PROMPT = "Create the synthetic record with {value}" +PARAMS = {"value": "one"} + + +def make_cache(tmp_path: Path) -> skills.SkillCache: + verify = tmp_path / "verify.yaml" + verify.write_text( + "verifier:\n kind: rest\n base_url: http://127.0.0.1:1\n" + " records_path: /records\n records_key: records\n" + ) + return skills.SkillCache( + url="http://127.0.0.1:1", + verify=verify, + expect={"kind": "synthetic"}, + on_screen=["Synthetic record"], + offer=lambda _: None, + canary_params=[], + cache_dir=tmp_path / "cache", + ) + + +@pytest.fixture +def model(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + return build_model(tmp_path, monkeypatch) + + +def build_model(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamespace: + from PIL import Image + + from openadapt_flow.jit import lifecycle + + cache = make_cache(tmp_path) + directory = tmp_path / "cache" / "task" + bundle = directory / "program" / "bundle" + bundle.mkdir(parents=True) + Image.new("RGB", (2, 2), "white").save(bundle / "target.png") + Workflow( + name="synthetic-task", + steps=[ + Step( + id="save", + intent="Save synthetic value", + action=ActionKind.CLICK, + risk="irreversible", + anchor=Anchor( + template="target.png", region=(0, 0, 2, 2), click_point=(1, 1) + ), + ) + ], + ).save(bundle) + digest = Workflow.load(bundle).manifest.content_digest + monkeypatch.setattr( + lifecycle, "verify_admission", lambda *_a, **_k: {"digest": digest} + ) + jit = SimpleNamespace(admitted=True, bundle_dir=bundle, runs_dir=directory / "runs") + jit.runs_dir.mkdir() + rows: list[dict[str, str]] = [] + + class Observer: + @property + def system_of_record(self): + return copy.deepcopy(rows) + + compiler = SimpleNamespace( + dir=directory, + cache_dir=tmp_path / "cache", + out_dir=directory / "compiled", + observer=Observer(), + key_dir=None, + _jit=lambda: jit, + require_credential_withholding=lambda: None, + ) + compiler.out_dir.mkdir() + server = compiler.out_dir / "server.py" + server.write_text("# Model boundary only; never executed.\n") + (compiler.out_dir / "emitted.json").write_text( + json.dumps({"mcp_server": str(server)}) + ) + key = cache.key(PROMPT, PARAMS) + (directory / skills._KEY_FILE).write_text(json.dumps(key)) + monkeypatch.setattr(cache, "_compiler", lambda *_: (compiler, key)) + monkeypatch.setattr( + cache, "_first_run", lambda *_: pytest.fail("a first run, not a fallback") + ) + return SimpleNamespace( + cache=cache, + compiler=compiler, + jit=jit, + rows=rows, + sent=[], + digest=digest, + tmp=tmp_path, + stop=directory / skills._STOP_FILE, + ) + + +def halted_run(model: SimpleNamespace, change: Optional[str] = None) -> Path: + run = model.jit.runs_dir / f"halt-{len(list(model.jit.runs_dir.iterdir()))}" + run.mkdir() + report = RunReport( + workflow_name="synthetic-task", + started_at="2026-01-01T00:00:00Z", + execution_outcome="HALTED", + transaction_outcome="HALTED_BEFORE_EFFECT", + bundle_content_digest=model.digest, + halt=HaltObservation(state_id="save", reason="target_not_found"), + results=[ + StepResult( + step_id="save", + intent="Save synthetic value", + risk="irreversible", + ok=False, + delivery_attempted=False, + error="Could not resolve target for step save", + ) + ], + ) + if change == "reconciliation": + report.transaction_outcome = "RECONCILIATION_REQUIRED" + elif change == "delivery": + report.results[0].delivery_attempted = True + elif change == "wrong_digest": + report.bundle_content_digest = "f" * 64 + (run / "report.json").write_text(report.model_dump_json()) + return run + + +def install_reply( + model: SimpleNamespace, + monkeypatch: pytest.MonkeyPatch, + *, + write: Optional[dict[str, str]] = None, + report: Optional[str] = None, + **reply: Any, +) -> None: + async def hit(_python, _server, params): + model.sent.append(dict(params)) + if write is not None: + model.rows.append(dict(write)) + return { + "status": "HALTED", + "verified": False, + "model_calls": 0, + "receipt_outcome": None, + "halt_reason": "target_not_found", + "run_dir": str(halted_run(model, report)), + **reply, + } + + monkeypatch.setattr(skills, "_call_skill", hit) + + +class FakeRun1: + """FirstRunCompiler's run 1, reduced to its contract with the policy: + a baseline, one gated save, and the record check of a draft.""" + + made: list["FakeRun1"] = [] + + def __init__(self, prompt: str, *, rows: list, spend: Any = None, **kw: Any): + self.kw = kw + self.rows = rows + self.spend = spend + self._baseline: Optional[list] = None + self.observer = SimpleNamespace() + type(self).made.append(self) + + @property + def system_of_record(self) -> list: + return copy.deepcopy(self.rows) + + def _secret_params(self) -> frozenset: + return frozenset() + + def record(self, agent: Any, params: dict, *, hold: Any) -> Any: + self._baseline = copy.deepcopy(self.rows) + agent.calls += 1 + agent.seen_cap = getattr(agent, "max_cost_usd", None) + if self.spend is not None: + agent.last_ledger = self.spend + if agent.raises: + raise RuntimeError("the agent crashed after its save") + request = compile_agent.GateRequest( + control="Save", identity=("Synthetic record",), url="", screenshot=None + ) + approved = hold(request) + gates = [{"decision": "approved_by_hold" if approved else "refused_by_hold"}] + ledger = {"model_calls": agent.model_calls, "cost_usd": agent.cost} + if not approved: + return SimpleNamespace( + status="refused_by_hold", + detail="the hold did not approve 'Save'", + run1={"agent": ledger, "gates": gates, "readbacks": []}, + record_check=None, + to_dict=lambda: {"status": "refused_by_hold"}, + ) + self.rows.append({"id": "f1", "kind": "synthetic", "value": params["value"]}) + return SimpleNamespace( + status="draft", + detail="run 1 passed its record check", + run1={"agent": ledger, "gates": gates, "readbacks": [{}]}, + record_check={"passed": True, "created": 1, "changed": 0, "removed": 0}, + to_dict=lambda: {"status": "draft"}, + ) + + +class Agent: + def __init__(self, *, model_free: bool = True, cap: Any = None, raises=False): + self.calls = 0 + self.raises = raises + self.requires_model_key = not model_free + self.model_calls = 0 if model_free else 3 + self.cost = 0.0 if model_free else 0.01 + if cap is not None: + self.max_cost_usd = cap + + +@pytest.fixture +def run1(model, monkeypatch) -> SimpleNamespace: + state = SimpleNamespace(spend=None) + FakeRun1.made = [] + + def factory(prompt: str, **kw: Any) -> FakeRun1: + made = FakeRun1(prompt, rows=model.rows, spend=state.spend, **kw) + made.observer = made # observer.system_of_record reads the same rows + return made + + monkeypatch.setattr(compile_agent, "FirstRunCompiler", factory) + return state + + +def policy(model, **kw: Any) -> FallbackPolicy: + from openadapt_flow.agent.repair import RepairAccessPolicy, RepairDesk + + kw.setdefault("gate", lambda request: True) + kw.setdefault("max_cost_usd", 0.5) + desk = RepairDesk(model.tmp / "repairs", RepairAccessPolicy(None)) + kw.setdefault("repair_desk", desk) + return FallbackPolicy(model.cache, **kw) + + +# -- when it falls back -------------------------------------------------------- + + +def test_proved_pre_effect_drift_falls_back_behind_the_gate( + model, monkeypatch, run1 +) -> None: + install_reply(model, monkeypatch) + seen: list = [] + agent = Agent() + chosen = policy(model, gate=lambda request: seen.append(request) or True) + result = chosen.run(PROMPT, PARAMS, agent) + assert result.path == fb.FALLBACK_PATH and result.verified, result.to_dict() + assert result.status == "VERIFIED" and agent.calls == 1 + assert [r.control for r in seen] == ["Save"] + assert model.rows == [{"id": "f1", "kind": "synthetic", "value": "one"}] + # Its own run directory, beside (not inside) the task's cache. + made = FakeRun1.made[0] + root = model.tmp / "cache" / "fallback" / "task" + assert made.kw["cache_dir"].parent.parent == root + assert "reset" not in made.kw and made.kw["task_id"].startswith("skill-") + assert not (root / fb._ACTIVE).exists() + assert chosen.last["approvals"] == 1 and chosen.last["admitted"] is False + + +def test_verified_fallback_opens_a_repair_but_admits_nothing( + model, monkeypatch, run1 +) -> None: + install_reply(model, monkeypatch) + chosen = policy(model) + result = chosen.run(PROMPT, PARAMS, Agent()) + repair = chosen.last["repair"] + assert result.verified and repair["opened"] and repair["step_id"] == "save" + token = json.loads(Path(repair["file"]).read_text())["repair_token"] + assert token not in json.dumps(result.to_dict()) + assert (Path(repair["file"]).stat().st_mode & 0o777) == 0o600 + # The program stays held and unserved; no admission or selection happened. + assert model.stop.is_file() + assert model.cache.server(PROMPT, PARAMS) is None + assert not (model.compiler.dir / "repair-selection.json").exists() + assert chosen.last["admitted"] is False + + +def test_a_later_held_call_falls_back_on_the_same_halt( + model, monkeypatch, run1 +) -> None: + install_reply(model, monkeypatch) + plain = model.cache.run(PROMPT, PARAMS, Agent()) + assert plain.status == "HALTED" + # Without the halted call going through the policy, no record check was + # kept with the halt, so a held call does not fall back. + later = policy(model).run(PROMPT, {"value": "two"}, Agent()) + assert later.status == "CACHE_HALTED" and model.rows == [] + model.stop.unlink() + chosen = policy(model) + assert chosen.run(PROMPT, PARAMS, Agent()).verified + held = policy(model).run(PROMPT, {"value": "two"}, Agent()) + assert held.path == fb.FALLBACK_PATH and held.verified + assert [r["value"] for r in model.rows] == ["one", "two"] + assert len(model.sent) == 2 # the held call did not run the program again + + +# -- when it never falls back -------------------------------------------------- + + +@pytest.mark.parametrize( + ("case", "reply", "status"), + [ + ("reconciliation_report", {"report": "reconciliation"}, "HALTED"), + ( + "reconciliation_status", + {"status": "RECONCILIATION_REQUIRED"}, + "RECONCILIATION_REQUIRED", + ), + ("delivery_attempted", {"report": "delivery"}, "HALTED"), + ("unbound_report", {"report": "wrong_digest"}, "HALTED"), + ( + "record_check_failed", + { + "verified": True, + "receipt_outcome": "VERIFIED", + "write": {"id": "1", "kind": "other", "value": "x"}, + }, + "RECORD_CHECK_FAILED", + ), + ( + "receipt_not_verified", + { + "verified": True, + "write": {"id": "1", "kind": "synthetic", "value": "one"}, + }, + "RECEIPT_NOT_VERIFIED", + ), + ("model_call_in_replay", {"model_calls": 1}, "HALTED"), + ("unproved_model_calls", {"model_calls": None}, "HALTED"), + ( + "halt_after_a_write", + {"write": {"id": "1", "kind": "synthetic", "value": "one"}}, + "HALTED", + ), + ], +) +def test_never_falls_back(model, monkeypatch, run1, case, reply, status) -> None: + write = reply.pop("write", None) + report = reply.pop("report", None) + install_reply(model, monkeypatch, write=write, report=report, **reply) + rows_before_agent = None + agent = Agent() + chosen = policy(model) + result = chosen.run(PROMPT, PARAMS, agent) + rows_before_agent = list(model.rows) + assert result.status == status and result.path == "skill", case + assert agent.calls == 0 and FakeRun1.made == [] + assert chosen.last is None or chosen.last["fallback"] is False + # Held, and the next call is held too: never a fallback. + again = policy(model).run(PROMPT, {"value": "two"}, agent) + assert again.status == "CACHE_HALTED" and agent.calls == 0 + assert model.rows == rows_before_agent + + +@pytest.mark.parametrize("error", [RuntimeError("private"), KeyboardInterrupt()]) +def test_a_lost_reply_never_falls_back(model, monkeypatch, run1, error) -> None: + async def hit(*_): + model.sent.append("sent") + raise error + + monkeypatch.setattr(skills, "_call_skill", hit) + agent = Agent() + with pytest.raises(type(error)): + policy(model).run(PROMPT, PARAMS, agent) + again = policy(model).run(PROMPT, {"value": "two"}, agent) + assert again.status == "CACHE_HALTED" and agent.calls == 0 + assert json.loads(model.stop.read_text())["phase"] == "running" + + +# -- the gate, the cap, the marker ---------------------------------------------- + + +def test_gate_refusal_means_no_save(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + chosen = policy(model, gate=lambda request: False) + result = chosen.run(PROMPT, PARAMS, Agent()) + assert result.status == "GATE_REFUSED" and not result.verified + # Read the state, not the report: nothing was saved. + assert model.cache.common["expect"] and model.rows == [] + assert chosen.last["task_record_check"]["created"] == 0 + root = model.tmp / "cache" / "fallback" / "task" + assert not (root / fb._ACTIVE).exists() + + +def test_unattended_terminal_gate_refuses_before_the_agent( + model, monkeypatch, run1 +) -> None: + install_reply(model, monkeypatch) + gate = TerminalGate(ask=lambda _: pytest.fail("asked"), attended=lambda: False) + agent = Agent() + result = policy(model, gate=gate).run(PROMPT, PARAMS, agent) + assert result.status == "FALLBACK_GATE_UNATTENDED" and agent.calls == 0 + assert gate(SimpleNamespace(control="Save")) is False + assert model.rows == [] + + +def test_attended_terminal_gate_uses_the_terminal_confirm(capsys) -> None: + answers = iter(["y", "no"]) + gate = TerminalGate(ask=lambda _: next(answers), attended=lambda: True) + request = compile_agent.GateRequest("Save", ("Synthetic record",), "", None) + assert gate(request) is True and gate(request) is False + assert "about to press 'Save'" in capsys.readouterr().out + + +@pytest.mark.parametrize("cap", [None, 0, -1, float("inf"), float("nan"), True, "1"]) +def test_the_cap_is_required(model, cap) -> None: + with pytest.raises(ValueError): + FallbackPolicy(model.cache, max_cost_usd=cap) + + +def test_cost_cap_is_enforced(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + run1.spend = SimpleNamespace(model_calls=3, usage_known=True, cost_usd=lambda: 0.9) + agent = Agent(model_free=False, cap=2.0) + result = policy(model, max_cost_usd=0.5).run(PROMPT, PARAMS, agent) + assert result.status == "COST_CAP_EXCEEDED" and not result.verified + assert model.rows == [] # held at the gate: over the cap, no save + assert agent.seen_cap == 0.5 and agent.max_cost_usd == 2.0 + + +def test_unknown_spend_is_refused_at_the_gate(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + run1.spend = SimpleNamespace(model_calls=1, usage_known=False, cost_usd=lambda: 0) + result = policy(model).run(PROMPT, PARAMS, Agent(model_free=False, cap=1.0)) + assert result.status == "COST_CAP_EXCEEDED" and model.rows == [] + + +def test_an_uncappable_agent_is_not_started(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + agent = Agent(model_free=False) + result = policy(model).run(PROMPT, PARAMS, agent) + assert result.status == "FALLBACK_COST_UNBOUNDED" and agent.calls == 0 + + +def test_a_crashed_fallback_needs_reconciliation(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + with pytest.raises(RuntimeError): + policy(model).run(PROMPT, PARAMS, Agent(raises=True)) + agent = Agent() + again = policy(model).run(PROMPT, {"value": "two"}, agent) + assert again.status == "RECONCILIATION_REQUIRED" and agent.calls == 0 + assert fb.clear_in_flight(model.cache, PROMPT, PARAMS) + assert policy(model).run(PROMPT, {"value": "two"}, agent).verified + + +def test_a_fallback_request_id_runs_once(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + assert policy(model, request_id="r1.fallback").run(PROMPT, PARAMS, Agent()).verified + agent = Agent() + again = policy(model, request_id="r1.fallback").run(PROMPT, PARAMS, agent) + assert again.status == "FALLBACK_REQUEST_REUSED" and agent.calls == 0 + runs = fb.fallback_runs(model.cache, PROMPT, PARAMS) + assert [r["status"] for r in runs["runs"]] == ["VERIFIED"] + assert not runs["in_flight"] + + +@pytest.mark.parametrize("bad", ["", "../x", ".hidden", "a/b", "x" * 129]) +def test_request_ids_are_plain_names(model, bad) -> None: + with pytest.raises(ValueError): + FallbackPolicy(model.cache, max_cost_usd=1, request_id=bad) + + +# -- the default is today's hold -------------------------------------------------- + + +def test_an_ineligible_halt_through_the_policy_is_byte_identical( + tmp_path, monkeypatch +) -> None: + """The default (no policy) is today's hold. Through an opt-in policy, a + halt that may not fall back returns the cache's own result object and + leaves the same hold bytes, with no fallback directory.""" + + results = {} + for name in ("plain", "policy"): + root = tmp_path / name + root.mkdir() + m = build_model(root, monkeypatch) + install_reply(m, monkeypatch, report="reconciliation") + runner: Any = m.cache + if name == "policy": + runner = FallbackPolicy( + m.cache, max_cost_usd=1, gate=lambda r: pytest.fail("gate") + ) + agent = Agent() + first = runner.run(PROMPT, PARAMS, agent) + second = runner.run(PROMPT, {"value": "two"}, agent) + assert agent.calls == 0 + hold = m.stop.read_text().replace(str(root), "ROOT").replace(m.digest, "DIGEST") + results[name] = ( + {**first.to_dict(), "seconds": 0, "replay": None}, + {**second.to_dict(), "seconds": 0, "replay": None}, + first.replay["status"], + hold, + sorted(p.name for p in (root / "cache").iterdir()), + ) + assert results["plain"] == results["policy"] + assert "fallback" not in results["policy"][4] + + +@pytest.mark.parametrize("report", [None, "reconciliation", "delivery", "wrong_digest"]) +def test_eligibility_agrees_with_open_repair(model, monkeypatch, report) -> None: + """proved_before_effect mirrors SkillCache.open_repair's halt checks + (inline in skills.py); pin the two together on the same halts.""" + from openadapt_flow.agent.repair import RepairAccessPolicy, RepairDesk, RepairError + + install_reply(model, monkeypatch, report=report) + assert model.cache.run(PROMPT, PARAMS, Agent()).status == "HALTED" + found = fb.proved_before_effect(model.cache, PROMPT, PARAMS) + desk = RepairDesk(model.tmp / "repairs", RepairAccessPolicy(None)) + try: + model.cache.open_repair(PROMPT, PARAMS, repair_desk=desk) + opened = True + except RepairError: + opened = False + assert found.eligible is opened is (report is None), (report, found.reason) From ac01fa9ce5d7f3e1ef461075b5c5f9601217b646 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:16:58 -0500 Subject: [PATCH 2/9] fix(flow): close the fallback's fail-open read, dispatch and release paths An unreadable system-of-record read no longer counts as unchanged: the task record check carries readable, and the fallback needs it to qualify a halt or to drop the in-flight marker. A verified fallback now needs the final task-scoped read to confirm the save; otherwise it is RECONCILIATION_REQUIRED with both readings kept, no repair and the marker kept. wrap-dispatch only replays (SkillCache.replay_only): a miss is NO_ADMITTED_PROGRAM and never reaches a first run, and the fallback agent is built only once a fallback may start. The stored request result is the whole dispatch envelope, so a retry replays fallback and the miss too. Fallback ids are derived by digest, so any valid parent id works. The in-flight marker names its owner (nonce, pid, host). A worker clears only its own marker; release refuses a live or unprovable owner, and a hold whose evidence does not prove nothing was written needs --after-reconciling. Adds ItemApprovalGate (--fallback-gate item-approval): a person approves each fallback save from Desktop or a paired phone through the signed item-approval store, so the fallback can run without a terminal. --- .../integrations/agents/skills.py | 29 +- packages/flow/openadapt_flow/wrap/__init__.py | 6 + .../flow/openadapt_flow/wrap/approval_gate.py | 272 +++++++++++++++ .../flow/openadapt_flow/wrap/compiled_only.py | 68 ++++ .../flow/openadapt_flow/wrap/dispatch_cli.py | 224 ++++++++++--- packages/flow/openadapt_flow/wrap/fallback.py | 129 +++++-- .../openadapt_flow/wrap/fallback_marker.py | 154 +++++++++ .../flow/tests/test_wrap_approval_gate.py | 314 ++++++++++++++++++ packages/flow/tests/test_wrap_dispatch_cli.py | 158 ++++++++- packages/flow/tests/test_wrap_fallback.py | 219 +++++++++++- 10 files changed, 1488 insertions(+), 85 deletions(-) create mode 100644 packages/flow/openadapt_flow/wrap/approval_gate.py create mode 100644 packages/flow/openadapt_flow/wrap/compiled_only.py create mode 100644 packages/flow/openadapt_flow/wrap/fallback_marker.py create mode 100644 packages/flow/tests/test_wrap_approval_gate.py diff --git a/packages/flow/openadapt_flow/integrations/agents/skills.py b/packages/flow/openadapt_flow/integrations/agents/skills.py index 00cc1799cb..cf5febd90c 100644 --- a/packages/flow/openadapt_flow/integrations/agents/skills.py +++ b/packages/flow/openadapt_flow/integrations/agents/skills.py @@ -510,6 +510,29 @@ def evict(self, prompt: str, params: Mapping[str, Any]) -> Optional[Path]: def run(self, prompt: str, params: Mapping[str, Any], agent: Any) -> SkillRun: started = time.monotonic() compiler, key = self._compiler(prompt, params) + served = self._compiled(compiler, key, params, started) + if served is not None: + return served + return self._first_run(compiler, key, prompt, params, agent, started) + + def replay_only(self, prompt: str, params: Mapping[str, Any]) -> Optional[SkillRun]: + """The admitted program, or the hold, and never a first run. + + None when the task has no admitted program (a miss): no agent is + involved, so a miss can't start one. + """ + + started = time.monotonic() + compiler, key = self._compiler(prompt, params) + return self._compiled(compiler, key, params, started) + + def _compiled( + self, + compiler: Any, + key: dict[str, Any], + params: Mapping[str, Any], + started: float, + ) -> Optional[SkillRun]: if (compiler.dir / _STOP_FILE).exists() or ( compiler.dir / _STOP_FILE ).is_symlink(): @@ -539,7 +562,7 @@ def run(self, prompt: str, params: Mapping[str, Any], agent: Any) -> SkillRun: stream.flush() os.fsync(stream.fileno()) return self._held(compiler, started) - return self._first_run(compiler, key, prompt, params, agent, started) + return None def _held(self, compiler: Any, started: float) -> SkillRun: try: @@ -1005,6 +1028,8 @@ class TaskRecordCheck: removed: int #: Writes to other records during the run (other users, other tasks). outside_run: dict[str, int] = field(default_factory=dict) + #: False when either read failed: the zero counts then prove nothing. + readable: bool = True def to_dict(self) -> dict[str, Any]: return dict(self.__dict__) @@ -1032,7 +1057,7 @@ def task_record_check( if before is None or after is None: return TaskRecordCheck( - False, ["the system of record could not be read"], 0, 0, 0 + False, ["the system of record could not be read"], 0, 0, 0, readable=False ) def mine(record: Optional[Mapping[str, Any]]) -> bool: diff --git a/packages/flow/openadapt_flow/wrap/__init__.py b/packages/flow/openadapt_flow/wrap/__init__.py index 17cf4a0a81..8edc2cd748 100644 --- a/packages/flow/openadapt_flow/wrap/__init__.py +++ b/packages/flow/openadapt_flow/wrap/__init__.py @@ -234,9 +234,15 @@ def call(self, request_id: str, arguments: Mapping[str, Any]) -> dict[str, Any]: if "receipt_binding" not in result: result["receipt_binding"] = unbound("NO_RECEIPT") result["reason"] = "cached_tool_result" + # The stored result is the reply, so a retry replays all of it. + result = self.finalize(result) store.finish(begin.record, result) return result + def finalize(self, result: dict[str, Any]) -> dict[str, Any]: + """The result as it is stored and returned; a caller may add fields.""" + return result + def _result(run: SkillRun, agent: Any) -> dict[str, Any]: """Keep raw inputs, model summaries and exception text out of run records.""" diff --git a/packages/flow/openadapt_flow/wrap/approval_gate.py b/packages/flow/openadapt_flow/wrap/approval_gate.py new file mode 100644 index 0000000000..c7c95c4ca5 --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/approval_gate.py @@ -0,0 +1,272 @@ +"""A pre-commit gate a person answers from Desktop or a paired phone. + +:class:`~openadapt_flow.wrap.fallback.TerminalGate` needs a person at the +terminal, so a fallback started by a service (no TTY) never starts the +agent. :class:`ItemApprovalGate` asks through the item-approval store that +``each_item`` runs and the agent guard use +(:mod:`openadapt_flow.approval_mode.item_approval`): before each save the +fallback run writes ``item-approval/request-.json`` with the gate +screenshot, and waits. Desktop's Run it (``openadapt-flow item-approval +approve``) or the decision portal on a paired phone writes the answer. + +The gate lets the save through only for an answer that +:func:`~openadapt_flow.approval_mode.item_approval.answer_refusal` accepts: +decided by a person, signed by an approver key on the pinned approver roster, +for this exact request, before the request expired, and not by the agent +that asked. Anything else, including no answer within ``wait_s``, a decline, +an unsigned or off-roster answer and a missing screenshot, refuses the save. +With no approver root pinned, :attr:`ItemApprovalGate.attended` is False and +the fallback agent is never started. +""" + +from __future__ import annotations + +import hashlib +import json +import time +from collections.abc import Callable +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow.compile_agent.harness import GateRequest + +#: The run id prefix the gate's requests carry (the fallback request id). +WORKFLOW_NAME = "wrap-fallback" +#: Default wait for a person, in seconds. The agent's own run ceiling (at +#: most 120 seconds for a provider agent) still bounds the whole run. +DEFAULT_WAIT_S = 60.0 + + +def pin_from_config(config: Optional[str]) -> dict[str, Any]: + """The approver pin a deployment config's ``approvers`` section names. + + ``{}`` without a config. A config that can't be read raises + ``ValueError``: it must not quietly drop its pin. + """ + + if not config: + return {} + from openadapt_flow.deployment import load_deployment + + try: + section = load_deployment(config, allow_unresolved=True).approvers + except (OSError, ValueError) as exc: + raise ValueError(f"deployment config {config} can't be read: {exc}") from exc + if section is None: + return {} + pin: dict[str, Any] = {"config_root": section.root_public_key} + if section.head: + pin["config_head"] = tuple(section.head) + if section.key_dir: + pin["key_dir"] = Path(section.key_dir).expanduser().resolve() + return pin + + +class ItemApprovalGate: + """Ask a person to approve each fallback save through the item-approval + store, and wait for a signed answer. + + Args: + approvals_dir: Where each fallback run's approval folder goes + (``//item-approval``), for a + Desktop or portal that scans that runs root. Default: inside the + fallback run's own directory. + wait_s: How long to wait for each answer. The request expires then, + so a later answer is refused. + key_dir: The approver key directory (default: the admission key + directory, ``$OPENADAPT_JIT_KEY_DIR`` or ``~/.openadapt/jit``). + approver_root, config_root, config_head, config_only: The approver + pin, as :class:`ItemApprovalStore` takes it. + agent_id: Who asks; recorded as the run's initiator, so it can never + answer. + """ + + def __init__( + self, + *, + approvals_dir: Optional[Path | str] = None, + wait_s: float = DEFAULT_WAIT_S, + key_dir: Optional[Path | str] = None, + approver_root: Optional[str] = None, + config_root: Optional[str] = None, + config_head: Optional[tuple[int, str]] = None, + config_only: bool = False, + agent_id: str = "wrap-fallback", + sleep: Callable[[float], None] = time.sleep, + ) -> None: + if isinstance(wait_s, bool) or not isinstance(wait_s, (int, float)): + raise ValueError("wait_s is a number of seconds") + if not 0 < float(wait_s) <= 4 * 3600: + raise ValueError("wait_s is more than 0 and at most 4 hours") + self.approvals_dir = ( + Path(approvals_dir).expanduser() if approvals_dir is not None else None + ) + self.wait_s = float(wait_s) + self.key_dir = Path(key_dir) if key_dir is not None else None + self._pin: dict[str, Any] = ( + { + "config_root": config_root, + "config_only": True, + "config_head": config_head, + } + if config_only + else { + "approver_root": approver_root, + "config_root": config_root, + "config_head": config_head, + } + ) + self.agent_id = agent_id + self._sleep = sleep + self._dir: Optional[Path] = None + self._run_id: Optional[str] = None + self._store: Any = None + self._asked = 0 + #: One row per save asked: request id and digest, and the decision + #: or the closed refusal code. PHI-free. + self.decisions: list[dict[str, Any]] = [] + + # -- whether anyone can answer --------------------------------------------- + + def _root(self) -> Optional[str]: + from openadapt_flow.approval_mode.approver_roster import ( + RosterError, + pinned_root, + verified_approvers, + ) + from openadapt_flow.jit.lifecycle import default_key_dir + + try: + root = pinned_root( + self._pin.get("approver_root"), + config_root=self._pin.get("config_root"), + config_only=bool(self._pin.get("config_only")), + ) + if root is None: + return None + verified_approvers( + self.key_dir or default_key_dir(), + root, + at_least=self._pin.get("config_head"), + ) + except RosterError: + return None + return root + + @property + def attended(self) -> bool: + """True only when a pinned approver roster verifies: otherwise every + person's answer would be refused, so the agent is not started.""" + + return self._root() is not None + + def bind(self, run_root: Path, request_id: str) -> None: + """The fallback run this gate serves (FallbackPolicy calls it).""" + + self._dir = ( + self.approvals_dir / request_id + if self.approvals_dir is not None + else Path(run_root) / "approval" + ) + self._run_id = request_id + self._store = None + self._asked = 0 + self.decisions = [] + + # -- one save ---------------------------------------------------------------- + + def _open_store(self) -> Any: + from openadapt_flow.approval_mode.approver import DEFAULT_APPROVER_POLICY + from openadapt_flow.approval_mode.item_approval import ItemApprovalStore + + assert self._dir is not None + store = ItemApprovalStore(self._dir, key_dir=self.key_dir, **self._pin) + # Person-only, pinned before anything is asked; the agent that asks + # is recorded so it can never answer. + store.write_policy(DEFAULT_APPROVER_POLICY) + store.write_initiator(f"agent:{self.agent_id}") + store.write_approver_root() + return store + + def _refuse(self, code: str, **row: Any) -> bool: + self.decisions.append({"decision": "refused", "code": code, **row}) + return False + + def __call__(self, request: GateRequest) -> bool: + from openadapt_flow.approval_mode.item_approval import ( + ItemApprovalRefused, + wait_for_answer, + ) + from openadapt_flow.approval_mode.model import ApprovalMode + + if self._dir is None or self._run_id is None: + return self._refuse("gate_not_bound") + shot = request.screenshot + try: + if shot is None or Path(shot).is_symlink(): + raise OSError("no screenshot") + frame = Path(shot).read_bytes() + except OSError: + # A person approves what they see; with nothing to show, refuse. + return self._refuse("screenshot_required") + if not frame: + return self._refuse("screenshot_required") + identity = [str(s) for s in request.identity] + facts = json.dumps( + {"control": request.control, "identity": identity, "url": request.url}, + sort_keys=True, + ).encode("utf-8") + index = self._asked + self._asked += 1 + try: + if self._store is None: + self._store = self._open_store() + store = self._store + asked = store.open_request( + run_id=self._run_id, + workflow_name=WORKFLOW_NAME, + step_id=f"save-{index + 1}", + step_index=index, + step_intent=( + f"Press '{request.control}' on the record showing " + + ", ".join(identity) + ), + mode=ApprovalMode.EACH_ITEM, + bundle_content_digest=None, + runtime_inputs_digest=None, + frame_png=frame, + form_state=( + "screen_text", + "sha256:" + hashlib.sha256(facts).hexdigest(), + ), + ttl_s=self.wait_s, + provenance={ + "actor": f"agent:{self.agent_id}", + "task_scope": "the task's own record, after the compiled " + "program stopped before saving", + }, + ) + except ItemApprovalRefused as exc: + return self._refuse(exc.code) + except Exception: # noqa: BLE001 - no request a person can answer + return self._refuse("request_refused") + row = {"request_id": asked.request_id, "request_sha256": asked.digest()} + answer, code = wait_for_answer( + store, asked, timeout_s=self.wait_s, sleep=self._sleep + ) + if answer is None: + return self._refuse(code or "no_answer", **row) + if answer.decision != "approve": + return self._refuse("declined", **row) + if not store.consume(asked.request_id): + return self._refuse("approval_already_used", **row) + self.decisions.append( + { + "decision": "approved", + "answer_sha256": answer.digest(), + "route": answer.route, + "signer": answer.attestation.signer if answer.attestation else None, + **row, + } + ) + return True diff --git a/packages/flow/openadapt_flow/wrap/compiled_only.py b/packages/flow/openadapt_flow/wrap/compiled_only.py new file mode 100644 index 0000000000..9d5fbe454e --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/compiled_only.py @@ -0,0 +1,68 @@ +"""Dispatch to a task's admitted program only: a miss never starts an agent. + +``SkillCache.run`` makes a first run when the task has no admitted program, +which hands the task to the agent with the normal compile and admission +settings. ``wrap-dispatch`` never does that, even when the program is +evicted between a status check and the call: it uses +:func:`compiled_only`, which reports ``NO_ADMITTED_PROGRAM`` instead. +""" + +from __future__ import annotations + +import time +from collections.abc import Mapping +from typing import Any + +from openadapt_flow.integrations.agents.skills import SkillRun + +#: ``status`` of a dispatch that found no admitted program and ran nothing. +NO_ADMITTED_PROGRAM = "NO_ADMITTED_PROGRAM" + + +def missed(started: float) -> SkillRun: + """The result of a dispatch with no admitted program: nothing ran.""" + + return SkillRun( + path="skill", + status=NO_ADMITTED_PROGRAM, + verified=False, + model_calls=0, + cost_usd=0.0, + usage=[], + usage_known=True, + seconds=round(time.monotonic() - started, 3), + detail="The task has no admitted program; nothing ran. " + "openadapt wrap makes the first run.", + ) + + +def compiled_only(cache: Any, prompt: str, params: Mapping[str, Any]) -> SkillRun: + """The cache's compiled replay or hold, or a miss. Never a first run. + + A cache without ``replay_only`` (not a SkillCache) can't promise that, + so it is treated as a miss. + """ + + started = time.monotonic() + replay_only = getattr(cache, "replay_only", None) + if not callable(replay_only): + return missed(started) + served = replay_only(prompt, params) + return served if served is not None else missed(started) + + +class CompiledOnly: + """A TaskCache for :class:`~openadapt_flow.wrap.WrappedTask` that only + replays. The agent ``WrappedTask`` passes is never used.""" + + def __init__(self, cache: Any) -> None: + self.cache = cache + + def __getattr__(self, name: str) -> Any: + return getattr(self.__dict__["cache"], name) + + def key(self, prompt: str, params: Mapping[str, Any]) -> dict[str, Any]: + return self.cache.key(prompt, params) + + def run(self, prompt: str, params: Mapping[str, Any], agent: Any) -> SkillRun: + return compiled_only(self.cache, prompt, params) diff --git a/packages/flow/openadapt_flow/wrap/dispatch_cli.py b/packages/flow/openadapt_flow/wrap/dispatch_cli.py index a95f4c3153..dd3820173c 100644 --- a/packages/flow/openadapt_flow/wrap/dispatch_cli.py +++ b/packages/flow/openadapt_flow/wrap/dispatch_cli.py @@ -24,6 +24,7 @@ from __future__ import annotations import argparse +import hashlib import json import math import sys @@ -93,6 +94,9 @@ def finish( result: dict[str, Any], fallback: Optional[Mapping[str, Any]] ) -> dict[str, Any]: """Add the dispatch fields to a WrappedTask per-run result.""" + if "outcome" in result and "fallback" in result: + # Already a dispatch envelope (stored, then replayed on a retry). + return dict(result) out = dict(result) out["path"] = dispatch_path(result) out["outcome"] = outcome(result) @@ -177,6 +181,37 @@ def add_run_arguments(p: argparse.ArgumentParser) -> None: "--fallback-request-id", help="The fallback run's own ID (default: derived from --request-id)", ) + p.add_argument( + "--fallback-gate", + choices=("terminal", "item-approval"), + default="terminal", + help="Who approves each fallback save: a person at this terminal " + "(terminal, the default), or a person in Desktop's Run it or on a " + "paired phone, through a signed item approval (item-approval; no " + "terminal needed)", + ) + p.add_argument( + "--fallback-approvals-dir", + help="With --fallback-gate item-approval: the runs root Desktop or the " + "decision portal scans (default: inside the fallback run's directory)", + ) + p.add_argument( + "--fallback-approval-wait-s", + type=float, + default=60.0, + help="With --fallback-gate item-approval: seconds to wait for each " + "answer (less than --max-run-seconds)", + ) + p.add_argument( + "--fallback-approver-root", + help="With --fallback-gate item-approval: the pinned approver root " + "(else OPENADAPT_APPROVER_ROOT or --fallback-approvers-config)", + ) + p.add_argument( + "--fallback-approvers-config", + help="With --fallback-gate item-approval: a deployment config whose " + "approvers section pins the root; it is then the only pin counted", + ) p.add_argument("--provider", choices=("claude", "openai"), default="claude") p.add_argument("--model") p.add_argument( @@ -260,6 +295,51 @@ def _fallback_agent(args: argparse.Namespace, setup: Any) -> Any: return agent +def child_request_id(parent: str) -> str: + """The fallback request id for a dispatch request id. + + A parent id is any 1 to 128 characters; a fallback id is a plain file + name. A digest of the parent fits both, and stays the same on a retry. + """ + + digest = hashlib.sha256(f"wrap-dispatch:{parent}".encode("utf-8")).hexdigest() + return f"fallback-{digest[:40]}" + + +def item_approval_gate(args: argparse.Namespace) -> Any: + """The non-terminal gate from the ``--fallback-*`` flags.""" + + from openadapt_flow.wrap.approval_gate import ItemApprovalGate, pin_from_config + + try: + pin = pin_from_config(args.fallback_approvers_config) + except ValueError as exc: + raise SystemExit(f"REFUSED (deployment_config_unreadable): {exc}") from None + key_dir = pin.pop("key_dir", None) or ( + Path(args.key_dir).expanduser() if args.key_dir else None + ) + return ItemApprovalGate( + approvals_dir=args.fallback_approvals_dir, + wait_s=args.fallback_approval_wait_s, + key_dir=key_dir, + approver_root=args.fallback_approver_root, + config_only=bool(args.fallback_approvers_config), + **pin, + ) + + +def _task(policy: Any, **options: Any) -> Any: + """A WrappedTask whose stored result is the whole dispatch envelope.""" + from openadapt_flow.wrap import WrappedTask + + class DispatchTask(WrappedTask): + def finalize(self, result: dict[str, Any]) -> dict[str, Any]: + last = getattr(policy, "last", None) if policy is not None else None + return finish(result, last) + + return DispatchTask(**options) + + def run( args: argparse.Namespace, *, @@ -268,9 +348,15 @@ def run( repair_desk: Any = None, ) -> dict[str, Any]: """One dispatch. ``agent``, ``gate`` and ``repair_desk`` are for tests and - embedding; the CLI builds the provider agent and the terminal gate.""" - from openadapt_flow.wrap import WrappedTask + embedding; the CLI builds the provider agent and the gate. + + Only the admitted program runs (:mod:`.compiled_only`): with none, the + result is ``NO_ADMITTED_PROGRAM`` and nothing runs. The result, + including ``fallback``, is stored with the request, so a retry of the + same request id returns it without running anything. + """ from openadapt_flow.wrap.cli import _params, _with_secret_env + from openadapt_flow.wrap.compiled_only import CompiledOnly if not args.task or not args.request_id: raise SystemExit("wrap-dispatch needs --task and --request-id") @@ -278,33 +364,25 @@ def run( cap = args.fallback_max_cost_usd if fallback_on and (cap is None or not math.isfinite(cap) or cap <= 0): raise SystemExit("--fallback agent requires a positive --fallback-max-cost-usd") - if not fallback_on and (cap is not None or args.fallback_request_id): - raise SystemExit("--fallback-max-cost-usd needs --fallback agent") + if not fallback_on and ( + cap is not None + or args.fallback_request_id + or args.fallback_gate != "terminal" + or args.fallback_approvals_dir + ): + raise SystemExit("the --fallback-* options need --fallback agent") + if args.fallback_gate == "item-approval" and not ( + 0 < args.fallback_approval_wait_s < args.max_run_seconds + ): + raise SystemExit( + "--fallback-approval-wait-s must be more than 0 and less than " + "--max-run-seconds" + ) from openadapt_flow.compile_agent.cli import _teach_authority setup = _setup(args.task, args.key_dir, _teach_authority(args)) names = _names(setup) - started = time.monotonic() - if not setup.cache.held(setup.instruction, names) and ( - setup.cache.server(setup.instruction, names) is None - ): - # Never a first run: that is openadapt wrap's, with its own review. - result = { - "request_id": args.request_id, - "path": "held", - "status": "NO_ADMITTED_PROGRAM", - "verified": False, - "model_calls": 0, - "cost_usd": 0.0, - "usage": [], - "usage_known": True, - "seconds": round(time.monotonic() - started, 3), - "wire_checked": False, - "receipt": None, - "receipt_outcome": None, - } - return finish(result, None) - cache: Any = setup.cache + cache: Any = CompiledOnly(setup.cache) policy = None if fallback_on: from openadapt_flow.wrap.fallback import ( @@ -318,26 +396,37 @@ def run( root = fallback_root(setup.cache, setup.instruction, names) repair_desk = RepairDesk(root / "repairs", RepairAccessPolicy(None)) - if agent is None: - agent = _fallback_agent(args, setup) + if gate is None: + gate = ( + item_approval_gate(args) + if args.fallback_gate == "item-approval" + else TerminalGate() + ) + given = agent policy = FallbackPolicy( setup.cache, max_cost_usd=cap, - gate=gate if gate is not None else TerminalGate(), - request_id=args.fallback_request_id or f"{args.request_id}.fallback", + gate=gate, + request_id=args.fallback_request_id or child_request_id(args.request_id), repair_desk=repair_desk, + # Built only once a fallback may start: a miss or a hold that + # may not fall back never makes the agent or loads a model key. + agent_factory=(lambda: given) + if given is not None + else (lambda: _fallback_agent(args, setup)), + parent_request_id=args.request_id, ) cache = policy - task = WrappedTask( + task = _task( + policy, cache=cache, - agent=agent if agent is not None else _NoAgent(), + agent=_NoAgent(), instruction=setup.instruction, parameters=setup.parameters, runs_dir=args.runs_dir, ) values = _with_secret_env(_params(args.param), task.parameters) - result = task.call(args.request_id, values) - return finish(result, policy.last if policy is not None else None) + return finish(task.call(args.request_id, values), None) def _hold_file(setup: Any) -> Path: @@ -381,10 +470,40 @@ def status(args: argparse.Namespace) -> dict[str, Any]: } +def _hold_is_proved_clean(setup: Any, names: Mapping[str, str]) -> bool: + """The hold's own evidence shows nothing was written: a halt the report + proves before effect, bound to the admitted bundle, or a hold whose + program never ran (no baseline, or no repair selection).""" + from openadapt_flow.wrap.fallback import proved_before_effect + + try: + stopped = json.loads(_hold_file(setup).read_text(encoding="utf-8")) + except (OSError, ValueError): + return False + if not isinstance(stopped, dict) or stopped.get("phase") != "halted": + return False + replay = stopped.get("replay") + if replay is None: + return stopped.get("reason") == "repair_selection_unavailable" + if not isinstance(replay, dict): + return False + if replay.get("status") == "BASELINE_UNAVAILABLE": + return replay.get("verified") is False + return proved_before_effect(setup.cache, setup.instruction, names).eligible + + def release(args: argparse.Namespace, ask: Any = input) -> dict[str, Any]: - """A person releases a hold at a terminal; the hold file is archived.""" + """A person releases a hold at a terminal; the hold file is archived. + + Without ``--after-reconciling`` only a hold whose evidence proves nothing + was written is released (see :func:`_hold_is_proved_clean`); a + ``RECONCILIATION_REQUIRED`` reply, a write, a ``running`` hold or an + unfinished fallback needs the person to check the record first. A + fallback whose owner is still running (or can't be checked from here) + is never released. + """ from openadapt_flow.compile_agent.cli import _interactive - from openadapt_flow.wrap.fallback import clear_in_flight, fallback_runs + from openadapt_flow.wrap.fallback import fallback_runs, release_in_flight person = (args.person or "").strip() if not person: @@ -394,7 +513,16 @@ def release(args: argparse.Namespace, ask: Any = input) -> dict[str, Any]: setup = _setup(args.task, args.key_dir) names = _names(setup) path = _hold_file(setup) - stuck = fallback_runs(setup.cache, setup.instruction, names)["in_flight"] + runs = fallback_runs(setup.cache, setup.instruction, names) + stuck = runs["in_flight"] + if stuck and runs["in_flight_owner"] != "ended": + return { + "released": False, + "reason": "FALLBACK_RUNNING", + "detail": "A fallback of this task is still running, or its owner " + "can't be checked from here; it may still save.", + "fallback_request_id": runs["in_flight_request_id"], + } phase = None if path.exists() or path.is_symlink(): try: @@ -403,7 +531,8 @@ def release(args: argparse.Namespace, ask: Any = input) -> dict[str, Any]: phase = "unreadable" elif not stuck: return {"released": False, "reason": "NOT_HELD"} - if (stuck or phase not in (None, "halted")) and not args.after_reconciling: + clean = phase is None or _hold_is_proved_clean(setup, names) + if (stuck or not clean) and not args.after_reconciling: return { "released": False, "reason": "RECONCILE_FIRST", @@ -412,6 +541,16 @@ def release(args: argparse.Namespace, ask: Any = input) -> dict[str, Any]: } if ask("Type release to release this hold: ").strip().lower() != "release": return {"released": False, "reason": "NOT_CONFIRMED"} + cleared = None + if stuck: + cleared = release_in_flight(setup.cache, setup.instruction, names) + if not cleared["cleared"]: + # Its owner came back to life, or it changed: keep everything. + return { + "released": False, + "reason": "FALLBACK_RUNNING", + "fallback_request_id": cleared.get("request_id"), + } archived = None if phase is not None: archived = path.with_name(f"skill-stop-released-{time.time_ns()}.json") @@ -420,14 +559,19 @@ def release(args: argparse.Namespace, ask: Any = input) -> dict[str, Any]: _write( archived.with_suffix(".by.json"), - {"person": person, "at": time.time(), "phase": phase}, + { + "person": person, + "at": time.time(), + "phase": phase, + "after_reconciling": bool(args.after_reconciling), + }, ) - cleared = clear_in_flight(setup.cache, setup.instruction, names) if stuck else False return { "released": True, "person": person, "archived": str(archived) if archived else None, - "fallback_cleared": cleared, + "fallback_cleared": bool(cleared and cleared["cleared"]), + "fallback_request_id": cleared.get("request_id") if cleared else None, } diff --git a/packages/flow/openadapt_flow/wrap/fallback.py b/packages/flow/openadapt_flow/wrap/fallback.py index 6618c40886..94ee4e20fd 100644 --- a/packages/flow/openadapt_flow/wrap/fallback.py +++ b/packages/flow/openadapt_flow/wrap/fallback.py @@ -42,6 +42,8 @@ from openadapt_flow.compile_agent.harness import GateRequest from openadapt_flow.integrations.agents.skills import SkillRun +from openadapt_flow.wrap import fallback_marker +from openadapt_flow.wrap.compiled_only import NO_ADMITTED_PROGRAM, compiled_only #: ``SkillRun.path`` of a run the agent did after a program's drift. FALLBACK_PATH = "agent_fallback" @@ -58,7 +60,7 @@ } ) -_ACTIVE = "in-flight.json" +_ACTIVE = fallback_marker.ACTIVE _HALT = "halt-evidence.json" _RESULT = "result.json" _REQUEST_CHARS = frozenset( @@ -119,9 +121,12 @@ def _int_zero(value: Any) -> bool: def _nothing_written(check: Any) -> bool: - """The cache's record check saw no change to the task's record.""" + """Both reads of the record check succeeded and saw no change to the + task's record. An unreadable store also reports zero counts; without + ``readable`` (an older check) nothing is proved.""" return ( isinstance(check, Mapping) + and check.get("readable") is True and _int_zero(check.get("created")) and _int_zero(check.get("changed")) and _int_zero(check.get("removed")) @@ -249,6 +254,11 @@ class FallbackPolicy: request_id: The fallback run's own id. Default: a new one per run. repair_desk: When given, a verified fallback opens a repair candidate with :meth:`SkillCache.open_repair`. + agent_factory: Builds the fallback agent. Called only after the halt + is proved before effect and a person is at the gate; then the + agent :meth:`run` was given is ignored. + parent_request_id: The dispatch request this fallback answers, + recorded with the fallback's result. """ def __init__( @@ -259,6 +269,8 @@ def __init__( gate: Optional[PreCommitGate] = None, request_id: Optional[str] = None, repair_desk: Any = None, + agent_factory: Optional[Callable[[], Any]] = None, + parent_request_id: Optional[str] = None, ) -> None: self.cache = cache self.max_cost_usd = _cap(max_cost_usd) @@ -272,6 +284,9 @@ def __init__( raise ValueError("a fallback request id is 1 to 128 of [A-Za-z0-9._-]") self.request_id = request_id self.repair_desk = repair_desk + #: Builds the fallback agent, called only once a fallback may start. + self.agent_factory = agent_factory + self.parent_request_id = parent_request_id #: What the last :meth:`run` did about a fallback (None: not tried). self.last: Optional[dict[str, Any]] = None @@ -287,9 +302,15 @@ def key(self, prompt: str, params: Mapping[str, Any]) -> dict[str, Any]: def run(self, prompt: str, params: Mapping[str, Any], agent: Any) -> SkillRun: self.last = None - # A lost reply raises here and stays held; it never falls back. - first = self.cache.run(prompt, params, agent) - if first.path != "skill" or first.verified or first.status in NEVER_FALL_BACK: + # Compiled replay only: a miss never reaches the agent. A lost reply + # raises here and stays held; it never falls back. + first = compiled_only(self.cache, prompt, params) + if ( + first.path != "skill" + or first.verified + or first.status in NEVER_FALL_BACK + or first.status == NO_ADMITTED_PROGRAM + ): return first root = fallback_root(self.cache, prompt, params) found = proved_before_effect(self.cache, prompt, params) @@ -355,6 +376,18 @@ def _fallback( root: Path, ) -> SkillRun: started = time.monotonic() + if getattr(self.gate, "attended", True) is False: + return self._refused( + first, + "FALLBACK_GATE_UNATTENDED", + "No person is at the pre-commit gate; the agent was not started.", + started, + ) + if self.agent_factory is not None: + try: + agent = self.agent_factory() + except (Exception, SystemExit): # noqa: BLE001 - nothing ran yet + agent = None if agent is None: return self._refused( first, "FALLBACK_NO_AGENT", "No fallback agent was given.", started @@ -370,20 +403,11 @@ def _fallback( "The fallback agent has no spend cap this policy can set.", started, ) - if getattr(self.gate, "attended", True) is False: - return self._refused( - first, - "FALLBACK_GATE_UNATTENDED", - "No person is at the pre-commit gate; the agent was not started.", - started, - ) request_id = self.request_id or f"fallback-{uuid.uuid4().hex}" root.mkdir(parents=True, exist_ok=True) - active = root / _ACTIVE + marker = fallback_marker.Marker(root, request_id) try: - _write( - active, {"request_id": request_id, "at": time.time()}, exclusive=True - ) + marker.claim() except FileExistsError: # Another fallback is running, or one ended without proving what # it wrote. A person reconciles it before another one starts. @@ -397,7 +421,7 @@ def _fallback( try: run_root.mkdir() except FileExistsError: - active.unlink() + marker.clear() return self._refused( first, "FALLBACK_REQUEST_REUSED", @@ -405,8 +429,18 @@ def _fallback( started, request_id=request_id, ) - # Any exception from here keeps the in-flight marker: a save may exist. - return self._run_agent(prompt, params, agent, first, root, run_root, started) + bind = getattr(self.gate, "bind", None) + if callable(bind): + # A gate that keeps its own evidence learns which run it serves. + bind(run_root, request_id) + try: + return self._run_agent( + prompt, params, agent, first, marker, run_root, started + ) + finally: + # A run that did not prove what it wrote (or raised) keeps the + # marker, marked ended, for a person; a cleared one is gone. + marker.end() def _run_agent( self, @@ -414,7 +448,7 @@ def _run_agent( params: Mapping[str, Any], agent: Any, first: SkillRun, - root: Path, + marker: fallback_marker.Marker, run_root: Path, started: float, ) -> SkillRun: @@ -514,11 +548,27 @@ def hold(request: GateRequest) -> bool: ) if status == "VERIFIED" and not verified: status, detail = "GATE_NOT_PROVED", "A save did not pass the gate." + # The final, task-scoped read decides: a success it doesn't confirm, + # or a stop it can't show wrote nothing, needs a person. Both + # readings are kept for that reconciliation. + confirmed = written.get("readable") is True and written.get("passed") is True + unchanged = _nothing_written(written) + run_status = status + if verified and not confirmed: + verified = False + status = "RECONCILIATION_REQUIRED" + detail = "The final read of the record does not confirm the save." + elif not verified and not unchanged and status != "GATE_NOT_PROVED": + status = "RECONCILIATION_REQUIRED" + detail = "The final read of the record can't show that nothing was saved." repair = self._open_repair(prompt, params, run_root) if verified else None self.last = { "fallback": True, "request_id": request_id, + "parent_request_id": self.parent_request_id, "status": status, + "run_status": run_status, + "readings_agree": verified or (unchanged and not check.get("passed")), "gates": gates, "decisions": decisions, "approvals": decisions.count("approved"), @@ -526,6 +576,11 @@ def hold(request: GateRequest) -> bool: "admitted": False, "task_record_check": written, } + answers = getattr(self.gate, "decisions", None) + if isinstance(answers, list): + # A gate that keeps its own evidence (ItemApprovalGate): which + # request each save asked and what answered it. PHI-free. + self.last["gate_answers"] = [dict(row) for row in answers] run = SkillRun( path=FALLBACK_PATH, status=status, @@ -544,10 +599,11 @@ def hold(request: GateRequest) -> bool: usage_known=usage_known, ) _write(run_root / _RESULT, run.to_dict()) - # The marker goes only when what the run did is known: a verified - # save, or an independent read that found the task's record unchanged. - if verified or _nothing_written(written): - (root / _ACTIVE).unlink(missing_ok=True) + # The marker goes only when what the run did is known (a save the + # final read confirmed, or a final read that found the task's record + # unchanged), and only while it is still this run's. + if verified or unchanged: + marker.clear() return run def _open_repair( @@ -593,17 +649,28 @@ def fallback_runs(cache: Any, prompt: str, params: Mapping[str, Any]) -> dict[st "repair": fallback.get("repair"), } ) + marker = fallback_marker.read(root) return { "dir": str(root), - "in_flight": (root / _ACTIVE).exists(), + "in_flight": marker is not None, + "in_flight_request_id": (marker or {}).get("request_id"), + # running or unknown: a save may still happen; release refuses. + "in_flight_owner": fallback_marker.owner_state(marker), "runs": runs, } +def release_in_flight( + cache: Any, prompt: str, params: Mapping[str, Any] +) -> dict[str, Any]: + """A person reconciled a stuck fallback: drop its marker (evidence stays). + + Only a marker whose owner ended is dropped; a live or unprovable owner + keeps it (``owner`` says which). + """ + return fallback_marker.release(fallback_root(cache, prompt, params)) + + def clear_in_flight(cache: Any, prompt: str, params: Mapping[str, Any]) -> bool: - """A person reconciled a stuck fallback: drop its marker (evidence stays).""" - marker = fallback_root(cache, prompt, params) / _ACTIVE - if not marker.exists(): - return False - marker.rename(marker.with_name(f"reconciled-{time.time_ns()}.json")) - return True + """:func:`release_in_flight`, True when a marker was dropped.""" + return bool(release_in_flight(cache, prompt, params)["cleared"]) diff --git a/packages/flow/openadapt_flow/wrap/fallback_marker.py b/packages/flow/openadapt_flow/wrap/fallback_marker.py new file mode 100644 index 0000000000..3f6e0cbe28 --- /dev/null +++ b/packages/flow/openadapt_flow/wrap/fallback_marker.py @@ -0,0 +1,154 @@ +"""The in-flight marker of a task's fallback run, and who owns it. + +While a fallback run may save, ``/in-flight.json`` exists and +no other fallback of the task starts. The marker names its owner: the +fallback request id, a nonce, the process id and the host. The owner removes +it only when it can prove what the run wrote, and only while it is still its +own. Otherwise the owner marks it ``ended`` and leaves it for a person. + +A person releases a marker (``wrap-dispatch release``) only when its owner +has ended: marked ``ended``, or a process on this host that no longer +exists. A live owner, or one on another host that this host can't check, +keeps its marker. +""" + +from __future__ import annotations + +import json +import os +import socket +import time +import uuid +from pathlib import Path +from typing import Any, Optional + +ACTIVE = "in-flight.json" + + +def _write(path: Path, data: dict[str, Any], *, exclusive: bool) -> None: + flags = os.O_WRONLY | os.O_CREAT | (os.O_EXCL if exclusive else os.O_TRUNC) + descriptor = os.open(path, flags, 0o600) + with os.fdopen(descriptor, "w", encoding="utf-8") as stream: + json.dump(data, stream, sort_keys=True) + stream.flush() + os.fsync(stream.fileno()) + + +def read(root: Path) -> Optional[dict[str, Any]]: + """The marker, ``{}`` when it is unreadable, None when there is none.""" + + path = root / ACTIVE + if not (path.exists() or path.is_symlink()): + return None + try: + if path.is_symlink(): + return {} + data = json.loads(path.read_text(encoding="utf-8")) + except (OSError, ValueError): + return {} + return data if isinstance(data, dict) else {} + + +class Marker: + """One fallback run's ownership of the task's in-flight marker.""" + + def __init__(self, root: Path, request_id: str) -> None: + self.root = root + self.request_id = request_id + self.nonce = uuid.uuid4().hex + + @property + def path(self) -> Path: + return self.root / ACTIVE + + def claim(self) -> None: + """Create the marker. Raises FileExistsError when one exists.""" + + _write( + self.path, + { + "request_id": self.request_id, + "nonce": self.nonce, + "pid": os.getpid(), + "host": socket.gethostname(), + "at": time.time(), + "state": "running", + }, + exclusive=True, + ) + + def owned(self) -> bool: + data = read(self.root) + return bool( + data + and data.get("nonce") == self.nonce + and data.get("request_id") == self.request_id + ) + + def clear(self) -> bool: + """Remove the marker if it is still this run's. False otherwise.""" + + if not self.owned(): + return False + self.path.unlink(missing_ok=True) + return True + + def end(self) -> bool: + """Mark the marker's owner ended; the marker stays for a person.""" + + data = read(self.root) + if not (data and data.get("nonce") == self.nonce): + return False + data = dict(data, state="ended", ended_at=time.time()) + temporary = self.root / f".{ACTIVE}.{self.nonce}" + _write(temporary, data, exclusive=False) + os.replace(temporary, self.path) + return True + + +def owner_state(data: Optional[dict[str, Any]]) -> str: + """``none``, ``ended``, ``running`` or ``unknown`` for a marker. + + ``running`` and ``unknown`` mean a save may still happen. + """ + + from openadapt_flow.agent.runs import pid_alive + + if data is None: + return "none" + if not data: + return "unknown" + if data.get("state") == "ended": + return "ended" + pid = data.get("pid") + if isinstance(pid, bool) or not isinstance(pid, int): + return "unknown" + if data.get("host") != socket.gethostname(): + return "unknown" + return "running" if pid_alive(pid) else "ended" + + +def release(root: Path) -> dict[str, Any]: + """A person drops a marker whose owner ended. The evidence stays. + + Returns ``{"cleared": bool, "owner": state, "request_id": ...}``. + """ + + data = read(root) + state = owner_state(data) + out = { + "cleared": False, + "owner": state, + "request_id": (data or {}).get("request_id"), + } + if state != "ended": + return out + path = root / ACTIVE + kept = path.with_name(f"reconciled-{time.time_ns()}.json") + try: + # An ended owner never writes again, and no other run claims the + # marker while it exists, so the file renamed is the one read. + path.rename(kept) + except FileNotFoundError: + return dict(out, owner="none") + return dict(out, cleared=True, kept_at=str(kept)) diff --git a/packages/flow/tests/test_wrap_approval_gate.py b/packages/flow/tests/test_wrap_approval_gate.py new file mode 100644 index 0000000000..019b2dbeab --- /dev/null +++ b/packages/flow/tests/test_wrap_approval_gate.py @@ -0,0 +1,314 @@ +"""ItemApprovalGate: the fallback's pre-commit gate without a terminal. + +A person answers in Desktop's Run it or on a paired phone; the answer is the +real item-approval store's, signed by a test approver key on a real roster +(tests/_approver_keys.py). The fallback's run 1 is the stand-in from +tests/test_wrap_fallback.py. +""" + +# ruff: noqa: F811 - pytest fixtures are imported by name +from __future__ import annotations + +from pathlib import Path +from typing import Any, Optional + +import pytest +from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey + +from openadapt_flow import compile_agent +from openadapt_flow.approval_mode.approver_roster import ROOT_ENV +from openadapt_flow.approval_mode.human_attestation import ApproverSigner +from openadapt_flow.approval_mode.item_approval import ( + ItemApprovalAnswer, + ItemApprovalStore, +) +from openadapt_flow.approval_mode.model import DECISION_PORTAL_ROUTE +from openadapt_flow.wrap.approval_gate import ItemApprovalGate +from tests._approver_keys import answer_as_person +from tests.test_wrap_fallback import ( # noqa: F401 - fixtures + PARAMS, + PROMPT, + Agent, + install_reply, + model, + policy, + run1, +) + +FRAME = b"\x89PNG\r\n\x1a\nsynthetic gate frame" + + +def request(tmp_path: Path) -> compile_agent.GateRequest: + shot = tmp_path / "gate.png" + shot.write_bytes(FRAME) + return compile_agent.GateRequest("Save", ("Synthetic record",), "", shot) + + +def answering( + gate: ItemApprovalGate, + write: Any, +) -> None: + """Stand in for the person: on the gate's first wait, answer the one + waiting request with ``write(store, request)``.""" + + done: list = [] + + def sleep(_seconds: float) -> None: + if done: + return + store = ItemApprovalStore(gate._dir, key_dir=gate.key_dir) + [asked] = store.requests() + done.append(write(store, asked)) + + gate._sleep = sleep + + +def person(decision: str = "approve", **extra: Any): + def write(store: ItemApprovalStore, asked: Any) -> None: + fields: dict[str, Any] = dict( + decision=decision, + decided_by="human", + route="desktop_run_it", + approver_id=None, + auth_method="none", + ) + if decision == "decline": + fields["decline_reason"] = "wrong_values" + fields.update(extra) + store.write_answer(answer_as_person(store, asked, **fields)) + + return write + + +def bound(tmp_path: Path, **kw: Any) -> ItemApprovalGate: + gate = ItemApprovalGate(wait_s=kw.pop("wait_s", 5.0), **kw) + gate.bind(tmp_path / "fallback-run", "fallback-abc") + return gate + + +def test_a_signed_person_approval_lets_the_save_through(tmp_path, approver) -> None: + gate = bound(tmp_path) + assert gate.attended + answering(gate, person()) + assert gate(request(tmp_path)) is True + [row] = gate.decisions + assert row["decision"] == "approved" and row["signer"] == "front-desk" + store = ItemApprovalStore(gate._dir) + [asked] = store.requests() + assert store.is_consumed(asked.request_id) + assert asked.run_id == "fallback-abc" and asked.provenance.actor.startswith( + "agent:" + ) + # The person is shown the gate screenshot itself. + assert store.read_frame(asked) == FRAME + + +def test_the_phone_portal_route_also_answers(tmp_path, approver) -> None: + gate = bound(tmp_path) + answering(gate, person(route=DECISION_PORTAL_ROUTE, signer=portal_signer())) + assert gate(request(tmp_path)) is True + assert gate.decisions[0]["route"] == DECISION_PORTAL_ROUTE + + +def test_a_decline_refuses(tmp_path, approver) -> None: + gate = bound(tmp_path) + answering(gate, person("decline")) + assert gate(request(tmp_path)) is False + assert gate.decisions[0]["code"] == "declined" + + +def test_an_unsigned_answer_refuses(tmp_path, approver) -> None: + def forged(store: ItemApprovalStore, asked: Any) -> None: + store.write_answer( + ItemApprovalAnswer( + request_id=asked.request_id, + request_sha256=asked.digest(), + decision="approve", + decided_by="human", + route="desktop_run_it", + approver_kind="unauthenticated", + auth_method="none", + answered_at=asked.created_at, + ) + ) + + gate = bound(tmp_path) + answering(gate, forged) + assert gate(request(tmp_path)) is False + assert gate.decisions[0]["code"] == "human_answer_unsigned" + + +@pytest.mark.parametrize("name", ["front-desk", "stranger"]) +def test_a_key_off_the_pinned_roster_refuses(tmp_path, approver, name) -> None: + """A new key claiming a roster name, or a name the roster doesn't hold.""" + stranger = ApproverSigner( + principal_id=name, method="desktop_key", signing=Ed25519PrivateKey.generate() + ) + + def write(store: ItemApprovalStore, asked: Any) -> None: + from openadapt_flow.approval_mode.item_approval import _iso, _utc_now + + answer = ItemApprovalAnswer( + request_id=asked.request_id, + request_sha256=asked.digest(), + decision="approve", + decided_by="human", + route="desktop_run_it", + approver_kind="unauthenticated", + auth_method="none", + answered_at=_iso(_utc_now()), + ) + from openadapt_flow.approval_mode.human_attestation import ANSWER_DOMAIN + + store.write_answer( + answer.model_copy( + update={ + "attestation": stranger.attest( + ANSWER_DOMAIN, answer.signed_payload() + ) + } + ) + ) + + gate = bound(tmp_path) + answering(gate, write) + assert gate(request(tmp_path)) is False + assert ( + gate.decisions[0]["code"] + == { + "front-desk": "human_answer_signature_invalid", + "stranger": "human_approver_unregistered", + }[name] + ) + + +def test_no_answer_before_expiry_refuses(tmp_path, approver) -> None: + gate = bound(tmp_path, wait_s=0.3) + gate._sleep = lambda s: __import__("time").sleep(s) + assert gate(request(tmp_path)) is False + assert gate.decisions[0]["code"] in ("request_expired", "approval_wait_timed_out") + + +def test_an_answer_after_expiry_refuses(tmp_path, approver) -> None: + """Signed while the request was open, read after it expired.""" + import time + + def late(store: ItemApprovalStore, asked: Any) -> None: + answer = answer_as_person( + store, + asked, + decision="approve", + decided_by="human", + route="desktop_run_it", + approver_id=None, + auth_method="none", + ) + time.sleep(0.4) + store.write_answer(answer) + + gate = bound(tmp_path, wait_s=0.3) + answering(gate, late) + assert gate(request(tmp_path)) is False + assert gate.decisions[0]["code"] in ("request_expired", "answer_after_expiry") + + +def test_no_screenshot_refuses_without_asking(tmp_path, approver) -> None: + gate = bound(tmp_path) + blind = compile_agent.GateRequest("Save", ("Synthetic record",), "", None) + assert gate(blind) is False and gate.decisions[0]["code"] == "screenshot_required" + assert ( + not (gate._dir / "item-approval").exists() + or not ItemApprovalStore(gate._dir).requests() + ) + + +def test_an_unbound_gate_refuses(tmp_path, approver) -> None: + gate = ItemApprovalGate(wait_s=1) + assert gate(request(tmp_path)) is False + + +def test_no_pinned_root_means_nobody_can_answer( + tmp_path, approver, monkeypatch +) -> None: + monkeypatch.delenv(ROOT_ENV) + assert ItemApprovalGate(wait_s=1).attended is False + + +# -- through the policy --------------------------------------------------------- + + +def test_a_service_fallback_saves_after_a_phone_approval( + model, + monkeypatch, + run1, + approver, + tmp_path, +) -> None: + install_reply(model, monkeypatch) + gate = ItemApprovalGate(wait_s=5, approvals_dir=tmp_path / "approvals") + real_bind = gate.bind + + def bind(run_root: Path, request_id: str) -> None: + real_bind(run_root, request_id) + answering(gate, person(route=DECISION_PORTAL_ROUTE, signer=portal_signer())) + + gate.bind = bind # type: ignore[method-assign] + chosen = policy(model, gate=gate) + result = chosen.run(PROMPT, PARAMS, Agent()) + assert result.verified and result.status == "VERIFIED" + assert model.rows == [{"id": "f1", "kind": "synthetic", "value": "one"}] + # The approval folder sits where Desktop or the portal scans for it. + assert ( + tmp_path / "approvals" / chosen.last["request_id"] / "item-approval" + ).is_dir() + assert chosen.last["gate_answers"][0]["decision"] == "approved" + + +def test_a_service_fallback_with_no_pin_never_starts( + model, + monkeypatch, + run1, + approver, +) -> None: + install_reply(model, monkeypatch) + monkeypatch.delenv(ROOT_ENV) + result = policy( + model, + gate=ItemApprovalGate(wait_s=1), + agent_factory=lambda: pytest.fail("agent started"), + ).run(PROMPT, PARAMS, None) + assert result.status == "FALLBACK_GATE_UNATTENDED" and model.rows == [] + + +def test_a_service_fallback_refused_at_the_gate_saves_nothing( + model, + monkeypatch, + run1, + approver, +) -> None: + install_reply(model, monkeypatch) + gate = ItemApprovalGate(wait_s=0.3) + gate._sleep = lambda s: __import__("time").sleep(s) + result = policy(model, gate=gate).run(PROMPT, PARAMS, Agent()) + assert result.status == "GATE_REFUSED" and model.rows == [] + + +def portal_signer(key_dir: Optional[Path] = None) -> ApproverSigner: + import os + + from openadapt_flow.approval_mode.human_attestation import ( + PORTAL_KEY_ENV, + load_signer, + ) + from openadapt_flow.jit.authority import KEY_PASSPHRASE_ENV + from openadapt_flow.jit.lifecycle import KEY_DIR_ENV + from tests._approver_keys import PASSPHRASE, root_of + + directory = key_dir or Path(os.environ[KEY_DIR_ENV]) + return load_signer( # type: ignore[return-value] + Path(os.environ[PORTAL_KEY_ENV]), + directory, + method="portal_key", + env={KEY_PASSPHRASE_ENV: PASSPHRASE}, + root=root_of(directory), + ) diff --git a/packages/flow/tests/test_wrap_dispatch_cli.py b/packages/flow/tests/test_wrap_dispatch_cli.py index 5040311d16..76ea91ad1f 100644 --- a/packages/flow/tests/test_wrap_dispatch_cli.py +++ b/packages/flow/tests/test_wrap_dispatch_cli.py @@ -4,6 +4,7 @@ (real cache, hold and report checks; the MCP reply and run 1 modelled). """ +# ruff: noqa: F811 - pytest fixtures are imported by name from __future__ import annotations import argparse @@ -48,7 +49,7 @@ def parse(*argv: str) -> argparse.Namespace: @pytest.fixture -def task(model, monkeypatch, tmp_path) -> SimpleNamespace: # noqa: F811 +def task(model, monkeypatch, tmp_path) -> SimpleNamespace: setup = SimpleNamespace( cache=model.cache, instruction=PROMPT, parameters=("value",) ) @@ -79,7 +80,7 @@ def test_the_verb_is_registered_in_openadapt_flow() -> None: def test_no_admitted_program_runs_nothing(task, monkeypatch) -> None: - monkeypatch.setattr(task.setup.cache, "server", lambda *_: None) + monkeypatch.setattr(task.setup.cache, "_server", lambda *_: None) result = dc.run(run_args(task, "r1", "one")) assert result["status"] == "NO_ADMITTED_PROGRAM" and result["path"] == "held" assert result["outcome"] == "ESCALATED" and result["model_calls"] == 0 @@ -131,7 +132,7 @@ def test_fallback_needs_its_own_cap(task) -> None: ) -def test_opt_in_fallback_result(task, monkeypatch, run1, tmp_path) -> None: # noqa: F811 +def test_opt_in_fallback_result(task, monkeypatch, run1, tmp_path) -> None: install_reply(task.model, monkeypatch) out = tmp_path / "result.json" args = run_args( @@ -149,7 +150,8 @@ def test_opt_in_fallback_result(task, monkeypatch, run1, tmp_path) -> None: # n result = dc.run(args, agent=Agent(), gate=lambda r: approvals.append(r) or True) assert result["path"] == "agent_fallback" and result["outcome"] == "VERIFIED" assert result["verified"] and result["model_calls"] == 0 and len(approvals) == 1 - assert result["fallback"]["request_id"] == "r1.fallback" + assert result["fallback"]["request_id"] == dc.child_request_id("r1") + assert result["fallback"]["parent_request_id"] == "r1" assert result["fallback"]["admitted"] is False assert result["fallback"]["repair"]["opened"] is True assert set(result) >= RUN_KEYS @@ -159,7 +161,7 @@ def test_opt_in_fallback_result(task, monkeypatch, run1, tmp_path) -> None: # n assert json.loads(out.read_text())["path"] == "agent_fallback" -def test_status_evict_and_release(task, monkeypatch, run1, capsys) -> None: # noqa: F811 +def test_status_evict_and_release(task, monkeypatch, run1, capsys) -> None: install_reply(task.model, monkeypatch) dc.run(run_args(task, "r1", "one")) shown = dc.status(parse("status", "task.json")) @@ -213,3 +215,149 @@ async def hit(*_): ) def test_outcomes(status: str, verified: bool, expected: str) -> None: assert dc.outcome({"status": status, "verified": verified}) == expected + + +# -- review fixes: compiled-only dispatch, stored envelope, release ------------ + +FALLBACK = ("--fallback", "agent", "--fallback-max-cost-usd", "0.25") + + +@pytest.mark.parametrize("extra", [(), FALLBACK]) +def test_a_program_evicted_after_the_check_is_a_miss( + task, + monkeypatch, + run1, + extra, +) -> None: + """server() still says yes (the old precheck); at dispatch there is no + admitted program. Nothing runs: no first run (fixture fails on one), no + program call, no agent.""" + monkeypatch.setattr(task.setup.cache, "server", lambda *_: Path("server.py")) + monkeypatch.setattr(task.setup.cache, "_server", lambda *_: None) + agent = Agent() + result = dc.run(run_args(task, "r1", "one", *extra), agent=agent) + assert result["status"] == "NO_ADMITTED_PROGRAM" and result["path"] == "held" + assert agent.calls == 0 and task.model.sent == [] + + +def test_no_admitted_program_is_stored_with_the_request(task, monkeypatch) -> None: + monkeypatch.setattr(task.setup.cache, "_server", lambda *_: None) + first = dc.run(run_args(task, "r1", "one")) + assert first["status"] == "NO_ADMITTED_PROGRAM" and first["replayed"] is False + # The program is admitted now; the same request still reports its outcome. + monkeypatch.undo() + monkeypatch.setattr(dc, "_setup", lambda *_a, **_k: task.setup) + install_reply(task.model, monkeypatch) + again = dc.run(run_args(task, "r1", "one")) + assert again["status"] == "NO_ADMITTED_PROGRAM" and again["replayed"] is True + assert task.model.sent == [] + + +def test_a_retry_replays_the_whole_dispatch_envelope( + task, + monkeypatch, + run1, +) -> None: + install_reply(task.model, monkeypatch) + agent = Agent() + first = dc.run( + run_args(task, "r1", "one", *FALLBACK), agent=agent, gate=lambda r: True + ) + assert first["verified"] and first["fallback"]["repair"]["opened"] + again = dc.run( + run_args(task, "r1", "one", *FALLBACK), + agent=agent, + gate=lambda r: pytest.fail("asked again"), + ) + assert again["replayed"] is True and agent.calls == 1 + assert again["fallback"] == first["fallback"] + assert again["path"] == "agent_fallback" and again["outcome"] == "VERIFIED" + # The stored run record is exactly the reply, so the strict readback + # does not fail on a reply/record mismatch. + from openadapt_flow.request_binding import BindingError + + wrapped = WrappedTask( + cache=task.setup.cache, + agent=dc._NoAgent(), + instruction=PROMPT, + parameters=("value",), + runs_dir=task.runs, + ) + try: + wrapped.verify_reply("r1", {"value": "one"}, first) + except BindingError as exc: + assert str(exc) != "terminal_result_mismatch" + + +@pytest.mark.parametrize("parent", ["p" * 128, "tenant/a:b c", ".hidden"]) +def test_any_valid_parent_id_gets_a_fallback( + task, + monkeypatch, + run1, + parent, +) -> None: + install_reply(task.model, monkeypatch) + result = dc.run( + run_args(task, parent, "one", *FALLBACK), agent=Agent(), gate=lambda r: True + ) + child = result["fallback"]["request_id"] + assert result["verified"] and child == dc.child_request_id(parent) + assert len(child) <= 128 and child.replace("-", "").isalnum() + assert result["fallback"]["parent_request_id"] == parent + + +def test_release_of_a_reconciliation_reply_needs_the_acknowledgement( + task, monkeypatch +) -> None: + """The hold's phase is ``halted``, but its reply says a write may exist.""" + install_reply(task.model, monkeypatch, status="RECONCILIATION_REQUIRED") + assert dc.run(run_args(task, "r1", "one"))["status"] == "RECONCILIATION_REQUIRED" + assert json.loads(task.model.stop.read_text())["phase"] == "halted" + monkeypatch.setattr(compile_cli, "_interactive", lambda: True) + args = parse("release", "task.json", "--person", "dana") + assert dc.release(args, ask=lambda _: "release")["reason"] == "RECONCILE_FIRST" + assert task.model.stop.exists() + args = parse("release", "task.json", "--person", "dana", "--after-reconciling") + done = dc.release(args, ask=lambda _: "release") + assert done["released"] + by = json.loads(Path(done["archived"]).with_suffix(".by.json").read_text()) + assert by["after_reconciling"] is True + + +def test_release_refuses_while_the_fallback_runs( + task, + monkeypatch, + run1, +) -> None: + install_reply(task.model, monkeypatch) + monkeypatch.setattr(compile_cli, "_interactive", lambda: True) + tried: list = [] + + def gate(request) -> bool: + args = parse("release", "task.json", "--person", "dana", "--after-reconciling") + tried.append(dc.release(args, ask=lambda _: "release")) + return True + + result = dc.run(run_args(task, "r1", "one", *FALLBACK), agent=Agent(), gate=gate) + assert tried[0]["released"] is False and tried[0]["reason"] == "FALLBACK_RUNNING" + assert result["verified"] + assert task.model.stop.exists() # the hold was not released either + + +def test_release_after_a_crashed_fallback(task, monkeypatch, run1) -> None: + install_reply(task.model, monkeypatch) + crashed = dc.run( + run_args(task, "r1", "one", *FALLBACK), + agent=Agent(raises=True), + gate=lambda r: True, + ) + assert crashed["status"] == "RECONCILIATION_REQUIRED" + shown = dc.status(parse("status", "task.json")) + assert shown["fallback"]["in_flight_owner"] == "ended" + monkeypatch.setattr(compile_cli, "_interactive", lambda: True) + args = parse("release", "task.json", "--person", "dana") + assert dc.release(args, ask=lambda _: "release")["reason"] == "RECONCILE_FIRST" + args = parse("release", "task.json", "--person", "dana", "--after-reconciling") + done = dc.release(args, ask=lambda _: "release") + assert done["released"] and done["fallback_cleared"] + assert done["fallback_request_id"] == dc.child_request_id("r1") diff --git a/packages/flow/tests/test_wrap_fallback.py b/packages/flow/tests/test_wrap_fallback.py index abd7131c6c..22bafe898a 100644 --- a/packages/flow/tests/test_wrap_fallback.py +++ b/packages/flow/tests/test_wrap_fallback.py @@ -87,11 +87,13 @@ def build_model(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> SimpleNamesp jit = SimpleNamespace(admitted=True, bundle_dir=bundle, runs_dir=directory / "runs") jit.runs_dir.mkdir() rows: list[dict[str, str]] = [] + reads = SimpleNamespace(fail=False) class Observer: @property def system_of_record(self): - return copy.deepcopy(rows) + # None is what an unreachable system of record reads as. + return None if reads.fail else copy.deepcopy(rows) compiler = SimpleNamespace( dir=directory, @@ -119,6 +121,7 @@ def system_of_record(self): compiler=compiler, jit=jit, rows=rows, + reads=reads, sent=[], digest=digest, tmp=tmp_path, @@ -163,12 +166,15 @@ def install_reply( *, write: Optional[dict[str, str]] = None, report: Optional[str] = None, + fail_read_after: bool = False, **reply: Any, ) -> None: async def hit(_python, _server, params): model.sent.append(dict(params)) if write is not None: model.rows.append(dict(write)) + if fail_read_after: + model.reads.fail = True return { "status": "HALTED", "verified": False, @@ -188,22 +194,40 @@ class FakeRun1: made: list["FakeRun1"] = [] - def __init__(self, prompt: str, *, rows: list, spend: Any = None, **kw: Any): + def __init__( + self, + prompt: str, + *, + rows: list, + spend: Any = None, + after: Any = None, + **kw: Any, + ): self.kw = kw self.rows = rows self.spend = spend + #: Called after run 1 ends, before the policy's final read. + self.after = after + self.fail_reads = False self._baseline: Optional[list] = None self.observer = SimpleNamespace() type(self).made.append(self) @property - def system_of_record(self) -> list: - return copy.deepcopy(self.rows) + def system_of_record(self) -> Optional[list]: + return None if self.fail_reads else copy.deepcopy(self.rows) def _secret_params(self) -> frozenset: return frozenset() def record(self, agent: Any, params: dict, *, hold: Any) -> Any: + try: + return self._record(agent, params, hold=hold) + finally: + if self.after is not None: + self.after(self) + + def _record(self, agent: Any, params: dict, *, hold: Any) -> Any: self._baseline = copy.deepcopy(self.rows) agent.calls += 1 agent.seen_cap = getattr(agent, "max_cost_usd", None) @@ -211,8 +235,11 @@ def record(self, agent: Any, params: dict, *, hold: Any) -> Any: agent.last_ledger = self.spend if agent.raises: raise RuntimeError("the agent crashed after its save") + shot = Path(self.kw["cache_dir"]) / "gate-01.png" + shot.parent.mkdir(parents=True, exist_ok=True) + shot.write_bytes(b"\x89PNG\r\n\x1a\nsynthetic gate frame") request = compile_agent.GateRequest( - control="Save", identity=("Synthetic record",), url="", screenshot=None + control="Save", identity=("Synthetic record",), url="", screenshot=shot ) approved = hold(request) gates = [{"decision": "approved_by_hold" if approved else "refused_by_hold"}] @@ -248,11 +275,13 @@ def __init__(self, *, model_free: bool = True, cap: Any = None, raises=False): @pytest.fixture def run1(model, monkeypatch) -> SimpleNamespace: - state = SimpleNamespace(spend=None) + state = SimpleNamespace(spend=None, after=None) FakeRun1.made = [] def factory(prompt: str, **kw: Any) -> FakeRun1: - made = FakeRun1(prompt, rows=model.rows, spend=state.spend, **kw) + made = FakeRun1( + prompt, rows=model.rows, spend=state.spend, after=state.after, **kw + ) made.observer = made # observer.system_of_record reads the same rows return made @@ -550,3 +579,179 @@ def test_eligibility_agrees_with_open_repair(model, monkeypatch, report) -> None except RepairError: opened = False assert found.eligible is opened is (report is None), (report, found.reason) + + +# -- review fixes: unreadable reads, the final read, the miss, the marker ------ + + +def test_an_unreadable_read_after_the_halt_never_falls_back( + model, monkeypatch, run1 +) -> None: + """An unreachable system of record also reports zero changes: that is not + "nothing written".""" + install_reply(model, monkeypatch, fail_read_after=True) + agent = Agent() + chosen = policy(model) + result = chosen.run(PROMPT, PARAMS, agent) + assert result.status == "HALTED" and result.path == "skill" + assert result.record_check["readable"] is False + assert agent.calls == 0 and FakeRun1.made == [] + assert chosen.last == {"fallback": False, "reason": "record_changed_or_unproved"} + assert not (model.tmp / "cache" / "fallback" / "task" / fb._HALT).exists() + + +def test_halt_evidence_without_a_readable_flag_proves_nothing( + model, monkeypatch, run1 +) -> None: + install_reply(model, monkeypatch) + assert model.cache.run(PROMPT, PARAMS, Agent()).status == "HALTED" + found = fb.proved_before_effect(model.cache, PROMPT, PARAMS) + root = model.tmp / "cache" / "fallback" / "task" + root.mkdir(parents=True) + zeros = {"created": 0, "changed": 0, "removed": 0, "passed": False} + (root / fb._HALT).write_text( + json.dumps( + { + "run_dir": str(found.run_dir), + "bundle_digest": found.bundle_digest, + "record_check": zeros, + } + ) + ) + agent = Agent() + result = policy(model).run(PROMPT, {"value": "two"}, agent) + assert result.status == "CACHE_HALTED" and agent.calls == 0 + + +@pytest.mark.parametrize("decision", ["refused", "approved"]) +def test_an_unreadable_final_read_keeps_the_marker( + model, monkeypatch, run1, decision +) -> None: + install_reply(model, monkeypatch) + + def unreadable(made: FakeRun1) -> None: + made.fail_reads = True + + run1.after = unreadable + chosen = policy(model, gate=lambda request: decision == "approved") + result = chosen.run(PROMPT, PARAMS, Agent()) + assert result.status == "RECONCILIATION_REQUIRED" and not result.verified + assert chosen.last["task_record_check"]["readable"] is False + assert chosen.last["repair"] is None + root = model.tmp / "cache" / "fallback" / "task" + assert (root / fb._ACTIVE).exists() + agent = Agent() + again = policy(model).run(PROMPT, {"value": "two"}, agent) + assert again.status == "RECONCILIATION_REQUIRED" and agent.calls == 0 + + +@pytest.mark.parametrize( + "late", + [ + {"id": "f2", "kind": "synthetic", "value": "one"}, # a duplicate + None, # the saved record changed after run 1's check + ], +) +def test_the_final_read_must_confirm_the_save(model, monkeypatch, run1, late) -> None: + install_reply(model, monkeypatch) + + def after(made: FakeRun1) -> None: + if late is not None: + made.rows.append(dict(late)) + else: + made.rows[-1]["value"] = "changed" + + run1.after = after + chosen = policy(model) + result = chosen.run(PROMPT, PARAMS, Agent()) + assert result.status == "RECONCILIATION_REQUIRED" and not result.verified + # Both readings are kept: run 1's check passed, the final read didn't. + assert result.record_check["passed"] is True + assert chosen.last["task_record_check"]["passed"] is False + assert chosen.last["run_status"] == "VERIFIED" + assert chosen.last["readings_agree"] is False + assert chosen.last["repair"] is None + assert (model.tmp / "cache" / "fallback" / "task" / fb._ACTIVE).exists() + saved = json.loads( + ( + model.tmp + / "cache" + / "fallback" + / "task" + / chosen.last["request_id"] + / fb._RESULT + ).read_text() + ) + assert saved["status"] == "RECONCILIATION_REQUIRED" and saved["verified"] is False + + +def test_a_miss_at_dispatch_never_starts_the_agent(model, monkeypatch, run1) -> None: + """The program was evicted between the caller's check and the call: the + policy reports the miss; the cache's first run (fixture: pytest.fail) and + the agent are never reached.""" + monkeypatch.setattr(model.cache, "_server", lambda *_: None) + agent = Agent() + result = policy(model).run(PROMPT, PARAMS, agent) + assert result.status == "NO_ADMITTED_PROGRAM" and not result.verified + assert agent.calls == 0 and model.sent == [] + built = policy( + model, agent_factory=lambda: pytest.fail("agent built on a miss") + ).run(PROMPT, PARAMS, None) + assert built.status == "NO_ADMITTED_PROGRAM" + + +def test_the_agent_is_built_only_for_an_eligible_halt(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch, report="reconciliation") + result = policy( + model, agent_factory=lambda: pytest.fail("agent built for a held halt") + ).run(PROMPT, PARAMS, None) + assert result.status == "HALTED" + model.stop.unlink() + install_reply(model, monkeypatch) + built: list = [] + result = policy( + model, agent_factory=lambda: built.append(Agent()) or built[-1] + ).run(PROMPT, PARAMS, None) + assert result.verified and len(built) == 1 and built[0].calls == 1 + + +def test_an_unattended_gate_never_builds_the_agent(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + gate = TerminalGate(ask=lambda _: pytest.fail("asked"), attended=lambda: False) + result = policy( + model, gate=gate, agent_factory=lambda: pytest.fail("agent built") + ).run(PROMPT, PARAMS, None) + assert result.status == "FALLBACK_GATE_UNATTENDED" + + +def test_a_worker_never_clears_a_marker_it_no_longer_owns( + model, monkeypatch, run1 +) -> None: + install_reply(model, monkeypatch) + root = model.tmp / "cache" / "fallback" / "task" + + def swapped(request) -> bool: + # Someone replaced this run's marker with a later dispatch's. + (root / fb._ACTIVE).write_text( + json.dumps({"request_id": "later", "nonce": "n", "pid": 1, "host": "h"}) + ) + return True + + result = policy(model, gate=swapped).run(PROMPT, PARAMS, Agent()) + assert result.verified + assert json.loads((root / fb._ACTIVE).read_text())["request_id"] == "later" + + +def test_release_never_drops_a_live_fallbacks_marker(model, monkeypatch, run1) -> None: + install_reply(model, monkeypatch) + seen: list = [] + + def gate(request) -> bool: + # A person runs release while this fallback waits at its gate. + seen.append(fb.release_in_flight(model.cache, PROMPT, PARAMS)) + return True + + result = policy(model, gate=gate).run(PROMPT, PARAMS, Agent()) + assert seen[0]["cleared"] is False and seen[0]["owner"] == "running" + assert result.verified + assert not (model.tmp / "cache" / "fallback" / "task" / fb._ACTIVE).exists() From 894da8e5b61e55dc98131c1c90ddcd2f58c53b74 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:28:09 -0500 Subject: [PATCH 3/9] docs(flow): describe the fallback's final read, item-approval gate and release rules Adds wrap-dispatch to both FLOW_NAMES copies as run --dispatch, narrows the CAPABILITIES row to experimental with the evidence it has, and lists what is still open. The rerun MockMed benchmark matched the committed results, so results.json is unchanged. --- CAPABILITIES.md | 4 +- llms-full.txt | 4 +- openadapt/cli_tasks.py | 1 + packages/flow/docs/WRAP_FALLBACK.md | 117 +++++++++++++++--- .../wrap-dispatch.md | 2 +- packages/flow/openadapt_flow/cli_tasks.py | 1 + .../flow/tests/test_wrap_approval_gate.py | 44 ++++--- 7 files changed, 131 insertions(+), 42 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 0d7dd5a8b8..ff4a12a130 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -304,7 +304,7 @@ improvising or retrying when something is off. | A duplicate check that asks the system of record (generic FHIR R4 `Patient` search; OpenEMR REST and SQL adapters): every page read, stop on an exact match, send a close match to a person, proceed otherwise, fail closed on any read problem. Close matching is heuristic and misses some duplicates; it is not patient identity resolution. One source for qualification, runs and resume; a program can pin it | On main | Synthetic: unit and HTTP tests; live OpenEMR 8.0.0.3 search decided 6 of 6 known referrals right through FHIR | [DUPLICATE_CHECK.md](packages/flow/docs/DUPLICATE_CHECK.md) | | A switched-off `problems_only` gate asks a person before the save instead of stopping the item | Released | Synthetic; real app in [#1513](https://github.com/OpenAdaptAI/OpenAdapt/pull/1513) | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md#when-the-mode-turns-itself-off) | | Fleet drift patches: a verified fix with no patient data, shared across sites under policy, moved as files or through a local reference hub | Released, local reference hub | Simulator | `openadapt-flow fleet`, [FLEET_DRIFT_PATCHES.md](packages/flow/docs/FLEET_DRIFT_PATCHES.md) | -| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check that found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED` or a receipt that is not `VERIFIED`. The agent runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate and its own spend cap; its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs the admitted program first and exposes the hold (`status`, `release`, `evict`) | On main | Synthetic: unit tests on the real cache, hold and report checks; MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](packages/flow/benchmark/wrap_fallback/README.md)) | `openadapt-flow wrap-dispatch`, `openadapt_flow.wrap.fallback`, [WRAP_FALLBACK.md](packages/flow/docs/WRAP_FALLBACK.md) | +| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check whose reads both succeeded and found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED`, an unreadable system of record or a receipt that is not `VERIFIED`. The agent is built only once a fallback may start and runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate (the terminal, or a signed item approval from Desktop's Run it or a paired phone) and its own spend cap. A fallback is `VERIFIED` only when the final task-scoped read confirms the save; otherwise it is `RECONCILIATION_REQUIRED` with both readings kept. Its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs only the admitted program (a miss runs nothing), stores the whole result with the request, and exposes the hold (`status`, `release`, `evict`); release refuses a fallback that is still running | Experimental, this PR | Synthetic: unit tests on the real cache, hold, report and item-approval checks (answers signed with a test approver key on a real roster); MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](packages/flow/benchmark/wrap_fallback/README.md)). No real model agent has run it | `openadapt-flow wrap-dispatch` (`--fallback-gate item-approval`), `openadapt_flow.wrap.fallback`, `openadapt_flow.wrap.approval_gate`, [WRAP_FALLBACK.md](packages/flow/docs/WRAP_FALLBACK.md) | ## Computer-use agents @@ -449,7 +449,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. -- `wrap-dispatch`: Run a wrapped task's admitted program. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate; `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). +- `wrap-dispatch`: Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from Desktop or a phone); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). **Proof:** diff --git a/llms-full.txt b/llms-full.txt index 75ffadf60c..aef23013f3 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -744,7 +744,7 @@ improvising or retrying when something is off. | A duplicate check that asks the system of record (generic FHIR R4 `Patient` search; OpenEMR REST and SQL adapters): every page read, stop on an exact match, send a close match to a person, proceed otherwise, fail closed on any read problem. Close matching is heuristic and misses some duplicates; it is not patient identity resolution. One source for qualification, runs and resume; a program can pin it | On main | Synthetic: unit and HTTP tests; live OpenEMR 8.0.0.3 search decided 6 of 6 known referrals right through FHIR | [DUPLICATE_CHECK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/DUPLICATE_CHECK.md) | | A switched-off `problems_only` gate asks a person before the save instead of stopping the item | Released | Synthetic; real app in [#1513](https://github.com/OpenAdaptAI/OpenAdapt/pull/1513) | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md#when-the-mode-turns-itself-off) | | Fleet drift patches: a verified fix with no patient data, shared across sites under policy, moved as files or through a local reference hub | Released, local reference hub | Simulator | `openadapt-flow fleet`, [FLEET_DRIFT_PATCHES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FLEET_DRIFT_PATCHES.md) | -| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check that found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED` or a receipt that is not `VERIFIED`. The agent runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate and its own spend cap; its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs the admitted program first and exposes the hold (`status`, `release`, `evict`) | On main | Synthetic: unit tests on the real cache, hold and report checks; MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/wrap_fallback/README.md)) | `openadapt-flow wrap-dispatch`, `openadapt_flow.wrap.fallback`, [WRAP_FALLBACK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_FALLBACK.md) | +| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check whose reads both succeeded and found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED`, an unreadable system of record or a receipt that is not `VERIFIED`. The agent is built only once a fallback may start and runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate (the terminal, or a signed item approval from Desktop's Run it or a paired phone) and its own spend cap. A fallback is `VERIFIED` only when the final task-scoped read confirms the save; otherwise it is `RECONCILIATION_REQUIRED` with both readings kept. Its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs only the admitted program (a miss runs nothing), stores the whole result with the request, and exposes the hold (`status`, `release`, `evict`); release refuses a fallback that is still running | Experimental, this PR | Synthetic: unit tests on the real cache, hold, report and item-approval checks (answers signed with a test approver key on a real roster); MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/wrap_fallback/README.md)). No real model agent has run it | `openadapt-flow wrap-dispatch` (`--fallback-gate item-approval`), `openadapt_flow.wrap.fallback`, `openadapt_flow.wrap.approval_gate`, [WRAP_FALLBACK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_FALLBACK.md) | ## Computer-use agents @@ -889,7 +889,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. -- `wrap-dispatch`: Run a wrapped task's admitted program. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate; `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). +- `wrap-dispatch`: Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from Desktop or a phone); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). **Proof:** diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 86eb1bc08b..78a9770be8 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -118,6 +118,7 @@ "variants": "compile --variants", "verify-run": "verify effect", "visualize": "inspect visualize", + "wrap-dispatch": "run --dispatch", } diff --git a/packages/flow/docs/WRAP_FALLBACK.md b/packages/flow/docs/WRAP_FALLBACK.md index e4bdccb9a0..bb155c79a1 100644 --- a/packages/flow/docs/WRAP_FALLBACK.md +++ b/packages/flow/docs/WRAP_FALLBACK.md @@ -18,13 +18,32 @@ openadapt-flow wrap-dispatch --task task.json --request-id r-118 \ In Python, wrap the task's `SkillCache`: +With no terminal (a service), a person approves each save from Desktop's Run +it or a paired phone instead: + +```bash +openadapt-flow wrap-dispatch --task task.json --request-id r-118 \ + --param note="Synthetic follow-up" \ + --fallback agent --fallback-max-cost-usd 0.50 \ + --fallback-gate item-approval --fallback-approvals-dir ~/.openadapt/runs +``` + +In Python, wrap the task's `SkillCache`: + ```python from openadapt_flow.wrap.fallback import FallbackPolicy -policy = FallbackPolicy(cache, max_cost_usd=0.50) # gate: the terminal confirm -run = policy.run(prompt, params, agent) +policy = FallbackPolicy( + cache, max_cost_usd=0.50, agent_factory=make_agent +) # gate: the terminal confirm +run = policy.run(prompt, params, None) ``` +`agent_factory` is called only once a fallback may start; without it the +policy uses the agent `run` is given. Either way, `run` only replays the +admitted program: with none it returns `NO_ADMITTED_PROGRAM` and starts +nothing. + ## When the agent gets the task All of these must hold. Each is read from files on disk, not from the reply's @@ -39,10 +58,12 @@ status text: `steps_requiring_reconciliation` (from `openadapt_flow.transaction`) lists no step. - The halted reply recorded exactly zero model calls. -- The cache's own record check of the halted run found no new, changed or - removed record of the task's record. The policy keeps that check beside the - halt, so a later call that finds the task held can fall back on the same - halt. +- The cache's own record check of the halted run read the system of record + both before and after (`readable: true`) and found no new, changed or + removed record of the task's record. An unreadable store also reports zero + changes, so it never counts as "nothing written". The policy keeps that + check beside the halt, so a later call that finds the task held can fall + back on the same halt. It never falls back on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED`, `RECEIPT_NOT_VERIFIED`, `MODEL_CALLS_NOT_ZERO`, a @@ -62,8 +83,9 @@ directory beside the task's cache (`/fallback///`): - the right-record check before every save; - a pre-commit gate before every save. The default `TerminalGate` is compile-agent's terminal confirmation; with no terminal it refuses, and the - agent is not started (`FALLBACK_GATE_UNATTENDED`). Any object with - `__call__(request) -> bool` can be the gate; + agent is not started (`FALLBACK_GATE_UNATTENDED`). `ItemApprovalGate` + (below) needs no terminal. Any object with `__call__(request) -> bool` can + be the gate; - the app's origin fence; - a read-back of every save from the system of record, and the record check of run 1; @@ -72,7 +94,20 @@ directory beside the task's cache (`/fallback///`): refuses a save when the spend so far is over the cap or unknown. An agent with model calls and no settable cap is not started (`FALLBACK_COST_UNBOUNDED`); -- its own request ID (default `.fallback`), which runs once. +- its own request ID, which runs once. `wrap-dispatch` derives it from the + dispatch request ID by digest (`fallback-` and 40 hex characters), so any + valid request ID (up to 128 characters, any characters) works, and records + the dispatch request ID as `parent_request_id`. + +A fallback is `VERIFIED` only when run 1's record check passed, every gate +was approved by the person, and a final task-scoped read (the baseline taken +as the run started against a fresh read after it) confirms exactly one new +record of the task's record with its values and nothing else changed on it. +When the final read disagrees (a duplicate, a changed or removed record, an +unreadable store), or a stopped run can't show it wrote nothing, the status is +`RECONCILIATION_REQUIRED`: no repair is opened, the in-flight marker stays, +and `fallback.run_status` keeps what the run itself reported, beside both +readings (`record_check` and `fallback.task_record_check`). The run's draft program is never confirmed or admitted. A verified fallback leaves the task held and opens a repair candidate with @@ -82,10 +117,41 @@ person demonstrates and approves the repair, and `SkillCache.complete_repair` runs its canaries and selects it. Nothing in the fallback path does either step. -A fallback that raises, or ends without proving what it wrote, leaves an -in-flight marker. Every later fallback of the task then returns -`RECONCILIATION_REQUIRED` until a person checks the record and runs -`wrap-dispatch release TASK --person NAME --after-reconciling`. +While a fallback may save, an in-flight marker names it: its request ID, a +nonce, its process ID and host. A fallback that raises, or ends without +proving what it wrote, leaves the marker, marked `ended`. Every later +fallback of the task then returns `RECONCILIATION_REQUIRED` until a person +checks the record and runs +`wrap-dispatch release TASK --person NAME --after-reconciling`. A run removes +the marker only while it is still its own. + +## The gate without a terminal + +`--fallback-gate item-approval` (`openadapt_flow.wrap.approval_gate.ItemApprovalGate`) +asks through the item-approval store that `each_item` runs and the agent +guard use. Before each save, the fallback run writes +`item-approval/request-.json` with the gate screenshot under +`--fallback-approvals-dir//` (default: the fallback +run's directory), and waits up to `--fallback-approval-wait-s` (default 60). +A person answers in Desktop's Run it (`openadapt-flow item-approval approve`) +or on a paired phone through the decision portal, when that runs root is one +they scan. + +The save goes through only for an answer decided by a person, signed by an +approver key on the pinned approver roster, for that exact request, before +it expired, and not by the agent that asked. A decline, no answer in time, an +answer after expiry, an unsigned answer, a key off the roster and a missing +screenshot all refuse the save. The pin is `--fallback-approver-root`, +`OPENADAPT_APPROVER_ROOT`, or the `approvers` section of +`--fallback-approvers-config` (then the only pin counted). With no pin whose +roster verifies, no person's answer could count, so the agent is not started +(`FALLBACK_GATE_UNATTENDED`). + +The agent's own run deadline keeps running while it waits at the gate: a +provider agent's run is at most 120 seconds (`--max-run-seconds`), so the +wait must be shorter than that, and the person has less time than the wait +when the agent is slow to reach the save. Whatever happens at the deadline, +the final read decides the outcome as above. ## The dispatcher @@ -94,7 +160,7 @@ in-flight marker. Every later fallback of the task then returns | Situation | Result `path` | `status` | | --- | --- | --- | | The program ran | `program` | its status (`VERIFIED`, `HALTED` ...) | -| No admitted program | `held` | `NO_ADMITTED_PROGRAM` (nothing runs; `openadapt wrap` makes the first run) | +| No admitted program, including one evicted after a `status` check | `held` | `NO_ADMITTED_PROGRAM` (nothing runs; `openadapt wrap` makes the first run) | | The task is held, no fallback | `held` | `CACHE_HALTED` | | The fallback ran or was refused | `agent_fallback` | `VERIFIED`, `GATE_REFUSED`, `COST_CAP_EXCEEDED` ... | @@ -104,8 +170,9 @@ Each run prints one JSON object with `openadapt wrap`'s per-run fields `receipt_outcome`, `receipt_binding`), with `path` as in the table, plus `outcome` (`VERIFIED`, `ESCALATED`, `CAUGHT_ERROR` or `FAILED`) and `fallback` (what the policy did, or null). `--result FILE` also writes it to -a file. Requests go through the same run store as `openadapt wrap`, so a -retried request ID returns its first result. +a file. Requests go through the same run store as `openadapt wrap`, and the +stored result is this whole object, `NO_ADMITTED_PROGRAM` included: a retried +request ID returns its first result, `fallback` and all, and runs nothing. The hold verbs: @@ -114,8 +181,13 @@ The hold verbs: the task's fallback runs. - `wrap-dispatch release TASK --person NAME`: a person at a terminal types `release`. The hold file is archived next to a record of who released it. - A hold that may have written (`running`, unreadable) or a stuck fallback - needs `--after-reconciling`. + Without `--after-reconciling`, only a hold whose own evidence proves + nothing was written is released: a halt that may fall back (the checks + above, without the record check), or a hold whose program never ran. Any + other hold (a `RECONCILIATION_REQUIRED` reply, a write, `running`, + unreadable) and an unfinished fallback need `--after-reconciling`. A + fallback that is still running, or whose owner is on another host or + can't be identified, is never released (`FALLBACK_RUNNING`). - `wrap-dispatch evict TASK`: sets the program aside as evidence; the next `openadapt wrap` run compiles afresh. @@ -125,8 +197,13 @@ The hold verbs: [#2406](https://github.com/OpenAdaptAI/OpenAdapt/pull/2406) under mcp 1.30.0. The end-to-end test runs the program in-process until then. - `openadapt wrap run` does not dispatch through this policy yet (#2407). -- The gate is the terminal confirmation. The guard approval card and the - flight gate are the next gates. +- A program hold left `running` by a live program replay is not told apart + from a lost reply; release with `--after-reconciling` can archive it while + that replay still runs. +- The item-approval gate's request shows the gate screenshot and the + control; it does not list the field values being saved (no `fields`). +- No real model agent has run the fallback; the benchmark's agent is + scripted. - Fallback runs have no receipt of their own (#2394); the evidence is the harness's gate log, read-backs and record check. diff --git a/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md b/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md index a26a48dd35..13d92b8929 100644 --- a/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md +++ b/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md @@ -1 +1 @@ -Run a wrapped task's admitted program. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate; `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). +Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from Desktop or a phone); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index cb075b91ae..5160df3108 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -117,6 +117,7 @@ "variants": "compile --variants", "verify-run": "verify effect", "visualize": "inspect visualize", + "wrap-dispatch": "run --dispatch", } diff --git a/packages/flow/tests/test_wrap_approval_gate.py b/packages/flow/tests/test_wrap_approval_gate.py index 019b2dbeab..10d004abf1 100644 --- a/packages/flow/tests/test_wrap_approval_gate.py +++ b/packages/flow/tests/test_wrap_approval_gate.py @@ -238,30 +238,40 @@ def test_no_pinned_root_means_nobody_can_answer( def test_a_service_fallback_saves_after_a_phone_approval( - model, - monkeypatch, - run1, - approver, - tmp_path, + model, monkeypatch, run1, approver, tmp_path ) -> None: + """The real decision portal finds the request under the runs root it + scans and records the phone's tap; the waiting gate lets the save go.""" + from openadapt_flow.console import save_approvals + install_reply(model, monkeypatch) - gate = ItemApprovalGate(wait_s=5, approvals_dir=tmp_path / "approvals") - real_bind = gate.bind + approvals = tmp_path / "approvals" + gate = ItemApprovalGate(wait_s=5, approvals_dir=approvals) + tapped: list = [] - def bind(run_root: Path, request_id: str) -> None: - real_bind(run_root, request_id) - answering(gate, person(route=DECISION_PORTAL_ROUTE, signer=portal_signer())) + def phone(_seconds: float) -> None: + if tapped: + return + [row] = save_approvals.list_save_approvals(approvals) + detail = save_approvals.save_approval_detail(approvals, row.request_id) + payload = save_approvals.SaveApprovalActionRequest( + action="verify_and_resume", + task_digest=detail["task_digest"], + task_signature=detail["task"]["signature"], + ) + tapped.append( + save_approvals.decide_save_approval(approvals, row.request_id, payload) + ) - gate.bind = bind # type: ignore[method-assign] + gate._sleep = phone chosen = policy(model, gate=gate) result = chosen.run(PROMPT, PARAMS, Agent()) - assert result.verified and result.status == "VERIFIED" + assert result.verified and result.status == "VERIFIED" and len(tapped) == 1 assert model.rows == [{"id": "f1", "kind": "synthetic", "value": "one"}] - # The approval folder sits where Desktop or the portal scans for it. - assert ( - tmp_path / "approvals" / chosen.last["request_id"] / "item-approval" - ).is_dir() - assert chosen.last["gate_answers"][0]["decision"] == "approved" + assert (approvals / chosen.last["request_id"] / "item-approval").is_dir() + [answer] = chosen.last["gate_answers"] + assert answer["decision"] == "approved" + assert answer["route"] == DECISION_PORTAL_ROUTE def test_a_service_fallback_with_no_pin_never_starts( From a7d5c31dce04eb2346d8bda8280eaeac49e7aaee Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:49:22 -0500 Subject: [PATCH 4/9] fix(flow): release and status use the fallback's own proof of a clean halt wrap-dispatch release and status now need the kept, readable record check for the halt, as the fallback does; the default dispatch keeps it too. A run whose own checks caught a wrong save keeps its status instead of becoming RECONCILIATION_REQUIRED. A gate bind or run-directory failure now leaves the marker ended rather than running. Adds dispatch-level tests of --fallback-gate item-approval with no injected gate, and narrows the docs: Desktop's Run it screen does not show these requests. --- CAPABILITIES.md | 4 +- llms-full.txt | 4 +- packages/flow/docs/WRAP_FALLBACK.md | 28 ++- .../wrap-dispatch.md | 2 +- .../flow/openadapt_flow/wrap/approval_gate.py | 12 +- .../flow/openadapt_flow/wrap/compiled_only.py | 24 ++- .../flow/openadapt_flow/wrap/dispatch_cli.py | 37 ++-- packages/flow/openadapt_flow/wrap/fallback.py | 127 +++++++----- packages/flow/tests/test_wrap_dispatch_cli.py | 182 +++++++++++++++++- packages/flow/tests/test_wrap_fallback.py | 49 ++++- 10 files changed, 375 insertions(+), 94 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index ff4a12a130..03c72a03d5 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -304,7 +304,7 @@ improvising or retrying when something is off. | A duplicate check that asks the system of record (generic FHIR R4 `Patient` search; OpenEMR REST and SQL adapters): every page read, stop on an exact match, send a close match to a person, proceed otherwise, fail closed on any read problem. Close matching is heuristic and misses some duplicates; it is not patient identity resolution. One source for qualification, runs and resume; a program can pin it | On main | Synthetic: unit and HTTP tests; live OpenEMR 8.0.0.3 search decided 6 of 6 known referrals right through FHIR | [DUPLICATE_CHECK.md](packages/flow/docs/DUPLICATE_CHECK.md) | | A switched-off `problems_only` gate asks a person before the save instead of stopping the item | Released | Synthetic; real app in [#1513](https://github.com/OpenAdaptAI/OpenAdapt/pull/1513) | [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md#when-the-mode-turns-itself-off) | | Fleet drift patches: a verified fix with no patient data, shared across sites under policy, moved as files or through a local reference hub | Released, local reference hub | Simulator | `openadapt-flow fleet`, [FLEET_DRIFT_PATCHES.md](packages/flow/docs/FLEET_DRIFT_PATCHES.md) | -| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check whose reads both succeeded and found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED`, an unreadable system of record or a receipt that is not `VERIFIED`. The agent is built only once a fallback may start and runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate (the terminal, or a signed item approval from Desktop's Run it or a paired phone) and its own spend cap. A fallback is `VERIFIED` only when the final task-scoped read confirms the save; otherwise it is `RECONCILIATION_REQUIRED` with both readings kept. Its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs only the admitted program (a miss runs nothing), stores the whole result with the request, and exposes the hold (`status`, `release`, `evict`); release refuses a fallback that is still running | Experimental, this PR | Synthetic: unit tests on the real cache, hold, report and item-approval checks (answers signed with a test approver key on a real roster); MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](packages/flow/benchmark/wrap_fallback/README.md)). No real model agent has run it | `openadapt-flow wrap-dispatch` (`--fallback-gate item-approval`), `openadapt_flow.wrap.fallback`, `openadapt_flow.wrap.approval_gate`, [WRAP_FALLBACK.md](packages/flow/docs/WRAP_FALLBACK.md) | +| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check whose reads both succeeded and found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED`, an unreadable system of record or a receipt that is not `VERIFIED`. The agent is built only once a fallback may start and runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate (the terminal, or a signed item approval from a paired phone or `openadapt-flow item-approval approve`) and its own spend cap. A fallback is `VERIFIED` only when the final task-scoped read confirms the save; otherwise it is `RECONCILIATION_REQUIRED` with both readings kept. Its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs only the admitted program (a miss runs nothing), stores the whole result with the request, and exposes the hold (`status`, `release`, `evict`); release refuses a fallback that is still running | Experimental, this PR | Synthetic: unit tests on the real cache, hold, report and item-approval checks (answers signed with a test approver key on a real roster, through the decision portal's functions and the `item-approval approve` command); MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](packages/flow/benchmark/wrap_fallback/README.md)). No real model agent has run it | `openadapt-flow wrap-dispatch` (`--fallback-gate item-approval`), `openadapt_flow.wrap.fallback`, `openadapt_flow.wrap.approval_gate`, [WRAP_FALLBACK.md](packages/flow/docs/WRAP_FALLBACK.md) | ## Computer-use agents @@ -449,7 +449,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. -- `wrap-dispatch`: Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from Desktop or a phone); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). +- `wrap-dispatch`: Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from a phone or `item-approval approve`); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). **Proof:** diff --git a/llms-full.txt b/llms-full.txt index aef23013f3..664e4f7d0c 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -744,7 +744,7 @@ improvising or retrying when something is off. | A duplicate check that asks the system of record (generic FHIR R4 `Patient` search; OpenEMR REST and SQL adapters): every page read, stop on an exact match, send a close match to a person, proceed otherwise, fail closed on any read problem. Close matching is heuristic and misses some duplicates; it is not patient identity resolution. One source for qualification, runs and resume; a program can pin it | On main | Synthetic: unit and HTTP tests; live OpenEMR 8.0.0.3 search decided 6 of 6 known referrals right through FHIR | [DUPLICATE_CHECK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/DUPLICATE_CHECK.md) | | A switched-off `problems_only` gate asks a person before the save instead of stopping the item | Released | Synthetic; real app in [#1513](https://github.com/OpenAdaptAI/OpenAdapt/pull/1513) | [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md#when-the-mode-turns-itself-off) | | Fleet drift patches: a verified fix with no patient data, shared across sites under policy, moved as files or through a local reference hub | Released, local reference hub | Simulator | `openadapt-flow fleet`, [FLEET_DRIFT_PATCHES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/FLEET_DRIFT_PATCHES.md) | -| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check whose reads both succeeded and found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED`, an unreadable system of record or a receipt that is not `VERIFIED`. The agent is built only once a fallback may start and runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate (the terminal, or a signed item approval from Desktop's Run it or a paired phone) and its own spend cap. A fallback is `VERIFIED` only when the final task-scoped read confirms the save; otherwise it is `RECONCILIATION_REQUIRED` with both readings kept. Its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs only the admitted program (a miss runs nothing), stores the whole result with the request, and exposes the hold (`status`, `release`, `evict`); release refuses a fallback that is still running | Experimental, this PR | Synthetic: unit tests on the real cache, hold, report and item-approval checks (answers signed with a test approver key on a real roster); MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/wrap_fallback/README.md)). No real model agent has run it | `openadapt-flow wrap-dispatch` (`--fallback-gate item-approval`), `openadapt_flow.wrap.fallback`, `openadapt_flow.wrap.approval_gate`, [WRAP_FALLBACK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_FALLBACK.md) | +| Opt-in fallback from a wrapped task's compiled program to the agent on drift: only when the hold is a terminal halt whose report is `HALTED_BEFORE_EFFECT` with no step needing reconciliation, bound to the admitted bundle, with zero replay model calls and a record check whose reads both succeeded and found no change. Never on `RECONCILIATION_REQUIRED`, a lost reply, `RECORD_CHECK_FAILED`, an unreadable system of record or a receipt that is not `VERIFIED`. The agent is built only once a fallback may start and runs through compile-agent's harness (right-record check, origin fence, read-back) with a person approving each save at a pre-commit gate (the terminal, or a signed item approval from a paired phone or `openadapt-flow item-approval approve`) and its own spend cap. A fallback is `VERIFIED` only when the final task-scoped read confirms the save; otherwise it is `RECONCILIATION_REQUIRED` with both readings kept. Its draft is never admitted, and a verified run opens a repair candidate for a person to approve. The default stays the hold. `openadapt-flow wrap-dispatch` runs only the admitted program (a miss runs nothing), stores the whole result with the request, and exposes the hold (`status`, `release`, `evict`); release refuses a fallback that is still running | Experimental, this PR | Synthetic: unit tests on the real cache, hold, report and item-approval checks (answers signed with a test approver key on a real roster, through the decision portal's functions and the `item-approval approve` command); MockMed in headless Chromium with a scripted fallback agent, program run in-process ([benchmark/wrap_fallback](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/benchmark/wrap_fallback/README.md)). No real model agent has run it | `openadapt-flow wrap-dispatch` (`--fallback-gate item-approval`), `openadapt_flow.wrap.fallback`, `openadapt_flow.wrap.approval_gate`, [WRAP_FALLBACK.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_FALLBACK.md) | ## Computer-use agents @@ -889,7 +889,7 @@ A test fails when a command has no file or this list is out of date. - `emit-mcp`: Write a standalone MCP `server.py` for one bundle. A pulled workflow is refused until `skill qualify` has passed, and the server refuses a run on any other app address. - `emit-skill`: Write an Agent Skills folder for one bundle. A pulled workflow is refused until `skill qualify` has passed. - `serve-execute`: With `--config DEPLOY_YAML`, a bundle recorded on Windows, macOS, Linux, RDP or Citrix runs through `openadapt-flow run --config`, under its admission's qualification authority. -- `wrap-dispatch`: Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from Desktop or a phone); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). +- `wrap-dispatch`: Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from a phone or `item-approval approve`); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). **Proof:** diff --git a/packages/flow/docs/WRAP_FALLBACK.md b/packages/flow/docs/WRAP_FALLBACK.md index bb155c79a1..3de41a72ce 100644 --- a/packages/flow/docs/WRAP_FALLBACK.md +++ b/packages/flow/docs/WRAP_FALLBACK.md @@ -18,14 +18,14 @@ openadapt-flow wrap-dispatch --task task.json --request-id r-118 \ In Python, wrap the task's `SkillCache`: -With no terminal (a service), a person approves each save from Desktop's Run -it or a paired phone instead: +With no terminal (a service), a person approves each save from a paired phone +or with `openadapt-flow item-approval approve` instead: ```bash openadapt-flow wrap-dispatch --task task.json --request-id r-118 \ --param note="Synthetic follow-up" \ --fallback agent --fallback-max-cost-usd 0.50 \ - --fallback-gate item-approval --fallback-approvals-dir ~/.openadapt/runs + --fallback-gate item-approval --fallback-approvals-dir PORTAL_RUNS_ROOT ``` In Python, wrap the task's `SkillCache`: @@ -133,9 +133,11 @@ guard use. Before each save, the fallback run writes `item-approval/request-.json` with the gate screenshot under `--fallback-approvals-dir//` (default: the fallback run's directory), and waits up to `--fallback-approval-wait-s` (default 60). -A person answers in Desktop's Run it (`openadapt-flow item-approval approve`) -or on a paired phone through the decision portal, when that runs root is one -they scan. +A person answers on a paired phone through the decision portal, when the +portal's runs root holds that folder, or with +`openadapt-flow item-approval approve` and their registered approver key. +Desktop's Run it screen lists only runs Desktop started, so it does not show +these requests yet. The save goes through only for an answer decided by a person, signed by an approver key on the pinned approver roster, for that exact request, before @@ -182,9 +184,10 @@ The hold verbs: - `wrap-dispatch release TASK --person NAME`: a person at a terminal types `release`. The hold file is archived next to a record of who released it. Without `--after-reconciling`, only a hold whose own evidence proves - nothing was written is released: a halt that may fall back (the checks - above, without the record check), or a hold whose program never ran. Any - other hold (a `RECONCILIATION_REQUIRED` reply, a write, `running`, + nothing was written is released: a halt that meets every check above, + including the kept record check (`wrap-dispatch` keeps it for a halt it + saw, with or without `--fallback agent`). Any other hold (a + `RECONCILIATION_REQUIRED` reply, a write, an unreadable read, `running`, unreadable) and an unfinished fallback need `--after-reconciling`. A fallback that is still running, or whose owner is on another host or can't be identified, is never released (`FALLBACK_RUNNING`). @@ -200,6 +203,13 @@ The hold verbs: - A program hold left `running` by a live program replay is not told apart from a lost reply; release with `--after-reconciling` can archive it while that replay still runs. +- A fallback marker whose owner is on another host, or that can't be read, + has no release command: a person checks the record and removes + `in-flight.json` by hand. +- The gate's wait is checked against `--max-run-seconds`, not against the + time the agent took to reach the save. An approval that arrives after the + agent's run deadline can still let the click through; the final read then + decides the outcome. - The item-approval gate's request shows the gate screenshot and the control; it does not list the field values being saved (no `fields`). - No real model agent has run the fallback; the benchmark's agent is diff --git a/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md b/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md index 13d92b8929..739d65da0a 100644 --- a/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md +++ b/packages/flow/docs/commands/06-give-agents-the-program/wrap-dispatch.md @@ -1 +1 @@ -Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from Desktop or a phone); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). +Run a wrapped task's admitted program only; a miss runs nothing. With `--fallback agent --fallback-max-cost-usd N`, a proved pre-effect drift goes to the agent behind a pre-commit gate (the terminal, or `--fallback-gate item-approval` for a signed approval from a phone or `item-approval approve`); `status`, `release` and `evict` manage the hold (docs/WRAP_FALLBACK.md). diff --git a/packages/flow/openadapt_flow/wrap/approval_gate.py b/packages/flow/openadapt_flow/wrap/approval_gate.py index c7c95c4ca5..1ae1f9ab7e 100644 --- a/packages/flow/openadapt_flow/wrap/approval_gate.py +++ b/packages/flow/openadapt_flow/wrap/approval_gate.py @@ -1,4 +1,4 @@ -"""A pre-commit gate a person answers from Desktop or a paired phone. +"""A pre-commit gate a person answers from a paired phone or the CLI. :class:`~openadapt_flow.wrap.fallback.TerminalGate` needs a person at the terminal, so a fallback started by a service (no TTY) never starts the @@ -6,8 +6,10 @@ ``each_item`` runs and the agent guard use (:mod:`openadapt_flow.approval_mode.item_approval`): before each save the fallback run writes ``item-approval/request-.json`` with the gate -screenshot, and waits. Desktop's Run it (``openadapt-flow item-approval -approve``) or the decision portal on a paired phone writes the answer. +screenshot, and waits. The decision portal on a paired phone (when its runs +root holds the approvals folder) or ``openadapt-flow item-approval approve`` +with the person's approver key writes the answer. Desktop's Run it screen +lists only runs Desktop started, so it does not show these requests. The gate lets the save through only for an answer that :func:`~openadapt_flow.approval_mode.item_approval.answer_refusal` accepts: @@ -68,8 +70,8 @@ class ItemApprovalGate: Args: approvals_dir: Where each fallback run's approval folder goes - (``//item-approval``), for a - Desktop or portal that scans that runs root. Default: inside the + (``//item-approval``), for + a decision portal that scans that runs root. Default: inside the fallback run's own directory. wait_s: How long to wait for each answer. The request expires then, so a later answer is refused. diff --git a/packages/flow/openadapt_flow/wrap/compiled_only.py b/packages/flow/openadapt_flow/wrap/compiled_only.py index 9d5fbe454e..894a946b8d 100644 --- a/packages/flow/openadapt_flow/wrap/compiled_only.py +++ b/packages/flow/openadapt_flow/wrap/compiled_only.py @@ -53,7 +53,9 @@ def compiled_only(cache: Any, prompt: str, params: Mapping[str, Any]) -> SkillRu class CompiledOnly: """A TaskCache for :class:`~openadapt_flow.wrap.WrappedTask` that only - replays. The agent ``WrappedTask`` passes is never used.""" + replays. The agent ``WrappedTask`` passes is never used. A halt it sees + keeps its record check as the fallback policy does, so ``wrap-dispatch + release`` can tell a proved clean halt from one that may have written.""" def __init__(self, cache: Any) -> None: self.cache = cache @@ -65,4 +67,22 @@ def key(self, prompt: str, params: Mapping[str, Any]) -> dict[str, Any]: return self.cache.key(prompt, params) def run(self, prompt: str, params: Mapping[str, Any], agent: Any) -> SkillRun: - return compiled_only(self.cache, prompt, params) + served = compiled_only(self.cache, prompt, params) + if ( + served.path == "skill" + and not served.verified + and served.status + not in ( + "CACHE_HALTED", + NO_ADMITTED_PROGRAM, + ) + ): + # Keep the halted run's record check beside its halt when it + # proves nothing was written, so release can rely on it. + from openadapt_flow.wrap.fallback import keep_halt_evidence + + try: + keep_halt_evidence(self.cache, prompt, params, served) + except OSError: + pass # No evidence kept: release then needs reconciling. + return served diff --git a/packages/flow/openadapt_flow/wrap/dispatch_cli.py b/packages/flow/openadapt_flow/wrap/dispatch_cli.py index dd3820173c..dffcc9faaf 100644 --- a/packages/flow/openadapt_flow/wrap/dispatch_cli.py +++ b/packages/flow/openadapt_flow/wrap/dispatch_cli.py @@ -186,14 +186,15 @@ def add_run_arguments(p: argparse.ArgumentParser) -> None: choices=("terminal", "item-approval"), default="terminal", help="Who approves each fallback save: a person at this terminal " - "(terminal, the default), or a person in Desktop's Run it or on a " - "paired phone, through a signed item approval (item-approval; no " - "terminal needed)", + "(terminal, the default), or a person on a paired phone or with " + "openadapt-flow item-approval approve, through a signed item " + "approval (item-approval; no terminal needed)", ) p.add_argument( "--fallback-approvals-dir", - help="With --fallback-gate item-approval: the runs root Desktop or the " - "decision portal scans (default: inside the fallback run's directory)", + help="With --fallback-gate item-approval: where each fallback's " + "approval folder goes, such as the runs root the decision portal " + "scans (default: inside the fallback run's directory)", ) p.add_argument( "--fallback-approval-wait-s", @@ -437,7 +438,7 @@ def _hold_file(setup: Any) -> Path: def status(args: argparse.Namespace) -> dict[str, Any]: from openadapt_flow.privacy import scrub_text - from openadapt_flow.wrap.fallback import fallback_runs, proved_before_effect + from openadapt_flow.wrap.fallback import fallback_runs, halt_evidence setup = _setup(args.task, args.key_dir) names = _names(setup) @@ -457,7 +458,7 @@ def status(args: argparse.Namespace) -> dict[str, Any]: } except (OSError, ValueError, AttributeError): hold = {"phase": "unreadable"} - found = proved_before_effect(cache, setup.instruction, names) + found = halt_evidence(cache, setup.instruction, names) return { "task_id": cache.task_id(setup.instruction, names), "held": cache.held(setup.instruction, names), @@ -471,25 +472,11 @@ def status(args: argparse.Namespace) -> dict[str, Any]: def _hold_is_proved_clean(setup: Any, names: Mapping[str, str]) -> bool: - """The hold's own evidence shows nothing was written: a halt the report - proves before effect, bound to the admitted bundle, or a hold whose - program never ran (no baseline, or no repair selection).""" - from openadapt_flow.wrap.fallback import proved_before_effect + """The hold's own evidence shows nothing was written: the same rule the + fallback uses (:func:`~openadapt_flow.wrap.fallback.halt_evidence`).""" + from openadapt_flow.wrap.fallback import halt_evidence - try: - stopped = json.loads(_hold_file(setup).read_text(encoding="utf-8")) - except (OSError, ValueError): - return False - if not isinstance(stopped, dict) or stopped.get("phase") != "halted": - return False - replay = stopped.get("replay") - if replay is None: - return stopped.get("reason") == "repair_selection_unavailable" - if not isinstance(replay, dict): - return False - if replay.get("status") == "BASELINE_UNAVAILABLE": - return replay.get("verified") is False - return proved_before_effect(setup.cache, setup.instruction, names).eligible + return halt_evidence(setup.cache, setup.instruction, names).eligible def release(args: argparse.Namespace, ask: Any = input) -> dict[str, Any]: diff --git a/packages/flow/openadapt_flow/wrap/fallback.py b/packages/flow/openadapt_flow/wrap/fallback.py index 94ee4e20fd..fa792ef006 100644 --- a/packages/flow/openadapt_flow/wrap/fallback.py +++ b/packages/flow/openadapt_flow/wrap/fallback.py @@ -61,6 +61,16 @@ ) _ACTIVE = fallback_marker.ACTIVE +#: Fallback statuses that already say a save went wrong (a check caught it): +#: kept as they are when the final read also shows a change. +_WROTE_WRONG = frozenset( + { + "GATE_NOT_PROVED", + "record_check_failed", + "readback_wrong_record", + "readback_refused", + } +) _HALT = "halt-evidence.json" _RESULT = "result.json" _REQUEST_CHARS = frozenset( @@ -241,6 +251,60 @@ def fallback_root(cache: Any, prompt: str, params: Mapping[str, Any]) -> Path: return task_dir.parent / "fallback" / task_dir.name +def keep_halt_evidence( + cache: Any, prompt: str, params: Mapping[str, Any], halted: SkillRun +) -> Eligibility: + """After a program run that just stopped: keep its record check beside + the halt when it proves nothing was written. Returns that halt's + eligibility (without the kept-evidence check of :func:`halt_evidence`).""" + + found = proved_before_effect(cache, prompt, params) + if not found.eligible: + return found + if not (_int_zero(halted.model_calls) and _nothing_written(halted.record_check)): + return Eligibility(False, "record_changed_or_unproved") + root = fallback_root(cache, prompt, params) + root.mkdir(parents=True, exist_ok=True) + _write( + root / _HALT, + { + "run_dir": str(found.run_dir), + "bundle_digest": found.bundle_digest, + "record_check": halted.record_check, + }, + ) + return found + + +def halt_evidence(cache: Any, prompt: str, params: Mapping[str, Any]) -> Eligibility: + """Whether the task's hold is proved to have written nothing. + + :func:`proved_before_effect`, plus the record check kept beside that + same halt (:func:`keep_halt_evidence`): both reads succeeded and found + no change to the task's record. A halt nobody kept a clean check for is + not proved. The fallback, ``wrap-dispatch status`` and ``release`` all + use this one rule. + """ + + found = proved_before_effect(cache, prompt, params) + if not found.eligible: + return found + try: + halt = json.loads( + (fallback_root(cache, prompt, params) / _HALT).read_text(encoding="utf-8") + ) + except (OSError, ValueError): + halt = None + if not ( + isinstance(halt, dict) + and halt.get("run_dir") == str(found.run_dir) + and halt.get("bundle_digest") == found.bundle_digest + and _nothing_written(halt.get("record_check")) + ): + return Eligibility(False, "no_record_check_for_halt") + return found + + class FallbackPolicy: """A TaskCache that may hand a proved pre-effect drift to the agent. @@ -313,38 +377,13 @@ def run(self, prompt: str, params: Mapping[str, Any], agent: Any) -> SkillRun: ): return first root = fallback_root(self.cache, prompt, params) - found = proved_before_effect(self.cache, prompt, params) + found = Eligibility(True, "") if first.status != "CACHE_HALTED": # The run that just halted: keep its record check with the halt, # so a later held call can rely on it too. - if ( - found.eligible - and _int_zero(first.model_calls) - and _nothing_written(first.record_check) - ): - root.mkdir(parents=True, exist_ok=True) - _write( - root / _HALT, - { - "run_dir": str(found.run_dir), - "bundle_digest": found.bundle_digest, - "record_check": first.record_check, - }, - ) - elif found.eligible: - found = Eligibility(False, "record_changed_or_unproved") + found = keep_halt_evidence(self.cache, prompt, params, first) if found.eligible: - try: - halt = json.loads((root / _HALT).read_text(encoding="utf-8")) - except (OSError, ValueError): - halt = None - if not ( - isinstance(halt, dict) - and halt.get("run_dir") == str(found.run_dir) - and halt.get("bundle_digest") == found.bundle_digest - and _nothing_written(halt.get("record_check")) - ): - found = Eligibility(False, "no_record_check_for_halt") + found = halt_evidence(self.cache, prompt, params) if not found.eligible: self.last = {"fallback": False, "reason": found.reason} return first @@ -419,21 +458,21 @@ def _fallback( ) run_root = root / request_id try: - run_root.mkdir() - except FileExistsError: - marker.clear() - return self._refused( - first, - "FALLBACK_REQUEST_REUSED", - "This fallback request id already ran.", - started, - request_id=request_id, - ) - bind = getattr(self.gate, "bind", None) - if callable(bind): - # A gate that keeps its own evidence learns which run it serves. - bind(run_root, request_id) - try: + try: + run_root.mkdir() + except FileExistsError: + marker.clear() + return self._refused( + first, + "FALLBACK_REQUEST_REUSED", + "This fallback request id already ran.", + started, + request_id=request_id, + ) + bind = getattr(self.gate, "bind", None) + if callable(bind): + # A gate that keeps its own evidence learns which run it serves. + bind(run_root, request_id) return self._run_agent( prompt, params, agent, first, marker, run_root, started ) @@ -558,7 +597,7 @@ def hold(request: GateRequest) -> bool: verified = False status = "RECONCILIATION_REQUIRED" detail = "The final read of the record does not confirm the save." - elif not verified and not unchanged and status != "GATE_NOT_PROVED": + elif not verified and not unchanged and status not in _WROTE_WRONG: status = "RECONCILIATION_REQUIRED" detail = "The final read of the record can't show that nothing was saved." repair = self._open_repair(prompt, params, run_root) if verified else None diff --git a/packages/flow/tests/test_wrap_dispatch_cli.py b/packages/flow/tests/test_wrap_dispatch_cli.py index 76ea91ad1f..88f8512129 100644 --- a/packages/flow/tests/test_wrap_dispatch_cli.py +++ b/packages/flow/tests/test_wrap_dispatch_cli.py @@ -283,10 +283,10 @@ def test_a_retry_replays_the_whole_dispatch_envelope( parameters=("value",), runs_dir=task.runs, ) - try: + with pytest.raises(BindingError) as raised: wrapped.verify_reply("r1", {"value": "one"}, first) - except BindingError as exc: - assert str(exc) != "terminal_result_mismatch" + # Past the reply/record and identity checks; a fallback has no receipt. + assert str(raised.value) == "receipt_unbound" @pytest.mark.parametrize("parent", ["p" * 128, "tenant/a:b c", ".hidden"]) @@ -361,3 +361,179 @@ def test_release_after_a_crashed_fallback(task, monkeypatch, run1) -> None: done = dc.release(args, ask=lambda _: "release") assert done["released"] and done["fallback_cleared"] assert done["fallback_request_id"] == dc.child_request_id("r1") + + +@pytest.mark.parametrize( + "reply", + [ + {"fail_read_after": True}, # the read after the halt failed + {"write": {"id": "1", "kind": "synthetic", "value": "one"}}, # it wrote + ], +) +def test_release_of_an_unproved_halt_needs_the_acknowledgement( + task, monkeypatch, reply +) -> None: + """The report says HALTED_BEFORE_EFFECT, but the record check does not + prove nothing was written: the same rule as the fallback's.""" + install_reply(task.model, monkeypatch, **reply) + assert dc.run(run_args(task, "r1", "one"))["status"] == "HALTED" + shown = dc.status(parse("status", "task.json")) + assert shown["fallback_eligible"] is False + monkeypatch.setattr(compile_cli, "_interactive", lambda: True) + args = parse("release", "task.json", "--person", "dana") + assert dc.release(args, ask=lambda _: "release")["reason"] == "RECONCILE_FIRST" + assert task.model.stop.exists() + + +# -- the item-approval gate through wrap-dispatch (no injected gate) ------------- + + +def _approve_with_cli(approvals: Path, key_path: Path, root: str) -> tuple: + """A person answers with openadapt-flow item-approval approve and their + approver key, from a thread, while the fallback waits at its gate.""" + import threading + import time + + from openadapt_flow.__main__ import main + + done: list = [] + + def answer() -> None: + deadline = time.monotonic() + 20 + while time.monotonic() < deadline and not done: + for request in approvals.glob("*/item-approval/request-*.json"): + data = json.loads(request.read_text()) + from openadapt_flow.approval_mode.item_approval import ( + ItemApprovalRequest, + ) + + asked = ItemApprovalRequest.model_validate(data) + done.append( + main( + [ + "item-approval", + "approve", + str(request.parent.parent), + "--request-id", + asked.request_id, + "--request-sha256", + asked.digest(), + "--decided-by", + "human", + "--route", + "desktop_run_it", + "--unauthenticated", + "--approver-key", + str(key_path), + "--approver-root", + root, + ] + ) + ) + return + time.sleep(0.05) + + thread = threading.Thread(target=answer, daemon=True) + thread.start() + return thread, done + + +GATE = ("--fallback-gate", "item-approval", "--fallback-approval-wait-s", "15") + + +def test_wrap_dispatch_item_approval_gate_saves_after_a_signed_answer( + task, monkeypatch, run1, approver, tmp_path +) -> None: + import os + + from openadapt_flow.approval_mode.approver_roster import ROOT_ENV + + install_reply(task.model, monkeypatch) + approvals = tmp_path / "approvals" + key_path, _signer = approver + thread, done = _approve_with_cli(approvals, key_path, os.environ[ROOT_ENV]) + agent = Agent() + result = dc.run( + run_args( + task, + "r1", + "one", + *FALLBACK, + *GATE, + "--fallback-approvals-dir", + str(approvals), + ), + agent=agent, + ) + thread.join(timeout=5) + assert done == [0] + assert result["verified"] and result["outcome"] == "VERIFIED" + [answer] = result["fallback"]["gate_answers"] + assert answer["decision"] == "approved" and answer["signer"] == "front-desk" + assert task.model.rows == [{"id": "f1", "kind": "synthetic", "value": "one"}] + + +def test_wrap_dispatch_item_approval_gate_with_a_config_pin( + task, monkeypatch, run1, approver, tmp_path +) -> None: + import os + + from openadapt_flow.approval_mode.approver_roster import ROOT_ENV + from tests._approver_keys import approver_config + + install_reply(task.model, monkeypatch) + root = os.environ[ROOT_ENV] + monkeypatch.delenv(ROOT_ENV) + config = approver_config(tmp_path / "deployment.yaml", root) + approvals = tmp_path / "approvals" + key_path, _signer = approver + thread, done = _approve_with_cli(approvals, key_path, root) + result = dc.run( + run_args( + task, + "r1", + "one", + *FALLBACK, + *GATE, + "--fallback-approvals-dir", + str(approvals), + "--fallback-approvers-config", + str(config), + ), + agent=Agent(), + ) + thread.join(timeout=5) + assert done == [0] and result["verified"] + + +def test_wrap_dispatch_item_approval_gate_without_a_pin_never_builds_the_agent( + task, monkeypatch, run1, approver +) -> None: + from openadapt_flow.approval_mode.approver_roster import ROOT_ENV + + install_reply(task.model, monkeypatch) + monkeypatch.delenv(ROOT_ENV) + monkeypatch.setattr( + dc, "_fallback_agent", lambda *_: pytest.fail("agent built with no pin") + ) + result = dc.run(run_args(task, "r1", "one", *FALLBACK, *GATE)) + assert result["status"] == "FALLBACK_GATE_UNATTENDED" + assert result["outcome"] == "ESCALATED" and task.model.rows == [] + + +def test_the_gate_flags_need_the_fallback(task) -> None: + with pytest.raises(SystemExit): + dc.run(run_args(task, "r1", "one", *GATE)) + with pytest.raises(SystemExit): + dc.run( + run_args( + task, + "r1", + "one", + *FALLBACK, + "--fallback-gate", + "item-approval", + "--fallback-approval-wait-s", + "200", + ) + ) diff --git a/packages/flow/tests/test_wrap_fallback.py b/packages/flow/tests/test_wrap_fallback.py index 22bafe898a..82f84d89de 100644 --- a/packages/flow/tests/test_wrap_fallback.py +++ b/packages/flow/tests/test_wrap_fallback.py @@ -252,6 +252,16 @@ def _record(self, agent: Any, params: dict, *, hold: Any) -> Any: record_check=None, to_dict=lambda: {"status": "refused_by_hold"}, ) + if getattr(self, "wrong", False): + # The agent saved a wrong value; run 1's record check caught it. + self.rows.append({"id": "f1", "kind": "synthetic", "value": "wrong"}) + return SimpleNamespace( + status="record_check_failed", + detail="input 'value' is not in the new record", + run1={"agent": ledger, "gates": gates, "readbacks": [{}]}, + record_check={"passed": False, "created": 1, "changed": 0}, + to_dict=lambda: {"status": "record_check_failed"}, + ) self.rows.append({"id": "f1", "kind": "synthetic", "value": params["value"]}) return SimpleNamespace( status="draft", @@ -275,13 +285,14 @@ def __init__(self, *, model_free: bool = True, cap: Any = None, raises=False): @pytest.fixture def run1(model, monkeypatch) -> SimpleNamespace: - state = SimpleNamespace(spend=None, after=None) + state = SimpleNamespace(spend=None, after=None, wrong=False) FakeRun1.made = [] def factory(prompt: str, **kw: Any) -> FakeRun1: made = FakeRun1( prompt, rows=model.rows, spend=state.spend, after=state.after, **kw ) + made.wrong = state.wrong made.observer = made # observer.system_of_record reads the same rows return made @@ -755,3 +766,39 @@ def gate(request) -> bool: assert seen[0]["cleared"] is False and seen[0]["owner"] == "running" assert result.verified assert not (model.tmp / "cache" / "fallback" / "task" / fb._ACTIVE).exists() + + +def test_a_caught_wrong_save_keeps_its_own_status(model, monkeypatch, run1) -> None: + """A check already caught the wrong write: it stays a caught error (not + reconciliation), and the marker stays for a person.""" + from openadapt_flow.wrap.dispatch_cli import outcome + + install_reply(model, monkeypatch) + run1.wrong = True + chosen = policy(model) + result = chosen.run(PROMPT, PARAMS, Agent()) + assert result.status == "record_check_failed" and not result.verified + assert outcome(result.to_dict()) == "CAUGHT_ERROR" + assert chosen.last["repair"] is None + assert (model.tmp / "cache" / "fallback" / "task" / fb._ACTIVE).exists() + + +def test_a_gate_that_fails_to_bind_leaves_an_ended_marker( + model, monkeypatch, run1 +) -> None: + install_reply(model, monkeypatch) + + class Broken: + attended = True + + def bind(self, run_root, request_id): + raise RuntimeError("no approvals folder") + + def __call__(self, request): + return True + + with pytest.raises(RuntimeError): + policy(model, gate=Broken()).run(PROMPT, PARAMS, Agent()) + runs = fb.fallback_runs(model.cache, PROMPT, PARAMS) + assert runs["in_flight"] and runs["in_flight_owner"] == "ended" + assert fb.clear_in_flight(model.cache, PROMPT, PARAMS) From 4bd5470c93c9449f9679b6c57ad5d366a0da3fd1 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 01:37:40 -0500 Subject: [PATCH 5/9] fix(flow): a change to another record is not 'nothing written' The fallback's no-write check ignored the record check's outside_run counts, so a write to another record during the halt or the fallback could qualify the halt or clear the in-flight marker. Any outside_run change, or a check without outside_run, now counts as something written. --- packages/flow/docs/WRAP_FALLBACK.md | 10 +++- packages/flow/openadapt_flow/wrap/fallback.py | 17 ++++-- packages/flow/tests/test_wrap_fallback.py | 56 +++++++++++++++++++ 3 files changed, 76 insertions(+), 7 deletions(-) diff --git a/packages/flow/docs/WRAP_FALLBACK.md b/packages/flow/docs/WRAP_FALLBACK.md index 3de41a72ce..a4ffc23adb 100644 --- a/packages/flow/docs/WRAP_FALLBACK.md +++ b/packages/flow/docs/WRAP_FALLBACK.md @@ -60,8 +60,11 @@ status text: - The halted reply recorded exactly zero model calls. - The cache's own record check of the halted run read the system of record both before and after (`readable: true`) and found no new, changed or - removed record of the task's record. An unreadable store also reports zero - changes, so it never counts as "nothing written". The policy keeps that + removed record of the task's record, and no change to any other record + during the run (`outside_run`; it may be the program's own write + elsewhere, so another user's write also stops the fallback). An + unreadable store also reports zero changes, so it never counts as + "nothing written". The policy keeps that check beside the halt, so a later call that finds the task held can fall back on the same halt. @@ -104,7 +107,8 @@ was approved by the person, and a final task-scoped read (the baseline taken as the run started against a fresh read after it) confirms exactly one new record of the task's record with its values and nothing else changed on it. When the final read disagrees (a duplicate, a changed or removed record, an -unreadable store), or a stopped run can't show it wrote nothing, the status is +unreadable store), or a stopped run can't show it wrote nothing (including a +change to another record), the status is `RECONCILIATION_REQUIRED`: no repair is opened, the in-flight marker stays, and `fallback.run_status` keeps what the run itself reported, beside both readings (`record_check` and `fallback.task_record_check`). diff --git a/packages/flow/openadapt_flow/wrap/fallback.py b/packages/flow/openadapt_flow/wrap/fallback.py index fa792ef006..34554f3d16 100644 --- a/packages/flow/openadapt_flow/wrap/fallback.py +++ b/packages/flow/openadapt_flow/wrap/fallback.py @@ -131,15 +131,24 @@ def _int_zero(value: Any) -> bool: def _nothing_written(check: Any) -> bool: - """Both reads of the record check succeeded and saw no change to the - task's record. An unreadable store also reports zero counts; without - ``readable`` (an older check) nothing is proved.""" - return ( + """Both reads of the record check succeeded and saw no change at all. + + An unreadable store also reports zero counts; without ``readable`` (an + older check) nothing is proved. A change to another record during the + run (``outside_run``) may be the run's own write elsewhere, so it counts + as something written too, as does a check without ``outside_run``. + """ + if not ( isinstance(check, Mapping) and check.get("readable") is True and _int_zero(check.get("created")) and _int_zero(check.get("changed")) and _int_zero(check.get("removed")) + ): + return False + outside = check.get("outside_run") + return isinstance(outside, Mapping) and all( + _int_zero(outside.get(key)) for key in ("created", "changed", "removed") ) diff --git a/packages/flow/tests/test_wrap_fallback.py b/packages/flow/tests/test_wrap_fallback.py index 82f84d89de..c82376e258 100644 --- a/packages/flow/tests/test_wrap_fallback.py +++ b/packages/flow/tests/test_wrap_fallback.py @@ -802,3 +802,59 @@ def __call__(self, request): runs = fb.fallback_runs(model.cache, PROMPT, PARAMS) assert runs["in_flight"] and runs["in_flight_owner"] == "ended" assert fb.clear_in_flight(model.cache, PROMPT, PARAMS) + + +def test_a_write_to_another_record_during_the_halt_never_falls_back( + model, monkeypatch, run1 +) -> None: + """The task's record is unchanged, but the real record check counts a + new record of another record during the replay: it may be the + program's own write, so the halt is not proved clean.""" + install_reply(model, monkeypatch, write={"id": "9", "kind": "other", "value": "x"}) + agent = Agent() + chosen = policy(model) + result = chosen.run(PROMPT, PARAMS, agent) + assert result.record_check["created"] == 0 + assert result.record_check["outside_run"]["created"] == 1 + assert result.status == "HALTED" and agent.calls == 0 + assert chosen.last == {"fallback": False, "reason": "record_changed_or_unproved"} + + +def test_a_fallback_write_to_another_record_keeps_the_marker( + model, monkeypatch, run1 +) -> None: + """The gate refused the task's save, but the final read (the real + task_record_check) shows a new record elsewhere: reconcile, keep the + marker.""" + install_reply(model, monkeypatch) + + def elsewhere(made: FakeRun1) -> None: + made.rows.append({"id": "9", "kind": "other", "value": "x"}) + + run1.after = elsewhere + chosen = policy(model, gate=lambda request: False) + result = chosen.run(PROMPT, PARAMS, Agent()) + written = chosen.last["task_record_check"] + assert written["created"] == 0 and written["outside_run"]["created"] == 1 + assert result.status == "RECONCILIATION_REQUIRED" and not result.verified + assert chosen.last["run_status"] == "GATE_REFUSED" + assert (model.tmp / "cache" / "fallback" / "task" / fb._ACTIVE).exists() + + +@pytest.mark.parametrize( + "check", + [ + {"readable": True, "created": 0, "changed": 0, "removed": 0}, + { + "readable": True, + "created": 0, + "changed": 0, + "removed": 0, + "outside_run": {"created": 0, "changed": 1, "removed": 0}, + }, + ], +) +def test_nothing_written_needs_no_change_outside_too(check) -> None: + assert fb._nothing_written(check) is False + clean = dict(check, outside_run={"created": 0, "changed": 0, "removed": 0}) + assert fb._nothing_written(clean) is True From c5b9f83004ce1dd430ac9d8639dd81b5218ffc17 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 02:02:33 -0500 Subject: [PATCH 6/9] fix(flow): a fallback that raises still answers its dispatch request The policy records the fallback (its request id, gate decisions) before the agent starts. If anything raises, it writes result.json with RECONCILIATION_REQUIRED and the exception's class, and the stored dispatch envelope says agent_fallback, so a retry returns the same answer instead of path program with fallback null. A repair-desk failure after a confirmed save no longer turns the save into a crash. Also: item-approval gate flags without --fallback-gate item-approval are refused, a bad --fallback-request-id is a clean error, and the gate's request text no longer carries the record's on-screen identity. --- packages/flow/docs/WRAP_FALLBACK.md | 7 ++ .../flow/openadapt_flow/wrap/approval_gate.py | 7 +- .../flow/openadapt_flow/wrap/dispatch_cli.py | 45 +++++++++-- packages/flow/openadapt_flow/wrap/fallback.py | 81 +++++++++++++++---- .../flow/tests/test_wrap_approval_gate.py | 2 + packages/flow/tests/test_wrap_dispatch_cli.py | 73 +++++++++++++++++ 6 files changed, 191 insertions(+), 24 deletions(-) diff --git a/packages/flow/docs/WRAP_FALLBACK.md b/packages/flow/docs/WRAP_FALLBACK.md index a4ffc23adb..1530c6c639 100644 --- a/packages/flow/docs/WRAP_FALLBACK.md +++ b/packages/flow/docs/WRAP_FALLBACK.md @@ -129,6 +129,13 @@ checks the record and runs `wrap-dispatch release TASK --person NAME --after-reconciling`. A run removes the marker only while it is still its own. +A fallback that raises after it started still answers its request: the +stored result has `path: agent_fallback`, `status: RECONCILIATION_REQUIRED`, +and `fallback` naming the fallback request ID, its gate decisions and the +exception's class; `result.json` in the run directory says the same, and a +retry returns it. A failure to open the repair candidate after a confirmed +save leaves the save `VERIFIED` with `repair.reason: repair_failed:`. + ## The gate without a terminal `--fallback-gate item-approval` (`openadapt_flow.wrap.approval_gate.ItemApprovalGate`) diff --git a/packages/flow/openadapt_flow/wrap/approval_gate.py b/packages/flow/openadapt_flow/wrap/approval_gate.py index 1ae1f9ab7e..4aec191cca 100644 --- a/packages/flow/openadapt_flow/wrap/approval_gate.py +++ b/packages/flow/openadapt_flow/wrap/approval_gate.py @@ -229,10 +229,9 @@ def __call__(self, request: GateRequest) -> bool: workflow_name=WORKFLOW_NAME, step_id=f"save-{index + 1}", step_index=index, - step_intent=( - f"Press '{request.control}' on the record showing " - + ", ".join(identity) - ), + # The control only: the record's on-screen identity stays in + # the screenshot, not in text that lists and summaries show. + step_intent=f"Press '{request.control}' (agent fallback save)", mode=ApprovalMode.EACH_ITEM, bundle_content_digest=None, runtime_inputs_digest=None, diff --git a/packages/flow/openadapt_flow/wrap/dispatch_cli.py b/packages/flow/openadapt_flow/wrap/dispatch_cli.py index dffcc9faaf..af24c76688 100644 --- a/packages/flow/openadapt_flow/wrap/dispatch_cli.py +++ b/packages/flow/openadapt_flow/wrap/dispatch_cli.py @@ -97,8 +97,13 @@ def finish( if "outcome" in result and "fallback" in result: # Already a dispatch envelope (stored, then replayed on a retry). return dict(result) + from openadapt_flow.wrap.fallback import FALLBACK_PATH + out = dict(result) - out["path"] = dispatch_path(result) + # A fallback that started speaks for this request, even when it raised + # before returning a result (then the status is RECONCILIATION_REQUIRED). + started = fallback is not None and fallback.get("fallback") is True + out["path"] = FALLBACK_PATH if started else dispatch_path(result) out["outcome"] = outcome(result) out["fallback"] = dict(fallback) if fallback is not None else None return out @@ -199,9 +204,8 @@ def add_run_arguments(p: argparse.ArgumentParser) -> None: p.add_argument( "--fallback-approval-wait-s", type=float, - default=60.0, help="With --fallback-gate item-approval: seconds to wait for each " - "answer (less than --max-run-seconds)", + "answer (default 60; less than --max-run-seconds)", ) p.add_argument( "--fallback-approver-root", @@ -307,6 +311,13 @@ def child_request_id(parent: str) -> str: return f"fallback-{digest[:40]}" +def _wait_s(args: argparse.Namespace) -> float: + from openadapt_flow.wrap.approval_gate import DEFAULT_WAIT_S + + wait = args.fallback_approval_wait_s + return DEFAULT_WAIT_S if wait is None else float(wait) + + def item_approval_gate(args: argparse.Namespace) -> Any: """The non-terminal gate from the ``--fallback-*`` flags.""" @@ -321,7 +332,7 @@ def item_approval_gate(args: argparse.Namespace) -> Any: ) return ItemApprovalGate( approvals_dir=args.fallback_approvals_dir, - wait_s=args.fallback_approval_wait_s, + wait_s=_wait_s(args), key_dir=key_dir, approver_root=args.fallback_approver_root, config_only=bool(args.fallback_approvers_config), @@ -365,15 +376,37 @@ def run( cap = args.fallback_max_cost_usd if fallback_on and (cap is None or not math.isfinite(cap) or cap <= 0): raise SystemExit("--fallback agent requires a positive --fallback-max-cost-usd") + gate_options = ( + args.fallback_approvals_dir, + args.fallback_approval_wait_s, + args.fallback_approver_root, + args.fallback_approvers_config, + ) if not fallback_on and ( cap is not None or args.fallback_request_id or args.fallback_gate != "terminal" - or args.fallback_approvals_dir + or any(option is not None for option in gate_options) ): raise SystemExit("the --fallback-* options need --fallback agent") + if args.fallback_gate != "item-approval" and any( + option is not None for option in gate_options + ): + raise SystemExit( + "--fallback-approvals-dir, --fallback-approval-wait-s, " + "--fallback-approver-root and --fallback-approvers-config need " + "--fallback-gate item-approval" + ) + if args.fallback_request_id is not None: + from openadapt_flow.wrap.fallback import valid_request_id + + if not valid_request_id(args.fallback_request_id): + raise SystemExit( + "--fallback-request-id is 1 to 128 of [A-Za-z0-9._-], " + "not starting with '.'" + ) if args.fallback_gate == "item-approval" and not ( - 0 < args.fallback_approval_wait_s < args.max_run_seconds + 0 < _wait_s(args) < args.max_run_seconds ): raise SystemExit( "--fallback-approval-wait-s must be more than 0 and less than " diff --git a/packages/flow/openadapt_flow/wrap/fallback.py b/packages/flow/openadapt_flow/wrap/fallback.py index 34554f3d16..954022b138 100644 --- a/packages/flow/openadapt_flow/wrap/fallback.py +++ b/packages/flow/openadapt_flow/wrap/fallback.py @@ -78,6 +78,16 @@ ) +def valid_request_id(value: Any) -> bool: + """A fallback request id: a plain file name of 1 to 128 safe characters.""" + return ( + isinstance(value, str) + and 0 < len(value) <= 128 + and set(value) <= _REQUEST_CHARS + and not value.startswith(".") + ) + + class PreCommitGate(Protocol): """Asked before every save in a fallback run; True lets that save through. @@ -348,12 +358,7 @@ def __init__( self.cache = cache self.max_cost_usd = _cap(max_cost_usd) self.gate: PreCommitGate = gate if gate is not None else TerminalGate() - if request_id is not None and ( - not isinstance(request_id, str) - or not 0 < len(request_id) <= 128 - or not set(request_id) <= _REQUEST_CHARS - or request_id.startswith(".") - ): + if request_id is not None and not valid_request_id(request_id): raise ValueError("a fallback request id is 1 to 128 of [A-Za-z0-9._-]") self.request_id = request_id self.repair_desk = repair_desk @@ -478,13 +483,30 @@ def _fallback( started, request_id=request_id, ) - bind = getattr(self.gate, "bind", None) - if callable(bind): - # A gate that keeps its own evidence learns which run it serves. - bind(run_root, request_id) - return self._run_agent( - prompt, params, agent, first, marker, run_root, started - ) + decisions: list[str] = [] + # Recorded before the agent starts: if anything below raises, the + # dispatch result still names this fallback, as a possible write. + self.last = { + "fallback": True, + "request_id": request_id, + "parent_request_id": self.parent_request_id, + "status": "RECONCILIATION_REQUIRED", + "run_status": None, + "decisions": decisions, + "admitted": False, + "error": None, + } + try: + bind = getattr(self.gate, "bind", None) + if callable(bind): + # A gate that keeps its own evidence learns its run. + bind(run_root, request_id) + return self._run_agent( + prompt, params, agent, first, marker, run_root, started, decisions + ) + except BaseException as exc: + self._crashed(first, run_root, started, exc) + raise finally: # A run that did not prove what it wrote (or raised) keeps the # marker, marked ended, for a person; a cleared one is gone. @@ -499,12 +521,12 @@ def _run_agent( marker: fallback_marker.Marker, run_root: Path, started: float, + decisions: list[str], ) -> SkillRun: from openadapt_flow.compile_agent import FirstRunCompiler request_id = run_root.name cap = self.max_cost_usd - decisions: list[str] = [] def hold(request: GateRequest) -> bool: spent = _spent(agent) @@ -654,6 +676,35 @@ def hold(request: GateRequest) -> bool: marker.clear() return run + def _crashed( + self, first: SkillRun, run_root: Path, started: float, exc: BaseException + ) -> None: + """A fallback that raised: keep what is known, as a possible write.""" + assert self.last is not None + self.last.update( + status="RECONCILIATION_REQUIRED", + error=type(exc).__name__, + gate_answers=[ + dict(row) for row in getattr(self.gate, "decisions", None) or [] + ], + ) + run = SkillRun( + path=FALLBACK_PATH, + status="RECONCILIATION_REQUIRED", + verified=False, + model_calls=None, + cost_usd=None, + seconds=round(time.monotonic() - started, 3), + detail="The fallback run raised; a save may exist.", + replay={"program": first.replay, "fallback": self.last}, + usage=None, + usage_known=False, + ) + try: + _write(run_root / _RESULT, run.to_dict()) + except OSError: + pass # The marker stays; a person reconciles without the file. + def _open_repair( self, prompt: str, params: Mapping[str, Any], run_root: Path ) -> dict[str, Any]: @@ -665,6 +716,8 @@ def _open_repair( reply = self.cache.open_repair(prompt, params, repair_desk=self.repair_desk) except RepairError: return {"opened": False, "reason": "no_one_step_repair"} + except Exception as exc: # noqa: BLE001 - the verified save stands + return {"opened": False, "reason": f"repair_failed:{type(exc).__name__}"} # The repair token is a one-use capability for the person who # demonstrates the fix; it stays in a private local file. _write(run_root / "repair.json", reply) diff --git a/packages/flow/tests/test_wrap_approval_gate.py b/packages/flow/tests/test_wrap_approval_gate.py index 10d004abf1..2123778a32 100644 --- a/packages/flow/tests/test_wrap_approval_gate.py +++ b/packages/flow/tests/test_wrap_approval_gate.py @@ -99,6 +99,8 @@ def test_a_signed_person_approval_lets_the_save_through(tmp_path, approver) -> N assert asked.run_id == "fallback-abc" and asked.provenance.actor.startswith( "agent:" ) + # The record's on-screen identity is only in the screenshot. + assert "Synthetic record" not in asked.step_intent # The person is shown the gate screenshot itself. assert store.read_frame(asked) == FRAME diff --git a/packages/flow/tests/test_wrap_dispatch_cli.py b/packages/flow/tests/test_wrap_dispatch_cli.py index 88f8512129..930005cf8d 100644 --- a/packages/flow/tests/test_wrap_dispatch_cli.py +++ b/packages/flow/tests/test_wrap_dispatch_cli.py @@ -537,3 +537,76 @@ def test_the_gate_flags_need_the_fallback(task) -> None: "200", ) ) + + +# -- a fallback that raises still names itself ---------------------------------- + + +def test_a_crashed_fallback_is_stored_as_a_possible_write( + task, monkeypatch, run1 +) -> None: + """From the reviewer's probe: the agent raises after the fallback started. + The stored envelope says agent_fallback and RECONCILIATION_REQUIRED, with + the child request and the error class, on the first call and on retry; + result.json is written.""" + from openadapt_flow.wrap.fallback import fallback_root + + install_reply(task.model, monkeypatch) + agent = Agent(raises=True) + args = run_args(task, "r1", "one", *FALLBACK) + crashed = dc.run(args, agent=agent, gate=lambda r: True) + assert crashed["path"] == "agent_fallback" + assert crashed["status"] == "RECONCILIATION_REQUIRED" + assert crashed["outcome"] == "ESCALATED" and crashed["verified"] is False + child = dc.child_request_id("r1") + assert crashed["fallback"]["request_id"] == child + assert crashed["fallback"]["error"] == "RuntimeError" + assert crashed["fallback"]["parent_request_id"] == "r1" + root = fallback_root(task.setup.cache, PROMPT, {"value": ""}) + saved = json.loads((root / child / "result.json").read_text()) + assert saved["path"] == "agent_fallback" + assert saved["status"] == "RECONCILIATION_REQUIRED" and saved["verified"] is False + assert saved["replay"]["fallback"]["error"] == "RuntimeError" + again = dc.run(args, agent=agent, gate=lambda r: pytest.fail("asked again")) + assert again["replayed"] is True and agent.calls == 1 + assert {k: again[k] for k in ("path", "status", "outcome", "fallback")} == { + k: crashed[k] for k in ("path", "status", "outcome", "fallback") + } + + +def test_a_repair_desk_failure_keeps_the_verified_save(task, monkeypatch, run1) -> None: + install_reply(task.model, monkeypatch) + + def broken(*_a, **_k): + raise OSError("repair desk unavailable") + + monkeypatch.setattr(task.setup.cache, "open_repair", broken) + result = dc.run( + run_args(task, "r1", "one", *FALLBACK), agent=Agent(), gate=lambda r: True + ) + assert result["verified"] and result["path"] == "agent_fallback" + assert result["fallback"]["repair"] == { + "opened": False, + "reason": "repair_failed:OSError", + } + + +@pytest.mark.parametrize( + "extra", + [ + ("--fallback-approver-root", "a" * 64), + ("--fallback-approvers-config", "deployment.yaml"), + ("--fallback-approval-wait-s", "10"), + (*FALLBACK, "--fallback-approver-root", "a" * 64), + (*FALLBACK, "--fallback-approvals-dir", "approvals"), + ], +) +def test_gate_options_without_the_item_approval_gate_are_refused(task, extra) -> None: + with pytest.raises(SystemExit): + dc.run(run_args(task, "r1", "one", *extra)) + + +@pytest.mark.parametrize("bad", ["a/b", ".hidden", "x" * 129, ""]) +def test_a_bad_fallback_request_id_is_a_clean_error(task, bad) -> None: + with pytest.raises(SystemExit, match="fallback-request-id"): + dc.run(run_args(task, "r1", "one", *FALLBACK, "--fallback-request-id", bad)) From 29c1b15622157183245a0991e8bca2c2301ac60d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 02:25:51 -0500 Subject: [PATCH 7/9] fix(flow): store an interrupted fallback before re-raising Ctrl-C at the gate or a SystemExit in the agent escaped WrappedTask.call's Exception handler, so the request stayed reserved and a retry reported a program run. The dispatch task now carries the interrupt through that path, stores the finished agent_fallback / RECONCILIATION_REQUIRED envelope, then raises it again. REQUEST_ID_CONFLICT reports path held, repair.json is written inside the repair try, and the docs list a killed process as not covered. --- packages/flow/docs/WRAP_FALLBACK.md | 8 ++- .../flow/openadapt_flow/wrap/dispatch_cli.py | 37 +++++++++- packages/flow/openadapt_flow/wrap/fallback.py | 6 +- packages/flow/tests/test_wrap_dispatch_cli.py | 68 +++++++++++++++++++ 4 files changed, 113 insertions(+), 6 deletions(-) diff --git a/packages/flow/docs/WRAP_FALLBACK.md b/packages/flow/docs/WRAP_FALLBACK.md index 1530c6c639..f66dd3d54f 100644 --- a/packages/flow/docs/WRAP_FALLBACK.md +++ b/packages/flow/docs/WRAP_FALLBACK.md @@ -129,7 +129,9 @@ checks the record and runs `wrap-dispatch release TASK --person NAME --after-reconciling`. A run removes the marker only while it is still its own. -A fallback that raises after it started still answers its request: the +A fallback that raises after it started, or is interrupted (Ctrl-C at the +gate, a `SystemExit` in the agent), still answers its request; an interrupt +is raised again after the request is stored: the stored result has `path: agent_fallback`, `status: RECONCILIATION_REQUIRED`, and `fallback` naming the fallback request ID, its gate decisions and the exception's class; `result.json` in the run directory says the same, and a @@ -214,6 +216,10 @@ The hold verbs: - A program hold left `running` by a live program replay is not told apart from a lost reply; release with `--after-reconciling` can archive it while that replay still runs. +- A process killed outright (`SIGKILL`, power loss) mid-fallback leaves the + request reserved and the marker `running` until its process is gone; a + retry then returns `RECONCILIATION_REQUIRED` without the fallback's + details, and `result.json` may be missing. - A fallback marker whose owner is on another host, or that can't be read, has no release command: a person checks the record and removes `in-flight.json` by hand. diff --git a/packages/flow/openadapt_flow/wrap/dispatch_cli.py b/packages/flow/openadapt_flow/wrap/dispatch_cli.py index af24c76688..04e6ac921c 100644 --- a/packages/flow/openadapt_flow/wrap/dispatch_cli.py +++ b/packages/flow/openadapt_flow/wrap/dispatch_cli.py @@ -85,7 +85,13 @@ def dispatch_path(result: Mapping[str, Any]) -> str: if result.get("path") == FALLBACK_PATH: return FALLBACK_PATH - if result.get("status") in ("CACHE_HALTED", "NO_ADMITTED_PROGRAM"): + # Nothing ran for a held task, a miss, or a request id already used for + # other inputs. + if result.get("status") in ( + "CACHE_HALTED", + "NO_ADMITTED_PROGRAM", + "REQUEST_ID_CONFLICT", + ): return "held" return "program" @@ -340,15 +346,42 @@ def item_approval_gate(args: argparse.Namespace) -> Any: ) +class _Interrupted(Exception): + """Carries a KeyboardInterrupt or SystemExit through WrappedTask.call.""" + + def _task(policy: Any, **options: Any) -> Any: - """A WrappedTask whose stored result is the whole dispatch envelope.""" + """A WrappedTask whose stored result is the whole dispatch envelope. + + WrappedTask.call stores RECONCILIATION_REQUIRED for an Exception. An + interrupt (Ctrl-C at the gate, a SystemExit in the agent) is carried + through that path as an Exception, so the request is stored as finished + and uncertain first; then the interrupt is raised again. + """ from openadapt_flow.wrap import WrappedTask class DispatchTask(WrappedTask): + interrupted: Optional[BaseException] = None + + def run(self, arguments: Mapping[str, Any]) -> Any: + try: + return super().run(arguments) + except Exception: + raise + except BaseException as exc: + self.interrupted = exc + raise _Interrupted(type(exc).__name__) from exc + def finalize(self, result: dict[str, Any]) -> dict[str, Any]: last = getattr(policy, "last", None) if policy is not None else None return finish(result, last) + def call(self, request_id: str, arguments: Mapping[str, Any]) -> Any: + result = super().call(request_id, arguments) + if self.interrupted is not None: + raise self.interrupted + return result + return DispatchTask(**options) diff --git a/packages/flow/openadapt_flow/wrap/fallback.py b/packages/flow/openadapt_flow/wrap/fallback.py index 954022b138..1cdc5805e5 100644 --- a/packages/flow/openadapt_flow/wrap/fallback.py +++ b/packages/flow/openadapt_flow/wrap/fallback.py @@ -714,13 +714,13 @@ def _open_repair( try: reply = self.cache.open_repair(prompt, params, repair_desk=self.repair_desk) + # The repair token is a one-use capability for the person who + # demonstrates the fix; it stays in a private local file. + _write(run_root / "repair.json", reply) except RepairError: return {"opened": False, "reason": "no_one_step_repair"} except Exception as exc: # noqa: BLE001 - the verified save stands return {"opened": False, "reason": f"repair_failed:{type(exc).__name__}"} - # The repair token is a one-use capability for the person who - # demonstrates the fix; it stays in a private local file. - _write(run_root / "repair.json", reply) return { "opened": True, "step_id": reply.get("step_id"), diff --git a/packages/flow/tests/test_wrap_dispatch_cli.py b/packages/flow/tests/test_wrap_dispatch_cli.py index 930005cf8d..68c7dbd5a0 100644 --- a/packages/flow/tests/test_wrap_dispatch_cli.py +++ b/packages/flow/tests/test_wrap_dispatch_cli.py @@ -610,3 +610,71 @@ def test_gate_options_without_the_item_approval_gate_are_refused(task, extra) -> def test_a_bad_fallback_request_id_is_a_clean_error(task, bad) -> None: with pytest.raises(SystemExit, match="fallback-request-id"): dc.run(run_args(task, "r1", "one", *FALLBACK, "--fallback-request-id", bad)) + + +@pytest.mark.parametrize( + "interrupt", [KeyboardInterrupt, lambda: SystemExit("agent exited")] +) +@pytest.mark.parametrize("where", ["gate", "agent"]) +def test_an_interrupted_fallback_is_stored_before_it_reraises( + task, monkeypatch, run1, interrupt, where +) -> None: + """From the reviewer's probe: Ctrl-C at the gate, or a SystemExit in the + agent. The request is stored as a finished agent_fallback that may have + written, result.json says so, the marker stays, and a retry replays it.""" + from openadapt_flow.wrap.fallback import fallback_root + + install_reply(task.model, monkeypatch) + agent = Agent() + args = run_args(task, "r1", "one", *FALLBACK) + + def gate(_request): + raise interrupt() + + if where == "agent": + run1.after = lambda made: (_ for _ in ()).throw(interrupt()) + gate = lambda _request: True # noqa: E731 + with pytest.raises((KeyboardInterrupt, SystemExit)): + dc.run(args, agent=agent, gate=gate) + root = fallback_root(task.setup.cache, PROMPT, {"value": ""}) + child = dc.child_request_id("r1") + saved = json.loads((root / child / "result.json").read_text()) + assert saved["path"] == "agent_fallback" + assert saved["status"] == "RECONCILIATION_REQUIRED" + assert json.loads((root / "in-flight.json").read_text())["state"] == "ended" + again = dc.run(args, agent=agent, gate=lambda r: pytest.fail("asked")) + assert again["replayed"] is True and agent.calls == 1 + assert again["path"] == "agent_fallback" + assert again["status"] == "RECONCILIATION_REQUIRED" + assert again["outcome"] == "ESCALATED" + assert again["fallback"]["request_id"] == child + assert again["fallback"]["error"] in ("KeyboardInterrupt", "SystemExit") + + +def test_a_reused_request_id_reports_nothing_ran(task, monkeypatch) -> None: + install_reply(task.model, monkeypatch) + dc.run(run_args(task, "r1", "one")) + conflict = dc.run(run_args(task, "r1", "two")) + assert conflict["status"] == "REQUEST_ID_CONFLICT" + assert conflict["path"] == "held" and len(task.model.sent) == 1 + + +def test_a_repair_file_write_failure_keeps_the_verified_save( + task, monkeypatch, run1 +) -> None: + from openadapt_flow.wrap import fallback as fb + + install_reply(task.model, monkeypatch) + real = fb._write + + def write(path, data, **kw): + if path.name == "repair.json": + raise OSError("disk full") + return real(path, data, **kw) + + monkeypatch.setattr(fb, "_write", write) + result = dc.run( + run_args(task, "r1", "one", *FALLBACK), agent=Agent(), gate=lambda r: True + ) + assert result["verified"] + assert result["fallback"]["repair"]["reason"] == "repair_failed:OSError" From 43d8dd71933e40498c90f5dc151b53b434df61e5 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 03:17:37 -0500 Subject: [PATCH 8/9] fix(flow): build the openadapt-flow parser without POSIX-only modules Registering wrap-dispatch imported openadapt_flow.wrap, whose top-level SkillRun import pulls in the agent integrations and write_ledger, which needs fcntl. On Windows every openadapt-flow command then failed while building its parser (windows replay). SkillRun is now a type-checking import. Also registers benchmark/wrap_fallback/results.json in the public artifact inventory (flow core lint). --- packages/flow/openadapt_flow/wrap/__init__.py | 7 +++++-- packages/flow/public-artifacts.json | 1 + packages/flow/tests/test_wrap_dispatch_cli.py | 17 +++++++++++++++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/wrap/__init__.py b/packages/flow/openadapt_flow/wrap/__init__.py index 8edc2cd748..a839dc92d4 100644 --- a/packages/flow/openadapt_flow/wrap/__init__.py +++ b/packages/flow/openadapt_flow/wrap/__init__.py @@ -8,9 +8,12 @@ import threading from collections.abc import Mapping, Sequence from pathlib import Path -from typing import Any, Protocol +from typing import TYPE_CHECKING, Any, Protocol -from openadapt_flow.integrations.agents.skills import SkillRun +if TYPE_CHECKING: + # Imported lazily: the agent integrations pull in POSIX-only modules, + # and building the openadapt-flow parser imports this package. + from openadapt_flow.integrations.agents.skills import SkillRun _PARAMETER = re.compile(r"[A-Za-z_][A-Za-z0-9_]*\Z") diff --git a/packages/flow/public-artifacts.json b/packages/flow/public-artifacts.json index 32c9b4bad1..be191d1451 100644 --- a/packages/flow/public-artifacts.json +++ b/packages/flow/public-artifacts.json @@ -1173,6 +1173,7 @@ "benchmark/vlm_identity/pairs/drift_MG4482_dark.png", "benchmark/vlm_identity/vlm_identity.json", "benchmark/windows_uia/results.json", + "benchmark/wrap_fallback/results.json", "benchmark/write_leaderboard_v2/cases.yaml", "benchmark/write_leaderboard_v2/practice_cases.yaml", "benchmark/zero_config_verify/generated/mockloan.D-net-read-complete.yaml", diff --git a/packages/flow/tests/test_wrap_dispatch_cli.py b/packages/flow/tests/test_wrap_dispatch_cli.py index 68c7dbd5a0..2dba61c150 100644 --- a/packages/flow/tests/test_wrap_dispatch_cli.py +++ b/packages/flow/tests/test_wrap_dispatch_cli.py @@ -678,3 +678,20 @@ def write(path, data, **kw): ) assert result["verified"] assert result["fallback"]["repair"]["reason"] == "repair_failed:OSError" + + +def test_the_parser_builds_without_posix_only_modules() -> None: + """Windows has no fcntl. Registering wrap-dispatch must not import the + agent integrations (they reach write_ledger, which needs fcntl).""" + import subprocess + import sys + + code = ( + "import sys; sys.modules['fcntl'] = None\n" + "from openadapt_flow.__main__ import build_parser\n" + "build_parser().parse_args(['wrap-dispatch', 'status', 'task.json'])\n" + ) + done = subprocess.run( + [sys.executable, "-c", code], capture_output=True, text=True, timeout=120 + ) + assert done.returncode == 0, done.stderr[-2000:] From aeb75c8b48a87a77da8b38ca276ad58ca4769f7e Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 04:11:59 -0500 Subject: [PATCH 9/9] fix(flow): disable argparse abbreviations in wrap-dispatch parsers The standalone wrap-dispatch parser and the benchmark's parser now pass allow_abbrev=False, and BACKEND_PARITY.md records why wrap-dispatch's --pricing-source-url is not an app URL. --- packages/flow/benchmark/wrap_fallback/measure.py | 2 +- packages/flow/docs/BACKEND_PARITY.md | 1 + packages/flow/openadapt_flow/wrap/dispatch_cli.py | 2 +- 3 files changed, 3 insertions(+), 2 deletions(-) diff --git a/packages/flow/benchmark/wrap_fallback/measure.py b/packages/flow/benchmark/wrap_fallback/measure.py index 23ebff2c7e..1bef267e8a 100644 --- a/packages/flow/benchmark/wrap_fallback/measure.py +++ b/packages/flow/benchmark/wrap_fallback/measure.py @@ -128,7 +128,7 @@ def trial(mode: str, approve: bool) -> dict[str, Any]: def main() -> int: - parser = argparse.ArgumentParser() + parser = argparse.ArgumentParser(allow_abbrev=False) parser.add_argument("--out", required=True) parser.add_argument("--modes", nargs="*", default=sorted(MODES)) args = parser.parse_args() diff --git a/packages/flow/docs/BACKEND_PARITY.md b/packages/flow/docs/BACKEND_PARITY.md index f82f749236..52ad243df6 100644 --- a/packages/flow/docs/BACKEND_PARITY.md +++ b/packages/flow/docs/BACKEND_PARITY.md @@ -343,6 +343,7 @@ and `--log-url`, the transparency log) are not app URLs. | `openadapt-flow validate-hosted` | `--target-url` | The surface comes from the signed run report. A non-web report refuses a target URL ("Target URL is web-only and must be omitted"). | | `openadapt-agent authoring connect` | `--url` | `--url` opens a fresh browser. Without it the command pins the local app window (one macOS or Linux window). Windows, RDP and Citrix are coach-only on the mailbox: the person drives and Capture records (`COACH_ONLY_BACKENDS` in `agent/mailbox.py`). | | `openadapt-agent seal keys pin` | `--url` | The seal key server's address, not an app. | +| `openadapt-flow wrap-dispatch` | `--pricing-source-url` | The primary source cited for the model prices the fallback's cost is computed with, not an app. The task's app comes from `--task`. | diff --git a/packages/flow/openadapt_flow/wrap/dispatch_cli.py b/packages/flow/openadapt_flow/wrap/dispatch_cli.py index 04e6ac921c..3f52fe9755 100644 --- a/packages/flow/openadapt_flow/wrap/dispatch_cli.py +++ b/packages/flow/openadapt_flow/wrap/dispatch_cli.py @@ -660,7 +660,7 @@ def cmd_wrap_dispatch(args: argparse.Namespace) -> int: def main(argv: Sequence[str] | None = None) -> int: """Run as ``python -m openadapt_flow.wrap.dispatch_cli``.""" - parser = argparse.ArgumentParser(prog="openadapt-flow") + parser = argparse.ArgumentParser(prog="openadapt-flow", allow_abbrev=False) register(parser.add_subparsers(dest="command", required=True)) rows = list(sys.argv[1:] if argv is None else argv) args = parser.parse_args(["wrap-dispatch", *rows])