claude-flow 3.77.1 → 3.77.2

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 (43) hide show
  1. package/.claude/helpers/hook-handler.cjs +85 -5
  2. package/README.md +12 -2
  3. package/node_modules/@claude-flow/plugin-agent-federation/README.md +18 -0
  4. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.d.ts +4 -1
  5. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.d.ts.map +1 -1
  6. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js +11 -0
  7. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-dispatcher.js.map +1 -1
  8. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.d.ts +29 -0
  9. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.d.ts.map +1 -0
  10. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.js +96 -0
  11. package/node_modules/@claude-flow/plugin-agent-federation/dist/application/inbound-envelope-guard.js.map +1 -0
  12. package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.d.ts.map +1 -1
  13. package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.js +3 -0
  14. package/node_modules/@claude-flow/plugin-agent-federation/dist/plugin.js.map +1 -1
  15. package/package.json +8 -5
  16. package/v3/@claude-flow/cli/README.md +5 -0
  17. package/v3/@claude-flow/cli/bin/cli.js +8 -3
  18. package/v3/@claude-flow/cli/dist/src/commands/init.js +8 -1
  19. package/v3/@claude-flow/cli/dist/src/commands/session.js +2 -1
  20. package/v3/@claude-flow/cli/dist/src/commands/workflow.js +2 -1
  21. package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +85 -5
  22. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.js +26 -25
  23. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +161 -157
  24. package/v3/@claude-flow/cli/dist/src/mcp-tools/claims-tools.js +257 -258
  25. package/v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.js +48 -29
  26. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +6 -0
  27. package/v3/@claude-flow/cli/dist/src/mcp-tools/locked-json-store.d.ts +20 -0
  28. package/v3/@claude-flow/cli/dist/src/mcp-tools/locked-json-store.js +99 -0
  29. package/v3/@claude-flow/cli/dist/src/mcp-tools/managed-agent-tools.js +51 -7
  30. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +19 -9
  31. package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.js +299 -270
  32. package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.js +245 -215
  33. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +5 -4
  34. package/v3/@claude-flow/cli/dist/src/missions/schemas.d.ts +38 -38
  35. package/v3/@claude-flow/cli/dist/src/mods/command-registry/schema.d.ts +210 -210
  36. package/v3/@claude-flow/cli/dist/src/services/managed-run-store.d.ts +11 -0
  37. package/v3/@claude-flow/cli/dist/src/services/managed-run-store.js +125 -3
  38. package/v3/@claude-flow/cli/dist/src/services/policy-runtime.d.ts +3 -0
  39. package/v3/@claude-flow/cli/dist/src/services/policy-runtime.js +3 -1
  40. package/v3/@claude-flow/cli/package.json +9 -6
  41. package/v3/@claude-flow/guidance/package.json +1 -0
  42. package/.claude/.proven-config-version +0 -1
  43. package/.claude/proven-config.json +0 -42
@@ -3,11 +3,12 @@
3
3
  *
4
4
  * Tool definitions for task management with file persistence.
5
5
  */
6
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
6
+ import { existsSync, readFileSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
8
  import { readRecordStore } from './record-store.js';
9
9
  import { getProjectCwd } from './types.js';
10
10
  import { validateIdentifier, validateText } from './validate-input.js';
11
+ import { saved, unchanged, updateJsonStore } from './locked-json-store.js';
11
12
  // Storage paths
12
13
  const STORAGE_DIR = '.claude-flow';
13
14
  const TASK_DIR = 'tasks';
@@ -33,18 +34,14 @@ function getTaskDir() {
33
34
  function getTaskPath() {
34
35
  return join(getTaskDir(), TASK_FILE);
35
36
  }
36
- function ensureTaskDir() {
37
- const dir = getTaskDir();
38
- if (!existsSync(dir)) {
39
- mkdirSync(dir, { recursive: true });
40
- }
41
- }
42
37
  function loadTaskStore() {
43
38
  return readRecordStore(getTaskPath(), 'tasks', () => ({ tasks: {}, version: '3.0.0' }));
44
39
  }
45
- function saveTaskStore(store) {
46
- ensureTaskDir();
47
- writeFileSync(getTaskPath(), JSON.stringify(store, null, 2), 'utf-8');
40
+ /** Every task write goes through here, under the tasks lock. */
41
+ async function updateTasks(mutate) {
42
+ const { response, afterSave } = await updateJsonStore(getTaskPath(), loadTaskStore, mutate, 'tasks');
43
+ await afterSave?.();
44
+ return response;
48
45
  }
49
46
  /**
50
47
  * Apply an agent-state change to every store that holds the agent.
@@ -55,7 +52,7 @@ function saveTaskStore(store) {
55
52
  * busy, and completing one never counted it: `hive-mind status` showed the
56
53
  * worker idle with 0 completed while its task sat in the queue.
57
54
  */
58
- function updateAgents(agentIds, mutate) {
55
+ async function updateAgents(agentIds, mutate) {
59
56
  if (agentIds.length === 0)
60
57
  return;
61
58
  const paths = [
@@ -66,18 +63,19 @@ function updateAgents(agentIds, mutate) {
66
63
  try {
67
64
  if (!existsSync(path))
68
65
  continue;
69
- const store = JSON.parse(readFileSync(path, 'utf-8'));
70
- if (!store.agents)
71
- continue;
72
- let touched = false;
73
- for (const id of agentIds) {
74
- if (Object.prototype.hasOwnProperty.call(store.agents, id) && store.agents[id]) {
75
- mutate(store.agents[id]);
76
- touched = true;
66
+ // Same lock as agent_* tools, so a concurrent agent write is not lost.
67
+ await updateJsonStore(path, () => JSON.parse(readFileSync(path, 'utf-8')), (store) => {
68
+ if (!store.agents)
69
+ return unchanged(undefined);
70
+ let touched = false;
71
+ for (const id of agentIds) {
72
+ if (Object.prototype.hasOwnProperty.call(store.agents, id) && store.agents[id]) {
73
+ mutate(store.agents[id]);
74
+ touched = true;
75
+ }
77
76
  }
78
- }
79
- if (touched)
80
- writeFileSync(path, JSON.stringify(store, null, 2), 'utf-8');
77
+ return { result: undefined, save: touched };
78
+ }, 'agents');
81
79
  }
82
80
  catch {
83
81
  // Best-effort agent sync: a corrupt agent store must not fail the task op.
@@ -86,7 +84,7 @@ function updateAgents(agentIds, mutate) {
86
84
  }
87
85
  /** Return agents still holding `taskId` to idle. */
88
86
  function releaseAgents(agentIds, taskId) {
89
- updateAgents(agentIds, (agent) => {
87
+ return updateAgents(agentIds, (agent) => {
90
88
  if (agent.currentTask === taskId) {
91
89
  agent.status = 'idle';
92
90
  agent.currentTask = null;
@@ -152,7 +150,6 @@ export const taskTools = [
152
150
  || !input.assignTo.every(id => validateIdentifier(id, 'assignTo').valid))) {
153
151
  return { success: false, error: 'assignTo must be an array of agent ids' };
154
152
  }
155
- const store = loadTaskStore();
156
153
  const taskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
157
154
  const task = {
158
155
  taskId,
@@ -167,25 +164,28 @@ export const taskTools = [
167
164
  startedAt: null,
168
165
  completedAt: null,
169
166
  };
170
- store.tasks[taskId] = task;
171
- saveTaskStore(store);
172
- // Assigning at creation must mark the workers busy, as task_assign and task_update do;
173
- // otherwise they read idle while holding the task, and task_complete or task_cancel,
174
- // which only release a worker whose currentTask is this task, never free them either.
175
- updateAgents(task.assignedTo, (agent) => {
176
- agent.status = 'busy';
177
- agent.currentTask = taskId;
167
+ return updateTasks((store) => {
168
+ store.tasks[taskId] = task;
169
+ return saved({
170
+ response: {
171
+ taskId,
172
+ type: task.type,
173
+ description: task.description,
174
+ priority: task.priority,
175
+ status: task.status,
176
+ createdAt: task.createdAt,
177
+ assignedTo: task.assignedTo,
178
+ tags: task.tags,
179
+ },
180
+ // Assigning at creation must mark the workers busy, as task_assign and task_update do;
181
+ // otherwise they read idle while holding the task, and task_complete or task_cancel,
182
+ // which only release a worker whose currentTask is this task, never free them either.
183
+ afterSave: () => updateAgents(task.assignedTo, (agent) => {
184
+ agent.status = 'busy';
185
+ agent.currentTask = taskId;
186
+ }),
187
+ });
178
188
  });
179
- return {
180
- taskId,
181
- type: task.type,
182
- description: task.description,
183
- priority: task.priority,
184
- status: task.status,
185
- createdAt: task.createdAt,
186
- assignedTo: task.assignedTo,
187
- tags: task.tags,
188
- };
189
189
  },
190
190
  },
191
191
  {
@@ -311,40 +311,46 @@ export const taskTools = [
311
311
  const vId = validateIdentifier(input.taskId, 'taskId');
312
312
  if (!vId.valid)
313
313
  return { success: false, error: vId.error };
314
- const store = loadTaskStore();
315
314
  const taskId = input.taskId;
316
- const task = store.tasks[taskId];
317
- if (task) {
318
- if (task.status === 'completed') {
319
- return { taskId: task.taskId, status: task.status, completedAt: task.completedAt, result: task.result };
320
- }
321
- task.status = 'completed';
322
- task.progress = 100;
323
- task.completedAt = new Date().toISOString();
324
- task.result = input.result || {};
325
- saveTaskStore(store);
326
- // Sync assigned agents back to idle and increment taskCount. Credited only to a worker
327
- // still holding this task, as task_update does, so completing a reopened task again
328
- // (complete -> pending -> complete, no reassignment) never counts the same work twice.
329
- updateAgents(task.assignedTo, (agent) => {
330
- if (agent.currentTask === taskId) {
331
- agent.status = 'idle';
332
- agent.currentTask = null;
333
- agent.taskCount = (agent.taskCount || 0) + 1;
315
+ return updateTasks((store) => {
316
+ const task = store.tasks[taskId];
317
+ if (task) {
318
+ if (task.status === 'completed') {
319
+ return unchanged({
320
+ response: { taskId: task.taskId, status: task.status, completedAt: task.completedAt, result: task.result },
321
+ });
334
322
  }
323
+ task.status = 'completed';
324
+ task.progress = 100;
325
+ task.completedAt = new Date().toISOString();
326
+ task.result = input.result || {};
327
+ return saved({
328
+ response: {
329
+ taskId: task.taskId,
330
+ status: task.status,
331
+ completedAt: task.completedAt,
332
+ result: task.result,
333
+ },
334
+ // Sync assigned agents back to idle and increment taskCount. Credited only to a worker
335
+ // still holding this task, as task_update does, so completing a reopened task again
336
+ // (complete -> pending -> complete, no reassignment) never counts the same work twice.
337
+ afterSave: () => updateAgents(task.assignedTo, (agent) => {
338
+ if (agent.currentTask === taskId) {
339
+ agent.status = 'idle';
340
+ agent.currentTask = null;
341
+ agent.taskCount = (agent.taskCount || 0) + 1;
342
+ }
343
+ }),
344
+ });
345
+ }
346
+ return unchanged({
347
+ response: {
348
+ taskId,
349
+ status: 'not_found',
350
+ error: 'Task not found',
351
+ },
335
352
  });
336
- return {
337
- taskId: task.taskId,
338
- status: task.status,
339
- completedAt: task.completedAt,
340
- result: task.result,
341
- };
342
- }
343
- return {
344
- taskId,
345
- status: 'not_found',
346
- error: 'Task not found',
347
- };
353
+ });
348
354
  },
349
355
  },
350
356
  {
@@ -379,89 +385,93 @@ export const taskTools = [
379
385
  || !input.assignTo.every(id => validateIdentifier(id, 'assignTo').valid))) {
380
386
  return { success: false, error: 'assignTo must be an array of agent ids' };
381
387
  }
382
- const store = loadTaskStore();
383
388
  const taskId = input.taskId;
384
- const task = store.tasks[taskId];
385
- if (task) {
386
- // Worker effects run AFTER the task store is saved, as task_complete does: a failed save must not leave
387
- // workers freed and counted against a task that still reads unfinished.
388
- let afterSave;
389
- const previouslyAssigned = Array.isArray(task.assignedTo) ? [...task.assignedTo] : [];
390
- if (status !== undefined) {
391
- const newStatus = status;
392
- const wasCompleted = task.status === 'completed';
393
- task.status = newStatus;
394
- if (newStatus === 'in_progress' && !task.startedAt) {
395
- task.startedAt = new Date().toISOString();
389
+ return updateTasks((store) => {
390
+ const task = store.tasks[taskId];
391
+ if (task) {
392
+ // Worker effects run AFTER the task store is saved, as task_complete does: a failed save must not leave
393
+ // workers freed and counted against a task that still reads unfinished.
394
+ let afterSave;
395
+ const previouslyAssigned = Array.isArray(task.assignedTo) ? [...task.assignedTo] : [];
396
+ if (status !== undefined) {
397
+ const newStatus = status;
398
+ const wasCompleted = task.status === 'completed';
399
+ task.status = newStatus;
400
+ if (newStatus === 'in_progress' && !task.startedAt) {
401
+ task.startedAt = new Date().toISOString();
402
+ }
403
+ // Reopening a finished task (completed/failed/cancelled -> pending/in_progress) makes it unfinished
404
+ // again, so it must not keep reporting the completedAt of the run that was undone.
405
+ if (newStatus === 'pending' || newStatus === 'in_progress') {
406
+ task.completedAt = null;
407
+ }
408
+ // A finished task frees its workers, as task_complete and task_cancel do; otherwise a worker
409
+ // whose task was finished through task_update stays `busy` forever, and a later task_complete
410
+ // returns early because the status already reads completed.
411
+ if (newStatus === 'failed' || newStatus === 'cancelled') {
412
+ task.completedAt = new Date().toISOString();
413
+ afterSave = () => releaseAgents(previouslyAssigned, taskId);
414
+ }
415
+ if (newStatus === 'completed' && !wasCompleted) {
416
+ task.completedAt = new Date().toISOString();
417
+ // Credited only to a worker still holding this task, so complete -> pending -> complete
418
+ // (no reassignment in between) never counts the same work twice.
419
+ afterSave = () => updateAgents(previouslyAssigned, (agent) => {
420
+ if (agent.currentTask === taskId) {
421
+ agent.status = 'idle';
422
+ agent.currentTask = null;
423
+ agent.taskCount = (agent.taskCount || 0) + 1;
424
+ }
425
+ });
426
+ }
396
427
  }
397
- // Reopening a finished task (completed/failed/cancelled -> pending/in_progress) makes it unfinished
398
- // again, so it must not keep reporting the completedAt of the run that was undone.
399
- if (newStatus === 'pending' || newStatus === 'in_progress') {
400
- task.completedAt = null;
428
+ if (typeof input.progress === 'number') {
429
+ task.progress = Math.min(100, Math.max(0, input.progress));
401
430
  }
402
- // A finished task frees its workers, as task_complete and task_cancel do; otherwise a worker
403
- // whose task was finished through task_update stays `busy` forever, and a later task_complete
404
- // returns early because the status already reads completed.
405
- if (newStatus === 'failed' || newStatus === 'cancelled') {
406
- task.completedAt = new Date().toISOString();
407
- afterSave = () => releaseAgents(previouslyAssigned, taskId);
431
+ // Completing is 100% whatever progress the same call carried.
432
+ if (task.status === 'completed')
433
+ task.progress = 100;
434
+ if (input.assignTo) {
435
+ task.assignedTo = input.assignTo;
436
+ // Reassignment must update the same worker stores as task_assign.
437
+ // Terminal transitions release/credit the workers that held the task
438
+ // before this update; replacement assignees did not perform that work.
439
+ if (!['completed', 'failed', 'cancelled'].includes(task.status)) {
440
+ afterSave = async () => {
441
+ await releaseAgents(previouslyAssigned.filter(id => !task.assignedTo.includes(id)), taskId);
442
+ // Echoing retained assignees must not take them from another task or re-credit completed work.
443
+ await updateAgents(task.assignedTo.filter(id => !previouslyAssigned.includes(id)), agent => {
444
+ agent.status = 'busy';
445
+ agent.currentTask = taskId;
446
+ });
447
+ };
448
+ }
449
+ else if (!afterSave) {
450
+ afterSave = () => releaseAgents(previouslyAssigned, taskId);
451
+ }
408
452
  }
409
- if (newStatus === 'completed' && !wasCompleted) {
410
- task.completedAt = new Date().toISOString();
411
- // Credited only to a worker still holding this task, so complete -> pending -> complete
412
- // (no reassignment in between) never counts the same work twice.
413
- afterSave = () => updateAgents(previouslyAssigned, (agent) => {
414
- if (agent.currentTask === taskId) {
415
- agent.status = 'idle';
416
- agent.currentTask = null;
417
- agent.taskCount = (agent.taskCount || 0) + 1;
418
- }
419
- });
453
+ if (input.result && typeof input.result === 'object') {
454
+ task.result = input.result;
420
455
  }
456
+ return saved({
457
+ response: {
458
+ success: true,
459
+ taskId: task.taskId,
460
+ status: task.status,
461
+ progress: task.progress,
462
+ assignedTo: task.assignedTo,
463
+ },
464
+ afterSave,
465
+ });
421
466
  }
422
- if (typeof input.progress === 'number') {
423
- task.progress = Math.min(100, Math.max(0, input.progress));
424
- }
425
- // Completing is 100% whatever progress the same call carried.
426
- if (task.status === 'completed')
427
- task.progress = 100;
428
- if (input.assignTo) {
429
- task.assignedTo = input.assignTo;
430
- // Reassignment must update the same worker stores as task_assign.
431
- // Terminal transitions release/credit the workers that held the task
432
- // before this update; replacement assignees did not perform that work.
433
- if (!['completed', 'failed', 'cancelled'].includes(task.status)) {
434
- afterSave = () => {
435
- releaseAgents(previouslyAssigned.filter(id => !task.assignedTo.includes(id)), taskId);
436
- // Echoing retained assignees must not take them from another task or re-credit completed work.
437
- updateAgents(task.assignedTo.filter(id => !previouslyAssigned.includes(id)), agent => {
438
- agent.status = 'busy';
439
- agent.currentTask = taskId;
440
- });
441
- };
442
- }
443
- else if (!afterSave) {
444
- afterSave = () => releaseAgents(previouslyAssigned, taskId);
445
- }
446
- }
447
- if (input.result && typeof input.result === 'object') {
448
- task.result = input.result;
449
- }
450
- saveTaskStore(store);
451
- afterSave?.();
452
- return {
453
- success: true,
454
- taskId: task.taskId,
455
- status: task.status,
456
- progress: task.progress,
457
- assignedTo: task.assignedTo,
458
- };
459
- }
460
- return {
461
- success: false,
462
- taskId,
463
- error: 'Task not found',
464
- };
467
+ return unchanged({
468
+ response: {
469
+ success: false,
470
+ taskId,
471
+ error: 'Task not found',
472
+ },
473
+ });
474
+ });
465
475
  },
466
476
  },
467
477
  {
@@ -482,70 +492,81 @@ export const taskTools = [
482
492
  const vId = validateIdentifier(input.taskId, 'taskId');
483
493
  if (!vId.valid)
484
494
  return { success: false, error: vId.error };
485
- const store = loadTaskStore();
486
495
  const taskId = input.taskId;
487
- const task = store.tasks[taskId];
488
- if (!task) {
489
- return { taskId, error: 'Task not found' };
490
- }
491
- // Completed and cancelled tasks are terminal (#4725). Assigning a
492
- // completed task marks the agent busy, and task_complete then returns
493
- // without releasing it; task_cancel refuses a finished task too, so
494
- // nothing ever sets that agent back to idle.
495
- if (task.status === 'completed' || task.status === 'cancelled') {
496
- return {
497
- success: false,
498
- taskId,
499
- status: task.status,
500
- error: `Cannot assign a ${task.status} task`,
501
- };
502
- }
503
- const previouslyAssigned = [...task.assignedTo];
504
- const agentStores = assignableAgentStores();
505
- if (input.unassign) {
506
- // Revert previously assigned agents to idle
507
- releaseAgents(previouslyAssigned, taskId);
508
- task.assignedTo = [];
509
- }
510
- else {
511
- const agentIds = input.agentIds || [];
512
- // An id in neither store is a ghost owner: the task would go
513
- // in_progress with nobody to do the work (#4725).
514
- if (Array.isArray(agentIds)) {
515
- const missing = agentIds.filter((id) => typeof id === 'string' && !agentIsAssignable(id, agentStores));
516
- if (missing.length > 0) {
517
- const listed = missing.join(', ');
518
- return {
496
+ return updateTasks((store) => {
497
+ const task = store.tasks[taskId];
498
+ if (!task) {
499
+ return unchanged({ response: { taskId, error: 'Task not found' } });
500
+ }
501
+ // Completed and cancelled tasks are terminal (#4725). Assigning a
502
+ // completed task marks the agent busy, and task_complete then returns
503
+ // without releasing it; task_cancel refuses a finished task too, so
504
+ // nothing ever sets that agent back to idle.
505
+ if (task.status === 'completed' || task.status === 'cancelled') {
506
+ return unchanged({
507
+ response: {
519
508
  success: false,
520
509
  taskId,
521
510
  status: task.status,
522
- error: missing.length === 1 ? `Agent not found: ${listed}` : `Agents not found: ${listed}`,
523
- };
524
- }
511
+ error: `Cannot assign a ${task.status} task`,
512
+ },
513
+ });
525
514
  }
526
- // Revert old agents to idle
527
- releaseAgents(previouslyAssigned.filter((id) => !agentIds.includes(id)), taskId);
528
- // Set new agents to active
529
- updateAgents(agentIds, (agent) => {
530
- agent.status = 'busy';
531
- agent.currentTask = taskId;
532
- });
533
- task.assignedTo = agentIds;
534
- // Auto-transition task to in_progress if pending
535
- if (task.status === 'pending' && agentIds.length > 0) {
536
- task.status = 'in_progress';
537
- if (!task.startedAt) {
538
- task.startedAt = new Date().toISOString();
515
+ const previouslyAssigned = [...task.assignedTo];
516
+ const agentStores = assignableAgentStores();
517
+ // Worker effects run after the task is saved, as in task_update.
518
+ let afterSave;
519
+ if (input.unassign) {
520
+ // Revert previously assigned agents to idle
521
+ afterSave = () => releaseAgents(previouslyAssigned, taskId);
522
+ task.assignedTo = [];
523
+ }
524
+ else {
525
+ const agentIds = input.agentIds || [];
526
+ // An id in neither store is a ghost owner: the task would go
527
+ // in_progress with nobody to do the work (#4725).
528
+ if (Array.isArray(agentIds)) {
529
+ const missing = agentIds.filter((id) => typeof id === 'string' && !agentIsAssignable(id, agentStores));
530
+ if (missing.length > 0) {
531
+ const listed = missing.join(', ');
532
+ return unchanged({
533
+ response: {
534
+ success: false,
535
+ taskId,
536
+ status: task.status,
537
+ error: missing.length === 1 ? `Agent not found: ${listed}` : `Agents not found: ${listed}`,
538
+ },
539
+ });
540
+ }
541
+ }
542
+ afterSave = async () => {
543
+ // Revert old agents to idle
544
+ await releaseAgents(previouslyAssigned.filter((id) => !agentIds.includes(id)), taskId);
545
+ // Set new agents to active
546
+ await updateAgents(agentIds, (agent) => {
547
+ agent.status = 'busy';
548
+ agent.currentTask = taskId;
549
+ });
550
+ };
551
+ task.assignedTo = agentIds;
552
+ // Auto-transition task to in_progress if pending
553
+ if (task.status === 'pending' && agentIds.length > 0) {
554
+ task.status = 'in_progress';
555
+ if (!task.startedAt) {
556
+ task.startedAt = new Date().toISOString();
557
+ }
539
558
  }
540
559
  }
541
- }
542
- saveTaskStore(store);
543
- return {
544
- taskId: task.taskId,
545
- assignedTo: task.assignedTo,
546
- previouslyAssigned,
547
- status: task.status,
548
- };
560
+ return saved({
561
+ response: {
562
+ taskId: task.taskId,
563
+ assignedTo: task.assignedTo,
564
+ previouslyAssigned,
565
+ status: task.status,
566
+ },
567
+ afterSave,
568
+ });
569
+ });
549
570
  },
550
571
  },
551
572
  {
@@ -570,40 +591,46 @@ export const taskTools = [
570
591
  if (!v.valid)
571
592
  return { success: false, error: v.error };
572
593
  }
573
- const store = loadTaskStore();
574
594
  const taskId = input.taskId;
575
- const task = store.tasks[taskId];
576
- if (task) {
577
- const previousStatus = task.status;
578
- // A finished task keeps its outcome: cancelling it used to overwrite a
579
- // completed task's result and completedAt with a cancel reason.
580
- if (previousStatus === 'completed' || previousStatus === 'failed' || previousStatus === 'cancelled') {
581
- return {
595
+ return updateTasks((store) => {
596
+ const task = store.tasks[taskId];
597
+ if (task) {
598
+ const previousStatus = task.status;
599
+ // A finished task keeps its outcome: cancelling it used to overwrite a
600
+ // completed task's result and completedAt with a cancel reason.
601
+ if (previousStatus === 'completed' || previousStatus === 'failed' || previousStatus === 'cancelled') {
602
+ return unchanged({
603
+ response: {
604
+ success: false,
605
+ taskId,
606
+ status: previousStatus,
607
+ previousStatus,
608
+ error: `Task is already ${previousStatus}`,
609
+ },
610
+ });
611
+ }
612
+ task.status = 'cancelled';
613
+ task.completedAt = new Date().toISOString();
614
+ task.result = { cancelReason: input.reason || 'Cancelled by user' };
615
+ return saved({
616
+ response: {
617
+ success: true,
618
+ taskId: task.taskId,
619
+ status: task.status,
620
+ previousStatus,
621
+ cancelledAt: task.completedAt,
622
+ },
623
+ afterSave: () => releaseAgents(task.assignedTo, taskId),
624
+ });
625
+ }
626
+ return unchanged({
627
+ response: {
582
628
  success: false,
583
629
  taskId,
584
- status: previousStatus,
585
- previousStatus,
586
- error: `Task is already ${previousStatus}`,
587
- };
588
- }
589
- task.status = 'cancelled';
590
- task.completedAt = new Date().toISOString();
591
- task.result = { cancelReason: input.reason || 'Cancelled by user' };
592
- saveTaskStore(store);
593
- releaseAgents(task.assignedTo, taskId);
594
- return {
595
- success: true,
596
- taskId: task.taskId,
597
- status: task.status,
598
- previousStatus,
599
- cancelledAt: task.completedAt,
600
- };
601
- }
602
- return {
603
- success: false,
604
- taskId,
605
- error: 'Task not found',
606
- };
630
+ error: 'Task not found',
631
+ },
632
+ });
633
+ });
607
634
  },
608
635
  },
609
636
  {
@@ -626,40 +653,42 @@ export const taskTools = [
626
653
  const v = validateIdentifier(input.taskId, 'taskId');
627
654
  if (!v.valid)
628
655
  return { success: false, error: v.error };
629
- const store = loadTaskStore();
630
656
  const taskId = input.taskId;
631
- const original = store.tasks[taskId];
632
- if (!original)
633
- return { success: false, taskId, error: 'Task not found' };
634
- const retainState = input.resetState === false;
635
- const newTaskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
636
- const retry = {
637
- taskId: newTaskId,
638
- type: original.type,
639
- description: original.description,
640
- priority: original.priority,
641
- status: 'pending',
642
- progress: retainState ? original.progress ?? 0 : 0,
643
- assignedTo: [...original.assignedTo],
644
- tags: [...original.tags, 'retry-of:' + taskId],
645
- createdAt: new Date().toISOString(),
646
- startedAt: null,
647
- completedAt: null,
648
- };
649
- if (retainState && original.result !== undefined)
650
- retry.result = original.result;
651
- store.tasks[newTaskId] = retry;
652
- saveTaskStore(store);
653
- updateAgents(retry.assignedTo, (agent) => {
654
- agent.status = 'busy';
655
- agent.currentTask = newTaskId;
657
+ return updateTasks((store) => {
658
+ const original = store.tasks[taskId];
659
+ if (!original)
660
+ return unchanged({ response: { success: false, taskId, error: 'Task not found' } });
661
+ const retainState = input.resetState === false;
662
+ const newTaskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
663
+ const retry = {
664
+ taskId: newTaskId,
665
+ type: original.type,
666
+ description: original.description,
667
+ priority: original.priority,
668
+ status: 'pending',
669
+ progress: retainState ? original.progress ?? 0 : 0,
670
+ assignedTo: [...original.assignedTo],
671
+ tags: [...original.tags, 'retry-of:' + taskId],
672
+ createdAt: new Date().toISOString(),
673
+ startedAt: null,
674
+ completedAt: null,
675
+ };
676
+ if (retainState && original.result !== undefined)
677
+ retry.result = original.result;
678
+ store.tasks[newTaskId] = retry;
679
+ return saved({
680
+ response: {
681
+ taskId,
682
+ newTaskId,
683
+ previousStatus: original.status,
684
+ status: 'pending',
685
+ },
686
+ afterSave: () => updateAgents(retry.assignedTo, (agent) => {
687
+ agent.status = 'busy';
688
+ agent.currentTask = newTaskId;
689
+ }),
690
+ });
656
691
  });
657
- return {
658
- taskId,
659
- newTaskId,
660
- previousStatus: original.status,
661
- status: 'pending',
662
- };
663
692
  },
664
693
  },
665
694
  ];