From 7e87bad60afbb6bc4b13d8e09ea1a6d36aae7c0c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:18:35 -0500 Subject: [PATCH 1/3] fix(kernel): require a signed VERIFIED_AUTOPILOT pack for autopilot Autopilot read the pack's stage from unsigned JSON and never checked it, so a SHADOW pack could submit through run_portal_pack, the CLI and MCP. - run_portal_pack(mode="autopilot") now loads the pack through the registry's signature, digest and zero-PII check against a pinned key (trusted_pack_public_key / --trusted-pack-pub) and requires the signed stage to be VERIFIED_AUTOPILOT. Anything else returns ESCALATED before the browser opens. Draft mode still accepts flat or signed packs. - NonDomKernelExecutor: autonomy_stage can only lower the pack's stage. - Self-heal no longer promotes or publishes its own pack; it qualified the pack against the values it had just written. - MCP server: mode ceiling, keys and output root are server config (serve-mcp flags). Tool calls default to draft, cannot pass key paths or other undeclared arguments, and write only under the output root. - pull_verified_pack raises ValueError instead of relying on assert. - New publish-pack command; README drops the stale line-count claim. - Version 0.2.0. --- packages/kernel/CHANGELOG.md | 12 + packages/kernel/README.md | 34 +- packages/kernel/pyproject.toml | 2 +- packages/kernel/src/openadapt_kernel/cli.py | 57 ++- .../kernel/src/openadapt_kernel/mcp_server.py | 117 +++++- .../src/openadapt_kernel/nondom_adapter.py | 21 +- .../kernel/src/openadapt_kernel/registry.py | 46 ++- .../kernel/src/openadapt_kernel/runner.py | 124 +++--- packages/kernel/tests/_signed_packs.py | 33 ++ .../kernel/tests/test_autopilot_stage_gate.py | 371 ++++++++++++++++++ .../kernel/tests/test_kernel_hardening.py | 11 + .../kernel/tests/test_kernel_runner_e2e.py | 8 + packages/kernel/tests/test_oracles_and_mcp.py | 5 + .../kernel/tests/test_probe_aci_and_suite.py | 4 + .../tests/test_receipt_bridge_and_nondom.py | 56 +++ .../test_runtime_wiring_and_raw_demos.py | 6 + packages/kernel/tests/test_unified_runtime.py | 25 +- packages/kernel/uv.lock | 2 +- 18 files changed, 822 insertions(+), 112 deletions(-) create mode 100644 packages/kernel/tests/_signed_packs.py create mode 100644 packages/kernel/tests/test_autopilot_stage_gate.py diff --git a/packages/kernel/CHANGELOG.md b/packages/kernel/CHANGELOG.md index 109bf88630..168d56ca3f 100644 --- a/packages/kernel/CHANGELOG.md +++ b/packages/kernel/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## v0.2.0 (2026-11-29) + +Breaking: autopilot now fails closed on any pack that is not signed and promoted. + +- `run_portal_pack(mode="autopilot")` and `openadapt-kernel run --mode autopilot` load the pack through the registry's Ed25519 signature, digest and zero-PII check against a pinned key (`trusted_pack_public_key` / `--trusted-pack-pub`). A missing key, unsigned file, foreign key, edited envelope, or a signed stage other than `VERIFIED_AUTOPILOT` returns `ESCALATED` with zero submissions. Draft mode still loads flat or signed packs. +- `NonDomKernelExecutor.execute(autonomy_stage=...)` can only lower the pack's stage; unknown stages resolve to `SHADOW`. +- Self-healing no longer promotes or publishes the healed pack. It used to qualify the pack against its own written values. `auto_publish_on_heal` and `registry_dir` are kept for compatibility but publish nothing. +- MCP server: mode ceiling, trusted pack key, receipt key and output root are server configuration (`McpServerConfig`, `serve-mcp --allow-autopilot --trusted-pack-pub --priv --output-root`). Tool calls default to draft, cannot request autopilot unless the server allows it, cannot pass `private_key_path` or any other undeclared argument, and write only under the output root. +- `pull_verified_pack` raises `ValueError` for non-envelope files, non-Ed25519 keys and bad signatures instead of relying on `assert`. +- New `openadapt-kernel publish-pack` command signs a pack into a registry directory. +- README: removed the stale line-count claim. + ## v0.1.0 (2026-11-25) - Initial release of `openadapt-kernel` with zero `openadapt-flow` dependencies and zero per-app engine code. diff --git a/packages/kernel/README.md b/packages/kernel/README.md index b496394214..e25582b1de 100644 --- a/packages/kernel/README.md +++ b/packages/kernel/README.md @@ -1,6 +1,6 @@ # openadapt-kernel -Minimal, self-contained runtime kernel (`< 3,200` LOC, zero `openadapt-flow` dependencies, zero per-app code) implementing commit-boundary verification, cross-rail read-back, reversible occlusion probing, online ACI calibration, macro staging, stepwise live-DOM healing, and shadow-to-autopilot execution: +Self-contained runtime kernel (zero `openadapt-flow` dependencies, zero per-app code) implementing commit-boundary verification, cross-rail read-back, reversible occlusion probing, online ACI calibration, macro staging, stepwise live-DOM healing, and shadow-to-autopilot execution: 1. **Default-Deny Obligation, Capability, and Saga Ledger (`ledger.py`):** Episodes start `UNVERIFIED` and emit `VERIFIED` only when every obligation has an independent post-commit read-back proof and zero dirty form buffers remain. Step-limit timeouts, crashes, and unverified exits deterministically return `ESCALATED`. Carries both cross-screen `` and `` (user consent and SSA opaque-ID provenance), with durable Saga checkpointing across multi-system workflows. 2. **Wire and DOM-Effect Commit Interceptor (`interceptor.py`):** Detects commits from actual network mutations (`POST`, `PUT`, `PATCH`, `DELETE`) or non-empty dirty form submissions instead of button-label regexes. Excludes search/filter inputs from dirty buffers and escapes escalation payloads safely. @@ -15,8 +15,36 @@ Minimal, self-contained runtime kernel (`< 3,200` LOC, zero `openadapt-flow` dep openadapt-kernel shadow-sync --dir ./recordings --pack-id portal-v1 --out pack.json openadapt-kernel qualify --pack pack.json --evidence ./recordings/run_1/extension_evidence.jsonl openadapt-kernel keygen --priv priv.pem --pub pub.pem +openadapt-kernel keygen --priv pack_priv.pem --pub pack_pub.pem openadapt-kernel run --pack pack.json --dossier dossier.json --mode draft --cdp-url http://127.0.0.1:9222 -openadapt-kernel run --pack pack.json --dossier dossier.json --mode autopilot --url https://portal.example --commit-selector '[data-testid="submit-btn"]' --priv priv.pem --receipt-out receipt.json +openadapt-kernel publish-pack --pack promoted_pack.json --priv pack_priv.pem --registry-dir ./registry +openadapt-kernel run --pack ./registry/portal-v1-.pack.json --dossier dossier.json --mode autopilot --trusted-pack-pub pack_pub.pem --url https://portal.example --commit-selector '[data-testid="submit-btn"]' --priv priv.pem --receipt-out receipt.json openadapt-kernel verify-receipt --receipt receipt.json --pub pub.pem -openadapt-kernel serve-mcp +openadapt-kernel serve-mcp --output-root ./mcp-out ``` + +## Autopilot needs a signed, promoted pack + +`--mode autopilot` submits only when the pack file is a signed +`openadapt.kernel.pack/v1` envelope that verifies against `--trusted-pack-pub` +and whose signed stage is `VERIFIED_AUTOPILOT`. An unsigned file, a pack signed +by another key, an envelope edited after signing, or a `SHADOW` or +`DRAFT_TO_COMMIT` stage returns `ESCALATED` before the browser opens, and +nothing is submitted. Draft mode accepts unsigned packs because it stops +before the commit control. + +Signing with `publish-pack` is the promotion step, so whoever holds the pack +key approves autopilot. Keep that key apart from the receipt key (`--priv`), +which the runner holds. A self-healed run never publishes or promotes its own +pack. + +`NonDomKernelExecutor.execute(autonomy_stage=...)` can only lower a pack's +stage, never raise it. + +## MCP server limits + +The model calling the MCP tools does not set how far a run may go. Autopilot, +the trusted pack key, the receipt key and the output root are `serve-mcp` flags +(`--allow-autopilot`, `--trusted-pack-pub`, `--priv`, `--output-root`). Tool +calls run in draft unless the server allows autopilot, cannot pass key paths, +and can write only under the output root (default `~/.openadapt/kernel/mcp`). diff --git a/packages/kernel/pyproject.toml b/packages/kernel/pyproject.toml index c00ec879f5..4001cc2c03 100644 --- a/packages/kernel/pyproject.toml +++ b/packages/kernel/pyproject.toml @@ -4,7 +4,7 @@ build-backend = "hatchling.build" [project] name = "openadapt-kernel" -version = "0.1.0" +version = "0.2.0" description = "Minimal commit-boundary verification, macro-action staging, stepwise live-DOM healing, and shadow-to-autopilot kernel for GUI agents" readme = "README.md" requires-python = ">=3.11" diff --git a/packages/kernel/src/openadapt_kernel/cli.py b/packages/kernel/src/openadapt_kernel/cli.py index cdced87290..64451b1449 100644 --- a/packages/kernel/src/openadapt_kernel/cli.py +++ b/packages/kernel/src/openadapt_kernel/cli.py @@ -28,7 +28,7 @@ induce_pack_from_extension_recordings, parse_extension_evidence_jsonl, ) -from openadapt_kernel.mcp_server import serve_stdio +from openadapt_kernel.mcp_server import DEFAULT_OUTPUT_ROOT, McpServerConfig, serve_stdio from openadapt_kernel.prepare import ( PrepareCard, PrepareResumeResponse, @@ -36,6 +36,7 @@ UnresolvedSlot, resume_from_prepare_card, ) +from openadapt_kernel.registry import portal_pack_from_dict, publish_signed_pack from openadapt_kernel.runner import format_run_result_json, run_portal_pack from openadapt_kernel.stateful_twin import synthesize_twin_with_coding_agent @@ -129,6 +130,14 @@ def _cmd_verify_receipt(args: argparse.Namespace) -> int: return 0 if valid else 1 +def _cmd_publish_pack(args: argparse.Namespace) -> int: + """Sign a flat pack JSON into the registry. Holding the key is the approval.""" + pack = portal_pack_from_dict(json.loads(Path(args.pack).read_text(encoding="utf-8"))) + out = publish_signed_pack(pack, Path(args.priv).read_bytes(), Path(args.registry_dir)) + print(json.dumps({"pack_id": pack.pack_id, "stage": pack.stage, "out": str(out)})) + return 0 + + def _cmd_run(args: argparse.Namespace) -> int: dossier = json.loads(Path(args.dossier).read_text(encoding="utf-8")) result = run_portal_pack( @@ -142,6 +151,9 @@ def _cmd_run(args: argparse.Namespace) -> int: receipt_out=Path(args.receipt_out) if args.receipt_out else None, episode_id=args.episode_id, headless=not args.headed, + trusted_pack_public_key=( + Path(args.trusted_pack_pub).read_bytes() if args.trusted_pack_pub else None + ), ) print(format_run_result_json(result)) return 0 if result.outcome in ("READY_FOR_HUMAN_COMMIT", "VERIFIED") else 1 @@ -166,8 +178,19 @@ def _cmd_shadow_sync(args: argparse.Namespace) -> int: return 0 -def _cmd_serve_mcp(_args: argparse.Namespace) -> int: - serve_stdio() +def _cmd_serve_mcp(args: argparse.Namespace) -> int: + if args.allow_autopilot and not args.trusted_pack_pub: + raise ValueError("serve-mcp --allow-autopilot requires --trusted-pack-pub") + serve_stdio( + config=McpServerConfig( + allow_autopilot=bool(args.allow_autopilot), + trusted_pack_public_key_path=( + Path(args.trusted_pack_pub) if args.trusted_pack_pub else None + ), + private_key_path=Path(args.priv) if args.priv else None, + output_root=Path(args.output_root), + ) + ) return 0 @@ -402,6 +425,15 @@ def build_parser() -> argparse.ArgumentParser: p_ver.add_argument("--pub", required=True) p_ver.set_defaults(func=_cmd_verify_receipt) + p_pub = sub.add_parser( + "publish-pack", + help="Sign a PortalPack with the pack-approval key and write it to a registry directory", + ) + p_pub.add_argument("--pack", required=True) + p_pub.add_argument("--priv", required=True, help="Ed25519 pack-approval private key PEM") + p_pub.add_argument("--registry-dir", required=True) + p_pub.set_defaults(func=_cmd_publish_pack) + p_run = sub.add_parser("run", help="Run a PortalPack in draft or verified autopilot mode") p_run.add_argument("--pack", required=True) p_run.add_argument("--dossier", required=True) @@ -413,6 +445,13 @@ def build_parser() -> argparse.ArgumentParser: p_run.add_argument("--receipt-out") p_run.add_argument("--episode-id", default=None) p_run.add_argument("--headed", action="store_true") + p_run.add_argument( + "--trusted-pack-pub", + help=( + "Ed25519 public key PEM that must have signed the pack. Required for " + "--mode autopilot; the signed stage must be VERIFIED_AUTOPILOT." + ), + ) p_run.set_defaults(func=_cmd_run) p_sync = sub.add_parser("shadow-sync", help="Scan a directory of Chrome Co-Pilot recordings and induce a PortalPack") @@ -422,6 +461,18 @@ def build_parser() -> argparse.ArgumentParser: p_sync.set_defaults(func=_cmd_shadow_sync) p_mcp = sub.add_parser("serve-mcp", help="Run the zero-dependency stdio JSON-RPC 2.0 MCP server") + p_mcp.add_argument( + "--allow-autopilot", + action="store_true", + help="Let tool calls request autopilot (still needs a pack signed by --trusted-pack-pub)", + ) + p_mcp.add_argument("--trusted-pack-pub", help="Ed25519 public key PEM that signs autopilot packs") + p_mcp.add_argument("--priv", help="Ed25519 private key PEM used to sign run receipts") + p_mcp.add_argument( + "--output-root", + default=str(DEFAULT_OUTPUT_ROOT), + help="Directory every tool-written file must resolve under", + ) p_mcp.set_defaults(func=_cmd_serve_mcp) p_twin = sub.add_parser("twin-synthesize", help="Synthesize a Zero-PHI StatefulTwinApp via a coding agent CLI") diff --git a/packages/kernel/src/openadapt_kernel/mcp_server.py b/packages/kernel/src/openadapt_kernel/mcp_server.py index 5ae7d70971..7b31215ee0 100644 --- a/packages/kernel/src/openadapt_kernel/mcp_server.py +++ b/packages/kernel/src/openadapt_kernel/mcp_server.py @@ -6,6 +6,12 @@ - kernel_qualify_offline - kernel_run_pack (draft or verified autopilot) - kernel_verify_receipt + +The model calling these tools does not choose how far a run may go. The +autopilot ceiling, the receipt signing key, the trusted pack key and the +output root are server configuration (:class:`McpServerConfig`, set from +``openadapt-kernel serve-mcp`` flags). A tool call may lower a run to draft, +and every file it writes must resolve under the output root. """ from __future__ import annotations @@ -13,7 +19,7 @@ import json import re import sys -from dataclasses import asdict +from dataclasses import asdict, dataclass from pathlib import Path from typing import Any, Dict, List, Optional, TextIO @@ -24,7 +30,35 @@ ) from openadapt_kernel.runner import run_portal_pack -SERVER_INFO = {"name": "openadapt-kernel", "version": "0.1.0"} +SERVER_INFO = {"name": "openadapt-kernel", "version": "0.2.0"} + +DEFAULT_OUTPUT_ROOT = Path.home() / ".openadapt" / "kernel" / "mcp" + + +@dataclass(frozen=True) +class McpServerConfig: + """Operator-set limits for tool calls. Tool arguments cannot widen them. + + Defaults are the safe ones: draft only, no signing key, writes confined to + ``DEFAULT_OUTPUT_ROOT``. + """ + + allow_autopilot: bool = False + trusted_pack_public_key_path: Optional[Path] = None + private_key_path: Optional[Path] = None + output_root: Path = DEFAULT_OUTPUT_ROOT + + +def _sandboxed_output_path(config: McpServerConfig, requested: str) -> Path: + """Resolve a tool-supplied output path; refuse anything outside the root.""" + root = Path(config.output_root).expanduser().resolve() + candidate = Path(requested).expanduser() + if not candidate.is_absolute(): + candidate = root / candidate + resolved = candidate.resolve() + if not resolved.is_relative_to(root): + raise ValueError(f"output path {requested!r} is outside the server output root {str(root)!r}") + return resolved TOOLS_SPEC: List[Dict[str, Any]] = [ { @@ -65,7 +99,12 @@ }, { "name": "kernel_run_pack", - "description": "Execute a PortalPack in draft (stop before submit) or verified autopilot mode with fresh-reload/cross-tab read-back.", + "description": ( + "Execute a PortalPack in draft (stop before submit) or, when the server " + "enables it, verified autopilot with fresh-reload/cross-tab read-back. " + "Autopilot needs a pack signed by the server's trusted key at stage " + "VERIFIED_AUTOPILOT." + ), "inputSchema": { "type": "object", "properties": { @@ -75,7 +114,6 @@ "url": {"type": "string"}, "cdp_url": {"type": "string"}, "commit_selector": {"type": "string"}, - "private_key_path": {"type": "string"}, "receipt_out": {"type": "string"}, "episode_id": {"type": "string"}, }, @@ -106,14 +144,49 @@ def _token_boundary_verifier(fields: Dict[str, str], text: str) -> bool: ) -def dispatch_tool_call(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: +_TOOL_ARGS: Dict[str, frozenset[str]] = { + spec["name"]: frozenset(spec["inputSchema"]["properties"]) for spec in TOOLS_SPEC +} + + +def _check_arguments(name: str, arguments: Dict[str, Any]) -> None: + allowed = _TOOL_ARGS.get(name) + if allowed is None: + raise ValueError(f"Unknown tool: {name}") + extra = sorted(set(arguments) - allowed) + if extra: + raise ValueError( + f"{name} does not accept {', '.join(extra)}; signing keys, trusted keys " + "and the autopilot ceiling are server configuration" + ) + + +def _resolve_run_mode(config: McpServerConfig, requested: Any) -> str: + mode = "draft" if requested is None else str(requested) + if mode not in ("draft", "autopilot"): + raise ValueError(f"unknown mode {mode!r}") + if mode == "autopilot" and not config.allow_autopilot: + raise ValueError( + "mode 'autopilot' is not enabled by the MCP server configuration; " + "tool calls may only run in draft" + ) + return mode + + +def dispatch_tool_call( + name: str, + arguments: Dict[str, Any], + config: Optional[McpServerConfig] = None, +) -> Dict[str, Any]: + cfg = config if config is not None else McpServerConfig() + _check_arguments(name, arguments) if name == "kernel_induce_pack": sessions = [ (Path(s["evidence_path"]), dict(s["dossier"]), None) for s in arguments["sessions"] ] + out = _sandboxed_output_path(cfg, str(arguments["out_path"])) pack = induce_pack_from_extension_recordings(arguments["pack_id"], sessions) - out = Path(arguments["out_path"]) out.parent.mkdir(parents=True, exist_ok=True) out.write_text(json.dumps(asdict(pack), indent=2), encoding="utf-8") return {"ok": True, "pack": asdict(pack), "out_path": str(out)} @@ -137,17 +210,29 @@ def dispatch_tool_call(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: return {"ok": report.qualified, "report": asdict(report)} if name == "kernel_run_pack": + mode = _resolve_run_mode(cfg, arguments.get("mode")) + receipt_out = ( + _sandboxed_output_path(cfg, str(arguments["receipt_out"])) + if arguments.get("receipt_out") + else None + ) + trusted_pub = ( + Path(cfg.trusted_pack_public_key_path).read_bytes() + if mode == "autopilot" and cfg.trusted_pack_public_key_path + else None + ) res = run_portal_pack( pack_path=Path(arguments["pack_path"]), dossier={str(k): str(v) for k, v in arguments["dossier"].items()}, - mode=arguments.get("mode", "draft"), + mode=mode, # type: ignore[arg-type] url=arguments.get("url"), cdp_url=arguments.get("cdp_url"), commit_selector=arguments.get("commit_selector"), - private_key_path=Path(arguments["private_key_path"]) if arguments.get("private_key_path") else None, - receipt_out=Path(arguments["receipt_out"]) if arguments.get("receipt_out") else None, + private_key_path=cfg.private_key_path, + receipt_out=receipt_out, episode_id=arguments.get("episode_id") or None, headless=True, + trusted_pack_public_key=trusted_pub, ) return {"ok": res.outcome in ("READY_FOR_HUMAN_COMMIT", "VERIFIED"), "result": asdict(res)} @@ -160,7 +245,9 @@ def dispatch_tool_call(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: raise ValueError(f"Unknown tool: {name}") -def handle_jsonrpc_message(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]: +def handle_jsonrpc_message( + msg: Dict[str, Any], config: Optional[McpServerConfig] = None +) -> Optional[Dict[str, Any]]: req_id = msg.get("id") method = str(msg.get("method") or "") params = msg.get("params") or {} @@ -183,7 +270,7 @@ def handle_jsonrpc_message(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]: try: tool_name = str(params.get("name") or "") tool_args = dict(params.get("arguments") or {}) - payload = dispatch_tool_call(tool_name, tool_args) + payload = dispatch_tool_call(tool_name, tool_args, config) return { "jsonrpc": "2.0", "id": req_id, @@ -208,7 +295,11 @@ def handle_jsonrpc_message(msg: Dict[str, Any]) -> Optional[Dict[str, Any]]: } -def serve_stdio(stdin: TextIO = sys.stdin, stdout: TextIO = sys.stdout) -> None: +def serve_stdio( + stdin: TextIO = sys.stdin, + stdout: TextIO = sys.stdout, + config: Optional[McpServerConfig] = None, +) -> None: """Line-delimited JSON-RPC 2.0 stdio loop.""" for raw in stdin: line = raw.strip() @@ -216,7 +307,7 @@ def serve_stdio(stdin: TextIO = sys.stdin, stdout: TextIO = sys.stdout) -> None: continue try: msg = json.loads(line) - reply = handle_jsonrpc_message(msg) + reply = handle_jsonrpc_message(msg, config) except Exception as exc: reply = {"jsonrpc": "2.0", "id": None, "error": {"code": -32700, "message": str(exc)}} if reply is not None: diff --git a/packages/kernel/src/openadapt_kernel/nondom_adapter.py b/packages/kernel/src/openadapt_kernel/nondom_adapter.py index 9a4ad12af9..e2c9f1eee2 100644 --- a/packages/kernel/src/openadapt_kernel/nondom_adapter.py +++ b/packages/kernel/src/openadapt_kernel/nondom_adapter.py @@ -346,6 +346,22 @@ def _default_steps_from_pack( return steps +_STAGE_RANK: Dict[str, int] = {"SHADOW": 0, "DRAFT_TO_COMMIT": 1, "VERIFIED_AUTOPILOT": 2} + + +def _lower_stage(pack_stage: Any, override: Optional[Any]) -> AutonomyStage: + """Return the lower of the pack's stage and an optional override. + + Unknown stage strings rank below SHADOW, so they resolve to SHADOW. + """ + candidates = [pack_stage] if override is None else [pack_stage, override] + ranks = [_STAGE_RANK.get(str(c), -1) for c in candidates] + lowest = min(ranks) + if lowest < 0: + return "SHADOW" + return candidates[ranks.index(lowest)] # type: ignore[no-any-return] + + class NonDomKernelExecutor: """Drives a PortalPack / PrepareCard plan on a pixel-only backend with OCR read-back. @@ -451,9 +467,8 @@ def execute( episode_id: Optional[str] = None, ) -> NonDomExecutionResult: """Execute a PortalPack or PrepareCard step plan on the configured pixel backend.""" - effective_stage: AutonomyStage = ( - autonomy_stage if autonomy_stage is not None else pack.stage - ) + # The override may lower the pack's stage, never raise it. + effective_stage: AutonomyStage = _lower_stage(pack.stage, autonomy_stage) signing_key = private_key if private_key is not None else self._private_key resolved_key_id = key_id if key_id is not None else self._key_id diff --git a/packages/kernel/src/openadapt_kernel/registry.py b/packages/kernel/src/openadapt_kernel/registry.py index 85d5890bce..d593e11705 100644 --- a/packages/kernel/src/openadapt_kernel/registry.py +++ b/packages/kernel/src/openadapt_kernel/registry.py @@ -19,6 +19,7 @@ from pathlib import Path from typing import Any, Dict, List +from cryptography.exceptions import InvalidSignature from cryptography.hazmat.primitives.asymmetric.ed25519 import Ed25519PrivateKey, Ed25519PublicKey from cryptography.hazmat.primitives.serialization import load_pem_private_key, load_pem_public_key @@ -65,7 +66,8 @@ def publish_signed_pack( digest = hashlib.sha256(canonical).hexdigest() priv = load_pem_private_key(private_key_pem, password=None) - assert isinstance(priv, Ed25519PrivateKey) + if not isinstance(priv, Ed25519PrivateKey): + raise ValueError("PortalPack signing key must be an Ed25519 private key") sig_b64 = base64.b64encode(priv.sign(canonical)).decode("ascii") envelope = SignedPackEnvelope( @@ -80,19 +82,9 @@ def publish_signed_pack( return out -def pull_verified_pack(pack_file: Path, public_key_pem: bytes) -> PortalPack: - """Verify Ed25519 signature, SHA-256 digest, and zero-PII invariant before loading.""" - data = json.loads(pack_file.read_text(encoding="utf-8")) - pack_dict = data["pack"] - canonical = json.dumps(pack_dict, sort_keys=True, separators=(",", ":")).encode("utf-8") - if hashlib.sha256(canonical).hexdigest() != data.get("pack_sha256"): - raise ValueError("PortalPack SHA-256 digest mismatch") - - pub = load_pem_public_key(public_key_pem) - assert isinstance(pub, Ed25519PublicKey) - pub.verify(base64.b64decode(data["signature_b64"]), canonical) - - pack = PortalPack( +def portal_pack_from_dict(pack_dict: Dict[str, Any]) -> PortalPack: + """Build a PortalPack from its JSON form. Does not check any signature.""" + return PortalPack( pack_id=pack_dict["pack_id"], portal_origin=pack_dict["portal_origin"], variable_fields=list(pack_dict.get("variable_fields") or []), @@ -103,6 +95,32 @@ def pull_verified_pack(pack_file: Path, public_key_pem: bytes) -> PortalPack: shadow_passes=int(pack_dict.get("shadow_passes", 0)), edge_branches=dict(pack_dict.get("edge_branches") or {}), ) + + +def pull_verified_pack(pack_file: Path, public_key_pem: bytes) -> PortalPack: + """Verify Ed25519 signature, SHA-256 digest, and zero-PII invariant before loading. + + Raises on any failure, including a file that is not a signed envelope. + """ + data = json.loads(pack_file.read_text(encoding="utf-8")) + if not isinstance(data, dict) or data.get("schema") != "openadapt.kernel.pack/v1": + raise ValueError("PortalPack file is not a signed openadapt.kernel.pack/v1 envelope") + pack_dict = data["pack"] + if not isinstance(pack_dict, dict): + raise ValueError("Signed PortalPack envelope has no pack object") + canonical = json.dumps(pack_dict, sort_keys=True, separators=(",", ":")).encode("utf-8") + if hashlib.sha256(canonical).hexdigest() != data.get("pack_sha256"): + raise ValueError("PortalPack SHA-256 digest mismatch") + + pub = load_pem_public_key(public_key_pem) + if not isinstance(pub, Ed25519PublicKey): + raise ValueError("Trusted PortalPack key must be an Ed25519 public key") + try: + pub.verify(base64.b64decode(data["signature_b64"], validate=True), canonical) + except InvalidSignature as exc: + raise ValueError("PortalPack Ed25519 signature does not verify") from exc + + pack = portal_pack_from_dict(pack_dict) if scan_pack_for_pii(pack): raise ValueError("Pulled PortalPack failed zero-PII check") return pack diff --git a/packages/kernel/src/openadapt_kernel/runner.py b/packages/kernel/src/openadapt_kernel/runner.py index f0254916a8..35432c5423 100644 --- a/packages/kernel/src/openadapt_kernel/runner.py +++ b/packages/kernel/src/openadapt_kernel/runner.py @@ -36,14 +36,15 @@ from openadapt_kernel.oracles import verify_cross_tab_dom, verify_pdf_readback, verify_sqlite_ro from openadapt_kernel.prepare import ( PrepareCard, - PrepareResolution, PrepareResumeResponse, UnresolvedSlot, - qualify_and_promote_pack, resume_from_prepare_card, ) from openadapt_kernel.probe import probe_before_click -from openadapt_kernel.registry import publish_signed_pack +from openadapt_kernel.registry import ( + portal_pack_from_dict, + pull_verified_pack, +) from openadapt_kernel.zero_phi_repair import replay_distilled_zero_phi_repair RunMode = Literal["draft", "autopilot"] @@ -94,18 +95,34 @@ def _sign_terminal_receipt( def _load_portal_pack(path: Path) -> PortalPack: + """Load a pack for draft mode, from a flat JSON pack or a signed envelope. + + No signature is checked here. Autopilot never uses this loader; it goes + through :func:`_load_autopilot_pack`. + """ data = json.loads(path.read_text(encoding="utf-8")) - return PortalPack( - pack_id=data["pack_id"], - portal_origin=data["portal_origin"], - variable_fields=list(data.get("variable_fields") or []), - static_defaults=dict(data.get("static_defaults") or {}), - provenance_map=dict(data.get("provenance_map") or {}), - readback_url_pattern=str(data.get("readback_url_pattern") or ""), - stage=data.get("stage", "SHADOW"), - shadow_passes=int(data.get("shadow_passes", 0)), - edge_branches=dict(data.get("edge_branches") or {}), - ) + if isinstance(data, dict) and isinstance(data.get("pack"), dict) and "signature_b64" in data: + data = data["pack"] + return portal_pack_from_dict(data) + + +def _load_autopilot_pack( + path: Path, trusted_public_key: Optional[bytes] +) -> tuple[Optional[PortalPack], str]: + """Return the pack only if it is signed by the trusted key and promoted. + + Fails closed: any missing key, unsigned file, bad digest, bad signature, + PII hit or stage other than VERIFIED_AUTOPILOT returns ``(None, reason)``. + """ + if not trusted_public_key: + return None, "autopilot_requires_trusted_pack_key" + try: + pack = pull_verified_pack(path, trusted_public_key) + except Exception as exc: # noqa: BLE001 - every failure must refuse autopilot + return None, f"autopilot_pack_signature_invalid:{type(exc).__name__}:{exc}" + if pack.stage != "VERIFIED_AUTOPILOT": + return None, f"autopilot_pack_stage_not_verified:{pack.stage}" + return pack, "" def _compute_bindings(pack: PortalPack, dossier: Dict[str, str]) -> Dict[str, str]: @@ -150,10 +167,6 @@ def _attempt_twin_self_heal_and_publish( sqlite_db_path: Optional[Path], sqlite_query: Optional[str], pdf_readback_path: Optional[Path], - auto_publish_on_heal: bool, - registry_dir: Optional[Path], - signing_key: Optional[bytes], - private_key_path: Optional[Path], use_bijective_twin_symbols: bool = False, ) -> tuple[bool, Any, str, Optional[str]]: symbol_codec = BijectiveSymbolCodec() if use_bijective_twin_symbols else None @@ -202,39 +215,12 @@ def _attempt_twin_self_heal_and_publish( if not verdict.verified: return False, verdict, heal_res.egress_ledger_entry_sha256, None + # A healed pack is never promoted or published from here. The only + # "observed" values this path has are the bindings it just wrote, so + # qualifying on them would compare the expected values with themselves. + # Promotion to VERIFIED_AUTOPILOT needs an independent read-back and goes + # through qualify_and_promote_pack and publish_signed_pack outside the run. published_path: Optional[str] = None - key_bytes = signing_key or (private_key_path.read_bytes() if private_key_path else None) - if auto_publish_on_heal and registry_dir is not None and key_bytes is not None: - schemas = { - k: DossierVariableSchema(var_name=k, field_type="casefold_ws", role_tokens=tokenize_role_label(k)) - for k in expected_vars - } - staged_map = {i: k for i, k in enumerate(expected_vars.keys())} - card = PrepareCard( - card_id=f"heal-{pack.pack_id}", - portal_origin=pack.portal_origin, - staged_bindings=staged_map, - control_labels=dict(staged_map), - ) - resolution = PrepareResolution( - card_id=card.card_id, - operator_id="auto_twin_healer", - slot_bindings=staged_map, - approve_all=False, - ) - promo = qualify_and_promote_pack( - pack_id=pack.pack_id, - card=card, - resolution=resolution, - variable_schemas=schemas, - dossier_values=expected_vars, - observed_readback=expected_vars, - ) - if promo.qualified: - pack.stage = "VERIFIED_AUTOPILOT" - pub_file = publish_signed_pack(pack, key_bytes, Path(registry_dir)) - published_path = str(pub_file) - return True, verdict, heal_res.egress_ledger_entry_sha256, published_path @@ -279,11 +265,33 @@ def run_portal_pack( settle_timeout_ms: int = 5000, aci_calibrator: Optional[OnlineACICalibrator] = None, include_plaintext_values: bool = False, + trusted_pack_public_key: Optional[bytes] = None, ) -> RunResult: - """Execute a PortalPack in Draft-to-Commit, Verified Autopilot, or Self-Healing mode.""" + """Execute a PortalPack in Draft-to-Commit, Verified Autopilot, or Self-Healing mode. + + ``mode="autopilot"`` submits only when ``pack_path`` is a signed + ``openadapt.kernel.pack/v1`` envelope that verifies against + ``trusted_pack_public_key`` (Ed25519 public key PEM) and whose signed stage + is ``VERIFIED_AUTOPILOT``. Otherwise the run returns ``ESCALATED`` before + any browser work. Draft mode accepts flat or signed packs unverified, since + it never submits. + + ``registry_dir`` and ``auto_publish_on_heal`` are accepted for + compatibility but no longer publish anything: a self-healed run cannot + promote its own pack, because its only read-back is the values it wrote. + """ + if mode == "autopilot": + verified_pack, refusal = _load_autopilot_pack(pack_path, trusted_pack_public_key) + if verified_pack is None: + return RunResult(mode=mode, outcome="ESCALATED", reason=refusal) + pack = verified_pack + elif mode == "draft": + pack = _load_portal_pack(pack_path) + else: + return RunResult(mode=mode, outcome="ESCALATED", reason=f"unknown_run_mode:{mode}") + from playwright.sync_api import sync_playwright - pack = _load_portal_pack(pack_path) working_dossier: Dict[str, str] = dict(dossier) required_params = [k for k in pack.variable_fields if k not in pack.static_defaults] @@ -518,10 +526,6 @@ def _finish( sqlite_db_path=sqlite_db_path, sqlite_query=sqlite_query, pdf_readback_path=pdf_readback_path, - auto_publish_on_heal=auto_publish_on_heal, - registry_dir=registry_dir, - signing_key=signing_key, - private_key_path=private_key_path, use_bijective_twin_symbols=use_bijective_twin_symbols, ) if healed_ok and heal_verdict is not None: @@ -617,10 +621,6 @@ def _finish( sqlite_db_path=sqlite_db_path, sqlite_query=sqlite_query, pdf_readback_path=pdf_readback_path, - auto_publish_on_heal=auto_publish_on_heal, - registry_dir=registry_dir, - signing_key=signing_key, - private_key_path=private_key_path, use_bijective_twin_symbols=use_bijective_twin_symbols, ) if healed_ok and heal_verdict is not None: @@ -685,10 +685,6 @@ def _finish( sqlite_db_path=sqlite_db_path, sqlite_query=sqlite_query, pdf_readback_path=pdf_readback_path, - auto_publish_on_heal=auto_publish_on_heal, - registry_dir=registry_dir, - signing_key=signing_key, - private_key_path=private_key_path, use_bijective_twin_symbols=use_bijective_twin_symbols, ) if healed_ok and heal_verdict is not None: diff --git a/packages/kernel/tests/_signed_packs.py b/packages/kernel/tests/_signed_packs.py new file mode 100644 index 0000000000..1acb2da8a8 --- /dev/null +++ b/packages/kernel/tests/_signed_packs.py @@ -0,0 +1,33 @@ +"""Test helper: turn a flat pack JSON file into a signed registry envelope.""" + +from __future__ import annotations + +import json +import tempfile +from pathlib import Path +from typing import Optional + +from openadapt_kernel.copilot import generate_ephemeral_ed25519_keypair +from openadapt_kernel.registry import portal_pack_from_dict, publish_signed_pack + + +def sign_pack_file(pack_path: Path, private_key_pem: Optional[bytes] = None) -> bytes: + """Sign the pack at ``pack_path`` in place and return the trusted public key PEM. + + The stage written in the file is signed as-is; set it to VERIFIED_AUTOPILOT + in the test when autopilot must be allowed. + """ + if private_key_pem is None: + private_key_pem, public_key_pem = generate_ephemeral_ed25519_keypair() + else: + from cryptography.hazmat.primitives import serialization + + priv = serialization.load_pem_private_key(private_key_pem, password=None) + public_key_pem = priv.public_key().public_bytes( + serialization.Encoding.PEM, serialization.PublicFormat.SubjectPublicKeyInfo + ) + pack = portal_pack_from_dict(json.loads(pack_path.read_text(encoding="utf-8"))) + with tempfile.TemporaryDirectory(prefix="oa_signed_pack_") as tmp: + signed = publish_signed_pack(pack, private_key_pem, Path(tmp)) + pack_path.write_text(signed.read_text(encoding="utf-8"), encoding="utf-8") + return public_key_pem diff --git a/packages/kernel/tests/test_autopilot_stage_gate.py b/packages/kernel/tests/test_autopilot_stage_gate.py new file mode 100644 index 0000000000..2b0d59b072 --- /dev/null +++ b/packages/kernel/tests/test_autopilot_stage_gate.py @@ -0,0 +1,371 @@ +"""Autopilot submits only for packs whose signed stage is VERIFIED_AUTOPILOT. + +Each test here reproduces a path that, before the stage gate, let an +unpromoted or unsigned pack submit a form in autopilot mode. +""" + +from __future__ import annotations + +import json +import threading +from dataclasses import asdict +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any, Dict, List, Tuple + +from openadapt_kernel.cli import main as cli_main +from openadapt_kernel.copilot import PortalPack, generate_ephemeral_ed25519_keypair +from openadapt_kernel.mcp_server import McpServerConfig, dispatch_tool_call, handle_jsonrpc_message +from openadapt_kernel.registry import publish_signed_pack, pull_verified_pack +from openadapt_kernel.runner import run_portal_pack + +_FORM_HTML = """ +
+ + + +
+
+ +""" + + +def _start_portal() -> Tuple[ThreadingHTTPServer, str, List[Dict[str, str]]]: + saved: List[Dict[str, str]] = [] + + class _Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + body = _FORM_HTML.replace( + "", " ".join(f"{k}:{v}" for rec in saved for k, v in rec.items()) + ).encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: # noqa: N802 + length = int(self.headers.get("Content-Length", "0") or "0") + raw = self.rfile.read(length).decode("utf-8") if length else "{}" + data = json.loads(raw) + saved.append({str(k): str(v) for k, v in data.items()}) + body = b'{"status":"ok"}' + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 + return + + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://127.0.0.1:{int(server.server_address[1])}", saved + + +def _pack(origin: str, stage: str) -> PortalPack: + return PortalPack( + pack_id="member-pack", + portal_origin=origin, + variable_fields=["member_id"], + static_defaults={}, + provenance_map={"member_id": "member_id"}, + readback_url_pattern="", + stage=stage, # type: ignore[arg-type] + ) + + +def _write_unsigned(tmp_path: Path, origin: str, stage: str) -> Path: + path = tmp_path / f"unsigned-{stage}.json" + path.write_text(json.dumps(asdict(_pack(origin, stage))), encoding="utf-8") + return path + + +def test_unsigned_verified_pack_in_autopilot_is_refused(tmp_path: Path) -> None: + """A plain JSON file that claims VERIFIED_AUTOPILOT must not submit.""" + server, base_url, saved = _start_portal() + try: + res = run_portal_pack( + pack_path=_write_unsigned(tmp_path, base_url, "VERIFIED_AUTOPILOT"), + dossier={"member_id": "MEM-1001"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + ) + assert res.outcome == "ESCALATED" + assert "trusted" in res.reason or "signature" in res.reason + assert saved == [] + finally: + server.shutdown() + server.server_close() + + +def test_cli_autopilot_on_unsigned_shadow_pack_is_refused(tmp_path: Path) -> None: + """`openadapt-kernel run --mode autopilot` on a SHADOW JSON pack submits nothing.""" + server, base_url, saved = _start_portal() + try: + dossier = tmp_path / "dossier.json" + dossier.write_text(json.dumps({"member_id": "MEM-1002"}), encoding="utf-8") + rc = cli_main( + [ + "run", + "--pack", + str(_write_unsigned(tmp_path, base_url, "SHADOW")), + "--dossier", + str(dossier), + "--mode", + "autopilot", + "--url", + base_url, + "--commit-selector", + "#save_btn", + ] + ) + assert rc == 1 + assert saved == [] + finally: + server.shutdown() + server.server_close() + + +def test_signed_shadow_pack_in_autopilot_is_refused(tmp_path: Path) -> None: + """A correctly signed pack that is still SHADOW must not submit.""" + priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() + server, base_url, saved = _start_portal() + try: + signed = publish_signed_pack(_pack(base_url, "SHADOW"), priv_pem, tmp_path / "registry") + res = run_portal_pack( + pack_path=signed, + dossier={"member_id": "MEM-1003"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=pub_pem, + ) + assert res.outcome == "ESCALATED" + assert res.reason == "autopilot_pack_stage_not_verified:SHADOW" + assert saved == [] + finally: + server.shutdown() + server.server_close() + + +def test_signed_pack_with_untrusted_key_or_edited_stage_is_refused(tmp_path: Path) -> None: + priv_pem, _ = generate_ephemeral_ed25519_keypair() + _, other_pub = generate_ephemeral_ed25519_keypair() + trusted_priv, trusted_pub = generate_ephemeral_ed25519_keypair() + server, base_url, saved = _start_portal() + try: + # Signed VERIFIED_AUTOPILOT, but by a key the runner does not trust. + foreign = publish_signed_pack( + _pack(base_url, "VERIFIED_AUTOPILOT"), priv_pem, tmp_path / "foreign" + ) + res = run_portal_pack( + pack_path=foreign, + dossier={"member_id": "MEM-1004"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=other_pub, + ) + assert res.outcome == "ESCALATED" + assert res.reason.startswith("autopilot_pack_signature_invalid") + + # Trusted SHADOW envelope whose stage was edited in place after signing. + shadow = publish_signed_pack(_pack(base_url, "SHADOW"), trusted_priv, tmp_path / "edited") + env = json.loads(shadow.read_text(encoding="utf-8")) + env["pack"]["stage"] = "VERIFIED_AUTOPILOT" + shadow.write_text(json.dumps(env), encoding="utf-8") + res = run_portal_pack( + pack_path=shadow, + dossier={"member_id": "MEM-1004"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=trusted_pub, + ) + assert res.outcome == "ESCALATED" + assert res.reason.startswith("autopilot_pack_signature_invalid") + assert saved == [] + finally: + server.shutdown() + server.server_close() + + +def test_signed_verified_pack_runs_autopilot_and_signed_pack_runs_draft(tmp_path: Path) -> None: + """Positive control: the gate lets a trusted VERIFIED_AUTOPILOT pack submit.""" + priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() + server, base_url, saved = _start_portal() + try: + signed = publish_signed_pack( + _pack(base_url, "VERIFIED_AUTOPILOT"), priv_pem, tmp_path / "registry" + ) + draft = run_portal_pack( + pack_path=signed, + dossier={"member_id": "MEM-1005"}, + mode="draft", + url=base_url, + ) + assert draft.outcome == "READY_FOR_HUMAN_COMMIT" + assert saved == [] + + res = run_portal_pack( + pack_path=signed, + dossier={"member_id": "MEM-1005"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=pub_pem, + ) + assert res.outcome == "VERIFIED" + assert saved == [{"member_id": "MEM-1005"}] + finally: + server.shutdown() + server.server_close() + + +def _mcp_call(name: str, arguments: Dict[str, Any]) -> Dict[str, Any]: + resp = handle_jsonrpc_message( + { + "jsonrpc": "2.0", + "id": 1, + "method": "tools/call", + "params": {"name": name, "arguments": arguments}, + } + ) + assert resp is not None + return resp["result"] + + +def test_mcp_tool_cannot_choose_autopilot_or_signing_key(tmp_path: Path) -> None: + """The model calling the MCP tool cannot raise the mode or pick the key.""" + priv_pem, _ = generate_ephemeral_ed25519_keypair() + key_path = tmp_path / "priv.pem" + key_path.write_bytes(priv_pem) + server, base_url, saved = _start_portal() + try: + pack_path = _write_unsigned(tmp_path, base_url, "VERIFIED_AUTOPILOT") + base_args = { + "pack_path": str(pack_path), + "dossier": {"member_id": "MEM-1006"}, + "url": base_url, + "commit_selector": "#save_btn", + } + asked_autopilot = _mcp_call("kernel_run_pack", {**base_args, "mode": "autopilot"}) + assert asked_autopilot["isError"] is True + assert "autopilot" in asked_autopilot["content"][0]["text"] + + asked_key = _mcp_call( + "kernel_run_pack", + { + **base_args, + "mode": "draft", + "private_key_path": str(key_path), + "receipt_out": str(tmp_path / "r.json"), + }, + ) + assert asked_key["isError"] is True + assert "private_key_path" in asked_key["content"][0]["text"] + assert not (tmp_path / "r.json").exists() + assert saved == [] + finally: + server.shutdown() + server.server_close() + + +def test_mcp_tool_writes_only_under_the_server_output_root(tmp_path: Path) -> None: + evidence = tmp_path / "extension_evidence.jsonl" + evidence.write_text( + "\n".join( + json.dumps(e) + for e in ( + {"kind": "input", "frame_origin": "https://p.example", "field": "policy", "value": "POL-1"}, + {"kind": "readback", "url": "https://p.example/ok", "text": "Saved POL-1"}, + ) + ) + + "\n", + encoding="utf-8", + ) + outside = tmp_path / "outside" / "pack.json" + res = _mcp_call( + "kernel_induce_pack", + { + "pack_id": "p", + "sessions": [{"evidence_path": str(evidence), "dossier": {"src_pol": "POL-1"}}], + "out_path": str(outside), + }, + ) + assert res["isError"] is True + assert not outside.exists() + + +def test_mcp_server_config_enables_autopilot_for_trusted_signed_packs(tmp_path: Path) -> None: + """Autopilot through MCP works only when the operator configured it.""" + pack_priv, pack_pub = generate_ephemeral_ed25519_keypair() + receipt_priv, _ = generate_ephemeral_ed25519_keypair() + (tmp_path / "pack_pub.pem").write_bytes(pack_pub) + (tmp_path / "receipt_priv.pem").write_bytes(receipt_priv) + out_root = tmp_path / "out" + config = McpServerConfig( + allow_autopilot=True, + trusted_pack_public_key_path=tmp_path / "pack_pub.pem", + private_key_path=tmp_path / "receipt_priv.pem", + output_root=out_root, + ) + server, base_url, saved = _start_portal() + try: + signed = publish_signed_pack( + _pack(base_url, "VERIFIED_AUTOPILOT"), pack_priv, tmp_path / "registry" + ) + unsigned = _write_unsigned(tmp_path, base_url, "VERIFIED_AUTOPILOT") + args = { + "dossier": {"member_id": "MEM-1007"}, + "mode": "autopilot", + "url": base_url, + "commit_selector": "#save_btn", + } + refused = dispatch_tool_call("kernel_run_pack", {**args, "pack_path": str(unsigned)}, config) + assert refused["ok"] is False + assert refused["result"]["outcome"] == "ESCALATED" + assert saved == [] + + ok = dispatch_tool_call( + "kernel_run_pack", + {**args, "pack_path": str(signed), "receipt_out": "receipts/r.json"}, + config, + ) + assert ok["ok"] is True + assert ok["result"]["outcome"] == "VERIFIED" + assert (out_root / "receipts" / "r.json").exists() + assert saved == [{"member_id": "MEM-1007"}] + finally: + server.shutdown() + server.server_close() + + +def test_cli_publish_pack_signs_a_pack_the_runner_trusts(tmp_path: Path, capsys: Any) -> None: + priv_path, pub_path = tmp_path / "pack_priv.pem", tmp_path / "pack_pub.pem" + assert cli_main(["keygen", "--priv", str(priv_path), "--pub", str(pub_path)]) == 0 + flat = _write_unsigned(tmp_path, "https://portal.example.test", "VERIFIED_AUTOPILOT") + capsys.readouterr() + assert ( + cli_main( + ["publish-pack", "--pack", str(flat), "--priv", str(priv_path), + "--registry-dir", str(tmp_path / "registry")] + ) + == 0 + ) + out = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) + pulled = pull_verified_pack(Path(out["out"]), pub_path.read_bytes()) + assert pulled.stage == "VERIFIED_AUTOPILOT" diff --git a/packages/kernel/tests/test_kernel_hardening.py b/packages/kernel/tests/test_kernel_hardening.py index 092b5e327a..9278efcaa5 100644 --- a/packages/kernel/tests/test_kernel_hardening.py +++ b/packages/kernel/tests/test_kernel_hardening.py @@ -12,6 +12,7 @@ from typing import Any, Dict, List import pytest +from _signed_packs import sign_pack_file from playwright.sync_api import sync_playwright from openadapt_kernel import ( @@ -157,14 +158,17 @@ def test_defect2_noop_click_never_returns_verified(tmp_path: Path) -> None: "static_defaults": {}, "provenance_map": {"policy_number": "policy_number"}, "readback_url_pattern": f"{base_url}/", + "stage": "VERIFIED_AUTOPILOT", } ), encoding="utf-8", ) + pack_pub = sign_pack_file(pack_path) res = run_portal_pack( pack_path=pack_path, dossier={"policy_number": "POL-STALE-1"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/", commit_selector="#noop-btn", headless=True, @@ -222,14 +226,17 @@ def handle_post(_path: str, raw: str) -> tuple[int, str]: "static_defaults": {}, "provenance_map": {"policy_number": "policy_number"}, "readback_url_pattern": f"{base_url}/", + "stage": "VERIFIED_AUTOPILOT", } ), encoding="utf-8", ) + pack_pub = sign_pack_file(pack_path) res = run_portal_pack( pack_path=pack_path, dossier={"policy_number": "POL-SLOW-550"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/", commit_selector="#slow-submit", settle_timeout_ms=5000, @@ -331,10 +338,12 @@ def handle_post(_path: str, raw: str) -> tuple[int, str]: "static_defaults": {}, "provenance_map": {"policy_number": "policy_number"}, "readback_url_pattern": f"{base_url}/", + "stage": "VERIFIED_AUTOPILOT", } ), encoding="utf-8", ) + pack_pub = sign_pack_file(pack_path) aci = OnlineACICalibrator(target_alpha=0.05, gamma=0.1, alpha_t=0.05) assert len(aci.history_scores) == 0 @@ -342,6 +351,7 @@ def handle_post(_path: str, raw: str) -> tuple[int, str]: pack_path=pack_path, dossier={"policy_number": "POL-ACI-1"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/", commit_selector="#submit-btn", aci_calibrator=aci, @@ -357,6 +367,7 @@ def handle_post(_path: str, raw: str) -> tuple[int, str]: pack_path=pack_path, dossier={"policy_number": "POL-ACI-2"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/", commit_selector="#nonfocus-div", aci_calibrator=aci, diff --git a/packages/kernel/tests/test_kernel_runner_e2e.py b/packages/kernel/tests/test_kernel_runner_e2e.py index db055e9ff2..41e314d070 100644 --- a/packages/kernel/tests/test_kernel_runner_e2e.py +++ b/packages/kernel/tests/test_kernel_runner_e2e.py @@ -8,6 +8,8 @@ from pathlib import Path from typing import Any, Dict, List +from _signed_packs import sign_pack_file + from openadapt_kernel.cli import main @@ -104,6 +106,8 @@ def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> No priv_path = tmp_path / "priv.pem" pub_path = tmp_path / "pub.pem" assert main(["keygen", "--priv", str(priv_path), "--pub", str(pub_path)]) == 0 + pack_pub_path = tmp_path / "pack_pub.pem" + pack_pub_path.write_bytes(sign_pack_file(pack_path)) # 1. Healthy server: Draft-to-Commit stages form without POST, Autopilot commits + verifies + signs srv_ok, url_ok, records_ok = _start_portal_server(drop_writes=False) @@ -122,6 +126,8 @@ def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> No str(dossier_path), "--mode", "autopilot", + "--trusted-pack-pub", + str(pack_pub_path), "--url", url_ok, "--commit-selector", @@ -155,6 +161,8 @@ def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> No str(dossier_path), "--mode", "autopilot", + "--trusted-pack-pub", + str(pack_pub_path), "--url", url_bad, "--commit-selector", diff --git a/packages/kernel/tests/test_oracles_and_mcp.py b/packages/kernel/tests/test_oracles_and_mcp.py index 5053f54954..bbbd09914e 100644 --- a/packages/kernel/tests/test_oracles_and_mcp.py +++ b/packages/kernel/tests/test_oracles_and_mcp.py @@ -11,6 +11,8 @@ from pathlib import Path from typing import Any +from _signed_packs import sign_pack_file + from openadapt_kernel import ( extract_pdf_visible_text, handle_jsonrpc_message, @@ -156,14 +158,17 @@ def do_POST(self) -> None: "static_defaults": {}, "provenance_map": {"policy_number": "src_policy"}, "readback_url_pattern": f"http://127.0.0.1:{port}/", + "stage": "VERIFIED_AUTOPILOT", } ), encoding="utf-8", ) + pack_pub = sign_pack_file(pack_path) res = run_portal_pack( pack_path=pack_path, dossier={"src_policy": "POL-555"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"http://127.0.0.1:{port}/", commit_selector="#submit-all", popup_trigger_selector="#open-est", diff --git a/packages/kernel/tests/test_probe_aci_and_suite.py b/packages/kernel/tests/test_probe_aci_and_suite.py index 564b0b405f..e9b50b73b8 100644 --- a/packages/kernel/tests/test_probe_aci_and_suite.py +++ b/packages/kernel/tests/test_probe_aci_and_suite.py @@ -8,6 +8,7 @@ from pathlib import Path from typing import Dict +from _signed_packs import sign_pack_file from playwright.sync_api import sync_playwright from openadapt_kernel import ( @@ -144,14 +145,17 @@ def test_probe_detects_transparent_overlay_and_runner_refuses_click(tmp_path: Pa "static_defaults": {}, "provenance_map": {"policy_id": "policy_id"}, "readback_url_pattern": f"{base_url}/occluded", + "stage": "VERIFIED_AUTOPILOT", } ), encoding="utf-8", ) + pack_pub = sign_pack_file(pack_path) res = run_portal_pack( pack_path=pack_path, dossier={"policy_id": "POL-889"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/occluded", commit_selector="#save-btn", headless=True, diff --git a/packages/kernel/tests/test_receipt_bridge_and_nondom.py b/packages/kernel/tests/test_receipt_bridge_and_nondom.py index 1bea3150cf..53e01a26a6 100644 --- a/packages/kernel/tests/test_receipt_bridge_and_nondom.py +++ b/packages/kernel/tests/test_receipt_bridge_and_nondom.py @@ -831,3 +831,59 @@ def test_dsse_verifier_rejects_non_canonical_json_even_with_valid_signature() -> assert ok is False assert decoded == {} assert reason == "non_canonical_json_payload" + + +def test_nondom_autonomy_stage_override_cannot_raise_the_pack_stage() -> None: + """A DRAFT_TO_COMMIT or SHADOW pack stays draft even when the caller asks for autopilot.""" + for pack_stage in ("DRAFT_TO_COMMIT", "SHADOW", "NOT_A_STAGE"): + backend = MockCanvasBrowserBackend(commit_persists=True) + grounder = _MockConstellationGrounder( + { + "account_id": (120, 80, 0.94), + "amount": (120, 140, 0.91), + "Submit Invoice": (300, 220, 0.96), + } + ) + executor = NonDomKernelExecutor( + backend=backend, + grounder=grounder, + ocr_oracle=_mock_ocr_oracle, + surface="canvas", + ) + res = executor.execute( + _make_pack(stage=pack_stage), + {"account_id": "ACC-77201", "amount": "1250.00"}, + autonomy_stage="VERIFIED_AUTOPILOT", + allow_commit=True, + commit_intent="Click Submit Invoice", + commit_ocr_text="Submit Invoice", + ) + assert res.outcome == "READY_FOR_HUMAN_COMMIT", pack_stage + assert res.commit_executed is False + assert backend.submit_clicks == 0 + assert res.autonomy_stage == ("SHADOW" if pack_stage == "NOT_A_STAGE" else pack_stage) + + +def test_nondom_autonomy_stage_override_can_lower_the_pack_stage() -> None: + backend = MockCanvasBrowserBackend(commit_persists=True) + grounder = _MockConstellationGrounder( + { + "account_id": (120, 80, 0.94), + "amount": (120, 140, 0.91), + "Submit Invoice": (300, 220, 0.96), + } + ) + executor = NonDomKernelExecutor( + backend=backend, grounder=grounder, ocr_oracle=_mock_ocr_oracle, surface="canvas" + ) + res = executor.execute( + _make_pack(stage="VERIFIED_AUTOPILOT"), + {"account_id": "ACC-77201", "amount": "1250.00"}, + autonomy_stage="DRAFT_TO_COMMIT", + allow_commit=True, + commit_intent="Click Submit Invoice", + commit_ocr_text="Submit Invoice", + ) + assert res.outcome == "READY_FOR_HUMAN_COMMIT" + assert res.autonomy_stage == "DRAFT_TO_COMMIT" + assert backend.submit_clicks == 0 diff --git a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py index 1d949ee16e..0867fc1d78 100644 --- a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py +++ b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py @@ -9,6 +9,7 @@ from pathlib import Path from typing import Any, Dict, List, Tuple +from _signed_packs import sign_pack_file from playwright.sync_api import sync_playwright from openadapt_kernel import ( @@ -225,6 +226,7 @@ def test_runner_bijective_symbols_ood_halt_and_canvas_servo(tmp_path: Path) -> N ) pack_path = tmp_path / "intl_pack.json" pack_path.write_text(json.dumps(asdict(pack)), encoding="utf-8") + pack_pub = sign_pack_file(pack_path) # 1. Cartridge OOD halt before staging/committing raw_cart = induce_cartridge_from_raw_demos( @@ -245,6 +247,7 @@ def test_runner_bijective_symbols_ood_halt_and_canvas_servo(tmp_path: Path) -> N pack_path=pack_path, dossier={"antrag_code": "DE-42", "tier": "platinum_unseen"}, mode="autopilot", + trusted_pack_public_key=pack_pub, cartridge=raw_cart, ) assert ood_res.outcome == "PREPARE_REQUIRED" @@ -287,6 +290,7 @@ def _intl_coding_agent(twin_html: str, var_keys: List[str], _err: str, _fb: Dict pack_path=pack_path, dossier={"antrag_code": "DE-2026-88"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/intl", commit_selector="#go", coding_agent_fn=_intl_coding_agent, @@ -303,6 +307,7 @@ def _intl_coding_agent(twin_html: str, var_keys: List[str], _err: str, _fb: Dict pack_path=pack_path, dossier={"antrag_code": "DE-1"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/canvas", ) assert esc_res.outcome == "ESCALATED" @@ -318,6 +323,7 @@ def _servo_cb(_page: Any, surface: Dict[str, Any]) -> None: pack_path=pack_path, dossier={"antrag_code": "DE-1"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=f"{base_url}/canvas", visual_servo_click_fn=_servo_cb, ) diff --git a/packages/kernel/tests/test_unified_runtime.py b/packages/kernel/tests/test_unified_runtime.py index 260b11059e..12d56ef773 100644 --- a/packages/kernel/tests/test_unified_runtime.py +++ b/packages/kernel/tests/test_unified_runtime.py @@ -14,12 +14,12 @@ from typing import Any, Dict, List import pytest +from _signed_packs import sign_pack_file from openadapt_kernel.cli import main as cli_main from openadapt_kernel.copilot import generate_ephemeral_ed25519_keypair, verify_receipt from openadapt_kernel.egress_guard import LocalEgressGuard from openadapt_kernel.prepare import PrepareCard, PrepareResumeResponse -from openadapt_kernel.registry import pull_verified_pack from openadapt_kernel.runner import run_portal_pack @@ -117,6 +117,7 @@ def test_run_portal_pack_step0_prepare_resume_closure_and_ed25519_receipt(tmp_pa ), encoding="utf-8", ) + pack_pub = sign_pack_file(pack_path) priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() priv_path = tmp_path / "priv.pem" priv_path.write_bytes(priv_pem) @@ -127,6 +128,7 @@ def test_run_portal_pack_step0_prepare_resume_closure_and_ed25519_receipt(tmp_pa pack_path=pack_path, dossier={"member_id": "MEM-7741"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=base_url, commit_selector="#save_btn", policy_specs=[ @@ -156,6 +158,7 @@ def operator_prepare_handler(card: PrepareCard) -> PrepareResumeResponse: pack_path=pack_path, dossier={}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=base_url, commit_selector="#save_btn", private_key_path=priv_path, @@ -176,8 +179,12 @@ def operator_prepare_handler(card: PrepareCard) -> PrepareResumeResponse: server.server_close() -def test_run_portal_pack_self_heal_fallback_egress_audit_and_auto_publish(tmp_path: Path) -> None: - """Warm staging failure -> Zero-PHI digital-twin self-heal -> LocalEgressGuard -> qualify & auto-publish.""" +def test_run_portal_pack_self_heal_fallback_egress_audit_and_no_self_promotion(tmp_path: Path) -> None: + """Warm staging failure -> Zero-PHI digital-twin self-heal -> LocalEgressGuard. + + The healed run must not publish or promote its own pack: its only read-back + is the values it wrote, so ``auto_publish_on_heal`` publishes nothing. + """ drifted_html = """

Patient: Maria Gonzalez SSN 123-45-6789

@@ -213,11 +220,12 @@ def test_run_portal_pack_self_heal_fallback_egress_audit_and_auto_publish(tmp_pa "variable_fields": ["claim_code", "member_code"], "static_defaults": {}, "provenance_map": {"claim_code": "claim_code", "member_code": "member_code"}, - "stage": "SHADOW", + "stage": "VERIFIED_AUTOPILOT", } ), encoding="utf-8", ) + pack_pub = sign_pack_file(pack_path) priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() egress_ledger = tmp_path / "heal_egress_ledger.jsonl" registry_dir = tmp_path / "registry" @@ -237,6 +245,7 @@ def heal_coder(twin_html: str, var_keys: List[str], safe_err: str) -> str: pack_path=pack_path, dossier={"claim_code": "CLM-8821", "member_code": "MBR-4402"}, mode="autopilot", + trusted_pack_public_key=pack_pub, url=base_url, commit_selector="#save_btn", coding_agent_fn=heal_coder, @@ -250,12 +259,8 @@ def heal_coder(twin_html: str, var_keys: List[str], safe_err: str) -> str: assert res.healed is True assert res.readback_verified is True assert len(res.egress_ledger_entry_sha256) == 64 - assert res.published_pack_path is not None - assert Path(res.published_pack_path).exists() - - pulled = pull_verified_pack(Path(res.published_pack_path), pub_pem) - assert pulled.pack_id == "drifted-claim-pack" - assert pulled.stage == "VERIFIED_AUTOPILOT" + assert res.published_pack_path is None + assert not registry_dir.exists() or not any(registry_dir.iterdir()) guard = LocalEgressGuard(egress_ledger) assert guard.verify_ledger_integrity() is True diff --git a/packages/kernel/uv.lock b/packages/kernel/uv.lock index 19dec5e87e..5148509fbd 100644 --- a/packages/kernel/uv.lock +++ b/packages/kernel/uv.lock @@ -522,7 +522,7 @@ wheels = [ [[package]] name = "openadapt-kernel" -version = "0.1.0" +version = "0.2.0" source = { editable = "." } dependencies = [ { name = "cryptography" }, From 0b879c8cb88dc7fa6c3b8d4ae830a2e763a3e4ef Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 21:37:56 -0500 Subject: [PATCH 2/3] fix(kernel): autopilot heal proposes only; never commits or re-submits A pack's signed VERIFIED_AUTOPILOT stage covers the pack as signed, not an in-memory repair from coding_agent_fn. Before this change: - When staging failed or the commit control was blocked, the model's unqualified repair was replayed on the live page and could click Save. A blocked Save behind an overlay ended VERIFIED. - When read-back refuted persistence after the commit click, the heal re-submitted. A dropped write was posted twice and reported VERIFIED. Now, in autopilot, the heal runs in the zero-PHI twin only and the run returns ESCALATED with heal_proposed=True and nothing clicked. A refuted read-back after the click escalates with readback_refuted_after_commit and adds a pending uncertain_write_reconcile obligation; it never heals, re-clicks or re-submits. Draft mode had no heal path and is unchanged. --- packages/kernel/CHANGELOG.md | 3 + packages/kernel/README.md | 10 +- .../kernel/src/openadapt_kernel/runner.py | 185 +++++------------- .../kernel/tests/test_autopilot_stage_gate.py | 131 +++++++++++++ .../test_runtime_wiring_and_raw_demos.py | 7 +- packages/kernel/tests/test_unified_runtime.py | 17 +- 6 files changed, 207 insertions(+), 146 deletions(-) diff --git a/packages/kernel/CHANGELOG.md b/packages/kernel/CHANGELOG.md index 168d56ca3f..938412755f 100644 --- a/packages/kernel/CHANGELOG.md +++ b/packages/kernel/CHANGELOG.md @@ -7,6 +7,9 @@ Breaking: autopilot now fails closed on any pack that is not signed and promoted - `run_portal_pack(mode="autopilot")` and `openadapt-kernel run --mode autopilot` load the pack through the registry's Ed25519 signature, digest and zero-PII check against a pinned key (`trusted_pack_public_key` / `--trusted-pack-pub`). A missing key, unsigned file, foreign key, edited envelope, or a signed stage other than `VERIFIED_AUTOPILOT` returns `ESCALATED` with zero submissions. Draft mode still loads flat or signed packs. - `NonDomKernelExecutor.execute(autonomy_stage=...)` can only lower the pack's stage; unknown stages resolve to `SHADOW`. - Self-healing no longer promotes or publishes the healed pack. It used to qualify the pack against its own written values. `auto_publish_on_heal` and `registry_dir` are kept for compatibility but publish nothing. +- Autopilot no longer repairs and commits in the same run. When staging fails or the commit control is blocked, `coding_agent_fn` may propose a repair inside the zero-PHI twin. The run then returns `ESCALATED` with `heal_proposed=True` and the reason suffix `self_heal_proposed_not_applied`, and clicks nothing on the live page. Before this change, the unqualified repair was replayed live and could click Save. +- When read-back refutes persistence after the commit click, the run returns `ESCALATED` with `readback_refuted_after_commit` and adds a pending `uncertain_write_reconcile` obligation to the ledger and receipt. It never heals, re-clicks or re-submits. Before this change, a heal could re-submit and report `VERIFIED` after a duplicate write. The old reason `readback_refuted_persistence` is replaced. +- `RunResult.heal_proposed` is new. In autopilot, `RunResult.healed` is now always `False`. - MCP server: mode ceiling, trusted pack key, receipt key and output root are server configuration (`McpServerConfig`, `serve-mcp --allow-autopilot --trusted-pack-pub --priv --output-root`). Tool calls default to draft, cannot request autopilot unless the server allows it, cannot pass `private_key_path` or any other undeclared argument, and write only under the output root. - `pull_verified_pack` raises `ValueError` for non-envelope files, non-Ed25519 keys and bad signatures instead of relying on `assert`. - New `openadapt-kernel publish-pack` command signs a pack into a registry directory. diff --git a/packages/kernel/README.md b/packages/kernel/README.md index e25582b1de..e73428fa37 100644 --- a/packages/kernel/README.md +++ b/packages/kernel/README.md @@ -35,8 +35,14 @@ before the commit control. Signing with `publish-pack` is the promotion step, so whoever holds the pack key approves autopilot. Keep that key apart from the receipt key (`--priv`), -which the runner holds. A self-healed run never publishes or promotes its own -pack. +which the runner holds. A run never publishes or promotes its own pack. + +Autopilot never repairs and commits in the same run. If staging fails or the +commit control is blocked, a coding agent may propose a repair inside the +zero-PHI twin; the run escalates with the proposal recorded and clicks nothing. +If read-back refutes persistence after the commit click, the run escalates with +`readback_refuted_after_commit` and records an uncertain write for +reconciliation. It never clicks or submits again. `NonDomKernelExecutor.execute(autonomy_stage=...)` can only lower a pack's stage, never raise it. diff --git a/packages/kernel/src/openadapt_kernel/runner.py b/packages/kernel/src/openadapt_kernel/runner.py index 35432c5423..caae1c9efa 100644 --- a/packages/kernel/src/openadapt_kernel/runner.py +++ b/packages/kernel/src/openadapt_kernel/runner.py @@ -29,7 +29,6 @@ ) from openadapt_kernel.macro import ( detect_opaque_visual_surfaces, - lift_distilled_repair_to_pack, observe_schema, stage_form, ) @@ -45,7 +44,6 @@ portal_pack_from_dict, pull_verified_pack, ) -from openadapt_kernel.zero_phi_repair import replay_distilled_zero_phi_repair RunMode = Literal["draft", "autopilot"] @@ -67,6 +65,10 @@ class RunResult: closure_passed: bool = False aci_alpha_t: Optional[float] = None aci_threshold: Optional[float] = None + heal_proposed: bool = False + + +_HEAL_PROPOSED = "self_heal_proposed_not_applied" def _sign_terminal_receipt( @@ -155,20 +157,23 @@ def _verify_post_commit_readback( ) -def _attempt_twin_self_heal_and_publish( +def _propose_twin_heal( page: Any, - pack: PortalPack, bindings: Dict[str, str], - working_dossier: Dict[str, str], *, coding_agent_fn: Callable[..., str], structural_error: str, egress_ledger_path: Optional[Path], - sqlite_db_path: Optional[Path], - sqlite_query: Optional[str], - pdf_readback_path: Optional[Path], use_bijective_twin_symbols: bool = False, -) -> tuple[bool, Any, str, Optional[str]]: +) -> tuple[bool, str]: + """Ask the coding agent for a repair inside the zero-PHI twin only. + + The repair is never replayed on the live page. Its selectors were never + qualified, and the pack's signed VERIFIED_AUTOPILOT stage covers the pack + as signed, not an in-memory repair, so applying it could click an + unqualified control. The caller escalates and records the proposal. + Returns ``(verified_in_twin, egress_ledger_entry_sha256)``. + """ symbol_codec = BijectiveSymbolCodec() if use_bijective_twin_symbols else None var_map = {f"${k}": str(v) for k, v in bindings.items()} egress_pol = EgressPolicy(allowed_var_keys=frozenset(var_map.keys())) @@ -190,38 +195,7 @@ def _attempt_twin_self_heal_and_publish( structural_error=structural_error, symbol_codec=symbol_codec, ).result() - if not heal_res.verified: - return False, None, heal_res.egress_ledger_entry_sha256, None - - replayed = replay_distilled_zero_phi_repair( - page, - heal_res.distilled_steps, - private_vars=var_map, - readback_oracle=lambda _p: True, - ) - if not replayed: - return False, None, heal_res.egress_ledger_entry_sha256, None - - lift_distilled_repair_to_pack(heal_res.distilled_steps, working_dossier) - expected_vars = {k: bindings[k] for k in pack.variable_fields if k in bindings} - verdict = _verify_post_commit_readback( - page, - expected_vars, - sqlite_db_path=sqlite_db_path, - sqlite_query=sqlite_query, - pdf_readback_path=pdf_readback_path, - reload_active=False, - ) - if not verdict.verified: - return False, verdict, heal_res.egress_ledger_entry_sha256, None - - # A healed pack is never promoted or published from here. The only - # "observed" values this path has are the bindings it just wrote, so - # qualifying on them would compare the expected values with themselves. - # Promotion to VERIFIED_AUTOPILOT needs an independent read-back and goes - # through qualify_and_promote_pack and publish_signed_pack outside the run. - published_path: Optional[str] = None - return True, verdict, heal_res.egress_ledger_entry_sha256, published_path + return bool(heal_res.verified), heal_res.egress_ledger_entry_sha256 def run_portal_pack( @@ -274,11 +248,18 @@ def run_portal_pack( ``trusted_pack_public_key`` (Ed25519 public key PEM) and whose signed stage is ``VERIFIED_AUTOPILOT``. Otherwise the run returns ``ESCALATED`` before any browser work. Draft mode accepts flat or signed packs unverified, since - it never submits. + it stops before the commit control. + + ``coding_agent_fn`` never repairs and commits within the same run. When + staging fails or the commit control is blocked, the agent may propose a + repair inside the zero-PHI twin; the run still returns ``ESCALATED`` with + ``heal_proposed`` set and nothing clicked on the live page. When read-back + refutes persistence after the commit click, the run escalates with + ``readback_refuted_after_commit`` and records an uncertain write in the + ledger; it never heals, re-clicks or re-submits. ``registry_dir`` and ``auto_publish_on_heal`` are accepted for - compatibility but no longer publish anything: a self-healed run cannot - promote its own pack, because its only read-back is the values it wrote. + compatibility but publish nothing: a run cannot promote its own pack. """ if mode == "autopilot": verified_pack, refusal = _load_autopilot_pack(pack_path, trusted_pack_public_key) @@ -403,6 +384,7 @@ def _finish( published_pack_path: Optional[str] = None, egress_ledger_entry_sha256: str = "", closure_passed: bool = False, + heal_proposed: bool = False, ) -> RunResult: rpath = _sign_terminal_receipt( ledger, @@ -429,6 +411,7 @@ def _finish( closure_passed=closure_passed, aci_alpha_t=calibrator.alpha_t if with_aci else None, aci_threshold=calibrator.threshold() if with_aci else None, + heal_proposed=heal_proposed, ) with sync_playwright() as pw: @@ -509,56 +492,27 @@ def _finish( reason="ssa_provenance_violation", ) - healed = False egress_entry_sha = "" - published_pack_path: Optional[str] = None if not staged.ok: + heal_proposed = False if coding_agent_fn is not None and mode == "autopilot": - healed_ok, heal_verdict, egress_entry_sha, published_pack_path = _attempt_twin_self_heal_and_publish( + heal_proposed, egress_entry_sha = _propose_twin_heal( page, - pack, bindings, - working_dossier, coding_agent_fn=coding_agent_fn, structural_error=f"stage_failed:{staged.unmatched}", egress_ledger_path=egress_ledger_path, - sqlite_db_path=sqlite_db_path, - sqlite_query=sqlite_query, - pdf_readback_path=pdf_readback_path, use_bijective_twin_symbols=use_bijective_twin_symbols, ) - if healed_ok and heal_verdict is not None: - healed = True - interceptor.clear_dirty_fields() - ledger.mark_committed("primary_commit", heal_verdict.to_proof()) - decision = ledger.finalize("done", dirty_fields=list(interceptor.dirty_fields.keys())) - saved_receipt: Optional[str] = None - key_bytes = signing_key or (private_key_path.read_bytes() if private_key_path else None) - if decision.outcome == "VERIFIED" and key_bytes and receipt_out: - receipt = mint_receipt(ledger, pack.pack_id, key_bytes) - receipt_out.parent.mkdir(parents=True, exist_ok=True) - receipt_out.write_text(json.dumps(receipt, indent=2), encoding="utf-8") - saved_receipt = str(receipt_out) - return RunResult( - mode="autopilot", - outcome=decision.outcome, - staged_fields=bindings, - commit_detected=True, - readback_verified=True, - receipt_path=saved_receipt, - reason=decision.reason, - healed=True, - published_pack_path=published_pack_path, - egress_ledger_entry_sha256=egress_entry_sha, - closure_passed=True, - ) ledger.finalize("error", dirty_fields=list(interceptor.dirty_fields.keys()), error_detail="stage_mismatch") + stage_reason = f"stage_failed(unmatched={staged.unmatched}, mismatched={staged.mismatched})" return _finish( "ESCALATED", staged_fields=staged.staged, - reason=f"stage_failed(unmatched={staged.unmatched}, mismatched={staged.mismatched})", + reason=f"{stage_reason};{_HEAL_PROPOSED}" if heal_proposed else stage_reason, egress_ledger_entry_sha256=egress_entry_sha, + heal_proposed=heal_proposed, ) # Optional child popup workflow @@ -609,50 +563,23 @@ def _finish( detail = f"commit_control_blocked:{probe.reason}" if probe.top_blocker: detail = f"{detail}({probe.top_blocker})" + heal_proposed = False if coding_agent_fn is not None: - healed_ok, heal_verdict, egress_entry_sha, published_pack_path = _attempt_twin_self_heal_and_publish( + heal_proposed, egress_entry_sha = _propose_twin_heal( page, - pack, bindings, - working_dossier, coding_agent_fn=coding_agent_fn, structural_error=detail, egress_ledger_path=egress_ledger_path, - sqlite_db_path=sqlite_db_path, - sqlite_query=sqlite_query, - pdf_readback_path=pdf_readback_path, use_bijective_twin_symbols=use_bijective_twin_symbols, ) - if healed_ok and heal_verdict is not None: - interceptor.clear_dirty_fields() - ledger.mark_committed("primary_commit", heal_verdict.to_proof()) - decision = ledger.finalize("done", dirty_fields=list(interceptor.dirty_fields.keys())) - saved_receipt = None - key_bytes = signing_key or (private_key_path.read_bytes() if private_key_path else None) - if decision.outcome == "VERIFIED" and key_bytes and receipt_out: - receipt = mint_receipt(ledger, pack.pack_id, key_bytes) - receipt_out.parent.mkdir(parents=True, exist_ok=True) - receipt_out.write_text(json.dumps(receipt, indent=2), encoding="utf-8") - saved_receipt = str(receipt_out) - return RunResult( - mode="autopilot", - outcome=decision.outcome, - staged_fields=staged.staged, - commit_detected=True, - readback_verified=True, - receipt_path=saved_receipt, - reason=decision.reason, - healed=True, - published_pack_path=published_pack_path, - egress_ledger_entry_sha256=egress_entry_sha, - closure_passed=True, - ) ledger.finalize("error", dirty_fields=list(interceptor.dirty_fields.keys()), error_detail=detail) return _finish( "ESCALATED", staged_fields=staged.staged, - reason=detail, + reason=f"{detail};{_HEAL_PROPOSED}" if heal_proposed else detail, egress_ledger_entry_sha256=egress_entry_sha, + heal_proposed=heal_proposed, ) interceptor.begin_step() @@ -673,29 +600,11 @@ def _finish( target_origin=target_origin, ) - if not verdict.verified and coding_agent_fn is not None: - healed_ok, heal_verdict, egress_entry_sha, published_pack_path = _attempt_twin_self_heal_and_publish( - page, - pack, - bindings, - working_dossier, - coding_agent_fn=coding_agent_fn, - structural_error="readback_refuted_persistence", - egress_ledger_path=egress_ledger_path, - sqlite_db_path=sqlite_db_path, - sqlite_query=sqlite_query, - pdf_readback_path=pdf_readback_path, - use_bijective_twin_symbols=use_bijective_twin_symbols, - ) - if healed_ok and heal_verdict is not None: - healed = True - verdict = heal_verdict - has_transition = (not pre_present) and verdict.verified - commit_confirmed = has_2xx_mut or has_transition or healed + commit_confirmed = has_2xx_mut or has_transition # Online ACI update from Level-2/3 read-back ground truth Y_t - anomaly_score = 0.0 if (has_2xx_mut and probe.focus_responded) else (1.0 if (has_transition or healed) else 3.0) + anomaly_score = 0.0 if (has_2xx_mut and probe.focus_responded) else (1.0 if has_transition else 3.0) flagged = calibrator.should_flag(anomaly_score) realized_error = flagged != (not (verdict.verified and commit_confirmed)) calibrator.update_from_readback(anomaly_score, realized_error=realized_error) @@ -713,17 +622,27 @@ def _finish( ) if not verdict.verified: + # The commit click may have landed. Never heal, re-click or + # re-submit here: a second write could duplicate the first. + # Record the uncertain write so it is reconciled, not retried. + ledger.add_obligation( + "uncertain_write_reconcile", + "Commit was clicked and the target answered, but read-back refuted " + "persistence. The write may have landed; reconcile with the system " + "of record before any retry.", + target_system=pack.portal_origin, + ) ledger.finalize( "error", dirty_fields=list(interceptor.dirty_fields.keys()), - error_detail="readback_refuted_persistence", + error_detail="readback_refuted_after_commit", ) return _finish( "ESCALATED", staged_fields=staged.staged, commit_detected=commit_confirmed, readback_verified=False, - reason="readback_refuted_persistence", + reason="readback_refuted_after_commit", egress_ledger_entry_sha256=egress_entry_sha, with_aci=True, ) @@ -762,8 +681,6 @@ def _finish( commit_detected=commit_confirmed, readback_verified=True, reason=f"completion_closure_failed:{closure.reason}", - healed=healed, - published_pack_path=published_pack_path, egress_ledger_entry_sha256=egress_entry_sha, closure_passed=False, with_aci=True, @@ -776,8 +693,6 @@ def _finish( commit_detected=commit_confirmed, readback_verified=True, reason=decision.reason, - healed=healed, - published_pack_path=published_pack_path, egress_ledger_entry_sha256=egress_entry_sha, closure_passed=closure.allowed, with_aci=True, diff --git a/packages/kernel/tests/test_autopilot_stage_gate.py b/packages/kernel/tests/test_autopilot_stage_gate.py index 2b0d59b072..e6c54d3314 100644 --- a/packages/kernel/tests/test_autopilot_stage_gate.py +++ b/packages/kernel/tests/test_autopilot_stage_gate.py @@ -369,3 +369,134 @@ def test_cli_publish_pack_signs_a_pack_the_runner_trusts(tmp_path: Path, capsys: out = json.loads(capsys.readouterr().out.strip().splitlines()[-1]) pulled = pull_verified_pack(Path(out["out"]), pub_path.read_bytes()) assert pulled.stage == "VERIFIED_AUTOPILOT" + + +# ---- A heal never repairs and commits within the same autopilot run ---- + +_OVERLAY = ( + '
' +) + + +def _start_heal_portal(*, blocked: bool, drop_writes: bool) -> Tuple[ThreadingHTTPServer, str, List[str]]: + """A form whose Save posts to /submit. ``posts`` counts every POST.""" + posts: List[str] = [] + saved: List[str] = [] + + class _Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + html = f""" + + + + {_OVERLAY if blocked else ""} +
{" ".join(saved)}
+ """ + body = html.encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: # noqa: N802 + length = int(self.headers.get("Content-Length", "0") or "0") + data = json.loads(self.rfile.read(length).decode("utf-8") or "{}") + posts.append(str(data.get("member_id", ""))) + if not drop_writes: + saved.append(f"member_id:{data.get('member_id', '')}") + body = b'{"status":"ok"}' + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 + return + + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://127.0.0.1:{int(server.server_address[1])}", posts + + +def _resubmitting_coder(calls: List[str]) -> Any: + def _coder(twin_html: str, var_keys: List[str], safe_err: str) -> str: + calls.append(safe_err) + return ( + "def repair(ui, vars):\n" + ' ui.fill(0, vars["$member_id"])\n' + " ui.click(1)\n" + ) + + return _coder + + +def test_autopilot_heal_on_blocked_commit_control_never_clicks_commit(tmp_path: Path) -> None: + priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() + server, base_url, posts = _start_heal_portal(blocked=True, drop_writes=False) + try: + signed = publish_signed_pack( + _pack(base_url, "VERIFIED_AUTOPILOT"), priv_pem, tmp_path / "registry" + ) + calls: List[str] = [] + res = run_portal_pack( + pack_path=signed, + dossier={"member_id": "MEM-2001"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=pub_pem, + coding_agent_fn=_resubmitting_coder(calls), + egress_ledger_path=tmp_path / "egress.jsonl", + ) + assert res.outcome in ("ESCALATED", "READY_FOR_HUMAN_COMMIT") + assert res.reason.startswith("commit_control_blocked") + assert res.commit_detected is False + assert res.healed is False + assert posts == [] + finally: + server.shutdown() + server.server_close() + + +def test_autopilot_refuted_readback_after_commit_never_resubmits(tmp_path: Path) -> None: + priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() + receipt_priv, receipt_pub = generate_ephemeral_ed25519_keypair() + server, base_url, posts = _start_heal_portal(blocked=False, drop_writes=True) + try: + signed = publish_signed_pack( + _pack(base_url, "VERIFIED_AUTOPILOT"), priv_pem, tmp_path / "registry" + ) + calls: List[str] = [] + receipt_out = tmp_path / "receipt.json" + res = run_portal_pack( + pack_path=signed, + dossier={"member_id": "MEM-2002"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=pub_pem, + coding_agent_fn=_resubmitting_coder(calls), + egress_ledger_path=tmp_path / "egress.jsonl", + signing_key=receipt_priv, + receipt_out=receipt_out, + ) + assert res.outcome == "ESCALATED" + assert res.reason == "readback_refuted_after_commit" + assert res.healed is False + assert posts == ["MEM-2002"] # the one commit click; no second write + assert calls == [] # the heal agent is not even asked + receipt = json.loads(receipt_out.read_text(encoding="utf-8")) + assert "uncertain_write_reconcile" in receipt["payload"]["obligations"] + finally: + server.shutdown() + server.server_close() diff --git a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py index 0867fc1d78..4b32e03cee 100644 --- a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py +++ b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py @@ -297,8 +297,11 @@ def _intl_coding_agent(twin_html: str, var_keys: List[str], _err: str, _fb: Dict egress_ledger_path=tmp_path / "intl_egress.jsonl", use_bijective_twin_symbols=True, ) - assert heal_res.healed is True - assert heal_res.outcome == "VERIFIED" + # The repair is proposed in the twin only; autopilot never applies it live. + assert heal_res.healed is False + assert heal_res.heal_proposed is True + assert heal_res.outcome == "ESCALATED" + assert heal_res.commit_detected is False assert heal_res.egress_ledger_entry_sha256 assert len(seen_html) == 1 diff --git a/packages/kernel/tests/test_unified_runtime.py b/packages/kernel/tests/test_unified_runtime.py index 12d56ef773..79a6b91fbc 100644 --- a/packages/kernel/tests/test_unified_runtime.py +++ b/packages/kernel/tests/test_unified_runtime.py @@ -179,11 +179,11 @@ def operator_prepare_handler(card: PrepareCard) -> PrepareResumeResponse: server.server_close() -def test_run_portal_pack_self_heal_fallback_egress_audit_and_no_self_promotion(tmp_path: Path) -> None: - """Warm staging failure -> Zero-PHI digital-twin self-heal -> LocalEgressGuard. +def test_run_portal_pack_self_heal_is_proposed_in_twin_not_applied(tmp_path: Path) -> None: + """Warm staging failure -> Zero-PHI digital-twin repair proposal -> LocalEgressGuard. - The healed run must not publish or promote its own pack: its only read-back - is the values it wrote, so ``auto_publish_on_heal`` publishes nothing. + The run must not apply the unqualified repair on the live page, commit, or + publish or promote its own pack. It escalates with the proposal recorded. """ drifted_html = """
@@ -255,9 +255,12 @@ def heal_coder(twin_html: str, var_keys: List[str], safe_err: str) -> str: auto_publish_on_heal=True, ) - assert res.outcome == "VERIFIED" - assert res.healed is True - assert res.readback_verified is True + assert res.outcome == "ESCALATED" + assert res.reason.endswith(";self_heal_proposed_not_applied") + assert res.heal_proposed is True + assert res.healed is False + assert res.commit_detected is False + assert res.readback_verified is False assert len(res.egress_ledger_entry_sha256) == 64 assert res.published_pack_path is None assert not registry_dir.exists() or not any(registry_dir.iterdir()) From 0e99cfcae0248bddad3ebab3318f11d509d4dae9 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 29 Nov 2026 23:28:06 -0500 Subject: [PATCH 3/3] fix(kernel): bind autopilot to the signed origin; record every post-click uncertain write A signed VERIFIED_AUTOPILOT pack now approves its own portal_origin only. Autopilot returns ESCALATED (autopilot_origin_not_signed) unless the page has exactly that scheme, host and port: before the browser opens when url is elsewhere, after navigation, redirects or CDP attach, on any popup before it is staged, and right before the commit click. A pack without a valid http(s) origin cannot run autopilot. Every exit after the commit click that does not end VERIFIED now adds an uncertain_write_reconcile obligation to the ledger and signed receipt and sets RunResult.uncertain_write: commit_not_observed, read-back refutation, completion-closure failure, and an exception after the click (now ESCALATED post_commit_error: instead of raising). --- packages/kernel/CHANGELOG.md | 6 +- packages/kernel/README.md | 12 +- .../kernel/src/openadapt_kernel/mcp_server.py | 4 +- .../kernel/src/openadapt_kernel/runner.py | 104 +++++++++- .../kernel/tests/test_autopilot_stage_gate.py | 189 ++++++++++++++++++ .../kernel/tests/test_kernel_runner_e2e.py | 17 +- .../test_runtime_wiring_and_raw_demos.py | 5 +- 7 files changed, 318 insertions(+), 19 deletions(-) diff --git a/packages/kernel/CHANGELOG.md b/packages/kernel/CHANGELOG.md index 938412755f..ad345abaef 100644 --- a/packages/kernel/CHANGELOG.md +++ b/packages/kernel/CHANGELOG.md @@ -5,11 +5,13 @@ Breaking: autopilot now fails closed on any pack that is not signed and promoted. - `run_portal_pack(mode="autopilot")` and `openadapt-kernel run --mode autopilot` load the pack through the registry's Ed25519 signature, digest and zero-PII check against a pinned key (`trusted_pack_public_key` / `--trusted-pack-pub`). A missing key, unsigned file, foreign key, edited envelope, or a signed stage other than `VERIFIED_AUTOPILOT` returns `ESCALATED` with zero submissions. Draft mode still loads flat or signed packs. +- The signature also binds autopilot to the signed `portal_origin`. Unless the page has exactly that scheme, host and port (default ports 80 and 443), the run returns `ESCALATED` with `autopilot_origin_not_signed`. The check runs before the browser opens when `url` is elsewhere, after navigation, redirects or CDP attach, on any popup before it is staged, and again right before the commit click. A pack with no valid http(s) origin cannot run autopilot. Before this change, a pack signed for one site could submit a form on any other. - `NonDomKernelExecutor.execute(autonomy_stage=...)` can only lower the pack's stage; unknown stages resolve to `SHADOW`. - Self-healing no longer promotes or publishes the healed pack. It used to qualify the pack against its own written values. `auto_publish_on_heal` and `registry_dir` are kept for compatibility but publish nothing. - Autopilot no longer repairs and commits in the same run. When staging fails or the commit control is blocked, `coding_agent_fn` may propose a repair inside the zero-PHI twin. The run then returns `ESCALATED` with `heal_proposed=True` and the reason suffix `self_heal_proposed_not_applied`, and clicks nothing on the live page. Before this change, the unqualified repair was replayed live and could click Save. -- When read-back refutes persistence after the commit click, the run returns `ESCALATED` with `readback_refuted_after_commit` and adds a pending `uncertain_write_reconcile` obligation to the ledger and receipt. It never heals, re-clicks or re-submits. Before this change, a heal could re-submit and report `VERIFIED` after a duplicate write. The old reason `readback_refuted_persistence` is replaced. -- `RunResult.heal_proposed` is new. In autopilot, `RunResult.healed` is now always `False`. +- When read-back refutes persistence after the commit click, the run returns `ESCALATED` with `readback_refuted_after_commit`. It never heals, re-clicks or re-submits. Before this change, a heal could re-submit and report `VERIFIED` after a duplicate write. The old reason `readback_refuted_persistence` is replaced. +- Every exit after the commit click that does not end `VERIFIED` adds a pending `uncertain_write_reconcile` obligation to the ledger and the signed receipt and sets `RunResult.uncertain_write`. That covers `commit_not_observed`, `readback_refuted_after_commit`, a completion-closure failure, and an exception after the click, which now returns `ESCALATED` with `post_commit_error:` instead of raising. +- `RunResult.heal_proposed` and `RunResult.uncertain_write` are new. In autopilot, `RunResult.healed` is now always `False`. - MCP server: mode ceiling, trusted pack key, receipt key and output root are server configuration (`McpServerConfig`, `serve-mcp --allow-autopilot --trusted-pack-pub --priv --output-root`). Tool calls default to draft, cannot request autopilot unless the server allows it, cannot pass `private_key_path` or any other undeclared argument, and write only under the output root. - `pull_verified_pack` raises `ValueError` for non-envelope files, non-Ed25519 keys and bad signatures instead of relying on `assert`. - New `openadapt-kernel publish-pack` command signs a pack into a registry directory. diff --git a/packages/kernel/README.md b/packages/kernel/README.md index e73428fa37..86147723b6 100644 --- a/packages/kernel/README.md +++ b/packages/kernel/README.md @@ -33,6 +33,12 @@ by another key, an envelope edited after signing, or a `SHADOW` or nothing is submitted. Draft mode accepts unsigned packs because it stops before the commit control. +The signature also covers where the run may click. Autopilot refuses with +`autopilot_origin_not_signed` unless the page has exactly the pack's +`portal_origin` (scheme, host and port), checked before the browser opens, +after navigation or CDP attach, on any popup, and right before the commit +click. + Signing with `publish-pack` is the promotion step, so whoever holds the pack key approves autopilot. Keep that key apart from the receipt key (`--priv`), which the runner holds. A run never publishes or promotes its own pack. @@ -41,8 +47,10 @@ Autopilot never repairs and commits in the same run. If staging fails or the commit control is blocked, a coding agent may propose a repair inside the zero-PHI twin; the run escalates with the proposal recorded and clicks nothing. If read-back refutes persistence after the commit click, the run escalates with -`readback_refuted_after_commit` and records an uncertain write for -reconciliation. It never clicks or submits again. +`readback_refuted_after_commit` and never clicks or submits again. Any run that +clicked commit and did not end `VERIFIED` records an `uncertain_write_reconcile` +obligation in the signed receipt, so the write is reconciled rather than +retried. `NonDomKernelExecutor.execute(autonomy_stage=...)` can only lower a pack's stage, never raise it. diff --git a/packages/kernel/src/openadapt_kernel/mcp_server.py b/packages/kernel/src/openadapt_kernel/mcp_server.py index 7b31215ee0..460599bf73 100644 --- a/packages/kernel/src/openadapt_kernel/mcp_server.py +++ b/packages/kernel/src/openadapt_kernel/mcp_server.py @@ -11,7 +11,9 @@ autopilot ceiling, the receipt signing key, the trusted pack key and the output root are server configuration (:class:`McpServerConfig`, set from ``openadapt-kernel serve-mcp`` flags). A tool call may lower a run to draft, -and every file it writes must resolve under the output root. +and every file it writes must resolve under the output root. Tool calls do +choose ``url`` and ``commit_selector``, but autopilot only clicks on the +origin the trusted pack is signed for. """ from __future__ import annotations diff --git a/packages/kernel/src/openadapt_kernel/runner.py b/packages/kernel/src/openadapt_kernel/runner.py index caae1c9efa..4b4370fe1a 100644 --- a/packages/kernel/src/openadapt_kernel/runner.py +++ b/packages/kernel/src/openadapt_kernel/runner.py @@ -8,6 +8,7 @@ from dataclasses import asdict, dataclass, field from pathlib import Path from typing import Any, Callable, Dict, List, Literal, Mapping, Optional, Sequence +from urllib.parse import urlsplit from openadapt_kernel.aci import OnlineACICalibrator from openadapt_kernel.app_cartridge import AppCartridge, evaluate_cartridge_ood_support @@ -66,9 +67,43 @@ class RunResult: aci_alpha_t: Optional[float] = None aci_threshold: Optional[float] = None heal_proposed: bool = False + uncertain_write: bool = False _HEAL_PROPOSED = "self_heal_proposed_not_applied" +_ORIGIN_NOT_SIGNED = "autopilot_origin_not_signed" +_UNCERTAIN_WRITE = "uncertain_write_reconcile" +_DEFAULT_PORTS = {"http": 80, "https": 443} + + +def _origin_tuple(value: str) -> Optional[tuple[str, str, int]]: + """Return ``(scheme, host, port)`` for an http(s) URL, else ``None``. + + The port is explicit or the scheme default, so ``https://a`` and + ``https://a:443`` are the same origin and ``http://a:8080`` is not + ``http://a``. Anything that is not http or https (``about:blank``, + ``data:``, ``file:``) has no origin here. + """ + try: + parts = urlsplit(str(value or "").strip()) + scheme = parts.scheme.lower() + host = (parts.hostname or "").lower() + port = parts.port + except ValueError: + return None + if scheme not in _DEFAULT_PORTS or not host: + return None + return scheme, host, port if port is not None else _DEFAULT_PORTS[scheme] + + +def _origin_refusal(signed_origin: str, observed_url: str) -> str: + """Return a refusal reason unless ``observed_url`` is on the signed origin.""" + signed = _origin_tuple(signed_origin) + if signed is None: + return f"{_ORIGIN_NOT_SIGNED}:pack_origin_invalid" + if _origin_tuple(observed_url) != signed: + return f"{_ORIGIN_NOT_SIGNED}:page_origin_mismatch" + return "" def _sign_terminal_receipt( @@ -124,6 +159,8 @@ def _load_autopilot_pack( return None, f"autopilot_pack_signature_invalid:{type(exc).__name__}:{exc}" if pack.stage != "VERIFIED_AUTOPILOT": return None, f"autopilot_pack_stage_not_verified:{pack.stage}" + if _origin_tuple(pack.portal_origin) is None: + return None, f"{_ORIGIN_NOT_SIGNED}:pack_origin_invalid" return pack, "" @@ -250,6 +287,17 @@ def run_portal_pack( any browser work. Draft mode accepts flat or signed packs unverified, since it stops before the commit control. + The signature also binds the run to ``pack.portal_origin``. Autopilot + refuses with ``autopilot_origin_not_signed`` unless the page (and any + popup it stages) has exactly that scheme, host and port: before the + browser opens when ``url`` is elsewhere, after navigation or CDP attach, + and again right before the commit click. + + Once the commit control is clicked the write may have landed, so every + exit that does not end ``VERIFIED`` (including an exception after the + click) adds an ``uncertain_write_reconcile`` obligation to the ledger and + the signed receipt and sets ``RunResult.uncertain_write``. + ``coding_agent_fn`` never repairs and commits within the same run. When staging fails or the commit control is blocked, the agent may propose a repair inside the zero-PHI twin; the run still returns ``ESCALATED`` with @@ -266,6 +314,11 @@ def run_portal_pack( if verified_pack is None: return RunResult(mode=mode, outcome="ESCALATED", reason=refusal) pack = verified_pack + # The signature approves one origin. Refuse a url elsewhere before the + # browser loads it; the page origin is checked again after navigation. + url_refusal = _origin_refusal(pack.portal_origin, url) if url else "" + if url_refusal: + return RunResult(mode=mode, outcome="ESCALATED", reason=url_refusal) elif mode == "draft": pack = _load_portal_pack(pack_path) else: @@ -369,6 +422,9 @@ def run_portal_pack( ledger.record_ssa_literal(k, str(v), source_window="dossier", turn=0) interceptor = CommitInterceptor() + # Set just before the commit click. From then on the write may have landed, + # so every exit that is not VERIFIED records an uncertain write (in _finish). + commit_clicked = [False] def _finish( outcome: str, @@ -386,6 +442,14 @@ def _finish( closure_passed: bool = False, heal_proposed: bool = False, ) -> RunResult: + uncertain_write = commit_clicked[0] and outcome != "VERIFIED" + if uncertain_write and _UNCERTAIN_WRITE not in ledger.obligations: + ledger.add_obligation( + _UNCERTAIN_WRITE, + f"Commit was clicked but the run ended {outcome} ({reason}). The write " + "may have landed; reconcile with the system of record before any retry.", + target_system=pack.portal_origin, + ) rpath = _sign_terminal_receipt( ledger, pack.pack_id, @@ -412,8 +476,19 @@ def _finish( aci_alpha_t=calibrator.alpha_t if with_aci else None, aci_threshold=calibrator.threshold() if with_aci else None, heal_proposed=heal_proposed, + uncertain_write=uncertain_write, ) + def _refuse_off_origin(target: Any, staged_fields: Optional[Dict[str, str]] = None) -> Optional[RunResult]: + """In autopilot, refuse unless ``target`` is on the signed pack origin.""" + if mode != "autopilot": + return None + refusal = _origin_refusal(pack.portal_origin, str(getattr(target, "url", "") or "")) + if not refusal: + return None + ledger.finalize("error", dirty_fields=list(interceptor.dirty_fields.keys()), error_detail=refusal) + return _finish("ESCALATED", staged_fields=staged_fields, reason=refusal) + with sync_playwright() as pw: if cdp_url: browser = pw.chromium.connect_over_cdp(cdp_url) @@ -429,6 +504,11 @@ def _finish( interceptor.attach_playwright_page(page) if url: page.goto(url, wait_until="domcontentloaded") + # After navigation, redirects or CDP attach: stage nothing on a page + # the pack signature does not cover. + off_origin = _refuse_off_origin(page) + if off_origin is not None: + return off_origin init_controls = observe_schema(page) opaque = detect_opaque_visual_surfaces(page) @@ -521,6 +601,9 @@ def _finish( page.locator(popup_trigger_selector).first.click() popup_page = pop_info.value popup_page.wait_for_load_state("domcontentloaded") + off_origin = _refuse_off_origin(popup_page, staged.staged) + if off_origin is not None: + return off_origin pop_staged = stage_form( popup_page, popup_bindings, @@ -582,7 +665,12 @@ def _finish( heal_proposed=heal_proposed, ) + off_origin = _refuse_off_origin(page, staged.staged) + if off_origin is not None: + return off_origin + interceptor.begin_step() + commit_clicked[0] = True page.locator(commit_selector).first.click() interceptor.wait_for_commit_settle( page, target_origin=target_origin, timeout_ms=settle_timeout_ms @@ -624,14 +712,7 @@ def _finish( if not verdict.verified: # The commit click may have landed. Never heal, re-click or # re-submit here: a second write could duplicate the first. - # Record the uncertain write so it is reconciled, not retried. - ledger.add_obligation( - "uncertain_write_reconcile", - "Commit was clicked and the target answered, but read-back refuted " - "persistence. The write may have landed; reconcile with the system " - "of record before any retry.", - target_system=pack.portal_origin, - ) + # _finish records the uncertain write so it is reconciled. ledger.finalize( "error", dirty_fields=list(interceptor.dirty_fields.keys()), @@ -697,6 +778,13 @@ def _finish( closure_passed=closure.allowed, with_aci=True, ) + except Exception as exc: + if not commit_clicked[0]: + raise + # A failure after the click cannot show the write did not land. + detail = f"post_commit_error:{type(exc).__name__}" + ledger.finalize("error", dirty_fields=list(interceptor.dirty_fields.keys()), error_detail=detail) + return _finish("ESCALATED", reason=detail) finally: if close_browser: browser.close() diff --git a/packages/kernel/tests/test_autopilot_stage_gate.py b/packages/kernel/tests/test_autopilot_stage_gate.py index e6c54d3314..0f89093b3d 100644 --- a/packages/kernel/tests/test_autopilot_stage_gate.py +++ b/packages/kernel/tests/test_autopilot_stage_gate.py @@ -500,3 +500,192 @@ def test_autopilot_refuted_readback_after_commit_never_resubmits(tmp_path: Path) finally: server.shutdown() server.server_close() + + +def _start_redirect(target: str) -> Tuple[ThreadingHTTPServer, str]: + """An origin whose every GET redirects to ``target`` (a different origin).""" + + class _Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + self.send_response(302) + self.send_header("Location", target) + self.send_header("Content-Length", "0") + self.end_headers() + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 + return + + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://127.0.0.1:{int(server.server_address[1])}" + + +def test_autopilot_pack_signed_for_one_origin_never_submits_on_another(tmp_path: Path) -> None: + """A signed pack is approval for its own origin only, through the API and MCP.""" + priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() + server_a, origin_a, saved_a = _start_portal() + server_b, origin_b, saved_b = _start_portal() + redirect, redirect_url = _start_redirect(origin_b) + try: + signed = publish_signed_pack( + _pack(origin_a, "VERIFIED_AUTOPILOT"), priv_pem, tmp_path / "registry" + ) + common: Dict[str, Any] = dict( + pack_path=signed, + dossier={"member_id": "MEM-3001"}, + mode="autopilot", + commit_selector="#save_btn", + trusted_pack_public_key=pub_pem, + ) + + # The caller's url is on B: refused before the browser loads it. + direct = run_portal_pack(url=origin_b, **common) + assert direct.outcome == "ESCALATED" + assert direct.reason == "autopilot_origin_not_signed:page_origin_mismatch" + + # Same host, scheme default port: still not the signed origin. + assert run_portal_pack(url="http://127.0.0.1", **common).reason.startswith( + "autopilot_origin_not_signed" + ) + + # The url is on neither origin but redirects to B: the page origin is + # checked after navigation, before anything is staged. + redirected = run_portal_pack(url=redirect_url, **common) + assert redirected.outcome == "ESCALATED" + assert redirected.reason == "autopilot_origin_not_signed:page_origin_mismatch" + assert redirected.staged_fields == {} + + # MCP with autopilot enabled: the model picks the url, not the origin. + pub_path = tmp_path / "pack_pub.pem" + pub_path.write_bytes(pub_pem) + config = McpServerConfig( + allow_autopilot=True, + trusted_pack_public_key_path=pub_path, + output_root=tmp_path / "mcp-out", + ) + via_mcp = dispatch_tool_call( + "kernel_run_pack", + { + "pack_path": str(signed), + "dossier": {"member_id": "MEM-3002"}, + "mode": "autopilot", + "url": origin_b, + "commit_selector": "#save_btn", + }, + config, + ) + assert via_mcp["ok"] is False + assert via_mcp["result"]["reason"].startswith("autopilot_origin_not_signed") + + assert saved_b == [] + assert saved_a == [] + + # Positive control: the same signed pack on its own origin submits. + own = run_portal_pack(url=origin_a, **common) + assert own.outcome == "VERIFIED", own.reason + assert saved_a == [{"member_id": "MEM-3001"}] + assert saved_b == [] + finally: + for srv in (server_a, server_b, redirect): + srv.shutdown() + srv.server_close() + + +def _start_rejecting_portal() -> Tuple[ThreadingHTTPServer, str, List[str]]: + """Same form; the POST is answered 500 and nothing is stored.""" + posts: List[str] = [] + + class _Handler(BaseHTTPRequestHandler): + def do_GET(self) -> None: # noqa: N802 + body = _FORM_HTML.replace("", "").encode("utf-8") + self.send_response(200) + self.send_header("Content-Type", "text/html; charset=utf-8") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def do_POST(self) -> None: # noqa: N802 + length = int(self.headers.get("Content-Length", "0") or "0") + posts.append(str(json.loads(self.rfile.read(length).decode("utf-8")).get("member_id"))) + body = b'{"status":"error"}' + self.send_response(500) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, format: str, *args: Any) -> None: # noqa: A002 + return + + server = ThreadingHTTPServer(("127.0.0.1", 0), _Handler) + threading.Thread(target=server.serve_forever, daemon=True).start() + return server, f"http://127.0.0.1:{int(server.server_address[1])}", posts + + +def test_commit_not_observed_after_click_records_uncertain_write(tmp_path: Path) -> None: + priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() + receipt_priv, _ = generate_ephemeral_ed25519_keypair() + server, base_url, posts = _start_rejecting_portal() + try: + signed = publish_signed_pack( + _pack(base_url, "VERIFIED_AUTOPILOT"), priv_pem, tmp_path / "registry" + ) + receipt_out = tmp_path / "receipt.json" + res = run_portal_pack( + pack_path=signed, + dossier={"member_id": "MEM-4001"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=pub_pem, + signing_key=receipt_priv, + receipt_out=receipt_out, + ) + assert res.outcome == "ESCALATED" + assert res.reason == "commit_not_observed" + assert res.uncertain_write is True + assert posts == ["MEM-4001"] + receipt = json.loads(receipt_out.read_text(encoding="utf-8")) + assert receipt["payload"]["outcome"] == "ESCALATED" + assert "uncertain_write_reconcile" in receipt["payload"]["obligations"] + finally: + server.shutdown() + server.server_close() + + +def test_error_after_commit_click_escalates_with_uncertain_write( + tmp_path: Path, monkeypatch: Any +) -> None: + import openadapt_kernel.runner as runner_mod + + def _broken_readback(*_args: Any, **_kwargs: Any) -> Any: + raise RuntimeError("read-back rail unavailable") + + monkeypatch.setattr(runner_mod, "_verify_post_commit_readback", _broken_readback) + priv_pem, pub_pem = generate_ephemeral_ed25519_keypair() + receipt_priv, _ = generate_ephemeral_ed25519_keypair() + server, base_url, saved = _start_portal() + try: + signed = publish_signed_pack( + _pack(base_url, "VERIFIED_AUTOPILOT"), priv_pem, tmp_path / "registry" + ) + receipt_out = tmp_path / "receipt.json" + res = run_portal_pack( + pack_path=signed, + dossier={"member_id": "MEM-4002"}, + mode="autopilot", + url=base_url, + commit_selector="#save_btn", + trusted_pack_public_key=pub_pem, + signing_key=receipt_priv, + receipt_out=receipt_out, + ) + assert res.outcome == "ESCALATED" + assert res.reason == "post_commit_error:RuntimeError" + assert res.uncertain_write is True + assert saved == [{"member_id": "MEM-4002"}] # the write did land + receipt = json.loads(receipt_out.read_text(encoding="utf-8")) + assert "uncertain_write_reconcile" in receipt["payload"]["obligations"] + finally: + server.shutdown() + server.server_close() diff --git a/packages/kernel/tests/test_kernel_runner_e2e.py b/packages/kernel/tests/test_kernel_runner_e2e.py index 41e314d070..1b06c8f229 100644 --- a/packages/kernel/tests/test_kernel_runner_e2e.py +++ b/packages/kernel/tests/test_kernel_runner_e2e.py @@ -82,17 +82,17 @@ def do_POST(self) -> None: return server, f"http://127.0.0.1:{port}/", saved_records -def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> None: - pack_path = tmp_path / "pack.json" +def _write_signed_pack(pack_path: Path, origin: str) -> bytes: + """Write a VERIFIED_AUTOPILOT pack signed for ``origin``; return its public key.""" pack_path.write_text( json.dumps( { "pack_id": "carrier-quote-v1", - "portal_origin": "http://127.0.0.1", + "portal_origin": origin, "variable_fields": ["policy_number", "postal_code"], "static_defaults": {"state_code": "OK"}, "provenance_map": {"policy_number": "src_policy", "postal_code": "src_zip"}, - "readback_url_pattern": "http://127.0.0.1/", + "readback_url_pattern": origin, "stage": "VERIFIED_AUTOPILOT", "shadow_passes": 10, "edge_branches": {}, @@ -100,6 +100,10 @@ def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> No ), encoding="utf-8", ) + return sign_pack_file(pack_path) + + +def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> None: dossier_path = tmp_path / "dossier.json" dossier_path.write_text(json.dumps({"src_policy": "POL-777", "src_zip": "74103"}), encoding="utf-8") @@ -107,10 +111,12 @@ def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> No pub_path = tmp_path / "pub.pem" assert main(["keygen", "--priv", str(priv_path), "--pub", str(pub_path)]) == 0 pack_pub_path = tmp_path / "pack_pub.pem" - pack_pub_path.write_bytes(sign_pack_file(pack_path)) # 1. Healthy server: Draft-to-Commit stages form without POST, Autopilot commits + verifies + signs srv_ok, url_ok, records_ok = _start_portal_server(drop_writes=False) + # The signature binds autopilot to one origin, so each server gets its own pack. + pack_path = tmp_path / "pack.json" + pack_pub_path.write_bytes(_write_signed_pack(pack_path, url_ok)) try: rc_draft = main(["run", "--pack", str(pack_path), "--dossier", str(dossier_path), "--mode", "draft", "--url", url_ok]) assert rc_draft == 0 @@ -150,6 +156,7 @@ def test_cli_run_draft_autopilot_and_dropped_write_refusal(tmp_path: Path) -> No # 2. Dropped-write server (shows 'Saved successfully!' banner while dropping DB write): # Fresh reload refutes persistence -> MUST return exit 1 (ESCALATED) and sign non-VERIFIED receipt. srv_bad, url_bad, records_bad = _start_portal_server(drop_writes=True) + pack_pub_path.write_bytes(_write_signed_pack(pack_path, url_bad)) try: bad_receipt = tmp_path / "bad_receipt.json" rc_bad = main( diff --git a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py index 4b32e03cee..21f24cdfc8 100644 --- a/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py +++ b/packages/kernel/tests/test_runtime_wiring_and_raw_demos.py @@ -4,7 +4,7 @@ import json import threading -from dataclasses import asdict +from dataclasses import asdict, replace from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from pathlib import Path from typing import Any, Dict, List, Tuple @@ -271,6 +271,9 @@ def test_runner_bijective_symbols_ood_halt_and_canvas_servo(tmp_path: Path) -> N "" ) server, base_url = _start_local_server({"/intl": intl_html, "/canvas": canvas_html}) + # Autopilot is bound to the signed origin, so re-sign for this server's port. + pack_path.write_text(json.dumps(asdict(replace(pack, portal_origin=base_url))), encoding="utf-8") + pack_pub = sign_pack_file(pack_path) try: seen_html: List[str] = []