Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 5 additions & 2 deletions CAPABILITIES.md

Large diffs are not rendered by default.

7 changes: 5 additions & 2 deletions llms-full.txt

Large diffs are not rendered by default.

53 changes: 53 additions & 0 deletions packages/flow/docs/LEARNED_EXCUSES.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,8 +184,61 @@ 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. 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.

## 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.
Expand Down
125 changes: 125 additions & 0 deletions packages/flow/docs/VERDICT_TIERS.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,125 @@
# Verdict tiers, entity-scoped frames and shadow mode

A whole-database frame stops a correct write whenever any row moves. On a
live app many rows move with no harm: a scheduler's heartbeat, a task queue,
prices or totals the app recomputes after a save, a notification for each
watcher of a record. This page describes how the verifier separates those
from real harm without letting any planted fault through.

## Three tiers

Every check of a write ends in one of these tiers. `WriteResult.tier` names
it, and `to_dict()` returns it with `side_effects`, `enforcement` and
`blocks`.

| Tier | Outcome | What it covers |
| --- | --- | --- |
| `hard` | `REFUTED` | The target is missing, a value is wrong after normalization, a duplicate, a changed or removed row in a business-entity table that the write doesn't declare (including another user's row and an unexcused column of the acting user's row), a late revert, a lost update, any removed row, and anything no row comparison explains. |
| `logged` | `CONFIRMED` | The write holds, and rows moved only outside the entity tables (added or changed, never removed). Each is listed in the frame evidence as `side_effects`: table, change, row count and column names, never keys or values. The same rows go to `openadapt-flow learn` as candidate excuses. |
| `doubt` | `UNCERTAIN` | Timing or knowledge doubt that the verifier's own waiting didn't clear. |
| `clean` | `CONFIRMED` | Nothing else moved. |

A logged pass is still `CONFIRMED`. A harm that slips through the logged
tier is therefore counted as a silent pass by any grader that reads the
outcome. The tier never hides a pass.

### Retry before reporting a doubt

Before a write is judged, the verifier waits for its declared records to
become visible: 0.5 s, then 1, 2 and 4 s, within 8 s in all
(`OPENADAPT_VERIFY_RETRY_S` sets the budget; 0 turns it off). The wait
reads only through database verifiers, so the wait itself can't move a
bookkeeping row. It never decides anything: the full judge runs afterwards
either way. A record that is present stops the wait at once.

The database frame's own settling (`settle_s`, `settle_attempts`) ignores
motion in tables outside the entity tables, so a scheduler that never stops
doesn't keep a write unsettled. Those tables are still diffed against the
baseline in the read that is judged.

## Entity-scoped frames

`frame.database.entity_tables` lists the business-entity tables. When it is
set, the hard checks cover those tables and rows elsewhere are logged. The
tables the frame already names (`views`, `judged_by`, `new_row_fields`,
side records, learned excuses, owner tables, the app profile's rules)
always count as entity tables. When it is unset, every table is judged as
before.

The list is derived from the setup, never written by hand
(`openadapt-flow learn entities`):

- each kind's main table;
- every table a contract's own read selects from, which covers the child
tables a write adds and the tables a field's location reads through;
- the acting user's table: the one table that every column bound to an
actor parameter references by foreign key. When it can't be derived, no
scope is proposed, because another user's row must stay a stop.

On a frame that diffs the whole database, a surface's own check columns
(`pin__*`, `empty__*`, which a generated read computes as 1 or 0) are not
compared on undeclared rows. One can flip with the clock and no write. The
stored columns they are computed from are compared themselves.

## The safety bar

A relaxation (an entity scope, or a learned mask) is admitted only if the
planted faults are all still caught under it
(`openadapt_flow.runtime.effects.admission`):

- wrong row, wrong value, duplicate, sibling business-record edit, late
revert and lost update;
- for a relaxation that touches the acting user's table, another user's row
and another column of the actor's own row.

Every class must have at least one case, every case must be caught, and
every case caught before the relaxation must be run again under it.
`fault_gate` names count for the same classes (`wrong_record` is a wrong
row, `unrelated_edit` a sibling edit).

```
openadapt-flow learn entities propose --manifest manifest.yaml --read read.yaml --out scope.json
openadapt-flow learn entities stage scope.json --out candidate/
# run the planted faults against candidate/ and write faults.json
openadapt-flow learn entities apply scope.json --faults faults.json --by "A. Reviewer"
```

`faults.json` is `openadapt.relaxation-faults/v1`: the proposal's
`proposal_sha256` and one `{case, class, caught}` per case. `apply` refuses
results run under another proposal, and writes every contract or none.

## Shadow mode by default

A contract is new to an app until it has been seen to judge real writes
correctly. Until then (`enforcement: shadow`) its verdicts are computed and
recorded in full, but `WriteResult.blocks` is false, so a caller that stops
on a verdict doesn't stop. Each check is appended to the contract's gate log
(`OPENADAPT_GATE_DIR`, by default `<OPENADAPT_LEDGER_DIR>/gates`, else
`~/.openadapt/gates`; names and outcomes only).

After N checks in a row with no stop of a correct write, gating is offered,
and a person turns it on:

```
openadapt-flow gate status contract.yaml
openadapt-flow gate label contract.yaml <write_id> caught # a real harm: keeps the run
openadapt-flow gate label contract.yaml <write_id> false_stop # breaks it, and is counted
openadapt-flow gate enable contract.yaml --by "A. Reviewer" # refused until offered
```

N is `OPENADAPT_GATE_CLEAN_RUNS`, kept between 20 and 50 (default 30). A
stop that nobody has labelled breaks the run, since it may be a false stop.
`OPENADAPT_ENFORCEMENT=gating` gates every contract (the behaviour before
shadow mode), and `shadow` keeps every contract in shadow. Shadow mode
changes only `blocks`. The ledger still holds a refuted attempt, so a retry
is never sent silently.

## Limits

- An edit by another user to a record in an entity table, with no audit
log or modified-by field to attribute it, still stops the write. Nothing
in the store tells it apart from the agent editing a sibling record.
- A harm confined to a table outside the entity tables (an agent that
changes a notification or a queue row) is logged, not stopped. The scope
is admitted only when the planted faults, which target business records,
are all caught. It is not a check on side tables.
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Show a contract's shadow-mode run of clean checks, label a stop as a real catch or a false stop, and turn gating on once it is offered (`docs/VERDICT_TIERS.md`).
Original file line number Diff line number Diff line change
@@ -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`), scope the frame to the setup's business entities (`learn entities`, admitted only if the planted faults are still caught), and write them into the contracts.
5 changes: 5 additions & 0 deletions packages/flow/openadapt_flow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13186,6 +13186,10 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None:

_register_shadow(sub)

from openadapt_flow.cli_gate import register as _register_gate

_register_gate(sub)

from openadapt_flow.cli_receipt import register as _register_receipt

_register_receipt(sub)
Expand Down Expand Up @@ -13735,6 +13739,7 @@ def _qualify_default_form(argv: list[str]) -> list[str]:
"openadapt_flow.cli_no_outbound:_cmd_list",
"openadapt_flow.cli_no_outbound:_cmd_remove",
"openadapt_flow.cli_local_seal:_guarded",
"openadapt_flow.cli_gate:cmd_gate",
"openadapt_flow.cli_receipt:cmd_anchor",
"openadapt_flow.cli_receipt:cmd_keys_export",
"openadapt_flow.cli_receipt:cmd_verify",
Expand Down
81 changes: 81 additions & 0 deletions packages/flow/openadapt_flow/cli_gate.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
"""CLI: ``openadapt-flow gate`` -- shadow mode and gating, per contract.

openadapt-flow gate status contract.yaml
openadapt-flow gate label contract.yaml <write_id> caught|false_stop
openadapt-flow gate enable contract.yaml --by "A. Reviewer"
openadapt-flow gate disable contract.yaml --by "A. Reviewer"

See ``openadapt_flow.enforcement`` and ``docs/VERDICT_TIERS.md``.
"""

from __future__ import annotations

import argparse
import json
import sys


def register(sub: argparse._SubParsersAction) -> None:
p = sub.add_parser(
"gate",
help="Show a contract's shadow run of clean checks, label a stop, or "
"turn gating on once it is offered",
allow_abbrev=False,
)
gsub = p.add_subparsers(dest="gate_command", required=True)
s = gsub.add_parser(
"status",
help="mode, clean checks in a row, whether gating is offered",
allow_abbrev=False,
)
s.add_argument("contract")
s.add_argument("--json", action="store_true")
s.set_defaults(func=cmd_gate)
s = gsub.add_parser(
"label",
help="label one stop: caught (a real harm) or false_stop",
allow_abbrev=False,
)
s.add_argument("contract")
s.add_argument("write_id")
s.add_argument("verdict", choices=("caught", "false_stop"))
s.set_defaults(func=cmd_gate)
for name, text in (
("enable", "turn gating on (only once it is offered)"),
("disable", "go back to shadow"),
):
s = gsub.add_parser(name, help=text, allow_abbrev=False)
s.add_argument("contract")
s.add_argument("--by", required=True, help="who decided")
s.set_defaults(func=cmd_gate)


def cmd_gate(args: argparse.Namespace) -> int:
from openadapt_flow import enforcement

digest = enforcement.contract_digest(args.contract)
if args.gate_command == "label":
enforcement.label(digest, args.write_id, args.verdict)
st = enforcement.status(digest)
elif args.gate_command == "enable":
try:
st = enforcement.enable(digest, args.by)
except enforcement.GateRefused as exc:
print(f"gate: {exc}", file=sys.stderr)
return 2
elif args.gate_command == "disable":
st = enforcement.disable(digest, args.by)
else:
st = enforcement.status(digest)
if getattr(args, "json", False):
print(json.dumps(st.to_dict(), indent=2))
return 0
print(f"mode: {st.mode}")
print(f"clean checks in a row: {st.clean_in_a_row} of {st.needed}")
print(f"checks recorded: {st.checks}; stops labelled false: {st.false_stops}")
if st.offered:
print(
"gating is offered: run `openadapt-flow gate enable "
f"{args.contract} --by <name>` to let this contract block"
)
return 0
Loading
Loading