diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 306c5c9da3..1229095270 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -187,6 +187,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 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) | @@ -510,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, 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 ae1ca3e8ca..1664ff6eec 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -647,6 +647,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 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) | @@ -970,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, 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/packages/flow/docs/BACKEND_PARITY.md b/packages/flow/docs/BACKEND_PARITY.md index 095cb658c8..3513ce685f 100644 --- a/packages/flow/docs/BACKEND_PARITY.md +++ b/packages/flow/docs/BACKEND_PARITY.md @@ -345,6 +345,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`. | | `openadapt-flow wrap-dispatch` | `--pricing-source-url` | The primary source cited for the model prices the fallback's cost is computed with, not an app. The task's app comes from `--task`. | diff --git a/packages/flow/docs/LEARNED_EXCUSES.md b/packages/flow/docs/LEARNED_EXCUSES.md index cb46acad14..7fcbb45ad0 100644 --- a/packages/flow/docs/LEARNED_EXCUSES.md +++ b/packages/flow/docs/LEARNED_EXCUSES.md @@ -184,8 +184,71 @@ 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 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. 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 +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. It writes them only into a +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`; 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 +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..eb11a04cf6 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.register_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..4ad53d1ada --- /dev/null +++ b/packages/flow/openadapt_flow/learn_probe.py @@ -0,0 +1,539 @@ +"""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. 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 + 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 +import time +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 +#: 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): + """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, + 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. 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 + + 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: + 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}", + ) + 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 + + +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 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 + 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``.""" + + 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") + # 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(): + 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 []: + 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) 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 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 + 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) + 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, 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 + + 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 + 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"] + 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 _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. + + 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) + 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) + 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( + 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 register_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 a3c1bd656e..ca6bf0f209 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/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": [ { diff --git a/packages/flow/tests/test_learn_probe.py b/packages/flow/tests/test_learn_probe.py new file mode 100644 index 0000000000..92f1d0ab3d --- /dev/null +++ b/packages/flow/tests/test_learn_probe.py @@ -0,0 +1,547 @@ +"""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, + asset_contract, + check, +) +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. +engine = _le.engine +_homes = _le._homes + +_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)) + + +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, idle: Any = None +) -> 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", + idle=idle or (lambda _s: None), + ) + 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 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) + 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 + + +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 + ) + + +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 + + +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 + + +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"]