kanban_db_context.py 10.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239
  1. """Worker-context rendering for ``build_worker_context``: the capped markdown sections a spawned
  2. worker reads about its task (header, attachments, prior attempts, parent handoffs, role
  3. history, comments).
  4. Split out of ``hermes_cli.kanban_db``; origin-resident helpers are reached late-bound via
  5. ``_kb`` so monkeypatching ``kanban_db.<name>`` keeps working.
  6. """
  7. from __future__ import annotations
  8. import json
  9. import os
  10. import sqlite3
  11. import time
  12. from typing import TYPE_CHECKING, Any, Optional
  13. import hermes_cli.kanban_db as _kb
  14. if TYPE_CHECKING:
  15. from hermes_cli.kanban_db import Attachment, Comment, Task
  16. # build_worker_context() caps, sized for a ~100k-char prompt with headroom.
  17. _CTX_MAX_PRIOR_ATTEMPTS = 10 # most recent N prior runs shown in full
  18. _CTX_MAX_COMMENTS = 30 # most recent N comments shown in full
  19. _CTX_MAX_FIELD_BYTES = 4 * 1024 # per summary/error/metadata/result
  20. _CTX_MAX_BODY_BYTES = 8 * 1024 # per task.body (opening post)
  21. _CTX_MAX_COMMENT_BYTES = 2 * 1024 # per comment
  22. def _relative_age(ts: Optional[int], now: Optional[int] = None) -> str:
  23. """``just now`` / ``18h ago`` / ``3d ago``; "" for a missing/invalid ts. An LLM
  24. reads a bare absolute timestamp as current fact — the relative age is what
  25. prompts a worker to re-verify stale sibling work."""
  26. try:
  27. ts = int(ts)
  28. except (TypeError, ValueError):
  29. return ""
  30. if now is None:
  31. now = int(time.time())
  32. delta = now - ts
  33. if delta < 60: # includes negative = clock skew across machines; never claim "in the future"
  34. return "just now"
  35. if delta < 3600:
  36. return f"{delta // 60}m ago"
  37. if delta < 86400:
  38. return f"{delta // 3600}h ago"
  39. return f"{delta // 86400}d ago"
  40. def _ctx_cap(s: Optional[str], limit: int = _CTX_MAX_FIELD_BYTES) -> str:
  41. """Truncate to ``limit`` chars with a visible ellipsis."""
  42. if not s:
  43. return ""
  44. s = s.strip()
  45. if len(s) <= limit:
  46. return s
  47. return s[:limit] + f"… [truncated, {len(s) - limit} chars omitted]"
  48. def _ctx_stamp(ts: int, now: int) -> str:
  49. """``YYYY-MM-DD HH:MM`` plus a relative age when one is available."""
  50. disp = time.strftime("%Y-%m-%d %H:%M", time.localtime(ts))
  51. age = _relative_age(ts, now)
  52. return f"{disp}, {age}" if age else disp
  53. def _ctx_metadata_line(metadata: Any) -> Optional[str]:
  54. if not metadata:
  55. return None
  56. try:
  57. return f"_metadata_: `{_ctx_cap(json.dumps(metadata, ensure_ascii=False, sort_keys=True))}`"
  58. except Exception:
  59. return None
  60. def _ctx_tail(items: list, cap: int, noun: str) -> tuple[list, Optional[str]]:
  61. """Keep the newest ``cap`` items; describe the omitted head, if any."""
  62. omitted = max(0, len(items) - cap)
  63. if not omitted:
  64. return items, None
  65. return items[-cap:], (
  66. f"_({omitted} earlier {noun}{'s' if omitted != 1 else ''} "
  67. f"omitted; showing most recent {cap})_"
  68. )
  69. def _ctx_header(lines: list[str], task: Task) -> None:
  70. lines.append(f"# Kanban task {task.id}: {task.title}")
  71. lines.append("")
  72. lines.append(f"Assignee: {task.assignee or '(unassigned)'}")
  73. lines.append(f"Status: {task.status}")
  74. if task.tenant:
  75. lines.append(f"Tenant: {task.tenant}")
  76. lines.append(f"Workspace: {task.workspace_kind} @ {task.workspace_path or '(unresolved)'}")
  77. if task.max_runtime_seconds is not None:
  78. terminal_timeout = _kb._worker_terminal_timeout_env(
  79. task.max_runtime_seconds, os.environ.get("TERMINAL_TIMEOUT"),
  80. )
  81. effective_terminal_timeout = terminal_timeout or os.environ.get("TERMINAL_TIMEOUT")
  82. lines.append(f"Max runtime: {task.max_runtime_seconds}s")
  83. if effective_terminal_timeout:
  84. lines.append(f"Terminal timeout: {effective_terminal_timeout}s")
  85. if task.branch_name:
  86. lines.append(f"Branch: {task.branch_name}")
  87. lines.append("")
  88. if task.body and task.body.strip():
  89. lines.append("## Body")
  90. lines.append(_ctx_cap(task.body, _CTX_MAX_BODY_BYTES))
  91. lines.append("")
  92. def _ctx_attachments(lines: list[str], attachments: list[Attachment]) -> None:
  93. """Absolute on-disk paths so the worker's file tools read them directly
  94. (remote terminal backends need the attachments dir mounted)."""
  95. if not attachments:
  96. return
  97. lines.append("## Attachments")
  98. lines.append(
  99. "Files attached to this task. Read them with the file/terminal "
  100. "tools at the absolute paths below:"
  101. )
  102. for att in attachments:
  103. size_kb = max(1, (att.size + 1023) // 1024) if att.size else 0
  104. size_str = f", {size_kb} KB" if size_kb else ""
  105. ctype = f", {att.content_type}" if att.content_type else ""
  106. lines.append(f"- `{att.filename}`{ctype}{size_str} → `{att.stored_path}`")
  107. lines.append("")
  108. def _ctx_prior_attempts(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:
  109. """Closed runs on this task (the active run is this worker), newest
  110. ``_CTX_MAX_PRIOR_ATTEMPTS`` in full, older ones as a one-line marker."""
  111. all_prior = [r for r in _kb.list_runs(conn, task_id) if r.ended_at is not None]
  112. shown, omitted_note = _ctx_tail(all_prior, _CTX_MAX_PRIOR_ATTEMPTS, "attempt")
  113. if not shown:
  114. return
  115. first_shown_idx = len(all_prior) - len(shown) + 1
  116. lines.append("## Prior attempts on this task")
  117. if omitted_note:
  118. lines.append(omitted_note)
  119. for offset, run in enumerate(shown):
  120. profile = run.profile or "(unknown)"
  121. outcome = run.outcome or run.status
  122. lines.append(
  123. f"### Attempt {first_shown_idx + offset} — {outcome} ({profile}, {_ctx_stamp(run.started_at, now)})"
  124. )
  125. if run.summary and run.summary.strip():
  126. lines.append(_ctx_cap(run.summary))
  127. if run.error and run.error.strip():
  128. lines.append(f"_error_: {_ctx_cap(run.error)}")
  129. meta_line = _ctx_metadata_line(run.metadata)
  130. if meta_line:
  131. lines.append(meta_line)
  132. lines.append("")
  133. def _ctx_parent_results(lines: list[str], conn: sqlite3.Connection, task_id: str, now: int) -> None:
  134. """Done-parent handoffs: newest ``completed`` run's summary+metadata,
  135. falling back to ``task.result`` for pre-runs-table data. Stamped with a
  136. relative age so the worker re-verifies stale upstream results."""
  137. parent_rows = conn.execute(
  138. "SELECT parent_id FROM task_links WHERE child_id = ? ORDER BY parent_id", (task_id,),
  139. ).fetchall()
  140. wrote_header = False
  141. for pid in (r["parent_id"] for r in parent_rows):
  142. pt = _kb.get_task(conn, pid)
  143. if not pt or pt.status != "done":
  144. continue
  145. runs = [r for r in _kb.list_runs(conn, pid) if r.outcome == "completed"]
  146. runs.sort(key=lambda r: r.started_at, reverse=True)
  147. run = runs[0] if runs else None
  148. if not wrote_header:
  149. lines.append("## Parent task results")
  150. lines.append(
  151. "_Handoffs from upstream tasks, captured when each parent "
  152. "completed (see age below). These are point-in-time "
  153. "snapshots, not live state — if a result drives your "
  154. "current work and it's not recent, re-verify against the "
  155. "source before acting on it as current._"
  156. )
  157. wrote_header = True
  158. done_ts = run.ended_at if run is not None and run.ended_at else (pt.completed_at or None)
  159. age = _relative_age(done_ts, now)
  160. lines.append(f"### {pid}" + (f" (completed {age})" if age else ""))
  161. if run is not None and run.summary and run.summary.strip():
  162. lines.append(_ctx_cap(run.summary))
  163. elif pt.result:
  164. lines.append(_ctx_cap(pt.result))
  165. else:
  166. lines.append("(no result recorded)")
  167. meta_line = _ctx_metadata_line(run.metadata) if run is not None else None
  168. if meta_line:
  169. lines.append(meta_line)
  170. lines.append("")
  171. def _ctx_role_history(lines: list[str], conn: sqlite3.Connection, task: Task, now: int) -> None:
  172. """The assignee's 5 most recent completed runs on OTHER tasks — implicit
  173. role continuity without wiring anything into SOUL.md / MEMORY.md."""
  174. if not task.assignee:
  175. return
  176. role_rows = conn.execute(
  177. "SELECT t.id, t.title, r.summary, r.ended_at "
  178. "FROM task_runs r JOIN tasks t ON r.task_id = t.id "
  179. "WHERE r.profile = ? AND r.task_id != ? "
  180. " AND r.outcome = 'completed' "
  181. "ORDER BY r.ended_at DESC LIMIT 5", (task.assignee, task.id),
  182. ).fetchall()
  183. if not role_rows:
  184. return
  185. lines.append(f"## Recent work by @{task.assignee}")
  186. for row in role_rows:
  187. first = _kb._first_line(row["summary"], 200) or "(no summary)"
  188. lines.append(
  189. f"- {row['id']} — {row['title']} ({_ctx_stamp(_kb._to_epoch(row['ended_at']) or 0, now)}): {first}"
  190. )
  191. lines.append("")
  192. def _ctx_comments(lines: list[str], comments: list[Comment], now: int) -> None:
  193. """Newest ``_CTX_MAX_COMMENTS`` comments. The explicit "comment from
  194. worker" framing stops an operator-controlled HERMES_PROFILE like
  195. "hermes-system" being read as a system directive above an
  196. attacker-influenceable body (defense-in-depth)."""
  197. shown, omitted_note = _ctx_tail(comments, _CTX_MAX_COMMENTS, "comment")
  198. if not shown:
  199. return
  200. lines.append("## Comment thread")
  201. if omitted_note:
  202. lines.append(omitted_note)
  203. for c in shown:
  204. # Render author with explicit "comment from worker" framing so operator-controlled HERMES_PROFILE
  205. # values like "hermes-system" or "operator" can't be misread by the next worker as a system
  206. # directive above the (attacker-influenceable) comment body. Defense-in-depth — the LLM-controlled
  207. # author-forgery surface was already closed in #22435. See #22452.
  208. safe_author = (c.author or "").replace("`", "")
  209. lines.append(f"comment from worker `{safe_author}` at {_ctx_stamp(c.created_at, now)}:")
  210. lines.append(_ctx_cap(c.body, _CTX_MAX_COMMENT_BYTES))
  211. lines.append("")