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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions openadapt/cli_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,6 +83,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",
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Synthesize and planted-fault-qualify a verification pack for any system of record.
24 changes: 11 additions & 13 deletions packages/flow/openadapt_flow/__main__.py
Original file line number Diff line number Diff line change
Expand Up @@ -13167,27 +13167,25 @@ 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)
_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)
Expand Down
1 change: 1 addition & 0 deletions packages/flow/openadapt_flow/cli_tasks.py
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
44 changes: 44 additions & 0 deletions packages/flow/openadapt_flow/onboard/__init__.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
"""Domain-agnostic pack onboarding and planted-fault qualification loop."""

from __future__ import annotations

from typing import TYPE_CHECKING, Any

from openadapt_flow.onboard.types import (
CleanWriteCase,
CleanWriteOutcome,
KindOnboardingSpec,
OnboardSpec,
PlantedFaultOutcome,
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",
"KindOnboardingSpec",
"OnboardSpec",
"PlantedFaultOutcome",
"QualificationResult",
"onboard_pack",
"qualify_pack",
"synthesize_pack",
]
149 changes: 149 additions & 0 deletions packages/flow/openadapt_flow/onboard/cli.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,149 @@
"""CLI entry point for ``openadapt onboard`` (single-command pack onboarding)."""

from __future__ import annotations

import argparse
import json
import sys
import urllib.request
from pathlib import Path
from typing import Any

import yaml

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:
from openadapt_flow.onboard.engine import onboard_pack, synthesize_pack

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

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:
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"receipts={result.receipts_issued} "
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(
"--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",
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)
Loading