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,12 +3,15 @@
3
3
  *
4
4
  * Tool definitions for workflow automation and orchestration.
5
5
  */
6
- import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
6
+ import { existsSync } from 'node:fs';
7
7
  import { join } from 'node:path';
8
8
  import { getProjectCwd } from './types.js';
9
9
  import { validateIdentifier, validatePath, validateText } from './validate-input.js';
10
10
  import { executeAgentTask } from './agent-execute-core.js';
11
11
  import { readPreservedJsonStore } from './record-store.js';
12
+ import { saved, unchanged, updateJsonStore } from './locked-json-store.js';
13
+ import { containedReadPath, isLocalCliCall } from './path-containment.js';
14
+ import { readImportFile } from './import-limits.js';
12
15
  // Storage paths
13
16
  const STORAGE_DIR = '.claude-flow';
14
17
  const WORKFLOW_DIR = 'workflows';
@@ -50,12 +53,6 @@ function getWorkflowDir() {
50
53
  function getWorkflowPath() {
51
54
  return join(getWorkflowDir(), WORKFLOW_FILE);
52
55
  }
53
- function ensureWorkflowDir() {
54
- const dir = getWorkflowDir();
55
- if (!existsSync(dir)) {
56
- mkdirSync(dir, { recursive: true });
57
- }
58
- }
59
56
  /**
60
57
  * SECURITY: record maps are keyed by ids taken from MCP tool input, and
61
58
  * validateIdentifier accepts names like `__proto__` and `constructor`. On a
@@ -88,13 +85,16 @@ function loadWorkflowStore() {
88
85
  }));
89
86
  return withRecordMaps(data, WORKFLOW_MAPS);
90
87
  }
91
- function saveWorkflowStore(store) {
92
- ensureWorkflowDir();
93
- writeFileSync(getWorkflowPath(), JSON.stringify(store, null, 2), 'utf-8');
88
+ /** Every workflow write goes through here, under the workflows lock. */
89
+ function updateWorkflows(mutate) {
90
+ return updateJsonStore(getWorkflowPath(), loadWorkflowStore, mutate, 'workflows');
94
91
  }
95
92
  // A paused in-flight step still owns its executor. Resume joins that execution
96
93
  // instead of dispatching the same side effect again (within this process).
97
94
  const workflowExecutions = new Map();
95
+ // Executions whose locked start has marked the workflow running. One that is
96
+ // registered but not yet started is still waiting for the store lock.
97
+ const startedExecutions = new Set();
98
98
  const workflowExecutionKey = (workflowId) => JSON.stringify([getWorkflowPath(), workflowId]);
99
99
  function withWorkflowExecution(workflowId, execute) {
100
100
  const key = workflowExecutionKey(workflowId);
@@ -104,8 +104,10 @@ function withWorkflowExecution(workflowId, execute) {
104
104
  const execution = execute();
105
105
  workflowExecutions.set(key, execution);
106
106
  return execution.finally(() => {
107
- if (workflowExecutions.get(key) === execution)
107
+ if (workflowExecutions.get(key) === execution) {
108
108
  workflowExecutions.delete(key);
109
+ startedExecutions.delete(key);
110
+ }
109
111
  });
110
112
  }
111
113
  export const workflowTools = [
@@ -148,7 +150,6 @@ export const workflowTools = [
148
150
  if (!v.valid)
149
151
  return { success: false, error: v.error };
150
152
  }
151
- const store = loadWorkflowStore();
152
153
  const template = input.template;
153
154
  const task = input.task;
154
155
  const options = input.options || {};
@@ -201,8 +202,10 @@ export const workflowTools = [
201
202
  variables: { template: templateName, ...options },
202
203
  createdAt: new Date().toISOString(),
203
204
  };
204
- store.workflows[workflowId] = workflow;
205
- saveWorkflowStore(store);
205
+ await updateWorkflows((store) => {
206
+ store.workflows[workflowId] = workflow;
207
+ return saved(undefined);
208
+ });
206
209
  }
207
210
  return {
208
211
  workflowId,
@@ -256,7 +259,6 @@ export const workflowTools = [
256
259
  if (!v.valid)
257
260
  return { success: false, error: v.error };
258
261
  }
259
- const store = loadWorkflowStore();
260
262
  const workflowId = `workflow-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
261
263
  const steps = (input.steps || []).map((s, i) => ({
262
264
  stepId: `step-${i + 1}`,
@@ -280,8 +282,10 @@ export const workflowTools = [
280
282
  variables: input.variables || {},
281
283
  createdAt: new Date().toISOString(),
282
284
  };
283
- store.workflows[workflowId] = workflow;
284
- saveWorkflowStore(store);
285
+ await updateWorkflows((store) => {
286
+ store.workflows[workflowId] = workflow;
287
+ return saved(undefined);
288
+ });
285
289
  return {
286
290
  workflowId,
287
291
  name: workflow.name,
@@ -309,74 +313,79 @@ export const workflowTools = [
309
313
  const vId = validateIdentifier(input.workflowId, 'workflowId');
310
314
  if (!vId.valid)
311
315
  return { success: false, error: vId.error };
312
- const store = loadWorkflowStore();
313
316
  const workflowId = input.workflowId;
314
- const workflow = store.workflows[workflowId];
315
- if (!workflow) {
316
- return { workflowId, error: 'Workflow not found' };
317
- }
318
- if (workflow.status === 'running') {
319
- return { workflowId, error: 'Workflow already running' };
320
- }
321
- // Older stored workflows may predate creation-time validation. Reject
322
- // unsupported steps before dispatching any task with side effects.
323
- for (const step of workflow.steps) {
324
- const error = validateExecutableStep(step);
325
- if (error) {
326
- workflow.status = 'failed';
327
- workflow.error = `${step.stepId} (${step.name}): ${error}`;
328
- step.status = 'failed';
329
- step.result = { error: workflow.error };
330
- workflow.completedAt = new Date().toISOString();
331
- saveWorkflowStore(store);
332
- return { workflowId, status: 'failed', failedStep: step.stepId, error: workflow.error };
317
+ // Check, validate and mark running in one locked step, so two processes
318
+ // cannot both start the same workflow.
319
+ const start = await updateWorkflows((store) => {
320
+ const workflow = store.workflows[workflowId];
321
+ if (!workflow) {
322
+ return unchanged({ refused: { workflowId, error: 'Workflow not found' } });
333
323
  }
334
- }
335
- // Indices may name a step or the end boundary (used when resuming
336
- // after the final step). Reject invalid control flow before any writes.
337
- const validIndex = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= workflow.steps.length;
338
- const startFromStep = input.startFromStep === undefined ? 0 : input.startFromStep;
339
- if (!validIndex(startFromStep)) {
340
- return { workflowId, error: `startFromStep must be an integer between 0 and ${workflow.steps.length}` };
341
- }
342
- for (const step of workflow.steps) {
343
- if (step.type !== 'condition')
344
- continue;
345
- for (const target of ['thenStep', 'elseStep']) {
346
- if (step.config[target] !== undefined && !validIndex(step.config[target])) {
347
- return { workflowId, error: `${step.stepId}.${target} must be an integer between 0 and ${workflow.steps.length}` };
324
+ if (workflow.status === 'running') {
325
+ return unchanged({ refused: { workflowId, error: 'Workflow already running' } });
326
+ }
327
+ // Older stored workflows may predate creation-time validation. Reject
328
+ // unsupported steps before dispatching any task with side effects.
329
+ for (const step of workflow.steps) {
330
+ const error = validateExecutableStep(step);
331
+ if (error) {
332
+ workflow.status = 'failed';
333
+ workflow.error = `${step.stepId} (${step.name}): ${error}`;
334
+ step.status = 'failed';
335
+ step.result = { error: workflow.error };
336
+ workflow.completedAt = new Date().toISOString();
337
+ return saved({ refused: { workflowId, status: 'failed', failedStep: step.stepId, error: workflow.error } });
348
338
  }
349
339
  }
350
- }
351
- const persistProgress = () => {
340
+ // Indices may name a step or the end boundary (used when resuming
341
+ // after the final step). Reject invalid control flow before any writes.
342
+ const validIndex = (value) => typeof value === 'number' && Number.isSafeInteger(value) && value >= 0 && value <= workflow.steps.length;
343
+ const startFromStep = input.startFromStep === undefined ? 0 : input.startFromStep;
344
+ if (!validIndex(startFromStep)) {
345
+ return unchanged({ refused: { workflowId, error: `startFromStep must be an integer between 0 and ${workflow.steps.length}` } });
346
+ }
347
+ for (const step of workflow.steps) {
348
+ if (step.type !== 'condition')
349
+ continue;
350
+ for (const target of ['thenStep', 'elseStep']) {
351
+ if (step.config[target] !== undefined && !validIndex(step.config[target])) {
352
+ return unchanged({ refused: { workflowId, error: `${step.stepId}.${target} must be an integer between 0 and ${workflow.steps.length}` } });
353
+ }
354
+ }
355
+ }
356
+ // Inject runtime variables
357
+ if (input.variables) {
358
+ workflow.variables = { ...workflow.variables, ...input.variables };
359
+ }
360
+ workflow.status = 'running';
361
+ workflow.startedAt = new Date().toISOString();
362
+ delete workflow.error;
363
+ delete workflow.completedAt;
364
+ workflow.currentStep = startFromStep;
365
+ return saved({ workflow });
366
+ });
367
+ if ('refused' in start)
368
+ return start.refused;
369
+ const { workflow } = start;
370
+ startedExecutions.add(workflowExecutionKey(workflowId));
371
+ const persistProgress = () => updateWorkflows((latest) => {
352
372
  // An awaited step may overlap pause/stop/delete or a sibling workflow
353
373
  // mutation. Merge only this workflow into the latest store snapshot.
354
- const latest = loadWorkflowStore();
355
374
  const current = latest.workflows[workflowId];
356
375
  if (!current) {
357
376
  workflow.status = 'failed';
358
377
  workflow.error = 'Workflow was deleted during execution';
359
- return;
378
+ return unchanged(undefined);
360
379
  }
361
380
  if (current.status === 'failed') {
362
381
  Object.assign(workflow, current);
363
- return;
382
+ return unchanged(undefined);
364
383
  }
365
384
  if (current.status === 'paused' && workflow.status !== 'failed')
366
385
  workflow.status = 'paused';
367
386
  latest.workflows[workflowId] = workflow;
368
- saveWorkflowStore(latest);
369
- };
370
- // Inject runtime variables
371
- if (input.variables) {
372
- workflow.variables = { ...workflow.variables, ...input.variables };
373
- }
374
- workflow.status = 'running';
375
- workflow.startedAt = new Date().toISOString();
376
- delete workflow.error;
377
- delete workflow.completedAt;
378
- workflow.currentStep = startFromStep;
379
- saveWorkflowStore(store);
387
+ return saved(undefined);
388
+ });
380
389
  // ADR-095 G3: real workflow runtime. Walk the steps in order;
381
390
  // dispatch each by type. Persist progress after each step so a
382
391
  // crash or pause can resume cleanly. No mock — task steps make
@@ -413,7 +422,7 @@ export const workflowTools = [
413
422
  if (live.status === 'paused') {
414
423
  workflow.status = 'paused';
415
424
  workflow.currentStep = i;
416
- persistProgress();
425
+ await persistProgress();
417
426
  break;
418
427
  }
419
428
  if (live.status === 'failed') {
@@ -424,7 +433,7 @@ export const workflowTools = [
424
433
  step.status = 'running';
425
434
  step.startedAt = new Date().toISOString();
426
435
  const stepStart = Date.now();
427
- persistProgress();
436
+ await persistProgress();
428
437
  let stepEntry = { stepId: step.stepId, type: step.type, status: 'running' };
429
438
  try {
430
439
  if (step.type === 'task') {
@@ -489,7 +498,7 @@ export const workflowTools = [
489
498
  workflow.status = 'failed';
490
499
  workflow.error = msg;
491
500
  workflow.completedAt = new Date().toISOString();
492
- persistProgress();
501
+ await persistProgress();
493
502
  return {
494
503
  workflowId,
495
504
  status: 'failed',
@@ -504,13 +513,13 @@ export const workflowTools = [
504
513
  stepEntry.durationMs = Date.now() - stepStart;
505
514
  stepResults.push(stepEntry);
506
515
  workflow.currentStep = i + 1;
507
- persistProgress();
516
+ await persistProgress();
508
517
  i++;
509
518
  }
510
519
  if (workflow.status === 'running') {
511
520
  workflow.status = 'completed';
512
521
  workflow.completedAt = new Date().toISOString();
513
- persistProgress();
522
+ await persistProgress();
514
523
  }
515
524
  return {
516
525
  workflowId,
@@ -644,23 +653,23 @@ export const workflowTools = [
644
653
  const vId = validateIdentifier(input.workflowId, 'workflowId');
645
654
  if (!vId.valid)
646
655
  return { success: false, error: vId.error };
647
- const store = loadWorkflowStore();
648
656
  const workflowId = input.workflowId;
649
- const workflow = store.workflows[workflowId];
650
- if (!workflow) {
651
- return { workflowId, error: 'Workflow not found' };
652
- }
653
- if (workflow.status !== 'running') {
654
- return { workflowId, error: 'Workflow not running' };
655
- }
656
- workflow.status = 'paused';
657
- saveWorkflowStore(store);
658
- return {
659
- workflowId,
660
- status: workflow.status,
661
- pausedAt: new Date().toISOString(),
662
- currentStep: workflow.currentStep,
663
- };
657
+ return updateWorkflows((store) => {
658
+ const workflow = store.workflows[workflowId];
659
+ if (!workflow) {
660
+ return unchanged({ workflowId, error: 'Workflow not found' });
661
+ }
662
+ if (workflow.status !== 'running') {
663
+ return unchanged({ workflowId, error: 'Workflow not running' });
664
+ }
665
+ workflow.status = 'paused';
666
+ return saved({
667
+ workflowId,
668
+ status: workflow.status,
669
+ pausedAt: new Date().toISOString(),
670
+ currentStep: workflow.currentStep,
671
+ });
672
+ });
664
673
  },
665
674
  },
666
675
  {
@@ -679,23 +688,36 @@ export const workflowTools = [
679
688
  const vId = validateIdentifier(input.workflowId, 'workflowId');
680
689
  if (!vId.valid)
681
690
  return { success: false, error: vId.error };
682
- const store = loadWorkflowStore();
683
691
  const workflowId = input.workflowId;
684
- const workflow = store.workflows[workflowId];
685
- if (!workflow) {
686
- return { workflowId, error: 'Workflow not found' };
687
- }
688
- if (workflow.status !== 'paused') {
689
- return { workflowId, error: 'Workflow not paused' };
690
- }
691
- const active = workflowExecutions.get(workflowExecutionKey(workflowId));
692
- if (active) {
693
- workflow.status = 'running';
694
- saveWorkflowStore(store);
695
- return { ...(await active), resumed: true };
696
- }
692
+ // Decide under the lock; wait on or start the execution after it is
693
+ // released, since workflow_execute takes the same lock.
694
+ const next = await updateWorkflows((store) => {
695
+ const workflow = store.workflows[workflowId];
696
+ if (!workflow) {
697
+ return unchanged({ refused: { workflowId, error: 'Workflow not found' } });
698
+ }
699
+ if (workflow.status !== 'paused') {
700
+ return unchanged({ refused: { workflowId, error: 'Workflow not paused' } });
701
+ }
702
+ const key = workflowExecutionKey(workflowId);
703
+ const active = workflowExecutions.get(key);
704
+ if (active && startedExecutions.has(key)) {
705
+ // A paused in-flight execution: running again lets it continue.
706
+ workflow.status = 'running';
707
+ return saved({ active });
708
+ }
709
+ if (active) {
710
+ // Another call is already starting it, as when resume is requested twice.
711
+ return unchanged({ refused: { workflowId, error: 'Workflow not paused' } });
712
+ }
713
+ return unchanged({ startFromStep: workflow.currentStep });
714
+ });
715
+ if ('refused' in next)
716
+ return next.refused;
717
+ if ('active' in next)
718
+ return { ...(await next.active), resumed: true };
697
719
  const execute = workflowTools.find(tool => tool.name === 'workflow_execute');
698
- const result = await execute.handler({ workflowId, startFromStep: workflow.currentStep });
720
+ const result = await execute.handler({ workflowId, startFromStep: next.startFromStep });
699
721
  return { ...result, resumed: true };
700
722
  },
701
723
  },
@@ -721,30 +743,30 @@ export const workflowTools = [
721
743
  if (!v.valid)
722
744
  return { success: false, error: v.error };
723
745
  }
724
- const store = loadWorkflowStore();
725
746
  const workflowId = input.workflowId;
726
- const workflow = store.workflows[workflowId];
727
- if (!workflow) {
728
- return { workflowId, error: 'Workflow not found' };
729
- }
730
- if (workflow.status === 'completed' || workflow.status === 'failed') {
731
- return { workflowId, error: 'Workflow already finished' };
732
- }
733
- workflow.status = 'failed';
734
- workflow.error = input.reason || 'Cancelled by user';
735
- workflow.completedAt = new Date().toISOString();
736
- // Mark remaining steps as skipped
737
- for (let i = workflow.currentStep; i < workflow.steps.length; i++) {
738
- workflow.steps[i].status = 'skipped';
739
- }
740
- saveWorkflowStore(store);
741
- return {
742
- workflowId,
743
- status: workflow.status,
744
- cancelledAt: workflow.completedAt,
745
- reason: workflow.error,
746
- skippedSteps: workflow.steps.length - workflow.currentStep,
747
- };
747
+ return updateWorkflows((store) => {
748
+ const workflow = store.workflows[workflowId];
749
+ if (!workflow) {
750
+ return unchanged({ workflowId, error: 'Workflow not found' });
751
+ }
752
+ if (workflow.status === 'completed' || workflow.status === 'failed') {
753
+ return unchanged({ workflowId, error: 'Workflow already finished' });
754
+ }
755
+ workflow.status = 'failed';
756
+ workflow.error = input.reason || 'Cancelled by user';
757
+ workflow.completedAt = new Date().toISOString();
758
+ // Mark remaining steps as skipped
759
+ for (let i = workflow.currentStep; i < workflow.steps.length; i++) {
760
+ workflow.steps[i].status = 'skipped';
761
+ }
762
+ return saved({
763
+ workflowId,
764
+ status: workflow.status,
765
+ cancelledAt: workflow.completedAt,
766
+ reason: workflow.error,
767
+ skippedSteps: workflow.steps.length - workflow.currentStep,
768
+ });
769
+ });
748
770
  },
749
771
  },
750
772
  {
@@ -763,22 +785,22 @@ export const workflowTools = [
763
785
  const vId = validateIdentifier(input.workflowId, 'workflowId');
764
786
  if (!vId.valid)
765
787
  return { success: false, error: vId.error };
766
- const store = loadWorkflowStore();
767
788
  const workflowId = input.workflowId;
768
- if (!store.workflows[workflowId]) {
769
- return { workflowId, error: 'Workflow not found' };
770
- }
771
- const workflow = store.workflows[workflowId];
772
- if (workflow.status === 'running') {
773
- return { workflowId, error: 'Cannot delete running workflow' };
774
- }
775
- delete store.workflows[workflowId];
776
- saveWorkflowStore(store);
777
- return {
778
- workflowId,
779
- deleted: true,
780
- deletedAt: new Date().toISOString(),
781
- };
789
+ return updateWorkflows((store) => {
790
+ if (!store.workflows[workflowId]) {
791
+ return unchanged({ workflowId, error: 'Workflow not found' });
792
+ }
793
+ const workflow = store.workflows[workflowId];
794
+ if (workflow.status === 'running') {
795
+ return unchanged({ workflowId, error: 'Cannot delete running workflow' });
796
+ }
797
+ delete store.workflows[workflowId];
798
+ return saved({
799
+ workflowId,
800
+ deleted: true,
801
+ deletedAt: new Date().toISOString(),
802
+ });
803
+ });
782
804
  },
783
805
  },
784
806
  {
@@ -818,64 +840,66 @@ export const workflowTools = [
818
840
  if (!v.valid)
819
841
  return { success: false, error: v.error };
820
842
  }
821
- const store = loadWorkflowStore();
822
843
  const action = input.action;
823
844
  if (action === 'save') {
824
- const workflow = store.workflows[input.workflowId];
825
- if (!workflow) {
826
- return { action, error: 'Workflow not found' };
827
- }
828
- const templateId = `template-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
829
- const template = {
830
- ...workflow,
831
- workflowId: templateId,
832
- name: input.templateName || `${workflow.name} Template`,
833
- status: 'draft',
834
- currentStep: 0,
835
- createdAt: new Date().toISOString(),
836
- startedAt: undefined,
837
- completedAt: undefined,
838
- };
839
- // Reset step statuses
840
- template.steps = template.steps.map(s => ({
841
- ...s,
842
- status: 'pending',
843
- result: undefined,
844
- startedAt: undefined,
845
- completedAt: undefined,
846
- }));
847
- store.templates[templateId] = template;
848
- saveWorkflowStore(store);
849
- return {
850
- action,
851
- templateId,
852
- name: template.name,
853
- savedAt: new Date().toISOString(),
854
- };
845
+ return updateWorkflows((store) => {
846
+ const workflow = store.workflows[input.workflowId];
847
+ if (!workflow) {
848
+ return unchanged({ action, error: 'Workflow not found' });
849
+ }
850
+ const templateId = `template-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
851
+ const template = {
852
+ ...workflow,
853
+ workflowId: templateId,
854
+ name: input.templateName || `${workflow.name} Template`,
855
+ status: 'draft',
856
+ currentStep: 0,
857
+ createdAt: new Date().toISOString(),
858
+ startedAt: undefined,
859
+ completedAt: undefined,
860
+ };
861
+ // Reset step statuses
862
+ template.steps = template.steps.map(s => ({
863
+ ...s,
864
+ status: 'pending',
865
+ result: undefined,
866
+ startedAt: undefined,
867
+ completedAt: undefined,
868
+ }));
869
+ store.templates[templateId] = template;
870
+ return saved({
871
+ action,
872
+ templateId,
873
+ name: template.name,
874
+ savedAt: new Date().toISOString(),
875
+ });
876
+ });
855
877
  }
856
878
  if (action === 'create') {
857
- const template = store.templates[input.templateId];
858
- if (!template) {
859
- return { action, error: 'Template not found' };
860
- }
861
- const workflowId = `workflow-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
862
- const workflow = {
863
- ...template,
864
- workflowId,
865
- name: input.newName || template.name.replace(' Template', ''),
866
- status: 'ready',
867
- createdAt: new Date().toISOString(),
868
- };
869
- store.workflows[workflowId] = workflow;
870
- saveWorkflowStore(store);
871
- return {
872
- action,
873
- workflowId,
874
- name: workflow.name,
875
- fromTemplate: input.templateId,
876
- createdAt: workflow.createdAt,
877
- };
879
+ return updateWorkflows((store) => {
880
+ const template = store.templates[input.templateId];
881
+ if (!template) {
882
+ return unchanged({ action, error: 'Template not found' });
883
+ }
884
+ const workflowId = `workflow-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
885
+ const workflow = {
886
+ ...template,
887
+ workflowId,
888
+ name: input.newName || template.name.replace(' Template', ''),
889
+ status: 'ready',
890
+ createdAt: new Date().toISOString(),
891
+ };
892
+ store.workflows[workflowId] = workflow;
893
+ return saved({
894
+ action,
895
+ workflowId,
896
+ name: workflow.name,
897
+ fromTemplate: input.templateId,
898
+ createdAt: workflow.createdAt,
899
+ });
900
+ });
878
901
  }
902
+ const store = loadWorkflowStore();
879
903
  if (action === 'list') {
880
904
  return {
881
905
  action,
@@ -910,22 +934,22 @@ export const workflowTools = [
910
934
  const vId = validateIdentifier(input.workflowId, 'workflowId');
911
935
  if (!vId.valid)
912
936
  return { success: false, error: vId.error };
913
- const store = loadWorkflowStore();
914
937
  const workflowId = input.workflowId;
915
- const workflow = store.workflows[workflowId];
916
- if (!workflow)
917
- return { workflowId, error: 'Workflow not found' };
918
- if (workflow.status === 'completed' || workflow.status === 'failed') {
919
- return { workflowId, error: 'Workflow already finished' };
920
- }
921
- workflow.status = 'failed';
922
- workflow.error = 'Stopped by user';
923
- workflow.completedAt = new Date().toISOString();
924
- for (let i = workflow.currentStep; i < workflow.steps.length; i++) {
925
- workflow.steps[i].status = 'skipped';
926
- }
927
- saveWorkflowStore(store);
928
- return { workflowId, stopped: true, stoppedAt: workflow.completedAt };
938
+ return updateWorkflows((store) => {
939
+ const workflow = store.workflows[workflowId];
940
+ if (!workflow)
941
+ return unchanged({ workflowId, error: 'Workflow not found' });
942
+ if (workflow.status === 'completed' || workflow.status === 'failed') {
943
+ return unchanged({ workflowId, error: 'Workflow already finished' });
944
+ }
945
+ workflow.status = 'failed';
946
+ workflow.error = 'Stopped by user';
947
+ workflow.completedAt = new Date().toISOString();
948
+ for (let i = workflow.currentStep; i < workflow.steps.length; i++) {
949
+ workflow.steps[i].status = 'skipped';
950
+ }
951
+ return saved({ workflowId, stopped: true, stoppedAt: workflow.completedAt });
952
+ });
929
953
  },
930
954
  },
931
955
  {
@@ -943,18 +967,23 @@ export const workflowTools = [
943
967
  },
944
968
  required: ['file'],
945
969
  },
946
- handler: async (input) => {
970
+ handler: async (input, context) => {
947
971
  const file = String(input.file ?? '');
948
972
  const errors = [];
949
973
  const warnings = [];
950
974
  let stages = 0;
951
975
  let agents = 0;
952
976
  try {
953
- if (!file || !existsSync(file)) {
954
- errors.push({ line: 0, message: `File not found: ${file || '(empty)'}`, severity: 'error' });
977
+ // MCP callers may only read regular files inside the project, matching
978
+ // memory_import; the local CLI may name any file the operator chooses.
979
+ const local = isLocalCliCall(context);
980
+ const resolved = !file ? null : local ? (existsSync(file) ? file : null) : containedReadPath(file);
981
+ if (!resolved) {
982
+ errors.push({ line: 0, message: !file || local ? `File not found: ${file || '(empty)'}`
983
+ : 'file must be an existing regular file inside the project directory (not a symlink)', severity: 'error' });
955
984
  }
956
985
  else {
957
- const raw = readFileSync(file, 'utf-8');
986
+ const raw = readImportFile(resolved).toString('utf-8');
958
987
  let doc = null;
959
988
  if (/\.ya?ml$/i.test(file)) {
960
989
  warnings.push({ line: 0, message: 'YAML workflow files are not schema-validated yet — only JSON is fully checked (#1916 follow-up)' });
@@ -1001,7 +1030,8 @@ export const workflowTools = [
1001
1030
  }
1002
1031
  }
1003
1032
  catch (e) {
1004
- errors.push({ line: 0, message: `Parse error: ${e.message}`, severity: 'error' });
1033
+ // Never echo parser text: a SyntaxError message quotes the file's contents.
1034
+ errors.push({ line: 0, message: e instanceof SyntaxError ? 'Parse error: file is not valid JSON' : `Parse error: ${e.message}`, severity: 'error' });
1005
1035
  }
1006
1036
  const valid = errors.length === 0 && (!input.strict || warnings.length === 0);
1007
1037
  return {