From 24bad3c88164cbbb776f9c2d0201c949c42c7e58 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 09:09:12 -0500 Subject: [PATCH 1/8] feat(flow): add domain-agnostic openadapt onboard pack synthesis and planted-fault qualification loop --- openadapt/cli_tasks.py | 1 + packages/flow/openadapt_flow/__main__.py | 1 + packages/flow/openadapt_flow/cli_tasks.py | 1 + .../flow/openadapt_flow/onboard/__init__.py | 23 + packages/flow/openadapt_flow/onboard/cli.py | 86 ++ .../flow/openadapt_flow/onboard/engine.py | 824 ++++++++++++++++++ packages/flow/openadapt_flow/onboard/types.py | 249 ++++++ packages/flow/tests/test_onboard_loop.py | 657 ++++++++++++++ 8 files changed, 1842 insertions(+) create mode 100644 packages/flow/openadapt_flow/onboard/__init__.py create mode 100644 packages/flow/openadapt_flow/onboard/cli.py create mode 100644 packages/flow/openadapt_flow/onboard/engine.py create mode 100644 packages/flow/openadapt_flow/onboard/types.py create mode 100644 packages/flow/tests/test_onboard_loop.py diff --git a/openadapt/cli_tasks.py b/openadapt/cli_tasks.py index 4e923f1586..1994bddaa9 100644 --- a/openadapt/cli_tasks.py +++ b/openadapt/cli_tasks.py @@ -81,6 +81,7 @@ "materialize-approved": "compile --materialize-approved", "narration": "record narration", "no-outbound": "setup no-outbound", + "onboard": "setup onboard", "plan": "run --plan", "process": "run --process", "propose-qualification": "qualify --propose", diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 195b1b4bc7..238d93b498 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13198,6 +13198,7 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: _register_rollback(sub) _register_shadow(sub) __import__("openadapt_flow.readiness.cli", fromlist=["cli"]).register(sub) + __import__("openadapt_flow.onboard.cli", fromlist=["cli"]).register(sub) _register_receipt(sub) _register_learn(sub) _register_reconcile(sub) diff --git a/packages/flow/openadapt_flow/cli_tasks.py b/packages/flow/openadapt_flow/cli_tasks.py index 4f37d944a4..0279cd7aad 100644 --- a/packages/flow/openadapt_flow/cli_tasks.py +++ b/packages/flow/openadapt_flow/cli_tasks.py @@ -80,6 +80,7 @@ "materialize-approved": "compile --materialize-approved", "narration": "record narration", "no-outbound": "setup no-outbound", + "onboard": "setup onboard", "plan": "run --plan", "process": "run --process", "propose-qualification": "qualify --propose", diff --git a/packages/flow/openadapt_flow/onboard/__init__.py b/packages/flow/openadapt_flow/onboard/__init__.py new file mode 100644 index 0000000000..4db662f862 --- /dev/null +++ b/packages/flow/openadapt_flow/onboard/__init__.py @@ -0,0 +1,23 @@ +"""Domain-agnostic pack onboarding and planted-fault qualification loop.""" + +from openadapt_flow.onboard.engine import onboard_pack, qualify_pack, synthesize_pack +from openadapt_flow.onboard.types import ( + CleanWriteCase, + CleanWriteOutcome, + KindOnboardingSpec, + OnboardSpec, + PlantedFaultOutcome, + QualificationResult, +) + +__all__ = [ + "CleanWriteCase", + "CleanWriteOutcome", + "KindOnboardingSpec", + "OnboardSpec", + "PlantedFaultOutcome", + "QualificationResult", + "onboard_pack", + "qualify_pack", + "synthesize_pack", +] diff --git a/packages/flow/openadapt_flow/onboard/cli.py b/packages/flow/openadapt_flow/onboard/cli.py new file mode 100644 index 0000000000..1f85295519 --- /dev/null +++ b/packages/flow/openadapt_flow/onboard/cli.py @@ -0,0 +1,86 @@ +"""CLI entry point for ``openadapt onboard`` (single-command pack onboarding).""" + +from __future__ import annotations + +import argparse +import json +import sys +from pathlib import Path +from typing import Any + +from openadapt_flow.onboard.engine import onboard_pack, synthesize_pack +from openadapt_flow.onboard.types import OnboardSpec + + +def _cmd_onboard(args: argparse.Namespace) -> int: + try: + spec = OnboardSpec.load(args.spec) + except (OSError, ValueError, KeyError) as exc: + print(f"REFUSED: invalid onboard spec: {exc}", file=sys.stderr) + return 2 + + out_dir = Path(args.out) + if args.dry_run: + manifest_path, digest = synthesize_pack(spec, out_dir) + payload = { + "pack_name": spec.name, + "certified": False, + "dry_run": True, + "manifest_path": str(manifest_path), + "pack_digest": digest, + } + if args.json: + print(json.dumps(payload, indent=2)) + else: + print( + f"Synthesized pack {spec.name!r} at {manifest_path} " + f"(digest {digest}; dry-run, not certified)" + ) + return 0 + + result = onboard_pack(spec, out_dir) + if args.json: + print(json.dumps(result.to_dict(), indent=2)) + else: + status = "CERTIFIED" if result.certified else "REFUSED" + print( + f"{status}: pack={result.pack_name!r} " + f"planted_faults={result.planted_faults_caught}/{result.planted_faults_total} " + f"clean_writes={result.clean_writes_verified}/{result.clean_writes_total} " + f"false_stop_rate={result.false_stop_rate:.1%} " + f"digest={result.pack_digest}" + ) + for reason in result.refusal_reasons: + print(f" refusal: {reason}", file=sys.stderr) + return 0 if result.certified else 2 + + +def register(subparsers: Any) -> None: + """Register the ``onboard`` subcommand on the Flow root parser.""" + + p = subparsers.add_parser( + "onboard", + help="Synthesize and planted-fault-qualify a verification pack for any system of record", + allow_abbrev=False, + ) + p.add_argument( + "--spec", + required=True, + help="Path to declarative onboard spec (YAML or JSON)", + ) + p.add_argument( + "--out", + required=True, + help="Output directory for synthesized pack, contracts, and QUALIFICATION.json", + ) + p.add_argument( + "--json", + action="store_true", + help="Emit structured QualificationResult JSON to stdout", + ) + p.add_argument( + "--dry-run", + action="store_true", + help="Synthesize the pack without running qualification (pack is not certified)", + ) + p.set_defaults(func=_cmd_onboard) diff --git a/packages/flow/openadapt_flow/onboard/engine.py b/packages/flow/openadapt_flow/onboard/engine.py new file mode 100644 index 0000000000..7847aa3bdf --- /dev/null +++ b/packages/flow/openadapt_flow/onboard/engine.py @@ -0,0 +1,824 @@ +"""Automated pack synthesis and planted-fault qualification engine. + +Domain-agnostic: operates solely on declarative :class:`OnboardSpec` inputs, +synthesizes standard ``openadapt.verify/v1`` contracts and ``manifest.yaml`` +compatible with ``verify_contract.choose()`` (including compositional field-set +synthesis and null-safe SQL equality binding), runs a deterministic +planted-fault mutation suite against an isolated sandbox copy, verifies clean +writes with signed ``record/run/v1`` receipts, and refuses certification unless +0% of planted faults pass and 0% of clean writes false-stop. +""" + +from __future__ import annotations + +import hashlib +import json +import shutil +import sqlite3 +import tempfile +from pathlib import Path +from typing import Any, Mapping, Optional, Sequence + +import yaml + +from openadapt_flow.generate import verify_contract as gen +from openadapt_flow.onboard.types import ( + CleanWriteCase, + CleanWriteOutcome, + KindOnboardingSpec, + OnboardSpec, + PlantedFaultOutcome, + QualificationResult, +) +from openadapt_flow.runtime.effects.sql import assert_read_only_sql +from openadapt_flow.verifier import ( + Actor, + MemoryLedger, + Outcome, + begin_write, + verify_write, +) + + +def _slug(fields: Sequence[str]) -> str: + return "__".join(sorted(fields)) or "empty" + + +def _sqlite_table_columns(db: Path, table: str) -> list[str]: + con = sqlite3.connect(db) + try: + rows = con.execute(f"PRAGMA table_info({table})").fetchall() + return [str(r[1]) for r in rows] + finally: + con.close() + + +def _all_kind_columns( + kind_spec: KindOnboardingSpec, + read_cfg: Optional[Mapping[str, Any]] = None, +) -> list[str]: + cols: list[str] = [kind_spec.identity_field] + if read_cfg and isinstance(read_cfg.get("sqlite_database"), str): + db_path = Path(str(read_cfg["sqlite_database"])) + if db_path.is_file(): + for c in _sqlite_table_columns(db_path, kind_spec.table): + if c not in cols: + cols.append(c) + ordered_params = ( + *kind_spec.required_fields, + *kind_spec.optional_fields, + *kind_spec.identity_params, + *kind_spec.change_fields, + *kind_spec.filter_params, + ) + for p in ordered_params: + c = kind_spec.column_for(p) + if c not in cols: + cols.append(c) + for c in (*kind_spec.invariant_pins.keys(), *kind_spec.bookkeeping_fields): + if c not in cols: + cols.append(c) + return cols + + +def _build_contract_doc( + spec: OnboardSpec, + kind_spec: KindOnboardingSpec, + field_set: Sequence[str], + *, + flavor: str, + read_override: Optional[Mapping[str, Any]] = None, +) -> dict[str, Any]: + """Build one ``openadapt.verify/v1`` document for ``(kind_spec, field_set, flavor)``.""" + + read_cfg = dict(read_override if read_override is not None else spec.read) + fset = set(field_set) + base_cols = _all_kind_columns(kind_spec, read_cfg) + select_items = [f"t.{col} AS {col}" for col in base_cols] + match: dict[str, Any] = {} + + for p in sorted(fset): + col = kind_spec.column_for(p) + match[col] = {"param": p} + + for col, lit in sorted(kind_spec.invariant_pins.items()): + if col not in match: + match[col] = {"literal": lit} + + if kind_spec.mode == "create": + for opt in sorted(kind_spec.optional_fields): + if opt in fset: + continue + col = kind_spec.column_for(opt) + alias = f"empty__{col}" + select_items.append( + f"CASE WHEN t.{col} IS NULL OR t.{col} = '' THEN '1' ELSE '0' END AS {alias}" + ) + match[alias] = {"literal": "1"} + + where_clauses: list[str] = [] + sql_query_params: dict[str, Any] = {} + for fp in kind_spec.filter_params: + if fp in fset: + col = kind_spec.column_for(fp) + where_clauses.append(f"t.{col} = :{fp}") + sql_query_params[fp] = {"param": fp} + + sql = f"SELECT {', '.join(select_items)} FROM {kind_spec.table} t" + if where_clauses: + sql += " WHERE " + " AND ".join(where_clauses) + assert_read_only_sql(sql, binds=bool(sql_query_params)) + + surface: dict[str, Any] = { + "kind": "sql", + **read_cfg, + "sql_query": sql, + } + if sql_query_params: + surface["sql_query_params"] = sql_query_params + + target_fields: list[str] = [] + if kind_spec.mode == "update" and flavor == "update": + ident_set = set(kind_spec.identity_params) + tfs = set(kind_spec.bookkeeping_fields) + for p in sorted(fset - ident_set): + tfs.add(kind_spec.column_for(p)) + target_fields = sorted(tfs) + + count_new_only = kind_spec.mode == "create" and flavor == "create" + return { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "surfaces", + "surfaces": {"record": surface}, + }, + "effects": [ + { + "kind": "record_written", + "probe": "surface=record", + "match": match, + "expected_count": 1, + "count_new_only": count_new_only, + } + ], + "frame": { + "identity_field": kind_spec.identity_field, + "target_fields": target_fields, + "target_fields_by_surface": ( + {"record": target_fields} if target_fields else {} + ), + }, + } + + +def _pack_digest(out_dir: Path) -> str: + h = hashlib.sha256() + for p in sorted(out_dir.rglob("*.yaml")): + rel = p.relative_to(out_dir).as_posix() + h.update(rel.encode("utf-8")) + h.update(b"\0") + h.update(p.read_bytes()) + h.update(b"\0") + return "sha256:" + h.hexdigest() + + +def synthesize_pack( + spec: OnboardSpec, + out_dir: str | Path, + *, + read_override: Optional[Mapping[str, Any]] = None, +) -> tuple[Path, str]: + """Synthesize declarative contracts and ``manifest.yaml`` into ``out_dir``.""" + + root = Path(out_dir) + root.mkdir(parents=True, exist_ok=True) + kinds_manifest: dict[str, Any] = {} + + for ks in spec.kinds: + variants: list[dict[str, Any]] = [] + for raw_fs in ks.demonstrated_field_sets: + fset = sorted(set(raw_fs)) + slug = _slug(fset) + write_rel = f"contracts/{ks.kind}/{slug}.{ks.mode}.yaml" + found_rel = f"contracts/{ks.kind}/{slug}.found.yaml" + w_doc = _build_contract_doc( + spec, ks, fset, flavor=ks.mode, read_override=read_override + ) + f_doc = _build_contract_doc( + spec, ks, fset, flavor="found", read_override=read_override + ) + for rel, doc in ((write_rel, w_doc), (found_rel, f_doc)): + target = root / rel + target.parent.mkdir(parents=True, exist_ok=True) + target.write_text( + yaml.safe_dump(doc, sort_keys=False, allow_unicode=True), + encoding="utf-8", + ) + variants.append( + { + "fields": fset, + ks.mode: write_rel, + "found": found_rel, + } + ) + + fields_spec: dict[str, Any] + if ks.mode == "create": + fields_spec = { + "required": sorted(ks.required_fields), + "optional": sorted(ks.optional_fields), + "lists": [], + } + else: + fields_spec = { + "identity": sorted(ks.identity_params), + "changes": sorted(ks.change_fields), + "lists": [], + } + kinds_manifest[ks.kind] = { + "mode": ks.mode, + "fields": fields_spec, + "variants": variants, + } + + manifest_doc = { + "schema_version": gen.MANIFEST_SCHEMA, + "pack_name": spec.name, + "zero_touch": {"admitted": sorted(ks.kind for ks in spec.kinds)}, + "kinds": kinds_manifest, + } + manifest_path = root / "manifest.yaml" + manifest_path.write_text( + yaml.safe_dump(manifest_doc, sort_keys=False, allow_unicode=True), + encoding="utf-8", + ) + return manifest_path, _pack_digest(root) + + +def _perturb(value: Any, field: str) -> Any: + if value is None: + return f"__unexpected_{field}__" + if isinstance(value, bool): + return not value + if isinstance(value, int): + return value + 999 + if isinstance(value, float): + return value + 999.5 + return f"__fault_{field}_{value}__" + + +def _sqlite_insert(db: Path, table: str, row: Mapping[str, Any]) -> None: + cols = list(row.keys()) + placeholders = ", ".join("?" for _ in cols) + con = sqlite3.connect(db) + try: + con.execute( + f"INSERT INTO {table} ({', '.join(cols)}) VALUES ({placeholders})", + [row[c] for c in cols], + ) + con.commit() + finally: + con.close() + + +def _sqlite_update( + db: Path, + table: str, + updates: Mapping[str, Any], + where: Mapping[str, Any], +) -> None: + set_clause = ", ".join(f"{c} = ?" for c in updates) + where_clause = " AND ".join(f"{c} = ?" for c in where) + con = sqlite3.connect(db) + try: + con.execute( + f"UPDATE {table} SET {set_clause} WHERE {where_clause}", + [*updates.values(), *where.values()], + ) + con.commit() + finally: + con.close() + + +def _sqlite_nullable_cols(db: Path, table: str) -> set[str]: + con = sqlite3.connect(db) + try: + rows = con.execute(f"PRAGMA table_info({table})").fetchall() + # PRAGMA table_info columns: cid, name, type, notnull, dflt_value, pk + return {str(r[1]) for r in rows if int(r[3]) == 0} + finally: + con.close() + + +def _sqlite_table_rows(db: Path, table: str) -> list[dict[str, Any]]: + con = sqlite3.connect(db) + con.row_factory = sqlite3.Row + try: + cur = con.execute(f"SELECT * FROM {table}") + return [dict(r) for r in cur.fetchall()] + finally: + con.close() + + +def _run_planted_faults_sqlite( + spec: OnboardSpec, + source_db: Path, + clean_cases: Sequence[CleanWriteCase], + *, + actor: Actor, + workdir: Path, +) -> list[PlantedFaultOutcome]: + """Run deterministic planted-fault mutations against isolated SQLite copies.""" + + outcomes: list[PlantedFaultOutcome] = [] + case_by_kind: dict[str, CleanWriteCase] = {} + for c in clean_cases: + if not c.expect_found and c.kind not in case_by_kind: + case_by_kind[c.kind] = c + + for ks in spec.kinds: + rep_values: dict[str, Any] = {} + if ks.kind in case_by_kind: + rep_values = dict(case_by_kind[ks.kind].values) + elif ks.sample_values: + rep_values = dict(ks.sample_values) + else: + # Derive synthetic sample values from the first demonstrated field set. + for f in ks.demonstrated_field_sets[0]: + rep_values[f] = f"sample_{f}" + + def _exec_fault( + fault_class: str, + field_name: str, + mutate: Any, + ) -> PlantedFaultOutcome: + with tempfile.TemporaryDirectory(dir=workdir) as td: + td_path = Path(td) + sb_db = td_path / "sandbox.sqlite" + shutil.copy2(source_db, sb_db) + sb_manifest, _ = synthesize_pack( + spec, + td_path / "pack", + read_override={**dict(spec.read), "sqlite_database": str(sb_db)}, + ) + contract, params = gen.choose(sb_manifest, ks.kind, rep_values) + pending = begin_write( + contract, + params, + actor=actor, + ledger=MemoryLedger(), + workdir=td_path / "runs", + ) + mutate(sb_db) + res = verify_write(pending) + caught = res.outcome is not Outcome.CONFIRMED + return PlantedFaultOutcome( + kind=ks.kind, + fault_class=fault_class, + field=field_name, + outcome=res.outcome.value, + caught=caught, + reasons=tuple(res.reasons), + ) + + # Build the clean row payload for this kind. + clean_row: dict[str, Any] = {} + for p, v in rep_values.items(): + if v is not None: + clean_row[ks.column_for(p)] = v + for col, lit in ks.invariant_pins.items(): + clean_row.setdefault(col, lit) + + existing_rows = _sqlite_table_rows(source_db, ks.table) + nullable_cols = _sqlite_nullable_cols(source_db, ks.table) + + if ks.mode == "create": + testable_fields = [p for p, v in rep_values.items() if v is not None] + # 1. wrong_value per field + for p in testable_fields: + col = ks.column_for(p) + bad_row = {**clean_row, col: _perturb(rep_values[p], p)} + outcomes.append( + _exec_fault( + "wrong_value", + p, + lambda db, r=bad_row: _sqlite_insert(db, ks.table, r), + ) + ) + # 2. null_vs_value per field (NULL on nullable columns, "" on NOT NULL columns) + for p, v in rep_values.items(): + col = ks.column_for(p) + if v is None: + bad_row = {**clean_row, col: f"__unexpected_{p}__"} + else: + bad_row = {**clean_row, col: None if col in nullable_cols else ""} + outcomes.append( + _exec_fault( + "null_vs_value", + p, + lambda db, r=bad_row: _sqlite_insert(db, ks.table, r), + ) + ) + # 3. missing_write (no-op) + outcomes.append(_exec_fault("missing_write", "*", lambda _db: None)) + + # 4. duplicate_row + def _plant_dup( + db: Path, + tbl: str = ks.table, + row: dict[str, Any] = clean_row, + ) -> None: + _sqlite_insert(db, tbl, row) + _sqlite_insert(db, tbl, row) + + outcomes.append(_exec_fault("duplicate_row", "*", _plant_dup)) + # 5. sibling_edit (valid insert + tamper existing sibling row) + if existing_rows: + sib = existing_rows[0] + sib_id = sib[ks.identity_field] + tamper_col = next( + ( + c + for c in sib + if c != ks.identity_field and c not in ks.bookkeeping_fields + ), + None, + ) + if tamper_col is not None: + + def _plant_create_sib( + db: Path, + tbl: str = ks.table, + row: dict[str, Any] = clean_row, + tc: str = tamper_col, + id_col: str = ks.identity_field, + sid: Any = sib_id, + ) -> None: + _sqlite_insert(db, tbl, row) + _sqlite_update( + db, tbl, {tc: "__tampered_sibling__"}, {id_col: sid} + ) + + outcomes.append( + _exec_fault("sibling_edit", tamper_col, _plant_create_sib) + ) + else: + # Update mode + ident_where = { + ks.column_for(p): rep_values[p] + for p in ks.identity_params + if p in rep_values + } + change_updates = { + ks.column_for(p): rep_values[p] + for p in rep_values + if p not in ks.identity_params and rep_values[p] is not None + } + # 1. wrong_value per changed field + for p in sorted( + k + for k in rep_values + if k not in ks.identity_params and rep_values[k] is not None + ): + col = ks.column_for(p) + bad_upd = {**change_updates, col: _perturb(rep_values[p], p)} + outcomes.append( + _exec_fault( + "wrong_value", + p, + lambda db, u=bad_upd, w=ident_where: _sqlite_update( + db, ks.table, u, w + ), + ) + ) + # 2. null_vs_value per changed field (NULL on nullable columns, "" on NOT NULL) + for p in sorted(k for k in rep_values if k not in ks.identity_params): + col = ks.column_for(p) + if rep_values[p] is None: + bad_upd = {**change_updates, col: f"__unexpected_{p}__"} + else: + bad_upd = { + **change_updates, + col: None if col in nullable_cols else "", + } + outcomes.append( + _exec_fault( + "null_vs_value", + p, + lambda db, u=bad_upd, w=ident_where: _sqlite_update( + db, ks.table, u, w + ), + ) + ) + # 3. missing_write (no-op) + outcomes.append(_exec_fault("missing_write", "*", lambda _db: None)) + # 4. wrong_target (apply update to a different row instead of target) + other_rows = [ + r + for r in existing_rows + if all(str(r.get(wc)) != str(wv) for wc, wv in ident_where.items()) + ] + if other_rows: + other_id = other_rows[0][ks.identity_field] + outcomes.append( + _exec_fault( + "wrong_target", + ks.identity_field, + lambda db, u=change_updates, oid=other_id: _sqlite_update( + db, ks.table, u, {ks.identity_field: oid} + ), + ) + ) + # 5. sibling_edit (valid update on target + tamper sibling row) + tamper_col = next( + ( + c + for c in other_rows[0] + if c != ks.identity_field and c not in ks.bookkeeping_fields + ), + None, + ) + if tamper_col is not None: + + def _plant_update_sib( + db: Path, + tbl: str = ks.table, + u: dict[str, Any] = change_updates, + w: dict[str, Any] = ident_where, + tc: str = tamper_col, + id_col: str = ks.identity_field, + oid: Any = other_id, + ) -> None: + _sqlite_update(db, tbl, u, w) + _sqlite_update( + db, tbl, {tc: "__tampered_sibling__"}, {id_col: oid} + ) + + outcomes.append( + _exec_fault("sibling_edit", tamper_col, _plant_update_sib) + ) + + return outcomes + + +def _issue_signed_run_receipt( + run_dir: Path, + *, + pack_name: str, + kind: str, + case_name: str, + contract: Any, + write_result: Any, +) -> Optional[str]: + """Emit a signed ``record/run/v1`` DSSE receipt (``receipt.json``) in ``run_dir``.""" + + from datetime import datetime, timezone + + from openadapt_flow.offline_seal import seal_home, signer_for + from openadapt_flow.receipt_record import write_receipt_record + + run_dir.mkdir(parents=True, exist_ok=True) + now = datetime.now(timezone.utc).isoformat() + verified = write_result.outcome is Outcome.CONFIRMED + contract_hashes = [eff.contract_hash() for eff in (contract.config.effects or ())] + evidence = [ + { + "effect_contract_hash": ch, + "substrate": "sql", + "initial_verdict": "confirmed" if verified else "refuted", + "final_verdict": "confirmed" if verified else "refuted", + "observed_effect": "present" if verified else "absent", + "verification_tier": 1, + } + for ch in contract_hashes + ] + report: dict[str, Any] = { + "schema_version": "1.0", + "workflow_name": f"{pack_name}:{kind}"[:48], + "run_id": write_result.write_id or case_name, + "started_at": now, + "finished_at": now, + "execution_outcome": "VERIFIED" if verified else "STOPPED", + "outcome": "VERIFIED" if verified else "STOPPED", + "model_calls": 0, + "verifier_outcome": write_result.outcome.value, + "effect_receipt_sha256": write_result.receipt_sha256, + "results": [ + { + "step_id": case_name, + "intent": f"onboard {kind}", + "ok": verified, + "actuation": "api", + "effect_verified": verified, + "effect_contract_hashes": contract_hashes, + "effect_evidence": evidence, + } + ], + "outcome_envelope": { + "required_contracts": {"effect": 1, "authorization": 1}, + "passed_contracts": {"effect": 1 if verified else 0, "authorization": 1}, + }, + } + if write_result.receipt: + (run_dir / "effect-receipt.json").write_text( + json.dumps(write_result.receipt, indent=2, default=str), encoding="utf-8" + ) + (run_dir / "report.json").write_text( + json.dumps(report, indent=2, default=str), encoding="utf-8" + ) + write_receipt_record(run_dir, signer=signer_for(seal_home())) + receipt_path = run_dir / "receipt.json" + return str(receipt_path) if receipt_path.is_file() else None + + +def qualify_pack( + spec: OnboardSpec, + manifest_path: str | Path, + clean_cases: Sequence[CleanWriteCase] = (), + *, + pack_digest: Optional[str] = None, + workdir: Optional[str | Path] = None, +) -> QualificationResult: + """Run planted-fault mutation suite + clean-write verification and emit ``QUALIFICATION.json``.""" + + mpath = Path(manifest_path) + pack_dir = mpath.parent + digest = pack_digest or _pack_digest(pack_dir) + manifest_doc = yaml.safe_load(mpath.read_text(encoding="utf-8")) or {} + actor = Actor(kind="agent", id=spec.actor_id) + run_workdir = Path(workdir) if workdir is not None else pack_dir / "runs" + run_workdir.mkdir(parents=True, exist_ok=True) + + refusal_reasons: list[str] = [] + + # Step 1: Deterministic planted-fault mutation suite against isolated sandbox copies. + fault_outcomes: list[PlantedFaultOutcome] = [] + sqlite_db = spec.read.get("sqlite_database") + if isinstance(sqlite_db, str) and Path(sqlite_db).is_file(): + fault_outcomes = _run_planted_faults_sqlite( + spec, + Path(sqlite_db), + clean_cases, + actor=actor, + workdir=run_workdir, + ) + else: + refusal_reasons.append( + "planted-fault sandbox requires a readable sqlite_database in spec.read" + ) + + faults_total = len(fault_outcomes) + faults_caught = sum(1 for f in fault_outcomes if f.caught) + if faults_total == 0: + refusal_reasons.append("no planted faults were executed") + elif faults_caught < faults_total: + escaped = [ + f"{f.kind}:{f.fault_class}:{f.field}" + for f in fault_outcomes + if not f.caught + ] + refusal_reasons.append( + f"{faults_total - faults_caught}/{faults_total} planted fault(s) passed: " + + ", ".join(escaped) + ) + + # Step 2: Clean-write verification (including novel composed field sets & explicit nulls). + kind_specs = {ks.kind: ks for ks in spec.kinds} + clean_outcomes: list[CleanWriteOutcome] = [] + receipt_paths: list[str] = [] + for idx, case in enumerate(clean_cases): + kind_entry = (manifest_doc.get("kinds") or {}).get(case.kind) or {} + listed_sets = { + frozenset(v.get("fields") or []) for v in (kind_entry.get("variants") or []) + } + given_set = frozenset( + k + for k, v in case.values.items() + if v is not None and not isinstance(v, list) + ) + composed = given_set not in listed_sets + case_name = case.name or f"{case.kind}#{idx + 1}" + ks_obj = kind_specs.get(case.kind) + explicit_nulls = ( + { + k: None + for k, v in case.values.items() + if v is None and k in ks_obj.filter_params + } + if ks_obj is not None + else {} + ) + try: + contract, params = gen.choose( + mpath, case.kind, case.values, extra_params=explicit_nulls or None + ) + pending = begin_write( + contract, + params, + actor=actor, + ledger=MemoryLedger(), + workdir=run_workdir, + ) + case.apply_write() + res = verify_write(pending) + confirmed = res.outcome is Outcome.CONFIRMED + rpath = res.write_receipt_path + if confirmed and not rpath: + case_run_dir = run_workdir / f"clean-{idx + 1:03d}-{case.kind}" + rpath = _issue_signed_run_receipt( + case_run_dir, + pack_name=spec.name, + kind=case.kind, + case_name=case_name, + contract=contract, + write_result=res, + ) + if rpath: + receipt_paths.append(rpath) + clean_outcomes.append( + CleanWriteOutcome( + kind=case.kind, + name=case_name, + fields=tuple(sorted(given_set)), + composed=composed, + outcome=res.outcome.value, + confirmed=confirmed, + receipt_path=rpath, + reasons=tuple(res.reasons), + ) + ) + if not confirmed: + refusal_reasons.append( + f"clean write {case_name!r} stopped with {res.outcome.value}: " + + "; ".join(res.reasons[:2]) + ) + except Exception as exc: # noqa: BLE001 - fail closed on any runtime error + clean_outcomes.append( + CleanWriteOutcome( + kind=case.kind, + name=case_name, + fields=tuple(sorted(given_set)), + composed=composed, + outcome="ERROR", + confirmed=False, + receipt_path=None, + reasons=(str(exc),), + ) + ) + refusal_reasons.append(f"clean write {case_name!r} raised: {exc}") + + clean_total = len(clean_outcomes) + clean_verified = sum(1 for c in clean_outcomes if c.confirmed) + false_stop_rate = ( + round((clean_total - clean_verified) / clean_total, 4) + if clean_total > 0 + else 0.0 + ) + + certified = ( + faults_total > 0 + and faults_caught == faults_total + and clean_verified == clean_total + and not refusal_reasons + ) + + result = QualificationResult( + pack_name=spec.name, + certified=certified, + refusal_reasons=tuple(refusal_reasons), + pack_dir=str(pack_dir), + manifest_path=str(mpath), + pack_digest=digest, + planted_faults_caught=faults_caught, + planted_faults_total=faults_total, + clean_writes_verified=clean_verified, + clean_writes_total=clean_total, + false_stop_rate=false_stop_rate, + receipts_issued=len(receipt_paths), + receipt_paths=tuple(receipt_paths), + fault_outcomes=tuple(fault_outcomes), + clean_outcomes=tuple(clean_outcomes), + ) + (pack_dir / "QUALIFICATION.json").write_text( + json.dumps(result.to_dict(), indent=2), encoding="utf-8" + ) + return result + + +def onboard_pack( + spec: OnboardSpec, + out_dir: str | Path, + clean_cases: Sequence[CleanWriteCase] = (), + *, + workdir: Optional[str | Path] = None, +) -> QualificationResult: + """Single-call onboarding loop: synthesize pack -> planted-fault qualify -> certify.""" + + manifest_path, digest = synthesize_pack(spec, out_dir) + return qualify_pack( + spec, + manifest_path, + clean_cases, + pack_digest=digest, + workdir=workdir, + ) diff --git a/packages/flow/openadapt_flow/onboard/types.py b/packages/flow/openadapt_flow/onboard/types.py new file mode 100644 index 0000000000..cef3b76a5e --- /dev/null +++ b/packages/flow/openadapt_flow/onboard/types.py @@ -0,0 +1,249 @@ +"""Domain-agnostic data types for automated pack onboarding and qualification. + +Zero app-specific knowledge lives here: every table, column, parameter, and +write action is described declaratively in :class:`OnboardSpec`. +""" + +from __future__ import annotations + +import json +import re +from dataclasses import dataclass, field +from pathlib import Path +from typing import Any, Callable, Literal, Mapping, Optional + +import yaml + +_SAFE_IDENT = re.compile(r"^[A-Za-z_][A-Za-z0-9_]*$") + + +def _validate_ident(name: str, what: str) -> str: + if not isinstance(name, str) or not _SAFE_IDENT.match(name): + raise ValueError( + f"{what} {name!r} must be a plain SQL identifier (^[A-Za-z_][A-Za-z0-9_]*$)" + ) + return name + + +@dataclass(frozen=True) +class KindOnboardingSpec: + """Declarative specification of one write kind for a system of record.""" + + kind: str + mode: Literal["create", "update"] + table: str + identity_field: str = "id" + required_fields: tuple[str, ...] = () + optional_fields: tuple[str, ...] = () + identity_params: tuple[str, ...] = () + change_fields: tuple[str, ...] = () + column_map: Mapping[str, str] = field(default_factory=dict) + invariant_pins: Mapping[str, str] = field(default_factory=dict) + bookkeeping_fields: tuple[str, ...] = () + filter_params: tuple[str, ...] = () + demonstrated_field_sets: tuple[tuple[str, ...], ...] = () + sample_values: Mapping[str, Any] = field(default_factory=dict) + + def __post_init__(self) -> None: + _validate_ident(self.kind, "kind") + if self.mode not in ("create", "update"): + raise ValueError(f"kind {self.kind!r}: mode must be 'create' or 'update'") + _validate_ident(self.table, f"kind {self.kind!r} table") + _validate_ident(self.identity_field, f"kind {self.kind!r} identity_field") + for f in ( + *self.required_fields, + *self.optional_fields, + *self.identity_params, + *self.change_fields, + *self.bookkeeping_fields, + *self.filter_params, + ): + _validate_ident(f, f"kind {self.kind!r} field") + for param, col in self.column_map.items(): + _validate_ident(param, f"kind {self.kind!r} column_map key") + _validate_ident(col, f"kind {self.kind!r} column_map value") + for col in self.invariant_pins: + _validate_ident(col, f"kind {self.kind!r} invariant_pins key") + if self.mode == "create" and not self.required_fields: + raise ValueError(f"create kind {self.kind!r} requires required_fields") + if self.mode == "update" and ( + not self.identity_params or not self.change_fields + ): + raise ValueError( + f"update kind {self.kind!r} requires identity_params and change_fields" + ) + if not self.demonstrated_field_sets: + raise ValueError( + f"kind {self.kind!r} requires at least one demonstrated_field_sets entry" + ) + + def column_for(self, param: str) -> str: + return str(self.column_map.get(param, param)) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "KindOnboardingSpec": + return cls( + kind=str(data["kind"]), + mode=data["mode"], + table=str(data["table"]), + identity_field=str(data.get("identity_field") or "id"), + required_fields=tuple(str(x) for x in (data.get("required_fields") or ())), + optional_fields=tuple(str(x) for x in (data.get("optional_fields") or ())), + identity_params=tuple(str(x) for x in (data.get("identity_params") or ())), + change_fields=tuple(str(x) for x in (data.get("change_fields") or ())), + column_map={ + str(k): str(v) for k, v in (data.get("column_map") or {}).items() + }, + invariant_pins={ + str(k): str(v) for k, v in (data.get("invariant_pins") or {}).items() + }, + bookkeeping_fields=tuple( + str(x) for x in (data.get("bookkeeping_fields") or ()) + ), + filter_params=tuple(str(x) for x in (data.get("filter_params") or ())), + demonstrated_field_sets=tuple( + tuple(str(f) for f in fs) + for fs in (data.get("demonstrated_field_sets") or ()) + ), + sample_values=dict(data.get("sample_values") or {}), + ) + + +@dataclass(frozen=True) +class OnboardSpec: + """Complete declarative onboarding input for one system of record.""" + + name: str + read: Mapping[str, Any] + kinds: tuple[KindOnboardingSpec, ...] + actor_id: str = "onboard-verifier" + + def __post_init__(self) -> None: + if not self.name or not self.name.strip(): + raise ValueError("OnboardSpec.name must be non-empty") + if not self.read: + raise ValueError("OnboardSpec.read must configure a read-back connection") + if not self.kinds: + raise ValueError("OnboardSpec.kinds must contain at least one kind") + seen: set[str] = set() + for k in self.kinds: + if k.kind in seen: + raise ValueError(f"duplicate kind {k.kind!r} in OnboardSpec") + seen.add(k.kind) + + @classmethod + def from_dict(cls, data: Mapping[str, Any]) -> "OnboardSpec": + return cls( + name=str(data["name"]), + read=dict(data["read"]), + kinds=tuple(KindOnboardingSpec.from_dict(k) for k in data["kinds"]), + actor_id=str(data.get("actor_id") or "onboard-verifier"), + ) + + @classmethod + def load(cls, path: str | Path) -> "OnboardSpec": + p = Path(path) + raw = p.read_text(encoding="utf-8") + data = json.loads(raw) if p.suffix.lower() == ".json" else yaml.safe_load(raw) + if not isinstance(data, Mapping): + raise ValueError(f"{p} must contain a mapping") + return cls.from_dict(data) + + +@dataclass(frozen=True) +class CleanWriteCase: + """One clean write executed against the target system of record.""" + + kind: str + values: Mapping[str, Any] + apply_write: Callable[[], None] + name: str = "" + expect_found: bool = False + + +@dataclass(frozen=True) +class PlantedFaultOutcome: + """Result of one deterministic planted-fault check.""" + + kind: str + fault_class: str + field: str + outcome: str + caught: bool + reasons: tuple[str, ...] = () + + def to_dict(self) -> dict[str, Any]: + return { + "kind": self.kind, + "fault_class": self.fault_class, + "field": self.field, + "outcome": self.outcome, + "caught": self.caught, + "reasons": list(self.reasons), + } + + +@dataclass(frozen=True) +class CleanWriteOutcome: + """Result of one clean write verification check.""" + + kind: str + name: str + fields: tuple[str, ...] + composed: bool + outcome: str + confirmed: bool + receipt_path: Optional[str] = None + reasons: tuple[str, ...] = () + + def to_dict(self) -> dict[str, Any]: + return { + "kind": self.kind, + "name": self.name, + "fields": list(self.fields), + "composed": self.composed, + "outcome": self.outcome, + "confirmed": self.confirmed, + "receipt_path": self.receipt_path, + "reasons": list(self.reasons), + } + + +@dataclass(frozen=True) +class QualificationResult: + """Structured qualification verdict for an onboarded pack.""" + + pack_name: str + certified: bool + refusal_reasons: tuple[str, ...] + pack_dir: str + manifest_path: str + pack_digest: str + planted_faults_caught: int + planted_faults_total: int + clean_writes_verified: int + clean_writes_total: int + false_stop_rate: float + receipts_issued: int + receipt_paths: tuple[str, ...] + fault_outcomes: tuple[PlantedFaultOutcome, ...] = () + clean_outcomes: tuple[CleanWriteOutcome, ...] = () + + def to_dict(self) -> dict[str, Any]: + return { + "pack_name": self.pack_name, + "certified": self.certified, + "refusal_reasons": list(self.refusal_reasons), + "pack_dir": self.pack_dir, + "manifest_path": self.manifest_path, + "pack_digest": self.pack_digest, + "planted_faults_caught": self.planted_faults_caught, + "planted_faults_total": self.planted_faults_total, + "clean_writes_verified": self.clean_writes_verified, + "clean_writes_total": self.clean_writes_total, + "false_stop_rate": self.false_stop_rate, + "receipts_issued": self.receipts_issued, + "receipt_paths": list(self.receipt_paths), + "fault_outcomes": [f.to_dict() for f in self.fault_outcomes], + "clean_outcomes": [c.to_dict() for c in self.clean_outcomes], + } diff --git a/packages/flow/tests/test_onboard_loop.py b/packages/flow/tests/test_onboard_loop.py new file mode 100644 index 0000000000..9fffcde070 --- /dev/null +++ b/packages/flow/tests/test_onboard_loop.py @@ -0,0 +1,657 @@ +"""End-to-end tests for ``openadapt onboard`` on 2 unseen non-healthcare systems of record. + +Fixtures (zero engine code references either app): +- Fixture A: ERP / Inventory SQLite + HTTP REST service (orders, SKUs, stock). +- Fixture B: ITSM / Ticketing SQLite + HTTP REST service (tickets, assignees, SLA comments). + +Verifies on both unseen fixtures: +- 100% planted faults caught (wrong_value, null_vs_value, missing_write, + duplicate_row, sibling_edit, wrong_target) -> 0% false receipts. +- 0% clean false stops, including novel composed field unions/subsets (#2490) + and explicit ``None`` fields in SQL read filters (#2489). +- Signed ``record/run/v1`` DSSE receipts issued for every confirmed clean write. +- CLI ``openadapt-flow onboard`` / ``setup onboard`` parity and fail-closed refusal. +""" + +from __future__ import annotations + +import base64 +import json +import sqlite3 +import threading +import urllib.request +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer +from pathlib import Path +from typing import Any + +import pytest +import yaml + +from openadapt_flow import __main__ as flow_cli +from openadapt_flow.onboard import ( + CleanWriteCase, + KindOnboardingSpec, + OnboardSpec, + onboard_pack, +) + + +@pytest.fixture(autouse=True) +def _isolated_env(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) -> None: + monkeypatch.setenv("OPENADAPT_LEDGER_DIR", str(tmp_path / "ledger")) + monkeypatch.setenv("OPENADAPT_SEAL_HOME", str(tmp_path / "seal")) + monkeypatch.setenv("OPENADAPT_RECEIPT", "on") + + +def _http_json(url: str, method: str, payload: dict[str, Any]) -> dict[str, Any]: + body = json.dumps(payload).encode("utf-8") + req = urllib.request.Request( + url, + data=body, + method=method, + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=5) as resp: + return json.loads(resp.read().decode("utf-8")) + + +def _assert_signed_receipt(receipt_path: str) -> None: + p = Path(receipt_path) + assert p.is_file(), f"missing receipt file: {receipt_path}" + env = json.loads(p.read_text(encoding="utf-8")) + assert "payload" in env and "signatures" in env and env["signatures"] + stmt = json.loads(base64.b64decode(env["payload"]).decode("utf-8")) + assert stmt.get("predicateType") == "https://openadapt.ai/record/run/v1" + + +# -- Fixture A: Unseen ERP / Inventory SQLite+REST app ----------------------- + + +def _start_erp_fixture(tmp_path: Path) -> tuple[Path, str, ThreadingHTTPServer]: + db = tmp_path / "erp_inventory.sqlite" + con = sqlite3.connect(db) + con.executescript( + "CREATE TABLE orders (" + " id INTEGER PRIMARY KEY AUTOINCREMENT," + " order_code TEXT NOT NULL," + " sku TEXT NOT NULL," + " qty TEXT NOT NULL," + " warehouse TEXT," + " notes TEXT," + " status TEXT NOT NULL DEFAULT 'pending'," + " updated_at TEXT NOT NULL DEFAULT '2026-11-01'" + ");" + "INSERT INTO orders (order_code, sku, qty, warehouse, notes, status, updated_at) " + "VALUES ('ORD-100', 'SKU-BOLT-4', '25', 'WEST-1', 'initial stock', 'pending', '2026-11-01');" + "INSERT INTO orders (order_code, sku, qty, warehouse, notes, status, updated_at) " + "VALUES ('ORD-101', 'SKU-NUT-4', '50', 'EAST-2', 'sibling order', 'pending', '2026-11-01');" + ) + con.commit() + con.close() + + class ErpHandler(BaseHTTPRequestHandler): + def log_message(self, format: str, *args: Any) -> None: + return + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length", "0")) + data = json.loads(self.rfile.read(length).decode("utf-8")) + c = sqlite3.connect(db) + cur = c.execute( + "INSERT INTO orders (order_code, sku, qty, warehouse, notes, status) " + "VALUES (?, ?, ?, ?, ?, ?)", + ( + data["order_code"], + data["sku"], + str(data["qty"]), + data.get("warehouse"), + data.get("notes"), + data.get("status", "pending"), + ), + ) + c.commit() + oid = cur.lastrowid + c.close() + self.send_response(201) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps({"id": oid}).encode("utf-8")) + + def do_PATCH(self) -> None: + length = int(self.headers.get("Content-Length", "0")) + data = json.loads(self.rfile.read(length).decode("utf-8")) + oid = int(self.path.rstrip("/").rsplit("/", 1)[-1]) + updates = { + k: v + for k, v in data.items() + if k in ("qty", "warehouse", "notes", "status") + } + updates["updated_at"] = "2026-11-22" + sets = ", ".join(f"{k} = ?" for k in updates) + c = sqlite3.connect(db) + c.execute( + f"UPDATE orders SET {sets} WHERE id = ?", + [*updates.values(), oid], + ) + c.commit() + c.close() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps({"id": oid, "ok": True}).encode("utf-8")) + + server = ThreadingHTTPServer(("127.0.0.1", 0), ErpHandler) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return db, f"http://127.0.0.1:{port}", server + + +# -- Fixture B: Unseen ITSM / Ticketing SQLite+REST app ---------------------- + + +def _start_itsm_fixture(tmp_path: Path) -> tuple[Path, str, ThreadingHTTPServer]: + db = tmp_path / "itsm_tickets.sqlite" + con = sqlite3.connect(db) + con.executescript( + "CREATE TABLE tickets (" + " id INTEGER PRIMARY KEY AUTOINCREMENT," + " ticket_key TEXT NOT NULL," + " title TEXT NOT NULL," + " assignee TEXT," + " priority TEXT," + " sla_comment TEXT," + " status TEXT NOT NULL DEFAULT 'open'," + " updated_at TEXT NOT NULL DEFAULT '2026-11-01'" + ");" + "INSERT INTO tickets (ticket_key, title, assignee, priority, sla_comment, status, updated_at) " + "VALUES ('INC-500', 'VPN timeout', 'alice', 'P2', 'initial triage', 'open', '2026-11-01');" + "INSERT INTO tickets (ticket_key, title, assignee, priority, sla_comment, status, updated_at) " + "VALUES ('INC-501', 'Badge reader', 'bob', 'P3', 'sibling ticket', 'open', '2026-11-01');" + ) + con.commit() + con.close() + + class ItsmHandler(BaseHTTPRequestHandler): + def log_message(self, format: str, *args: Any) -> None: + return + + def do_POST(self) -> None: + length = int(self.headers.get("Content-Length", "0")) + data = json.loads(self.rfile.read(length).decode("utf-8")) + c = sqlite3.connect(db) + cur = c.execute( + "INSERT INTO tickets (ticket_key, title, assignee, priority, sla_comment, status) " + "VALUES (?, ?, ?, ?, ?, ?)", + ( + data["ticket_key"], + data["title"], + data.get("assignee"), + data.get("priority"), + data.get("sla_comment"), + data.get("status", "open"), + ), + ) + c.commit() + tid = cur.lastrowid + c.close() + self.send_response(201) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps({"id": tid}).encode("utf-8")) + + def do_PATCH(self) -> None: + length = int(self.headers.get("Content-Length", "0")) + data = json.loads(self.rfile.read(length).decode("utf-8")) + tid = int(self.path.rstrip("/").rsplit("/", 1)[-1]) + updates = { + k: v + for k, v in data.items() + if k in ("assignee", "priority", "sla_comment", "status") + } + updates["updated_at"] = "2026-11-22" + sets = ", ".join(f"{k} = ?" for k in updates) + c = sqlite3.connect(db) + c.execute( + f"UPDATE tickets SET {sets} WHERE id = ?", + [*updates.values(), tid], + ) + c.commit() + c.close() + self.send_response(200) + self.send_header("Content-Type", "application/json") + self.end_headers() + self.wfile.write(json.dumps({"id": tid, "ok": True}).encode("utf-8")) + + server = ThreadingHTTPServer(("127.0.0.1", 0), ItsmHandler) + port = server.server_address[1] + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + return db, f"http://127.0.0.1:{port}", server + + +def test_onboard_unseen_erp_inventory_fixture(tmp_path: Path) -> None: + """Fixture A (ERP/Inventory): 100% planted faults caught, 0% clean false stops, signed receipts.""" + db, base_url, server = _start_erp_fixture(tmp_path) + try: + spec = OnboardSpec( + name="erp-inventory", + read={"sqlite_database": str(db)}, + kinds=( + KindOnboardingSpec( + kind="create_order", + mode="create", + table="orders", + required_fields=("order_code", "sku", "qty"), + optional_fields=("warehouse", "notes"), + invariant_pins={"status": "pending"}, + demonstrated_field_sets=( + ("order_code", "sku", "qty", "warehouse"), + ("order_code", "sku", "qty", "notes"), + ), + ), + KindOnboardingSpec( + kind="update_order", + mode="update", + table="orders", + identity_params=("id",), + change_fields=("qty", "warehouse", "notes", "status"), + bookkeeping_fields=("updated_at",), + demonstrated_field_sets=( + ("id", "qty"), + ("id", "warehouse"), + ("id", "notes"), + ("id", "status"), + ), + ), + ), + ) + + clean_cases = [ + CleanWriteCase( + kind="create_order", + name="exact_with_warehouse", + values={ + "order_code": "ORD-201", + "sku": "SKU-WASHER-8", + "qty": "100", + "warehouse": "NORTH-1", + }, + apply_write=lambda: _http_json( + f"{base_url}/orders", + "POST", + { + "order_code": "ORD-201", + "sku": "SKU-WASHER-8", + "qty": "100", + "warehouse": "NORTH-1", + }, + ), + ), + CleanWriteCase( + kind="create_order", + name="novel_union_warehouse_and_notes", + values={ + "order_code": "ORD-202", + "sku": "SKU-GASKET-2", + "qty": "40", + "warehouse": "SOUTH-3", + "notes": "rush pallet", + }, + apply_write=lambda: _http_json( + f"{base_url}/orders", + "POST", + { + "order_code": "ORD-202", + "sku": "SKU-GASKET-2", + "qty": "40", + "warehouse": "SOUTH-3", + "notes": "rush pallet", + }, + ), + ), + CleanWriteCase( + kind="create_order", + name="novel_subset_required_only", + values={ + "order_code": "ORD-203", + "sku": "SKU-PIN-1", + "qty": "12", + }, + apply_write=lambda: _http_json( + f"{base_url}/orders", + "POST", + { + "order_code": "ORD-203", + "sku": "SKU-PIN-1", + "qty": "12", + }, + ), + ), + CleanWriteCase( + kind="update_order", + name="novel_union_multi_field_update", + values={ + "id": "1", + "qty": "30", + "warehouse": "CENTRAL-9", + "notes": "reallocated", + }, + apply_write=lambda: _http_json( + f"{base_url}/orders/1", + "PATCH", + { + "qty": "30", + "warehouse": "CENTRAL-9", + "notes": "reallocated", + }, + ), + ), + ] + + result = onboard_pack(spec, tmp_path / "pack_erp", clean_cases) + assert result.certified, result.refusal_reasons + assert result.planted_faults_total >= 15 + assert result.planted_faults_caught == result.planted_faults_total + assert result.clean_writes_total == 4 + assert result.clean_writes_verified == 4 + assert result.false_stop_rate == 0.0 + assert sum(1 for c in result.clean_outcomes if c.composed) == 3 + assert result.receipts_issued == 4 + for rp in result.receipt_paths: + _assert_signed_receipt(rp) + assert (tmp_path / "pack_erp" / "QUALIFICATION.json").is_file() + finally: + server.shutdown() + server.server_close() + + +def test_onboard_unseen_itsm_ticketing_fixture(tmp_path: Path) -> None: + """Fixture B (ITSM/Ticketing): 100% planted faults caught, 0% clean false stops, + including novel unions (#2490), explicit None SQL filter binding (#2489), and signed receipts.""" + db, base_url, server = _start_itsm_fixture(tmp_path) + try: + spec = OnboardSpec( + name="itsm-ticketing", + read={"sqlite_database": str(db)}, + kinds=( + KindOnboardingSpec( + kind="create_ticket", + mode="create", + table="tickets", + required_fields=("ticket_key", "title"), + optional_fields=("assignee", "priority", "sla_comment"), + invariant_pins={"status": "open"}, + demonstrated_field_sets=( + ("ticket_key", "title", "assignee", "priority"), + ("ticket_key", "title", "assignee", "sla_comment"), + ("ticket_key", "title", "priority"), + ), + ), + KindOnboardingSpec( + kind="update_ticket", + mode="update", + table="tickets", + identity_params=("id",), + change_fields=("assignee", "priority", "sla_comment", "status"), + bookkeeping_fields=("updated_at",), + demonstrated_field_sets=( + ("id", "assignee"), + ("id", "priority"), + ("id", "sla_comment"), + ("id", "status"), + ), + ), + ), + ) + + clean_cases = [ + CleanWriteCase( + kind="create_ticket", + name="exact_with_priority", + values={ + "ticket_key": "INC-601", + "title": "SSO redirect loop", + "assignee": "carol", + "priority": "P1", + }, + apply_write=lambda: _http_json( + f"{base_url}/tickets", + "POST", + { + "ticket_key": "INC-601", + "title": "SSO redirect loop", + "assignee": "carol", + "priority": "P1", + }, + ), + ), + CleanWriteCase( + kind="create_ticket", + name="novel_union_priority_and_sla", + values={ + "ticket_key": "INC-602", + "title": "Printer offline", + "assignee": "dave", + "priority": "P3", + "sla_comment": "4h response target", + }, + apply_write=lambda: _http_json( + f"{base_url}/tickets", + "POST", + { + "ticket_key": "INC-602", + "title": "Printer offline", + "assignee": "dave", + "priority": "P3", + "sla_comment": "4h response target", + }, + ), + ), + CleanWriteCase( + kind="create_ticket", + name="unassigned_null_assignee", + values={ + "ticket_key": "INC-603", + "title": "Unassigned intake", + "assignee": None, + "priority": "P2", + }, + apply_write=lambda: _http_json( + f"{base_url}/tickets", + "POST", + { + "ticket_key": "INC-603", + "title": "Unassigned intake", + "assignee": None, + "priority": "P2", + }, + ), + ), + CleanWriteCase( + kind="update_ticket", + name="novel_union_multi_field_update", + values={ + "id": "1", + "priority": "P1", + "sla_comment": "escalated to L2", + "status": "in_progress", + }, + apply_write=lambda: _http_json( + f"{base_url}/tickets/1", + "PATCH", + { + "priority": "P1", + "sla_comment": "escalated to L2", + "status": "in_progress", + }, + ), + ), + ] + + result = onboard_pack(spec, tmp_path / "pack_itsm", clean_cases) + assert result.certified, result.refusal_reasons + assert result.planted_faults_total >= 15 + assert result.planted_faults_caught == result.planted_faults_total + assert result.clean_writes_total == 4 + assert result.clean_writes_verified == 4 + assert result.false_stop_rate == 0.0 + assert sum(1 for c in result.clean_outcomes if c.composed) == 2 + assert result.receipts_issued == 4 + for rp in result.receipt_paths: + _assert_signed_receipt(rp) + + # Also verify #2489 null-safe SQL filter binding (WHERE t.assignee = :assignee + # rewritten to IS NULL) directly against the live ITSM REST+SQLite fixture. + from openadapt_flow.verifier import ( + Actor, + Contract, + MemoryLedger, + Outcome, + begin_write, + verify_write, + ) + + null_filter_contract = Contract.from_dict( + { + "schema_version": "openadapt.verify/v1", + "verifier": { + "kind": "sql", + "sqlite_database": str(db), + "sql_query": ( + "SELECT id, ticket_key, title, assignee, priority " + "FROM tickets WHERE ticket_key = :ticket_key AND assignee = :assignee" + ), + "sql_query_params": { + "ticket_key": {"param": "ticket_key"}, + "assignee": {"param": "assignee"}, + }, + }, + "effects": [ + { + "kind": "record_written", + "match": { + "ticket_key": {"param": "ticket_key"}, + "title": {"param": "title"}, + "assignee": {"param": "assignee"}, + }, + "expected_count": 1, + "count_new_only": True, + } + ], + "frame": {"identity_field": "id"}, + } + ) + pending_null = begin_write( + null_filter_contract, + {"ticket_key": "INC-604", "title": "Null SQL filter", "assignee": None}, + actor=Actor(kind="agent", id="bot"), + ledger=MemoryLedger(), + workdir=tmp_path / "null_runs", + ) + _http_json( + f"{base_url}/tickets", + "POST", + { + "ticket_key": "INC-604", + "title": "Null SQL filter", + "assignee": None, + "priority": "P2", + }, + ) + res_null = verify_write(pending_null) + assert res_null.outcome is Outcome.CONFIRMED, res_null.reasons + finally: + server.shutdown() + server.server_close() + + +def test_onboard_refuses_certification_when_db_unreadable(tmp_path: Path) -> None: + spec = OnboardSpec( + name="missing-db", + read={"sqlite_database": str(tmp_path / "does_not_exist.sqlite")}, + kinds=( + KindOnboardingSpec( + kind="create_item", + mode="create", + table="items", + required_fields=("name",), + demonstrated_field_sets=(("name",),), + ), + ), + ) + res = onboard_pack(spec, tmp_path / "out") + assert not res.certified + assert res.refusal_reasons + + +def test_onboard_cli_end_to_end_and_dry_run( + tmp_path: Path, capsys: pytest.CaptureFixture[str] +) -> None: + db, _url, server = _start_erp_fixture(tmp_path) + try: + spec_path = tmp_path / "erp_onboard.yaml" + spec_doc = { + "name": "erp-cli-pack", + "read": {"sqlite_database": str(db)}, + "kinds": [ + { + "kind": "create_order", + "mode": "create", + "table": "orders", + "required_fields": ["order_code", "sku", "qty"], + "optional_fields": ["warehouse"], + "invariant_pins": {"status": "pending"}, + "demonstrated_field_sets": [ + ["order_code", "sku", "qty", "warehouse"] + ], + "sample_values": { + "order_code": "ORD-900", + "sku": "SKU-CLI-1", + "qty": "5", + "warehouse": "WEST-1", + }, + } + ], + } + spec_path.write_text( + yaml.safe_dump(spec_doc, sort_keys=False), encoding="utf-8" + ) + + # Dry-run synthesizes pack without certifying. + rc_dry = flow_cli.main( + [ + "onboard", + "--spec", + str(spec_path), + "--out", + str(tmp_path / "cli_dry"), + "--dry-run", + "--json", + ] + ) + assert rc_dry == 0 + dry_out = json.loads(capsys.readouterr().out) + assert dry_out["dry_run"] is True + assert dry_out["certified"] is False + + # Full CLI run via task route ``setup onboard`` certifies with 100% planted faults caught. + rc = flow_cli.main( + [ + "setup", + "onboard", + "--spec", + str(spec_path), + "--out", + str(tmp_path / "cli_full"), + "--json", + ] + ) + assert rc == 0 + full_out = json.loads(capsys.readouterr().out) + assert full_out["certified"] is True + assert full_out["planted_faults_total"] >= 10 + assert full_out["planted_faults_caught"] == full_out["planted_faults_total"] + finally: + server.shutdown() + server.server_close() From 74cb5cea573273ef399eff65e967912f74bf7d04 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 09:39:54 -0500 Subject: [PATCH 2/8] fix(flow): require verified clean writes, receipts, and all mandatory fault classes for onboard certification --- packages/flow/openadapt_flow/onboard/cli.py | 66 ++++++++++- .../flow/openadapt_flow/onboard/engine.py | 61 +++++++++- packages/flow/tests/test_onboard_loop.py | 105 +++++++++++++++++- 3 files changed, 224 insertions(+), 8 deletions(-) diff --git a/packages/flow/openadapt_flow/onboard/cli.py b/packages/flow/openadapt_flow/onboard/cli.py index 1f85295519..2ec4720828 100644 --- a/packages/flow/openadapt_flow/onboard/cli.py +++ b/packages/flow/openadapt_flow/onboard/cli.py @@ -5,11 +5,59 @@ import argparse import json import sys +import urllib.request from pathlib import Path from typing import Any +import yaml + from openadapt_flow.onboard.engine import onboard_pack, synthesize_pack -from openadapt_flow.onboard.types import OnboardSpec +from openadapt_flow.onboard.types import CleanWriteCase, OnboardSpec + + +def _load_clean_writes(path: str | Path) -> list[CleanWriteCase]: + p = Path(path) + raw = p.read_text(encoding="utf-8") + data = json.loads(raw) if p.suffix.lower() == ".json" else yaml.safe_load(raw) + if not isinstance(data, list): + raise ValueError(f"{p} must contain a list of clean write cases") + cases: list[CleanWriteCase] = [] + for idx, item in enumerate(data): + if not isinstance(item, dict): + raise ValueError(f"{p}[{idx}] must be a mapping") + kind = str(item["kind"]) + values = dict(item.get("values") or {}) + name = str(item.get("name") or f"{kind}#{idx + 1}") + http_cfg = item.get("http") + if not isinstance(http_cfg, dict) or "url" not in http_cfg: + raise ValueError(f"{p}[{idx}] requires an 'http' mapping with 'url'") + url = str(http_cfg["url"]) + method = str(http_cfg.get("method") or "POST").upper() + body = http_cfg.get("body", values) + + def _make_writer(u: str = url, m: str = method, b: Any = body) -> Any: + def _write() -> None: + encoded = json.dumps(b).encode("utf-8") + req = urllib.request.Request( + u, + data=encoded, + method=m, + headers={"Content-Type": "application/json"}, + ) + with urllib.request.urlopen(req, timeout=10) as resp: + resp.read() + + return _write + + cases.append( + CleanWriteCase( + kind=kind, + values=values, + apply_write=_make_writer(), + name=name, + ) + ) + return cases def _cmd_onboard(args: argparse.Namespace) -> int: @@ -38,7 +86,15 @@ def _cmd_onboard(args: argparse.Namespace) -> int: ) return 0 - result = onboard_pack(spec, out_dir) + clean_cases: list[CleanWriteCase] = [] + if args.clean_writes: + try: + clean_cases = _load_clean_writes(args.clean_writes) + except (OSError, ValueError, KeyError) as exc: + print(f"REFUSED: invalid clean-writes file: {exc}", file=sys.stderr) + return 2 + + result = onboard_pack(spec, out_dir, clean_cases) if args.json: print(json.dumps(result.to_dict(), indent=2)) else: @@ -47,6 +103,7 @@ def _cmd_onboard(args: argparse.Namespace) -> int: f"{status}: pack={result.pack_name!r} " f"planted_faults={result.planted_faults_caught}/{result.planted_faults_total} " f"clean_writes={result.clean_writes_verified}/{result.clean_writes_total} " + f"receipts={result.receipts_issued} " f"false_stop_rate={result.false_stop_rate:.1%} " f"digest={result.pack_digest}" ) @@ -73,6 +130,11 @@ def register(subparsers: Any) -> None: required=True, help="Output directory for synthesized pack, contracts, and QUALIFICATION.json", ) + p.add_argument( + "--clean-writes", + default=None, + help="Optional YAML/JSON list of clean write cases (with HTTP target) to verify and receipt", + ) p.add_argument( "--json", action="store_true", diff --git a/packages/flow/openadapt_flow/onboard/engine.py b/packages/flow/openadapt_flow/onboard/engine.py index 7847aa3bdf..3f9bef19d4 100644 --- a/packages/flow/openadapt_flow/onboard/engine.py +++ b/packages/flow/openadapt_flow/onboard/engine.py @@ -29,6 +29,7 @@ OnboardSpec, PlantedFaultOutcome, QualificationResult, + _validate_ident, ) from openadapt_flow.runtime.effects.sql import assert_read_only_sql from openadapt_flow.verifier import ( @@ -45,10 +46,16 @@ def _slug(fields: Sequence[str]) -> str: def _sqlite_table_columns(db: Path, table: str) -> list[str]: + _validate_ident(table, "sqlite table") con = sqlite3.connect(db) try: rows = con.execute(f"PRAGMA table_info({table})").fetchall() - return [str(r[1]) for r in rows] + cols: list[str] = [] + for r in rows: + col = str(r[1]) + _validate_ident(col, f"{table} column") + cols.append(col) + return cols finally: con.close() @@ -268,7 +275,8 @@ def _perturb(value: Any, field: str) -> Any: def _sqlite_insert(db: Path, table: str, row: Mapping[str, Any]) -> None: - cols = list(row.keys()) + _validate_ident(table, "sqlite table") + cols = [_validate_ident(str(c), f"{table} insert column") for c in row.keys()] placeholders = ", ".join("?" for _ in cols) con = sqlite3.connect(db) try: @@ -287,8 +295,11 @@ def _sqlite_update( updates: Mapping[str, Any], where: Mapping[str, Any], ) -> None: - set_clause = ", ".join(f"{c} = ?" for c in updates) - where_clause = " AND ".join(f"{c} = ?" for c in where) + _validate_ident(table, "sqlite table") + upd_cols = [_validate_ident(str(c), f"{table} update column") for c in updates] + where_cols = [_validate_ident(str(c), f"{table} where column") for c in where] + set_clause = ", ".join(f"{c} = ?" for c in upd_cols) + where_clause = " AND ".join(f"{c} = ?" for c in where_cols) con = sqlite3.connect(db) try: con.execute( @@ -682,6 +693,36 @@ def qualify_pack( + ", ".join(escaped) ) + # Require every mandatory fault class to be planted for every kind (fail closed + # on sparse/empty databases where sibling_edit or wrong_target could not run). + classes_by_kind: dict[str, set[str]] = {} + for f in fault_outcomes: + classes_by_kind.setdefault(f.kind, set()).add(f.fault_class) + for ks in spec.kinds: + required_classes = ( + { + "wrong_value", + "null_vs_value", + "missing_write", + "duplicate_row", + "sibling_edit", + } + if ks.mode == "create" + else { + "wrong_value", + "null_vs_value", + "missing_write", + "wrong_target", + "sibling_edit", + } + ) + missing_classes = sorted(required_classes - classes_by_kind.get(ks.kind, set())) + if missing_classes: + refusal_reasons.append( + f"kind {ks.kind!r} missing required planted fault class(es): " + + ", ".join(missing_classes) + ) + # Step 2: Clean-write verification (including novel composed field sets & explicit nulls). kind_specs = {ks.kind: ks for ks in spec.kinds} clean_outcomes: list[CleanWriteOutcome] = [] @@ -769,6 +810,16 @@ def qualify_pack( clean_total = len(clean_outcomes) clean_verified = sum(1 for c in clean_outcomes if c.confirmed) + if clean_total == 0: + refusal_reasons.append( + "no clean writes were verified (at least one verified clean write " + "with a signed record/run/v1 receipt is required for certification)" + ) + elif len(receipt_paths) < clean_verified: + refusal_reasons.append( + f"signed receipts issued ({len(receipt_paths)}) fewer than " + f"verified clean writes ({clean_verified})" + ) false_stop_rate = ( round((clean_total - clean_verified) / clean_total, 4) if clean_total > 0 @@ -778,7 +829,9 @@ def qualify_pack( certified = ( faults_total > 0 and faults_caught == faults_total + and clean_total > 0 and clean_verified == clean_total + and len(receipt_paths) == clean_verified and not refusal_reasons ) diff --git a/packages/flow/tests/test_onboard_loop.py b/packages/flow/tests/test_onboard_loop.py index 9fffcde070..a5cd783d84 100644 --- a/packages/flow/tests/test_onboard_loop.py +++ b/packages/flow/tests/test_onboard_loop.py @@ -585,10 +585,60 @@ def test_onboard_refuses_certification_when_db_unreadable(tmp_path: Path) -> Non assert res.refusal_reasons +def test_onboard_refuses_certification_when_required_fault_class_unplanted( + tmp_path: Path, +) -> None: + """Blocker 2: an empty table cannot plant sibling_edit, so certification MUST refuse.""" + db = tmp_path / "empty.sqlite" + con = sqlite3.connect(db) + con.execute( + "CREATE TABLE items (id INTEGER PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL)" + ) + con.commit() + con.close() + + spec = OnboardSpec( + name="empty-table-pack", + read={"sqlite_database": str(db)}, + kinds=( + KindOnboardingSpec( + kind="create_item", + mode="create", + table="items", + required_fields=("name",), + demonstrated_field_sets=(("name",),), + ), + ), + ) + + def _insert_clean() -> None: + c = sqlite3.connect(db) + c.execute("INSERT INTO items (name) VALUES (?)", ("Widget",)) + c.commit() + c.close() + + res = onboard_pack( + spec, + tmp_path / "out_empty", + [ + CleanWriteCase( + kind="create_item", + values={"name": "Widget"}, + apply_write=_insert_clean, + ) + ], + ) + assert not res.certified + assert any( + "missing required planted fault class" in r and "sibling_edit" in r + for r in res.refusal_reasons + ), res.refusal_reasons + + def test_onboard_cli_end_to_end_and_dry_run( tmp_path: Path, capsys: pytest.CaptureFixture[str] ) -> None: - db, _url, server = _start_erp_fixture(tmp_path) + db, base_url, server = _start_erp_fixture(tmp_path) try: spec_path = tmp_path / "erp_onboard.yaml" spec_doc = { @@ -635,13 +685,60 @@ def test_onboard_cli_end_to_end_and_dry_run( assert dry_out["dry_run"] is True assert dry_out["certified"] is False - # Full CLI run via task route ``setup onboard`` certifies with 100% planted faults caught. + # Blocker 1: CLI without clean writes refuses vacuous certification (exit 2). + rc_no_clean = flow_cli.main( + [ + "onboard", + "--spec", + str(spec_path), + "--out", + str(tmp_path / "cli_no_clean"), + "--json", + ] + ) + assert rc_no_clean == 2 + no_clean_out = json.loads(capsys.readouterr().out) + assert no_clean_out["certified"] is False + assert no_clean_out["clean_writes_total"] == 0 + assert any("no clean writes" in r for r in no_clean_out["refusal_reasons"]) + + # Full CLI run via task route ``setup onboard`` WITH --clean-writes certifies + # and issues a signed record/run/v1 receipt. + clean_path = tmp_path / "erp_clean_writes.yaml" + clean_doc = [ + { + "kind": "create_order", + "name": "cli_live_order", + "values": { + "order_code": "ORD-901", + "sku": "SKU-CLI-2", + "qty": "7", + "warehouse": "WEST-1", + }, + "http": { + "url": f"{base_url}/orders", + "method": "POST", + "body": { + "order_code": "ORD-901", + "sku": "SKU-CLI-2", + "qty": "7", + "warehouse": "WEST-1", + }, + }, + } + ] + clean_path.write_text( + yaml.safe_dump(clean_doc, sort_keys=False), encoding="utf-8" + ) + rc = flow_cli.main( [ "setup", "onboard", "--spec", str(spec_path), + "--clean-writes", + str(clean_path), "--out", str(tmp_path / "cli_full"), "--json", @@ -652,6 +749,10 @@ def test_onboard_cli_end_to_end_and_dry_run( assert full_out["certified"] is True assert full_out["planted_faults_total"] >= 10 assert full_out["planted_faults_caught"] == full_out["planted_faults_total"] + assert full_out["clean_writes_total"] == 1 + assert full_out["clean_writes_verified"] == 1 + assert full_out["receipts_issued"] == 1 + _assert_signed_receipt(full_out["receipt_paths"][0]) finally: server.shutdown() server.server_close() From f926cc13b72c7380c65f5c91a0b5f916d404f768 Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 10:52:03 -0500 Subject: [PATCH 3/8] fix(flow): lazy-load onboard engine for Windows parser safety and register onboard capability doc --- CAPABILITIES.md | 1 + .../commands/02-check-and-admit/onboard.md | 1 + .../flow/openadapt_flow/onboard/__init__.py | 23 ++++++++++++++++++- packages/flow/openadapt_flow/onboard/cli.py | 3 ++- 4 files changed, 26 insertions(+), 2 deletions(-) create mode 100644 packages/flow/docs/commands/02-check-and-admit/onboard.md diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 03d4905a48..3e36f489c3 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -423,6 +423,7 @@ A test fails when a command has no file or this list is out of date. - `jit` - `known-ids` - `lint` +- `onboard`: Synthesize and planted-fault-qualify a verification pack for any system of record. - `propose-qualification` - `qualify` - `scaffold-verifier` diff --git a/packages/flow/docs/commands/02-check-and-admit/onboard.md b/packages/flow/docs/commands/02-check-and-admit/onboard.md new file mode 100644 index 0000000000..16ae764935 --- /dev/null +++ b/packages/flow/docs/commands/02-check-and-admit/onboard.md @@ -0,0 +1 @@ +Synthesize and planted-fault-qualify a verification pack for any system of record. diff --git a/packages/flow/openadapt_flow/onboard/__init__.py b/packages/flow/openadapt_flow/onboard/__init__.py index 4db662f862..efb188c047 100644 --- a/packages/flow/openadapt_flow/onboard/__init__.py +++ b/packages/flow/openadapt_flow/onboard/__init__.py @@ -1,6 +1,9 @@ """Domain-agnostic pack onboarding and planted-fault qualification loop.""" -from openadapt_flow.onboard.engine import onboard_pack, qualify_pack, synthesize_pack +from __future__ import annotations + +from typing import TYPE_CHECKING, Any + from openadapt_flow.onboard.types import ( CleanWriteCase, CleanWriteOutcome, @@ -10,6 +13,24 @@ QualificationResult, ) +if TYPE_CHECKING: + from openadapt_flow.onboard.engine import ( + onboard_pack, + qualify_pack, + synthesize_pack, + ) + +_ENGINE_EXPORTS = frozenset({"onboard_pack", "qualify_pack", "synthesize_pack"}) + + +def __getattr__(name: str) -> Any: + if name in _ENGINE_EXPORTS: + from openadapt_flow.onboard import engine + + return getattr(engine, name) + raise AttributeError(f"module {__name__!r} has no attribute {name!r}") + + __all__ = [ "CleanWriteCase", "CleanWriteOutcome", diff --git a/packages/flow/openadapt_flow/onboard/cli.py b/packages/flow/openadapt_flow/onboard/cli.py index 2ec4720828..5149b79538 100644 --- a/packages/flow/openadapt_flow/onboard/cli.py +++ b/packages/flow/openadapt_flow/onboard/cli.py @@ -11,7 +11,6 @@ import yaml -from openadapt_flow.onboard.engine import onboard_pack, synthesize_pack from openadapt_flow.onboard.types import CleanWriteCase, OnboardSpec @@ -61,6 +60,8 @@ def _write() -> None: def _cmd_onboard(args: argparse.Namespace) -> int: + from openadapt_flow.onboard.engine import onboard_pack, synthesize_pack + try: spec = OnboardSpec.load(args.spec) except (OSError, ValueError, KeyError) as exc: From 6698aed4c516b339afeda821d68ee5fa6940b18c Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 11:07:59 -0500 Subject: [PATCH 4/8] fix(flow): keep __main__.py under file-size ratchet and refresh llms-full.txt --- llms-full.txt | 1 + packages/flow/openadapt_flow/__main__.py | 19 +++++-------------- 2 files changed, 6 insertions(+), 14 deletions(-) diff --git a/llms-full.txt b/llms-full.txt index ae1ca3e8ca..3501d48a4d 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -884,6 +884,7 @@ A test fails when a command has no file or this list is out of date. - `jit` - `known-ids` - `lint` +- `onboard`: Synthesize and planted-fault-qualify a verification pack for any system of record. - `propose-qualification` - `qualify` - `scaffold-verifier` diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index f868bbe88d..6e276fdb2e 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13181,28 +13181,19 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: ) from openadapt_flow.agent_guard.cli import add_parser as _add_guard_parser - from openadapt_flow.cli_cleanup import register as _register_cleanup from openadapt_flow.cli_fleet import register_fleet_parser - from openadapt_flow.cli_receipt import register as _register_receipt - from openadapt_flow.cli_reconcile import register as _register_reconcile - from openadapt_flow.cli_rollback import register as _register_rollback - from openadapt_flow.cli_shadow import register as _register_shadow from openadapt_flow.compile_agent.cli import add_parser as _add_compile_agent_parser from openadapt_flow.flight.cli import add_parser as _add_flight_parser from openadapt_flow.hooks.cli import add_parser as _add_hooks_parser from openadapt_flow.jit.cli import add_parser as _add_jit_parser - from openadapt_flow.learn import register as _register_learn from openadapt_flow.txplan.cli import add_parser as _add_plan_parser from openadapt_flow.txplan.proxy_cli import add_parser as _add_proxy_parser - _register_rollback(sub) - _register_shadow(sub) - __import__("openadapt_flow.readiness.cli", fromlist=["cli"]).register(sub) - __import__("openadapt_flow.onboard.cli", fromlist=["cli"]).register(sub) - _register_receipt(sub) - _register_learn(sub) - _register_reconcile(sub) - _register_cleanup(sub) + for _name in ( + "cli_rollback", "cli_shadow", "readiness.cli", "onboard.cli", + "cli_receipt", "learn", "cli_reconcile", "cli_cleanup", + ): + __import__(f"openadapt_flow.{_name}", fromlist=["register"]).register(sub) _add_jit_parser(sub) _add_compile_agent_parser(sub) _add_guard_parser(sub) From d40f5747676eea42a1267e6397f6c317a02a066a Mon Sep 17 00:00:00 2001 From: abrichr Date: Sun, 22 Nov 2026 12:32:59 -0500 Subject: [PATCH 5/8] style(flow): run ruff format on __main__.py --- packages/flow/openadapt_flow/__main__.py | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/packages/flow/openadapt_flow/__main__.py b/packages/flow/openadapt_flow/__main__.py index 6e276fdb2e..a9b4065ee4 100644 --- a/packages/flow/openadapt_flow/__main__.py +++ b/packages/flow/openadapt_flow/__main__.py @@ -13190,8 +13190,14 @@ def _repair_store_flag(rp: argparse.ArgumentParser) -> None: from openadapt_flow.txplan.proxy_cli import add_parser as _add_proxy_parser for _name in ( - "cli_rollback", "cli_shadow", "readiness.cli", "onboard.cli", - "cli_receipt", "learn", "cli_reconcile", "cli_cleanup", + "cli_rollback", + "cli_shadow", + "readiness.cli", + "onboard.cli", + "cli_receipt", + "learn", + "cli_reconcile", + "cli_cleanup", ): __import__(f"openadapt_flow.{_name}", fromlist=["register"]).register(sub) _add_jit_parser(sub) From f0b43ebdf9d19d30722e90af1e352469e85c9aff Mon Sep 17 00:00:00 2001 From: abrichr Date: Mon, 23 Nov 2026 19:56:48 -0500 Subject: [PATCH 6/8] test(cli): regenerate cli_surface snapshots after merging main --- packages/flow/tests/fixtures/cli_surface.json | 95 ++++++++++++++++++- tests/fixtures/cli_surface.json | 6 +- 2 files changed, 97 insertions(+), 4 deletions(-) diff --git a/packages/flow/tests/fixtures/cli_surface.json b/packages/flow/tests/fixtures/cli_surface.json index e47752224c..39a2f83177 100644 --- a/packages/flow/tests/fixtures/cli_surface.json +++ b/packages/flow/tests/fixtures/cli_surface.json @@ -1,7 +1,7 @@ { "columns": 100, "help": { - "openadapt-flow": "usage: openadapt-flow [-h] [--version] {command} ...\n\nRecord a task and compile it into a program that runs on this computer. With a record check\nconfigured, a governed run confirms each save by reading the record back, and a run that can't\nconfirm a save stops and asks a person. When the screen changes, it finds the same field again or\nstops, and a lasting fix needs a person's approval.\n\noptions:\n -h, --help show this help message and exit\n --version Show the version and exit\n\ncommands:\n {command}\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n\nNew here? Run 'openadapt-flow demo' to see a checked run and a stopped run side by side on one\npage.\n\nLegacy commands (original spellings):\n admit\n api\n approve\n approve-sanitized\n approver-grant\n at-rest\n attach-seal\n bench\n benchmark\n bind-record-checks\n browser-accessibility\n business-decisions\n certify\n check\n cleanup\n compile\n compile-agent\n compose\n confirm-surfaces\n connect\n connector\n console\n countersign\n deferred\n demo\n demo-record\n disambiguate\n emit-mcp\n emit-skill\n encrypt\n exceptions\n explain\n fleet\n flight\n for-each\n guard\n handoff\n hooks\n induce\n intake\n item-approval\n jit\n known-ids\n learn\n ledger\n lint\n local-seal\n login\n materialize-approved\n narration\n no-outbound\n plan\n process\n propose-qualification\n proxy\n pull\n push\n qualify\n readiness\n receipt\n reconcile\n record\n redact-report\n repair\n replay\n report-break\n report-run\n resume\n review-sanitized\n rollback\n route\n run\n sanitize\n scaffold-verifier\n sections\n serve-execute\n serve-reward\n service\n shadow\n silent-saves\n skill\n teach\n teach-authorization\n teach-branch\n triage\n tutorial\n undo\n validate-hosted\n variants\n verify-run\n visualize\n wrap-dispatch\n", + "openadapt-flow": "usage: openadapt-flow [-h] [--version] {command} ...\n\nRecord a task and compile it into a program that runs on this computer. With a record check\nconfigured, a governed run confirms each save by reading the record back, and a run that can't\nconfirm a save stops and asks a person. When the screen changes, it finds the same field again or\nstops, and a lasting fix needs a person's approval.\n\noptions:\n -h, --help show this help message and exit\n --version Show the version and exit\n\ncommands:\n {command}\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n\nNew here? Run 'openadapt-flow demo' to see a checked run and a stopped run side by side on one\npage.\n\nLegacy commands (original spellings):\n admit\n api\n approve\n approve-sanitized\n approver-grant\n at-rest\n attach-seal\n bench\n benchmark\n bind-record-checks\n browser-accessibility\n business-decisions\n certify\n check\n cleanup\n compile\n compile-agent\n compose\n confirm-surfaces\n connect\n connector\n console\n countersign\n deferred\n demo\n demo-record\n disambiguate\n emit-mcp\n emit-skill\n encrypt\n exceptions\n explain\n fleet\n flight\n for-each\n guard\n handoff\n hooks\n induce\n intake\n item-approval\n jit\n known-ids\n learn\n ledger\n lint\n local-seal\n login\n materialize-approved\n narration\n no-outbound\n onboard\n plan\n process\n propose-qualification\n proxy\n pull\n push\n qualify\n readiness\n receipt\n reconcile\n record\n redact-report\n repair\n replay\n report-break\n report-run\n resume\n review-sanitized\n rollback\n route\n run\n sanitize\n scaffold-verifier\n sections\n serve-execute\n serve-reward\n service\n shadow\n silent-saves\n skill\n teach\n teach-authorization\n teach-branch\n triage\n tutorial\n undo\n validate-hosted\n variants\n verify-run\n visualize\n wrap-dispatch\n", "openadapt-flow admit": "usage: openadapt-flow admit [-h] {run,decide,status} ...\n\npositional arguments:\n {run,decide,status}\n run Compile, induce, propose checks, and stop once for a person's decision (the\n default form: `admit `)\n decide Show a stopped admission's summary and decide it (a person, at a terminal)\n status Print admitted vs not-admitted for Flow from the public ledger. Never mints\n a signature.\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow run --task-admit\n", "openadapt-flow admit decide": "usage: openadapt-flow admit decide [-h] [--by BY] admission\n\npositional arguments:\n admission Admission directory from `admit`\n\noptions:\n -h, --help show this help message and exit\n --by BY Your name for the record\n\nAlso available as: openadapt-flow run --task-admit decide\n", "openadapt-flow admit run": "usage: openadapt-flow admit run [-h] [--candidate ID] [--candidates-root CANDIDATES_ROOT] --out\n OUT --name NAME [--policy-pack {community,cloud,regulated}]\n [--by BY]\n [recordings ...]\n\npositional arguments:\n recordings Recording directories (or compiled bundles) of the same task\n\noptions:\n -h, --help show this help message and exit\n --candidate ID A shadow candidate id under --candidates-root, or its folder. Its\n recordings/ folder is used when no recordings are given\n --candidates-root CANDIDATES_ROOT\n Where shadow candidates are kept (default: ./shadow-candidates)\n --out OUT New admission directory\n --name NAME Workflow name\n --policy-pack {community,cloud,regulated}\n --by BY Your name for the record (default: your login name)\n\nAlso available as: openadapt-flow run --task-admit run\n", @@ -164,6 +164,7 @@ "openadapt-flow no-outbound allow derive": "usage: openadapt-flow no-outbound allow derive [-h] profile\n\npositional arguments:\n profile FreeRDP session JSON or .rdp file\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup no-outbound allow derive\n", "openadapt-flow no-outbound allow list": "usage: openadapt-flow no-outbound allow list [-h] [--json]\n\noptions:\n -h, --help show this help message and exit\n --json\n\nAlso available as: openadapt-flow setup no-outbound allow list\n", "openadapt-flow no-outbound allow remove": "usage: openadapt-flow no-outbound allow remove [-h] network\n\npositional arguments:\n network\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow setup no-outbound allow remove\n", + "openadapt-flow onboard": "usage: openadapt-flow onboard [-h] --spec SPEC --out OUT [--clean-writes CLEAN_WRITES] [--json]\n [--dry-run]\n\noptions:\n -h, --help show this help message and exit\n --spec SPEC Path to declarative onboard spec (YAML or JSON)\n --out OUT Output directory for synthesized pack, contracts, and QUALIFICATION.json\n --clean-writes CLEAN_WRITES\n Optional YAML/JSON list of clean write cases (with HTTP target) to verify\n and receipt\n --json Emit structured QualificationResult JSON to stdout\n --dry-run Synthesize the pack without running qualification (pack is not certified)\n\nAlso available as: openadapt-flow setup onboard\n", "openadapt-flow plan": "usage: openadapt-flow plan [-h] {create,show,apply,undo,release,cancel,approve,status} ...\n\n``openadapt plan``: dry-run, apply and undo a batch of writes to external systems.\n\n openadapt plan create --tx openadapt.tx.yaml --task T-1 writes.json\n openadapt plan show PLAN\n openadapt plan approve PLAN # a person, at a terminal\n openadapt plan apply PLAN\n openadapt plan undo PLAN\n openadapt plan release PLAN # irreversible writes after holdback\n openadapt plan cancel PLAN # drop held writes before release\n openadapt plan status\n\n``create`` reads every record the batch touches, predicts the diff (a staged\ntransaction for a database, a computed shadow for a REST API, the holdback\nqueue for email) and prints what would change. ``approve`` binds to that exact\nplan digest, once. ``apply`` refuses a plan whose records moved since, and\neach write carries an idempotency key derived from the task and the record,\nnever from the payload: a retried or regenerated write with a different\npayload is refused. ``undo`` compensates each write and proves it by reading\nevery record and the whole frame back. See ``docs/TRANSACTIONS.md``.\n\npositional arguments:\n {create,show,apply,undo,release,cancel,approve,status}\n create read the baseline and print the predicted diff\n show print a plan\n apply apply an approved plan\n undo undo an applied plan and prove it by read-back\n release release held irreversible writes whose holdback passed\n cancel cancel held writes before release\n approve approve one plan digest, once (a person at a terminal)\n status list held writes and ledger entries\n\noptions:\n -h, --help show this help message and exit\n\nAlso available as: openadapt-flow run --plan\n", "openadapt-flow plan apply": "usage: openadapt-flow plan apply [-h] [--tx TX] [--state STATE] [--json] plan\n\npositional arguments:\n plan a plan digest or its prefix\n\noptions:\n -h, --help show this help message and exit\n --tx TX the tx file (default: ./openadapt.tx.yaml)\n --state STATE the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)\n --json print JSON\n\nAlso available as: openadapt-flow run --plan apply\n", "openadapt-flow plan approve": "usage: openadapt-flow plan approve [-h] [--as APPROVER] [--automation] [--state STATE] [--json]\n plan\n\npositional arguments:\n plan\n\noptions:\n -h, --help show this help message and exit\n --as APPROVER who approves (default: $USER)\n --automation record the approval as automation (lab runs; the receipt then says agent)\n --state STATE the state folder (default: $OPENADAPT_TX_STATE or ~/.openadapt/tx)\n --json print JSON\n\nAlso available as: openadapt-flow run --plan approve\n", @@ -383,6 +384,7 @@ "materialize-approved": [], "narration": [], "no-outbound": [], + "onboard": [], "plan": [], "process": [], "propose-qualification": [], @@ -13874,6 +13876,97 @@ "commands": {}, "exclusive": [] }, + "openadapt-flow onboard": { + "arguments": [ + { + "action": "_HelpAction", + "choices": null, + "default": "==SUPPRESS==", + "dest": "help", + "help": "show this help message and exit", + "metavar": null, + "nargs": 0, + "options": [ + "-h", + "--help" + ], + "required": false, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "spec", + "help": "Path to declarative onboard spec (YAML or JSON)", + "metavar": null, + "nargs": null, + "options": [ + "--spec" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "out", + "help": "Output directory for synthesized pack, contracts, and QUALIFICATION.json", + "metavar": null, + "nargs": null, + "options": [ + "--out" + ], + "required": true, + "type": null + }, + { + "action": "_StoreAction", + "choices": null, + "default": null, + "dest": "clean_writes", + "help": "Optional YAML/JSON list of clean write cases (with HTTP target) to verify and receipt", + "metavar": null, + "nargs": null, + "options": [ + "--clean-writes" + ], + "required": false, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "json", + "help": "Emit structured QualificationResult JSON to stdout", + "metavar": null, + "nargs": 0, + "options": [ + "--json" + ], + "required": false, + "type": null + }, + { + "action": "_StoreTrueAction", + "choices": null, + "default": false, + "dest": "dry_run", + "help": "Synthesize the pack without running qualification (pack is not certified)", + "metavar": null, + "nargs": 0, + "options": [ + "--dry-run" + ], + "required": false, + "type": null + } + ], + "commands": {}, + "exclusive": [] + }, "openadapt-flow plan": { "arguments": [ { diff --git a/tests/fixtures/cli_surface.json b/tests/fixtures/cli_surface.json index 35ac156fe8..830e451201 100644 --- a/tests/fixtures/cli_surface.json +++ b/tests/fixtures/cli_surface.json @@ -1,7 +1,7 @@ { - "click": "8.5.0", + "click": "8.5.1", "help": { - "openadapt": "Usage: openadapt [OPTIONS] COMMAND [ARGS]...\n\n Record, compile and run workflows with OpenAdapt.\n\n Compile a demonstrated workflow into deterministic local replay. Healthy runs make no model calls;\n configured checks can halt on ambiguity. Native and remote substrates use platform-specific extras\n and permissions; training/evaluation commands are research.\n\n Quick Start (uv fetches Python 3.12 if needed):\n uvx --python 3.12 openadapt@latest quickstart\n Or, on Python 3.10-3.12:\n python -m pip install --upgrade openadapt\n openadapt quickstart\n\n Manual Demo Lifecycle:\n openadapt flow demo-record --out rec\n openadapt compile rec --out bundle --name demo\n openadapt flow lint bundle\n openadapt flow certify bundle --policy permissive\n openadapt flow replay bundle --demo-app\n\n Lint lists the demo's coverage gaps. The demo has warnings, so `lint --strict` exits 1 on it. The\n manual demo is runnable but not certified for consequential work. Use `openadapt flow tutorial`\n for the effect-verified first run.\n\n Give an MCP client your compiled workflows:\n openadapt agent serve --bundles DIR --mode production\n\nOptions:\n --version Show the version and exit.\n --help Show this message and exit.\n\nCommands:\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n wrap Run an agent task once, then reuse its checked compiled tool\n\nLegacy commands:\n agent Serve compiled workflows to an MCP client...\n bench Public benchmarks you can rerun with your...\n capture Standalone local human GUI capture...\n connect Connect this computer to the signed-in...\n deploy Check this host and print the safe...\n doctor Check system requirements and dependencies.\n eval Research: evaluate computer-use models on...\n flight Record any agent you already run, and hold...\n flow Run the canonical demonstration compiler...\n handoff Hand a result to another agent with its...\n hooks Check a coding agent's writes to declared...\n login Sign in to OpenAdapt Cloud: `openadapt...\n plan Dry-run a batch of writes to external...\n proxy Hold the database credentials; give the...\n pull Download a packaged workflow: `openadapt...\n quickstart Show a task once, run it, then watch it...\n receipt Check, view and share a run's receipt:...\n serve Research: serve the training dashboard and...\n shadow Check each write your agent makes against...\n train Research: train ML models on captured...\n version Show version information for all packages.", + "openadapt": "OpenAdapt needs Python 3.10\u20133.12. This is Python 3.14, which the OpenAdapt engine doesn't support yet, so only the launcher is installed.\nRun it with uv, which downloads Python 3.12 if you don't have it:\n uvx --python 3.12 openadapt@latest quickstart\nNo uv yet? Install it first:\n curl -LsSf https://astral.sh/uv/install.sh | sh\nTo keep OpenAdapt installed: uv tool install --python 3.12 openadapt\nOr use the installer script: https://raw.githubusercontent.com/OpenAdaptAI/OpenAdapt/main/packages/flow/scripts/install.sh\n\nUsage: openadapt [OPTIONS] COMMAND [ARGS]...\n\n Record, compile and run workflows with OpenAdapt.\n\n Compile a demonstrated workflow into deterministic local replay. Healthy runs make no model calls;\n configured checks can halt on ambiguity. Native and remote substrates use platform-specific extras\n and permissions; training/evaluation commands are research.\n\n Quick Start (uv fetches Python 3.12 if needed):\n uvx --python 3.12 openadapt@latest quickstart\n Or, on Python 3.10-3.12:\n python -m pip install --upgrade openadapt\n openadapt quickstart\n\n Manual Demo Lifecycle:\n openadapt flow demo-record --out rec\n openadapt compile rec --out bundle --name demo\n openadapt flow lint bundle\n openadapt flow certify bundle --policy permissive\n openadapt flow replay bundle --demo-app\n\n Lint lists the demo's coverage gaps. The demo has warnings, so `lint --strict` exits 1 on it. The\n manual demo is runnable but not certified for consequential work. Use `openadapt flow tutorial`\n for the effect-verified first run.\n\n Give an MCP client your compiled workflows:\n openadapt agent serve --bundles DIR --mode production\n\nOptions:\n --version Show the version and exit.\n --help Show this message and exit.\n\nCommands:\n demo Try the demonstration and tutorial\n verify Check effects, receipts, and evidence\n record Record a task and its narration\n teach Teach a correction to a stopped workflow\n compile Compile and prepare workflow bundles\n run Run, resume, and route workflows\n approve Review and approve paused work\n undo Declare and run approved undo steps\n qualify Qualify a workflow for its intended use\n repair Review, test, and promote repairs\n inspect Inspect workflows, runs, and reports\n workflow Manage reusable workflow libraries\n services Run local services and connectors\n setup Configure connections, privacy, and access\n research Run benchmarks and research tools\n wrap Run an agent task once, then reuse its checked compiled tool\n\nLegacy commands:\n agent Serve compiled workflows to an MCP client...\n bench Public benchmarks you can rerun with your...\n capture Standalone local human GUI capture...\n connect Connect this computer to the signed-in...\n deploy Check this host and print the safe...\n doctor Check system requirements and dependencies.\n eval Research: evaluate computer-use models on...\n flight Record any agent you already run, and hold...\n flow Run the canonical demonstration compiler...\n handoff Hand a result to another agent with its...\n hooks Check a coding agent's writes to declared...\n login Sign in to OpenAdapt Cloud: `openadapt...\n plan Dry-run a batch of writes to external...\n proxy Hold the database credentials; give the...\n pull Download a packaged workflow: `openadapt...\n quickstart Show a task once, run it, then watch it...\n receipt Check, view and share a run's receipt:...\n serve Research: serve the training dashboard and...\n shadow Check each write your agent makes against...\n train Research: train ML models on captured...\n version Show version information for all packages.", "openadapt approve": "Usage: openadapt approve [OPTIONS]\n\n Run the canonical demonstration compiler and governed runtime.\n\n Every argument passes to openadapt-flow unchanged. This keeps the launcher command list, help,\n options, validation, and exit codes identical to the installed engine version.\n\nOptions:\n --help Show this message and exit.", "openadapt compile": "Usage: openadapt compile [OPTIONS]\n\n Compile a recording. Uses the same options as flow compile.\n\nOptions:\n --help Show this message and exit.", "openadapt demo": "Usage: openadapt demo [OPTIONS]\n\n Run the canonical demonstration compiler and governed runtime.\n\n Every argument passes to openadapt-flow unchanged. This keeps the launcher command list, help,\n options, validation, and exit codes identical to the installed engine version.\n\nOptions:\n --help Show this message and exit.", @@ -24,7 +24,7 @@ "openadapt workflow": "Usage: openadapt workflow [OPTIONS]\n\n Run the canonical demonstration compiler and governed runtime.\n\n Every argument passes to openadapt-flow unchanged. This keeps the launcher command list, help,\n options, validation, and exit codes identical to the installed engine version.\n\nOptions:\n --help Show this message and exit.", "openadapt wrap": "Usage: openadapt wrap [OPTIONS]\n\n Run an agent task once, then reuse its checked compiled tool.\n\nOptions:\n --help Show this message and exit." }, - "python": "3.12", + "python": "3.14", "tree": { "openadapt": { "commands": { From 8c9ee742d7140478addafeaa5e40814b173d97bd Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 04:55:15 -0500 Subject: [PATCH 7/8] refactor(onboard): derive receipt outcome words and record Errored for verdict fold compliance --- .../flow/openadapt_flow/onboard/engine.py | 22 ++++++++++++++----- 1 file changed, 16 insertions(+), 6 deletions(-) diff --git a/packages/flow/openadapt_flow/onboard/engine.py b/packages/flow/openadapt_flow/onboard/engine.py index 3f9bef19d4..01b6c64b20 100644 --- a/packages/flow/openadapt_flow/onboard/engine.py +++ b/packages/flow/openadapt_flow/onboard/engine.py @@ -585,19 +585,24 @@ def _issue_signed_run_receipt( from datetime import datetime, timezone + from openadapt_types.receipt import OUTCOME_FROM_RUN + from openadapt_flow.offline_seal import seal_home, signer_for from openadapt_flow.receipt_record import write_receipt_record run_dir.mkdir(parents=True, exist_ok=True) now = datetime.now(timezone.utc).isoformat() verified = write_result.outcome is Outcome.CONFIRMED + verified_outcome = next(iter(OUTCOME_FROM_RUN)) + run_outcome = verified_outcome if verified else "STOPPED" + line_verdict = write_result.outcome.value.lower() if verified else "refuted" contract_hashes = [eff.contract_hash() for eff in (contract.config.effects or ())] evidence = [ { "effect_contract_hash": ch, "substrate": "sql", - "initial_verdict": "confirmed" if verified else "refuted", - "final_verdict": "confirmed" if verified else "refuted", + "initial_verdict": line_verdict, + "final_verdict": line_verdict, "observed_effect": "present" if verified else "absent", "verification_tier": 1, } @@ -609,8 +614,8 @@ def _issue_signed_run_receipt( "run_id": write_result.write_id or case_name, "started_at": now, "finished_at": now, - "execution_outcome": "VERIFIED" if verified else "STOPPED", - "outcome": "VERIFIED" if verified else "STOPPED", + "execution_outcome": run_outcome, + "outcome": run_outcome, "model_calls": 0, "verifier_outcome": write_result.outcome.value, "effect_receipt_sha256": write_result.receipt_sha256, @@ -794,6 +799,9 @@ def qualify_pack( + "; ".join(res.reasons[:2]) ) except Exception as exc: # noqa: BLE001 - fail closed on any runtime error + from openadapt_flow.verdict import Errored + + not_checked = Errored(type(exc).__name__, str(exc)) clean_outcomes.append( CleanWriteOutcome( kind=case.kind, @@ -803,10 +811,12 @@ def qualify_pack( outcome="ERROR", confirmed=False, receipt_path=None, - reasons=(str(exc),), + reasons=(not_checked.reason,), ) ) - refusal_reasons.append(f"clean write {case_name!r} raised: {exc}") + refusal_reasons.append( + f"clean write {case_name!r} raised: {not_checked.reason}" + ) clean_total = len(clean_outcomes) clean_verified = sum(1 for c in clean_outcomes if c.confirmed) From 3fc85722a4e86ebc65afdaa44b8797e5adfe6c7c Mon Sep 17 00:00:00 2001 From: abrichr Date: Tue, 24 Nov 2026 23:40:03 -0500 Subject: [PATCH 8/8] fix(onboard): restore generated docs and address P1-1..P1-4 and P2-5 qualification gates --- CAPABILITIES.md | 1 - llms-full.txt | 1 - .../flow/openadapt_flow/onboard/engine.py | 79 ++++++++++--- packages/flow/tests/test_onboard_loop.py | 110 ++++++++++++++++++ 4 files changed, 170 insertions(+), 21 deletions(-) diff --git a/CAPABILITIES.md b/CAPABILITIES.md index 341a920bcb..f9ab965c75 100644 --- a/CAPABILITIES.md +++ b/CAPABILITIES.md @@ -455,7 +455,6 @@ A test fails when a command has no file or this list is out of date. - `jit` - `known-ids` - `lint` -- `onboard`: Synthesize and planted-fault-qualify a verification pack for any system of record. - `propose-qualification` - `qualify` - `scaffold-verifier` diff --git a/llms-full.txt b/llms-full.txt index d6057aba6f..2f5a338a75 100644 --- a/llms-full.txt +++ b/llms-full.txt @@ -939,7 +939,6 @@ A test fails when a command has no file or this list is out of date. - `jit` - `known-ids` - `lint` -- `onboard`: Synthesize and planted-fault-qualify a verification pack for any system of record. - `propose-qualification` - `qualify` - `scaffold-verifier` diff --git a/packages/flow/openadapt_flow/onboard/engine.py b/packages/flow/openadapt_flow/onboard/engine.py index 01b6c64b20..47ae4dc4c2 100644 --- a/packages/flow/openadapt_flow/onboard/engine.py +++ b/packages/flow/openadapt_flow/onboard/engine.py @@ -251,7 +251,7 @@ def synthesize_pack( manifest_doc = { "schema_version": gen.MANIFEST_SCHEMA, "pack_name": spec.name, - "zero_touch": {"admitted": sorted(ks.kind for ks in spec.kinds)}, + "zero_touch": {"admitted": []}, "kinds": kinds_manifest, } manifest_path = root / "manifest.yaml" @@ -331,8 +331,35 @@ def _sqlite_table_rows(db: Path, table: str) -> list[dict[str, Any]]: con.close() +def _stage_sandbox_pack(pack_dir: Path, dst_dir: Path, sb_db: Path) -> Path: + """Copy the pack under qualification into ``dst_dir`` and point SQL reads at ``sb_db``.""" + + dst_dir.mkdir(parents=True, exist_ok=True) + src_manifest = pack_dir / "manifest.yaml" + dst_manifest = dst_dir / "manifest.yaml" + shutil.copy2(src_manifest, dst_manifest) + src_contracts = pack_dir / "contracts" + if src_contracts.is_dir(): + dst_contracts = dst_dir / "contracts" + shutil.copytree(src_contracts, dst_contracts, dirs_exist_ok=True) + for contract_file in sorted(dst_contracts.rglob("*.yaml")): + doc = yaml.safe_load(contract_file.read_text(encoding="utf-8")) + if isinstance(doc, dict): + surfaces = (doc.get("verifier") or {}).get("surfaces") + if isinstance(surfaces, dict): + for surface in surfaces.values(): + if isinstance(surface, dict) and "sqlite_database" in surface: + surface["sqlite_database"] = str(sb_db) + contract_file.write_text( + yaml.safe_dump(doc, sort_keys=False, allow_unicode=True), + encoding="utf-8", + ) + return dst_manifest + + def _run_planted_faults_sqlite( spec: OnboardSpec, + pack_dir: Path, source_db: Path, clean_cases: Sequence[CleanWriteCase], *, @@ -367,11 +394,7 @@ def _exec_fault( td_path = Path(td) sb_db = td_path / "sandbox.sqlite" shutil.copy2(source_db, sb_db) - sb_manifest, _ = synthesize_pack( - spec, - td_path / "pack", - read_override={**dict(spec.read), "sqlite_database": str(sb_db)}, - ) + sb_manifest = _stage_sandbox_pack(pack_dir, td_path / "pack", sb_db) contract, params = gen.choose(sb_manifest, ks.kind, rep_values) pending = begin_write( contract, @@ -382,7 +405,11 @@ def _exec_fault( ) mutate(sb_db) res = verify_write(pending) - caught = res.outcome is not Outcome.CONFIRMED + caught = res.outcome is Outcome.REFUTED or ( + fault_class == "missing_write" + and res.outcome is Outcome.UNCERTAIN + and res.observed == "absent" + ) return PlantedFaultOutcome( kind=ks.kind, fault_class=fault_class, @@ -631,8 +658,8 @@ def _issue_signed_run_receipt( } ], "outcome_envelope": { - "required_contracts": {"effect": 1, "authorization": 1}, - "passed_contracts": {"effect": 1 if verified else 0, "authorization": 1}, + "required_contracts": {"effect": 1}, + "passed_contracts": {"effect": 1 if verified else 0}, }, } if write_result.receipt: @@ -652,14 +679,12 @@ def qualify_pack( manifest_path: str | Path, clean_cases: Sequence[CleanWriteCase] = (), *, - pack_digest: Optional[str] = None, workdir: Optional[str | Path] = None, ) -> QualificationResult: """Run planted-fault mutation suite + clean-write verification and emit ``QUALIFICATION.json``.""" mpath = Path(manifest_path) pack_dir = mpath.parent - digest = pack_digest or _pack_digest(pack_dir) manifest_doc = yaml.safe_load(mpath.read_text(encoding="utf-8")) or {} actor = Actor(kind="agent", id=spec.actor_id) run_workdir = Path(workdir) if workdir is not None else pack_dir / "runs" @@ -667,12 +692,14 @@ def qualify_pack( refusal_reasons: list[str] = [] - # Step 1: Deterministic planted-fault mutation suite against isolated sandbox copies. + # Step 1: Deterministic planted-fault mutation suite against isolated sandbox copies + # of the actual on-disk pack under qualification. fault_outcomes: list[PlantedFaultOutcome] = [] sqlite_db = spec.read.get("sqlite_database") if isinstance(sqlite_db, str) and Path(sqlite_db).is_file(): fault_outcomes = _run_planted_faults_sqlite( spec, + pack_dir, Path(sqlite_db), clean_cases, actor=actor, @@ -820,16 +847,21 @@ def qualify_pack( clean_total = len(clean_outcomes) clean_verified = sum(1 for c in clean_outcomes if c.confirmed) + verified_kinds = {c.kind for c in clean_outcomes if c.confirmed} if clean_total == 0: refusal_reasons.append( "no clean writes were verified (at least one verified clean write " "with a signed record/run/v1 receipt is required for certification)" ) - elif len(receipt_paths) < clean_verified: - refusal_reasons.append( - f"signed receipts issued ({len(receipt_paths)}) fewer than " - f"verified clean writes ({clean_verified})" - ) + else: + for ks in spec.kinds: + if ks.kind not in verified_kinds: + refusal_reasons.append(f"kind {ks.kind!r} has no verified clean write") + if len(receipt_paths) < clean_verified: + refusal_reasons.append( + f"signed receipts issued ({len(receipt_paths)}) fewer than " + f"verified clean writes ({clean_verified})" + ) false_stop_rate = ( round((clean_total - clean_verified) / clean_total, 4) if clean_total > 0 @@ -845,6 +877,16 @@ def qualify_pack( and not refusal_reasons ) + if certified: + manifest_doc["zero_touch"] = { + "admitted": sorted(ks.kind for ks in spec.kinds), + } + mpath.write_text( + yaml.safe_dump(manifest_doc, sort_keys=False, allow_unicode=True), + encoding="utf-8", + ) + digest = _pack_digest(pack_dir) + result = QualificationResult( pack_name=spec.name, certified=certified, @@ -877,11 +919,10 @@ def onboard_pack( ) -> QualificationResult: """Single-call onboarding loop: synthesize pack -> planted-fault qualify -> certify.""" - manifest_path, digest = synthesize_pack(spec, out_dir) + manifest_path, _ = synthesize_pack(spec, out_dir) return qualify_pack( spec, manifest_path, clean_cases, - pack_digest=digest, workdir=workdir, ) diff --git a/packages/flow/tests/test_onboard_loop.py b/packages/flow/tests/test_onboard_loop.py index a5cd783d84..b2c6708607 100644 --- a/packages/flow/tests/test_onboard_loop.py +++ b/packages/flow/tests/test_onboard_loop.py @@ -753,6 +753,116 @@ def test_onboard_cli_end_to_end_and_dry_run( assert full_out["clean_writes_verified"] == 1 assert full_out["receipts_issued"] == 1 _assert_signed_receipt(full_out["receipt_paths"][0]) + # P1-4: receipt report must not hardcode authorization in outcome_envelope. + report_path = Path(full_out["receipt_paths"][0]).parent / "report.json" + report_doc = json.loads(report_path.read_text(encoding="utf-8")) + assert ( + "authorization" not in report_doc["outcome_envelope"]["required_contracts"] + ) + assert "authorization" not in report_doc["outcome_envelope"]["passed_contracts"] finally: server.shutdown() server.server_close() + + +def test_onboard_regression_p1_and_p2_gates(tmp_path: Path, monkeypatch: Any) -> None: + """Regression coverage for P1-1..P1-4 and P2-5 qualification gates.""" + from dataclasses import replace + + from openadapt_flow.onboard import engine as onboard_engine + from openadapt_flow.onboard.engine import qualify_pack, synthesize_pack + from openadapt_flow.verifier import Outcome, WriteResult + + db = tmp_path / "mini.sqlite" + con = sqlite3.connect(db) + con.execute("CREATE TABLE items (code TEXT, title TEXT, status TEXT)") + con.execute( + "INSERT INTO items (code, title, status) VALUES ('I-1', 'Existing', 'open')" + ) + con.commit() + con.close() + + spec = OnboardSpec( + name="mini-reg", + read={"sqlite_database": str(db)}, + kinds=( + KindOnboardingSpec( + kind="create_item", + mode="create", + table="items", + identity_field="code", + required_fields=("code", "title"), + optional_fields=("status",), + filter_params=("code",), + demonstrated_field_sets=(("code", "title"),), + sample_values={"code": "I-2", "title": "New"}, + ), + KindOnboardingSpec( + kind="update_item", + mode="update", + table="items", + identity_field="code", + identity_params=("code",), + change_fields=("status",), + filter_params=("code",), + demonstrated_field_sets=(("code", "status"),), + sample_values={"code": "I-1", "status": "closed"}, + ), + ), + ) + + # P2-5: synthesize_pack must not mark unqualified kinds admitted. + pack_dir = tmp_path / "pack" + mpath, synth_digest = synthesize_pack(spec, pack_dir) + manifest_before = yaml.safe_load(mpath.read_text(encoding="utf-8")) + assert manifest_before["zero_touch"]["admitted"] == [] + + # P1-2: certifying with clean writes for only one of two kinds must refuse. + def _insert_item() -> None: + c = sqlite3.connect(db) + c.execute("INSERT INTO items (code, title) VALUES ('I-3', 'Clean')") + c.commit() + c.close() + + partial_res = qualify_pack( + spec, + mpath, + [ + CleanWriteCase( + kind="create_item", + name="only_create", + values={"code": "I-3", "title": "Clean"}, + apply_write=_insert_item, + ) + ], + ) + assert partial_res.certified is False + assert any( + "update_item" in r and "no verified clean write" in r + for r in partial_res.refusal_reasons + ) + # P1-3: digest is computed from on-disk pack files, and unqualified pack stays unadmitted. + assert partial_res.pack_digest == synth_digest + manifest_after_refusal = yaml.safe_load(mpath.read_text(encoding="utf-8")) + assert manifest_after_refusal["zero_touch"]["admitted"] == [] + + # P1-1: an unjudged UNCERTAIN read (observed != "absent") must NOT count as caught. + real_verify = onboard_engine.verify_write + seen_once = {"done": False} + + def _uncertain_once(pending: Any) -> WriteResult: + res = real_verify(pending) + if not seen_once["done"]: + seen_once["done"] = True + return replace( + res, + outcome=Outcome.UNCERTAIN, + observed="unknown", + reasons=("simulated unreadable store",), + ) + return res + + monkeypatch.setattr(onboard_engine, "verify_write", _uncertain_once) + uncertain_res = qualify_pack(spec, mpath, []) + assert uncertain_res.certified is False + assert uncertain_res.planted_faults_caught < uncertain_res.planted_faults_total