claude-flow 3.71.3 → 3.72.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (86) hide show
  1. package/.claude/helpers/auto-memory-hook.mjs +17 -0
  2. package/.claude/helpers/hook-handler.cjs +23 -10
  3. package/.claude/helpers/intelligence.cjs +23 -1
  4. package/.claude/helpers/statusline.cjs +29 -14
  5. package/.claude/proven-config.json +1 -1
  6. package/README.md +18 -3
  7. package/README.zh-CN.md +16 -3
  8. package/package.json +1 -1
  9. package/v3/@claude-flow/cli/README.md +18 -3
  10. package/v3/@claude-flow/cli/bin/cli.js +13 -18
  11. package/v3/@claude-flow/cli/bin/mcp-server.js +13 -18
  12. package/v3/@claude-flow/cli/catalog-manifest.json +2 -2
  13. package/v3/@claude-flow/cli/dist/src/appliance/rvfa-distribution.js +2 -2
  14. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.d.ts +1 -7
  15. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-critic.js +1 -7
  16. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.d.ts +1 -8
  17. package/v3/@claude-flow/cli/dist/src/benchmarks/gaia-decomposer.js +1 -8
  18. package/v3/@claude-flow/cli/dist/src/commands/agent-wasm.js +2 -2
  19. package/v3/@claude-flow/cli/dist/src/commands/analyze.js +1 -1
  20. package/v3/@claude-flow/cli/dist/src/commands/daemon.js +1 -1
  21. package/v3/@claude-flow/cli/dist/src/commands/doctor.js +3 -2
  22. package/v3/@claude-flow/cli/dist/src/commands/guidance.js +9 -9
  23. package/v3/@claude-flow/cli/dist/src/commands/hooks.js +13 -8
  24. package/v3/@claude-flow/cli/dist/src/commands/init.js +14 -16
  25. package/v3/@claude-flow/cli/dist/src/commands/memory.js +4 -3
  26. package/v3/@claude-flow/cli/dist/src/commands/neural.js +8 -6
  27. package/v3/@claude-flow/cli/dist/src/commands/route.js +1 -1
  28. package/v3/@claude-flow/cli/dist/src/commands/ruvector/backup.js +7 -5
  29. package/v3/@claude-flow/cli/dist/src/commands/ruvector/benchmark.js +6 -1
  30. package/v3/@claude-flow/cli/dist/src/commands/ruvector/import.js +19 -5
  31. package/v3/@claude-flow/cli/dist/src/commands/ruvector/init.js +1 -1
  32. package/v3/@claude-flow/cli/dist/src/commands/start.js +1 -1
  33. package/v3/@claude-flow/cli/dist/src/commands/status.js +1 -1
  34. package/v3/@claude-flow/cli/dist/src/commands/task.js +18 -1
  35. package/v3/@claude-flow/cli/dist/src/commands/update.js +1 -1
  36. package/v3/@claude-flow/cli/dist/src/funnel/local-signals.js +7 -2
  37. package/v3/@claude-flow/cli/dist/src/init/helpers-generator.js +16 -1
  38. package/v3/@claude-flow/cli/dist/src/mcp-protocol.d.ts +90 -0
  39. package/v3/@claude-flow/cli/dist/src/mcp-protocol.js +179 -0
  40. package/v3/@claude-flow/cli/dist/src/mcp-server.d.ts +1 -0
  41. package/v3/@claude-flow/cli/dist/src/mcp-server.js +20 -22
  42. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-execute-core.js +9 -1
  43. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.d.ts +13 -0
  44. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +63 -12
  45. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentbbs-federation.d.ts +18 -1
  46. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentbbs-federation.js +23 -7
  47. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-argv.d.ts +27 -0
  48. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-argv.js +92 -0
  49. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-session-tools.js +4 -0
  50. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-tools.d.ts +1 -1
  51. package/v3/@claude-flow/cli/dist/src/mcp-tools/browser-tools.js +25 -8
  52. package/v3/@claude-flow/cli/dist/src/mcp-tools/coordination-tools.js +5 -4
  53. package/v3/@claude-flow/cli/dist/src/mcp-tools/embeddings-tools.js +12 -4
  54. package/v3/@claude-flow/cli/dist/src/mcp-tools/glob-exclusions.d.ts +6 -0
  55. package/v3/@claude-flow/cli/dist/src/mcp-tools/glob-exclusions.js +81 -0
  56. package/v3/@claude-flow/cli/dist/src/mcp-tools/hive-mind-tools.js +104 -35
  57. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +12 -5
  58. package/v3/@claude-flow/cli/dist/src/mcp-tools/import-limits.d.ts +4 -0
  59. package/v3/@claude-flow/cli/dist/src/mcp-tools/import-limits.js +28 -0
  60. package/v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.js +68 -72
  61. package/v3/@claude-flow/cli/dist/src/mcp-tools/neural-tools.js +8 -2
  62. package/v3/@claude-flow/cli/dist/src/mcp-tools/path-containment.d.ts +34 -0
  63. package/v3/@claude-flow/cli/dist/src/mcp-tools/path-containment.js +133 -0
  64. package/v3/@claude-flow/cli/dist/src/mcp-tools/performance-tools.js +7 -2
  65. package/v3/@claude-flow/cli/dist/src/mcp-tools/record-store.d.ts +15 -0
  66. package/v3/@claude-flow/cli/dist/src/mcp-tools/record-store.js +117 -3
  67. package/v3/@claude-flow/cli/dist/src/mcp-tools/security-tools.d.ts +9 -0
  68. package/v3/@claude-flow/cli/dist/src/mcp-tools/security-tools.js +39 -3
  69. package/v3/@claude-flow/cli/dist/src/mcp-tools/session-tools.js +9 -41
  70. package/v3/@claude-flow/cli/dist/src/mcp-tools/swarm-tools.js +36 -14
  71. package/v3/@claude-flow/cli/dist/src/mcp-tools/task-tools.js +68 -5
  72. package/v3/@claude-flow/cli/dist/src/mcp-tools/terminal-tools.js +16 -2
  73. package/v3/@claude-flow/cli/dist/src/mcp-tools/validate-input.d.ts +2 -0
  74. package/v3/@claude-flow/cli/dist/src/mcp-tools/validate-input.js +14 -0
  75. package/v3/@claude-flow/cli/dist/src/mcp-tools/workflow-tools.js +13 -12
  76. package/v3/@claude-flow/cli/dist/src/mcp-tools/x-federation-join.js +55 -14
  77. package/v3/@claude-flow/cli/dist/src/memory/intelligence.d.ts +11 -0
  78. package/v3/@claude-flow/cli/dist/src/memory/intelligence.js +84 -6
  79. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +6 -2
  80. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +15 -6
  81. package/v3/@claude-flow/cli/dist/src/ruvector/model-router.d.ts +6 -1
  82. package/v3/@claude-flow/cli/dist/src/ruvector/model-router.js +16 -4
  83. package/v3/@claude-flow/cli/dist/src/services/worker-daemon.js +30 -12
  84. package/v3/@claude-flow/cli/dist/src/transfer/storage/gcs.js +3 -2
  85. package/v3/@claude-flow/cli/package.json +1 -1
  86. package/.claude/security-scans/scan-all-quick.json +0 -201
@@ -0,0 +1,133 @@
1
+ /**
2
+ * Path checks for MCP tools that read or write a caller-named file.
3
+ *
4
+ * Paths in tool input come from whoever drives the MCP server, including a
5
+ * model following injected instructions. A tool that writes or reads such a
6
+ * path must keep it inside the project directory, and must not follow a
7
+ * symlink out of it.
8
+ */
9
+ import { closeSync, lstatSync, openSync, readSync, realpathSync } from 'node:fs';
10
+ import { basename, dirname, extname, isAbsolute, join, relative, resolve, sep } from 'node:path';
11
+ import { isNonProjectDir } from '@claude-flow/cli-core/mcp-tools/types';
12
+ import { getProjectCwd } from './types.js';
13
+ import { existingFileIsEncrypted } from '../fs-secure.js';
14
+ function lstatOrNull(p) {
15
+ try {
16
+ return lstatSync(p);
17
+ }
18
+ catch {
19
+ return null;
20
+ }
21
+ }
22
+ function projectRoot() {
23
+ const root = realpathSync(getProjectCwd());
24
+ // A server started in a home or filesystem root has no project to contain
25
+ // writes to; "inside the root" would mean the whole home directory.
26
+ return isNonProjectDir(root) ? null : root;
27
+ }
28
+ function insideRoot(root, target) {
29
+ const rel = relative(root, target);
30
+ if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
31
+ return false;
32
+ return !rel.split(sep).includes('.git');
33
+ }
34
+ /**
35
+ * Resolve a caller-named output file inside the project. The real parent
36
+ * directory must be inside the real project root and outside `.git`, and an
37
+ * existing target must be a regular, non-executable file — not a symlink.
38
+ * `extensions`, when given, lists the allowed lower-case file extensions.
39
+ */
40
+ export function containedWritePath(p, extensions) {
41
+ if (!p || p.includes('\0'))
42
+ return null;
43
+ try {
44
+ const root = projectRoot();
45
+ if (!root)
46
+ return null;
47
+ const abs = resolve(root, p);
48
+ if (extensions && !extensions.includes(extname(abs).toLowerCase()))
49
+ return null;
50
+ const target = join(realpathSync(dirname(abs)), basename(abs));
51
+ if (!insideRoot(root, target))
52
+ return null;
53
+ const existing = lstatOrNull(target);
54
+ if (existing && (existing.isSymbolicLink() || !existing.isFile() || (existing.mode & 0o111) !== 0))
55
+ return null;
56
+ return target;
57
+ }
58
+ catch {
59
+ return null;
60
+ }
61
+ }
62
+ /** Resolve a caller-named input file inside the project: a regular file, not a symlink. */
63
+ export function containedReadPath(p) {
64
+ if (!p || p.includes('\0'))
65
+ return null;
66
+ try {
67
+ const root = projectRoot();
68
+ if (!root)
69
+ return null;
70
+ const abs = resolve(root, p);
71
+ const existing = lstatOrNull(abs);
72
+ if (!existing || existing.isSymbolicLink() || !existing.isFile())
73
+ return null;
74
+ const target = realpathSync(abs);
75
+ return insideRoot(root, target) ? target : null;
76
+ }
77
+ catch {
78
+ return null;
79
+ }
80
+ }
81
+ const DB_EXTENSIONS = ['.db', '.sqlite', '.sqlite3'];
82
+ const SQLITE_HEADER = 'SQLite format 3\0';
83
+ /**
84
+ * Check a caller-named memory database path. It may live outside the project
85
+ * (the CLI's `--path` flag passes one), so this does not contain it; instead
86
+ * it refuses anything that is not plainly a SQLite database (plaintext, or
87
+ * encrypted at rest per ADR-096), so the memory tools cannot be pointed at and
88
+ * overwrite an unrelated file.
89
+ */
90
+ export function dbPathError(p) {
91
+ if (p.includes('\0'))
92
+ return 'dbPath contains a null byte';
93
+ if (!DB_EXTENSIONS.includes(extname(p).toLowerCase())) {
94
+ return `dbPath must end in ${DB_EXTENSIONS.join(', ')}`;
95
+ }
96
+ const existing = lstatOrNull(p);
97
+ if (!existing)
98
+ return null;
99
+ if (existing.isSymbolicLink())
100
+ return 'dbPath must not be a symlink';
101
+ if (!existing.isFile())
102
+ return 'dbPath must be a regular file';
103
+ if (existing.size === 0 || existingFileIsEncrypted(p) === true)
104
+ return null;
105
+ const header = Buffer.alloc(SQLITE_HEADER.length);
106
+ let fd;
107
+ try {
108
+ fd = openSync(p, 'r');
109
+ readSync(fd, header, 0, header.length, 0);
110
+ }
111
+ catch {
112
+ return 'dbPath could not be read';
113
+ }
114
+ finally {
115
+ if (fd !== undefined)
116
+ closeSync(fd);
117
+ }
118
+ return header.toString('latin1') === SQLITE_HEADER ? null : 'dbPath is not a SQLite database';
119
+ }
120
+ /**
121
+ * Marks a tool call made by the local CLI on the operator's behalf (for
122
+ * example `ruflo memory export --output ~/backup.json`). MCP requests arrive
123
+ * as JSON and cannot carry a symbol key, so this cannot be forged remotely.
124
+ */
125
+ export const LOCAL_CLI_CALL = Symbol('ruflo.localCliCall');
126
+ export function localCliContext() {
127
+ return { [LOCAL_CLI_CALL]: true };
128
+ }
129
+ export function isLocalCliCall(context) {
130
+ return !!context && typeof context === 'object'
131
+ && context[LOCAL_CLI_CALL] === true;
132
+ }
133
+ //# sourceMappingURL=path-containment.js.map
@@ -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 = {
@@ -1,3 +1,18 @@
1
+ /**
2
+ * Give a record map a null prototype. Record keys come from MCP tool input; on
3
+ * a plain object `__proto__` or `constructor` resolve to Object.prototype or a
4
+ * built-in, which a handler would then write into. A null-prototype map only
5
+ * ever returns its own records.
6
+ */
7
+ export declare function nullPrototypeRecords<M extends object>(map: M | undefined | null): M;
1
8
  /** Only an absent store is empty. Failed reads must never authorize replacement. */
2
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;
3
18
  //# sourceMappingURL=record-store.d.ts.map
@@ -1,4 +1,18 @@
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';
3
+ /**
4
+ * Give a record map a null prototype. Record keys come from MCP tool input; on
5
+ * a plain object `__proto__` or `constructor` resolve to Object.prototype or a
6
+ * built-in, which a handler would then write into. A null-prototype map only
7
+ * ever returns its own records.
8
+ */
9
+ export function nullPrototypeRecords(map) {
10
+ if (map && typeof map === 'object' && !Array.isArray(map)) {
11
+ Object.setPrototypeOf(map, null);
12
+ return map;
13
+ }
14
+ return Object.create(null);
15
+ }
2
16
  /** Only an absent store is empty. Failed reads must never authorize replacement. */
3
17
  export function readRecordStore(path, collection, empty) {
4
18
  let text;
@@ -6,8 +20,11 @@ export function readRecordStore(path, collection, empty) {
6
20
  text = readFileSync(path, 'utf-8');
7
21
  }
8
22
  catch (error) {
9
- if (error.code === 'ENOENT')
10
- return empty();
23
+ if (error.code === 'ENOENT') {
24
+ const store = empty();
25
+ store[collection] = nullPrototypeRecords(store[collection]);
26
+ return store;
27
+ }
11
28
  throw error;
12
29
  }
13
30
  const store = JSON.parse(text);
@@ -16,6 +33,103 @@ export function readRecordStore(path, collection, empty) {
16
33
  || !records || typeof records !== 'object' || Array.isArray(records)) {
17
34
  throw new Error(`Invalid ${collection} store at ${path}; existing data was preserved`);
18
35
  }
36
+ nullPrototypeRecords(records);
19
37
  return store;
20
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
+ }
21
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
  }
@@ -3,11 +3,13 @@
3
3
  *
4
4
  * Tool definitions for session management with file persistence.
5
5
  */
6
- import { existsSync, lstatSync, readFileSync, readdirSync, realpathSync, unlinkSync, statSync, writeFileSync } from 'node:fs';
6
+ import { existsSync, readFileSync, readdirSync, unlinkSync, statSync, writeFileSync } from 'node:fs';
7
7
  import { randomUUID } from 'node:crypto';
8
8
  import { gunzipSync } from 'node:zlib';
9
- import { basename, dirname, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
+ import { join } from 'node:path';
10
10
  import { getProjectCwd } from './types.js';
11
+ import { containedWritePath } from './path-containment.js';
12
+ import { MAX_IMPORT_BYTES, readImportFile } from './import-limits.js';
11
13
  import { mkdirRestricted, readFileMaybeEncrypted, writeFileRestricted, } from '../fs-secure.js';
12
14
  import { validateIdentifier, validateText } from './validate-input.js';
13
15
  function isRecord(value) {
@@ -351,41 +353,6 @@ function isSessionRecordLike(value) {
351
353
  const v = value;
352
354
  return 'data' in v || 'stats' in v || 'sessionId' in v || 'savedAt' in v;
353
355
  }
354
- /**
355
- * SECURITY: `outputPath` comes from MCP tool input. Resolve it against the
356
- * project root and require the real (symlink-resolved) parent directory to stay
357
- * inside the real project root, and refuse an existing symlink as the target,
358
- * so session_export cannot write files elsewhere on the host. The CLI's
359
- * `session export` writes its own file and does not pass outputPath.
360
- */
361
- function containedExportPath(outputPath) {
362
- if (!outputPath || outputPath.includes('\0'))
363
- return null;
364
- try {
365
- const root = realpathSync(getProjectCwd());
366
- const abs = resolve(root, outputPath);
367
- const parent = realpathSync(dirname(abs));
368
- const target = join(parent, basename(abs));
369
- const rel = relative(root, target);
370
- if (!rel || rel === '..' || rel.startsWith(`..${sep}`) || isAbsolute(rel))
371
- return null;
372
- const existing = lstatOrNull(target);
373
- if (existing && (existing.isSymbolicLink() || !existing.isFile()))
374
- return null;
375
- return target;
376
- }
377
- catch {
378
- return null;
379
- }
380
- }
381
- function lstatOrNull(p) {
382
- try {
383
- return lstatSync(p);
384
- }
385
- catch {
386
- return null;
387
- }
388
- }
389
356
  export const sessionTools = [
390
357
  {
391
358
  name: 'session_save',
@@ -740,7 +707,7 @@ export const sessionTools = [
740
707
  let path = null;
741
708
  const outputPath = input.outputPath ? String(input.outputPath) : null;
742
709
  if (outputPath) {
743
- const target = containedExportPath(outputPath);
710
+ const target = containedWritePath(outputPath);
744
711
  if (!target)
745
712
  return { sessionId, error: 'outputPath must be a file inside the project directory (no symlinks)' };
746
713
  try {
@@ -763,7 +730,7 @@ export const sessionTools = [
763
730
  inputSchema: {
764
731
  type: 'object',
765
732
  properties: {
766
- 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' },
767
734
  data: { type: 'object', description: 'The session record itself, as written by session_export (or pass inputPath)' },
768
735
  name: { type: 'string', description: 'Override the imported session name' },
769
736
  activate: { type: 'boolean', description: 'Restore the imported session into the active stores' },
@@ -781,8 +748,9 @@ export const sessionTools = [
781
748
  if (!existsSync(inputPath))
782
749
  return { error: `File not found: ${inputPath}` };
783
750
  try {
784
- const bytes = readFileSync(inputPath);
785
- 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;
786
754
  parsed = JSON.parse(content.toString('utf-8'));
787
755
  }
788
756
  catch (e) {
@@ -4,8 +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, readPreservedJsonStore } from './record-store.js';
9
10
  import { getProjectCwd } from './types.js';
10
11
  import { validateIdentifier } from './validate-input.js';
11
12
  import { createApscState, isApscAgentEligible, normalizeApscConfig, recordApscSignal, } from '../services/pheromone-adaptive.js';
@@ -84,14 +85,18 @@ function reconcileOrphanSwarms(store) {
84
85
  // #2085 — exported so `agent-tools.ts agent_spawn` can push into
85
86
  // `swarm.agents` (the field `swarm_status` reads).
86
87
  export function loadSwarmStore() {
87
- let store = { swarms: {}, version: '3.0.0' };
88
- try {
89
- const path = getSwarmStatePath();
90
- if (existsSync(path)) {
91
- store = JSON.parse(readFileSync(path, 'utf-8'));
92
- }
93
- }
94
- catch { /* fall through with default */ }
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.
99
+ store.swarms = nullPrototypeRecords(store.swarms);
95
100
  // #1799 — reconcile orphans on every load and persist if anything changed.
96
101
  // Cheap (process.kill(pid, 0) is sub-millisecond) and means
97
102
  // `swarm_status`/`swarm_health` never see ghost "running" entries.
@@ -365,14 +370,18 @@ export const swarmTools = [
365
370
  }
366
371
  const store = loadSwarmStore();
367
372
  const swarmId = input.swarmId;
368
- 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) {
369
378
  const swarm = store.swarms[swarmId];
370
379
  return {
371
380
  swarmId: swarm.swarmId,
372
381
  status: swarm.status,
373
382
  topology: swarm.topology,
374
383
  maxAgents: swarm.maxAgents,
375
- agentCount: swarm.agents.length,
384
+ agentCount: getLiveAgentIds(swarm.agents).length,
376
385
  taskCount: swarm.tasks.length,
377
386
  config: swarm.config,
378
387
  apsc: apscStateOf(swarm),
@@ -397,7 +406,7 @@ export const swarmTools = [
397
406
  status: latest.status,
398
407
  topology: latest.topology,
399
408
  maxAgents: latest.maxAgents,
400
- agentCount: latest.agents.length,
409
+ agentCount: getLiveAgentIds(latest.agents).length,
401
410
  taskCount: latest.tasks.length,
402
411
  config: latest.config,
403
412
  apsc: apscStateOf(latest),
@@ -429,7 +438,7 @@ export const swarmTools = [
429
438
  const swarmId = input.swarmId;
430
439
  // Find the swarm
431
440
  let target;
432
- if (swarmId && store.swarms[swarmId]) {
441
+ if (swarmId) {
433
442
  target = store.swarms[swarmId];
434
443
  }
435
444
  else {
@@ -452,6 +461,19 @@ export const swarmTools = [
452
461
  error: 'Swarm already terminated',
453
462
  };
454
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
+ }
455
477
  target.status = 'terminated';
456
478
  target.updatedAt = new Date().toISOString();
457
479
  saveSwarmStore(store);
@@ -460,7 +482,7 @@ export const swarmTools = [
460
482
  swarmId: target.swarmId,
461
483
  terminated: true,
462
484
  graceful: input.graceful ?? true,
463
- agentsTerminated: target.agents.length,
485
+ agentsTerminated,
464
486
  terminatedAt: target.updatedAt,
465
487
  };
466
488
  },