From 6dd4b4a77807a3e4e6a2ac7209c939d65b3a4493 Mon Sep 17 00:00:00 2001 From: Fredrick Campogni Date: Sun, 17 May 2026 20:52:19 -0400 Subject: [PATCH 1/3] feat(kanban): add runtime guardrails to decomposed tasks --- hermes_cli/config.py | 10 +++++++ hermes_cli/kanban_decompose.py | 30 ++++++++++++++++++- tests/hermes_cli/test_kanban_decompose.py | 36 +++++++++++++++++++++++ 3 files changed, 75 insertions(+), 1 deletion(-) diff --git a/hermes_cli/config.py b/hermes_cli/config.py index 9c4197c80fbc..b03bce767566 100644 --- a/hermes_cli/config.py +++ b/hermes_cli/config.py @@ -1554,6 +1554,16 @@ def _ensure_hermes_home_managed(home: Path): # large bulk-load of triage tasks from spending a burst of aux # LLM calls in one tick. Excess tasks defer to the next tick. "auto_decompose_per_tick": 3, + # Add a compact execution-safety footer to every decomposed child + # body. This makes auto-decomposed missions self-governing even + # when a worker profile does not have the full orchestrator skill + # loaded: preflight first, split broad work into lanes, defer heavy + # autonomy to approved overnight windows, and report only grounded + # status. Set runtime_guardrails.enabled=false to preserve raw + # decomposer output. + "runtime_guardrails": { + "enabled": True, + }, # Stale detection: running tasks that have exceeded this many # seconds without a heartbeat (since ``last_heartbeat_at``) are # auto-reclaimed to ``ready`` on the next dispatcher tick. The diff --git a/hermes_cli/kanban_decompose.py b/hermes_cli/kanban_decompose.py index 063abcf7b513..8ac3d0b8c2ba 100644 --- a/hermes_cli/kanban_decompose.py +++ b/hermes_cli/kanban_decompose.py @@ -268,6 +268,34 @@ def _normalize_assignee_choice( return chosen +_RUNTIME_GUARDRAILS = """Runtime guardrails: +- Runtime preflight: before state-changing work, verify repo/path, git state, required credentials, model/tool availability, and the exact command or file scope. +- If the task is too broad, decompose into scoped lanes before executing; keep independent lanes parallel and gate synthesis/review on parent results. +- Apply the overnight approval gate: do not start heavy, recurring, quota-expensive, or long-running autonomous work during daytime unless the user explicitly approved it for now. Prefer cheap/read-only checks or prepare an overnight plan. +- Report only grounded status from tool output; if blocked, name the missing prerequisite and the safest next action. +""".strip() + + +def _runtime_guardrails_enabled(cfg: dict) -> bool: + kanban_cfg = cfg.get("kanban", {}) if isinstance(cfg, dict) else {} + guard_cfg = kanban_cfg.get("runtime_guardrails", {}) if isinstance(kanban_cfg, dict) else {} + if isinstance(guard_cfg, dict) and "enabled" in guard_cfg: + return bool(guard_cfg.get("enabled")) + return True + + +def _append_runtime_guardrails(body: str, cfg: dict) -> str: + if not _runtime_guardrails_enabled(cfg): + return body + clean = body.strip() + if "Runtime preflight" in clean and "overnight approval gate" in clean: + return clean + if not clean: + return _RUNTIME_GUARDRAILS + return f"{clean}\n\n{_RUNTIME_GUARDRAILS}" + + + def decompose_task( task_id: str, *, @@ -433,7 +461,7 @@ def decompose_task( clean_parents = [p for p in parents if isinstance(p, int) and 0 <= p < len(raw_tasks) and p != idx] children.append({ "title": title.strip()[:200], - "body": body.strip(), + "body": _append_runtime_guardrails(body.strip(), cfg), "assignee": chosen, "parents": clean_parents, }) diff --git a/tests/hermes_cli/test_kanban_decompose.py b/tests/hermes_cli/test_kanban_decompose.py index 62937abba281..882dc25a780e 100644 --- a/tests/hermes_cli/test_kanban_decompose.py +++ b/tests/hermes_cli/test_kanban_decompose.py @@ -252,6 +252,42 @@ def test_decompose_fanout_false_invalid_llm_assignee_uses_default(kanban_home): assert task.assignee == "fallback" +def test_decompose_child_body_includes_runtime_guardrails(kanban_home): + with kb.connect() as conn: + tid = kb.create_task(conn, title="autonomous research", triage=True) + + llm_payload = jsonlib.dumps({ + "fanout": True, + "rationale": "test split", + "tasks": [ + {"title": "inspect", "body": "Check current state.", "assignee": "engineer", "parents": []}, + ], + }) + + patches = _patch_list_profiles(["orchestrator", "engineer"]) + for p in patches: + p.start() + try: + with _patch_aux_client(llm_payload), _patch_extra_body(), patch( + "hermes_cli.kanban_decompose._load_config", + return_value={"kanban": {"runtime_guardrails": {"enabled": True}}}, + ): + outcome = decomp.decompose_task(tid, author="me") + finally: + for p in patches: + p.stop() + + assert outcome.ok, outcome.reason + assert outcome.child_ids and len(outcome.child_ids) == 1 + with kb.connect() as conn: + child = kb.get_task(conn, outcome.child_ids[0]) + assert child is not None + body = child.body or "" + assert "Runtime preflight" in body + assert "overnight approval gate" in body + assert "decompose into scoped lanes" in body + + def test_decompose_unknown_assignee_falls_back_to_default(kanban_home): with kb.connect() as conn: tid = kb.create_task(conn, title="x", triage=True) From 49fc94cf183eee1879e8d71a50c251395c1837b5 Mon Sep 17 00:00:00 2001 From: Fredrick Campogni Date: Sun, 17 May 2026 21:06:51 -0400 Subject: [PATCH 2/3] feat(runtime): add kanban preflight command --- hermes_cli/main.py | 34 ++++++ hermes_cli/runtime_preflight.py | 131 +++++++++++++++++++++ tests/hermes_cli/test_runtime_preflight.py | 51 ++++++++ 3 files changed, 216 insertions(+) create mode 100644 hermes_cli/runtime_preflight.py create mode 100644 tests/hermes_cli/test_runtime_preflight.py diff --git a/hermes_cli/main.py b/hermes_cli/main.py index 4ae845d2e53d..cb514dc378a8 100644 --- a/hermes_cli/main.py +++ b/hermes_cli/main.py @@ -5747,6 +5747,13 @@ def cmd_kanban(args): return kanban_command(args) +def cmd_runtime(args): + """Runtime safety and health checks.""" + from hermes_cli.runtime_preflight import runtime_command + + runtime_command(args) + + def cmd_hooks(args): """Shell-hook inspection and management.""" from hermes_cli.hooks import hooks_command @@ -10742,6 +10749,33 @@ def main(): ) status_parser.set_defaults(func=cmd_status) + # ========================================================================= + # runtime command + # ========================================================================= + runtime_parser = subparsers.add_parser( + "runtime", + help="Runtime safety and health checks", + description="Run executable preflight checks before autonomous runtime work", + ) + runtime_subparsers = runtime_parser.add_subparsers(dest="runtime_action") + runtime_preflight = runtime_subparsers.add_parser( + "preflight", + help="Run preflight checks for an operational scope", + ) + runtime_preflight.add_argument( + "--scope", + choices=["kanban"], + default="kanban", + help="Operational scope to check (default: kanban)", + ) + runtime_preflight.add_argument( + "--json", + action="store_true", + help="Print machine-readable JSON output", + ) + runtime_parser.set_defaults(func=cmd_runtime) + runtime_preflight.set_defaults(func=cmd_runtime) + # ========================================================================= # cron command # ========================================================================= diff --git a/hermes_cli/runtime_preflight.py b/hermes_cli/runtime_preflight.py new file mode 100644 index 000000000000..f7c600d8710e --- /dev/null +++ b/hermes_cli/runtime_preflight.py @@ -0,0 +1,131 @@ +"""Executable runtime preflight checks for Hermes operational scopes.""" + +from __future__ import annotations + +import json as jsonlib +import os +from dataclasses import asdict, dataclass +from pathlib import Path +from typing import Any + +from hermes_cli.config import get_hermes_home, load_config + + +@dataclass +class PreflightCheck: + name: str + ok: bool + detail: str = "" + + +def _configured_model(config: dict[str, Any]) -> str: + model_cfg = config.get("model") + if isinstance(model_cfg, dict): + return str(model_cfg.get("default") or model_cfg.get("name") or "").strip() + return str(model_cfg or "").strip() + + +def _configured_provider(config: dict[str, Any]) -> str: + provider = str(config.get("provider") or "").strip() + if provider: + return provider + model_cfg = config.get("model") + if isinstance(model_cfg, dict): + return str(model_cfg.get("provider") or "").strip() + return "" + + +def _can_write_probe(directory: Path, label: str) -> PreflightCheck: + try: + directory.mkdir(parents=True, exist_ok=True) + probe = directory / ".hermes-preflight-write-test" + probe.write_text("ok\n", encoding="utf-8") + probe.unlink() + return PreflightCheck(label, True, str(directory)) + except Exception as exc: + return PreflightCheck(label, False, f"{directory}: {exc}") + + +def _guardrails_enabled(config: dict[str, Any]) -> bool: + kanban_cfg = config.get("kanban") if isinstance(config, dict) else None + guard_cfg = kanban_cfg.get("runtime_guardrails", {}) if isinstance(kanban_cfg, dict) else {} + return guard_cfg.get("enabled", True) is not False + + +def collect_kanban_preflight() -> list[PreflightCheck]: + """Collect executable checks needed before Kanban worker autonomy.""" + checks: list[PreflightCheck] = [] + + try: + config = load_config() or {} + checks.append(PreflightCheck("config load", True, "config.yaml loaded")) + except Exception as exc: + config = {} + checks.append(PreflightCheck("config load", False, str(exc))) + + provider = _configured_provider(config) + model = _configured_model(config) + checks.append( + PreflightCheck( + "provider/model", + bool(provider and model), + f"provider={provider or '(missing)'} model={model or '(missing)'}", + ) + ) + + checks.append( + PreflightCheck( + "kanban runtime guardrails", + _guardrails_enabled(config), + "kanban.runtime_guardrails.enabled must not be false", + ) + ) + + home = Path(os.environ.get("HERMES_HOME") or get_hermes_home()).expanduser() + checks.append(_can_write_probe(home, "HERMES_HOME writable")) + + try: + from hermes_cli import kanban_db as kb + + board = kb.get_current_board() + db_path = kb.kanban_db_path(board) + checks.append(PreflightCheck("kanban board", True, board)) + checks.append(_can_write_probe(db_path.parent, "kanban db writable")) + checks.append(_can_write_probe(kb.workspaces_root(board), "kanban workspaces writable")) + except Exception as exc: + checks.append(PreflightCheck("kanban paths", False, str(exc))) + + return checks + + +def _print_human(scope: str, checks: list[PreflightCheck]) -> None: + print(f"Runtime preflight: {scope}") + for check in checks: + status = "PASS" if check.ok else "FAIL" + suffix = f" — {check.detail}" if check.detail else "" + print(f"[{status}] {check.name}{suffix}") + print("PASS" if all(check.ok for check in checks) else "FAIL") + + +def run_runtime_preflight(args) -> int: + scope = getattr(args, "scope", "kanban") or "kanban" + if scope != "kanban": + checks = [PreflightCheck("scope", False, f"unsupported scope: {scope}")] + else: + checks = collect_kanban_preflight() + + if getattr(args, "json", False): + print(jsonlib.dumps({"scope": scope, "ok": all(c.ok for c in checks), "checks": [asdict(c) for c in checks]}, indent=2)) + else: + _print_human(scope, checks) + return 0 if all(check.ok for check in checks) else 1 + + +def runtime_command(args) -> None: + import sys + + action = getattr(args, "runtime_action", None) + if action == "preflight": + raise SystemExit(run_runtime_preflight(args)) + print("Unknown runtime subcommand") + raise SystemExit(1) diff --git a/tests/hermes_cli/test_runtime_preflight.py b/tests/hermes_cli/test_runtime_preflight.py new file mode 100644 index 000000000000..7fffcf3415d9 --- /dev/null +++ b/tests/hermes_cli/test_runtime_preflight.py @@ -0,0 +1,51 @@ +from types import SimpleNamespace + + +def test_runtime_preflight_kanban_passes_with_writable_home(monkeypatch, capsys, tmp_path): + from hermes_cli import runtime_preflight as mod + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("HERMES_KANBAN_HOME", str(tmp_path)) + monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "kanban.db")) + monkeypatch.setattr( + mod, + "load_config", + lambda: { + "model": "gpt-5.5", + "provider": "openai-codex", + "kanban": {"runtime_guardrails": {"enabled": True}}, + }, + ) + + rc = mod.run_runtime_preflight(SimpleNamespace(scope="kanban", json=False)) + + out = capsys.readouterr().out + assert rc == 0 + assert "Runtime preflight: kanban" in out + assert "provider/model" in out + assert "kanban db writable" in out + assert "PASS" in out + + +def test_runtime_preflight_kanban_fails_when_guardrails_disabled(monkeypatch, capsys, tmp_path): + from hermes_cli import runtime_preflight as mod + + monkeypatch.setenv("HERMES_HOME", str(tmp_path)) + monkeypatch.setenv("HERMES_KANBAN_HOME", str(tmp_path)) + monkeypatch.setenv("HERMES_KANBAN_DB", str(tmp_path / "kanban.db")) + monkeypatch.setattr( + mod, + "load_config", + lambda: { + "model": "gpt-5.5", + "provider": "openai-codex", + "kanban": {"runtime_guardrails": {"enabled": False}}, + }, + ) + + rc = mod.run_runtime_preflight(SimpleNamespace(scope="kanban", json=False)) + + out = capsys.readouterr().out + assert rc == 1 + assert "kanban runtime guardrails" in out + assert "FAIL" in out From e36894d2b460f4e6913c1b6f10f19709d493e2c2 Mon Sep 17 00:00:00 2001 From: Fredrick Campogni Date: Tue, 19 May 2026 08:16:47 -0400 Subject: [PATCH 3/3] feat(kanban): expose runtime preflight contract to workers --- hermes_cli/kanban_db.py | 6 ++++++ tests/hermes_cli/test_kanban_db.py | 2 ++ 2 files changed, 8 insertions(+) diff --git a/hermes_cli/kanban_db.py b/hermes_cli/kanban_db.py index 9cbc010ac64a..50b77248f492 100644 --- a/hermes_cli/kanban_db.py +++ b/hermes_cli/kanban_db.py @@ -5239,6 +5239,12 @@ def _default_spawn( # board slug still forces it to the right directory. resolved_board = _normalize_board_slug(board) or get_current_board() env["HERMES_KANBAN_BOARD"] = resolved_board + # Make inline preflight expectations visible to spawned workers and logs. + # The dispatcher already resolves the concrete board/db/workspace paths above; + # these flags let runtime guardrails assert that Kanban work was launched + # through the checked path instead of an ad-hoc shell. + env["HERMES_RUNTIME_PREFLIGHT_SCOPE"] = "kanban" + env["HERMES_RUNTIME_PREFLIGHT_REQUIRED"] = "1" # HERMES_PROFILE is the author the kanban_comment tool defaults to. # `hermes -p ` activates the profile, but the env var is # what the tool reads — set it explicitly here so comments are diff --git a/tests/hermes_cli/test_kanban_db.py b/tests/hermes_cli/test_kanban_db.py index 64ed630db1c0..86f13da11e74 100644 --- a/tests/hermes_cli/test_kanban_db.py +++ b/tests/hermes_cli/test_kanban_db.py @@ -1860,6 +1860,8 @@ def __init__(self, cmd, **kwargs): ) assert env["HERMES_KANBAN_TASK"] == "t_dispatch_env" assert env["HERMES_KANBAN_BRANCH"] == "wt/t_dispatch_env" + assert env["HERMES_RUNTIME_PREFLIGHT_SCOPE"] == "kanban" + assert env["HERMES_RUNTIME_PREFLIGHT_REQUIRED"] == "1" # ---------------------------------------------------------------------------