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
@@ -8,6 +8,7 @@ import { join } from 'node:path';
8
8
  import { randomBytes, createHash, timingSafeEqual } from 'node:crypto';
9
9
  import { getProjectCwd } from './types.js';
10
10
  import { validateIdentifier, validateText } from './validate-input.js';
11
+ import { readPreservedJsonStore } from './record-store.js';
11
12
  // Storage paths
12
13
  const STORAGE_DIR = '.claude-flow';
13
14
  const HIVE_DIR = 'hive-mind';
@@ -199,17 +200,10 @@ function ensureHiveDir() {
199
200
  catch { /* not ours / unsupported */ }
200
201
  }
201
202
  function loadHiveState() {
202
- try {
203
- const path = getHivePath();
204
- if (existsSync(path)) {
205
- const data = readFileSync(path, 'utf-8');
206
- return JSON.parse(data);
207
- }
208
- }
209
- catch {
210
- // Return default state on error
211
- }
212
- return {
203
+ // #4737: a parse error used to return a fresh hive, and the next save
204
+ // overwrote state.json (including its capability token). Only a missing
205
+ // file is empty; corrupt bytes are copied aside and the error is reported.
206
+ return readPreservedJsonStore(getHivePath(), 'hive-mind', () => ({
213
207
  initialized: false,
214
208
  topology: 'mesh',
215
209
  workers: [],
@@ -217,7 +211,7 @@ function loadHiveState() {
217
211
  sharedMemory: {},
218
212
  createdAt: new Date().toISOString(),
219
213
  updatedAt: new Date().toISOString(),
220
- };
214
+ }));
221
215
  }
222
216
  function saveHiveState(state) {
223
217
  ensureHiveDir();
@@ -243,24 +237,50 @@ function saveHiveState(state) {
243
237
  throw err;
244
238
  }
245
239
  }
246
- // Import agent store helpers for spawn functionality
247
- import { existsSync as agentStoreExists, readFileSync as readAgentStore, writeFileSync as writeAgentStore, mkdirSync as mkdirAgentStore } from 'node:fs';
248
- function loadAgentStore() {
249
- const storePath = join(getProjectCwd(), '.claude-flow', 'agents.json');
240
+ function getHiveAgentPath() {
241
+ return join(getProjectCwd(), STORAGE_DIR, 'agents.json');
242
+ }
243
+ function loadAgentStore(storePath = getHiveAgentPath()) {
244
+ let text;
250
245
  try {
251
- if (agentStoreExists(storePath)) {
252
- return JSON.parse(readAgentStore(storePath, 'utf-8'));
253
- }
246
+ text = readFileSync(storePath, 'utf-8');
254
247
  }
255
- catch { /* ignore */ }
256
- return { agents: {} };
257
- }
258
- function saveAgentStore(store) {
259
- const storeDir = join(getProjectCwd(), '.claude-flow');
260
- if (!agentStoreExists(storeDir)) {
261
- mkdirAgentStore(storeDir, { recursive: true });
248
+ catch (error) {
249
+ // Only an absent file is empty: never replace corrupt/unreadable data.
250
+ if (error.code === 'ENOENT')
251
+ return { agents: {} };
252
+ throw error;
262
253
  }
263
- writeAgentStore(join(storeDir, 'agents.json'), JSON.stringify(store, null, 2), 'utf-8');
254
+ const store = JSON.parse(text);
255
+ if (!store || typeof store !== 'object' || Array.isArray(store)
256
+ || !store.agents || typeof store.agents !== 'object'
257
+ || Object.values(store.agents).some(agent => !agent || typeof agent !== 'object' || Array.isArray(agent))) {
258
+ throw new Error(`Invalid agent store at ${storePath}; existing data was preserved`);
259
+ }
260
+ return store;
261
+ }
262
+ function saveAgentStore(store, storePath = getHiveAgentPath()) {
263
+ // A new hive store lives directly in STORAGE_DIR; join only writes stores
264
+ // that already contain its agent, so their parent directories already exist.
265
+ mkdirSync(join(getProjectCwd(), STORAGE_DIR), { recursive: true });
266
+ writeFileSync(storePath, JSON.stringify(store, null, 2), 'utf-8');
267
+ }
268
+ function findAgent(store, agentId) {
269
+ if (Array.isArray(store.agents))
270
+ return store.agents.find(agent => agent.agentId === agentId);
271
+ return Object.prototype.hasOwnProperty.call(store.agents, agentId) ? store.agents[agentId] : undefined;
272
+ }
273
+ const HIVE_ROLES = new Set(['worker', 'specialist', 'scout']);
274
+ function capacityError(state, additionalWorkers) {
275
+ const maxAgents = state.maxAgents ?? 15;
276
+ if (state.workers.length + additionalWorkers <= maxAgents)
277
+ return null;
278
+ return {
279
+ success: false,
280
+ error: `Hive-mind capacity exceeded: ${state.workers.length}/${maxAgents} workers; cannot add ${additionalWorkers}. Leave the hive or initialize with a larger maxAgents.`,
281
+ totalWorkers: state.workers.length,
282
+ maxAgents,
283
+ };
264
284
  }
265
285
  export const hiveMindTools = [
266
286
  {
@@ -303,8 +323,19 @@ export const hiveMindTools = [
303
323
  if (!v.valid)
304
324
  return { success: false, error: v.error };
305
325
  }
306
- const count = Math.min(Math.max(1, input.count || 1), 20); // Cap at 20
326
+ const requestedCount = input.count === undefined ? 1 : input.count;
327
+ if (typeof requestedCount !== 'number' || !Number.isInteger(requestedCount) || requestedCount < 1) {
328
+ return { success: false, error: 'count must be a positive integer' };
329
+ }
330
+ const count = Math.min(requestedCount, 20); // Preserve the per-call cap.
331
+ // Reject the entire batch before creating agents or mutating the roster.
332
+ const full = capacityError(state, count);
333
+ if (full)
334
+ return full;
307
335
  const role = input.role || 'worker';
336
+ if (!HIVE_ROLES.has(role)) {
337
+ return { success: false, error: `role must be one of: ${[...HIVE_ROLES].join(', ')}` };
338
+ }
308
339
  const agentType = input.agentType || 'worker';
309
340
  const prefix = input.prefix || 'hive-worker';
310
341
  const agentStore = loadAgentStore();
@@ -312,7 +343,7 @@ export const hiveMindTools = [
312
343
  for (let i = 0; i < count; i++) {
313
344
  const agentId = `${prefix}-${Date.now()}-${Math.random().toString(36).slice(2, 6)}`;
314
345
  // Create agent record (like agent/spawn)
315
- agentStore.agents[agentId] = {
346
+ const agent = {
316
347
  agentId,
317
348
  agentType,
318
349
  status: 'idle',
@@ -322,6 +353,10 @@ export const hiveMindTools = [
322
353
  createdAt: new Date().toISOString(),
323
354
  domain: 'hive-mind',
324
355
  };
356
+ if (Array.isArray(agentStore.agents))
357
+ agentStore.agents.push(agent);
358
+ else
359
+ agentStore.agents[agentId] = agent;
325
360
  // Join to hive-mind (like hive-mind/join)
326
361
  if (!state.workers.includes(agentId)) {
327
362
  state.workers.push(agentId);
@@ -521,7 +556,7 @@ export const hiveMindTools = [
521
556
  term: state.queen.term,
522
557
  } : { id: 'N/A', status: 'offline', load: 0, tasksQueued: 0 },
523
558
  workers: state.workers.map(w => {
524
- const agent = agentStore.agents[w];
559
+ const agent = findAgent(agentStore, w);
525
560
  return {
526
561
  id: w,
527
562
  type: agent?.agentType || 'worker',
@@ -601,14 +636,43 @@ export const hiveMindTools = [
601
636
  if (tokenError) {
602
637
  return { success: false, agentId, error: tokenError };
603
638
  }
604
- if (!state.workers.includes(agentId)) {
639
+ const alreadyJoined = state.workers.includes(agentId);
640
+ // Retrying a registered member does not consume another slot.
641
+ if (!alreadyJoined) {
642
+ const full = capacityError(state, 1);
643
+ if (full)
644
+ return { ...full, agentId };
645
+ }
646
+ // Both registration paths are legitimate (#1916). Update each existing
647
+ // record in place, preserving metadata and map/array representation.
648
+ const paths = [
649
+ join(getProjectCwd(), STORAGE_DIR, 'agents', 'store.json'),
650
+ getHiveAgentPath(),
651
+ ];
652
+ const records = paths.flatMap(path => {
653
+ const store = loadAgentStore(path);
654
+ const agent = findAgent(store, agentId);
655
+ return agent ? [{ path, store, agent }] : [];
656
+ });
657
+ if (records.length === 0) {
658
+ return { success: false, agentId, error: 'Agent not found. Register it with agent_spawn or hive-mind_spawn first.' };
659
+ }
660
+ const role = input.role || 'worker';
661
+ if (!HIVE_ROLES.has(role)) {
662
+ return { success: false, agentId, error: `role must be one of: ${[...HIVE_ROLES].join(', ')}` };
663
+ }
664
+ for (const { path, store, agent } of records) {
665
+ agent.config = { ...agent.config, role, hiveRole: role };
666
+ saveAgentStore(store, path);
667
+ }
668
+ if (!alreadyJoined) {
605
669
  state.workers.push(agentId);
606
670
  saveHiveState(state);
607
671
  }
608
672
  return {
609
673
  success: true,
610
674
  agentId,
611
- role: input.role || 'worker',
675
+ role,
612
676
  totalWorkers: state.workers.length,
613
677
  joinedAt: new Date().toISOString(),
614
678
  };
@@ -1073,9 +1137,14 @@ export const hiveMindTools = [
1073
1137
  }
1074
1138
  // Clear workers from agent store
1075
1139
  const agentStore = loadAgentStore();
1076
- for (const workerId of state.workers) {
1077
- if (agentStore.agents[workerId]) {
1078
- delete agentStore.agents[workerId];
1140
+ if (Array.isArray(agentStore.agents)) {
1141
+ agentStore.agents = agentStore.agents.filter(agent => !state.workers.includes(agent.agentId));
1142
+ }
1143
+ else {
1144
+ for (const workerId of state.workers) {
1145
+ if (Object.prototype.hasOwnProperty.call(agentStore.agents, workerId)) {
1146
+ delete agentStore.agents[workerId];
1147
+ }
1079
1148
  }
1080
1149
  }
1081
1150
  saveAgentStore(agentStore);
@@ -2288,7 +2288,8 @@ export const hooksTransfer = {
2288
2288
  },
2289
2289
  handler: async (params) => {
2290
2290
  const sourcePath = params.sourcePath;
2291
- const minConfidence = params.minConfidence || 0.7;
2291
+ // #4728: an explicit 0 must not fall through to 0.7 (`0 || 0.7` is 0.7).
2292
+ const minConfidence = params.minConfidence ?? 0.7;
2292
2293
  const filter = params.filter;
2293
2294
  {
2294
2295
  const v = validatePath(sourcePath, 'sourcePath');
@@ -3474,7 +3475,8 @@ export const hooksPatternStore = {
3474
3475
  handler: async (params) => {
3475
3476
  const pattern = params.pattern;
3476
3477
  const type = params.type || 'general';
3477
- const confidence = params.confidence || 0.8;
3478
+ // #4728: an explicit 0 must not fall through to 0.8 (`0 || 0.8` is 0.8).
3479
+ const confidence = params.confidence ?? 0.8;
3478
3480
  const metadata = params.metadata;
3479
3481
  const timestamp = new Date().toISOString();
3480
3482
  {
@@ -3559,7 +3561,8 @@ export const hooksPatternSearch = {
3559
3561
  handler: async (params) => {
3560
3562
  const query = params.query;
3561
3563
  const topK = params.topK || 5;
3562
- const minConfidence = params.minConfidence || 0.3;
3564
+ // #4728: an explicit 0 must not fall through to 0.3 (`0 || 0.3` is 0.3).
3565
+ const minConfidence = params.minConfidence ?? 0.3;
3563
3566
  const namespace = params.namespace || 'pattern';
3564
3567
  const strategy = params.strategy || 'semantic';
3565
3568
  {
@@ -4865,7 +4868,8 @@ export const hooksWorkerDetect = {
4865
4868
  handler: async (params) => {
4866
4869
  const prompt = params.prompt;
4867
4870
  const autoDispatch = params.autoDispatch;
4868
- const minConfidence = params.minConfidence || 0.5;
4871
+ // #4728: an explicit 0 must not fall through to 0.5 (`0 || 0.5` is 0.5).
4872
+ const minConfidence = params.minConfidence ?? 0.5;
4869
4873
  {
4870
4874
  const v = validateText(prompt, 'prompt');
4871
4875
  if (!v.valid)
@@ -4968,7 +4972,10 @@ export const hooksModelRoute = {
4968
4972
  implementation: 'fallback',
4969
4973
  };
4970
4974
  }
4971
- const result = await router.route(task);
4975
+ const result = await router.route(task, undefined, {
4976
+ preferCost: typeof params.preferCost === 'boolean' ? params.preferCost : undefined,
4977
+ preferSpeed: typeof params.preferSpeed === 'boolean' ? params.preferSpeed : undefined,
4978
+ });
4972
4979
  return {
4973
4980
  model: result.model,
4974
4981
  confidence: result.confidence,
@@ -0,0 +1,4 @@
1
+ export declare const MAX_IMPORT_BYTES: number;
2
+ /** Bound allocation and reads even if an import file grows after its size check. */
3
+ export declare function readImportFile(file: string): Buffer;
4
+ //# sourceMappingURL=import-limits.d.ts.map
@@ -0,0 +1,28 @@
1
+ import { closeSync, constants, fstatSync, openSync, readSync } from 'node:fs';
2
+ export const MAX_IMPORT_BYTES = 16 * 1024 * 1024;
3
+ /** Bound allocation and reads even if an import file grows after its size check. */
4
+ export function readImportFile(file) {
5
+ const fd = openSync(file, constants.O_RDONLY | (constants.O_NONBLOCK ?? 0));
6
+ try {
7
+ const stat = fstatSync(fd);
8
+ if (!stat.isFile())
9
+ throw new Error('Import input must be a regular file');
10
+ if (stat.size > MAX_IMPORT_BYTES)
11
+ throw new Error('Import file exceeds the 16 MiB limit');
12
+ const buffer = Buffer.alloc(stat.size + 1);
13
+ let total = 0;
14
+ while (total < buffer.length) {
15
+ const count = readSync(fd, buffer, total, buffer.length - total, null);
16
+ if (count === 0)
17
+ break;
18
+ total += count;
19
+ }
20
+ if (total > stat.size)
21
+ throw new Error('Import input changed size while reading');
22
+ return buffer.subarray(0, total);
23
+ }
24
+ finally {
25
+ closeSync(fd);
26
+ }
27
+ }
28
+ //# sourceMappingURL=import-limits.js.map
@@ -12,11 +12,14 @@
12
12
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'fs';
13
13
  import { homedir } from 'os';
14
14
  import { basename, dirname, join, resolve } from 'path';
15
+ import { containedReadPath, containedWritePath, dbPathError, isLocalCliCall } from './path-containment.js';
15
16
  import { execFileSync } from 'node:child_process';
16
17
  import { createHash } from 'crypto';
17
18
  import { getProjectCwd } from './types.js';
18
19
  import { validateIdentifier } from './validate-input.js';
19
20
  import { DEFAULT_SEARCH_THRESHOLD, nearMisses } from '../memory/search-defaults.js';
21
+ import { compileExclusionPatterns, MAX_EXCLUDE_PATTERNS, MAX_EXCLUDE_PATTERN_LENGTH } from './glob-exclusions.js';
22
+ import { readImportFile } from './import-limits.js';
20
23
  // #1604: Align with memory-initializer.ts — single source of truth is .swarm/memory.db
21
24
  const MEMORY_DIR = '.swarm';
22
25
  const LEGACY_MEMORY_FILE = 'store.json';
@@ -27,10 +30,21 @@ const LEGACY_MEMORY_DIR = '.claude-flow/memory';
27
30
  * deliberately not an implicit `CLAUDE_FLOW_DB_PATH` override because the
28
31
  * native/encrypted CLI store and the AgentDB sibling are separate backends.
29
32
  */
30
- function resolveDbPathOption(inputDbPath) {
31
- return typeof inputDbPath === 'string' && inputDbPath.trim().length > 0
32
- ? resolve(inputDbPath)
33
- : undefined;
33
+ /**
34
+ * Resolve an explicit `dbPath`. MCP callers may only name a SQLite database
35
+ * file, so the memory tools cannot be aimed at and overwrite an unrelated file;
36
+ * the local CLI (`--path`) keeps operator-chosen paths as-is.
37
+ */
38
+ function resolveDbPathOption(inputDbPath, context) {
39
+ if (typeof inputDbPath !== 'string' || inputDbPath.trim().length === 0)
40
+ return undefined;
41
+ const dbPath = resolve(inputDbPath);
42
+ if (!isLocalCliCall(context)) {
43
+ const error = dbPathError(dbPath);
44
+ if (error)
45
+ throw new Error(error);
46
+ }
47
+ return dbPath;
34
48
  }
35
49
  const MIGRATION_MARKER = '.migrated-to-sqlite';
36
50
  function getMemoryDir() {
@@ -112,37 +126,6 @@ function sanitizeMemoryKey(key) {
112
126
  const safe = key.replace(DANGEROUS_KEY_CHARS, '_');
113
127
  return safe.length > MAX_KEY_LENGTH ? safe.slice(0, MAX_KEY_LENGTH) : safe;
114
128
  }
115
- // #1937 — minimal glob → RegExp helper for memory_import_claude exclusion
116
- // patterns. Anchored. Supports the three operators the issue's voice-fidelity
117
- // workflow needs:
118
- // `**` — any chars including path separators
119
- // `*` — any chars except path separators
120
- // `?` — exactly one char except a path separator
121
- // Everything else is regex-escaped. Used to match absolute file paths.
122
- function globToRegex(pattern) {
123
- // Tokenize so we can replace `**` before `*` without overlap.
124
- let out = '';
125
- for (let i = 0; i < pattern.length; i++) {
126
- const c = pattern[i];
127
- if (c === '*' && pattern[i + 1] === '*') {
128
- out += '.*';
129
- i++;
130
- }
131
- else if (c === '*') {
132
- out += '[^/\\\\]*';
133
- }
134
- else if (c === '?') {
135
- out += '[^/\\\\]';
136
- }
137
- else if (/[.+^$|(){}\[\]\\]/.test(c)) {
138
- out += '\\' + c;
139
- }
140
- else {
141
- out += c;
142
- }
143
- }
144
- return new RegExp('^' + out + '$');
145
- }
146
129
  // #1883 — resolve the Claude-Code project memory directory for the *current*
147
130
  // project. Claude Code hashes the project path differently per host OS, and
148
131
  // our previous logic only POSIX-slash-replaced cwd, which breaks for:
@@ -462,12 +445,12 @@ export const memoryTools = [
462
445
  },
463
446
  required: ['key', 'value'],
464
447
  },
465
- handler: async (input) => {
448
+ handler: async (input, context) => {
466
449
  const missingKey = missingRequiredString(input, 'key', 'memory_store');
467
450
  if (missingKey) {
468
451
  return { success: false, key: input.key, stored: false, hasEmbedding: false, ...missingKey };
469
452
  }
470
- const dbPath = resolveDbPathOption(input.dbPath);
453
+ const dbPath = resolveDbPathOption(input.dbPath, context);
471
454
  if (!dbPath)
472
455
  await ensureInitialized();
473
456
  const { storeEntry } = await getMemoryFunctions();
@@ -549,12 +532,12 @@ export const memoryTools = [
549
532
  },
550
533
  required: ['key'],
551
534
  },
552
- handler: async (input) => {
535
+ handler: async (input, context) => {
553
536
  const missingKey = missingRequiredString(input, 'key', 'memory_retrieve');
554
537
  if (missingKey) {
555
538
  return { key: input.key, namespace: input.namespace, value: null, found: false, ...missingKey };
556
539
  }
557
- const dbPath = resolveDbPathOption(input.dbPath);
540
+ const dbPath = resolveDbPathOption(input.dbPath, context);
558
541
  if (!dbPath)
559
542
  await ensureInitialized();
560
543
  const { getEntry } = await getMemoryFunctions();
@@ -624,12 +607,12 @@ export const memoryTools = [
624
607
  },
625
608
  required: ['query'],
626
609
  },
627
- handler: async (input) => {
610
+ handler: async (input, context) => {
628
611
  const missingQuery = missingRequiredString(input, 'query', 'memory_search');
629
612
  if (missingQuery) {
630
613
  return { query: input.query, results: [], total: 0, ...missingQuery };
631
614
  }
632
- const dbPath = resolveDbPathOption(input.dbPath);
615
+ const dbPath = resolveDbPathOption(input.dbPath, context);
633
616
  if (!dbPath)
634
617
  await ensureInitialized();
635
618
  const { searchEntries } = await getMemoryFunctions();
@@ -810,12 +793,12 @@ export const memoryTools = [
810
793
  },
811
794
  required: ['key'],
812
795
  },
813
- handler: async (input) => {
796
+ handler: async (input, context) => {
814
797
  const missingKey = missingRequiredString(input, 'key', 'memory_delete');
815
798
  if (missingKey) {
816
799
  return { success: false, key: input.key, namespace: input.namespace, deleted: false, ...missingKey };
817
800
  }
818
- const dbPath = resolveDbPathOption(input.dbPath);
801
+ const dbPath = resolveDbPathOption(input.dbPath, context);
819
802
  if (!dbPath)
820
803
  await ensureInitialized();
821
804
  const { deleteEntry } = await getMemoryFunctions();
@@ -862,8 +845,8 @@ export const memoryTools = [
862
845
  dbPath: { type: 'string', description: 'Explicit SQLite store to read/write; omit to use the MCP default (the native/AgentDB sibling).' },
863
846
  },
864
847
  },
865
- handler: async (input) => {
866
- const dbPath = resolveDbPathOption(input.dbPath);
848
+ handler: async (input, context) => {
849
+ const dbPath = resolveDbPathOption(input.dbPath, context);
867
850
  if (!dbPath)
868
851
  await ensureInitialized();
869
852
  const { listEntries } = await getMemoryFunctions();
@@ -939,11 +922,11 @@ export const memoryTools = [
939
922
  dbPath: { type: 'string', description: 'Explicit SQLite store to read/write; omit to use the MCP default (the native/AgentDB sibling).' },
940
923
  },
941
924
  },
942
- handler: async (input) => {
925
+ handler: async (input, context) => {
943
926
  if (input.dbPath !== undefined && (typeof input.dbPath !== 'string' || !input.dbPath.trim())) {
944
927
  return memoryStatsUnavailable('dbPath must be a non-empty string');
945
928
  }
946
- const dbPath = resolveDbPathOption(input.dbPath);
929
+ const dbPath = resolveDbPathOption(input.dbPath, context);
947
930
  // An explicit read must not initialize or migrate the unrelated default store.
948
931
  if (!dbPath)
949
932
  await ensureInitialized();
@@ -1116,8 +1099,9 @@ export const memoryTools = [
1116
1099
  projectPath: { type: 'string', description: '#1883 — explicit project path to hash, used when cwd does not match Claude Code\'s view (e.g. WSL bridge to Windows host). Pass the canonical project root as Claude Code sees it.' },
1117
1100
  excludeFilePatterns: {
1118
1101
  type: 'array',
1119
- items: { type: 'string' },
1120
- description: '#1937 — glob patterns matched against the absolute file path. Files matching ANY pattern are skipped. Supports `*` (any chars within a path segment), `**` (any chars including separators), and `?` (single char). Examples: `**/voice-*.md`, `**/persona-*.md`. Combine with excludeFiles for explicit paths.',
1102
+ maxItems: MAX_EXCLUDE_PATTERNS,
1103
+ items: { type: 'string', maxLength: MAX_EXCLUDE_PATTERN_LENGTH },
1104
+ description: '#1937 — glob patterns matched against the absolute file path. Files matching ANY pattern are skipped. Supports `*` (any chars within a path segment), `**` (any chars including separators), and `?` (single char). At most 64 patterns, 1024 characters and 32 wildcard operators per pattern. Examples: `**/voice-*.md`, `**/persona-*.md`. Combine with excludeFiles for explicit paths.',
1121
1105
  },
1122
1106
  excludeFiles: {
1123
1107
  type: 'array',
@@ -1127,6 +1111,13 @@ export const memoryTools = [
1127
1111
  },
1128
1112
  },
1129
1113
  handler: async (input) => {
1114
+ let excludeMatchers;
1115
+ try {
1116
+ excludeMatchers = compileExclusionPatterns(input.excludeFilePatterns);
1117
+ }
1118
+ catch (error) {
1119
+ return { success: false, imported: 0, error: error.message };
1120
+ }
1130
1121
  await ensureInitialized();
1131
1122
  const { storeEntry } = await getMemoryFunctions();
1132
1123
  const ns = input.namespace || 'claude-memories';
@@ -1139,13 +1130,11 @@ export const memoryTools = [
1139
1130
  const projectPathOverride = input.projectPath;
1140
1131
  const claudeProjectsDir = join(homedir(), '.claude', 'projects');
1141
1132
  // #1937 — voice-fidelity / persona-restricted exclusion.
1142
- const excludeFilePatterns = Array.isArray(input.excludeFilePatterns) ? input.excludeFilePatterns : [];
1143
1133
  const excludeFilesList = Array.isArray(input.excludeFiles) ? new Set(input.excludeFiles) : new Set();
1144
- const excludeRegexes = excludeFilePatterns.map(globToRegex);
1145
1134
  const isExcluded = (absPath) => {
1146
1135
  if (excludeFilesList.has(absPath))
1147
1136
  return true;
1148
- return excludeRegexes.some(re => re.test(absPath));
1137
+ return excludeMatchers.some(matches => matches(absPath));
1149
1138
  };
1150
1139
  // Find memory files
1151
1140
  const memoryFiles = [];
@@ -1648,18 +1637,19 @@ export const memoryTools = [
1648
1637
  },
1649
1638
  required: ['outputPath'],
1650
1639
  },
1651
- handler: async (input) => {
1652
- const requestedDbPath = typeof input.dbPath === 'string' && input.dbPath.trim()
1653
- ? resolve(input.dbPath)
1654
- : undefined;
1640
+ handler: async (input, context) => {
1641
+ const requestedOutput = String(input.outputPath ?? '');
1642
+ if (!requestedOutput)
1643
+ return { error: 'outputPath is required' };
1644
+ const outputPath = isLocalCliCall(context) ? resolve(requestedOutput) : containedWritePath(requestedOutput, ['.json']);
1645
+ if (!outputPath)
1646
+ return { error: 'outputPath must be a .json file inside the project directory (not a symlink, not in .git)' };
1647
+ const requestedDbPath = resolveDbPathOption(input.dbPath, context);
1655
1648
  // An explicit file selection is a single-store read. Do not initialize or
1656
1649
  // migrate the unrelated default store just to export a snapshot.
1657
1650
  if (!requestedDbPath)
1658
1651
  await ensureInitialized();
1659
1652
  const { listEntries } = await getMemoryFunctions();
1660
- const outputPath = String(input.outputPath ?? '');
1661
- if (!outputPath)
1662
- return { error: 'outputPath is required' };
1663
1653
  const namespace = input.namespace ? String(input.namespace) : undefined;
1664
1654
  if (namespace) {
1665
1655
  const v = validateIdentifier(namespace, 'namespace');
@@ -1763,33 +1753,39 @@ export const memoryTools = [
1763
1753
  inputSchema: {
1764
1754
  type: 'object',
1765
1755
  properties: {
1766
- inputPath: { type: 'string', description: 'Path to the JSON export file' },
1756
+ inputPath: { type: 'string', description: 'Path to the JSON export file (maximum 16 MiB)' },
1767
1757
  merge: { type: 'boolean', description: 'Merge into existing entries (upsert) vs. fail on conflict (default true)' },
1768
1758
  namespace: { type: 'string', description: 'Override the namespace for all imported entries' },
1769
1759
  dbPath: { type: 'string', description: 'Database file to import into (defaults to the MCP memory store)' },
1770
1760
  },
1771
1761
  required: ['inputPath'],
1772
1762
  },
1773
- handler: async (input) => {
1774
- const dbPath = typeof input.dbPath === 'string' && input.dbPath.trim()
1775
- ? resolve(input.dbPath)
1776
- : undefined;
1777
- await ensureInitialized(dbPath);
1778
- const { storeEntry } = await getMemoryFunctions();
1763
+ handler: async (input, context) => {
1764
+ const dbPath = resolveDbPathOption(input.dbPath, context);
1779
1765
  const t0 = Date.now();
1780
1766
  // Values are re-embedded on import; count the vectors actually written
1781
1767
  // rather than reporting a constant 0 next to entries that show a vector.
1782
1768
  let vectors = 0;
1783
- const inputPath = String(input.inputPath ?? '');
1784
- if (!inputPath || !existsSync(inputPath))
1785
- return { error: `File not found: ${inputPath || '(empty)'}` };
1769
+ const requestedInput = String(input.inputPath ?? '');
1770
+ const inputPath = !requestedInput ? null
1771
+ : isLocalCliCall(context) ? (existsSync(requestedInput) ? resolve(requestedInput) : null)
1772
+ : containedReadPath(requestedInput);
1773
+ if (!inputPath) {
1774
+ return { error: isLocalCliCall(context) || !requestedInput
1775
+ ? `File not found: ${requestedInput || '(empty)'}`
1776
+ : 'inputPath must be an existing regular file inside the project directory (not a symlink)' };
1777
+ }
1786
1778
  let doc;
1787
1779
  try {
1788
- doc = JSON.parse(readFileSync(inputPath, 'utf-8'));
1780
+ doc = JSON.parse(readImportFile(inputPath).toString('utf-8'));
1789
1781
  }
1790
- catch (e) {
1791
- return { error: `Invalid export JSON: ${e.message}` };
1782
+ catch (error) {
1783
+ return { error: error instanceof SyntaxError
1784
+ ? 'inputPath is not a valid memory export (JSON parse failed)'
1785
+ : error instanceof Error ? error.message : 'Could not read memory import' };
1792
1786
  }
1787
+ await ensureInitialized(dbPath);
1788
+ const { storeEntry } = await getMemoryFunctions();
1793
1789
  const entries = Array.isArray(doc.entries) ? doc.entries : [];
1794
1790
  const nsOverride = input.namespace ? String(input.namespace) : undefined;
1795
1791
  if (nsOverride) {
@@ -12,6 +12,7 @@
12
12
  * Note: For production neural features, use @claude-flow/neural module
13
13
  */
14
14
  import { getProjectCwd } from './types.js';
15
+ import { nullPrototypeRecords } from './record-store.js';
15
16
  import { validateIdentifier, validateText } from './validate-input.js';
16
17
  import { existsSync, readFileSync, writeFileSync, mkdirSync } from 'node:fs';
17
18
  import { join } from 'node:path';
@@ -223,13 +224,18 @@ function loadNeuralStore() {
223
224
  try {
224
225
  const path = getNeuralPath();
225
226
  if (existsSync(path)) {
226
- return JSON.parse(readFileSync(path, 'utf-8'));
227
+ const parsed = JSON.parse(readFileSync(path, 'utf-8'));
228
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
229
+ parsed.models = nullPrototypeRecords(parsed.models);
230
+ parsed.patterns = nullPrototypeRecords(parsed.patterns);
231
+ return parsed;
232
+ }
227
233
  }
228
234
  }
229
235
  catch {
230
236
  // Return empty store
231
237
  }
232
- return { models: {}, patterns: {}, version: '3.0.0' };
238
+ return { models: nullPrototypeRecords(undefined), patterns: nullPrototypeRecords(undefined), version: '3.0.0' };
233
239
  }
234
240
  /**
235
241
  * ADR-176 flywheel: expose the stored patterns (id/name/content) so the
@@ -0,0 +1,34 @@
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
+ /**
10
+ * Resolve a caller-named output file inside the project. The real parent
11
+ * directory must be inside the real project root and outside `.git`, and an
12
+ * existing target must be a regular, non-executable file — not a symlink.
13
+ * `extensions`, when given, lists the allowed lower-case file extensions.
14
+ */
15
+ export declare function containedWritePath(p: string, extensions?: readonly string[]): string | null;
16
+ /** Resolve a caller-named input file inside the project: a regular file, not a symlink. */
17
+ export declare function containedReadPath(p: string): string | null;
18
+ /**
19
+ * Check a caller-named memory database path. It may live outside the project
20
+ * (the CLI's `--path` flag passes one), so this does not contain it; instead
21
+ * it refuses anything that is not plainly a SQLite database (plaintext, or
22
+ * encrypted at rest per ADR-096), so the memory tools cannot be pointed at and
23
+ * overwrite an unrelated file.
24
+ */
25
+ export declare function dbPathError(p: string): string | null;
26
+ /**
27
+ * Marks a tool call made by the local CLI on the operator's behalf (for
28
+ * example `ruflo memory export --output ~/backup.json`). MCP requests arrive
29
+ * as JSON and cannot carry a symbol key, so this cannot be forged remotely.
30
+ */
31
+ export declare const LOCAL_CLI_CALL: unique symbol;
32
+ export declare function localCliContext(): Record<string, unknown>;
33
+ export declare function isLocalCliCall(context: unknown): boolean;
34
+ //# sourceMappingURL=path-containment.d.ts.map