kanban_db_graph.py 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214
  1. """Task graph initialization and atomic decomposition persistence."""
  2. from __future__ import annotations
  3. import sqlite3
  4. import time
  5. from typing import Any, Optional
  6. def inherit_creator_origin(
  7. conn: sqlite3.Connection, task_id: str, creator_task_id: Optional[str], *,
  8. created_at: int,
  9. ) -> None:
  10. """Copy durable origin inside creation's transaction, never adding dependencies."""
  11. if not creator_task_id:
  12. return
  13. from hermes_cli.kanban_db import _inherit_notify_subs
  14. conn.execute(
  15. "UPDATE tasks SET session_id = COALESCE(session_id, "
  16. "(SELECT session_id FROM tasks WHERE id = ?)) WHERE id = ?",
  17. (creator_task_id, task_id),
  18. )
  19. _inherit_notify_subs(conn, task_id, (creator_task_id,), created_at=created_at)
  20. def initial_task_state(
  21. conn: sqlite3.Connection, parents: tuple[str, ...], initial_status: str,
  22. triage: bool, tenant: Optional[str],
  23. ) -> tuple[str, Optional[str]]:
  24. """Resolve state and tenant under the creator's write transaction.
  25. Parent order breaks ties in this soft namespace; explicit tenant wins.
  26. Validate parents even for parked tasks so links never dangle.
  27. """
  28. rows = {}
  29. if parents:
  30. rows = {row["id"]: row for row in conn.execute(
  31. "SELECT id, status, tenant FROM tasks WHERE id IN "
  32. "(" + ",".join("?" * len(parents)) + ")", parents,
  33. )}
  34. missing = [pid for pid in parents if pid not in rows]
  35. if missing:
  36. raise ValueError(f"unknown parent task(s): {', '.join(missing)}")
  37. if tenant is None:
  38. tenant = next((rows[pid]["tenant"] for pid in parents if rows[pid]["tenant"]), None)
  39. if initial_status == "blocked":
  40. return "blocked", tenant
  41. if triage:
  42. return "triage", tenant
  43. if any(row["status"] != "done" for row in rows.values()):
  44. return "todo", tenant
  45. return "ready", tenant
  46. def _validate_children_graph(children: list) -> None:
  47. """DB-free shape check + Kahn's cycle check on the sibling graph (a cycle
  48. would deadlock every involved child in ``todo`` forever)."""
  49. for idx, child in enumerate(children):
  50. if not isinstance(child, dict):
  51. raise ValueError(f"child[{idx}] is not a dict")
  52. title = child.get("title")
  53. if not isinstance(title, str) or not title.strip():
  54. raise ValueError(f"child[{idx}].title is required")
  55. parents_idx = child.get("parents") or []
  56. if not isinstance(parents_idx, list):
  57. raise ValueError(f"child[{idx}].parents must be a list")
  58. for p in parents_idx:
  59. if not isinstance(p, int) or p < 0 or p >= len(children):
  60. raise ValueError(f"child[{idx}].parents[{p}] is not a valid index into children")
  61. if p == idx:
  62. raise ValueError(f"child[{idx}] cannot list itself as a parent")
  63. in_deg = [0] * len(children)
  64. adj: list[list[int]] = [[] for _ in children]
  65. for i, c in enumerate(children):
  66. for p in (c.get("parents") or []):
  67. adj[p].append(i)
  68. in_deg[i] += 1
  69. queue = [i for i in range(len(children)) if in_deg[i] == 0]
  70. seen = 0
  71. while queue:
  72. seen += 1
  73. for nb in adj[queue.pop()]:
  74. in_deg[nb] -= 1
  75. if in_deg[nb] == 0:
  76. queue.append(nb)
  77. if seen != len(children):
  78. raise ValueError("cyclic dependency detected in decomposed children list")
  79. def decompose_triage_task(
  80. conn: sqlite3.Connection, task_id: str, *, root_assignee: Optional[str], children: list[dict],
  81. author: Optional[str] = None, auto_promote: bool = True,
  82. ) -> Optional[list[str]]:
  83. """Fan a triage task out into children and move the root to ``todo``; the root
  84. waits on every child and wakes (``ready``) when all are done.
  85. ``children``: dicts of ``title`` (required), ``body``, ``assignee``,
  86. ``parents`` (indices into this list), optional workspace overrides.
  87. Returns child ids in input order, or None when the root is missing / not
  88. in triage, or has already decomposed. Atomic: malformed entries abort fan-out.
  89. """
  90. from hermes_cli.kanban_db import (
  91. _canonical_assignee, _link, _append_event, _insert_comment,
  92. write_txn, recompute_ready,
  93. )
  94. if not children:
  95. return None
  96. if root_assignee is not None:
  97. root_assignee = _canonical_assignee(root_assignee)
  98. _validate_children_graph(children)
  99. # ONE txn so the fan-out is atomic; helpers that open their own write_txn
  100. # (create_task, link_tasks, add_comment) must not be called in here.
  101. now = int(time.time())
  102. with write_txn(conn):
  103. root_row = conn.execute(
  104. "SELECT id, status, tenant, workspace_kind, workspace_path "
  105. "FROM tasks WHERE id = ?", (task_id,),
  106. ).fetchone()
  107. if root_row is None or root_row["status"] != "triage":
  108. return None
  109. # Dependency links alone do not imply lineage. The completion event is
  110. # committed with the graph, and survives re-triage or unlinking.
  111. if conn.execute(
  112. "SELECT 1 FROM task_events WHERE task_id = ? AND kind = 'decomposed' LIMIT 1",
  113. (task_id,),
  114. ).fetchone():
  115. return None
  116. child_ids = [
  117. _insert_decomposed_child(conn, task_id, root_row, child, author, now)
  118. for child in children
  119. ]
  120. # Sibling edges within the decomposed graph.
  121. for idx, child in enumerate(children):
  122. for p_idx in child.get("parents") or []:
  123. parent_id, child_id = child_ids[p_idx], child_ids[idx]
  124. _link(conn, parent_id, child_id)
  125. _append_event(conn, child_id, "linked", {"parent": parent_id, "child": child_id})
  126. # Root waits for the whole graph: link it under EVERY child (simpler
  127. # than computing leaves; cycle-free since the root is only ever a child).
  128. for cid in child_ids:
  129. _link(conn, cid, task_id)
  130. # Flip the root triage -> todo, assignee -> orchestrator.
  131. sets = ["status = 'todo'"]
  132. params: list[Any] = []
  133. if root_assignee is not None:
  134. sets.append("assignee = ?")
  135. params.append(root_assignee)
  136. params.append(task_id)
  137. conn.execute(f"UPDATE tasks SET {', '.join(sets)} WHERE id = ?", tuple(params))
  138. if author and author.strip():
  139. _insert_comment(
  140. conn, task_id, author.strip(),
  141. "Decomposed into " + ", ".join(child_ids)
  142. + ". Root will wake when all children complete.",
  143. now,
  144. )
  145. _append_event(
  146. conn, task_id, "decomposed", {"child_ids": child_ids, "root_assignee": root_assignee},
  147. )
  148. # Outside the txn (own IMMEDIATE txn). ``auto_promote=False`` leaves the
  149. # children in ``todo`` for manual-review-first workflows.
  150. if auto_promote:
  151. recompute_ready(conn)
  152. return child_ids
  153. def _insert_decomposed_child(
  154. conn: sqlite3.Connection, root_id: str, root_row: sqlite3.Row, child: dict,
  155. author: Optional[str], now: int,
  156. ) -> str:
  157. """Insert one decomposed child as ``todo`` (linked under the root later so
  158. the dispatcher only ever sees a coherent graph); returns its id.
  159. Workspace: per-child override wins, else inherit the root's kind. Path
  160. inherits only when kinds match (a 'dir' child must not point at the
  161. root's worktree) and NEVER for worktrees — siblings dispatch concurrently
  162. and one shared checkout would put them all on the first sibling's branch
  163. with no lock; leaving it unset makes dispatch materialize a fresh
  164. ``<repo>/.worktrees/<child-id>`` per child from the board anchor.
  165. """
  166. from hermes_cli.kanban_db import (
  167. _new_task_id, _canonical_assignee, _append_event,
  168. )
  169. root_ws_kind = root_row["workspace_kind"] or "scratch"
  170. child_ws_kind = child.get("workspace_kind") or root_ws_kind
  171. if child.get("workspace_path"):
  172. child_ws_path = child.get("workspace_path")
  173. elif child_ws_kind == "worktree":
  174. child_ws_path = None
  175. elif child_ws_kind == root_ws_kind:
  176. child_ws_path = root_row["workspace_path"]
  177. else:
  178. child_ws_path = None
  179. new_id = _new_task_id()
  180. body = child.get("body")
  181. conn.execute(
  182. "INSERT INTO tasks "
  183. "(id, title, body, assignee, status, workspace_kind, "
  184. " workspace_path, tenant, created_at, created_by) "
  185. "VALUES (?, ?, ?, ?, 'todo', ?, ?, ?, ?, ?)",
  186. (
  187. new_id, child["title"].strip(), body if isinstance(body, str) else None,
  188. _canonical_assignee(child.get("assignee")), child_ws_kind, child_ws_path,
  189. root_row["tenant"], now, (author or "decomposer"),
  190. ),
  191. )
  192. _append_event(
  193. conn, new_id, "created", {"by": author or "decomposer", "from_decompose_of": root_id},
  194. )
  195. inherit_creator_origin(conn, new_id, root_id, created_at=now)
  196. return new_id