kanban.py 63 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436
  1. """``hermes kanban …`` — dispatch (``kanban_command``), task-verb handlers, ``run_slash`` for ``/kanban``.
  2. DB work lives in ``kanban_db``; siblings: ``kanban_parser`` (argparse, re-exported ``build_parser``),
  3. ``kanban_output`` (text/--json), ``kanban_boards`` (``boards …``), ``kanban_ops`` (dispatch/daemon/
  4. tail/watch/gc/repair).
  5. """
  6. from __future__ import annotations
  7. import argparse
  8. import contextlib
  9. import json
  10. import os
  11. import shlex
  12. import sys
  13. import time
  14. from pathlib import Path
  15. from typing import Optional
  16. from hermes_cli import kanban_db as kb
  17. from hermes_cli import kanban_db_connect as kbc
  18. from hermes_cli import kanban_db_dispatch as kbd
  19. from hermes_cli import kanban_db_workspace as kbw
  20. from hermes_cli import kanban_db_notify as kbn
  21. from hermes_cli import kanban_swarm as ks
  22. from hermes_cli import kanban_workflow
  23. from hermes_cli.kanban_output import (
  24. _ATTACHMENT_FIELDS, _RUNS_RUN_FIELDS, _SHOW_RUN_FIELDS, _bulk_apply, _err,
  25. _fmt_counts, _fmt_task_line, _fmt_ts, _json_out, _obj_dict, _print_json,
  26. _task_to_dict,
  27. )
  28. from hermes_cli.kanban_boards import _dispatch_boards
  29. from hermes_cli.kanban_ops import (
  30. _cmd_daemon, _kanban_config, _cmd_dispatch, _cmd_gc, _cmd_repair, _cmd_tail, _cmd_watch,
  31. )
  32. from hermes_cli.kanban_parser import build_parser
  33. # --- Flag parsing helpers ---
  34. def _none_profile(value: str) -> Optional[str]:
  35. """``none`` / ``-`` / ``null`` mean "unassign"."""
  36. return None if value.lower() in {"none", "-", "null"} else value
  37. def _parse_metadata_flag(raw: Optional[str]) -> tuple[Optional[dict], int]:
  38. """Parse ``--metadata`` JSON; returns ``(dict|None, rc)`` with rc=2 on error."""
  39. if not raw:
  40. return None, 0
  41. try:
  42. metadata = json.loads(raw)
  43. if not isinstance(metadata, dict):
  44. raise ValueError("must be a JSON object")
  45. except (ValueError, json.JSONDecodeError) as exc:
  46. return None, _err(f"kanban: --metadata: {exc}", 2)
  47. return metadata, 0
  48. def _run_state_kwargs(args: argparse.Namespace, cmd: str) -> tuple[Optional[dict[str, str]], int]:
  49. """``--state-type``/``--state-name`` must be given together: ``(kwargs, 0)`` or ``(None, 2)``."""
  50. st = getattr(args, "state_type", None)
  51. sn = getattr(args, "state_name", None)
  52. if (st is None) != (sn is None):
  53. return None, _err(f"kanban {cmd}: pass both --state-type and --state-name, or omit both", 2)
  54. return ({} if st is None else {"state_type": st, "state_name": sn}), 0
  55. def _parse_workspace_flag(value: Optional[str]) -> tuple[Optional[str], Optional[str]]:
  56. """``--workspace`` -> ``(kind, path|None)``: ``scratch``, ``worktree``, ``worktree:<p>``, ``dir:<p>``.
  57. Omitted -> ``(None, None)`` so ``create_task`` can tell "default" from an explicit scratch."""
  58. if not value:
  59. return (None, None)
  60. v = value.strip()
  61. if v in {"scratch", "worktree"}:
  62. return (v, None)
  63. for prefix, kind in (("dir:", "dir"), ("worktree:", "worktree")):
  64. if not v.startswith(prefix):
  65. continue
  66. path = v[len(prefix):].strip()
  67. if not path:
  68. raise argparse.ArgumentTypeError(f"--workspace {prefix} requires a path after the colon")
  69. return (kind, os.path.expanduser(path))
  70. raise argparse.ArgumentTypeError(f"unknown --workspace value {value!r}: use scratch, worktree, "
  71. "worktree:<path>, or dir:<path>")
  72. def _parse_branch_flag(value: Optional[str]) -> Optional[str]:
  73. """Normalize an optional branch name from ``kanban create --branch``."""
  74. if value is None:
  75. return None
  76. branch = value.strip()
  77. if not branch:
  78. raise argparse.ArgumentTypeError("--branch requires a non-empty name")
  79. if branch.startswith("-"):
  80. raise argparse.ArgumentTypeError("--branch must not start with '-'")
  81. if any(ch.isspace() for ch in branch):
  82. raise argparse.ArgumentTypeError("--branch must not contain whitespace")
  83. return branch
  84. def _check_dispatcher_presence(hermes_home: Optional[Path] = None) -> tuple[bool, str]:
  85. """``(running, message)`` for the "will anything dispatch this?" warning: True when a gateway is
  86. alive for this HERMES_HOME with ``kanban.dispatch_in_gateway`` on, else False + human guidance.
  87. Fails OPEN (probe/config errors -> ``(True, "")``) — a missed warning beats crying wolf.
  88. ``hermes_home`` scopes the probe to a profile dir (dashboard backend); CLI callers pass None.
  89. The dashboard plugin API passes it because the dashboard backend process can be running under a
  90. different HERMES_HOME than the profile the request targets, which otherwise produced a "no gateway is
  91. running" warning against a perfectly healthy profile gateway (#71211). CLI callers leave it ``None`` and
  92. keep the existing process-level behavior.
  93. """
  94. try:
  95. from gateway.status import resolve_gateway_liveness # type: ignore
  96. # Same ladder as the dashboard status endpoints so PID-file-less / cross-container gateways
  97. # aren't misreported; use_cache=False because this one-shot probe must see the state now.
  98. liveness = resolve_gateway_liveness(profile_dir=hermes_home, use_cache=False)
  99. except Exception:
  100. return (True, "") # can't probe — silent
  101. if liveness.probe_error: # resolver swallows per-rung failures; "can't tell" != "no gateway"
  102. return (True, "")
  103. pid = liveness.pid
  104. # Even if the gateway is up, dispatch_in_gateway may be off (can't tell -> assume default).
  105. if pid and bool(_kanban_config().get("dispatch_in_gateway", True)):
  106. return (True, f"gateway pid={pid}, dispatch enabled")
  107. if pid:
  108. return (False, "Gateway is running but kanban.dispatch_in_gateway=false in "
  109. "config.yaml — the task will sit in 'ready' until you flip it "
  110. "back on and restart the gateway, OR run the legacy "
  111. "standalone daemon (`hermes kanban daemon --force`).")
  112. return (False, "No gateway is running — the task will sit in 'ready' until you "
  113. "start it. Run:\n hermes gateway start\n"
  114. "The gateway hosts an embedded dispatcher (tick interval 60s by "
  115. "default); your task will be picked up on the next tick after "
  116. "the gateway comes up.")
  117. # --- Command dispatch ---
  118. def kanban_command(args: argparse.Namespace) -> int:
  119. """Entry point from ``hermes kanban …``; returns a shell-style exit code."""
  120. action = getattr(args, "kanban_action", None)
  121. if not action:
  122. parser = getattr(args, "_kanban_parser", None)
  123. if parser is not None:
  124. parser.print_help()
  125. else:
  126. print("usage: hermes kanban <action> [options]\n"
  127. "Run 'hermes kanban --help' for the full list of actions.", file=sys.stderr)
  128. return 0
  129. # Fast-fail for UX only; the durable trust boundary is in kanban_db, since children can
  130. # import DB mutators directly.
  131. if _is_delegated_child_cli_mutation(args):
  132. return _err("kanban: delegate_task child contexts cannot mutate Kanban tasks via the CLI")
  133. # `boards …` manages board metadata and the current-board pointer itself, so it must ignore
  134. # the `--board` routing override (else `--board beta boards show` reports beta).
  135. if action == "boards":
  136. return _dispatch_boards(args)
  137. # `--board <slug>` pins HERMES_KANBAN_BOARD for the duration of this call so it inherits the
  138. # exact resolution the dispatcher uses for workers.
  139. board_override = getattr(args, "board", None)
  140. board_scope = contextlib.nullcontext()
  141. if board_override:
  142. try:
  143. normed = kb._normalize_board_slug(board_override)
  144. except ValueError as exc:
  145. return _err(f"kanban: {exc}", 2)
  146. if not normed:
  147. return _err("kanban: --board requires a slug", 2)
  148. # Boards other than 'default' must already exist — typoed slugs would otherwise silently
  149. # create an empty board.
  150. if normed != kb.DEFAULT_BOARD and not kb.board_exists(normed):
  151. return _err(f"kanban: board {normed!r} does not exist. "
  152. f"Create it with `hermes kanban boards create {normed}`.")
  153. board_scope = kb.scoped_current_board(normed)
  154. with board_scope:
  155. # `repair` dispatches BEFORE auto-init: on a corrupt DB init_db() itself raises
  156. # KanbanDbCorruptError, which would turn every repair into "could not initialize database".
  157. if action == "repair":
  158. return _cmd_repair(args)
  159. # init_db is idempotent (one sqlite_master SELECT when tables exist) and prevents
  160. # "no such table: tasks" on first use from a fresh HERMES_HOME.
  161. try:
  162. kb.init_db()
  163. except Exception as exc:
  164. return _err(f"kanban: could not initialize database: {exc}")
  165. handler = _HANDLERS.get(action)
  166. if not handler:
  167. return _err(f"kanban: unknown action {action!r}", 2)
  168. try:
  169. return int(handler(args) or 0)
  170. except (ValueError, RuntimeError, PermissionError) as exc:
  171. return _err(f"kanban: {exc}")
  172. # --- Handlers ---
  173. def _profile_author() -> str:
  174. """Best-effort author name for an interactive CLI call."""
  175. from hermes_cli.profiles import current_profile_name
  176. return current_profile_name("user") or "user"
  177. _DELEGATED_CHILD_DENIED_ACTIONS: frozenset[str] = frozenset({
  178. "init", "create", "swarm", "assign", "reclaim", "reassign", "link", "unlink",
  179. "claim", "comment", "attach", "attach-rm", "complete", "edit", "block",
  180. "schedule", "unblock", "promote", "archive", "dispatch", "daemon", "repair",
  181. "heartbeat", "notify-subscribe", "notify-unsubscribe", "specify", "decompose",
  182. "request-review", "request-changes", "reopen-review",
  183. "gc",
  184. })
  185. _DELEGATED_CHILD_DENIED_BOARD_ACTIONS: frozenset[str] = frozenset({
  186. "create", "new", "rm", "remove", "delete", "switch", "use", "rename",
  187. "set-default-workdir", "import",
  188. })
  189. def _is_delegated_child_cli_mutation(args: argparse.Namespace) -> bool:
  190. action = getattr(args, "kanban_action", None)
  191. if action == "boards":
  192. if (getattr(args, "boards_action", None) or "list") not in _DELEGATED_CHILD_DENIED_BOARD_ACTIONS:
  193. return False
  194. elif action not in _DELEGATED_CHILD_DENIED_ACTIONS:
  195. return False
  196. from agent.delegation_context import kanban_path_is_fenced
  197. return kanban_path_is_fenced(kb.kanban_home()) or kanban_path_is_fenced(kb.kanban_db_path())
  198. def _joined_words(words) -> Optional[str]:
  199. """Free-text positional ``nargs="*"`` words -> stripped string, or None when absent."""
  200. return " ".join(words).strip() if words else None
  201. def _stripped_or_none(value: Optional[str]) -> Optional[str]:
  202. """``None`` stays ``None``; otherwise strip, and treat the empty string as ``None``."""
  203. return None if value is None else (value.strip() or None)
  204. def _ok_or_err(ok, fail: str, done: str) -> int:
  205. """Single-mutation handlers: print ``done`` (rc 0) or ``fail`` to stderr (rc 1)."""
  206. if not ok:
  207. return _err(fail)
  208. print(done)
  209. return 0
  210. def _bulk_ids(args: argparse.Namespace) -> list[str]:
  211. """Positional ``task_id`` plus ``--ids`` extras (bulk verbs)."""
  212. return [args.task_id] + list(getattr(args, "ids", None) or [])
  213. def _require_ids(args: argparse.Namespace) -> tuple[list[str], int]:
  214. """``args.task_ids`` -> ``(ids, 0)`` or ``([], 1)`` after printing the standard error."""
  215. ids = list(args.task_ids or [])
  216. if not ids:
  217. return ids, _err("at least one task_id is required")
  218. return ids, 0
  219. def _parse_duration(val) -> Optional[int]:
  220. """``30s`` / ``5m`` / ``2h`` / ``1d`` or a raw integer → seconds; None for empty input;
  221. ValueError on malformed input."""
  222. if val is None or val == "":
  223. return None
  224. s = str(val).strip().lower()
  225. try:
  226. return int(s) # bare integer → seconds
  227. except ValueError:
  228. pass
  229. units = {"s": 1, "m": 60, "h": 3600, "d": 86400}
  230. if not (s and s[-1] in units):
  231. raise ValueError(f"malformed duration {val!r} (expected 30s, 5m, 2h, 1d, or a number)")
  232. try:
  233. n = float(s[:-1])
  234. except ValueError as exc:
  235. raise ValueError(f"malformed duration {val!r}") from exc
  236. return int(n * units[s[-1]])
  237. def _cmd_init(args: argparse.Namespace) -> int:
  238. path = kb.init_db()
  239. print(f"Kanban DB initialized at {path}")
  240. print()
  241. # Profiles on disk == assignees already addressable.
  242. try:
  243. profiles = kb.list_profiles_on_disk()
  244. except Exception:
  245. profiles = []
  246. if profiles:
  247. print(f"Discovered {len(profiles)} profile(s) on disk; any of these can be an --assignee:")
  248. for name in profiles:
  249. print(f" {name}")
  250. else:
  251. print("No profiles found under ~/.hermes/profiles/.\n"
  252. "Create one with `hermes -p <name> setup` before assigning tasks.")
  253. print(
  254. "\nNext step: start the gateway so ready tasks actually get picked up.\n"
  255. " hermes gateway start\n\n"
  256. "The gateway hosts an embedded dispatcher that ticks every 60 seconds\n"
  257. "by default (config: kanban.dispatch_interval_seconds). Without a\n"
  258. "running gateway, tasks stay in 'ready' forever."
  259. )
  260. return 0
  261. def _cmd_heartbeat(args: argparse.Namespace) -> int:
  262. with kbc.connect_closing() as conn:
  263. ok = kbd.heartbeat_worker(conn, args.task_id, note=getattr(args, "note", None),
  264. expected_run_id=_worker_run_id_for(args.task_id))
  265. return _ok_or_err(ok, f"cannot heartbeat {args.task_id} (not running?)",
  266. f"Heartbeat recorded for {args.task_id}")
  267. def _cmd_assignees(args: argparse.Namespace) -> int:
  268. with kbc.connect_closing() as conn:
  269. data = kb.known_assignees(conn)
  270. if _json_out(args, data):
  271. return 0
  272. if not data:
  273. print("(no assignees — create a profile with `hermes -p <name> setup`)")
  274. return 0
  275. print(f"{'NAME':20s} {'ON DISK':8s} COUNTS")
  276. for entry in data:
  277. on_disk = "yes" if entry["on_disk"] else "no"
  278. print(f"{entry['name']:20s} {on_disk:8s} {_fmt_counts(entry['counts'] or {}, '(idle)')}")
  279. return 0
  280. def _cmd_create(args: argparse.Namespace) -> int:
  281. from agent.delegation_context import is_dispatcher_owned_worker_context
  282. body = args.body
  283. body_file = getattr(args, "body_file", None)
  284. if body is not None and body_file is not None:
  285. return _err("kanban: --body and --body-file are mutually exclusive", 2)
  286. if body_file is not None:
  287. try:
  288. body = sys.stdin.read() if body_file == "-" else Path(body_file).read_text(encoding="utf-8-sig")
  289. except OSError as exc:
  290. return _err(f"kanban: --body-file: {exc}", 2)
  291. try:
  292. ws_kind, ws_path = _parse_workspace_flag(args.workspace)
  293. branch_name = _parse_branch_flag(getattr(args, "branch", None))
  294. except argparse.ArgumentTypeError as exc:
  295. return _err(f"kanban: {exc}", 2)
  296. if branch_name and ws_kind != "worktree":
  297. return _err("kanban: --branch is only valid with --workspace worktree", 2)
  298. try:
  299. max_runtime = _parse_duration(getattr(args, "max_runtime", None))
  300. except ValueError as exc:
  301. return _err(f"kanban: --max-runtime: {exc}", 2)
  302. max_retries = getattr(args, "max_retries", None)
  303. if max_retries is not None and max_retries < 1:
  304. return _err(f"kanban: --max-retries must be >= 1 (got {max_retries}); "
  305. "use 1 to trip on the first failure.", 2)
  306. with kbc.connect_closing() as conn:
  307. task_id = kb.create_task(
  308. conn, title=args.title, body=body, assignee=args.assignee,
  309. created_by=args.created_by or _profile_author(),
  310. workspace_kind=ws_kind, workspace_path=ws_path, branch_name=branch_name,
  311. project_id=getattr(args, "project", None), tenant=args.tenant, priority=args.priority,
  312. parents=tuple(args.parent or ()), triage=bool(getattr(args, "triage", False)),
  313. idempotency_key=getattr(args, "idempotency_key", None),
  314. max_runtime_seconds=max_runtime, skills=getattr(args, "skills", None) or None,
  315. max_retries=max_retries, model_override=getattr(args, "model_override", None),
  316. provider_override=getattr(args, "provider_override", None),
  317. goal_mode=bool(getattr(args, "goal_mode", False)),
  318. goal_max_turns=getattr(args, "goal_max_turns", None),
  319. completion_contract=getattr(args, "completion_contract", None),
  320. initial_status=getattr(args, "initial_status", "running"),
  321. creator_task_id=(os.environ.get("HERMES_KANBAN_TASK")
  322. if is_dispatcher_owned_worker_context() else None),
  323. )
  324. task = kb.get_task(conn, task_id)
  325. if getattr(args, "json", False):
  326. _print_json(_task_to_dict(task))
  327. else:
  328. print(f"Created {task_id} ({task.status}, assignee={task.assignee or '-'})")
  329. # Warn only for ready+assigned tasks that would sit without a dispatcher (triage/todo idle
  330. # by design, unassigned can't dispatch); skipped under --json so stdout stays parseable.
  331. if task.status == "ready" and task.assignee:
  332. running, message = _check_dispatcher_presence()
  333. if not running and message:
  334. print(f"\n⚠ {message}", file=sys.stderr)
  335. return 0
  336. def _cmd_swarm(args: argparse.Namespace) -> int:
  337. try:
  338. workers = [ks.parse_worker_arg(raw) for raw in (args.worker or [])]
  339. except ValueError as exc:
  340. return _err(f"kanban swarm: {exc}", 2)
  341. if not workers:
  342. return _err("kanban swarm: at least one --worker is required", 2)
  343. with kbc.connect_closing() as conn:
  344. created = ks.create_swarm(
  345. conn, goal=args.goal, workers=workers, verifier_assignee=args.verifier,
  346. synthesizer_assignee=args.synthesizer, tenant=args.tenant,
  347. created_by=args.created_by or _profile_author(), priority=args.priority,
  348. idempotency_key=getattr(args, "idempotency_key", None),
  349. )
  350. if getattr(args, "json", False):
  351. _print_json(created.as_dict())
  352. else:
  353. print(f"Swarm root: {created.root_id}\n"
  354. "Workers: " + ", ".join(created.worker_ids) + "\n"
  355. f"Verifier: {created.verifier_id}\n"
  356. f"Synthesizer: {created.synthesizer_id}")
  357. return 0
  358. def _cmd_list(args: argparse.Namespace) -> int:
  359. assignee = args.assignee
  360. if args.mine and not assignee:
  361. assignee = _profile_author()
  362. with kbc.connect_closing() as conn:
  363. # Cheap mini-dispatch so list reflects dependencies cleared since the last tick.
  364. kb.recompute_ready(conn)
  365. tasks = kb.list_tasks(
  366. conn, assignee=assignee, status=args.status, tenant=args.tenant, session_id=args.session,
  367. include_archived=args.archived, order_by=getattr(args, "sort", None),
  368. workflow_template_id=args.workflow_template_id, current_step_key=args.current_step_key,
  369. )
  370. if _json_out(args, [_task_to_dict(t) for t in tasks]):
  371. return 0
  372. # Passive discoverability: only multi-board users see which board this is.
  373. try:
  374. all_boards = kb.list_boards(include_archived=False)
  375. except Exception:
  376. all_boards = []
  377. if len(all_boards) > 1:
  378. other_count = len(all_boards) - 1
  379. print(f"Board: {kb.get_current_board()} ({other_count} other board{'s' if other_count != 1 else ''} — "
  380. f"`hermes kanban boards list`)\n")
  381. if not tasks:
  382. print("(no matching tasks)")
  383. return 0
  384. for t in tasks:
  385. print(_fmt_task_line(t))
  386. return 0
  387. def _print_diagnostics(diags, indent: str, *, with_kind: bool) -> None:
  388. """Shared human rendering for ``show`` and ``diagnostics`` (suggested actions only)."""
  389. sev_marker = {"warning": "⚠", "error": "!!", "critical": "!!!"}
  390. for d in diags:
  391. head = f"{d.kind}: {d.title}" if with_kind else d.title
  392. print(f"{indent}{sev_marker.get(d.severity, '?')} [{d.severity}] {head}")
  393. if d.data:
  394. bits = [f"{k}={','.join(str(x) for x in v)}" if isinstance(v, list) else f"{k}={v}"
  395. for k, v in d.data.items()]
  396. if bits:
  397. print(f"{indent} data: {' | '.join(bits)}")
  398. for a in d.actions:
  399. if a.suggested:
  400. print(f"{indent} → {a.label}")
  401. def _print_section(title: str, lines) -> None:
  402. """Blank line, ``title``, then each line (``show`` body sections)."""
  403. print()
  404. print(title)
  405. for line in lines:
  406. print(line)
  407. def _cmd_show(args: argparse.Namespace) -> int:
  408. rsk, rc = _run_state_kwargs(args, "show")
  409. if rc:
  410. return rc
  411. graph = None
  412. want_json = getattr(args, "json", False)
  413. with kbc.connect_closing() as conn:
  414. task = kb.get_task(conn, args.task_id)
  415. if not task:
  416. return _err(f"no such task: {args.task_id}")
  417. comments = kb.list_comments(conn, args.task_id)
  418. events = kb.list_events(conn, args.task_id)
  419. parents = kb.parent_ids(conn, args.task_id)
  420. children = kb.child_ids(conn, args.task_id)
  421. runs = kb.list_runs(conn, args.task_id, **rsk)
  422. # Workers hand off via task_runs.summary; tasks.result stays NULL unless set.
  423. latest_summary = kb.latest_summary(conn, args.task_id)
  424. if not want_json:
  425. graph = kb.task_graph_context(conn, task.id)
  426. if want_json:
  427. _print_json({
  428. "task": _task_to_dict(task), "latest_summary": latest_summary, "parents": parents, "children": children,
  429. "comments": [_obj_dict(c, ("author", "body", "created_at")) for c in comments],
  430. "events": [_obj_dict(e, ("kind", "payload", "created_at", "run_id")) for e in events],
  431. "runs": [_obj_dict(r, _SHOW_RUN_FIELDS) for r in runs],
  432. })
  433. return 0
  434. def field(label: str, value) -> None:
  435. print(f" {label + ':':<11}{value}")
  436. print(f"Task {task.id}: {task.title}")
  437. field("status", task.status)
  438. field("assignee", task.assignee or "-")
  439. if task.tenant:
  440. field("tenant", task.tenant)
  441. field("workspace", f"{task.workspace_kind}" + (f" @ {task.workspace_path}" if task.workspace_path else ""))
  442. if task.branch_name:
  443. field("branch", task.branch_name)
  444. if task.skills:
  445. field("skills", ", ".join(task.skills))
  446. if task.model_override:
  447. _prov = f" (provider: {task.provider_override})" if task.provider_override else ""
  448. field("model", f"{task.model_override}{_prov}")
  449. # Effective retry threshold (task > config > default) explains auto-blocks.
  450. if task.max_retries is not None:
  451. print(f" max-retries: {task.max_retries} (task)")
  452. else:
  453. cfg_val = _kanban_config().get("failure_limit")
  454. if cfg_val is not None and int(cfg_val) != kb.DEFAULT_FAILURE_LIMIT:
  455. print(f" max-retries: {int(cfg_val)} (config kanban.failure_limit)")
  456. else:
  457. print(f" max-retries: {kb.DEFAULT_FAILURE_LIMIT} (default)")
  458. field("created", f"{_fmt_ts(task.created_at)} by {task.created_by or '-'}")
  459. # Diagnostics up top so CLI users see distress signals before scrolling.
  460. from hermes_cli import kanban_diagnostics as kd
  461. diags = kd.compute_task_diagnostics(task, events, runs, graph=graph)
  462. if diags:
  463. print(f"\n Diagnostics ({len(diags)}):")
  464. _print_diagnostics(diags, " ", with_kind=False)
  465. if task.started_at:
  466. field("started", _fmt_ts(task.started_at))
  467. if task.completed_at:
  468. field("completed", _fmt_ts(task.completed_at))
  469. if parents:
  470. field("parents", ", ".join(parents))
  471. if children:
  472. field("children", ", ".join(children))
  473. if task.body:
  474. _print_section("Body:", [task.body])
  475. if task.result:
  476. _print_section("Result:", [task.result])
  477. elif latest_summary:
  478. _print_section("Latest summary:", [latest_summary])
  479. if comments:
  480. _print_section(f"Comments ({len(comments)}):",
  481. (f" [{_fmt_ts(c.created_at)}] {c.author}: {c.body}" for c in comments))
  482. if events:
  483. _print_section(f"Events ({len(events)}):", (
  484. f" [{_fmt_ts(e.created_at)}]{f' [run {e.run_id}]' if e.run_id else ''} {e.kind}"
  485. f"{f' {e.payload}' if e.payload else ''}" for e in events[-20:]))
  486. if runs:
  487. print()
  488. print(f"Runs ({len(runs)}):")
  489. for r in runs:
  490. # Clamp to 0 so NTP backward-jumps don't print negative seconds.
  491. elapsed = max(0, r.ended_at - r.started_at) if r.ended_at else None
  492. el = f"{elapsed}s" if elapsed is not None else "active"
  493. outcome = r.outcome or r.status or "active"
  494. print(f" #{r.id:<3} {outcome:<12} @{r.profile or '-'} {el} {_fmt_ts(r.started_at)}")
  495. if r.summary:
  496. print(f" → {r.summary.splitlines()[0][:160]}")
  497. if r.error:
  498. print(f" ! {r.error.splitlines()[0][:160]}")
  499. return 0
  500. def _cmd_assign(args: argparse.Namespace) -> int:
  501. profile = _none_profile(args.profile)
  502. with kbc.connect_closing() as conn:
  503. ok = kb.assign_task(conn, args.task_id, profile)
  504. return _ok_or_err(ok, f"no such task: {args.task_id}",
  505. f"Assigned {args.task_id} to {profile or '(unassigned)'}")
  506. def _cmd_set_model(args: argparse.Namespace) -> int:
  507. model = args.model
  508. if model is not None and model.lower() in {"none", "-", "null", ""}:
  509. model = None
  510. provider = getattr(args, "provider", None)
  511. try:
  512. with kbc.connect_closing() as conn:
  513. ok = kb.set_model_override(conn, args.task_id, model, provider=provider)
  514. except (ValueError, RuntimeError) as exc:
  515. return _err(f"kanban: {exc}", 2)
  516. if not ok:
  517. return _err(f"no such task: {args.task_id}")
  518. if model:
  519. label = f"{provider}:{model}" if provider else model
  520. print(f"Set model override on {args.task_id}: {label} (applies on next dispatch)")
  521. else:
  522. print(f"Cleared model override on {args.task_id} (worker uses its profile default)")
  523. return 0
  524. def _cmd_reclaim(args: argparse.Namespace) -> int:
  525. with kbc.connect_closing() as conn:
  526. ok = kb.reclaim_task(conn, args.task_id, reason=getattr(args, "reason", None))
  527. return _ok_or_err(ok, f"cannot reclaim {args.task_id} (not running or unknown id)",
  528. f"Reclaimed {args.task_id}")
  529. def _cmd_reassign(args: argparse.Namespace) -> int:
  530. profile = _none_profile(args.profile)
  531. reclaim = bool(getattr(args, "reclaim", False))
  532. with kbc.connect_closing() as conn:
  533. ok = kb.reassign_task(conn, args.task_id, profile, reclaim_first=reclaim, reason=getattr(args, "reason", None))
  534. return _ok_or_err(
  535. ok,
  536. f"cannot reassign {args.task_id} (unknown id, or still running — pass --reclaim to release first)",
  537. f"Reassigned {args.task_id} to {profile or '(unassigned)'}" + (" (claim reclaimed)" if reclaim else ""),
  538. )
  539. def _rows_by_task(conn, table: str, ids: list[str]) -> dict[str, list]:
  540. """``{task_id: [rows ordered by id]}`` for every id (empty list when none)."""
  541. by = {i: [] for i in ids}
  542. placeholders = ",".join(["?"] * len(ids))
  543. for row in conn.execute(f"SELECT * FROM {table} WHERE task_id IN ({placeholders}) ORDER BY id", tuple(ids)):
  544. by.setdefault(row["task_id"], []).append(row)
  545. return by
  546. def _cmd_diagnostics(args: argparse.Namespace) -> int:
  547. """List active diagnostics on the board via the same rule engine the dashboard uses."""
  548. from hermes_cli import kanban_diagnostics as kd
  549. # Honour kanban.default_assignee as the fallback for unassigned ready tasks (#27145),
  550. # kanban.max_in_progress as the global concurrency cap (#33488), kanban.max_in_progress_per_profile as
  551. # the per-profile cap (#21582), and kanban.max_spawn as the per-tick spawn limit (#28805). Same
  552. # semantics as the gateway dispatch path so behavior matches whether the user runs the CLI directly or
  553. # relies on the gateway-embedded dispatcher.
  554. from hermes_cli.config import load_config
  555. diag_config = kd.config_from_runtime_config(load_config())
  556. with kbc.connect_closing() as conn:
  557. # Either one-task mode or fleet mode.
  558. if getattr(args, "task", None):
  559. task = kb.get_task(conn, args.task)
  560. if task is None:
  561. return _err(f"no such task: {args.task}")
  562. diags_by_task = {args.task: kd.compute_task_diagnostics(
  563. task, kb.list_events(conn, args.task), kb.list_runs(conn, args.task),
  564. graph=kb.task_graph_context(conn, args.task), config=diag_config)}
  565. else:
  566. # Fleet mode: pull all non-archived tasks + their events/runs.
  567. rows = list(conn.execute("SELECT * FROM tasks WHERE status != 'archived'").fetchall())
  568. ids = [r["id"] for r in rows]
  569. diags_by_task = {}
  570. if ids:
  571. ev_by = _rows_by_task(conn, "task_events", ids)
  572. run_by = _rows_by_task(conn, "task_runs", ids)
  573. graph_by = kb.task_graph_contexts(conn, ids)
  574. for r in rows:
  575. tid = r["id"]
  576. dl = kd.compute_task_diagnostics(r, ev_by.get(tid, []), run_by.get(tid, []),
  577. graph=graph_by.get(tid), config=diag_config)
  578. if dl:
  579. diags_by_task[tid] = dl
  580. sev = getattr(args, "severity", None)
  581. if sev:
  582. floor = kd.SEVERITY_ORDER.index(sev)
  583. diags_by_task = {tid: kept for tid, dl in diags_by_task.items()
  584. if (kept := [d for d in dl if kd.SEVERITY_ORDER.index(d.severity) >= floor])}
  585. # Map task_id → title/status/assignee for the table output.
  586. meta: dict[str, dict] = {}
  587. if diags_by_task:
  588. placeholders = ",".join(["?"] * len(diags_by_task))
  589. for r in conn.execute(f"SELECT id, title, status, assignee FROM tasks WHERE id IN ({placeholders})",
  590. tuple(diags_by_task.keys())):
  591. meta[r["id"]] = {k: r[k] for k in ("title", "status", "assignee")}
  592. # What this home believes it may claim on a shared board (#113620).
  593. allowlist = kbd.dispatch_profile_allowlist_summary()
  594. if getattr(args, "json", False):
  595. # Per-task rows unchanged; the home-scope allowlist rides as a trailing row
  596. # (task_id null) so existing `payload[0]["diagnostics"]` consumers keep working.
  597. _print_json([{"task_id": tid, **meta.get(tid, {}), "diagnostics": [d.to_dict() for d in dl]}
  598. for tid, dl in diags_by_task.items()]
  599. + [{"task_id": None, "dispatch_profiles": allowlist, "diagnostics": []}])
  600. return 0
  601. print(f"kanban.dispatch_profiles: {allowlist}")
  602. if not diags_by_task:
  603. print("No active diagnostics on this board.")
  604. return 0
  605. total = sum(len(dl) for dl in diags_by_task.values())
  606. print(f"{total} active diagnostic(s) across {len(diags_by_task)} task(s):\n")
  607. for tid, dl in diags_by_task.items():
  608. m = meta.get(tid, {})
  609. print(f" {tid} {m.get('status') or '?':8s} @{m.get('assignee') or '(unassigned)':18s} "
  610. f"{m.get('title') or '(untitled)'}")
  611. _print_diagnostics(dl, " ", with_kind=True)
  612. print()
  613. return 0
  614. def _cmd_link(args: argparse.Namespace) -> int:
  615. # A worker linking its own running card (dependency-block handoff) proves
  616. # ownership with its run id; linking a foreign task never needs one.
  617. expected_child_run_id = (
  618. _worker_run_id_for(args.child_id)
  619. if args.child_id == os.environ.get("HERMES_KANBAN_TASK") else None)
  620. with kbc.connect_closing() as conn:
  621. gated = kb.link_tasks(conn, args.parent_id, args.child_id,
  622. expected_child_run_id=expected_child_run_id)
  623. print(f"Linked {args.parent_id} -> {args.child_id}")
  624. if gated:
  625. print(
  626. f"Note: {args.child_id} was ready and is now todo — parent "
  627. f"{args.parent_id} is not done yet. The ready -> running claim "
  628. f"re-checks parents, so the child only runs after the parent "
  629. f"completes; use `hermes kanban unlink {args.parent_id} {args.child_id}` "
  630. f"to run it now."
  631. )
  632. return 0
  633. def _cmd_unlink(args: argparse.Namespace) -> int:
  634. with kbc.connect_closing() as conn:
  635. ok = kb.unlink_tasks(conn, args.parent_id, args.child_id)
  636. return _ok_or_err(ok, f"No such link: {args.parent_id} -> {args.child_id}",
  637. f"Unlinked {args.parent_id} -> {args.child_id}")
  638. def _cmd_claim(args: argparse.Namespace) -> int:
  639. with kbc.connect_closing() as conn:
  640. task = kb.claim_task(conn, args.task_id, ttl_seconds=args.ttl)
  641. if task is None:
  642. existing = kb.get_task(conn, args.task_id)
  643. if existing is None:
  644. return _err(f"no such task: {args.task_id}")
  645. return _err(f"cannot claim {args.task_id}: status={existing.status} "
  646. f"lock={existing.claim_lock or '(none)'}")
  647. workspace = kbw.resolve_workspace(task)
  648. kbw.set_workspace_path(conn, task.id, str(workspace))
  649. print(f"Claimed {task.id}\nWorkspace: {workspace}")
  650. return 0
  651. def _cmd_comment(args: argparse.Namespace) -> int:
  652. body = " ".join(args.text).strip()
  653. if args.max_len is not None:
  654. if args.max_len < 1:
  655. return _err("kanban: --max-len must be positive", 2)
  656. if len(body) > args.max_len:
  657. suffix = f"\n\n[trimmed to {args.max_len} chars by --max-len]"
  658. body = body[: max(0, args.max_len - len(suffix))].rstrip() + suffix
  659. author = args.author or _profile_author()
  660. with kbc.connect_closing() as conn:
  661. kb.add_comment(conn, args.task_id, author, body)
  662. print(f"Comment added to {args.task_id}")
  663. return 0
  664. def _cmd_attach(args: argparse.Namespace) -> int:
  665. """Attach a local file via the shared ``store_attachment_bytes`` path (same 25 MB cap and name
  666. sanitisation as the dashboard upload and agent tool)."""
  667. import mimetypes
  668. _worker_run_id_for(args.task_id)
  669. src = Path(args.path).expanduser()
  670. if not src.is_file():
  671. return _err(f"kanban: no such file: {src}")
  672. data = src.read_bytes()
  673. name = args.name or src.name
  674. content_type = args.content_type or mimetypes.guess_type(name)[0]
  675. uploaded_by = args.author or _profile_author()
  676. try:
  677. with kbc.connect_closing() as conn:
  678. att_id = kb.store_attachment_bytes(conn, args.task_id, name, data, content_type=content_type,
  679. uploaded_by=uploaded_by)
  680. except kb.AttachmentTooLarge as exc:
  681. return _err(f"kanban: {exc}")
  682. print(f"Attached {name} to {args.task_id} (attachment {att_id}, {len(data)} bytes)")
  683. return 0
  684. def _cmd_attachments(args: argparse.Namespace) -> int:
  685. with kbc.connect_closing() as conn:
  686. if kb.get_task(conn, args.task_id) is None:
  687. return _err(f"no such task: {args.task_id}")
  688. atts = kb.list_attachments(conn, args.task_id)
  689. if _json_out(args, [_obj_dict(a, _ATTACHMENT_FIELDS) for a in atts], ascii=True):
  690. return 0
  691. if not atts:
  692. print(f"No attachments on {args.task_id}")
  693. return 0
  694. print(f"Attachments on {args.task_id}:")
  695. for a in atts:
  696. ct = a.content_type or "-"
  697. print(f" [{a.id}] {a.filename} ({a.size} bytes, {ct}, by {a.uploaded_by or '-'})")
  698. print(f" {a.stored_path}")
  699. return 0
  700. def _cmd_attach_rm(args: argparse.Namespace) -> int:
  701. with kbc.connect_closing() as conn:
  702. removed = kb.delete_attachment(conn, args.attachment_id)
  703. if removed is None:
  704. return _err(f"no such attachment: {args.attachment_id}")
  705. print(f"Deleted attachment {args.attachment_id} ({removed.filename}) from {removed.task_id}")
  706. return 0
  707. def _worker_run_id_for(task_id: str) -> Optional[int]:
  708. env_tid = os.environ.get("HERMES_KANBAN_TASK")
  709. if env_tid and env_tid != task_id:
  710. raise ValueError(f"worker is scoped to task {env_tid}; refusing to mutate {task_id}")
  711. raw = os.environ.get("HERMES_KANBAN_RUN_ID")
  712. if os.environ.get("HERMES_KANBAN_TASK") != task_id or not raw:
  713. return None
  714. try:
  715. return int(raw)
  716. except ValueError:
  717. return None
  718. def _goal_mode_handoff_rejection(task: Optional[kb.Task], evidence: str):
  719. """Goal judge for every terminal worker handoff (including review).
  720. Returns ``(verdict, reason_or_None)``: ``"done"`` allows; ``"blocked"`` = judge ruled the goal
  721. unachievable; ``"continue"``/``"wait"`` reject with the judge's reason. Judge failures allow
  722. the handoff (logged).
  723. See #100954.
  724. ``{"done", None}`` means the judge allows the handoff; anything else is a rejection whose verdict
  725. disambiguates the guidance the caller gives the worker (``continue`` = not done yet, ``blocked`` =
  726. judged unachievable — see #100954).
  727. """
  728. if task is None or not task.goal_mode:
  729. return ("done", None)
  730. try:
  731. from agent.auxiliary_client import get_text_auxiliary_client
  732. client, model = get_text_auxiliary_client("goal_judge")
  733. except Exception:
  734. client, model = None, None
  735. if client is None or not model:
  736. return ("done", None)
  737. from hermes_cli.goals import judge_goal
  738. verdict, reason, transport_failed = "done", "", False
  739. try:
  740. # Headless handoff checks run outside any agent turn: bind the per-task relay-affinity
  741. # scope (mirrors kanban_specify) so the relay does not reject the judge call (#113669).
  742. from agent.portal_tags import get_affinity_scope, reset_affinity_scope, set_affinity_scope
  743. affinity_token = None if get_affinity_scope() else set_affinity_scope(f"kanban:{task.id}")
  744. try:
  745. verdict, reason, _, _, transport_failed = judge_goal(
  746. goal=f"{task.title}\n\n{task.body or ''}".strip(),
  747. last_response=evidence.strip())
  748. finally:
  749. if affinity_token is not None:
  750. reset_affinity_scope(affinity_token)
  751. except Exception as judge_exc:
  752. import logging as _logging
  753. _logging.getLogger(__name__).warning("goal judge check failed, allowing lifecycle handoff: %s",
  754. judge_exc, exc_info=True)
  755. if transport_failed:
  756. # ``judge_goal`` fails open to ``continue`` on transport errors (relay 400, auth, timeout);
  757. # an unreachable judge is not a human "not done" and must not reject the handoff (#83610).
  758. import logging as _logging
  759. _logging.getLogger(__name__).warning("goal judge unreachable (%s), allowing lifecycle handoff", reason)
  760. return ("done", None)
  761. return (verdict, None if verdict == "done" else reason)
  762. def _goal_gate_error(conn, tid: str, evidence: str, handoff: str, blocked_hint: str,
  763. continue_hint: str) -> Optional[str]:
  764. """Goal-mode judge gate shared by ``complete`` / ``request-review`` (mirrors tools/kanban_tools.py);
  765. applied to every terminal handoff so request-review can't bypass it. Returns the error line, or
  766. None to allow."""
  767. verdict, rejection = _goal_mode_handoff_rejection(kb.get_task(conn, tid), evidence)
  768. if verdict == "blocked":
  769. return (f"kanban: goal {handoff} of {tid} rejected: judge ruled "
  770. f"the goal unachievable — {rejection}. {blocked_hint}")
  771. if rejection is not None:
  772. return f"kanban: goal {handoff} of {tid} rejected by judge: {rejection}. {continue_hint}"
  773. return None
  774. def _cmd_complete(args: argparse.Namespace) -> int:
  775. """Mark one or more tasks done. Supports a single id or a list."""
  776. ids, rc = _require_ids(args)
  777. if rc:
  778. return rc
  779. summary = getattr(args, "summary", None)
  780. raw_meta = getattr(args, "metadata", None)
  781. # Handoff fields are per-run; refuse to copy them across N runs.
  782. if len(ids) > 1 and (summary or raw_meta):
  783. return _err("kanban: --summary / --metadata are per-task and can't be used "
  784. "with multiple ids (would apply the same handoff to every task). "
  785. "Complete tasks one at a time, or drop the flags for the bulk close.", 2)
  786. metadata, rc = _parse_metadata_flag(raw_meta)
  787. if rc:
  788. return rc
  789. fail_msg: dict[str, str] = {}
  790. with kbc.connect_closing() as conn:
  791. def op(tid):
  792. gate_err = _goal_gate_error(
  793. conn, tid, (summary or args.result or "").strip(), "completion",
  794. "Re-scope with kanban edit, or record the block with kanban block instead of completing.",
  795. "Provide evidence matching the task's acceptance criteria.")
  796. if gate_err:
  797. fail_msg[tid] = gate_err
  798. return False
  799. fail_msg[tid] = f"cannot complete {tid} (unknown id or terminal state)"
  800. try:
  801. done = kb.complete_task(conn, tid, result=args.result, summary=summary, metadata=metadata,
  802. expected_run_id=_worker_run_id_for(tid),
  803. force=bool(getattr(args, "force", False)))
  804. except kb.LiveClaimError:
  805. fail_msg[tid] = (f"cannot complete {tid}: a live worker is running it. Wait for the "
  806. f"worker, `hermes kanban reclaim {tid}` to release it, or re-run with "
  807. f"--force to close its run and complete anyway.")
  808. return False
  809. except kb.EmptyCompletionError as empty_err:
  810. fail_msg[tid] = (f"cannot complete {tid}: {empty_err}. Pass --result/--summary "
  811. f"describing what was done (an empty completion is not evidence).")
  812. return False
  813. if not done:
  814. # complete_task returns bare False for a dependency refusal too;
  815. # name the open parents instead of claiming the id is unknown.
  816. blockers = kb.unsatisfied_parents(conn, tid)
  817. if blockers:
  818. detail = ", ".join(f"{pid} ({status})" for pid, status in blockers)
  819. fail_msg[tid] = (f"cannot complete {tid}: unsatisfied parent dependencies: {detail}; "
  820. f"complete the parents first, or `hermes kanban unlink <parent> {tid}`.")
  821. return done
  822. return _bulk_apply(ids, op, lambda tid: f"Completed {tid}", fail_msg.__getitem__)
  823. def _cmd_edit(args: argparse.Namespace) -> int:
  824. result = getattr(args, "result", None)
  825. raw_metadata = getattr(args, "metadata", None)
  826. summary = getattr(args, "summary", None)
  827. title = getattr(args, "title", None)
  828. body = getattr(args, "body", None)
  829. priority = getattr(args, "priority", None)
  830. if result is None and (summary is not None or raw_metadata is not None):
  831. return _err("kanban edit: --summary and --metadata require --result", 2)
  832. if all(value is None for value in (title, body, priority, result)):
  833. return _err("kanban edit: provide --title, --body, --priority, or --result", 2)
  834. metadata, rc = _parse_metadata_flag(raw_metadata)
  835. if rc:
  836. return rc
  837. with kbc.connect_closing() as conn:
  838. ok = kb.edit_task(
  839. conn, args.task_id, title=title, body=body, priority=priority,
  840. result=result, summary=summary, metadata=metadata,
  841. )
  842. return _ok_or_err(
  843. ok,
  844. f"cannot edit {args.task_id} (unknown id, or --result used on a task that is not done)",
  845. f"Edited {args.task_id}",
  846. )
  847. def _commented(conn, reason: Optional[str], author, prefix: str, op):
  848. """Wrap a per-task ``op`` so a ``reason`` is first recorded as a ``PREFIX: reason`` comment."""
  849. def run(tid):
  850. if reason:
  851. kb.add_comment(conn, tid, author, f"{prefix}: {reason}")
  852. return op(tid)
  853. return run
  854. def _cmd_block(args: argparse.Namespace) -> int:
  855. reason = _joined_words(args.reason)
  856. kind = getattr(args, "kind", None)
  857. author = _profile_author()
  858. ids = _bulk_ids(args)
  859. suffix = f": {reason}" if reason else ""
  860. with kbc.connect_closing() as conn:
  861. def ok_msg(tid):
  862. # Report where it landed: dependency blocks -> todo, tripped unblock-loop breaker -> triage.
  863. landed = kb.get_task(conn, tid)
  864. where = landed.status if landed else "blocked"
  865. if where == "todo":
  866. return f"{tid} → todo (dependency wait){suffix}"
  867. if kind == "dependency" and where == "blocked":
  868. return f"Blocked {tid} as needs_input (no open parent to wait on){suffix}"
  869. if where == "triage":
  870. # Only a typed owner-input block carries a question for a human.
  871. verdict = ("needs a human decision" if (landed.block_kind if landed else kind) == "needs_input"
  872. else "orchestration attention needed")
  873. return f"{tid} → triage (unblock loop detected — {verdict}){suffix}"
  874. return f"Blocked {tid}{suffix}"
  875. op = _commented(conn, reason, author, "BLOCKED", lambda tid: kb.block_task(
  876. conn, tid, reason=reason, kind=kind, expected_run_id=_worker_run_id_for(tid)))
  877. return _bulk_apply(ids, op, ok_msg, lambda tid: f"cannot block {tid}")
  878. def _cmd_schedule(args: argparse.Namespace) -> int:
  879. reason = _joined_words(args.reason)
  880. author = _profile_author()
  881. ids = _bulk_ids(args)
  882. suffix = f": {reason}" if reason else ""
  883. with kbc.connect_closing() as conn:
  884. op = _commented(conn, reason, author, "SCHEDULED", lambda tid: kb.schedule_task(
  885. conn, tid, reason=reason, expected_run_id=_worker_run_id_for(tid)))
  886. return _bulk_apply(ids, op, lambda tid: f"Scheduled {tid}{suffix}", lambda tid: f"cannot schedule {tid}")
  887. def _cmd_unblock(args: argparse.Namespace) -> int:
  888. if os.environ.get("HERMES_KANBAN_TASK"):
  889. return _err("kanban unblock is orchestrator-only; workers must hand off their assigned task")
  890. ids, rc = _require_ids(args)
  891. if rc:
  892. return rc
  893. reason = _stripped_or_none(getattr(args, "reason", None))
  894. author = _profile_author() if reason else None
  895. suffix = f": {reason}" if reason else ""
  896. with kbc.connect_closing() as conn:
  897. op = _commented(conn, reason, author, "UNBLOCK", lambda tid: kb.unblock_task(conn, tid))
  898. return _bulk_apply(ids, op, lambda tid: f"Unblocked {tid}{suffix}",
  899. lambda tid: f"cannot unblock {tid} (not blocked/scheduled?)")
  900. def _cmd_request_review(args: argparse.Namespace) -> int:
  901. tid = args.task_id
  902. summary = _stripped_or_none(getattr(args, "summary", None))
  903. metadata, rc = _parse_metadata_flag(getattr(args, "metadata", None))
  904. if rc:
  905. return rc
  906. with kbc.connect_closing() as conn:
  907. gate_err = _goal_gate_error(
  908. conn, tid, summary or "", "review handoff",
  909. "Record the block with kanban block instead of requesting review.",
  910. "Provide acceptance evidence matching the task.")
  911. if gate_err:
  912. return _err(gate_err)
  913. ok, reason = kb.request_review(
  914. conn, tid, summary=summary, metadata=metadata, reviewer=getattr(args, "reviewer", None),
  915. expected_run_id=_worker_run_id_for(tid), force=bool(getattr(args, "force", False)), with_reason=True)
  916. if not ok:
  917. return _err(f"cannot request review for {tid}: {reason or 'not running/ready?'}")
  918. persisted_run = kb.latest_run(conn, tid)
  919. display_summary = persisted_run.summary if persisted_run else None
  920. print(f"Requested review for {tid}" + (f": {display_summary}" if display_summary else ""))
  921. return 0
  922. def _cmd_request_changes(args: argparse.Namespace) -> int:
  923. tid = args.task_id
  924. reason = " ".join(args.reason).strip()
  925. with kbc.connect_closing() as conn:
  926. ok, detail = kb.request_changes(conn, tid, reason=reason, expected_run_id=_worker_run_id_for(tid))
  927. if not ok:
  928. return _err(f"cannot request changes for {tid}: {detail or 'invalid review state'}")
  929. print(f"Requested changes for {tid}" + (f"; routed to {detail}" if detail else ""))
  930. return 0
  931. def _cmd_reopen_review(args: argparse.Namespace) -> int:
  932. ids, rc = _require_ids(args)
  933. if rc:
  934. return rc
  935. reason = getattr(args, "reason", None)
  936. if reason is not None:
  937. reason = str(kb.redact_review_value(reason.strip())).strip() or None
  938. author = _profile_author() if reason else None
  939. suffix = f": {reason}" if reason else ""
  940. with kbc.connect_closing() as conn:
  941. def op(tid):
  942. if not kb.reopen_review_task(conn, tid):
  943. return False
  944. if reason:
  945. kb.add_comment(conn, tid, author or "operator", f"CHANGES REQUESTED: {reason}")
  946. return True
  947. return _bulk_apply(ids, op, lambda tid: f"Reopened {tid}{suffix}",
  948. lambda tid: f"cannot reopen {tid} (not in review?)")
  949. def _cmd_promote(args: argparse.Namespace) -> int:
  950. reason = _joined_words(args.reason)
  951. author = _profile_author()
  952. # Dedupe while preserving order; positional task_id always first.
  953. ids = list(dict.fromkeys(_bulk_ids(args)))
  954. dry_run = bool(args.dry_run)
  955. results: list[dict[str, object]] = []
  956. with kbc.connect_closing() as conn:
  957. for tid in ids:
  958. ok, err = kb.promote_task(conn, tid, actor=author, reason=reason, dry_run=dry_run)
  959. results.append({"task_id": tid, "promoted": ok, "dry_run": dry_run,
  960. "reason": reason, "error": err})
  961. failed = [r for r in results if not r["promoted"]]
  962. if getattr(args, "json", False):
  963. # Single-id stays a flat object for back-compat; bulk emits a list.
  964. _print_json(results[0] if len(results) == 1 else results)
  965. return 0 if not failed else 1
  966. tag = " (dry)" if dry_run else ""
  967. label = "Would promote" if dry_run else "Promoted"
  968. suffix = f": {reason}" if reason else ""
  969. for r in results:
  970. if r["promoted"]:
  971. print(f"{label} {r['task_id']} -> ready{tag}{suffix}")
  972. else:
  973. print(f"cannot promote {r['task_id']}: {r['error']}", file=sys.stderr)
  974. return 0 if not failed else 1
  975. def _cmd_archive(args: argparse.Namespace) -> int:
  976. ids = list(args.task_ids or [])
  977. purge_ids = list(getattr(args, "purge_ids", None) or [])
  978. if ids and purge_ids:
  979. return _err("choose either task_ids to archive or --rm archived task_ids")
  980. if not ids and not purge_ids:
  981. return _err("at least one task_id is required")
  982. with kbc.connect_closing() as conn:
  983. if purge_ids:
  984. return _bulk_apply(purge_ids, lambda tid: kb.delete_archived_task(conn, tid), lambda tid: f"Deleted {tid}",
  985. lambda tid: f"cannot delete {tid} (must already be archived)")
  986. return _bulk_apply(ids, lambda tid: kb.archive_task(conn, tid),
  987. lambda tid: f"Archived {tid}", lambda tid: f"cannot archive {tid}")
  988. def _cmd_stats(args: argparse.Namespace) -> int:
  989. with kbc.connect_closing() as conn:
  990. stats = kb.board_stats(conn)
  991. if _json_out(args, stats):
  992. return 0
  993. print("By status:")
  994. for k in kanban_workflow.DEFAULT_WORKFLOW.keys():
  995. print(f" {k:8s} {stats['by_status'].get(k, 0)}")
  996. if stats["by_assignee"]:
  997. print("\nBy assignee:")
  998. for who, counts in sorted(stats["by_assignee"].items()):
  999. print(f" {who:20s} {_fmt_counts(counts)}")
  1000. age = stats["oldest_ready_age_seconds"]
  1001. if age is not None:
  1002. print(f"\nOldest ready task age: {int(age)}s")
  1003. return 0
  1004. def _cmd_notify_subscribe(args: argparse.Namespace) -> int:
  1005. delivery_metadata = {
  1006. key: value
  1007. for key, value in (
  1008. ("parent_chat_id", getattr(args, "parent_chat_id", None)),
  1009. ("guild_id", getattr(args, "guild_id", None)),
  1010. )
  1011. if value
  1012. }
  1013. with kbc.connect_closing() as conn:
  1014. if kb.get_task(conn, args.task_id) is None:
  1015. return _err(f"no such task: {args.task_id}")
  1016. kbn.add_notify_sub(
  1017. conn, task_id=args.task_id, platform=args.platform, chat_id=args.chat_id,
  1018. chat_type=args.chat_type, thread_id=args.thread_id, user_id=args.user_id,
  1019. user_id_alt=getattr(args, "user_id_alt", None),
  1020. notifier_profile=args.notifier_profile or _profile_author(),
  1021. delivery_mode=getattr(args, "delivery_mode", None),
  1022. delivery_metadata=delivery_metadata or None,
  1023. )
  1024. print(f"Subscribed {args.platform}:{args.chat_id}" + (f":{args.thread_id}" if args.thread_id else "")
  1025. + f" to {args.task_id}")
  1026. return 0
  1027. def _cmd_notify_list(args: argparse.Namespace) -> int:
  1028. with kbc.connect_closing() as conn:
  1029. subs = kbn.list_notify_subs(conn, args.task_id)
  1030. if _json_out(args, subs):
  1031. return 0
  1032. if not subs:
  1033. print("(no subscriptions)")
  1034. return 0
  1035. for s in subs:
  1036. thr = f":{s['thread_id']}" if s.get("thread_id") else ""
  1037. dmode, ctype = s.get("delivery_mode") or "notify", s.get("chat_type") or "dm"
  1038. extras = "".join((
  1039. f" owner={s['notifier_profile']}" if s.get("notifier_profile") else "",
  1040. "" if ctype == "dm" else f" chat_type={ctype}",
  1041. f" user_id_alt={s['user_id_alt']}" if s.get("user_id_alt") else "",
  1042. "" if dmode == "notify" else f" mode={dmode}",
  1043. ))
  1044. print(f" {s['task_id']:10s} {s['platform']}:{s['chat_id']}{thr} (since event {s['last_event_id']}){extras}")
  1045. return 0
  1046. def _cmd_notify_unsubscribe(args: argparse.Namespace) -> int:
  1047. with kbc.connect_closing() as conn:
  1048. ok = kbn.remove_notify_sub(conn, task_id=args.task_id, platform=args.platform, chat_id=args.chat_id,
  1049. thread_id=args.thread_id)
  1050. return _ok_or_err(ok, "(no such subscription)", f"Unsubscribed from {args.task_id}")
  1051. def _cmd_log(args: argparse.Namespace) -> int:
  1052. content = kb.read_worker_log(args.task_id, tail_bytes=args.tail)
  1053. if content is None:
  1054. return _err(f"(no log for {args.task_id} — task may not have spawned yet)")
  1055. sys.stdout.write(content)
  1056. if not content.endswith("\n"):
  1057. sys.stdout.write("\n")
  1058. return 0
  1059. def _cmd_runs(args: argparse.Namespace) -> int:
  1060. """Show attempt history for a task."""
  1061. rsk, rc = _run_state_kwargs(args, "runs")
  1062. if rc:
  1063. return rc
  1064. with kbc.connect_closing() as conn:
  1065. runs = kb.list_runs(conn, args.task_id, **rsk)
  1066. if _json_out(args, [_obj_dict(r, _RUNS_RUN_FIELDS) for r in runs]):
  1067. return 0
  1068. if not runs:
  1069. print(f"(no runs yet for {args.task_id})")
  1070. return 0
  1071. print(f"{'#':3s} {'OUTCOME':12s} {'PROFILE':16s} {'ELAPSED':>8s} STARTED")
  1072. for i, r in enumerate(runs, 1):
  1073. end = r.ended_at or int(time.time())
  1074. # Clamp to 0 so NTP backward-jumps don't print negative durations.
  1075. elapsed = max(0, end - r.started_at)
  1076. el = f"{elapsed}s" if elapsed < 60 else f"{elapsed // 60}m" if elapsed < 3600 else f"{elapsed / 3600:.1f}h"
  1077. outcome = r.outcome or ("(running)" if not r.ended_at else r.status)
  1078. print(f"{i:3d} {outcome:12s} {(r.profile or '-'):16s} {el:>8s} {_fmt_ts(r.started_at)}")
  1079. if r.summary:
  1080. print(f" → {r.summary.splitlines()[0][:100]}")
  1081. if r.error:
  1082. print(f" ✖ {r.error[:100]}")
  1083. return 0
  1084. def _cmd_context(args: argparse.Namespace) -> int:
  1085. with kbc.connect_closing() as conn:
  1086. text = kb.build_worker_context(conn, args.task_id)
  1087. print(text)
  1088. return 0
  1089. def _run_triage_sweep(args: argparse.Namespace, verb: str, mod, run_one, json_key: str,
  1090. json_fields: tuple[str, ...], human_ok) -> int:
  1091. """Shared driver for ``specify`` / ``decompose``: validate ids (one task id XOR ``--all``), run
  1092. ``run_one(tid, author=...)`` per id, print JSON or human lines, exit code."""
  1093. all_flag = bool(getattr(args, "all_triage", False))
  1094. author = getattr(args, "author", None) or _profile_author()
  1095. want_json = bool(getattr(args, "json", False))
  1096. tenant = getattr(args, "tenant", None)
  1097. if args.task_id and all_flag:
  1098. return _err("kanban: pass either a task id OR --all, not both", 2)
  1099. if all_flag:
  1100. ids = mod.list_triage_ids(tenant=tenant)
  1101. if not ids:
  1102. if want_json:
  1103. print(json.dumps({json_key: 0, "total": 0}))
  1104. else:
  1105. print("No triage tasks" + (f" for tenant {tenant!r}" if tenant else "") + ".")
  1106. return 0
  1107. elif args.task_id:
  1108. ids = [args.task_id]
  1109. else:
  1110. return _err(f"kanban: {verb} requires a task id or --all", 2)
  1111. ok_count = 0
  1112. for tid in ids:
  1113. outcome = run_one(tid, author=author)
  1114. if outcome.ok:
  1115. ok_count += 1
  1116. if want_json:
  1117. print(json.dumps(_obj_dict(outcome, json_fields)))
  1118. elif outcome.ok:
  1119. print(human_ok(outcome))
  1120. else:
  1121. print(f"kanban: {verb} {outcome.task_id}: {outcome.reason}", file=sys.stderr)
  1122. if not all_flag:
  1123. return 0 if ok_count == 1 else 1
  1124. # --all: exit 1 only when every candidate failed (honest signal for scripts).
  1125. return 0 if (ok_count > 0 or not ids) else 1
  1126. def _retitled_suffix(outcome) -> str:
  1127. return f" — retitled: {outcome.new_title!r}" if outcome.new_title else ""
  1128. def _cmd_specify(args: argparse.Namespace) -> int:
  1129. """Spec a triage task (or all) via the auxiliary LLM, promote to todo."""
  1130. from hermes_cli import kanban_specify as spec
  1131. return _run_triage_sweep(args, "specify", spec, spec.specify_task, "specified",
  1132. ("task_id", "ok", "reason", "new_title"),
  1133. lambda o: f"Specified {o.task_id} → todo{_retitled_suffix(o)}")
  1134. def _decompose_ok_line(o) -> str:
  1135. if o.fanout and o.child_ids:
  1136. return (f"Decomposed {o.task_id} → {len(o.child_ids)} "
  1137. f"children ({', '.join(o.child_ids)}); root promoted to todo")
  1138. return f"Specified {o.task_id} → todo (no fanout){_retitled_suffix(o)}"
  1139. def _cmd_decompose(args: argparse.Namespace) -> int:
  1140. """Fan a triage task (or all) out into child tasks via the auxiliary LLM."""
  1141. from hermes_cli import kanban_decompose as decomp
  1142. return _run_triage_sweep(args, "decompose", decomp, decomp.decompose_task, "decomposed",
  1143. ("task_id", "ok", "reason", "fanout", "child_ids", "new_title"), _decompose_ok_line)
  1144. _HANDLERS = {
  1145. "init": _cmd_init, "create": _cmd_create, "swarm": _cmd_swarm,
  1146. "list": _cmd_list, "ls": _cmd_list, "show": _cmd_show,
  1147. "assign": _cmd_assign, "set-model": _cmd_set_model,
  1148. "reclaim": _cmd_reclaim, "reassign": _cmd_reassign,
  1149. "diagnostics": _cmd_diagnostics, "diag": _cmd_diagnostics,
  1150. "link": _cmd_link, "unlink": _cmd_unlink, "claim": _cmd_claim,
  1151. "comment": _cmd_comment, "attach": _cmd_attach,
  1152. "attachments": _cmd_attachments, "attach-rm": _cmd_attach_rm,
  1153. "complete": _cmd_complete, "edit": _cmd_edit, "block": _cmd_block,
  1154. "schedule": _cmd_schedule, "unblock": _cmd_unblock,
  1155. "request-review": _cmd_request_review, "request-changes": _cmd_request_changes,
  1156. "reopen-review": _cmd_reopen_review, "promote": _cmd_promote,
  1157. "archive": _cmd_archive, "tail": _cmd_tail, "dispatch": _cmd_dispatch,
  1158. "daemon": _cmd_daemon, "watch": _cmd_watch, "stats": _cmd_stats,
  1159. "log": _cmd_log, "runs": _cmd_runs, "heartbeat": _cmd_heartbeat,
  1160. "assignees": _cmd_assignees, "notify-subscribe": _cmd_notify_subscribe,
  1161. "notify-list": _cmd_notify_list, "notify-unsubscribe": _cmd_notify_unsubscribe,
  1162. "context": _cmd_context, "specify": _cmd_specify, "decompose": _cmd_decompose,
  1163. "gc": _cmd_gc,
  1164. }
  1165. # --- Slash-command entry point (used by /kanban from CLI and gateway) ---
  1166. _SLASH_KANBAN_HELP = """\
  1167. **/kanban** — manage the shared task board.
  1168. Common subcommands:
  1169. `list` (alias `ls`) List tasks on the current board
  1170. `show <id>` Task details + comments + events
  1171. `stats` Per-status / per-assignee counts
  1172. `create <title>…` Create a task (auto-subscribes you to events)
  1173. `comment <id> <msg>` Append a comment
  1174. `attach <id> <path>` Attach a local file; `attachments <id>` to list
  1175. `complete <id>…` Mark task(s) done
  1176. `request-review <id>` Enter first-class review; `request-changes <id> <reason>` returns an active review to its implementer
  1177. `block <id> [reason]` Mark blocked; `schedule <id> [reason]` parks time-delay work; `unblock <id>` to revive
  1178. `assign <id> <profile>` Reassign
  1179. `boards list` Show all boards
  1180. `assignees` Known profiles + counts
  1181. `context <id>` Full worker-context dump
  1182. `runs <id>` Attempt history
  1183. `log <id>` Worker log
  1184. Run `/kanban <subcommand> -h` for arguments. \
  1185. Read-only commands are safe while an agent is running.\
  1186. """
  1187. def run_slash(rest: str) -> str:
  1188. """Execute a ``/kanban …`` string (``rest`` = everything after ``/kanban``) and return captured
  1189. stdout/stderr. Shared by the interactive CLI and the gateway so formatting is identical."""
  1190. import io
  1191. # Non-posix split (Windows) keeps backslashes as path separators but
  1192. # leaves quote characters in the tokens — strip a fully wrapping pair
  1193. # so `"my task"` reaches argparse as `my task`, not `"my task"`.
  1194. tokens = []
  1195. if rest and rest.strip():
  1196. for tok in shlex.split(rest, posix=os.name == "posix"):
  1197. if len(tok) >= 2 and tok[0] == tok[-1] and tok[0] in ("'", '"'):
  1198. tok = tok[1:-1]
  1199. tokens.append(tok)
  1200. # Bare ``/kanban`` or ``/kanban help`` / ``--help`` / ``-h`` / ``?``:
  1201. # show the curated short-help block instead of dumping argparse's full
  1202. # usage tree (which is enormous and reads as garbage in a chat
  1203. # bubble). Per-subcommand help still works via ``/kanban foo -h``.
  1204. if not tokens or tokens[0] in {"help", "--help", "-h", "?"}:
  1205. return _SLASH_KANBAN_HELP
  1206. # build_parser() needs a subparsers action to attach to: build a throwaway one and drive
  1207. # kanban_parser directly so usage/error text reads ``/kanban``.
  1208. _wrap = argparse.ArgumentParser(prog="/kanban-wrap", add_help=False)
  1209. _wrap.exit_on_error = False # type: ignore[attr-defined]
  1210. kanban_parser = build_parser(_wrap.add_subparsers(dest="_top"))
  1211. kanban_parser.prog = "/kanban"
  1212. kanban_parser.exit_on_error = False # type: ignore[attr-defined]
  1213. subparsers = [a for a in kanban_parser._actions if isinstance(a, argparse._SubParsersAction)]
  1214. for _action in subparsers:
  1215. for _name, _choice in _action.choices.items():
  1216. _choice.prog = f"/kanban {_name}"
  1217. _choice.exit_on_error = False # type: ignore[attr-defined]
  1218. def _usage_for_error() -> str:
  1219. if tokens:
  1220. for _action in subparsers:
  1221. subparser = _action.choices.get(tokens[0])
  1222. if subparser is not None:
  1223. return subparser.format_usage().rstrip()
  1224. return kanban_parser.format_usage().rstrip()
  1225. buf_out, buf_err = io.StringIO(), io.StringIO()
  1226. try:
  1227. with contextlib.redirect_stdout(buf_out), contextlib.redirect_stderr(buf_err):
  1228. args = kanban_parser.parse_args(tokens)
  1229. except SystemExit as exc:
  1230. out, err = buf_out.getvalue().rstrip(), buf_err.getvalue().rstrip()
  1231. if exc.code in {0, None} and out: # ``-h`` help dump
  1232. return out
  1233. body = err or out
  1234. return f"⚠ /kanban usage error\n{body}" if body else "⚠ /kanban usage error"
  1235. except argparse.ArgumentError as exc:
  1236. return f"⚠ /kanban usage error\n{_usage_for_error()}\n{exc}"
  1237. with contextlib.redirect_stdout(buf_out), contextlib.redirect_stderr(buf_err):
  1238. try:
  1239. kanban_command(args)
  1240. except SystemExit:
  1241. pass
  1242. except Exception as exc:
  1243. print(f"error: {exc}", file=sys.stderr)
  1244. out, err = buf_out.getvalue().rstrip(), buf_err.getvalue().rstrip()
  1245. if err and out:
  1246. return f"{out}\n{err}"
  1247. return err if err else (out or "(no output)")