@claude-flow/cli 3.56.9 → 3.57.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 (101) hide show
  1. package/.claude/helpers/.helpers-version +1 -1
  2. package/.claude/helpers/helpers.manifest.json +3 -3
  3. package/.claude/helpers/intelligence.cjs +51 -9
  4. package/.claude/helpers/router.cjs +0 -0
  5. package/.claude/skills/verification-quality/SKILL.md +14 -11
  6. package/README.md +1 -1
  7. package/catalog-manifest.json +2 -2
  8. package/dist/src/autopilot-state.d.ts +2 -0
  9. package/dist/src/autopilot-state.js +36 -8
  10. package/dist/src/command-resolution.d.ts +15 -0
  11. package/dist/src/command-resolution.js +25 -0
  12. package/dist/src/commands/agent.js +17 -17
  13. package/dist/src/commands/claims.js +6 -8
  14. package/dist/src/commands/daemon.js +94 -33
  15. package/dist/src/commands/doctor.js +95 -18
  16. package/dist/src/commands/memory.js +14 -2
  17. package/dist/src/commands/policy.js +6 -1
  18. package/dist/src/commands/security-code-patterns.d.ts +2 -2
  19. package/dist/src/commands/security-code-patterns.js +61 -3
  20. package/dist/src/commands/security.d.ts +24 -0
  21. package/dist/src/commands/security.js +81 -35
  22. package/dist/src/commands/tui.d.ts +9 -0
  23. package/dist/src/commands/tui.js +29 -3
  24. package/dist/src/config/proven-config-refresh.d.ts +9 -0
  25. package/dist/src/config/proven-config-refresh.js +24 -3
  26. package/dist/src/funnel/local-signals.js +2 -1
  27. package/dist/src/index.js +11 -47
  28. package/dist/src/init/settings-generator.js +4 -58
  29. package/dist/src/init/types.js +1 -1
  30. package/dist/src/mcp-tools/agent-execute-core.d.ts +2 -0
  31. package/dist/src/mcp-tools/agent-execute-core.js +15 -0
  32. package/dist/src/mcp-tools/agent-health-metrics.d.ts +22 -0
  33. package/dist/src/mcp-tools/agent-health-metrics.js +33 -0
  34. package/dist/src/mcp-tools/agent-tools.js +45 -22
  35. package/dist/src/mcp-tools/agentbbs-federation.d.ts +1 -1
  36. package/dist/src/mcp-tools/agentbbs-federation.js +7 -2
  37. package/dist/src/mcp-tools/agentdb-tools.js +25 -2
  38. package/dist/src/mcp-tools/aidefence-known-misses.d.ts +22 -0
  39. package/dist/src/mcp-tools/aidefence-known-misses.js +57 -0
  40. package/dist/src/mcp-tools/analyze-tools.js +10 -11
  41. package/dist/src/mcp-tools/autopilot-tools.js +2 -2
  42. package/dist/src/mcp-tools/browser-intent-tools.js +6 -2
  43. package/dist/src/mcp-tools/embeddings-tools.js +29 -7
  44. package/dist/src/mcp-tools/hooks-tools.js +4 -0
  45. package/dist/src/mcp-tools/memory-tools.d.ts +1 -1
  46. package/dist/src/mcp-tools/memory-tools.js +100 -25
  47. package/dist/src/mcp-tools/metaharness-tools.js +1 -1
  48. package/dist/src/mcp-tools/neural-tools.js +48 -54
  49. package/dist/src/mcp-tools/policy-tools.js +5 -3
  50. package/dist/src/mcp-tools/ruvllm-tools.js +6 -0
  51. package/dist/src/mcp-tools/security-tools.js +55 -17
  52. package/dist/src/mcp-tools/workflow-tools.js +66 -17
  53. package/dist/src/memory/intelligence.d.ts +5 -1
  54. package/dist/src/memory/intelligence.js +158 -35
  55. package/dist/src/memory/memory-bridge.js +10 -3
  56. package/dist/src/memory/memory-initializer.js +2 -1
  57. package/dist/src/memory/search-defaults.d.ts +54 -0
  58. package/dist/src/memory/search-defaults.js +37 -0
  59. package/dist/src/memory/sona-optimizer.d.ts +28 -0
  60. package/dist/src/memory/sona-optimizer.js +59 -2
  61. package/dist/src/memory/stats-file-lock.d.ts +7 -0
  62. package/dist/src/memory/stats-file-lock.js +53 -0
  63. package/dist/src/mods/command-registry/schema.d.ts +24 -24
  64. package/dist/src/ruvector/agent-wasm.d.ts +10 -0
  65. package/dist/src/ruvector/agent-wasm.js +27 -1
  66. package/dist/src/ruvector/diff-classifier.d.ts +2 -4
  67. package/dist/src/ruvector/diff-classifier.js +202 -69
  68. package/dist/src/ruvector/ruvllm-wasm.d.ts +4 -0
  69. package/dist/src/ruvector/ruvllm-wasm.js +12 -1
  70. package/dist/src/services/distill-oracle.d.ts +1 -1
  71. package/dist/src/services/distill-oracle.js +2 -2
  72. package/dist/src/services/policy-anchor-log.d.ts +13 -0
  73. package/dist/src/services/policy-anchor-log.js +242 -0
  74. package/dist/src/services/policy-archive-scan.d.ts +7 -0
  75. package/dist/src/services/policy-archive-scan.js +50 -0
  76. package/dist/src/services/policy-ledger-anchor.d.ts +14 -8
  77. package/dist/src/services/policy-ledger-anchor.js +356 -40
  78. package/dist/src/services/policy-ledger-audit.d.ts +22 -0
  79. package/dist/src/services/policy-ledger-audit.js +260 -0
  80. package/dist/src/services/policy-ledger-record.d.ts +3 -0
  81. package/dist/src/services/policy-ledger-record.js +22 -0
  82. package/dist/src/services/policy-runtime.d.ts +2 -1
  83. package/dist/src/services/policy-runtime.js +267 -40
  84. package/dist/src/services/worker-daemon.d.ts +11 -0
  85. package/dist/src/services/worker-daemon.js +37 -0
  86. package/dist/src/transfer/store/discovery.js +16 -17
  87. package/dist/src/transfer/store/types.d.ts +4 -0
  88. package/node_modules/@claude-flow/codex/dist/cli.js +0 -0
  89. package/node_modules/@claude-flow/plugin-agent-federation/dist/bin.js +0 -0
  90. package/node_modules/@claude-flow/security/dist/policy/engine.d.ts +17 -1
  91. package/node_modules/@claude-flow/security/dist/policy/engine.d.ts.map +1 -1
  92. package/node_modules/@claude-flow/security/dist/policy/engine.js +99 -24
  93. package/node_modules/@claude-flow/security/dist/policy/engine.js.map +1 -1
  94. package/node_modules/@claude-flow/security/dist/policy/types.d.ts +14 -1
  95. package/node_modules/@claude-flow/security/dist/policy/types.d.ts.map +1 -1
  96. package/node_modules/@claude-flow/security/dist/policy/types.js +3 -1
  97. package/node_modules/@claude-flow/security/dist/policy/types.js.map +1 -1
  98. package/package.json +5 -5
  99. package/plugins/ruflo-console/dist/tui.mjs +162 -161
  100. package/plugins/ruflo-metaharness/hooks/screen.ts +7 -1
  101. package/plugins/ruflo-metaharness/scripts/_darwin.mjs +4 -4
@@ -80,6 +80,21 @@ async function bridgeUnavailableResult() {
80
80
  hint: 'Check Node version + try `ruflo memory init` to initialize manually.',
81
81
  };
82
82
  }
83
+ // #4135 / #4161: graph reads (agentdb_graph-query, agentdb_graph-pathfinder) open the
84
+ // graph_edges database; under encryption at rest that file is an RFE1 blob they cannot
85
+ // open. A recorded edge is then unreadable even though the write reports success, so the
86
+ // write says so instead of letting a caller assume it can read the edge back.
87
+ async function unreadableEdgeWarning() {
88
+ try {
89
+ const { isBridgeDbEncryptedAtRest } = await getGraphEdgeWriter();
90
+ if (!isBridgeDbEncryptedAtRest())
91
+ return undefined;
92
+ return 'Edge recorded, but graph reads (agentdb_graph-query, agentdb_graph-pathfinder) cannot open the graph_edges database because it is encrypted at rest (RFE1), so this edge cannot be read back yet. Your data is intact (#2889, #4135).';
93
+ }
94
+ catch {
95
+ return undefined;
96
+ }
97
+ }
83
98
  let memInitMod = null;
84
99
  async function getMemInit() {
85
100
  if (!memInitMod)
@@ -554,7 +569,9 @@ export const agentdbCausalEdge = {
554
569
  // Also record in AgentDB bridge for compatibility
555
570
  const bridge = await getBridge();
556
571
  await bridge.bridgeRecordCausalEdge({ sourceId, targetId, relation, weight: typeof params.weight === 'number' ? validateScore(params.weight, 0.5) : undefined }).catch(() => { });
557
- return { ...graphResult, _graphNodeBackend: true, ...(legacyWarning && { warning: legacyWarning }) };
572
+ const unreadable = await unreadableEdgeWarning();
573
+ const warning = [legacyWarning, unreadable].filter(Boolean).join(' ');
574
+ return { ...graphResult, _graphNodeBackend: true, ...(unreadable && { readable: false }), ...(warning && { warning }) };
558
575
  }
559
576
  }
560
577
  }
@@ -567,7 +584,9 @@ export const agentdbCausalEdge = {
567
584
  weight: typeof params.weight === 'number' ? validateScore(params.weight, 0.5) : undefined,
568
585
  });
569
586
  const baseResult = result ?? { success: false, error: 'AgentDB bridge not available. Use memory_store/memory_search instead.' };
570
- return legacyWarning ? { ...baseResult, warning: legacyWarning } : baseResult;
587
+ const unreadable = baseResult.success === false ? undefined : await unreadableEdgeWarning();
588
+ const warning = [legacyWarning, unreadable].filter(Boolean).join(' ');
589
+ return warning ? { ...baseResult, ...(unreadable && { readable: false }), warning } : baseResult;
571
590
  }
572
591
  catch (error) {
573
592
  return { success: false, error: sanitizeError(error) };
@@ -1157,6 +1176,10 @@ export const agentdbGraphQuery = {
1157
1176
  catch (error) {
1158
1177
  return { success: false, error: `Retained SQL graph query failed: ${sanitizeError(error)}`, mode, nodeId };
1159
1178
  }
1179
+ // #4135: name the real reason when the retained store is encrypted at rest.
1180
+ const encryptedAtRest = await getGraphEdgeWriter().then((w) => w.isBridgeDbEncryptedAtRest()).catch(() => false);
1181
+ if (encryptedAtRest)
1182
+ return { success: false, ...(await bridgeUnavailableResult()), mode, nodeId };
1160
1183
  return { success: false, error: 'Retained SQL graph_edges backend is unavailable for k-hop query', mode, nodeId };
1161
1184
  }
1162
1185
  // ── semantic mode ────────────────────────────────────────────────────────
@@ -0,0 +1,22 @@
1
+ /**
2
+ * Known-miss registry for aidefence_learn (#4147).
3
+ *
4
+ * The detector's learned patterns are written by `learnFromDetection`, but
5
+ * they are only created from threats the detector already found, and
6
+ * `detect()` never reads them back. A threat the detector MISSED (a false
7
+ * negative, the case feedback matters most for) therefore had nowhere to go.
8
+ *
9
+ * This registry stores a SHA-256 of the whitespace/case-normalised input so a
10
+ * reported miss is flagged next time the identical text is scanned. It is an
11
+ * exact-match list, not generalisation: the raw text is never stored.
12
+ */
13
+ export interface KnownMiss {
14
+ hash: string;
15
+ threatType: string;
16
+ reportedAt: string;
17
+ }
18
+ export declare function hashInput(input: string): string;
19
+ /** Returns true when the miss was newly recorded, false when it was already known. */
20
+ export declare function recordKnownMiss(input: string, threatType: string, cwd?: string): boolean;
21
+ export declare function findKnownMiss(input: string, cwd?: string): KnownMiss | undefined;
22
+ //# sourceMappingURL=aidefence-known-misses.d.ts.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Known-miss registry for aidefence_learn (#4147).
3
+ *
4
+ * The detector's learned patterns are written by `learnFromDetection`, but
5
+ * they are only created from threats the detector already found, and
6
+ * `detect()` never reads them back. A threat the detector MISSED (a false
7
+ * negative, the case feedback matters most for) therefore had nowhere to go.
8
+ *
9
+ * This registry stores a SHA-256 of the whitespace/case-normalised input so a
10
+ * reported miss is flagged next time the identical text is scanned. It is an
11
+ * exact-match list, not generalisation: the raw text is never stored.
12
+ */
13
+ import { createHash } from 'node:crypto';
14
+ import { existsSync, mkdirSync, readFileSync, renameSync, writeFileSync } from 'node:fs';
15
+ import { join } from 'node:path';
16
+ const MAX_ENTRIES = 500;
17
+ function storePath(cwd) {
18
+ return join(cwd, '.claude-flow', 'aidefence-known-misses.json');
19
+ }
20
+ export function hashInput(input) {
21
+ const normalised = input.normalize('NFKC').toLowerCase().replace(/\s+/g, ' ').trim();
22
+ return createHash('sha256').update(normalised).digest('hex');
23
+ }
24
+ function load(cwd) {
25
+ try {
26
+ const p = storePath(cwd);
27
+ if (!existsSync(p))
28
+ return [];
29
+ const parsed = JSON.parse(readFileSync(p, 'utf8'));
30
+ return Array.isArray(parsed) ? parsed.filter((e) => e && typeof e.hash === 'string') : [];
31
+ }
32
+ catch {
33
+ return [];
34
+ }
35
+ }
36
+ /** Returns true when the miss was newly recorded, false when it was already known. */
37
+ export function recordKnownMiss(input, threatType, cwd = process.cwd()) {
38
+ const hash = hashInput(input);
39
+ const entries = load(cwd);
40
+ if (entries.some((e) => e.hash === hash))
41
+ return false;
42
+ entries.push({ hash, threatType, reportedAt: new Date().toISOString() });
43
+ const dir = join(cwd, '.claude-flow');
44
+ mkdirSync(dir, { recursive: true });
45
+ const tmp = `${storePath(cwd)}.${process.pid}.tmp`;
46
+ writeFileSync(tmp, JSON.stringify(entries.slice(-MAX_ENTRIES), null, 2), { mode: 0o600 });
47
+ renameSync(tmp, storePath(cwd));
48
+ return true;
49
+ }
50
+ export function findKnownMiss(input, cwd = process.cwd()) {
51
+ const entries = load(cwd);
52
+ if (entries.length === 0)
53
+ return undefined;
54
+ const hash = hashInput(input);
55
+ return entries.find((e) => e.hash === hash);
56
+ }
57
+ //# sourceMappingURL=aidefence-known-misses.js.map
@@ -3,14 +3,14 @@
3
3
  * Provides diff analysis and classification via MCP protocol
4
4
  */
5
5
  import { validateGitRef, validatePath } from './validate-input.js';
6
- import { analyzeDiff, assessFileRisk, assessOverallRisk, classifyDiff, suggestReviewers, getGitDiffNumstat, } from '../ruvector/diff-classifier.js';
6
+ import { analyzeDiff, assessFileRisk, assessOverallRisk, suggestReviewers, getGitDiffNumstat, } from '../ruvector/diff-classifier.js';
7
7
  /**
8
8
  * Diff Analysis Tool
9
9
  * Analyzes git diffs for change risk assessment and classification
10
10
  */
11
11
  export const analyzeDiffTool = {
12
12
  name: 'analyze_diff',
13
- description: 'Analyze git diff for change risk assessment and classification Use when native `git diff` / `grep` / static analysis is wrong because you want LLM-graded change classification, reviewer recommendations, or risk scoring. For literal-text inspection, native tools are fine.',
13
+ description: 'Heuristically analyze git diff paths, changed lines, and one-commit subjects for risk and classification. Use when preparing a review that needs a quick evidence-based summary; inspect the diff for final judgment.',
14
14
  category: 'analyze',
15
15
  tags: ['diff', 'risk', 'classification', 'git'],
16
16
  inputSchema: {
@@ -85,7 +85,7 @@ export const analyzeDiffTool = {
85
85
  */
86
86
  export const diffRiskTool = {
87
87
  name: 'analyze_diff-risk',
88
- description: 'Quick risk assessment for git diff Use when native `git diff` / `grep` / static analysis is wrong because you want LLM-graded change classification, reviewer recommendations, or risk scoring. For literal-text inspection, native tools are fine.',
88
+ description: 'Heuristically assess git diff risk from changed file paths, sizes, and status. Use when triaging which files merit closer human review; this is not a security guarantee.',
89
89
  category: 'analyze',
90
90
  tags: ['diff', 'risk', 'git'],
91
91
  inputSchema: {
@@ -130,7 +130,7 @@ export const diffRiskTool = {
130
130
  */
131
131
  export const diffClassifyTool = {
132
132
  name: 'analyze_diff-classify',
133
- description: 'Classify git diff change type Use when native `git diff` / `grep` / static analysis is wrong because you want LLM-graded change classification, reviewer recommendations, or risk scoring. For literal-text inspection, native tools are fine.',
133
+ description: 'Heuristically classify a git diff from changed lines, file paths, and a single-commit subject when available. Use when you need a coarse change category; inspect the diff to confirm.',
134
134
  category: 'analyze',
135
135
  tags: ['diff', 'classification', 'git'],
136
136
  inputSchema: {
@@ -151,12 +151,11 @@ export const diffClassifyTool = {
151
151
  }
152
152
  const ref = params.ref || 'HEAD';
153
153
  try {
154
- const files = getGitDiffNumstat(ref);
155
- const classification = classifyDiff(files);
154
+ const result = await analyzeDiff({ ref });
156
155
  return {
157
156
  ref,
158
- classification,
159
- files: files.length,
157
+ classification: result.classification,
158
+ files: result.files.length,
160
159
  };
161
160
  }
162
161
  catch (error) {
@@ -174,7 +173,7 @@ export const diffClassifyTool = {
174
173
  */
175
174
  export const diffReviewersTool = {
176
175
  name: 'analyze_diff-reviewers',
177
- description: 'Suggest reviewers for git diff changes Use when native `git diff` / `grep` / static analysis is wrong because you want LLM-graded change classification, reviewer recommendations, or risk scoring. For literal-text inspection, native tools are fine.',
176
+ description: 'Suggest reviewer roles from git diff paths and risk; does not identify people or read CODEOWNERS. Use when triaging expertise for a change, then consult CODEOWNERS to assign people.',
178
177
  category: 'analyze',
179
178
  tags: ['diff', 'reviewers', 'git'],
180
179
  inputSchema: {
@@ -225,7 +224,7 @@ export const diffReviewersTool = {
225
224
  */
226
225
  export const fileRiskTool = {
227
226
  name: 'analyze_file-risk',
228
- description: 'Assess risk for a specific file change Use when native `git diff` / `grep` / static analysis is wrong because you want LLM-graded change classification, reviewer recommendations, or risk scoring. For literal-text inspection, native tools are fine.',
227
+ description: 'Heuristically assess risk for a file path and optional change metadata. Use when triaging a changed file for focused review; inspect the source for final judgment.',
229
228
  category: 'analyze',
230
229
  tags: ['file', 'risk'],
231
230
  inputSchema: {
@@ -280,7 +279,7 @@ export const fileRiskTool = {
280
279
  */
281
280
  export const diffStatsTool = {
282
281
  name: 'analyze_diff-stats',
283
- description: 'Get quick statistics for git diff Use when native `git diff` / `grep` / static analysis is wrong because you want LLM-graded change classification, reviewer recommendations, or risk scoring. For literal-text inspection, native tools are fine.',
282
+ description: 'Count changed files, additions, and deletions in a git diff. Use when you need a quick size summary before inspecting the full patch.',
284
283
  category: 'analyze',
285
284
  tags: ['diff', 'stats', 'git'],
286
285
  inputSchema: {
@@ -8,7 +8,7 @@
8
8
  * @module @claude-flow/cli/mcp-tools/autopilot
9
9
  */
10
10
  import { validateText } from './validate-input.js';
11
- import { loadState, saveState, appendLog, loadLog, discoverTasks, isTerminal, tryLoadLearning, validateNumber, validateConfiguredTaskSources, VALID_TASK_SOURCES, } from '../autopilot-state.js';
11
+ import { loadState, saveState, appendLog, loadLog, discoverTasks, isTerminal, tryLoadLearning, getLearningLoadError, validateNumber, validateConfiguredTaskSources, VALID_TASK_SOURCES, } from '../autopilot-state.js';
12
12
  function ok(data) {
13
13
  return { content: [{ type: 'text', text: JSON.stringify(data, null, 2) }] };
14
14
  }
@@ -175,7 +175,7 @@ const autopilotLearn = {
175
175
  ]);
176
176
  return ok({ metrics, patterns });
177
177
  }
178
- return ok({ available: false, reason: 'AgentDB/AutopilotLearning not initialized', patterns: [] });
178
+ return ok({ available: false, reason: getLearningLoadError() ?? 'AgentDB/AutopilotLearning not initialized', patterns: [] });
179
179
  },
180
180
  };
181
181
  const autopilotHistory = {
@@ -85,9 +85,13 @@
85
85
  * @module @claude-flow/cli/mcp-tools/browser-intent
86
86
  */
87
87
  import { createRequire } from 'node:module';
88
- import { createServer } from 'node:http';
89
88
  import { readFileSync, existsSync } from 'node:fs';
90
89
  import { dirname, join } from 'node:path';
90
+ // Lazy, CommonJS-style load of node:http: an ESM `import … from 'node:http'`
91
+ // materialises every export of the builtin, which trips http's lazy undici
92
+ // getters (~2.5 MB heap / ~6 MB RSS) at MCP startup even when no server is
93
+ // ever started. require() of the builtin does not touch those getters.
94
+ const loadHttp = () => createRequire(import.meta.url)('node:http');
91
95
  import { validateText, validateIdentifier } from './validate-input.js';
92
96
  import { execBrowserCommand } from './browser-tools.js';
93
97
  import { storeEntry } from '../memory/memory-initializer.js';
@@ -175,7 +179,7 @@ export function resolvePageAgentLLMConfig(env = process.env) {
175
179
  export const PLACEHOLDER_API_KEY = 'ruflo-proxied-key';
176
180
  export function startLocalLLMProxy(real) {
177
181
  return new Promise((resolve, reject) => {
178
- const server = createServer((req, res) => {
182
+ const server = loadHttp().createServer((req, res) => {
179
183
  const target = `${real.baseURL.replace(/\/+$/, '')}${req.url ?? ''}`;
180
184
  const chunks = [];
181
185
  req.on('data', (c) => chunks.push(c));
@@ -93,16 +93,28 @@ function toPoincare(euclidean, curvature) {
93
93
  const factor = Math.tanh(sqrtC * norm / 2) / (sqrtC * norm + 1e-15);
94
94
  return euclidean.map(x => x * factor);
95
95
  }
96
- // Poincaré distance
96
+ // #4159: a point is usable only strictly inside the ball of radius 1/sqrt(c).
97
+ function insidePoincareBall(p, curvature) {
98
+ const c = Math.abs(curvature);
99
+ return c * p.reduce((sum, x) => sum + x * x, 0) < 1;
100
+ }
101
+ // Poincaré distance, d_c(a,b) = acosh(1 + 2c|a-b|^2 / ((1-c|a|^2)(1-c|b|^2))) / sqrt(c).
102
+ // Returns NaN for a point on or outside the ball (the formula is undefined there);
103
+ // callers must check Number.isFinite before reporting it.
97
104
  function poincareDistance(a, b, curvature) {
98
105
  const c = Math.abs(curvature);
106
+ if (a.length !== b.length || !insidePoincareBall(a, curvature) || !insidePoincareBall(b, curvature)) {
107
+ return NaN;
108
+ }
99
109
  const diffSq = a.reduce((sum, _, i) => sum + (a[i] - b[i]) ** 2, 0);
100
110
  const normASq = a.reduce((sum, x) => sum + x * x, 0);
101
111
  const normBSq = b.reduce((sum, x) => sum + x * x, 0);
102
- const denom = (1 - normASq) * (1 - normBSq);
103
- const delta = 2 * diffSq / (denom + 1e-15);
112
+ const denom = (1 - c * normASq) * (1 - c * normBSq);
113
+ const delta = (2 * c * diffSq) / denom;
104
114
  return (1 / Math.sqrt(c)) * Math.acosh(1 + delta);
105
115
  }
116
+ const HYPERBOLIC_RADIUS_NOTE = 'convert is an exponential map at the origin: it preserves the input norm ordering, so unit-norm text embeddings all land at the same radius. ' +
117
+ 'It does not encode hierarchy; depth/tree structure has to come from the hierarchy itself (for example depth chosen as the radius, or embeddings trained on the tree edges).';
106
118
  // Cosine similarity
107
119
  function cosineSimilarity(a, b) {
108
120
  const dot = a.reduce((sum, _, i) => sum + a[i] * b[i], 0);
@@ -339,6 +351,9 @@ export const embeddingsTools = [
339
351
  const poinc1 = toPoincare(emb1, config.hyperbolic.curvature);
340
352
  const poinc2 = toPoincare(emb2, config.hyperbolic.curvature);
341
353
  distance = poincareDistance(poinc1, poinc2, config.hyperbolic.curvature);
354
+ if (!Number.isFinite(distance)) {
355
+ return { success: false, error: 'Hyperbolic distance is undefined for these inputs (a converted point reached the ball boundary).' };
356
+ }
342
357
  similarity = 1 / (1 + distance);
343
358
  break;
344
359
  case 'euclidean':
@@ -739,6 +754,7 @@ export const embeddingsTools = [
739
754
  poincare,
740
755
  curvature,
741
756
  poincareNorm: Math.sqrt(poincare.reduce((sum, x) => sum + x * x, 0)),
757
+ note: HYPERBOLIC_RADIUS_NOTE,
742
758
  };
743
759
  case 'distance':
744
760
  const emb1 = input.embedding1;
@@ -747,6 +763,13 @@ export const embeddingsTools = [
747
763
  return { success: false, error: 'embedding1 and embedding2 required for distance action' };
748
764
  }
749
765
  const dist = poincareDistance(emb1, emb2, curvature);
766
+ if (!Number.isFinite(dist)) {
767
+ return {
768
+ success: false,
769
+ error: 'Poincaré distance needs two points of equal length strictly inside the ball (|x| < 1/sqrt(c)); got a point on or outside it, or mismatched lengths. Run convert on Euclidean vectors first.',
770
+ curvature,
771
+ };
772
+ }
750
773
  return {
751
774
  success: true,
752
775
  action: 'distance',
@@ -780,11 +803,10 @@ export const embeddingsTools = [
780
803
  epsilon: config.hyperbolic.epsilon,
781
804
  maxNorm: config.hyperbolic.maxNorm,
782
805
  },
806
+ note: HYPERBOLIC_RADIUS_NOTE,
783
807
  benefits: [
784
- 'Better hierarchical data representation',
785
- 'Exponential capacity in low dimensions',
786
- 'Preserves tree-like structures',
787
- 'Natural for taxonomy embeddings',
808
+ 'Exponential capacity in low dimensions when the points are placed by hierarchy (for example by depth)',
809
+ 'Natural geometry for taxonomy embeddings that are trained or constructed for it',
788
810
  ],
789
811
  };
790
812
  }
@@ -3253,6 +3253,8 @@ export const hooksTrajectoryEnd = {
3253
3253
  learned: result.learned,
3254
3254
  patternKey: result.patternKey,
3255
3255
  confidence: result.confidence,
3256
+ reinforcedNeighbour: result.reinforcedNeighbour,
3257
+ routingGate: result.routingGate,
3256
3258
  };
3257
3259
  }
3258
3260
  catch {
@@ -3416,6 +3418,8 @@ export const hooksTrajectoryEnd = {
3416
3418
  sonaUpdate: sonaResult.learned,
3417
3419
  sonaPatternKey: sonaResult.patternKey || undefined,
3418
3420
  sonaConfidence: sonaResult.confidence || undefined,
3421
+ sonaReinforcedNeighbour: sonaResult.reinforcedNeighbour || undefined,
3422
+ sonaRoutingGate: sonaResult.routingGate,
3419
3423
  ewcConsolidation: ewcResult.consolidated,
3420
3424
  ewcPenalty: ewcResult.penalty || undefined,
3421
3425
  patternsExtracted,
@@ -9,7 +9,7 @@
9
9
  *
10
10
  * @module v3/cli/mcp-tools/memory-tools
11
11
  */
12
- import type { MCPTool } from './types.js';
12
+ import { type MCPTool } from './types.js';
13
13
  export declare const DANGEROUS_KEY_PATTERN: RegExp;
14
14
  /**
15
15
  * #3570: the one key rule for every memory write path (MCP store, CLI store,
@@ -11,9 +11,12 @@
11
11
  */
12
12
  import { existsSync, mkdirSync, readdirSync, readFileSync, statSync, unlinkSync, writeFileSync } from 'fs';
13
13
  import { homedir } from 'os';
14
- import { join, resolve } from 'path';
14
+ import { basename, dirname, join, resolve } from 'path';
15
+ import { execFileSync } from 'node:child_process';
15
16
  import { createHash } from 'crypto';
17
+ import { getProjectCwd } from './types.js';
16
18
  import { validateIdentifier } from './validate-input.js';
19
+ import { DEFAULT_SEARCH_THRESHOLD, nearMisses } from '../memory/search-defaults.js';
17
20
  // #1604: Align with memory-initializer.ts — single source of truth is .swarm/memory.db
18
21
  const MEMORY_DIR = '.swarm';
19
22
  const LEGACY_MEMORY_FILE = 'store.json';
@@ -145,7 +148,24 @@ function resolveProjectMemoryDir(claudeProjectsDir, projectPathOverride) {
145
148
  sources.push(projectPathOverride);
146
149
  }
147
150
  else {
148
- sources.push(process.cwd());
151
+ const project = getProjectCwd();
152
+ sources.push(project);
153
+ // Claude Code shares auto-memory across linked Git worktrees under the
154
+ // main checkout's project slug. Preserve the direct-path match first,
155
+ // then try the common Git directory's parent. Explicit overrides above
156
+ // remain authoritative, and non-Git projects need no Git dependency.
157
+ try {
158
+ const commonDir = execFileSync('git', ['rev-parse', '--path-format=absolute', '--git-common-dir'], {
159
+ cwd: project,
160
+ encoding: 'utf-8',
161
+ timeout: 1000,
162
+ windowsHide: true,
163
+ stdio: ['ignore', 'pipe', 'ignore'],
164
+ }).trim();
165
+ if (basename(commonDir) === '.git')
166
+ sources.push(dirname(resolve(project, commonDir)));
167
+ }
168
+ catch { /* Git unavailable or not a repository: use the project path */ }
149
169
  }
150
170
  for (const source of sources) {
151
171
  // Candidate 1: legacy POSIX hash — what shipped before #1883
@@ -231,6 +251,19 @@ async function getMemoryFunctions() {
231
251
  checkMemoryInitialization,
232
252
  };
233
253
  }
254
+ /**
255
+ * Path of the CLI's own store (.swarm/memory.db or CLAUDE_FLOW_DB_PATH), or
256
+ * undefined when the memory module cannot say (#4148). Never throws.
257
+ */
258
+ async function resolveCliStorePath() {
259
+ try {
260
+ const mod = await import('../memory/memory-initializer.js');
261
+ return typeof mod.resolveDbPath === 'function' ? mod.resolveDbPath() : undefined;
262
+ }
263
+ catch {
264
+ return undefined;
265
+ }
266
+ }
234
267
  /**
235
268
  * #2922: every `backend:` field in this file's tool responses used to be the
236
269
  * hardcoded literal `'sql.js + HNSW'` regardless of which search path was
@@ -538,7 +571,7 @@ export const memoryTools = [
538
571
  query: { type: 'string', description: 'Search query (semantic similarity)' },
539
572
  namespace: { type: 'string', description: 'Namespace to search (default: all namespaces — omit to search across every namespace)' },
540
573
  limit: { type: 'number', description: 'Maximum results (default: 10)' },
541
- threshold: { type: 'number', description: 'Minimum raw retrieval relevance 0-1 for candidate admission, applied per query before SmartRetrieval ranking; not a floor on rankingScore (default: 0.3)' },
574
+ threshold: { type: 'number', description: 'Minimum raw retrieval relevance 0-1 for candidate admission, applied per query before SmartRetrieval ranking; not a floor on rankingScore (default: 0.2; calibrated for the bundled embedding model, pass 0 to see every match)' },
542
575
  smart: { type: 'boolean', description: 'Enable SmartRetrieval — query expansion, RRF fusion, recency boost, MMR diversity; preserves raw similarity and adds rankingScore (default: false)' },
543
576
  provenance_filter: {
544
577
  type: 'array',
@@ -567,7 +600,8 @@ export const memoryTools = [
567
600
  // in the search layer actually fires.
568
601
  const namespace = input.namespace;
569
602
  const limit = input.limit ?? 10;
570
- const threshold = input.threshold ?? 0.3;
603
+ const threshold = input.threshold ?? DEFAULT_SEARCH_THRESHOLD;
604
+ const thresholdWasDefault = input.threshold === undefined || input.threshold === null;
571
605
  validateMemoryInput(undefined, undefined, query, namespace);
572
606
  const startTime = performance.now();
573
607
  try {
@@ -638,10 +672,14 @@ export const memoryTools = [
638
672
  provenanceType: r.provenanceType,
639
673
  };
640
674
  });
675
+ const smartNearMisses = results.length === 0 && thresholdWasDefault
676
+ ? await nearMisses(searchEntries, { query, namespace, provenanceFilter })
677
+ : undefined;
641
678
  return {
642
679
  query,
643
680
  results,
644
681
  total: results.length,
682
+ ...(smartNearMisses ?? {}),
645
683
  searchTime: `${duration.toFixed(2)}ms`,
646
684
  backend: 'SmartRetrieval (RRF + MMR + Recency)',
647
685
  stats: smartResult.stats,
@@ -685,10 +723,14 @@ export const memoryTools = [
685
723
  provenanceType: r.provenanceType,
686
724
  };
687
725
  });
726
+ const nearMissInfo = results.length === 0 && thresholdWasDefault
727
+ ? await nearMisses(searchEntries, { query, namespace, provenanceFilter })
728
+ : undefined;
688
729
  return {
689
730
  query,
690
731
  results,
691
732
  total: results.length,
733
+ ...(nearMissInfo ?? {}),
692
734
  searchTime: `${duration.toFixed(2)}ms`,
693
735
  backend: 'HNSW + sql.js',
694
736
  ...(smartFallbackReason ? { smartFallback: smartFallbackReason } : {}),
@@ -1043,6 +1085,7 @@ export const memoryTools = [
1043
1085
  }
1044
1086
  let imported = 0;
1045
1087
  let skipped = 0;
1088
+ const importErrors = [];
1046
1089
  // #1791.8 — Claude Code's `~/.claude/projects/` accumulates historical
1047
1090
  // project_id directories (truncated forms, sandbox cwds, renamed
1048
1091
  // workspaces) that all contain copies of the same memory files. The
@@ -1082,7 +1125,7 @@ export const memoryTools = [
1082
1125
  // #1884 — sanitize key so memory_delete can later remove it. Without
1083
1126
  // this, dangerous chars from frontmatter `name` strand the key.
1084
1127
  const key = sanitizeMemoryKey(`claude:${memFile.project}:${name}`);
1085
- const stored = await storeEntry({ key, value: body, namespace: ns, generateEmbeddingFlag: true });
1128
+ const stored = await storeEntry({ key, value: body, namespace: ns, generateEmbeddingFlag: true, upsert: true });
1086
1129
  if (!stored.success)
1087
1130
  throw new Error(stored.error || `Failed to store ${key}`);
1088
1131
  imported++;
@@ -1097,15 +1140,19 @@ export const memoryTools = [
1097
1140
  // #1884 — sanitize so any dangerous chars in the heading don't
1098
1141
  // produce keys memory_delete will reject.
1099
1142
  const key = sanitizeMemoryKey(`claude:${memFile.project}:${name}:${sectionTitle.slice(0, 50)}`);
1100
- const stored = await storeEntry({ key, value: sectionBody, namespace: ns, generateEmbeddingFlag: true });
1143
+ const stored = await storeEntry({ key, value: sectionBody, namespace: ns, generateEmbeddingFlag: true, upsert: true });
1101
1144
  if (!stored.success)
1102
1145
  throw new Error(stored.error || `Failed to store ${key}`);
1103
1146
  imported++;
1104
1147
  }
1105
1148
  }
1106
1149
  }
1107
- catch {
1150
+ catch (err) {
1108
1151
  skipped++;
1152
+ // Say why a file was skipped instead of returning a bare failure (#4197).
1153
+ if (importErrors.length < 5) {
1154
+ importErrors.push(`${memFile.path}: ${err instanceof Error ? err.message : String(err)}`);
1155
+ }
1109
1156
  }
1110
1157
  }
1111
1158
  // AUDIT #3: report the embedding backend truthfully — a hash-fallback
@@ -1124,6 +1171,7 @@ export const memoryTools = [
1124
1171
  skipped,
1125
1172
  duplicatesSkipped,
1126
1173
  excludedByPattern,
1174
+ ...(importErrors.length > 0 ? { errors: importErrors } : {}),
1127
1175
  files: memoryFiles.length,
1128
1176
  projects: projects.size,
1129
1177
  namespace: ns,
@@ -1497,25 +1545,50 @@ export const memoryTools = [
1497
1545
  if (!v.valid)
1498
1546
  throw new Error(v.error);
1499
1547
  }
1500
- // #2073: pass includeContent so the value field carries the actual
1501
- // entry body. Without this, `value` is always null because listEntries
1502
- // strips content by default (callers pay for the JSON parse only when
1503
- // they need it).
1504
- // A successful export must cover the whole reported store. Read all
1505
- // pages before touching an existing snapshot, including on read failure.
1506
- const entries = [];
1507
- let total;
1508
- do {
1509
- const page = await listEntries({ limit: 10000, offset: entries.length, namespace, includeContent: true });
1510
- if (!page.success)
1511
- return { error: page.error || 'Could not read memory for export' };
1512
- total ??= page.total;
1513
- if (page.entries.length === 0 && entries.length < total) {
1514
- return { error: `Incomplete memory export: read ${entries.length} of ${total} entries` };
1548
+ const readStore = async (dbPath) => {
1549
+ const out = [];
1550
+ let total;
1551
+ do {
1552
+ const page = await listEntries({ limit: 10000, offset: out.length, namespace, includeContent: true, ...(dbPath ? { dbPath } : {}) });
1553
+ if (!page.success)
1554
+ return { error: page.error || 'Could not read memory for export' };
1555
+ total ??= page.total;
1556
+ if (page.entries.length === 0 && out.length < total) {
1557
+ return { error: `Incomplete memory export: read ${out.length} of ${total} entries` };
1558
+ }
1559
+ out.push(...page.entries);
1560
+ } while (out.length < total);
1561
+ return { entries: out };
1562
+ };
1563
+ const primary = await readStore();
1564
+ if ('error' in primary)
1565
+ return { error: primary.error };
1566
+ // #4148: the default reader is the AgentDB bridge, but the CLI's own store
1567
+ // (.swarm/memory.db, possibly encrypted) can hold rows the bridge never
1568
+ // sees, so an export silently covered one store and reported success. Read
1569
+ // the CLI store too and merge, newest copy of a (namespace, key) winning.
1570
+ const warnings = [];
1571
+ const stores = [{ store: 'default', entries: primary.entries.length }];
1572
+ const merged = new Map();
1573
+ const keep = (e) => {
1574
+ const id = `${e.namespace}\u0000${e.key}`;
1575
+ const have = merged.get(id);
1576
+ if (!have || String(e.updatedAt) > String(have.updatedAt))
1577
+ merged.set(id, e);
1578
+ };
1579
+ primary.entries.forEach(keep);
1580
+ const cliStore = await resolveCliStorePath();
1581
+ if (cliStore && existsSync(cliStore)) {
1582
+ const secondary = await readStore(cliStore);
1583
+ if ('error' in secondary) {
1584
+ warnings.push(`Could not read the CLI store ${cliStore} (${secondary.error}); the export covers the AgentDB store only.`);
1515
1585
  }
1516
- entries.push(...page.entries);
1517
- } while (entries.length < total);
1518
- const all = { entries };
1586
+ else {
1587
+ stores.push({ store: cliStore, entries: secondary.entries.length });
1588
+ secondary.entries.forEach(keep);
1589
+ }
1590
+ }
1591
+ const all = { entries: [...merged.values()] };
1519
1592
  const payload = {
1520
1593
  schema: 'ruflo-memory-export/v1',
1521
1594
  exportedAt: new Date().toISOString(),
@@ -1542,6 +1615,8 @@ export const memoryTools = [
1542
1615
  outputPath,
1543
1616
  format: input.format || 'json',
1544
1617
  exported: { entries: all.entries.length, vectors: vectorsWithEmb, patterns: 0 },
1618
+ stores,
1619
+ ...(warnings.length ? { warnings } : {}),
1545
1620
  fileSize: `${Buffer.byteLength(JSON.stringify(payload))}B`,
1546
1621
  note: input.format === 'csv' ? 'CSV not implemented yet — wrote JSON' : undefined,
1547
1622
  };
@@ -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.10.2` npm package, NOT
402
+ // Backed by the separate `@metaharness/darwin@~0.12.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
  // ───────────────────────────────────────────────────────────────────────