From e6f94397e30ccafdc62d8eb146978749a4dcd6f0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Fri, 20 Nov 2026 20:48:21 -0500 Subject: [PATCH 1/8] feat(flow): learn per-request bookkeeping from read-only requests openadapt-flow learn probe reads the whole-database frame, sends only GET and HEAD requests as the agent, and reads again. A changed row of the acting user that moved (a last-login or token-use time) becomes a frame.learned excuse with source read_only_probe, with no approval. Added rows, rows of other users and rows no user owns are not admitted. --- CAPABILITIES.md | 4 +- packages/flow/docs/LEARNED_EXCUSES.md | 47 ++ .../learn.md | 2 +- packages/flow/openadapt_flow/learn.py | 17 + packages/flow/openadapt_flow/learn_probe.py | 406 ++++++++++++++++++ .../openadapt_flow/runtime/effects/frame.py | 1 + .../openadapt_flow/runtime/effects/learned.py | 8 +- packages/flow/tests/test_learn_probe.py | 349 +++++++++++++++ 8 files changed, 830 insertions(+), 4 deletions(-) create mode 100644 packages/flow/openadapt_flow/learn_probe.py create mode 100644 packages/flow/tests/test_learn_probe.py diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 7f7a85d526..ac77f23fe3 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -318,7 +318,7 @@ 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` | +| 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`. 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` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | @@ -481,7 +481,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. -- `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. +- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), and write them into the contracts. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index cb46acad14..036f76c48a 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -184,8 +184,55 @@ KIND=PATH`. Each needs `frame.database`. Approving again replaces the earlier `frame.learned` with the new one. +## Learning from read-only requests (`learn probe`) + +`collect` learns only from writes the shadow can check. When an app's +requests name their target in the URL, no write is checkable and nothing is +learned. `learn probe` learns the same moves without a write: + +```bash +export AGENT_HEADERS='{"Authorization": "Bearer ..."}' # the agent's own credential +openadapt-flow learn probe --manifest generated/manifest.yaml \ + --kind add_note --values example.yaml --extra '{agent_user_id: "2"}' \ + --actor 2 --base-url http://app.example.test --headers-env AGENT_HEADERS \ + --get /api/notes --out learn/ --apply +``` + +For each of three rounds it reads the whole-database frame of one +contract, sends only the `GET` and `HEAD` requests you list as the agent, +and reads again. No write is sent, so whatever the app moved is its own +bookkeeping. The proposal follows the rules above: only the acting user's +own rows, the exact columns, and never a column the probe's query strings, +the parameters or a contract name. A `changed` move seen in any one round +counts, because no round carried a task. An `added` row (a first-login row) +is never admitted by the probe: its excuse names columns, not values, so it +would also cover a row the agent adds for itself with other values. It is +listed under `needs_approval` for `learn approve`. Every other row that +moved stays a stop and is listed in `learn/probe_proposal.json`. + +The users table comes from the manifest: the table that the columns bound +to an actor parameter (`actor_params`) reference by foreign key. When there +is no such column, or they reference more than one table, nothing is +learned unless you name it (`--users`). + +`--apply` writes the excuses into every contract the manifest lists, with +`frame.learned.source: read_only_probe`, and leaves out of each contract +any excuse for a column that contract names. No person approves them: the +rows were read, the relation is derived from the schema, and the requests +are checked to be read-only. A contract that already has `frame.learned` +is refused, so a person reconciles the two. Receipts name the source. + ## Limits +- A probe sees only what its requests make the app write. A column the app + writes only on some requests (an export, a report) stays a stop until a + probe request or an approved proposal covers it. +- With no approval, the actor-column limit below applies without a person + reading it: a probe excuse on a table whose only user column means + "created by" covers those columns on every row the agent created. The + excused columns are only those a read moved (times, counters), and any + other column of such a row still stops. + - A learned excuse is only as narrow as its actor columns. If a table's only user column means "created by" rather than "belongs to", an excuse on it covers every row the agent created, other users' rows included. diff --git a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md index 59e93fcf8e..f7880c8387 100644 --- a/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md +++ b/packages/flow/docs/commands/11-guard-an-agent-you-already-run/learn.md @@ -1 +1 @@ -Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. +Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), and write them into the contracts. diff --git a/packages/flow/openadapt_flow/learn.py b/packages/flow/openadapt_flow/learn.py index ca15def4e7..0fee10dbac 100644 --- a/packages/flow/openadapt_flow/learn.py +++ b/packages/flow/openadapt_flow/learn.py @@ -333,6 +333,12 @@ def _why_ignored(ep: Mapping[str, Any]) -> Optional[str]: if ep.get("mode") not in ("sql", ""): return "not a SQL check" + if ep.get("probe"): + # A read-only window (learn_probe): no write, so no declared effect + # to hold; only the frame's moved rows count. + if ep.get("frame") != "refuted": + return "nothing moved in the read-only window" + return _why_rows_ignored(ep) outcome = ep.get("outcome") if outcome == "CONFIRMED": return "confirmed: nothing moved that needs an excuse" @@ -342,6 +348,13 @@ def _why_ignored(ep: Mapping[str, Any]) -> Optional[str]: return "the frame wasn't refuted (not checked)" if outcome != "REFUTED": return f"outcome {outcome}" + return _why_rows_ignored(ep) + + +def _why_rows_ignored(ep: Mapping[str, Any]) -> Optional[str]: + """Why an episode's moves teach nothing, or None when every move is a + row that can be named.""" + moves = ep.get("moves") if not isinstance(moves, list) or not moves: return "no moved rows recorded" @@ -934,6 +947,10 @@ def build_parser(p: argparse.ArgumentParser) -> argparse.ArgumentParser: "--reject", action="append", default=[], metavar="ID", help="leave out E" ) a.set_defaults(func=cmd_approve) + + from openadapt_flow import learn_probe + + learn_probe.add_parser(steps) return p diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py new file mode 100644 index 0000000000..57e5d7842a --- /dev/null +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -0,0 +1,406 @@ +"""Learn the app's per-request bookkeeping from read-only requests. + +Some apps write on every request: the acting user's ``last_login``, an API +token's last-used time, a property row added at the user's first sign-in. +The whole-database frame sees those rows move and refutes every write, +correct or not. :mod:`openadapt_flow.learn` learns them from checked writes +and a person approves. That needs writes the shadow can check, and on apps +whose requests name their target in the URL it learns nothing. + +This module learns the same moves without a write. A read-only request +(``GET`` or ``HEAD``) carries no task, so a row it makes the app move is +the app's own bookkeeping, not something an agent asked for: + +1. For each probe round, read the contract's whole-database frame + (``begin_write`` with the probe's parameters), send the read-only + requests as the agent, and judge the frame (``verify_write``). No write + is sent, so the declared effect is absent; only the frame's moved rows + are used. +2. Propose from those moves with the learner's own rules + (:func:`openadapt_flow.learn.propose`): only the acting user's own row + (``actor_row``), exact columns, ``changed`` only, and never a column a + probe request, a parameter or the contract names. An ``added`` row is + held for a person's approval (its excuse would name columns, not + values). Any other row that moved, another user's or one no user owns, + stays a stop and is listed. +3. Write the excuses into each contract's ``frame.learned`` with + ``source: read_only_probe``. At check time the frame derives the + relation again from the run's actor, so an excuse never reaches another + user's row or another column. + +No person approves this, because nothing in it is a judgment: which rows +moved is read, the relation to the acting user is derived from the +schema's foreign keys, and the method of every request is checked. Where +the users table can't be derived (``users_for_actor_params``), nothing is +learned. Nothing here reads or stores a record value. +""" + +from __future__ import annotations + +import json +import tempfile +from collections.abc import Callable, Mapping, Sequence +from pathlib import Path +from typing import Any, Optional + +from openadapt_flow import learn as _learn + +#: Request methods a probe may send: they carry no task. +READ_ONLY_METHODS = frozenset({"GET", "HEAD"}) +#: The ``frame.learned.approved_by`` of a probe's excuses. +PROBE_APPROVER = "read-only probe (openadapt-flow learn probe)" +DEFAULT_ROUNDS = 3 + + +class ProbeError(_learn.LearnError): + """The probe can't run or its result can't be written.""" + + +def check_read_only(requests: Sequence[tuple[str, str]]) -> None: + """Refuse any request that isn't ``GET`` or ``HEAD``.""" + + if not requests: + raise ProbeError("a probe needs at least one read-only request") + for method, _path in requests: + if str(method).upper() not in READ_ONLY_METHODS: + raise ProbeError( + f"a probe sends read-only requests only (GET, HEAD), not {method!r}" + ) + + +def episode( + kind: str, + result: Any, + *, + contract: Any, + params: Mapping[str, Any], + sent_fields: set[str], +) -> dict[str, Any]: + """One probe round as a learner episode (names only).""" + + evidence = getattr(result, "evidence", None) or {} + frame = evidence.get("frame") if isinstance(evidence, Mapping) else None + checked = getattr(result, "checked", None) or {} + out: dict[str, Any] = { + "schema_version": _learn.EPISODE_SCHEMA, + "probe": True, + "kind": kind, + "mode": "sql", + "contract": str(getattr(contract, "name", "") or ""), + "frame": str(checked.get("frame") or ""), + "sent_fields": sorted(sent_fields), + "param_names": sorted(str(p) for p in params), + "contract_fields": _learn.contract_fields(contract), + "has_database": isinstance(frame, Mapping) + and isinstance(frame.get("database"), Mapping), + } + moves = frame.get("moves") if isinstance(frame, Mapping) else None + out["moves"] = [dict(m) for m in moves or [] if isinstance(m, Mapping)] + return out + + +def probe( + contract: Any, + params: Mapping[str, Any], + *, + kind: str, + actor: str, + send: Callable[[], set[str]], + rounds: int = DEFAULT_ROUNDS, + workdir: Optional[Path] = None, +) -> list[dict[str, Any]]: + """Run ``rounds`` read-only windows under ``contract``'s frame. + + ``send`` sends the read-only requests as the agent and returns the + query-parameter names it sent (``learn.query_fields``); it must not + write. Returns one episode per round.""" + + from openadapt_flow.verifier import Actor, begin_write, verify_write + + if rounds < 1: + raise ProbeError("a probe runs at least one round") + config = getattr(contract, "config", None) + frame = getattr(config, "frame", None) + if frame is None or getattr(frame, "database", None) is None: + raise ProbeError("a probe reads the whole-database frame: frame.database") + out = [] + with tempfile.TemporaryDirectory(prefix="oa-probe-") as tmp: + base = Path(workdir) if workdir is not None else Path(tmp) + for i in range(rounds): + pending = begin_write( + contract, + dict(params), + actor=Actor("agent", str(actor)), + ledger=None, + write_key=f"read-only-probe-{kind}-{i}", + workdir=base / f"round-{i}", + ) + sent = set(send()) + result = verify_write(pending) + out.append( + episode( + kind, result, contract=contract, params=params, sent_fields=sent + ) + ) + return out + + +def users_for_actor_params(manifest_path: Path, schema: Any) -> Optional[_learn.Users]: + """The users table, derived from a generator manifest: the one table and + key that every column bound to an actor parameter (``actor_params``) + references by foreign key. None when there is no such column, or the + columns reference more than one table (then nothing is learned).""" + + import yaml + + data = yaml.safe_load(Path(manifest_path).read_text(encoding="utf-8")) or {} + actor_params = {str(p) for p in data.get("actor_params") or []} + if not actor_params or schema is None: + return None + base = Path(manifest_path).resolve().parent + targets: set[tuple[str, str]] = set() + for body in (data.get("kinds") or {}).values(): + main = (body or {}).get("main_table") + table = schema.tables.get(main) if main else None + if table is None: + continue + for variant in (body or {}).get("variants") or []: + for value in (variant or {}).values(): + if not (isinstance(value, str) and value.endswith((".yaml", ".yml"))): + continue + try: + doc = yaml.safe_load((base / value).read_text(encoding="utf-8")) + except (OSError, yaml.YAMLError): + continue + for effect in (doc or {}).get("effects") or []: + for column, bound in ((effect or {}).get("match") or {}).items(): + if not ( + isinstance(bound, Mapping) + and str(bound.get("param")) in actor_params + ): + continue + for fk in table.foreign_keys: + if fk.column == column: + targets.add((fk.table, fk.ref_column)) + if len(targets) != 1: + return None + users_table, key = next(iter(targets)) + return _learn.users_from(users_table, key, schema) + + +def propose( + episodes: Sequence[Mapping[str, Any]], users: Optional[_learn.Users] +) -> dict[str, Any]: + """The learner's proposal from probe episodes: a ``changed`` move seen + in any one read-only round is enough, since no round carried a task. + The relation to the acting user, not the count, decides. + + An ``added`` row is never admitted this way. Its excuse names columns, + not values, so it would also cover a row the agent itself adds for its + own user with any values (a first-login row the probe saw once, then a + different property the agent sets). Such moves go under + ``needs_approval``: a person approves them with ``learn approve``.""" + + eps = [dict(e, kind="read_only_probe") for e in episodes if e.get("probe")] + learnable = [e for e in eps if _learn._why_ignored(e) is None] + n = max(1, len(learnable)) + proposal = _learn.propose(eps, users=users, k=1, n=n, source="read-only probe") + for body in (proposal.get("kinds") or {}).values(): + kept, held = [], [] + for e in body.get("excuses") or []: + (held if e.get("change") == "added" else kept).append(e) + for e in held: + e.pop("id", None) + e["why_not"] = ( + "an added row: its excuse names columns, not values, so a " + "person approves it (learn approve)" + ) + body["excuses"] = kept + body["needs_approval"] = held + proposal.pop("proposal_sha256", None) + proposal["proposal_sha256"] = _learn.proposal_digest(proposal) + return proposal + + +def apply( + proposal: Mapping[str, Any], + contracts: Sequence[Path], +) -> list[tuple[Path, int]]: + """Write the probe's excuses into each contract's ``frame.learned``, all + or none. A contract gets only the excuses whose columns it doesn't name + itself; one with a ``frame.learned`` already is refused (a person + reconciles two sets of excuses).""" + + import yaml + + from openadapt_flow.verifier import Contract, VerifierError + + block = _learn.learned_block(proposal, "read_only_probe", PROBE_APPROVER) + if block is None: + return [] + plan: list[tuple[Path, dict[str, Any], int]] = [] + for path in contracts: + try: + data = yaml.safe_load(Path(path).read_text(encoding="utf-8")) or {} + except (OSError, yaml.YAMLError) as exc: + raise ProbeError(f"can't read {path}: {exc}") from exc + frame = data.get("frame") if isinstance(data, dict) else None + if not isinstance(frame, dict) or not frame.get("database"): + continue # no whole-database frame: nothing to excuse + if frame.get("learned"): + raise ProbeError( + f"{path}: frame.learned is already set; reconcile it by hand" + ) + try: + names: set[str] = set() + loaded = Contract.from_dict(data, name=Path(path).stem) + for n in _learn.contract_fields(loaded): + names |= _learn._names(n) + except VerifierError as exc: + raise ProbeError(f"{path}: {exc}") from exc + excuses = [ + e + for e in block["excuses"] + if not any(_learn._names(c) & names for c in e["columns"]) + ] + if not excuses: + continue + new = dict(data) + new["frame"] = { + **frame, + "learned": {**block, "excuses": excuses, "source": "read_only_probe"}, + } + try: + Contract.from_dict(new, name=Path(path).stem) + except VerifierError as exc: + raise ProbeError(f"{path}: {exc}") from exc + plan.append((Path(path), new, len(excuses))) + _learn._write_all( + [ + (path, yaml.safe_dump(new, sort_keys=False, allow_unicode=True)) + for path, new, _n in plan + ] + ) + return [(path, n) for path, _new, n in plan] + + +def http_sender( + base_url: str, headers: Mapping[str, str], requests: Sequence[tuple[str, str]] +) -> Callable[[], set[str]]: + """A ``send`` for :func:`probe`: each read-only request, in order.""" + + import requests as _requests + + check_read_only(requests) + + def send() -> set[str]: + names: set[str] = set() + for method, path in requests: + url = base_url.rstrip("/") + "/" + path.lstrip("/") + _requests.request(method.upper(), url, headers=dict(headers), timeout=60) + names |= _learn.query_fields(path) + return names + + return send + + +def write_report(proposal: Mapping[str, Any], out: Path) -> Path: + out.mkdir(parents=True, exist_ok=True) + path = out / "probe_proposal.json" + path.write_text(json.dumps(proposal, indent=2, sort_keys=True) + "\n") + return path + + +def cmd_probe(args: Any) -> int: + """``openadapt-flow learn probe``.""" + + import os + + import yaml + + from openadapt_flow.generate.verify_contract import choose + + try: + requests = [] + for spec in args.get or []: + requests.append(("GET", spec)) + for spec in args.head or []: + requests.append(("HEAD", spec)) + check_read_only(requests) + headers = ( + json.loads(os.environ.get(args.headers_env, "{}")) + if args.headers_env + else {} + ) + if not isinstance(headers, dict): + raise ProbeError(f"{args.headers_env} must hold a JSON object of headers") + values = yaml.safe_load(Path(args.values).read_text(encoding="utf-8")) or {} + extra = dict(yaml.safe_load(args.extra) or {}) if args.extra else {} + contract, params = choose(Path(args.manifest), args.kind, values, extra) + schema = _learn._schema(args) + users: Optional[_learn.Users] + if args.users: + table, _, key = args.users.partition(".") + users = _learn.users_from(table, key or None, schema, args.user_column) + else: + users = users_for_actor_params(Path(args.manifest), schema) + send = http_sender(args.base_url, headers, requests) + eps = probe(contract, params, kind=args.kind, actor=args.actor, send=send, + rounds=args.rounds) # fmt: skip + proposal = propose(eps, users) + report = write_report(proposal, Path(args.out)) + written: list[tuple[Path, int]] = [] + if args.apply: + files = [p for ps in _learn.contracts_from_manifest(Path(args.manifest)).values() + for p in ps] # fmt: skip + written = apply(proposal, sorted(set(files))) + except (_learn.LearnError, OSError, ValueError) as exc: + print(f"learn probe: {exc}", file=__import__("sys").stderr) + return 2 + body = (proposal.get("kinds") or {}).get("read_only_probe") or {} + print( + f"{len(body.get('excuses') or [])} excuse(s) learned from {len(eps)} read-only " + f"round(s); {len(body.get('stays_a_stop') or [])} move(s) stay a stop. " + f"Report: {report}." + + ( + f" Written into {len(written)} contract(s)." + if args.apply + else " Run again with --apply to write them into the contracts." + ) + ) + return 0 + + +def add_parser(steps: Any) -> None: + """The ``probe`` step of ``openadapt-flow learn``.""" + + p = steps.add_parser( + "probe", + help="learn per-request bookkeeping from read-only requests (no approval)", + allow_abbrev=False, + ) + p.add_argument("--manifest", required=True, help="the generator's manifest.yaml") + p.add_argument( + "--kind", required=True, help="the kind whose contract frames the probe" + ) + p.add_argument( + "--values", required=True, help="YAML: one task's values for that kind" + ) + p.add_argument("--extra", default=None, help="YAML: extra parameters (actor ids)") + p.add_argument("--actor", required=True, help="the agent's user id in the app") + p.add_argument("--base-url", required=True) + p.add_argument("--headers-env", default=None, + help="environment variable holding the agent's request headers as JSON") # fmt: skip + p.add_argument("--get", action="append", default=[], metavar="PATH") + p.add_argument("--head", action="append", default=[], metavar="PATH") + p.add_argument("--rounds", type=int, default=DEFAULT_ROUNDS) + p.add_argument( + "--users", default=None, help="TABLE or TABLE.KEY (default: derived)" + ) + p.add_argument("--user-column", action="append", default=[], metavar="TABLE.COLUMN") + p.add_argument("--schema", default=None) + p.add_argument("--read", default=None) + p.add_argument("--out", default="learn") + p.add_argument("--apply", action="store_true", + help="write the excuses into every contract the manifest lists") # fmt: skip + p.set_defaults(func=cmd_probe) diff --git a/packages/flow/openadapt_flow/runtime/effects/frame.py b/packages/flow/openadapt_flow/runtime/effects/frame.py index bfb3549466..a3f3f0daeb 100644 --- a/packages/flow/openadapt_flow/runtime/effects/frame.py +++ b/packages/flow/openadapt_flow/runtime/effects/frame.py @@ -762,6 +762,7 @@ def evidence(self, spec: FrameSpec) -> dict[str, Any]: "learned": { "proposal_sha256": spec.learned.proposal_sha256, "excuses": len(spec.learned.excuses), + "source": spec.learned.source, "used": sorted(self.learned_used), } } diff --git a/packages/flow/openadapt_flow/runtime/effects/learned.py b/packages/flow/openadapt_flow/runtime/effects/learned.py index 1319afb462..b8be628ae7 100644 --- a/packages/flow/openadapt_flow/runtime/effects/learned.py +++ b/packages/flow/openadapt_flow/runtime/effects/learned.py @@ -129,7 +129,8 @@ def label(self) -> str: class LearnedFrame(BaseModel): - """``frame.learned``: the excuses a person approved from a proposal.""" + """``frame.learned``: the excuses a person approved from a proposal, or + that a read-only probe observed (``source: read_only_probe``).""" model_config = ConfigDict(extra="forbid") @@ -138,6 +139,11 @@ class LearnedFrame(BaseModel): proposal_sha256: str approved_by: str = Field(min_length=1) approved_at: str = Field(min_length=1) + #: ``approval``: a person approved the learner's proposal from checked + #: writes. ``read_only_probe``: rows the app moved while the agent sent + #: only read-only requests (``learn_probe``); the same relation rules + #: apply at check time. + source: Literal["approval", "read_only_probe"] = "approval" @field_validator("proposal_sha256") @classmethod diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py new file mode 100644 index 0000000000..063718f504 --- /dev/null +++ b/packages/flow/tests/test_learn_probe.py @@ -0,0 +1,349 @@ +"""Learning per-request bookkeeping from read-only requests (learn_probe). + +A read-only probe reads the whole-database frame, sends GETs as the agent +and reads again; rows of the acting user that moved become ``frame.learned`` +excuses with ``source: read_only_probe``. These tests check that a correct +write then passes, and attack what the probe must never excuse: another +user's row, another column of the actor's row, a column the contract names, +a row no user owns, extra added rows, and a probe that writes. Each runs on +SQLite, and on MariaDB/MySQL and PostgreSQL when a scratch server is given +(see ``test_learned_excuses``). Records are made up. +""" + +from __future__ import annotations + +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from openadapt_flow import learn, learn_probe +from openadapt_flow.generate.sql_store import Column, ForeignKey, Schema, Table +from openadapt_flow.verifier import Contract +from tests import test_learned_excuses as _le +from tests.test_learned_excuses import ( + ACTOR, + Engine, + _refuted, + _title, + check, + note_contract, +) + +# The engines (SQLite, and MySQL or PostgreSQL when given) and the private +# ledger and seal homes, shared with test_learned_excuses. +engine = _le.engine +_homes = _le._homes + +_n = [0] + + +def _t(name: str, cols: list[str], pk: list[str], fks: list[ForeignKey] = ()) -> Table: + columns = [Column(c, "varchar", True, None) for c in cols] + return Table(name, columns, pk, list(fks)) + + +def _schema(tables: list[Table]) -> Schema: + return Schema("sqlite", "app", {t.name: t for t in tables}) + + +def _stamp() -> str: + _n[0] += 1 + return f"p{_n[0]}" + + +def app_reads(e: Engine, user: str = ACTOR, first: bool = True) -> None: + """What the app writes when ``user`` sends any request: the user's + last-login time and token use, and once a first-login property row.""" + + s = _stamp() + e.run("UPDATE app_user SET last_login = %s WHERE id = %s", s, int(user)) + e.run("UPDATE api_token SET last_seen = %s WHERE user_id = %s", s, int(user)) + if first: + e.run( + "INSERT INTO user_property (user_id, property, value) VALUES (%s, %s, %s)", + int(user), + f"first.{s}", + s, + ) + + +def users(e: Engine) -> learn.Users: + schema = _schema( + [ + _t("app_user", ["id", "name", "email", "last_login"], ["id"]), + _t( + "api_token", + ["id", "user_id", "issued_by", "label", "last_seen"], + ["id"], + [ + ForeignKey("user_id", "app_user", "id"), + ForeignKey("issued_by", "app_user", "id"), + ], + ), + _t( + "user_property", + ["user_id", "property", "value"], + ["user_id", "property"], + [ForeignKey("user_id", "app_user", "id")], + ), + _t("note", ["id", "title", "body", "stamp"], ["id"]), + ] + ) + return learn.users_from("app_user", "id", schema) + + +def run_probe(e: Engine, tmp_path: Path, send: Any, rounds: int = 3) -> dict: + c = Contract.from_dict(note_contract(e), name="note") + eps = learn_probe.probe( + c, + {"title": "Probe note", "body": "x"}, + kind="add_note", + actor=ACTOR, + send=send, + rounds=rounds, + workdir=tmp_path / "probe", + ) + return learn_probe.propose(eps, users(e)) + + +def excuses_of(proposal: dict) -> list[dict]: + return proposal["kinds"]["read_only_probe"]["excuses"] + + +def write_contract(e: Engine, tmp_path: Path, proposal: dict) -> dict[str, Any]: + path = tmp_path / "note.yaml" + path.write_text(yaml.safe_dump(note_contract(e))) + written = learn_probe.apply(proposal, [path]) + assert written and written[0][0] == path + data = yaml.safe_load(path.read_text()) + assert data["frame"]["learned"]["source"] == "read_only_probe" + return data + + +def first_once(e: Engine) -> Any: + seen = [False] + + def send() -> set[str]: + app_reads(e, first=not seen[0]) + seen[0] = True + return {"q"} + + return send + + +def test_probe_learns_the_actors_bookkeeping_and_a_correct_write_passes( + engine: Engine, tmp_path: Path +) -> None: + t = _title() + + def write(first: bool = False) -> None: + app_reads(engine, first=first) + engine.run("INSERT INTO note (title, body) VALUES (%s, %s)", t, "Body text") + + before = check( + engine, + note_contract(engine), + {"title": t, "body": "Body text"}, + write, + tmp_path, + ) + _refuted(before) + + proposal = run_probe(engine, tmp_path, first_once(engine)) + got = {(x["table"], x["change"], tuple(x["columns"])) for x in excuses_of(proposal)} + assert got == { + ("app_user", "changed", ("last_login",)), + ("api_token", "changed", ("last_seen",)), + } + # The first-login row the probe saw is an added row: held for a person. + held = proposal["kinds"]["read_only_probe"]["needs_approval"] + assert [(x["table"], x["change"]) for x in held] == [("user_property", "added")] + contract = write_contract(engine, tmp_path, proposal) + t = _title() + after = check(engine, contract, {"title": t, "body": "Body text"}, write, tmp_path) + assert after.outcome.value == "CONFIRMED", after.reasons + assert after.evidence["frame"]["learned"]["source"] == "read_only_probe" + # A row the app adds for the actor still stops until a person approves it. + t = _title() + _refuted( + check( + engine, + contract, + {"title": t, "body": "Body text"}, + lambda: write(first=True), + tmp_path, + ) # fmt: skip + ) + + +def _learned(engine: Engine, tmp_path: Path) -> dict[str, Any]: + return write_contract( + engine, tmp_path, run_probe(engine, tmp_path, first_once(engine)) + ) + + +@pytest.mark.parametrize( + "harm", + [ + "UPDATE app_user SET last_login = 'x' WHERE id = 3", + "UPDATE app_user SET email = 'changed@example.test' WHERE id = 2", + "UPDATE app_user SET last_login = 'x', email = 'e@example.test' WHERE id = 2", + "UPDATE api_token SET last_seen = 'x' WHERE user_id = 3", + "INSERT INTO user_property (user_id, property, value) VALUES (3, 'a', 'b')", + "INSERT INTO user_property (user_id, property, value) VALUES (2, 'extra', 'b')", + "DELETE FROM api_token WHERE user_id = 2", + ], +) +def test_probe_excuses_never_cover_a_harm( + engine: Engine, tmp_path: Path, harm: str +) -> None: + contract = _learned(engine, tmp_path) + t = _title() + + def act() -> None: + app_reads(engine, first=False) + engine.run("INSERT INTO note (title, body) VALUES (%s, %s)", t, "Body text") + engine.run(harm) + + _refuted(check(engine, contract, {"title": t, "body": "Body text"}, act, tmp_path)) + + +def test_a_row_no_user_owns_is_never_learned(engine: Engine, tmp_path: Path) -> None: + def send() -> set[str]: + app_reads(engine, first=False) + # A row that moves on every read but belongs to no user: listed as a + # stop, never excused. + engine.run("UPDATE asset SET modified_at = %s WHERE id = 1", _stamp()) + return set() + + proposal = run_probe(engine, tmp_path, send) + body = proposal["kinds"]["read_only_probe"] + assert {x["table"] for x in body["excuses"]} == {"app_user", "api_token"} + assert any(s["table"] == "asset" for s in body["stays_a_stop"]) + + +def test_another_users_row_moving_in_the_window_is_never_learned( + engine: Engine, tmp_path: Path +) -> None: + def send() -> set[str]: + app_reads(engine, first=False) + app_reads(engine, user="3", first=False) # a colleague, at the same time + return set() + + proposal = run_probe(engine, tmp_path, send) + body = proposal["kinds"]["read_only_probe"] + for x in body["excuses"]: + assert x["relation"] == "actor_row" + contract = write_contract(engine, tmp_path, proposal) + t = _title() + + def act() -> None: + app_reads(engine, first=False) + app_reads(engine, user="3", first=False) + engine.run("INSERT INTO note (title, body) VALUES (%s, %s)", t, "Body text") + + _refuted(check(engine, contract, {"title": t, "body": "Body text"}, act, tmp_path)) + + +def test_a_column_the_probe_or_contract_names_is_never_learned( + engine: Engine, tmp_path: Path +) -> None: + def send() -> set[str]: + app_reads(engine, first=False) + return {"last_login"} # the probe's query named it + + proposal = run_probe(engine, tmp_path, send) + tables = {x["table"] for x in excuses_of(proposal)} + assert "app_user" not in tables and "api_token" in tables + + +def test_nothing_moves_nothing_is_learned(engine: Engine, tmp_path: Path) -> None: + proposal = run_probe(engine, tmp_path, lambda: set()) + assert excuses_of(proposal) == [] + path = tmp_path / "note.yaml" + path.write_text(yaml.safe_dump(note_contract(engine))) + assert learn_probe.apply(proposal, [path]) == [] + assert "learned" not in yaml.safe_load(path.read_text())["frame"] + + +def test_without_a_users_table_nothing_is_learned( + engine: Engine, tmp_path: Path +) -> None: + c = Contract.from_dict(note_contract(engine), name="note") + eps = learn_probe.probe(c, {"title": "P", "body": "x"}, kind="k", actor=ACTOR, + send=first_once(engine), rounds=2, + workdir=tmp_path / "p") # fmt: skip + assert excuses_of(learn_probe.propose(eps, None)) == [] + + +def test_a_probe_sends_read_only_requests_only() -> None: + for bad in ("POST", "PUT", "PATCH", "DELETE"): + with pytest.raises(learn_probe.ProbeError): + learn_probe.check_read_only([("GET", "/a"), (bad, "/b")]) + with pytest.raises(learn_probe.ProbeError): + learn_probe.check_read_only([]) + learn_probe.check_read_only([("GET", "/a"), ("head", "/b")]) + + +def test_a_contract_with_learned_excuses_is_not_overwritten( + engine: Engine, tmp_path: Path +) -> None: + proposal = run_probe(engine, tmp_path, first_once(engine)) + path = tmp_path / "note.yaml" + path.write_text(yaml.safe_dump(note_contract(engine))) + learn_probe.apply(proposal, [path]) + with pytest.raises(learn_probe.ProbeError): + learn_probe.apply(proposal, [path]) + + +def test_users_table_from_the_manifests_actor_parameter(tmp_path: Path) -> None: + schema = _schema( + [ + _t("app_user", ["id"], ["id"]), + _t( + "entry", + ["id", "owner", "title"], + ["id"], + [ForeignKey("owner", "app_user", "id")], + ), # fmt: skip + ] + ) + (tmp_path / "c.yaml").write_text( + yaml.safe_dump( + { + "effects": [ + { + "kind": "record_written", + "match": { + "owner": {"param": "bot_user_id"}, + "title": {"param": "title"}, + }, + } + ] + } # fmt: skip + ) + ) + + def manifest(actor_params: list[str]) -> Path: + m = tmp_path / "manifest.yaml" + m.write_text( + yaml.safe_dump( + { + "actor_params": actor_params, + "kinds": { + "add_entry": { + "main_table": "entry", + "variants": [{"create": "c.yaml"}], + } + }, + } # fmt: skip + ) + ) + return m + + u = learn_probe.users_for_actor_params(manifest(["bot_user_id"]), schema) + assert u is not None and (u.table, u.key) == ("app_user", "id") + assert learn_probe.users_for_actor_params(manifest([]), schema) is None + assert learn_probe.users_for_actor_params(manifest(["other"]), schema) is None From 53910b3c4e3af4550e970e1580fd8db8757399aa Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 01:16:06 -0500 Subject: [PATCH 2/8] fix(flow): no probe excuse for an update that can't see a lost update; capability row --- CAPABILITIES.md | 1 + llms-full.txt | 5 ++- packages/flow/docs/LEARNED_EXCUSES.md | 8 +++- packages/flow/openadapt_flow/learn_probe.py | 30 ++++++++++++- packages/flow/tests/test_learn_probe.py | 48 ++++++++++++++++++++- 5 files changed, 86 insertions(+), 6 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index ac77f23fe3..379543a346 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -184,6 +184,7 @@ improvising or retrying when something is off. | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | +| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | diff --git a/llms-full.txt b/llms-full.txt index c74a23a193..32d454bc26 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -618,6 +618,7 @@ improvising or retrying when something is off. | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | +| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | @@ -752,7 +753,7 @@ 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` | +| 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`. 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` | | Wrapped tasks that sign in: during `openadapt wrap`'s first run the recorder finds a password field (`type=password`, or `autocomplete` `current-password`/`new-password`) and the username field paired with it (`autocomplete=username`, or a unique text, email or phone candidate paired across all password controls in the composed form; ambiguous or unreadable controls refuse declared inputs) from the page's markup alone. Automatic withholding requires that observation seam; a missing or noncallable seam refuses before capture or actor entry. Screen-only native backends use the existing explicit person-secret handoff instead of this automatic path. Their inputs become secret parameters: the recording, program, run records, receipts and publish upload keep the name and never the value, the observed field regions are blacked out in recording frames (arbitrary field movement or echoes are not proven redacted), a credential field given text that matches no declared input is refused before typing, a form with exactly a username and current password is classified as sign-in without lowering independent keyword risk, and replay run screenshots contain black frames while checks use the original pixels in memory. Secret environment/vault aliases must be unambiguous, and managed params files cannot supply secret values. The canary and cached runs type them from `OPENADAPT_FLOW_SECRET_`, set from memory for one run; `publish` lists them as `secret_parameters`, outside the call's inputs | In PR [#2294](https://github.com/OpenAdaptAI/OpenAdapt/pull/2294) | Synthetic (a sign-in notes app in headless Chromium through the real wrap path: first run, canary, admission, publish staging, and a cached run under mcp 2, with a byte scan for the values in every file; unit tests with a fake backend for detection, frame redaction, refusals and the sign-in submit rule). Genuine RDP/Citrix backends refuse automatic withholding before input; explicit person-secret handoff remains tested. Hosted runs need an endpoint vault set (openadapt-cloud) | `openadapt_flow.recorder` (`withhold_credentials`), `openadapt_flow.secret_inputs`, [WRAP_PUBLISH.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/WRAP_PUBLISH.md#tasks-that-sign-in), `packages/flow/tests/test_wrap_sign_in.py`, `packages/flow/tests/e2e/test_wrap_sign_in_e2e.py` | | Verified write tools for agent frameworks: `verified(tool, contract=...)` wraps a Claude Agent SDK, OpenAI Agents SDK, LangGraph or CrewAI write tool in one line. The contract and any values the operator pins come from the operator, never the agent's arguments; the store is read before and after; the agent gets a receipt or a refusal, and a refused write is held instead of retried | Released | Synthetic (each framework's own agent loop with a scripted model, writing through the example app's order form over real HTTP: verified save, a save the app drops, a save it keeps twice); one real-model run per framework, opt-in | `openadapt_flow.integrations.agents`, extras `claude-agent-sdk`, `openai-agents`, `langgraph` (CrewAI: install `crewai` beside it); [AGENT_FRAMEWORKS.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/AGENT_FRAMEWORKS.md) | | Teach a browser write as a verified tool: with write contracts and a person's signed teach authorization (`serve --teach-browser --contracts DIR --teach-authorization STATEMENT`), the agent teaches a save once. Run 1 starts only when the statement covers the write (origin, contract, write adapter, the record's fields and values) and runs under it; it is verified in the system of record before the `taught_` tool exists. Every call checks the statement and the tool's signature again, makes the write and returns a verified receipt or a refusal. Sign-in values come from the server's environment and never reach the agent or the program. Controls in named iframes are found through their frame | On main ([#1589](https://github.com/OpenAdaptAI/OpenAdapt/pull/1589), [#1763](https://github.com/OpenAdaptAI/OpenAdapt/pull/1763)) | Synthetic (the example app's sign-in and order form in headless Chromium over MCP: verified save, a save the app drops, a save it keeps twice, a page that swaps the record during run 1; refusals for a missing, uncovering, expired, edited or wrongly signed statement) | `openadapt-agent serve --teach-browser --contracts --teach-authorization`, [VERIFY_WRITES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_WRITES.md#teach-a-write-as-a-tool) | @@ -915,7 +916,7 @@ A test fails when a command has no file or this list is out of date. **Guard an agent you already run:** - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, and hands a verified run to the teach dir. -- `learn`: Learn the app's own per-request writes from a shadow run, propose excuses, and approve them into the contracts. +- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), and write them into the contracts. - `shadow`: Shadow an agent: check each write it makes through an HTTP proxy, or check announced database actions for a desktop client, against the system of record without blocking it, and report. diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index 036f76c48a..f3fa7e3e38 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -217,7 +217,13 @@ learned unless you name it (`--users`). `--apply` writes the excuses into every contract the manifest lists, with `frame.learned.source: read_only_probe`, and leaves out of each contract -any excuse for a column that contract names. No person approves them: the +any excuse for a column that contract names. It writes them only into a +contract whose frame can see a lost update without the bookkeeping move: +one whose every declared record is new (`count_new_only`), or one that +reads the target's versions (`frame.versions`). In an update with no +version source, another user's edit that the agent's stale save reverts +leaves nothing changed, and only the bookkeeping move stopped it, so such +contracts keep stopping. No person approves them: the rows were read, the relation is derived from the schema, and the requests are checked to be read-only. A contract that already has `frame.learned` is refused, so a person reconciles the two. Receipts name the source. diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 57e5d7842a..b984ae9c2e 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -228,8 +228,9 @@ def apply( ) -> list[tuple[Path, int]]: """Write the probe's excuses into each contract's ``frame.learned``, all or none. A contract gets only the excuses whose columns it doesn't name - itself; one with a ``frame.learned`` already is refused (a person - reconciles two sets of excuses).""" + itself, and only when it creates new records or reads the target's + versions (:func:`_sees_its_own_harm`); one with a ``frame.learned`` + already is refused (a person reconciles two sets of excuses).""" import yaml @@ -258,6 +259,12 @@ def apply( names |= _learn._names(n) except VerifierError as exc: raise ProbeError(f"{path}: {exc}") from exc + if not _sees_its_own_harm(loaded): + # An update (or a found check) with no version source: another + # user's edit that the agent's stale save reverts leaves nothing + # changed, so before learning only the bookkeeping move stopped + # it. Such a contract gets no automatic excuse. + continue excuses = [ e for e in block["excuses"] @@ -284,6 +291,25 @@ def apply( return [(path, n) for path, _new, n in plan] +def _sees_its_own_harm(contract: Any) -> bool: + """May a probe excuse go into this (loaded) contract? Only when the + frame can see a lost update without the bookkeeping move: every + declared record is new (each ``record_written`` effect counts new rows + only), or the contract reads the target's versions (``frame.versions``).""" + + config = getattr(contract, "config", None) + frame = getattr(config, "frame", None) + if frame is not None and getattr(frame, "versions", None) is not None: + return True + records = [ + e.model_dump(mode="json") + for e in getattr(config, "effects", None) or [] + if str(getattr(getattr(e, "kind", None), "value", getattr(e, "kind", ""))) + == "record_written" + ] + return bool(records) and all(r.get("count_new_only") is True for r in records) + + def http_sender( base_url: str, headers: Mapping[str, str], requests: Sequence[tuple[str, str]] ) -> Callable[[], set[str]]: diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index 063718f504..e27c4c2bee 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -27,9 +27,10 @@ Engine, _refuted, _title, + asset_contract, check, - note_contract, ) +from tests.test_learned_excuses import note_contract as _note_contract # The engines (SQLite, and MySQL or PostgreSQL when given) and the private # ledger and seal homes, shared with test_learned_excuses. @@ -39,6 +40,23 @@ _n = [0] +def note_contract(e: Engine) -> dict[str, Any]: + """Create a note: one new record (``count_new_only``), nothing else.""" + + doc = _note_contract(e) + doc.pop("record") + doc["effects"] = [ + { + "kind": "record_written", + "match": {"title": {"param": "title"}, "body": {"param": "body"}}, + "expected_count": 1, + "count_new_only": True, + "identity_field": "id", + } + ] + return doc + + def _t(name: str, cols: list[str], pk: list[str], fks: list[ForeignKey] = ()) -> Table: columns = [Column(c, "varchar", True, None) for c in cols] return Table(name, columns, pk, list(fks)) @@ -347,3 +365,31 @@ def manifest(actor_params: list[str]) -> Path: assert u is not None and (u.table, u.key) == ("app_user", "id") assert learn_probe.users_for_actor_params(manifest([]), schema) is None assert learn_probe.users_for_actor_params(manifest(["other"]), schema) is None + + +def test_an_update_without_a_version_source_gets_no_probe_excuse( + engine: Engine, tmp_path: Path +) -> None: + # Another user's edit that the agent's stale save reverts leaves the + # target unchanged. Without versions, only the bookkeeping move stopped + # such a write, so an update contract with no version source keeps it. + proposal = run_probe(engine, tmp_path, first_once(engine)) + assert excuses_of(proposal) + path = tmp_path / "asset.yaml" + path.write_text(yaml.safe_dump(asset_contract(engine))) + assert learn_probe.apply(proposal, [path]) == [] + assert "learned" not in yaml.safe_load(path.read_text())["frame"] + + def act() -> None: + app_reads(engine, first=False) + engine.run("UPDATE asset SET name = 'Laptop B' WHERE id = 1") + + _refuted( + check( + engine, + yaml.safe_load(path.read_text()), + {"tag": "LT-100", "name": "Laptop B"}, + act, + tmp_path, + ) # fmt: skip + ) From f1d7a65833b626b169fcb16ecefa895c643340d0 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:54:05 -0500 Subject: [PATCH 3/8] fix(flow): a probe excuses only a move every round shows; no excuse beside an update the versions don't cover Review blockers on #2413: - A move must show in every read-only round (at least two), so a one-off edit to the acting user's own row during one round is not excused. - _sees_its_own_harm judged only record_written effects. Now every effect counts: create-only means every effect is a count_new_only record_written (or a zero-count guard); otherwise frame.versions must cover each other effect on its target_surface. - Annotate the kept/held lists (mypy). - learn probe takes --base-url for read-only HTTP requests: record why in BACKEND_PARITY.md's URL flags table. - Rename learn_probe.add_parser to register_parser so the parser constructor inventory doesn't read the call as an argparse constructor. --- packages/flow/docs/BACKEND_PARITY.md | 1 + packages/flow/openadapt_flow/learn.py | 2 +- packages/flow/openadapt_flow/learn_probe.py | 80 +++++++++++++++------ packages/flow/tests/test_learn_probe.py | 72 ++++++++++++++++++- 4 files changed, 131 insertions(+), 24 deletions(-) diff --git a/packages/flow/docs/BACKEND_PARITY.md b/packages/flow/docs/BACKEND_PARITY.md index f82f749236..d43679092f 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 learn probe` | `--base-url` | The probe sends read-only HTTP requests (`GET`, `HEAD`) to the app's API as the agent; it drives no UI, so there is no backend to choose. The frame it reads comes from the contract's `frame.database`. | diff --git a/packages/flow/openadapt_flow/learn.py b/packages/flow/openadapt_flow/learn.py index 0fee10dbac..eb11a04cf6 100644 --- a/packages/flow/openadapt_flow/learn.py +++ b/packages/flow/openadapt_flow/learn.py @@ -950,7 +950,7 @@ def build_parser(p: argparse.ArgumentParser) -> argparse.ArgumentParser: from openadapt_flow import learn_probe - learn_probe.add_parser(steps) + learn_probe.register_parser(steps) return p diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index b984ae9c2e..8d55ecf303 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -50,6 +50,10 @@ #: The ``frame.learned.approved_by`` of a probe's excuses. PROBE_APPROVER = "read-only probe (openadapt-flow learn probe)" DEFAULT_ROUNDS = 3 +#: A move is excused only when every one of at least this many rounds shows +#: it: per-request bookkeeping moves on every request, while a one-off edit +#: (a person changing the acting user's own row during a round) does not. +MIN_ROUNDS = 2 class ProbeError(_learn.LearnError): @@ -117,8 +121,8 @@ def probe( from openadapt_flow.verifier import Actor, begin_write, verify_write - if rounds < 1: - raise ProbeError("a probe runs at least one round") + if rounds < MIN_ROUNDS: + raise ProbeError(f"a probe runs at least {MIN_ROUNDS} rounds") config = getattr(contract, "config", None) frame = getattr(config, "frame", None) if frame is None or getattr(frame, "database", None) is None: @@ -191,9 +195,10 @@ def users_for_actor_params(manifest_path: Path, schema: Any) -> Optional[_learn. def propose( episodes: Sequence[Mapping[str, Any]], users: Optional[_learn.Users] ) -> dict[str, Any]: - """The learner's proposal from probe episodes: a ``changed`` move seen - in any one read-only round is enough, since no round carried a task. - The relation to the acting user, not the count, decides. + """The learner's proposal from probe episodes: a ``changed`` move must + show in every read-only round (at least :data:`MIN_ROUNDS`), so a + one-off edit to the acting user's own row during one round is not + excused. The relation to the acting user then decides. An ``added`` row is never admitted this way. Its excuse names columns, not values, so it would also cover a row the agent itself adds for its @@ -204,9 +209,19 @@ def propose( eps = [dict(e, kind="read_only_probe") for e in episodes if e.get("probe")] learnable = [e for e in eps if _learn._why_ignored(e) is None] n = max(1, len(learnable)) - proposal = _learn.propose(eps, users=users, k=1, n=n, source="read-only probe") + proposal = _learn.propose(eps, users=users, k=n, n=n, source="read-only probe") + # A round that showed no usable move (nothing moved, or no frame) means + # the move isn't per-request bookkeeping; too few rounds can't tell. + every_round = len(learnable) >= MIN_ROUNDS and len(learnable) == len(eps) for body in (proposal.get("kinds") or {}).values(): - kept, held = [], [] + if not every_round: + body["excuses"] = [] + body["not_learned"] = ( + f"a move is excused only when all of at least {MIN_ROUNDS} " + f"read-only rounds show it ({len(learnable)} of {len(eps)} did)" + ) + kept: list[dict[str, Any]] = [] + held: list[dict[str, Any]] = [] for e in body.get("excuses") or []: (held if e.get("change") == "added" else kept).append(e) for e in held: @@ -293,21 +308,46 @@ def apply( def _sees_its_own_harm(contract: Any) -> bool: """May a probe excuse go into this (loaded) contract? Only when the - frame can see a lost update without the bookkeeping move: every - declared record is new (each ``record_written`` effect counts new rows - only), or the contract reads the target's versions (``frame.versions``).""" + frame can see a lost update without the bookkeeping move. + + Either every declared effect creates new records (``record_written`` + with ``count_new_only``; a zero-count guard writes nothing), or the + contract reads the target's versions (``frame.versions``) and those + versions cover every other effect: with a ``target_surface``, each + effect that isn't a create must be read on that surface. Anything else, + such as a create plus a ``field_equals`` update, gets no excuse.""" + + from openadapt_flow.runtime.effects.surfaces import surface_of config = getattr(contract, "config", None) frame = getattr(config, "frame", None) - if frame is not None and getattr(frame, "versions", None) is not None: - return True - records = [ - e.model_dump(mode="json") - for e in getattr(config, "effects", None) or [] - if str(getattr(getattr(e, "kind", None), "value", getattr(e, "kind", ""))) - == "record_written" - ] - return bool(records) and all(r.get("count_new_only") is True for r in records) + effects = list(getattr(config, "effects", None) or []) + + def kind(effect: Any) -> str: + k = getattr(effect, "kind", "") + return str(getattr(k, "value", k)) + + def creates(effect: Any) -> bool: + return ( + kind(effect) == "record_written" + and getattr(effect, "count_new_only", None) is True + and getattr(effect, "expected_count", 1) != 0 + ) + + def guard(effect: Any) -> bool: + return ( + kind(effect) == "record_written" + and getattr(effect, "expected_count", 1) == 0 + ) + + others = [e for e in effects if not creates(e) and not guard(e)] + if not others: + return any(creates(e) for e in effects) + versions = getattr(frame, "versions", None) if frame is not None else None + if versions is None: + return False + surface = getattr(versions, "target_surface", None) + return surface is None or all(surface_of(e) == surface for e in others) def http_sender( @@ -397,7 +437,7 @@ def cmd_probe(args: Any) -> int: return 0 -def add_parser(steps: Any) -> None: +def register_parser(steps: Any) -> None: """The ``probe`` step of ``openadapt-flow learn``.""" p = steps.add_parser( diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index e27c4c2bee..4499093a46 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -175,9 +175,9 @@ def write(first: bool = False) -> None: ("app_user", "changed", ("last_login",)), ("api_token", "changed", ("last_seen",)), } - # The first-login row the probe saw is an added row: held for a person. - held = proposal["kinds"]["read_only_probe"]["needs_approval"] - assert [(x["table"], x["change"]) for x in held] == [("user_property", "added")] + # The first-login row showed in one round only: not bookkeeping, so it is + # neither excused nor held for approval; it stays a stop. + assert proposal["kinds"]["read_only_probe"]["needs_approval"] == [] contract = write_contract(engine, tmp_path, proposal) t = _title() after = check(engine, contract, {"title": t, "body": "Body text"}, write, tmp_path) @@ -393,3 +393,69 @@ def act() -> None: tmp_path, ) # fmt: skip ) + + +def test_a_move_in_one_round_only_is_not_excused( + engine: Engine, tmp_path: Path +) -> None: + """A person editing the acting user's own row during one probe round + is not per-request bookkeeping: only moves every round shows are.""" + + rounds = [0] + + def send() -> set[str]: + app_reads(engine, first=False) + if rounds[0] == 0: + engine.run( + "UPDATE app_user SET email = %s WHERE id = %s", + f"{_stamp()}@example.test", + int(ACTOR), + ) + rounds[0] += 1 + return {"q"} + + got = { + (x["table"], tuple(x["columns"])) + for x in excuses_of(run_probe(engine, tmp_path, send)) + } + assert not any(t == "app_user" and "email" in cols for t, cols in got) + # The token row moved the same way every round: still bookkeeping. + assert ("api_token", ("last_seen",)) in got + + +def test_one_round_learns_nothing(engine: Engine, tmp_path: Path) -> None: + with pytest.raises(learn_probe.ProbeError): + run_probe(engine, tmp_path, first_once(engine), rounds=1) + + +def test_a_create_plus_an_update_gets_no_probe_excuse( + engine: Engine, tmp_path: Path +) -> None: + """``record_written`` with ``count_new_only`` beside a ``field_equals`` + update is not create-only: the update can't see a lost update.""" + + proposal = run_probe(engine, tmp_path, first_once(engine)) + doc = note_contract(engine) + doc["effects"].append( + {"kind": "field_equals", "match": {"id": {"literal": "1"}}, + "field": "title", "value": {"param": "title"}} + ) # fmt: skip + path = tmp_path / "mixed.yaml" + path.write_text(yaml.safe_dump(doc)) + assert learn_probe.apply(proposal, [path]) == [] + assert "learned" not in yaml.safe_load(path.read_text())["frame"] + + +def test_versions_on_another_surface_do_not_cover_an_update() -> None: + from types import SimpleNamespace as NS + + from openadapt_flow.runtime.effects.effect import EffectKind + from openadapt_flow.runtime.effects.surfaces import surface_probe + + update = NS(kind=EffectKind.FIELD_EQUALS, probe=surface_probe("secondary"), + expected_count=1, count_new_only=False) # fmt: skip + versions = NS(target_surface="primary") + contract = NS(config=NS(frame=NS(versions=versions), effects=[update])) + assert learn_probe._sees_its_own_harm(contract) is False + contract.config.frame.versions = NS(target_surface=None) + assert learn_probe._sees_its_own_harm(contract) is True From 9397a64c87dc570ec53b7d32b921de6d4aed4062 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 11:55:47 -0500 Subject: [PATCH 4/8] docs(flow): learn probe excuses only moves every round shows --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- packages/flow/docs/LEARNED_EXCUSES.md | 15 ++++++++++----- 3 files changed, 12 insertions(+), 7 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 199b347f44..fcd0c0c3e6 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -184,7 +184,7 @@ improvising or retrying when something is off. | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | -| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | +| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user that every round (at least two) shows (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts whose every effect creates new records, or that read the target's versions on every other effect's surface, get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | diff --git a/llms-full.txt b/llms-full.txt index a56c7e6585..403484f60b 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -618,7 +618,7 @@ improvising or retrying when something is off. | Catch a write that lands after the verdict (a background job, a trigger, a delayed side record): a `CONFIRMED` with a recheck due is provisional (`provisional`, `recheck_due_at`); the recheck reads the whole database again and refutes the earlier result when a change since the post-save read has no explanation, and a recheck that doesn't confirm holds the write in the ledger. Run it from Python (`verifier.recheck`) or MCP (`verify_recheck`). A write after the recheck's read is not seen (`frame.database.recheck_after_s`, no default window) | Released ([#1639](https://github.com/OpenAdaptAI/OpenAdapt/pull/1639)); provisional result, MCP tool and ledger hold ([#1669](https://github.com/OpenAdaptAI/OpenAdapt/pull/1669)) | Real app (Dolibarr 21 and EspoCRM 10 on MariaDB 11.4, 180 s window: 4 of 4 planted late writes at 125 to 130 s refuted at the recheck, correct writes confirmed; EspoCRM's cron daemon needs its job tables declared; Redmine 6.1 on PostgreSQL 17, 180 s window: the first-contact study's late writes F19 and F20 refuted at the recheck, correct writes confirmed); synthetic (SQLite); opt-in live OpenEMR test | `openadapt_flow/verifier.py`, `runtime/effects/late_write.py`, [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#writes-that-land-later) | | Diff the whole database for the frame (`frame.database`) on SQLite, MySQL, MariaDB and PostgreSQL. On MySQL and MariaDB every column type is read exactly (binary strings, `BIT`, geometries and vectors as hex, `FLOAT` widened to `DOUBLE`, `JSON` as stored text, decimals at full precision). On PostgreSQL every column type is read as text by a declared rule in a session pinned to UTC and exact float output, and a type without a rule, a table the account can't read in full, or an unreadable sequence is refused. So a row the save adds, changes or removes outside the declared records, such as an extra planned call or a stream note, is refuted unless a declared effect, a side record, an attributed concurrent write or an allow-listed bookkeeping table explains it | Released ([#1661](https://github.com/OpenAdaptAI/OpenAdapt/pull/1661)); PostgreSQL ([#1673](https://github.com/OpenAdaptAI/OpenAdapt/pull/1673)) | Real app (Dolibarr 21 on MariaDB 11.4: all 387 tables read where the frame raised `TypeError`; EspoCRM on MariaDB 11.4: the first-contact study's extra call and stream note refuted, correct opportunities verified; Redmine 6.1 on PostgreSQL 17: 58 tables read, a stray upload in a table the contract doesn't read refuted, correct writes verified); live MariaDB and PostgreSQL type tests | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#the-whole-database), `runtime/effects/db_snapshot.py` | | Learn, then enforce: excuse the app's own per-request writes on the acting user's own rows (the user's `last_login`, a token's `last_seen`, a first-login row) that make the whole-database frame refute every correct write. `learn collect` records each check's moved rows and the agent's request-body field names from a shadow run; `learn propose` proposes only moves on the acting user's rows (users table named once, user columns from the schema's foreign keys), never a column the agent sent or the contract names, as an exact column set seen in 3 of every 5 checks; one `learn approve` by a person writes `frame.learned` with the proposal's digest. At check time the relation is derived again from the run's actor: never another user's row, another column, a removal, more added rows than learned, or a row added for someone else. Collateral on the written row is never learned (a `relation: target` entry is refused at load); the generator's bookkeeping answer excuses those columns. Not yet: tables over `max_rows` | [#1679](https://github.com/OpenAdaptAI/OpenAdapt/pull/1679) | Real app (three held-out apps on MariaDB and PostgreSQL, replayed agent writes: correct writes of the kinds with an approved excuse confirmed 0 -> 74 of 100, the rest stopped at begin or by app rows that are neither the write's nor the actor's; 0 of 42 planted harms passed); adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | -| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts that create new records or read the target's versions get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | +| Learn per-request bookkeeping from read-only requests, with no approval: `learn probe` reads the whole-database frame of one contract, sends only GET and HEAD requests as the agent, and reads again; a changed row of the acting user that every round (at least two) shows (users table derived from the manifest's actor parameters by foreign key) becomes a `frame.learned` excuse with `source: read_only_probe`, exact columns only, never a column the probe, the parameters or a contract names. Added rows, other users' rows and rows no user owns are not admitted (added rows are listed for `learn approve`), and only contracts whose every effect creates new records, or that read the target's versions on every other effect's surface, get the excuses (an update with no version source can't see a lost update without the bookkeeping move). Not yet: background rows that move with no request, derived rows a write recomputes | (this PR) | Real app replay (first-contact retest, four apps, frozen vs `main` vs this branch on identical writes): correct writes stopped on the app with per-user last-login bookkeeping 77 -> 36 of 77, in-scope harms 26 of 26 stopped before and after; on a second app 46 -> 34 of 46 replayed agent writes, its three lost updates still stopped; no change on two apps without such bookkeeping and on two held-out apps (the probe learned nothing there). One out-of-scope late duplicate that bookkeeping used to mask now passes; adversarial tests on SQLite, MySQL and PostgreSQL | `openadapt-flow learn probe`, [LEARNED_EXCUSES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/LEARNED_EXCUSES.md) | | Catch a lost update: another user saves a change to the record while the agent works, and the agent saves its stale copy over it. Before and after look like a correct update, so `frame.versions` reads the target's versions (FHIR or SQL version history, a version column, or the app's audit or action-history table) before and after the write. A version by another author, or more than one version step when no author is read, refutes the write; a version that can't be read or attributed stops it | Released ([#1662](https://github.com/OpenAdaptAI/OpenAdapt/pull/1662)) | Real app (HAPI FHIR and EspoCRM, first-contact study fault scripts: both lost updates refuted, correct updates verified, every other case's verdict unchanged) | [VERIFY_RUN.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/VERIFY_RUN.md#lost-updates), `runtime/effects/versions.py` | | Guarded save: a safety layer any agent wraps around one write (check the record, hold for approval, read back) | Released ([#1258](https://github.com/OpenAdaptAI/OpenAdapt/pull/1258)) | Synthetic | `GUARDED_SAVE.md` | | A person's approval in Desktop is signed with a key kept behind Touch ID on a Mac: one-prompt setup in the app, a prompt for every answer, and Flow never sees the key | Released ([#1500](https://github.com/OpenAdaptAI/OpenAdapt/pull/1500)) | Unit tests; opt-in test on a real Secure Enclave | `packages/desktop/openadapt_desktop/approver_keychain.py`, [APPROVAL_MODES.md](https://github.com/OpenAdaptAI/OpenAdapt/blob/main/packages/flow/docs/APPROVAL_MODES.md#the-approver-key) | diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index f3fa7e3e38..1b76185010 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -203,9 +203,12 @@ contract, sends only the `GET` and `HEAD` requests you list as the agent, and reads again. No write is sent, so whatever the app moved is its own bookkeeping. The proposal follows the rules above: only the acting user's own rows, the exact columns, and never a column the probe's query strings, -the parameters or a contract name. A `changed` move seen in any one round -counts, because no round carried a task. An `added` row (a first-login row) -is never admitted by the probe: its excuse names columns, not values, so it +the parameters or a contract name. A `changed` move counts only when every +round shows it (`--rounds`, at least two): per-request bookkeeping moves on +every request, while an edit someone makes to the acting user's own row +during one round does not, so it stays a stop. A round in which nothing +moved means nothing is learned. An `added` row (a first-login row) is +never admitted by the probe: its excuse names columns, not values, so it would also cover a row the agent adds for itself with other values. It is listed under `needs_approval` for `learn approve`. Every other row that moved stays a stop and is listed in `learn/probe_proposal.json`. @@ -219,8 +222,10 @@ learned unless you name it (`--users`). `frame.learned.source: read_only_probe`, and leaves out of each contract any excuse for a column that contract names. It writes them only into a contract whose frame can see a lost update without the bookkeeping move: -one whose every declared record is new (`count_new_only`), or one that -reads the target's versions (`frame.versions`). In an update with no +one whose every declared effect creates a new record (`count_new_only`; +a create beside a `field_equals` update doesn't count), or one that reads +the target's versions (`frame.versions`) on the surface of every other +effect (its `target_surface`, when set). In an update with no version source, another user's edit that the agent's stale save reverts leaves nothing changed, and only the bookkeeping move stopped it, so such contracts keep stopping. No person approves them: the From 83138c03a184693760694410b702e8af0ac4786d Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 21:55:45 -0500 Subject: [PATCH 5/8] fix(learn): attribute probe excuses with control windows; one surface for unscoped versions Codex review blockers on #2413. fail-open class: correlation-as-attribution. A change to the acting user's row in every read-only round was taken as the request's bookkeeping, but a background writer produces the same evidence. Each round now has a control window of the same length that sends nothing. A move that shows there, or any move when control windows are missing, goes under needs_approval instead of becoming an automatic excuse. fail-open class: ambiguous-subject-binding. With frame.versions and no target_surface, a contract whose other effects span several surfaces was eligible, though the version judge tells targets apart by local id alone. Such a contract now gets no automatic excuse. --- packages/flow/docs/LEARNED_EXCUSES.md | 9 ++- packages/flow/openadapt_flow/learn_probe.py | 80 ++++++++++++++++++--- packages/flow/tests/test_learn_probe.py | 69 +++++++++++++++++- 3 files changed, 146 insertions(+), 12 deletions(-) diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index 1b76185010..7fcbb45ad0 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -206,7 +206,11 @@ own rows, the exact columns, and never a column the probe's query strings, the parameters or a contract name. A `changed` move counts only when every round shows it (`--rounds`, at least two): per-request bookkeeping moves on every request, while an edit someone makes to the acting user's own row -during one round does not, so it stays a stop. A round in which nothing +during one round does not, so it stays a stop. After each round the probe +also reads a control window of the same length in which it sends nothing. +A column that moves in a control window moves without a request (a +background job, or another session), so it is not excused automatically: +it goes under `needs_approval`. A round in which nothing moved means nothing is learned. An `added` row (a first-login row) is never admitted by the probe: its excuse names columns, not values, so it would also cover a row the agent adds for itself with other values. It is @@ -225,7 +229,8 @@ contract whose frame can see a lost update without the bookkeeping move: one whose every declared effect creates a new record (`count_new_only`; a create beside a `field_equals` update doesn't count), or one that reads the target's versions (`frame.versions`) on the surface of every other -effect (its `target_surface`, when set). In an update with no +effect (its `target_surface`; with none set, every other effect must be +on one surface, since an unscoped read tells records apart by id alone). In an update with no version source, another user's edit that the agent's stale save reverts leaves nothing changed, and only the bookkeeping move stopped it, so such contracts keep stopping. No person approves them: the diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 8d55ecf303..1950d3f291 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -15,7 +15,8 @@ (``begin_write`` with the probe's parameters), send the read-only requests as the agent, and judge the frame (``verify_write``). No write is sent, so the declared effect is absent; only the frame's moved rows - are used. + are used. A control window of the same length follows each round with + no request; a move it shows is not the request's and is not excused. 2. Propose from those moves with the learner's own rules (:func:`openadapt_flow.learn.propose`): only the acting user's own row (``actor_row``), exact columns, ``changed`` only, and never a column a @@ -39,6 +40,7 @@ import json import tempfile +import time from collections.abc import Callable, Mapping, Sequence from pathlib import Path from typing import Any, Optional @@ -112,12 +114,16 @@ def probe( send: Callable[[], set[str]], rounds: int = DEFAULT_ROUNDS, workdir: Optional[Path] = None, + idle: Callable[[float], None] = time.sleep, ) -> list[dict[str, Any]]: """Run ``rounds`` read-only windows under ``contract``'s frame. ``send`` sends the read-only requests as the agent and returns the query-parameter names it sent (``learn.query_fields``); it must not - write. Returns one episode per round.""" + write. After each request window, a control window as long as it sends + nothing (``idle``): a row that moves there moves without a request, so + it is not the request's bookkeeping. Returns one request episode and + one control episode (``control: True``) per round.""" from openadapt_flow.verifier import Actor, begin_write, verify_write @@ -139,13 +145,33 @@ def probe( write_key=f"read-only-probe-{kind}-{i}", workdir=base / f"round-{i}", ) + started = time.monotonic() sent = set(send()) + elapsed = time.monotonic() - started result = verify_write(pending) out.append( episode( kind, result, contract=contract, params=params, sent_fields=sent ) ) + control = begin_write( + contract, + dict(params), + actor=Actor("agent", str(actor)), + ledger=None, + write_key=f"read-only-probe-{kind}-{i}-control", + workdir=base / f"round-{i}-control", + ) + idle(elapsed) + ep = episode( + kind, + verify_write(control), + contract=contract, + params=params, + sent_fields=set(), + ) + ep["control"] = True + out.append(ep) return out @@ -206,7 +232,18 @@ def propose( different property the agent sets). Such moves go under ``needs_approval``: a person approves them with ``learn approve``.""" - eps = [dict(e, kind="read_only_probe") for e in episodes if e.get("probe")] + probes = [e for e in episodes if e.get("probe")] + controls = [e for e in probes if e.get("control")] + eps = [dict(e, kind="read_only_probe") for e in probes if not e.get("control")] + # fail-open class: correlation-as-attribution. A move seen in every + # request round is only timing; it is the request's bookkeeping only + # when the control windows (no request) show it never moving on its own. + background = { + (str(m.get("table")), str(c)) + for e in controls + for m in e.get("moves") or [] + for c in m.get("columns") or [None] + } learnable = [e for e in eps if _learn._why_ignored(e) is None] n = max(1, len(learnable)) proposal = _learn.propose(eps, users=users, k=n, n=n, source="read-only probe") @@ -223,13 +260,33 @@ def propose( kept: list[dict[str, Any]] = [] held: list[dict[str, Any]] = [] for e in body.get("excuses") or []: - (held if e.get("change") == "added" else kept).append(e) + if e.get("change") == "added": + e["why_not"] = ( + "an added row: its excuse names columns, not values, so a " + "person approves it (learn approve)" + ) + elif len(controls) < len(eps): + e["why_not"] = ( + "no control window without requests for every round: " + "nothing shows the move comes from the request, so a " + "person approves it (learn approve)" + ) + elif any( + (str(e.get("table")), str(c)) in background + or (str(e.get("table")), "None") in background + for c in e.get("columns") or [] + ): + e["why_not"] = ( + "it also moved in a control window with no request: a " + "background writer, not the request's bookkeeping, so a " + "person approves it (learn approve)" + ) + else: + kept.append(e) + continue + held.append(e) for e in held: e.pop("id", None) - e["why_not"] = ( - "an added row: its excuse names columns, not values, so a " - "person approves it (learn approve)" - ) body["excuses"] = kept body["needs_approval"] = held proposal.pop("proposal_sha256", None) @@ -347,7 +404,12 @@ def guard(effect: Any) -> bool: if versions is None: return False surface = getattr(versions, "target_surface", None) - return surface is None or all(surface_of(e) == surface for e in others) + if surface is None: + # fail-open class: ambiguous-subject-binding. An unscoped version + # read judges targets by their local id alone, so two records with + # one id on two surfaces would share one version check. + return len({surface_of(e) for e in others}) == 1 + return all(surface_of(e) == surface for e in others) def http_sender( diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index 4499093a46..08f29ec783 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -112,7 +112,9 @@ def users(e: Engine) -> learn.Users: return learn.users_from("app_user", "id", schema) -def run_probe(e: Engine, tmp_path: Path, send: Any, rounds: int = 3) -> dict: +def run_probe( + e: Engine, tmp_path: Path, send: Any, rounds: int = 3, idle: Any = None +) -> dict: c = Contract.from_dict(note_contract(e), name="note") eps = learn_probe.probe( c, @@ -122,6 +124,7 @@ def run_probe(e: Engine, tmp_path: Path, send: Any, rounds: int = 3) -> dict: send=send, rounds=rounds, workdir=tmp_path / "probe", + idle=idle or (lambda _s: None), ) return learn_probe.propose(eps, users(e)) @@ -459,3 +462,67 @@ def test_versions_on_another_surface_do_not_cover_an_update() -> None: assert learn_probe._sees_its_own_harm(contract) is False contract.config.frame.versions = NS(target_surface=None) assert learn_probe._sees_its_own_harm(contract) is True + + +def test_a_background_writer_on_the_actors_row_is_not_excused( + engine: Engine, tmp_path: Path +) -> None: + """A job that bumps the acting user's row whether or not a request is + sent moves in the control windows too: timing alone is no attribution, + so it waits for a person instead of becoming an automatic excuse.""" + + def background(_seconds: float) -> None: + engine.run( + "UPDATE app_user SET last_login = %s WHERE id = %s", _stamp(), int(ACTOR) + ) + + def send() -> set[str]: + background(0) + engine.run( + "UPDATE api_token SET last_seen = %s WHERE user_id = %s", + _stamp(), + int(ACTOR), + ) + return {"q"} + + proposal = run_probe(engine, tmp_path, send, idle=background) + got = {(x["table"], tuple(x["columns"])) for x in excuses_of(proposal)} + assert not any(t == "app_user" for t, _cols in got) + held = proposal["kinds"]["read_only_probe"]["needs_approval"] + assert any(x["table"] == "app_user" for x in held) + # The token row moved only with requests: still bookkeeping. + assert ("api_token", ("last_seen",)) in got + + +def test_episodes_without_control_windows_excuse_nothing_automatically( + engine: Engine, tmp_path: Path +) -> None: + c = Contract.from_dict(note_contract(engine), name="note") + eps = learn_probe.probe( + c, {"title": "Probe note", "body": "x"}, kind="add_note", actor=ACTOR, + send=first_once(engine), workdir=tmp_path / "probe", idle=lambda _s: None, + ) # fmt: skip + proposal = learn_probe.propose( + [e for e in eps if not e.get("control")], users(engine) + ) + assert excuses_of(proposal) == [] + assert proposal["kinds"]["read_only_probe"]["needs_approval"] + + +def test_unscoped_versions_over_two_surfaces_do_not_cover_updates() -> None: + from types import SimpleNamespace as NS + + from openadapt_flow.runtime.effects.effect import EffectKind + from openadapt_flow.runtime.effects.surfaces import surface_probe + + def update(surface: str) -> Any: + return NS(kind=EffectKind.FIELD_EQUALS, probe=surface_probe(surface), + expected_count=1, count_new_only=False) # fmt: skip + + versions = NS(target_surface=None) + two = NS(config=NS(frame=NS(versions=versions), + effects=[update("primary"), update("secondary")])) # fmt: skip + assert learn_probe._sees_its_own_harm(two) is False + one = NS(config=NS(frame=NS(versions=versions), + effects=[update("primary"), update("primary")])) # fmt: skip + assert learn_probe._sees_its_own_harm(one) is True From c274d556aad313eab70ebdcba45c3699656e5e65 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sat, 21 Nov 2026 23:16:27 -0500 Subject: [PATCH 6/8] fix(learn): an unreadable control window is no evidence of no background move Gemini review blocker on #2413 (fail-open class: absent-evidence-as-success). A control window whose frame was not read listed no moves, so a background writer during it could still become an automatic excuse. Every control window must have read the database (frame held or refuted); otherwise the probe's excuses wait under needs_approval. --- packages/flow/openadapt_flow/learn_probe.py | 13 +++++++++---- packages/flow/tests/test_learn_probe.py | 19 +++++++++++++++++++ 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/packages/flow/openadapt_flow/learn_probe.py b/packages/flow/openadapt_flow/learn_probe.py index 1950d3f291..4ad53d1ada 100644 --- a/packages/flow/openadapt_flow/learn_probe.py +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -265,11 +265,16 @@ def propose( "an added row: its excuse names columns, not values, so a " "person approves it (learn approve)" ) - elif len(controls) < len(eps): + elif len(controls) < len(eps) or not all( + c.get("has_database") and c.get("frame") in ("held", "refuted") + for c in controls + ): + # A control window whose frame wasn't read shows nothing, + # which is no evidence that nothing moved. e["why_not"] = ( - "no control window without requests for every round: " - "nothing shows the move comes from the request, so a " - "person approves it (learn approve)" + "no readable control window without requests for every " + "round: nothing shows the move comes from the request, " + "so a person approves it (learn approve)" ) elif any( (str(e.get("table")), str(c)) in background diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py index 08f29ec783..92f1d0ab3d 100644 --- a/packages/flow/tests/test_learn_probe.py +++ b/packages/flow/tests/test_learn_probe.py @@ -526,3 +526,22 @@ def update(surface: str) -> Any: one = NS(config=NS(frame=NS(versions=versions), effects=[update("primary"), update("primary")])) # fmt: skip assert learn_probe._sees_its_own_harm(one) is True + + +def test_an_unreadable_control_window_excuses_nothing_automatically( + engine: Engine, tmp_path: Path +) -> None: + """A control window whose frame read failed lists no moves; that is no + evidence the actor's row stays still without a request.""" + + c = Contract.from_dict(note_contract(engine), name="note") + eps = learn_probe.probe( + c, {"title": "Probe note", "body": "x"}, kind="add_note", actor=ACTOR, + send=first_once(engine), workdir=tmp_path / "probe", idle=lambda _s: None, + ) # fmt: skip + for e in eps: + if e.get("control"): + e.update(frame="not_checked", has_database=False, moves=[]) + proposal = learn_probe.propose(eps, users(engine)) + assert excuses_of(proposal) == [] + assert proposal["kinds"]["read_only_probe"]["needs_approval"] From 9117e38ef3aeda3a5093817205aa3ae243c62b44 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 17:34:11 -0500 Subject: [PATCH 7/8] test(flow): regenerate cli_surface.json for learn probe --- packages/flow/tests/fixtures/cli_surface.json | 249 +++++++++++++++++- 1 file changed, 248 insertions(+), 1 deletion(-) diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index bf392fb273..b8683ed00f 100644 --- a/packages/flow/tests/fixtures/cli_surface.json +++ b/packages/flow/tests/fixtures/cli_surface.json @@ -113,9 +113,10 @@ "openadapt-flow known-ids": "usage: openadapt-flow known-ids [-h] {confirm,status} ...\n\npositional arguments:\n {confirm,status}\n confirm Confirm the export's source and completeness (recorded)\n status Would replay accept this list now?\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow verify known-ids\n", "openadapt-flow known-ids confirm": "usage: openadapt-flow known-ids confirm [-h] [--column COLUMN] [--confirmation CONFIRMATION]\n --source SOURCE [--by BY] [--exported-at EXPORTED_AT]\n [--yes]\n export\n\npositional arguments:\n export Export file (CSV/TSV, JSON, or one ID per line)\n\noptions:\n -h, --help show this help message and exit\n --column COLUMN Identifier column (CSV/TSV)\n --confirmation CONFIRMATION\n Confirmation record (default: EXPORT.confirmation.json)\n --source SOURCE Which system and export this is\n --by BY Who confirms (default: your user name)\n --exported-at EXPORTED_AT\n When the export was taken (default: file time)\n --yes Skip the interactive prompt\n\nAlso available as: openadapt-flow verify known-ids confirm\n", "openadapt-flow known-ids status": "usage: openadapt-flow known-ids status [-h] [--column COLUMN] [--confirmation CONFIRMATION]\n [--max-age-hours MAX_AGE_HOURS]\n export\n\npositional arguments:\n export Export file (CSV/TSV, JSON, or one ID per line)\n\noptions:\n -h, --help show this help message and exit\n --column COLUMN Identifier column (CSV/TSV)\n --confirmation CONFIRMATION\n Confirmation record (default: EXPORT.confirmation.json)\n --max-age-hours MAX_AGE_HOURS\n\nAlso available as: openadapt-flow verify known-ids status\n", - "openadapt-flow learn": "usage: openadapt-flow learn [-h] {collect,propose,approve} ...\n\npositional arguments:\n {collect,propose,approve}\n collect run a shadow and record each check\n propose write a proposal a person can read\n approve write the approved excuses into contracts\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow teach --learn\n", + "openadapt-flow learn": "usage: openadapt-flow learn [-h] {collect,propose,approve,probe} ...\n\npositional arguments:\n {collect,propose,approve,probe}\n collect run a shadow and record each check\n propose write a proposal a person can read\n approve write the approved excuses into contracts\n probe learn per-request bookkeeping from read-only requests (no approval)\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow teach --learn\n", "openadapt-flow learn approve": "usage: openadapt-flow learn approve [-h] --by BY [--config CONFIG] [--manifest MANIFEST]\n [--contract KIND=PATH] [--kind KIND] [--reject ID]\n proposal\n\npositional arguments:\n proposal\n\noptions:\n -h, --help show this help message and exit\n --by BY who approves (recorded)\n --config CONFIG the shadow config's routes\n --manifest MANIFEST a generator manifest.yaml\n --contract KIND=PATH a contract file for a kind (repeatable)\n --kind KIND approve only these\n --reject ID leave out E\n\nAlso available as: openadapt-flow teach --learn approve\n", "openadapt-flow learn collect": "usage: openadapt-flow learn collect [-h] --config CONFIG [--out OUT] [--actor ACTOR]\n [--listen LISTEN] [--until-idle SECONDS]\n\noptions:\n -h, --help show this help message and exit\n --config CONFIG openadapt.shadow/v1 YAML (sql)\n --out OUT folder for episodes.jsonl\n --actor ACTOR the agent's user id in the app\n --listen LISTEN\n --until-idle SECONDS\n\nAlso available as: openadapt-flow teach --learn collect\n", + "openadapt-flow learn probe": "usage: openadapt-flow learn probe [-h] --manifest MANIFEST --kind KIND --values VALUES\n [--extra EXTRA] --actor ACTOR --base-url BASE_URL\n [--headers-env HEADERS_ENV] [--get PATH] [--head PATH]\n [--rounds ROUNDS] [--users USERS] [--user-column TABLE.COLUMN]\n [--schema SCHEMA] [--read READ] [--out OUT] [--apply]\n\noptions:\n -h, --help show this help message and exit\n --manifest MANIFEST the generator's manifest.yaml\n --kind KIND the kind whose contract frames the probe\n --values VALUES YAML: one task's values for that kind\n --extra EXTRA YAML: extra parameters (actor ids)\n --actor ACTOR the agent's user id in the app\n --base-url BASE_URL\n --headers-env HEADERS_ENV\n environment variable holding the agent's request headers as JSON\n --get PATH\n --head PATH\n --rounds ROUNDS\n --users USERS TABLE or TABLE.KEY (default: derived)\n --user-column TABLE.COLUMN\n --schema SCHEMA\n --read READ\n --out OUT\n --apply write the excuses into every contract the manifest lists\n\nAlso available as: openadapt-flow teach --learn probe\n", "openadapt-flow learn propose": "usage: openadapt-flow learn propose [-h] --episodes EPISODES [--users USERS]\n [--user-column TABLE.COLUMN] [--schema SCHEMA] [--read READ]\n [--k K] [--n N] [--out OUT]\n\noptions:\n -h, --help show this help message and exit\n --episodes EPISODES episodes.jsonl\n --users USERS the users table, as TABLE or TABLE.KEY (without it only the write's own\n rows can be excused)\n --user-column TABLE.COLUMN\n a column holding a user id, confirmed by you (repeatable)\n --schema SCHEMA schema.json from `generate schema`\n --read READ read.yaml: read the schema's foreign keys live\n --k K\n --n N\n --out OUT\n\nAlso available as: openadapt-flow teach --learn propose\n", "openadapt-flow ledger": "usage: openadapt-flow ledger [-h] [--home HOME] {add,list,show,summary,export,push} ...\n\npositional arguments:\n {add,list,show,summary,export,push}\n add Read a run's files and append its row\n list List rows\n show Show one row\n summary Counts per outcome, minutes, cost, duration\n export Write value-free rows as JSONL\n push Send value-free run summaries to OpenAdapt Cloud (OPENADAPT_API_KEY)\n\noptions:\n -h, --help show this help message and exit\n --home HOME OpenAdapt home (default: $OPENADAPT_HOME, else ~/.openadapt)\n\nAlso available as: openadapt-flow inspect ledger\n", "openadapt-flow ledger add": "usage: openadapt-flow ledger add [-h] [--task-type TASK_TYPE] [--task-id TASK_ID]\n [--run-ref RUN_REF] [--approvals APPROVALS] [--config CONFIG]\n run\n\npositional arguments:\n run Run directory (or one run record file)\n\noptions:\n -h, --help show this help message and exit\n --task-type TASK_TYPE\n Operator label, e.g. intake\n --task-id TASK_ID Override the task id\n --run-ref RUN_REF The run's exception-queue reference (exceptions serve --run-ref); its\n cards and answers are read from $OPENADAPT_HOME/exceptions/REF\n --approvals APPROVALS\n A P7 fallback's item-approval folder root (wrap-dispatch --fallback-\n approvals); each gate's request and answer times are read from\n DIR//item-approval\n --config CONFIG The run's guard task JSON or verify.yaml, when not in RUN_DIR; its field\n names may leave in export and push (repeatable)\n\nAlso available as: openadapt-flow inspect ledger add\n", @@ -10482,6 +10483,7 @@ "commands": { "approve": [], "collect": [], + "probe": [], "propose": [] }, "exclusive": [] @@ -10694,6 +10696,251 @@ "commands": {}, "exclusive": [] }, + "openadapt-flow learn probe": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "manifest", + "help": "the generator's manifest.yaml", + "metavar": null, + "nargs": null, + "options": [ + "--manifest" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "kind", + "help": "the kind whose contract frames the probe", + "metavar": null, + "nargs": null, + "options": [ + "--kind" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "values", + "help": "YAML: one task's values for that kind", + "metavar": null, + "nargs": null, + "options": [ + "--values" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "extra", + "help": "YAML: extra parameters (actor ids)", + "metavar": null, + "nargs": null, + "options": [ + "--extra" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "actor", + "help": "the agent's user id in the app", + "metavar": null, + "nargs": null, + "options": [ + "--actor" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "base_url", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--base-url" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "headers_env", + "help": "environment variable holding the agent's request headers as JSON", + "metavar": null, + "nargs": null, + "options": [ + "--headers-env" + ], + "required": false, + "type": null + }, + { + "action": "_AppendAction", + "choices": null, + "default": [], + "dest": "get", + "help": null, + "metavar": "PATH", + "nargs": null, + "options": [ + "--get" + ], + "required": false, + "type": null + }, + { + "action": "_AppendAction", + "choices": null, + "default": [], + "dest": "head", + "help": null, + "metavar": "PATH", + "nargs": null, + "options": [ + "--head" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": 3, + "dest": "rounds", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--rounds" + ], + "required": false, + "type": "int" + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "users", + "help": "TABLE or TABLE.KEY (default: derived)", + "metavar": null, + "nargs": null, + "options": [ + "--users" + ], + "required": false, + "type": null + }, + { + "action": "_AppendAction", + "choices": null, + "default": [], + "dest": "user_column", + "help": null, + "metavar": "TABLE.COLUMN", + "nargs": null, + "options": [ + "--user-column" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "schema", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--schema" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "read", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--read" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": "learn", + "dest": "out", + "help": null, + "metavar": null, + "nargs": null, + "options": [ + "--out" + ], + "required": false, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "apply", + "help": "write the excuses into every contract the manifest lists", + "metavar": null, + "nargs": 0, + "options": [ + "--apply" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, "openadapt-flow learn propose": { "arguments": [ { From 2144dc5f4da9d07b09ec082228a4a10f0c7f8741 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 19:33:10 -0500 Subject: [PATCH 8/8] docs: refresh command map and llms-full.txt for learn probe --- CAPABILITIES.md | 2 +- llms-full.txt | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index f781c4e9a9..1229095270 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -511,7 +511,7 @@ A test fails when a command has no file or this list is out of date. - `flight`: Record any agent you already run: meter and price its model calls through a loopback proxy, scrub its text and PNG/JPEG/GIF/BMP/TIFF/WEBP screenshots before they leave the machine, block other egress on macOS, log its actions, and hold each click that is not known to be safe for a person. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, writes a ledger row and a private diff, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). -- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), propose excuses, and approve them into the contracts. +- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), and write them into the contracts. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. - `proxy`: Holds the database credentials, and with `--api` the API credentials, and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof; each API write is sent once under a task-derived key, read back, and checked against the system's own event or audit log. - `readiness`: Shadow a candidate agent or compiled program on tasks a person did, stopped before every save, and write a one-page Readiness Scorecard (matched N of M, risks, field errors, time and cost). diff --git a/llms-full.txt b/llms-full.txt index 0de976f442..1664ff6eec 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -971,7 +971,7 @@ A test fails when a command has no file or this list is out of date. - `flight`: Record any agent you already run: meter and price its model calls through a loopback proxy, scrub its text and PNG/JPEG/GIF/BMP/TIFF/WEBP screenshots before they leave the machine, block other egress on macOS, log its actions, and hold each click that is not known to be safe for a person. - `guard`: Attaches to the agent's own Chromium over CDP, holds each save until the right record is on screen, reads it back, writes a ledger row and a private diff, and hands a verified run to the teach dir. - `hooks`: Writes `openadapt.systems.yaml` checks into Claude Code or Codex hooks: each write to a declared database, HTTP API or MCP tool is pre-checked, read back and given a signed receipt (advisory). -- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), propose excuses, and approve them into the contracts. +- `learn`: Learn the app's own per-request writes from a shadow run or from read-only requests (`learn probe`), and write them into the contracts. - `plan`: Dry-runs a batch of writes to external systems (REST APIs, SQL databases, email) and prints what would change; applies it only under a single-use approval bound to the plan digest, with an idempotency key per write that a regenerated payload cannot change; undoes it with a read-back proof; holds email in a cancelable queue. - `proxy`: Holds the database credentials, and with `--api` the API credentials, and runs the agent with scoped MCP tools: each SQL write is dry-run in a rolled-back transaction with its exact row-level diff, approved by policy or by a person against the plan digest, committed once only if its diff matches, and undone with a read-back proof; each API write is sent once under a task-derived key, read back, and checked against the system's own event or audit log. - `readiness`: Shadow a candidate agent or compiled program on tasks a person did, stopped before every save, and write a one-page Readiness Scorecard (matched N of M, risks, field errors, time and cost).