@wrongstack/tools 0.306.4 → 0.307.0

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 (71) hide show
  1. package/dist/audit.js +14 -8
  2. package/dist/auto-proceed-loop-guard.js +8 -2
  3. package/dist/bash.js +57 -22
  4. package/dist/builtin.d.ts +6 -6
  5. package/dist/builtin.js +11302 -9305
  6. package/dist/clarify.d.ts +32 -0
  7. package/dist/codebase-index/ast-invariant-engine.d.ts +102 -0
  8. package/dist/codebase-index/ast-symbol-mutator.d.ts +28 -0
  9. package/dist/codebase-index/background-indexer.d.ts +9 -0
  10. package/dist/codebase-index/codebase-ast-replace-tool.d.ts +31 -0
  11. package/dist/codebase-index/codebase-impact-analysis-tool.d.ts +40 -0
  12. package/dist/codebase-index/codebase-invariant-check-tool.d.ts +23 -0
  13. package/dist/codebase-index/codebase-repo-map-tool.d.ts +22 -0
  14. package/dist/codebase-index/codebase-skeleton-tool.d.ts +36 -0
  15. package/dist/codebase-index/codebase-targeted-test-tool.d.ts +30 -0
  16. package/dist/codebase-index/index.d.ts +11 -1
  17. package/dist/codebase-index/index.js +4141 -1479
  18. package/dist/codebase-index/project-server-client-state.d.ts +79 -0
  19. package/dist/codebase-index/project-server-client.d.ts +3 -71
  20. package/dist/codebase-index/project-server-protocol.d.ts +1 -0
  21. package/dist/codebase-index/project-server.js +751 -909
  22. package/dist/codebase-index/repo-map.d.ts +20 -0
  23. package/dist/codebase-index/skeleton-extractor.d.ts +64 -0
  24. package/dist/codebase-index/tree-sitter-parser.d.ts +11 -0
  25. package/dist/codebase-index/worker.js +723 -891
  26. package/dist/codebase-index/writer-mutations.d.ts +26 -0
  27. package/dist/codebase-index/writer-refs.d.ts +50 -0
  28. package/dist/codebase-index/writer-search.d.ts +30 -0
  29. package/dist/codebase-index/writer.d.ts +2 -320
  30. package/dist/edit.js +8558 -349
  31. package/dist/exec.js +73 -20
  32. package/dist/fetch.js +11 -9
  33. package/dist/format.js +14 -8
  34. package/dist/glob.js +5 -1
  35. package/dist/grep.js +19 -8
  36. package/dist/index.d.ts +3 -1
  37. package/dist/index.js +11386 -9416
  38. package/dist/install.js +14 -8
  39. package/dist/json.js +88 -15
  40. package/dist/kanban-board-actions.d.ts +4 -0
  41. package/dist/kanban-lifecycle-actions.d.ts +4 -0
  42. package/dist/kanban-serializer.d.ts +21 -0
  43. package/dist/kanban.js +985 -1034
  44. package/dist/languages/index.js +14 -8
  45. package/dist/lint.js +14 -8
  46. package/dist/logs.js +13 -3
  47. package/dist/next-steps.d.ts +8 -0
  48. package/dist/next-steps.js +18 -0
  49. package/dist/outdated.js +14 -8
  50. package/dist/pack.js +11295 -9305
  51. package/dist/patch.js +8301 -78
  52. package/dist/plan.js +1231 -1281
  53. package/dist/process-registry.js +14 -8
  54. package/dist/ps-slash.js +65 -30
  55. package/dist/read.js +751 -910
  56. package/dist/replace.js +8450 -224
  57. package/dist/search.js +21 -15
  58. package/dist/security-ast-scan-tool.d.ts +43 -0
  59. package/dist/session-kanban-graph.d.ts +9 -0
  60. package/dist/session-kanban-sync.d.ts +31 -0
  61. package/dist/session-kanban.d.ts +5 -141
  62. package/dist/session-kanban.js +367 -360
  63. package/dist/task.js +1157 -1207
  64. package/dist/test.js +14 -8
  65. package/dist/todo.js +2187 -2237
  66. package/dist/tool-diff.js +6 -1
  67. package/dist/tool-summary.js +4 -2
  68. package/dist/tool-tier.js +11302 -9305
  69. package/dist/typecheck.js +14 -8
  70. package/dist/write.js +8374 -153
  71. package/package.json +7 -7
package/dist/kanban.js CHANGED
@@ -1,49 +1,29 @@
1
1
  // src/kanban.ts
2
- import { randomUUID as randomUUID2 } from "node:crypto";
2
+ import { stripLifecycleIssues as stripLifecycleIssues2 } from "@wrongstack/kanban";
3
+
4
+ // src/kanban-board-actions.ts
3
5
  import { loadTasks as loadTasks2 } from "@wrongstack/core/storage";
4
6
  import { deserializeTaskGraph as deserializeTaskGraph2, serializeTaskGraph } from "@wrongstack/core/tasking";
5
7
  import {
6
8
  addTask,
7
9
  adoptManagedLifecycle,
8
- assignTask,
9
- claimReadyTask,
10
- copyTaskToBoard,
11
10
  createBoard as createBoard2,
12
11
  createBoardFromTaskGraph,
13
12
  createBoardFromText,
14
13
  duplicateBoard,
15
- evaluateContractGraphReadiness,
16
14
  exportBoardAsMarkdown,
17
15
  exportBoardToTaskGraph,
18
- finalizeTaskCompletion,
19
16
  getBoard as getBoard3,
20
17
  getKanbanOrchestrationSnapshot as getKanbanOrchestrationSnapshot2,
21
18
  getKanbanQueueHealth,
22
- getTask,
23
- getTaskChain,
24
- heartbeatTaskAssignment,
25
19
  listBoards as listBoards2,
26
20
  listKanbanEvents,
27
21
  listReadyTasks,
28
- mergeTasks,
29
- moveTask,
30
22
  parseLinesIntoTasks,
31
- recoverStaleTaskAssignments,
32
- releaseTaskClaim,
33
23
  removeBoard as removeBoard2,
34
- removeTask,
35
- repairManagedTaskProjection,
36
- resolveAutoAccept,
37
24
  searchKanban,
38
- setTaskChain,
39
- stripLifecycleIssues,
40
25
  syncBoardFromTaskGraph as syncBoardFromTaskGraph2,
41
- transferTaskToBoard,
42
- transitionTask,
43
- updateBoard as updateBoard2,
44
- updateTask as updateTask2,
45
- updateTaskAssignment,
46
- verifyTaskCompletion as verifyTaskCompletion2
26
+ updateBoard as updateBoard2
47
27
  } from "@wrongstack/kanban";
48
28
 
49
29
  // src/kanban-board-inputs.ts
@@ -90,16 +70,8 @@ function duplicateBoardOptions(input) {
90
70
  };
91
71
  }
92
72
 
93
- // src/kanban-contract-actions.ts
94
- import {
95
- addContractEdge,
96
- configureContractGraph,
97
- evaluateTaskContractGraph,
98
- getContractGraph,
99
- removeContractEdge,
100
- removeContractNode,
101
- upsertContractNode
102
- } from "@wrongstack/kanban";
73
+ // src/kanban-split-task-handler.ts
74
+ import { getBoard, splitTask } from "@wrongstack/kanban";
103
75
 
104
76
  // src/kanban-tool-results.ts
105
77
  function atomicityNudge(task) {
@@ -121,7 +93,378 @@ function okTask(board, task, message) {
121
93
  return { ok: true, message, board, task };
122
94
  }
123
95
 
96
+ // src/kanban-split-task-handler.ts
97
+ async function handleSplitTask(projectRoot, input, extraSplitOptions) {
98
+ const boardId = input.boardId;
99
+ const taskId = input.taskId;
100
+ const childTitles = input.childTitles;
101
+ if (!boardId || !taskId || !childTitles?.length) {
102
+ return fail("split requires boardId, taskId, and at least one childTitles.");
103
+ }
104
+ const {
105
+ targetColumnId,
106
+ inheritAssignment,
107
+ inheritLabels,
108
+ inheritSuccessCriteria,
109
+ inheritGoalMetrics,
110
+ inheritDependencies,
111
+ chainChildren,
112
+ rewireDependents
113
+ } = input;
114
+ const result = await splitTask(projectRoot, boardId, taskId, {
115
+ titles: childTitles,
116
+ ...extraSplitOptions,
117
+ ...targetColumnId !== void 0 ? { columnId: targetColumnId } : {},
118
+ ...inheritAssignment !== void 0 ? { inheritAssignment } : {},
119
+ ...inheritLabels !== void 0 ? { inheritLabels } : {},
120
+ ...inheritSuccessCriteria !== void 0 ? { inheritSuccessCriteria } : {},
121
+ ...inheritGoalMetrics !== void 0 ? { inheritGoalMetrics } : {},
122
+ ...inheritDependencies !== void 0 ? { inheritDependencies } : {},
123
+ ...chainChildren !== void 0 ? { chainChildren } : {},
124
+ ...rewireDependents !== void 0 ? { rewireDependents } : {}
125
+ });
126
+ if (!result) return fail("Task not found.");
127
+ const freshParent = result.board.tasks?.find((t) => t.id === taskId);
128
+ if (!freshParent) {
129
+ return fail(
130
+ `Split succeeded but parent ${taskId} not found in returned board. Children: [${result.children.map((c) => c.id).join(", ")}].`
131
+ );
132
+ }
133
+ return {
134
+ ok: true,
135
+ message: `${result.children.length} child task(s) created.`,
136
+ board: result.board,
137
+ task: freshParent,
138
+ children: result.children
139
+ };
140
+ }
141
+ async function requireBoard(projectRoot, boardId) {
142
+ return boardId ? getBoard(projectRoot, boardId) : null;
143
+ }
144
+
145
+ // src/session-kanban.ts
146
+ import { loadPlan, loadTasks } from "@wrongstack/core/storage";
147
+ import { deserializeTaskGraph } from "@wrongstack/core/tasking";
148
+ import {
149
+ bridgeKanbanSupervisor,
150
+ compactSessionMirrorBoard,
151
+ createBoard,
152
+ DEFAULT_COLUMNS,
153
+ getBoard as getBoard2,
154
+ getKanbanOrchestrationSnapshot,
155
+ listBoards,
156
+ pruneSessionBoards,
157
+ removeBoard,
158
+ syncBoardFromTaskGraph,
159
+ touchKanbanPresence,
160
+ updateBoard
161
+ } from "@wrongstack/kanban";
162
+
163
+ // src/session-kanban-graph.ts
164
+ function taskFileToSerializedGraph(tasks, sessionId) {
165
+ const graphId = `session:${sessionId}`;
166
+ const ids = new Set(tasks.map((task) => task.id));
167
+ const nodes = tasks.map((task, index) => ({
168
+ id: task.id,
169
+ title: task.title,
170
+ description: task.description ?? "",
171
+ type: task.type,
172
+ priority: task.priority,
173
+ status: task.status,
174
+ specRequirementId: `${graphId}:${task.id}`,
175
+ ...task.assignee ? { assignee: task.assignee } : {},
176
+ ...task.estimateHours !== void 0 ? { estimateHours: task.estimateHours } : {},
177
+ createdAt: index,
178
+ updatedAt: index
179
+ }));
180
+ const edges = tasks.flatMap(
181
+ (task) => (task.dependsOn ?? []).filter((dependency) => ids.has(dependency)).map((dependency) => ({
182
+ id: `${dependency}->${task.id}`,
183
+ from: dependency,
184
+ to: task.id,
185
+ type: "depends_on"
186
+ }))
187
+ );
188
+ const hasIncoming = new Set(edges.map((edge) => edge.to));
189
+ const rootNodes = nodes.filter((node) => !hasIncoming.has(node.id)).map((node) => node.id);
190
+ return {
191
+ // Keep the historical graph id so existing mirrored task cards are reused.
192
+ id: graphId,
193
+ specId: graphId,
194
+ requiredRequirementIds: nodes.map((node) => node.specRequirementId),
195
+ title: "Session tasks",
196
+ nodes,
197
+ edges,
198
+ rootNodes: rootNodes.length ? rootNodes : nodes[0] ? [nodes[0].id] : [],
199
+ createdAt: 0,
200
+ updatedAt: 0
201
+ };
202
+ }
203
+
204
+ // src/session-kanban.ts
205
+ var SESSION_KANBAN_COLUMNS = DEFAULT_COLUMNS.map((column) => ({
206
+ ...column
207
+ }));
208
+
209
+ // src/kanban-board-actions.ts
210
+ async function handleKanbanBoardAction(projectRoot, input, ctx) {
211
+ switch (input.action) {
212
+ case "list_boards": {
213
+ const boards = await listBoards2(projectRoot);
214
+ return { ok: true, message: `${boards.length} board(s).`, boards };
215
+ }
216
+ case "get_board": {
217
+ const board = await requireBoard(projectRoot, input.boardId);
218
+ return board ? okBoard(board) : fail("Board not found.");
219
+ }
220
+ case "create_board": {
221
+ if (!input.title) return fail("create_board requires title.");
222
+ const existing = (await listBoards2(projectRoot)).filter(
223
+ (candidate) => (candidate.kind ?? "project") === "project"
224
+ );
225
+ const board = await createBoard2(projectRoot, boardCreateInput(input, input.title));
226
+ 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(
227
+ ", "
228
+ )}${existing.length > 3 ? ", \u2026" : ""}. If this work belongs to one of them, add_task there instead and delete this board.` : "";
229
+ return { ok: true, message: `Board created: ${board.title}.${note}`, board };
230
+ }
231
+ case "update_board": {
232
+ if (!input.boardId) return fail("update_board requires boardId.");
233
+ const board = await updateBoard2(projectRoot, input.boardId, boardUpdatePatch(input));
234
+ return board ? okBoard(board, "Board updated.") : fail("Board not found.");
235
+ }
236
+ case "adopt_managed_lifecycle": {
237
+ if (!input.boardId || !input.author || !input.transitionComment) {
238
+ return fail(
239
+ "adopt_managed_lifecycle requires boardId, author, transitionComment, and five ordered columns."
240
+ );
241
+ }
242
+ if (input.columns?.length !== 5) {
243
+ return fail(
244
+ "adopt_managed_lifecycle columns must be ordered as backlog, todo, running, review, done."
245
+ );
246
+ }
247
+ const [backlog, todo, running, review, done] = input.columns;
248
+ if (!backlog || !todo || !running || !review || !done) {
249
+ return fail("adopt_managed_lifecycle columns must contain five nonblank ids.");
250
+ }
251
+ const board = await adoptManagedLifecycle(projectRoot, input.boardId, {
252
+ columns: { backlog, todo, running, review, done },
253
+ actor: input.author,
254
+ comment: input.transitionComment
255
+ });
256
+ return board ? okBoard(board, "Managed lifecycle adopted without moving existing cards.") : fail("Board not found.");
257
+ }
258
+ case "release_managed_lifecycle": {
259
+ if (!input.boardId) return fail("release_managed_lifecycle requires boardId.");
260
+ const board = await updateBoard2(projectRoot, input.boardId, { lifecycle: null });
261
+ return board ? okBoard(
262
+ board,
263
+ "Managed lifecycle released; the board now tracks work without strict gates."
264
+ ) : fail("Board not found.");
265
+ }
266
+ case "duplicate_board": {
267
+ if (!input.boardId) return fail("duplicate_board requires boardId.");
268
+ const board = await duplicateBoard(projectRoot, input.boardId, duplicateBoardOptions(input));
269
+ return board ? okBoard(board, "Board duplicated.") : fail("Board not found.");
270
+ }
271
+ case "delete_board": {
272
+ if (!input.boardId) return fail("delete_board requires boardId.");
273
+ const removed = await removeBoard2(projectRoot, input.boardId);
274
+ return { ok: removed, message: removed ? "Board deleted." : "Board not found." };
275
+ }
276
+ case "generate_board": {
277
+ if (!input.description) return fail("generate_board requires description.");
278
+ const boardInput = createBoardFromText({
279
+ description: input.description,
280
+ ...input.title !== void 0 ? { title: input.title } : {},
281
+ ...input.context !== void 0 ? { context: input.context } : {}
282
+ });
283
+ const board = await createBoard2(projectRoot, boardInput);
284
+ for (const tInput of parseLinesIntoTasks(
285
+ input.description,
286
+ board.columns[0]?.id ?? "backlog"
287
+ )) {
288
+ await addTask(projectRoot, board.id, tInput);
289
+ }
290
+ return okBoard(await getBoard3(projectRoot, board.id) ?? board, "Board generated.");
291
+ }
292
+ case "export_markdown": {
293
+ const board = await requireBoard(projectRoot, input.boardId);
294
+ if (!board) return fail("Board not found.");
295
+ return {
296
+ ok: true,
297
+ message: "Board exported.",
298
+ board,
299
+ markdown: exportBoardAsMarkdown(board)
300
+ };
301
+ }
302
+ case "export_task_graph": {
303
+ if (!input.boardId) return fail("export_task_graph requires boardId.");
304
+ const exported = await exportBoardToTaskGraph(projectRoot, input.boardId, {
305
+ ...input.graphId !== void 0 ? { graphId: input.graphId } : {},
306
+ ...input.specId !== void 0 ? { specId: input.specId } : {},
307
+ ...input.title !== void 0 ? { title: input.title } : {},
308
+ ...input.preserveOriginTaskIds !== void 0 ? { preserveOriginTaskIds: input.preserveOriginTaskIds } : {},
309
+ ...input.includeArchived !== void 0 ? { includeArchived: input.includeArchived } : {}
310
+ });
311
+ if (!exported) return fail("Board not found.");
312
+ return {
313
+ ok: true,
314
+ message: `Task graph exported with ${exported.graph.nodes.size} node(s).`,
315
+ board: exported.board,
316
+ taskGraph: serializeTaskGraph(exported.graph)
317
+ };
318
+ }
319
+ case "sync_task_graph": {
320
+ if (!input.boardId || !input.taskGraph) {
321
+ return fail("sync_task_graph requires boardId and taskGraph.");
322
+ }
323
+ const graph = deserializeTaskGraph2(input.taskGraph);
324
+ const result = await syncBoardFromTaskGraph2(projectRoot, input.boardId, graph, {
325
+ ...input.title !== void 0 ? { title: input.title } : {},
326
+ ...input.description !== void 0 ? { description: input.description } : {},
327
+ ...input.tags !== void 0 ? { tags: input.tags } : {},
328
+ ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
329
+ ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
330
+ ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
331
+ ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {},
332
+ ...input.archiveMissingTasks !== void 0 ? { archiveMissingTasks: input.archiveMissingTasks } : {},
333
+ ...input.preserveManualDependencies !== void 0 ? { preserveManualDependencies: input.preserveManualDependencies } : {}
334
+ });
335
+ return result ? {
336
+ ok: true,
337
+ message: `Task graph synced: ${result.createdTaskIds.length} created, ${result.updatedTaskIds.length} updated, ${result.archivedTaskIds.length} archived.`,
338
+ board: result.board
339
+ } : fail("Board not found.");
340
+ }
341
+ case "create_from_graph": {
342
+ if (!input.taskGraph) return fail("create_from_graph requires taskGraph.");
343
+ const graph = deserializeTaskGraph2(input.taskGraph);
344
+ const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
345
+ ...input.title !== void 0 ? { title: input.title } : {},
346
+ ...input.description !== void 0 ? { description: input.description } : {},
347
+ ...input.tags !== void 0 ? { tags: input.tags } : {},
348
+ ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
349
+ ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
350
+ ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
351
+ ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {}
352
+ });
353
+ return {
354
+ ok: true,
355
+ message: `Created board "${board.title}" from task graph with ${board.tasks.length} tasks.`,
356
+ board
357
+ };
358
+ }
359
+ case "import_session_tasks": {
360
+ const taskPath = ctx.meta?.["task.path"];
361
+ if (!taskPath) return fail("No session task file for this session.");
362
+ const file = await loadTasks2(taskPath);
363
+ if (!file || file.tasks.length === 0) return fail("No session tasks to import.");
364
+ const sessionId = ctx.session?.id ?? file.sessionId ?? "session";
365
+ const graph = deserializeTaskGraph2(taskFileToSerializedGraph(file.tasks, sessionId));
366
+ const tags = ["session", `session:${sessionId}`];
367
+ const existing = (await listBoards2(projectRoot)).find(
368
+ (b) => b.tags?.includes(`session:${sessionId}`)
369
+ );
370
+ if (existing) {
371
+ const result = await syncBoardFromTaskGraph2(projectRoot, existing.id, graph, {
372
+ sourceSystem: "session",
373
+ tags,
374
+ archiveMissingTasks: true,
375
+ includeCompletedTasks: true
376
+ });
377
+ return result ? {
378
+ ok: true,
379
+ message: `Synced ${file.tasks.length} session tasks into board "${result.board.title}".`,
380
+ board: result.board
381
+ } : fail("Session board vanished mid-sync.");
382
+ }
383
+ const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
384
+ title: `Session tasks (${sessionId.slice(0, 8)})`,
385
+ sourceSystem: "session",
386
+ tags
387
+ });
388
+ return {
389
+ ok: true,
390
+ message: `Imported ${file.tasks.length} session tasks into new board "${board.title}".`,
391
+ board
392
+ };
393
+ }
394
+ case "search_tasks": {
395
+ const tasks = await searchKanban(projectRoot, {
396
+ query: input.query,
397
+ boardId: input.boardId,
398
+ assignedAgent: input.agentId,
399
+ status: input.status,
400
+ priority: input.priority,
401
+ label: input.labels?.[0],
402
+ chainId: input.chainId
403
+ });
404
+ return { ok: true, message: `${tasks.length} task(s) matched.`, tasks };
405
+ }
406
+ case "ready_tasks": {
407
+ const tasks = await listReadyTasks(projectRoot, {
408
+ query: input.query,
409
+ boardId: input.boardId,
410
+ assignedAgent: input.agentId,
411
+ priority: input.priority,
412
+ label: input.labels?.[0],
413
+ chainId: input.chainId,
414
+ limit: input.limit
415
+ });
416
+ return { ok: true, message: `${tasks.length} ready task(s).`, tasks };
417
+ }
418
+ case "snapshot": {
419
+ const snapshot = await getKanbanOrchestrationSnapshot2(projectRoot, {
420
+ query: input.query,
421
+ boardId: input.boardId,
422
+ assignedAgent: input.agentId,
423
+ status: input.status,
424
+ priority: input.priority,
425
+ label: input.labels?.[0],
426
+ chainId: input.chainId
427
+ });
428
+ return {
429
+ ok: true,
430
+ message: `${snapshot.ready.length} ready, ${snapshot.running.length} running, ${snapshot.blocked.length} blocked.`,
431
+ snapshot
432
+ };
433
+ }
434
+ case "events": {
435
+ if (!input.boardId) return fail("events requires boardId.");
436
+ const eventList = await listKanbanEvents(projectRoot, input.boardId);
437
+ return {
438
+ ok: true,
439
+ message: `${eventList.length} event(s).`,
440
+ events: eventList
441
+ };
442
+ }
443
+ case "queue_health": {
444
+ const health = await getKanbanQueueHealth(projectRoot, {
445
+ ...input.boardId !== void 0 ? { boardId: input.boardId } : {}
446
+ });
447
+ return {
448
+ ok: true,
449
+ message: `Counts: startable=${health.counts.startable}, running=${health.counts.running}, stale=${health.staleAssignments.count}.`,
450
+ queueHealth: health
451
+ };
452
+ }
453
+ default:
454
+ return void 0;
455
+ }
456
+ }
457
+
124
458
  // src/kanban-contract-actions.ts
459
+ import {
460
+ addContractEdge,
461
+ configureContractGraph,
462
+ evaluateTaskContractGraph,
463
+ getContractGraph,
464
+ removeContractEdge,
465
+ removeContractNode,
466
+ upsertContractNode
467
+ } from "@wrongstack/kanban";
125
468
  async function handleKanbanContractAction(projectRoot, input, actor) {
126
469
  switch (input.action) {
127
470
  case "get_contract_graph": {
@@ -345,58 +688,6 @@ import {
345
688
  updateCheckOnTask,
346
689
  updateGoalMetricOnTask
347
690
  } from "@wrongstack/kanban";
348
-
349
- // src/kanban-split-task-handler.ts
350
- import { getBoard, splitTask } from "@wrongstack/kanban";
351
- async function handleSplitTask(projectRoot, input, extraSplitOptions) {
352
- const boardId = input.boardId;
353
- const taskId = input.taskId;
354
- const childTitles = input.childTitles;
355
- if (!boardId || !taskId || !childTitles?.length) {
356
- return fail("split requires boardId, taskId, and at least one childTitles.");
357
- }
358
- const {
359
- targetColumnId,
360
- inheritAssignment,
361
- inheritLabels,
362
- inheritSuccessCriteria,
363
- inheritGoalMetrics,
364
- inheritDependencies,
365
- chainChildren,
366
- rewireDependents
367
- } = input;
368
- const result = await splitTask(projectRoot, boardId, taskId, {
369
- titles: childTitles,
370
- ...extraSplitOptions,
371
- ...targetColumnId !== void 0 ? { columnId: targetColumnId } : {},
372
- ...inheritAssignment !== void 0 ? { inheritAssignment } : {},
373
- ...inheritLabels !== void 0 ? { inheritLabels } : {},
374
- ...inheritSuccessCriteria !== void 0 ? { inheritSuccessCriteria } : {},
375
- ...inheritGoalMetrics !== void 0 ? { inheritGoalMetrics } : {},
376
- ...inheritDependencies !== void 0 ? { inheritDependencies } : {},
377
- ...chainChildren !== void 0 ? { chainChildren } : {},
378
- ...rewireDependents !== void 0 ? { rewireDependents } : {}
379
- });
380
- if (!result) return fail("Task not found.");
381
- const freshParent = result.board.tasks?.find((t) => t.id === taskId);
382
- if (!freshParent) {
383
- return fail(
384
- `Split succeeded but parent ${taskId} not found in returned board. Children: [${result.children.map((c) => c.id).join(", ")}].`
385
- );
386
- }
387
- return {
388
- ok: true,
389
- message: `${result.children.length} child task(s) created.`,
390
- board: result.board,
391
- task: freshParent,
392
- children: result.children
393
- };
394
- }
395
- async function requireBoard(projectRoot, boardId) {
396
- return boardId ? getBoard(projectRoot, boardId) : null;
397
- }
398
-
399
- // src/kanban-detail-actions.ts
400
691
  async function handleKanbanDetailAction(projectRoot, input) {
401
692
  switch (input.action) {
402
693
  case "workbench": {
@@ -529,26 +820,34 @@ async function handleKanbanDetailAction(projectRoot, input) {
529
820
  }
530
821
  }
531
822
 
532
- // src/kanban-presence.ts
533
- import { touchKanbanPresence } from "@wrongstack/kanban";
534
- function createKanbanPresenceWrapper(projectRoot, input, ctx) {
535
- return async (result) => {
536
- const boardId = result.board?.id ?? input.boardId;
537
- if (!result.ok || !boardId || !ctx.session?.id || !ctx.agentId) return result;
538
- try {
539
- const board = await touchKanbanPresence(projectRoot, boardId, {
540
- sessionId: ctx.session.id,
541
- agentId: ctx.agentId,
542
- agentName: ctx.agentName,
543
- taskId: input.taskId ?? result.task?.id,
544
- runTaskId: input.runTaskId
545
- });
546
- return board ? { ...result, board } : result;
547
- } catch {
548
- return result;
549
- }
550
- };
551
- }
823
+ // src/kanban-lifecycle-actions.ts
824
+ import { randomUUID as randomUUID2 } from "node:crypto";
825
+ import {
826
+ addTask as addTask2,
827
+ assignTask,
828
+ claimReadyTask,
829
+ copyTaskToBoard,
830
+ evaluateContractGraphReadiness,
831
+ finalizeTaskCompletion,
832
+ getBoard as getBoard4,
833
+ getTask,
834
+ getTaskChain,
835
+ heartbeatTaskAssignment,
836
+ mergeTasks,
837
+ moveTask,
838
+ recoverStaleTaskAssignments,
839
+ releaseTaskClaim,
840
+ removeTask,
841
+ repairManagedTaskProjection,
842
+ resolveAutoAccept,
843
+ setTaskChain,
844
+ stripLifecycleIssues,
845
+ transferTaskToBoard,
846
+ transitionTask,
847
+ updateTask as updateTask2,
848
+ updateTaskAssignment,
849
+ verifyTaskCompletion as verifyTaskCompletion2
850
+ } from "@wrongstack/kanban";
552
851
 
553
852
  // src/kanban-task-inputs.ts
554
853
  import { randomUUID } from "node:crypto";
@@ -724,6 +1023,572 @@ function assignmentForTaskCreate(input) {
724
1023
  };
725
1024
  }
726
1025
 
1026
+ // src/kanban-lifecycle-actions.ts
1027
+ async function handleKanbanLifecycleAction(projectRoot, input, ctx) {
1028
+ switch (input.action) {
1029
+ case "add_task": {
1030
+ if (!input.boardId || !input.title) return fail("add_task requires boardId and title.");
1031
+ const result = await addTask2(projectRoot, input.boardId, taskInput(input));
1032
+ if (!result) return fail("Board not found.");
1033
+ return okTask(result.board, result.task, `Task added.${atomicityNudge(result.task)}`);
1034
+ }
1035
+ case "split_task": {
1036
+ if (!input.boardId || !input.taskId || !input.childTitles?.length) {
1037
+ return fail("split_task requires boardId, taskId, and childTitles.");
1038
+ }
1039
+ return handleSplitTask(projectRoot, input, {});
1040
+ }
1041
+ case "merge_tasks": {
1042
+ if (!input.boardId || !input.taskIds?.length || !input.title) {
1043
+ return fail("merge_tasks requires boardId, taskIds, and title.");
1044
+ }
1045
+ const result = await mergeTasks(projectRoot, input.boardId, {
1046
+ taskIds: input.taskIds,
1047
+ title: input.title,
1048
+ ...input.description !== void 0 ? { description: input.description } : {},
1049
+ ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1050
+ ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1051
+ ...input.closeSourceTasks !== void 0 ? { closeSourceTasks: input.closeSourceTasks } : {}
1052
+ });
1053
+ return result ? okTask(result.board, result.task, "Tasks merged.") : fail("Board or task not found.");
1054
+ }
1055
+ case "copy_task": {
1056
+ if (!input.boardId || !input.taskId || !input.targetBoardId) {
1057
+ return fail("copy_task requires boardId, taskId, and targetBoardId.");
1058
+ }
1059
+ const result = await copyTaskToBoard(
1060
+ projectRoot,
1061
+ input.boardId,
1062
+ input.taskId,
1063
+ input.targetBoardId,
1064
+ {
1065
+ ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1066
+ ...input.order !== void 0 ? { targetOrder: input.order } : {},
1067
+ ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1068
+ ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1069
+ }
1070
+ );
1071
+ return result ? okTask(result.targetBoard, result.task, "Task copied to target board.") : fail("Board or task not found.");
1072
+ }
1073
+ case "transfer_task": {
1074
+ if (!input.boardId || !input.taskId || !input.targetBoardId) {
1075
+ return fail("transfer_task requires boardId, taskId, and targetBoardId.");
1076
+ }
1077
+ const result = await transferTaskToBoard(
1078
+ projectRoot,
1079
+ input.boardId,
1080
+ input.taskId,
1081
+ input.targetBoardId,
1082
+ {
1083
+ ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1084
+ ...input.order !== void 0 ? { targetOrder: input.order } : {},
1085
+ ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1086
+ ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1087
+ }
1088
+ );
1089
+ return result ? okTask(result.targetBoard, result.task, "Task transferred to target board.") : fail("Board or task not found.");
1090
+ }
1091
+ case "get_task": {
1092
+ if (!input.boardId || !input.taskId) return fail("get_task requires boardId and taskId.");
1093
+ const task = await getTask(projectRoot, input.boardId, input.taskId);
1094
+ return task ? { ok: true, message: "Task loaded.", task } : fail("Task not found.");
1095
+ }
1096
+ case "start_task": {
1097
+ if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1098
+ return fail("start_task requires boardId, taskId, author, and transitionComment.");
1099
+ }
1100
+ let board = await getBoard4(projectRoot, input.boardId);
1101
+ let task = board?.tasks.find((candidate) => candidate.id === input.taskId);
1102
+ if (!board || !task) return fail("Board or task not found.");
1103
+ const readiness = evaluateContractGraphReadiness(board, task.id);
1104
+ if (!readiness.ready) {
1105
+ return fail(
1106
+ `Task is not implementation-ready: ${readiness.issues.map((issue) => issue.message).join(" | ")}`
1107
+ );
1108
+ }
1109
+ if (board.lifecycle?.mode !== "managed") {
1110
+ const now = /* @__PURE__ */ new Date();
1111
+ const assigned = await updateTaskAssignment(projectRoot, board.id, task.id, {
1112
+ status: "running",
1113
+ agentId: input.agentId ?? input.author,
1114
+ leaseId: input.leaseId ?? randomUUID2(),
1115
+ claimedAt: input.claimedAt ?? now.toISOString(),
1116
+ heartbeatAt: input.heartbeatAt ?? now.toISOString(),
1117
+ leaseExpiresAt: input.leaseExpiresAt ?? new Date(now.getTime() + 15 * 6e4).toISOString(),
1118
+ attempt: input.attempt ?? 1,
1119
+ maxAttempts: input.maxAttempts ?? 3
1120
+ });
1121
+ if (!assigned) return fail("Task assignment could not be started.");
1122
+ const started = await updateTask2(projectRoot, board.id, task.id, {
1123
+ status: "in_progress"
1124
+ });
1125
+ const current = started ?? assigned;
1126
+ const claimed = task;
1127
+ const currentTask = current.tasks.find((candidate) => candidate.id === claimed.id) ?? claimed;
1128
+ ctx.setCurrentKanbanTask?.(currentTask.id, current.id);
1129
+ return okTask(
1130
+ current,
1131
+ currentTask,
1132
+ "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."
1133
+ );
1134
+ }
1135
+ let stage = task.lifecycle?.currentStage;
1136
+ if (stage === "backlog") {
1137
+ const moved = await transitionTask(projectRoot, board.id, task.id, {
1138
+ to: "todo",
1139
+ actor: input.author,
1140
+ comment: input.transitionComment
1141
+ });
1142
+ if (!moved) return fail("Task could not enter Todo.");
1143
+ board = moved.board;
1144
+ task = moved.task;
1145
+ stage = task.lifecycle?.currentStage;
1146
+ }
1147
+ if (stage === "todo" || stage === "review") {
1148
+ const now = /* @__PURE__ */ new Date();
1149
+ const leaseId = input.leaseId ?? randomUUID2();
1150
+ const assigned = await updateTaskAssignment(projectRoot, board.id, task.id, {
1151
+ status: "running",
1152
+ agentId: input.agentId ?? input.author,
1153
+ leaseId,
1154
+ claimedAt: input.claimedAt ?? now.toISOString(),
1155
+ heartbeatAt: input.heartbeatAt ?? now.toISOString(),
1156
+ leaseExpiresAt: input.leaseExpiresAt ?? new Date(now.getTime() + 15 * 6e4).toISOString(),
1157
+ attempt: input.attempt ?? 1,
1158
+ maxAttempts: input.maxAttempts ?? 3
1159
+ });
1160
+ if (!assigned) return fail("Task assignment could not be started.");
1161
+ const moved = await transitionTask(projectRoot, board.id, task.id, {
1162
+ to: "running",
1163
+ actor: input.author,
1164
+ comment: input.transitionComment
1165
+ });
1166
+ if (!moved) return fail("Task could not enter Running.");
1167
+ board = moved.board;
1168
+ task = moved.task;
1169
+ stage = task.lifecycle?.currentStage;
1170
+ }
1171
+ if (stage !== "running" || task.assignment?.status !== "running") {
1172
+ return fail(
1173
+ `start_task only accepts Backlog, Todo, Review repair, or live Running cards (current: ${stage ?? "unknown"}).`
1174
+ );
1175
+ }
1176
+ ctx.setCurrentKanbanTask(task.id, board.id);
1177
+ return okTask(
1178
+ board,
1179
+ task,
1180
+ "Task is active; runtime Kanban governance is now bound to this run."
1181
+ );
1182
+ }
1183
+ case "update_task": {
1184
+ if (!input.boardId || !input.taskId) return fail("update_task requires boardId and taskId.");
1185
+ const board = await updateTask2(projectRoot, input.boardId, input.taskId, taskPatch(input));
1186
+ return board ? okBoard(board, "Task updated.") : fail("Task not found.");
1187
+ }
1188
+ case "transition_task": {
1189
+ if (!input.boardId || !input.taskId || !input.lifecycleStage || !input.author || !input.transitionComment) {
1190
+ return fail(
1191
+ "transition_task requires boardId, taskId, lifecycleStage, author, and transitionComment."
1192
+ );
1193
+ }
1194
+ if (input.lifecycleStage === "done") {
1195
+ const boardBefore = await getBoard4(projectRoot, input.boardId);
1196
+ const taskBefore = boardBefore ? await getTask(projectRoot, input.boardId, input.taskId) : null;
1197
+ if (boardBefore && taskBefore && !taskBefore.verificationReport && (taskBefore.atomic || Boolean(taskBefore.successCriteria?.length))) {
1198
+ const preGate = await verifyTaskCompletion2(projectRoot, input.boardId, taskBefore.id, {
1199
+ persist: false
1200
+ });
1201
+ await updateTask2(projectRoot, input.boardId, taskBefore.id, {
1202
+ verificationReport: preGate.report,
1203
+ successCriteria: preGate.task.successCriteria
1204
+ });
1205
+ }
1206
+ }
1207
+ const result = await transitionTask(projectRoot, input.boardId, input.taskId, {
1208
+ to: input.lifecycleStage,
1209
+ actor: input.author,
1210
+ comment: input.transitionComment,
1211
+ ...input.transitionAction !== void 0 ? { action: input.transitionAction } : {},
1212
+ ...input.tickChecks !== void 0 ? { tickChecks: input.tickChecks } : {},
1213
+ ...input.attachmentUrl !== void 0 ? {
1214
+ attachment: {
1215
+ url: input.attachmentUrl,
1216
+ type: input.attachmentType ?? "url",
1217
+ ...input.attachmentTitle !== void 0 ? { title: input.attachmentTitle } : {}
1218
+ }
1219
+ } : {},
1220
+ patch: taskPatch(input)
1221
+ });
1222
+ if (result && input.lifecycleStage === "done" && result.task.verificationReport) {
1223
+ recordKanbanVerificationEvidence(ctx, result.task.verificationReport);
1224
+ }
1225
+ return result ? okTask(result.board, result.task, `Task advanced to ${result.transition.to}.`) : fail("Board or task not found.");
1226
+ }
1227
+ case "repair_managed_projection": {
1228
+ if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1229
+ return fail(
1230
+ "repair_managed_projection requires boardId, taskId, author, and transitionComment."
1231
+ );
1232
+ }
1233
+ const result = await repairManagedTaskProjection(projectRoot, input.boardId, input.taskId, {
1234
+ actor: input.author,
1235
+ comment: input.transitionComment
1236
+ });
1237
+ return result ? okTask(
1238
+ result.board,
1239
+ result.task,
1240
+ "Managed card projection repaired from lifecycle history."
1241
+ ) : fail("Board or task not found.");
1242
+ }
1243
+ case "move_task": {
1244
+ if (!input.boardId || !input.taskId || !input.targetColumnId) {
1245
+ return fail("move_task requires boardId, taskId, and targetColumnId.");
1246
+ }
1247
+ const board = await moveTask(
1248
+ projectRoot,
1249
+ input.boardId,
1250
+ input.taskId,
1251
+ input.targetColumnId,
1252
+ input.order
1253
+ );
1254
+ return board ? okBoard(board, "Task moved.") : fail("Move failed.");
1255
+ }
1256
+ case "delete_task": {
1257
+ if (!input.boardId || !input.taskId) return fail("delete_task requires boardId and taskId.");
1258
+ const board = await removeTask(projectRoot, input.boardId, input.taskId);
1259
+ if (board && ctx.currentKanbanTaskId === input.taskId) {
1260
+ ctx.setCurrentKanbanTask?.(void 0, ctx.currentKanbanBoardId);
1261
+ }
1262
+ return board ? okBoard(board, "Task deleted.") : fail("Task not found.");
1263
+ }
1264
+ case "set_chain": {
1265
+ if (!input.boardId || !input.taskIds?.length) {
1266
+ return fail("set_chain requires boardId and taskIds.");
1267
+ }
1268
+ const result = await setTaskChain(projectRoot, input.boardId, {
1269
+ taskIds: input.taskIds,
1270
+ ...input.chainId !== void 0 ? { chainId: input.chainId } : {},
1271
+ ...input.enforceDependencies !== void 0 ? { enforceDependencies: input.enforceDependencies } : {}
1272
+ });
1273
+ return result ? {
1274
+ ok: true,
1275
+ message: `Chain set: ${result.chainId}`,
1276
+ board: result.board,
1277
+ chain: result.tasks
1278
+ } : fail("Board or task not found.");
1279
+ }
1280
+ case "get_chain": {
1281
+ if (!input.boardId || !(input.taskId || input.chainId)) {
1282
+ return fail("get_chain requires boardId and taskId or chainId.");
1283
+ }
1284
+ const result = await getTaskChain(
1285
+ projectRoot,
1286
+ input.boardId,
1287
+ input.taskId ?? input.chainId ?? ""
1288
+ );
1289
+ return result ? {
1290
+ ok: true,
1291
+ message: `Chain loaded: ${result.chainId}`,
1292
+ board: result.board,
1293
+ chain: result.tasks
1294
+ } : fail("Chain not found.");
1295
+ }
1296
+ case "claim_task": {
1297
+ const result = await claimReadyTask(projectRoot, {
1298
+ ...input.boardId !== void 0 ? { boardId: input.boardId } : {},
1299
+ ...input.taskId !== void 0 ? { taskId: input.taskId } : {},
1300
+ ...assignmentInput(input),
1301
+ status: input.assignmentStatus ?? "queued"
1302
+ });
1303
+ return result ? okTask(result.board, result.task, "Task claimed.") : fail("No ready kanban task matched the claim.");
1304
+ }
1305
+ case "release_task": {
1306
+ if (!input.boardId || !input.taskId) {
1307
+ return fail("release_task requires boardId and taskId.");
1308
+ }
1309
+ const board = await releaseTaskClaim(projectRoot, input.boardId, input.taskId, {
1310
+ ...input.releaseStatus !== void 0 ? { status: input.releaseStatus } : {},
1311
+ ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
1312
+ ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {}
1313
+ });
1314
+ return board ? okBoard(board, "Task claim released.") : fail("Task not found.");
1315
+ }
1316
+ case "assign_task": {
1317
+ if (!input.boardId || !input.taskId) return fail("assign_task requires boardId and taskId.");
1318
+ const board = await assignTask(
1319
+ projectRoot,
1320
+ input.boardId,
1321
+ input.taskId,
1322
+ assignmentInput(input)
1323
+ );
1324
+ return board ? okBoard(board, "Task assigned.") : fail("Task not found.");
1325
+ }
1326
+ case "mark_assignment": {
1327
+ if (!input.boardId || !input.taskId)
1328
+ return fail("mark_assignment requires boardId and taskId.");
1329
+ const assignmentStatus = input.assignmentStatus ?? (input.status === "completed" ? "completed" : input.error ? "failed" : void 0);
1330
+ const board = await updateTaskAssignment(
1331
+ projectRoot,
1332
+ input.boardId,
1333
+ input.taskId,
1334
+ {
1335
+ ...assignmentStatus !== void 0 ? { status: assignmentStatus } : {},
1336
+ ...input.subagentId !== void 0 ? { subagentId: input.subagentId } : {},
1337
+ ...input.runTaskId !== void 0 ? { runTaskId: input.runTaskId } : {},
1338
+ ...input.lastResult !== void 0 ? { lastResult: input.lastResult } : {},
1339
+ ...input.error !== void 0 ? { error: input.error } : {},
1340
+ ...input.agentId !== void 0 ? { agentId: input.agentId } : {},
1341
+ ...input.leaseId !== void 0 ? { leaseId: input.leaseId } : {},
1342
+ ...input.claimedAt !== void 0 ? { claimedAt: input.claimedAt } : {},
1343
+ ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1344
+ ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1345
+ ...input.attempt !== void 0 ? { attempt: input.attempt } : {},
1346
+ ...input.maxAttempts !== void 0 ? { maxAttempts: input.maxAttempts } : {}
1347
+ },
1348
+ input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
1349
+ );
1350
+ if (!board) return fail("Task not found.");
1351
+ if (assignmentStatus === "completed" && board.lifecycle?.mode !== "managed") {
1352
+ const envGate = readEnvGateEnforcement();
1353
+ const finalized = await finalizeTaskCompletion(projectRoot, board.id, input.taskId, {
1354
+ ...board.completionGate === void 0 && envGate !== void 0 ? { enforcement: envGate } : {},
1355
+ ...ctx.agentId !== void 0 ? { eventContext: { actor: ctx.agentId } } : {}
1356
+ });
1357
+ if (finalized) {
1358
+ if (finalized.gate.report) {
1359
+ recordKanbanVerificationEvidence(ctx, finalized.gate.report);
1360
+ }
1361
+ const gateSummary = {
1362
+ enforcement: finalized.gate.enforcement,
1363
+ allowed: finalized.gate.allowed,
1364
+ verdict: finalized.gate.verdict,
1365
+ issues: finalized.gate.issues.map((issue) => issue.message)
1366
+ };
1367
+ 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(" | ")}`;
1368
+ return {
1369
+ ...okTask(finalized.board, finalized.task, `Assignment updated. ${gateMessage}`),
1370
+ gate: gateSummary
1371
+ };
1372
+ }
1373
+ } else if (board.lifecycle?.mode === "managed") {
1374
+ const managedTask = board.tasks.find((candidate) => candidate.id === input.taskId);
1375
+ const stage = managedTask?.lifecycle?.currentStage;
1376
+ const actor = ctx.agentId ?? "kanban-agent";
1377
+ let transitionResult = null;
1378
+ const lifecycleWarnings = [];
1379
+ if (assignmentStatus === "running" && stage === "todo") {
1380
+ try {
1381
+ transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
1382
+ to: "running",
1383
+ actor,
1384
+ comment: "Work started."
1385
+ });
1386
+ } catch (err) {
1387
+ lifecycleWarnings.push(
1388
+ `Lifecycle transition to Running deferred: ${stripLifecycleIssues(err instanceof Error ? err.message : String(err))}`
1389
+ );
1390
+ }
1391
+ }
1392
+ if (assignmentStatus === "completed" && stage === "running") {
1393
+ const comment = typeof input.lastResult === "string" && input.lastResult.trim().length > 0 ? input.lastResult.trim().slice(0, 1e3) : "Work completed.";
1394
+ try {
1395
+ transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
1396
+ to: "review",
1397
+ actor,
1398
+ comment,
1399
+ attachment: {
1400
+ url: `kanban://task/${input.taskId}/result`,
1401
+ title: "Worker completion result",
1402
+ type: "file"
1403
+ },
1404
+ patch: {
1405
+ ...input.agentId !== void 0 ? { assignedAgent: input.agentId } : {}
1406
+ }
1407
+ });
1408
+ } catch (err) {
1409
+ lifecycleWarnings.push(
1410
+ `Lifecycle transition to Review failed: ${stripLifecycleIssues(err instanceof Error ? err.message : String(err))}`
1411
+ );
1412
+ }
1413
+ if (transitionResult) {
1414
+ const hasCriteria = (transitionResult.task.successCriteria?.length ?? 0) > 0 || transitionResult.task.atomic === true;
1415
+ if (hasCriteria) {
1416
+ try {
1417
+ const verResult = await verifyTaskCompletion2(projectRoot, board.id, input.taskId);
1418
+ if (verResult.report) {
1419
+ recordKanbanVerificationEvidence(ctx, verResult.report);
1420
+ }
1421
+ await updateTask2(projectRoot, board.id, input.taskId, {
1422
+ verificationReport: verResult.report,
1423
+ successCriteria: verResult.task.successCriteria
1424
+ });
1425
+ const verdict = verResult.report.verdict;
1426
+ if (verdict === "passed" && !resolveAutoAccept(board)) {
1427
+ lifecycleWarnings.push(
1428
+ "Verification passed, but this board does not auto-accept. The card is in Review awaiting an explicit transition_task to done."
1429
+ );
1430
+ } else if (verdict === "passed") {
1431
+ try {
1432
+ const doneResult = await transitionTask(projectRoot, board.id, input.taskId, {
1433
+ to: "done",
1434
+ actor,
1435
+ action: "Automated acceptance after verification",
1436
+ comment: "Auto-accepted: verification passed.",
1437
+ attachment: {
1438
+ url: `kanban://task/${input.taskId}/verification`,
1439
+ title: "Auto-verification result",
1440
+ type: "file"
1441
+ }
1442
+ });
1443
+ transitionResult = doneResult;
1444
+ } catch (acceptErr) {
1445
+ lifecycleWarnings.push(
1446
+ `Auto-accept to Done deferred: ${acceptErr instanceof Error ? acceptErr.message : String(acceptErr)}`
1447
+ );
1448
+ }
1449
+ } else {
1450
+ lifecycleWarnings.push(
1451
+ `Verification verdict: ${verdict} \u2014 card left in Review for manual acceptance.`
1452
+ );
1453
+ }
1454
+ } catch (verifyErr) {
1455
+ lifecycleWarnings.push(
1456
+ `Auto-verification error: ${verifyErr instanceof Error ? verifyErr.message : String(verifyErr)}`
1457
+ );
1458
+ }
1459
+ } else {
1460
+ lifecycleWarnings.push(
1461
+ "No automatic success criteria \u2014 card left in Review for manual verification."
1462
+ );
1463
+ }
1464
+ }
1465
+ }
1466
+ const responseBoard = transitionResult?.board ?? board;
1467
+ const responseTask = transitionResult?.task ?? managedTask;
1468
+ const msgParts = ["Assignment updated."];
1469
+ if (transitionResult) {
1470
+ msgParts.push(`Card advanced to ${transitionResult.transition.to}.`);
1471
+ }
1472
+ for (const w of lifecycleWarnings) msgParts.push(`Warning: ${w}`);
1473
+ return okTask(responseBoard, responseTask, msgParts.join(" "));
1474
+ }
1475
+ return okBoard(board, "Assignment updated.");
1476
+ }
1477
+ case "heartbeat_assignment": {
1478
+ if (!input.boardId || !input.taskId) {
1479
+ return fail("heartbeat_assignment requires boardId and taskId.");
1480
+ }
1481
+ const board = await heartbeatTaskAssignment(projectRoot, input.boardId, input.taskId, {
1482
+ ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1483
+ ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1484
+ ...input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
1485
+ });
1486
+ return board ? okBoard(board, "Assignment heartbeat updated.") : fail("Task assignment not found.");
1487
+ }
1488
+ case "recover_stale": {
1489
+ if (!input.boardId) return fail("recover_stale requires boardId.");
1490
+ const policyFields = [
1491
+ input.recoveryPolicyFailOnCostCeiling !== void 0,
1492
+ input.recoveryPolicyReleaseOnFailureKinds !== void 0,
1493
+ input.recoveryPolicyReleaseOnHeartbeatDue !== void 0,
1494
+ input.recoveryPolicyRetryPolicyOverride !== void 0
1495
+ ].some(Boolean);
1496
+ const result = await recoverStaleTaskAssignments(projectRoot, input.boardId, {
1497
+ ...input.recoveryMode !== void 0 ? { mode: input.recoveryMode } : {},
1498
+ ...input.recoveryNow !== void 0 ? { now: input.recoveryNow } : {},
1499
+ ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
1500
+ ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {},
1501
+ ...policyFields ? {
1502
+ policy: {
1503
+ ...input.recoveryPolicyFailOnCostCeiling !== void 0 ? { failWhenCostCeilingSet: input.recoveryPolicyFailOnCostCeiling } : {},
1504
+ ...input.recoveryPolicyReleaseOnFailureKinds !== void 0 ? {
1505
+ releaseOnFailureKinds: input.recoveryPolicyReleaseOnFailureKinds
1506
+ } : {},
1507
+ ...input.recoveryPolicyReleaseOnHeartbeatDue !== void 0 ? {
1508
+ releaseOnHeartbeatDue: input.recoveryPolicyReleaseOnHeartbeatDue
1509
+ } : {},
1510
+ ...input.recoveryPolicyRetryPolicyOverride !== void 0 ? {
1511
+ retryPolicyOverride: input.recoveryPolicyRetryPolicyOverride
1512
+ } : {}
1513
+ }
1514
+ } : {}
1515
+ });
1516
+ return result ? {
1517
+ ok: true,
1518
+ message: `Recovered ${result.tasks.length} stale assignment(s).`,
1519
+ board: result.board,
1520
+ recoveredTasks: result.tasks
1521
+ } : { ok: true, message: "No stale assignment matched.", recoveredTasks: [] };
1522
+ }
1523
+ default:
1524
+ return void 0;
1525
+ }
1526
+ }
1527
+
1528
+ // src/kanban-presence.ts
1529
+ import { touchKanbanPresence as touchKanbanPresence2 } from "@wrongstack/kanban";
1530
+ function createKanbanPresenceWrapper(projectRoot, input, ctx) {
1531
+ return async (result) => {
1532
+ const boardId = result.board?.id ?? input.boardId;
1533
+ if (!result.ok || !boardId || !ctx.session?.id || !ctx.agentId) return result;
1534
+ try {
1535
+ const board = await touchKanbanPresence2(projectRoot, boardId, {
1536
+ sessionId: ctx.session.id,
1537
+ agentId: ctx.agentId,
1538
+ agentName: ctx.agentName,
1539
+ taskId: input.taskId ?? result.task?.id,
1540
+ runTaskId: input.runTaskId
1541
+ });
1542
+ return board ? { ...result, board } : result;
1543
+ } catch {
1544
+ return result;
1545
+ }
1546
+ };
1547
+ }
1548
+
1549
+ // src/kanban-serializer.ts
1550
+ var KANBAN_BOARD_TRANSCRIPT_BYTE_CAP = 16384;
1551
+ var KANBAN_FULL_BOARD_ACTIONS = /* @__PURE__ */ new Set([
1552
+ "get_board",
1553
+ "export_markdown",
1554
+ "export_task_graph"
1555
+ ]);
1556
+ function serializeKanbanOutput(output, input) {
1557
+ const action = input && typeof input === "object" ? input.action : void 0;
1558
+ const board = output.board;
1559
+ if (board) {
1560
+ const keepFull = typeof action === "string" && KANBAN_FULL_BOARD_ACTIONS.has(action);
1561
+ let boardBytes = 0;
1562
+ if (!keepFull) {
1563
+ try {
1564
+ boardBytes = Buffer.byteLength(JSON.stringify(board), "utf8");
1565
+ } catch {
1566
+ boardBytes = 0;
1567
+ }
1568
+ }
1569
+ if (!keepFull && boardBytes > KANBAN_BOARD_TRANSCRIPT_BYTE_CAP) {
1570
+ const columns = {};
1571
+ for (const column of board.columns) {
1572
+ columns[column.title || column.id] = board.tasks.filter(
1573
+ (task) => task.columnId === column.id
1574
+ ).length;
1575
+ }
1576
+ const compact = {
1577
+ ...output,
1578
+ board: {
1579
+ id: board.id,
1580
+ title: board.title,
1581
+ columns,
1582
+ totalTasks: board.tasks.length,
1583
+ note: `Full board (${boardBytes} bytes) omitted from the transcript; use get_board to load it.`
1584
+ }
1585
+ };
1586
+ return JSON.stringify(compact, null, 2);
1587
+ }
1588
+ }
1589
+ return JSON.stringify(output, null, 2);
1590
+ }
1591
+
727
1592
  // src/kanban-tool-schema.ts
728
1593
  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.";
729
1594
  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.';
@@ -1052,74 +1917,6 @@ var KANBAN_INPUT_SCHEMA = {
1052
1917
  required: ["action"]
1053
1918
  };
1054
1919
 
1055
- // src/session-kanban.ts
1056
- import { getSharedProjectMailbox } from "@wrongstack/core/coordination";
1057
- import {
1058
- loadPlan,
1059
- loadTasks,
1060
- mutatePlan,
1061
- mutateTasks
1062
- } from "@wrongstack/core/storage";
1063
- import { deserializeTaskGraph } from "@wrongstack/core/tasking";
1064
- import { formatTodosForModel, resolveWstackPaths } from "@wrongstack/core/utils";
1065
- import {
1066
- bridgeKanbanSupervisor,
1067
- compactSessionMirrorBoard,
1068
- createBoard,
1069
- DEFAULT_COLUMNS,
1070
- getBoard as getBoard2,
1071
- getDependencyReadinessIssues,
1072
- getKanbanOrchestrationSnapshot,
1073
- listBoards,
1074
- pruneSessionBoards,
1075
- removeBoard,
1076
- syncBoardFromTaskGraph,
1077
- touchKanbanPresence as touchKanbanPresence2,
1078
- updateBoard
1079
- } from "@wrongstack/kanban";
1080
- var SESSION_KANBAN_COLUMNS = DEFAULT_COLUMNS.map((column) => ({
1081
- ...column
1082
- }));
1083
- function taskFileToSerializedGraph(tasks, sessionId) {
1084
- const graphId = `session:${sessionId}`;
1085
- const ids = new Set(tasks.map((task) => task.id));
1086
- const nodes = tasks.map((task, index) => ({
1087
- id: task.id,
1088
- title: task.title,
1089
- description: task.description ?? "",
1090
- type: task.type,
1091
- priority: task.priority,
1092
- status: task.status,
1093
- specRequirementId: `${graphId}:${task.id}`,
1094
- ...task.assignee ? { assignee: task.assignee } : {},
1095
- ...task.estimateHours !== void 0 ? { estimateHours: task.estimateHours } : {},
1096
- createdAt: index,
1097
- updatedAt: index
1098
- }));
1099
- const edges = tasks.flatMap(
1100
- (task) => (task.dependsOn ?? []).filter((dependency) => ids.has(dependency)).map((dependency) => ({
1101
- id: `${dependency}->${task.id}`,
1102
- from: dependency,
1103
- to: task.id,
1104
- type: "depends_on"
1105
- }))
1106
- );
1107
- const hasIncoming = new Set(edges.map((edge) => edge.to));
1108
- const rootNodes = nodes.filter((node) => !hasIncoming.has(node.id)).map((node) => node.id);
1109
- return {
1110
- // Keep the historical graph id so existing mirrored task cards are reused.
1111
- id: graphId,
1112
- specId: graphId,
1113
- requiredRequirementIds: nodes.map((node) => node.specRequirementId),
1114
- title: "Session tasks",
1115
- nodes,
1116
- edges,
1117
- rootNodes: rootNodes.length ? rootNodes : nodes[0] ? [nodes[0].id] : [],
1118
- createdAt: 0,
1119
- updatedAt: 0
1120
- };
1121
- }
1122
-
1123
1920
  // src/kanban.ts
1124
1921
  var kanbanTool = {
1125
1922
  name: "kanban",
@@ -1127,8 +1924,6 @@ var kanbanTool = {
1127
1924
  description: KANBAN_TOOL_DESCRIPTION,
1128
1925
  usageHint: KANBAN_TOOL_USAGE_HINT,
1129
1926
  permission: "confirm",
1130
- // WS-046: gives permission decisions something to key on.
1131
- // The action performed; kanban has no single file or path subject.
1132
1927
  subjectKey: "action",
1133
1928
  mutating: true,
1134
1929
  capabilities: ["fs.write"],
@@ -1143,873 +1938,29 @@ var kanbanTool = {
1143
1938
  const result = await (async () => {
1144
1939
  const decompositionResult = await handleKanbanDecompositionAction(projectRoot, input, ctx);
1145
1940
  if (decompositionResult !== void 0) return decompositionResult;
1146
- switch (input.action) {
1147
- case "list_boards": {
1148
- const boards = await listBoards2(projectRoot);
1149
- return { ok: true, message: `${boards.length} board(s).`, boards };
1150
- }
1151
- case "get_board": {
1152
- const board = await requireBoard(projectRoot, input.boardId);
1153
- return board ? okBoard(board) : fail("Board not found.");
1154
- }
1155
- case "create_board": {
1156
- if (!input.title) return fail("create_board requires title.");
1157
- const existing = (await listBoards2(projectRoot)).filter(
1158
- (candidate) => (candidate.kind ?? "project") === "project"
1159
- );
1160
- const board = await createBoard2(projectRoot, boardCreateInput(input, input.title));
1161
- 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(
1162
- ", "
1163
- )}${existing.length > 3 ? ", \u2026" : ""}. If this work belongs to one of them, add_task there instead and delete this board.` : "";
1164
- return { ok: true, message: `Board created: ${board.title}.${note}`, board };
1165
- }
1166
- case "update_board": {
1167
- if (!input.boardId) return fail("update_board requires boardId.");
1168
- const board = await updateBoard2(projectRoot, input.boardId, boardUpdatePatch(input));
1169
- return board ? okBoard(board, "Board updated.") : fail("Board not found.");
1170
- }
1171
- case "adopt_managed_lifecycle": {
1172
- if (!input.boardId || !input.author || !input.transitionComment) {
1173
- return fail(
1174
- "adopt_managed_lifecycle requires boardId, author, transitionComment, and five ordered columns."
1175
- );
1176
- }
1177
- if (input.columns?.length !== 5) {
1178
- return fail(
1179
- "adopt_managed_lifecycle columns must be ordered as backlog, todo, running, review, done."
1180
- );
1181
- }
1182
- const [backlog, todo, running, review, done] = input.columns;
1183
- if (!backlog || !todo || !running || !review || !done) {
1184
- return fail("adopt_managed_lifecycle columns must contain five nonblank ids.");
1185
- }
1186
- const board = await adoptManagedLifecycle(projectRoot, input.boardId, {
1187
- columns: { backlog, todo, running, review, done },
1188
- actor: input.author,
1189
- comment: input.transitionComment
1190
- });
1191
- return board ? okBoard(board, "Managed lifecycle adopted without moving existing cards.") : fail("Board not found.");
1192
- }
1193
- // Adoption used to be a one-way door: the strict lifecycle carries
1194
- // acceptance-criteria, verification-report, review-evidence and
1195
- // one-stage-at-a-time gates, and nothing on the tool surface could
1196
- // undo it, so a board adopted once kept its ceremony forever. The
1197
- // gates are worth having where a fleet is supervised; they are not
1198
- // worth being unable to leave. Cards and columns are untouched.
1199
- case "release_managed_lifecycle": {
1200
- if (!input.boardId) return fail("release_managed_lifecycle requires boardId.");
1201
- const board = await updateBoard2(projectRoot, input.boardId, { lifecycle: null });
1202
- return board ? okBoard(
1203
- board,
1204
- "Managed lifecycle released; the board now tracks work without strict gates."
1205
- ) : fail("Board not found.");
1206
- }
1207
- case "duplicate_board": {
1208
- if (!input.boardId) return fail("duplicate_board requires boardId.");
1209
- const board = await duplicateBoard(
1210
- projectRoot,
1211
- input.boardId,
1212
- duplicateBoardOptions(input)
1213
- );
1214
- return board ? okBoard(board, "Board duplicated.") : fail("Board not found.");
1215
- }
1216
- case "delete_board": {
1217
- if (!input.boardId) return fail("delete_board requires boardId.");
1218
- const removed = await removeBoard2(projectRoot, input.boardId);
1219
- return { ok: removed, message: removed ? "Board deleted." : "Board not found." };
1220
- }
1221
- case "generate_board": {
1222
- if (!input.description) return fail("generate_board requires description.");
1223
- const boardInput = createBoardFromText({
1224
- description: input.description,
1225
- ...input.title !== void 0 ? { title: input.title } : {},
1226
- ...input.context !== void 0 ? { context: input.context } : {}
1227
- });
1228
- const board = await createBoard2(projectRoot, boardInput);
1229
- for (const taskInput2 of parseLinesIntoTasks(
1230
- input.description,
1231
- board.columns[0]?.id ?? "backlog"
1232
- )) {
1233
- await addTask(projectRoot, board.id, taskInput2);
1234
- }
1235
- return okBoard(await getBoard3(projectRoot, board.id) ?? board, "Board generated.");
1236
- }
1237
- case "export_markdown": {
1238
- const board = await requireBoard(projectRoot, input.boardId);
1239
- if (!board) return fail("Board not found.");
1240
- return {
1241
- ok: true,
1242
- message: "Board exported.",
1243
- board,
1244
- markdown: exportBoardAsMarkdown(board)
1245
- };
1246
- }
1247
- case "export_task_graph": {
1248
- if (!input.boardId) return fail("export_task_graph requires boardId.");
1249
- const exported = await exportBoardToTaskGraph(projectRoot, input.boardId, {
1250
- ...input.graphId !== void 0 ? { graphId: input.graphId } : {},
1251
- ...input.specId !== void 0 ? { specId: input.specId } : {},
1252
- ...input.title !== void 0 ? { title: input.title } : {},
1253
- ...input.preserveOriginTaskIds !== void 0 ? { preserveOriginTaskIds: input.preserveOriginTaskIds } : {},
1254
- ...input.includeArchived !== void 0 ? { includeArchived: input.includeArchived } : {}
1255
- });
1256
- if (!exported) return fail("Board not found.");
1257
- return {
1258
- ok: true,
1259
- message: `Task graph exported with ${exported.graph.nodes.size} node(s).`,
1260
- board: exported.board,
1261
- taskGraph: serializeTaskGraph(exported.graph)
1262
- };
1263
- }
1264
- case "sync_task_graph": {
1265
- if (!input.boardId || !input.taskGraph) {
1266
- return fail("sync_task_graph requires boardId and taskGraph.");
1267
- }
1268
- const graph = deserializeTaskGraph2(input.taskGraph);
1269
- const result2 = await syncBoardFromTaskGraph2(projectRoot, input.boardId, graph, {
1270
- ...input.title !== void 0 ? { title: input.title } : {},
1271
- ...input.description !== void 0 ? { description: input.description } : {},
1272
- ...input.tags !== void 0 ? { tags: input.tags } : {},
1273
- ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
1274
- ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
1275
- ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
1276
- ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {},
1277
- ...input.archiveMissingTasks !== void 0 ? { archiveMissingTasks: input.archiveMissingTasks } : {},
1278
- ...input.preserveManualDependencies !== void 0 ? { preserveManualDependencies: input.preserveManualDependencies } : {}
1279
- });
1280
- return result2 ? {
1281
- ok: true,
1282
- message: `Task graph synced: ${result2.createdTaskIds.length} created, ${result2.updatedTaskIds.length} updated, ${result2.archivedTaskIds.length} archived.`,
1283
- board: result2.board
1284
- } : fail("Board not found.");
1285
- }
1286
- case "create_from_graph": {
1287
- if (!input.taskGraph) return fail("create_from_graph requires taskGraph.");
1288
- const graph = deserializeTaskGraph2(input.taskGraph);
1289
- const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
1290
- ...input.title !== void 0 ? { title: input.title } : {},
1291
- ...input.description !== void 0 ? { description: input.description } : {},
1292
- ...input.tags !== void 0 ? { tags: input.tags } : {},
1293
- ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
1294
- ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
1295
- ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
1296
- ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {}
1297
- });
1298
- return {
1299
- ok: true,
1300
- message: `Created board "${board.title}" from task graph with ${board.tasks.length} tasks.`,
1301
- board
1302
- };
1303
- }
1304
- case "import_session_tasks": {
1305
- const taskPath = ctx.meta?.["task.path"];
1306
- if (!taskPath) return fail("No session task file for this session.");
1307
- const file = await loadTasks2(taskPath);
1308
- if (!file || file.tasks.length === 0) return fail("No session tasks to import.");
1309
- const sessionId = ctx.session?.id ?? file.sessionId ?? "session";
1310
- const graph = deserializeTaskGraph2(taskFileToSerializedGraph(file.tasks, sessionId));
1311
- const tags = ["session", `session:${sessionId}`];
1312
- const existing = (await listBoards2(projectRoot)).find(
1313
- (b) => b.tags?.includes(`session:${sessionId}`)
1314
- );
1315
- if (existing) {
1316
- const result2 = await syncBoardFromTaskGraph2(projectRoot, existing.id, graph, {
1317
- sourceSystem: "session",
1318
- tags,
1319
- archiveMissingTasks: true,
1320
- includeCompletedTasks: true
1321
- });
1322
- return result2 ? {
1323
- ok: true,
1324
- message: `Synced ${file.tasks.length} session tasks into board "${result2.board.title}".`,
1325
- board: result2.board
1326
- } : fail("Session board vanished mid-sync.");
1327
- }
1328
- const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
1329
- title: `Session tasks (${sessionId.slice(0, 8)})`,
1330
- sourceSystem: "session",
1331
- tags
1332
- });
1333
- return {
1334
- ok: true,
1335
- message: `Imported ${file.tasks.length} session tasks into new board "${board.title}".`,
1336
- board
1337
- };
1338
- }
1339
- case "search_tasks": {
1340
- const tasks = await searchKanban(projectRoot, {
1341
- query: input.query,
1342
- boardId: input.boardId,
1343
- assignedAgent: input.agentId,
1344
- status: input.status,
1345
- priority: input.priority,
1346
- label: input.labels?.[0],
1347
- chainId: input.chainId
1348
- });
1349
- return { ok: true, message: `${tasks.length} task(s) matched.`, tasks };
1350
- }
1351
- case "ready_tasks": {
1352
- const tasks = await listReadyTasks(projectRoot, {
1353
- query: input.query,
1354
- boardId: input.boardId,
1355
- assignedAgent: input.agentId,
1356
- priority: input.priority,
1357
- label: input.labels?.[0],
1358
- chainId: input.chainId,
1359
- limit: input.limit
1360
- });
1361
- return { ok: true, message: `${tasks.length} ready task(s).`, tasks };
1362
- }
1363
- case "snapshot": {
1364
- const snapshot = await getKanbanOrchestrationSnapshot2(projectRoot, {
1365
- query: input.query,
1366
- boardId: input.boardId,
1367
- assignedAgent: input.agentId,
1368
- status: input.status,
1369
- priority: input.priority,
1370
- label: input.labels?.[0],
1371
- chainId: input.chainId
1372
- });
1373
- return {
1374
- ok: true,
1375
- message: `${snapshot.ready.length} ready, ${snapshot.running.length} running, ${snapshot.blocked.length} blocked.`,
1376
- snapshot
1377
- };
1378
- }
1379
- case "add_task": {
1380
- if (!input.boardId || !input.title) return fail("add_task requires boardId and title.");
1381
- const result2 = await addTask(projectRoot, input.boardId, taskInput(input));
1382
- if (!result2) return fail("Board not found.");
1383
- return okTask(result2.board, result2.task, `Task added.${atomicityNudge(result2.task)}`);
1384
- }
1385
- case "split_task": {
1386
- if (!input.boardId || !input.taskId || !input.childTitles?.length) {
1387
- return fail("split_task requires boardId, taskId, and childTitles.");
1388
- }
1389
- return handleSplitTask(projectRoot, input, {});
1390
- }
1391
- case "merge_tasks": {
1392
- if (!input.boardId || !input.taskIds?.length || !input.title) {
1393
- return fail("merge_tasks requires boardId, taskIds, and title.");
1394
- }
1395
- const result2 = await mergeTasks(projectRoot, input.boardId, {
1396
- taskIds: input.taskIds,
1397
- title: input.title,
1398
- ...input.description !== void 0 ? { description: input.description } : {},
1399
- ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1400
- ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1401
- ...input.closeSourceTasks !== void 0 ? { closeSourceTasks: input.closeSourceTasks } : {}
1402
- });
1403
- return result2 ? okTask(result2.board, result2.task, "Tasks merged.") : fail("Board or task not found.");
1404
- }
1405
- case "copy_task": {
1406
- if (!input.boardId || !input.taskId || !input.targetBoardId) {
1407
- return fail("copy_task requires boardId, taskId, and targetBoardId.");
1408
- }
1409
- const result2 = await copyTaskToBoard(
1410
- projectRoot,
1411
- input.boardId,
1412
- input.taskId,
1413
- input.targetBoardId,
1414
- {
1415
- ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1416
- ...input.order !== void 0 ? { targetOrder: input.order } : {},
1417
- ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1418
- ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1419
- }
1420
- );
1421
- return result2 ? okTask(result2.targetBoard, result2.task, "Task copied to target board.") : fail("Board or task not found.");
1422
- }
1423
- case "transfer_task": {
1424
- if (!input.boardId || !input.taskId || !input.targetBoardId) {
1425
- return fail("transfer_task requires boardId, taskId, and targetBoardId.");
1426
- }
1427
- const result2 = await transferTaskToBoard(
1428
- projectRoot,
1429
- input.boardId,
1430
- input.taskId,
1431
- input.targetBoardId,
1432
- {
1433
- ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1434
- ...input.order !== void 0 ? { targetOrder: input.order } : {},
1435
- ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1436
- ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1437
- }
1438
- );
1439
- return result2 ? okTask(result2.targetBoard, result2.task, "Task transferred to target board.") : fail("Board or task not found.");
1440
- }
1441
- case "get_task": {
1442
- if (!input.boardId || !input.taskId)
1443
- return fail("get_task requires boardId and taskId.");
1444
- const task = await getTask(projectRoot, input.boardId, input.taskId);
1445
- return task ? { ok: true, message: "Task loaded.", task } : fail("Task not found.");
1446
- }
1447
- case "start_task": {
1448
- if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1449
- return fail("start_task requires boardId, taskId, author, and transitionComment.");
1450
- }
1451
- let board = await getBoard3(projectRoot, input.boardId);
1452
- let task = board?.tasks.find((candidate) => candidate.id === input.taskId);
1453
- if (!board || !task) return fail("Board or task not found.");
1454
- const readiness = evaluateContractGraphReadiness(board, task.id);
1455
- if (!readiness.ready) {
1456
- return fail(
1457
- `Task is not implementation-ready: ${readiness.issues.map((issue) => issue.message).join(" | ")}`
1458
- );
1459
- }
1460
- if (board.lifecycle?.mode !== "managed") {
1461
- const now = /* @__PURE__ */ new Date();
1462
- const assigned = await updateTaskAssignment(projectRoot, board.id, task.id, {
1463
- status: "running",
1464
- agentId: input.agentId ?? input.author,
1465
- leaseId: input.leaseId ?? randomUUID2(),
1466
- claimedAt: input.claimedAt ?? now.toISOString(),
1467
- heartbeatAt: input.heartbeatAt ?? now.toISOString(),
1468
- leaseExpiresAt: input.leaseExpiresAt ?? new Date(now.getTime() + 15 * 6e4).toISOString(),
1469
- attempt: input.attempt ?? 1,
1470
- maxAttempts: input.maxAttempts ?? 3
1471
- });
1472
- if (!assigned) return fail("Task assignment could not be started.");
1473
- const started = await updateTask2(projectRoot, board.id, task.id, {
1474
- status: "in_progress"
1475
- });
1476
- const current = started ?? assigned;
1477
- const claimed = task;
1478
- const currentTask = current.tasks.find((candidate) => candidate.id === claimed.id) ?? claimed;
1479
- ctx.setCurrentKanbanTask?.(currentTask.id, current.id);
1480
- return okTask(
1481
- current,
1482
- currentTask,
1483
- "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."
1484
- );
1485
- }
1486
- let stage = task.lifecycle?.currentStage;
1487
- if (stage === "backlog") {
1488
- const moved = await transitionTask(projectRoot, board.id, task.id, {
1489
- to: "todo",
1490
- actor: input.author,
1491
- comment: input.transitionComment
1492
- });
1493
- if (!moved) return fail("Task could not enter Todo.");
1494
- board = moved.board;
1495
- task = moved.task;
1496
- stage = task.lifecycle?.currentStage;
1497
- }
1498
- if (stage === "todo" || stage === "review") {
1499
- const now = /* @__PURE__ */ new Date();
1500
- const leaseId = input.leaseId ?? randomUUID2();
1501
- const assigned = await updateTaskAssignment(projectRoot, board.id, task.id, {
1502
- status: "running",
1503
- agentId: input.agentId ?? input.author,
1504
- leaseId,
1505
- claimedAt: input.claimedAt ?? now.toISOString(),
1506
- heartbeatAt: input.heartbeatAt ?? now.toISOString(),
1507
- leaseExpiresAt: input.leaseExpiresAt ?? new Date(now.getTime() + 15 * 6e4).toISOString(),
1508
- attempt: input.attempt ?? 1,
1509
- maxAttempts: input.maxAttempts ?? 3
1510
- });
1511
- if (!assigned) return fail("Task assignment could not be started.");
1512
- const moved = await transitionTask(projectRoot, board.id, task.id, {
1513
- to: "running",
1514
- actor: input.author,
1515
- comment: input.transitionComment
1516
- });
1517
- if (!moved) return fail("Task could not enter Running.");
1518
- board = moved.board;
1519
- task = moved.task;
1520
- stage = task.lifecycle?.currentStage;
1521
- }
1522
- if (stage !== "running" || task.assignment?.status !== "running") {
1523
- return fail(
1524
- `start_task only accepts Backlog, Todo, Review repair, or live Running cards (current: ${stage ?? "unknown"}).`
1525
- );
1526
- }
1527
- ctx.setCurrentKanbanTask(task.id, board.id);
1528
- return okTask(
1529
- board,
1530
- task,
1531
- "Task is active; runtime Kanban governance is now bound to this run."
1532
- );
1533
- }
1534
- case "update_task": {
1535
- if (!input.boardId || !input.taskId)
1536
- return fail("update_task requires boardId and taskId.");
1537
- const board = await updateTask2(
1538
- projectRoot,
1539
- input.boardId,
1540
- input.taskId,
1541
- taskPatch(input)
1542
- );
1543
- return board ? okBoard(board, "Task updated.") : fail("Task not found.");
1544
- }
1545
- case "transition_task": {
1546
- if (!input.boardId || !input.taskId || !input.lifecycleStage || !input.author || !input.transitionComment) {
1547
- return fail(
1548
- "transition_task requires boardId, taskId, lifecycleStage, author, and transitionComment."
1549
- );
1550
- }
1551
- if (input.lifecycleStage === "done") {
1552
- const boardBefore = await getBoard3(projectRoot, input.boardId);
1553
- const taskBefore = boardBefore ? await getTask(projectRoot, input.boardId, input.taskId) : null;
1554
- if (boardBefore && taskBefore && !taskBefore.verificationReport && (taskBefore.atomic || Boolean(taskBefore.successCriteria?.length))) {
1555
- const preGate = await verifyTaskCompletion2(
1556
- projectRoot,
1557
- input.boardId,
1558
- taskBefore.id,
1559
- {
1560
- persist: false
1561
- }
1562
- );
1563
- await updateTask2(projectRoot, input.boardId, taskBefore.id, {
1564
- verificationReport: preGate.report,
1565
- successCriteria: preGate.task.successCriteria
1566
- });
1567
- }
1568
- }
1569
- const result2 = await transitionTask(projectRoot, input.boardId, input.taskId, {
1570
- to: input.lifecycleStage,
1571
- actor: input.author,
1572
- comment: input.transitionComment,
1573
- ...input.transitionAction !== void 0 ? { action: input.transitionAction } : {},
1574
- ...input.tickChecks !== void 0 ? { tickChecks: input.tickChecks } : {},
1575
- ...input.attachmentUrl !== void 0 ? {
1576
- attachment: {
1577
- url: input.attachmentUrl,
1578
- type: input.attachmentType ?? "url",
1579
- ...input.attachmentTitle !== void 0 ? { title: input.attachmentTitle } : {}
1580
- }
1581
- } : {},
1582
- patch: taskPatch(input)
1583
- });
1584
- if (result2 && input.lifecycleStage === "done" && result2.task.verificationReport) {
1585
- recordKanbanVerificationEvidence(ctx, result2.task.verificationReport);
1586
- }
1587
- return result2 ? okTask(result2.board, result2.task, `Task advanced to ${result2.transition.to}.`) : fail("Board or task not found.");
1588
- }
1589
- case "repair_managed_projection": {
1590
- if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1591
- return fail(
1592
- "repair_managed_projection requires boardId, taskId, author, and transitionComment."
1593
- );
1594
- }
1595
- const result2 = await repairManagedTaskProjection(
1596
- projectRoot,
1597
- input.boardId,
1598
- input.taskId,
1599
- {
1600
- actor: input.author,
1601
- comment: input.transitionComment
1602
- }
1603
- );
1604
- return result2 ? okTask(
1605
- result2.board,
1606
- result2.task,
1607
- "Managed card projection repaired from lifecycle history."
1608
- ) : fail("Board or task not found.");
1609
- }
1610
- case "move_task": {
1611
- if (!input.boardId || !input.taskId || !input.targetColumnId) {
1612
- return fail("move_task requires boardId, taskId, and targetColumnId.");
1613
- }
1614
- const board = await moveTask(
1615
- projectRoot,
1616
- input.boardId,
1617
- input.taskId,
1618
- input.targetColumnId,
1619
- input.order
1620
- );
1621
- return board ? okBoard(board, "Task moved.") : fail("Move failed.");
1622
- }
1623
- case "delete_task": {
1624
- if (!input.boardId || !input.taskId)
1625
- return fail("delete_task requires boardId and taskId.");
1626
- const board = await removeTask(projectRoot, input.boardId, input.taskId);
1627
- if (board && ctx.currentKanbanTaskId === input.taskId) {
1628
- ctx.setCurrentKanbanTask?.(void 0, ctx.currentKanbanBoardId);
1629
- }
1630
- return board ? okBoard(board, "Task deleted.") : fail("Task not found.");
1631
- }
1632
- case "set_chain": {
1633
- if (!input.boardId || !input.taskIds?.length) {
1634
- return fail("set_chain requires boardId and taskIds.");
1635
- }
1636
- const result2 = await setTaskChain(projectRoot, input.boardId, {
1637
- taskIds: input.taskIds,
1638
- ...input.chainId !== void 0 ? { chainId: input.chainId } : {},
1639
- ...input.enforceDependencies !== void 0 ? { enforceDependencies: input.enforceDependencies } : {}
1640
- });
1641
- return result2 ? {
1642
- ok: true,
1643
- message: `Chain set: ${result2.chainId}`,
1644
- board: result2.board,
1645
- chain: result2.tasks
1646
- } : fail("Board or task not found.");
1647
- }
1648
- case "get_chain": {
1649
- if (!input.boardId || !(input.taskId || input.chainId)) {
1650
- return fail("get_chain requires boardId and taskId or chainId.");
1651
- }
1652
- const result2 = await getTaskChain(
1653
- projectRoot,
1654
- input.boardId,
1655
- input.taskId ?? input.chainId ?? ""
1656
- );
1657
- return result2 ? {
1658
- ok: true,
1659
- message: `Chain loaded: ${result2.chainId}`,
1660
- board: result2.board,
1661
- chain: result2.tasks
1662
- } : fail("Chain not found.");
1663
- }
1664
- case "claim_task": {
1665
- const result2 = await claimReadyTask(projectRoot, {
1666
- ...input.boardId !== void 0 ? { boardId: input.boardId } : {},
1667
- ...input.taskId !== void 0 ? { taskId: input.taskId } : {},
1668
- ...assignmentInput(input),
1669
- status: input.assignmentStatus ?? "queued"
1670
- });
1671
- return result2 ? okTask(result2.board, result2.task, "Task claimed.") : fail("No ready kanban task matched the claim.");
1672
- }
1673
- case "release_task": {
1674
- if (!input.boardId || !input.taskId) {
1675
- return fail("release_task requires boardId and taskId.");
1676
- }
1677
- const board = await releaseTaskClaim(projectRoot, input.boardId, input.taskId, {
1678
- ...input.releaseStatus !== void 0 ? { status: input.releaseStatus } : {},
1679
- ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
1680
- ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {}
1681
- });
1682
- return board ? okBoard(board, "Task claim released.") : fail("Task not found.");
1683
- }
1684
- case "assign_task": {
1685
- if (!input.boardId || !input.taskId)
1686
- return fail("assign_task requires boardId and taskId.");
1687
- const board = await assignTask(
1688
- projectRoot,
1689
- input.boardId,
1690
- input.taskId,
1691
- assignmentInput(input)
1692
- );
1693
- return board ? okBoard(board, "Task assigned.") : fail("Task not found.");
1694
- }
1695
- case "mark_assignment": {
1696
- if (!input.boardId || !input.taskId)
1697
- return fail("mark_assignment requires boardId and taskId.");
1698
- const assignmentStatus = input.assignmentStatus ?? (input.status === "completed" ? "completed" : input.error ? "failed" : void 0);
1699
- const board = await updateTaskAssignment(
1700
- projectRoot,
1701
- input.boardId,
1702
- input.taskId,
1703
- {
1704
- ...assignmentStatus !== void 0 ? { status: assignmentStatus } : {},
1705
- ...input.subagentId !== void 0 ? { subagentId: input.subagentId } : {},
1706
- ...input.runTaskId !== void 0 ? { runTaskId: input.runTaskId } : {},
1707
- ...input.lastResult !== void 0 ? { lastResult: input.lastResult } : {},
1708
- ...input.error !== void 0 ? { error: input.error } : {},
1709
- ...input.agentId !== void 0 ? { agentId: input.agentId } : {},
1710
- ...input.leaseId !== void 0 ? { leaseId: input.leaseId } : {},
1711
- ...input.claimedAt !== void 0 ? { claimedAt: input.claimedAt } : {},
1712
- ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1713
- ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1714
- ...input.attempt !== void 0 ? { attempt: input.attempt } : {},
1715
- ...input.maxAttempts !== void 0 ? { maxAttempts: input.maxAttempts } : {}
1716
- },
1717
- // Ownership fence: when expectedLeaseId is supplied, the write is
1718
- // applied only if the current assignment still holds this lease.
1719
- // This prevents a recovered+reassigned stale worker's terminal
1720
- // mark_assignment from overwriting the successor's state. The check
1721
- // is atomic inside updateTaskAssignment's mutateBoard lock.
1722
- input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
1723
- );
1724
- if (!board) return fail("Task not found.");
1725
- if (assignmentStatus === "completed" && board.lifecycle?.mode !== "managed") {
1726
- const envGate = readEnvGateEnforcement();
1727
- const finalized = await finalizeTaskCompletion(projectRoot, board.id, input.taskId, {
1728
- ...board.completionGate === void 0 && envGate !== void 0 ? { enforcement: envGate } : {},
1729
- ...ctx.agentId !== void 0 ? { eventContext: { actor: ctx.agentId } } : {}
1730
- });
1731
- if (finalized) {
1732
- if (finalized.gate.report) {
1733
- recordKanbanVerificationEvidence(ctx, finalized.gate.report);
1734
- }
1735
- const gateSummary = {
1736
- enforcement: finalized.gate.enforcement,
1737
- allowed: finalized.gate.allowed,
1738
- verdict: finalized.gate.verdict,
1739
- issues: finalized.gate.issues.map((issue) => issue.message)
1740
- };
1741
- const gateMessage = finalized.gate.allowed ? `Completion gate ${finalized.gate.verdict === "skipped" ? "skipped" : "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(" | ")}`;
1742
- return {
1743
- ...okTask(finalized.board, finalized.task, `Assignment updated. ${gateMessage}`),
1744
- gate: gateSummary
1745
- };
1746
- }
1747
- } else if (board.lifecycle?.mode === "managed") {
1748
- const managedTask = board.tasks.find((candidate) => candidate.id === input.taskId);
1749
- const stage = managedTask?.lifecycle?.currentStage;
1750
- const actor = ctx.agentId ?? "kanban-agent";
1751
- let transitionResult = null;
1752
- const lifecycleWarnings = [];
1753
- if (assignmentStatus === "running" && stage === "todo") {
1754
- try {
1755
- transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
1756
- to: "running",
1757
- actor,
1758
- comment: "Work started."
1759
- });
1760
- } catch (err) {
1761
- lifecycleWarnings.push(
1762
- `Lifecycle transition to Running deferred: ${stripLifecycleIssues(err instanceof Error ? err.message : String(err))}`
1763
- );
1764
- }
1765
- }
1766
- if (assignmentStatus === "completed" && stage === "running") {
1767
- const comment = typeof input.lastResult === "string" && input.lastResult.trim().length > 0 ? input.lastResult.trim().slice(0, 1e3) : "Work completed.";
1768
- try {
1769
- transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
1770
- to: "review",
1771
- actor,
1772
- comment,
1773
- attachment: {
1774
- url: `kanban://task/${input.taskId}/result`,
1775
- title: "Worker completion result",
1776
- type: "file"
1777
- },
1778
- patch: {
1779
- // Only patch non-description fields so the
1780
- // original card description is preserved.
1781
- ...input.agentId !== void 0 ? { assignedAgent: input.agentId } : {}
1782
- }
1783
- });
1784
- } catch (err) {
1785
- lifecycleWarnings.push(
1786
- `Lifecycle transition to Review failed: ${stripLifecycleIssues(err instanceof Error ? err.message : String(err))}`
1787
- );
1788
- }
1789
- if (transitionResult) {
1790
- const hasCriteria = (transitionResult.task.successCriteria?.length ?? 0) > 0 || transitionResult.task.atomic === true;
1791
- if (hasCriteria) {
1792
- try {
1793
- const verResult = await verifyTaskCompletion2(
1794
- projectRoot,
1795
- board.id,
1796
- input.taskId
1797
- );
1798
- if (verResult.report) {
1799
- recordKanbanVerificationEvidence(ctx, verResult.report);
1800
- }
1801
- await updateTask2(projectRoot, board.id, input.taskId, {
1802
- verificationReport: verResult.report,
1803
- successCriteria: verResult.task.successCriteria
1804
- });
1805
- const verdict = verResult.report.verdict;
1806
- if (verdict === "passed" && !resolveAutoAccept(board)) {
1807
- lifecycleWarnings.push(
1808
- "Verification passed, but this board does not auto-accept. The card is in Review awaiting an explicit transition_task to done."
1809
- );
1810
- } else if (verdict === "passed") {
1811
- try {
1812
- const doneResult = await transitionTask(
1813
- projectRoot,
1814
- board.id,
1815
- input.taskId,
1816
- {
1817
- to: "done",
1818
- actor,
1819
- action: "Automated acceptance after verification",
1820
- comment: "Auto-accepted: verification passed.",
1821
- attachment: {
1822
- url: `kanban://task/${input.taskId}/verification`,
1823
- title: "Auto-verification result",
1824
- type: "file"
1825
- }
1826
- }
1827
- );
1828
- transitionResult = doneResult;
1829
- } catch (acceptErr) {
1830
- lifecycleWarnings.push(
1831
- `Auto-accept to Done deferred: ${acceptErr instanceof Error ? acceptErr.message : String(acceptErr)}`
1832
- );
1833
- }
1834
- } else {
1835
- lifecycleWarnings.push(
1836
- `Verification verdict: ${verdict} \u2014 card left in Review for manual acceptance.`
1837
- );
1838
- }
1839
- } catch (verifyErr) {
1840
- lifecycleWarnings.push(
1841
- `Auto-verification error: ${verifyErr instanceof Error ? verifyErr.message : String(verifyErr)}`
1842
- );
1843
- }
1844
- } else {
1845
- lifecycleWarnings.push(
1846
- "No automatic success criteria \u2014 card left in Review for manual verification."
1847
- );
1848
- }
1849
- }
1850
- }
1851
- const responseBoard = transitionResult?.board ?? board;
1852
- const responseTask = transitionResult?.task ?? managedTask;
1853
- const msgParts = ["Assignment updated."];
1854
- if (transitionResult) {
1855
- msgParts.push(`Card advanced to ${transitionResult.transition.to}.`);
1856
- }
1857
- for (const w of lifecycleWarnings) msgParts.push(`Warning: ${w}`);
1858
- return okTask(responseBoard, responseTask, msgParts.join(" "));
1859
- }
1860
- return okBoard(board, "Assignment updated.");
1861
- }
1862
- case "heartbeat_assignment": {
1863
- if (!input.boardId || !input.taskId) {
1864
- return fail("heartbeat_assignment requires boardId and taskId.");
1865
- }
1866
- const board = await heartbeatTaskAssignment(projectRoot, input.boardId, input.taskId, {
1867
- ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1868
- ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1869
- // Ownership fence: when expectedLeaseId is supplied, the renewal
1870
- // is applied only if the current assignment still holds this lease.
1871
- // This prevents a recovered+reassigned stale worker's heartbeat
1872
- // from renewing the successor's lease. The check is atomic inside
1873
- // heartbeatTaskAssignment's mutateBoard lock.
1874
- ...input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
1875
- });
1876
- return board ? okBoard(board, "Assignment heartbeat updated.") : fail("Task assignment not found.");
1877
- }
1878
- case "recover_stale": {
1879
- if (!input.boardId) return fail("recover_stale requires boardId.");
1880
- const policyFields = [
1881
- input.recoveryPolicyFailOnCostCeiling !== void 0,
1882
- input.recoveryPolicyReleaseOnFailureKinds !== void 0,
1883
- input.recoveryPolicyReleaseOnHeartbeatDue !== void 0,
1884
- input.recoveryPolicyRetryPolicyOverride !== void 0
1885
- ].some(Boolean);
1886
- const result2 = await recoverStaleTaskAssignments(projectRoot, input.boardId, {
1887
- ...input.recoveryMode !== void 0 ? { mode: input.recoveryMode } : {},
1888
- ...input.recoveryNow !== void 0 ? { now: input.recoveryNow } : {},
1889
- ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
1890
- ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {},
1891
- ...policyFields ? {
1892
- policy: {
1893
- ...input.recoveryPolicyFailOnCostCeiling !== void 0 ? { failWhenCostCeilingSet: input.recoveryPolicyFailOnCostCeiling } : {},
1894
- ...input.recoveryPolicyReleaseOnFailureKinds !== void 0 ? {
1895
- releaseOnFailureKinds: input.recoveryPolicyReleaseOnFailureKinds
1896
- } : {},
1897
- ...input.recoveryPolicyReleaseOnHeartbeatDue !== void 0 ? {
1898
- releaseOnHeartbeatDue: input.recoveryPolicyReleaseOnHeartbeatDue
1899
- } : {},
1900
- ...input.recoveryPolicyRetryPolicyOverride !== void 0 ? {
1901
- retryPolicyOverride: input.recoveryPolicyRetryPolicyOverride
1902
- } : {}
1903
- }
1904
- } : {}
1905
- });
1906
- return result2 ? {
1907
- ok: true,
1908
- message: `Recovered ${result2.tasks.length} stale assignment(s).`,
1909
- board: result2.board,
1910
- recoveredTasks: result2.tasks
1911
- } : { ok: true, message: "No stale assignment matched.", recoveredTasks: [] };
1912
- }
1913
- case "events": {
1914
- if (!input.boardId) return fail("events requires boardId.");
1915
- const eventList = await listKanbanEvents(projectRoot, input.boardId);
1916
- return {
1917
- ok: true,
1918
- message: `${eventList.length} event(s).`,
1919
- events: eventList
1920
- };
1921
- }
1922
- case "queue_health": {
1923
- const health = await getKanbanQueueHealth(projectRoot, {
1924
- ...input.boardId !== void 0 ? { boardId: input.boardId } : {}
1925
- });
1926
- return {
1927
- ok: true,
1928
- message: `Counts: startable=${health.counts.startable}, running=${health.counts.running}, stale=${health.staleAssignments.count}.`,
1929
- queueHealth: health
1930
- };
1931
- }
1932
- // Not every action is handled above. These are dispatched from here,
1933
- // and the split has already cost real time: an agent that read this
1934
- // file concluded `add_check` / `update_check` did not exist, wrote
1935
- // that on a card, and spent a session trying to satisfy a gate it
1936
- // already had the tool to clear. Keep this index in step with the
1937
- // handlers.
1938
- //
1939
- // kanban-detail-actions.ts workbench · add_dependency ·
1940
- // add_goal_metric · update_goal_metric · add_check ·
1941
- // update_check · add_note · add_link · split_atomic
1942
- // kanban-decomposition-actions.ts verify_completion ·
1943
- // assess_atomicity · propose_decomposition
1944
- // kanban-contract-actions.ts get_contract_graph ·
1945
- // configure_contract_graph · upsert_contract_node ·
1946
- // remove_contract_node · add_contract_edge · remove_contract_edge
1947
- default:
1948
- {
1949
- const contractResult = await handleKanbanContractAction(
1950
- projectRoot,
1951
- input,
1952
- input.author ?? input.agentId
1953
- );
1954
- if (contractResult !== void 0) return contractResult;
1955
- }
1956
- {
1957
- const detailResult = await handleKanbanDetailAction(projectRoot, input);
1958
- if (detailResult !== void 0) return detailResult;
1959
- }
1960
- return fail(`Unknown kanban action: ${input.action}`);
1961
- }
1941
+ const boardResult = await handleKanbanBoardAction(projectRoot, input, ctx);
1942
+ if (boardResult !== void 0) return boardResult;
1943
+ const lifecycleResult = await handleKanbanLifecycleAction(projectRoot, input, ctx);
1944
+ if (lifecycleResult !== void 0) return lifecycleResult;
1945
+ const contractResult = await handleKanbanContractAction(
1946
+ projectRoot,
1947
+ input,
1948
+ input.author ?? input.agentId
1949
+ );
1950
+ if (contractResult !== void 0) return contractResult;
1951
+ const detailResult = await handleKanbanDetailAction(projectRoot, input);
1952
+ if (detailResult !== void 0) return detailResult;
1953
+ return fail(`Unknown kanban action: ${input.action}`);
1962
1954
  })();
1963
1955
  return withPresence(result);
1964
1956
  } catch (err) {
1965
- return fail(stripLifecycleIssues(err instanceof Error ? err.message : String(err)));
1957
+ return fail(stripLifecycleIssues2(err instanceof Error ? err.message : String(err)));
1966
1958
  }
1967
1959
  },
1968
1960
  serialize(output, input) {
1969
1961
  return serializeKanbanOutput(output, input);
1970
1962
  }
1971
1963
  };
1972
- var KANBAN_BOARD_TRANSCRIPT_BYTE_CAP = 16384;
1973
- var KANBAN_FULL_BOARD_ACTIONS = /* @__PURE__ */ new Set([
1974
- "get_board",
1975
- "export_markdown",
1976
- "export_task_graph"
1977
- ]);
1978
- function serializeKanbanOutput(output, input) {
1979
- const action = input && typeof input === "object" ? input.action : void 0;
1980
- const board = output.board;
1981
- if (board) {
1982
- const keepFull = typeof action === "string" && KANBAN_FULL_BOARD_ACTIONS.has(action);
1983
- let boardBytes = 0;
1984
- if (!keepFull) {
1985
- try {
1986
- boardBytes = Buffer.byteLength(JSON.stringify(board), "utf8");
1987
- } catch {
1988
- boardBytes = 0;
1989
- }
1990
- }
1991
- if (!keepFull && boardBytes > KANBAN_BOARD_TRANSCRIPT_BYTE_CAP) {
1992
- const columns = {};
1993
- for (const column of board.columns) {
1994
- columns[column.title || column.id] = board.tasks.filter(
1995
- (task) => task.columnId === column.id
1996
- ).length;
1997
- }
1998
- const compact = {
1999
- ...output,
2000
- board: {
2001
- id: board.id,
2002
- title: board.title,
2003
- columns,
2004
- totalTasks: board.tasks.length,
2005
- note: `Full board (${boardBytes} bytes) omitted from the transcript; use get_board to load it.`
2006
- }
2007
- };
2008
- return JSON.stringify(compact, null, 2);
2009
- }
2010
- }
2011
- return JSON.stringify(output, null, 2);
2012
- }
2013
1964
  export {
2014
1965
  kanbanTool
2015
1966
  };