Merge branch 'simp/r2-kanban-cli' into simp/integration2

This commit is contained in:
Teknium
2026-09-02 17:05:17 -07:00
5 changed files with 1435 additions and 1512 deletions
+156 -1512
View File
File diff suppressed because it is too large Load Diff
+237
View File
@@ -0,0 +1,237 @@
"""``hermes kanban boards …`` — board directories, the ``current`` pointer and
``board.json``. Filesystem-only, so every action works before ``kanban init``
and must ignore the shared ``--board`` task-routing override.
"""
from __future__ import annotations
import argparse
from typing import Optional
from hermes_cli import kanban_db as kb
from hermes_cli.kanban_output import _err, _fmt_counts, _json_out
def _dispatch_boards(args: argparse.Namespace) -> int:
"""``hermes kanban boards <action>`` — filesystem-only (board dirs, the
``current`` pointer, ``board.json``), so it works before ``kanban init``."""
sub = getattr(args, "boards_action", None) or "list"
handler = _BOARD_HANDLERS.get(sub)
if handler is None:
return _err(f"kanban boards: unknown action {sub!r}", 2)
return handler(args)
def _board_task_counts(slug: str) -> dict[str, int]:
"""Return ``{status: count}`` for a board. Safe to call on an empty DB."""
try:
path = kb.kanban_db_path(board=slug)
if not path.exists():
return {}
with kb.connect_closing(board=slug) as conn:
rows = conn.execute(
"SELECT status, COUNT(*) AS n FROM tasks GROUP BY status"
).fetchall()
return {r["status"]: int(r["n"]) for r in rows}
except Exception:
return {}
def _board_slug_arg(args: argparse.Namespace, cmd: str, *, must_exist: bool) -> tuple[Optional[str], int]:
"""Normalize ``args.slug`` for a ``boards`` subcommand; ``(slug, 0)`` or ``(None, rc)``."""
try:
normed = kb._normalize_board_slug(args.slug)
except ValueError as exc:
return None, _err(f"kanban boards {cmd}: {exc}", 2)
if must_exist:
if not normed or not kb.board_exists(normed):
return None, _err(f"kanban boards {cmd}: board {args.slug!r} does not exist")
elif not normed:
return None, _err(f"kanban boards {cmd}: slug is required", 2)
return normed, 0
def _cmd_boards_list(args: argparse.Namespace) -> int:
boards = kb.list_boards(include_archived=bool(getattr(args, "all", False)))
current = kb.get_current_board()
for b in boards:
b["is_current"] = (b["slug"] == current)
b["counts"] = _board_task_counts(b["slug"])
b["total"] = sum(b["counts"].values())
if _json_out(args, boards):
return 0
if not boards:
print("(no boards — create one with `hermes kanban boards create <slug>`)")
return 0
print(f"{'':2s} {'SLUG':24s} {'NAME':28s} COUNTS")
for b in boards:
marker = "●" if b["is_current"] else " "
name = b.get("name") or ""
if b.get("archived"):
name += " [archived]"
print(f"{marker:2s} {b['slug']:24s} {name:28s} {_fmt_counts(b['counts'] or {}, '(empty)')}")
print()
print(f"Current board: {current}")
if len(boards) > 1:
print("Switch boards with `hermes kanban boards switch <slug>`.")
return 0
def _cmd_boards_create(args: argparse.Namespace) -> int:
normed, rc = _board_slug_arg(args, "create", must_exist=False)
if rc:
return rc
already = kb.board_exists(normed) and normed != kb.DEFAULT_BOARD
meta = kb.create_board(
normed,
name=args.name,
description=args.description,
icon=args.icon,
color=args.color,
default_workdir=args.default_workdir,
)
verb = "already exists" if already else "created"
print(f"Board {meta['slug']!r} {verb}.")
print(f" Display name: {meta.get('name', '')}")
print(f" DB path: {meta['db_path']}")
if getattr(args, "switch", False):
kb.set_current_board(meta["slug"])
print(f" Switched to {meta['slug']!r}.")
else:
print(f" Use `hermes kanban boards switch {meta['slug']}` to make it current.")
return 0
def _cmd_boards_rm(args: argparse.Namespace) -> int:
# `boards delete <slug>` (alias) never sets args.delete because --delete
# belongs to the 'rm' subparser only; treat the alias as `rm --delete`.
force_delete = getattr(args, "delete", False) or getattr(args, "boards_action", "") == "delete"
try:
res = kb.remove_board(args.slug, archive=not force_delete)
except ValueError as exc:
return _err(f"kanban boards rm: {exc}")
if res["action"] == "archived":
print(f"Board {res['slug']!r} archived → {res['new_path']}")
print("Recover by moving the directory back to "
"<root>/kanban/boards/<slug>/.")
else:
print(f"Board {res['slug']!r} deleted.")
return 0
def _cmd_boards_switch(args: argparse.Namespace) -> int:
normed, rc = _board_slug_arg(args, "switch", must_exist=False)
if rc:
return rc
if not kb.board_exists(normed):
return _err(
f"kanban boards switch: board {normed!r} does not exist. "
f"Create it with `hermes kanban boards create {normed}`."
)
kb.set_current_board(normed)
print(f"Active board is now {normed!r}.")
return 0
def _cmd_boards_show(args: argparse.Namespace) -> int:
current = kb.get_current_board()
meta = kb.read_board_metadata(current)
counts = _board_task_counts(current)
print(f"Current board: {current}")
print(f" Display name: {meta.get('name', '')}")
if meta.get("description"):
print(f" Description: {meta['description']}")
print(f" DB path: {meta['db_path']}")
print(f" Tasks: {sum(counts.values())} total"
+ (f" ({_fmt_counts(counts)})" if counts else ""))
return 0
def _cmd_boards_rename(args: argparse.Namespace) -> int:
normed, rc = _board_slug_arg(args, "rename", must_exist=True)
if rc:
return rc
meta = kb.write_board_metadata(normed, name=args.name)
print(f"Board {normed!r} renamed to {meta['name']!r}.")
return 0
def _cmd_boards_set_default_workdir(args: argparse.Namespace) -> int:
normed, rc = _board_slug_arg(args, "set-default-workdir", must_exist=True)
if rc:
return rc
meta = kb.write_board_metadata(normed, default_workdir=args.path)
new_val = meta.get("default_workdir")
if new_val:
print(f"Board {normed!r} default workdir set to {new_val!r}.")
else:
print(f"Board {normed!r} default workdir cleared.")
return 0
def _cmd_boards_export(args: argparse.Namespace) -> int:
from hermes_cli import kanban_transfer
from hermes_cli.sizefmt import format_bytes
slug = args.slug or kb.get_current_board()
output = args.output or f"{slug}.tar.gz"
try:
res = kanban_transfer.export_board(
slug,
output,
include_attachments=not args.no_attachments,
include_logs=args.include_logs,
)
except (OSError, ValueError) as exc:
return _err(f"kanban boards export: {exc}")
if _json_out(args, res):
return 0
counts = res["counts"]
print(f"Exported board {res['board']!r} → {res['archive']}")
print(f" Size: {format_bytes(res['size'])}")
print(f" Tasks: {counts['tasks']}")
print(f" Comments: {counts['task_comments']}")
print(f" Attachments: {counts['attachment_files']}")
print("Import it with `hermes kanban boards import <archive>`.")
return 0
def _cmd_boards_import(args: argparse.Namespace) -> int:
from hermes_cli import kanban_transfer
try:
res = kanban_transfer.import_board(
args.archive, args.as_slug, activate=args.switch
)
except (OSError, ValueError) as exc:
return _err(f"kanban boards import: {exc}")
if _json_out(args, res):
return 0
print(f"Imported board {res['board']!r} ({res['name']}).")
if res["renamed"]:
print(f" Renamed from {res['requested_board']!r} — that slug was taken.")
print(f" Path: {res['path']}")
print(f" Tasks: {res['counts']['tasks']}")
for warning in res["warnings"]:
print(f" Note: {warning}")
if res["activated"]:
print(f" Active board is now {res['board']!r}.")
else:
print(f" Switch to it with `hermes kanban boards switch {res['board']}`.")
return 0
_BOARD_HANDLERS = {
"list": _cmd_boards_list, "ls": _cmd_boards_list,
"create": _cmd_boards_create, "new": _cmd_boards_create,
"rm": _cmd_boards_rm, "remove": _cmd_boards_rm, "delete": _cmd_boards_rm,
"switch": _cmd_boards_switch, "use": _cmd_boards_switch,
"show": _cmd_boards_show, "current": _cmd_boards_show,
"rename": _cmd_boards_rename,
"set-default-workdir": _cmd_boards_set_default_workdir,
"export": _cmd_boards_export,
"import": _cmd_boards_import,
}
+426
View File
@@ -0,0 +1,426 @@
"""Dispatcher and maintenance verbs for ``hermes kanban``: ``dispatch``,
``daemon`` (deprecated standalone loop), ``tail``/``watch`` event streaming,
``gc`` and ``repair``.
"""
from __future__ import annotations
import argparse
import json
import os
import sys
import time
from pathlib import Path
from hermes_cli import kanban_db as kb
from hermes_cli.kanban_output import _err, _fmt_ts, _print_json
def _kanban_config() -> dict:
"""``config.yaml`` ``kanban:`` section, or ``{}`` when config can't be loaded."""
try:
from hermes_cli.config import load_config
cfg = load_config()
return (cfg.get("kanban", {}) if isinstance(cfg, dict) else {}) or {}
except Exception:
return {}
def _cmd_tail(args: argparse.Namespace) -> int:
last_id = 0
print(f"Tailing events for {args.task_id}. Ctrl-C to stop.")
try:
while True:
with kb.connect_closing() as conn:
events = kb.list_events(conn, args.task_id)
for e in events:
if e.id > last_id:
pl = f" {e.payload}" if e.payload else ""
print(f"[{_fmt_ts(e.created_at)}] {e.kind}{pl}", flush=True)
last_id = e.id
time.sleep(max(0.1, args.interval))
except KeyboardInterrupt:
print("\n(stopped)")
return 0
def _coerce_positive_int(value):
if value is None:
return None
try:
ival = int(value)
except (TypeError, ValueError):
return None
return ival if ival >= 1 else None
def _cmd_dispatch(args: argparse.Namespace) -> int:
# Honour kanban.default_assignee, kanban.max_in_progress,
# kanban.max_in_progress_per_profile and kanban.max_spawn with the same
# semantics as the gateway dispatch path.
try:
from hermes_cli.config import load_config
_cfg = load_config()
_kanban_cfg = _cfg.get("kanban", {}) if isinstance(_cfg, dict) else {}
default_assignee = (_kanban_cfg.get("default_assignee") or "").strip() or None
max_in_progress_per_profile = _coerce_positive_int(
_kanban_cfg.get("max_in_progress_per_profile")
)
# Memory-derived default when unset — same fallback the gateway applies.
max_in_progress = kb.resolve_max_in_progress(
_coerce_positive_int(_kanban_cfg.get("max_in_progress"))
)
# CLI --max is the more explicit signal, so it wins over kanban.max_spawn.
cli_max = getattr(args, "max", None)
max_spawn = cli_max if cli_max is not None else _coerce_positive_int(
_kanban_cfg.get("max_spawn")
)
except Exception:
default_assignee = None
max_in_progress_per_profile = None
max_in_progress = None
max_spawn = getattr(args, "max", None)
with kb.connect_closing() as conn:
res = kb.dispatch_once(
conn,
dry_run=args.dry_run,
max_spawn=max_spawn,
max_in_progress=max_in_progress,
failure_limit=getattr(args, "failure_limit", kb.DEFAULT_SPAWN_FAILURE_LIMIT),
default_assignee=default_assignee,
max_in_progress_per_profile=max_in_progress_per_profile,
)
if getattr(args, "json", False):
_print_json({
"reclaimed": res.reclaimed,
"crashed": res.crashed,
"timed_out": res.timed_out,
"stale": res.stale,
"auto_blocked": res.auto_blocked,
"promoted": res.promoted,
"spawned": [
{"task_id": tid, "assignee": who, "workspace": ws}
for (tid, who, ws) in res.spawned
],
"skipped_unassigned": res.skipped_unassigned,
"skipped_nonspawnable": res.skipped_nonspawnable,
"skipped_per_profile_capped": [
{"task_id": tid, "assignee": who, "current": current}
for (tid, who, current) in res.skipped_per_profile_capped
],
"auto_assigned_default": res.auto_assigned_default,
}, ascii=True)
return 0
print(f"Reclaimed: {res.reclaimed}")
for label, items in (
("Crashed: ", res.crashed),
("Timed out: ", res.timed_out),
("Stale: ", res.stale),
("Auto-blocked:", res.auto_blocked),
):
print(f"{label} {len(items)}")
if items:
print(f" {', '.join(items)}")
print(f"Promoted: {res.promoted}")
print(f"Spawned: {len(res.spawned)}")
tag = " (dry)" if args.dry_run else ""
for tid, who, ws in res.spawned:
print(f" - {tid} -> {who} @ {ws or '-'}{tag}")
if res.auto_assigned_default:
print(
f"Auto-assigned to kanban.default_assignee={default_assignee!r}: "
f"{', '.join(res.auto_assigned_default)}"
)
if res.skipped_unassigned:
print(f"Skipped (unassigned): {', '.join(res.skipped_unassigned)}")
for tid, who, current in res.skipped_per_profile_capped:
print(f"Deferred ({who} at per-profile cap, {current} running): {tid}")
if res.skipped_nonspawnable:
print(
f"Skipped (non-spawnable assignee — terminal lane, OK): "
f"{', '.join(res.skipped_nonspawnable)}"
)
return 0
def _cmd_daemon(args: argparse.Namespace) -> int:
"""Deprecated — the dispatcher now runs inside the gateway.
Kept as a stub so old scripts/systemd units get a clear migration message.
``--force`` (hidden from --help) keeps the standalone loop for hosts that
truly cannot run the gateway; the default path exits 2 so nobody
accidentally runs two dispatchers against the same kanban.db.
"""
if not getattr(args, "force", False):
return _err(
"hermes kanban daemon: DEPRECATED — the dispatcher now runs\n"
"inside the gateway. To use kanban:\n"
"\n"
" hermes gateway start # starts the gateway + embedded dispatcher\n"
"\n"
"Ready tasks will be picked up on the next dispatcher tick\n"
"(default: every 60 seconds). Configure via config.yaml:\n"
"\n"
" kanban:\n"
" dispatch_in_gateway: true # default\n"
" dispatch_interval_seconds: 60\n"
" failure_limit: 2 # consecutive non-success attempts before auto-block\n"
"\n"
"Running both the gateway AND this standalone daemon will\n"
"race for claims. If you truly need the old standalone\n"
"daemon (no gateway available), rerun with --force.",
2,
)
# Init before printing "started" so the DB path is right and init errors
# surface immediately.
kb.init_db()
pidfile = getattr(args, "pidfile", None)
if pidfile:
try:
Path(pidfile).parent.mkdir(parents=True, exist_ok=True)
Path(pidfile).write_text(str(os.getpid()), encoding="utf-8")
except OSError as exc:
print(f"warning: could not write pidfile {pidfile}: {exc}", file=sys.stderr)
verbose = bool(getattr(args, "verbose", False))
print(
f"Kanban dispatcher running STANDALONE via --force "
f"(interval={args.interval}s, pid={os.getpid()}). "
f"Ctrl-C to stop. NOTE: if a gateway is also running with "
f"dispatch_in_gateway=true (default), you have two dispatchers "
f"racing for claims.",
file=sys.stderr,
)
# Health telemetry: warn when every tick finds ready work but spawns
# nothing (broken profile, PATH drift, missing venv, credential loss) —
# the per-task breaker auto-blocks quietly, so the operator needs a signal.
HEALTH_WINDOW = 6 # ticks (default 30s at interval=5)
health_state = {"bad_ticks": 0, "last_warn_at": 0}
def _on_tick(res):
ready_pending = bool(res.skipped_unassigned) or _ready_queue_nonempty()
spawned_any = bool(res.spawned)
if ready_pending and not spawned_any:
health_state["bad_ticks"] += 1
else:
health_state["bad_ticks"] = 0
# Warn once per HEALTH_WINDOW bad ticks, at most every 5 minutes.
if health_state["bad_ticks"] >= HEALTH_WINDOW:
now = int(time.time())
if now - health_state["last_warn_at"] >= 300:
print(
f"[{_fmt_ts(now)}] WARN dispatcher stuck: "
f"ready queue non-empty for {health_state['bad_ticks']} "
f"consecutive ticks but 0 workers spawned successfully. "
f"Check profile health (venv, PATH, credentials) and "
f"`hermes kanban list --status ready` / "
f"`hermes kanban list --status blocked` for recent "
f"spawn_failed tasks.",
file=sys.stderr, flush=True,
)
health_state["last_warn_at"] = now
if not verbose:
return
did_work = (
res.reclaimed or res.crashed or res.timed_out or res.promoted
or res.spawned or res.auto_blocked or res.stale
)
if did_work:
print(
f"[{_fmt_ts(int(time.time()))}] "
f"reclaimed={res.reclaimed} crashed={len(res.crashed)} "
f"timed_out={len(res.timed_out)} stale={len(res.stale)} "
f"promoted={res.promoted} spawned={len(res.spawned)} "
f"auto_blocked={len(res.auto_blocked)}",
flush=True,
)
def _ready_queue_nonempty() -> bool:
"""Is there a ready+assigned+unclaimed task the dispatcher would spawn for?
Control-plane lanes pulled via ``claim_task`` are correctly idle, not stuck."""
try:
with kb.connect_closing() as conn:
return kb.has_spawnable_ready(conn)
except Exception:
return False
try:
kb.run_daemon(
interval=args.interval,
max_spawn=args.max,
failure_limit=getattr(args, "failure_limit", kb.DEFAULT_SPAWN_FAILURE_LIMIT),
on_tick=_on_tick,
)
finally:
if pidfile:
try:
Path(pidfile).unlink()
except OSError:
pass
print("(dispatcher stopped)")
return 0
def _cmd_watch(args: argparse.Namespace) -> int:
"""Live-stream task_events to the terminal."""
kinds = (
{k.strip() for k in args.kinds.split(",") if k.strip()}
if args.kinds else None
)
print("Watching kanban events. Ctrl-C to stop.", flush=True)
# Seed cursor at the latest id so we don't replay history.
with kb.connect_closing() as conn:
row = conn.execute(
"SELECT COALESCE(MAX(id), 0) AS m FROM task_events"
).fetchone()
cursor = int(row["m"])
try:
while True:
with kb.connect_closing() as conn:
rows = conn.execute(
"SELECT e.id, e.task_id, e.kind, e.payload, e.created_at, "
" t.assignee, t.tenant "
"FROM task_events e LEFT JOIN tasks t ON t.id = e.task_id "
"WHERE e.id > ? ORDER BY e.id ASC LIMIT 200",
(cursor,),
).fetchall()
for r in rows:
cursor = max(cursor, int(r["id"]))
if kinds and r["kind"] not in kinds:
continue
if args.assignee and r["assignee"] != args.assignee:
continue
if args.tenant and r["tenant"] != args.tenant:
continue
try:
payload = json.loads(r["payload"]) if r["payload"] else None
except Exception:
payload = None
pl = f" {payload}" if payload else ""
print(
f"[{_fmt_ts(r['created_at'])}] {r['task_id']:10s} "
f"{r['kind']:18s} (@{r['assignee'] or '-'}){pl}",
flush=True,
)
time.sleep(max(0.1, args.interval))
except KeyboardInterrupt:
print("\n(stopped)")
return 0
def _cmd_gc(args: argparse.Namespace) -> int:
"""Remove archived tasks' scratch workspaces, old events, and old worker logs."""
import shutil
scratch_root = kb.workspaces_root()
removed_ws = 0
with kb.connect_closing() as conn:
rows = conn.execute(
"SELECT id, workspace_kind, workspace_path, branch_name FROM tasks "
"WHERE status = 'archived'"
).fetchall()
for row in rows:
if row["workspace_kind"] == "worktree":
# Backstop for worktrees that escaped the completion/archive hook.
# Same safety predicate: only clean, fully-pushed worktrees go.
wt_path = row["workspace_path"]
if wt_path and Path(wt_path).is_dir():
kb._cleanup_worktree_workspace(row["id"], wt_path, row["branch_name"])
if not Path(wt_path).is_dir():
removed_ws += 1
continue
if row["workspace_kind"] != "scratch":
continue
path = Path(row["workspace_path"] or (scratch_root / row["id"]))
try:
path = path.resolve()
except OSError:
continue
try:
path.relative_to(scratch_root.resolve())
except ValueError:
# Safety: never delete outside the scratch root.
continue
if path.exists() and path.is_dir():
shutil.rmtree(path, ignore_errors=True)
removed_ws += 1
event_days = getattr(args, "event_retention_days", 30)
log_days = getattr(args, "log_retention_days", 30)
with kb.connect_closing() as conn:
removed_events = kb.gc_events(
conn, older_than_seconds=event_days * 24 * 3600,
)
removed_logs = kb.gc_worker_logs(
older_than_seconds=log_days * 24 * 3600,
)
print(f"GC complete: {removed_ws} workspace(s), "
f"{removed_events} event row(s), {removed_logs} log file(s) removed")
return 0
def _cmd_repair(args: argparse.Namespace) -> int:
"""Integrity check + narrow index-REINDEX auto-repair. Dispatched BEFORE
the auto ``kb.init_db()`` (init refuses corrupt DBs). Exit 0 = healthy /
repaired / no DB file, 1 = still corrupt."""
try:
report = kb.repair_db()
except Exception as exc: # locked/busy probe, unexpected I/O
return _err(f"kanban repair: {exc}")
if getattr(args, "json", False):
_print_json({
"status": report.status,
"db_path": str(report.db_path),
"messages": report.messages,
"post_repair_messages": report.post_repair_messages,
"backup_path": (
str(report.backup_path) if report.backup_path else None
),
"reindexed": report.reindexed,
}, ascii=True)
return 0 if report.status in {"ok", "repaired", "missing"} else 1
if report.status == "missing":
print(f"No kanban DB at {report.db_path} — nothing to repair.")
return 0
if report.status == "ok":
print(f"{report.db_path}: integrity_check ok — no repair needed.")
return 0
if report.status == "repaired":
print(f"{report.db_path}: repaired.")
print(f" reindexed: {', '.join(report.reindexed)}")
if report.backup_path:
print(f" pre-repair backup: {report.backup_path}")
print(" integrity_check now ok.")
return 0
# still corrupt
print(f"{report.db_path}: CORRUPT.", file=sys.stderr)
for line in (report.messages or [])[:10]:
print(f" {line}", file=sys.stderr)
if report.reindexed:
print(
f" REINDEX ({', '.join(report.reindexed)}) attempted but "
f"integrity_check is still failing:",
file=sys.stderr,
)
for line in (report.post_repair_messages or [])[:10]:
print(f" {line}", file=sys.stderr)
else:
print(
" Not an index-only failure — automatic REINDEX repair does "
"not apply (fail-closed).",
file=sys.stderr,
)
if report.backup_path:
print(f" corrupt copy quarantined at: {report.backup_path}",
file=sys.stderr)
print(
" Recover manually (e.g. `sqlite3 kanban.db \".recover\"` into a "
"fresh file) or move the file aside to start a new board.",
file=sys.stderr,
)
return 1
+95
View File
@@ -0,0 +1,95 @@
"""Text / ``--json`` output helpers shared by the ``hermes kanban`` CLI modules."""
from __future__ import annotations
import argparse
import json
import sys
import time
from typing import Any, Callable, Iterable, Optional
from hermes_cli import kanban_db as kb
_STATUS_ICONS = {
"todo": "◻",
"ready": "▶",
"running": "●",
"scheduled":"⏱",
"blocked": "⊘",
"done": "✓",
"archived": "—",
}
_TASK_DICT_FIELDS = (
"id", "title", "body", "assignee", "status", "priority", "tenant",
"workspace_kind", "workspace_path", "branch_name", "project_id",
"created_by", "created_at", "started_at", "completed_at", "result",
"skills", "max_retries", "model_override", "provider_override",
"session_id", "workflow_template_id", "current_step_key",
)
_SHOW_RUN_FIELDS = (
"id", "profile", "step_key", "status", "outcome", "summary", "error",
"metadata", "worker_pid", "started_at", "ended_at",
)
_RUNS_RUN_FIELDS = (
"id", "profile", "status", "outcome", "started_at", "ended_at",
"summary", "error", "metadata", "worker_pid", "step_key",
)
_ATTACHMENT_FIELDS = (
"id", "filename", "content_type", "size", "uploaded_by", "stored_path", "created_at",
)
def _fmt_ts(ts: Optional[int]) -> str:
return time.strftime("%Y-%m-%d %H:%M", time.localtime(ts)) if ts else ""
def _print_json(obj: Any, *, ascii: bool = False) -> None:
print(json.dumps(obj, indent=2, ensure_ascii=ascii))
def _json_out(args: argparse.Namespace, obj: Any, *, ascii: bool = False) -> bool:
"""Print ``obj`` as JSON and return True when ``--json`` was passed."""
if not getattr(args, "json", False):
return False
_print_json(obj, ascii=ascii)
return True
def _fmt_counts(counts: dict, empty: str = "") -> str:
return ", ".join(f"{k}={v}" for k, v in sorted(counts.items())) or empty
def _err(msg: str, rc: int = 1) -> int:
print(msg, file=sys.stderr)
return rc
def _bulk_apply(ids: Iterable[str], op: Callable[[str], Any],
ok_msg: Callable[[str], str], fail_msg: Callable[[str], str]) -> int:
"""Run ``op(tid) -> bool`` per id, print ok/fail lines, exit 1 if any failed."""
failed = False
for tid in ids:
if not op(tid):
failed = True
print(fail_msg(tid), file=sys.stderr)
else:
print(ok_msg(tid))
return 1 if failed else 0
def _fmt_task_line(t: kb.Task) -> str:
icon = _STATUS_ICONS.get(t.status, "?")
assignee = t.assignee or "(unassigned)"
tenant = f" [{t.tenant}]" if t.tenant else ""
return f"{icon} {t.id} {t.status:8s} {assignee:20s}{tenant} {t.title}"
def _obj_dict(obj: Any, fields: tuple[str, ...]) -> dict[str, Any]:
return {k: getattr(obj, k) for k in fields}
def _task_to_dict(t: kb.Task) -> dict[str, Any]:
d = _obj_dict(t, _TASK_DICT_FIELDS)
d["skills"] = list(t.skills) if t.skills else []
return d
+521
View File
@@ -0,0 +1,521 @@
"""Argparse tree for ``hermes kanban …`` (``build_parser``).
The subcommand tree is declared as data — one ``_cmd(...)`` record per
subcommand holding its ``add_parser`` kwargs and an ordered tuple of
``add_argument`` specs — and materialised by ``_add_commands``. Order of
records and arguments is the order argparse renders in ``--help``.
"""
from __future__ import annotations
import argparse
from hermes_cli import kanban_db as kb
def _arg(*flags: str, **kw):
return (flags, kw)
def _cmd(name: str, args=(), *, children=None, **parser_kw):
"""``children`` = ``(dest, [specs])`` for a nested subparser group."""
return (name, parser_kw, tuple(args), children)
def _add_commands(sub: argparse._SubParsersAction, specs) -> None:
for name, parser_kw, args, children in specs:
p = sub.add_parser(name, **parser_kw)
for flags, kw in args:
p.add_argument(*flags, **kw)
if children:
dest, child_specs = children
_add_commands(p.add_subparsers(dest=dest), child_specs)
def _run_state_args(type_help: str):
return (
_arg("--state-type", choices=("status", "outcome"), default=None,
help=f"With --state-name: {type_help}"),
_arg("--state-name", default=None, metavar="VALUE",
help="With --state-type: keep runs whose column equals this value"),
)
def _triage_sweep_args(verb: str, Verb: str, noun: str):
"""Shared ``specify`` / ``decompose`` arguments."""
return (
_arg("task_id", nargs="?", default=None,
help=f"Task id to {verb} (required unless --all is given)"),
_arg("--all", dest="all_triage", action="store_true",
help=f"{Verb} every task currently in the triage column"),
_arg("--tenant", default=None,
help="When used with --all, restrict the sweep to this tenant"),
_arg("--author", default=None,
help="Author name recorded on the audit comment "
f"(default: $HERMES_PROFILE or '{noun}')"),
_arg("--json", action="store_true", help="Emit one JSON object per task on stdout"),
)
def _json_flag(**kw):
return _arg("--json", action="store_true", **kw)
def _bulk_ids(verb: str):
return _arg("--ids", nargs="+", default=None,
help=f"Additional task ids to {verb} with the same reason (bulk mode)")
def _board_specs():
return [
_cmd("list", [
_json_flag(),
_arg("--all", action="store_true", help="Include archived boards too"),
], aliases=["ls"], help="List all boards with task counts"),
_cmd("create", [
_arg("slug", help="Board slug (kebab-case, e.g. atm10-server)"),
_arg("--name", default=None,
help="Human-readable display name (defaults to Title Case of slug)"),
_arg("--description", default=None, help="Optional description"),
_arg("--icon", default=None,
help="Optional emoji or single-character icon for the dashboard"),
_arg("--color", default=None,
help="Optional hex color (e.g. '#8b5cf6') for the dashboard"),
_arg("--switch", action="store_true", help="Switch to the new board after creating it"),
_arg("--default-workdir", default=None,
help="Default workspace path for tasks created on this board"),
], aliases=["new"], help="Create a new board"),
_cmd("rm", [
_arg("slug"),
_arg("--delete", action="store_true",
help="Hard-delete the board directory instead of archiving it. "
"Default is to move it to boards/_archived/ so it's recoverable."),
], aliases=["remove", "delete"], help="Archive (default) or delete a board"),
_cmd("switch", [_arg("slug")], aliases=["use"],
help="Set the active board for subsequent CLI calls"),
_cmd("show", aliases=["current"], help="Print the currently-active board slug"),
_cmd("rename", [
_arg("slug"),
_arg("name", help="New display name"),
], help="Change a board's human-readable display name (slug is immutable)"),
_cmd("set-default-workdir", [
_arg("slug"),
_arg("path", nargs="?", default=None,
help="Absolute path to use as default workdir. Omit to clear."),
], help="Set the default workspace path for tasks on a board"),
_cmd("export", [
_arg("slug", nargs="?", default=None, help="Board to export (default: the current board)"),
_arg("-o", "--output", default=None, help="Archive path (default: ./<slug>.tar.gz)"),
_arg("--no-attachments", action="store_true",
help="Skip attachment files, keeping the archive small"),
_arg("--include-logs", action="store_true", help="Include per-task worker logs"),
_json_flag(),
], help="Export a board to a portable .tar.gz archive", description=(
"Package a board's tasks, comments, links, history, and file "
"attachments into one archive that can be imported on another "
"machine. Claims, worker PIDs, chat subscriptions, and paths "
"belonging to this machine are stripped. Workspaces are never "
"included — they are rebuilt on demand."
)),
_cmd("import", [
_arg("archive", help="Path to the .tar.gz archive"),
_arg("--as", dest="as_slug", default=None,
help="Slug for the imported board (default: from the archive)"),
_arg("--switch", action="store_true", help="Switch to the imported board afterwards"),
_json_flag(),
], help="Import a board archive as a new board", description=(
"Import a .tar.gz produced by `hermes kanban boards export`. "
"The board always lands as a NEW board — the slug gains a "
"numeric suffix if it is already taken — so an import can "
"never overwrite or merge into a board you already have."
)),
]
def _task_specs():
"""``init`` … ``attach-rm``: creation, listing, inspection and attachment verbs."""
return [
_cmd("init", help="Create kanban.db if missing (idempotent)"),
_cmd("boards", children=("boards_action", _board_specs()),
help="Manage kanban boards (one board per project / workstream)",
description=(
"Boards let you separate unrelated streams of work "
"(projects, repos, domains) into isolated queues. Each "
"board has its own DB, workspaces directory, and dispatcher "
"loop — tasks on one board cannot collide with tasks on "
"another. The first board is 'default' and always exists."
)),
_cmd("create", [
_arg("title", help="Task title"),
_arg("--body", default=None, help="Optional opening post"),
_arg("--assignee", default=None, help="Profile name to assign"),
_arg("--parent", action="append", default=[], help="Parent task id (repeatable)"),
_arg("--workspace", default="scratch",
help="scratch | worktree | worktree:<path> | dir:<path> (default: scratch)"),
_arg("--branch", default=None, help="Branch name for worktree tasks, e.g. wt/t6-wire"),
_arg("--project", default=None,
help="Link to a project (id or slug). Anchors the task's "
"worktree under the project's primary repo with a "
"deterministic branch. See `hermes project list`."),
_arg("--tenant", default=None, help="Tenant namespace"),
_arg("--priority", type=int, default=0, help="Priority tiebreaker"),
_arg("--triage", action="store_true",
help="Park in triage — a specifier will flesh out the spec and promote to todo"),
_arg("--idempotency-key", default=None,
help="Dedup key. If a non-archived task with this key exists, "
"its id is returned instead of creating a duplicate."),
_arg("--max-runtime", default=None,
help="Per-task runtime cap. Accepts seconds (300) or durations (90s, "
"30m, 2h, 1d). When exceeded, the dispatcher SIGTERMs (then "
"SIGKILLs) the worker and re-queues the task."),
_arg("--created-by", default="user",
help="Author name recorded on the task (default: user)"),
_arg("--skill", action="append", default=[], dest="skills",
help="Skill to force-load into the worker (repeatable). The kanban "
"lifecycle is already injected automatically. Example: --skill "
"translation --skill github-code-review"),
_arg("--max-retries", type=int, default=None, metavar="N",
help="Per-task override for the consecutive-failure "
"circuit breaker. Trip on the Nth failure — "
"e.g. --max-retries 1 blocks on the first "
"failure (no retries), --max-retries 3 allows "
"two retries. Omit to use the dispatcher's "
"kanban.failure_limit config "
f"(default {kb.DEFAULT_FAILURE_LIMIT})."),
_arg("--model", default=None, dest="model_override",
help="Pin the worker to this model (passed as -m <model>) without "
"changing the profile's configured model. Combine with --provider "
"when the model belongs to a different backend than the profile's "
"default."),
_arg("--provider", default=None, dest="provider_override",
help="Provider the --model belongs to (passed as --provider <name> to "
"the worker). Requires --model."),
_arg("--goal", action="store_true", dest="goal_mode",
help="Run the worker in a goal loop: after each turn a judge checks the "
"response against the card title/body and, if not done, the worker "
"keeps going in the same session until the judge agrees it's "
"complete (or the turn budget runs out, which blocks the card for "
"review). Best for open-ended cards one shot rarely finishes."),
_arg("--goal-max-turns", type=int, default=None, metavar="N", dest="goal_max_turns",
help="Turn budget for --goal workers (default 20). Ignored without --goal."),
_arg("--initial-status", choices=sorted(kb.VALID_INITIAL_STATUSES), default="running",
help="Initial card status. Use 'blocked' for cards "
"that require immediate human ops (R3 gate) "
"to skip the brief running-to-blocked transition."),
_json_flag(help="Emit JSON output"),
], help="Create a new task"),
_cmd("swarm", [
_arg("goal", help="Swarm goal / final outcome"),
_arg("--worker", action="append", default=[], metavar="PROFILE:TITLE[:SKILL,SKILL]",
help="Parallel worker card (repeatable)"),
_arg("--verifier", required=True, help="Verifier profile"),
_arg("--synthesizer", required=True, help="Synthesizer/writer profile"),
_arg("--tenant", default=None, help="Tenant namespace"),
_arg("--priority", type=int, default=0, help="Priority tiebreaker"),
_arg("--created-by", default=None, help="Creator/anchor profile"),
_arg("--idempotency-key", default=None, help="Dedup key for the root card"),
_json_flag(help="Emit JSON output"),
], help="Create a Kanban Swarm v1 graph (parallel workers → verifier → synthesizer)"),
_cmd("list", [
_arg("--mine", action="store_true", help="Filter by $HERMES_PROFILE as assignee"),
_arg("--assignee", default=None),
_arg("--status", default=None, choices=sorted(kb.VALID_STATUSES)),
_arg("--tenant", default=None),
_arg("--session", default=None,
help="Filter by originating chat/agent session id "
"(set on tasks created from inside an ACP loop)"),
_arg("--archived", action="store_true", help="Include archived tasks"),
_json_flag(),
_arg("--sort", default=None, choices=sorted(kb.VALID_SORT_ORDERS.keys()),
help="Sort order for listed tasks (default: priority)"),
_arg("--workflow-template-id", default=None, metavar="ID",
help="Restrict to tasks with this workflow_template_id"),
_arg("--step-key", default=None, dest="current_step_key", metavar="KEY",
help="Restrict to tasks with this current_step_key"),
], aliases=["ls"], help="List tasks"),
_cmd("show", [
_arg("task_id"),
_json_flag(),
*_run_state_args("filter listed runs by task_runs column"),
], help="Show a task with comments + events"),
_cmd("assign", [
_arg("task_id"),
_arg("profile", help="Profile name (or 'none' to unassign)"),
], help="Assign or reassign a task"),
_cmd("set-model", [
_arg("task_id"),
_arg("model", nargs="?", default=None,
help="Model to pin the worker to (or 'none' to clear the override)"),
_arg("--provider", default=None,
help="Provider the model belongs to (worker is spawned with "
"--provider <name>). Cleared together with the model."),
], help="Set or clear a task's model/provider override (takes effect on the next dispatch)"),
_cmd("reclaim", [
_arg("task_id"),
_arg("--reason", default=None, help="Human-readable reason (recorded on the reclaimed event)"),
], help="Release an active worker claim on a running task"),
_cmd("reassign", [
_arg("task_id"),
_arg("profile", help="New profile name (or 'none' to unassign)"),
_arg("--reclaim", action="store_true",
help="Release any active claim before reassigning (required if task is running)"),
_arg("--reason", default=None, help="Human-readable reason (recorded on the reclaimed event)"),
], help="Reassign a task to a different profile, optionally reclaiming first"),
_cmd("diagnostics", [
_arg("--severity", choices=["warning", "error", "critical"], default=None,
help="Only show diagnostics at or above this severity"),
_arg("--task", default=None, help="Only show diagnostics for one task id"),
_json_flag(help="Emit JSON (structured) instead of the default human table"),
], aliases=["diag"], help="List active diagnostics on the current board"),
_cmd("link", [_arg("parent_id"), _arg("child_id")], help="Add a parent->child dependency"),
_cmd("unlink", [_arg("parent_id"), _arg("child_id")], help="Remove a parent->child dependency"),
_cmd("claim", [
_arg("task_id"),
_arg("--ttl", type=int, default=kb.DEFAULT_CLAIM_TTL_SECONDS,
help="Claim TTL in seconds (default: 900)"),
], help="Atomically claim a ready task (prints resolved workspace path)"),
_cmd("comment", [
_arg("task_id"),
_arg("text", nargs="+", help="Comment body"),
_arg("--author", default=None, help="Author name (default: $HERMES_PROFILE or 'user')"),
_arg("--max-len", type=int, default=None,
help="Trim the stored comment body to this many characters"),
], help="Append a comment"),
_cmd("attach", [
_arg("task_id"),
_arg("path", help="Path to the local file to attach"),
_arg("--content-type", default=None,
help="MIME type (default: guessed from the file extension)"),
_arg("--name", default=None, help="Stored filename (default: the source file's basename)"),
_arg("--author", default=None, help="uploaded_by label (default: $HERMES_PROFILE or 'user')"),
], help="Attach a local file to a task"),
_cmd("attachments", [_arg("task_id"), _json_flag()], help="List a task's attachments"),
_cmd("attach-rm", [_arg("attachment_id", type=int)], help="Delete an attachment by id"),
]
def _lifecycle_specs():
"""``complete`` … ``repair``: state transitions, dispatcher, notify and maintenance verbs."""
return [
_cmd("complete", [
_arg("task_ids", nargs="+",
help="One or more task ids (only --result applies to all of them)"),
_arg("--result", default=None, help="Result summary"),
_arg("--summary", default=None,
help="Structured handoff summary for downstream tasks. "
"Falls back to --result if omitted."),
_arg("--metadata", default=None,
help='JSON dict of structured facts (e.g. \'{"changed_files": [...], '
'"tests_run": 12}\'). Stored on the closing run.'),
], help="Mark one or more tasks done"),
_cmd("edit", [
_arg("task_id"),
_arg("--result", required=True, help="Backfilled task result text for a done task"),
_arg("--summary", default=None,
help="Structured handoff summary. Falls back to --result if omitted."),
_arg("--metadata", default=None,
help="JSON dict of structured facts to store on the latest completed run."),
], help="Edit recovery fields on an already-completed task"),
_cmd("block", [
_arg("task_id"),
_arg("reason", nargs="*", help="Reason (also appended as a comment)"),
_bulk_ids("block"),
_arg("--kind", default=None, choices=sorted(kb.VALID_BLOCK_KINDS),
help="Typed block reason. 'dependency' waits in todo (auto-promoted when "
"parents finish, no human); 'needs_input'/'capability' go to "
"blocked for a human; 'transient' marks a maybe-flaky failure. "
"Repeated same-kind re-blocks after unblock route the task to "
"triage to break unblock loops. Omit for a generic block."),
], help="Mark one or more tasks blocked"),
_cmd("schedule", [
_arg("task_id"),
_arg("reason", nargs="*", help="Reason/timing note (also appended as a comment)"),
_bulk_ids("schedule"),
], help="Park one or more tasks in Scheduled (waiting on time, not human input)"),
_cmd("unblock", [
_arg("--reason", default=None,
help="Optional reason/note — recorded as a comment before unblocking. "
"Quote multi-word reasons."),
_arg("task_ids", nargs="+"),
], help="Return blocked/scheduled tasks to ready, or todo while parents remain open"),
_cmd("request-review", [
_arg("task_id"),
_arg("--summary", default=None,
help="What was implemented and how it was verified — shown to the reviewer."),
_arg("--reviewer", default=None,
help="Optional reviewer profile; reassigns the task before review dispatch."),
_arg("--metadata", default=None, help="JSON object with structured reviewer handoff facts."),
_arg("--force", action="store_true",
help="Override the live-claim guard: move a running, claimed "
"task to review even without owning its run (clears the "
"worker's claim)."),
], help="Move a task to 'review' (implementation done, awaiting review) — NOT a block"),
_cmd("request-changes", [
_arg("task_id"),
_arg("reason", nargs="+", help="Concrete changes required before re-review"),
], help="Reviewer verdict: return the active review run to its implementer"),
_cmd("reopen-review", [
_arg("task_ids", nargs="+"),
_arg("--reason", default=None,
help="Optional reason/note — recorded as a comment before "
"reopening. Quote multi-word reasons."),
], help="Send one or more review tasks back for changes (review -> ready/todo)"),
_cmd("promote", [
_arg("task_id"),
_arg("reason", nargs="*", help="Audit-trail reason (recorded on the task_events row)"),
_bulk_ids("promote"),
_arg("--force", action="store_true",
help="Promote even if parent dependencies are not yet done/archived"),
_arg("--dry-run", action="store_true", help="Validate the promotion without mutating state"),
_arg("--json", dest="json", action="store_true", help="Emit machine-readable JSON result"),
], help="Manually move one or more todo/blocked tasks to ready (recovery path)"),
_cmd("archive", [
_arg("task_ids", nargs="*", help="Task ids to archive (default mode)"),
_arg("--rm", dest="purge_ids", nargs="+", default=None,
help="Permanently delete already-archived task ids from the board"),
], help="Archive one or more tasks"),
_cmd("tail", [
_arg("task_id"),
_arg("--interval", type=float, default=1.0),
], help="Follow a task's event stream"),
_cmd("dispatch", [
_arg("--dry-run", action="store_true",
help="Don't actually spawn processes; just print what would happen"),
_arg("--max", type=int, default=None, help="Cap number of spawns this pass"),
_arg("--failure-limit", type=int, default=kb.DEFAULT_SPAWN_FAILURE_LIMIT,
help=f"Auto-block a task after this many consecutive non-success attempts "
f"(spawn_failed, timed_out, or crashed; default: {kb.DEFAULT_SPAWN_FAILURE_LIMIT})"),
_json_flag(),
], help="One dispatcher pass: reclaim stale, promote ready, spawn workers"),
_cmd("daemon", [
_arg("--interval", type=float, default=60.0, help="Seconds between dispatch ticks (default: 60)"),
_arg("--max", type=int, default=None, help="Cap number of spawns per tick"),
_arg("--failure-limit", type=int, default=kb.DEFAULT_SPAWN_FAILURE_LIMIT),
_arg("--pidfile", default=None, help="Write the daemon's PID to this file on start"),
_arg("--verbose", "-v", action="store_true", help="Log each tick's outcome to stdout"),
# Escape hatch for hosts that truly cannot run the gateway; hidden from
# --help so nobody casually keeps the double-dispatcher pattern alive.
_arg("--force", action="store_true", help=argparse.SUPPRESS),
], help="DEPRECATED — dispatcher now runs in the gateway. Use `hermes gateway start`."),
_cmd("watch", [
_arg("--assignee", default=None, help="Only show events for tasks assigned to this profile"),
_arg("--tenant", default=None, help="Only show events from tasks in this tenant"),
_arg("--kinds", default=None,
help="Comma-separated event kinds to include "
"(e.g. 'completed,blocked,gave_up,crashed,timed_out')"),
_arg("--interval", type=float, default=0.5, help="Poll interval in seconds (default: 0.5)"),
], help="Live-stream task_events to the terminal (Ctrl+C to exit)"),
_cmd("stats", [_json_flag()], help="Per-status + per-assignee counts + oldest-ready age"),
_cmd("notify-subscribe", [
_arg("task_id"),
_arg("--platform", required=True),
_arg("--chat-id", required=True),
_arg("--thread-id", default=None),
_arg("--user-id", default=None),
_arg("--user-id-alt", default=None),
_arg("--chat-type", choices=("dm", "group", "channel", "thread"), default=None,
help="Originating source chat_type, recorded so the active-wake delivery "
"modes resolve the operator's real session. Omit to leave an "
"existing sub unchanged (new subs default to 'dm')."),
_arg("--notifier-profile", default=None,
help="Profile gateway that owns/delivers this subscription (default: active profile)"),
# choices: single source of truth shared with the DB/watcher enum.
_arg("--delivery-mode", choices=kb._NOTIFY_DELIVERY_MODES, default=None,
help="How the kanban-notifier reacts to terminal events for this "
"subscription: 'notify' (passive message only; default), "
"'notify+wake' (message AND wake the destination gateway agent so "
"it reads the full board context and replies in its own voice), or "
"'wake' (wake the agent only, no passive message). Omit to leave an "
"existing subscription's mode unchanged (new subs default to 'notify')."),
], help="Subscribe a gateway source to a task's terminal events (used by "
"/kanban subscribe in the gateway adapter)"),
_cmd("notify-list", [
_arg("task_id", nargs="?", default=None),
_json_flag(),
], help="List notification subscriptions (optionally for a single task)"),
_cmd("notify-unsubscribe", [
_arg("task_id"),
_arg("--platform", required=True),
_arg("--chat-id", required=True),
_arg("--thread-id", default=None),
], help="Remove a gateway subscription from a task"),
_cmd("log", [
_arg("task_id"),
_arg("--tail", type=int, default=None, help="Only print the last N bytes"),
], help="Print the worker log for a task (from <kanban-root>/kanban/logs/)"),
_cmd("runs", [
_arg("task_id"),
_json_flag(),
*_run_state_args("filter runs by task_runs column"),
], help="Show attempt history for a task (one row per run: profile, outcome, elapsed, summary)"),
_cmd("heartbeat", [
_arg("task_id"),
_arg("--note", default=None, help="Optional short note attached to the heartbeat event"),
], help="Emit a heartbeat event for a running task (worker liveness signal)"),
_cmd("assignees", [_json_flag()],
help="List known profiles + per-profile task counts (union of "
"~/.hermes/profiles/ and current assignees on the board)"),
_cmd("context", [_arg("task_id")],
help="Print the full context a worker sees for a task (title + body + "
"parent results + comments)."),
_cmd("specify", _triage_sweep_args("specify", "Specify", "specifier"),
help="Flesh out a triage-column task into a concrete spec (title + "
"body) and promote it to todo. Uses the auxiliary LLM "
"configured under auxiliary.triage_specifier."),
_cmd("decompose", _triage_sweep_args("decompose", "Decompose", "decomposer"),
help="Decompose a triage-column task into a graph of child tasks "
"routed to specialist profiles by description. Falls back "
"to specify-style single-task promotion when the task "
"doesn't benefit from fan-out. Uses "
"auxiliary.kanban_decomposer."),
_cmd("gc", [
_arg("--event-retention-days", type=int, default=30,
help="Delete task_events older than N days for terminal tasks (default: 30)"),
_arg("--log-retention-days", type=int, default=30,
help="Delete worker log files older than N days (default: 30)"),
], help="Garbage-collect archived-task workspaces, old events, and old logs"),
_cmd("repair", [_json_flag(help="Emit the repair report as JSON")],
help="Check kanban.db integrity and auto-repair index-only corruption",
description=(
"Runs PRAGMA integrity_check on the board's DB and reports the "
"result. When the failure consists only of index-scoped errors "
"('wrong # of entries in index <name>' / 'row N missing from "
"index <name>'), the corrupt file is quarantined to a "
".corrupt.<hash>.bak sibling first and the damaged indexes are "
"rebuilt with REINDEX — the same narrow auto-repair the "
"connect-time guard applies. Any other corruption class is "
"reported and left untouched (fail-closed). Exits 0 when the DB "
"is healthy or was repaired, non-zero when it is still corrupt."
)),
]
def _specs():
"""Top-level ``hermes kanban <action>`` records, in ``--help`` order."""
return _task_specs() + _lifecycle_specs()
def build_parser(parent_subparsers: argparse._SubParsersAction) -> argparse.ArgumentParser:
"""Attach the ``kanban`` subcommand tree; returns the ``kanban`` parser."""
kanban_parser = parent_subparsers.add_parser(
"kanban",
help="Multi-profile collaboration board (tasks, links, comments)",
description=(
"Durable SQLite-backed task board shared across Hermes profiles. "
"Tasks are claimed atomically, can depend on other tasks, and "
"are executed by a named profile in an isolated workspace. "
"See https://hermes-agent.nousresearch.com/docs/user-guide/features/kanban "
"or docs/hermes-kanban-v1-spec.pdf for the full design."
),
)
# --board scopes every subcommand to one board's DB; when omitted the
# resolution is HERMES_KANBAN_BOARD, then the persisted current-board
# file, then "default" (kanban_db.get_current_board()).
kanban_parser.add_argument("--board", default=None, metavar="<slug>",
help="Board slug to operate on. Defaults to the current board (set "
"via `hermes kanban boards switch <slug>` or the "
"HERMES_KANBAN_BOARD env var). Use `hermes kanban boards "
"list` to see all boards.")
_add_commands(kanban_parser.add_subparsers(dest="kanban_action"), _specs())
kanban_parser.set_defaults(_kanban_parser=kanban_parser)
return kanban_parser