diff --git a/packages/flow/benchmark/repair_every_backend/qualify_linux.py b/packages/flow/benchmark/repair_every_backend/qualify_linux.py index 000906c0c5..c8763fd055 100644 --- a/packages/flow/benchmark/repair_every_backend/qualify_linux.py +++ b/packages/flow/benchmark/repair_every_backend/qualify_linux.py @@ -63,11 +63,13 @@ from qualify_macos import ( # noqa: E402 APPROVER, + SELF_REPAIR_MODE, LaterAgent, _approver, _approver_roster, _find_text, _rows, + _self_repair_legs, ) APP_SOURCE = FLOW / "tests" / "native_apps" / "chart_gtk.py" @@ -149,6 +151,7 @@ def _point(backend: Any, role: str, name: str) -> tuple[int, int]: def _record(root: Path, db: Path) -> tuple[Path, dict]: """Record the healthy workflow on the old version and compile it.""" + from openadapt_flow import sealed_set as _sealed from openadapt_flow.compiler import compile_recording from openadapt_flow.ir import Workflow from openadapt_flow.policy import evaluate_policy, load_policy @@ -172,7 +175,9 @@ def _record(root: Path, db: Path) -> tuple[Path, dict]: finally: app.close() events_path = recording / "events.jsonl" - events = [json.loads(line) for line in events_path.read_text().splitlines()] + # Encrypted at rest by default (#2423): the recording is a sealed set, so + # read and rewrite its events through the sealed-set API (in memory). + events = [json.loads(line) for line in _sealed.read_text(events_path).splitlines()] pad = 6 for event in events: if event.get("kind") == "click": @@ -182,7 +187,7 @@ def _record(root: Path, db: Path) -> tuple[Path, dict]: banner[2] + 2 * pad, banner[3] + 2 * pad, ] - events_path.write_text("".join(json.dumps(e) + "\n" for e in events)) + _sealed.write_text(events_path, "".join(json.dumps(e) + "\n" for e in events)) bundle = root / "bundle" workflow = compile_recording(recording, bundle, name="chart-note-linux") save = workflow.steps[-1] @@ -200,7 +205,7 @@ def _record(root: Path, db: Path) -> tuple[Path, dict]: save.risk = "irreversible" for step in workflow.steps[:-1]: step.risk = "reversible" - (bundle / "manifest.json").unlink(missing_ok=True) + _sealed.unlink(bundle / "manifest.json", missing_ok=True) workflow.save(bundle, encrypt=bool(workflow.encrypted)) workflow = Workflow.load(bundle) report = evaluate_policy(workflow, load_policy("clinical-write")) @@ -371,9 +376,10 @@ def qualify(root: Path) -> dict[str, Any]: clean = _governed(root, bundle, "clean", None) other = _governed(root, bundle, "other-patient", "other_patient") look_alike = _governed(root, bundle, "look-alike", "look_alike") - checked = _repair(root, bundle, "repair-with-record-check") - no_verifier = _repair(root, bundle, "repair-no-verifier", verifier=False) - demo = _repair(root, bundle, "repair-demo-profile", profile="demo") + with _self_repair_legs(bundle, root / "repair-bundle") as plain: + checked = _repair(root, plain, "repair-with-record-check") + no_verifier = _repair(root, plain, "repair-no-verifier", verifier=False) + demo = _repair(root, plain, "repair-demo-profile", profile="demo") checks = { "demonstration_saved_one_row": _rows(demo_db) == [(PATIENT[0], DEMO_NOTE)], "bundle_certified": compiled["certified_clinical_write"], @@ -420,6 +426,7 @@ def qualify(root: Path) -> dict[str, Any]: if "repair_every_backend/results/" not in line ], "compiled": compiled, + "self_repair_mode": SELF_REPAIR_MODE, "governed_clean": clean, "governed_other_patient": other, "governed_look_alike": look_alike, @@ -455,6 +462,7 @@ def main() -> int: out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(report, indent=2) + "\n") print(f"linux atspi: {'PASSED' if report['passed'] else 'FAILED'} -> {out}") + print(f" self-repair legs ran {report['self_repair_mode']}") for name, ok in report["checks"].items(): print(f" {'ok ' if ok else 'BAD'} {name}") return 0 if report["passed"] else 1 diff --git a/packages/flow/benchmark/repair_every_backend/qualify_macos.py b/packages/flow/benchmark/repair_every_backend/qualify_macos.py index da7af589c5..7d783ff0c7 100644 --- a/packages/flow/benchmark/repair_every_backend/qualify_macos.py +++ b/packages/flow/benchmark/repair_every_backend/qualify_macos.py @@ -50,9 +50,10 @@ import sys import tempfile import time +from contextlib import contextmanager from datetime import datetime, timezone from pathlib import Path -from typing import Any, Optional +from typing import Any, Iterator, Optional FLOW = Path(__file__).resolve().parents[2] if str(FLOW) not in sys.path: @@ -188,6 +189,7 @@ def _rows(db: Path) -> list[tuple[str, str]]: def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]: """Record the healthy workflow on the old version and compile it.""" + from openadapt_flow import sealed_set as _sealed from openadapt_flow.compiler import compile_recording from openadapt_flow.ir import Workflow from openadapt_flow.policy import evaluate_policy, load_policy @@ -215,7 +217,9 @@ def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]: app.close() # The banner is every click's identity band (``--identifier`` in a browser). events_path = recording / "events.jsonl" - events = [json.loads(line) for line in events_path.read_text().splitlines()] + # Encrypted at rest by default (#2423): the recording is a sealed set, so + # read and rewrite its events through the sealed-set API (in memory). + events = [json.loads(line) for line in _sealed.read_text(events_path).splitlines()] pad = 6 for event in events: if event.get("kind") == "click": @@ -225,7 +229,7 @@ def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]: banner[2] + 2 * pad, banner[3] + 2 * pad, ] - events_path.write_text("".join(json.dumps(e) + "\n" for e in events)) + _sealed.write_text(events_path, "".join(json.dumps(e) + "\n" for e in events)) bundle = root / "bundle" workflow = compile_recording(recording, bundle, name=f"chart-note-{kind}") save = workflow.steps[-1] @@ -245,7 +249,7 @@ def _record(binary: Path, root: Path, kind: str, db: Path) -> tuple[Path, dict]: # ``openadapt-flow qualify set-risk`` records for a person). for step in workflow.steps[:-1]: step.risk = "reversible" - (bundle / "manifest.json").unlink(missing_ok=True) + _sealed.unlink(bundle / "manifest.json", missing_ok=True) workflow.save(bundle, encrypt=bool(workflow.encrypted)) workflow = Workflow.load(bundle) report = evaluate_policy(workflow, load_policy("clinical-write")) @@ -339,6 +343,40 @@ def open_session(fault: Optional[str]) -> Any: ) +#: How the self-repair legs run, recorded in the results and printed. Under +#: the encryption-at-rest default an attended approval (a person's decision, +#: which self-repair's probe and resume need) is refused in a sealed run +#: (#2423), so these legs alone run on a plaintext copy of the bundle under +#: the product's documented opt-out. Record, compile and the governed runs +#: stay under the default. +SELF_REPAIR_MODE = ( + "plaintext (known limitation: attended approvals are refused in sealed runs, #2423)" +) + + +@contextmanager +def _self_repair_legs(bundle: Path, dest: Path) -> Iterator[Path]: + """A plaintext copy of ``bundle`` at ``dest``, with encryption at rest + off (``at_rest.opted_out``, named on stderr and in the ledger) until the + block ends. The copy is decrypted in memory and saved under the same + content digest, so it is the same program.""" + from openadapt_flow import at_rest + from openadapt_flow.ir import Workflow + + print(f"self-repair legs: {SELF_REPAIR_MODE}", flush=True) + with at_rest.opted_out("qualification: self-repair legs (#2423 limitation)"): + source = Workflow.load(bundle) + source.save(dest) + copy = Workflow.load(dest) + if ( + copy.manifest is None + or source.manifest is None + or (copy.manifest.content_digest != source.manifest.content_digest) + ): + raise RuntimeError("the plaintext copy is not the same program") + yield dest + + def _repair( binary: Path, root: Path, @@ -431,9 +469,10 @@ def qualify(kind: str, root: Path) -> dict[str, Any]: binary = _build(root) demo_db = root / "sor-demo.db" bundle, compiled = _record(binary, root / "record", kind, demo_db) - checked = _repair(binary, root, bundle, kind, "with-record-check") - no_verifier = _repair(binary, root, bundle, kind, "no-verifier", verifier=False) - demo = _repair(binary, root, bundle, kind, "demo-profile", profile="demo") + with _self_repair_legs(bundle, root / "repair-bundle") as plain: + checked = _repair(binary, root, plain, kind, "with-record-check") + no_verifier = _repair(binary, root, plain, kind, "no-verifier", verifier=False) + demo = _repair(binary, root, plain, kind, "demo-profile", profile="demo") expected_basis = "element_and_record_check" if kind == "ax" else "record_check" checks = { "demonstration_saved_one_row": _rows(demo_db) == [(PATIENT[0], DEMO_NOTE)], @@ -485,6 +524,7 @@ def qualify(kind: str, root: Path) -> dict[str, Any]: if "repair_every_backend/results/" not in line ], "compiled": compiled, + "self_repair_mode": SELF_REPAIR_MODE, "repair_with_record_check": checked, "repair_without_verifier": no_verifier, "repair_under_demo_profile": demo, @@ -540,6 +580,7 @@ def main() -> int: out = RESULTS / f"macos-{mode}-{datetime.now(timezone.utc):%Y%m%d}.json" out.write_text(json.dumps(report, indent=2) + "\n") print(f"{kind}: {'PASSED' if report['passed'] else 'FAILED'} -> {out}") + print(f" self-repair legs ran {report['self_repair_mode']}") for name, ok in report["checks"].items(): print(f" {'ok ' if ok else 'BAD'} {name}") failed |= not report["passed"] diff --git a/packages/flow/openadapt_flow/bundle_persistence.py b/packages/flow/openadapt_flow/bundle_persistence.py index 4b47049c0b..0e1a4e9053 100644 --- a/packages/flow/openadapt_flow/bundle_persistence.py +++ b/packages/flow/openadapt_flow/bundle_persistence.py @@ -460,6 +460,43 @@ def prepare_derived_assets( workflow._pending_derived_assets = dict(candidate._pending_derived_assets) +def copy_bundle_files( + source: Path | str, destination: Path | str, *, ignore: Iterable[str] = () +) -> None: + """Copy a bundle's files to a new ``destination``, leaving out any path + with a component matching a pattern in ``ignore`` (as + ``shutil.ignore_patterns`` does). + + A plaintext source is copied as files. A sealed source becomes a new + sealed set written through its own writer: each file is decrypted in + memory and sealed again, so nothing lands in plaintext. A file-by-file copy + of a sealed set that leaves files out would not match the copied index, + and every reader refuses that. + """ + import fnmatch + import shutil + + from openadapt_flow import sealed_set as _sealed + + patterns = tuple(ignore) + source, destination = Path(source), Path(destination) + if not _sealed.is_sealed(source): + shutil.copytree(source, destination, ignore=shutil.ignore_patterns(*patterns)) + return + reader = _sealed.open_set(source) + passphrase = _sealed.output_bundle_key() + if not passphrase: + raise _sealed.SealedSetKeyError( + _sealed.missing_key_message(destination, "bundle") + ) + with _sealed.writing(destination, "bundle", passphrase): + for rel in reader.files(): + parts = rel.split("/") + if any(fnmatch.fnmatch(part, pat) for part in parts for pat in patterns): + continue + _sealed.write_bytes(destination / rel, reader.read_bytes(rel)) + + def copy_genesis_template_inputs( workflow: Workflow, source: Path | str, destination: Path | str ) -> None: diff --git a/packages/flow/openadapt_flow/compiler/compile.py b/packages/flow/openadapt_flow/compiler/compile.py index 20a3b056cb..0e089c0f4b 100644 --- a/packages/flow/openadapt_flow/compiler/compile.py +++ b/packages/flow/openadapt_flow/compiler/compile.py @@ -2345,7 +2345,7 @@ def _hover_evidence( return None # nothing answered the pointer: no evidence to keep crop_rel = f"{HOVER_CROP_DIR}/{step_id}.png" (bundle / HOVER_CROP_DIR).mkdir(parents=True, exist_ok=True) - (bundle / crop_rel).write_bytes(response.crop) + _sealed.write_bytes(bundle / crop_rel, response.crop) return HoverEvidence( response=True, region=hover_mod.relative(response.region, click), diff --git a/packages/flow/openadapt_flow/repair/cli.py b/packages/flow/openadapt_flow/repair/cli.py index 31841a0e2f..c999bcb46f 100644 --- a/packages/flow/openadapt_flow/repair/cli.py +++ b/packages/flow/openadapt_flow/repair/cli.py @@ -36,6 +36,11 @@ load_detached_candidate, register_bundle_candidate, ) +from openadapt_flow.runtime.heal import ( + has_heal_frame, + heal_frame_path, + read_heal_frame, +) DEFAULT_STORE = "repair-store" @@ -202,8 +207,8 @@ def _campaign_inputs( step = steps.get(step_id) if step is None or step.anchor is None: continue - frame_path = run_dir / "heals" / step_id / "screen.png" - if not frame_path.is_file(): + frame_path = heal_frame_path(run_dir, step_id) + if not has_heal_frame(run_dir, step_id): raise RepairLifecycleError( f"refused (fail closed): no evidence frame for changed step " f"{step_id!r} at {frame_path}" @@ -214,7 +219,9 @@ def _campaign_inputs( if template is None: template_path = bundle / step.anchor.template template = template_path.read_bytes() if template_path.is_file() else None - inputs.append((step_id, step.anchor, frame_path.read_bytes(), template)) + inputs.append( + (step_id, step.anchor, read_heal_frame(run_dir, step_id), template) + ) if not inputs: raise RepairLifecycleError( "refused (fail closed): the candidate has no changed anchored " diff --git a/packages/flow/openadapt_flow/repair/relabel.py b/packages/flow/openadapt_flow/repair/relabel.py index 744e3f47ec..6cf0e8f7fa 100644 --- a/packages/flow/openadapt_flow/repair/relabel.py +++ b/packages/flow/openadapt_flow/repair/relabel.py @@ -315,9 +315,9 @@ def build( _uncertify_patch(patched) if out_dir.exists(): shutil.rmtree(out_dir) - shutil.copytree( - bundle_dir, out_dir, ignore=shutil.ignore_patterns("repair", "manifest.json") - ) + from openadapt_flow.bundle_persistence import copy_bundle_files + + copy_bundle_files(bundle_dir, out_dir, ignore=("repair", "manifest.json")) patched.save(out_dir, encrypt=bool(workflow.encrypted), key=key) return out_dir diff --git a/packages/flow/openadapt_flow/repair/self_repair.py b/packages/flow/openadapt_flow/repair/self_repair.py index 40286d422f..0495555618 100644 --- a/packages/flow/openadapt_flow/repair/self_repair.py +++ b/packages/flow/openadapt_flow/repair/self_repair.py @@ -71,6 +71,7 @@ from pathlib import Path from typing import TYPE_CHECKING, Any, Callable, Mapping, Optional, Protocol, Sequence +from openadapt_flow import sealed_set as _sealed from openadapt_flow.approval_mode.gate import ApprovalGate, GateVerdict, SaveContext from openadapt_flow.approval_mode.model import ItemDecisionKind from openadapt_flow.approval_mode.post import ItemDecision @@ -1162,7 +1163,11 @@ def _patch( from openadapt_flow.compiler.compile import _postconditions from openadapt_flow.repair.registration import build_candidate from openadapt_flow.run_gate import is_consequential - from openadapt_flow.runtime.heal import persist_heal + from openadapt_flow.runtime.heal import ( + persist_heal, + read_heal_frame, + write_heal_frame, + ) assert step.anchor is not None natives = proposal.bridge() @@ -1287,9 +1292,7 @@ def _patch( if admission.basis == BASIS_RECORD_IDENTITY else f"clicks {label!r} (checked by the record check)" ) - frame_dir = evidence_dir / "heals" / new_id - frame_dir.mkdir(parents=True, exist_ok=True) - (frame_dir / "screen.png").write_bytes(screen) + write_heal_frame(evidence_dir, new_id, screen) touched[0] = True session.backend.click( int(point[0]), int(point[1]), double=op.kind == "double_click" @@ -1360,18 +1363,20 @@ def _patch( patched.steps = steps bundle_out = attempt_dir / "bundle" from openadapt_flow.bundle_persistence import ( + copy_bundle_files, copy_genesis_template_inputs, prepare_derived_assets, validate_derived_asset_paths, ) changes = {} + # Staged through the sealed set (an encrypted run holds them sealed). staged = evidence_dir / "expect" / "templates" - staged_paths = ( - {f"templates/{path.name}": path for path in staged.iterdir()} - if staged.is_dir() - else {} - ) + staged_paths = { + f"templates/{path.name}": path + for path in _sealed.list_files(staged) + if path.parent.name == "templates" + } for step_id, crop in crops.items(): target = next(s for s in steps if s.id == step_id) assert target.anchor is not None @@ -1383,25 +1388,27 @@ def _patch( patched, bundle_out, { - **{rel: path.read_bytes() for rel, path in staged_paths.items()}, + **{rel: _sealed.read_bytes(path) for rel, path in staged_paths.items()}, **changes, }, output="encrypted" if workflow.encrypted else "plain", ) if bundle_out.exists(): shutil.rmtree(bundle_out) - shutil.copytree( - bundle_dir, - bundle_out, - ignore=shutil.ignore_patterns("repair", "manifest.json", "templates"), + # A sealed source makes a sealed patched bundle (a nested set in the + # run), never a partial copy of the source's index. + copy_bundle_files( + bundle_dir, bundle_out, ignore=("repair", "manifest.json", "templates") ) copy_genesis_template_inputs(patched, bundle_dir, bundle_out) patched.save(bundle_out, encrypt=bool(workflow.encrypted)) run_dir = attempt_dir.parent.parent halted_report = run_dir / "report.json" evidence_dir.mkdir(parents=True, exist_ok=True) - if halted_report.is_file(): - shutil.copy2(halted_report, evidence_dir / "report.json") + if _sealed.is_file(halted_report): + _sealed.write_bytes( + evidence_dir / "report.json", _sealed.read_bytes(halted_report) + ) candidate = build_candidate( bundle_dir, bundle_out, @@ -1416,9 +1423,7 @@ def _patch( candidate.taught_steps = [ TaughtStep( step_id=s.id, - frame_sha256=sha256_hex( - (evidence_dir / "heals" / s.id / "screen.png").read_bytes() - ), + frame_sha256=sha256_hex(read_heal_frame(evidence_dir, s.id)), ) for s in new_steps if s.anchor is not None @@ -2489,8 +2494,8 @@ def _finish( pass if status != "not_needed": work.mkdir(parents=True, exist_ok=True) - (work / "self-repair.json").write_text( - evidence.model_dump_json(indent=2), encoding="utf-8" + _sealed.write_text( + work / "self-repair.json", evidence.model_dump_json(indent=2) ) return SelfRepairResult( status=status, @@ -3241,7 +3246,8 @@ def _before_frame(run_dir: Path, result: Any) -> Optional[bytes]: return None path = run_dir / rel try: - return path.read_bytes() + # A missing frame is no frame; a tampered sealed one still refuses. + return _sealed.read_bytes(path) except OSError: return None diff --git a/packages/flow/openadapt_flow/runtime/heal.py b/packages/flow/openadapt_flow/runtime/heal.py index 18ab450cdd..31516d8474 100644 --- a/packages/flow/openadapt_flow/runtime/heal.py +++ b/packages/flow/openadapt_flow/runtime/heal.py @@ -281,6 +281,37 @@ def apply_heal(workflow: Workflow, event: HealEvent) -> None: raise ValueError(f"workflow has no step {event.step_id!r}") +def heal_frame_path(run_dir: Path | str, step_id: str) -> Path: + """Where a step's heal evidence frame lives: ``run_dir/heals//screen.png``.""" + return Path(run_dir) / "heals" / step_id / _HEAL_SCREEN_NAME + + +def write_heal_frame(run_dir: Path | str, step_id: str, frame_png: bytes) -> Path: + """Write a step's heal evidence frame as given (its digest is taken over + these bytes), through the sealed set when ``run_dir`` is in one, so a + screenshot never lands in plaintext inside an encrypted run.""" + from openadapt_flow import sealed_set + + path = heal_frame_path(run_dir, step_id) + path.parent.mkdir(parents=True, exist_ok=True) + sealed_set.write_bytes(path, frame_png) + return path + + +def has_heal_frame(run_dir: Path | str, step_id: str) -> bool: + """Whether ``run_dir`` holds a heal evidence frame for ``step_id``.""" + from openadapt_flow import sealed_set + + return sealed_set.is_file(heal_frame_path(run_dir, step_id)) + + +def read_heal_frame(run_dir: Path | str, step_id: str) -> bytes: + """A step's heal evidence frame, decrypted in memory when sealed.""" + from openadapt_flow import sealed_set + + return sealed_set.read_bytes(heal_frame_path(run_dir, step_id)) + + def persist_heal( event: HealEvent, crop_png: bytes, @@ -311,7 +342,7 @@ def persist_heal( from openadapt_flow import sealed_set sealed_set.write_bytes(heal_dir / _HEAL_TEMPLATE_NAME, _scrub_png(crop_png)) - sealed_set.write_bytes(heal_dir / _HEAL_SCREEN_NAME, _scrub_png(frame_png)) + write_heal_frame(run_dir, event.step_id, _scrub_png(frame_png)) event.screenshot = f"heals/{event.step_id}/{_HEAL_SCREEN_NAME}" sealed_set.write_text(heal_dir / _HEAL_JSON_NAME, event.model_dump_json(indent=2)) return heal_dir diff --git a/packages/flow/tests/test_heal_evidence_sealed.py b/packages/flow/tests/test_heal_evidence_sealed.py new file mode 100644 index 0000000000..67b3575cf5 --- /dev/null +++ b/packages/flow/tests/test_heal_evidence_sealed.py @@ -0,0 +1,139 @@ +"""Heal evidence frames inside an encrypted run directory stay sealed. + +Self-repair writes the frame each new bridge step was captured from under +``run_dir/self-repair/attempt-N/evidence/heals//screen.png``. Under the +encryption-at-rest default the run directory is a sealed set, so that +screenshot (which can show a person's record) must be written through the +set: a plaintext file there is a leak, and the next write to the run (the +report) refuses the whole set. +""" + +from __future__ import annotations + +from pathlib import Path +from types import SimpleNamespace + +import pytest + +from openadapt_flow import at_rest, crypto, sealed_set +from openadapt_flow.bundle_persistence import copy_bundle_files +from openadapt_flow.ir import Workflow +from openadapt_flow.repair.self_repair import _before_frame +from openadapt_flow.runtime.heal import ( + has_heal_frame, + heal_frame_path, + read_heal_frame, + write_heal_frame, +) +from tests.test_sealed_at_rest import ( + KEY, + PNG_SIGNATURE, + _assert_ciphertext_only, + _png, + sealed_pair, # noqa: F401 - the shared sealed-bundle fixture +) + + +@pytest.fixture +def sealed_run(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> Path: + """A finalized sealed run directory under the default at-rest mode.""" + for name in ( + at_rest.OPT_OUT_ENV, + at_rest.MODE_ENV, + at_rest.ENCRYPT_ENV, + crypto.ENV_KEY, + sealed_set.RECORDING_ENV_KEY, + "OPENADAPT_POLICY", + ): + monkeypatch.delenv(name, raising=False) + monkeypatch.setenv(at_rest.HOME_ENV, str(tmp_path / "at-rest-home")) + at_rest._reset_for_tests() + run_dir = tmp_path / "run" + with sealed_set.writing(run_dir, "run", crypto.resolve_key(None)): + sealed_set.write_text(run_dir / "report.json", "{}") + assert sealed_set.is_sealed(run_dir) + yield run_dir + at_rest._reset_for_tests() + + +def _plaintext_pngs(root: Path) -> list[Path]: + return [ + p + for p in root.rglob("*") + if p.is_file() and p.read_bytes().startswith(PNG_SIGNATURE) + ] + + +def test_a_bridge_frame_in_a_sealed_run_is_sealed_and_readable( + sealed_run: Path, +) -> None: + evidence = sealed_run / "self-repair" / "attempt-1" / "evidence" + frame = _png() + write_heal_frame(evidence, "step_000_bridge_1", frame) + + # The set still opens, and a later write to it (the run report, as + # self-repair's finish does) is accepted rather than refused. + sealed_set.open_set(sealed_run) + sealed_set.write_text(sealed_run / "report.json", '{"ok": true}') + sealed_set.open_set(sealed_run) + + assert not heal_frame_path(evidence, "step_000_bridge_1").exists() + assert _plaintext_pngs(sealed_run) == [] + _assert_ciphertext_only(sealed_run) + assert has_heal_frame(evidence, "step_000_bridge_1") + assert read_heal_frame(evidence, "step_000_bridge_1") == frame + + +def test_a_plain_run_keeps_its_frame_where_reviewers_look(tmp_path: Path) -> None: + frame = _png() + path = write_heal_frame(tmp_path / "run", "step_000_bridge_1", frame) + assert path == tmp_path / "run" / "heals" / "step_000_bridge_1" / "screen.png" + assert path.read_bytes() == frame + assert read_heal_frame(tmp_path / "run", "step_000_bridge_1") == frame + + +def test_the_halted_frame_is_read_through_the_sealed_run(sealed_run: Path) -> None: + frame = _png(shade=200) + sealed_set.write_bytes(sealed_run / "steps" / "step_000_before.png", frame) + halted = SimpleNamespace(before_png="steps/step_000_before.png") + assert _before_frame(sealed_run, halted) == frame + missing = SimpleNamespace(before_png="steps/step_009_before.png") + assert _before_frame(sealed_run, missing) is None + + +def test_a_patched_copy_of_a_sealed_bundle_is_a_sealed_set_that_opens( + sealed_pair: tuple[Path, Path], # noqa: F811 - the shared fixture + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + """Self-repair copies the bundle without its templates and manifest and + then saves the patch into the copy. A file copy of a sealed set that + leaves files out no longer matches its index, and the save refused it.""" + source, _ = sealed_pair + monkeypatch.setenv(crypto.ENV_KEY, KEY) + workflow = Workflow.load(source) + out = tmp_path / "patched" + copy_bundle_files(source, out, ignore=("repair", "manifest.json", "templates")) + copied = sealed_set.open_set(out).files() + assert copied + assert not [r for r in copied if r == "manifest.json" or r.startswith("templates/")] + _assert_ciphertext_only(out) + + patched = workflow.model_copy(deep=True) + patched.name = "patched-copy" + patched.save(out, encrypt=True) + sealed_set.open_set(out).verify_all() + _assert_ciphertext_only(out) + assert _plaintext_pngs(out) == [] + assert Workflow.load(out).name == "patched-copy" + + +def test_a_plain_bundle_copy_is_a_plain_file_copy(tmp_path: Path) -> None: + source = tmp_path / "plain" + (source / "templates").mkdir(parents=True) + (source / "workflow.json").write_text("{}") + (source / "manifest.json").write_text("{}") + (source / "templates" / "a.png").write_bytes(_png()) + out = tmp_path / "copy" + copy_bundle_files(source, out, ignore=("manifest.json", "templates")) + assert sorted(p.name for p in out.rglob("*")) == ["workflow.json"]