kanban_specify.py 9.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241
  1. """Kanban triage specifier — flesh out a one-liner into a real spec.
  2. ``hermes kanban specify [task_id | --all]`` asks the auxiliary LLM for a
  3. tightened title + concrete body for a Triage task, then flips it
  4. ``triage -> todo`` via ``kanban_db.specify_triage_task``.
  5. Mirrors ``hermes_cli/goals.py``: same aux-client pattern, same "empty config
  6. => skip, don't crash" tolerance. One shot, no retry loop. JSON mode is not
  7. requested (works on providers without it); the parse is lenient and falls
  8. back to "whole reply is the body" so a malformed reply never strands a task.
  9. """
  10. from __future__ import annotations
  11. import json
  12. import logging
  13. import os
  14. import re
  15. from dataclasses import dataclass
  16. from typing import Optional
  17. from hermes_cli import kanban_db as kb
  18. from hermes_cli import kanban_db_connect as kbc
  19. from utils import env_int
  20. HERMES_KANBAN_SPECIFY_MAX_TOKENS = max(1500, env_int("HERMES_KANBAN_SPECIFY_MAX_TOKENS", 6000))
  21. logger = logging.getLogger(__name__)
  22. _SYSTEM_PROMPT = """You are the Kanban triage specifier for the Hermes Agent board.
  23. A user dropped a rough idea into the Triage column. Your job is to turn it
  24. into a concrete, actionable task spec that an autonomous worker can pick up
  25. and execute without further clarification.
  26. Output a single JSON object with exactly two keys:
  27. {
  28. "title": "<tightened task title, <= 80 chars, imperative voice>",
  29. "body": "<multi-line spec, see structure below>"
  30. }
  31. The body MUST include these sections, each prefixed with a bold markdown
  32. heading, in this order:
  33. **Goal** — one sentence, user-facing outcome.
  34. **Approach** — 2-5 bullets on how a worker should tackle it.
  35. **Acceptance criteria** — checklist of concrete, verifiable conditions.
  36. **Out of scope** — short list of things NOT to touch (omit if nothing
  37. obvious; never invent scope creep).
  38. Rules:
  39. - Keep the tightened title close in meaning to the original idea — do
  40. NOT invent a different project.
  41. - If the original idea is already detailed, preserve its substance and
  42. just reformat into the sections above.
  43. - Never add invented requirements the user didn't hint at.
  44. - No preamble, no closing remarks, no code fences around the JSON.
  45. - Output only the JSON object and nothing else.
  46. """
  47. _USER_TEMPLATE = """Task id: {task_id}
  48. Current title: {title}
  49. Current body:
  50. {body}
  51. """
  52. @dataclass
  53. class SpecifyOutcome:
  54. """Result of specifying a single triage task."""
  55. task_id: str
  56. ok: bool
  57. reason: str = ""
  58. new_title: Optional[str] = None
  59. def _truncate(text: str, limit: int) -> str:
  60. # Plain length clamp for LLM prompt fields; these never reach a terminal, so no escape stripping here.
  61. if len(text) <= limit:
  62. return text
  63. return text[: limit - 1] + "…"
  64. _FENCE_RE = re.compile(r"^\s*```(?:json)?\s*|\s*```\s*$", re.IGNORECASE)
  65. def _extract_json_blob(raw: str, fence_re: re.Pattern = _FENCE_RE) -> Optional[dict]:
  66. """Lenient JSON object extraction: strip code fences, take the first ``{``
  67. to the last ``}``. None if nothing parses to a dict."""
  68. if not raw:
  69. return None
  70. stripped = fence_re.sub("", raw.strip())
  71. first = stripped.find("{")
  72. last = stripped.rfind("}")
  73. if first == -1 or last == -1 or last <= first:
  74. return None
  75. try:
  76. val = json.loads(stripped[first : last + 1])
  77. except (ValueError, json.JSONDecodeError):
  78. return None
  79. return val if isinstance(val, dict) else None
  80. def _nonblank(v) -> Optional[str]:
  81. return v if isinstance(v, str) and v.strip() else None
  82. def _title_body(parsed: dict) -> tuple[Optional[str], Optional[str]]:
  83. """``(title, body)`` from an LLM reply: title stripped, body verbatim,
  84. either None when missing/blank."""
  85. title = _nonblank(parsed.get("title"))
  86. return (title.strip() if title else None), _nonblank(parsed.get("body"))
  87. def _profile_author(default: str = "specifier") -> str:
  88. """Same identity contract as ``hermes_cli.kanban._profile_author``; ``$USER`` as the last
  89. resort for a human running the CLI outside any profile."""
  90. from hermes_cli.profiles import current_profile_name
  91. return current_profile_name() or os.environ.get("USER") or default
  92. def _load_triage_task(task_id: str) -> tuple[Optional[kb.Task], str]:
  93. """``(task, "")`` when the task exists and is in triage, else ``(None, reason)``."""
  94. with kbc.connect_closing() as conn:
  95. task = kb.get_task(conn, task_id)
  96. if task is None:
  97. return None, "unknown task id"
  98. if task.status != "triage":
  99. return None, f"task is not in triage (status={task.status!r})"
  100. return task, ""
  101. def _task_prompt_fields(task: kb.Task) -> dict[str, str]:
  102. """Bounded ``task_id``/``title``/``body`` for the user prompt templates."""
  103. return {
  104. "task_id": task.id,
  105. "title": _truncate(task.title or "", 400),
  106. "body": _truncate(task.body or "(no body)", 4000),
  107. }
  108. def _call_aux(verb: str, task_id: str, *, aux_task: str, system: str, user: str,
  109. max_tokens: int, timeout: int, log: logging.Logger = logger) -> tuple[Optional[str], str]:
  110. """One auxiliary LLM call; ``(reply_text, "")`` or ``(None, reason)``.
  111. ``call_llm`` applies all ``auxiliary.<aux_task>.*`` config (provider/model/
  112. base_url, extra_body, reasoning_effort, retries). Imported lazily so a
  113. missing aux client degrades to a skip instead of an import-time crash.
  114. """
  115. try:
  116. from agent.auxiliary_client import call_llm
  117. except Exception as exc: # pragma: no cover — import smoke test
  118. log.debug("%s: auxiliary client import failed: %s", verb, exc)
  119. return None, "auxiliary client unavailable"
  120. # Specify/decompose run outside any agent turn (CLI, dashboard route, gateway watcher), so no
  121. # conversation affinity scope is bound and the relay-affinity headers (x-opencode-session, the
  122. # OpenRouter/Portal sticky key) are omitted — the OpenCode Go relay rejects that with 400
  123. # MissingSessionID (#112043). Declare a per-task scope, but only when none is already bound so an
  124. # in-turn caller keeps its conversation's key.
  125. from agent.portal_tags import get_affinity_scope, reset_affinity_scope, set_affinity_scope
  126. affinity_token = None if get_affinity_scope() else set_affinity_scope(f"kanban:{task_id}")
  127. try:
  128. # Route through call_llm so auxiliary.triage_specifier.* config (provider/model/base_url,
  129. # extra_body, reasoning_effort, retries) all apply — the direct-create path dropped extra_body
  130. # (#35566).
  131. resp = call_llm(
  132. task=aux_task,
  133. messages=[{"role": "system", "content": system}, {"role": "user", "content": user}],
  134. temperature=0.3,
  135. max_tokens=max_tokens,
  136. timeout=timeout,
  137. )
  138. except Exception as exc:
  139. suffix = " — skipping" if verb == "specify" else ""
  140. log.info("%s: API call failed for %s (%s)%s", verb, task_id, exc, suffix)
  141. return None, f"LLM error: {type(exc).__name__}"
  142. finally:
  143. if affinity_token is not None:
  144. reset_affinity_scope(affinity_token)
  145. try:
  146. return resp.choices[0].message.content or "", ""
  147. except Exception:
  148. return "", ""
  149. def specify_task(
  150. task_id: str,
  151. *,
  152. author: Optional[str] = None,
  153. timeout: Optional[int] = None,
  154. ) -> SpecifyOutcome:
  155. """Specify one triage task and promote it to ``todo``. Expected failures
  156. (not in triage, no aux client, API error, malformed reply) surface as
  157. ``ok=False`` so an ``--all`` sweep continues."""
  158. task, reason = _load_triage_task(task_id)
  159. if task is None:
  160. return SpecifyOutcome(task_id, False, reason)
  161. raw, reason = _call_aux(
  162. "specify", task_id, aux_task="triage_specifier", system=_SYSTEM_PROMPT,
  163. user=_USER_TEMPLATE.format(**_task_prompt_fields(task)),
  164. max_tokens=HERMES_KANBAN_SPECIFY_MAX_TOKENS, timeout=timeout or 120,
  165. )
  166. if raw is None:
  167. return SpecifyOutcome(task_id, False, reason)
  168. raw = raw.strip()
  169. parsed = _extract_json_blob(raw)
  170. if parsed is None:
  171. # Whole reply becomes the body; the user can edit afterward.
  172. if not raw:
  173. return SpecifyOutcome(task_id, False, "LLM returned an empty response")
  174. new_title, new_body = None, raw
  175. else:
  176. new_title, new_body = _title_body(parsed)
  177. if new_body is None and new_title is None:
  178. return SpecifyOutcome(task_id, False, "LLM response missing title and body")
  179. with kbc.connect_closing() as conn:
  180. ok = kb.specify_triage_task(
  181. conn,
  182. task_id,
  183. title=new_title,
  184. body=new_body,
  185. author=author or _profile_author(),
  186. )
  187. if not ok:
  188. # Race: promoted/archived between our read and the write.
  189. return SpecifyOutcome(task_id, False, "task moved out of triage before promotion")
  190. return SpecifyOutcome(task_id, True, "specified", new_title=new_title)
  191. def list_triage_ids(*, tenant: Optional[str] = None) -> list[str]:
  192. """Task ids in the triage column; ``tenant`` narrows the sweep."""
  193. with kbc.connect_closing() as conn:
  194. tasks = kb.list_tasks(conn, status="triage", tenant=tenant, include_archived=False)
  195. return [t.id for t in tasks]