@claude-flow/cli 3.71.4 → 3.72.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (124) hide show
  1. package/.claude/helpers/helpers.manifest.json +4 -4
  2. package/.claude/helpers/hook-handler.cjs +23 -10
  3. package/.claude/helpers/statusline.cjs +29 -14
  4. package/.claude/skills/fast-code-edits/SKILL.md +45 -0
  5. package/.claude/skills/graph-mincut/SKILL.md +32 -0
  6. package/.claude/skills/injection-defense/SKILL.md +36 -0
  7. package/.claude/skills/lora-learning/SKILL.md +30 -0
  8. package/.claude/skills/sublinear-solver/SKILL.md +34 -0
  9. package/.claude/skills/vector-quantization/SKILL.md +36 -0
  10. package/README.md +18 -3
  11. package/bin/cli.js +13 -18
  12. package/bin/mcp-server.js +13 -18
  13. package/catalog-manifest.json +4 -4
  14. package/dist/src/appliance/ruvllm-bridge.d.ts +6 -2
  15. package/dist/src/appliance/ruvllm-bridge.js +13 -8
  16. package/dist/src/appliance/rvfa-distribution.js +2 -2
  17. package/dist/src/benchmarks/gaia-critic.d.ts +1 -7
  18. package/dist/src/benchmarks/gaia-critic.js +1 -7
  19. package/dist/src/benchmarks/gaia-decomposer.d.ts +1 -8
  20. package/dist/src/benchmarks/gaia-decomposer.js +1 -8
  21. package/dist/src/commands/agent-wasm.js +2 -2
  22. package/dist/src/commands/analyze.js +1 -1
  23. package/dist/src/commands/daemon.js +1 -1
  24. package/dist/src/commands/doctor.js +3 -2
  25. package/dist/src/commands/guidance.js +9 -9
  26. package/dist/src/commands/hooks.js +13 -8
  27. package/dist/src/commands/init.js +16 -16
  28. package/dist/src/commands/neural.js +87 -77
  29. package/dist/src/commands/route.js +1 -1
  30. package/dist/src/commands/ruvector/backup.js +7 -5
  31. package/dist/src/commands/ruvector/benchmark.js +6 -1
  32. package/dist/src/commands/ruvector/import.js +19 -5
  33. package/dist/src/commands/ruvector/init.js +1 -1
  34. package/dist/src/commands/start.js +1 -1
  35. package/dist/src/commands/status.js +1 -1
  36. package/dist/src/commands/task.js +18 -1
  37. package/dist/src/commands/update.js +1 -1
  38. package/dist/src/funnel/local-signals.js +7 -2
  39. package/dist/src/init/executor.js +13 -0
  40. package/dist/src/init/types.d.ts +6 -0
  41. package/dist/src/init/types.js +3 -0
  42. package/dist/src/mcp-client.js +2 -0
  43. package/dist/src/mcp-protocol.d.ts +90 -0
  44. package/dist/src/mcp-protocol.js +179 -0
  45. package/dist/src/mcp-server.d.ts +1 -0
  46. package/dist/src/mcp-server.js +20 -22
  47. package/dist/src/mcp-tools/agent-execute-core.js +9 -1
  48. package/dist/src/mcp-tools/agent-tools.d.ts +13 -0
  49. package/dist/src/mcp-tools/agent-tools.js +59 -8
  50. package/dist/src/mcp-tools/agentdb-tools.js +34 -2
  51. package/dist/src/mcp-tools/browser-argv.d.ts +9 -0
  52. package/dist/src/mcp-tools/browser-argv.js +33 -0
  53. package/dist/src/mcp-tools/browser-session-tools.js +4 -0
  54. package/dist/src/mcp-tools/browser-tools.js +12 -2
  55. package/dist/src/mcp-tools/coordination-tools.js +5 -4
  56. package/dist/src/mcp-tools/embeddings-tools.js +12 -4
  57. package/dist/src/mcp-tools/fast-apply-tools.d.ts +4 -0
  58. package/dist/src/mcp-tools/fast-apply-tools.js +85 -0
  59. package/dist/src/mcp-tools/glob-exclusions.d.ts +6 -0
  60. package/dist/src/mcp-tools/glob-exclusions.js +81 -0
  61. package/dist/src/mcp-tools/hive-mind-tools.js +104 -35
  62. package/dist/src/mcp-tools/hooks-tools.js +14 -38
  63. package/dist/src/mcp-tools/import-limits.d.ts +4 -0
  64. package/dist/src/mcp-tools/import-limits.js +28 -0
  65. package/dist/src/mcp-tools/memory-tools.js +21 -42
  66. package/dist/src/mcp-tools/metaharness-tools.js +1 -1
  67. package/dist/src/mcp-tools/performance-tools.js +7 -2
  68. package/dist/src/mcp-tools/realpath-containment.d.ts +3 -0
  69. package/dist/src/mcp-tools/realpath-containment.js +39 -0
  70. package/dist/src/mcp-tools/record-store.d.ts +8 -0
  71. package/dist/src/mcp-tools/record-store.js +98 -1
  72. package/dist/src/mcp-tools/security-tools.d.ts +9 -0
  73. package/dist/src/mcp-tools/security-tools.js +39 -3
  74. package/dist/src/mcp-tools/session-tools.js +5 -3
  75. package/dist/src/mcp-tools/swarm-tools.js +35 -17
  76. package/dist/src/mcp-tools/task-tools.js +68 -5
  77. package/dist/src/mcp-tools/terminal-tools.js +9 -0
  78. package/dist/src/mcp-tools/workflow-tools.js +13 -12
  79. package/dist/src/mcp-tools/x-federation-join.js +55 -14
  80. package/dist/src/memory/intelligence.d.ts +11 -0
  81. package/dist/src/memory/intelligence.js +84 -6
  82. package/dist/src/memory/memory-initializer.d.ts +6 -2
  83. package/dist/src/memory/memory-initializer.js +15 -6
  84. package/dist/src/mods/command-registry/schema.d.ts +12 -12
  85. package/dist/src/ruvector/ast-analyzer.d.ts +1 -2
  86. package/dist/src/ruvector/ast-analyzer.js +4 -12
  87. package/dist/src/ruvector/coverage-router.d.ts +1 -2
  88. package/dist/src/ruvector/coverage-router.js +4 -12
  89. package/dist/src/ruvector/diff-classifier.d.ts +1 -2
  90. package/dist/src/ruvector/diff-classifier.js +3 -12
  91. package/dist/src/ruvector/fast-apply.d.ts +46 -0
  92. package/dist/src/ruvector/fast-apply.js +73 -0
  93. package/dist/src/ruvector/graph-analyzer.d.ts +11 -1
  94. package/dist/src/ruvector/graph-analyzer.js +22 -36
  95. package/dist/src/ruvector/mincut-bridge.d.ts +70 -0
  96. package/dist/src/ruvector/mincut-bridge.js +172 -0
  97. package/dist/src/ruvector/model-router.d.ts +6 -1
  98. package/dist/src/ruvector/model-router.js +16 -4
  99. package/dist/src/services/distill-oracle.d.ts +1 -1
  100. package/dist/src/services/distill-oracle.js +2 -2
  101. package/dist/src/services/worker-daemon.js +30 -12
  102. package/dist/src/transfer/storage/gcs.js +3 -2
  103. package/node_modules/@claude-flow/codex/.agents/skills/fast-code-edits/SKILL.md +42 -0
  104. package/node_modules/@claude-flow/codex/.agents/skills/graph-mincut/SKILL.md +42 -0
  105. package/node_modules/@claude-flow/codex/.agents/skills/injection-defense/SKILL.md +45 -0
  106. package/node_modules/@claude-flow/codex/.agents/skills/lora-learning/SKILL.md +39 -0
  107. package/node_modules/@claude-flow/codex/.agents/skills/sublinear-solver/SKILL.md +38 -0
  108. package/node_modules/@claude-flow/codex/.agents/skills/vector-quantization/SKILL.md +49 -0
  109. package/node_modules/@claude-flow/codex/dist/generators/skill-md.d.ts.map +1 -1
  110. package/node_modules/@claude-flow/codex/dist/generators/skill-md.js +6 -0
  111. package/node_modules/@claude-flow/codex/dist/generators/skill-md.js.map +1 -1
  112. package/node_modules/@claude-flow/codex/dist/index.d.ts +3 -3
  113. package/node_modules/@claude-flow/codex/dist/index.js +1 -1
  114. package/node_modules/@claude-flow/codex/dist/templates/index.d.ts.map +1 -1
  115. package/node_modules/@claude-flow/codex/dist/templates/index.js +37 -0
  116. package/node_modules/@claude-flow/codex/dist/templates/index.js.map +1 -1
  117. package/node_modules/@claude-flow/codex/dist/types.d.ts +1 -1
  118. package/node_modules/@claude-flow/codex/dist/types.d.ts.map +1 -1
  119. package/node_modules/@claude-flow/codex/package.json +1 -1
  120. package/package.json +11 -9
  121. package/plugins/ruflo-metaharness/.claude-plugin/plugin.json +2 -1
  122. package/plugins/ruflo-metaharness/scripts/_darwin.mjs +4 -4
  123. package/plugins/ruflo-metaharness/scripts/_harness.mjs +1 -1
  124. package/plugins/ruflo-metaharness/scripts/smoke.sh +4 -4
@@ -399,7 +399,7 @@ export const metaharnessTools = [
399
399
  },
400
400
  // ───────────────────────────────────────────────────────────────────────
401
401
  // ADR-153 — @metaharness/darwin integration (3 tools).
402
- // Backed by the separate `@metaharness/darwin@~0.12.0` npm package, NOT
402
+ // Backed by the separate `@metaharness/darwin@~0.13.0` npm package, NOT
403
403
  // the umbrella `metaharness`. Plugin scripts shell out via _darwin.mjs.
404
404
  // Same {success, data, degraded, exitCode} contract.
405
405
  // ───────────────────────────────────────────────────────────────────────
@@ -21,6 +21,7 @@ const STORAGE_DIR = '.claude-flow';
21
21
  const PERF_DIR = 'performance';
22
22
  const METRICS_FILE = 'metrics.json';
23
23
  const BENCHMARKS_FILE = 'benchmarks.json';
24
+ const MAX_BENCHMARK_ITERATIONS = 10_000;
24
25
  function getPerfDir() {
25
26
  return join(getProjectCwd(), STORAGE_DIR, PERF_DIR);
26
27
  }
@@ -246,14 +247,18 @@ export const performanceTools = [
246
247
  type: 'object',
247
248
  properties: {
248
249
  suite: { type: 'string', enum: ['all', 'memory', 'neural', 'swarm', 'io'], description: 'Benchmark suite' },
249
- iterations: { type: 'number', description: 'Number of iterations' },
250
+ iterations: { type: 'integer', minimum: 1, maximum: MAX_BENCHMARK_ITERATIONS, description: 'Number of iterations (maximum 10000)' },
250
251
  warmup: { type: 'boolean', description: 'Include warmup phase' },
251
252
  },
252
253
  },
253
254
  handler: async (input) => {
255
+ const requestedIterations = input.iterations === undefined ? 100 : input.iterations;
256
+ if (typeof requestedIterations !== 'number' || !Number.isSafeInteger(requestedIterations) || requestedIterations < 1) {
257
+ return { success: false, error: 'iterations must be a positive safe integer' };
258
+ }
259
+ const iterations = Math.min(requestedIterations, MAX_BENCHMARK_ITERATIONS);
254
260
  const store = loadPerfStore();
255
261
  const suite = input.suite || 'all';
256
- const iterations = input.iterations || 100;
257
262
  const warmup = input.warmup !== false;
258
263
  // Synthetic data benchmarks — measures actual CPU/memory throughput
259
264
  const benchmarkFunctions = {
@@ -0,0 +1,3 @@
1
+ export declare function realpathNearest(p: string): string;
2
+ export declare function isInsideRealRoot(realRoot: string, abs: string): boolean;
3
+ //# sourceMappingURL=realpath-containment.d.ts.map
@@ -0,0 +1,39 @@
1
+ /**
2
+ * Project-root containment for MCP tools that read or write files.
3
+ * Shared by hooks_codemod and hooks_fast-apply (moved out of hooks-tools.ts).
4
+ */
5
+ import * as nodeFs from 'fs';
6
+ import { basename, dirname, isAbsolute, join, relative, sep } from 'path';
7
+ // Canonicalize a path that may not exist yet: realpath the nearest existing
8
+ // ancestor and re-attach the missing tail, so a symlinked parent still
9
+ // resolves to its real location (mirrors @claude-flow/security's
10
+ // canonicalizeSync, which is not exported).
11
+ export function realpathNearest(p) {
12
+ try {
13
+ return nodeFs.realpathSync(p);
14
+ }
15
+ catch (err) {
16
+ if (err?.code !== 'ENOENT')
17
+ throw err;
18
+ }
19
+ const parent = dirname(p);
20
+ if (parent === p)
21
+ return p;
22
+ return join(realpathNearest(parent), basename(p));
23
+ }
24
+ // CWE-59 (#4346): containment must compare real paths on BOTH sides — a
25
+ // symlink inside the project pointing outside it must not pass, and a
26
+ // symlinked project root (e.g. macOS /var -> /private/var) must not make
27
+ // every path fail. Fails closed if canonicalization throws (ELOOP, EACCES).
28
+ export function isInsideRealRoot(realRoot, abs) {
29
+ let real;
30
+ try {
31
+ real = realpathNearest(abs);
32
+ }
33
+ catch {
34
+ return false;
35
+ }
36
+ const rel = relative(realRoot, real);
37
+ return rel === '' || (rel !== '..' && !rel.startsWith('..' + sep) && !isAbsolute(rel));
38
+ }
39
+ //# sourceMappingURL=realpath-containment.js.map
@@ -7,4 +7,12 @@
7
7
  export declare function nullPrototypeRecords<M extends object>(map: M | undefined | null): M;
8
8
  /** Only an absent store is empty. Failed reads must never authorize replacement. */
9
9
  export declare function readRecordStore<T>(path: string, collection: string, empty: () => T): T;
10
+ /**
11
+ * JSON object store read for workflow, hive-mind, and swarm (#4737).
12
+ * Same rule as {@link readRecordStore}: only a missing file is empty.
13
+ * A parse failure, a non-object document, or a document `accept` rejects is
14
+ * copied to `${path}.corrupt-<timestamp>` and thrown, so a later save cannot
15
+ * replace the original.
16
+ */
17
+ export declare function readPreservedJsonStore<T extends object>(path: string, label: string, empty: () => T, accept?: (store: T) => boolean): T;
10
18
  //# sourceMappingURL=record-store.d.ts.map
@@ -1,4 +1,5 @@
1
- import { readFileSync } from 'node:fs';
1
+ import { chmodSync, copyFileSync, existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
2
+ import { basename, dirname, join } from 'node:path';
2
3
  /**
3
4
  * Give a record map a null prototype. Record keys come from MCP tool input; on
4
5
  * a plain object `__proto__` or `constructor` resolve to Object.prototype or a
@@ -35,4 +36,100 @@ export function readRecordStore(path, collection, empty) {
35
36
  nullPrototypeRecords(records);
36
37
  return store;
37
38
  }
39
+ /**
40
+ * JSON object store read for workflow, hive-mind, and swarm (#4737).
41
+ * Same rule as {@link readRecordStore}: only a missing file is empty.
42
+ * A parse failure, a non-object document, or a document `accept` rejects is
43
+ * copied to `${path}.corrupt-<timestamp>` and thrown, so a later save cannot
44
+ * replace the original.
45
+ */
46
+ export function readPreservedJsonStore(path, label, empty, accept = () => true) {
47
+ let text;
48
+ try {
49
+ text = readFileSync(path, 'utf-8');
50
+ }
51
+ catch (error) {
52
+ if (error.code === 'ENOENT')
53
+ return empty();
54
+ throw error;
55
+ }
56
+ let parsed;
57
+ try {
58
+ parsed = JSON.parse(text);
59
+ }
60
+ catch (error) {
61
+ const why = error instanceof Error ? error.message : String(error);
62
+ refuseCorruptStore(path, label, why);
63
+ }
64
+ if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed) || !accept(parsed)) {
65
+ refuseCorruptStore(path, label);
66
+ }
67
+ return parsed;
68
+ }
69
+ function refuseCorruptStore(path, label, detail) {
70
+ let where = 'existing data was preserved';
71
+ try {
72
+ where = `corrupt file backed up to ${backupCorruptStore(path)}; existing data was preserved`;
73
+ }
74
+ catch (error) {
75
+ const why = error instanceof Error ? error.message : String(error);
76
+ where = `backup failed (${why}); existing data was preserved`;
77
+ }
78
+ const suffix = detail ? ` (${detail})` : '';
79
+ throw new Error(`Invalid ${label} store at ${path}${suffix}; ${where}`);
80
+ }
81
+ /**
82
+ * Copy `path` to `${path}.corrupt-<timestamp>` without removing the original.
83
+ * A backup with identical bytes is reused, so polling a corrupt store does not
84
+ * add a copy on every read.
85
+ */
86
+ function backupCorruptStore(path) {
87
+ const existing = existingIdenticalBackup(path);
88
+ if (existing)
89
+ return existing;
90
+ const stamp = Date.now();
91
+ let backup = `${path}.corrupt-${stamp}`;
92
+ let n = 0;
93
+ while (existsSync(backup)) {
94
+ n += 1;
95
+ backup = `${path}.corrupt-${stamp}-${n}`;
96
+ }
97
+ copyFileSync(path, backup);
98
+ try {
99
+ chmodSync(backup, statSync(path).mode & 0o777);
100
+ }
101
+ catch {
102
+ /* content is already copied; mode is best-effort */
103
+ }
104
+ return backup;
105
+ }
106
+ function existingIdenticalBackup(path) {
107
+ const dir = dirname(path);
108
+ const prefix = `${basename(path)}.corrupt-`;
109
+ let current;
110
+ try {
111
+ current = readFileSync(path);
112
+ }
113
+ catch {
114
+ return null;
115
+ }
116
+ let names;
117
+ try {
118
+ names = readdirSync(dir).filter((name) => name.startsWith(prefix));
119
+ }
120
+ catch {
121
+ return null;
122
+ }
123
+ for (const name of names) {
124
+ const candidate = join(dir, name);
125
+ try {
126
+ if (statSync(candidate).size === current.length && readFileSync(candidate).equals(current))
127
+ return candidate;
128
+ }
129
+ catch {
130
+ /* unreadable candidate: keep looking */
131
+ }
132
+ }
133
+ return null;
134
+ }
38
135
  //# sourceMappingURL=record-store.js.map
@@ -10,6 +10,15 @@
10
10
  * Created with ❤️ by ruv.io
11
11
  */
12
12
  import type { MCPTool } from './types.js';
13
+ /**
14
+ * Pattern-pack selection for the shared defender (#4785, ADR-517), read once
15
+ * per process from RUFLO_AIDEFENCE_PACKS:
16
+ * unset/empty current default (option omitted)
17
+ * true|false all enabled packs | built-in patterns only
18
+ * a,b,c exactly the named packs
19
+ * Anything else is refused rather than silently falling back.
20
+ */
21
+ export declare function aidefencePackSelection(raw?: string | undefined): boolean | string[] | undefined;
13
22
  /**
14
23
  * Export all security tools
15
24
  */
@@ -33,6 +33,42 @@ const wrapperStats = {
33
33
  quickScanCalls: 0,
34
34
  quickScanThreats: 0,
35
35
  };
36
+ const KNOWN_PACKS = new Set([
37
+ 'core',
38
+ 'tool_invocation',
39
+ 'exfil_url',
40
+ 'encoded_instruction',
41
+ 'slack_markup_forgery',
42
+ 'instruction_override_i18n',
43
+ ]);
44
+ /**
45
+ * Pattern-pack selection for the shared defender (#4785, ADR-517), read once
46
+ * per process from RUFLO_AIDEFENCE_PACKS:
47
+ * unset/empty current default (option omitted)
48
+ * true|false all enabled packs | built-in patterns only
49
+ * a,b,c exactly the named packs
50
+ * Anything else is refused rather than silently falling back.
51
+ */
52
+ export function aidefencePackSelection(raw = process.env.RUFLO_AIDEFENCE_PACKS) {
53
+ const value = raw?.trim();
54
+ if (!value)
55
+ return undefined;
56
+ const lower = value.toLowerCase();
57
+ if (lower === 'true')
58
+ return true;
59
+ if (lower === 'false')
60
+ return false;
61
+ const names = value.split(',').map(name => name.trim()).filter(Boolean);
62
+ const unknown = names.filter(name => !KNOWN_PACKS.has(name));
63
+ if (names.length === 0 || unknown.length > 0) {
64
+ throw new Error(`Invalid RUFLO_AIDEFENCE_PACKS=${JSON.stringify(value)}: use true, false, or a comma list of ${[...KNOWN_PACKS].join(', ')}`);
65
+ }
66
+ return [...new Set(names)];
67
+ }
68
+ function aidefenceOptions() {
69
+ const packs = aidefencePackSelection();
70
+ return packs === undefined ? { enableLearning: true } : { enableLearning: true, packs };
71
+ }
36
72
  /**
37
73
  * Get or create AIDefence instance (throws if unavailable)
38
74
  */
@@ -44,7 +80,7 @@ async function getAIDefence() {
44
80
  // First attempt - try to load via dynamic import (ESM)
45
81
  try {
46
82
  const aidefence = await import(packageName);
47
- const instance = aidefence.createAIDefence({ enableLearning: true });
83
+ const instance = aidefence.createAIDefence(aidefenceOptions());
48
84
  if (!instance) {
49
85
  throw new Error('createAIDefence returned null');
50
86
  }
@@ -81,7 +117,7 @@ async function getAIDefence() {
81
117
  // the module cache is stable across the await boundary.
82
118
  try {
83
119
  const aidefence = await import(packageName);
84
- const instance = aidefence.createAIDefence({ enableLearning: true });
120
+ const instance = aidefence.createAIDefence(aidefenceOptions());
85
121
  if (instance) {
86
122
  aidefenceInstance = instance;
87
123
  console.error(`[claude-flow] ${packageName} loaded after install (resolver path)`);
@@ -95,7 +131,7 @@ async function getAIDefence() {
95
131
  const modulePath = require.resolve(packageName);
96
132
  const cacheBust = `?t=${Date.now()}`;
97
133
  const aidefence = await import(`file://${modulePath}${cacheBust}`);
98
- const instance = aidefence.createAIDefence({ enableLearning: true });
134
+ const instance = aidefence.createAIDefence(aidefenceOptions());
99
135
  if (!instance) {
100
136
  throw new Error('createAIDefence returned null after install');
101
137
  }
@@ -9,6 +9,7 @@ import { gunzipSync } from 'node:zlib';
9
9
  import { join } from 'node:path';
10
10
  import { getProjectCwd } from './types.js';
11
11
  import { containedWritePath } from './path-containment.js';
12
+ import { MAX_IMPORT_BYTES, readImportFile } from './import-limits.js';
12
13
  import { mkdirRestricted, readFileMaybeEncrypted, writeFileRestricted, } from '../fs-secure.js';
13
14
  import { validateIdentifier, validateText } from './validate-input.js';
14
15
  function isRecord(value) {
@@ -729,7 +730,7 @@ export const sessionTools = [
729
730
  inputSchema: {
730
731
  type: 'object',
731
732
  properties: {
732
- inputPath: { type: 'string', description: 'Path to the session JSON file to import (or pass data)' },
733
+ inputPath: { type: 'string', description: 'Path to the session JSON file to import (or pass data); file and gzip output are each limited to 16 MiB' },
733
734
  data: { type: 'object', description: 'The session record itself, as written by session_export (or pass inputPath)' },
734
735
  name: { type: 'string', description: 'Override the imported session name' },
735
736
  activate: { type: 'boolean', description: 'Restore the imported session into the active stores' },
@@ -747,8 +748,9 @@ export const sessionTools = [
747
748
  if (!existsSync(inputPath))
748
749
  return { error: `File not found: ${inputPath}` };
749
750
  try {
750
- const bytes = readFileSync(inputPath);
751
- const content = bytes[0] === 0x1f && bytes[1] === 0x8b ? gunzipSync(bytes) : bytes;
751
+ const bytes = readImportFile(inputPath);
752
+ const content = bytes[0] === 0x1f && bytes[1] === 0x8b
753
+ ? gunzipSync(bytes, { maxOutputLength: MAX_IMPORT_BYTES }) : bytes;
752
754
  parsed = JSON.parse(content.toString('utf-8'));
753
755
  }
754
756
  catch (e) {
@@ -4,9 +4,9 @@
4
4
  * Tool definitions for swarm coordination with file-based state persistence.
5
5
  * Replaces previous stub implementations with real state tracking.
6
6
  */
7
- import { closeSync, existsSync, mkdirSync, openSync, readFileSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
7
+ import { closeSync, existsSync, mkdirSync, openSync, renameSync, statSync, unlinkSync, writeFileSync, } from 'node:fs';
8
8
  import { join } from 'node:path';
9
- import { nullPrototypeRecords } from './record-store.js';
9
+ import { nullPrototypeRecords, readPreservedJsonStore } from './record-store.js';
10
10
  import { getProjectCwd } from './types.js';
11
11
  import { validateIdentifier } from './validate-input.js';
12
12
  import { createApscState, isApscAgentEligible, normalizeApscConfig, recordApscSignal, } from '../services/pheromone-adaptive.js';
@@ -85,16 +85,17 @@ function reconcileOrphanSwarms(store) {
85
85
  // #2085 — exported so `agent-tools.ts agent_spawn` can push into
86
86
  // `swarm.agents` (the field `swarm_status` reads).
87
87
  export function loadSwarmStore() {
88
- let store = { swarms: {}, version: '3.0.0' };
89
- try {
90
- const path = getSwarmStatePath();
91
- if (existsSync(path)) {
92
- store = JSON.parse(readFileSync(path, 'utf-8'));
93
- }
94
- }
95
- catch { /* fall through with default */ }
96
- if (!store || typeof store !== 'object' || Array.isArray(store))
97
- store = { swarms: {}, version: '3.0.0' };
88
+ // #4737: a parse error used to fall through to an empty store, and the next
89
+ // save (or orphan reconcile) overwrote swarm-state.json. Only a missing
90
+ // file is empty; corrupt bytes are copied aside and the error is reported.
91
+ const store = readPreservedJsonStore(getSwarmStatePath(), 'swarm', () => ({ swarms: {}, version: '3.0.0' }), (candidate) => {
92
+ const swarms = candidate.swarms;
93
+ return swarms === undefined || (!!swarms && typeof swarms === 'object' && !Array.isArray(swarms));
94
+ });
95
+ if (!store.swarms)
96
+ store.swarms = {};
97
+ // Record ids come from MCP input. A null prototype stops `__proto__` and
98
+ // `constructor` from resolving onto Object.prototype.
98
99
  store.swarms = nullPrototypeRecords(store.swarms);
99
100
  // #1799 — reconcile orphans on every load and persist if anything changed.
100
101
  // Cheap (process.kill(pid, 0) is sub-millisecond) and means
@@ -369,14 +370,18 @@ export const swarmTools = [
369
370
  }
370
371
  const store = loadSwarmStore();
371
372
  const swarmId = input.swarmId;
372
- if (swarmId && store.swarms[swarmId]) {
373
+ if (swarmId && !store.swarms[swarmId]) {
374
+ return { success: false, error: `Swarm ${swarmId} not found` };
375
+ }
376
+ const { getLiveAgentIds } = await import('./agent-tools.js');
377
+ if (swarmId) {
373
378
  const swarm = store.swarms[swarmId];
374
379
  return {
375
380
  swarmId: swarm.swarmId,
376
381
  status: swarm.status,
377
382
  topology: swarm.topology,
378
383
  maxAgents: swarm.maxAgents,
379
- agentCount: swarm.agents.length,
384
+ agentCount: getLiveAgentIds(swarm.agents).length,
380
385
  taskCount: swarm.tasks.length,
381
386
  config: swarm.config,
382
387
  apsc: apscStateOf(swarm),
@@ -401,7 +406,7 @@ export const swarmTools = [
401
406
  status: latest.status,
402
407
  topology: latest.topology,
403
408
  maxAgents: latest.maxAgents,
404
- agentCount: latest.agents.length,
409
+ agentCount: getLiveAgentIds(latest.agents).length,
405
410
  taskCount: latest.tasks.length,
406
411
  config: latest.config,
407
412
  apsc: apscStateOf(latest),
@@ -433,7 +438,7 @@ export const swarmTools = [
433
438
  const swarmId = input.swarmId;
434
439
  // Find the swarm
435
440
  let target;
436
- if (swarmId && store.swarms[swarmId]) {
441
+ if (swarmId) {
437
442
  target = store.swarms[swarmId];
438
443
  }
439
444
  else {
@@ -456,6 +461,19 @@ export const swarmTools = [
456
461
  error: 'Swarm already terminated',
457
462
  };
458
463
  }
464
+ const { agentTools, getLiveAgentIds } = await import('./agent-tools.js');
465
+ const terminateAgent = agentTools.find(tool => tool.name === 'agent_terminate');
466
+ let agentsTerminated = 0;
467
+ for (const agentId of getLiveAgentIds(target.agents)) {
468
+ const result = await terminateAgent.handler({
469
+ agentId,
470
+ force: input.graceful === false,
471
+ });
472
+ if (!result.success) {
473
+ return { success: false, swarmId: target.swarmId, agentsTerminated, error: result.error };
474
+ }
475
+ agentsTerminated++;
476
+ }
459
477
  target.status = 'terminated';
460
478
  target.updatedAt = new Date().toISOString();
461
479
  saveSwarmStore(store);
@@ -464,7 +482,7 @@ export const swarmTools = [
464
482
  swarmId: target.swarmId,
465
483
  terminated: true,
466
484
  graceful: input.graceful ?? true,
467
- agentsTerminated: target.agents.length,
485
+ agentsTerminated,
468
486
  terminatedAt: target.updatedAt,
469
487
  };
470
488
  },
@@ -93,6 +93,37 @@ function releaseAgents(agentIds, taskId) {
93
93
  }
94
94
  });
95
95
  }
96
+ /**
97
+ * Stores `task_assign` may bind an agent from.
98
+ *
99
+ * The canonical file is `.claude-flow/agents/store.json`. `hive-mind_spawn`
100
+ * writes its workers to `.claude-flow/agents.json` instead (#1916), so an id
101
+ * that exists in either store is a real agent. A corrupt canonical store
102
+ * throws, matching the read this handler already performed, so a bad file is
103
+ * never replaced. The hive file stays best-effort: a corrupt copy must not
104
+ * hide agents that are present in the canonical store.
105
+ */
106
+ function assignableAgentStores() {
107
+ const canonical = readRecordStore(join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json'), 'agents', () => ({ agents: {} }));
108
+ const stores = [canonical.agents];
109
+ const hivePath = join(getProjectCwd(), STORAGE_DIR, 'agents.json');
110
+ try {
111
+ if (!existsSync(hivePath))
112
+ return stores;
113
+ const parsed = JSON.parse(readFileSync(hivePath, 'utf-8'));
114
+ const agents = parsed?.agents;
115
+ if (agents && typeof agents === 'object' && !Array.isArray(agents)) {
116
+ stores.push(agents);
117
+ }
118
+ }
119
+ catch {
120
+ // Best-effort, same as updateAgents.
121
+ }
122
+ return stores;
123
+ }
124
+ function agentIsAssignable(id, stores) {
125
+ return stores.some((agents) => Object.prototype.hasOwnProperty.call(agents, id) && Boolean(agents[id]));
126
+ }
96
127
  export const taskTools = [
97
128
  {
98
129
  name: 'task_create',
@@ -450,10 +481,20 @@ export const taskTools = [
450
481
  if (!task) {
451
482
  return { taskId, error: 'Task not found' };
452
483
  }
484
+ // Completed and cancelled tasks are terminal (#4725). Assigning a
485
+ // completed task marks the agent busy, and task_complete then returns
486
+ // without releasing it; task_cancel refuses a finished task too, so
487
+ // nothing ever sets that agent back to idle.
488
+ if (task.status === 'completed' || task.status === 'cancelled') {
489
+ return {
490
+ success: false,
491
+ taskId,
492
+ status: task.status,
493
+ error: `Cannot assign a ${task.status} task`,
494
+ };
495
+ }
453
496
  const previouslyAssigned = [...task.assignedTo];
454
- // Load agent store to sync worker state
455
- const agentStorePath = join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json');
456
- readRecordStore(agentStorePath, 'agents', () => ({ agents: {} }));
497
+ const agentStores = assignableAgentStores();
457
498
  if (input.unassign) {
458
499
  // Revert previously assigned agents to idle
459
500
  releaseAgents(previouslyAssigned, taskId);
@@ -461,6 +502,20 @@ export const taskTools = [
461
502
  }
462
503
  else {
463
504
  const agentIds = input.agentIds || [];
505
+ // An id in neither store is a ghost owner: the task would go
506
+ // in_progress with nobody to do the work (#4725).
507
+ if (Array.isArray(agentIds)) {
508
+ const missing = agentIds.filter((id) => typeof id === 'string' && !agentIsAssignable(id, agentStores));
509
+ if (missing.length > 0) {
510
+ const listed = missing.join(', ');
511
+ return {
512
+ success: false,
513
+ taskId,
514
+ status: task.status,
515
+ error: missing.length === 1 ? `Agent not found: ${listed}` : `Agents not found: ${listed}`,
516
+ };
517
+ }
518
+ }
464
519
  // Revert old agents to idle
465
520
  releaseAgents(previouslyAssigned.filter((id) => !agentIds.includes(id)), taskId);
466
521
  // Set new agents to active
@@ -569,21 +624,29 @@ export const taskTools = [
569
624
  const original = store.tasks[taskId];
570
625
  if (!original)
571
626
  return { success: false, taskId, error: 'Task not found' };
627
+ const retainState = input.resetState === false;
572
628
  const newTaskId = `task-${Date.now()}-${Math.random().toString(36).slice(2, 8)}`;
573
- store.tasks[newTaskId] = {
629
+ const retry = {
574
630
  taskId: newTaskId,
575
631
  type: original.type,
576
632
  description: original.description,
577
633
  priority: original.priority,
578
634
  status: 'pending',
579
- progress: 0,
635
+ progress: retainState ? original.progress ?? 0 : 0,
580
636
  assignedTo: [...original.assignedTo],
581
637
  tags: [...original.tags, 'retry-of:' + taskId],
582
638
  createdAt: new Date().toISOString(),
583
639
  startedAt: null,
584
640
  completedAt: null,
585
641
  };
642
+ if (retainState && original.result !== undefined)
643
+ retry.result = original.result;
644
+ store.tasks[newTaskId] = retry;
586
645
  saveTaskStore(store);
646
+ updateAgents(retry.assignedTo, (agent) => {
647
+ agent.status = 'busy';
648
+ agent.currentTask = newTaskId;
649
+ });
587
650
  return {
588
651
  taskId,
589
652
  newTaskId,
@@ -144,6 +144,15 @@ export const terminalTools = [
144
144
  }
145
145
  // Find or create default session
146
146
  let session = sessionId ? store.sessions[sessionId] : Object.values(store.sessions).find(s => s.status === 'active');
147
+ // #4730: terminal_close only flips status to "closed". Executing anyway
148
+ // ran the command and then wrote status back to "active", so a closed
149
+ // session kept accepting commands. Reject anything that is not active
150
+ // before the process is spawned and before that status write. When no
151
+ // sessionId was given, the lookup above already selected an active
152
+ // session (or we create one below).
153
+ if (session && session.status !== 'active') {
154
+ return { success: false, error: `Session is not active (${session.status})` };
155
+ }
147
156
  if (!session) {
148
157
  // Create default session
149
158
  const id = `term-${Date.now()}-${randomBytes(4).toString('hex')}`;
@@ -8,6 +8,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
+ import { readPreservedJsonStore } from './record-store.js';
11
12
  // Storage paths
12
13
  const STORAGE_DIR = '.claude-flow';
13
14
  const WORKFLOW_DIR = 'workflows';
@@ -73,19 +74,19 @@ function withRecordMaps(store, keys) {
73
74
  return store;
74
75
  }
75
76
  const WORKFLOW_MAPS = ['workflows', 'templates'];
77
+ function isRecordMap(value) {
78
+ return !!value && typeof value === 'object' && !Array.isArray(value);
79
+ }
76
80
  function loadWorkflowStore() {
77
- try {
78
- const path = getWorkflowPath();
79
- if (existsSync(path)) {
80
- const data = JSON.parse(readFileSync(path, 'utf-8'));
81
- if (data && typeof data === 'object' && !Array.isArray(data))
82
- return withRecordMaps(data, WORKFLOW_MAPS);
83
- }
84
- }
85
- catch {
86
- // Return default store on error
87
- }
88
- return withRecordMaps({ workflows: {}, templates: {}, version: '3.0.0' }, WORKFLOW_MAPS);
81
+ // #4737: a parse error used to return an empty store, and the next save
82
+ // overwrote the file. Only a missing file is empty; corrupt bytes are
83
+ // copied aside and the error is reported.
84
+ const path = getWorkflowPath();
85
+ const data = readPreservedJsonStore(path, 'workflow', () => ({ workflows: {}, templates: {}, version: '3.0.0' }), (store) => WORKFLOW_MAPS.every((key) => {
86
+ const map = store[key];
87
+ return map === undefined || isRecordMap(map);
88
+ }));
89
+ return withRecordMaps(data, WORKFLOW_MAPS);
89
90
  }
90
91
  function saveWorkflowStore(store) {
91
92
  ensureWorkflowDir();