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

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions hermes_cli/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
6 changes: 6 additions & 0 deletions hermes_cli/kanban_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If this env var is meant to prove the worker was launched through the dispatcher, collect_kanban_preflight() should read and validate it; otherwise the contract is only informational despite the guardrail wording.

env["HERMES_RUNTIME_PREFLIGHT_REQUIRED"] = "1"
# HERMES_PROFILE is the author the kanban_comment tool defaults to.
# `hermes -p <assignee>` activates the profile, but the env var is
# what the tool reads — set it explicitly here so comments are
Expand Down
30 changes: 29 additions & 1 deletion hermes_cli/kanban_decompose.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
*,
Expand Down Expand Up @@ -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,
})
Expand Down
34 changes: 34 additions & 0 deletions hermes_cli/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
# =========================================================================
Expand Down
131 changes: 131 additions & 0 deletions hermes_cli/runtime_preflight.py
Original file line number Diff line number Diff line change
@@ -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:

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This should also consider model_cfg.get("model"): existing config compatibility treats model.model as a valid backcompat key, so this preflight can false-fail configs the runtime accepts.

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()


Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Root-level provider is not the current runtime selection source; provider setup writes model.provider, and trusting a stale root key here can turn a missing runtime provider into a false PASS.

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)
2 changes: 2 additions & 0 deletions tests/hermes_cli/test_kanban_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"


# ---------------------------------------------------------------------------
Expand Down
36 changes: 36 additions & 0 deletions tests/hermes_cli/test_kanban_decompose.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
51 changes: 51 additions & 0 deletions tests/hermes_cli/test_runtime_preflight.py
Original file line number Diff line number Diff line change
@@ -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