@wrongstack/tools 0.310.1 → 0.313.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (135) hide show
  1. package/dist/_shell-pick.d.ts +5 -10
  2. package/dist/audit.js +10 -4055
  3. package/dist/bash.js +9 -2332
  4. package/dist/batch-tool-use.js +2 -187
  5. package/dist/browser/index.js +25 -1339
  6. package/dist/builtin.js +69 -33985
  7. package/dist/chunk-2CTB3UK5.js +197 -0
  8. package/dist/chunk-2ME7ZWDD.js +1272 -0
  9. package/dist/chunk-2TFQDEPU.js +113 -0
  10. package/dist/chunk-2ZCJNKFE.js +315 -0
  11. package/dist/chunk-3PVYQFRQ.js +472 -0
  12. package/dist/chunk-3QMQBO5Z.js +89 -0
  13. package/dist/chunk-42AKKX7O.js +385 -0
  14. package/dist/chunk-42SKEETB.js +113 -0
  15. package/dist/chunk-4BHUSMNL.js +104 -0
  16. package/dist/chunk-4I4LWFOO.js +431 -0
  17. package/dist/chunk-553IQUMO.js +478 -0
  18. package/dist/chunk-55KF77OK.js +1944 -0
  19. package/dist/chunk-6HLZK37X.js +359 -0
  20. package/dist/chunk-6RNIFLG4.js +305 -0
  21. package/dist/chunk-A6BRWIXN.js +317 -0
  22. package/dist/chunk-AHHDWNXC.js +200 -0
  23. package/dist/chunk-B2CIOKWP.js +899 -0
  24. package/dist/chunk-BTSFTGIL.js +7 -0
  25. package/dist/chunk-D33S4RQG.js +222 -0
  26. package/dist/chunk-DIJKHSUO.js +134 -0
  27. package/dist/chunk-DPL47QGS.js +3515 -0
  28. package/dist/chunk-EMRGN4KM.js +170 -0
  29. package/dist/chunk-FGOABE4Z.js +955 -0
  30. package/dist/chunk-FW65TP4G.js +520 -0
  31. package/dist/chunk-GOIZNNOA.js +221 -0
  32. package/dist/chunk-H5MJUAA6.js +295 -0
  33. package/dist/chunk-H5OHH6F4.js +223 -0
  34. package/dist/chunk-HC5RM4WY.js +199 -0
  35. package/dist/chunk-HEQFMLZ7.js +190 -0
  36. package/dist/chunk-HFXSNKCV.js +196 -0
  37. package/dist/chunk-HXSBQ2SE.js +1723 -0
  38. package/dist/chunk-ILESNGNM.js +163 -0
  39. package/dist/chunk-INF5CGAO.js +137 -0
  40. package/dist/chunk-IWDFZ6XR.js +337 -0
  41. package/dist/chunk-IXMNTNW5.js +238 -0
  42. package/dist/chunk-J4SRJKBW.js +428 -0
  43. package/dist/chunk-J5SKD6LN.js +235 -0
  44. package/dist/chunk-JRJJX3L5.js +424 -0
  45. package/dist/chunk-KXNDHMUB.js +366 -0
  46. package/dist/chunk-LIJQMYYX.js +59 -0
  47. package/dist/chunk-MAN26PZ5.js +260 -0
  48. package/dist/chunk-MKRQMLZA.js +474 -0
  49. package/dist/chunk-NBDZMMG2.js +169 -0
  50. package/dist/chunk-NHA6BEIH.js +101 -0
  51. package/dist/chunk-OA6YJIWL.js +4412 -0
  52. package/dist/chunk-OZC255IC.js +2830 -0
  53. package/dist/chunk-PUR6WU2B.js +154 -0
  54. package/dist/chunk-Q5JPPCZC.js +12 -0
  55. package/dist/chunk-QBV725YG.js +128 -0
  56. package/dist/chunk-QHVW4AAM.js +892 -0
  57. package/dist/chunk-QNJ7AQ4B.js +1000 -0
  58. package/dist/chunk-RGISBZBD.js +231 -0
  59. package/dist/chunk-RJZQWEMS.js +84 -0
  60. package/dist/chunk-RP2ZA47V.js +15 -0
  61. package/dist/chunk-RXISBFR5.js +315 -0
  62. package/dist/chunk-S5CCLZL3.js +99 -0
  63. package/dist/chunk-TVTCSBJF.js +122 -0
  64. package/dist/chunk-U4D5S3VQ.js +21 -0
  65. package/dist/chunk-U4VAATKP.js +193 -0
  66. package/dist/chunk-UKU2ZX4C.js +203 -0
  67. package/dist/chunk-UNSKG6DC.js +159 -0
  68. package/dist/chunk-URFKEIHM.js +1091 -0
  69. package/dist/chunk-UTV7YAW7.js +178 -0
  70. package/dist/chunk-V43EQ6VR.js +68 -0
  71. package/dist/chunk-VB3MJGCV.js +610 -0
  72. package/dist/chunk-WHIIIREL.js +223 -0
  73. package/dist/chunk-XMIFYKUT.js +1371 -0
  74. package/dist/chunk-YF2RSV34.js +54 -0
  75. package/dist/chunk-Z6DAKQ3U.js +1 -0
  76. package/dist/chunk-ZIGAZFWE.js +522 -0
  77. package/dist/circuit-breaker.js +3 -191
  78. package/dist/codebase-index/index.js +84 -13688
  79. package/dist/codebase-index/parser-worker-script.js +8 -3995
  80. package/dist/codebase-index/project-server.js +60 -8548
  81. package/dist/codebase-index/worker.js +20 -8416
  82. package/dist/design.js +2 -299
  83. package/dist/diff.js +4 -256
  84. package/dist/document.js +4 -222
  85. package/dist/e2e.js +5 -476
  86. package/dist/edit.js +14 -10200
  87. package/dist/exec.js +16 -3131
  88. package/dist/fetch.js +8 -398
  89. package/dist/format.js +10 -3750
  90. package/dist/generic-parser-VUXDIAOZ.js +13 -0
  91. package/dist/git.js +4 -380
  92. package/dist/glob.js +6 -280
  93. package/dist/go-parser-6CA77WZ4.js +469 -0
  94. package/dist/grep.js +7 -604
  95. package/dist/index.js +318 -35423
  96. package/dist/install.js +10 -4091
  97. package/dist/json-parser-7YMDJSBJ.js +213 -0
  98. package/dist/json.js +4 -665
  99. package/dist/kanban.js +3 -2096
  100. package/dist/languages/index.js +23 -4664
  101. package/dist/legacy-bridge-7UKZT46G.js +18 -0
  102. package/dist/lint.js +10 -3706
  103. package/dist/logs.js +4 -287
  104. package/dist/memory.js +6 -215
  105. package/dist/mode.js +3 -99
  106. package/dist/outdated.js +4 -5170
  107. package/dist/pack.js +65 -33933
  108. package/dist/parser-dispatch-VPOFDO2U.js +14 -0
  109. package/dist/patch.js +13 -9935
  110. package/dist/plan.js +5 -3286
  111. package/dist/process-registry.js +8 -651
  112. package/dist/ps-slash.js +12 -1439
  113. package/dist/py-parser-GPM5VYRG.js +16 -0
  114. package/dist/read.js +13 -9816
  115. package/dist/replace.js +15 -10014
  116. package/dist/rs-parser-WVQ4KYCX.js +81 -0
  117. package/dist/scaffold.js +4 -253
  118. package/dist/search.js +5 -585
  119. package/dist/session-kanban.js +30 -972
  120. package/dist/skill.js +2 -215
  121. package/dist/task.js +5 -3410
  122. package/dist/test.js +10 -3773
  123. package/dist/todo.js +4 -2891
  124. package/dist/tool-help.js +3 -123
  125. package/dist/tool-search.js +3 -79
  126. package/dist/tool-tier.js +68 -34020
  127. package/dist/tool-use.js +2 -93
  128. package/dist/tree-sitter-parser-YCILHGZD.js +17 -0
  129. package/dist/tree.js +4 -288
  130. package/dist/ts-parser-YH4ZMWMH.js +232 -0
  131. package/dist/typecheck.js +10 -3753
  132. package/dist/win32.js +6 -60
  133. package/dist/write.js +14 -9882
  134. package/dist/yaml-parser-GFAOKV53.js +157 -0
  135. package/package.json +5 -5
package/dist/plan.js CHANGED
@@ -1,3290 +1,9 @@
1
- // src/plan.ts
2
- import { randomUUID as randomUUID3 } from "node:crypto";
3
1
  import {
4
- addPlanItem,
5
- clearPlan,
6
- deriveTodosFromPlanItem,
7
- formatPlan,
8
- getPlanTemplate,
9
- mutatePlan as mutatePlan2,
10
- mutateTasks as mutateTasks2,
11
- removePlanItem,
12
- setPlanItemStatus as setPlanItemStatus2
13
- } from "@wrongstack/core/storage";
14
- import { formatTaskList } from "@wrongstack/core/utils";
15
-
16
- // src/session-kanban.ts
17
- import { loadPlan, loadTasks } from "@wrongstack/core/storage";
18
- import { deserializeTaskGraph } from "@wrongstack/core/tasking";
19
- import {
20
- bridgeKanbanSupervisor,
21
- compactSessionMirrorBoard,
22
- createBoard,
23
- DEFAULT_COLUMNS,
24
- getBoard,
25
- getKanbanOrchestrationSnapshot,
26
- listBoards,
27
- pruneSessionBoards,
28
- removeBoard,
29
- syncBoardFromTaskGraph,
30
- touchKanbanPresence,
31
- updateBoard
32
- } from "@wrongstack/kanban";
33
-
34
- // src/session-kanban-graph.ts
35
- var PLAN_STATUS_TO_TASK = {
36
- open: "pending",
37
- in_progress: "in_progress",
38
- done: "completed"
39
- };
40
- function todoListToSerializedGraph(todos, sessionId) {
41
- const graphId = `todo:${sessionId}`;
42
- const nodes = todos.map((todo, index) => ({
43
- id: todo.id,
44
- title: todo.content,
45
- description: todo.activeForm ?? "",
46
- type: "chore",
47
- priority: "medium",
48
- status: todo.status,
49
- specRequirementId: `${graphId}:${todo.id}`,
50
- createdAt: index,
51
- updatedAt: index
52
- }));
53
- return {
54
- id: graphId,
55
- specId: graphId,
56
- requiredRequirementIds: nodes.map((node) => node.specRequirementId),
57
- title: "Session todos",
58
- nodes,
59
- edges: [],
60
- rootNodes: nodes.map((node) => node.id),
61
- createdAt: 0,
62
- updatedAt: 0
63
- };
64
- }
65
- function taskFileToSerializedGraph(tasks, sessionId) {
66
- const graphId = `session:${sessionId}`;
67
- const ids = new Set(tasks.map((task) => task.id));
68
- const nodes = tasks.map((task, index) => ({
69
- id: task.id,
70
- title: task.title,
71
- description: task.description ?? "",
72
- type: task.type,
73
- priority: task.priority,
74
- status: task.status,
75
- specRequirementId: `${graphId}:${task.id}`,
76
- ...task.assignee ? { assignee: task.assignee } : {},
77
- ...task.estimateHours !== void 0 ? { estimateHours: task.estimateHours } : {},
78
- createdAt: index,
79
- updatedAt: index
80
- }));
81
- const edges = tasks.flatMap(
82
- (task) => (task.dependsOn ?? []).filter((dependency) => ids.has(dependency)).map((dependency) => ({
83
- id: `${dependency}->${task.id}`,
84
- from: dependency,
85
- to: task.id,
86
- type: "depends_on"
87
- }))
88
- );
89
- const hasIncoming = new Set(edges.map((edge) => edge.to));
90
- const rootNodes = nodes.filter((node) => !hasIncoming.has(node.id)).map((node) => node.id);
91
- return {
92
- // Keep the historical graph id so existing mirrored task cards are reused.
93
- id: graphId,
94
- specId: graphId,
95
- requiredRequirementIds: nodes.map((node) => node.specRequirementId),
96
- title: "Session tasks",
97
- nodes,
98
- edges,
99
- rootNodes: rootNodes.length ? rootNodes : nodes[0] ? [nodes[0].id] : [],
100
- createdAt: 0,
101
- updatedAt: 0
102
- };
103
- }
104
- function planFileToSerializedGraph(items, sessionId) {
105
- const graphId = `plan:${sessionId}`;
106
- const nodes = items.map((item, index) => ({
107
- id: item.id,
108
- title: item.title,
109
- description: item.details ?? "",
110
- type: "chore",
111
- priority: "medium",
112
- status: PLAN_STATUS_TO_TASK[item.status],
113
- specRequirementId: `${graphId}:${item.id}`,
114
- createdAt: index,
115
- updatedAt: index
116
- }));
117
- return {
118
- id: graphId,
119
- specId: graphId,
120
- requiredRequirementIds: nodes.map((node) => node.specRequirementId),
121
- title: "Session plan",
122
- nodes,
123
- edges: [],
124
- rootNodes: nodes.map((node) => node.id),
125
- createdAt: 0,
126
- updatedAt: 0
127
- };
128
- }
129
-
130
- // src/session-kanban-sync.ts
131
- import { getSharedProjectMailbox } from "@wrongstack/core/coordination";
132
- import { mutatePlan, mutateTasks } from "@wrongstack/core/storage";
133
- import { formatTodosForModel, resolveWstackPaths } from "@wrongstack/core/utils";
134
- import {
135
- getDependencyReadinessIssues
136
- } from "@wrongstack/kanban";
137
- function sourceStatus(task) {
138
- if (task.status === "completed") return "completed";
139
- if (task.status === "in_progress") return "in_progress";
140
- if (task.status === "review") return "review";
141
- if (task.status === "blocked") return "blocked";
142
- if (task.status === "failed") return "failed";
143
- return "pending";
144
- }
145
- function todoStatus(task) {
146
- const status = sourceStatus(task);
147
- if (status === "completed") return "completed";
148
- if (status === "review" && task.assignment?.status === "completed") return "completed";
149
- if (status === "in_progress" || status === "review") return "in_progress";
150
- return "pending";
151
- }
152
- function sessionTodoFromTask(task, board) {
153
- const blockedBy = board ? blockingTitles(board, task) : [];
154
- return {
155
- id: task.origin?.taskId ?? task.id,
156
- content: task.title,
157
- status: todoStatus(task),
158
- ...task.description ? { activeForm: task.description } : {},
159
- ...blockedBy.length ? { blockedBy } : {}
160
- };
161
- }
162
- function managedTodoFromTask(task, board) {
163
- return {
164
- ...sessionTodoFromTask(task, board),
165
- kanbanBoardId: board.id,
166
- kanbanTaskId: task.id
167
- };
168
- }
169
- function blockingTitles(board, task) {
170
- return getDependencyReadinessIssues(board, task).map((issue) => {
171
- const dependency = board.tasks.find((candidate) => candidate.id === issue.dependencyId);
172
- if (!dependency) return `${issue.dependencyId} (missing)`;
173
- return dependency.title;
174
- });
175
- }
176
- var PRIORITY_ORDER = {
177
- critical: 0,
178
- high: 1,
179
- medium: 2,
180
- low: 3
181
- };
182
- function orderTasksForTodos(board, tasks) {
183
- const columnOrder = new Map(board.columns.map((column) => [column.id, column.order]));
184
- const baseline = [...tasks].sort(
185
- (left, right) => (columnOrder.get(left.columnId) ?? 0) - (columnOrder.get(right.columnId) ?? 0) || (PRIORITY_ORDER[left.priority] ?? 2) - (PRIORITY_ORDER[right.priority] ?? 2) || left.order - right.order || left.createdAt.localeCompare(right.createdAt) || left.id.localeCompare(right.id)
186
- );
187
- const included = new Set(baseline.map((task) => task.id));
188
- const remaining = new Map(baseline.map((task) => [task.id, task]));
189
- const emitted = [];
190
- const done = /* @__PURE__ */ new Set();
191
- while (remaining.size > 0) {
192
- const ready = baseline.filter(
193
- (task) => remaining.has(task.id) && (task.dependsOn ?? []).every(
194
- (dependencyId) => !included.has(dependencyId) || done.has(dependencyId)
195
- )
196
- );
197
- if (ready.length === 0) break;
198
- for (const task of ready) {
199
- remaining.delete(task.id);
200
- done.add(task.id);
201
- emitted.push(task);
202
- }
203
- }
204
- for (const task of baseline) if (remaining.has(task.id)) emitted.push(task);
205
- return emitted;
206
- }
207
- function sameTodos(left, right) {
208
- return left.length === right.length && left.every((todo, index) => {
209
- const candidate = right[index];
210
- return candidate?.id === todo.id && candidate.content === todo.content && candidate.status === todo.status && candidate.activeForm === todo.activeForm && candidate.promotedFromPlan === todo.promotedFromPlan && candidate.promotedFromTask === todo.promotedFromTask && candidate.kanbanBoardId === todo.kanbanBoardId && candidate.kanbanTaskId === todo.kanbanTaskId && (candidate.blockedBy ?? []).join("\0") === (todo.blockedBy ?? []).join("\0");
211
- });
212
- }
213
- function broadcastTodoUpdate(context, todos) {
214
- const sessionId = context.session?.id ?? "";
215
- if (!context.agentId || !sessionId) return;
216
- const statusCounts = { pending: 0, inProgress: 0, completed: 0 };
217
- for (const todo of todos) {
218
- if (todo.status === "completed") statusCounts.completed++;
219
- else if (todo.status === "in_progress") statusCounts.inProgress++;
220
- else statusCounts.pending++;
221
- }
222
- const projectDir = resolveWstackPaths({ projectRoot: context.projectRoot }).projectDir;
223
- const mailbox = getSharedProjectMailbox(projectDir);
224
- void mailbox.send({
225
- from: context.agentId,
226
- to: `@session:${sessionId}`,
227
- type: "status",
228
- subject: `Kanban todo list updated (${todos.length} item${todos.length === 1 ? "" : "s"})`,
229
- body: `Shared Kanban board synced this session's todo list: ${todos.length} item${todos.length === 1 ? "" : "s"} \u2014 ${statusCounts.completed} completed, ${statusCounts.inProgress} in progress, ${statusCounts.pending} pending.`,
230
- priority: "normal",
231
- senderSessionId: sessionId
232
- }).catch(() => {
233
- });
234
- }
235
- function notifyTodoUpdate(context, todos) {
236
- const summary = formatTodosForModel(todos);
237
- const text = `[KANBAN TODO UPDATE]
238
- Another Kanban agent reassessed the shared board. The canonical todo list is now:
239
- ${summary}
240
- Reassess your current plan before continuing; do not rely on the initial todo snapshot. Preserve each row's <kanban board/task> binding verbatim on your next \`todo\` call \u2014 a row that loses it stops advancing its card.`;
241
- const state = context.state;
242
- if (typeof state.appendBlockToLastUserMessage === "function") {
243
- if (state.appendBlockToLastUserMessage({ type: "text", text })) return;
244
- }
245
- if (typeof state.appendMessage === "function") {
246
- state.appendMessage({ role: "user", content: [{ type: "text", text }] });
247
- }
248
- }
249
- function applyManagedKanbanBoardToTodos(context, board, suppressedTodoMirrors2, options = {}) {
250
- const metaKanban = context.meta["kanban"];
251
- const metaBoardId = metaKanban && typeof metaKanban === "object" ? metaKanban["boardId"] : void 0;
252
- const activeBoardId2 = context.currentKanbanBoardId ?? (typeof metaBoardId === "string" ? metaBoardId : void 0);
253
- if (!activeBoardId2 || board.id !== activeBoardId2 || board.lifecycle?.mode !== "managed") {
254
- return [...context.todos];
255
- }
256
- const ownerSessionId = options.sessionOwnerFromTags?.(board.tags);
257
- if (ownerSessionId && ownerSessionId !== (context.session?.id ?? "")) {
258
- return [...context.todos];
259
- }
260
- const projectedTodos = orderTasksForTodos(
261
- board,
262
- board.tasks.filter(
263
- (task) => task.status !== "archived" && task.mergedIntoTaskId === void 0 && (!task.childTaskIds || task.childTaskIds.length === 0)
264
- )
265
- ).map((task) => managedTodoFromTask(task, board));
266
- if (sameTodos(context.todos, projectedTodos)) return [...context.todos];
267
- suppressedTodoMirrors2.add(context);
268
- try {
269
- context.state.replaceTodos(projectedTodos);
270
- } finally {
271
- suppressedTodoMirrors2.delete(context);
272
- }
273
- notifyTodoUpdate(context, context.todos);
274
- broadcastTodoUpdate(context, context.todos);
275
- return [...context.todos];
276
- }
277
- async function applySessionKanbanTaskToSource(context, task, suppressedTodoMirrors2, options = {}) {
278
- const originId = task.origin?.taskId;
279
- const graphId = task.origin?.graphId ?? "";
280
- const isTodoOrigin = task.origin?.system === "session-todo" || graphId.startsWith("todo:");
281
- const targetTodo = context.todos?.find(
282
- (todo) => originId !== void 0 && todo.id === originId || todo.kanbanTaskId === task.id || todo.id === task.id && !todo.promotedFromPlan && !todo.promotedFromTask
283
- );
284
- if (isTodoOrigin || targetTodo) {
285
- const matchedId = targetTodo?.id ?? originId;
286
- if (matchedId) {
287
- const mappedStatus = todoStatus(task);
288
- const next = options.remove ? context.todos.filter((todo) => todo.id !== matchedId) : context.todos.map(
289
- (todo) => todo.id === matchedId ? {
290
- ...todo,
291
- content: task.title,
292
- status: mappedStatus,
293
- kanbanTaskId: task.id
294
- } : todo
295
- );
296
- suppressedTodoMirrors2.add(context);
297
- try {
298
- context.state.replaceTodos(next);
299
- } finally {
300
- suppressedTodoMirrors2.delete(context);
301
- }
302
- return { source: "todo", todos: [...context.todos] };
303
- }
304
- }
305
- if (!originId) return { source: null };
306
- const id = context.session?.id ?? "";
307
- if (task.origin?.system === "session-plan" || graphId.startsWith("plan:")) {
308
- const planPath = context.meta["plan.path"];
309
- if (typeof planPath !== "string" || !planPath) {
310
- throw new Error(
311
- "Cannot reflect this Kanban edit back to its plan source: the session has no plan.path configured. The board mutation already succeeded; the plan file is now out of sync."
312
- );
313
- }
314
- const plan = await mutatePlan(planPath, id, (file) => ({
315
- ...file,
316
- updatedAt: (/* @__PURE__ */ new Date()).toISOString(),
317
- items: options.remove ? file.items.filter((item) => item.id !== originId) : file.items.map(
318
- (item) => item.id === originId ? {
319
- ...item,
320
- title: task.title,
321
- details: task.description,
322
- status: task.status === "completed" ? "done" : task.status === "in_progress" || task.status === "review" ? "in_progress" : "open",
323
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
324
- } : item
325
- )
326
- }));
327
- return { source: "plan", plan };
328
- }
329
- if (task.origin?.system === "session-task" || task.origin?.system === "session" || graphId.startsWith("session:")) {
330
- const taskPath = context.meta["task.path"];
331
- if (typeof taskPath !== "string" || !taskPath) {
332
- throw new Error(
333
- "Cannot reflect this Kanban edit back to its task source: the session has no task.path configured. The board mutation already succeeded; the task file is now out of sync."
334
- );
335
- }
336
- const tasks = await mutateTasks(taskPath, id, (file) => ({
337
- ...file,
338
- tasks: options.remove ? file.tasks.filter((item) => item.id !== originId) : file.tasks.map(
339
- (item) => item.id === originId ? {
340
- ...item,
341
- title: task.title,
342
- description: task.description,
343
- status: sourceStatus(task),
344
- updatedAt: (/* @__PURE__ */ new Date()).toISOString()
345
- } : item
346
- )
347
- }));
348
- return { source: "task", tasks };
349
- }
350
- return { source: null };
351
- }
352
-
353
- // src/session-kanban.ts
354
- var SESSION_BOARD_TAG = "session-work";
355
- var MIRROR_DISABLED_ENV = "WRONGSTACK_KANBAN_TASK_MIRROR";
356
- var SESSION_KANBAN_COLUMNS = DEFAULT_COLUMNS.map((column) => ({
357
- ...column
358
- }));
359
- var boardQueue = /* @__PURE__ */ new Map();
360
- var boardEnsures = /* @__PURE__ */ new Map();
361
- var pendingMirrors = /* @__PURE__ */ new Map();
362
- var activeMirrors = /* @__PURE__ */ new Set();
363
- var mirrorFailures = /* @__PURE__ */ new Map();
364
- var suppressedTodoMirrors = /* @__PURE__ */ new WeakSet();
365
- function boardKey(projectRoot, sessionId) {
366
- return `${projectRoot}\0${sessionId}`;
367
- }
368
- function mirrorKey(projectRoot, sessionId, sourceSystem) {
369
- return `${boardKey(projectRoot, sessionId)}\0${sourceSystem}`;
370
- }
371
- function completedReconciliationGraph(latest, candidates) {
372
- const latestNodeIds = new Set(latest.nodes.map((node) => node.id));
373
- const carriedNodeIds = /* @__PURE__ */ new Set();
374
- const completedNodes = candidates.flatMap(
375
- (candidate) => candidate.nodes.filter((node) => {
376
- if (node.status !== "completed" || latestNodeIds.has(node.id) || carriedNodeIds.has(node.id)) {
377
- return false;
378
- }
379
- carriedNodeIds.add(node.id);
380
- return true;
381
- })
382
- );
383
- if (completedNodes.length === 0) return void 0;
384
- const carriedRequirements = completedNodes.flatMap(
385
- (node) => node.specRequirementId ? [node.specRequirementId] : []
386
- );
387
- return {
388
- ...latest,
389
- nodes: [...latest.nodes, ...completedNodes],
390
- rootNodes: [.../* @__PURE__ */ new Set([...latest.rootNodes, ...completedNodes.map((node) => node.id)])],
391
- ...latest.requiredRequirementIds ? {
392
- requiredRequirementIds: [
393
- .../* @__PURE__ */ new Set([...latest.requiredRequirementIds, ...carriedRequirements])
394
- ]
395
- } : {}
396
- };
397
- }
398
- function sessionTag(sessionId) {
399
- return `session:${sessionId}`;
400
- }
401
- function sessionBoardTitle(sessionId) {
402
- const leaf = sessionId.split(/[\\/]/).filter(Boolean).pop() ?? sessionId;
403
- return `Session ${leaf.slice(0, 12)}`;
404
- }
405
- function sessionBoardTags(sessionId) {
406
- return ["session", SESSION_BOARD_TAG, sessionTag(sessionId)];
407
- }
408
- function sessionIdFromTags(tags) {
409
- const tag = tags?.find((candidate) => candidate.startsWith("session:"));
410
- return tag?.slice("session:".length) || null;
411
- }
412
- function sameColumns(columns) {
413
- return columns.length === SESSION_KANBAN_COLUMNS.length && columns.every((column, index) => column.id === SESSION_KANBAN_COLUMNS[index]?.id);
414
- }
415
- async function ensureSessionKanbanBoard(projectRoot, sessionId) {
416
- if (!projectRoot || !sessionId || process.env[MIRROR_DISABLED_ENV] === "0") return null;
417
- const key = boardKey(projectRoot, sessionId);
418
- const inFlight = boardEnsures.get(key);
419
- if (inFlight) return inFlight;
420
- const promise = (async () => {
421
- const summary = (await listBoards(projectRoot)).find(
422
- (board2) => board2.tags?.includes(sessionTag(sessionId))
423
- );
424
- let board = summary ? await getBoard(projectRoot, summary.id) : null;
425
- if (!board) {
426
- return createBoard(projectRoot, {
427
- title: sessionBoardTitle(sessionId),
428
- description: "Live session work: todos, tasks, and plan items.",
429
- tags: sessionBoardTags(sessionId),
430
- columns: SESSION_KANBAN_COLUMNS,
431
- generatedBy: `session-kanban:${sessionId}`,
432
- kind: "session_mirror",
433
- retention: { mode: "archive_after_ttl", ttlMs: 7 * 24 * 60 * 60 * 1e3 }
434
- });
435
- }
436
- if (!sameColumns(board.columns) || !board.tags?.includes(SESSION_BOARD_TAG)) {
437
- board = await updateBoard(projectRoot, board.id, {
438
- title: sessionBoardTitle(sessionId),
439
- description: "Live session work: todos, tasks, and plan items.",
440
- tags: [.../* @__PURE__ */ new Set([...board.tags ?? [], ...sessionBoardTags(sessionId)])],
441
- columns: SESSION_KANBAN_COLUMNS
442
- }) ?? board;
443
- }
444
- return board;
445
- })();
446
- boardEnsures.set(key, promise);
447
- try {
448
- return await promise;
449
- } finally {
450
- boardEnsures.delete(key);
451
- }
452
- }
453
- function enqueueBoardWork(projectRoot, sessionId, work) {
454
- const key = boardKey(projectRoot, sessionId);
455
- const previous = boardQueue.get(key) ?? Promise.resolve();
456
- const result = previous.catch(() => void 0).then(work);
457
- const tail = result.then(
458
- () => void 0,
459
- () => void 0
460
- );
461
- boardQueue.set(key, tail);
462
- void tail.then(() => {
463
- if (boardQueue.get(key) === tail) boardQueue.delete(key);
464
- });
465
- return result;
466
- }
467
- async function projectGraph(projectRoot, sessionId, graph, sourceSystem) {
468
- if (!projectRoot || !sessionId || process.env[MIRROR_DISABLED_ENV] === "0") return null;
469
- return enqueueBoardWork(projectRoot, sessionId, async () => {
470
- const board = await ensureSessionKanbanBoard(projectRoot, sessionId);
471
- if (!board) return null;
472
- const result = await syncBoardFromTaskGraph(
473
- projectRoot,
474
- board.id,
475
- deserializeTaskGraph(graph),
476
- {
477
- sourceSystem,
478
- tags: [.../* @__PURE__ */ new Set([...board.tags ?? [], ...sessionBoardTags(sessionId)])],
479
- archiveMissingTasks: true,
480
- includeCompletedTasks: true,
481
- allowRequirementScopeShrink: true
482
- }
483
- );
484
- if (!result) return null;
485
- const compacted = await compactSessionMirrorBoard(projectRoot, board.id);
486
- if (compacted?.removedTaskIds.length) {
487
- return await getBoard(projectRoot, board.id) ?? result.board;
488
- }
489
- return result.board;
490
- });
491
- }
492
- function queueLatestMirror(projectRoot, sessionId, graph, sourceSystem) {
493
- if (!projectRoot || !sessionId || process.env[MIRROR_DISABLED_ENV] === "0") return;
494
- const key = mirrorKey(projectRoot, sessionId, sourceSystem);
495
- const previous = pendingMirrors.get(key);
496
- const reconciliationGraph = previous ? completedReconciliationGraph(
497
- graph,
498
- [previous.reconciliationGraph, previous.graph].filter(
499
- (candidate) => candidate !== void 0
500
- )
501
- ) : void 0;
502
- pendingMirrors.set(key, {
503
- projectRoot,
504
- sessionId,
505
- graph,
506
- ...reconciliationGraph ? { reconciliationGraph } : {},
507
- sourceSystem
508
- });
509
- if (activeMirrors.has(key)) return;
510
- activeMirrors.add(key);
511
- void (async () => {
512
- try {
513
- for (; ; ) {
514
- const pending = pendingMirrors.get(key);
515
- if (!pending) break;
516
- pendingMirrors.delete(key);
517
- try {
518
- if (pending.reconciliationGraph) {
519
- await projectGraph(
520
- pending.projectRoot,
521
- pending.sessionId,
522
- pending.reconciliationGraph,
523
- pending.sourceSystem
524
- );
525
- }
526
- await projectGraph(
527
- pending.projectRoot,
528
- pending.sessionId,
529
- pending.graph,
530
- pending.sourceSystem
531
- );
532
- mirrorFailures.delete(boardKey(pending.projectRoot, pending.sessionId));
533
- } catch (error) {
534
- const message = error instanceof Error ? error.message : String(error);
535
- mirrorFailures.set(boardKey(pending.projectRoot, pending.sessionId), {
536
- message,
537
- sourceSystem: pending.sourceSystem
538
- });
539
- console.warn(
540
- JSON.stringify({
541
- level: "warn",
542
- event: "session-kanban.mirror-failed",
543
- sessionId: pending.sessionId,
544
- sourceSystem: pending.sourceSystem,
545
- message,
546
- timestamp: (/* @__PURE__ */ new Date()).toISOString()
547
- })
548
- );
549
- }
550
- }
551
- } finally {
552
- activeMirrors.delete(key);
553
- const pending = pendingMirrors.get(key);
554
- if (pending) {
555
- pendingMirrors.delete(key);
556
- queueLatestMirror(
557
- pending.projectRoot,
558
- pending.sessionId,
559
- pending.graph,
560
- pending.sourceSystem
561
- );
562
- }
563
- }
564
- })();
565
- }
566
- function takeSessionMirrorFailure(projectRoot, sessionId) {
567
- if (!projectRoot || !sessionId) return void 0;
568
- const key = boardKey(projectRoot, sessionId);
569
- const failure = mirrorFailures.get(key);
570
- if (!failure) return void 0;
571
- mirrorFailures.delete(key);
572
- return `Kanban mirror (${failure.sourceSystem}) failed and the board may be stale: ${failure.message}`;
573
- }
574
- function projectSessionPlanToKanban(projectRoot, items, sessionId) {
575
- return projectGraph(
576
- projectRoot,
577
- sessionId,
578
- planFileToSerializedGraph(items, sessionId),
579
- "session-plan"
580
- );
581
- }
582
- function mirrorSessionTodosToKanban(projectRoot, todos, sessionId) {
583
- queueLatestMirror(
584
- projectRoot,
585
- sessionId,
586
- todoListToSerializedGraph(todos, sessionId),
587
- "session-todo"
588
- );
589
- }
590
- function applyManagedKanbanBoardToTodos2(context, board) {
591
- return applyManagedKanbanBoardToTodos(context, board, suppressedTodoMirrors, {
592
- sessionOwnerFromTags: sessionIdFromTags
593
- });
594
- }
595
- function applySessionKanbanTaskToSource2(context, task, options = {}) {
596
- return applySessionKanbanTaskToSource(context, task, suppressedTodoMirrors, options);
597
- }
598
-
599
- // src/todo.ts
600
- import {
601
- loadPlan as loadPlan2,
602
- loadTasks as loadTasks3,
603
- savePlan,
604
- saveTasks,
605
- setPlanItemStatus
606
- } from "@wrongstack/core/storage";
607
- import { addTask as addTask3, getBoard as getBoard5 } from "@wrongstack/kanban";
608
-
609
- // src/kanban.ts
610
- import { stripLifecycleIssues as stripLifecycleIssues2 } from "@wrongstack/kanban";
611
-
612
- // src/kanban-board-actions.ts
613
- import { loadTasks as loadTasks2 } from "@wrongstack/core/storage";
614
- import { deserializeTaskGraph as deserializeTaskGraph2, serializeTaskGraph } from "@wrongstack/core/tasking";
615
- import {
616
- addTask,
617
- adoptManagedLifecycle,
618
- createBoard as createBoard2,
619
- createBoardFromTaskGraph,
620
- createBoardFromText,
621
- duplicateBoard,
622
- exportBoardAsMarkdown,
623
- exportBoardToTaskGraph,
624
- getBoard as getBoard3,
625
- getKanbanOrchestrationSnapshot as getKanbanOrchestrationSnapshot2,
626
- getKanbanQueueHealth,
627
- listBoards as listBoards2,
628
- listKanbanEvents,
629
- listReadyTasks,
630
- parseLinesIntoTasks,
631
- removeBoard as removeBoard2,
632
- searchKanban,
633
- syncBoardFromTaskGraph as syncBoardFromTaskGraph2,
634
- updateBoard as updateBoard2
635
- } from "@wrongstack/kanban";
636
-
637
- // src/kanban-board-inputs.ts
638
- function agentSettableGate(enforcement) {
639
- if (enforcement === void 0 || enforcement === "off") return {};
640
- return { completionGate: { enforcement } };
641
- }
642
- function boardCreateInput(input, title) {
643
- return {
644
- title,
645
- ...input.description !== void 0 ? { description: input.description } : {},
646
- ...input.tags !== void 0 ? { tags: input.tags } : {},
647
- ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
648
- ...input.atomicityMode !== void 0 ? {
649
- atomicity: {
650
- mode: input.atomicityMode,
651
- decomposition: input.atomicityDecomposition ?? "propose"
652
- }
653
- } : {},
654
- ...agentSettableGate(input.gateEnforcement)
655
- };
656
- }
657
- function boardUpdatePatch(input) {
658
- return {
659
- ...input.title !== void 0 ? { title: input.title } : {},
660
- ...input.description !== void 0 ? { description: input.description } : {},
661
- ...input.tags !== void 0 ? { tags: input.tags } : {},
662
- ...input.atomicityMode !== void 0 ? {
663
- atomicity: {
664
- mode: input.atomicityMode,
665
- decomposition: input.atomicityDecomposition ?? "propose"
666
- }
667
- } : {},
668
- ...agentSettableGate(input.gateEnforcement)
669
- };
670
- }
671
- function duplicateBoardOptions(input) {
672
- return {
673
- ...input.title !== void 0 ? { title: input.title } : {},
674
- ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
675
- ...input.includeTasks !== void 0 ? { includeTasks: input.includeTasks } : {},
676
- ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {},
677
- ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {}
678
- };
679
- }
680
-
681
- // src/kanban-split-task-handler.ts
682
- import { getBoard as getBoard2, splitTask } from "@wrongstack/kanban";
683
-
684
- // src/kanban-tool-results.ts
685
- function atomicityNudge(task) {
686
- if (task.atomicityAssessment?.verdict !== "needs_decomposition") return "";
687
- const reasons = task.atomicityAssessment.criteria.filter((entry) => entry.score < 1).map((entry) => entry.reason).join(" | ");
688
- return ` Atomicity: needs_decomposition (score ${task.atomicityAssessment.score}) \u2014 call propose_decomposition with 2+ subtasks before dispatch. Reasons: ${reasons}`;
689
- }
690
- function readEnvGateEnforcement() {
691
- const raw = process.env["WRONGSTACK_KANBAN_GATE"]?.trim().toLowerCase();
692
- return raw === "strict" || raw === "soft" || raw === "off" ? raw : void 0;
693
- }
694
- function fail(message) {
695
- return { ok: false, message };
696
- }
697
- function okBoard(board, message = "Board loaded.") {
698
- return { ok: true, message, board };
699
- }
700
- function okTask(board, task, message) {
701
- return { ok: true, message, board, task };
702
- }
703
-
704
- // src/kanban-split-task-handler.ts
705
- async function handleSplitTask(projectRoot, input, extraSplitOptions) {
706
- const boardId = input.boardId;
707
- const taskId = input.taskId;
708
- const childTitles = input.childTitles;
709
- if (!boardId || !taskId || !childTitles?.length) {
710
- return fail("split requires boardId, taskId, and at least one childTitles.");
711
- }
712
- const {
713
- targetColumnId,
714
- inheritAssignment,
715
- inheritLabels,
716
- inheritSuccessCriteria,
717
- inheritGoalMetrics,
718
- inheritDependencies,
719
- chainChildren,
720
- rewireDependents
721
- } = input;
722
- const result = await splitTask(projectRoot, boardId, taskId, {
723
- titles: childTitles,
724
- ...extraSplitOptions,
725
- ...targetColumnId !== void 0 ? { columnId: targetColumnId } : {},
726
- ...inheritAssignment !== void 0 ? { inheritAssignment } : {},
727
- ...inheritLabels !== void 0 ? { inheritLabels } : {},
728
- ...inheritSuccessCriteria !== void 0 ? { inheritSuccessCriteria } : {},
729
- ...inheritGoalMetrics !== void 0 ? { inheritGoalMetrics } : {},
730
- ...inheritDependencies !== void 0 ? { inheritDependencies } : {},
731
- ...chainChildren !== void 0 ? { chainChildren } : {},
732
- ...rewireDependents !== void 0 ? { rewireDependents } : {}
733
- });
734
- if (!result) return fail("Task not found.");
735
- const freshParent = result.board.tasks?.find((t) => t.id === taskId);
736
- if (!freshParent) {
737
- return fail(
738
- `Split succeeded but parent ${taskId} not found in returned board. Children: [${result.children.map((c) => c.id).join(", ")}].`
739
- );
740
- }
741
- return {
742
- ok: true,
743
- message: `${result.children.length} child task(s) created.`,
744
- board: result.board,
745
- task: freshParent,
746
- children: result.children
747
- };
748
- }
749
- async function requireBoard(projectRoot, boardId) {
750
- return boardId ? getBoard2(projectRoot, boardId) : null;
751
- }
752
-
753
- // src/kanban-board-actions.ts
754
- async function handleKanbanBoardAction(projectRoot, input, ctx) {
755
- switch (input.action) {
756
- case "list_boards": {
757
- const boards = await listBoards2(projectRoot);
758
- return { ok: true, message: `${boards.length} board(s).`, boards };
759
- }
760
- case "get_board": {
761
- const board = await requireBoard(projectRoot, input.boardId);
762
- return board ? okBoard(board) : fail("Board not found.");
763
- }
764
- case "create_board": {
765
- if (!input.title) return fail("create_board requires title.");
766
- const existing = (await listBoards2(projectRoot)).filter(
767
- (candidate) => (candidate.kind ?? "project") === "project"
768
- );
769
- const board = await createBoard2(projectRoot, boardCreateInput(input, input.title));
770
- const note = existing.length ? ` ${existing.length} other project board(s) already exist: ${existing.slice(0, 3).map((candidate) => `"${candidate.title}" (${candidate.taskCount} task(s))`).join(
771
- ", "
772
- )}${existing.length > 3 ? ", \u2026" : ""}. If this work belongs to one of them, add_task there instead and delete this board.` : "";
773
- return { ok: true, message: `Board created: ${board.title}.${note}`, board };
774
- }
775
- case "update_board": {
776
- if (!input.boardId) return fail("update_board requires boardId.");
777
- const board = await updateBoard2(projectRoot, input.boardId, boardUpdatePatch(input));
778
- return board ? okBoard(board, "Board updated.") : fail("Board not found.");
779
- }
780
- case "adopt_managed_lifecycle": {
781
- if (!input.boardId || !input.author || !input.transitionComment) {
782
- return fail(
783
- "adopt_managed_lifecycle requires boardId, author, transitionComment, and five ordered columns."
784
- );
785
- }
786
- if (input.columns?.length !== 5) {
787
- return fail(
788
- "adopt_managed_lifecycle columns must be ordered as backlog, todo, running, review, done."
789
- );
790
- }
791
- const [backlog, todo, running, review, done] = input.columns;
792
- if (!backlog || !todo || !running || !review || !done) {
793
- return fail("adopt_managed_lifecycle columns must contain five nonblank ids.");
794
- }
795
- const board = await adoptManagedLifecycle(projectRoot, input.boardId, {
796
- columns: { backlog, todo, running, review, done },
797
- actor: input.author,
798
- comment: input.transitionComment
799
- });
800
- return board ? okBoard(board, "Managed lifecycle adopted without moving existing cards.") : fail("Board not found.");
801
- }
802
- case "release_managed_lifecycle": {
803
- if (!input.boardId) return fail("release_managed_lifecycle requires boardId.");
804
- const board = await updateBoard2(projectRoot, input.boardId, { lifecycle: null });
805
- return board ? okBoard(
806
- board,
807
- "Managed lifecycle released; the board now tracks work without strict gates."
808
- ) : fail("Board not found.");
809
- }
810
- case "duplicate_board": {
811
- if (!input.boardId) return fail("duplicate_board requires boardId.");
812
- const board = await duplicateBoard(projectRoot, input.boardId, duplicateBoardOptions(input));
813
- return board ? okBoard(board, "Board duplicated.") : fail("Board not found.");
814
- }
815
- case "delete_board": {
816
- if (!input.boardId) return fail("delete_board requires boardId.");
817
- const removed = await removeBoard2(projectRoot, input.boardId);
818
- return { ok: removed, message: removed ? "Board deleted." : "Board not found." };
819
- }
820
- case "generate_board": {
821
- if (!input.description) return fail("generate_board requires description.");
822
- const boardInput = createBoardFromText({
823
- description: input.description,
824
- ...input.title !== void 0 ? { title: input.title } : {},
825
- ...input.context !== void 0 ? { context: input.context } : {}
826
- });
827
- const board = await createBoard2(projectRoot, boardInput);
828
- for (const tInput of parseLinesIntoTasks(
829
- input.description,
830
- board.columns[0]?.id ?? "backlog"
831
- )) {
832
- await addTask(projectRoot, board.id, tInput);
833
- }
834
- return okBoard(await getBoard3(projectRoot, board.id) ?? board, "Board generated.");
835
- }
836
- case "export_markdown": {
837
- const board = await requireBoard(projectRoot, input.boardId);
838
- if (!board) return fail("Board not found.");
839
- return {
840
- ok: true,
841
- message: "Board exported.",
842
- board,
843
- markdown: exportBoardAsMarkdown(board)
844
- };
845
- }
846
- case "export_task_graph": {
847
- if (!input.boardId) return fail("export_task_graph requires boardId.");
848
- const exported = await exportBoardToTaskGraph(projectRoot, input.boardId, {
849
- ...input.graphId !== void 0 ? { graphId: input.graphId } : {},
850
- ...input.specId !== void 0 ? { specId: input.specId } : {},
851
- ...input.title !== void 0 ? { title: input.title } : {},
852
- ...input.preserveOriginTaskIds !== void 0 ? { preserveOriginTaskIds: input.preserveOriginTaskIds } : {},
853
- ...input.includeArchived !== void 0 ? { includeArchived: input.includeArchived } : {}
854
- });
855
- if (!exported) return fail("Board not found.");
856
- return {
857
- ok: true,
858
- message: `Task graph exported with ${exported.graph.nodes.size} node(s).`,
859
- board: exported.board,
860
- taskGraph: serializeTaskGraph(exported.graph)
861
- };
862
- }
863
- case "sync_task_graph": {
864
- if (!input.boardId || !input.taskGraph) {
865
- return fail("sync_task_graph requires boardId and taskGraph.");
866
- }
867
- const graph = deserializeTaskGraph2(input.taskGraph);
868
- const result = await syncBoardFromTaskGraph2(projectRoot, input.boardId, graph, {
869
- ...input.title !== void 0 ? { title: input.title } : {},
870
- ...input.description !== void 0 ? { description: input.description } : {},
871
- ...input.tags !== void 0 ? { tags: input.tags } : {},
872
- ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
873
- ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
874
- ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
875
- ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {},
876
- ...input.archiveMissingTasks !== void 0 ? { archiveMissingTasks: input.archiveMissingTasks } : {},
877
- ...input.preserveManualDependencies !== void 0 ? { preserveManualDependencies: input.preserveManualDependencies } : {}
878
- });
879
- return result ? {
880
- ok: true,
881
- message: `Task graph synced: ${result.createdTaskIds.length} created, ${result.updatedTaskIds.length} updated, ${result.archivedTaskIds.length} archived.`,
882
- board: result.board
883
- } : fail("Board not found.");
884
- }
885
- case "create_from_graph": {
886
- if (!input.taskGraph) return fail("create_from_graph requires taskGraph.");
887
- const graph = deserializeTaskGraph2(input.taskGraph);
888
- const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
889
- ...input.title !== void 0 ? { title: input.title } : {},
890
- ...input.description !== void 0 ? { description: input.description } : {},
891
- ...input.tags !== void 0 ? { tags: input.tags } : {},
892
- ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
893
- ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
894
- ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
895
- ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {}
896
- });
897
- return {
898
- ok: true,
899
- message: `Created board "${board.title}" from task graph with ${board.tasks.length} tasks.`,
900
- board
901
- };
902
- }
903
- case "import_session_tasks": {
904
- const taskPath = ctx.meta?.["task.path"];
905
- if (!taskPath) return fail("No session task file for this session.");
906
- const file = await loadTasks2(taskPath);
907
- if (!file || file.tasks.length === 0) return fail("No session tasks to import.");
908
- const sessionId = ctx.session?.id ?? file.sessionId ?? "session";
909
- const graph = deserializeTaskGraph2(taskFileToSerializedGraph(file.tasks, sessionId));
910
- const tags = ["session", `session:${sessionId}`];
911
- const existing = (await listBoards2(projectRoot)).find(
912
- (b) => b.tags?.includes(`session:${sessionId}`)
913
- );
914
- if (existing) {
915
- const result = await syncBoardFromTaskGraph2(projectRoot, existing.id, graph, {
916
- sourceSystem: "session",
917
- tags,
918
- archiveMissingTasks: true,
919
- includeCompletedTasks: true
920
- });
921
- return result ? {
922
- ok: true,
923
- message: `Synced ${file.tasks.length} session tasks into board "${result.board.title}".`,
924
- board: result.board
925
- } : fail("Session board vanished mid-sync.");
926
- }
927
- const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
928
- title: `Session tasks (${sessionId.slice(0, 8)})`,
929
- sourceSystem: "session",
930
- tags
931
- });
932
- return {
933
- ok: true,
934
- message: `Imported ${file.tasks.length} session tasks into new board "${board.title}".`,
935
- board
936
- };
937
- }
938
- case "search_tasks": {
939
- const tasks = await searchKanban(projectRoot, {
940
- query: input.query,
941
- boardId: input.boardId,
942
- assignedAgent: input.agentId,
943
- status: input.status,
944
- priority: input.priority,
945
- label: input.labels?.[0],
946
- chainId: input.chainId
947
- });
948
- return { ok: true, message: `${tasks.length} task(s) matched.`, tasks };
949
- }
950
- case "ready_tasks": {
951
- const tasks = await listReadyTasks(projectRoot, {
952
- query: input.query,
953
- boardId: input.boardId,
954
- assignedAgent: input.agentId,
955
- priority: input.priority,
956
- label: input.labels?.[0],
957
- chainId: input.chainId,
958
- limit: input.limit
959
- });
960
- return { ok: true, message: `${tasks.length} ready task(s).`, tasks };
961
- }
962
- case "snapshot": {
963
- const snapshot = await getKanbanOrchestrationSnapshot2(projectRoot, {
964
- query: input.query,
965
- boardId: input.boardId,
966
- assignedAgent: input.agentId,
967
- status: input.status,
968
- priority: input.priority,
969
- label: input.labels?.[0],
970
- chainId: input.chainId
971
- });
972
- return {
973
- ok: true,
974
- message: `${snapshot.ready.length} ready, ${snapshot.running.length} running, ${snapshot.blocked.length} blocked.`,
975
- snapshot
976
- };
977
- }
978
- case "events": {
979
- if (!input.boardId) return fail("events requires boardId.");
980
- const eventList = await listKanbanEvents(projectRoot, input.boardId);
981
- return {
982
- ok: true,
983
- message: `${eventList.length} event(s).`,
984
- events: eventList
985
- };
986
- }
987
- case "queue_health": {
988
- const health = await getKanbanQueueHealth(projectRoot, {
989
- ...input.boardId !== void 0 ? { boardId: input.boardId } : {}
990
- });
991
- return {
992
- ok: true,
993
- message: `Counts: startable=${health.counts.startable}, running=${health.counts.running}, stale=${health.staleAssignments.count}.`,
994
- queueHealth: health
995
- };
996
- }
997
- default:
998
- return void 0;
999
- }
1000
- }
1001
-
1002
- // src/kanban-contract-actions.ts
1003
- import {
1004
- addContractEdge,
1005
- configureContractGraph,
1006
- evaluateTaskContractGraph,
1007
- getContractGraph,
1008
- removeContractEdge,
1009
- removeContractNode,
1010
- upsertContractNode
1011
- } from "@wrongstack/kanban";
1012
- async function handleKanbanContractAction(projectRoot, input, actor) {
1013
- switch (input.action) {
1014
- case "get_contract_graph": {
1015
- if (!input.boardId) return fail("get_contract_graph requires boardId.");
1016
- const found = await getContractGraph(projectRoot, input.boardId);
1017
- if (!found) return fail("Board not found.");
1018
- const evaluated = input.taskId ? await evaluateTaskContractGraph(projectRoot, input.boardId, input.taskId) : null;
1019
- if (input.taskId && !evaluated) return fail("Task not found on this board.");
1020
- return {
1021
- ok: true,
1022
- message: found.graph ? `Contract map: ${found.graph.nodes.length} node(s), ${found.graph.edges.length} edge(s), enforcement ${found.graph.enforcement}.` : "No contract map on this board yet. Call configure_contract_graph to start one.",
1023
- board: found.board,
1024
- contractGraph: found.graph,
1025
- ...evaluated ? { contractEvaluation: evaluated.evaluation } : {}
1026
- };
1027
- }
1028
- case "configure_contract_graph": {
1029
- if (!input.boardId) return fail("configure_contract_graph requires boardId.");
1030
- const enforcement = input.contractEnforcement ?? "advisory";
1031
- const board = await configureContractGraph(projectRoot, input.boardId, enforcement);
1032
- return board ? okBoard(board, `Contract map enforcement set to ${enforcement}.`) : fail("Board not found.");
1033
- }
1034
- case "upsert_contract_node": {
1035
- if (!input.boardId || !input.taskId) {
1036
- return fail("upsert_contract_node requires boardId and taskId.");
1037
- }
1038
- if (!input.contractNodeKind || !input.contractNodeTitle) {
1039
- return fail("upsert_contract_node requires contractNodeKind and contractNodeTitle.");
1040
- }
1041
- const waiver = input.contractNodeState === "waived" ? {
1042
- actor: actor ?? "agent",
1043
- reason: input.contractWaiverReason ?? "",
1044
- at: (/* @__PURE__ */ new Date()).toISOString()
1045
- } : void 0;
1046
- if (waiver && !waiver.reason.trim()) {
1047
- return fail("A waived contract node requires contractWaiverReason.");
1048
- }
1049
- const result = await upsertContractNode(projectRoot, input.boardId, {
1050
- taskId: input.taskId,
1051
- kind: input.contractNodeKind,
1052
- title: input.contractNodeTitle,
1053
- ...input.contractNodeId !== void 0 ? { id: input.contractNodeId } : {},
1054
- ...input.contractNodeDescription !== void 0 ? { description: input.contractNodeDescription } : {},
1055
- ...input.contractNodeState !== void 0 ? { state: input.contractNodeState } : {},
1056
- ...input.contractNodeEnforcement !== void 0 ? { enforcement: input.contractNodeEnforcement } : {},
1057
- ...input.contractCheckId !== void 0 ? { checkId: input.contractCheckId } : {},
1058
- ...input.contractMetricId !== void 0 ? { metricId: input.contractMetricId } : {},
1059
- ...waiver ? { waiver } : {},
1060
- ...actor !== void 0 ? { createdBy: actor } : {}
1061
- });
1062
- if (!result) return fail("Board or task not found.");
1063
- return {
1064
- ok: true,
1065
- message: `Contract node ${result.node.kind} "${result.node.title}" saved (${result.node.id}).`,
1066
- board: result.board,
1067
- contractGraph: result.board.contractGraph ?? null
1068
- };
1069
- }
1070
- case "remove_contract_node": {
1071
- if (!input.boardId || !input.contractNodeId) {
1072
- return fail("remove_contract_node requires boardId and contractNodeId.");
1073
- }
1074
- const board = await removeContractNode(projectRoot, input.boardId, input.contractNodeId);
1075
- return board ? okBoard(board, "Contract node removed, along with every edge that touched it.") : fail("Contract node not found.");
1076
- }
1077
- case "add_contract_edge": {
1078
- if (!input.boardId || !input.contractEdgeFrom || !input.contractEdgeTo) {
1079
- return fail("add_contract_edge requires boardId, contractEdgeFrom, and contractEdgeTo.");
1080
- }
1081
- if (!input.contractEdgeType) return fail("add_contract_edge requires contractEdgeType.");
1082
- const result = await addContractEdge(projectRoot, input.boardId, {
1083
- from: input.contractEdgeFrom,
1084
- to: input.contractEdgeTo,
1085
- type: input.contractEdgeType,
1086
- ...input.contractEdgeId !== void 0 ? { id: input.contractEdgeId } : {},
1087
- ...input.contractNodeEnforcement !== void 0 ? { enforcement: input.contractNodeEnforcement } : {},
1088
- ...input.contractEdgeRationale !== void 0 ? { rationale: input.contractEdgeRationale } : {},
1089
- ...actor !== void 0 ? { createdBy: actor } : {}
1090
- });
1091
- if (!result) return fail("Board not found.");
1092
- return {
1093
- ok: true,
1094
- message: `Contract edge ${result.edge.type}: ${result.edge.from} \u2192 ${result.edge.to}.`,
1095
- board: result.board,
1096
- contractGraph: result.board.contractGraph ?? null
1097
- };
1098
- }
1099
- case "remove_contract_edge": {
1100
- if (!input.boardId || !input.contractEdgeId) {
1101
- return fail("remove_contract_edge requires boardId and contractEdgeId.");
1102
- }
1103
- const board = await removeContractEdge(projectRoot, input.boardId, input.contractEdgeId);
1104
- return board ? okBoard(board, "Contract edge removed.") : fail("Contract edge not found.");
1105
- }
1106
- default:
1107
- return void 0;
1108
- }
1109
- }
1110
-
1111
- // src/kanban-decomposition-actions.ts
1112
- import {
1113
- assessTaskAtomicity,
1114
- proposeTaskDecomposition,
1115
- updateTask,
1116
- verifyTaskCompletion
1117
- } from "@wrongstack/kanban";
1118
-
1119
- // src/kanban-evidence-bridge.ts
1120
- import { recordCompletedWorkEvidence } from "@wrongstack/core/utils";
1121
- function kanbanEvidenceKey(boardId, taskId) {
1122
- return `kanban:${boardId}:${taskId}`;
1123
- }
1124
- function kanbanEvidencePointer(boardId, taskId) {
1125
- return `kanban://${boardId}/${taskId}#verificationReport`;
1126
- }
1127
- function recordKanbanVerificationEvidence(ctx, report) {
1128
- try {
1129
- const passed = report.checks.filter((check) => check.status === "passed").length;
1130
- const completedAt = Date.parse(report.completedAt);
1131
- recordCompletedWorkEvidence(ctx, {
1132
- key: kanbanEvidenceKey(report.boardId, report.taskId),
1133
- source: "verification",
1134
- summary: `${report.taskTitle} \u2014 verification ${report.verdict} (${passed}/${report.checks.length} checks)`,
1135
- ...Number.isFinite(completedAt) ? { completedAt } : {},
1136
- evidence: kanbanEvidencePointer(report.boardId, report.taskId)
1137
- });
1138
- } catch {
1139
- }
1140
- }
1141
-
1142
- // src/kanban-decomposition-actions.ts
1143
- async function handleKanbanDecompositionAction(projectRoot, input, ctx) {
1144
- switch (input.action) {
1145
- case "assess_atomicity": {
1146
- if (!input.boardId || !input.taskId) {
1147
- return fail("assess_atomicity requires boardId and taskId.");
1148
- }
1149
- const result = await assessTaskAtomicity(projectRoot, input.boardId, input.taskId, {
1150
- assessedBy: "agent",
1151
- ...ctx.agentId !== void 0 ? { eventContext: { actor: ctx.agentId } } : {}
1152
- });
1153
- if (!result) return fail("Task not found.");
1154
- const failing = result.assessment.criteria.filter((entry) => entry.score < 1).map((entry) => entry.reason);
1155
- const guidance = result.assessment.verdict === "needs_decomposition" ? ` This task should be split before dispatch \u2014 call propose_decomposition with 2+ subtasks (each with one verifiable success criterion). Reasons: ${failing.join(" | ")}` : result.assessment.verdict === "composite" ? " Container task: work happens in its children; it is verified via subtask aggregation." : "";
1156
- return okTask(
1157
- result.board,
1158
- result.task,
1159
- `Atomicity verdict: ${result.assessment.verdict} (score ${result.assessment.score}).${guidance}`
1160
- );
1161
- }
1162
- case "propose_decomposition": {
1163
- if (!input.boardId || !input.taskId || !input.subtasks?.length) {
1164
- return fail("propose_decomposition requires boardId, taskId, and subtasks (2+).");
1165
- }
1166
- if (input.subtasks.length < 2) {
1167
- return fail("propose_decomposition requires at least two subtasks.");
1168
- }
1169
- const invalid = input.subtasks.find(
1170
- (subtask) => typeof subtask?.title !== "string" || !subtask.title.trim()
1171
- );
1172
- if (invalid) return fail("Every proposed subtask needs a non-blank title.");
1173
- const result = await proposeTaskDecomposition(
1174
- projectRoot,
1175
- input.boardId,
1176
- input.taskId,
1177
- {
1178
- subtasks: input.subtasks,
1179
- ...input.note !== void 0 ? { rationale: input.note } : {},
1180
- ...ctx.agentId !== void 0 ? { proposedBy: ctx.agentId } : {}
1181
- },
1182
- ctx.agentId !== void 0 ? { actor: ctx.agentId } : {}
1183
- );
1184
- if (!result) return fail("Task not found.");
1185
- const message = result.proposal.status === "applied" ? `Decomposition applied: ${result.proposal.appliedChildTaskIds?.length ?? 0} child tasks created (parent marked atomic).` : 'Decomposition proposal recorded \u2014 awaiting approval (board policy is "propose"). It can be approved from the WebUI or via update_task.';
1186
- return okTask(result.board, result.task, message);
1187
- }
1188
- case "verify_completion": {
1189
- if (!input.boardId || !input.taskId) {
1190
- return fail("verify_completion requires boardId and taskId.");
1191
- }
1192
- const verResult = await verifyTaskCompletion(projectRoot, input.boardId, input.taskId);
1193
- const persistedBoard = await updateTask(projectRoot, input.boardId, input.taskId, {
1194
- verificationReport: verResult.report,
1195
- successCriteria: verResult.task.successCriteria
1196
- });
1197
- if (!persistedBoard) {
1198
- return {
1199
- ok: false,
1200
- verdict: verResult.report.verdict,
1201
- message: `Verification succeeded but persist failed: ${verResult.report.markdownSummary}. Board may be stale \u2014 re-run verify_completion.`,
1202
- board: verResult.board
1203
- };
1204
- }
1205
- recordKanbanVerificationEvidence(ctx, verResult.report);
1206
- const freshTask = persistedBoard.tasks?.find((t) => t.id === input.taskId);
1207
- const deterministicVerdicts = ["passed", "failed", "needs_human", "incomplete"];
1208
- return {
1209
- ok: deterministicVerdicts.includes(
1210
- verResult.report.verdict
1211
- ),
1212
- verdict: verResult.report.verdict,
1213
- message: verResult.report.markdownSummary,
1214
- board: persistedBoard,
1215
- task: freshTask ?? verResult.task
1216
- };
1217
- }
1218
- default:
1219
- return void 0;
1220
- }
1221
- }
1222
-
1223
- // src/kanban-detail-actions.ts
1224
- import {
1225
- addCheckToTask,
1226
- addDependency,
1227
- addGoalMetricToTask,
1228
- addLinkToTask,
1229
- addNoteToTask,
1230
- getKanbanWorkbench,
1231
- removeCheckFromTask,
1232
- updateCheckOnTask,
1233
- updateGoalMetricOnTask
1234
- } from "@wrongstack/kanban";
1235
- async function handleKanbanDetailAction(projectRoot, input) {
1236
- switch (input.action) {
1237
- case "workbench": {
1238
- const workbench = await getKanbanWorkbench(projectRoot, {
1239
- ...input.limit !== void 0 ? { limitPerLane: input.limit, alertLimit: input.limit } : {}
1240
- });
1241
- return {
1242
- ok: true,
1243
- message: `${workbench.totals.now} now, ${workbench.totals.next} next, ${workbench.totals.blocked} blocked, ${workbench.totals.review} review; ${workbench.alertTotal} alert(s).`,
1244
- workbench
1245
- };
1246
- }
1247
- case "add_dependency": {
1248
- if (!input.boardId || !input.taskId || !input.dependencyTaskId) {
1249
- return fail("add_dependency requires boardId, taskId, and dependencyTaskId.");
1250
- }
1251
- const board = await addDependency(
1252
- projectRoot,
1253
- input.boardId,
1254
- input.taskId,
1255
- input.dependencyTaskId
1256
- );
1257
- return board ? okBoard(board, "Dependency added.") : fail("Task not found.");
1258
- }
1259
- case "add_goal_metric": {
1260
- if (!input.boardId || !input.taskId || !input.metricName) {
1261
- return fail("add_goal_metric requires boardId, taskId, and metricName.");
1262
- }
1263
- const board = await addGoalMetricToTask(projectRoot, input.boardId, input.taskId, {
1264
- name: input.metricName,
1265
- ...input.metricStatus !== void 0 ? { status: input.metricStatus } : {},
1266
- ...input.metricTarget !== void 0 ? { target: input.metricTarget } : {},
1267
- ...input.metricCurrent !== void 0 ? { current: input.metricCurrent } : {},
1268
- ...input.metricDirection !== void 0 ? { direction: input.metricDirection } : {},
1269
- ...input.metricUnit !== void 0 ? { unit: input.metricUnit } : {},
1270
- ...input.metricNotes !== void 0 ? { notes: input.metricNotes } : {}
1271
- });
1272
- return board ? okBoard(board, "Goal metric added.") : fail("Task not found.");
1273
- }
1274
- case "update_goal_metric": {
1275
- if (!input.boardId || !input.taskId || !input.metricId) {
1276
- return fail("update_goal_metric requires boardId, taskId, and metricId.");
1277
- }
1278
- const board = await updateGoalMetricOnTask(
1279
- projectRoot,
1280
- input.boardId,
1281
- input.taskId,
1282
- input.metricId,
1283
- {
1284
- ...input.metricName !== void 0 ? { name: input.metricName } : {},
1285
- ...input.metricStatus !== void 0 ? { status: input.metricStatus } : {},
1286
- ...input.metricTarget !== void 0 ? { target: input.metricTarget } : {},
1287
- ...input.metricCurrent !== void 0 ? { current: input.metricCurrent } : {},
1288
- ...input.metricDirection !== void 0 ? { direction: input.metricDirection } : {},
1289
- ...input.metricUnit !== void 0 ? { unit: input.metricUnit } : {},
1290
- ...input.metricNotes !== void 0 ? { notes: input.metricNotes } : {}
1291
- }
1292
- );
1293
- return board ? okBoard(board, "Goal metric updated.") : fail("Metric not found.");
1294
- }
1295
- case "add_check": {
1296
- if (!input.boardId || !input.taskId || !input.checkDescription) {
1297
- return fail("add_check requires boardId, taskId, and checkDescription.");
1298
- }
1299
- const board = await addCheckToTask(projectRoot, input.boardId, input.taskId, {
1300
- description: input.checkDescription,
1301
- type: input.checkType ?? "manual",
1302
- status: input.checkStatus,
1303
- ...input.checkNotes !== void 0 ? { notes: input.checkNotes } : {}
1304
- });
1305
- return board ? okBoard(board, "Check added.") : fail("Task not found.");
1306
- }
1307
- case "update_check": {
1308
- if (!input.boardId || !input.taskId || !input.checkId) {
1309
- return fail("update_check requires boardId, taskId, and checkId.");
1310
- }
1311
- const board = await updateCheckOnTask(
1312
- projectRoot,
1313
- input.boardId,
1314
- input.taskId,
1315
- input.checkId,
1316
- {
1317
- ...input.checkDescription !== void 0 ? { description: input.checkDescription } : {},
1318
- ...input.checkStatus !== void 0 ? { status: input.checkStatus } : {},
1319
- // Promoting an existing manual criterion to an executable one is the
1320
- // common repair: the card was written before anyone knew the command.
1321
- ...input.checkType !== void 0 ? { type: input.checkType } : {},
1322
- ...input.checkNotes !== void 0 ? { notes: input.checkNotes } : {}
1323
- }
1324
- );
1325
- return board ? okBoard(board, "Check updated.") : fail("Check not found.");
1326
- }
1327
- case "remove_check": {
1328
- if (!input.boardId || !input.taskId || !input.checkId) {
1329
- return fail("remove_check requires boardId, taskId, and checkId.");
1330
- }
1331
- const board = await removeCheckFromTask(
1332
- projectRoot,
1333
- input.boardId,
1334
- input.taskId,
1335
- input.checkId
1336
- );
1337
- return board ? okBoard(board, "Acceptance criterion removed.") : fail("Check not found on this task.");
1338
- }
1339
- case "add_note": {
1340
- if (!input.boardId || !input.taskId || !input.note)
1341
- return fail("add_note requires boardId, taskId, and note.");
1342
- const board = await addNoteToTask(projectRoot, input.boardId, input.taskId, {
1343
- author: input.author ?? "agent",
1344
- content: input.note
1345
- });
1346
- return board ? okBoard(board, "Note added.") : fail("Task not found.");
1347
- }
1348
- case "add_link": {
1349
- if (!input.boardId || !input.taskId || !input.url)
1350
- return fail("add_link requires boardId, taskId, and url.");
1351
- const board = await addLinkToTask(projectRoot, input.boardId, input.taskId, {
1352
- url: input.url,
1353
- type: input.linkType ?? "url",
1354
- ...input.linkTitle !== void 0 ? { title: input.linkTitle } : {}
1355
- });
1356
- return board ? okBoard(board, "Link added.") : fail("Task not found.");
1357
- }
1358
- case "split_atomic": {
1359
- if (!input.boardId || !input.taskId || !input.childTitles?.length) {
1360
- return fail("split_atomic requires boardId, taskId, and childTitles (at least one).");
1361
- }
1362
- return handleSplitTask(projectRoot, input, { atomic: true });
1363
- }
1364
- default:
1365
- return void 0;
1366
- }
1367
- }
1368
-
1369
- // src/kanban-lifecycle-actions.ts
1370
- import { randomUUID as randomUUID2 } from "node:crypto";
1371
- import {
1372
- addTask as addTask2,
1373
- assignTask,
1374
- claimReadyTask,
1375
- copyTaskToBoard,
1376
- evaluateContractGraphReadiness,
1377
- finalizeTaskCompletion,
1378
- getBoard as getBoard4,
1379
- getTask,
1380
- getTaskChain,
1381
- heartbeatTaskAssignment,
1382
- mergeTasks,
1383
- moveTask,
1384
- recoverStaleTaskAssignments,
1385
- releaseTaskClaim,
1386
- removeTask,
1387
- repairManagedTaskProjection,
1388
- resolveAutoAccept,
1389
- setTaskChain,
1390
- stripLifecycleIssues,
1391
- transferTaskToBoard,
1392
- transitionTask,
1393
- updateTask as updateTask2,
1394
- updateTaskAssignment,
1395
- verifyTaskCompletion as verifyTaskCompletion2
1396
- } from "@wrongstack/kanban";
1397
-
1398
- // src/kanban-task-inputs.ts
1399
- import { randomUUID } from "node:crypto";
1400
- import { clampSubagentCapabilities } from "@wrongstack/core/security";
1401
- function taskInput(input) {
1402
- const assignment = hasAssignmentInput(input) ? assignmentForTaskCreate(input) : void 0;
1403
- return {
1404
- title: input.title ?? "",
1405
- columnId: input.columnId,
1406
- description: input.description,
1407
- dueDate: input.dueDate,
1408
- priority: input.priority,
1409
- ...input.taskType !== void 0 ? { type: input.taskType } : {},
1410
- status: input.status,
1411
- labels: input.labels,
1412
- ...assignment?.agentId ?? assignment?.role ?? assignment?.name ? { assignedAgent: assignment.agentId ?? assignment.role ?? assignment.name } : {},
1413
- ...input.assignee ?? assignment?.name ?? assignment?.agentId ? { assignee: input.assignee ?? assignment?.name ?? assignment?.agentId } : {},
1414
- ...mergedDependsOn(input) ? { dependsOn: mergedDependsOn(input) } : {},
1415
- ...input.estimatedHours !== void 0 ? { estimatedHours: input.estimatedHours } : {},
1416
- ...input.actualHours !== void 0 ? { actualHours: input.actualHours } : {},
1417
- ...assignment ? { assignment } : {},
1418
- ...input.order !== void 0 ? { order: input.order } : {},
1419
- ...input.retryPolicy !== void 0 ? { retryPolicy: input.retryPolicy } : {},
1420
- ...input.costCeilingUsd !== void 0 ? { costCeilingUsd: input.costCeilingUsd } : {},
1421
- // The system prompt has always told the model it may "set atomic: true"
1422
- // when creating a composite parent. It could not: the field reached
1423
- // neither the create input nor the patch, so the instruction described a
1424
- // capability that did not exist and the attempt was silently dropped.
1425
- ...input.atomic !== void 0 ? { atomic: input.atomic } : {},
1426
- ...input.childTitles !== void 0 ? { childTaskIds: input.childTitles } : {},
1427
- ...input.checkDescription !== void 0 ? {
1428
- successCriteria: [
1429
- {
1430
- id: randomUUID(),
1431
- description: input.checkDescription,
1432
- // `manual` only as the fallback. Hard-coding it here meant every
1433
- // agent-authored criterion was unverifiable by construction: the
1434
- // deterministic plugins never matched, the registry passed the
1435
- // hand-set status straight through, and "verified" collapsed into
1436
- // "the author ticked its own box".
1437
- type: input.checkType ?? "manual",
1438
- status: input.checkStatus ?? "pending",
1439
- ...input.checkNotes !== void 0 ? { notes: input.checkNotes } : {}
1440
- }
1441
- ]
1442
- } : {},
1443
- ...input.metricName !== void 0 ? {
1444
- goalMetrics: [
1445
- {
1446
- id: randomUUID(),
1447
- name: input.metricName,
1448
- status: input.metricStatus ?? "pending",
1449
- ...input.metricTarget !== void 0 ? { target: input.metricTarget } : {},
1450
- ...input.metricCurrent !== void 0 ? { current: input.metricCurrent } : {},
1451
- ...input.metricDirection !== void 0 ? { direction: input.metricDirection } : {},
1452
- ...input.metricUnit !== void 0 ? { unit: input.metricUnit } : {},
1453
- ...input.metricNotes !== void 0 ? { notes: input.metricNotes } : {}
1454
- }
1455
- ]
1456
- } : {},
1457
- ...input.url !== void 0 ? {
1458
- links: [
1459
- {
1460
- url: input.url,
1461
- type: input.linkType ?? "url",
1462
- ...input.linkTitle !== void 0 ? { title: input.linkTitle } : {}
1463
- }
1464
- ]
1465
- } : {},
1466
- ...input.note !== void 0 ? {
1467
- notes: [
1468
- {
1469
- id: randomUUID(),
1470
- author: input.author ?? "agent",
1471
- content: input.note,
1472
- createdAt: (/* @__PURE__ */ new Date()).toISOString()
1473
- }
1474
- ]
1475
- } : {},
1476
- ...[input.graphId, input.specId, input.specRequirementId].some((value) => value !== void 0) ? {
1477
- origin: {
1478
- system: input.sourceSystem ?? "kanban-tool",
1479
- ...input.graphId !== void 0 ? { graphId: input.graphId } : {},
1480
- ...input.specId !== void 0 ? { specId: input.specId } : {},
1481
- ...input.specRequirementId !== void 0 ? { specRequirementId: input.specRequirementId } : {},
1482
- ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {}
1483
- }
1484
- } : {}
1485
- };
1486
- }
1487
- function mergedDependsOn(input) {
1488
- if (input.dependsOn === void 0 && input.dependencyTaskId === void 0) return void 0;
1489
- return [
1490
- ...input.dependsOn ?? [],
1491
- ...input.dependencyTaskId !== void 0 ? [input.dependencyTaskId] : []
1492
- ].filter((id, i, arr) => id && arr.indexOf(id) === i);
1493
- }
1494
- function taskPatch(input) {
1495
- return {
1496
- title: input.title,
1497
- description: input.description,
1498
- dueDate: input.dueDate,
1499
- columnId: input.columnId,
1500
- order: input.order,
1501
- priority: input.priority,
1502
- ...input.taskType !== void 0 ? { type: input.taskType } : {},
1503
- status: input.status,
1504
- labels: input.labels,
1505
- assignedAgent: input.agentId,
1506
- ...mergedDependsOn(input) !== void 0 ? { dependsOn: mergedDependsOn(input) } : {},
1507
- // `atomic` and `childTaskIds` are the composite-parent contract, and the
1508
- // managed gate reads both: an `atomic` parent may not move forward without
1509
- // children, and may not reach Done until every child is completed. The
1510
- // manager has always accepted both on a patch; only this surface withheld
1511
- // them, so `split_atomic` was a one-way door — delete the children and the
1512
- // parent was stranded with no way to declare itself a leaf again.
1513
- ...input.atomic !== void 0 ? { atomic: input.atomic } : {},
1514
- ...input.childTaskIds !== void 0 ? { childTaskIds: input.childTaskIds } : {},
1515
- ...input.estimatedHours !== void 0 ? { estimatedHours: input.estimatedHours } : {},
1516
- ...input.actualHours !== void 0 ? { actualHours: input.actualHours } : {}
1517
- };
1518
- }
1519
- function clampRequestedCapabilities(requested) {
1520
- if (requested === void 0) return void 0;
1521
- return clampSubagentCapabilities(requested).granted;
1522
- }
1523
- function assignmentInput(input) {
1524
- return {
1525
- agentId: input.agentId,
1526
- name: input.name,
1527
- role: input.role,
1528
- provider: input.provider,
1529
- model: input.model,
1530
- fallbackProfile: input.fallbackProfile,
1531
- fallbackModels: input.fallbackModels,
1532
- tools: input.tools,
1533
- allowedCapabilities: clampRequestedCapabilities(input.allowedCapabilities),
1534
- assignee: input.assignee,
1535
- leaseId: input.leaseId,
1536
- claimedAt: input.claimedAt,
1537
- heartbeatAt: input.heartbeatAt,
1538
- leaseExpiresAt: input.leaseExpiresAt,
1539
- attempt: input.attempt,
1540
- maxAttempts: input.maxAttempts,
1541
- costCeilingUsd: input.costCeilingUsd,
1542
- retryPolicy: input.retryPolicy,
1543
- lastFailureKind: input.lastFailureKind
1544
- };
1545
- }
1546
- function hasAssignmentInput(input) {
1547
- return input.agentId !== void 0 || input.name !== void 0 || input.role !== void 0 || input.provider !== void 0 || input.model !== void 0 || input.fallbackProfile !== void 0 || input.fallbackModels !== void 0 || input.tools !== void 0 || input.allowedCapabilities !== void 0 || input.assignee !== void 0 || input.leaseId !== void 0 || input.claimedAt !== void 0 || input.heartbeatAt !== void 0 || input.leaseExpiresAt !== void 0 || input.attempt !== void 0 || input.maxAttempts !== void 0 || input.costCeilingUsd !== void 0 || input.retryPolicy !== void 0 || input.lastFailureKind !== void 0 || input.assignmentStatus !== void 0;
1548
- }
1549
- function assignmentForTaskCreate(input) {
1550
- return {
1551
- status: input.assignmentStatus ?? "assigned",
1552
- ...input.agentId !== void 0 ? { agentId: input.agentId } : {},
1553
- ...input.name !== void 0 ? { name: input.name } : {},
1554
- ...input.role !== void 0 ? { role: input.role } : {},
1555
- ...input.provider !== void 0 ? { provider: input.provider } : {},
1556
- ...input.model !== void 0 ? { model: input.model } : {},
1557
- ...input.fallbackProfile !== void 0 ? { fallbackProfile: input.fallbackProfile } : {},
1558
- ...input.fallbackModels !== void 0 ? { fallbackModels: input.fallbackModels } : {},
1559
- ...input.tools !== void 0 ? { tools: input.tools } : {},
1560
- ...input.allowedCapabilities !== void 0 ? { allowedCapabilities: clampRequestedCapabilities(input.allowedCapabilities) } : {},
1561
- ...input.leaseId !== void 0 ? { leaseId: input.leaseId } : {},
1562
- ...input.claimedAt !== void 0 ? { claimedAt: input.claimedAt } : {},
1563
- ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1564
- ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1565
- ...input.attempt !== void 0 ? { attempt: input.attempt } : {},
1566
- ...input.maxAttempts !== void 0 ? { maxAttempts: input.maxAttempts } : {},
1567
- ...input.costCeilingUsd !== void 0 ? { costCeilingUsd: input.costCeilingUsd } : {},
1568
- ...input.retryPolicy !== void 0 ? { retryPolicy: input.retryPolicy } : {},
1569
- ...input.lastFailureKind !== void 0 ? { lastFailureKind: input.lastFailureKind } : {}
1570
- };
1571
- }
1572
-
1573
- // src/kanban-lifecycle-actions.ts
1574
- async function syncContextTask(ctx, task, options = {}) {
1575
- if (!ctx?.state || !task) return;
1576
- try {
1577
- await applySessionKanbanTaskToSource2(ctx, task, options);
1578
- } catch {
1579
- }
1580
- }
1581
- async function handleKanbanLifecycleAction(projectRoot, input, ctx) {
1582
- switch (input.action) {
1583
- case "add_task": {
1584
- if (!input.boardId || !input.title) return fail("add_task requires boardId and title.");
1585
- const result = await addTask2(projectRoot, input.boardId, taskInput(input));
1586
- if (!result) return fail("Board not found.");
1587
- await syncContextTask(ctx, result.task);
1588
- return okTask(result.board, result.task, `Task added.${atomicityNudge(result.task)}`);
1589
- }
1590
- case "split_task": {
1591
- if (!input.boardId || !input.taskId || !input.childTitles?.length) {
1592
- return fail("split_task requires boardId, taskId, and childTitles.");
1593
- }
1594
- return handleSplitTask(projectRoot, input, {});
1595
- }
1596
- case "merge_tasks": {
1597
- if (!input.boardId || !input.taskIds?.length || !input.title) {
1598
- return fail("merge_tasks requires boardId, taskIds, and title.");
1599
- }
1600
- const result = await mergeTasks(projectRoot, input.boardId, {
1601
- taskIds: input.taskIds,
1602
- title: input.title,
1603
- ...input.description !== void 0 ? { description: input.description } : {},
1604
- ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1605
- ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1606
- ...input.closeSourceTasks !== void 0 ? { closeSourceTasks: input.closeSourceTasks } : {}
1607
- });
1608
- return result ? okTask(result.board, result.task, "Tasks merged.") : fail("Board or task not found.");
1609
- }
1610
- case "copy_task": {
1611
- if (!input.boardId || !input.taskId || !input.targetBoardId) {
1612
- return fail("copy_task requires boardId, taskId, and targetBoardId.");
1613
- }
1614
- const result = await copyTaskToBoard(
1615
- projectRoot,
1616
- input.boardId,
1617
- input.taskId,
1618
- input.targetBoardId,
1619
- {
1620
- ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1621
- ...input.order !== void 0 ? { targetOrder: input.order } : {},
1622
- ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1623
- ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1624
- }
1625
- );
1626
- return result ? okTask(result.targetBoard, result.task, "Task copied to target board.") : fail("Board or task not found.");
1627
- }
1628
- case "transfer_task": {
1629
- if (!input.boardId || !input.taskId || !input.targetBoardId) {
1630
- return fail("transfer_task requires boardId, taskId, and targetBoardId.");
1631
- }
1632
- const result = await transferTaskToBoard(
1633
- projectRoot,
1634
- input.boardId,
1635
- input.taskId,
1636
- input.targetBoardId,
1637
- {
1638
- ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1639
- ...input.order !== void 0 ? { targetOrder: input.order } : {},
1640
- ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1641
- ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1642
- }
1643
- );
1644
- return result ? okTask(result.targetBoard, result.task, "Task transferred to target board.") : fail("Board or task not found.");
1645
- }
1646
- case "get_task": {
1647
- if (!input.boardId || !input.taskId) return fail("get_task requires boardId and taskId.");
1648
- const task = await getTask(projectRoot, input.boardId, input.taskId);
1649
- return task ? { ok: true, message: "Task loaded.", task } : fail("Task not found.");
1650
- }
1651
- case "start_task": {
1652
- if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1653
- return fail("start_task requires boardId, taskId, author, and transitionComment.");
1654
- }
1655
- let board = await getBoard4(projectRoot, input.boardId);
1656
- let task = board?.tasks.find((candidate) => candidate.id === input.taskId);
1657
- if (!board || !task) return fail("Board or task not found.");
1658
- const readiness = evaluateContractGraphReadiness(board, task.id);
1659
- if (!readiness.ready) {
1660
- return fail(
1661
- `Task is not implementation-ready: ${readiness.issues.map((issue) => issue.message).join(" | ")}`
1662
- );
1663
- }
1664
- if (board.lifecycle?.mode !== "managed") {
1665
- const now = /* @__PURE__ */ new Date();
1666
- const assigned = await updateTaskAssignment(projectRoot, board.id, task.id, {
1667
- status: "running",
1668
- agentId: input.agentId ?? input.author,
1669
- leaseId: input.leaseId ?? randomUUID2(),
1670
- claimedAt: input.claimedAt ?? now.toISOString(),
1671
- heartbeatAt: input.heartbeatAt ?? now.toISOString(),
1672
- leaseExpiresAt: input.leaseExpiresAt ?? new Date(now.getTime() + 15 * 6e4).toISOString(),
1673
- attempt: input.attempt ?? 1,
1674
- maxAttempts: input.maxAttempts ?? 3
1675
- });
1676
- if (!assigned) return fail("Task assignment could not be started.");
1677
- const started = await updateTask2(projectRoot, board.id, task.id, {
1678
- status: "in_progress"
1679
- });
1680
- const current = started ?? assigned;
1681
- const claimed = task;
1682
- const currentTask = current.tasks.find((candidate) => candidate.id === claimed.id) ?? claimed;
1683
- ctx.setCurrentKanbanTask?.(currentTask.id, current.id);
1684
- return okTask(
1685
- current,
1686
- currentTask,
1687
- "Task is active and bound to this run for attribution. This board is not in managed lifecycle mode, so runtime Kanban governance was not bound to it."
1688
- );
1689
- }
1690
- let stage = task.lifecycle?.currentStage;
1691
- if (stage === "backlog") {
1692
- const moved = await transitionTask(projectRoot, board.id, task.id, {
1693
- to: "todo",
1694
- actor: input.author,
1695
- comment: input.transitionComment
1696
- });
1697
- if (!moved) return fail("Task could not enter Todo.");
1698
- board = moved.board;
1699
- task = moved.task;
1700
- stage = task.lifecycle?.currentStage;
1701
- }
1702
- if (stage === "todo" || stage === "review") {
1703
- const now = /* @__PURE__ */ new Date();
1704
- const leaseId = input.leaseId ?? randomUUID2();
1705
- const assigned = await updateTaskAssignment(projectRoot, board.id, task.id, {
1706
- status: "running",
1707
- agentId: input.agentId ?? input.author,
1708
- leaseId,
1709
- claimedAt: input.claimedAt ?? now.toISOString(),
1710
- heartbeatAt: input.heartbeatAt ?? now.toISOString(),
1711
- leaseExpiresAt: input.leaseExpiresAt ?? new Date(now.getTime() + 15 * 6e4).toISOString(),
1712
- attempt: input.attempt ?? 1,
1713
- maxAttempts: input.maxAttempts ?? 3
1714
- });
1715
- if (!assigned) return fail("Task assignment could not be started.");
1716
- const moved = await transitionTask(projectRoot, board.id, task.id, {
1717
- to: "running",
1718
- actor: input.author,
1719
- comment: input.transitionComment
1720
- });
1721
- if (!moved) return fail("Task could not enter Running.");
1722
- board = moved.board;
1723
- task = moved.task;
1724
- stage = task.lifecycle?.currentStage;
1725
- }
1726
- if (stage !== "running" || task.assignment?.status !== "running") {
1727
- return fail(
1728
- `start_task only accepts Backlog, Todo, Review repair, or live Running cards (current: ${stage ?? "unknown"}).`
1729
- );
1730
- }
1731
- ctx.setCurrentKanbanTask(task.id, board.id);
1732
- await syncContextTask(ctx, task);
1733
- return okTask(
1734
- board,
1735
- task,
1736
- "Task is active; runtime Kanban governance is now bound to this run."
1737
- );
1738
- }
1739
- case "update_task": {
1740
- if (!input.boardId || !input.taskId) return fail("update_task requires boardId and taskId.");
1741
- const board = await updateTask2(projectRoot, input.boardId, input.taskId, taskPatch(input));
1742
- if (board) {
1743
- await syncContextTask(ctx, board.tasks.find((t) => t.id === input.taskId));
1744
- }
1745
- return board ? okBoard(board, "Task updated.") : fail("Task not found.");
1746
- }
1747
- case "transition_task": {
1748
- if (!input.boardId || !input.taskId || !input.lifecycleStage || !input.author || !input.transitionComment) {
1749
- return fail(
1750
- "transition_task requires boardId, taskId, lifecycleStage, author, and transitionComment."
1751
- );
1752
- }
1753
- if (input.lifecycleStage === "done") {
1754
- const boardBefore = await getBoard4(projectRoot, input.boardId);
1755
- const taskBefore = boardBefore ? await getTask(projectRoot, input.boardId, input.taskId) : null;
1756
- if (boardBefore && taskBefore && !taskBefore.verificationReport && (taskBefore.atomic || Boolean(taskBefore.successCriteria?.length))) {
1757
- const preGate = await verifyTaskCompletion2(projectRoot, input.boardId, taskBefore.id, {
1758
- persist: false
1759
- });
1760
- await updateTask2(projectRoot, input.boardId, taskBefore.id, {
1761
- verificationReport: preGate.report,
1762
- successCriteria: preGate.task.successCriteria
1763
- });
1764
- }
1765
- }
1766
- const result = await transitionTask(projectRoot, input.boardId, input.taskId, {
1767
- to: input.lifecycleStage,
1768
- actor: input.author,
1769
- comment: input.transitionComment,
1770
- ...input.transitionAction !== void 0 ? { action: input.transitionAction } : {},
1771
- ...input.tickChecks !== void 0 ? { tickChecks: input.tickChecks } : {},
1772
- ...input.attachmentUrl !== void 0 ? {
1773
- attachment: {
1774
- url: input.attachmentUrl,
1775
- type: input.attachmentType ?? "url",
1776
- ...input.attachmentTitle !== void 0 ? { title: input.attachmentTitle } : {}
1777
- }
1778
- } : {},
1779
- patch: taskPatch(input)
1780
- });
1781
- if (result && input.lifecycleStage === "done" && result.task.verificationReport) {
1782
- recordKanbanVerificationEvidence(ctx, result.task.verificationReport);
1783
- }
1784
- if (result?.task) {
1785
- await syncContextTask(ctx, result.task);
1786
- }
1787
- return result ? okTask(result.board, result.task, `Task advanced to ${result.transition.to}.`) : fail("Board or task not found.");
1788
- }
1789
- case "repair_managed_projection": {
1790
- if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1791
- return fail(
1792
- "repair_managed_projection requires boardId, taskId, author, and transitionComment."
1793
- );
1794
- }
1795
- const result = await repairManagedTaskProjection(projectRoot, input.boardId, input.taskId, {
1796
- actor: input.author,
1797
- comment: input.transitionComment
1798
- });
1799
- if (result?.task) {
1800
- await syncContextTask(ctx, result.task);
1801
- }
1802
- return result ? okTask(
1803
- result.board,
1804
- result.task,
1805
- "Managed card projection repaired from lifecycle history."
1806
- ) : fail("Board or task not found.");
1807
- }
1808
- case "move_task": {
1809
- if (!input.boardId || !input.taskId || !input.targetColumnId) {
1810
- return fail("move_task requires boardId, taskId, and targetColumnId.");
1811
- }
1812
- const board = await moveTask(
1813
- projectRoot,
1814
- input.boardId,
1815
- input.taskId,
1816
- input.targetColumnId,
1817
- input.order
1818
- );
1819
- if (board) {
1820
- await syncContextTask(ctx, board.tasks.find((t) => t.id === input.taskId));
1821
- }
1822
- return board ? okBoard(board, "Task moved.") : fail("Move failed.");
1823
- }
1824
- case "delete_task": {
1825
- if (!input.boardId || !input.taskId) return fail("delete_task requires boardId and taskId.");
1826
- const boardBefore = await getBoard4(projectRoot, input.boardId);
1827
- const taskToDelete = boardBefore?.tasks.find((t) => t.id === input.taskId);
1828
- const board = await removeTask(projectRoot, input.boardId, input.taskId);
1829
- if (board && ctx.currentKanbanTaskId === input.taskId) {
1830
- ctx.setCurrentKanbanTask?.(void 0, ctx.currentKanbanBoardId);
1831
- }
1832
- if (board && taskToDelete) {
1833
- await syncContextTask(ctx, taskToDelete, { remove: true });
1834
- }
1835
- return board ? okBoard(board, "Task deleted.") : fail("Task not found.");
1836
- }
1837
- case "set_chain": {
1838
- if (!input.boardId || !input.taskIds?.length) {
1839
- return fail("set_chain requires boardId and taskIds.");
1840
- }
1841
- const result = await setTaskChain(projectRoot, input.boardId, {
1842
- taskIds: input.taskIds,
1843
- ...input.chainId !== void 0 ? { chainId: input.chainId } : {},
1844
- ...input.enforceDependencies !== void 0 ? { enforceDependencies: input.enforceDependencies } : {}
1845
- });
1846
- return result ? {
1847
- ok: true,
1848
- message: `Chain set: ${result.chainId}`,
1849
- board: result.board,
1850
- chain: result.tasks
1851
- } : fail("Board or task not found.");
1852
- }
1853
- case "get_chain": {
1854
- if (!input.boardId || !(input.taskId || input.chainId)) {
1855
- return fail("get_chain requires boardId and taskId or chainId.");
1856
- }
1857
- const result = await getTaskChain(
1858
- projectRoot,
1859
- input.boardId,
1860
- input.taskId ?? input.chainId ?? ""
1861
- );
1862
- return result ? {
1863
- ok: true,
1864
- message: `Chain loaded: ${result.chainId}`,
1865
- board: result.board,
1866
- chain: result.tasks
1867
- } : fail("Chain not found.");
1868
- }
1869
- case "claim_task": {
1870
- const result = await claimReadyTask(projectRoot, {
1871
- ...input.boardId !== void 0 ? { boardId: input.boardId } : {},
1872
- ...input.taskId !== void 0 ? { taskId: input.taskId } : {},
1873
- ...assignmentInput(input),
1874
- status: input.assignmentStatus ?? "queued"
1875
- });
1876
- return result ? okTask(result.board, result.task, "Task claimed.") : fail("No ready kanban task matched the claim.");
1877
- }
1878
- case "release_task": {
1879
- if (!input.boardId || !input.taskId) {
1880
- return fail("release_task requires boardId and taskId.");
1881
- }
1882
- const board = await releaseTaskClaim(projectRoot, input.boardId, input.taskId, {
1883
- ...input.releaseStatus !== void 0 ? { status: input.releaseStatus } : {},
1884
- ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
1885
- ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {}
1886
- });
1887
- return board ? okBoard(board, "Task claim released.") : fail("Task not found.");
1888
- }
1889
- case "assign_task": {
1890
- if (!input.boardId || !input.taskId) return fail("assign_task requires boardId and taskId.");
1891
- const board = await assignTask(
1892
- projectRoot,
1893
- input.boardId,
1894
- input.taskId,
1895
- assignmentInput(input)
1896
- );
1897
- return board ? okBoard(board, "Task assigned.") : fail("Task not found.");
1898
- }
1899
- case "mark_assignment": {
1900
- if (!input.boardId || !input.taskId)
1901
- return fail("mark_assignment requires boardId and taskId.");
1902
- const assignmentStatus = input.assignmentStatus ?? (input.status === "completed" ? "completed" : input.error ? "failed" : void 0);
1903
- const board = await updateTaskAssignment(
1904
- projectRoot,
1905
- input.boardId,
1906
- input.taskId,
1907
- {
1908
- ...assignmentStatus !== void 0 ? { status: assignmentStatus } : {},
1909
- ...input.subagentId !== void 0 ? { subagentId: input.subagentId } : {},
1910
- ...input.runTaskId !== void 0 ? { runTaskId: input.runTaskId } : {},
1911
- ...input.lastResult !== void 0 ? { lastResult: input.lastResult } : {},
1912
- ...input.error !== void 0 ? { error: input.error } : {},
1913
- ...input.agentId !== void 0 ? { agentId: input.agentId } : {},
1914
- ...input.leaseId !== void 0 ? { leaseId: input.leaseId } : {},
1915
- ...input.claimedAt !== void 0 ? { claimedAt: input.claimedAt } : {},
1916
- ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1917
- ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1918
- ...input.attempt !== void 0 ? { attempt: input.attempt } : {},
1919
- ...input.maxAttempts !== void 0 ? { maxAttempts: input.maxAttempts } : {}
1920
- },
1921
- input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
1922
- );
1923
- if (!board) return fail("Task not found.");
1924
- if (assignmentStatus === "completed" && board.lifecycle?.mode !== "managed") {
1925
- const envGate = readEnvGateEnforcement();
1926
- const finalized = await finalizeTaskCompletion(projectRoot, board.id, input.taskId, {
1927
- ...board.completionGate === void 0 && envGate !== void 0 ? { enforcement: envGate } : {},
1928
- ...ctx.agentId !== void 0 ? { eventContext: { actor: ctx.agentId } } : {}
1929
- });
1930
- if (finalized) {
1931
- if (finalized.gate.report) {
1932
- recordKanbanVerificationEvidence(ctx, finalized.gate.report);
1933
- }
1934
- const gateSummary = {
1935
- enforcement: finalized.gate.enforcement,
1936
- allowed: finalized.gate.allowed,
1937
- verdict: finalized.gate.verdict,
1938
- issues: finalized.gate.issues.map((issue) => issue.message)
1939
- };
1940
- const gateMessage = finalized.gate.allowed ? `Completion gate ${finalized.gate.verdict === "skipped" ? "passed" : "passed"}; task completed.` : finalized.gate.enforcement === "strict" ? `Completion gate BLOCKED (verdict: ${finalized.gate.verdict}); task parked in review. Issues: ${gateSummary.issues.join(" | ")}` : `Completion gate failed softly (verdict: ${finalized.gate.verdict}); task completed with warnings. Issues: ${gateSummary.issues.join(" | ")}`;
1941
- await syncContextTask(ctx, finalized.task);
1942
- return {
1943
- ...okTask(finalized.board, finalized.task, `Assignment updated. ${gateMessage}`),
1944
- gate: gateSummary
1945
- };
1946
- }
1947
- } else if (board.lifecycle?.mode === "managed") {
1948
- const managedTask = board.tasks.find((candidate) => candidate.id === input.taskId);
1949
- const stage = managedTask?.lifecycle?.currentStage;
1950
- const actor = ctx.agentId ?? "kanban-agent";
1951
- let transitionResult = null;
1952
- const lifecycleWarnings = [];
1953
- if (assignmentStatus === "running" && stage === "todo") {
1954
- try {
1955
- transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
1956
- to: "running",
1957
- actor,
1958
- comment: "Work started."
1959
- });
1960
- } catch (err) {
1961
- lifecycleWarnings.push(
1962
- `Lifecycle transition to Running deferred: ${stripLifecycleIssues(err instanceof Error ? err.message : String(err))}`
1963
- );
1964
- }
1965
- }
1966
- if (assignmentStatus === "completed" && stage === "running") {
1967
- const comment = typeof input.lastResult === "string" && input.lastResult.trim().length > 0 ? input.lastResult.trim().slice(0, 1e3) : "Work completed.";
1968
- try {
1969
- transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
1970
- to: "review",
1971
- actor,
1972
- comment,
1973
- attachment: {
1974
- url: `kanban://task/${input.taskId}/result`,
1975
- title: "Worker completion result",
1976
- type: "file"
1977
- },
1978
- patch: {
1979
- ...input.agentId !== void 0 ? { assignedAgent: input.agentId } : {}
1980
- }
1981
- });
1982
- } catch (err) {
1983
- lifecycleWarnings.push(
1984
- `Lifecycle transition to Review failed: ${stripLifecycleIssues(err instanceof Error ? err.message : String(err))}`
1985
- );
1986
- }
1987
- if (transitionResult) {
1988
- const hasCriteria = (transitionResult.task.successCriteria?.length ?? 0) > 0 || transitionResult.task.atomic === true;
1989
- if (hasCriteria) {
1990
- try {
1991
- const verResult = await verifyTaskCompletion2(projectRoot, board.id, input.taskId);
1992
- if (verResult.report) {
1993
- recordKanbanVerificationEvidence(ctx, verResult.report);
1994
- }
1995
- await updateTask2(projectRoot, board.id, input.taskId, {
1996
- verificationReport: verResult.report,
1997
- successCriteria: verResult.task.successCriteria
1998
- });
1999
- const verdict = verResult.report.verdict;
2000
- if (verdict === "passed" && !resolveAutoAccept(board)) {
2001
- lifecycleWarnings.push(
2002
- "Verification passed, but this board does not auto-accept. The card is in Review awaiting an explicit transition_task to done."
2003
- );
2004
- } else if (verdict === "passed") {
2005
- try {
2006
- const doneResult = await transitionTask(projectRoot, board.id, input.taskId, {
2007
- to: "done",
2008
- actor,
2009
- action: "Automated acceptance after verification",
2010
- comment: "Auto-accepted: verification passed.",
2011
- attachment: {
2012
- url: `kanban://task/${input.taskId}/verification`,
2013
- title: "Auto-verification result",
2014
- type: "file"
2015
- }
2016
- });
2017
- transitionResult = doneResult;
2018
- } catch (acceptErr) {
2019
- lifecycleWarnings.push(
2020
- `Auto-accept to Done deferred: ${acceptErr instanceof Error ? acceptErr.message : String(acceptErr)}`
2021
- );
2022
- }
2023
- } else {
2024
- lifecycleWarnings.push(
2025
- `Verification verdict: ${verdict} \u2014 card left in Review for manual acceptance.`
2026
- );
2027
- }
2028
- } catch (verifyErr) {
2029
- lifecycleWarnings.push(
2030
- `Auto-verification error: ${verifyErr instanceof Error ? verifyErr.message : String(verifyErr)}`
2031
- );
2032
- }
2033
- } else {
2034
- lifecycleWarnings.push(
2035
- "No automatic success criteria \u2014 card left in Review for manual verification."
2036
- );
2037
- }
2038
- }
2039
- }
2040
- const responseBoard = transitionResult?.board ?? board;
2041
- const responseTask = transitionResult?.task ?? managedTask;
2042
- const msgParts = ["Assignment updated."];
2043
- if (transitionResult) {
2044
- msgParts.push(`Card advanced to ${transitionResult.transition.to}.`);
2045
- }
2046
- for (const w of lifecycleWarnings) msgParts.push(`Warning: ${w}`);
2047
- await syncContextTask(ctx, responseTask);
2048
- return okTask(responseBoard, responseTask, msgParts.join(" "));
2049
- }
2050
- return okBoard(board, "Assignment updated.");
2051
- }
2052
- case "heartbeat_assignment": {
2053
- if (!input.boardId || !input.taskId) {
2054
- return fail("heartbeat_assignment requires boardId and taskId.");
2055
- }
2056
- const board = await heartbeatTaskAssignment(projectRoot, input.boardId, input.taskId, {
2057
- ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
2058
- ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
2059
- ...input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
2060
- });
2061
- return board ? okBoard(board, "Assignment heartbeat updated.") : fail("Task assignment not found.");
2062
- }
2063
- case "recover_stale": {
2064
- if (!input.boardId) return fail("recover_stale requires boardId.");
2065
- const policyFields = [
2066
- input.recoveryPolicyFailOnCostCeiling !== void 0,
2067
- input.recoveryPolicyReleaseOnFailureKinds !== void 0,
2068
- input.recoveryPolicyReleaseOnHeartbeatDue !== void 0,
2069
- input.recoveryPolicyRetryPolicyOverride !== void 0
2070
- ].some(Boolean);
2071
- const result = await recoverStaleTaskAssignments(projectRoot, input.boardId, {
2072
- ...input.recoveryMode !== void 0 ? { mode: input.recoveryMode } : {},
2073
- ...input.recoveryNow !== void 0 ? { now: input.recoveryNow } : {},
2074
- ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
2075
- ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {},
2076
- ...policyFields ? {
2077
- policy: {
2078
- ...input.recoveryPolicyFailOnCostCeiling !== void 0 ? { failWhenCostCeilingSet: input.recoveryPolicyFailOnCostCeiling } : {},
2079
- ...input.recoveryPolicyReleaseOnFailureKinds !== void 0 ? {
2080
- releaseOnFailureKinds: input.recoveryPolicyReleaseOnFailureKinds
2081
- } : {},
2082
- ...input.recoveryPolicyReleaseOnHeartbeatDue !== void 0 ? {
2083
- releaseOnHeartbeatDue: input.recoveryPolicyReleaseOnHeartbeatDue
2084
- } : {},
2085
- ...input.recoveryPolicyRetryPolicyOverride !== void 0 ? {
2086
- retryPolicyOverride: input.recoveryPolicyRetryPolicyOverride
2087
- } : {}
2088
- }
2089
- } : {}
2090
- });
2091
- return result ? {
2092
- ok: true,
2093
- message: `Recovered ${result.tasks.length} stale assignment(s).`,
2094
- board: result.board,
2095
- recoveredTasks: result.tasks
2096
- } : { ok: true, message: "No stale assignment matched.", recoveredTasks: [] };
2097
- }
2098
- default:
2099
- return void 0;
2100
- }
2101
- }
2102
-
2103
- // src/kanban-presence.ts
2104
- import { touchKanbanPresence as touchKanbanPresence2 } from "@wrongstack/kanban";
2105
- function createKanbanPresenceWrapper(projectRoot, input, ctx) {
2106
- return async (result) => {
2107
- const boardId = result.board?.id ?? input.boardId;
2108
- if (!result.ok || !boardId || !ctx.session?.id || !ctx.agentId) return result;
2109
- try {
2110
- const board = await touchKanbanPresence2(projectRoot, boardId, {
2111
- sessionId: ctx.session.id,
2112
- agentId: ctx.agentId,
2113
- agentName: ctx.agentName,
2114
- taskId: input.taskId ?? result.task?.id,
2115
- runTaskId: input.runTaskId
2116
- });
2117
- return board ? { ...result, board } : result;
2118
- } catch {
2119
- return result;
2120
- }
2121
- };
2122
- }
2123
-
2124
- // src/kanban-serializer.ts
2125
- var KANBAN_BOARD_TRANSCRIPT_BYTE_CAP = 16384;
2126
- var KANBAN_FULL_BOARD_ACTIONS = /* @__PURE__ */ new Set([
2127
- "get_board",
2128
- "export_markdown",
2129
- "export_task_graph"
2130
- ]);
2131
- function serializeKanbanOutput(output, input) {
2132
- const action = input && typeof input === "object" ? input.action : void 0;
2133
- const board = output.board;
2134
- if (board) {
2135
- const keepFull = typeof action === "string" && KANBAN_FULL_BOARD_ACTIONS.has(action);
2136
- let boardBytes = 0;
2137
- if (!keepFull) {
2138
- try {
2139
- boardBytes = Buffer.byteLength(JSON.stringify(board), "utf8");
2140
- } catch {
2141
- boardBytes = 0;
2142
- }
2143
- }
2144
- if (!keepFull && boardBytes > KANBAN_BOARD_TRANSCRIPT_BYTE_CAP) {
2145
- const columns = {};
2146
- for (const column of board.columns) {
2147
- columns[column.title || column.id] = board.tasks.filter(
2148
- (task) => task.columnId === column.id
2149
- ).length;
2150
- }
2151
- const compact = {
2152
- ...output,
2153
- board: {
2154
- id: board.id,
2155
- title: board.title,
2156
- columns,
2157
- totalTasks: board.tasks.length,
2158
- note: `Full board (${boardBytes} bytes) omitted from the transcript; use get_board to load it.`
2159
- }
2160
- };
2161
- return JSON.stringify(compact, null, 2);
2162
- }
2163
- }
2164
- return JSON.stringify(output, null, 2);
2165
- }
2166
-
2167
- // src/kanban-tool-schema.ts
2168
- var KANBAN_TOOL_DESCRIPTION = "Durable project task boards: create and move cards, record checks, notes, links and assignments. The board is a record of the work, not a permit for it \u2014 nothing here gates other tools. Managed boards additionally enforce ordered Backlog \u2192 Todo \u2192 Running \u2192 Review \u2192 Done transitions; release_managed_lifecycle turns that off.";
2169
- var KANBAN_TOOL_USAGE_HINT = 'Track substantial or multi-step work so it survives the session; a trivial edit or a question needs no card. Work stays on ONE board: call list_boards first and add_task to the board this project already uses. create_board is for a genuinely separate line of work, not for each new piece of it \u2014 a second board splits the same effort in two, and a board holding a single card is the usual sign. Common flow: list_boards or search_tasks to orient, add_task to record work, start_task when you begin, update_check with checkStatus "passed" to tick acceptance criteria (read their ids from get_task), then transition_task. On a managed board a refused transition names the field it wants \u2014 supply it and retry. When the acceptance criterion is something a machine can run, say so: set checkType ("command", "test", "file_exists", "file_matches", "git_diff", "metric") and put the command, pattern or path in checkNotes, then verify_completion executes it and the result is real evidence. Leave checkType off (or "manual") only for criteria that genuinely need a human eye \u2014 a manual check records your assertion, it does not test anything. Goal metrics pass when current >= target by default; when lower is better (error rate, cost ceiling, latency, open-bug count), pass metricDirection "at_most" with add_goal_metric / update_goal_metric so verification compares current <= target instead.';
2170
- var KANBAN_INPUT_SCHEMA = {
2171
- type: "object",
2172
- properties: {
2173
- action: {
2174
- type: "string",
2175
- enum: [
2176
- "list_boards",
2177
- "get_board",
2178
- "create_board",
2179
- "duplicate_board",
2180
- "update_board",
2181
- "adopt_managed_lifecycle",
2182
- "release_managed_lifecycle",
2183
- "delete_board",
2184
- "generate_board",
2185
- "export_markdown",
2186
- "export_task_graph",
2187
- "sync_task_graph",
2188
- "create_from_graph",
2189
- "import_session_tasks",
2190
- "search_tasks",
2191
- "ready_tasks",
2192
- "snapshot",
2193
- "workbench",
2194
- "add_task",
2195
- "split_task",
2196
- "merge_tasks",
2197
- "copy_task",
2198
- "transfer_task",
2199
- "get_task",
2200
- "start_task",
2201
- "update_task",
2202
- "transition_task",
2203
- "repair_managed_projection",
2204
- "move_task",
2205
- "delete_task",
2206
- "set_chain",
2207
- "get_chain",
2208
- "claim_task",
2209
- "release_task",
2210
- "assign_task",
2211
- "mark_assignment",
2212
- "heartbeat_assignment",
2213
- "recover_stale",
2214
- "events",
2215
- "queue_health",
2216
- "add_dependency",
2217
- "add_goal_metric",
2218
- "update_goal_metric",
2219
- "add_check",
2220
- "update_check",
2221
- "remove_check",
2222
- "add_note",
2223
- "add_link",
2224
- "verify_completion",
2225
- "split_atomic",
2226
- "assess_atomicity",
2227
- "propose_decomposition",
2228
- "get_contract_graph",
2229
- "configure_contract_graph",
2230
- "upsert_contract_node",
2231
- "remove_contract_node",
2232
- "add_contract_edge",
2233
- "remove_contract_edge"
2234
- ]
2235
- },
2236
- boardId: { type: "string" },
2237
- taskId: { type: "string" },
2238
- taskIds: { type: "array", items: { type: "string" } },
2239
- chainId: { type: "string" },
2240
- fromNodeId: { type: "string" },
2241
- toNodeId: { type: "string" },
2242
- baseline: { oneOf: [{ type: "string" }, { type: "number" }] },
2243
- threshold: { oneOf: [{ type: "string" }, { type: "number" }] },
2244
- columnId: { type: "string" },
2245
- targetBoardId: { type: "string" },
2246
- targetColumnId: { type: "string" },
2247
- title: { type: "string" },
2248
- description: { type: "string" },
2249
- dueDate: { type: "string" },
2250
- tags: { type: "array", items: { type: "string" } },
2251
- labels: { type: "array", items: { type: "string" } },
2252
- priority: { type: "string", enum: ["critical", "high", "medium", "low"] },
2253
- taskType: {
2254
- type: "string",
2255
- enum: ["feature", "bugfix", "refactor", "docs", "test", "chore"]
2256
- },
2257
- status: {
2258
- type: "string",
2259
- enum: [
2260
- "pending",
2261
- "ready",
2262
- "in_progress",
2263
- "blocked",
2264
- "review",
2265
- "completed",
2266
- "failed",
2267
- "archived"
2268
- ]
2269
- },
2270
- order: { type: "number" },
2271
- query: { type: "string" },
2272
- limit: { type: "number" },
2273
- agentId: { type: "string" },
2274
- name: { type: "string" },
2275
- role: { type: "string" },
2276
- provider: { type: "string" },
2277
- model: { type: "string" },
2278
- fallbackProfile: { type: "string" },
2279
- fallbackModels: { type: "array", items: { type: "string" } },
2280
- tools: { type: "array", items: { type: "string" } },
2281
- allowedCapabilities: { type: "array", items: { type: "string" } },
2282
- leaseId: { type: "string" },
2283
- claimedAt: { type: "string" },
2284
- heartbeatAt: { type: "string" },
2285
- leaseExpiresAt: { type: "string" },
2286
- attempt: { type: "number" },
2287
- maxAttempts: { type: "number" },
2288
- subagentId: { type: "string" },
2289
- runTaskId: { type: "string" },
2290
- lastResult: { type: "string" },
2291
- error: { type: "string" },
2292
- expectedLeaseId: { type: "string" },
2293
- assignmentStatus: {
2294
- type: "string",
2295
- enum: ["assigned", "queued", "running", "completed", "failed", "cancelled"]
2296
- },
2297
- lifecycleStage: {
2298
- type: "string",
2299
- enum: ["backlog", "todo", "running", "review", "done"]
2300
- },
2301
- transitionAction: { type: "string" },
2302
- transitionComment: { type: "string" },
2303
- tickChecks: {
2304
- type: "array",
2305
- items: {
2306
- type: "object",
2307
- properties: {
2308
- checkId: { type: "string" },
2309
- checkStatus: { type: "string", enum: ["passed", "failed", "skipped"] }
2310
- },
2311
- required: ["checkId", "checkStatus"]
2312
- },
2313
- description: "`transition_task` (to=done only): flip one or more manual criteria to `passed` before the gate fires. Read ids from kanban get_task. Non-manual criteria are refused."
2314
- },
2315
- attachmentUrl: { type: "string" },
2316
- attachmentTitle: { type: "string" },
2317
- attachmentType: {
2318
- type: "string",
2319
- enum: ["issue", "pr", "doc", "commit", "design", "file", "url", "other"]
2320
- },
2321
- releaseStatus: { type: "string", enum: ["pending", "ready", "blocked"] },
2322
- releaseReason: { type: "string" },
2323
- clearAssignee: { type: "boolean" },
2324
- recoveryMode: { type: "string", enum: ["auto", "release", "retry", "fail"] },
2325
- recoveryNow: { type: "string" },
2326
- recoveryPolicyFailOnCostCeiling: { type: "boolean" },
2327
- recoveryPolicyReleaseOnFailureKinds: { type: "array", items: { type: "string" } },
2328
- recoveryPolicyReleaseOnHeartbeatDue: { type: "boolean" },
2329
- recoveryPolicyRetryPolicyOverride: {
2330
- type: "string",
2331
- enum: ["off", "incremental", "exponential"]
2332
- },
2333
- assignee: { type: "string" },
2334
- costCeilingUsd: { type: "number" },
2335
- retryPolicy: { type: "string", enum: ["off", "incremental", "exponential"] },
2336
- lastFailureKind: { type: "string" },
2337
- dependsOn: {
2338
- type: "array",
2339
- items: { type: "string" },
2340
- description: "Task ids this card waits on. On update_task an explicit empty array clears them \u2014 use it when a dependency was recorded in error rather than completing work nobody wants."
2341
- },
2342
- atomic: {
2343
- type: "boolean",
2344
- description: "Composite parent (true) or executable leaf (false). Set false to make a stranded parent a leaf again after its children were dropped."
2345
- },
2346
- childTaskIds: {
2347
- type: "array",
2348
- items: { type: "string" },
2349
- description: "Children of a composite parent. On update_task an explicit empty array detaches them all."
2350
- },
2351
- estimatedHours: { type: "number" },
2352
- actualHours: { type: "number" },
2353
- taskGraph: { type: "object" },
2354
- graphId: { type: "string" },
2355
- specId: { type: "string" },
2356
- specRequirementId: { type: "string" },
2357
- sourceSystem: { type: "string" },
2358
- phaseId: { type: "string" },
2359
- preserveOriginTaskIds: { type: "boolean" },
2360
- includeArchived: { type: "boolean" },
2361
- archiveMissingTasks: { type: "boolean" },
2362
- preserveManualDependencies: { type: "boolean" },
2363
- dependencyTaskId: { type: "string" },
2364
- enforceDependencies: { type: "boolean" },
2365
- childTitles: { type: "array", items: { type: "string" } },
2366
- inheritAssignment: { type: "boolean" },
2367
- inheritLabels: { type: "boolean" },
2368
- inheritSuccessCriteria: { type: "boolean" },
2369
- inheritGoalMetrics: { type: "boolean" },
2370
- inheritDependencies: { type: "boolean" },
2371
- chainChildren: { type: "boolean" },
2372
- rewireDependents: { type: "boolean" },
2373
- closeSourceTasks: { type: "boolean" },
2374
- metricId: { type: "string" },
2375
- metricName: { type: "string" },
2376
- metricTarget: { oneOf: [{ type: "string" }, { type: "number" }] },
2377
- metricCurrent: { oneOf: [{ type: "string" }, { type: "number" }] },
2378
- metricDirection: { type: "string", enum: ["at_least", "at_most"] },
2379
- metricUnit: { type: "string" },
2380
- metricStatus: { type: "string", enum: ["pending", "met", "missed", "waived"] },
2381
- metricNotes: { type: "string" },
2382
- checkId: { type: "string" },
2383
- checkDescription: { type: "string" },
2384
- checkStatus: { type: "string", enum: ["pending", "passed", "failed", "skipped"] },
2385
- checkType: {
2386
- type: "string",
2387
- // Only types a verifier can actually execute. `manual` is the default and
2388
- // means a human or agent asserts the status by hand. The rest are run by
2389
- // `verify_completion` against the default deterministic registry. Types
2390
- // with no plugin in that registry (`auto`, `review`, `agent`, `council`)
2391
- // are deliberately omitted: offering them would produce criteria that
2392
- // silently report `skipped — no verifier plugin registered`.
2393
- enum: ["manual", "command", "test", "file_exists", "file_matches", "git_diff", "metric"],
2394
- description: 'How this acceptance criterion is verified. Default "manual" (status set by hand). Any other value makes verify_completion execute it, so the criterion becomes real evidence rather than a self-assertion. Pair with checkNotes.'
2395
- },
2396
- checkNotes: {
2397
- type: "string",
2398
- description: 'The executable body for a non-manual checkType, read in preference to checkDescription. command/test: the shell command or test pattern. file_exists: the path. file_matches: JSON {"file","pattern","flags"}. git_diff: JSON {"expectedFiles","minChanges","maxChanges"}.'
2399
- },
2400
- // ── Contract map ───────────────────────────────────────────────────
2401
- // The card contract: what this work targets, what it must not break, what
2402
- // it risks, and what verifies it. Advisory by default — the readiness gate
2403
- // deliberately does not require map structure, so a map is an operator
2404
- // review aid, not work the model must complete before implementing.
2405
- contractEnforcement: {
2406
- type: "string",
2407
- enum: ["off", "advisory", "strict"],
2408
- description: "Board-level contract map enforcement. Default when first configured: advisory."
2409
- },
2410
- contractNodeId: { type: "string" },
2411
- contractNodeKind: {
2412
- type: "string",
2413
- enum: ["objective", "guardrail", "risk", "component", "artifact", "verification"],
2414
- description: "objective = what this card is for; guardrail = what must keep working; risk = what could go wrong; component/artifact = what it touches; verification = what settles it."
2415
- },
2416
- contractNodeTitle: { type: "string" },
2417
- contractNodeDescription: { type: "string" },
2418
- contractNodeState: {
2419
- type: "string",
2420
- enum: ["unknown", "active", "satisfied", "violated", "waived", "resolved"]
2421
- },
2422
- contractNodeEnforcement: {
2423
- type: "string",
2424
- enum: ["blocking", "advisory", "informational"]
2425
- },
2426
- /** Bind a node to an acceptance criterion or goal metric already on the task. */
2427
- contractCheckId: { type: "string" },
2428
- contractMetricId: { type: "string" },
2429
- contractWaiverReason: {
2430
- type: "string",
2431
- description: 'Required, with an actor, when contractNodeState is "waived".'
2432
- },
2433
- contractEdgeId: { type: "string" },
2434
- contractEdgeFrom: {
2435
- type: "string",
2436
- description: 'A contract node id, or a task id (bare or "task:<id>") for the card endpoint.'
2437
- },
2438
- contractEdgeTo: { type: "string" },
2439
- contractEdgeType: {
2440
- type: "string",
2441
- enum: [
2442
- "targets",
2443
- "affects",
2444
- "must_preserve",
2445
- "exposes",
2446
- "verified_by",
2447
- "conflicts_with",
2448
- "derived_from",
2449
- "relates_to"
2450
- ]
2451
- },
2452
- contractEdgeRationale: { type: "string" },
2453
- note: { type: "string" },
2454
- author: { type: "string" },
2455
- url: { type: "string" },
2456
- linkTitle: { type: "string" },
2457
- linkType: {
2458
- type: "string",
2459
- enum: ["issue", "pr", "doc", "commit", "design", "file", "url", "other"]
2460
- },
2461
- context: { type: "string" },
2462
- columns: { type: "array", items: { type: "string" } },
2463
- generatedBy: { type: "string" },
2464
- includeTasks: { type: "boolean" },
2465
- includeCompletedTasks: { type: "boolean" },
2466
- preserveAssignment: { type: "boolean" },
2467
- preserveDependencies: { type: "boolean" },
2468
- moveTasksToColumnId: { type: "string" },
2469
- atomicityMode: { type: "string", enum: ["off", "assess", "enforce"] },
2470
- atomicityDecomposition: { type: "string", enum: ["auto", "propose"] },
2471
- gateEnforcement: {
2472
- type: "string",
2473
- // WS-023: `'off'` is deliberately absent. The agent whose work this gate
2474
- // checks must not be able to switch it off; it may only tighten. Turning
2475
- // a gate off stays a human decision, made through board config.
2476
- enum: ["strict", "soft"]
2477
- },
2478
- subtasks: {
2479
- type: "array",
2480
- minItems: 2,
2481
- items: {
2482
- type: "object",
2483
- properties: {
2484
- title: { type: "string" },
2485
- description: { type: "string" },
2486
- successCriteria: { type: "array", items: { type: "string" } },
2487
- dependsOnIndex: { type: "array", items: { type: "number" } }
2488
- },
2489
- required: ["title"]
2490
- }
2491
- }
2492
- },
2493
- required: ["action"]
2494
- };
2495
-
2496
- // src/kanban.ts
2497
- var kanbanTool = {
2498
- name: "kanban",
2499
- category: "Project",
2500
- description: KANBAN_TOOL_DESCRIPTION,
2501
- usageHint: KANBAN_TOOL_USAGE_HINT,
2502
- permission: "confirm",
2503
- subjectKey: "action",
2504
- mutating: true,
2505
- capabilities: ["fs.write"],
2506
- icon: "task",
2507
- timeoutMs: 3e4,
2508
- inputSchema: KANBAN_INPUT_SCHEMA,
2509
- async execute(input, ctx) {
2510
- const projectRoot = ctx.projectRoot;
2511
- if (!projectRoot) return fail("No project root is available.");
2512
- const withPresence = createKanbanPresenceWrapper(projectRoot, input, ctx);
2513
- try {
2514
- const result = await (async () => {
2515
- const decompositionResult = await handleKanbanDecompositionAction(projectRoot, input, ctx);
2516
- if (decompositionResult !== void 0) return decompositionResult;
2517
- const boardResult = await handleKanbanBoardAction(projectRoot, input, ctx);
2518
- if (boardResult !== void 0) return boardResult;
2519
- const lifecycleResult = await handleKanbanLifecycleAction(projectRoot, input, ctx);
2520
- if (lifecycleResult !== void 0) return lifecycleResult;
2521
- const contractResult = await handleKanbanContractAction(
2522
- projectRoot,
2523
- input,
2524
- input.author ?? input.agentId
2525
- );
2526
- if (contractResult !== void 0) return contractResult;
2527
- const detailResult = await handleKanbanDetailAction(projectRoot, input);
2528
- if (detailResult !== void 0) return detailResult;
2529
- return fail(`Unknown kanban action: ${input.action}`);
2530
- })();
2531
- return withPresence(result);
2532
- } catch (err) {
2533
- return fail(stripLifecycleIssues2(err instanceof Error ? err.message : String(err)));
2534
- }
2535
- },
2536
- serialize(output, input) {
2537
- return serializeKanbanOutput(output, input);
2538
- }
2539
- };
2540
-
2541
- // src/todo.ts
2542
- function normalizedTitle(value) {
2543
- return value.trim().toLocaleLowerCase().replace(/\s+/g, " ");
2544
- }
2545
- function activeBoardId(items, ctx) {
2546
- const metaKanban = ctx.meta?.["kanban"];
2547
- const metaBoardId = metaKanban && typeof metaKanban === "object" ? metaKanban["boardId"] : void 0;
2548
- return ctx.currentKanbanBoardId ?? (typeof metaBoardId === "string" ? metaBoardId : void 0) ?? items.find((item) => item.kanbanBoardId)?.kanbanBoardId ?? "";
2549
- }
2550
- function bindTodosToBoard(items, previous, board) {
2551
- const previousById = new Map(previous.map((item) => [item.id, item]));
2552
- const available = board.tasks.filter(
2553
- (task) => task.status !== "archived" && task.mergedIntoTaskId === void 0 && (!task.childTaskIds || task.childTaskIds.length === 0)
2554
- ).sort(
2555
- (left, right) => left.createdAt.localeCompare(right.createdAt) || left.order - right.order
2556
- );
2557
- const used = /* @__PURE__ */ new Set();
2558
- return items.map((item) => {
2559
- const previousItem = previousById.get(item.id);
2560
- const requestedTaskId = item.kanbanBoardId === board.id ? item.kanbanTaskId : previousItem?.kanbanBoardId === board.id ? previousItem.kanbanTaskId : void 0;
2561
- const title = normalizedTitle(item.content);
2562
- const candidates = [
2563
- requestedTaskId ? board.tasks.find((task2) => task2.id === requestedTaskId) : void 0,
2564
- board.tasks.find((task2) => task2.id === item.id),
2565
- board.tasks.find((task2) => task2.origin?.taskId === item.id),
2566
- available.find((task2) => !used.has(task2.id) && normalizedTitle(task2.title) === title)
2567
- ];
2568
- const task = candidates.find((candidate) => candidate && !used.has(candidate.id));
2569
- if (!task) {
2570
- const { blockedBy: _discarded, ...rest } = item;
2571
- return { ...rest };
2572
- }
2573
- used.add(task.id);
2574
- const blockedBy = blockingTitles(board, task);
2575
- return {
2576
- ...item,
2577
- kanbanBoardId: board.id,
2578
- kanbanTaskId: task.id,
2579
- ...blockedBy.length ? { blockedBy } : { blockedBy: void 0 }
2580
- };
2581
- });
2582
- }
2583
- function demoteBlockedInProgress(items, warnings) {
2584
- return items.map((item) => {
2585
- if (item.status !== "in_progress" || !item.blockedBy?.length) return item;
2586
- warnings.push(
2587
- `"${item.content}" cannot start yet \u2014 it waits on: ${item.blockedBy.join("; ")}. Kept as pending; complete the blocking work first.`
2588
- );
2589
- return { ...item, status: "pending" };
2590
- });
2591
- }
2592
- async function createMissingManagedCards(items, board, ctx, warnings) {
2593
- const created = /* @__PURE__ */ new Map();
2594
- for (const item of items) {
2595
- if (item.kanbanBoardId === board.id && item.kanbanTaskId) continue;
2596
- try {
2597
- const result = await addTask3(ctx.projectRoot, board.id, {
2598
- title: item.content,
2599
- description: item.activeForm?.trim() || `Added from the session todo list: ${item.content}`
2600
- });
2601
- if (!result) {
2602
- warnings.push(`Could not open a Kanban card for "${item.content}": board not found.`);
2603
- continue;
2604
- }
2605
- created.set(item.id, result.task.id);
2606
- } catch (error) {
2607
- warnings.push(
2608
- `Could not open a Kanban card for "${item.content}": ${error instanceof Error ? error.message : String(error)}`
2609
- );
2610
- }
2611
- }
2612
- return created;
2613
- }
2614
- async function synchronizeManagedKanban(items, board, ctx, signal) {
2615
- let synced = 0;
2616
- const warnings = [];
2617
- const actor = ctx.agentId?.trim() || ctx.agentName?.trim() || "kanban-agent";
2618
- const execute = async (input) => {
2619
- const result = await kanbanTool.execute(input, ctx, { signal });
2620
- if (!result.ok) warnings.push(result.message);
2621
- else {
2622
- synced++;
2623
- if (result.message.includes("Warning:")) warnings.push(result.message);
2624
- }
2625
- return result;
2626
- };
2627
- for (const item of items) {
2628
- if (item.status !== "pending" || item.kanbanBoardId !== board.id || !item.kanbanTaskId) {
2629
- continue;
2630
- }
2631
- const task = board.tasks.find((candidate) => candidate.id === item.kanbanTaskId);
2632
- if (task?.lifecycle?.currentStage !== "running") continue;
2633
- const released = await execute({
2634
- action: "mark_assignment",
2635
- boardId: board.id,
2636
- taskId: task.id,
2637
- assignmentStatus: "assigned",
2638
- agentId: actor,
2639
- lastResult: `Todo returned to queue: ${item.content}`
2640
- });
2641
- if (!released.ok) continue;
2642
- await execute({
2643
- action: "transition_task",
2644
- boardId: board.id,
2645
- taskId: task.id,
2646
- lifecycleStage: "todo",
2647
- author: actor,
2648
- transitionComment: `Todo returned to queue: ${item.content}`
2649
- });
2650
- }
2651
- for (const item of items) {
2652
- if (item.status === "completed" || item.kanbanBoardId !== board.id || !item.kanbanTaskId) {
2653
- continue;
2654
- }
2655
- const task = board.tasks.find((candidate) => candidate.id === item.kanbanTaskId);
2656
- if (task?.status !== "completed") continue;
2657
- warnings.push(
2658
- `"${item.content}" is already Done on the Kanban board and a completed card cannot be reopened; the row stays completed. Create a follow-up card for any remaining work.`
2659
- );
2660
- }
2661
- for (const item of items) {
2662
- if (item.status !== "completed" || item.kanbanBoardId !== board.id || !item.kanbanTaskId) {
2663
- continue;
2664
- }
2665
- const task = board.tasks.find((candidate) => candidate.id === item.kanbanTaskId);
2666
- if (!task || task.status === "completed") continue;
2667
- const stage = task.lifecycle?.currentStage;
2668
- if (stage === "backlog" || stage === "todo") {
2669
- const started = await execute({
2670
- action: "start_task",
2671
- boardId: board.id,
2672
- taskId: task.id,
2673
- author: actor,
2674
- agentId: actor,
2675
- transitionComment: `Auto-started for completion: ${item.content}`
2676
- });
2677
- if (!started.ok) {
2678
- continue;
2679
- }
2680
- }
2681
- await execute({
2682
- action: "mark_assignment",
2683
- boardId: board.id,
2684
- taskId: task.id,
2685
- assignmentStatus: "completed",
2686
- agentId: actor,
2687
- lastResult: `Todo completed: ${item.content}`
2688
- });
2689
- }
2690
- const attemptedParents = /* @__PURE__ */ new Set();
2691
- let afterCompletions = await getBoard5(ctx.projectRoot, board.id);
2692
- while (afterCompletions) {
2693
- const parent = afterCompletions.tasks.find(
2694
- (task) => task.atomic === true && task.status !== "completed" && Boolean(task.childTaskIds?.length) && !attemptedParents.has(task.id) && task.childTaskIds?.every(
2695
- (childId) => afterCompletions?.tasks.find((candidate) => candidate.id === childId)?.status === "completed"
2696
- )
2697
- );
2698
- if (!parent) break;
2699
- attemptedParents.add(parent.id);
2700
- const started = await execute({
2701
- action: "start_task",
2702
- boardId: board.id,
2703
- taskId: parent.id,
2704
- author: actor,
2705
- agentId: actor,
2706
- transitionComment: "All child tasks completed; validating composite parent."
2707
- });
2708
- if (started.ok) {
2709
- await execute({
2710
- action: "mark_assignment",
2711
- boardId: board.id,
2712
- taskId: parent.id,
2713
- assignmentStatus: "completed",
2714
- agentId: actor,
2715
- lastResult: "All child tasks completed; composite result ready for verification."
2716
- });
2717
- }
2718
- afterCompletions = await getBoard5(ctx.projectRoot, board.id);
2719
- }
2720
- const completionPending = items.some(
2721
- (item) => item.status === "completed" && item.kanbanBoardId === board.id && Boolean(item.kanbanTaskId) && afterCompletions?.tasks.find((task) => task.id === item.kanbanTaskId)?.status !== "completed"
2722
- );
2723
- const active = items.find(
2724
- (item) => item.status === "in_progress" && item.kanbanBoardId === board.id && Boolean(item.kanbanTaskId)
2725
- );
2726
- const activeStage = active?.kanbanTaskId ? afterCompletions?.tasks.find((task) => task.id === active.kanbanTaskId)?.lifecycle?.currentStage : void 0;
2727
- if (active?.kanbanTaskId) {
2728
- if (activeStage === "review" || activeStage === "done") {
2729
- warnings.push(
2730
- `"${active.content}" is in ${activeStage === "review" ? "Review" : "Done"} awaiting acceptance; not re-activating it from the todo list. ` + (activeStage === "review" ? "Call kanban start_task explicitly to reopen it as a repair." : "Done is terminal; reopen only by creating a follow-up card.")
2731
- );
2732
- } else {
2733
- await execute({
2734
- action: "start_task",
2735
- boardId: board.id,
2736
- taskId: active.kanbanTaskId,
2737
- author: actor,
2738
- agentId: actor,
2739
- transitionComment: `Todo activated: ${active.content}`
2740
- });
2741
- }
2742
- }
2743
- if (active?.kanbanTaskId && activeStage === "review") {
2744
- } else if (active?.kanbanTaskId && completionPending) {
2745
- warnings.push(
2746
- "A completed todo is still awaiting acceptance; the next independent Kanban task was started."
2747
- );
2748
- } else if (!active && ctx.currentKanbanBoardId === board.id) {
2749
- ctx.setCurrentKanbanTask(void 0, board.id);
2750
- }
2751
- return { synced, warnings };
2752
- }
2753
- var todoTool = {
2754
- name: "todo",
2755
- category: "Session",
2756
- description: "Manage the compact active-work list. With a managed Kanban binding, every row resolves to a real card and status changes advance that card; without Kanban it remains session-only state. Each call replaces ordering and supplied fields, but unfinished omitted rows are retained until completed.",
2757
- usageHint: "BEST PRACTICE for complex tasks:\n- At the beginning of a non-trivial task, create a clear todo list with specific, actionable items.\n- Only **one** item should be `in_progress` at any time.\n- Update the list frequently as work progresses (mark items done, add new ones, change status).\n- **Re-order items** to reflect current priorities. Omission is not cancellation: unfinished rows are retained until completed.\n- When all items are completed the board auto-clears \u2014 you do NOT need to send an empty list.\n- The system and user can see this list, so keep it honest and up-to-date.\nThis tool is extremely valuable for maintaining focus and giving the user visibility into your plan.",
2758
- permission: "confirm",
2759
- mutating: true,
2760
- timeoutMs: 3e4,
2761
- capabilities: ["session.todo", "fs.write"],
2762
- subjectKey: "todos",
2763
- icon: "todo",
2764
- inputSchema: {
2765
- type: "object",
2766
- properties: {
2767
- todos: {
2768
- type: "array",
2769
- items: {
2770
- type: "object",
2771
- properties: {
2772
- id: {
2773
- type: "string",
2774
- description: 'Unique identifier for the todo item (e.g. "1", "auth-flow").'
2775
- },
2776
- content: {
2777
- type: "string",
2778
- description: "Clear, actionable description of the task."
2779
- },
2780
- status: {
2781
- type: "string",
2782
- enum: ["pending", "in_progress", "completed"],
2783
- description: 'Current status. Only one item should be "in_progress" at a time.'
2784
- },
2785
- activeForm: {
2786
- type: "string",
2787
- description: 'Optional present-tense form shown while the task is active (e.g. "Fixing auth bug").'
2788
- },
2789
- kanbanBoardId: {
2790
- type: "string",
2791
- description: "Kanban board that owns this UI row when Kanban is active."
2792
- },
2793
- kanbanTaskId: {
2794
- type: "string",
2795
- description: "Real Kanban task represented by this UI row."
2796
- }
2797
- },
2798
- required: ["id", "content", "status"]
2799
- },
2800
- description: "The desired todo list. Supplied rows are replaced/reordered; unfinished omitted rows are retained."
2801
- }
2802
- },
2803
- required: ["todos"]
2804
- },
2805
- async execute(input, ctx, call) {
2806
- if (!Array.isArray(input?.todos)) {
2807
- throw new Error("todo: todos must be an array");
2808
- }
2809
- const items = input.todos.filter((t) => Boolean(t?.id && t.content));
2810
- const todoIdentity = (item) => item.kanbanBoardId && item.kanbanTaskId ? `kanban:${item.kanbanBoardId}:${item.kanbanTaskId}` : item.promotedFromTask ? `task:${item.promotedFromTask}` : item.promotedFromPlan ? `plan:${item.promotedFromPlan}` : `todo:${item.id}`;
2811
- const requestedIdentities = new Set(items.map(todoIdentity));
2812
- for (const previous of ctx.todos ?? []) {
2813
- const identity = todoIdentity(previous);
2814
- if (previous.status === "completed" || requestedIdentities.has(identity)) {
2815
- continue;
2816
- }
2817
- items.push({ ...previous });
2818
- requestedIdentities.add(identity);
2819
- }
2820
- const inProgress = items.filter((t) => t.status === "in_progress");
2821
- if (inProgress.length > 1) {
2822
- let seenInProgress = false;
2823
- for (const item of items) {
2824
- if (item.status === "in_progress") {
2825
- if (seenInProgress) item.status = "pending";
2826
- seenInProgress = true;
2827
- }
2828
- }
2829
- }
2830
- const boardId = activeBoardId(items, ctx);
2831
- let board = boardId ? await getBoard5(ctx.projectRoot, boardId) : null;
2832
- const managed = board?.lifecycle?.mode === "managed";
2833
- let boundItems = managed && board ? bindTodosToBoard(items, ctx.todos ?? [], board) : items;
2834
- const creationWarnings = [];
2835
- if (managed && board) {
2836
- const managedBoardId = board.id;
2837
- const created = await createMissingManagedCards(boundItems, board, ctx, creationWarnings);
2838
- if (created.size > 0) {
2839
- boundItems = boundItems.map((item) => {
2840
- const taskId = created.get(item.id);
2841
- return taskId ? { ...item, kanbanBoardId: managedBoardId, kanbanTaskId: taskId } : item;
2842
- });
2843
- board = await getBoard5(ctx.projectRoot, managedBoardId) ?? board;
2844
- boundItems = bindTodosToBoard(boundItems, ctx.todos ?? [], board);
2845
- }
2846
- boundItems = demoteBlockedInProgress(boundItems, creationWarnings);
2847
- }
2848
- ctx.state.replaceTodos(boundItems);
2849
- const kanbanSync = managed && board ? await synchronizeManagedKanban(boundItems, board, ctx, call.signal) : { synced: 0, warnings: [] };
2850
- kanbanSync.warnings.unshift(...creationWarnings);
2851
- if (managed && board) {
2852
- const unresolved = boundItems.filter(
2853
- (item) => item.kanbanBoardId !== board.id || !item.kanbanTaskId
2854
- );
2855
- if (unresolved.length > 0) {
2856
- kanbanSync.warnings.push(
2857
- `${unresolved.length} Todo row(s) could not be bound to a Kanban task and were not applied. Preserve kanbanBoardId/kanbanTaskId when updating the projection.`
2858
- );
2859
- }
2860
- }
2861
- const mirrorFailure = takeSessionMirrorFailure(ctx.projectRoot, ctx.session?.id ?? "");
2862
- if (mirrorFailure) kanbanSync.warnings.push(mirrorFailure);
2863
- let projectedBoard = board;
2864
- if (managed && board) {
2865
- const refreshed = await getBoard5(ctx.projectRoot, board.id);
2866
- if (refreshed) {
2867
- projectedBoard = refreshed;
2868
- applyManagedKanbanBoardToTodos2(ctx, refreshed);
2869
- }
2870
- }
2871
- if (!managed) {
2872
- mirrorSessionTodosToKanban(ctx.projectRoot, items, ctx.session?.id ?? "session");
2873
- }
2874
- const completedPlanIds = /* @__PURE__ */ new Set();
2875
- const completedTaskIds = /* @__PURE__ */ new Set();
2876
- const pendingPlanIds = /* @__PURE__ */ new Set();
2877
- const pendingTaskIds = /* @__PURE__ */ new Set();
2878
- for (const item of items) {
2879
- if (item.promotedFromPlan) {
2880
- (item.status === "completed" ? completedPlanIds : pendingPlanIds).add(
2881
- item.promotedFromPlan
2882
- );
2883
- }
2884
- if (item.promotedFromTask) {
2885
- (item.status === "completed" ? completedTaskIds : pendingTaskIds).add(
2886
- item.promotedFromTask
2887
- );
2888
- }
2889
- }
2890
- for (const planId of completedPlanIds) {
2891
- if (pendingPlanIds.has(planId)) continue;
2892
- const meta = ctx.meta;
2893
- const planPath = meta["plan.path.resolved"] ?? meta["plan.path"];
2894
- if (typeof planPath !== "string" || !planPath) continue;
2895
- try {
2896
- const plan = await loadPlan2(planPath);
2897
- if (plan) {
2898
- const updated = setPlanItemStatus(plan, planId, "done");
2899
- await savePlan(planPath, updated);
2900
- }
2901
- } catch {
2902
- }
2903
- }
2904
- for (const taskId of completedTaskIds) {
2905
- if (pendingTaskIds.has(taskId)) continue;
2906
- const meta = ctx.meta;
2907
- const taskPath = meta["task.path.resolved"] ?? meta["task.path"];
2908
- if (typeof taskPath !== "string" || !taskPath) continue;
2909
- try {
2910
- const file = await loadTasks3(taskPath);
2911
- if (file) {
2912
- const task = file.tasks.find((t) => t.id === taskId);
2913
- if (task && task.status !== "completed") {
2914
- task.status = "completed";
2915
- task.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2916
- await saveTasks(taskPath, file);
2917
- }
2918
- }
2919
- } catch {
2920
- }
2921
- }
2922
- return {
2923
- count: items.length,
2924
- in_progress: (ctx.todos ?? boundItems).filter((t) => t.status === "in_progress").length,
2925
- ...kanbanSync.synced > 0 ? { kanban_synced: kanbanSync.synced } : {},
2926
- ...kanbanSync.warnings.length > 0 ? { kanban_warnings: kanbanSync.warnings } : {},
2927
- ...projectedBoard?.lifecycle?.mode === "managed" ? {
2928
- kanban_bindings: boundItems.flatMap((item) => {
2929
- if (item.kanbanBoardId !== projectedBoard.id || !item.kanbanTaskId) return [];
2930
- const task = projectedBoard.tasks.find(
2931
- (candidate) => candidate.id === item.kanbanTaskId
2932
- );
2933
- return task ? [
2934
- {
2935
- todoId: item.id,
2936
- boardId: projectedBoard.id,
2937
- taskId: task.id,
2938
- taskStatus: task.status
2939
- }
2940
- ] : [];
2941
- })
2942
- } : {}
2943
- };
2944
- }
2945
- };
2946
-
2947
- // src/plan.ts
2948
- var planTool = {
2949
- name: "plan",
2950
- category: "Session",
2951
- description: 'Manage a session-persistent strategic plan. The plan is written to disk and survives conversation resumptions within the same session, but is isolated to this session \u2014 other sessions have their own separate plans. Unlike todos (which are per-turn and lost on restart), a plan tracks high-level progress across multiple turns. Use this to outline big-picture work, then promote concrete items into the todo list when ready to execute. By default plans are isolated to this session; use `scope: "project"` to store the plan in a shared project-level file visible to all sessions.',
2952
- usageHint: 'RECOMMENDED FOR COMPLEX, MULTI-PHASE WORK:\n\n- Start by creating a high-level plan with `action: "add"` or using templates (`template_use`).\n- Use `action: "status"` with `open`, `in_progress`, or `done` for exact status changes.\n- Use `promote` to turn a plan item into actionable todos.\n- Use `taskify` to convert a plan item into a structured task (with type/priority/deps).\n- Unfinished plan items cannot be removed or cleared; complete them first.\n- Keep plans at the "why and what" level, and todos at the "how and next step" level.\n- Common templates: "new-feature", "bug-fix", "refactor", "release", "security-audit".\n\nThis tool is excellent for maintaining long-term direction across many turns within a session. Plans survive resume but are not shared across separate sessions.\nUse `scope: "project"` to use a shared project-level plan file.',
2953
- permission: "confirm",
2954
- // WS-046: gives permission decisions something to key on.
2955
- // The action performed; plan has no single file or path subject.
2956
- subjectKey: "action",
2957
- mutating: true,
2958
- capabilities: ["fs.write"],
2959
- icon: "plan",
2960
- timeoutMs: 3e4,
2961
- inputSchema: {
2962
- type: "object",
2963
- properties: {
2964
- action: {
2965
- type: "string",
2966
- enum: [
2967
- "show",
2968
- "add",
2969
- "status",
2970
- "start",
2971
- "done",
2972
- "remove",
2973
- "promote",
2974
- "template_use",
2975
- "clear",
2976
- "taskify"
2977
- ],
2978
- description: "The operation to perform on the plan board."
2979
- },
2980
- title: {
2981
- type: "string",
2982
- description: "Title of the plan item. Required for action=add."
2983
- },
2984
- details: {
2985
- type: "string",
2986
- description: "Additional details or description for a new plan item (action=add)."
2987
- },
2988
- target: {
2989
- type: "string",
2990
- description: "Identifier for the target plan item (id, 1-based index, or partial title). Required for most actions except add/show/clear."
2991
- },
2992
- status: {
2993
- type: "string",
2994
- enum: ["open", "in_progress", "done"],
2995
- description: "Exact plan item status for action=status."
2996
- },
2997
- subtasks: {
2998
- type: "array",
2999
- items: { type: "string" },
3000
- description: "List of subtask titles. Used with promote to break a plan item into multiple todos."
3001
- },
3002
- template: {
3003
- type: "string",
3004
- description: "Template identifier when using action=template_use. Common values: new-feature, bug-fix, refactor, release, security-audit."
3005
- },
3006
- scope: {
3007
- type: "string",
3008
- enum: ["session", "project"],
3009
- description: 'Storage scope: "session" (default, isolated to this session) or "project" (shared across all sessions for this project).'
3010
- }
3011
- },
3012
- required: ["action"]
3013
- },
3014
- async execute(input, ctx) {
3015
- const sessionPlanPath = ctx.meta["plan.path"];
3016
- let planPath;
3017
- if (input.scope === "project") {
3018
- if (typeof sessionPlanPath === "string") {
3019
- const lastSep = Math.max(
3020
- sessionPlanPath.lastIndexOf("/"),
3021
- sessionPlanPath.lastIndexOf("\\")
3022
- );
3023
- if (lastSep < 0) {
3024
- return {
3025
- ok: false,
3026
- message: `Cannot derive the project-scoped plan path: session plan path "${sessionPlanPath}" has no directory component.`,
3027
- plan: "",
3028
- count: 0,
3029
- open: 0
3030
- };
3031
- }
3032
- planPath = sessionPlanPath.slice(0, lastSep + 1) + "backlog.plan.json";
3033
- }
3034
- } else {
3035
- planPath = sessionPlanPath;
3036
- }
3037
- if (typeof planPath !== "string" || !planPath) {
3038
- return {
3039
- ok: false,
3040
- message: "Plan storage path is not configured for this session.",
3041
- plan: "",
3042
- count: 0,
3043
- open: 0
3044
- };
3045
- }
3046
- const sessionId = ctx.session?.id ?? "unknown";
3047
- let early = null;
3048
- const taskifyMeta = { title: "", details: "" };
3049
- let didTaskify = false;
3050
- let todosToReplace = null;
3051
- let plan;
3052
- try {
3053
- plan = await mutatePlan2(planPath, sessionId, async (p) => {
3054
- switch (input.action) {
3055
- case "show":
3056
- break;
3057
- case "add": {
3058
- const title = input.title?.trim();
3059
- if (!title) {
3060
- early = mkResult(p, false, "add requires `title`.");
3061
- return p;
3062
- }
3063
- const { plan: updated } = addPlanItem(p, title, input.details?.trim() || void 0);
3064
- return updated;
3065
- }
3066
- case "start":
3067
- case "done": {
3068
- if (!input.target) {
3069
- early = mkResult(
3070
- p,
3071
- false,
3072
- `${input.action} requires \`target\` (id|index|substring).`
3073
- );
3074
- return p;
3075
- }
3076
- const next = setPlanItemStatus2(
3077
- p,
3078
- input.target,
3079
- input.action === "start" ? "in_progress" : "done"
3080
- );
3081
- if (next === p) {
3082
- early = mkResult(p, false, `No plan item matched "${input.target}".`);
3083
- return p;
3084
- }
3085
- return next;
3086
- }
3087
- case "status": {
3088
- if (!input.target || !input.status) {
3089
- early = mkResult(
3090
- p,
3091
- false,
3092
- "status requires `target` (id|index|substring) and `status`."
3093
- );
3094
- return p;
3095
- }
3096
- const next = setPlanItemStatus2(p, input.target, input.status);
3097
- if (next === p) {
3098
- early = mkResult(p, false, `No plan item matched "${input.target}".`);
3099
- return p;
3100
- }
3101
- return next;
3102
- }
3103
- case "remove": {
3104
- if (!input.target) {
3105
- early = mkResult(p, false, "remove requires `target` (id|index|substring).");
3106
- return p;
3107
- }
3108
- const next = removePlanItem(p, input.target);
3109
- if (next === p) {
3110
- early = mkResult(p, false, `No plan item matched "${input.target}".`);
3111
- return p;
3112
- }
3113
- const nextIds = new Set(next.items.map((item) => item.id));
3114
- const removed = p.items.find((item) => !nextIds.has(item.id));
3115
- if (removed?.status !== "done") {
3116
- early = mkResult(
3117
- p,
3118
- false,
3119
- `Plan item "${removed?.title ?? input.target}" is not done and cannot be removed. Complete it first.`
3120
- );
3121
- return p;
3122
- }
3123
- return next;
3124
- }
3125
- case "promote": {
3126
- if (!input.target) {
3127
- early = mkResult(
3128
- p,
3129
- false,
3130
- `${input.action} requires \`target\` (id|index|substring).`
3131
- );
3132
- return p;
3133
- }
3134
- const derived = deriveTodosFromPlanItem(p, input.target, input.subtasks);
3135
- if (!derived) {
3136
- early = mkResult(p, false, `No plan item matched "${input.target}".`);
3137
- return p;
3138
- }
3139
- todosToReplace = derived.todos;
3140
- early = mkResult(
3141
- derived.plan,
3142
- true,
3143
- `${input.action} ok \u2014 ${derived.todos.length} todo(s) created.`,
3144
- derived.todos
3145
- );
3146
- return derived.plan;
3147
- }
3148
- case "template_use": {
3149
- const templateName = input.template?.trim();
3150
- if (!templateName) {
3151
- early = mkResult(p, false, "template_use requires `template` name.");
3152
- return p;
3153
- }
3154
- const template = getPlanTemplate(templateName);
3155
- if (!template) {
3156
- early = mkResult(p, false, `Unknown template "${templateName}".`);
3157
- return p;
3158
- }
3159
- let updated = p;
3160
- for (const item of template.items) {
3161
- ({ plan: updated } = addPlanItem(updated, item.title, item.details));
3162
- }
3163
- early = mkResult(
3164
- updated,
3165
- true,
3166
- `Applied template "${template.name}" \u2014 ${template.items.length} items added.`
3167
- );
3168
- return updated;
3169
- }
3170
- case "clear":
3171
- if (p.items.some((item) => item.status !== "done")) {
3172
- early = mkResult(
3173
- p,
3174
- false,
3175
- "Plan contains unfinished items and cannot be cleared. Complete them first."
3176
- );
3177
- return p;
3178
- }
3179
- return clearPlan(p);
3180
- case "taskify": {
3181
- if (!input.target) {
3182
- early = mkResult(
3183
- p,
3184
- false,
3185
- "taskify requires `target` (plan item id|index|substring)."
3186
- );
3187
- return p;
3188
- }
3189
- let itemIdx = -1;
3190
- const asNum = Number.parseInt(input.target, 10);
3191
- if (!Number.isNaN(asNum) && asNum >= 1 && asNum <= p.items.length) {
3192
- itemIdx = asNum - 1;
3193
- } else {
3194
- itemIdx = p.items.findIndex((it) => it.id === input.target);
3195
- if (itemIdx === -1) {
3196
- const lower = input.target.toLowerCase();
3197
- itemIdx = p.items.findIndex((it) => it.title.toLowerCase().includes(lower));
3198
- }
3199
- }
3200
- if (itemIdx === -1 || !p.items[itemIdx]) {
3201
- early = mkResult(p, false, `No plan item matched "${input.target}".`);
3202
- return p;
3203
- }
3204
- const item = p.items[itemIdx];
3205
- taskifyMeta.title = item.title;
3206
- taskifyMeta.details = item.details ?? "";
3207
- didTaskify = true;
3208
- break;
3209
- }
3210
- default:
3211
- early = mkResult(p, false, `Unknown action "${input.action}".`);
3212
- return p;
3213
- }
3214
- return p;
3215
- });
3216
- } catch (err) {
3217
- return {
3218
- ok: false,
3219
- message: `Plan change not saved \u2014 ${err instanceof Error ? err.message : String(err)}`,
3220
- plan: "",
3221
- count: 0,
3222
- open: 0
3223
- };
3224
- }
3225
- ctx.meta["plan.path.resolved"] = planPath;
3226
- await projectSessionPlanToKanban(ctx.projectRoot, plan.items, sessionId);
3227
- if (todosToReplace) {
3228
- await todoTool.execute({ todos: todosToReplace }, ctx, {
3229
- signal: AbortSignal.timeout(3e4)
3230
- });
3231
- }
3232
- if (early) return early;
3233
- if (didTaskify) {
3234
- const taskPathRaw = ctx.meta["task.path"];
3235
- if (typeof taskPathRaw !== "string" || !taskPathRaw) {
3236
- return mkResult(plan, false, "Task storage path not configured \u2014 cannot taskify.");
3237
- }
3238
- let taskPath = taskPathRaw;
3239
- if (input.scope === "project") {
3240
- const lastSep = Math.max(taskPath.lastIndexOf("/"), taskPath.lastIndexOf("\\"));
3241
- taskPath = lastSep >= 0 ? taskPath.slice(0, lastSep + 1) + "backlog.tasks.json" : "backlog.tasks.json";
3242
- }
3243
- const now = (/* @__PURE__ */ new Date()).toISOString();
3244
- try {
3245
- const taskFile = await mutateTasks2(taskPath, sessionId, (f) => {
3246
- f.tasks.push({
3247
- id: `task_${randomUUID3()}`,
3248
- title: taskifyMeta.title,
3249
- description: taskifyMeta.details || void 0,
3250
- type: "feature",
3251
- priority: "medium",
3252
- status: "pending",
3253
- createdAt: now,
3254
- updatedAt: now
3255
- });
3256
- return f;
3257
- });
3258
- ctx.meta["task.path.resolved"] = taskPath;
3259
- return mkResult(
3260
- plan,
3261
- true,
3262
- `taskify ok \u2014 added "${taskifyMeta.title}" to tasks.
3263
- ${formatTaskList(taskFile.tasks)}`
3264
- );
3265
- } catch (err) {
3266
- return mkResult(
3267
- plan,
3268
- false,
3269
- `taskify: task not saved \u2014 ${err instanceof Error ? err.message : String(err)}`
3270
- );
3271
- }
3272
- }
3273
- return mkResult(plan, true, `Plan ${input.action} ok.`);
3274
- }
3275
- };
3276
- function mkResult(plan, ok, message, todos) {
3277
- const open = plan.items.filter((i) => i.status !== "done").length;
3278
- const result = {
3279
- ok,
3280
- message,
3281
- plan: formatPlan(plan),
3282
- count: plan.items.length,
3283
- open
3284
- };
3285
- if (todos !== void 0) result.todos = todos;
3286
- return result;
3287
- }
2
+ planTool
3
+ } from "./chunk-KXNDHMUB.js";
4
+ import "./chunk-J4SRJKBW.js";
5
+ import "./chunk-55KF77OK.js";
6
+ import "./chunk-QNJ7AQ4B.js";
3288
7
  export {
3289
8
  planTool
3290
9
  };