@wrongstack/tools 0.302.0 → 0.303.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 (40) hide show
  1. package/dist/builtin.js +2799 -609
  2. package/dist/codebase-index/binary-frame.d.ts +43 -0
  3. package/dist/codebase-index/codebase-incoming-calls-tool.d.ts +1 -0
  4. package/dist/codebase-index/codebase-outgoing-calls-tool.d.ts +1 -0
  5. package/dist/codebase-index/content-hash.d.ts +66 -0
  6. package/dist/codebase-index/index.js +1569 -148
  7. package/dist/codebase-index/parser-worker-pool.d.ts +63 -0
  8. package/dist/codebase-index/parser-worker-script.d.ts +42 -0
  9. package/dist/codebase-index/project-server-protocol.d.ts +2 -0
  10. package/dist/codebase-index/project-server.js +1455 -99
  11. package/dist/codebase-index/schema.d.ts +7 -0
  12. package/dist/codebase-index/tree-sitter/queries.d.ts +48 -0
  13. package/dist/codebase-index/tree-sitter/util.d.ts +31 -0
  14. package/dist/codebase-index/tree-sitter/visitor.d.ts +47 -0
  15. package/dist/codebase-index/tree-sitter-parser.d.ts +58 -0
  16. package/dist/codebase-index/vector-search.d.ts +62 -0
  17. package/dist/codebase-index/worker-protocol.d.ts +2 -0
  18. package/dist/codebase-index/worker.js +1424 -68
  19. package/dist/codebase-index/writer-bulk-insert.d.ts +5 -0
  20. package/dist/codebase-index/writer-graph-reader.d.ts +39 -0
  21. package/dist/codebase-index/writer-schema.d.ts +9 -2
  22. package/dist/codebase-index/writer.d.ts +36 -0
  23. package/dist/index.d.ts +1 -0
  24. package/dist/index.js +2785 -634
  25. package/dist/kanban-task-inputs.d.ts +1 -0
  26. package/dist/kanban-tool-schema.d.ts +2 -2
  27. package/dist/kanban-tool-types.d.ts +18 -2
  28. package/dist/kanban.js +392 -126
  29. package/dist/pack.js +2799 -609
  30. package/dist/plan.d.ts +4 -1
  31. package/dist/plan.js +2380 -9
  32. package/dist/read.js +1531 -98
  33. package/dist/session-kanban.d.ts +8 -0
  34. package/dist/session-kanban.js +111 -17
  35. package/dist/task.d.ts +5 -4
  36. package/dist/task.js +2418 -43
  37. package/dist/todo.d.ts +10 -1
  38. package/dist/todo.js +2152 -20
  39. package/dist/tool-tier.js +2799 -609
  40. package/package.json +8 -4
package/dist/plan.js CHANGED
@@ -1,5 +1,5 @@
1
1
  // src/plan.ts
2
- import { randomUUID } from "node:crypto";
2
+ import { randomUUID as randomUUID3 } from "node:crypto";
3
3
  import {
4
4
  addPlanItem,
5
5
  clearPlan,
@@ -9,7 +9,7 @@ import {
9
9
  mutatePlan as mutatePlan2,
10
10
  mutateTasks as mutateTasks2,
11
11
  removePlanItem,
12
- setPlanItemStatus
12
+ setPlanItemStatus as setPlanItemStatus2
13
13
  } from "@wrongstack/core/storage";
14
14
  import { formatTaskList } from "@wrongstack/core/utils";
15
15
 
@@ -43,9 +43,15 @@ var SESSION_KANBAN_COLUMNS = [
43
43
  ];
44
44
  var boardQueue = /* @__PURE__ */ new Map();
45
45
  var boardEnsures = /* @__PURE__ */ new Map();
46
+ var pendingMirrors = /* @__PURE__ */ new Map();
47
+ var activeMirrors = /* @__PURE__ */ new Set();
48
+ var suppressedTodoMirrors = /* @__PURE__ */ new WeakSet();
46
49
  function boardKey(projectRoot, sessionId) {
47
50
  return `${projectRoot}\0${sessionId}`;
48
51
  }
52
+ function mirrorKey(projectRoot, sessionId, sourceSystem) {
53
+ return `${boardKey(projectRoot, sessionId)}\0${sourceSystem}`;
54
+ }
49
55
  function sessionTag(sessionId) {
50
56
  return `session:${sessionId}`;
51
57
  }
@@ -130,12 +136,124 @@ async function projectGraph(projectRoot, sessionId, graph, sourceSystem) {
130
136
  return result?.board ?? null;
131
137
  });
132
138
  }
139
+ function queueLatestMirror(projectRoot, sessionId, graph, sourceSystem) {
140
+ if (!projectRoot || !sessionId || process.env[MIRROR_DISABLED_ENV] === "0") return;
141
+ const key = mirrorKey(projectRoot, sessionId, sourceSystem);
142
+ pendingMirrors.set(key, { projectRoot, sessionId, graph, sourceSystem });
143
+ if (activeMirrors.has(key)) return;
144
+ activeMirrors.add(key);
145
+ void (async () => {
146
+ try {
147
+ for (; ; ) {
148
+ const pending = pendingMirrors.get(key);
149
+ if (!pending) break;
150
+ pendingMirrors.delete(key);
151
+ try {
152
+ await projectGraph(
153
+ pending.projectRoot,
154
+ pending.sessionId,
155
+ pending.graph,
156
+ pending.sourceSystem
157
+ );
158
+ } catch (error) {
159
+ console.warn(
160
+ JSON.stringify({
161
+ level: "warn",
162
+ event: "session-kanban.mirror-failed",
163
+ sessionId: pending.sessionId,
164
+ sourceSystem: pending.sourceSystem,
165
+ message: error instanceof Error ? error.message : String(error),
166
+ timestamp: (/* @__PURE__ */ new Date()).toISOString()
167
+ })
168
+ );
169
+ }
170
+ }
171
+ } finally {
172
+ activeMirrors.delete(key);
173
+ const pending = pendingMirrors.get(key);
174
+ if (pending) {
175
+ pendingMirrors.delete(key);
176
+ queueLatestMirror(
177
+ pending.projectRoot,
178
+ pending.sessionId,
179
+ pending.graph,
180
+ pending.sourceSystem
181
+ );
182
+ }
183
+ }
184
+ })();
185
+ }
186
+ function todoListToSerializedGraph(todos, sessionId) {
187
+ const graphId = `todo:${sessionId}`;
188
+ const nodes = todos.map((todo, index) => ({
189
+ id: todo.id,
190
+ title: todo.content,
191
+ description: todo.activeForm ?? "",
192
+ type: "chore",
193
+ priority: "medium",
194
+ status: todo.status,
195
+ specRequirementId: `${graphId}:${todo.id}`,
196
+ createdAt: index,
197
+ updatedAt: index
198
+ }));
199
+ return {
200
+ id: graphId,
201
+ specId: graphId,
202
+ requiredRequirementIds: nodes.map((node) => node.specRequirementId),
203
+ title: "Session todos",
204
+ nodes,
205
+ edges: [],
206
+ rootNodes: nodes.map((node) => node.id),
207
+ createdAt: 0,
208
+ updatedAt: 0
209
+ };
210
+ }
211
+ function taskFileToSerializedGraph(tasks, sessionId) {
212
+ const graphId = `session:${sessionId}`;
213
+ const ids = new Set(tasks.map((task) => task.id));
214
+ const nodes = tasks.map((task, index) => ({
215
+ id: task.id,
216
+ title: task.title,
217
+ description: task.description ?? "",
218
+ type: task.type,
219
+ priority: task.priority,
220
+ status: task.status,
221
+ specRequirementId: `${graphId}:${task.id}`,
222
+ ...task.assignee ? { assignee: task.assignee } : {},
223
+ ...task.estimateHours !== void 0 ? { estimateHours: task.estimateHours } : {},
224
+ createdAt: index,
225
+ updatedAt: index
226
+ }));
227
+ const edges = tasks.flatMap(
228
+ (task) => (task.dependsOn ?? []).filter((dependency) => ids.has(dependency)).map((dependency) => ({
229
+ id: `${dependency}->${task.id}`,
230
+ from: dependency,
231
+ to: task.id,
232
+ type: "depends_on"
233
+ }))
234
+ );
235
+ const hasIncoming = new Set(edges.map((edge) => edge.to));
236
+ const rootNodes = nodes.filter((node) => !hasIncoming.has(node.id)).map((node) => node.id);
237
+ return {
238
+ // Keep the historical graph id so existing mirrored task cards are reused.
239
+ id: graphId,
240
+ specId: graphId,
241
+ requiredRequirementIds: nodes.map((node) => node.specRequirementId),
242
+ title: "Session tasks",
243
+ nodes,
244
+ edges,
245
+ rootNodes: rootNodes.length ? rootNodes : nodes[0] ? [nodes[0].id] : [],
246
+ createdAt: 0,
247
+ updatedAt: 0
248
+ };
249
+ }
133
250
  var PLAN_STATUS_TO_TASK = {
134
251
  open: "pending",
135
252
  in_progress: "in_progress",
136
253
  done: "completed"
137
254
  };
138
255
  function planFileToSerializedGraph(items, sessionId) {
256
+ const graphId = `plan:${sessionId}`;
139
257
  const nodes = items.map((item, index) => ({
140
258
  id: item.id,
141
259
  title: item.title,
@@ -143,12 +261,14 @@ function planFileToSerializedGraph(items, sessionId) {
143
261
  type: "chore",
144
262
  priority: "medium",
145
263
  status: PLAN_STATUS_TO_TASK[item.status],
264
+ specRequirementId: `${graphId}:${item.id}`,
146
265
  createdAt: index,
147
266
  updatedAt: index
148
267
  }));
149
268
  return {
150
- id: `plan:${sessionId}`,
151
- specId: `plan:${sessionId}`,
269
+ id: graphId,
270
+ specId: graphId,
271
+ requiredRequirementIds: nodes.map((node) => node.specRequirementId),
152
272
  title: "Session plan",
153
273
  nodes,
154
274
  edges: [],
@@ -165,13 +285,2218 @@ function projectSessionPlanToKanban(projectRoot, items, sessionId) {
165
285
  "session-plan"
166
286
  );
167
287
  }
288
+ function broadcastTodoUpdate(context, todos) {
289
+ const sessionId = context.session?.id ?? "";
290
+ if (!context.agentId || !sessionId) return;
291
+ const statusCounts = { pending: 0, inProgress: 0, completed: 0 };
292
+ for (const todo of todos) {
293
+ if (todo.status === "completed") statusCounts.completed++;
294
+ else if (todo.status === "in_progress") statusCounts.inProgress++;
295
+ else statusCounts.pending++;
296
+ }
297
+ const projectDir = resolveWstackPaths({ projectRoot: context.projectRoot }).projectDir;
298
+ const mailbox = getSharedProjectMailbox(projectDir);
299
+ void mailbox.send({
300
+ from: context.agentId,
301
+ to: "*",
302
+ type: "status",
303
+ subject: `Kanban todo list updated (${todos.length} item${todos.length === 1 ? "" : "s"})`,
304
+ body: JSON.stringify({
305
+ kind: "kanban.todos.updated",
306
+ sessionId,
307
+ revision: context.state.revision,
308
+ todoCount: todos.length,
309
+ statusCounts
310
+ }),
311
+ priority: "normal",
312
+ senderSessionId: sessionId
313
+ }).catch(() => {
314
+ });
315
+ }
316
+ function notifyTodoUpdate(context, todos) {
317
+ const summary = todos.length ? todos.map((todo) => `- [${todo.status}] ${todo.content} (${todo.id})`).join("\n") : "- No active todos remain.";
318
+ const text = `[KANBAN TODO UPDATE]
319
+ Another Kanban agent reassessed the shared board. The canonical todo list is now:
320
+ ${summary}
321
+ Reassess your current plan before continuing; do not rely on the initial todo snapshot.`;
322
+ const state = context.state;
323
+ if (typeof state.appendBlockToLastUserMessage === "function") {
324
+ if (state.appendBlockToLastUserMessage({ type: "text", text })) return;
325
+ }
326
+ if (typeof state.appendMessage === "function") {
327
+ state.appendMessage({ role: "user", content: [{ type: "text", text }] });
328
+ }
329
+ }
330
+ function mirrorSessionTodosToKanban(projectRoot, todos, sessionId) {
331
+ queueLatestMirror(
332
+ projectRoot,
333
+ sessionId,
334
+ todoListToSerializedGraph(todos, sessionId),
335
+ "session-todo"
336
+ );
337
+ }
338
+ function sourceStatus(task) {
339
+ if (task.status === "completed") return "completed";
340
+ if (task.status === "in_progress") return "in_progress";
341
+ if (task.status === "review") return "review";
342
+ if (task.status === "blocked") return "blocked";
343
+ if (task.status === "failed") return "failed";
344
+ return "pending";
345
+ }
346
+ function todoStatus(task) {
347
+ const status = sourceStatus(task);
348
+ if (status === "completed") return "completed";
349
+ if (status === "in_progress" || status === "review") return "in_progress";
350
+ return "pending";
351
+ }
352
+ function sessionTodoFromTask(task, boardId) {
353
+ return {
354
+ id: task.origin?.taskId ?? task.id,
355
+ content: task.title,
356
+ status: todoStatus(task),
357
+ kanbanBoardId: boardId,
358
+ kanbanTaskId: task.id,
359
+ ...task.description ? { activeForm: task.description } : {}
360
+ };
361
+ }
362
+ function managedTodoFromTask(task, boardId) {
363
+ return {
364
+ ...sessionTodoFromTask(task, boardId),
365
+ status: task.status === "completed" ? "completed" : task.status === "in_progress" ? "in_progress" : "pending"
366
+ };
367
+ }
368
+ function sameTodos(left, right) {
369
+ return left.length === right.length && left.every((todo, index) => {
370
+ const candidate = right[index];
371
+ return candidate?.id === todo.id && candidate.content === todo.content && candidate.status === todo.status && candidate.activeForm === todo.activeForm && candidate.promotedFromPlan === todo.promotedFromPlan && candidate.promotedFromTask === todo.promotedFromTask && candidate.kanbanBoardId === todo.kanbanBoardId && candidate.kanbanTaskId === todo.kanbanTaskId;
372
+ });
373
+ }
374
+ function applyManagedKanbanBoardToTodos(context, board) {
375
+ const metaKanban = context.meta["kanban"];
376
+ const metaBoardId = metaKanban && typeof metaKanban === "object" ? metaKanban["boardId"] : void 0;
377
+ const activeBoardId2 = context.currentKanbanBoardId ?? (typeof metaBoardId === "string" ? metaBoardId : void 0);
378
+ if (!activeBoardId2 || board.id !== activeBoardId2 || board.lifecycle?.mode !== "managed") {
379
+ return [...context.todos];
380
+ }
381
+ const projectedTodos = board.tasks.filter(
382
+ (task) => task.status !== "archived" && task.mergedIntoTaskId === void 0 && (!task.childTaskIds || task.childTaskIds.length === 0)
383
+ ).sort(
384
+ (left, right) => left.createdAt.localeCompare(right.createdAt) || left.order - right.order
385
+ ).map((task) => managedTodoFromTask(task, board.id));
386
+ if (sameTodos(context.todos, projectedTodos)) return [...context.todos];
387
+ suppressedTodoMirrors.add(context);
388
+ try {
389
+ context.state.replaceTodos(projectedTodos);
390
+ } finally {
391
+ suppressedTodoMirrors.delete(context);
392
+ }
393
+ notifyTodoUpdate(context, context.todos);
394
+ broadcastTodoUpdate(context, context.todos);
395
+ return [...context.todos];
396
+ }
397
+
398
+ // src/todo.ts
399
+ import {
400
+ loadPlan as loadPlan2,
401
+ loadTasks as loadTasks3,
402
+ savePlan,
403
+ saveTasks,
404
+ setPlanItemStatus
405
+ } from "@wrongstack/core/storage";
406
+ import { getBoard as getBoard4 } from "@wrongstack/kanban";
407
+
408
+ // src/kanban.ts
409
+ import { randomUUID as randomUUID2 } from "node:crypto";
410
+ import { loadTasks as loadTasks2 } from "@wrongstack/core/storage";
411
+ import { deserializeTaskGraph as deserializeTaskGraph2, serializeTaskGraph } from "@wrongstack/core/tasking";
412
+ import {
413
+ addColumn,
414
+ addTask,
415
+ adoptManagedLifecycle,
416
+ assignTask,
417
+ claimReadyTask,
418
+ copyTaskToBoard,
419
+ createBoard as createBoard2,
420
+ createBoardFromTaskGraph,
421
+ createBoardFromText,
422
+ duplicateBoard,
423
+ evaluateContractGraphReadiness,
424
+ exportBoardAsMarkdown,
425
+ exportBoardToTaskGraph,
426
+ finalizeTaskCompletion,
427
+ getBoard as getBoard3,
428
+ getKanbanOrchestrationSnapshot,
429
+ getKanbanQueueHealth,
430
+ getTask,
431
+ getTaskChain,
432
+ heartbeatTaskAssignment,
433
+ listBoards as listBoards2,
434
+ listKanbanEvents,
435
+ listReadyTasks,
436
+ mergeTasks,
437
+ moveTask,
438
+ parseLinesIntoTasks,
439
+ recoverStaleTaskAssignments,
440
+ releaseTaskClaim,
441
+ removeBoard as removeBoard2,
442
+ removeColumn,
443
+ removeTask,
444
+ repairManagedTaskProjection,
445
+ searchKanban,
446
+ setTaskChain,
447
+ syncBoardFromTaskGraph as syncBoardFromTaskGraph2,
448
+ transferTaskToBoard,
449
+ transitionTask,
450
+ updateBoard as updateBoard2,
451
+ updateColumn,
452
+ updateTask as updateTask2,
453
+ updateTaskAssignment,
454
+ verifyTaskCompletion as verifyTaskCompletion2
455
+ } from "@wrongstack/kanban";
456
+
457
+ // src/kanban-board-inputs.ts
458
+ function agentSettableGate(enforcement) {
459
+ if (enforcement === void 0 || enforcement === "off") return {};
460
+ return { completionGate: { enforcement } };
461
+ }
462
+ function boardCreateInput(input, title) {
463
+ return {
464
+ title,
465
+ ...input.description !== void 0 ? { description: input.description } : {},
466
+ ...input.tags !== void 0 ? { tags: input.tags } : {},
467
+ ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
468
+ ...input.atomicityMode !== void 0 ? {
469
+ atomicity: {
470
+ mode: input.atomicityMode,
471
+ decomposition: input.atomicityDecomposition ?? "propose"
472
+ }
473
+ } : {},
474
+ ...agentSettableGate(input.gateEnforcement)
475
+ };
476
+ }
477
+ function boardUpdatePatch(input) {
478
+ return {
479
+ ...input.title !== void 0 ? { title: input.title } : {},
480
+ ...input.description !== void 0 ? { description: input.description } : {},
481
+ ...input.tags !== void 0 ? { tags: input.tags } : {},
482
+ ...input.atomicityMode !== void 0 ? {
483
+ atomicity: {
484
+ mode: input.atomicityMode,
485
+ decomposition: input.atomicityDecomposition ?? "propose"
486
+ }
487
+ } : {},
488
+ ...agentSettableGate(input.gateEnforcement)
489
+ };
490
+ }
491
+ function duplicateBoardOptions(input) {
492
+ return {
493
+ ...input.title !== void 0 ? { title: input.title } : {},
494
+ ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
495
+ ...input.includeTasks !== void 0 ? { includeTasks: input.includeTasks } : {},
496
+ ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {},
497
+ ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {}
498
+ };
499
+ }
500
+
501
+ // src/kanban-decomposition-actions.ts
502
+ import {
503
+ assessTaskAtomicity,
504
+ proposeTaskDecomposition,
505
+ updateTask,
506
+ verifyTaskCompletion
507
+ } from "@wrongstack/kanban";
508
+
509
+ // src/kanban-evidence-bridge.ts
510
+ import { recordCompletedWorkEvidence } from "@wrongstack/core/utils";
511
+ function kanbanEvidenceKey(boardId, taskId) {
512
+ return `kanban:${boardId}:${taskId}`;
513
+ }
514
+ function kanbanEvidencePointer(boardId, taskId) {
515
+ return `kanban://${boardId}/${taskId}#verificationReport`;
516
+ }
517
+ function recordKanbanVerificationEvidence(ctx, report) {
518
+ try {
519
+ const passed = report.checks.filter((check) => check.status === "passed").length;
520
+ const completedAt = Date.parse(report.completedAt);
521
+ recordCompletedWorkEvidence(ctx, {
522
+ key: kanbanEvidenceKey(report.boardId, report.taskId),
523
+ source: "verification",
524
+ summary: `${report.taskTitle} \u2014 verification ${report.verdict} (${passed}/${report.checks.length} checks)`,
525
+ ...Number.isFinite(completedAt) ? { completedAt } : {},
526
+ evidence: kanbanEvidencePointer(report.boardId, report.taskId)
527
+ });
528
+ } catch {
529
+ }
530
+ }
531
+
532
+ // src/kanban-tool-results.ts
533
+ function atomicityNudge(task) {
534
+ if (task.atomicityAssessment?.verdict !== "needs_decomposition") return "";
535
+ const reasons = task.atomicityAssessment.criteria.filter((entry) => entry.score < 1).map((entry) => entry.reason).join(" | ");
536
+ return ` Atomicity: needs_decomposition (score ${task.atomicityAssessment.score}) \u2014 call propose_decomposition with 2+ subtasks before dispatch. Reasons: ${reasons}`;
537
+ }
538
+ function readEnvGateEnforcement() {
539
+ const raw = process.env["WRONGSTACK_KANBAN_GATE"]?.trim().toLowerCase();
540
+ return raw === "strict" || raw === "soft" || raw === "off" ? raw : void 0;
541
+ }
542
+ function fail(message) {
543
+ return { ok: false, message };
544
+ }
545
+ function okBoard(board, message = "Board loaded.") {
546
+ return { ok: true, message, board };
547
+ }
548
+ function okTask(board, task, message) {
549
+ return { ok: true, message, board, task };
550
+ }
551
+
552
+ // src/kanban-decomposition-actions.ts
553
+ async function handleKanbanDecompositionAction(projectRoot, input, ctx) {
554
+ switch (input.action) {
555
+ case "assess_atomicity": {
556
+ if (!input.boardId || !input.taskId) {
557
+ return fail("assess_atomicity requires boardId and taskId.");
558
+ }
559
+ const result = await assessTaskAtomicity(projectRoot, input.boardId, input.taskId, {
560
+ assessedBy: "agent",
561
+ ...ctx.agentId !== void 0 ? { eventContext: { actor: ctx.agentId } } : {}
562
+ });
563
+ if (!result) return fail("Task not found.");
564
+ const failing = result.assessment.criteria.filter((entry) => entry.score < 1).map((entry) => entry.reason);
565
+ const guidance = result.assessment.verdict === "needs_decomposition" ? ` This task should be split before dispatch \u2014 call propose_decomposition with 2+ subtasks (each with one verifiable success criterion). Reasons: ${failing.join(" | ")}` : result.assessment.verdict === "composite" ? " Container task: work happens in its children; it is verified via subtask aggregation." : "";
566
+ return okTask(
567
+ result.board,
568
+ result.task,
569
+ `Atomicity verdict: ${result.assessment.verdict} (score ${result.assessment.score}).${guidance}`
570
+ );
571
+ }
572
+ case "propose_decomposition": {
573
+ if (!input.boardId || !input.taskId || !input.subtasks?.length) {
574
+ return fail("propose_decomposition requires boardId, taskId, and subtasks (2+).");
575
+ }
576
+ if (input.subtasks.length < 2) {
577
+ return fail("propose_decomposition requires at least two subtasks.");
578
+ }
579
+ const invalid = input.subtasks.find(
580
+ (subtask) => typeof subtask?.title !== "string" || !subtask.title.trim()
581
+ );
582
+ if (invalid) return fail("Every proposed subtask needs a non-blank title.");
583
+ const result = await proposeTaskDecomposition(
584
+ projectRoot,
585
+ input.boardId,
586
+ input.taskId,
587
+ {
588
+ subtasks: input.subtasks,
589
+ ...input.note !== void 0 ? { rationale: input.note } : {},
590
+ ...ctx.agentId !== void 0 ? { proposedBy: ctx.agentId } : {}
591
+ },
592
+ ctx.agentId !== void 0 ? { actor: ctx.agentId } : {}
593
+ );
594
+ if (!result) return fail("Task not found.");
595
+ const message = result.proposal.status === "applied" ? `Decomposition applied: ${result.proposal.appliedChildTaskIds?.length ?? 0} child tasks created (parent marked atomic).` : 'Decomposition proposal recorded \u2014 awaiting approval (board policy is "propose"). It can be approved from the WebUI or via update_task.';
596
+ return okTask(result.board, result.task, message);
597
+ }
598
+ case "verify_completion": {
599
+ if (!input.boardId || !input.taskId) {
600
+ return fail("verify_completion requires boardId and taskId.");
601
+ }
602
+ const verResult = await verifyTaskCompletion(projectRoot, input.boardId, input.taskId);
603
+ const persistedBoard = await updateTask(projectRoot, input.boardId, input.taskId, {
604
+ verificationReport: verResult.report,
605
+ successCriteria: verResult.task.successCriteria
606
+ });
607
+ if (!persistedBoard) {
608
+ return {
609
+ ok: false,
610
+ verdict: verResult.report.verdict,
611
+ message: `Verification succeeded but persist failed: ${verResult.report.markdownSummary}. Board may be stale \u2014 re-run verify_completion.`,
612
+ board: verResult.board
613
+ };
614
+ }
615
+ recordKanbanVerificationEvidence(ctx, verResult.report);
616
+ const freshTask = persistedBoard.tasks?.find((t) => t.id === input.taskId);
617
+ const deterministicVerdicts = ["passed", "failed", "needs_human", "incomplete"];
618
+ return {
619
+ ok: deterministicVerdicts.includes(
620
+ verResult.report.verdict
621
+ ),
622
+ verdict: verResult.report.verdict,
623
+ message: verResult.report.markdownSummary,
624
+ board: persistedBoard,
625
+ task: freshTask ?? verResult.task
626
+ };
627
+ }
628
+ default:
629
+ return void 0;
630
+ }
631
+ }
632
+
633
+ // src/kanban-detail-actions.ts
634
+ import {
635
+ addCheckToTask,
636
+ addContractEdge,
637
+ addDependency,
638
+ addGoalMetricToTask,
639
+ addLinkToTask,
640
+ addNoteToTask,
641
+ configureContractGraph,
642
+ evaluateTaskContractGraph,
643
+ getContractGraph,
644
+ getKanbanWorkbench,
645
+ removeContractEdge,
646
+ removeContractNode,
647
+ updateCheckOnTask,
648
+ updateGoalMetricOnTask,
649
+ upsertContractNode
650
+ } from "@wrongstack/kanban";
651
+
652
+ // src/kanban-split-task-handler.ts
653
+ import { getBoard as getBoard2, splitTask } from "@wrongstack/kanban";
654
+ async function handleSplitTask(projectRoot, input, extraSplitOptions) {
655
+ const boardId = input.boardId;
656
+ const taskId = input.taskId;
657
+ const childTitles = input.childTitles;
658
+ if (!boardId || !taskId || !childTitles?.length) {
659
+ return fail("split requires boardId, taskId, and at least one childTitles.");
660
+ }
661
+ const {
662
+ targetColumnId,
663
+ inheritAssignment,
664
+ inheritLabels,
665
+ inheritSuccessCriteria,
666
+ inheritGoalMetrics,
667
+ inheritDependencies,
668
+ chainChildren,
669
+ rewireDependents
670
+ } = input;
671
+ const result = await splitTask(projectRoot, boardId, taskId, {
672
+ titles: childTitles,
673
+ ...extraSplitOptions,
674
+ ...targetColumnId !== void 0 ? { columnId: targetColumnId } : {},
675
+ ...inheritAssignment !== void 0 ? { inheritAssignment } : {},
676
+ ...inheritLabels !== void 0 ? { inheritLabels } : {},
677
+ ...inheritSuccessCriteria !== void 0 ? { inheritSuccessCriteria } : {},
678
+ ...inheritGoalMetrics !== void 0 ? { inheritGoalMetrics } : {},
679
+ ...inheritDependencies !== void 0 ? { inheritDependencies } : {},
680
+ ...chainChildren !== void 0 ? { chainChildren } : {},
681
+ ...rewireDependents !== void 0 ? { rewireDependents } : {}
682
+ });
683
+ if (!result) return fail("Task not found.");
684
+ const freshParent = result.board.tasks?.find((t) => t.id === taskId);
685
+ if (!freshParent) {
686
+ return fail(
687
+ `Split succeeded but parent ${taskId} not found in returned board. Children: [${result.children.map((c) => c.id).join(", ")}].`
688
+ );
689
+ }
690
+ return {
691
+ ok: true,
692
+ message: `${result.children.length} child task(s) created.`,
693
+ board: result.board,
694
+ task: freshParent,
695
+ children: result.children
696
+ };
697
+ }
698
+ async function requireBoard(projectRoot, boardId) {
699
+ return boardId ? getBoard2(projectRoot, boardId) : null;
700
+ }
701
+
702
+ // src/kanban-detail-actions.ts
703
+ async function handleKanbanDetailAction(projectRoot, input) {
704
+ switch (input.action) {
705
+ case "workbench": {
706
+ const workbench = await getKanbanWorkbench(projectRoot, {
707
+ ...input.limit !== void 0 ? { limitPerLane: input.limit, alertLimit: input.limit } : {}
708
+ });
709
+ return {
710
+ ok: true,
711
+ message: `${workbench.totals.now} now, ${workbench.totals.next} next, ${workbench.totals.blocked} blocked, ${workbench.totals.review} review; ${workbench.alertTotal} alert(s).`,
712
+ workbench
713
+ };
714
+ }
715
+ case "get_contract_graph": {
716
+ if (!input.boardId) return fail("get_contract_graph requires boardId.");
717
+ const result = await getContractGraph(projectRoot, input.boardId);
718
+ return result ? {
719
+ ok: true,
720
+ message: result.graph ? `${result.graph.nodes.length} contract node(s), ${result.graph.edges.length} edge(s).` : "Contract graph is not configured.",
721
+ board: result.board,
722
+ ...result.graph ? { contractGraph: result.graph } : {}
723
+ } : fail("Board not found.");
724
+ }
725
+ case "configure_contract_graph": {
726
+ if (!input.boardId || !input.contractGraphEnforcement) {
727
+ return fail("configure_contract_graph requires boardId and contractGraphEnforcement.");
728
+ }
729
+ const current = await getContractGraph(projectRoot, input.boardId);
730
+ if (!current) return fail("Board not found.");
731
+ if (input.contractGraphEnforcement === "strict" && current.graph?.enforcement !== "strict") {
732
+ return fail(
733
+ "Strict Contract Map enforcement is operator-owned. Autonomous agents may use advisory maps but may not turn them into an execution gate."
734
+ );
735
+ }
736
+ if (current.graph?.enforcement === "strict" && input.contractGraphEnforcement !== "strict") {
737
+ return fail("An autonomous agent may not loosen a strict contract graph.");
738
+ }
739
+ const board = await configureContractGraph(
740
+ projectRoot,
741
+ input.boardId,
742
+ input.contractGraphEnforcement
743
+ );
744
+ return board ? okBoard(board, "Contract graph configured.") : fail("Board not found.");
745
+ }
746
+ case "upsert_contract_node": {
747
+ if (!input.boardId || !input.taskId || !input.contractNodeKind || !input.title) {
748
+ return fail("upsert_contract_node requires boardId, taskId, contractNodeKind, and title.");
749
+ }
750
+ if (input.contractNodeState === "waived") {
751
+ return fail(
752
+ "The autonomous kanban tool may not waive contract nodes; a human-owned review surface must record that exception."
753
+ );
754
+ }
755
+ if (input.contractNodeId) {
756
+ const current = await getContractGraph(projectRoot, input.boardId);
757
+ const existing = current?.graph?.nodes.find((node) => node.id === input.contractNodeId);
758
+ if (current?.graph?.enforcement === "strict" && existing && (existing.kind !== input.contractNodeKind || input.contractEnforcement !== void 0 && input.contractEnforcement !== existing.enforcement)) {
759
+ return fail(
760
+ "The autonomous kanban tool may not change the kind or enforcement of an existing strict contract node."
761
+ );
762
+ }
763
+ }
764
+ const result = await upsertContractNode(projectRoot, input.boardId, {
765
+ ...input.contractNodeId ? { id: input.contractNodeId } : {},
766
+ taskId: input.taskId,
767
+ kind: input.contractNodeKind,
768
+ title: input.title,
769
+ ...input.description !== void 0 ? { description: input.description } : {},
770
+ ...input.contractEnforcement !== void 0 ? { enforcement: input.contractEnforcement } : {},
771
+ ...input.contractNodeState !== void 0 ? { state: input.contractNodeState } : {},
772
+ ...input.checkId !== void 0 ? { checkId: input.checkId } : {},
773
+ ...input.metricId !== void 0 ? { metricId: input.metricId } : {},
774
+ ...input.baseline !== void 0 ? { baseline: input.baseline } : {},
775
+ ...input.threshold !== void 0 ? { threshold: input.threshold } : {},
776
+ ...input.author !== void 0 ? { createdBy: input.author } : {}
777
+ });
778
+ return result ? {
779
+ ...okBoard(result.board, "Contract node saved."),
780
+ contractGraph: result.board.contractGraph
781
+ } : fail("Task not found.");
782
+ }
783
+ case "link_contract_nodes": {
784
+ if (!input.boardId || !input.fromNodeId || !input.toNodeId || !input.contractEdgeType) {
785
+ return fail(
786
+ "link_contract_nodes requires boardId, fromNodeId, toNodeId, and contractEdgeType."
787
+ );
788
+ }
789
+ const result = await addContractEdge(projectRoot, input.boardId, {
790
+ from: input.fromNodeId,
791
+ to: input.toNodeId,
792
+ type: input.contractEdgeType,
793
+ ...input.contractEdgeId ? { id: input.contractEdgeId } : {},
794
+ ...input.contractEnforcement ? { enforcement: input.contractEnforcement } : {},
795
+ ...input.contractRationale ? { rationale: input.contractRationale } : {},
796
+ ...input.author ? { createdBy: input.author } : {}
797
+ });
798
+ return result ? {
799
+ ...okBoard(result.board, "Contract edge added."),
800
+ contractGraph: result.board.contractGraph
801
+ } : fail("Board not found.");
802
+ }
803
+ case "remove_contract_node": {
804
+ if (!input.boardId || !input.contractNodeId) {
805
+ return fail("remove_contract_node requires boardId and contractNodeId.");
806
+ }
807
+ const current = await getContractGraph(projectRoot, input.boardId);
808
+ const node = current?.graph?.nodes.find((candidate) => candidate.id === input.contractNodeId);
809
+ if (current?.graph?.enforcement === "strict" && node?.enforcement === "blocking") {
810
+ return fail("The autonomous kanban tool may not remove a blocking strict contract node.");
811
+ }
812
+ const board = await removeContractNode(projectRoot, input.boardId, input.contractNodeId);
813
+ return board ? okBoard(board, "Contract node removed.") : fail("Contract node not found.");
814
+ }
815
+ case "remove_contract_edge": {
816
+ if (!input.boardId || !input.contractEdgeId) {
817
+ return fail("remove_contract_edge requires boardId and contractEdgeId.");
818
+ }
819
+ const current = await getContractGraph(projectRoot, input.boardId);
820
+ const edge = current?.graph?.edges.find((candidate) => candidate.id === input.contractEdgeId);
821
+ if (current?.graph?.enforcement === "strict" && edge?.enforcement === "blocking") {
822
+ return fail("The autonomous kanban tool may not remove a blocking strict contract edge.");
823
+ }
824
+ const board = await removeContractEdge(projectRoot, input.boardId, input.contractEdgeId);
825
+ return board ? okBoard(board, "Contract edge removed.") : fail("Contract edge not found.");
826
+ }
827
+ case "evaluate_contract_graph": {
828
+ if (!input.boardId || !input.taskId) {
829
+ return fail("evaluate_contract_graph requires boardId and taskId.");
830
+ }
831
+ const result = await evaluateTaskContractGraph(projectRoot, input.boardId, input.taskId);
832
+ return result ? {
833
+ ok: result.evaluation.allowed,
834
+ message: result.evaluation.allowed ? "Contract graph is closed." : `Contract graph has ${result.evaluation.issues.length} unresolved issue(s).`,
835
+ board: result.board,
836
+ contractGraph: result.board.contractGraph,
837
+ contractEvaluation: result.evaluation
838
+ } : fail("Task not found.");
839
+ }
840
+ case "add_dependency": {
841
+ if (!input.boardId || !input.taskId || !input.dependencyTaskId) {
842
+ return fail("add_dependency requires boardId, taskId, and dependencyTaskId.");
843
+ }
844
+ const board = await addDependency(
845
+ projectRoot,
846
+ input.boardId,
847
+ input.taskId,
848
+ input.dependencyTaskId
849
+ );
850
+ return board ? okBoard(board, "Dependency added.") : fail("Task not found.");
851
+ }
852
+ case "add_goal_metric": {
853
+ if (!input.boardId || !input.taskId || !input.metricName) {
854
+ return fail("add_goal_metric requires boardId, taskId, and metricName.");
855
+ }
856
+ const board = await addGoalMetricToTask(projectRoot, input.boardId, input.taskId, {
857
+ name: input.metricName,
858
+ ...input.metricStatus !== void 0 ? { status: input.metricStatus } : {},
859
+ ...input.metricTarget !== void 0 ? { target: input.metricTarget } : {},
860
+ ...input.metricCurrent !== void 0 ? { current: input.metricCurrent } : {},
861
+ ...input.metricUnit !== void 0 ? { unit: input.metricUnit } : {},
862
+ ...input.metricNotes !== void 0 ? { notes: input.metricNotes } : {}
863
+ });
864
+ return board ? okBoard(board, "Goal metric added.") : fail("Task not found.");
865
+ }
866
+ case "update_goal_metric": {
867
+ if (!input.boardId || !input.taskId || !input.metricId) {
868
+ return fail("update_goal_metric requires boardId, taskId, and metricId.");
869
+ }
870
+ const board = await updateGoalMetricOnTask(
871
+ projectRoot,
872
+ input.boardId,
873
+ input.taskId,
874
+ input.metricId,
875
+ {
876
+ ...input.metricName !== void 0 ? { name: input.metricName } : {},
877
+ ...input.metricStatus !== void 0 ? { status: input.metricStatus } : {},
878
+ ...input.metricTarget !== void 0 ? { target: input.metricTarget } : {},
879
+ ...input.metricCurrent !== void 0 ? { current: input.metricCurrent } : {},
880
+ ...input.metricUnit !== void 0 ? { unit: input.metricUnit } : {},
881
+ ...input.metricNotes !== void 0 ? { notes: input.metricNotes } : {}
882
+ }
883
+ );
884
+ return board ? okBoard(board, "Goal metric updated.") : fail("Metric not found.");
885
+ }
886
+ case "add_check": {
887
+ if (!input.boardId || !input.taskId || !input.checkDescription) {
888
+ return fail("add_check requires boardId, taskId, and checkDescription.");
889
+ }
890
+ const board = await addCheckToTask(projectRoot, input.boardId, input.taskId, {
891
+ description: input.checkDescription,
892
+ type: "manual",
893
+ status: input.checkStatus
894
+ });
895
+ return board ? okBoard(board, "Check added.") : fail("Task not found.");
896
+ }
897
+ case "update_check": {
898
+ if (!input.boardId || !input.taskId || !input.checkId) {
899
+ return fail("update_check requires boardId, taskId, and checkId.");
900
+ }
901
+ const board = await updateCheckOnTask(
902
+ projectRoot,
903
+ input.boardId,
904
+ input.taskId,
905
+ input.checkId,
906
+ {
907
+ ...input.checkDescription !== void 0 ? { description: input.checkDescription } : {},
908
+ ...input.checkStatus !== void 0 ? { status: input.checkStatus } : {}
909
+ }
910
+ );
911
+ return board ? okBoard(board, "Check updated.") : fail("Check not found.");
912
+ }
913
+ case "add_note": {
914
+ if (!input.boardId || !input.taskId || !input.note)
915
+ return fail("add_note requires boardId, taskId, and note.");
916
+ const board = await addNoteToTask(projectRoot, input.boardId, input.taskId, {
917
+ author: input.author ?? "agent",
918
+ content: input.note
919
+ });
920
+ return board ? okBoard(board, "Note added.") : fail("Task not found.");
921
+ }
922
+ case "add_link": {
923
+ if (!input.boardId || !input.taskId || !input.url)
924
+ return fail("add_link requires boardId, taskId, and url.");
925
+ const board = await addLinkToTask(projectRoot, input.boardId, input.taskId, {
926
+ url: input.url,
927
+ type: input.linkType ?? "url",
928
+ ...input.linkTitle !== void 0 ? { title: input.linkTitle } : {}
929
+ });
930
+ return board ? okBoard(board, "Link added.") : fail("Task not found.");
931
+ }
932
+ case "split_atomic": {
933
+ if (!input.boardId || !input.taskId || !input.childTitles?.length) {
934
+ return fail("split_atomic requires boardId, taskId, and childTitles (at least one).");
935
+ }
936
+ return handleSplitTask(projectRoot, input, { atomic: true });
937
+ }
938
+ default:
939
+ return void 0;
940
+ }
941
+ }
942
+
943
+ // src/kanban-presence.ts
944
+ import { touchKanbanPresence as touchKanbanPresence2 } from "@wrongstack/kanban";
945
+ function createKanbanPresenceWrapper(projectRoot, input, ctx) {
946
+ return async (result) => {
947
+ const boardId = result.board?.id ?? input.boardId;
948
+ if (!result.ok || !boardId || !ctx.session?.id || !ctx.agentId) return result;
949
+ try {
950
+ const board = await touchKanbanPresence2(projectRoot, boardId, {
951
+ sessionId: ctx.session.id,
952
+ agentId: ctx.agentId,
953
+ agentName: ctx.agentName,
954
+ taskId: input.taskId ?? result.task?.id,
955
+ runTaskId: input.runTaskId
956
+ });
957
+ return board ? { ...result, board } : result;
958
+ } catch {
959
+ return result;
960
+ }
961
+ };
962
+ }
963
+
964
+ // src/kanban-task-inputs.ts
965
+ import { randomUUID } from "node:crypto";
966
+ import { clampSubagentCapabilities } from "@wrongstack/core/security";
967
+ function taskInput(input) {
968
+ const assignment = hasAssignmentInput(input) ? assignmentForTaskCreate(input) : void 0;
969
+ return {
970
+ title: input.title ?? "",
971
+ columnId: input.columnId,
972
+ description: input.description,
973
+ dueDate: input.dueDate,
974
+ priority: input.priority,
975
+ ...input.taskType !== void 0 ? { type: input.taskType } : {},
976
+ status: input.status,
977
+ labels: input.labels,
978
+ ...assignment?.agentId ?? assignment?.role ?? assignment?.name ? { assignedAgent: assignment.agentId ?? assignment.role ?? assignment.name } : {},
979
+ ...input.assignee ?? assignment?.name ?? assignment?.agentId ? { assignee: input.assignee ?? assignment?.name ?? assignment?.agentId } : {},
980
+ ...mergedDependsOn(input) ? { dependsOn: mergedDependsOn(input) } : {},
981
+ ...input.estimatedHours !== void 0 ? { estimatedHours: input.estimatedHours } : {},
982
+ ...input.actualHours !== void 0 ? { actualHours: input.actualHours } : {},
983
+ ...assignment ? { assignment } : {},
984
+ ...input.order !== void 0 ? { order: input.order } : {},
985
+ ...input.retryPolicy !== void 0 ? { retryPolicy: input.retryPolicy } : {},
986
+ ...input.costCeilingUsd !== void 0 ? { costCeilingUsd: input.costCeilingUsd } : {},
987
+ ...input.childTitles !== void 0 ? { childTaskIds: input.childTitles } : {},
988
+ ...input.checkDescription !== void 0 ? {
989
+ successCriteria: [
990
+ {
991
+ id: randomUUID(),
992
+ description: input.checkDescription,
993
+ type: "manual",
994
+ status: input.checkStatus ?? "pending"
995
+ }
996
+ ]
997
+ } : {},
998
+ ...input.metricName !== void 0 ? {
999
+ goalMetrics: [
1000
+ {
1001
+ id: randomUUID(),
1002
+ name: input.metricName,
1003
+ status: input.metricStatus ?? "pending",
1004
+ ...input.metricTarget !== void 0 ? { target: input.metricTarget } : {},
1005
+ ...input.metricCurrent !== void 0 ? { current: input.metricCurrent } : {},
1006
+ ...input.metricUnit !== void 0 ? { unit: input.metricUnit } : {},
1007
+ ...input.metricNotes !== void 0 ? { notes: input.metricNotes } : {}
1008
+ }
1009
+ ]
1010
+ } : {},
1011
+ ...input.url !== void 0 ? {
1012
+ links: [
1013
+ {
1014
+ url: input.url,
1015
+ type: input.linkType ?? "url",
1016
+ ...input.linkTitle !== void 0 ? { title: input.linkTitle } : {}
1017
+ }
1018
+ ]
1019
+ } : {},
1020
+ ...input.note !== void 0 ? {
1021
+ notes: [
1022
+ {
1023
+ id: randomUUID(),
1024
+ author: input.author ?? "agent",
1025
+ content: input.note,
1026
+ createdAt: (/* @__PURE__ */ new Date()).toISOString()
1027
+ }
1028
+ ]
1029
+ } : {},
1030
+ ...[input.graphId, input.specId, input.specRequirementId].some((value) => value !== void 0) ? {
1031
+ origin: {
1032
+ system: input.sourceSystem ?? "kanban-tool",
1033
+ ...input.graphId !== void 0 ? { graphId: input.graphId } : {},
1034
+ ...input.specId !== void 0 ? { specId: input.specId } : {},
1035
+ ...input.specRequirementId !== void 0 ? { specRequirementId: input.specRequirementId } : {},
1036
+ ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {}
1037
+ }
1038
+ } : {}
1039
+ };
1040
+ }
1041
+ function mergedDependsOn(input) {
1042
+ const ids = [
1043
+ ...input.dependsOn ?? [],
1044
+ ...input.dependencyTaskId !== void 0 ? [input.dependencyTaskId] : []
1045
+ ].filter((id, i, arr) => id && arr.indexOf(id) === i);
1046
+ return ids.length > 0 ? ids : void 0;
1047
+ }
1048
+ function taskPatch(input) {
1049
+ return {
1050
+ title: input.title,
1051
+ description: input.description,
1052
+ dueDate: input.dueDate,
1053
+ columnId: input.columnId,
1054
+ order: input.order,
1055
+ priority: input.priority,
1056
+ ...input.taskType !== void 0 ? { type: input.taskType } : {},
1057
+ status: input.status,
1058
+ labels: input.labels,
1059
+ assignedAgent: input.agentId,
1060
+ ...mergedDependsOn(input) ? { dependsOn: mergedDependsOn(input) } : {},
1061
+ ...input.estimatedHours !== void 0 ? { estimatedHours: input.estimatedHours } : {},
1062
+ ...input.actualHours !== void 0 ? { actualHours: input.actualHours } : {}
1063
+ };
1064
+ }
1065
+ function clampRequestedCapabilities(requested) {
1066
+ if (requested === void 0) return void 0;
1067
+ return clampSubagentCapabilities(requested).granted;
1068
+ }
1069
+ function assignmentInput(input) {
1070
+ return {
1071
+ agentId: input.agentId,
1072
+ name: input.name,
1073
+ role: input.role,
1074
+ provider: input.provider,
1075
+ model: input.model,
1076
+ fallbackProfile: input.fallbackProfile,
1077
+ fallbackModels: input.fallbackModels,
1078
+ tools: input.tools,
1079
+ allowedCapabilities: clampRequestedCapabilities(input.allowedCapabilities),
1080
+ assignee: input.assignee,
1081
+ leaseId: input.leaseId,
1082
+ claimedAt: input.claimedAt,
1083
+ heartbeatAt: input.heartbeatAt,
1084
+ leaseExpiresAt: input.leaseExpiresAt,
1085
+ attempt: input.attempt,
1086
+ maxAttempts: input.maxAttempts,
1087
+ costCeilingUsd: input.costCeilingUsd,
1088
+ retryPolicy: input.retryPolicy,
1089
+ lastFailureKind: input.lastFailureKind
1090
+ };
1091
+ }
1092
+ function hasAssignmentInput(input) {
1093
+ return input.agentId !== void 0 || input.name !== void 0 || input.role !== void 0 || input.provider !== void 0 || input.model !== void 0 || input.fallbackProfile !== void 0 || input.fallbackModels !== void 0 || input.tools !== void 0 || input.allowedCapabilities !== void 0 || input.assignee !== void 0 || input.leaseId !== void 0 || input.claimedAt !== void 0 || input.heartbeatAt !== void 0 || input.leaseExpiresAt !== void 0 || input.attempt !== void 0 || input.maxAttempts !== void 0 || input.costCeilingUsd !== void 0 || input.retryPolicy !== void 0 || input.lastFailureKind !== void 0 || input.assignmentStatus !== void 0;
1094
+ }
1095
+ function assignmentForTaskCreate(input) {
1096
+ return {
1097
+ status: input.assignmentStatus ?? "assigned",
1098
+ ...input.agentId !== void 0 ? { agentId: input.agentId } : {},
1099
+ ...input.name !== void 0 ? { name: input.name } : {},
1100
+ ...input.role !== void 0 ? { role: input.role } : {},
1101
+ ...input.provider !== void 0 ? { provider: input.provider } : {},
1102
+ ...input.model !== void 0 ? { model: input.model } : {},
1103
+ ...input.fallbackProfile !== void 0 ? { fallbackProfile: input.fallbackProfile } : {},
1104
+ ...input.fallbackModels !== void 0 ? { fallbackModels: input.fallbackModels } : {},
1105
+ ...input.tools !== void 0 ? { tools: input.tools } : {},
1106
+ ...input.allowedCapabilities !== void 0 ? { allowedCapabilities: clampRequestedCapabilities(input.allowedCapabilities) } : {},
1107
+ ...input.leaseId !== void 0 ? { leaseId: input.leaseId } : {},
1108
+ ...input.claimedAt !== void 0 ? { claimedAt: input.claimedAt } : {},
1109
+ ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1110
+ ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1111
+ ...input.attempt !== void 0 ? { attempt: input.attempt } : {},
1112
+ ...input.maxAttempts !== void 0 ? { maxAttempts: input.maxAttempts } : {},
1113
+ ...input.costCeilingUsd !== void 0 ? { costCeilingUsd: input.costCeilingUsd } : {},
1114
+ ...input.retryPolicy !== void 0 ? { retryPolicy: input.retryPolicy } : {},
1115
+ ...input.lastFailureKind !== void 0 ? { lastFailureKind: input.lastFailureKind } : {}
1116
+ };
1117
+ }
1118
+
1119
+ // src/kanban-tool-schema.ts
1120
+ var KANBAN_TOOL_DESCRIPTION = "Manage and audit project-scoped multi-kanban boards through the shared IPC Kanban server and its SQLite store. Managed cards enforce fully specified details and adjacent Backlog \u2192 Todo \u2192 Running \u2192 Review \u2192 Done transitions with persistent comments and evidence. Contract Map actions are optional advisory metadata unless an operator explicitly enabled strict enforcement. Use verify_completion to validate executable success criteria before Done.";
1121
+ var KANBAN_TOOL_USAGE_HINT = "Use this for durable project kanban state. Read workbench when orienting across boards; it returns bounded Now, Next, Blocked, Review lanes and operational alerts. Before coding mutation, create a fully detailed card on a managed board with executable acceptance criteria, then call start_task. The runtime blocks product mutations until start_task binds a ready Running card. Do not create, inspect, repair, or enable a Contract Map during ordinary work; every map mode stays off the execution and completion path. Worker completion enters Review; Done requires passed acceptance criteria and review evidence. Surface existing strict-map findings for operator review without stopping work to repair them.";
1122
+ var KANBAN_INPUT_SCHEMA = {
1123
+ type: "object",
1124
+ properties: {
1125
+ action: {
1126
+ type: "string",
1127
+ enum: [
1128
+ "list_boards",
1129
+ "get_board",
1130
+ "create_board",
1131
+ "duplicate_board",
1132
+ "update_board",
1133
+ "adopt_managed_lifecycle",
1134
+ "delete_board",
1135
+ "generate_board",
1136
+ "export_markdown",
1137
+ "export_task_graph",
1138
+ "sync_task_graph",
1139
+ "create_from_graph",
1140
+ "import_session_tasks",
1141
+ "search_tasks",
1142
+ "ready_tasks",
1143
+ "snapshot",
1144
+ "workbench",
1145
+ "add_column",
1146
+ "update_column",
1147
+ "delete_column",
1148
+ "add_task",
1149
+ "split_task",
1150
+ "merge_tasks",
1151
+ "copy_task",
1152
+ "transfer_task",
1153
+ "get_task",
1154
+ "start_task",
1155
+ "update_task",
1156
+ "transition_task",
1157
+ "repair_managed_projection",
1158
+ "move_task",
1159
+ "delete_task",
1160
+ "set_chain",
1161
+ "get_chain",
1162
+ "get_contract_graph",
1163
+ "configure_contract_graph",
1164
+ "upsert_contract_node",
1165
+ "link_contract_nodes",
1166
+ "remove_contract_node",
1167
+ "remove_contract_edge",
1168
+ "evaluate_contract_graph",
1169
+ "claim_task",
1170
+ "release_task",
1171
+ "assign_task",
1172
+ "mark_assignment",
1173
+ "heartbeat_assignment",
1174
+ "recover_stale",
1175
+ "events",
1176
+ "queue_health",
1177
+ "add_dependency",
1178
+ "add_goal_metric",
1179
+ "update_goal_metric",
1180
+ "add_check",
1181
+ "update_check",
1182
+ "add_note",
1183
+ "add_link",
1184
+ "verify_completion",
1185
+ "split_atomic",
1186
+ "assess_atomicity",
1187
+ "propose_decomposition"
1188
+ ]
1189
+ },
1190
+ boardId: { type: "string" },
1191
+ taskId: { type: "string" },
1192
+ taskIds: { type: "array", items: { type: "string" } },
1193
+ chainId: { type: "string" },
1194
+ contractNodeId: { type: "string" },
1195
+ contractNodeKind: {
1196
+ type: "string",
1197
+ enum: ["objective", "guardrail", "risk", "component", "artifact", "verification"]
1198
+ },
1199
+ contractNodeState: {
1200
+ type: "string",
1201
+ enum: ["unknown", "active", "satisfied", "violated", "resolved"]
1202
+ },
1203
+ contractEnforcement: {
1204
+ type: "string",
1205
+ enum: ["blocking", "advisory", "informational"]
1206
+ },
1207
+ contractGraphEnforcement: { type: "string", enum: ["off", "advisory", "strict"] },
1208
+ contractEdgeId: { type: "string" },
1209
+ contractEdgeType: {
1210
+ type: "string",
1211
+ enum: [
1212
+ "targets",
1213
+ "affects",
1214
+ "must_preserve",
1215
+ "exposes",
1216
+ "verified_by",
1217
+ "conflicts_with",
1218
+ "derived_from",
1219
+ "relates_to"
1220
+ ]
1221
+ },
1222
+ fromNodeId: { type: "string" },
1223
+ toNodeId: { type: "string" },
1224
+ contractRationale: { type: "string" },
1225
+ baseline: { oneOf: [{ type: "string" }, { type: "number" }] },
1226
+ threshold: { oneOf: [{ type: "string" }, { type: "number" }] },
1227
+ columnId: { type: "string" },
1228
+ targetBoardId: { type: "string" },
1229
+ targetColumnId: { type: "string" },
1230
+ title: { type: "string" },
1231
+ description: { type: "string" },
1232
+ dueDate: { type: "string" },
1233
+ tags: { type: "array", items: { type: "string" } },
1234
+ labels: { type: "array", items: { type: "string" } },
1235
+ priority: { type: "string", enum: ["critical", "high", "medium", "low"] },
1236
+ taskType: {
1237
+ type: "string",
1238
+ enum: ["feature", "bugfix", "refactor", "docs", "test", "chore"]
1239
+ },
1240
+ status: {
1241
+ type: "string",
1242
+ enum: [
1243
+ "pending",
1244
+ "ready",
1245
+ "in_progress",
1246
+ "blocked",
1247
+ "review",
1248
+ "completed",
1249
+ "failed",
1250
+ "archived"
1251
+ ]
1252
+ },
1253
+ order: { type: "number" },
1254
+ query: { type: "string" },
1255
+ limit: { type: "number" },
1256
+ agentId: { type: "string" },
1257
+ name: { type: "string" },
1258
+ role: { type: "string" },
1259
+ provider: { type: "string" },
1260
+ model: { type: "string" },
1261
+ fallbackProfile: { type: "string" },
1262
+ fallbackModels: { type: "array", items: { type: "string" } },
1263
+ tools: { type: "array", items: { type: "string" } },
1264
+ allowedCapabilities: { type: "array", items: { type: "string" } },
1265
+ leaseId: { type: "string" },
1266
+ claimedAt: { type: "string" },
1267
+ heartbeatAt: { type: "string" },
1268
+ leaseExpiresAt: { type: "string" },
1269
+ attempt: { type: "number" },
1270
+ maxAttempts: { type: "number" },
1271
+ subagentId: { type: "string" },
1272
+ runTaskId: { type: "string" },
1273
+ lastResult: { type: "string" },
1274
+ error: { type: "string" },
1275
+ expectedLeaseId: { type: "string" },
1276
+ assignmentStatus: {
1277
+ type: "string",
1278
+ enum: ["assigned", "queued", "running", "completed", "failed", "cancelled"]
1279
+ },
1280
+ lifecycleStage: {
1281
+ type: "string",
1282
+ enum: ["backlog", "todo", "running", "review", "done"]
1283
+ },
1284
+ transitionAction: { type: "string" },
1285
+ transitionComment: { type: "string" },
1286
+ attachmentUrl: { type: "string" },
1287
+ attachmentTitle: { type: "string" },
1288
+ attachmentType: {
1289
+ type: "string",
1290
+ enum: ["issue", "pr", "doc", "commit", "design", "file", "url", "other"]
1291
+ },
1292
+ releaseStatus: { type: "string", enum: ["pending", "ready", "blocked"] },
1293
+ releaseReason: { type: "string" },
1294
+ clearAssignee: { type: "boolean" },
1295
+ recoveryMode: { type: "string", enum: ["auto", "release", "retry", "fail"] },
1296
+ recoveryNow: { type: "string" },
1297
+ recoveryPolicyFailOnCostCeiling: { type: "boolean" },
1298
+ recoveryPolicyReleaseOnFailureKinds: { type: "array", items: { type: "string" } },
1299
+ recoveryPolicyReleaseOnHeartbeatDue: { type: "boolean" },
1300
+ recoveryPolicyRetryPolicyOverride: {
1301
+ type: "string",
1302
+ enum: ["off", "incremental", "exponential"]
1303
+ },
1304
+ assignee: { type: "string" },
1305
+ costCeilingUsd: { type: "number" },
1306
+ retryPolicy: { type: "string", enum: ["off", "incremental", "exponential"] },
1307
+ lastFailureKind: { type: "string" },
1308
+ dependsOn: { type: "array", items: { type: "string" } },
1309
+ estimatedHours: { type: "number" },
1310
+ actualHours: { type: "number" },
1311
+ taskGraph: { type: "object" },
1312
+ graphId: { type: "string" },
1313
+ specId: { type: "string" },
1314
+ specRequirementId: { type: "string" },
1315
+ sourceSystem: { type: "string" },
1316
+ phaseId: { type: "string" },
1317
+ preserveOriginTaskIds: { type: "boolean" },
1318
+ includeArchived: { type: "boolean" },
1319
+ archiveMissingTasks: { type: "boolean" },
1320
+ preserveManualDependencies: { type: "boolean" },
1321
+ dependencyTaskId: { type: "string" },
1322
+ enforceDependencies: { type: "boolean" },
1323
+ childTitles: { type: "array", items: { type: "string" } },
1324
+ inheritAssignment: { type: "boolean" },
1325
+ inheritLabels: { type: "boolean" },
1326
+ inheritSuccessCriteria: { type: "boolean" },
1327
+ inheritGoalMetrics: { type: "boolean" },
1328
+ inheritDependencies: { type: "boolean" },
1329
+ chainChildren: { type: "boolean" },
1330
+ rewireDependents: { type: "boolean" },
1331
+ closeSourceTasks: { type: "boolean" },
1332
+ metricId: { type: "string" },
1333
+ metricName: { type: "string" },
1334
+ metricTarget: { oneOf: [{ type: "string" }, { type: "number" }] },
1335
+ metricCurrent: { oneOf: [{ type: "string" }, { type: "number" }] },
1336
+ metricUnit: { type: "string" },
1337
+ metricStatus: { type: "string", enum: ["pending", "met", "missed", "waived"] },
1338
+ metricNotes: { type: "string" },
1339
+ checkId: { type: "string" },
1340
+ checkDescription: { type: "string" },
1341
+ checkStatus: { type: "string", enum: ["pending", "passed", "failed", "skipped"] },
1342
+ note: { type: "string" },
1343
+ author: { type: "string" },
1344
+ url: { type: "string" },
1345
+ linkTitle: { type: "string" },
1346
+ linkType: {
1347
+ type: "string",
1348
+ enum: ["issue", "pr", "doc", "commit", "design", "file", "url", "other"]
1349
+ },
1350
+ context: { type: "string" },
1351
+ columns: { type: "array", items: { type: "string" } },
1352
+ generatedBy: { type: "string" },
1353
+ includeTasks: { type: "boolean" },
1354
+ includeCompletedTasks: { type: "boolean" },
1355
+ preserveAssignment: { type: "boolean" },
1356
+ preserveDependencies: { type: "boolean" },
1357
+ moveTasksToColumnId: { type: "string" },
1358
+ atomicityMode: { type: "string", enum: ["off", "assess", "enforce"] },
1359
+ atomicityDecomposition: { type: "string", enum: ["auto", "propose"] },
1360
+ gateEnforcement: {
1361
+ type: "string",
1362
+ // WS-023: `'off'` is deliberately absent. The agent whose work this gate
1363
+ // checks must not be able to switch it off; it may only tighten. Turning
1364
+ // a gate off stays a human decision, made through board config.
1365
+ enum: ["strict", "soft"]
1366
+ },
1367
+ subtasks: {
1368
+ type: "array",
1369
+ minItems: 2,
1370
+ items: {
1371
+ type: "object",
1372
+ properties: {
1373
+ title: { type: "string" },
1374
+ description: { type: "string" },
1375
+ successCriteria: { type: "array", items: { type: "string" } },
1376
+ dependsOnIndex: { type: "array", items: { type: "number" } }
1377
+ },
1378
+ required: ["title"]
1379
+ }
1380
+ }
1381
+ },
1382
+ required: ["action"]
1383
+ };
1384
+
1385
+ // src/kanban.ts
1386
+ var kanbanTool = {
1387
+ name: "kanban",
1388
+ category: "Project",
1389
+ description: KANBAN_TOOL_DESCRIPTION,
1390
+ usageHint: KANBAN_TOOL_USAGE_HINT,
1391
+ permission: "confirm",
1392
+ mutating: true,
1393
+ capabilities: ["fs.write"],
1394
+ icon: "task",
1395
+ timeoutMs: 3e4,
1396
+ inputSchema: KANBAN_INPUT_SCHEMA,
1397
+ async execute(input, ctx) {
1398
+ const projectRoot = ctx.projectRoot;
1399
+ if (!projectRoot) return fail("No project root is available.");
1400
+ const withPresence = createKanbanPresenceWrapper(projectRoot, input, ctx);
1401
+ try {
1402
+ const result = await (async () => {
1403
+ const decompositionResult = await handleKanbanDecompositionAction(projectRoot, input, ctx);
1404
+ if (decompositionResult !== void 0) return decompositionResult;
1405
+ switch (input.action) {
1406
+ case "list_boards": {
1407
+ const boards = await listBoards2(projectRoot);
1408
+ return { ok: true, message: `${boards.length} board(s).`, boards };
1409
+ }
1410
+ case "get_board": {
1411
+ const board = await requireBoard(projectRoot, input.boardId);
1412
+ return board ? okBoard(board) : fail("Board not found.");
1413
+ }
1414
+ case "create_board": {
1415
+ if (!input.title) return fail("create_board requires title.");
1416
+ const board = await createBoard2(projectRoot, boardCreateInput(input, input.title));
1417
+ return { ok: true, message: `Board created: ${board.title}`, board };
1418
+ }
1419
+ case "update_board": {
1420
+ if (!input.boardId) return fail("update_board requires boardId.");
1421
+ const board = await updateBoard2(projectRoot, input.boardId, boardUpdatePatch(input));
1422
+ return board ? okBoard(board, "Board updated.") : fail("Board not found.");
1423
+ }
1424
+ case "adopt_managed_lifecycle": {
1425
+ if (!input.boardId || !input.author || !input.transitionComment) {
1426
+ return fail(
1427
+ "adopt_managed_lifecycle requires boardId, author, transitionComment, and five ordered columns."
1428
+ );
1429
+ }
1430
+ if (input.columns?.length !== 5) {
1431
+ return fail(
1432
+ "adopt_managed_lifecycle columns must be ordered as backlog, todo, running, review, done."
1433
+ );
1434
+ }
1435
+ const [backlog, todo, running, review, done] = input.columns;
1436
+ if (!backlog || !todo || !running || !review || !done) {
1437
+ return fail("adopt_managed_lifecycle columns must contain five nonblank ids.");
1438
+ }
1439
+ const board = await adoptManagedLifecycle(projectRoot, input.boardId, {
1440
+ columns: { backlog, todo, running, review, done },
1441
+ actor: input.author,
1442
+ comment: input.transitionComment
1443
+ });
1444
+ return board ? okBoard(board, "Managed lifecycle adopted without moving existing cards.") : fail("Board not found.");
1445
+ }
1446
+ case "duplicate_board": {
1447
+ if (!input.boardId) return fail("duplicate_board requires boardId.");
1448
+ const board = await duplicateBoard(
1449
+ projectRoot,
1450
+ input.boardId,
1451
+ duplicateBoardOptions(input)
1452
+ );
1453
+ return board ? okBoard(board, "Board duplicated.") : fail("Board not found.");
1454
+ }
1455
+ case "delete_board": {
1456
+ if (!input.boardId) return fail("delete_board requires boardId.");
1457
+ const removed = await removeBoard2(projectRoot, input.boardId);
1458
+ return { ok: removed, message: removed ? "Board deleted." : "Board not found." };
1459
+ }
1460
+ case "generate_board": {
1461
+ if (!input.description) return fail("generate_board requires description.");
1462
+ const boardInput = createBoardFromText({
1463
+ description: input.description,
1464
+ ...input.title !== void 0 ? { title: input.title } : {},
1465
+ ...input.context !== void 0 ? { context: input.context } : {},
1466
+ ...input.columns !== void 0 ? { columns: input.columns } : {}
1467
+ });
1468
+ const board = await createBoard2(projectRoot, boardInput);
1469
+ for (const taskInput2 of parseLinesIntoTasks(
1470
+ input.description,
1471
+ board.columns[0]?.id ?? "backlog"
1472
+ )) {
1473
+ await addTask(projectRoot, board.id, taskInput2);
1474
+ }
1475
+ return okBoard(await getBoard3(projectRoot, board.id) ?? board, "Board generated.");
1476
+ }
1477
+ case "export_markdown": {
1478
+ const board = await requireBoard(projectRoot, input.boardId);
1479
+ if (!board) return fail("Board not found.");
1480
+ return {
1481
+ ok: true,
1482
+ message: "Board exported.",
1483
+ board,
1484
+ markdown: exportBoardAsMarkdown(board)
1485
+ };
1486
+ }
1487
+ case "export_task_graph": {
1488
+ if (!input.boardId) return fail("export_task_graph requires boardId.");
1489
+ const exported = await exportBoardToTaskGraph(projectRoot, input.boardId, {
1490
+ ...input.graphId !== void 0 ? { graphId: input.graphId } : {},
1491
+ ...input.specId !== void 0 ? { specId: input.specId } : {},
1492
+ ...input.title !== void 0 ? { title: input.title } : {},
1493
+ ...input.preserveOriginTaskIds !== void 0 ? { preserveOriginTaskIds: input.preserveOriginTaskIds } : {},
1494
+ ...input.includeArchived !== void 0 ? { includeArchived: input.includeArchived } : {}
1495
+ });
1496
+ if (!exported) return fail("Board not found.");
1497
+ return {
1498
+ ok: true,
1499
+ message: `Task graph exported with ${exported.graph.nodes.size} node(s).`,
1500
+ board: exported.board,
1501
+ taskGraph: serializeTaskGraph(exported.graph)
1502
+ };
1503
+ }
1504
+ case "sync_task_graph": {
1505
+ if (!input.boardId || !input.taskGraph) {
1506
+ return fail("sync_task_graph requires boardId and taskGraph.");
1507
+ }
1508
+ const graph = deserializeTaskGraph2(input.taskGraph);
1509
+ const result2 = await syncBoardFromTaskGraph2(projectRoot, input.boardId, graph, {
1510
+ ...input.title !== void 0 ? { title: input.title } : {},
1511
+ ...input.description !== void 0 ? { description: input.description } : {},
1512
+ ...input.tags !== void 0 ? { tags: input.tags } : {},
1513
+ ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
1514
+ ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
1515
+ ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
1516
+ ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {},
1517
+ ...input.archiveMissingTasks !== void 0 ? { archiveMissingTasks: input.archiveMissingTasks } : {},
1518
+ ...input.preserveManualDependencies !== void 0 ? { preserveManualDependencies: input.preserveManualDependencies } : {}
1519
+ });
1520
+ return result2 ? {
1521
+ ok: true,
1522
+ message: `Task graph synced: ${result2.createdTaskIds.length} created, ${result2.updatedTaskIds.length} updated, ${result2.archivedTaskIds.length} archived.`,
1523
+ board: result2.board
1524
+ } : fail("Board not found.");
1525
+ }
1526
+ case "create_from_graph": {
1527
+ if (!input.taskGraph) return fail("create_from_graph requires taskGraph.");
1528
+ const graph = deserializeTaskGraph2(input.taskGraph);
1529
+ const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
1530
+ ...input.title !== void 0 ? { title: input.title } : {},
1531
+ ...input.description !== void 0 ? { description: input.description } : {},
1532
+ ...input.tags !== void 0 ? { tags: input.tags } : {},
1533
+ ...input.generatedBy !== void 0 ? { generatedBy: input.generatedBy } : {},
1534
+ ...input.sourceSystem !== void 0 ? { sourceSystem: input.sourceSystem } : {},
1535
+ ...input.phaseId !== void 0 ? { phaseId: input.phaseId } : {},
1536
+ ...input.includeCompletedTasks !== void 0 ? { includeCompletedTasks: input.includeCompletedTasks } : {}
1537
+ });
1538
+ return {
1539
+ ok: true,
1540
+ message: `Created board "${board.title}" from task graph with ${board.tasks.length} tasks.`,
1541
+ board
1542
+ };
1543
+ }
1544
+ case "import_session_tasks": {
1545
+ const taskPath = ctx.meta?.["task.path"];
1546
+ if (!taskPath) return fail("No session task file for this session.");
1547
+ const file = await loadTasks2(taskPath);
1548
+ if (!file || file.tasks.length === 0) return fail("No session tasks to import.");
1549
+ const sessionId = ctx.session?.id ?? file.sessionId ?? "session";
1550
+ const graph = deserializeTaskGraph2(taskFileToSerializedGraph(file.tasks, sessionId));
1551
+ const tags = ["session", `session:${sessionId}`];
1552
+ const existing = (await listBoards2(projectRoot)).find(
1553
+ (b) => b.tags?.includes(`session:${sessionId}`)
1554
+ );
1555
+ if (existing) {
1556
+ const result2 = await syncBoardFromTaskGraph2(projectRoot, existing.id, graph, {
1557
+ sourceSystem: "session",
1558
+ tags,
1559
+ archiveMissingTasks: true,
1560
+ includeCompletedTasks: true
1561
+ });
1562
+ return result2 ? {
1563
+ ok: true,
1564
+ message: `Synced ${file.tasks.length} session tasks into board "${result2.board.title}".`,
1565
+ board: result2.board
1566
+ } : fail("Session board vanished mid-sync.");
1567
+ }
1568
+ const { board } = await createBoardFromTaskGraph(projectRoot, graph, {
1569
+ title: `Session tasks (${sessionId.slice(0, 8)})`,
1570
+ sourceSystem: "session",
1571
+ tags
1572
+ });
1573
+ return {
1574
+ ok: true,
1575
+ message: `Imported ${file.tasks.length} session tasks into new board "${board.title}".`,
1576
+ board
1577
+ };
1578
+ }
1579
+ case "search_tasks": {
1580
+ const tasks = await searchKanban(projectRoot, {
1581
+ query: input.query,
1582
+ boardId: input.boardId,
1583
+ assignedAgent: input.agentId,
1584
+ status: input.status,
1585
+ priority: input.priority,
1586
+ label: input.labels?.[0],
1587
+ chainId: input.chainId
1588
+ });
1589
+ return { ok: true, message: `${tasks.length} task(s) matched.`, tasks };
1590
+ }
1591
+ case "ready_tasks": {
1592
+ const tasks = await listReadyTasks(projectRoot, {
1593
+ query: input.query,
1594
+ boardId: input.boardId,
1595
+ assignedAgent: input.agentId,
1596
+ priority: input.priority,
1597
+ label: input.labels?.[0],
1598
+ chainId: input.chainId,
1599
+ limit: input.limit
1600
+ });
1601
+ return { ok: true, message: `${tasks.length} ready task(s).`, tasks };
1602
+ }
1603
+ case "snapshot": {
1604
+ const snapshot = await getKanbanOrchestrationSnapshot(projectRoot, {
1605
+ query: input.query,
1606
+ boardId: input.boardId,
1607
+ assignedAgent: input.agentId,
1608
+ status: input.status,
1609
+ priority: input.priority,
1610
+ label: input.labels?.[0],
1611
+ chainId: input.chainId
1612
+ });
1613
+ return {
1614
+ ok: true,
1615
+ message: `${snapshot.ready.length} ready, ${snapshot.running.length} running, ${snapshot.blocked.length} blocked.`,
1616
+ snapshot
1617
+ };
1618
+ }
1619
+ case "add_column": {
1620
+ if (!input.boardId || !input.title)
1621
+ return fail("add_column requires boardId and title.");
1622
+ const result2 = await addColumn(projectRoot, input.boardId, {
1623
+ title: input.title,
1624
+ ...input.description !== void 0 ? { description: input.description } : {}
1625
+ });
1626
+ return result2 ? okBoard(result2.board, "Column added.") : fail("Board not found.");
1627
+ }
1628
+ case "update_column": {
1629
+ if (!input.boardId || !input.columnId)
1630
+ return fail("update_column requires boardId and columnId.");
1631
+ const board = await updateColumn(projectRoot, input.boardId, input.columnId, {
1632
+ ...input.title !== void 0 ? { title: input.title } : {},
1633
+ ...input.description !== void 0 ? { description: input.description } : {},
1634
+ ...input.order !== void 0 ? { order: input.order } : {}
1635
+ });
1636
+ return board ? okBoard(board, "Column updated.") : fail("Column not found.");
1637
+ }
1638
+ case "delete_column": {
1639
+ if (!input.boardId || !input.columnId)
1640
+ return fail("delete_column requires boardId and columnId.");
1641
+ const board = await removeColumn(projectRoot, input.boardId, input.columnId, {
1642
+ moveTasksToColumnId: input.moveTasksToColumnId
1643
+ });
1644
+ return board ? okBoard(board, "Column deleted.") : fail("Column not found.");
1645
+ }
1646
+ case "add_task": {
1647
+ if (!input.boardId || !input.title) return fail("add_task requires boardId and title.");
1648
+ const result2 = await addTask(projectRoot, input.boardId, taskInput(input));
1649
+ if (!result2) return fail("Board not found.");
1650
+ return okTask(result2.board, result2.task, `Task added.${atomicityNudge(result2.task)}`);
1651
+ }
1652
+ case "split_task": {
1653
+ if (!input.boardId || !input.taskId || !input.childTitles?.length) {
1654
+ return fail("split_task requires boardId, taskId, and childTitles.");
1655
+ }
1656
+ return handleSplitTask(projectRoot, input, {});
1657
+ }
1658
+ case "merge_tasks": {
1659
+ if (!input.boardId || !input.taskIds?.length || !input.title) {
1660
+ return fail("merge_tasks requires boardId, taskIds, and title.");
1661
+ }
1662
+ const result2 = await mergeTasks(projectRoot, input.boardId, {
1663
+ taskIds: input.taskIds,
1664
+ title: input.title,
1665
+ ...input.description !== void 0 ? { description: input.description } : {},
1666
+ ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1667
+ ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1668
+ ...input.closeSourceTasks !== void 0 ? { closeSourceTasks: input.closeSourceTasks } : {}
1669
+ });
1670
+ return result2 ? okTask(result2.board, result2.task, "Tasks merged.") : fail("Board or task not found.");
1671
+ }
1672
+ case "copy_task": {
1673
+ if (!input.boardId || !input.taskId || !input.targetBoardId) {
1674
+ return fail("copy_task requires boardId, taskId, and targetBoardId.");
1675
+ }
1676
+ const result2 = await copyTaskToBoard(
1677
+ projectRoot,
1678
+ input.boardId,
1679
+ input.taskId,
1680
+ input.targetBoardId,
1681
+ {
1682
+ ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1683
+ ...input.order !== void 0 ? { targetOrder: input.order } : {},
1684
+ ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1685
+ ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1686
+ }
1687
+ );
1688
+ return result2 ? okTask(result2.targetBoard, result2.task, "Task copied to target board.") : fail("Board or task not found.");
1689
+ }
1690
+ case "transfer_task": {
1691
+ if (!input.boardId || !input.taskId || !input.targetBoardId) {
1692
+ return fail("transfer_task requires boardId, taskId, and targetBoardId.");
1693
+ }
1694
+ const result2 = await transferTaskToBoard(
1695
+ projectRoot,
1696
+ input.boardId,
1697
+ input.taskId,
1698
+ input.targetBoardId,
1699
+ {
1700
+ ...input.targetColumnId !== void 0 ? { targetColumnId: input.targetColumnId } : {},
1701
+ ...input.order !== void 0 ? { targetOrder: input.order } : {},
1702
+ ...input.preserveAssignment !== void 0 ? { preserveAssignment: input.preserveAssignment } : {},
1703
+ ...input.preserveDependencies !== void 0 ? { preserveDependencies: input.preserveDependencies } : {}
1704
+ }
1705
+ );
1706
+ return result2 ? okTask(result2.targetBoard, result2.task, "Task transferred to target board.") : fail("Board or task not found.");
1707
+ }
1708
+ case "get_task": {
1709
+ if (!input.boardId || !input.taskId)
1710
+ return fail("get_task requires boardId and taskId.");
1711
+ const task = await getTask(projectRoot, input.boardId, input.taskId);
1712
+ return task ? { ok: true, message: "Task loaded.", task } : fail("Task not found.");
1713
+ }
1714
+ case "start_task": {
1715
+ if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1716
+ return fail("start_task requires boardId, taskId, author, and transitionComment.");
1717
+ }
1718
+ let board = await getBoard3(projectRoot, input.boardId);
1719
+ let task = board?.tasks.find((candidate) => candidate.id === input.taskId);
1720
+ if (!board || !task) return fail("Board or task not found.");
1721
+ const readiness = evaluateContractGraphReadiness(board, task.id);
1722
+ if (!readiness.ready) {
1723
+ return fail(
1724
+ `Task is not implementation-ready: ${readiness.issues.map((issue) => issue.message).join(" | ")}`
1725
+ );
1726
+ }
1727
+ let stage = task.lifecycle?.currentStage;
1728
+ if (stage === "backlog") {
1729
+ const moved = await transitionTask(projectRoot, board.id, task.id, {
1730
+ to: "todo",
1731
+ actor: input.author,
1732
+ comment: input.transitionComment
1733
+ });
1734
+ if (!moved) return fail("Task could not enter Todo.");
1735
+ board = moved.board;
1736
+ task = moved.task;
1737
+ stage = task.lifecycle?.currentStage;
1738
+ }
1739
+ if (stage === "todo" || stage === "review") {
1740
+ const now = /* @__PURE__ */ new Date();
1741
+ const leaseId = input.leaseId ?? randomUUID2();
1742
+ const assigned = await updateTaskAssignment(projectRoot, board.id, task.id, {
1743
+ status: "running",
1744
+ agentId: input.agentId ?? input.author,
1745
+ leaseId,
1746
+ claimedAt: input.claimedAt ?? now.toISOString(),
1747
+ heartbeatAt: input.heartbeatAt ?? now.toISOString(),
1748
+ leaseExpiresAt: input.leaseExpiresAt ?? new Date(now.getTime() + 15 * 6e4).toISOString(),
1749
+ attempt: input.attempt ?? 1,
1750
+ maxAttempts: input.maxAttempts ?? 3
1751
+ });
1752
+ if (!assigned) return fail("Task assignment could not be started.");
1753
+ const moved = await transitionTask(projectRoot, board.id, task.id, {
1754
+ to: "running",
1755
+ actor: input.author,
1756
+ comment: input.transitionComment
1757
+ });
1758
+ if (!moved) return fail("Task could not enter Running.");
1759
+ board = moved.board;
1760
+ task = moved.task;
1761
+ stage = task.lifecycle?.currentStage;
1762
+ }
1763
+ if (stage !== "running" || task.assignment?.status !== "running") {
1764
+ return fail(
1765
+ `start_task only accepts Backlog, Todo, Review repair, or live Running cards (current: ${stage ?? "unknown"}).`
1766
+ );
1767
+ }
1768
+ ctx.setCurrentKanbanTask(task.id, board.id);
1769
+ return okTask(
1770
+ board,
1771
+ task,
1772
+ "Task is active; runtime Kanban governance is now bound to this run."
1773
+ );
1774
+ }
1775
+ case "update_task": {
1776
+ if (!input.boardId || !input.taskId)
1777
+ return fail("update_task requires boardId and taskId.");
1778
+ const board = await updateTask2(
1779
+ projectRoot,
1780
+ input.boardId,
1781
+ input.taskId,
1782
+ taskPatch(input)
1783
+ );
1784
+ return board ? okBoard(board, "Task updated.") : fail("Task not found.");
1785
+ }
1786
+ case "transition_task": {
1787
+ if (!input.boardId || !input.taskId || !input.lifecycleStage || !input.author || !input.transitionComment) {
1788
+ return fail(
1789
+ "transition_task requires boardId, taskId, lifecycleStage, author, and transitionComment."
1790
+ );
1791
+ }
1792
+ if (input.lifecycleStage === "done") {
1793
+ const boardBefore = await getBoard3(projectRoot, input.boardId);
1794
+ const taskBefore = boardBefore ? await getTask(projectRoot, input.boardId, input.taskId) : null;
1795
+ if (boardBefore && taskBefore && !taskBefore.verificationReport && (taskBefore.atomic || Boolean(taskBefore.successCriteria?.length))) {
1796
+ const preGate = await verifyTaskCompletion2(
1797
+ projectRoot,
1798
+ input.boardId,
1799
+ taskBefore.id,
1800
+ {
1801
+ persist: false
1802
+ }
1803
+ );
1804
+ await updateTask2(projectRoot, input.boardId, taskBefore.id, {
1805
+ verificationReport: preGate.report,
1806
+ successCriteria: preGate.task.successCriteria
1807
+ });
1808
+ }
1809
+ }
1810
+ const result2 = await transitionTask(projectRoot, input.boardId, input.taskId, {
1811
+ to: input.lifecycleStage,
1812
+ actor: input.author,
1813
+ comment: input.transitionComment,
1814
+ ...input.transitionAction !== void 0 ? { action: input.transitionAction } : {},
1815
+ ...input.attachmentUrl !== void 0 ? {
1816
+ attachment: {
1817
+ url: input.attachmentUrl,
1818
+ type: input.attachmentType ?? "url",
1819
+ ...input.attachmentTitle !== void 0 ? { title: input.attachmentTitle } : {}
1820
+ }
1821
+ } : {},
1822
+ patch: taskPatch(input)
1823
+ });
1824
+ if (result2 && input.lifecycleStage === "done" && result2.task.verificationReport) {
1825
+ recordKanbanVerificationEvidence(ctx, result2.task.verificationReport);
1826
+ }
1827
+ return result2 ? okTask(result2.board, result2.task, `Task advanced to ${result2.transition.to}.`) : fail("Board or task not found.");
1828
+ }
1829
+ case "repair_managed_projection": {
1830
+ if (!input.boardId || !input.taskId || !input.author || !input.transitionComment) {
1831
+ return fail(
1832
+ "repair_managed_projection requires boardId, taskId, author, and transitionComment."
1833
+ );
1834
+ }
1835
+ const result2 = await repairManagedTaskProjection(
1836
+ projectRoot,
1837
+ input.boardId,
1838
+ input.taskId,
1839
+ {
1840
+ actor: input.author,
1841
+ comment: input.transitionComment
1842
+ }
1843
+ );
1844
+ return result2 ? okTask(
1845
+ result2.board,
1846
+ result2.task,
1847
+ "Managed card projection repaired from lifecycle history."
1848
+ ) : fail("Board or task not found.");
1849
+ }
1850
+ case "move_task": {
1851
+ if (!input.boardId || !input.taskId || !input.targetColumnId) {
1852
+ return fail("move_task requires boardId, taskId, and targetColumnId.");
1853
+ }
1854
+ const board = await moveTask(
1855
+ projectRoot,
1856
+ input.boardId,
1857
+ input.taskId,
1858
+ input.targetColumnId,
1859
+ input.order
1860
+ );
1861
+ return board ? okBoard(board, "Task moved.") : fail("Move failed.");
1862
+ }
1863
+ case "delete_task": {
1864
+ if (!input.boardId || !input.taskId)
1865
+ return fail("delete_task requires boardId and taskId.");
1866
+ const board = await removeTask(projectRoot, input.boardId, input.taskId);
1867
+ return board ? okBoard(board, "Task deleted.") : fail("Task not found.");
1868
+ }
1869
+ case "set_chain": {
1870
+ if (!input.boardId || !input.taskIds?.length) {
1871
+ return fail("set_chain requires boardId and taskIds.");
1872
+ }
1873
+ const result2 = await setTaskChain(projectRoot, input.boardId, {
1874
+ taskIds: input.taskIds,
1875
+ ...input.chainId !== void 0 ? { chainId: input.chainId } : {},
1876
+ ...input.enforceDependencies !== void 0 ? { enforceDependencies: input.enforceDependencies } : {}
1877
+ });
1878
+ return result2 ? {
1879
+ ok: true,
1880
+ message: `Chain set: ${result2.chainId}`,
1881
+ board: result2.board,
1882
+ chain: result2.tasks
1883
+ } : fail("Board or task not found.");
1884
+ }
1885
+ case "get_chain": {
1886
+ if (!input.boardId || !(input.taskId || input.chainId)) {
1887
+ return fail("get_chain requires boardId and taskId or chainId.");
1888
+ }
1889
+ const result2 = await getTaskChain(
1890
+ projectRoot,
1891
+ input.boardId,
1892
+ input.taskId ?? input.chainId ?? ""
1893
+ );
1894
+ return result2 ? {
1895
+ ok: true,
1896
+ message: `Chain loaded: ${result2.chainId}`,
1897
+ board: result2.board,
1898
+ chain: result2.tasks
1899
+ } : fail("Chain not found.");
1900
+ }
1901
+ case "claim_task": {
1902
+ const result2 = await claimReadyTask(projectRoot, {
1903
+ ...input.boardId !== void 0 ? { boardId: input.boardId } : {},
1904
+ ...input.taskId !== void 0 ? { taskId: input.taskId } : {},
1905
+ ...assignmentInput(input),
1906
+ status: input.assignmentStatus ?? "queued"
1907
+ });
1908
+ return result2 ? okTask(result2.board, result2.task, "Task claimed.") : fail("No ready kanban task matched the claim.");
1909
+ }
1910
+ case "release_task": {
1911
+ if (!input.boardId || !input.taskId) {
1912
+ return fail("release_task requires boardId and taskId.");
1913
+ }
1914
+ const board = await releaseTaskClaim(projectRoot, input.boardId, input.taskId, {
1915
+ ...input.releaseStatus !== void 0 ? { status: input.releaseStatus } : {},
1916
+ ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
1917
+ ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {}
1918
+ });
1919
+ return board ? okBoard(board, "Task claim released.") : fail("Task not found.");
1920
+ }
1921
+ case "assign_task": {
1922
+ if (!input.boardId || !input.taskId)
1923
+ return fail("assign_task requires boardId and taskId.");
1924
+ const board = await assignTask(
1925
+ projectRoot,
1926
+ input.boardId,
1927
+ input.taskId,
1928
+ assignmentInput(input)
1929
+ );
1930
+ return board ? okBoard(board, "Task assigned.") : fail("Task not found.");
1931
+ }
1932
+ case "mark_assignment": {
1933
+ if (!input.boardId || !input.taskId)
1934
+ return fail("mark_assignment requires boardId and taskId.");
1935
+ const assignmentStatus = input.assignmentStatus ?? (input.status === "completed" ? "completed" : input.error ? "failed" : void 0);
1936
+ const board = await updateTaskAssignment(
1937
+ projectRoot,
1938
+ input.boardId,
1939
+ input.taskId,
1940
+ {
1941
+ ...assignmentStatus !== void 0 ? { status: assignmentStatus } : {},
1942
+ ...input.subagentId !== void 0 ? { subagentId: input.subagentId } : {},
1943
+ ...input.runTaskId !== void 0 ? { runTaskId: input.runTaskId } : {},
1944
+ ...input.lastResult !== void 0 ? { lastResult: input.lastResult } : {},
1945
+ ...input.error !== void 0 ? { error: input.error } : {},
1946
+ ...input.agentId !== void 0 ? { agentId: input.agentId } : {},
1947
+ ...input.leaseId !== void 0 ? { leaseId: input.leaseId } : {},
1948
+ ...input.claimedAt !== void 0 ? { claimedAt: input.claimedAt } : {},
1949
+ ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
1950
+ ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
1951
+ ...input.attempt !== void 0 ? { attempt: input.attempt } : {},
1952
+ ...input.maxAttempts !== void 0 ? { maxAttempts: input.maxAttempts } : {}
1953
+ },
1954
+ // Ownership fence: when expectedLeaseId is supplied, the write is
1955
+ // applied only if the current assignment still holds this lease.
1956
+ // This prevents a recovered+reassigned stale worker's terminal
1957
+ // mark_assignment from overwriting the successor's state. The check
1958
+ // is atomic inside updateTaskAssignment's mutateBoard lock.
1959
+ input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
1960
+ );
1961
+ if (!board) return fail("Task not found.");
1962
+ if (assignmentStatus === "completed" && board.lifecycle?.mode !== "managed") {
1963
+ const envGate = readEnvGateEnforcement();
1964
+ const finalized = await finalizeTaskCompletion(projectRoot, board.id, input.taskId, {
1965
+ ...board.completionGate === void 0 && envGate !== void 0 ? { enforcement: envGate } : {},
1966
+ ...ctx.agentId !== void 0 ? { eventContext: { actor: ctx.agentId } } : {}
1967
+ });
1968
+ if (finalized) {
1969
+ if (finalized.gate.report) {
1970
+ recordKanbanVerificationEvidence(ctx, finalized.gate.report);
1971
+ }
1972
+ const gateSummary = {
1973
+ enforcement: finalized.gate.enforcement,
1974
+ allowed: finalized.gate.allowed,
1975
+ verdict: finalized.gate.verdict,
1976
+ issues: finalized.gate.issues.map((issue) => issue.message)
1977
+ };
1978
+ 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(" | ")}`;
1979
+ return {
1980
+ ...okTask(finalized.board, finalized.task, `Assignment updated. ${gateMessage}`),
1981
+ gate: gateSummary
1982
+ };
1983
+ }
1984
+ } else if (board.lifecycle?.mode === "managed") {
1985
+ const managedTask = board.tasks.find((candidate) => candidate.id === input.taskId);
1986
+ const stage = managedTask?.lifecycle?.currentStage;
1987
+ const actor = ctx.agentId ?? "kanban-agent";
1988
+ let transitionResult = null;
1989
+ const lifecycleWarnings = [];
1990
+ if (assignmentStatus === "running" && stage === "todo") {
1991
+ try {
1992
+ transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
1993
+ to: "running",
1994
+ actor,
1995
+ comment: "Work started."
1996
+ });
1997
+ } catch (err) {
1998
+ lifecycleWarnings.push(
1999
+ `Lifecycle transition to Running deferred: ${err instanceof Error ? err.message : String(err)}`
2000
+ );
2001
+ }
2002
+ }
2003
+ if (assignmentStatus === "completed" && stage === "running") {
2004
+ const comment = typeof input.lastResult === "string" && input.lastResult.trim().length > 0 ? input.lastResult.trim().slice(0, 1e3) : "Work completed.";
2005
+ try {
2006
+ transitionResult = await transitionTask(projectRoot, board.id, input.taskId, {
2007
+ to: "review",
2008
+ actor,
2009
+ comment,
2010
+ attachment: {
2011
+ url: `kanban://task/${input.taskId}/result`,
2012
+ title: "Worker completion result",
2013
+ type: "file"
2014
+ },
2015
+ patch: {
2016
+ // Only patch non-description fields so the
2017
+ // original card description is preserved.
2018
+ ...input.agentId !== void 0 ? { assignedAgent: input.agentId } : {}
2019
+ }
2020
+ });
2021
+ } catch (err) {
2022
+ lifecycleWarnings.push(
2023
+ `Lifecycle transition to Review failed: ${err instanceof Error ? err.message : String(err)}`
2024
+ );
2025
+ }
2026
+ if (transitionResult) {
2027
+ const hasCriteria = (transitionResult.task.successCriteria?.length ?? 0) > 0 || transitionResult.task.atomic === true;
2028
+ if (hasCriteria) {
2029
+ try {
2030
+ const verResult = await verifyTaskCompletion2(
2031
+ projectRoot,
2032
+ board.id,
2033
+ input.taskId
2034
+ );
2035
+ if (verResult.report) {
2036
+ recordKanbanVerificationEvidence(ctx, verResult.report);
2037
+ }
2038
+ await updateTask2(projectRoot, board.id, input.taskId, {
2039
+ verificationReport: verResult.report,
2040
+ successCriteria: verResult.task.successCriteria
2041
+ });
2042
+ const verdict = verResult.report.verdict;
2043
+ if (verdict === "passed") {
2044
+ try {
2045
+ const doneResult = await transitionTask(
2046
+ projectRoot,
2047
+ board.id,
2048
+ input.taskId,
2049
+ {
2050
+ to: "done",
2051
+ actor,
2052
+ action: "Automated acceptance after verification",
2053
+ comment: "Auto-accepted: verification passed.",
2054
+ attachment: {
2055
+ url: `kanban://task/${input.taskId}/verification`,
2056
+ title: "Auto-verification result",
2057
+ type: "file"
2058
+ }
2059
+ }
2060
+ );
2061
+ transitionResult = doneResult;
2062
+ } catch (acceptErr) {
2063
+ lifecycleWarnings.push(
2064
+ `Auto-accept to Done deferred: ${acceptErr instanceof Error ? acceptErr.message : String(acceptErr)}`
2065
+ );
2066
+ }
2067
+ } else {
2068
+ lifecycleWarnings.push(
2069
+ `Verification verdict: ${verdict} \u2014 card left in Review for manual acceptance.`
2070
+ );
2071
+ }
2072
+ } catch (verifyErr) {
2073
+ lifecycleWarnings.push(
2074
+ `Auto-verification error: ${verifyErr instanceof Error ? verifyErr.message : String(verifyErr)}`
2075
+ );
2076
+ }
2077
+ } else {
2078
+ lifecycleWarnings.push(
2079
+ "No automatic success criteria \u2014 card left in Review for manual verification."
2080
+ );
2081
+ }
2082
+ }
2083
+ }
2084
+ const responseBoard = transitionResult?.board ?? board;
2085
+ const responseTask = transitionResult?.task ?? managedTask;
2086
+ const msgParts = ["Assignment updated."];
2087
+ if (transitionResult) {
2088
+ msgParts.push(`Card advanced to ${transitionResult.transition.to}.`);
2089
+ }
2090
+ for (const w of lifecycleWarnings) msgParts.push(`Warning: ${w}`);
2091
+ return okTask(responseBoard, responseTask, msgParts.join(" "));
2092
+ }
2093
+ return okBoard(board, "Assignment updated.");
2094
+ }
2095
+ case "heartbeat_assignment": {
2096
+ if (!input.boardId || !input.taskId) {
2097
+ return fail("heartbeat_assignment requires boardId and taskId.");
2098
+ }
2099
+ const board = await heartbeatTaskAssignment(projectRoot, input.boardId, input.taskId, {
2100
+ ...input.heartbeatAt !== void 0 ? { heartbeatAt: input.heartbeatAt } : {},
2101
+ ...input.leaseExpiresAt !== void 0 ? { leaseExpiresAt: input.leaseExpiresAt } : {},
2102
+ // Ownership fence: when expectedLeaseId is supplied, the renewal
2103
+ // is applied only if the current assignment still holds this lease.
2104
+ // This prevents a recovered+reassigned stale worker's heartbeat
2105
+ // from renewing the successor's lease. The check is atomic inside
2106
+ // heartbeatTaskAssignment's mutateBoard lock.
2107
+ ...input.expectedLeaseId !== void 0 ? { expectedLeaseId: input.expectedLeaseId } : {}
2108
+ });
2109
+ return board ? okBoard(board, "Assignment heartbeat updated.") : fail("Task assignment not found.");
2110
+ }
2111
+ case "recover_stale": {
2112
+ if (!input.boardId) return fail("recover_stale requires boardId.");
2113
+ const policyFields = [
2114
+ input.recoveryPolicyFailOnCostCeiling !== void 0,
2115
+ input.recoveryPolicyReleaseOnFailureKinds !== void 0,
2116
+ input.recoveryPolicyReleaseOnHeartbeatDue !== void 0,
2117
+ input.recoveryPolicyRetryPolicyOverride !== void 0
2118
+ ].some(Boolean);
2119
+ const result2 = await recoverStaleTaskAssignments(projectRoot, input.boardId, {
2120
+ ...input.recoveryMode !== void 0 ? { mode: input.recoveryMode } : {},
2121
+ ...input.recoveryNow !== void 0 ? { now: input.recoveryNow } : {},
2122
+ ...input.releaseReason !== void 0 ? { reason: input.releaseReason } : {},
2123
+ ...input.clearAssignee !== void 0 ? { clearAssignee: input.clearAssignee } : {},
2124
+ ...policyFields ? {
2125
+ policy: {
2126
+ ...input.recoveryPolicyFailOnCostCeiling !== void 0 ? { failWhenCostCeilingSet: input.recoveryPolicyFailOnCostCeiling } : {},
2127
+ ...input.recoveryPolicyReleaseOnFailureKinds !== void 0 ? {
2128
+ releaseOnFailureKinds: input.recoveryPolicyReleaseOnFailureKinds
2129
+ } : {},
2130
+ ...input.recoveryPolicyReleaseOnHeartbeatDue !== void 0 ? {
2131
+ releaseOnHeartbeatDue: input.recoveryPolicyReleaseOnHeartbeatDue
2132
+ } : {},
2133
+ ...input.recoveryPolicyRetryPolicyOverride !== void 0 ? {
2134
+ retryPolicyOverride: input.recoveryPolicyRetryPolicyOverride
2135
+ } : {}
2136
+ }
2137
+ } : {}
2138
+ });
2139
+ return result2 ? {
2140
+ ok: true,
2141
+ message: `Recovered ${result2.tasks.length} stale assignment(s).`,
2142
+ board: result2.board,
2143
+ recoveredTasks: result2.tasks
2144
+ } : { ok: true, message: "No stale assignment matched.", recoveredTasks: [] };
2145
+ }
2146
+ case "events": {
2147
+ if (!input.boardId) return fail("events requires boardId.");
2148
+ const eventList = await listKanbanEvents(projectRoot, input.boardId);
2149
+ return {
2150
+ ok: true,
2151
+ message: `${eventList.length} event(s).`,
2152
+ events: eventList
2153
+ };
2154
+ }
2155
+ case "queue_health": {
2156
+ const health = await getKanbanQueueHealth(projectRoot, {
2157
+ ...input.boardId !== void 0 ? { boardId: input.boardId } : {}
2158
+ });
2159
+ return {
2160
+ ok: true,
2161
+ message: `Counts: ready=${health.counts.ready}, running=${health.counts.running}, stale=${health.staleAssignments.count}.`,
2162
+ queueHealth: health
2163
+ };
2164
+ }
2165
+ default:
2166
+ {
2167
+ const detailResult = await handleKanbanDetailAction(projectRoot, input);
2168
+ if (detailResult !== void 0) return detailResult;
2169
+ }
2170
+ return fail(`Unknown kanban action: ${input.action}`);
2171
+ }
2172
+ })();
2173
+ return withPresence(result);
2174
+ } catch (err) {
2175
+ return fail(err instanceof Error ? err.message : String(err));
2176
+ }
2177
+ }
2178
+ };
2179
+
2180
+ // src/todo.ts
2181
+ function normalizedTitle(value) {
2182
+ return value.trim().toLocaleLowerCase().replace(/\s+/g, " ");
2183
+ }
2184
+ function activeBoardId(items, ctx) {
2185
+ const metaKanban = ctx.meta?.["kanban"];
2186
+ const metaBoardId = metaKanban && typeof metaKanban === "object" ? metaKanban["boardId"] : void 0;
2187
+ return ctx.currentKanbanBoardId ?? (typeof metaBoardId === "string" ? metaBoardId : void 0) ?? items.find((item) => item.kanbanBoardId)?.kanbanBoardId ?? "";
2188
+ }
2189
+ function bindTodosToBoard(items, previous, board) {
2190
+ const previousById = new Map(previous.map((item) => [item.id, item]));
2191
+ const available = board.tasks.filter(
2192
+ (task) => task.status !== "archived" && task.mergedIntoTaskId === void 0 && (!task.childTaskIds || task.childTaskIds.length === 0)
2193
+ ).sort(
2194
+ (left, right) => left.createdAt.localeCompare(right.createdAt) || left.order - right.order
2195
+ );
2196
+ const used = /* @__PURE__ */ new Set();
2197
+ return items.map((item) => {
2198
+ const previousItem = previousById.get(item.id);
2199
+ const requestedTaskId = item.kanbanBoardId === board.id ? item.kanbanTaskId : previousItem?.kanbanBoardId === board.id ? previousItem.kanbanTaskId : void 0;
2200
+ const title = normalizedTitle(item.content);
2201
+ const candidates = [
2202
+ requestedTaskId ? board.tasks.find((task2) => task2.id === requestedTaskId) : void 0,
2203
+ board.tasks.find((task2) => task2.id === item.id),
2204
+ board.tasks.find((task2) => task2.origin?.taskId === item.id),
2205
+ available.find((task2) => !used.has(task2.id) && normalizedTitle(task2.title) === title)
2206
+ ];
2207
+ const task = candidates.find((candidate) => candidate && !used.has(candidate.id));
2208
+ if (!task) return { ...item };
2209
+ used.add(task.id);
2210
+ return { ...item, kanbanBoardId: board.id, kanbanTaskId: task.id };
2211
+ });
2212
+ }
2213
+ async function synchronizeManagedKanban(items, board, ctx, signal) {
2214
+ let synced = 0;
2215
+ const warnings = [];
2216
+ const actor = ctx.agentId?.trim() || ctx.agentName?.trim() || "kanban-agent";
2217
+ const execute = async (input) => {
2218
+ const result = await kanbanTool.execute(input, ctx, { signal });
2219
+ if (!result.ok) warnings.push(result.message);
2220
+ else {
2221
+ synced++;
2222
+ if (result.message.includes("Warning:")) warnings.push(result.message);
2223
+ }
2224
+ return result;
2225
+ };
2226
+ for (const item of items) {
2227
+ if (item.status !== "pending" || item.kanbanBoardId !== board.id || !item.kanbanTaskId) {
2228
+ continue;
2229
+ }
2230
+ const task = board.tasks.find((candidate) => candidate.id === item.kanbanTaskId);
2231
+ if (task?.lifecycle?.currentStage !== "running") continue;
2232
+ const released = await execute({
2233
+ action: "mark_assignment",
2234
+ boardId: board.id,
2235
+ taskId: task.id,
2236
+ assignmentStatus: "assigned",
2237
+ agentId: actor,
2238
+ lastResult: `Todo returned to queue: ${item.content}`
2239
+ });
2240
+ if (!released.ok) continue;
2241
+ await execute({
2242
+ action: "transition_task",
2243
+ boardId: board.id,
2244
+ taskId: task.id,
2245
+ lifecycleStage: "todo",
2246
+ author: actor,
2247
+ transitionComment: `Todo returned to queue: ${item.content}`
2248
+ });
2249
+ }
2250
+ for (const item of items) {
2251
+ if (item.status !== "completed" || item.kanbanBoardId !== board.id || !item.kanbanTaskId) {
2252
+ continue;
2253
+ }
2254
+ const task = board.tasks.find((candidate) => candidate.id === item.kanbanTaskId);
2255
+ if (!task || task.status === "completed") continue;
2256
+ await execute({
2257
+ action: "mark_assignment",
2258
+ boardId: board.id,
2259
+ taskId: task.id,
2260
+ assignmentStatus: "completed",
2261
+ agentId: actor,
2262
+ lastResult: `Todo completed: ${item.content}`
2263
+ });
2264
+ }
2265
+ const attemptedParents = /* @__PURE__ */ new Set();
2266
+ let afterCompletions = await getBoard4(ctx.projectRoot, board.id);
2267
+ while (afterCompletions) {
2268
+ const parent = afterCompletions.tasks.find(
2269
+ (task) => task.atomic === true && task.status !== "completed" && Boolean(task.childTaskIds?.length) && !attemptedParents.has(task.id) && task.childTaskIds?.every(
2270
+ (childId) => afterCompletions?.tasks.find((candidate) => candidate.id === childId)?.status === "completed"
2271
+ )
2272
+ );
2273
+ if (!parent) break;
2274
+ attemptedParents.add(parent.id);
2275
+ const started = await execute({
2276
+ action: "start_task",
2277
+ boardId: board.id,
2278
+ taskId: parent.id,
2279
+ author: actor,
2280
+ agentId: actor,
2281
+ transitionComment: "All child tasks completed; validating composite parent."
2282
+ });
2283
+ if (started.ok) {
2284
+ await execute({
2285
+ action: "mark_assignment",
2286
+ boardId: board.id,
2287
+ taskId: parent.id,
2288
+ assignmentStatus: "completed",
2289
+ agentId: actor,
2290
+ lastResult: "All child tasks completed; composite result ready for verification."
2291
+ });
2292
+ }
2293
+ afterCompletions = await getBoard4(ctx.projectRoot, board.id);
2294
+ }
2295
+ const completionPending = items.some(
2296
+ (item) => item.status === "completed" && item.kanbanBoardId === board.id && Boolean(item.kanbanTaskId) && afterCompletions?.tasks.find((task) => task.id === item.kanbanTaskId)?.status !== "completed"
2297
+ );
2298
+ const active = items.find(
2299
+ (item) => item.status === "in_progress" && item.kanbanBoardId === board.id && Boolean(item.kanbanTaskId)
2300
+ );
2301
+ if (active?.kanbanTaskId) {
2302
+ await execute({
2303
+ action: "start_task",
2304
+ boardId: board.id,
2305
+ taskId: active.kanbanTaskId,
2306
+ author: actor,
2307
+ agentId: actor,
2308
+ transitionComment: `Todo activated: ${active.content}`
2309
+ });
2310
+ }
2311
+ if (active?.kanbanTaskId && completionPending) {
2312
+ warnings.push(
2313
+ "A completed todo is still awaiting acceptance; the next independent Kanban task was started."
2314
+ );
2315
+ } else if (!active && ctx.currentKanbanBoardId === board.id) {
2316
+ ctx.setCurrentKanbanTask(void 0, board.id);
2317
+ }
2318
+ return { synced, warnings };
2319
+ }
2320
+ var todoTool = {
2321
+ name: "todo",
2322
+ category: "Session",
2323
+ description: "Manage the compact active-work list. With a managed Kanban binding, every row resolves to a real card and status changes advance that card; without Kanban it remains session-only state. Each call replaces ordering and supplied fields, but unfinished omitted rows are retained until completed.",
2324
+ usageHint: "BEST PRACTICE for complex tasks:\n- At the beginning of a non-trivial task, create a clear todo list with specific, actionable items.\n- Only **one** item should be `in_progress` at any time.\n- Update the list frequently as work progresses (mark items done, add new ones, change status).\n- **Re-order items** to reflect current priorities. Omission is not cancellation: unfinished rows are retained until completed.\n- When all items are completed the board auto-clears \u2014 you do NOT need to send an empty list.\n- The system and user can see this list, so keep it honest and up-to-date.\nThis tool is extremely valuable for maintaining focus and giving the user visibility into your plan.",
2325
+ permission: "confirm",
2326
+ mutating: true,
2327
+ timeoutMs: 3e4,
2328
+ capabilities: ["session.todo", "fs.write"],
2329
+ subjectKey: "todos",
2330
+ icon: "todo",
2331
+ inputSchema: {
2332
+ type: "object",
2333
+ properties: {
2334
+ todos: {
2335
+ type: "array",
2336
+ items: {
2337
+ type: "object",
2338
+ properties: {
2339
+ id: {
2340
+ type: "string",
2341
+ description: 'Unique identifier for the todo item (e.g. "1", "auth-flow").'
2342
+ },
2343
+ content: {
2344
+ type: "string",
2345
+ description: "Clear, actionable description of the task."
2346
+ },
2347
+ status: {
2348
+ type: "string",
2349
+ enum: ["pending", "in_progress", "completed"],
2350
+ description: 'Current status. Only one item should be "in_progress" at a time.'
2351
+ },
2352
+ activeForm: {
2353
+ type: "string",
2354
+ description: 'Optional present-tense form shown while the task is active (e.g. "Fixing auth bug").'
2355
+ },
2356
+ kanbanBoardId: {
2357
+ type: "string",
2358
+ description: "Kanban board that owns this UI row when Kanban is active."
2359
+ },
2360
+ kanbanTaskId: {
2361
+ type: "string",
2362
+ description: "Real Kanban task represented by this UI row."
2363
+ }
2364
+ },
2365
+ required: ["id", "content", "status"]
2366
+ },
2367
+ description: "The desired todo list. Supplied rows are replaced/reordered; unfinished omitted rows are retained."
2368
+ }
2369
+ },
2370
+ required: ["todos"]
2371
+ },
2372
+ async execute(input, ctx, call) {
2373
+ if (!Array.isArray(input?.todos)) {
2374
+ throw new Error("todo: todos must be an array");
2375
+ }
2376
+ const items = input.todos.filter((t) => Boolean(t?.id && t.content));
2377
+ const todoIdentity = (item) => item.kanbanBoardId && item.kanbanTaskId ? `kanban:${item.kanbanBoardId}:${item.kanbanTaskId}` : item.promotedFromTask ? `task:${item.promotedFromTask}` : item.promotedFromPlan ? `plan:${item.promotedFromPlan}` : `todo:${item.id}`;
2378
+ const requestedIdentities = new Set(items.map(todoIdentity));
2379
+ for (const previous of ctx.todos ?? []) {
2380
+ const identity = todoIdentity(previous);
2381
+ if (previous.status === "completed" || requestedIdentities.has(identity)) {
2382
+ continue;
2383
+ }
2384
+ items.push({ ...previous });
2385
+ requestedIdentities.add(identity);
2386
+ }
2387
+ const inProgress = items.filter((t) => t.status === "in_progress");
2388
+ if (inProgress.length > 1) {
2389
+ let seenInProgress = false;
2390
+ for (const item of items) {
2391
+ if (item.status === "in_progress") {
2392
+ if (seenInProgress) item.status = "pending";
2393
+ seenInProgress = true;
2394
+ }
2395
+ }
2396
+ }
2397
+ const boardId = activeBoardId(items, ctx);
2398
+ const board = boardId ? await getBoard4(ctx.projectRoot, boardId) : null;
2399
+ const boundItems = board?.lifecycle?.mode === "managed" ? bindTodosToBoard(items, ctx.todos ?? [], board) : items;
2400
+ ctx.state.replaceTodos(boundItems);
2401
+ const kanbanSync = board?.lifecycle?.mode === "managed" ? await synchronizeManagedKanban(boundItems, board, ctx, call.signal) : { synced: 0, warnings: [] };
2402
+ if (board?.lifecycle?.mode === "managed") {
2403
+ const unresolved = boundItems.filter(
2404
+ (item) => item.kanbanBoardId !== board.id || !item.kanbanTaskId
2405
+ );
2406
+ if (unresolved.length > 0) {
2407
+ kanbanSync.warnings.push(
2408
+ `${unresolved.length} Todo row(s) did not match a real Kanban task and were not applied. Preserve kanbanBoardId/kanbanTaskId when updating the projection.`
2409
+ );
2410
+ }
2411
+ }
2412
+ let projectedBoard = board;
2413
+ if (board?.lifecycle?.mode === "managed") {
2414
+ const refreshed = await getBoard4(ctx.projectRoot, board.id);
2415
+ if (refreshed) {
2416
+ projectedBoard = refreshed;
2417
+ applyManagedKanbanBoardToTodos(ctx, refreshed);
2418
+ }
2419
+ }
2420
+ if (board?.lifecycle?.mode !== "managed") {
2421
+ mirrorSessionTodosToKanban(ctx.projectRoot, items, ctx.session?.id ?? "session");
2422
+ }
2423
+ const completedPlanIds = /* @__PURE__ */ new Set();
2424
+ const completedTaskIds = /* @__PURE__ */ new Set();
2425
+ const pendingPlanIds = /* @__PURE__ */ new Set();
2426
+ const pendingTaskIds = /* @__PURE__ */ new Set();
2427
+ for (const item of items) {
2428
+ if (item.promotedFromPlan) {
2429
+ (item.status === "completed" ? completedPlanIds : pendingPlanIds).add(
2430
+ item.promotedFromPlan
2431
+ );
2432
+ }
2433
+ if (item.promotedFromTask) {
2434
+ (item.status === "completed" ? completedTaskIds : pendingTaskIds).add(
2435
+ item.promotedFromTask
2436
+ );
2437
+ }
2438
+ }
2439
+ for (const planId of completedPlanIds) {
2440
+ if (pendingPlanIds.has(planId)) continue;
2441
+ const planPath = ctx.meta["plan.path"];
2442
+ if (typeof planPath !== "string" || !planPath) continue;
2443
+ try {
2444
+ const plan = await loadPlan2(planPath);
2445
+ if (plan) {
2446
+ const updated = setPlanItemStatus(plan, planId, "done");
2447
+ await savePlan(planPath, updated);
2448
+ }
2449
+ } catch {
2450
+ }
2451
+ }
2452
+ for (const taskId of completedTaskIds) {
2453
+ if (pendingTaskIds.has(taskId)) continue;
2454
+ const taskPath = ctx.meta["task.path"];
2455
+ if (typeof taskPath !== "string" || !taskPath) continue;
2456
+ try {
2457
+ const file = await loadTasks3(taskPath);
2458
+ if (file) {
2459
+ const task = file.tasks.find((t) => t.id === taskId);
2460
+ if (task && task.status !== "completed") {
2461
+ task.status = "completed";
2462
+ task.updatedAt = (/* @__PURE__ */ new Date()).toISOString();
2463
+ await saveTasks(taskPath, file);
2464
+ }
2465
+ }
2466
+ } catch {
2467
+ }
2468
+ }
2469
+ return {
2470
+ count: items.length,
2471
+ in_progress: (ctx.todos ?? boundItems).filter((t) => t.status === "in_progress").length,
2472
+ ...kanbanSync.synced > 0 ? { kanban_synced: kanbanSync.synced } : {},
2473
+ ...kanbanSync.warnings.length > 0 ? { kanban_warnings: kanbanSync.warnings } : {},
2474
+ ...projectedBoard?.lifecycle?.mode === "managed" ? {
2475
+ kanban_bindings: boundItems.flatMap((item) => {
2476
+ if (item.kanbanBoardId !== projectedBoard.id || !item.kanbanTaskId) return [];
2477
+ const task = projectedBoard.tasks.find(
2478
+ (candidate) => candidate.id === item.kanbanTaskId
2479
+ );
2480
+ return task ? [
2481
+ {
2482
+ todoId: item.id,
2483
+ boardId: projectedBoard.id,
2484
+ taskId: task.id,
2485
+ taskStatus: task.status
2486
+ }
2487
+ ] : [];
2488
+ })
2489
+ } : {}
2490
+ };
2491
+ }
2492
+ };
168
2493
 
169
2494
  // src/plan.ts
170
2495
  var planTool = {
171
2496
  name: "plan",
172
2497
  category: "Session",
173
2498
  description: 'Manage a session-persistent strategic plan. The plan is written to disk and survives conversation resumptions within the same session, but is isolated to this session \u2014 other sessions have their own separate plans. Unlike todos (which are per-turn and lost on restart), a plan tracks high-level progress across multiple turns. Use this to outline big-picture work, then promote concrete items into the todo list when ready to execute. By default plans are isolated to this session; use `scope: "project"` to store the plan in a shared project-level file visible to all sessions.',
174
- usageHint: 'RECOMMENDED FOR COMPLEX, MULTI-PHASE WORK:\n\n- Start by creating a high-level plan with `action: "add"` or using templates (`template_use`).\n- Use `promote` to turn a plan item into actionable todos.\n- Use `taskify` to convert a plan item into a structured task (with type/priority/deps).\n- Keep plans at the "why and what" level, and todos at the "how and next step" level.\n- Common templates: "new-feature", "bug-fix", "refactor", "release", "security-audit".\n\nThis tool is excellent for maintaining long-term direction across many turns within a session. Plans survive resume but are not shared across separate sessions.\nUse `scope: "project"` to use a shared project-level plan file.',
2499
+ usageHint: 'RECOMMENDED FOR COMPLEX, MULTI-PHASE WORK:\n\n- Start by creating a high-level plan with `action: "add"` or using templates (`template_use`).\n- Use `action: "status"` with `open`, `in_progress`, or `done` for exact status changes.\n- Use `promote` to turn a plan item into actionable todos.\n- Use `taskify` to convert a plan item into a structured task (with type/priority/deps).\n- Unfinished plan items cannot be removed or cleared; complete them first.\n- Keep plans at the "why and what" level, and todos at the "how and next step" level.\n- Common templates: "new-feature", "bug-fix", "refactor", "release", "security-audit".\n\nThis tool is excellent for maintaining long-term direction across many turns within a session. Plans survive resume but are not shared across separate sessions.\nUse `scope: "project"` to use a shared project-level plan file.',
175
2500
  permission: "confirm",
176
2501
  // WS-046: gives permission decisions something to key on.
177
2502
  // The action performed; plan has no single file or path subject.
@@ -179,7 +2504,7 @@ var planTool = {
179
2504
  mutating: true,
180
2505
  capabilities: ["fs.write"],
181
2506
  icon: "plan",
182
- timeoutMs: 2e3,
2507
+ timeoutMs: 3e4,
183
2508
  inputSchema: {
184
2509
  type: "object",
185
2510
  properties: {
@@ -188,6 +2513,7 @@ var planTool = {
188
2513
  enum: [
189
2514
  "show",
190
2515
  "add",
2516
+ "status",
191
2517
  "start",
192
2518
  "done",
193
2519
  "remove",
@@ -210,6 +2536,11 @@ var planTool = {
210
2536
  type: "string",
211
2537
  description: "Identifier for the target plan item (id, 1-based index, or partial title). Required for most actions except add/show/clear."
212
2538
  },
2539
+ status: {
2540
+ type: "string",
2541
+ enum: ["open", "in_progress", "done"],
2542
+ description: "Exact plan item status for action=status."
2543
+ },
213
2544
  subtasks: {
214
2545
  type: "array",
215
2546
  items: { type: "string" },
@@ -254,6 +2585,7 @@ var planTool = {
254
2585
  let early = null;
255
2586
  const taskifyMeta = { title: "", details: "" };
256
2587
  let didTaskify = false;
2588
+ let todosToReplace = null;
257
2589
  let plan;
258
2590
  try {
259
2591
  plan = await mutatePlan2(planPath, sessionId, async (p) => {
@@ -279,7 +2611,7 @@ var planTool = {
279
2611
  );
280
2612
  return p;
281
2613
  }
282
- const next = setPlanItemStatus(
2614
+ const next = setPlanItemStatus2(
283
2615
  p,
284
2616
  input.target,
285
2617
  input.action === "start" ? "in_progress" : "done"
@@ -290,6 +2622,22 @@ var planTool = {
290
2622
  }
291
2623
  return next;
292
2624
  }
2625
+ case "status": {
2626
+ if (!input.target || !input.status) {
2627
+ early = mkResult(
2628
+ p,
2629
+ false,
2630
+ "status requires `target` (id|index|substring) and `status`."
2631
+ );
2632
+ return p;
2633
+ }
2634
+ const next = setPlanItemStatus2(p, input.target, input.status);
2635
+ if (next === p) {
2636
+ early = mkResult(p, false, `No plan item matched "${input.target}".`);
2637
+ return p;
2638
+ }
2639
+ return next;
2640
+ }
293
2641
  case "remove": {
294
2642
  if (!input.target) {
295
2643
  early = mkResult(p, false, "remove requires `target` (id|index|substring).");
@@ -300,6 +2648,16 @@ var planTool = {
300
2648
  early = mkResult(p, false, `No plan item matched "${input.target}".`);
301
2649
  return p;
302
2650
  }
2651
+ const nextIds = new Set(next.items.map((item) => item.id));
2652
+ const removed = p.items.find((item) => !nextIds.has(item.id));
2653
+ if (removed?.status !== "done") {
2654
+ early = mkResult(
2655
+ p,
2656
+ false,
2657
+ `Plan item "${removed?.title ?? input.target}" is not done and cannot be removed. Complete it first.`
2658
+ );
2659
+ return p;
2660
+ }
303
2661
  return next;
304
2662
  }
305
2663
  case "promote": {
@@ -316,7 +2674,7 @@ var planTool = {
316
2674
  early = mkResult(p, false, `No plan item matched "${input.target}".`);
317
2675
  return p;
318
2676
  }
319
- ctx.state.replaceTodos(derived.todos);
2677
+ todosToReplace = derived.todos;
320
2678
  early = mkResult(
321
2679
  derived.plan,
322
2680
  true,
@@ -348,6 +2706,14 @@ var planTool = {
348
2706
  return updated;
349
2707
  }
350
2708
  case "clear":
2709
+ if (p.items.some((item) => item.status !== "done")) {
2710
+ early = mkResult(
2711
+ p,
2712
+ false,
2713
+ "Plan contains unfinished items and cannot be cleared. Complete them first."
2714
+ );
2715
+ return p;
2716
+ }
351
2717
  return clearPlan(p);
352
2718
  case "taskify": {
353
2719
  if (!input.target) {
@@ -395,6 +2761,11 @@ var planTool = {
395
2761
  };
396
2762
  }
397
2763
  await projectSessionPlanToKanban(ctx.projectRoot, plan.items, sessionId);
2764
+ if (todosToReplace) {
2765
+ await todoTool.execute({ todos: todosToReplace }, ctx, {
2766
+ signal: AbortSignal.timeout(3e4)
2767
+ });
2768
+ }
398
2769
  if (early) return early;
399
2770
  if (didTaskify) {
400
2771
  const taskPathRaw = ctx.meta["task.path"];
@@ -410,7 +2781,7 @@ var planTool = {
410
2781
  try {
411
2782
  const taskFile = await mutateTasks2(taskPath, sessionId, (f) => {
412
2783
  f.tasks.push({
413
- id: `task_${randomUUID()}`,
2784
+ id: `task_${randomUUID3()}`,
414
2785
  title: taskifyMeta.title,
415
2786
  description: taskifyMeta.details || void 0,
416
2787
  type: "feature",