# ===== file: integrations/harbor/experimental/deepseek_server_readiness_subset.py ===== from __future__ import annotations import argparse import json import re import sys from pathlib import Path from typing import Any try: from statem.miniyaml import loads as _yaml_loads except ImportError: # Allow the public helper to be copied outside the StateM tree. import yaml _yaml_loads = yaml.safe_load DEFAULT_RUNBOOK = ( Path(__file__).resolve().parents[3] / "examples" / "terminal-bench-2.1-deepseek-server-readiness-subset.yaml" ) def load_runbook(path: Path = DEFAULT_RUNBOOK) -> dict[str, Any]: value = _yaml_loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError("server-readiness runbook must be a YAML object") if value.get("schema_version") != 1: raise ValueError("server-readiness runbook schema_version must be 1") if value.get("policy_version") != 9: raise ValueError("server-readiness runbook policy_version must be 9") if value.get("family") != "server_readiness": raise ValueError("server-readiness runbook has the wrong family") selection = value.get("selection") lens = value.get("lens") runtime = value.get("runtime") if not all(isinstance(item, dict) for item in (selection, lens, runtime)): raise ValueError("server-readiness runbook is missing structured sections") if lens.get("id") != "service_lifecycle_readiness": raise ValueError("server-readiness runbook has the wrong lens id") groups = selection.get("require_all_groups") if not isinstance(groups, list) or [item.get("name") for item in groups] != [ "service", "public_client", "persistence", ]: raise ValueError("server-readiness runbook requires exactly three trigger groups") for group in groups: patterns = group.get("any_regex") if isinstance(group, dict) else None if not isinstance(patterns, list) or not patterns or not all( isinstance(pattern, str) and pattern for pattern in patterns ): raise ValueError("every server-readiness trigger group needs regex patterns") for pattern in patterns: re.compile(pattern, flags=re.IGNORECASE) return value def select_review_lens(task_text: str, runbook: dict[str, Any]) -> dict[str, Any]: normalized = re.sub(r"[ \t]+", " ", task_text.lower()) selection = runbook["selection"] selected = all( any( re.search(pattern, normalized, flags=re.IGNORECASE) for pattern in group["any_regex"] ) for group in selection["require_all_groups"] ) if selected: lens = runbook["lens"] return { "version": runbook["policy_version"], "selected": True, "selection_basis": selection["selection_basis"], "applies_in_state": selection["applies_in_state"], "lens": { "id": lens["id"], "instruction": lens["instruction"], "receipt": {"required_fields": lens["receipt"]["required_fields"]}, }, "limits": lens["limits"], } non_match = runbook["non_match"] return { "version": runbook["policy_version"], "selected": False, "selection_basis": non_match["selection_basis"], "applies_in_state": non_match["applies_in_state"], "lens": None, "limits": non_match["limits"], } def render_review_lens(selection: dict[str, Any], runbook: dict[str, Any]) -> str: if not selection.get("selected"): return "" binding_errors = _selection_binding_errors(selection, runbook) if binding_errors: raise ValueError("; ".join(binding_errors)) lens = runbook["lens"] fields = ", ".join(lens["receipt"]["required_fields"]) runtime = runbook["runtime"] return ( "DeepSeek review adaptation (self_review only):\n" f"- {lens['id']}: {lens['instruction']}\n" "- Run only one bounded countercheck. Do not broaden the solve, invent " "an acceptance rule, or delay handoff after the deadline reserve begins.\n" f"- Record the bounded evidence receipt at {runtime['receipt_path']} with fields: " f"{fields}. Validate it with `python3 {runtime['validator_path']} " f"validate --selection {runtime['selection_path']} --receipt " f"{runtime['receipt_path']}`. A pending or failed receipt is a concrete issue, " "not a clean handoff." ) def receipt_template( selection: dict[str, Any], runbook: dict[str, Any] ) -> dict[str, Any] | None: lens = selection.get("lens") if not selection.get("selected") or not isinstance(lens, dict): return None binding_errors = _selection_binding_errors(selection, runbook) if binding_errors: raise ValueError("; ".join(binding_errors)) lens = runbook["lens"] payload: dict[str, Any] = { "version": selection["version"], "lens_id": lens["id"], "status": "pending", } for field in lens["receipt"]["required_fields"]: payload.setdefault(field, None) return payload def _selection_binding_errors( selection: dict[str, Any], runbook: dict[str, Any] ) -> list[str]: errors: list[str] = [] expected_selection = runbook["selection"] expected_lens = runbook["lens"] if selection.get("version") != runbook["policy_version"]: errors.append("selection version does not match runbook") if selection.get("selection_basis") != expected_selection["selection_basis"]: errors.append("selection basis does not match runbook") if selection.get("applies_in_state") != expected_selection["applies_in_state"]: errors.append("selection state does not match runbook") if selection.get("limits") != expected_lens["limits"]: errors.append("selection limits do not match runbook") lens = selection.get("lens") if not isinstance(lens, dict) or lens.get("id") != expected_lens["id"]: errors.append("selection is not bound to the server-readiness lens") return errors if lens.get("instruction") != expected_lens["instruction"]: errors.append("selection instruction does not match runbook") contract = lens.get("receipt") if not isinstance(contract, dict) or contract.get( "required_fields" ) != expected_lens["receipt"]["required_fields"]: errors.append("selection receipt fields do not match runbook") return errors def validate_receipt( selection: dict[str, Any], receipt: dict[str, Any], runbook: dict[str, Any] ) -> list[str]: lens = selection.get("lens") if not selection.get("selected") or not isinstance(lens, dict): return ["selection does not require a DeepSeek contract receipt"] binding_errors = _selection_binding_errors(selection, runbook) if binding_errors: return binding_errors errors: list[str] = [] if receipt.get("lens_id") != lens["id"]: errors.append("receipt lens_id does not match selection") required_values = runbook["lens"]["receipt"]["required_values"] if receipt.get("status") != required_values["status"]: errors.append("receipt status must be passed") for field in runbook["lens"]["receipt"]["required_fields"]: value = receipt.get(field) if value is None or value == "" or value == [] or value == {}: errors.append(f"missing receipt field: {field}") if ( receipt.get("detached_from_agent_session") is not required_values["detached_from_agent_session"] ): errors.append("service is not detached from the agent session") return errors def _read_json(path: Path) -> dict[str, Any]: value = json.loads(path.read_text(encoding="utf-8")) if not isinstance(value, dict): raise ValueError(f"expected JSON object: {path}") return value def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser(description="Verify the public server-readiness subset.") parser.add_argument("--runbook", type=Path, default=DEFAULT_RUNBOOK) subparsers = parser.add_subparsers(dest="command", required=True) select_parser = subparsers.add_parser("select") select_parser.add_argument("--task-text", type=Path, required=True) validate_parser = subparsers.add_parser("validate") validate_parser.add_argument("--selection", type=Path, required=True) validate_parser.add_argument("--receipt", type=Path, required=True) args = parser.parse_args(argv) try: runbook = load_runbook(args.runbook) if args.command == "select": result = select_review_lens( args.task_text.read_text(encoding="utf-8"), runbook ) print(json.dumps(result, indent=2, sort_keys=True)) return 0 selection = _read_json(args.selection) receipt = _read_json(args.receipt) errors = validate_receipt(selection, receipt, runbook) except (OSError, ValueError, json.JSONDecodeError, re.error) as exc: print(json.dumps({"status": "failed", "errors": [str(exc)]})) return 2 status = "passed" if not errors else "failed" print(json.dumps({"status": status, "errors": errors}, sort_keys=True)) return 0 if not errors else 1 if __name__ == "__main__": sys.exit(main()) # ===== file: integrations/harbor/experimental/git_webserver_deploy_family.py ===== from __future__ import annotations import atexit import argparse import hashlib import json import os import pwd import shutil import socket import subprocess import tempfile import time import urllib.error import urllib.parse import urllib.request from pathlib import Path from typing import Any FAMILY = "git_webserver_deploy" VERSION = 1 GATE_TIMEOUT_SECONDS = float(os.environ.get("STATEM_GIT_WEBSERVER_CHECK_TIMEOUT", "90")) DEFAULT_TASK = Path("/tmp/statem-verification-checks/task.txt") DEFAULT_SELECTION = Path("/tmp/statem-verification-checks/git-webserver-selection.json") DEFAULT_CONTRACT = Path("/tmp/statem-verification-checks/task-contract-receipt.json") DEFAULT_REVIEW = Path("/tmp/statem-verification-checks/self-review.json") DEFAULT_RECEIPT = Path("/tmp/statem-verification-checks/git-webserver-receipt.json") DEFAULT_DEADLINE = Path("/tmp/statem-verification-checks/deadline.json") REQUIRED_HINTS = ( "ssh_user", "repo_path", "branch", "web_file", "expected_content", "web_url", ) PRACTICE = { "id": FAMILY, "role": "reviewer", "instruction": ( "Review the exact consumer path, not just the local implementation: a fresh client must " "clone the configured bare repository over SSH as the named user, commit and push the " "requested branch, and then fetch the exact expected body from the public HTTP URL. " "Treat repository existence, an executable hook, an open port, a direct write into the web " "root, and a curl against pre-existing content as separate partial observations, not proof " "of the end-to-end deployment contract. Preserve a working candidate and repair a concrete " "broken link before considering rollback." ), "review_questions": [ "Does the configured SSH user reach the exact bare repository path from the prompt?", "Does a new push to the requested branch trigger deployment without an agent-side copy?", "Does a fresh HTTP request observe the pushed file with byte-exact body content?", "Could the current evidence be stale, circular, or produced through a privileged shortcut?", ], "required_evidence": [ "fresh SSH clone", "fresh commit and push to the requested branch", "post-push HTTP body equality", "post-check repository ref and HTTP freshness", ], "anti_patterns": [ "writing directly to the web root", "testing only localhost content created before the push", "checking only that sshd, Git, a hook, or an HTTP port exists", "replacing a failed end-to-end check with a proxy assertion", ], } def extract_hints(task_text: str) -> dict[str, str]: import re hints: dict[str, str] = {} remote = re.search(r"\b([A-Za-z0-9._-]+)@([A-Za-z0-9._-]+):(/[^\s'\"`]+)", task_text) if remote: hints["ssh_user"] = remote.group(1) hints["prompt_host"] = remote.group(2) hints["repo_path"] = remote.group(3).rstrip(".,)") url = re.search(r"https?://[^\s'\"`]+", task_text) if url: hints["web_url"] = url.group(0).rstrip(".,)") echo = re.search(r"\becho\s+([\"'])(.*?)\1\s*>\s*([A-Za-z0-9_./-]+)", task_text) if echo: hints["expected_content"] = echo.group(2) hints["web_file"] = echo.group(3).rstrip(".,)") push = re.search(r"\bgit\s+push\s+origin\s+([A-Za-z0-9_./-]+)", task_text) if push: hints["branch"] = push.group(1).rstrip(".,)") return hints def select_family(task_text: str) -> dict[str, Any]: lower = task_text.lower() hints = extract_hints(task_text) selected = bool( all(str(hints.get(key) or "").strip() for key in REQUIRED_HINTS) and "git clone" in lower and "git push" in lower and ("curl " in lower or "http request" in lower or "webserver" in lower) ) basis = ( "task_visible_git_ssh_push_http_contract" if selected else "no_high_confidence_git_ssh_push_http_contract" ) payload: dict[str, Any] = { "version": VERSION, "selected": selected, "family": FAMILY, "selection_basis": basis, "applies_in_state": "self_review", "practice": PRACTICE if selected else None, "gate": { "name": FAMILY, "effect_scope": "stateful", "git_webserver_hints": hints if selected else {}, }, "limits": [ "solve the visible task normally before loading family review practice", "execute at most one stateful family gate per evidence-state entry", "repair concrete failures non-destructively before considering rollback", "under handoff deadline pressure preserve the best runnable candidate", ], } payload["selection_fingerprint"] = _selection_fingerprint(payload) return payload def validate_selection(selection: Any, task_text: str) -> list[str]: expected = select_family(task_text) if not isinstance(selection, dict): return ["family selection must be a JSON object"] if selection != expected: return [ "family selection does not exactly match the task-visible contract; " "regenerate it instead of editing routes, hints, practice, or limits" ] return [] def render_practice(selection: dict[str, Any], task_text: str) -> str: _raise_errors(validate_selection(selection, task_text)) if not selection["selected"]: return "" practice = selection["practice"] lines = [ "Selected reviewer practice: git_webserver_deploy", str(practice["instruction"]), "Review questions:", ] lines.extend(f"- {item}" for item in practice["review_questions"]) lines.append("Required evidence:") lines.extend(f"- {item}" for item in practice["required_evidence"]) lines.append("Reject these proxy checks:") lines.extend(f"- {item}" for item in practice["anti_patterns"]) return "\n".join(lines) def initial_contract() -> dict[str, Any]: return { "version": 1, "source": "agent", "status": "pending", "artifact_or_service_identity": "", "checks": [], "remaining_risk": "", "next_action": "", } def validate_contract(receipt: Any) -> list[str]: if not isinstance(receipt, dict): return ["task contract receipt must be a JSON object"] problems: list[str] = [] if not str(receipt.get("source") or "").startswith("agent"): problems.append("task contract receipt source must start with 'agent'") status = str(receipt.get("status") or "").strip().lower() if status not in {"passed", "failed"}: problems.append("task contract receipt status must be passed or failed") checks = receipt.get("checks") if not isinstance(checks, list) or not any(_meaningful(item) for item in checks): problems.append("task contract receipt needs at least one concrete current check") if status == "passed": if not _meaningful(receipt.get("artifact_or_service_identity")): problems.append("passed task contract receipt needs artifact_or_service_identity") if receipt.get("next_action") != "self_review": problems.append("passed task contract receipt next_action must be self_review") if status == "failed" and receipt.get("next_action") != "repair": problems.append("failed task contract receipt next_action must be repair") return problems def initial_review(selection: dict[str, Any]) -> dict[str, Any]: lenses = { "task_contract": {"evidence": ""}, "evidence_freshness": {"evidence": ""}, "edge_risk": {"evidence": ""}, } if selection.get("selected"): lenses["consumer_path"] = {"evidence": ""} return { "version": 1, "source": "agent", "mode": "bounded", "status": "pending", "family": FAMILY if selection.get("selected") else None, "lenses": lenses, "findings": [], "evidence_gaps": [], "next_fix": "", "residual_risk": "", } def validate_review(review: Any, selection: Any, task_text: str) -> list[str]: problems = validate_selection(selection, task_text) safe_selection = selection if isinstance(selection, dict) else {} if not isinstance(review, dict): return problems + ["self-review must be a JSON object"] if not str(review.get("source") or "").startswith("agent"): problems.append("self-review source must start with 'agent'") if review.get("mode") not in {"bounded", "deadline_bounded"}: problems.append("self-review mode must be bounded or deadline_bounded") expected_family = FAMILY if safe_selection.get("selected") else None if review.get("family") != expected_family: problems.append("self-review family must match the immutable selection") status = str(review.get("status") or "").strip().lower() if status not in {"clean", "issues_found", "needs_evidence", "deadline_handoff"}: problems.append( "self-review status must be clean, issues_found, needs_evidence, or deadline_handoff" ) return problems lenses = review.get("lenses") if isinstance(review.get("lenses"), dict) else {} required_lenses = ["task_contract", "evidence_freshness", "edge_risk"] if safe_selection.get("selected"): required_lenses.append("consumer_path") for name in required_lenses: lens = lenses.get(name) if isinstance(lenses, dict) else None evidence = lens.get("evidence") if isinstance(lens, dict) else "" if not _meaningful(evidence, minimum=12): problems.append(f"self-review lens {name} needs concrete evidence") findings = review.get("findings") gaps = review.get("evidence_gaps") if status == "clean": if _has_open_items(findings) or _has_open_items(gaps): problems.append("clean self-review cannot retain open findings or evidence gaps") elif status == "issues_found": if not _has_open_items(findings): problems.append("issues_found self-review needs at least one concrete finding") if not _meaningful(review.get("next_fix"), minimum=8): problems.append("issues_found self-review needs a concrete next_fix") elif status == "needs_evidence": if not safe_selection.get("selected"): problems.append("needs_evidence requires a selected fixed family gate") if not _has_open_items(gaps): problems.append("needs_evidence self-review needs at least one concrete evidence gap") else: if review.get("mode") != "deadline_bounded": problems.append("deadline_handoff self-review mode must be deadline_bounded") if not _meaningful(review.get("residual_risk"), minimum=12): problems.append("deadline_handoff self-review needs specific residual_risk") return problems def run_gate( selection: Any, task_text: str, receipt_path: Path, ) -> tuple[bool, dict[str, Any]]: selection_errors = validate_selection(selection, task_text) safe_selection = selection if isinstance(selection, dict) else {} messages: list[str] = [] passed = False if selection_errors: messages.extend(selection_errors) elif not safe_selection.get("selected"): messages.append("git_webserver_deploy is not selected for this task") else: try: passed, raw_messages = run_git_webserver_check( {"git_webserver_hints": safe_selection["gate"]["git_webserver_hints"]} ) messages.extend(str(item)[:500] for item in raw_messages[:30]) except Exception as exc: # The failed receipt must survive an unexpected checker error. messages.append(f"git_webserver_deploy checker raised {type(exc).__name__}: {exc}") passed = False hints = safe_selection.get("gate", {}).get("git_webserver_hints", {}) branch_head = _branch_head(hints) if passed else "" observed_url, observed_body, observation_error = _observe_http(hints) if passed else ("", "", "") expected = str(hints.get("expected_content") or "") if isinstance(hints, dict) else "" if passed and (not branch_head or observation_error or observed_body != expected): passed = False if not branch_head: messages.append("post-gate freshness check could not resolve the deployed branch head") if observation_error: messages.append(observation_error) elif observed_body != expected: messages.append( f"post-gate HTTP body was {observed_body!r}, expected {expected!r}" ) receipt = { "version": 1, "source": "statem_fixed_family_gate", "family": FAMILY, "gate": FAMILY, "effect_scope": "stateful", "status": "passed" if passed else "failed", "selection_fingerprint": safe_selection.get("selection_fingerprint"), "gate_implementation_sha256": _implementation_sha256(), "recorded_at_epoch": time.time(), "branch_head": branch_head, "observed_url": observed_url, "observed_body": observed_body, "messages": messages, } _write_json(receipt_path, receipt) return passed, receipt def validate_receipt( receipt: Any, selection: Any, task_text: str, *, max_age_seconds: int = 900, now: float | None = None, ) -> list[str]: problems = validate_selection(selection, task_text) safe_selection = selection if isinstance(selection, dict) else {} if not safe_selection.get("selected"): problems.append("a family gate receipt is invalid when the family route is not selected") if not isinstance(receipt, dict): return problems + ["family gate receipt must be a JSON object"] expected_fields = { "source": "statem_fixed_family_gate", "family": FAMILY, "gate": FAMILY, "effect_scope": "stateful", "status": "passed", "selection_fingerprint": safe_selection.get("selection_fingerprint"), } for key, expected in expected_fields.items(): if receipt.get(key) != expected: problems.append(f"family gate receipt {key} must equal {expected!r}") current_gate_hash = _implementation_sha256() if not current_gate_hash or receipt.get("gate_implementation_sha256") != current_gate_hash: problems.append("family gate receipt does not match the current fixed gate implementation") recorded = _as_float(receipt.get("recorded_at_epoch")) current_time = time.time() if now is None else now if recorded is None: problems.append("family gate receipt needs recorded_at_epoch") elif recorded > current_time + 5: problems.append("family gate receipt timestamp is in the future") elif current_time - recorded > max_age_seconds: problems.append("family gate receipt is older than the allowed freshness window") hints = safe_selection.get("gate", {}).get("git_webserver_hints", {}) current_head = _branch_head(hints) if not current_head: problems.append("current deployed branch head is unavailable") elif receipt.get("branch_head") != current_head: problems.append("deployed branch changed after the family gate receipt") observed_url, observed_body, observation_error = _observe_http(hints) expected_body = str(hints.get("expected_content") or "") if isinstance(hints, dict) else "" if observation_error: problems.append(observation_error) elif observed_body != expected_body: problems.append( f"current HTTP body was {observed_body!r}, expected {expected_body!r}" ) if receipt.get("observed_url") != observed_url: problems.append("family gate receipt URL does not match the current consumer URL") if receipt.get("observed_body") != expected_body: problems.append("family gate receipt does not record the expected HTTP body") return problems def _selection_fingerprint(payload: dict[str, Any]) -> str: canonical = {key: value for key, value in payload.items() if key != "selection_fingerprint"} encoded = json.dumps(canonical, sort_keys=True, separators=(",", ":")).encode("utf-8") return hashlib.sha256(encoded).hexdigest() def _implementation_sha256() -> str: path = Path(__file__) if not path.is_file(): return "" return hashlib.sha256(path.read_bytes()).hexdigest() def run_git_webserver_check(selection: dict[str, Any]) -> tuple[bool, list[str]]: hints = selection.get("git_webserver_hints") if isinstance(selection, dict) else {} hints = hints if isinstance(hints, dict) else {} ssh_user = str(hints.get("ssh_user") or "").strip() repo_path = str(hints.get("repo_path") or "").strip() branch = str(hints.get("branch") or "").strip() web_file = str(hints.get("web_file") or "").strip() expected = str(hints.get("expected_content") or "").strip() raw_web_url = str(hints.get("web_url") or "").strip() web_url = _local_web_url(raw_web_url) prompt_host = str(hints.get("prompt_host") or "").strip() messages = [ f"ssh_user={ssh_user}", f"repo_path={repo_path}", f"branch={branch}", f"web_url={web_url}", ] problems: list[str] = [] for key, value in ( ("ssh_user", ssh_user), ("repo_path", repo_path), ("branch", branch), ("web_file", web_file), ("expected_content", expected), ("web_url", raw_web_url), ): if not value: problems.append(f"missing required git_webserver_hints.{key}") for command in ("git", "ssh", "ssh-keygen"): if shutil.which(command) is None: problems.append(f"missing required command: {command}") if problems: return False, messages + problems try: user_info = pwd.getpwnam(ssh_user) except KeyError: return False, messages + [f"SSH user does not exist: {ssh_user!r}"] repo_check = _run_command( ["git", f"--git-dir={repo_path}", "rev-parse", "--is-bare-repository"] ) if repo_check.returncode != 0: return False, messages + [ f"{repo_path} is not a readable bare Git repository: {_command_output(repo_check)}" ] with tempfile.TemporaryDirectory(prefix="statem-git-webserver-check-") as temp_dir: root = Path(temp_dir) key_path = root / "id_ed25519" problems.extend(_prepare_ssh_key(ssh_user, user_info, key_path)) if problems: return False, messages + problems ssh_env = os.environ.copy() ssh_env["GIT_SSH_COMMAND"] = ( f"ssh -i {key_path} -o StrictHostKeyChecking=no " "-o UserKnownHostsFile=/dev/null -o BatchMode=yes" ) clone_dir = root / "repo" clone_url = f"{ssh_user}@localhost:{repo_path}" clone = _run_command( ["git", "clone", clone_url, str(clone_dir)], env=ssh_env, timeout=GATE_TIMEOUT_SECONDS, ) if clone.returncode != 0: return False, messages + [ f"SSH git clone failed for {clone_url}: {_command_output(clone)}" ] _run_command(["git", "config", "user.email", "statem@example.com"], cwd=clone_dir) _run_command(["git", "config", "user.name", "statem deploy check"], cwd=clone_dir) target_path = clone_dir / web_file target_path.parent.mkdir(parents=True, exist_ok=True) target_path.write_text(expected + "\n", encoding="utf-8") probe_name = f".statem-deploy-check-{int(time.time())}-{os.getpid()}.txt" probe_path = clone_dir / probe_name probe_path.write_text("statem git webserver deployment check\n", encoding="utf-8") add = _run_command(["git", "add", web_file, probe_name], cwd=clone_dir) if add.returncode != 0: return False, messages + [f"git add failed in SSH clone: {_command_output(add)}"] commit = _run_command( ["git", "commit", "-m", "statem git webserver deployment check"], cwd=clone_dir, ) if commit.returncode != 0: return False, messages + [ f"git commit failed in SSH clone: {_command_output(commit)}" ] push = _run_command( ["git", "push", "origin", f"HEAD:{branch}"], cwd=clone_dir, env=ssh_env, timeout=GATE_TIMEOUT_SECONDS, ) if push.returncode != 0: return False, messages + [f"git push over SSH failed: {_command_output(push)}"] body_problem = _wait_for_http_body(web_url, expected) if body_problem: return False, messages + [body_problem] cleanup = _run_command(["git", "rm", "--ignore-unmatch", probe_name], cwd=clone_dir) if cleanup.returncode != 0: return False, messages + [f"git cleanup failed: {_command_output(cleanup)}"] cleanup_status = _run_command(["git", "status", "--porcelain"], cwd=clone_dir) if cleanup_status.returncode != 0: return False, messages + [ f"git cleanup status failed: {_command_output(cleanup_status)}" ] if cleanup_status.stdout.strip(): cleanup_commit = _run_command( ["git", "commit", "-m", "statem git webserver deployment check cleanup"], cwd=clone_dir, ) if cleanup_commit.returncode != 0: return False, messages + [ f"git cleanup commit failed: {_command_output(cleanup_commit)}" ] cleanup_push = _run_command( ["git", "push", "origin", f"HEAD:{branch}"], cwd=clone_dir, env=ssh_env, timeout=GATE_TIMEOUT_SECONDS, ) if cleanup_push.returncode != 0: return False, messages + [ f"git cleanup push failed: {_command_output(cleanup_push)}" ] body_problem = _wait_for_http_body(web_url, expected) if body_problem: return False, messages + [f"post-cleanup web check failed: {body_problem}"] messages.append("temporary deploy probe cleaned") if raw_web_url != web_url and _host_resolves(_url_host(raw_web_url)): prompt_problem = _wait_for_http_body(raw_web_url, expected, attempts=3) if prompt_problem: return False, messages + [f"prompt URL check failed: {prompt_problem}"] elif prompt_host and prompt_host not in {"localhost", "127.0.0.1"}: messages.append( f"prompt_host={prompt_host} was not resolvable; localhost service check was used" ) return True, messages + ["git_webserver_deploy_check passed"] def _prepare_ssh_key( ssh_user: str, user_info: pwd.struct_passwd, key_path: Path, ) -> list[str]: keygen = _run_command(["ssh-keygen", "-t", "ed25519", "-f", str(key_path), "-N", "", "-q"]) if keygen.returncode != 0: return [f"ssh-keygen failed: {_command_output(keygen)}"] ssh_dir = Path(user_info.pw_dir) / ".ssh" authorized_keys = ssh_dir / "authorized_keys" try: ssh_dir.mkdir(parents=True, exist_ok=True) public_key = key_path.with_suffix(".pub").read_text(encoding="utf-8").strip() existing = ( authorized_keys.read_text(encoding="utf-8", errors="ignore") if authorized_keys.exists() else "" ) added_key = public_key not in {line.strip() for line in existing.splitlines()} if added_key: with authorized_keys.open("a", encoding="utf-8") as handle: if existing and not existing.endswith("\n"): handle.write("\n") handle.write(public_key + "\n") os.chown(ssh_dir, user_info.pw_uid, user_info.pw_gid) os.chown(authorized_keys, user_info.pw_uid, user_info.pw_gid) ssh_dir.chmod(0o700) authorized_keys.chmod(0o600) if added_key: atexit.register( _remove_authorized_key, authorized_keys, public_key, user_info.pw_uid, user_info.pw_gid, ) except OSError as exc: return [f"could not authorize SSH key for {ssh_user}: {exc}"] return [] def _remove_authorized_key( authorized_keys: Path, public_key: str, uid: int, gid: int, ) -> None: try: if not authorized_keys.exists(): return remaining = [ line for line in authorized_keys.read_text(encoding="utf-8", errors="ignore").splitlines() if line.strip() != public_key ] payload = "\n".join(remaining) authorized_keys.write_text(payload + ("\n" if payload else ""), encoding="utf-8") os.chown(authorized_keys, uid, gid) authorized_keys.chmod(0o600) except OSError: return def _wait_for_http_body(url: str, expected: str, attempts: int = 12) -> str | None: last_error = "" for _ in range(attempts): _, body, error = _observe_url(url) if not error and body == expected: return None last_error = error or f"{url} returned {body!r}, expected {expected!r}" time.sleep(1) return last_error or f"{url} did not return expected content" def _observe_url(url: str) -> tuple[str, str, str]: try: with urllib.request.urlopen(url, timeout=5) as response: status = int(getattr(response, "status", 200)) body = response.read().decode("utf-8", errors="replace").rstrip("\r\n") except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc: return url, "", f"{url} request failed: {exc}" if status != 200: return url, body, f"{url} returned HTTP {status}" return url, body, "" def _host_resolves(host: str) -> bool: if not host: return False try: socket.getaddrinfo(host, None) except OSError: return False return True def _url_host(url: str) -> str: try: return urllib.parse.urlparse(url).hostname or "" except ValueError: return "" def _run_command( command: list[str], *, cwd: Path | None = None, env: dict[str, str] | None = None, timeout: float = 30, ) -> subprocess.CompletedProcess[str]: try: return subprocess.run( command, cwd=str(cwd) if cwd else None, env=env, text=True, capture_output=True, timeout=timeout, check=False, ) except subprocess.TimeoutExpired as exc: return subprocess.CompletedProcess( command, 124, exc.stdout or "", (exc.stderr or "") + f"\ntimed out after {timeout:g}s", ) def _command_output(completed: subprocess.CompletedProcess[str]) -> str: return "\n".join( part.strip() for part in (completed.stdout, completed.stderr) if part.strip() )[:2000] def _branch_head(hints: Any) -> str: if not isinstance(hints, dict): return "" repo_path = str(hints.get("repo_path") or "").strip() branch = str(hints.get("branch") or "").strip() if not repo_path or not branch: return "" try: completed = subprocess.run( ["git", f"--git-dir={repo_path}", "rev-parse", f"refs/heads/{branch}"], capture_output=True, check=False, text=True, timeout=10, ) except (OSError, subprocess.TimeoutExpired): return "" return completed.stdout.strip() if completed.returncode == 0 else "" def _observe_http(hints: Any) -> tuple[str, str, str]: if not isinstance(hints, dict): return "", "", "missing git webserver hints" raw_url = str(hints.get("web_url") or "").strip() if not raw_url: return "", "", "missing consumer HTTP URL" url = _local_web_url(raw_url) try: with urllib.request.urlopen(url, timeout=5) as response: status = int(getattr(response, "status", 200)) body = response.read().decode("utf-8", errors="replace").rstrip("\r\n") except (urllib.error.URLError, TimeoutError, OSError, ValueError) as exc: return url, "", f"current HTTP request failed: {exc}" if status != 200: return url, body, f"current HTTP request returned status {status}" return url, body, "" def _local_web_url(url: str) -> str: parsed = urllib.parse.urlparse(url) if not parsed.scheme or not parsed.netloc: return url if parsed.hostname in {"localhost", "127.0.0.1", "::1"}: return url netloc = "localhost" + (f":{parsed.port}" if parsed.port else "") return urllib.parse.urlunparse(parsed._replace(netloc=netloc)) def _meaningful(value: Any, *, minimum: int = 4) -> bool: if isinstance(value, dict): return any(_meaningful(item, minimum=minimum) for item in value.values()) if isinstance(value, list): return any(_meaningful(item, minimum=minimum) for item in value) return len(str(value or "").strip()) >= minimum def _has_open_items(value: Any) -> bool: if not isinstance(value, list): return False for item in value: if isinstance(item, dict): status = str(item.get("status") or "open").strip().lower() if status not in {"fixed", "resolved", "not_applicable"} and _meaningful(item): return True elif _meaningful(item): return True return False def _as_float(value: Any) -> float | None: try: return float(value) except (TypeError, ValueError): return None def _read_text(path: Path) -> str: return path.read_text(encoding="utf-8") def _read_json(path: Path) -> Any: return json.loads(path.read_text(encoding="utf-8")) def _write_json(path: Path, payload: Any) -> None: path.parent.mkdir(parents=True, exist_ok=True) temporary = path.with_suffix(path.suffix + ".tmp") temporary.write_text(json.dumps(payload, indent=2, sort_keys=True) + "\n", encoding="utf-8") temporary.replace(path) def _raise_errors(problems: list[str]) -> None: if problems: raise ValueError("; ".join(problems)) def _print_errors(problems: list[str]) -> int: for problem in problems: print(problem) return 1 if problems else 0 def deadline_status(path: Path, *, now: float | None = None) -> dict[str, Any]: try: payload = _read_json(path) except (OSError, json.JSONDecodeError): payload = {} if not isinstance(payload, dict) or not payload.get("deadline_at_epoch"): return { "configured": False, "mode": "unbounded", "remaining_seconds": None, } current = time.time() if now is None else now deadline_at = _as_float(payload.get("deadline_at_epoch")) if deadline_at is None: return { "configured": False, "mode": "unbounded", "remaining_seconds": None, } handoff_buffer = _positive_int(payload.get("handoff_buffer_seconds"), 120) heavy_buffer = _positive_int(payload.get("heavy_work_buffer_seconds"), 240) remaining = int(deadline_at - current) if remaining <= 0: mode = "expired" elif remaining <= handoff_buffer: mode = "handoff_due" elif remaining <= heavy_buffer: mode = "heavy_work_closed" else: mode = "normal" return { "configured": True, "mode": mode, "remaining_seconds": remaining, "handoff_buffer_seconds": handoff_buffer, "heavy_work_buffer_seconds": heavy_buffer, } def validate_deadline_predicate( status: dict[str, Any], *, required_modes: set[str] | None = None, min_remaining: int | None = None, handoff_due_or_expired: bool = False, heavy_work_closed_or_worse: bool = False, ) -> list[str]: if not status.get("configured"): return [] mode = str(status.get("mode") or "") remaining = status.get("remaining_seconds") problems: list[str] = [] if required_modes and mode not in required_modes: problems.append(f"deadline mode {mode!r} is not one of {sorted(required_modes)!r}") if min_remaining is not None and isinstance(remaining, int) and remaining < min_remaining: problems.append( f"deadline remaining_seconds={remaining} is below required {min_remaining}" ) if handoff_due_or_expired and mode not in {"handoff_due", "expired"}: problems.append("deadline is not handoff_due or expired") if heavy_work_closed_or_worse and mode not in { "heavy_work_closed", "handoff_due", "expired", }: problems.append("deadline has not closed heavy work") return problems def _positive_int(value: Any, default: int) -> int: try: parsed = int(value) except (TypeError, ValueError): return default return parsed if parsed > 0 else default def main(argv: list[str] | None = None) -> int: parser = argparse.ArgumentParser( description="Standalone git_webserver_deploy family router, reviewer, and receipt gate." ) subparsers = parser.add_subparsers(dest="command", required=True) select_parser = subparsers.add_parser("select") select_parser.add_argument("--task", type=Path, default=DEFAULT_TASK) select_parser.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) select_parser.add_argument("--quiet", action="store_true") for name in ("validate-selection", "render-practice"): command = subparsers.add_parser(name) command.add_argument("--task", type=Path, default=DEFAULT_TASK) command.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) route_parser = subparsers.add_parser("route") route_parser.add_argument("--task", type=Path, default=DEFAULT_TASK) route_parser.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) route_parser.add_argument("--target", choices=("family_evidence", "handoff"), required=True) contract_init = subparsers.add_parser("init-contract") contract_init.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT) contract_check = subparsers.add_parser("validate-contract") contract_check.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT) contract_status = subparsers.add_parser("contract-status") contract_status.add_argument("--contract", type=Path, default=DEFAULT_CONTRACT) contract_status.add_argument("--status", choices=("passed", "failed"), required=True) review_init = subparsers.add_parser("init-review") review_init.add_argument("--task", type=Path, default=DEFAULT_TASK) review_init.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) review_init.add_argument("--review", type=Path, default=DEFAULT_REVIEW) review_check = subparsers.add_parser("validate-review") review_check.add_argument("--task", type=Path, default=DEFAULT_TASK) review_check.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) review_check.add_argument("--review", type=Path, default=DEFAULT_REVIEW) review_status = subparsers.add_parser("review-status") review_status.add_argument("--task", type=Path, default=DEFAULT_TASK) review_status.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) review_status.add_argument("--review", type=Path, default=DEFAULT_REVIEW) review_status.add_argument( "--target", choices=("repair", "family_evidence", "handoff", "deadline_handoff"), required=True ) gate_run = subparsers.add_parser("run-gate") gate_run.add_argument("--task", type=Path, default=DEFAULT_TASK) gate_run.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) gate_run.add_argument("--receipt", type=Path, default=DEFAULT_RECEIPT) receipt_check = subparsers.add_parser("validate-receipt") receipt_check.add_argument("--task", type=Path, default=DEFAULT_TASK) receipt_check.add_argument("--selection", type=Path, default=DEFAULT_SELECTION) receipt_check.add_argument("--receipt", type=Path, default=DEFAULT_RECEIPT) receipt_check.add_argument("--max-age-seconds", type=int, default=900) receipt_status = subparsers.add_parser("receipt-status") receipt_status.add_argument("--receipt", type=Path, default=DEFAULT_RECEIPT) receipt_status.add_argument("--status", choices=("passed", "failed"), required=True) deadline_parser = subparsers.add_parser("deadline") deadline_parser.add_argument("--deadline", type=Path, default=DEFAULT_DEADLINE) deadline_parser.add_argument("--require-mode", default="") deadline_parser.add_argument("--min-remaining", type=int) deadline_parser.add_argument("--handoff-due-or-expired", action="store_true") deadline_parser.add_argument("--heavy-work-closed-or-worse", action="store_true") args = parser.parse_args(argv) try: if args.command == "select": selected = select_family(_read_text(args.task)) if args.selection.exists(): _raise_errors(validate_selection(_read_json(args.selection), _read_text(args.task))) else: _write_json(args.selection, selected) if not args.quiet: print(json.dumps(selected, indent=2, sort_keys=True)) return 0 if args.command in {"validate-selection", "render-practice", "route"}: task_text = _read_text(args.task) selection = _read_json(args.selection) problems = validate_selection(selection, task_text) if problems: return _print_errors(problems) if args.command == "validate-selection": print("git_webserver_deploy selection is valid") return 0 if args.command == "render-practice": rendered = render_practice(selection, task_text) if rendered: print(rendered) return 0 expected_selected = args.target == "family_evidence" return 0 if bool(selection["selected"]) == expected_selected else 1 if args.command == "init-contract": _write_json(args.contract, initial_contract()) return 0 if args.command in {"validate-contract", "contract-status"}: contract = _read_json(args.contract) problems = validate_contract(contract) if problems: return _print_errors(problems) if args.command == "validate-contract": print("task contract receipt is valid") return 0 return 0 if contract.get("status") == args.status else 1 if args.command == "init-review": selection = _read_json(args.selection) _raise_errors(validate_selection(selection, _read_text(args.task))) _write_json(args.review, initial_review(selection)) return 0 if args.command in {"validate-review", "review-status"}: task_text = _read_text(args.task) selection = _read_json(args.selection) review = _read_json(args.review) problems = validate_review(review, selection, task_text) if problems: return _print_errors(problems) if args.command == "validate-review": print("bounded self-review is valid") return 0 status = review.get("status") allowed = { "repair": {"issues_found"}, "family_evidence": {"clean", "needs_evidence"}, "handoff": {"clean"}, "deadline_handoff": {"deadline_handoff"}, }[args.target] return 0 if status in allowed else 1 if args.command == "run-gate": passed, receipt = run_gate( _read_json(args.selection), _read_text(args.task), args.receipt ) for message in receipt["messages"]: print(message) return 0 if passed else 1 if args.command == "validate-receipt": problems = validate_receipt( _read_json(args.receipt), _read_json(args.selection), _read_text(args.task), max_age_seconds=args.max_age_seconds, ) if problems: return _print_errors(problems) print("git_webserver_deploy receipt is current and valid") return 0 if args.command == "receipt-status": try: status = str(_read_json(args.receipt).get("status") or "failed") except (OSError, json.JSONDecodeError, AttributeError): status = "failed" return 0 if status == args.status else 1 if args.command == "deadline": status = deadline_status(args.deadline) print( "deadline_status " f"mode={status.get('mode')} " f"remaining_seconds={status.get('remaining_seconds')} " f"configured={str(bool(status.get('configured'))).lower()}" ) required_modes = { item.strip() for item in str(args.require_mode or "").split(",") if item.strip() } return _print_errors( validate_deadline_predicate( status, required_modes=required_modes, min_remaining=args.min_remaining, handoff_due_or_expired=args.handoff_due_or_expired, heavy_work_closed_or_worse=args.heavy_work_closed_or_worse, ) ) except (OSError, json.JSONDecodeError, TypeError, ValueError) as exc: print(f"git_webserver_deploy family error: {exc}") return 1 return 2 if __name__ == "__main__": raise SystemExit(main()) # ===== file: integrations/harbor/statem_codex_git_webserver_deploy.py ===== from __future__ import annotations import base64 import hashlib import json import os import re import shlex import tempfile import time from pathlib import Path, PurePosixPath from typing import Any from harbor.agents.installed.codex import Codex from harbor.environments.base import BaseEnvironment from harbor.models.agent.context import AgentContext from harbor.models.trial.paths import EnvironmentPaths FAMILY_METADATA = { "name": "git_webserver_deploy", "policy_surface": "single_family", "selection_basis": "task_visible_contract", } class GitWebserverDeployFamilyStatemCodex(Codex): """Self-contained Harbor adapter for one executable StateM task family.""" _PINNED_CODEX_VERSION = "0.146.0" _REMOTE_STATEM_SRC = PurePosixPath("/tmp/statem-src") _REMOTE_RUNBOOK_DIR = PurePosixPath("/tmp/statem-runbooks") _REMOTE_STATE_DIR = PurePosixPath("/tmp/statem-state") _REMOTE_CHECKS = PurePosixPath("/tmp/statem-verification-checks") _REMOTE_RUNBOOK = _REMOTE_RUNBOOK_DIR / "git-webserver-family.yaml" _REMOTE_HELPER = _REMOTE_CHECKS / "git_webserver_deploy_family.py" _REMOTE_STOP_HOOK = _REMOTE_CHECKS / "statem_stop_hook.py" _REMOTE_ADAPTER = _REMOTE_CHECKS / "git-webserver-family-adapter.py" _PUBLIC_STATEM_FILES = ( "__init__.py", "__main__.py", "cli.py", "core.py", "miniyaml.py", ) def __init__( self, *args: Any, statem_source_dir: str | None = None, runbook_path: str | None = None, run_id_prefix: str = "tb21-git-webserver-deploy", final_state: str = "handoff", enforce_final_state: bool = True, agent_deadline_seconds: int = 900, handoff_buffer_seconds: int = 120, heavy_work_buffer_seconds: int = 240, **kwargs: Any, ) -> None: requested_version = kwargs.get("version") if requested_version not in (None, self._PINNED_CODEX_VERSION): raise ValueError( "git_webserver_deploy family reproduction requires Codex " f"{self._PINNED_CODEX_VERSION}, got {requested_version}" ) kwargs["version"] = self._PINNED_CODEX_VERSION super().__init__(*args, **kwargs) repo_root = Path(__file__).resolve().parents[2] self._statem_source_dir = ( Path(statem_source_dir).expanduser().resolve() if statem_source_dir else repo_root ) self._runbook_path = ( Path(runbook_path).expanduser().resolve() if runbook_path else repo_root / "examples" / "terminal-bench-2.1-git-webserver-deploy-family.yaml" ) self._helper_path = ( repo_root / "integrations" / "harbor" / "experimental" / "git_webserver_deploy_family.py" ) self._stop_hook_path = ( repo_root / "integrations" / "hooks" / "statem_stop_hook.py" ) self._adapter_path = Path(__file__).resolve() self._run_id_prefix = run_id_prefix self._final_state = final_state self._enforce_final_state = bool(enforce_final_state) self._agent_deadline_seconds = max(1, int(agent_deadline_seconds)) self._handoff_buffer_seconds = max(1, int(handoff_buffer_seconds)) self._heavy_work_buffer_seconds = max(1, int(heavy_work_buffer_seconds)) self._source_manifest: dict[str, Any] | None = None @staticmethod def name() -> str: return "statem-codex-git-webserver-deploy-family" def build_cli_flags(self) -> str: flags = super().build_cli_flags() if self._get_env("CODEX_AUTH_JSON_PATH"): flags = f"{flags} -c cli_auth_credentials_store=file".strip() return f"{flags} --dangerously-bypass-hook-trust".strip() async def setup(self, environment: BaseEnvironment) -> None: await super().setup(environment) await self._install_family_runtime(environment) async def _install_family_runtime(self, environment: BaseEnvironment) -> None: required = [ self._runbook_path, self._helper_path, self._stop_hook_path, self._adapter_path, *[ self._statem_source_dir / "statem" / name for name in self._PUBLIC_STATEM_FILES ], ] missing = [str(path) for path in required if not path.is_file()] if missing: raise FileNotFoundError( "single-family publication is missing required files: " + ", ".join(missing) ) await self.exec_as_root( environment, command=( "if command -v python3 >/dev/null 2>&1; then python3 --version; " "elif [ -f /etc/alpine-release ]; then apk add --no-cache python3; " "elif command -v apt-get >/dev/null 2>&1; then " "DEBIAN_FRONTEND=noninteractive apt-get update && " "DEBIAN_FRONTEND=noninteractive apt-get install -y python3; " "else echo 'python3 is required for statem' >&2; exit 1; fi" ), ) await self.exec_as_root( environment, command=( f"rm -rf {shlex.quote(self._REMOTE_STATEM_SRC.as_posix())} " f"{shlex.quote(self._REMOTE_RUNBOOK_DIR.as_posix())} " f"{shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"{shlex.quote(self._REMOTE_CHECKS.as_posix())} && " f"mkdir -p {shlex.quote((self._REMOTE_STATEM_SRC / 'statem').as_posix())} " f"{shlex.quote(self._REMOTE_RUNBOOK_DIR.as_posix())} " f"{shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"{shlex.quote(self._REMOTE_CHECKS.as_posix())} && " f"chmod -R 777 {shlex.quote(self._REMOTE_STATEM_SRC.as_posix())} " f"{shlex.quote(self._REMOTE_RUNBOOK_DIR.as_posix())} " f"{shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"{shlex.quote(self._REMOTE_CHECKS.as_posix())}" ), ) for name in self._PUBLIC_STATEM_FILES: await environment.upload_file( self._statem_source_dir / "statem" / name, (self._REMOTE_STATEM_SRC / "statem" / name).as_posix(), ) for local_path, remote_path in ( (self._runbook_path, self._REMOTE_RUNBOOK), (self._helper_path, self._REMOTE_HELPER), (self._stop_hook_path, self._REMOTE_STOP_HOOK), (self._adapter_path, self._REMOTE_ADAPTER), ): await environment.upload_file(local_path, remote_path.as_posix()) manifest = self._build_source_manifest() self._source_manifest = manifest await self._write_remote_text( environment, (self._REMOTE_CHECKS / "source-manifest.json").as_posix(), json.dumps(manifest, indent=2, sort_keys=True) + "\n", ) await self.exec_as_root( environment, command=( "cat >/usr/local/bin/statem <<'SH'\n" "#!/bin/sh\n" f"PYTHONPATH={shlex.quote(self._REMOTE_STATEM_SRC.as_posix())} " "exec python3 -m statem.cli \"$@\"\n" "SH\n" "chmod +x /usr/local/bin/statem\n" f"statem validate {shlex.quote(self._REMOTE_RUNBOOK.as_posix())} " "--json >/tmp/statem-family-validate.json" ), ) def _build_source_manifest(self) -> dict[str, Any]: entries: list[dict[str, Any]] = [] for name in self._PUBLIC_STATEM_FILES: local = self._statem_source_dir / "statem" / name entries.append( self._manifest_entry( "statem", local, self._REMOTE_STATEM_SRC / "statem" / name, ) ) entries.extend( [ self._manifest_entry("runbook", self._runbook_path, self._REMOTE_RUNBOOK), self._manifest_entry("family_helper", self._helper_path, self._REMOTE_HELPER), self._manifest_entry("stop_hook", self._stop_hook_path, self._REMOTE_STOP_HOOK), self._manifest_entry("family_adapter", self._adapter_path, self._REMOTE_ADAPTER), ] ) payload: dict[str, Any] = { "version": 1, "agent": self.name(), "family": FAMILY_METADATA, "runbook": self._local_relative(self._runbook_path), "file_count": len(entries), "files": entries, } encoded = json.dumps(payload, sort_keys=True, separators=(",", ":")).encode("utf-8") payload["manifest_sha256"] = hashlib.sha256(encoded).hexdigest() return payload def _manifest_entry( self, group: str, path: Path, remote_path: PurePosixPath, ) -> dict[str, Any]: return { "group": group, "local_relative_path": self._local_relative(path), "remote_path": remote_path.as_posix(), "size_bytes": path.stat().st_size, "sha256": hashlib.sha256(path.read_bytes()).hexdigest(), } def _local_relative(self, path: Path) -> str: try: return path.relative_to(self._statem_source_dir).as_posix() except ValueError: return path.name async def _write_remote_text( self, environment: BaseEnvironment, remote_path: str, text: str, ) -> None: encoded = base64.b64encode(text.encode("utf-8")).decode("ascii") await self.exec_as_root( environment, command=( "python3 -c " + shlex.quote( "import base64, pathlib; " f"pathlib.Path({remote_path!r}).write_bytes(base64.b64decode({encoded!r}))" ) ), ) def _run_id(self, environment: BaseEnvironment) -> str: raw = f"{self._run_id_prefix}-{environment.session_id}" return re.sub(r"[^A-Za-z0-9_.-]+", "-", raw).strip("-") or self._run_id_prefix def _statem_env(self, run_id: str) -> dict[str, str]: return { "STATEM_STATE_DIR": self._REMOTE_STATE_DIR.as_posix(), "STATEM_AGENT_ID": self.name(), "STATEM_AGENT_ROLE": "benchmark-agent", "STATEM_RUN_ID": run_id, "STATEM_DEADLINE_FILE": (self._REMOTE_CHECKS / "deadline.json").as_posix(), } async def _write_task_and_deadline( self, environment: BaseEnvironment, run_id: str, instruction: str, ) -> None: await self._write_remote_text( environment, (self._REMOTE_CHECKS / "task.txt").as_posix(), instruction, ) started = time.time() deadline = { "version": 1, "source": "git_webserver_deploy_family_adapter", "run_id": run_id, "started_at_epoch": started, "deadline_at_epoch": started + self._agent_deadline_seconds, "agent_deadline_seconds": self._agent_deadline_seconds, "handoff_buffer_seconds": self._handoff_buffer_seconds, "heavy_work_buffer_seconds": self._heavy_work_buffer_seconds, } await self._write_remote_text( environment, (self._REMOTE_CHECKS / "deadline.json").as_posix(), json.dumps(deadline, indent=2, sort_keys=True) + "\n", ) async def _start_statem(self, environment: BaseEnvironment, run_id: str) -> None: result = await self.exec_as_agent( environment, command=( f"statem start {shlex.quote(self._REMOTE_RUNBOOK.as_posix())} " f"--state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"--run-id {shlex.quote(run_id)} " f"--agent-id {shlex.quote(self.name())} " "--agent-role benchmark-agent" ), env=self._statem_env(run_id), ) return_code = getattr( result, "return_code", getattr(result, "returncode", 0), ) if return_code not in (None, 0): raise RuntimeError(f"could not start StateM family run: {result.stderr}") async def _current_context(self, environment: BaseEnvironment, run_id: str) -> str: result = await self.exec_as_agent( environment, command=( "statem cur " f"--state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"--run-id {shlex.quote(run_id)} --json" ), env=self._statem_env(run_id), ) return (result.stdout or "").strip() def _augment_instruction( self, instruction: str, run_id: str, current_context: str, ) -> str: state_dir = self._REMOTE_STATE_DIR.as_posix() return f"""You are {self.name()}, a Codex agent using one executable StateM task-family runbook. Required StateM protocol: - Inspect the current state before substantive work with: `statem cur --state-dir {state_dir} --run-id {run_id}` - Follow the current state's prompt and hooks. Inspect the graph with: `statem state --state-dir {state_dir} --run-id {run_id}` - Move only through explicit transitions with `statem goto TARGET --state-dir {state_dir} --run-id {run_id}`. - Use `--yes` only after satisfying a transition's checklist and machine checks. - If a transition fails, remain in the current state, repair the recorded issue, and retry it. - Keep progress.md current with the visible contract, candidate identity, checks, and residual risk. - The graph is `direct_solve -> task_contract_check -> self_review`, followed by a selected `family_evidence_check`, targeted `repair`, ordinary non-match `handoff`, or explicit `deadline_handoff`. There is no broad catalog or unrelated family route. - Solve normally before self_review. Only the immutable task-visible selector may expose the git_webserver_deploy reviewer practice. A selected task normally requires the fixed stateful gate receipt before handoff; do not replace it with proxy evidence or rerun it at final handoff. - Do not inspect benchmark answers, hidden tests, verifier internals, credentials, or unrelated files. Current StateM state: {current_context} Benchmark task: {instruction} """ def _codex_stop_hook_payload(self) -> dict[str, Any]: command = ( f"STATEM_STATE_DIR={shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " "STATEM_COMMAND=statem STATEM_HOST=codex " f"python3 {shlex.quote(self._REMOTE_STOP_HOOK.as_posix())}" ) return { "hooks": { "Stop": [ { "hooks": [ { "type": "command", "command": command, "timeout": 15, "statusMessage": "Checking active StateM run", } ] } ] } } async def _install_codex_stop_hook(self, environment: BaseEnvironment) -> None: await self.exec_as_agent( environment, command=f"mkdir -p {shlex.quote(self._REMOTE_CODEX_HOME.as_posix())}", env={"CODEX_HOME": self._REMOTE_CODEX_HOME.as_posix()}, ) await self._write_remote_text( environment, (self._REMOTE_CODEX_HOME / "hooks.json").as_posix(), json.dumps(self._codex_stop_hook_payload(), indent=2, sort_keys=True) + "\n", ) async def _effective_agent_user(self, environment: BaseEnvironment) -> str | int: if environment.default_user is not None: return environment.default_user result = await self.exec_as_agent(environment, command="id -u") user = (result.stdout or "").strip() if not user.isdigit(): raise RuntimeError(f"could not resolve container agent uid: {user!r}") return int(user) async def run( self, instruction: str, environment: BaseEnvironment, context: AgentContext, ) -> None: run_id = self._run_id(environment) await self._write_task_and_deadline(environment, run_id, instruction) await self._start_statem(environment, run_id) current_context = await self._current_context(environment, run_id) augmented = self._augment_instruction(instruction, run_id, current_context) await self._install_codex_stop_hook(environment) try: if environment.default_user is None: effective_user = await self._effective_agent_user(environment) with environment.with_default_user(effective_user): await super().run(augmented, environment, context) else: await super().run(augmented, environment, context) finally: try: Codex.populate_context_post_run(self, context) finally: await self._remove_session_logs(environment) await self._collect_family_artifacts(environment, context, run_id) async def _remove_session_logs(self, environment: BaseEnvironment) -> None: try: await self.exec_as_agent( environment, command=( f"rm -rf {shlex.quote((EnvironmentPaths.agent_dir / 'sessions').as_posix())}" ), ) except Exception: return async def _collect_family_artifacts( self, environment: BaseEnvironment, context: AgentContext, run_id: str, ) -> None: current: dict[str, Any] | None = None try: current_raw = await self._current_context(environment, run_id) current = json.loads(current_raw) except (OSError, json.JSONDecodeError, TypeError, ValueError): current = None agent_statem = (EnvironmentPaths.agent_dir / "statem").as_posix() copy_names = ( "git-webserver-selection.json", "task-contract-receipt.json", "self-review.json", "git-webserver-receipt.json", "task.txt", "deadline.json", "source-manifest.json", ) commands = [f"mkdir -p {shlex.quote(agent_statem)}"] commands.extend( f"cp {shlex.quote((self._REMOTE_CHECKS / name).as_posix())} " f"{shlex.quote(f'{agent_statem}/{name}')} || true" for name in copy_names ) commands.extend( [ f"statem cur --state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"--run-id {shlex.quote(run_id)} --json >" f"{shlex.quote(f'{agent_statem}/current.json')} || true", f"statem history --state-dir {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"--run-id {shlex.quote(run_id)} --limit 100 --json >" f"{shlex.quote(f'{agent_statem}/history.json')} || true", f"cp -R {shlex.quote(self._REMOTE_STATE_DIR.as_posix())} " f"{shlex.quote(f'{agent_statem}/state')} || true", ] ) await self.exec_as_agent( environment, command="\n".join(commands), env=self._statem_env(run_id), ) context.metadata = dict(context.metadata or {}) context.metadata["statem"] = { "run_id": run_id, "agent": self.name(), "family": FAMILY_METADATA, "current": current.get("current") if current else None, "current_entry_id": current.get("current_entry_id") if current else None, "source_manifest_sha256": ( self._source_manifest.get("manifest_sha256") if self._source_manifest else None ), "family_artifacts": list(copy_names), } if self._enforce_final_state and ( not current or current.get("current") != self._final_state ): raise RuntimeError( f"statem final state is {(current or {}).get('current')!r}, " f"expected {self._final_state!r}" ) class DeepSeekGitWebserverDeployFamilyStatemCodex( GitWebserverDeployFamilyStatemCodex ): """Self-contained family adapter with DeepSeek's official Codex config.""" _EXPECTED_MODEL = "deepseek-v4-flash" def __init__( self, *args: Any, deepseek_config_home: str | None = None, **kwargs: Any, ) -> None: config_home = deepseek_config_home or os.environ.get( "DEEPSEEK_CODEX_CONFIG_HOME", "" ) if not config_home: raise ValueError( "deepseek_config_home or DEEPSEEK_CODEX_CONFIG_HOME is required" ) self._deepseek_config_home = Path(config_home).expanduser().resolve() self._deepseek_config = self._deepseek_config_home / "config.toml" self._deepseek_models = self._deepseek_config_home / "models.json" self._validate_deepseek_config() super().__init__(*args, **kwargs) @staticmethod def name() -> str: return "statem-deepseek-git-webserver-deploy-family" def _validate_deepseek_config(self) -> None: if not self._deepseek_config.is_file() or not self._deepseek_models.is_file(): raise FileNotFoundError( "DeepSeek Codex config home must contain config.toml and models.json" ) models = json.loads(self._deepseek_models.read_text(encoding="utf-8")) slugs = { str(item.get("slug")) for item in models.get("models", []) if isinstance(item, dict) } if self._EXPECTED_MODEL not in slugs: raise ValueError(f"DeepSeek model catalog is missing {self._EXPECTED_MODEL}") config_text = self._deepseek_config.read_text(encoding="utf-8") required_fragments = ( 'model_provider = "deepseek"', 'base_url = "https://api.deepseek.com/"', 'wire_api = "responses"', "experimental_bearer_token", ) if any(fragment not in config_text for fragment in required_fragments): raise ValueError("DeepSeek config.toml is not an official provider config") @classmethod def _container_config_text(cls, source: str) -> str: catalog_path = cls._REMOTE_CODEX_HOME / "models.json" replacement = f'model_catalog_json = "{catalog_path}"' rendered, count = re.subn( r"(?m)^\s*model_catalog_json\s*=\s*[^\n]+$", replacement, source, count=1, ) if count != 1: raise ValueError("DeepSeek config.toml must contain one model_catalog_json") return rendered async def _stage_deepseek_config(self, environment: BaseEnvironment) -> None: remote_home = self._REMOTE_CODEX_HOME.as_posix() await self.exec_as_agent( environment, command=f"mkdir -p {shlex.quote(remote_home)} && chmod 700 {shlex.quote(remote_home)}", ) rendered = self._container_config_text( self._deepseek_config.read_text(encoding="utf-8") ) temporary_name = "" try: with tempfile.NamedTemporaryFile( mode="w", encoding="utf-8", prefix="statem-deepseek-family-", suffix=".toml", delete=False, ) as handle: temporary_name = handle.name handle.write(rendered) os.chmod(temporary_name, 0o600) await environment.upload_file( Path(temporary_name), (self._REMOTE_CODEX_HOME / "config.toml").as_posix(), ) await environment.upload_file( self._deepseek_models, (self._REMOTE_CODEX_HOME / "models.json").as_posix(), ) if environment.default_user is not None: await self.exec_as_root( environment, command=( f"chown {environment.default_user} " f"{remote_home}/config.toml {remote_home}/models.json && " f"chmod 600 {remote_home}/config.toml {remote_home}/models.json" ), ) finally: if temporary_name: Path(temporary_name).unlink(missing_ok=True) async def run( self, instruction: str, environment: BaseEnvironment, context: AgentContext, ) -> None: await self._stage_deepseek_config(environment) await super().run(instruction, environment, context) # ===== file: integrations/hooks/statem_stop_hook.py ===== #!/usr/bin/env python3 """Host Stop hook adapter for statem-managed runs. Works with hosts whose Stop hook supports `{"decision": "block", "reason": ...}` continuations, including Codex and Claude Code. This script intentionally does not advance statem state. It only nudges the agent to inspect statem and keep working when a run is active. """ from __future__ import annotations import json import os import shlex import subprocess import sys from pathlib import Path from typing import Any DEFAULT_STOP_STATES = {"handoff", "done", "complete", "completed", "finished"} def main() -> int: payload = _read_payload() if payload.get("stop_hook_active") is True: return _allow() cwd = Path(str(payload.get("cwd") or os.getcwd())).expanduser().resolve() state_dir = Path(os.environ.get("STATEM_STATE_DIR", cwd / ".statem")).expanduser() if not state_dir.is_absolute(): state_dir = (cwd / state_dir).resolve() if not (state_dir / "active_run").exists(): return _allow() statem_cmd = os.environ.get("STATEM_COMMAND", f"{sys.executable} -m statem") cur = _run_statem_json(statem_cmd, cwd, state_dir, "cur") if cur is None: return _allow( system_message="statem Stop hook found an active run but could not read it; allowing stop." ) current = str(cur.get("current") or "") stop_states = _stop_states() next_states = cur.get("next") or [] if current in stop_states or not next_states: return _allow() reason = _continuation_reason(statem_cmd, state_dir, current, next_states) return _continue(reason) def _read_payload() -> dict[str, Any]: try: raw = sys.stdin.read() return json.loads(raw) if raw.strip() else {} except json.JSONDecodeError: return {} def _stop_states() -> set[str]: raw = os.environ.get("STATEM_AUTOLOOP_STOP_STATES") if not raw: return DEFAULT_STOP_STATES return {part.strip() for part in raw.split(",") if part.strip()} def _run_statem_json(statem_cmd: str, cwd: Path, state_dir: Path, command: str) -> dict[str, Any] | None: try: argv = [*shlex.split(statem_cmd), command, "--state-dir", str(state_dir), "--json"] completed = subprocess.run( argv, cwd=cwd, text=True, capture_output=True, check=False, timeout=10, ) except (OSError, ValueError, subprocess.TimeoutExpired): return None if completed.returncode != 0: return None try: return json.loads(completed.stdout) except json.JSONDecodeError: return None def _continuation_reason(statem_cmd: str, state_dir: Path, current: str, next_states: list[Any]) -> str: next_names = ", ".join(str(edge.get("to")) for edge in next_states if isinstance(edge, dict)) or "(none)" return "\n".join( [ "Continue the active statem-managed run instead of stopping.", "", "First inspect durable state:", f"{statem_cmd} cur --state-dir {sh_quote(str(state_dir))} --json", f"{statem_cmd} next --state-dir {sh_quote(str(state_dir))} --json", "", f"Current state: {current}", f"Allowed next states: {next_names}", "", "Follow the current node prompt. Move only with `statem goto `.", "If the current node requires user input or is ready for handoff, explain that and stop.", ] ) def _allow(*, system_message: str | None = None) -> int: if system_message: print(json.dumps({"systemMessage": system_message})) return 0 def _continue(reason: str) -> int: print(json.dumps({"decision": "block", "reason": reason})) return 0 def sh_quote(value: str) -> str: return "'" + value.replace("'", "'\"'\"'") + "'" if __name__ == "__main__": raise SystemExit(main()) # ===== file: statem/__init__.py ===== """Command line state machine for agent long runs.""" __version__ = "0.1.0" # ===== file: statem/__main__.py ===== from .cli import main if __name__ == "__main__": raise SystemExit(main()) # ===== file: statem/cli.py ===== from __future__ import annotations import argparse import json import os import sys from pathlib import Path from typing import Any from .core import RunOptions, StatemError, StatemRuntime, validate_spec def main(argv: list[str] | None = None) -> int: parser = _build_parser() args = parser.parse_args(argv) if not hasattr(args, "handler"): parser.print_help() return 1 options = RunOptions( state_dir=Path(args.state_dir), yes=bool(args.yes), json_mode=bool(args.json), run_id=args.run_id, agent_id=args.agent_id, agent_role=args.agent_role, ) try: payload = args.handler(args, options) except StatemError as exc: if getattr(args, "json", False): error_payload: dict[str, Any] = {"ok": False, "error": str(exc)} if exc.details: error_payload["details"] = exc.details print(json.dumps(error_payload, indent=2, sort_keys=True)) else: print(f"statem: {exc}", file=sys.stderr) return getattr(exc, "exit_code", 1) if args.json: print(json.dumps(payload, indent=2, sort_keys=True)) else: _print_payload(args.command, payload) return 0 def _build_parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser( prog="statem", description="Command line state machine for agent long runs.", epilog=( "Loop hygiene: for cyclic runbooks, model compaction as an explicit node " "and use 'statem compact-prompt' to generate a safe /compact instruction." ), ) subparsers = parser.add_subparsers(dest="command") common = argparse.ArgumentParser(add_help=False) common.add_argument( "--state-dir", default=os.environ.get("STATEM_STATE_DIR", ".statem"), help="runtime state directory (default: $STATEM_STATE_DIR or .statem)", ) common.add_argument("--run-id", help="run id to use instead of the active run") common.add_argument("--agent-id", default=os.environ.get("STATEM_AGENT_ID"), help="agent instance id for dynamic checks") common.add_argument("--agent-role", default=os.environ.get("STATEM_AGENT_ROLE"), help="agent role metadata for dynamic checks") common.add_argument("--yes", action="store_true", help="auto-confirm manual checks and checklists") common.add_argument("--json", action="store_true", help="emit machine-readable JSON") start = subparsers.add_parser("start", parents=[common], help="create or resume a run from a spec") start.add_argument("spec", help="spec file") start.add_argument("--fresh", action="store_true", help="force a new run even if an active run exists") start.set_defaults(handler=_cmd_start) cur = subparsers.add_parser("cur", parents=[common], help="show current state") cur.set_defaults(handler=_cmd_cur) state = subparsers.add_parser("state", parents=[common], help="list states and edges") state.set_defaults(handler=_cmd_state) show = subparsers.add_parser("ls", parents=[common], help="show node details") show.add_argument("node") show.set_defaults(handler=_cmd_ls) next_cmd = subparsers.add_parser("next", parents=[common], help="show next states") next_cmd.set_defaults(handler=_cmd_next) goto = subparsers.add_parser("goto", parents=[common], help="move to a next state") goto.add_argument("target") goto.set_defaults(handler=_cmd_goto) transfer = subparsers.add_parser("transfer", parents=[common], help="alias for goto") transfer.add_argument("target") transfer.set_defaults(handler=_cmd_goto) save = subparsers.add_parser("save", parents=[common], help="persist state and run current out_hook") save.add_argument("--skip-hooks", action="store_true", help="persist runtime state without running out_hook") save.set_defaults(handler=_cmd_save) history = subparsers.add_parser("history", parents=[common], help="show run history") history.add_argument("--limit", "--tail", dest="limit", type=int, help="show only the last N events") history.set_defaults(handler=_cmd_history) prompt = subparsers.add_parser("prompt", parents=[common], help="print a post-clear resume prompt") prompt.add_argument( "--command", dest="statem_command", default="statem", help="statem command to embed in the prompt", ) prompt.set_defaults(handler=_cmd_prompt) compact_prompt = subparsers.add_parser( "compact-prompt", parents=[common], help="print a safe /compact prompt for loop hygiene", ) compact_prompt.add_argument( "--command", dest="statem_command", default="statem", help="statem command to embed in the prompt", ) compact_prompt.set_defaults(handler=_cmd_compact_prompt) validate = subparsers.add_parser("validate", parents=[common], help="validate a spec") validate.add_argument("spec") validate.add_argument( "--strict", action="store_true", help="reject unknown runbook keywords at every supported schema level", ) validate.set_defaults(handler=_cmd_validate) dynamic = subparsers.add_parser("dynamic", parents=[common], help="manage current-entry dynamic checks") dynamic_subparsers = dynamic.add_subparsers(dest="dynamic_command") dynamic_path = dynamic_subparsers.add_parser("path", parents=[common], help="show dynamic check directory") dynamic_path.set_defaults(handler=_cmd_dynamic_path) dynamic_write = dynamic_subparsers.add_parser("write", parents=[common], help="write checks for this agent") dynamic_write.add_argument("checks_file", help="JSON or mini-YAML dynamic checks file") dynamic_write.add_argument("--role", help="producer role metadata") dynamic_write.set_defaults(handler=_cmd_dynamic_write) dynamic_list = dynamic_subparsers.add_parser("list", parents=[common], help="list current dynamic check producers") dynamic_list.set_defaults(handler=_cmd_dynamic_list) dynamic_show = dynamic_subparsers.add_parser("show", parents=[common], help="alias for dynamic list") dynamic_show.set_defaults(handler=_cmd_dynamic_list) return parser def _cmd_start(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).start(args.spec, fresh=args.fresh) def _cmd_cur(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).cur() def _cmd_state(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).graph_state() def _cmd_ls(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).node_details(args.node) def _cmd_next(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).next_states() def _cmd_goto(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).goto(args.target) def _cmd_save(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).save(skip_hooks=args.skip_hooks) def _cmd_history(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).history(limit=args.limit) def _cmd_prompt(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).prompt(command=args.statem_command) def _cmd_compact_prompt(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).compact_prompt(command=args.statem_command) def _cmd_validate(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return validate_spec(args.spec, strict=args.strict) def _cmd_dynamic_path(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).dynamic_path() def _cmd_dynamic_write(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).dynamic_write(args.checks_file, agent_id=args.agent_id, role=args.role) def _cmd_dynamic_list(args: argparse.Namespace, options: RunOptions) -> dict[str, Any]: return StatemRuntime(options).dynamic_list() def _print_payload(command: str, payload: dict[str, Any]) -> None: if command in {"start", "cur"}: _print_cur(payload) elif command == "state": _print_state(payload) elif command == "ls": _print_node(payload) elif command == "next": _print_next(payload) elif command in {"goto", "transfer"}: _print_goto(payload) elif command == "save": _print_save(payload) elif command == "history": _print_history(payload) elif command in {"prompt", "compact-prompt"}: print(payload["prompt"], end="") elif command == "validate": _print_validate(payload) elif command == "dynamic": _print_dynamic(payload) else: print(json.dumps(payload, indent=2, sort_keys=True)) def _print_cur(payload: dict[str, Any]) -> None: print(f"Run: {payload['run_id']}") print(f"Spec: {payload['spec_name']} ({payload['spec']})") print(f"Current: {payload['current']}") if payload.get("current_entry_id"): print(f"Entry: {payload['current_entry_id']}") if payload.get("dynamic_before_transfer"): dynamic = payload["dynamic_before_transfer"] print(f"Dynamic checks: {dynamic.get('resolved_path') or dynamic.get('path')}") if payload.get("prompt"): print("\nPrompt:") print(payload["prompt"]) if payload.get("before_transfer"): print("\nBefore transfer:") for item in payload["before_transfer"]: print(f"- {_summary_text(item)}") _print_next({"next": payload.get("next", [])}) def _print_state(payload: dict[str, Any]) -> None: print(f"Run: {payload['run_id']}") print(f"Current: {payload['current']}") print("\nStates:") for node in payload["nodes"]: marker = "*" if node["name"] == payload["current"] else "-" print(f"{marker} {node['name']}") print("\nEdges:") for edge in payload["edges"]: print(f"- {edge['from']} -> {edge['to']}") def _print_node(payload: dict[str, Any]) -> None: current_marker = " (current)" if payload["node"] == payload["current"] else "" print(f"Node: {payload['node']}{current_marker}") if payload.get("prompt"): print("\nPrompt:") print(payload["prompt"]) for key, title in [("in_hook", "In hook"), ("before_transfer", "Before transfer"), ("out_hook", "Out hook")]: if payload.get(key): print(f"\n{title}:") for item in payload[key]: print(f"- {_summary_text(item)}") if payload.get("dynamic_before_transfer"): dynamic = payload["dynamic_before_transfer"] print("\nDynamic before transfer:") print(f"- path: {dynamic.get('resolved_path') or dynamic.get('path')}") print(f"- allow_types: {', '.join(dynamic.get('allow_types', []))}") _print_next({"next": payload.get("next", [])}) def _print_next(payload: dict[str, Any]) -> None: print("\nNext:") if not payload.get("next"): print("- (none)") return for edge in payload["next"]: condition = "" if edge.get("condition"): condition = " | condition: " + "; ".join(_summary_text(item) for item in edge["condition"]) attempts = f" | max_attempts: {edge['max_attempts']}" if "max_attempts" in edge else "" print(f"- {edge['to']}{attempts}{condition}") def _print_goto(payload: dict[str, Any]) -> None: print(f"Moved: {payload['from']} -> {payload['to']}") _print_results(payload.get("results", [])) def _print_save(payload: dict[str, Any]) -> None: print(f"Saved run {payload['run_id']} at {payload['current']}") _print_results(payload.get("results", [])) def _print_history(payload: dict[str, Any]) -> None: print(f"Run: {payload['run_id']}") print(f"Current: {payload['current']}") for event in payload.get("history", []): if event["event"] == "goto": detail = f"{event.get('from')} -> {event.get('to')}" elif event["event"] in {"goto_blocked", "save", "save_blocked"}: detail = event.get("stage") or event.get("node") or "" else: detail = event.get("current") or event.get("node") or "" print(f"- {event['ts']} {event['event']} {detail}".rstrip()) def _print_validate(payload: dict[str, Any]) -> None: print(f"Valid spec: {payload['name']}") if payload.get("strict"): print("Strict keywords: yes") print(f"Initial: {payload['initial']}") print(f"Nodes: {', '.join(payload['nodes'])}") print(f"Edges: {len(payload['edges'])}") def _print_dynamic(payload: dict[str, Any]) -> None: print(f"Run: {payload['run_id']}") print(f"Current: {payload['current']}") print(f"Entry: {payload.get('current_entry_id')}") if payload.get("agent_id"): print(f"Agent: {payload['agent_id']}") if payload.get("path"): print(f"Path: {payload['path']}") if "checks" in payload: print(f"Checks: {payload['checks']}") for producer in payload.get("producers", []): details = producer.get("producer", {}) label = details.get("agent_id") or producer.get("path") print(f"- {label}: {producer.get('checks', 0)} check(s)") def _print_results(results: list[dict[str, Any]]) -> None: interesting = [result for result in results if not result["passed"] or result.get("continued")] if not interesting: return print("\nChecks:") for result in interesting: status = "continued" if result.get("continued") else "failed" print(f"- {result['purpose']} {result['type']} {status}: {result.get('output', '')}") def _summary_text(item: dict[str, Any]) -> str: item_type = item.get("type") if item_type == "command": return f"command: {item.get('run')}" if item_type == "llm_review": command = item.get("run") or "$STATEM_LLM_REVIEW_CMD" return f"llm_review: {item.get('prompt')} via {command}" if item_type == "predicate": bits = [f"predicate: {item.get('path')}"] for key in ("exists", "non_empty", "contains", "matches", "json_path", "equals"): if key in item: bits.append(f"{key}={item[key]!r}") return ", ".join(bits) if item_type == "checklist": return "checklist: " + ", ".join(str(value) for value in item.get("items", [])) return f"{item_type}: {item.get('text')}" if __name__ == "__main__": raise SystemExit(main()) # ===== file: statem/core.py ===== from __future__ import annotations import difflib import hashlib import json import os import re import shlex import subprocess import sys import time import uuid from dataclasses import dataclass from pathlib import Path from typing import Any from . import miniyaml class StatemError(Exception): exit_code = 1 def __init__(self, message: str, *, details: dict[str, Any] | None = None) -> None: super().__init__(message) self.details = details or {} class TransitionBlocked(StatemError): exit_code = 2 DYNAMIC_PURPOSE = "dynamic_before_transfer" GATING_PURPOSES = {"condition", "before_transfer", DYNAMIC_PURPOSE} HOOK_KEYS = {"in_hook", "before_transfer", "out_hook", "condition", "hook"} CHECK_TYPES = {"message", "manual", "checklist", "command", "predicate", "llm_review"} STRICT_ROOT_KEYS = {"name", "initial", "start", "nodes", "edges"} STRICT_NODE_KEYS = { "name", "prompt", "pre_request", "pre-request", "next", "next_states", "in_hook", "before_transfer", DYNAMIC_PURPOSE, "out_hook", } STRICT_EDGE_KEYS = { "from", "source", "node1", "to", "target", "node2", "condition", "hook", "max_attempts", } STRICT_NESTED_EDGE_KEYS = {"to", "target", "name", "condition", "hook", "max_attempts"} STRICT_DYNAMIC_CONFIG_KEYS = { "path", "required", "min_items", "require_reason", "require_basis", "merge", "refresh", "stale_policy", "allow_types", } STRICT_CHECK_COMMON_KEYS = {"type", "blocking", "on_failure"} STRICT_CHECK_KEYS = { "message": STRICT_CHECK_COMMON_KEYS | {"text", "prompt"}, "manual": STRICT_CHECK_COMMON_KEYS | {"prompt", "text", "name", "confirmation", "confirm"}, "checklist": STRICT_CHECK_COMMON_KEYS | {"items", "checks", "confirmation", "confirm"}, "command": STRICT_CHECK_COMMON_KEYS | {"run", "cmd", "command", "timeout", "cwd"}, "predicate": STRICT_CHECK_COMMON_KEYS | { "path", "cwd", "exists", "non_empty", "contains", "not_contains", "matches", "json_path", "equals", "one_of", }, "llm_review": STRICT_CHECK_COMMON_KEYS | { "run", "cmd", "command", "prompt", "text", "name", "timeout", "cwd", "stdin", "accept_contains", "reject_contains", "accept_regex", "reject_regex", }, } @dataclass class RunOptions: state_dir: Path yes: bool = False json_mode: bool = False run_id: str | None = None agent_id: str | None = None agent_role: str | None = None def emit(self, message: str) -> None: if message and not self.json_mode: print(message) @dataclass class StatemSpec: path: Path raw: dict[str, Any] name: str initial: str nodes: dict[str, dict[str, Any]] edges: list[dict[str, Any]] outgoing: dict[str, list[dict[str, Any]]] spec_hash: str @classmethod def load(cls, path: str | os.PathLike[str], *, strict: bool = False) -> "StatemSpec": spec_path = Path(path).expanduser().resolve() if not spec_path.exists(): raise StatemError(f"Spec file not found: {spec_path}") text = spec_path.read_text(encoding="utf-8") raw = _load_mapping(text, spec_path) if strict: strict_errors = _strict_keyword_errors(raw) if strict_errors: raise StatemError("Invalid spec:\n" + "\n".join(f"- {error}" for error in strict_errors)) name = str(raw.get("name") or spec_path.stem) nodes = _normalize_nodes(raw.get("nodes")) if not nodes: raise StatemError("Spec must define at least one node") initial = str(raw.get("initial") or raw.get("start") or next(iter(nodes))) edges = _normalize_edges(raw, nodes) outgoing: dict[str, list[dict[str, Any]]] = {name: [] for name in nodes} for edge in edges: outgoing.setdefault(edge["from"], []).append(edge) spec = cls( path=spec_path, raw=raw, name=name, initial=initial, nodes=nodes, edges=edges, outgoing=outgoing, spec_hash=_sha256_text(text), ) errors = spec.validation_errors() if errors: raise StatemError("Invalid spec:\n" + "\n".join(f"- {error}" for error in errors)) return spec def validation_errors(self) -> list[str]: errors: list[str] = [] if self.initial not in self.nodes: errors.append(f"initial node '{self.initial}' is not defined") seen_edges: set[tuple[str, str]] = set() for index, edge in enumerate(self.edges, start=1): source = edge.get("from") target = edge.get("to") if source not in self.nodes: errors.append(f"edge {index} source '{source}' is not a node") if target not in self.nodes: errors.append(f"edge {index} target '{target}' is not a node") edge_key = (str(source), str(target)) if edge_key in seen_edges: errors.append(f"duplicate edge '{source}' -> '{target}' makes goto ambiguous") seen_edges.add(edge_key) errors.extend(_validate_edge_max_attempts(edge, f"edge {source}->{target}")) errors.extend(_validate_items(edge.get("condition"), "condition", f"edge {source}->{target} condition")) errors.extend(_validate_items(edge.get("hook"), "hook", f"edge {source}->{target} hook")) for name, node in self.nodes.items(): errors.extend(_validate_items(node.get("in_hook"), "in_hook", f"node {name} in_hook")) errors.extend(_validate_items(node.get("before_transfer"), "before_transfer", f"node {name} before_transfer")) errors.extend(_validate_items(node.get("out_hook"), "out_hook", f"node {name} out_hook")) errors.extend(_validate_dynamic_config(node.get(DYNAMIC_PURPOSE), f"node {name} {DYNAMIC_PURPOSE}")) return errors def node_prompt(self, name: str) -> str: node = self.nodes[name] return str(node.get("prompt") or node.get("pre_request") or node.get("pre-request") or "") def edge_to(self, source: str, target: str) -> dict[str, Any] | None: matches = [edge for edge in self.outgoing.get(source, []) if edge.get("to") == target] if not matches: return None return matches[0] class StatemRuntime: def __init__(self, options: RunOptions) -> None: self.options = options self.state_dir = options.state_dir.expanduser().resolve() def start(self, spec_path: str, *, fresh: bool = False) -> dict[str, Any]: spec = StatemSpec.load(spec_path) self.state_dir.mkdir(parents=True, exist_ok=True) (self.state_dir / "runs").mkdir(parents=True, exist_ok=True) requested_run_id = _clean_run_id(self.options.run_id) if self.options.run_id else None run_id = requested_run_id if run_id is None and not fresh: run_id = self._active_run_for_spec(spec) if run_id is None: run_id = _new_run_id() state_path = self._state_path(run_id) is_new = fresh or not state_path.exists() if is_new: state = { "version": 1, "run_id": run_id, "spec_path": str(spec.path), "spec_hash": spec.spec_hash, "current": spec.initial, "current_entry_id": _new_entry_id(), "created_at": _now(), "updated_at": _now(), "history": [], } self._ensure_agent_identity(state) self._ensure_entry_manifest(spec, state, spec.initial) _append_event(state, "start", {"current": spec.initial, "spec": str(spec.path)}) else: state = _read_json(state_path) self._ensure_agent_identity(state) previous_current = str(state.get("current")) if previous_current not in spec.nodes: state["current"] = spec.initial state["current_entry_id"] = _new_entry_id() self._ensure_entry_manifest(spec, state, spec.initial) _append_event( state, "migrate_current", { "from": previous_current, "to": spec.initial, "reason": "current state missing from updated spec", }, ) state["spec_path"] = str(spec.path) state["spec_hash"] = spec.spec_hash self._ensure_current_entry(spec, state) _append_event(state, "resume", {"current": state["current"], "spec": str(spec.path)}) self._write_active(run_id) self._write_state(state) results = self._run_node_items(spec, state, str(state["current"]), "in_hook") _append_event( state, "in_hook", {"node": state["current"], "reason": "start" if is_new else "resume", "results": results}, ) self._write_state(state) _raise_if_blocked( results, f"Run '{run_id}' started, but in_hook failed for '{state['current']}'", details={ "run_id": run_id, "current": state["current"], "stage": "in_hook", "results": results, }, ) return self.cur(run_id=run_id) def cur(self, *, run_id: str | None = None) -> dict[str, Any]: spec, state = self._load_runtime(run_id) current = state["current"] return { "run_id": state["run_id"], "spec": str(spec.path), "spec_name": spec.name, "current": current, "current_entry_id": state.get("current_entry_id"), "agent_id": self._ensure_agent_identity(state), "dynamic_before_transfer": _dynamic_summary( spec.nodes[current].get(DYNAMIC_PURPOSE), self._dynamic_dir(state, current, str(state.get("current_entry_id"))), ), "prompt": spec.node_prompt(current), "before_