kanban_parser.py 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477
  1. """Argparse tree for ``hermes kanban …`` (``build_parser``).
  2. The subcommand tree is declared as data — one ``_cmd(...)`` record per
  3. subcommand holding its ``add_parser`` kwargs and an ordered tuple of
  4. ``add_argument`` specs — and materialised by ``_add_commands``. Order of
  5. records and arguments is the order argparse renders in ``--help``.
  6. """
  7. from __future__ import annotations
  8. import argparse
  9. from hermes_cli import kanban_db as kb
  10. from hermes_cli import kanban_db_dispatch as kbd
  11. from hermes_cli import kanban_db_notify as kbn
  12. def _arg(*flags: str, **kw):
  13. return (flags, kw)
  14. def _cmd(name: str, args=(), *, children=None, **parser_kw):
  15. """``children`` = ``(dest, [specs])`` for a nested subparser group."""
  16. return (name, parser_kw, tuple(args), children)
  17. def _add_commands(sub: argparse._SubParsersAction, specs) -> None:
  18. for name, parser_kw, args, children in specs:
  19. p = sub.add_parser(name, **parser_kw)
  20. for flags, kw in args:
  21. p.add_argument(*flags, **kw)
  22. if children:
  23. dest, child_specs = children
  24. _add_commands(p.add_subparsers(dest=dest), child_specs)
  25. def _json_flag(**kw):
  26. return _arg("--json", action="store_true", **kw)
  27. def _reason(help: str):
  28. return _arg("--reason", help=help)
  29. def _nonnegative_int(value: str) -> int:
  30. """argparse type for retention days: a negative window builds a future cutoff
  31. that matches every row, so reject it at the CLI boundary before any sweep."""
  32. try:
  33. parsed = int(value)
  34. except ValueError as exc:
  35. raise argparse.ArgumentTypeError("must be an integer") from exc
  36. if parsed < 0:
  37. raise argparse.ArgumentTypeError("retention days must be >= 0 (0 disables that sweep)")
  38. return parsed
  39. def _run_state_args(type_help: str):
  40. return (
  41. _arg("--state-type", choices=("status", "outcome"), help=f"With --state-name: {type_help}"),
  42. _arg("--state-name", metavar="VALUE",
  43. help="With --state-type: keep runs whose column equals this value"),
  44. )
  45. def _triage_sweep_args(verb: str, Verb: str, noun: str):
  46. """Shared ``specify`` / ``decompose`` arguments."""
  47. return (
  48. _arg("task_id", nargs="?", help=f"Task id to {verb} (required unless --all is given)"),
  49. _arg("--all", dest="all_triage", action="store_true", help=f"{Verb} every task currently in the triage column"),
  50. _arg("--tenant", help="When used with --all, restrict the sweep to this tenant"),
  51. _arg("--author",
  52. help=f"Author name recorded on the audit comment (default: $HERMES_PROFILE or '{noun}')"),
  53. _json_flag(help="Emit one JSON object per task on stdout"),
  54. )
  55. def _bulk_ids(verb: str):
  56. return _arg("--ids", nargs="+", help=f"Additional task ids to {verb} with the same reason (bulk mode)")
  57. _TASK_ID = _arg("task_id")
  58. _TASK_IDS = _arg("task_ids", nargs="+")
  59. _SLUG = _arg("slug")
  60. _TENANT = _arg("--tenant", help="Tenant namespace")
  61. _PRIORITY = _arg("--priority", type=int, default=0, help="Priority tiebreaker")
  62. _RECLAIM_REASON = _reason("Human-readable reason (recorded on the reclaimed event)")
  63. _NOTIFY_TARGET = (
  64. _arg("--platform", required=True),
  65. _arg("--chat-id", required=True),
  66. _arg("--thread-id"),
  67. )
  68. _STEP_HANDOFF = (
  69. _arg("--summary", help="Structured handoff summary. Falls back to --result if omitted."),
  70. _arg("--metadata", help="JSON dict of structured facts to store on the latest completed run."),
  71. )
  72. _BOARD_SPECS = [
  73. _cmd("list", [
  74. _json_flag(),
  75. _arg("--all", action="store_true", help="Include archived boards too"),
  76. ], aliases=["ls"], help="List all boards with task counts"),
  77. _cmd("create", [
  78. _arg("slug", help="Board slug (kebab-case, e.g. atm10-server)"),
  79. _arg("--name", help="Human-readable display name (defaults to Title Case of slug)"),
  80. _arg("--description", help="Optional description"),
  81. _arg("--icon", help="Optional emoji or single-character icon for the dashboard"),
  82. _arg("--color", help="Optional hex color (e.g. '#8b5cf6') for the dashboard"),
  83. _arg("--switch", action="store_true", help="Switch to the new board after creating it"),
  84. _arg("--default-workdir", help="Default workspace path for tasks created on this board"),
  85. ], aliases=["new"], help="Create a new board"),
  86. _cmd("rm", [
  87. _SLUG,
  88. _arg("--delete", action="store_true",
  89. help="Hard-delete the board directory instead of archiving it. "
  90. "Default is to move it to boards/_archived/ so it's recoverable."),
  91. ], aliases=["remove", "delete"], help="Archive (default) or delete a board"),
  92. _cmd("switch", [_SLUG], aliases=["use"], help="Set the active board for subsequent CLI calls"),
  93. _cmd("show", aliases=["current"], help="Print the currently-active board slug"),
  94. _cmd("rename", [_SLUG, _arg("name", help="New display name")],
  95. help="Change a board's human-readable display name (slug is immutable)"),
  96. _cmd("set-default-workdir", [
  97. _SLUG,
  98. _arg("path", nargs="?", help="Absolute path to use as default workdir. Omit to clear."),
  99. ], help="Set the default workspace path for tasks on a board"),
  100. _cmd("export", [
  101. _arg("slug", nargs="?", help="Board to export (default: the current board)"),
  102. _arg("-o", "--output", help="Archive path (default: ./<slug>.tar.gz)"),
  103. _arg("--no-attachments", action="store_true", help="Skip attachment files, keeping the archive small"),
  104. _arg("--include-logs", action="store_true", help="Include per-task worker logs"),
  105. _json_flag(),
  106. ], help="Export a board to a portable .tar.gz archive", description=(
  107. "Package a board's tasks, comments, links, history, and file attachments into one archive "
  108. "that can be imported on another machine. Claims, worker PIDs, chat subscriptions, and "
  109. "paths belonging to this machine are stripped. Workspaces are never included — they are "
  110. "rebuilt on demand."
  111. )),
  112. _cmd("import", [
  113. _arg("archive", help="Path to the .tar.gz archive"),
  114. _arg("--as", dest="as_slug", help="Slug for the imported board (default: from the archive)"),
  115. _arg("--switch", action="store_true", help="Switch to the imported board afterwards"),
  116. _json_flag(),
  117. ], help="Import a board archive as a new board", description=(
  118. "Import a .tar.gz produced by `hermes kanban boards export`. The board always lands as a "
  119. "NEW board — the slug gains a numeric suffix if it is already taken — so an import can "
  120. "never overwrite or merge into a board you already have."
  121. )),
  122. ]
  123. # Top-level ``hermes kanban <action>`` records, in ``--help`` order.
  124. _SPECS = [
  125. _cmd("init", help="Create kanban.db if missing (idempotent)"),
  126. _cmd("boards", children=("boards_action", _BOARD_SPECS),
  127. help="Manage kanban boards (one board per project / workstream)",
  128. description=(
  129. "Boards let you separate unrelated streams of work (projects, repos, domains) into "
  130. "isolated queues. Each board has its own DB, workspaces directory, and dispatcher "
  131. "loop — tasks on one board cannot collide with tasks on another. The first board is "
  132. "'default' and always exists."
  133. )),
  134. _cmd("create", [
  135. _arg("title", help="Task title"),
  136. _arg("--body", help="Optional opening post"),
  137. _arg("--body-file", metavar="PATH",
  138. help="Read the opening post from a file ('-' = stdin), so bodies with embedded "
  139. "newlines or flag-like lines survive shell quoting. "
  140. "Mutually exclusive with --body."),
  141. _arg("--assignee", help="Profile name to assign"),
  142. _arg("--parent", action="append", default=[], help="Parent task id (repeatable)"),
  143. _arg("--workspace",
  144. help="scratch | worktree | worktree:<path> | dir:<path> (default: scratch; "
  145. "an explicit 'scratch' also opts out of a project-scoped board's project)"),
  146. _arg("--branch", help="Branch name for worktree tasks, e.g. wt/t6-wire"),
  147. _arg("--project",
  148. help="Link to a project (id or slug). Anchors the task's "
  149. "worktree under the project's primary repo with a "
  150. "deterministic branch. See `hermes project list`."),
  151. _TENANT,
  152. _PRIORITY,
  153. _arg("--triage", action="store_true",
  154. help="Park in triage — a specifier will flesh out the spec and promote to todo"),
  155. _arg("--idempotency-key",
  156. help="Dedup key. If a non-archived task with this key exists, "
  157. "its id is returned instead of creating a duplicate."),
  158. _arg("--max-runtime",
  159. help="Per-task runtime cap. Accepts seconds (300) or durations (90s, "
  160. "30m, 2h, 1d). When exceeded, the dispatcher SIGTERMs (then "
  161. "SIGKILLs) the worker and re-queues the task."),
  162. _arg("--created-by", default="user", help="Author name recorded on the task (default: user)"),
  163. _arg("--skill", action="append", default=[], dest="skills",
  164. help="Skill to force-load into the worker (repeatable). The kanban "
  165. "lifecycle is already injected automatically. Example: --skill "
  166. "translation --skill github-code-review"),
  167. _arg("--max-retries", type=int, metavar="N",
  168. help="Per-task override for the consecutive-failure "
  169. f"circuit breaker. Trip on the Nth failure — e.g. --max-retries 1 blocks on the "
  170. f"first failure (no retries), --max-retries 3 allows two retries. Omit to use "
  171. f"the dispatcher's kanban.failure_limit config (default "
  172. f"{kb.DEFAULT_FAILURE_LIMIT})."),
  173. _arg("--model", dest="model_override",
  174. help="Pin the worker to this model (passed as -m <model>) without "
  175. "changing the profile's configured model. Combine with --provider "
  176. "when the model belongs to a different backend than the profile's default."),
  177. _arg("--provider", dest="provider_override",
  178. help="Provider the --model belongs to (passed as --provider <name> to "
  179. "the worker). Requires --model."),
  180. _arg("--completion-contract", metavar="CONTRACT",
  181. help="local-only (default), OWNER/REPO for publication, or exact GitHub PR URL; required CI gates done."),
  182. _arg("--goal", action="store_true", dest="goal_mode",
  183. help="Run the worker in a goal loop: after each turn a judge checks the "
  184. "response against the card title/body and, if not done, the worker "
  185. "keeps going in the same session until the judge agrees it's "
  186. "complete (or the turn budget runs out, which blocks the card for "
  187. "review). Best for open-ended cards one shot rarely finishes."),
  188. _arg("--goal-max-turns", type=int, metavar="N", dest="goal_max_turns",
  189. help="Turn budget for --goal workers (default 20). Ignored without --goal."),
  190. _arg("--initial-status", choices=sorted(kb.VALID_INITIAL_STATUSES), default="running",
  191. help="Initial card status. Use 'blocked' for cards "
  192. "that require immediate human ops (R3 gate) "
  193. "to skip the brief running-to-blocked transition."),
  194. _json_flag(help="Emit JSON output"),
  195. ], help="Create a new task"),
  196. _cmd("swarm", [
  197. _arg("goal", help="Swarm goal / final outcome"),
  198. _arg("--worker", action="append", default=[], metavar="PROFILE:TITLE[:SKILL,SKILL]",
  199. help="Parallel worker card (repeatable)"),
  200. _arg("--verifier", required=True, help="Verifier profile"),
  201. _arg("--synthesizer", required=True, help="Synthesizer/writer profile"),
  202. _TENANT,
  203. _PRIORITY,
  204. _arg("--created-by", help="Creator/anchor profile"),
  205. _arg("--idempotency-key", help="Dedup key for the root card"),
  206. _json_flag(help="Emit JSON output"),
  207. ], help="Create a Kanban Swarm v1 graph (parallel workers → verifier → synthesizer)"),
  208. _cmd("list", [
  209. _arg("--mine", action="store_true", help="Filter by $HERMES_PROFILE as assignee"),
  210. _arg("--assignee"),
  211. _arg("--status", choices=sorted(kb.VALID_STATUSES)),
  212. _arg("--tenant"),
  213. _arg("--session",
  214. help="Filter by originating chat/agent session id (set on tasks created from inside an ACP loop)"),
  215. _arg("--archived", action="store_true", help="Include archived tasks"),
  216. _json_flag(),
  217. _arg("--sort", choices=sorted(kb.VALID_SORT_ORDERS.keys()),
  218. help="Sort order for listed tasks (default: priority)"),
  219. _arg("--workflow-template-id", metavar="ID", help="Restrict to tasks with this workflow_template_id"),
  220. _arg("--step-key", dest="current_step_key", metavar="KEY",
  221. help="Restrict to tasks with this current_step_key"),
  222. ], aliases=["ls"], help="List tasks"),
  223. _cmd("show", [_TASK_ID, _json_flag(), *_run_state_args("filter listed runs by task_runs column")],
  224. help="Show a task with comments + events"),
  225. _cmd("assign", [_TASK_ID, _arg("profile", help="Profile name (or 'none' to unassign)")],
  226. help="Assign or reassign a task"),
  227. _cmd("set-model", [
  228. _TASK_ID,
  229. _arg("model", nargs="?", help="Model to pin the worker to (or 'none' to clear the override)"),
  230. _arg("--provider",
  231. help="Provider the model belongs to (worker is spawned with "
  232. "--provider <name>). Cleared together with the model."),
  233. ], help="Set or clear a task's model/provider override (takes effect on the next dispatch)"),
  234. _cmd("reclaim", [_TASK_ID, _RECLAIM_REASON], help="Release an active worker claim on a running task"),
  235. _cmd("reassign", [
  236. _TASK_ID,
  237. _arg("profile", help="New profile name (or 'none' to unassign)"),
  238. _arg("--reclaim", action="store_true",
  239. help="Release any active claim before reassigning (required if task is running)"),
  240. _RECLAIM_REASON,
  241. ], help="Reassign a task to a different profile, optionally reclaiming first"),
  242. _cmd("diagnostics", [
  243. _arg("--severity", choices=["warning", "error", "critical"],
  244. help="Only show diagnostics at or above this severity"),
  245. _arg("--task", help="Only show diagnostics for one task id"),
  246. _json_flag(help="Emit JSON (structured) instead of the default human table"),
  247. ], aliases=["diag"], help="List active diagnostics on the current board"),
  248. _cmd("link", [_arg("parent_id"), _arg("child_id")], help="Add a parent->child dependency"),
  249. _cmd("unlink", [_arg("parent_id"), _arg("child_id")], help="Remove a parent->child dependency"),
  250. _cmd("claim", [
  251. _TASK_ID,
  252. _arg("--ttl", type=int, default=kb.DEFAULT_CLAIM_TTL_SECONDS, help="Claim TTL in seconds (default: 900)"),
  253. ], help="Atomically claim a ready task (prints resolved workspace path)"),
  254. _cmd("comment", [
  255. _TASK_ID,
  256. _arg("text", nargs="+", help="Comment body"),
  257. _arg("--author", help="Author name (default: $HERMES_PROFILE or 'user')"),
  258. _arg("--max-len", type=int, help="Trim the stored comment body to this many characters"),
  259. ], help="Append a comment"),
  260. _cmd("attach", [
  261. _TASK_ID,
  262. _arg("path", help="Path to the local file to attach"),
  263. _arg("--content-type", help="MIME type (default: guessed from the file extension)"),
  264. _arg("--name", help="Stored filename (default: the source file's basename)"),
  265. _arg("--author", help="uploaded_by label (default: $HERMES_PROFILE or 'user')"),
  266. ], help="Attach a local file to a task"),
  267. _cmd("attachments", [_TASK_ID, _json_flag()], help="List a task's attachments"),
  268. _cmd("attach-rm", [_arg("attachment_id", type=int)], help="Delete an attachment by id"),
  269. _cmd("complete", [
  270. _arg("task_ids", nargs="+", help="One or more task ids (only --result applies to all of them)"),
  271. _arg("--result", help="Result summary"),
  272. _arg("--summary",
  273. help="Structured handoff summary for downstream tasks. Falls back to --result if omitted."),
  274. _arg("--metadata",
  275. help='JSON dict of structured facts (e.g. \'{"changed_files": [...], '
  276. '"tests_run": 12}\'). Stored on the closing run.'),
  277. _arg("--force", action="store_true",
  278. help="Override the live-claim guard: complete a running, claimed task "
  279. "even without owning its run (closes the worker's run)."),
  280. ], help="Mark one or more tasks done"),
  281. _cmd("edit", [
  282. _TASK_ID,
  283. _arg("--title", help="Replace the task title"),
  284. _arg("--body", help="Replace the task body"),
  285. _arg("--priority", type=int, help="Replace the task priority"),
  286. _arg("--result", help="Backfilled task result text for a done task"),
  287. *_STEP_HANDOFF,
  288. ], help="Edit task fields or recovery fields on an already-completed task"),
  289. _cmd("block", [
  290. _TASK_ID,
  291. _arg("reason", nargs="*", help="Reason (also appended as a comment)"),
  292. _bulk_ids("block"),
  293. _arg("--kind", choices=sorted(kb.VALID_BLOCK_KINDS),
  294. help="Typed block reason. 'dependency' waits in todo (auto-promoted when "
  295. "parents finish, no human); 'needs_input'/'capability' go to "
  296. "blocked for a human; 'transient' marks a maybe-flaky failure. "
  297. "Repeated same-kind re-blocks after unblock route the task to "
  298. "triage to break unblock loops. Omit for a generic block."),
  299. ], help="Mark one or more tasks blocked"),
  300. _cmd("schedule", [
  301. _TASK_ID,
  302. _arg("reason", nargs="*", help="Reason/timing note (also appended as a comment)"),
  303. _bulk_ids("schedule"),
  304. ], help="Park one or more tasks in Scheduled (waiting on time, not human input)"),
  305. _cmd("unblock", [
  306. _reason("Optional reason/note — recorded as a comment before unblocking. Quote multi-word reasons."),
  307. _TASK_IDS,
  308. ], help="Return blocked/scheduled tasks to ready, or todo while parents remain open"),
  309. _cmd("request-review", [
  310. _TASK_ID,
  311. _arg("--summary", help="What was implemented and how it was verified — shown to the reviewer."),
  312. _arg("--reviewer", help="Optional reviewer profile; reassigns the task before review dispatch."),
  313. _arg("--metadata", help="JSON object with structured reviewer handoff facts."),
  314. _arg("--force", action="store_true",
  315. help="Override the live-claim guard: move a running, claimed "
  316. "task to review even without owning its run (clears the worker's claim)."),
  317. ], help="Move a task to 'review' (implementation done, awaiting review) — NOT a block"),
  318. _cmd("request-changes", [_TASK_ID, _arg("reason", nargs="+", help="Concrete changes required before re-review")],
  319. help="Reviewer verdict: return the active review run to its implementer"),
  320. _cmd("reopen-review", [
  321. _TASK_IDS,
  322. _reason("Optional reason/note — recorded as a comment before reopening. Quote multi-word reasons."),
  323. ], help="Send one or more review tasks back for changes (review -> ready/todo)"),
  324. _cmd("promote", [
  325. _TASK_ID,
  326. _arg("reason", nargs="*", help="Audit-trail reason (recorded on the task_events row)"),
  327. _bulk_ids("promote"),
  328. _arg("--dry-run", action="store_true", help="Validate the promotion without mutating state"),
  329. _arg("--json", dest="json", action="store_true", help="Emit machine-readable JSON result"),
  330. ], help="Manually move one or more todo/blocked tasks to ready (recovery path)"),
  331. _cmd("archive", [
  332. _arg("task_ids", nargs="*", help="Task ids to archive (default mode)"),
  333. _arg("--rm", dest="purge_ids", nargs="+",
  334. help="Permanently delete already-archived task ids from the board"),
  335. ], help="Archive one or more tasks"),
  336. _cmd("tail", [_TASK_ID, _arg("--interval", type=float, default=1.0)], help="Follow a task's event stream"),
  337. _cmd("dispatch", [
  338. _arg("--dry-run", action="store_true", help="Don't actually spawn processes; just print what would happen"),
  339. _arg("--max", type=int, help="Cap number of spawns this pass"),
  340. _arg("--failure-limit", type=int, default=kbd.DEFAULT_FAILURE_LIMIT,
  341. help=f"Auto-block a task after this many consecutive non-success attempts "
  342. f"(spawn_failed, timed_out, or crashed; default: {kbd.DEFAULT_FAILURE_LIMIT})"),
  343. _json_flag(),
  344. ], help="One dispatcher pass: reclaim stale, promote ready, spawn workers"),
  345. _cmd("daemon", [
  346. _arg("--interval", type=float, default=60.0, help="Seconds between dispatch ticks (default: 60)"),
  347. _arg("--max", type=int, help="Cap number of spawns per tick"),
  348. _arg("--failure-limit", type=int, default=kbd.DEFAULT_FAILURE_LIMIT),
  349. _arg("--pidfile", help="Write the daemon's PID to this file on start"),
  350. _arg("--verbose", "-v", action="store_true", help="Log each tick's outcome to stdout"),
  351. # Escape hatch for hosts that truly cannot run the gateway; hidden from
  352. # --help so nobody casually keeps the double-dispatcher pattern alive.
  353. _arg("--force", action="store_true", help=argparse.SUPPRESS),
  354. ], help="DEPRECATED — dispatcher now runs in the gateway. Use `hermes gateway start`."),
  355. _cmd("watch", [
  356. _arg("--assignee", help="Only show events for tasks assigned to this profile"),
  357. _arg("--tenant", help="Only show events from tasks in this tenant"),
  358. _arg("--kinds",
  359. help="Comma-separated event kinds to include (e.g. 'completed,blocked,gave_up,crashed,timed_out')"),
  360. _arg("--interval", type=float, default=0.5, help="Poll interval in seconds (default: 0.5)"),
  361. ], help="Live-stream task_events to the terminal (Ctrl+C to exit)"),
  362. _cmd("stats", [_json_flag()], help="Per-status + per-assignee counts + oldest-ready age"),
  363. _cmd("notify-subscribe", [
  364. _TASK_ID,
  365. *_NOTIFY_TARGET,
  366. _arg("--user-id"),
  367. _arg("--user-id-alt"),
  368. _arg("--chat-type", choices=("dm", "group", "channel", "thread"),
  369. help="Originating source chat_type, recorded so the active-wake delivery "
  370. "modes resolve the operator's real session. Omit to leave an "
  371. "existing sub unchanged (new subs default to 'dm')."),
  372. _arg("--parent-chat-id",
  373. help="Parent channel ID for a thread or forum post, used for multiplex profile routing."),
  374. _arg("--guild-id",
  375. help="Discord guild ID, used for multiplex profile routing."),
  376. _arg("--notifier-profile",
  377. help="Profile gateway that owns/delivers this subscription (default: active profile)"),
  378. # choices: single source of truth shared with the DB/watcher enum.
  379. _arg("--delivery-mode", choices=kbn._NOTIFY_DELIVERY_MODES,
  380. help="How the kanban-notifier reacts to terminal events for this "
  381. "subscription: 'notify' (passive message only; default), "
  382. "'notify+wake' (message AND wake the destination gateway agent so "
  383. "it reads the full board context and replies in its own voice), or "
  384. "'wake' (wake the agent only, no passive message). Omit to leave an "
  385. "existing subscription's mode unchanged (new subs default to 'notify')."),
  386. ], help="Subscribe a gateway source to a task's terminal events (used by /kanban subscribe in the gateway adapter)"),
  387. _cmd("notify-list", [_arg("task_id", nargs="?"), _json_flag()],
  388. help="List notification subscriptions (optionally for a single task)"),
  389. _cmd("notify-unsubscribe", [_TASK_ID, *_NOTIFY_TARGET], help="Remove a gateway subscription from a task"),
  390. _cmd("log", [_TASK_ID, _arg("--tail", type=int, help="Only print the last N bytes")],
  391. help="Print the worker log for a task (from <kanban-root>/kanban/logs/)"),
  392. _cmd("runs", [_TASK_ID, _json_flag(), *_run_state_args("filter runs by task_runs column")],
  393. help="Show attempt history for a task (one row per run: profile, outcome, elapsed, summary)"),
  394. _cmd("heartbeat", [
  395. _TASK_ID,
  396. _arg("--note", help="Optional short note attached to the heartbeat event"),
  397. ], help="Emit a heartbeat event for a running task (worker liveness signal)"),
  398. _cmd("assignees", [_json_flag()],
  399. help="List known profiles + per-profile task counts (union of ~/.hermes/profiles/ and current assignees on the board)"),
  400. _cmd("context", [_TASK_ID],
  401. help="Print the full context a worker sees for a task (title + body + parent results + comments)."),
  402. _cmd("specify", _triage_sweep_args("specify", "Specify", "specifier"),
  403. help="Flesh out a triage-column task into a concrete spec (title + "
  404. "body) and promote it to todo. Uses the auxiliary LLM "
  405. "configured under auxiliary.triage_specifier."),
  406. _cmd("decompose", _triage_sweep_args("decompose", "Decompose", "decomposer"),
  407. help="Decompose a triage-column task into a graph of child tasks "
  408. "routed to specialist profiles by description. Falls back "
  409. "to specify-style single-task promotion when the task "
  410. "doesn't benefit from fan-out. Uses auxiliary.kanban_decomposer."),
  411. _cmd("gc", [
  412. _arg("--event-retention-days", type=_nonnegative_int, default=30,
  413. help="Delete task_events older than N days for terminal tasks (default: 30; 0 disables)"),
  414. _arg("--log-retention-days", type=_nonnegative_int, default=30,
  415. help="Delete worker log files older than N days (default: 30; 0 disables)"),
  416. ], help="Garbage-collect archived-task workspaces, old events, and old logs"),
  417. _cmd("repair", [_json_flag(help="Emit the repair report as JSON")],
  418. help="Check kanban.db integrity and auto-repair index-only corruption",
  419. description=(
  420. "Runs PRAGMA integrity_check on the board's DB and reports the result. When the "
  421. "failure consists only of index-scoped errors ('wrong # of entries in index <name>' / "
  422. "'row N missing from index <name>'), the corrupt file is quarantined to a "
  423. ".corrupt.<hash>.bak sibling first and the damaged indexes are rebuilt with REINDEX — "
  424. "the same narrow auto-repair the connect-time guard applies. Any other corruption "
  425. "class is reported and left untouched (fail-closed). Exits 0 when the DB is healthy "
  426. "or was repaired, non-zero when it is still corrupt."
  427. )),
  428. ]
  429. def build_parser(parent_subparsers: argparse._SubParsersAction) -> argparse.ArgumentParser:
  430. """Attach the ``kanban`` subcommand tree; returns the ``kanban`` parser."""
  431. kanban_parser = parent_subparsers.add_parser(
  432. "kanban",
  433. help="Multi-profile collaboration board (tasks, links, comments)",
  434. description="Durable SQLite-backed task board shared across Hermes profiles. "
  435. "Tasks are claimed atomically, can depend on other tasks, and "
  436. "are executed by a named profile in an isolated workspace. "
  437. "See https://hermes-agent.nousresearch.com/docs/user-guide/features/kanban.",
  438. )
  439. # --board scopes every subcommand to one board's DB; when omitted the
  440. # resolution is HERMES_KANBAN_BOARD, then the persisted current-board
  441. # file, then "default" (kanban_db.get_current_board()).
  442. kanban_parser.add_argument("--board", default=None, metavar="<slug>",
  443. help="Board slug to operate on. Defaults to the current board (set "
  444. "via `hermes kanban boards switch <slug>` or the "
  445. "HERMES_KANBAN_BOARD env var). Use `hermes kanban boards "
  446. "list` to see all boards.")
  447. _add_commands(kanban_parser.add_subparsers(dest="kanban_action"), _SPECS)
  448. kanban_parser.set_defaults(_kanban_parser=kanban_parser)
  449. return kanban_parser