diff --git a/capabilities/10-computer-use-agents/0158-wrap-the-same-task-again-on-the-same-app.md b/capabilities/10-computer-use-agents/0158-wrap-the-same-task-again-on-the-same-app.md new file mode 100644 index 0000000000..5036f3dbc5 --- /dev/null +++ b/capabilities/10-computer-use-agents/0158-wrap-the-same-task-again-on-the-same-app.md @@ -0,0 +1 @@ +| Wrap the same task again on the same app: when the app already has a record matching a canary's values (an earlier wrap's or attempt's canary), `openadapt wrap` adds a short random suffix (`oa` and six hex digits) to one text input of that canary, the longest public input that every claim of the new record binds as plain text (never a sign-in input, an email address, a URL, or an input the checks declare as a code or a typed value), so the second canary isn't confused with the first; otherwise the values are saved as written, and the record check still wants exactly one match. `"unique_canaries": false` in the task file saves the values as written. `status: admitted` exits 0 even when the attempt only admitted a kept draft (`verified: false`, with a stderr line that nothing was saved with the caller's inputs), and a run prints one plaintext-at-rest warning while the ledger keeps a line per write | In PR | Synthetic (the bundled clinic app, never reset between wraps, with saves not deduplicated: two wraps of one task both admit, the second canary with a suffix; with the suffix off the second canary halts on two matching records, and a CLI retry of that draft admits it with exit 0) and unit tests for the collision check, the input choice, `admit` with a stubbed canary (secret inputs unchanged), the exit status and the one-line warning (strict mode and a failed ledger write still refuse) | [WRAP_PUBLISH.md](packages/flow/docs/WRAP_PUBLISH.md#3-describe-the-task), `openadapt_flow.compile_agent.pipeline`, `openadapt_flow.at_rest.one_warning_line`, `packages/flow/tests/e2e/test_wrap_canary_unique_e2e.py`, `packages/flow/tests/test_wrap_rough_edges.py` | diff --git a/packages/flow/docs/WRAP_PUBLISH.md b/packages/flow/docs/WRAP_PUBLISH.md index 084db4f5de..c4bc6d1df6 100644 --- a/packages/flow/docs/WRAP_PUBLISH.md +++ b/packages/flow/docs/WRAP_PUBLISH.md @@ -63,6 +63,23 @@ Save this as `task.json`, with your app's address: `expect` names the fields that every record this task saves shares (here, the demo list). `verifier` is the read that checks the save independently. +`canary_params` are the values of the test save (the canary) that runs +before the program is admitted. The canary is a real save, so choose values +that are safe to write to the app. + +The checks want exactly one record that matches the canary's values. If the +app already has one, from an earlier wrap of the same task or an earlier +attempt, `wrap` adds a short random suffix to one text input of that canary, +for example `canary note 1 oa3f9c2e`. Otherwise the values are saved as +written. The suffix goes on the longest input that the checks compare as plain +text and whose value has a letter. It never goes on a sign-in input, an email +address, a URL, or an input the checks declare as a code (`map`) or a typed +value (`kind`). A field that accepts only certain text, such as a list of +options stored as their labels or a date written in words, can still get it, +and then the canary fails without saving anything wrong. To keep the values +exactly as written, add `"unique_canaries": false` and remove the earlier +canary's record before you wrap the task again. + ## 4. Wrap the task ```bash @@ -82,6 +99,35 @@ the run is a script. To admit without a person at the terminal, pass If the model key for `--provider` is not set, `wrap` stops before the agent starts with `[MISSING_MODEL_KEY]` and the variable to set. Nothing is recorded. +`wrap` prints one JSON result. `verified` says whether this call's own save +was read back `VERIFIED`: run 1's save on a first run, the program's save on +a later run. The exit status follows from it: + +| Exit status | When | +|---|---| +| 0 | `verified` is `true`, or `status` is `admitted`. | +| 1 | Anything else that ran, such as a run that halted or an attempt to check in the app (`RECONCILIATION_REQUIRED`). | +| 2 | Nothing ran: a setup problem, a missing model key, or `wrap run` with no admitted program. | +| 130 | Interrupted (Ctrl-C); the wrapped command was stopped. | + +Run 1 can save and be read back while the program is not admitted yet (a +`draft`, or a failed canary), so check `status` as well as the exit status. + +A program is admitted only after its canary ended `VERIFIED`, so admission +exits 0 even when `verified` is `false`. That happens when you run `wrap` +again after a failed canary: the earlier attempt's run 1 already saved your +values, so this attempt only runs the canary and admits the program. `wrap` +says on stderr that this attempt saved nothing with your inputs. Check the +app before you save the same values again. When you wrap your own agent +command (`-- COMMAND`) and it exits with an error, `wrap` exits with that +command's status instead. + +The first run writes a JIT draft (its recording, bundle and run folders) in +plaintext. `wrap` prints one warning about it per run, and every plaintext +write still gets a line in the plaintext ledger +(`~/.openadapt/plaintext-at-rest.jsonl` by default). With +`OPENADAPT_FLOW_AT_REST=strict`, Flow refuses to write the plaintext draft. + ## 5. Publish ```bash diff --git a/packages/flow/openadapt_flow/at_rest.py b/packages/flow/openadapt_flow/at_rest.py index 170fdba0bc..f999021d2b 100644 --- a/packages/flow/openadapt_flow/at_rest.py +++ b/packages/flow/openadapt_flow/at_rest.py @@ -78,6 +78,11 @@ _KEY_BYTES: Final[int] = 32 _lock = threading.Lock() _warned: set[str] = set() +#: Open :func:`one_warning_line` blocks, and whether one of them already +#: printed its line. Process-wide (not per thread): a wrapped run writes from +#: its MCP endpoint's threads too, and the run gets one line in all. +_one_line_depth = 0 +_one_line_printed = False class LocalKeyError(RuntimeError): @@ -135,6 +140,29 @@ def opted_out(source: str) -> Iterator[None]: os.environ[name] = value +@contextmanager +def one_warning_line() -> Iterator[None]: + """Print at most one plaintext-at-rest warning while the block runs. + + For one run of a command that writes several plaintext artifacts (a JIT + draft's recording, bundle and run directories): the first write prints + one line that names it and the ledger, and every later write in the block + gets its ledger line only. Nothing else changes: strict mode still + refuses before anything is written, and a write the ledger can't record + is still refused. + """ + global _one_line_depth, _one_line_printed + with _lock: + _one_line_depth += 1 + try: + yield + finally: + with _lock: + _one_line_depth -= 1 + if _one_line_depth == 0: + _one_line_printed = False + + def explicit_key() -> bool: """Whether the deployment configured a key (rather than the local one).""" return bool( @@ -286,12 +314,22 @@ def record_plaintext(purpose: str, reason: str) -> None: def _record( purpose: str, reason: str, *, warning: str, path: Optional[str] = None ) -> None: + global _one_line_printed strict() # an unknown mode stops here too, not only at the CLI with _lock: if purpose in _warned: return _warned.add(purpose) - print(warning, file=sys.stderr) + quiet = _one_line_depth > 0 and _one_line_printed + if _one_line_depth > 0 and not quiet: + _one_line_printed = True + warning = ( + "WARNING: this run writes files in plaintext that can hold " + f"patient data, starting with {purpose}. Each one is listed in " + f"{ledger_path()}. Set {MODE_ENV}=strict to refuse instead." + ) + if not quiet: + print(warning, file=sys.stderr) try: ledger = ledger_path() ledger.parent.mkdir(parents=True, exist_ok=True) @@ -845,5 +883,8 @@ def default_key() -> Optional[str]: def _reset_for_tests() -> None: + global _one_line_depth, _one_line_printed with _lock: _warned.clear() + _one_line_depth = 0 + _one_line_printed = False diff --git a/packages/flow/openadapt_flow/compile_agent/cli.py b/packages/flow/openadapt_flow/compile_agent/cli.py index 1e86e76396..841e1c39dc 100644 --- a/packages/flow/openadapt_flow/compile_agent/cli.py +++ b/packages/flow/openadapt_flow/compile_agent/cli.py @@ -327,8 +327,16 @@ def review(stage: str, shown: dict[str, Any]) -> bool: prompt = "Type ok to confirm you reviewed every step: " else: for canary in shown["canaries"]: + stamp = canary.get("stamp") or {} + # The suffix tells the person which record the canary saved. + suffix = ( + f" ({stamp['param']} ends in {stamp['suffix']})" + if stamp.get("param") and stamp.get("suffix") + else "" + ) print( - f"Canary: {canary['status']}, receipt {canary['receipt_outcome']}" + f"Canary: {canary['status']}, receipt " + f"{canary['receipt_outcome']}{suffix}" ) prompt = "Type ok to admit this program: " return ask(prompt).strip().lower() == "ok" diff --git a/packages/flow/openadapt_flow/compile_agent/pipeline.py b/packages/flow/openadapt_flow/compile_agent/pipeline.py index b05adbf6aa..b4ad65a2da 100644 --- a/packages/flow/openadapt_flow/compile_agent/pipeline.py +++ b/packages/flow/openadapt_flow/compile_agent/pipeline.py @@ -34,6 +34,7 @@ import hashlib import json import re +import secrets import time import uuid from dataclasses import dataclass, field @@ -1178,6 +1179,7 @@ def admit( person: Optional[str] = None, review: Optional[Callable[[str, dict[str, Any]], bool]] = None, canary_params: Optional[Sequence[Mapping[str, Any]]] = None, + unique_canaries: bool = False, ) -> CompileResult: """Canary the draft, then admit it. @@ -1194,6 +1196,14 @@ def admit( Each canary also gets a verify-run receipt against the confirmed checks; a canary passes only when both end VERIFIED. + + ``unique_canaries``: when a record already in the system of record + matches what a canary would save (an earlier attempt's or an earlier + wrap's canary), a short random suffix goes on one text input of that + canary (see :func:`_canary_stamp_param`), so the record check doesn't + find two matching records. The check still wants exactly one. With + no such record the values are saved as given. The values given are + checked against run 1's before any suffix is added. """ jit = self._jit() @@ -1248,6 +1258,19 @@ def admit( if getattr(self.task, "params", None) else rows[min(i, len(rows) - 1)] ) + stamp: Optional[dict[str, str]] = None + if unique_canaries and _canary_would_collide( + self.out_dir / CONFIRMED_FILE, + self.observer.system_of_record, + params, + ): + name = _canary_stamp_param( + self.out_dir / CONFIRMED_FILE, self._public_params(), params + ) + if name is not None: + suffix = "oa" + secrets.token_hex(3) + params = {**params, name: f"{params[name]} {suffix}"} + stamp = {"param": name, "suffix": suffix} values = self.task.validate(params) try: result, receipt, path = self._governed( @@ -1265,15 +1288,18 @@ def admit( "needs_person", str(exc), admission={"canaries": canaries} ) outcome = _receipt_outcome(receipt) - canaries.append( - { - "status": result.status, - "model_calls": result.model_calls, - "receipt_outcome": outcome, - "receipt": str(path) if path else None, - "halt_reason": result.halt_reason, - } - ) + entry: dict[str, Any] = { + "status": result.status, + "model_calls": result.model_calls, + "receipt_outcome": outcome, + "receipt": str(path) if path else None, + "halt_reason": result.halt_reason, + } + if stamp is not None: + # Which input got the suffix, so the person can find the + # canary's record in the app. Never a value. + entry["stamp"] = stamp + canaries.append(entry) if result.status != "VERIFIED" or outcome != "VERIFIED": return self._result( "canary_failed", @@ -1520,6 +1546,123 @@ def _duplicate_canary_rows( return None +def _canary_would_collide( + confirmed: Path, + records: Optional[Sequence[Mapping[str, Any]]], + row: Mapping[str, Any], +) -> bool: + """Whether a record already there could match what this canary saves. + + Compares each new-record claim's match with every record: a literal with + the record's field, an input with the canary's value, ignoring case and + repeated spaces. Anything it can't judge counts as a possible match + (no read, a claim routed to another read, an input the checks read as a + code or a typed value), so the canary then gets its suffix. + """ + + import yaml + + if records is None: + return True + try: + doc = yaml.safe_load(confirmed.read_text(encoding="utf-8")) or {} + except (OSError, yaml.YAMLError): + return True + claims = [ + effect + for effect in doc.get("effects") or [] + if isinstance(effect, dict) and _claims_new_record(effect, count_new_only=False) + ] + if not claims: + return True + + def text(value: Any) -> str: + return " ".join(str(value).split()).casefold() + + def same(stored: Any, wanted: Any) -> bool: + if isinstance(wanted, dict): + if isinstance(wanted.get("param"), str): + keys = {k for k, v in wanted.items() if v is not None} + value = row.get(wanted["param"]) + if not keys <= _STAMPABLE_BINDING_KEYS or value is None: + return True + wanted = value + elif "literal" in wanted: + wanted = wanted["literal"] + else: + return True + if stored is None or wanted is None: + return stored is None and wanted is None + return text(stored) == text(wanted) + + for claim in claims: + if str(claim.get("probe") or "").startswith(_SURFACE_ROUTE): + return True + match = claim.get("match") or {} + if not isinstance(match, dict) or not match: + return True + for record in records: + if all(same(record.get(field), want) for field, want in match.items()): + return True + return False + + +#: Binding keys a stamped input may carry. ``map`` (a select's codes), +#: ``kind`` (a typed value such as a date) and ``null`` mean the app or the +#: check would not take arbitrary text, so such an input is never stamped. +_STAMPABLE_BINDING_KEYS = frozenset({"param", "stored"}) + + +def _canary_stamp_param( + confirmed: Path, public: Sequence[str], row: Mapping[str, Any] +) -> Optional[str]: + """The one input a canary suffix goes on, or None when none can take it. + + A candidate is a public (never a secret) input that every claim of the + new record in the confirmed checks binds plainly, whose canary value is + free text: it has a letter and isn't an email address or a URL. The + longest value wins (a note rather than a short label), then the name. + The suffix keeps the record's match unique, so one input is enough. + """ + + import yaml + + try: + doc = yaml.safe_load(confirmed.read_text(encoding="utf-8")) or {} + except (OSError, yaml.YAMLError): + return None + plain: set[str] = set() + typed: set[str] = set() + for effect in doc.get("effects") or []: + if not isinstance(effect, dict) or not _claims_new_record( + effect, count_new_only=False + ): + continue + for binding in (effect.get("match") or {}).values(): + if not isinstance(binding, dict) or not isinstance( + binding.get("param"), str + ): + continue + keys = {k for k, v in binding.items() if v is not None} + if keys <= _STAMPABLE_BINDING_KEYS: + plain.add(binding["param"]) + else: + typed.add(binding["param"]) + candidates = [] + for name in sorted((plain - typed) & set(public)): + value = row.get(name) + if ( + isinstance(value, str) + and any(c.isalpha() for c in value) + and "@" not in value + and "://" not in value + ): + candidates.append(name) + if not candidates: + return None + return max(candidates, key=lambda name: (len(row[name]), name)) + + def compile_first_run( prompt: str, *, @@ -1538,6 +1681,7 @@ def compile_first_run( review: Optional[Callable[[str, dict[str, Any]], bool]] = None, hold: Optional[Callable[[GateRequest], bool]] = None, canary_params: Optional[Sequence[Mapping[str, Any]]] = None, + unique_canaries: bool = False, task_id: Optional[str] = None, policy: str = "clinical-write", cache_dir: Union[str, Path] = ".openadapt-compile-agent", @@ -1587,6 +1731,9 @@ def compile_first_run( canary_params: The values each canary saves, one mapping per canary (the last is reused). A canary is a real save on the record the task names, so choose values that are safe there. Required. + unique_canaries: When a record already matches a canary's values + (an earlier attempt's canary), add a short random suffix to one + text input of that canary (see :meth:`FirstRunCompiler.admit`). model_key: The customer's own model key, for a model-driven agent. reset: Called before every run to reset a test app. Tests only. before_capture: Trusted Python preparation/preflight on the exact @@ -1649,6 +1796,7 @@ def compile_first_run( person=person, review=review, canary_params=canary_params, + unique_canaries=unique_canaries, ) if first is not None: admitted.run1 = first.run1 diff --git a/packages/flow/openadapt_flow/integrations/agents/recording.py b/packages/flow/openadapt_flow/integrations/agents/recording.py index d7348c96ef..e22105dfe0 100644 --- a/packages/flow/openadapt_flow/integrations/agents/recording.py +++ b/packages/flow/openadapt_flow/integrations/agents/recording.py @@ -43,6 +43,7 @@ "constants", "allow_origins", "headless", + "unique_canaries", } ) _MAX_TASK_BYTES = 65_536 @@ -197,6 +198,8 @@ def load_task( strings[name] = value if type(task.get("headless", True)) is not bool: raise TaskSetupError("INVALID_TASK_OPTIONS") + if type(task.get("unique_canaries", True)) is not bool: + raise TaskSetupError("INVALID_TASK_OPTIONS") constants = _strings(task.get("constants", [])) origins = _strings(task.get("allow_origins", [])) from openadapt_flow.compile_agent.pipeline import check_target @@ -244,6 +247,10 @@ def load_task( "on_screen": on_screen, "offer": offer if offer is not None else (lambda _proposal: None), "canary_params": canaries, + # Each attempt suffixes one text input of its canary, so a second wrap + # of this task, or a retry, doesn't find the earlier canary's record + # too. ``"unique_canaries": false`` saves the values exactly as given. + "unique_canaries": task.get("unique_canaries", True), "cache_dir": cache_dir, "key_dir": key_dir, "admitter": admitter, diff --git a/packages/flow/openadapt_flow/integrations/agents/skills.py b/packages/flow/openadapt_flow/integrations/agents/skills.py index c413452ef6..9d7e7721e4 100644 --- a/packages/flow/openadapt_flow/integrations/agents/skills.py +++ b/packages/flow/openadapt_flow/integrations/agents/skills.py @@ -350,6 +350,7 @@ def __init__( environment: str = "", python: str = sys.executable, before_capture: Optional[Callable[[Any], None]] = None, + unique_canaries: bool = False, **compile_options: Any, ) -> None: if before_capture is not None and not callable(before_capture): @@ -368,6 +369,9 @@ def __init__( self.environment = environment self.offer = offer self.canary_params = [dict(row) for row in canary_params] + #: Suffix one text input of each canary, per attempt, so canary + #: records from earlier attempts don't collide (``admit``). + self.unique_canaries = bool(unique_canaries) self.admitter = admitter self.person = person self.drop_fields = list(drop_fields) @@ -915,6 +919,7 @@ def _first_run( admitter=self.admitter, person=self.person, canary_params=self.canary_params, + unique_canaries=self.unique_canaries, model_key=self.model_key, before_capture=self.before_capture, **common, diff --git a/packages/flow/openadapt_flow/wrap/cli.py b/packages/flow/openadapt_flow/wrap/cli.py index e47fce493f..61b61f93e4 100644 --- a/packages/flow/openadapt_flow/wrap/cli.py +++ b/packages/flow/openadapt_flow/wrap/cli.py @@ -648,7 +648,15 @@ def main(argv: Sequence[str] | None = None) -> int: serve(task) return 0 - with _commands_stopped_on_signal(agent is not None), _with_cdp_env(cdp_url): + from openadapt_flow import at_rest + + # One plaintext-at-rest line for the whole run, not one per artifact + # of the JIT draft; the ledger still lists every write. + with ( + _commands_stopped_on_signal(agent is not None), + _with_cdp_env(cdp_url), + at_rest.one_warning_line(), + ): result = task.call( args.request_id, _with_secret_env(values, task.parameters) ) @@ -726,7 +734,33 @@ def main(argv: Sequence[str] | None = None) -> int: if isinstance(exit_code, int) and exit_code != 0: # The wrapped command's own failure is its exit status. return exit_code if 0 < exit_code < 256 else 1 - return 0 if result.get("verified") is True else 1 + return _exit_status(result) + + +def _exit_status(result: Mapping[str, Any]) -> int: + """0 when this call's save was read back VERIFIED or the program was admitted. + + ``verified`` is this call's own save: run 1's record check on a first + run, the program's receipt and record check on a later run. A program + is admitted only after its canary (a test save in this call) ended + VERIFIED, so ``admitted`` is a success even when ``verified`` is false. + That is a retry that only admitted the kept draft (the earlier + attempt's run 1 made the save with these inputs), or a program that was + already admitted; either way this call made no save of its own. Say so, + so nobody saves the same values twice. Everything else is 1. + """ + + if result.get("verified") is True: + return 0 + if result.get("status") == "admitted": + print( + "openadapt wrap: the program is admitted. This attempt saved " + "nothing with your inputs; an earlier run may have saved them, " + "so check the app before you save these values again", + file=sys.stderr, + ) + return 0 + return 1 if __name__ == "__main__": diff --git a/packages/flow/tests/default_at_rest_skips.txt b/packages/flow/tests/default_at_rest_skips.txt index 0f94f394ea..ccb07c852b 100644 --- a/packages/flow/tests/default_at_rest_skips.txt +++ b/packages/flow/tests/default_at_rest_skips.txt @@ -2,6 +2,8 @@ # | . Group (a): the test reads or plants plaintext and the # product correctly refuses. Group (b, open): a known product limitation. +tests/e2e/test_wrap_canary_unique_e2e.py::test_same_values_still_halt_and_a_cli_retry_admits_with_exit_zero | known limitation (b, open): confirming a JIT draft's parameters recompiles it into its plaintext folder, which the default mode refuses; OpenAdaptAI/OpenAdapt#2842 fixes it +tests/e2e/test_wrap_canary_unique_e2e.py::test_two_wraps_of_one_task_both_admit_without_a_reset | known limitation (b, open): confirming a JIT draft's parameters recompiles it into its plaintext folder, which the default mode refuses; OpenAdaptAI/OpenAdapt#2842 fixes it tests/test_admit_pipeline.py::test_a_decision_file_written_without_the_admission_key_admits_nothing | the test plants or edits a plaintext file inside an encrypted set, or recompiles into a plaintext directory; the product refuses it, as it should tests/test_admit_pipeline.py::test_a_signed_decision_edited_afterwards_admits_nothing | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) tests/test_admit_pipeline.py::test_an_agent_admission_stops_applying_when_its_grant_does | the test reads a run, recording or bundle file from disk as plaintext; by default it is ciphertext in an encrypted set (the product reads it through the set) diff --git a/packages/flow/tests/e2e/test_wrap_canary_unique_e2e.py b/packages/flow/tests/e2e/test_wrap_canary_unique_e2e.py new file mode 100644 index 0000000000..c5c225fcc7 --- /dev/null +++ b/packages/flow/tests/e2e/test_wrap_canary_unique_e2e.py @@ -0,0 +1,270 @@ +"""Wrapping the same task twice against the same app, end to end. + +Everything is real: the bundled clinic app over HTTP, headless Chromium, an +outside command driving it through the MCP endpoint, the read-back, compile, +canary and admission by a registered admitter key. The app is never reset +between wraps, as on a staging server, and it does not dedupe saves (see +``_task_file``). + +- By default a canary whose values an earlier record already has gets a + short suffix on its note, so the second wrap's canary is the only record + that matches it and both wraps admit. The first canary is saved as written. +- With ``"unique_canaries": false`` the second canary finds the first one's + record too and halts: the record check still wants exactly one. +- Retrying that draft through the CLI only admits it (no new save with the + caller's inputs): ``status: admitted``, ``verified: false``, exit 0. +""" + +from __future__ import annotations + +import json +import sys +from pathlib import Path +from typing import Any, Iterator + +import pytest + +pytest.importorskip("playwright") +pytest.importorskip("mcp") +pytest.importorskip("uvicorn") + +from openadapt_flow.integrations.agents.recording import load_task # noqa: E402 +from openadapt_flow.mockmed.fault_server import serve # noqa: E402 +from openadapt_flow.teach_authorization_fixture import LocalAuthorizer # noqa: E402 +from openadapt_flow.tutorial import _http_json # noqa: E402 +from openadapt_flow.wrap import WrappedTask # noqa: E402 +from openadapt_flow.wrap.process import ProcessAgent # noqa: E402 + +pytestmark = pytest.mark.timeout(1200) +AGENT = Path(__file__).resolve().parents[2] / "examples" / "wrap_command" / "agent.py" +INSTRUCTION = ( + "Open the referral for Jane Sample, start a Triage encounter, and save " + "this note: {note}" +) +CANARY = "Synthetic canary note" + + +@pytest.fixture() +def clinic() -> Iterator[str]: + base, _db, stop = serve() + yield base.rstrip("/") + stop() + + +@pytest.fixture() +def admit_key(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> tuple[Path, Any]: + from openadapt_flow.jit import authority + + monkeypatch.setenv(authority.KEY_PASSPHRASE_ENV, "e2e passphrase") + key_dir = tmp_path / "keys" + pem = tmp_path / "keyfiles" / "ci.pem" + authority.register_principal( + key_dir, + role="admitter_key", + principal_id="ci:wrap-canary", + public_key_hex=authority.generate_encrypted_key(pem), + ) + return pem, authority.principal_from_key(authority.load_encrypted_key(pem), key_dir) + + +@pytest.fixture() +def signer(tmp_path: Path) -> LocalAuthorizer: + """The person who signs each run 1's teach authorization, with the + approver roster in the same key directory as the admitter key.""" + return LocalAuthorizer(tmp_path / "keys", "ci:wrap-canary-approver") + + +def _task_file(path: Path, base: str, cache: Path, **extra: Any) -> Path: + path.write_text( + json.dumps( + { + "schema": "openadapt.wrap-task/v1", + "instruction": INSTRUCTION, + "parameters": ["note"], + # Not ?idempotency=demo: that mode dedupes every save after + # the first on one fixed key, so without a reset no second + # canary lands. The clinical policies require that key, so + # this task uses the bundled permissive policy; the canary's + # record check is the same under every policy. + "url": f"{base}/?fault=ok#tasks", + "policy": "permissive", + "verifier": { + "kind": "rest", + "base_url": base, + "records_path": "/api/db", + "records_key": "records", + "records_complete": True, + }, + "expect": {"patient_id": "p1", "type": "Triage"}, + "on_screen": ["Jane Sample", "MRN P1"], + "canary_params": [{"note": CANARY}], + "cache_dir": str(cache), + **extra, + } + ) + ) + return path + + +def _wrap( + tmp_path: Path, + task_file: Path, + admitter: Any, + signer: LocalAuthorizer, + note: str, + name: str, +) -> dict[str, Any]: + """One wrap through the library, under a teach authorization for it.""" + from openadapt_flow.teach_scope import origin_of + + setup = load_task( + task_file, + offer=lambda proposal: "ci:wrap-canary-reviewer", + admitter=admitter, + key_dir=tmp_path / "keys", + ) + statement = signer.issue( + tmp_path / f"teach-authorization-{name}", + { + "task": { + "task_id": setup.cache.task_id(setup.instruction, {"note": note}), + "summary": "Save a note", + }, + "purposes": ["teach", "repair"], + "origins": [str(origin_of(setup.cache.common["url"]))], + "inputs": {"note": {"value": note}}, + "constants": [{"value": "Jane Sample"}, {"value": "MRN P1"}], + "writes": { + "record_kind": "encounter", + "identity": { + "patient_id": {"value": "p1"}, + "type": {"value": "Triage"}, + }, + "fields": {}, + }, + }, + ) + setup.cache.common["teach_authorization"] = signer.authority(statement) + task = WrappedTask( + cache=setup.cache, + agent=ProcessAgent([sys.executable, str(AGENT)], timeout_s=300), + instruction=setup.instruction, + parameters=setup.parameters, + runs_dir=tmp_path / f"runs-{name}", + ) + return task.call(name, {"note": note}) + + +def _notes(base: str) -> list[str]: + return [r["note"] for r in _http_json(f"{base}/api/db")["records"]] + + +def test_two_wraps_of_one_task_both_admit_without_a_reset( + clinic: str, + tmp_path: Path, + admit_key: tuple[Path, Any], + signer: LocalAuthorizer, +) -> None: + _pem, admitter = admit_key + _http_json(f"{clinic}/api/reset", method="POST", body={}) + for n, note in enumerate(["Follow-up in two weeks", "Recheck knee in ten days"]): + task_file = _task_file( + tmp_path / f"task-{n}.json", clinic, tmp_path / f"cache-{n}" + ) + result = _wrap(tmp_path, task_file, admitter, signer, note, f"wrap-{n}") + assert result["status"] == "admitted" and result["verified"] is True, result + canaries = [note for note in _notes(clinic) if note.startswith(CANARY)] + # The first canary saved the value as written; the second found that + # record already there, so its value got a suffix. + assert len(canaries) == 2 and canaries[0] == CANARY, canaries + assert ( + canaries[1].startswith(CANARY + " oa") and len(canaries[1]) == len(CANARY) + 9 + ) + + +def test_same_values_still_halt_and_a_cli_retry_admits_with_exit_zero( + clinic: str, + tmp_path: Path, + admit_key: tuple[Path, Any], + signer: LocalAuthorizer, + capsys: pytest.CaptureFixture[str], + monkeypatch: pytest.MonkeyPatch, +) -> None: + from openadapt_flow import at_rest + from openadapt_flow.approval_mode.approver_roster import ROOT_ENV + from openadapt_flow.wrap import cli + + pem, admitter = admit_key + _http_json(f"{clinic}/api/reset", method="POST", body={}) + first = _task_file( + tmp_path / "first.json", + clinic, + tmp_path / "cache-first", + unique_canaries=False, + ) + result = _wrap(tmp_path, first, admitter, signer, "Follow-up in two weeks", "first") + assert result["status"] == "admitted", result + assert _notes(clinic).count(CANARY) == 1 + + # The staging case: the same canary values again, on the same app. + second = _task_file( + tmp_path / "second.json", + clinic, + tmp_path / "cache-second", + unique_canaries=False, + ) + note = "Recheck knee in ten days" + result = _wrap(tmp_path, second, admitter, signer, note, "second") + # Run 1 saved and was read back, so this exits 0; status tells the rest. + assert result["status"] == "canary_failed" and result["verified"] is True, result + assert _notes(clinic).count(CANARY) == 2 + halts = [ + path + for path in (tmp_path / "cache-second").rglob("*.json") + if "records match the target selector but exactly 1 was expected" + in path.read_text(errors="replace") + ] + assert halts, "the second canary halted for another reason" + capsys.readouterr() + + # Retry the kept draft through the CLI with the default (suffixed) + # canary. Run 1 already saved, so this call only admits. + _task_file(tmp_path / "second.json", clinic, tmp_path / "cache-second") + # Admission checks run 1's teach authorization again: pin its roster. + monkeypatch.setenv(ROOT_ENV, signer.root) + at_rest._reset_for_tests() + code = cli.main( + [ + "--task", + str(second), + "--param", + "note=" + note, + "--key-dir", + str(tmp_path / "keys"), + "--admit-key", + str(pem), + "--runs-dir", + str(tmp_path / "runs-cli"), + "--", + sys.executable, + str(AGENT), + ] + ) + captured = capsys.readouterr() + retry = json.loads(captured.out.strip().splitlines()[-1]) + assert retry["status"] == "admitted" and retry["verified"] is False, ( + retry, + captured.err[-3000:], + ) + assert code == 0 + assert "saved nothing with your inputs" in captured.err + plaintext = [ + line + for line in captured.err.splitlines() + if line.startswith("WARNING") and "plaintext" in line + ] + assert len(plaintext) <= 1, plaintext + # The retry's canary got a suffix; the run-1 note was not saved again. + notes = _notes(clinic) + assert notes.count(note) == 1 + assert [n for n in notes if n.startswith(CANARY + " oa")], notes diff --git a/packages/flow/tests/test_wrap_rough_edges.py b/packages/flow/tests/test_wrap_rough_edges.py new file mode 100644 index 0000000000..46f05812e3 --- /dev/null +++ b/packages/flow/tests/test_wrap_rough_edges.py @@ -0,0 +1,478 @@ +"""Three edges of self-serve ``openadapt wrap`` found on staging (Nov 30). + +1. Canary values are suffixed per attempt, so a second wrap of a task does + not find the first canary's record too (the record check still wants + exactly one). +2. ``status: admitted`` exits 0, with a line saying nothing was saved with + the caller's inputs when ``verified`` is false. +3. A wrap run prints one plaintext-at-rest line, and the ledger still lists + every write; strict mode still refuses. + +The end-to-end runs on the real synthetic clinic app are in +``tests/e2e/test_wrap_canary_unique_e2e.py``. +""" + +from __future__ import annotations + +import json +import sqlite3 +from pathlib import Path + +import pytest +import yaml + +from openadapt_flow import at_rest, crypto, sealed_set +from openadapt_flow.compile_agent.pipeline import ( + CONFIRMED_FILE, + RUN1_VALUES_FILE, + FirstRunCompiler, + _canary_stamp_param, + _canary_would_collide, + _write_run1_values, +) +from openadapt_flow.integrations.agents.recording import TaskSetupError, load_task +from openadapt_flow.wrap.cli import _exit_status + +# -- 3. one plaintext line per run --------------------------------------------- + + +@pytest.fixture +def default_mode(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.MODE_ENV, + at_rest.ENCRYPT_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + ): + monkeypatch.delenv(name, raising=False) + monkeypatch.delenv(at_rest.LEDGER_DIR_ENV, raising=False) + home = tmp_path / "at-rest-home" + monkeypatch.setenv(at_rest.HOME_ENV, str(home)) + at_rest._reset_for_tests() + yield home + at_rest._reset_for_tests() + + +def _ledger(home: Path) -> list[dict]: + path = home / at_rest.LEDGER_NAME + if not path.exists(): + return [] + return [json.loads(line) for line in path.read_text().splitlines()] + + +def _warnings(err: str) -> list[str]: + return [line for line in err.splitlines() if line.startswith("WARNING")] + + +def test_a_run_prints_one_line_and_the_ledger_lists_every_write( + default_mode: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + with at_rest.one_warning_line(): + at_rest.unsealed_write("a JIT draft", tmp_path / "program") + with at_rest.opted_out("a JIT draft"): + assert at_rest.plaintext_allowed("a recording") + assert at_rest.plaintext_allowed("a compiled bundle") + at_rest.unsealed_write("a run directory", tmp_path / "runs" / "canary") + lines = _warnings(capsys.readouterr().err) + assert len(lines) == 1, lines + assert "a JIT draft at" in lines[0] + assert str(at_rest.ledger_path()) in lines[0] + assert "strict" in lines[0] + purposes = [row["purpose"] for row in _ledger(default_mode)] + assert len(purposes) == 4, purposes + assert purposes[1:3] == ["a recording", "a compiled bundle"] + + # After the run, each write warns on its own again. + at_rest.unsealed_write("a report", tmp_path / "report") + assert len(_warnings(capsys.readouterr().err)) == 1 + assert len(_ledger(default_mode)) == 5 + + +def test_nested_blocks_still_print_one_line( + default_mode: Path, tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + with at_rest.one_warning_line(): + at_rest.unsealed_write("one", tmp_path / "a") + with at_rest.one_warning_line(): + at_rest.unsealed_write("two", tmp_path / "b") + at_rest.unsealed_write("three", tmp_path / "c") + assert len(_warnings(capsys.readouterr().err)) == 1 + assert len(_ledger(default_mode)) == 3 + + +def test_strict_mode_still_refuses_inside_a_run( + default_mode: Path, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + monkeypatch.setenv(at_rest.MODE_ENV, "strict") + with at_rest.one_warning_line(): + with pytest.raises(at_rest.AtRestRefused, match="strict"): + at_rest.unsealed_write("a JIT draft", tmp_path / "program") + assert _ledger(default_mode) == [] + assert _warnings(capsys.readouterr().err) == [] + + +def test_a_write_the_ledger_cannot_record_is_still_refused_when_quiet( + default_mode: Path, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, + capsys: pytest.CaptureFixture[str], +) -> None: + with at_rest.one_warning_line(): + at_rest.unsealed_write("first", tmp_path / "a") + # The second write prints nothing, so its ledger line is its only + # record: when that can't be written, the write is refused. + blocked = tmp_path / "not-a-dir" + blocked.write_text("") + monkeypatch.setenv(at_rest.LEDGER_DIR_ENV, str(blocked)) + with pytest.raises(at_rest.AtRestRefused, match="ledger"): + at_rest.unsealed_write("second", tmp_path / "b") + assert len(_warnings(capsys.readouterr().err)) == 1 + + +# -- 1. which canary input gets the suffix ----------------------------------------- + + +def _confirmed(tmp_path: Path, match: dict) -> Path: + path = tmp_path / "verify.yaml" + path.write_text( + yaml.safe_dump( + { + "effects": [ + { + "kind": "record_written", + "expected_count": 1, + "count_new_only": True, + "match": match, + }, + # A "nothing else changed" check never decides the suffix. + { + "kind": "record_written", + "expected_count": 0, + "match": {"code": {"param": "code"}}, + }, + ] + } + ) + ) + return path + + +def test_the_suffix_goes_on_the_longest_plain_text_input(tmp_path: Path) -> None: + path = _confirmed( + tmp_path, + { + "list": {"literal": "demo"}, + "title": {"param": "title"}, + "body": {"param": "body", "stored": "upper"}, + }, + ) + row = {"title": "Canary", "body": "Synthetic canary body"} + assert _canary_stamp_param(path, ["title", "body"], row) == "body" + + +def test_typed_secret_and_non_text_inputs_never_get_the_suffix( + tmp_path: Path, +) -> None: + path = _confirmed( + tmp_path, + { + "state": {"param": "state", "map": {"Massachusetts": "MA"}}, + "due": {"param": "due", "kind": "date"}, + "email": {"param": "email"}, + "site": {"param": "site"}, + "count": {"param": "count"}, + "password": {"param": "password"}, + }, + ) + row = { + "state": "Massachusetts", + "due": "December 1 2026", + "email": "canary@example.com", + "site": "https://example.com/a", + "count": "12", + "password": "a long secret value here", + } + public = ["state", "due", "email", "site", "count"] + assert _canary_stamp_param(path, public, row) is None + + +def test_an_input_bound_with_a_map_in_any_claim_is_not_stamped( + tmp_path: Path, +) -> None: + path = tmp_path / "verify.yaml" + path.write_text( + yaml.safe_dump( + { + "effects": [ + { + "kind": "record_written", + "expected_count": 1, + "probe": "surface=a|x", + "match": {"label": {"param": "label"}}, + }, + { + "kind": "record_written", + "expected_count": 1, + "probe": "surface=b|x", + "match": {"label": {"param": "label", "map": {"A b": "1"}}}, + }, + ] + } + ) + ) + assert _canary_stamp_param(path, ["label"], {"label": "A b"}) is None + + +def test_no_confirmed_checks_means_no_suffix(tmp_path: Path) -> None: + assert ( + _canary_stamp_param(tmp_path / "missing.yaml", ["note"], {"note": "x"}) is None + ) + + +# -- 1. a suffix only when an earlier record could match ------------------------------ + + +def test_a_suffix_is_needed_only_when_a_record_already_matches(tmp_path: Path) -> None: + path = _confirmed( + tmp_path, + { + "list": {"literal": "demo"}, + "note": {"param": "note"}, + "state": {"param": "state", "map": {"Ohio": "OH"}}, + }, + ) + row = {"note": "Canary note", "state": "Ohio"} + # Nothing there yet (a first wrap): the values are saved as written. + assert not _canary_would_collide(path, [], row) + assert not _canary_would_collide( + path, [{"list": "demo", "note": "Follow-up"}, {"list": "other"}], row + ) + # An earlier canary's record (case and spacing aside) would match too. + assert _canary_would_collide(path, [{"list": "demo", "note": "canary note"}], row) + # Another list's record never matches the claim's literal. + assert not _canary_would_collide(path, [{"list": "x", "note": "Canary note"}], row) + + +def test_what_it_cannot_judge_counts_as_a_possible_match(tmp_path: Path) -> None: + path = _confirmed(tmp_path, {"note": {"param": "note"}}) + assert _canary_would_collide(path, None, {"note": "a"}) # no read + assert _canary_would_collide(tmp_path / "missing.yaml", [], {"note": "a"}) + routed = tmp_path / "routed.yaml" + routed.write_text( + yaml.safe_dump( + { + "effects": [ + { + "kind": "record_written", + "expected_count": 1, + "probe": "surface=a|x", + "match": {"note": {"param": "note"}}, + } + ] + } + ) + ) + assert _canary_would_collide(routed, [], {"note": "a"}) + + +class _Jit: + def __init__(self) -> None: + self.saved: list[dict] = [] + + def canary_params(self, params, *, principal_id): # noqa: ANN001 + self.saved.append(dict(params)) + + def admit_with_key(self, admitter): # noqa: ANN001 + return {"outcome": "admitted", "manifest": {"digest": "d"}} + + +class _Result: + status = "VERIFIED" + model_calls = 0 + halt_reason = None + detail = None + + +def _compiler(tmp_path: Path, records: list[dict]) -> tuple[FirstRunCompiler, _Jit]: + """An admit() with its collaborators stubbed: the canary saves nothing.""" + + compiler = object.__new__(FirstRunCompiler) + jit = _Jit() + out = tmp_path / "task-key" / "compiled" + out.mkdir(parents=True) + _confirmed(out, {"list": {"literal": "demo"}, "note": {"param": "note"}}) + (out / "verify.yaml").rename(out / CONFIRMED_FILE) + _write_run1_values(out / RUN1_VALUES_FILE, {"note": "run 1's note"}) + + class Task: + key = "task-key" + params = {"note": "str", "password": "str"} + + @staticmethod + def validate(row): # noqa: ANN001 + return {k: str(v) for k, v in row.items()} + + class Observer: + system_of_record = records + + def governed(kind, values, run): # noqa: ANN001 + run() + return _Result(), {"receipt": {"outcome": "verified"}}, None + + compiler.__dict__.update( + cache_dir=tmp_path, + task=Task, + observer=Observer, + expect={"list": "demo"}, + _jit=lambda: jit, + _confirmed_config=lambda: None, + _public_params=lambda: ["note"], + _governed=governed, + _result=lambda status, detail, **kw: {"status": status, **kw}, + ) + return compiler, jit + + +def test_admit_suffixes_a_public_input_when_an_earlier_canary_matches( + tmp_path: Path, +) -> None: + compiler, jit = _compiler(tmp_path, [{"list": "demo", "note": "canary"}]) + row = {"note": "canary", "password": "a long sign-in value"} + out = compiler.admit(admitter=object(), canary_params=[row], unique_canaries=True) + assert out["status"] == "admitted" + [saved] = jit.saved + assert saved["note"].startswith("canary oa") and len(saved["note"]) == 15 + assert saved["password"] == row["password"] # a secret never changes + [canary] = out["admission"]["canaries"] + assert canary["stamp"] == {"param": "note", "suffix": saved["note"][-8:]} + + +def test_admit_saves_the_values_as_written_with_no_earlier_match( + tmp_path: Path, +) -> None: + compiler, jit = _compiler(tmp_path, [{"list": "demo", "note": "other"}]) + out = compiler.admit( + admitter=object(), canary_params=[{"note": "canary"}], unique_canaries=True + ) + assert jit.saved == [{"note": "canary"}] + assert "stamp" not in out["admission"]["canaries"][0] + + +def test_admit_keeps_the_values_when_the_option_is_off(tmp_path: Path) -> None: + compiler, jit = _compiler(tmp_path, [{"list": "demo", "note": "canary"}]) + compiler.admit(admitter=object(), canary_params=[{"note": "canary"}]) + assert jit.saved == [{"note": "canary"}] + + +def test_the_terminal_canary_line_names_the_suffix( + capsys: pytest.CaptureFixture[str], +) -> None: + from openadapt_flow.compile_agent.cli import _terminal_review + + review = _terminal_review(lambda prompt: "ok") + shown = { + "canaries": [ + { + "status": "VERIFIED", + "receipt_outcome": "VERIFIED", + "stamp": {"param": "note", "suffix": "oa1b2c3d"}, + } + ] + } + assert review("admit", shown) + assert "note ends in oa1b2c3d" in capsys.readouterr().out + + +# -- 1. the task file turns it on by default ------------------------------------- + + +@pytest.fixture +def task(tmp_path: Path) -> tuple[Path, dict]: + database = tmp_path / "records.sqlite" + with sqlite3.connect(database) as connection: + connection.execute( + "CREATE TABLE entries (id INTEGER PRIMARY KEY, project TEXT, body TEXT)" + ) + document = { + "instruction": "Save {body}", + "parameters": ["body"], + "url": "http://127.0.0.1:8080/", + "verifier": { + "kind": "sql", + "sqlite_database": str(database), + "sql_query": "SELECT id, project, body FROM entries", + }, + "expect": {"project": "demo"}, + "on_screen": ["Demo"], + "canary_params": [{"body": "canary"}], + "cache_dir": "cache", + } + path = tmp_path / "task.json" + path.write_text(json.dumps(document)) + return path, document + + +def test_a_wrap_task_suffixes_canaries_unless_it_opts_out(task) -> None: + path, document = task + setup = load_task(path) + assert setup.cache.unique_canaries is True + # Not part of which task this is: opting out reuses the same program. + key = setup.cache.key(setup.instruction, {"body": ""}) + path.write_text(json.dumps({**document, "unique_canaries": False})) + setup = load_task(path) + assert setup.cache.unique_canaries is False + assert setup.cache.key(setup.instruction, {"body": ""}) == key + assert "unique_canaries" not in setup.cache.common + + +def test_unique_canaries_must_be_a_boolean(task) -> None: + path, document = task + path.write_text(json.dumps({**document, "unique_canaries": "no"})) + with pytest.raises(TaskSetupError, match="INVALID_TASK_OPTIONS"): + load_task(path) + + +# -- 2. exit status ------------------------------------------------------------------ + + +def test_admitted_exits_zero_and_says_nothing_was_saved_with_the_inputs( + capsys: pytest.CaptureFixture[str], +) -> None: + assert _exit_status({"status": "admitted", "verified": False}) == 0 + err = capsys.readouterr().err + assert "admitted" in err and "saved nothing with your inputs" in err + # An earlier run made the save: never suggest saving again. + assert "check the app before you save" in err + assert "wrap run" not in err + + +def test_a_verified_run_exits_zero_quietly( + capsys: pytest.CaptureFixture[str], +) -> None: + assert _exit_status({"status": "admitted", "verified": True}) == 0 + assert _exit_status({"status": "VERIFIED", "verified": True}) == 0 + assert capsys.readouterr().err == "" + + +def test_a_read_back_run_1_exits_zero_before_admission() -> None: + # ``verified`` is this call's own save; ``status`` says what became of it. + assert _exit_status({"status": "draft", "verified": True}) == 0 + assert _exit_status({"status": "canary_failed", "verified": True}) == 0 + + +@pytest.mark.parametrize( + "result", + [ + {"status": "draft", "verified": False}, + {"status": "canary_failed", "verified": False}, + {"status": "RECONCILIATION_REQUIRED", "verified": False}, + {"status": "CACHE_HALTED", "verified": False}, + {"status": "VERIFIED", "verified": "true"}, + ], +) +def test_everything_else_exits_one(result: dict) -> None: + assert _exit_status(result) == 1