claude-flow 3.74.0 → 3.75.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 (93) hide show
  1. package/.claude/helpers/auto-memory-hook.mjs +262 -81
  2. package/node_modules/@claude-flow/codex/README.md +38 -0
  3. package/node_modules/@claude-flow/codex/dist/generators/agents-md.d.ts +1 -0
  4. package/node_modules/@claude-flow/codex/dist/generators/agents-md.d.ts.map +1 -1
  5. package/node_modules/@claude-flow/codex/dist/generators/agents-md.js +4 -4
  6. package/node_modules/@claude-flow/codex/dist/generators/agents-md.js.map +1 -1
  7. package/node_modules/@claude-flow/codex/dist/generators/dual-instructions.d.ts +20 -0
  8. package/node_modules/@claude-flow/codex/dist/generators/dual-instructions.d.ts.map +1 -0
  9. package/node_modules/@claude-flow/codex/dist/generators/dual-instructions.js +104 -0
  10. package/node_modules/@claude-flow/codex/dist/generators/dual-instructions.js.map +1 -0
  11. package/node_modules/@claude-flow/codex/dist/generators/index.d.ts +2 -0
  12. package/node_modules/@claude-flow/codex/dist/generators/index.d.ts.map +1 -1
  13. package/node_modules/@claude-flow/codex/dist/generators/index.js +2 -0
  14. package/node_modules/@claude-flow/codex/dist/generators/index.js.map +1 -1
  15. package/node_modules/@claude-flow/codex/dist/generators/shared-instructions.d.ts +46 -0
  16. package/node_modules/@claude-flow/codex/dist/generators/shared-instructions.d.ts.map +1 -0
  17. package/node_modules/@claude-flow/codex/dist/generators/shared-instructions.js +162 -0
  18. package/node_modules/@claude-flow/codex/dist/generators/shared-instructions.js.map +1 -0
  19. package/node_modules/@claude-flow/codex/dist/index.d.ts +3 -3
  20. package/node_modules/@claude-flow/codex/dist/index.js +1 -1
  21. package/node_modules/@claude-flow/codex/dist/initializer.d.ts.map +1 -1
  22. package/node_modules/@claude-flow/codex/dist/initializer.js +16 -93
  23. package/node_modules/@claude-flow/codex/dist/initializer.js.map +1 -1
  24. package/node_modules/@claude-flow/codex/package.json +8 -6
  25. package/node_modules/@claude-flow/mcp/README.md +44 -0
  26. package/node_modules/@claude-flow/mcp/package.json +16 -4
  27. package/package.json +4 -4
  28. package/v3/@claude-flow/cli/catalog-manifest.json +3 -3
  29. package/v3/@claude-flow/cli/dist/src/autopilot-state.js +17 -8
  30. package/v3/@claude-flow/cli/dist/src/commands/agent.js +2 -1
  31. package/v3/@claude-flow/cli/dist/src/commands/init.js +28 -6
  32. package/v3/@claude-flow/cli/dist/src/commands/memory-backup.js +2 -1
  33. package/v3/@claude-flow/cli/dist/src/commands/memory-distill.js +2 -1
  34. package/v3/@claude-flow/cli/dist/src/commands/memory.js +47 -3
  35. package/v3/@claude-flow/cli/dist/src/commands/neural.js +6 -5
  36. package/v3/@claude-flow/cli/dist/src/commands/plugins-host.d.ts +13 -0
  37. package/v3/@claude-flow/cli/dist/src/commands/plugins-host.js +161 -0
  38. package/v3/@claude-flow/cli/dist/src/commands/plugins.js +3 -1
  39. package/v3/@claude-flow/cli/dist/src/commands/start-all.d.ts +28 -0
  40. package/v3/@claude-flow/cli/dist/src/commands/start-all.js +99 -0
  41. package/v3/@claude-flow/cli/dist/src/commands/start.d.ts +5 -1
  42. package/v3/@claude-flow/cli/dist/src/commands/start.js +17 -10
  43. package/v3/@claude-flow/cli/dist/src/commands/swarm.js +2 -1
  44. package/v3/@claude-flow/cli/dist/src/fs-secure.js +9 -2
  45. package/v3/@claude-flow/cli/dist/src/init/claudemd-generator.d.ts +15 -0
  46. package/v3/@claude-flow/cli/dist/src/init/claudemd-generator.js +64 -114
  47. package/v3/@claude-flow/cli/dist/src/init/dual-instructions.d.ts +29 -0
  48. package/v3/@claude-flow/cli/dist/src/init/dual-instructions.js +87 -0
  49. package/v3/@claude-flow/cli/dist/src/init/executor.js +96 -13
  50. package/v3/@claude-flow/cli/dist/src/init/index.d.ts +3 -1
  51. package/v3/@claude-flow/cli/dist/src/init/index.js +5 -1
  52. package/v3/@claude-flow/cli/dist/src/init/plugin-dedup.d.ts +61 -0
  53. package/v3/@claude-flow/cli/dist/src/init/plugin-dedup.js +130 -0
  54. package/v3/@claude-flow/cli/dist/src/init/shared-instructions.d.ts +46 -0
  55. package/v3/@claude-flow/cli/dist/src/init/shared-instructions.js +162 -0
  56. package/v3/@claude-flow/cli/dist/src/init/types.d.ts +33 -0
  57. package/v3/@claude-flow/cli/dist/src/init/types.js +3 -0
  58. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.d.ts +14 -0
  59. package/v3/@claude-flow/cli/dist/src/mcp-tools/agent-tools.js +48 -5
  60. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-hierarchical-inventory-tools.d.ts +15 -0
  61. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-hierarchical-inventory-tools.js +115 -0
  62. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-inventory-tools.d.ts +21 -0
  63. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-inventory-tools.js +152 -0
  64. package/v3/@claude-flow/cli/dist/src/mcp-tools/agentdb-tools.js +56 -7
  65. package/v3/@claude-flow/cli/dist/src/mcp-tools/aidefence-known-misses.d.ts +6 -0
  66. package/v3/@claude-flow/cli/dist/src/mcp-tools/aidefence-known-misses.js +23 -5
  67. package/v3/@claude-flow/cli/dist/src/mcp-tools/hooks-tools.js +21 -3
  68. package/v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.d.ts +29 -0
  69. package/v3/@claude-flow/cli/dist/src/mcp-tools/memory-tools.js +239 -19
  70. package/v3/@claude-flow/cli/dist/src/mcp-tools/security-tools.js +53 -5
  71. package/v3/@claude-flow/cli/dist/src/memory/embedding-config.d.ts +79 -0
  72. package/v3/@claude-flow/cli/dist/src/memory/embedding-config.js +250 -0
  73. package/v3/@claude-flow/cli/dist/src/memory/ewc-consolidation.js +2 -1
  74. package/v3/@claude-flow/cli/dist/src/memory/intelligence.d.ts +28 -2
  75. package/v3/@claude-flow/cli/dist/src/memory/intelligence.js +37 -7
  76. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.d.ts +42 -0
  77. package/v3/@claude-flow/cli/dist/src/memory/memory-bridge.js +267 -28
  78. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.d.ts +1 -1
  79. package/v3/@claude-flow/cli/dist/src/memory/memory-initializer.js +47 -22
  80. package/v3/@claude-flow/cli/dist/src/ruvector/lora-adapter.js +3 -2
  81. package/v3/@claude-flow/cli/dist/src/ruvector/task-embedder.d.ts +2 -1
  82. package/v3/@claude-flow/cli/dist/src/ruvector/task-embedder.js +7 -3
  83. package/v3/@claude-flow/cli/dist/src/services/daemon-autostart.d.ts +4 -6
  84. package/v3/@claude-flow/cli/dist/src/services/daemon-autostart.js +6 -46
  85. package/v3/@claude-flow/cli/dist/src/services/host-executable.d.ts +68 -0
  86. package/v3/@claude-flow/cli/dist/src/services/host-executable.js +175 -0
  87. package/v3/@claude-flow/cli/dist/src/services/host-plugin-manager.d.ts +137 -0
  88. package/v3/@claude-flow/cli/dist/src/services/host-plugin-manager.js +374 -0
  89. package/v3/@claude-flow/cli/dist/src/services/project-root.d.ts +37 -0
  90. package/v3/@claude-flow/cli/dist/src/services/project-root.js +122 -0
  91. package/v3/@claude-flow/cli/package.json +7 -7
  92. package/.claude/.proven-config-version +0 -1
  93. package/.claude/proven-config.json +0 -42
@@ -27,6 +27,7 @@ import { mkdirSync, realpathSync } from 'node:fs';
27
27
  import { createRequire } from 'node:module';
28
28
  import { AsyncLocalStorage } from 'node:async_hooks';
29
29
  import { validateFeedbackPatterns } from './feedback-patterns.js';
30
+ import { DEFAULT_EMBEDDING_MODEL, resolveEffectiveEmbeddingConfig, resolveEmbeddingConfig, } from './embedding-config.js';
30
31
  // ===== Lazy registry cache, keyed by database path =====
31
32
  /**
32
33
  * #3196: this cache is keyed by resolved database path, and that is the whole
@@ -45,6 +46,23 @@ import { validateFeedbackPatterns } from './feedback-patterns.js';
45
46
  */
46
47
  const registryPromises = new Map();
47
48
  const registryInstances = new Map();
49
+ /**
50
+ * #2305: the embedding model/dimension the AgentDB registry was opened with —
51
+ * `.claude-flow/embeddings.json`, or the store's recorded dimension when that
52
+ * differs. Falls back to the configured value before any registry opened.
53
+ */
54
+ let bridgeEmbeddingConfig = null;
55
+ function activeEmbeddingConfig() {
56
+ return bridgeEmbeddingConfig ?? resolveEmbeddingConfig(process.cwd());
57
+ }
58
+ /** Model name recorded next to a vector of `dimension` length. */
59
+ function embeddingModelLabel(dimension) {
60
+ const cfg = activeEmbeddingConfig();
61
+ if (dimension === cfg.dimension)
62
+ return cfg.model;
63
+ // Unchanged pre-#2305 label for any other size.
64
+ return DEFAULT_EMBEDDING_MODEL;
65
+ }
48
66
  // One lease spans an entire bridge operation, including its awaited controller
49
67
  // effects and nested bridge calls. Initializer ownership alone is insufficient:
50
68
  // a ReasoningBank write can still be pending after its registry has opened.
@@ -284,11 +302,22 @@ async function getRegistry(dbPath) {
284
302
  try {
285
303
  if (resolvedPath !== ':memory:')
286
304
  mkdirSync(path.dirname(resolvedPath), { recursive: true });
305
+ // Check memory.db as well as this store: the memory path mirrors
306
+ // the same vectors into both, so an old 384-dim memory.db must keep
307
+ // an empty agentdb-memory.db at 384 too (same order as the
308
+ // initializer, so both converge on one answer).
309
+ const embCfg = await resolveEffectiveEmbeddingConfig({
310
+ root: process.cwd(),
311
+ dbPaths: resolvedPath === ':memory:'
312
+ ? []
313
+ : [path.join(path.dirname(resolvedPath), 'memory.db'), resolvedPath],
314
+ });
315
+ bridgeEmbeddingConfig = embCfg;
287
316
  await registry.initialize({
288
317
  // #2786: use agentdb-memory.db (plaintext) so native better-sqlite3 doesn't hit the encrypted memory.db.
289
318
  dbPath: resolvedPath,
290
- embeddingModel: 'Xenova/all-MiniLM-L6-v2',
291
- dimension: 384,
319
+ embeddingModel: embCfg.model,
320
+ dimension: embCfg.dimension,
292
321
  vectorBackend: 'auto',
293
322
  controllers: {
294
323
  reasoningBank: true,
@@ -569,6 +598,7 @@ export function _resetRegistryCacheForTest() {
569
598
  testRegistryOverride = null;
570
599
  testRegistryFactory = null;
571
600
  bridgeFailureReasons.clear();
601
+ bridgeEmbeddingConfig = null;
572
602
  }
573
603
  /** Inject registry construction without requiring the optional native package in tests. */
574
604
  export function __setMemoryBridgeRegistryFactoryForTests(factory) {
@@ -1017,7 +1047,7 @@ async function embedForBridge(agentdb, text) {
1017
1047
  try {
1018
1048
  const emb = await embedder.embed(text);
1019
1049
  if (emb && emb.length > 0) {
1020
- return { vector: Array.from(emb), model: 'Xenova/all-MiniLM-L6-v2' };
1050
+ return { vector: Array.from(emb), model: embeddingModelLabel(emb.length) };
1021
1051
  }
1022
1052
  agentdbProblem = 'agentdb embedder returned no vector';
1023
1053
  }
@@ -1894,17 +1924,18 @@ export async function bridgeGenerateEmbedding(text, dbPath) {
1894
1924
  // yet) and silently fall back to a 128-dim hash stub. The embedder doesn't
1895
1925
  // expose isMock=true in that path, so the wrapper above was reporting
1896
1926
  // backend='onnx' on what's actually 128-dim hash garbage. The model name
1897
- // we hardcode ('Xenova/all-MiniLM-L6-v2') always produces 384-dim, so a
1898
- // dimensions mismatch is a definitive stub signal: return null and let
1899
- // the caller fall through to generateLocalEmbedding which routes to
1900
- // transformers.js / ruvector ONNX directly.
1901
- if (emb.length !== 384) {
1927
+ // the registry was opened with (#2305: from embeddings.json, default
1928
+ // MiniLM/384) has a fixed dimension, so a dimensions mismatch is a
1929
+ // definitive stub signal: return null and let the caller fall through to
1930
+ // generateLocalEmbedding which routes to transformers.js / ruvector ONNX.
1931
+ const embCfg = activeEmbeddingConfig();
1932
+ if (emb.length !== embCfg.dimension) {
1902
1933
  return null;
1903
1934
  }
1904
1935
  return {
1905
1936
  embedding: Array.from(emb),
1906
1937
  dimensions: emb.length,
1907
- model: 'Xenova/all-MiniLM-L6-v2',
1938
+ model: embCfg.model,
1908
1939
  backend: isMock ? 'mock' : 'onnx',
1909
1940
  };
1910
1941
  }
@@ -1935,7 +1966,7 @@ export async function bridgeLoadEmbeddingModel(dbPath) {
1935
1966
  return {
1936
1967
  success: true,
1937
1968
  dimensions: test.length,
1938
- modelName: 'Xenova/all-MiniLM-L6-v2',
1969
+ modelName: embeddingModelLabel(test.length),
1939
1970
  loadTime: Date.now() - startTime,
1940
1971
  };
1941
1972
  }
@@ -2172,7 +2203,7 @@ export async function bridgeAddEmbedding(id, embedding, entry, dbPath) {
2172
2203
  id, key, namespace, content, type,
2173
2204
  embedding, embedding_dimensions, embedding_model,
2174
2205
  created_at, updated_at, status
2175
- ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, 'Xenova/all-MiniLM-L6-v2', ?, ?, 'active')
2206
+ ) VALUES (?, ?, ?, ?, 'semantic', ?, ?, ?, ?, ?, 'active')
2176
2207
  ON CONFLICT(namespace, key) DO UPDATE SET
2177
2208
  id = excluded.id,
2178
2209
  content = excluded.content,
@@ -2182,7 +2213,7 @@ export async function bridgeAddEmbedding(id, embedding, entry, dbPath) {
2182
2213
  embedding_model = excluded.embedding_model,
2183
2214
  updated_at = excluded.updated_at,
2184
2215
  status = 'active'
2185
- `).run(id, entry.key, entry.namespace, entry.content, embeddingJson, embedding.length, now, now);
2216
+ `).run(id, entry.key, entry.namespace, entry.content, embeddingJson, embedding.length, embeddingModelLabel(embedding.length), now, now);
2186
2217
  return true;
2187
2218
  }
2188
2219
  catch {
@@ -2298,6 +2329,7 @@ export function __setMemoryBridgeRegistryForTests(registry) {
2298
2329
  testRegistryOverride = registry;
2299
2330
  testRegistryFactory = null;
2300
2331
  bridgeFailureReasons.clear();
2332
+ bridgeEmbeddingConfig = null;
2301
2333
  }
2302
2334
  /**
2303
2335
  * Shutdown the bridge and release resources.
@@ -2478,23 +2510,34 @@ export async function bridgeStorePattern(options) {
2478
2510
  /**
2479
2511
  * Case-insensitive substring match over agentdb's reasoning_patterns table —
2480
2512
  * the rows ReasoningBank.storePattern() writes. Used only when the vector
2481
- * search returns nothing. Returns [] when the table or handle is unavailable.
2513
+ * search returns nothing. Returns no rows (and no error) when there is no
2514
+ * database handle to scan.
2515
+ *
2516
+ * #4714: a read that throws is reported through `error`, not turned into an
2517
+ * empty list. The pattern-search handler reports an error-free empty result
2518
+ * as a healthy no-match, so a SQL failure must not look like one.
2482
2519
  */
2483
2520
  function substringSearchReasoningPatterns(registry, query, k) {
2521
+ const db = registry?.getAgentDB?.()?.database;
2522
+ if (!db || typeof db.prepare !== 'function')
2523
+ return { rows: [] };
2484
2524
  try {
2485
- const db = registry?.getAgentDB?.()?.database;
2486
- if (!db || typeof db.prepare !== 'function')
2487
- return [];
2488
2525
  const like = `%${query.toLowerCase().replace(/[\\%_]/g, (c) => `\\${c}`)}%`;
2489
2526
  const rows = db.prepare("SELECT id, approach, success_rate FROM reasoning_patterns WHERE lower(approach) LIKE ? ESCAPE '\\' ORDER BY id DESC LIMIT ?").all(like, k);
2490
- return rows.map((r) => ({ id: String(r.id), content: r.approach, score: r.success_rate ?? 0 }));
2527
+ return { rows: rows.map((r) => ({ id: String(r.id), content: r.approach, score: r.success_rate ?? 0 })) };
2491
2528
  }
2492
- catch {
2493
- return [];
2529
+ catch (err) {
2530
+ return { rows: [], error: `reasoning_patterns substring scan failed: ${err instanceof Error ? err.message : String(err)}` };
2494
2531
  }
2495
2532
  }
2496
2533
  /**
2497
2534
  * Search patterns via ReasoningBank controller.
2535
+ *
2536
+ * Returns null when no registry is available. With `controller:
2537
+ * 'reasoningBank'`, an empty `results` and no `error` means the controller
2538
+ * ran and found nothing. #4714: when the controller throws, returns a
2539
+ * non-array, or the substring scan fails, the result carries `error` so the
2540
+ * caller cannot mistake the failure for a no-match.
2498
2541
  */
2499
2542
  export async function bridgeSearchPatterns(options) {
2500
2543
  if (!operationContext.getStore()?.active)
@@ -2507,11 +2550,27 @@ export async function bridgeSearchPatterns(options) {
2507
2550
  // ReasoningBank may expose .searchPatterns() (agentdb) or .search() (legacy) (#1492 Bug 2)
2508
2551
  if (reasoningBank && typeof (reasoningBank.searchPatterns ?? reasoningBank.search) === 'function') {
2509
2552
  let results;
2510
- if (typeof reasoningBank.searchPatterns === 'function') {
2511
- results = await reasoningBank.searchPatterns({ task: options.query, k: options.topK || 5, threshold: options.minConfidence || 0.3 });
2553
+ try {
2554
+ if (typeof reasoningBank.searchPatterns === 'function') {
2555
+ results = await reasoningBank.searchPatterns({ task: options.query, k: options.topK || 5, threshold: options.minConfidence || 0.3 });
2556
+ }
2557
+ else {
2558
+ results = await reasoningBank.search(options.query, { topK: options.topK || 5, minScore: options.minConfidence || 0.3 });
2559
+ }
2512
2560
  }
2513
- else {
2514
- results = await reasoningBank.search(options.query, { topK: options.topK || 5, minScore: options.minConfidence || 0.3 });
2561
+ catch (err) {
2562
+ // #4714 — report the failure with the result instead of a bare null,
2563
+ // which callers read as "no registry". Still recorded for agentdb_health.
2564
+ const message = err instanceof Error ? err.message : String(err);
2565
+ bridgeFailureReasons.set(canonicalDbPath(options.dbPath), message);
2566
+ return { results: [], controller: 'reasoningBank', error: `ReasoningBank search failed: ${message}` };
2567
+ }
2568
+ if (!Array.isArray(results)) {
2569
+ return {
2570
+ results: [],
2571
+ controller: 'reasoningBank',
2572
+ error: `ReasoningBank search returned a non-array result (${results === null ? 'null' : typeof results})`,
2573
+ };
2515
2574
  }
2516
2575
  // #3327 Finding A — agentdb returns ReasoningPattern[]: the text lives in
2517
2576
  // `approach` and the cosine score in `similarity`. Neither `content`/
@@ -2519,19 +2578,22 @@ export async function bridgeSearchPatterns(options) {
2519
2578
  // mapping produced `content: ''` and `score: 0` for every hit even when
2520
2579
  // the search itself succeeded. Read the real fields first, keeping the
2521
2580
  // legacy names as fallbacks for the pre-agentdb shape.
2522
- let mapped = Array.isArray(results) ? results.map((r) => ({
2581
+ const mapped = results.map((r) => ({
2523
2582
  id: String(r.id ?? r.patternId ?? ''),
2524
2583
  content: r.approach ?? r.content ?? r.pattern ?? '',
2525
2584
  score: r.similarity ?? r.score ?? r.successRate ?? r.confidence ?? 0,
2526
- })) : [];
2585
+ }));
2586
+ if (mapped.length > 0)
2587
+ return { results: mapped, controller: 'reasoningBank' };
2527
2588
  // #4643 — with agentdb's mock embedder (Transformers.js failed to load:
2528
2589
  // offline, or a failed `sharp` install) a passage and a query embed to
2529
2590
  // unrelated hash vectors, so the vector search misses a pattern that
2530
2591
  // storePattern just wrote. Scan the same reasoning_patterns table for the
2531
2592
  // query text, as the LocalReasoningBank branch below does over getAll().
2532
- if (mapped.length === 0)
2533
- mapped = substringSearchReasoningPatterns(registry, options.query, options.topK || 5);
2534
- return { results: mapped, controller: 'reasoningBank' };
2593
+ const scan = substringSearchReasoningPatterns(registry, options.query, options.topK || 5);
2594
+ return scan.error
2595
+ ? { results: scan.rows, controller: 'reasoningBank', error: scan.error }
2596
+ : { results: scan.rows, controller: 'reasoningBank' };
2535
2597
  }
2536
2598
  // #2226 — the wired-in LocalReasoningBank implements store() + findSimilar()/getAll()
2537
2599
  // but NOT searchPatterns()/search(). bridgeStorePattern commits patterns to its
@@ -3887,4 +3949,181 @@ export async function getMemoryBridgeStats(options = {}) {
3887
3949
  return { totalEntries: 0, perNamespace: {}, source: 'memory-bridge (error)', reachable: false };
3888
3950
  }
3889
3951
  }
3952
+ // ===== #4712: persisted inventory of the hierarchical (tiered) store =====
3953
+ /** Smallest @claude-flow/memory that ships TieredMemoryStore.listEntries/getEntry. */
3954
+ const TIERED_INVENTORY_MIN_MEMORY = '3.3.0';
3955
+ /**
3956
+ * Run a read-only inventory call against the `hierarchicalMemory` controller
3957
+ * inside one bridge operation. Refuses, never fabricates: a native agentdb
3958
+ * controller, an older @claude-flow/memory without the API, a volatile store
3959
+ * and a failed read each come back as `success: false` with the reason.
3960
+ */
3961
+ async function withHierarchicalInventory(operation, read) {
3962
+ if (!operationContext.getStore()?.active)
3963
+ return withBridgeOperation(() => withHierarchicalInventory(operation, read));
3964
+ const registry = await getRegistry();
3965
+ if (!registry)
3966
+ return null;
3967
+ let hm;
3968
+ try {
3969
+ hm = registry.get('hierarchicalMemory');
3970
+ }
3971
+ catch (e) {
3972
+ return { success: false, error: `HierarchicalMemory not available: ${e?.message ?? e}` };
3973
+ }
3974
+ if (!hm)
3975
+ return { success: false, error: 'HierarchicalMemory not available' };
3976
+ if (typeof hm.getStats === 'function' && typeof hm.promote === 'function') {
3977
+ return {
3978
+ success: false,
3979
+ controller: 'native-unsupported',
3980
+ error: `hierarchical-${operation} reads the tiered_memory table; the native agentdb HierarchicalMemory has no inventory API`,
3981
+ };
3982
+ }
3983
+ const info = describeHierarchicalStore(hm, getHierarchicalFallback(registry));
3984
+ if (typeof hm.listEntries !== 'function' || typeof hm.getEntry !== 'function') {
3985
+ return {
3986
+ success: false,
3987
+ ...info,
3988
+ code: 'unsupported',
3989
+ error: `the installed @claude-flow/memory predates TieredMemoryStore.listEntries/getEntry (needs >= ${TIERED_INVENTORY_MIN_MEMORY})`,
3990
+ };
3991
+ }
3992
+ try {
3993
+ return { success: true, ...info, ...read(hm) };
3994
+ }
3995
+ catch (e) {
3996
+ return {
3997
+ success: false,
3998
+ ...info,
3999
+ ...(typeof e?.code === 'string' ? { code: e.code } : {}),
4000
+ error: String(e?.message ?? e),
4001
+ };
4002
+ }
4003
+ }
4004
+ /** Page through every persisted hierarchical-memory entry (#4712). */
4005
+ export async function bridgeHierarchicalList(params) {
4006
+ return withHierarchicalInventory('list', hm => hm.listEntries({
4007
+ tier: params.tier,
4008
+ status: params.status,
4009
+ limit: params.limit,
4010
+ cursor: params.cursor,
4011
+ }));
4012
+ }
4013
+ /** Exact read of one hierarchical-memory entry by its stable id (#4712). */
4014
+ export async function bridgeHierarchicalGet(params) {
4015
+ return withHierarchicalInventory('get', hm => {
4016
+ const entry = hm.getEntry(params.id, { includeInactive: params.includeInactive === true });
4017
+ return { found: entry !== null, entry };
4018
+ });
4019
+ }
4020
+ // ===== #4707: read-only pattern / skill inventory and hierarchical counts =====
4021
+ /** Smallest agentdb whose ReasoningBank/SkillLibrary ship listPatterns/listSkills/getSkill. */
4022
+ const AGENTDB_INVENTORY_MIN = '3.3.0';
4023
+ /**
4024
+ * Run one read against a registry controller inside a bridge operation.
4025
+ * Refuses, never fabricates: a missing controller and a controller without
4026
+ * the method both come back as `success: false, code: 'unsupported'` naming
4027
+ * the method, so neither can be read as an empty inventory. A native error
4028
+ * (bad page arguments, the graph-adapter refusal) keeps its own code.
4029
+ */
4030
+ async function withInventoryController(controllerName, method, read) {
4031
+ if (!operationContext.getStore()?.active) {
4032
+ return withBridgeOperation(() => withInventoryController(controllerName, method, read));
4033
+ }
4034
+ const registry = await getRegistry();
4035
+ if (!registry)
4036
+ return null;
4037
+ let controller;
4038
+ try {
4039
+ controller = registry.get(controllerName);
4040
+ }
4041
+ catch (e) {
4042
+ return { success: false, controller: controllerName, code: 'unsupported', error: `${controllerName} not available, so ${method} cannot run: ${e?.message ?? e}` };
4043
+ }
4044
+ if (!controller) {
4045
+ return { success: false, controller: controllerName, code: 'unsupported', error: `${controllerName} controller is not available, so ${method} cannot run` };
4046
+ }
4047
+ if (typeof controller[method] !== 'function') {
4048
+ return {
4049
+ success: false,
4050
+ controller: controllerName,
4051
+ code: 'unsupported',
4052
+ error: `the active ${controllerName} controller has no ${method}() (needs agentdb >= ${AGENTDB_INVENTORY_MIN})`,
4053
+ };
4054
+ }
4055
+ try {
4056
+ return { success: true, controller: controllerName, ...read(controller) };
4057
+ }
4058
+ catch (e) {
4059
+ return {
4060
+ success: false,
4061
+ controller: controllerName,
4062
+ ...(typeof e?.code === 'string' ? { code: e.code } : {}),
4063
+ ...(typeof e?.field === 'string' ? { field: e.field } : {}),
4064
+ error: String(e?.message ?? e),
4065
+ };
4066
+ }
4067
+ }
4068
+ /** Native list result envelope, passed through unchanged. */
4069
+ function pageOf(page) {
4070
+ return { items: page?.items, total: page?.total, limit: page?.limit, offset: page?.offset };
4071
+ }
4072
+ /** Page through ReasoningBank patterns, newest first (#4707). */
4073
+ export async function bridgeListPatterns(params) {
4074
+ return withInventoryController('reasoningBank', 'listPatterns', rb => pageOf(rb.listPatterns({ taskType: params.taskType, limit: params.limit, offset: params.offset })));
4075
+ }
4076
+ /** Page through SkillLibrary skills, newest first (#4707). */
4077
+ export async function bridgeListSkills(params) {
4078
+ return withInventoryController('skills', 'listSkills', sk => pageOf(sk.listSkills({ minSuccessRate: params.minSuccessRate, limit: params.limit, offset: params.offset })));
4079
+ }
4080
+ /** Exact read of one skill by its numeric id (#4707). */
4081
+ export async function bridgeGetSkill(params) {
4082
+ return withInventoryController('skills', 'getSkill', sk => {
4083
+ const skill = sk.getSkill(params.id);
4084
+ return { found: skill != null, skill: skill ?? null };
4085
+ });
4086
+ }
4087
+ /**
4088
+ * Count-only view of the hierarchical store (#4707). `tiers` is the
4089
+ * in-memory tier map sizes from getTierStats(); `persistedRows` is the
4090
+ * tiered_memory row count from countPersisted() (null on a volatile store).
4091
+ * They measure different things and are reported side by side.
4092
+ */
4093
+ export async function bridgeHierarchicalStats() {
4094
+ if (!operationContext.getStore()?.active)
4095
+ return withBridgeOperation(() => bridgeHierarchicalStats());
4096
+ const registry = await getRegistry();
4097
+ if (!registry)
4098
+ return null;
4099
+ let hm;
4100
+ try {
4101
+ hm = registry.get('hierarchicalMemory');
4102
+ }
4103
+ catch (e) {
4104
+ return { success: false, code: 'unsupported', error: `HierarchicalMemory not available, so getTierStats/countPersisted cannot run: ${e?.message ?? e}` };
4105
+ }
4106
+ if (!hm) {
4107
+ return { success: false, code: 'unsupported', error: 'HierarchicalMemory not available, so getTierStats/countPersisted cannot run' };
4108
+ }
4109
+ const isNative = typeof hm.getStats === 'function' && typeof hm.promote === 'function';
4110
+ const missing = ['getTierStats', 'countPersisted'].filter(m => typeof hm[m] !== 'function');
4111
+ if (isNative || missing.length > 0) {
4112
+ return {
4113
+ success: false,
4114
+ controller: isNative ? 'hierarchicalMemory' : 'tieredMemoryStore',
4115
+ code: 'unsupported',
4116
+ error: isNative
4117
+ ? 'the native agentdb HierarchicalMemory has no getTierStats()/countPersisted()'
4118
+ : `the active hierarchical store has no ${missing.join('()/')}() (the installed @claude-flow/memory predates it)`,
4119
+ };
4120
+ }
4121
+ const info = describeHierarchicalStore(hm, getHierarchicalFallback(registry));
4122
+ try {
4123
+ return { success: true, ...info, tiers: hm.getTierStats(), persistedRows: hm.countPersisted() };
4124
+ }
4125
+ catch (e) {
4126
+ return { success: false, ...info, error: String(e?.message ?? e) };
4127
+ }
4128
+ }
3890
4129
  //# sourceMappingURL=memory-bridge.js.map
@@ -172,7 +172,7 @@ export declare function flashAttentionSearch(query: Float32Array | number[], vec
172
172
  /**
173
173
  * Initial metadata to insert after schema creation
174
174
  */
175
- export declare function getInitialMetadata(backend: string): string;
175
+ export declare function getInitialMetadata(backend: string, dimension?: number): string;
176
176
  /**
177
177
  * Memory initialization result
178
178
  */
@@ -1,5 +1,6 @@
1
1
  import { loadBetterSqlite3 } from './shared-sqlite.js';
2
2
  import { resolveMemoryRoot } from './memory-root.js';
3
+ import { getProjectRoot } from '../services/project-root.js';
3
4
  import { DEFAULT_SEARCH_THRESHOLD } from './search-defaults.js';
4
5
  import { liveMemoryRowSql } from './live-memory-row.js';
5
6
  import { encodeEmbeddingQ8, MAX_LIST_EMBEDDINGS } from './embedding-q8.js';
@@ -8,6 +9,7 @@ import * as path from 'path';
8
9
  import { AsyncLocalStorage } from 'node:async_hooks';
9
10
  import { createRequire } from 'node:module';
10
11
  import { readFileMaybeEncrypted, writeDbImagePreservingFormat, writeFileRestricted } from '../fs-secure.js';
12
+ import { _resetEmbeddingConfigCache, DEFAULT_EMBEDDING_DIMENSION, resolveEffectiveEmbeddingConfig, resolveEmbeddingConfig, } from './embedding-config.js';
11
13
  import { restoreMemoryDbFromBackup } from '../services/memory-backup.js';
12
14
  import { validateIdentifier } from '../mcp-tools/validate-input.js';
13
15
  import { resolveModelCacheDir } from './model-cache-dir.js';
@@ -167,10 +169,18 @@ async function releaseOwnNativeHandle(dbPath) {
167
169
  * this file flows through it.
168
170
  *
169
171
  * Precedence (highest → lowest):
170
- * 1. CLAUDE_FLOW_MEMORY_PATH env var
171
- * 2. memory.persistPath / memory.path in claude-flow.config.json (cwd or
172
- * the directory the CLI was invoked from)
173
- * 3. Default: cwd/.swarm
172
+ * 1. CLAUDE_FLOW_MEMORY_PATH env var (a relative value resolves against
173
+ * the project root)
174
+ * 2. memory.persistPath / memory.path in claude-flow.config.json or
175
+ * .claude-flow/config.json at the project root
176
+ * 3. Default: <project root>/.swarm
177
+ *
178
+ * #2633: "project root" is the nearest ancestor of process.cwd() carrying a
179
+ * Ruflo marker (getProjectRoot: the walk the daemon uses since #2877, minus
180
+ * home / filesystem roots),
181
+ * so a shell that drifted into a subdirectory still opens the project's
182
+ * memory DB instead of silently starting a new one. With no marker it is
183
+ * process.cwd(), exactly as before.
174
184
  *
175
185
  * Cached per-process so repeated lookups are cheap; reset only by spawning
176
186
  * a fresh process (which is how config changes already propagate).
@@ -179,7 +189,7 @@ let _memoryRootCache;
179
189
  export function getMemoryRoot() {
180
190
  if (_memoryRootCache !== undefined)
181
191
  return _memoryRootCache;
182
- _memoryRootCache = resolveMemoryRoot(process.cwd());
192
+ _memoryRootCache = resolveMemoryRoot(getProjectRoot());
183
193
  return _memoryRootCache;
184
194
  }
185
195
  /** For tests + the `memory configure` flow that mutates the config at runtime. */
@@ -1149,7 +1159,7 @@ export function flashAttentionSearch(query, vectors, options = {}) {
1149
1159
  /**
1150
1160
  * Initial metadata to insert after schema creation
1151
1161
  */
1152
- export function getInitialMetadata(backend) {
1162
+ export function getInitialMetadata(backend, dimension = DEFAULT_EMBEDDING_DIMENSION) {
1153
1163
  return `
1154
1164
  INSERT OR REPLACE INTO metadata (key, value) VALUES
1155
1165
  ('schema_version', '3.0.0'),
@@ -1161,13 +1171,13 @@ INSERT OR REPLACE INTO metadata (key, value) VALUES
1161
1171
  ('temporal_decay', 'enabled'),
1162
1172
  ('hnsw_indexing', 'enabled');
1163
1173
 
1164
- -- Create default vector index configuration. Dimension matches the default
1165
- -- ONNX embedding model (Xenova/all-MiniLM-L6-v2, 384-dim); HNSW rejects
1166
- -- inserts whose dim does not match this row, so a 768 here breaks every
1167
- -- memory_store --vector and memory_search on a fresh install (#1947).
1174
+ -- Create default vector index configuration. Dimension matches the
1175
+ -- configured embedding model (#2305; default Xenova/all-MiniLM-L6-v2,
1176
+ -- 384-dim); HNSW rejects inserts whose dim does not match this row, so a
1177
+ -- mismatch here breaks every memory_store --vector and memory_search (#1947).
1168
1178
  INSERT OR IGNORE INTO vector_indexes (id, name, dimensions) VALUES
1169
- ('default', 'default', 384),
1170
- ('patterns', 'patterns', 384);
1179
+ ('default', 'default', ${dimension}),
1180
+ ('patterns', 'patterns', ${dimension});
1171
1181
  `;
1172
1182
  }
1173
1183
  /**
@@ -1765,6 +1775,8 @@ export async function initializeMemoryDatabase(options) {
1765
1775
  // Load existing database or create new
1766
1776
  if (fs.existsSync(dbPath) && force) {
1767
1777
  fs.unlinkSync(dbPath);
1778
+ // #2305: the recorded dimension of the deleted store no longer binds.
1779
+ _resetEmbeddingConfigCache();
1768
1780
  }
1769
1781
  db = new SQL.Database();
1770
1782
  usedSqlJs = true;
@@ -1779,7 +1791,7 @@ export async function initializeMemoryDatabase(options) {
1779
1791
  // Execute schema
1780
1792
  db.run(MEMORY_SCHEMA_V3);
1781
1793
  // Insert initial metadata
1782
- db.run(getInitialMetadata(backend));
1794
+ db.run(getInitialMetadata(backend, resolveEmbeddingConfig(process.cwd()).dimension));
1783
1795
  // Save to file
1784
1796
  const data = db.export();
1785
1797
  const buffer = Buffer.from(data);
@@ -1788,7 +1800,7 @@ export async function initializeMemoryDatabase(options) {
1788
1800
  db.close();
1789
1801
  // Also create schema file for reference
1790
1802
  const schemaPath = path.join(dbDir, 'schema.sql');
1791
- fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend));
1803
+ fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend, resolveEmbeddingConfig(process.cwd()).dimension));
1792
1804
  // ADR-053: Activate ControllerRegistry so controllers (ReasoningBank,
1793
1805
  // SkillLibrary, ExplainableRecall, etc.) are instantiated during init
1794
1806
  const controllerResult = await activateControllerRegistry(verbose);
@@ -1836,7 +1848,7 @@ export async function initializeMemoryDatabase(options) {
1836
1848
  else {
1837
1849
  // Fall back to schema file approach
1838
1850
  const schemaPath = path.join(dbDir, 'schema.sql');
1839
- fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend));
1851
+ fs.writeFileSync(schemaPath, MEMORY_SCHEMA_V3 + '\n' + getInitialMetadata(backend, resolveEmbeddingConfig(process.cwd()).dimension));
1840
1852
  // Create minimal valid SQLite file
1841
1853
  const sqliteHeader = Buffer.alloc(4096, 0);
1842
1854
  // SQLite format 3 header
@@ -2070,6 +2082,19 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now())
2070
2082
  // failure (e.g. EACCES on the model cache dir) may now be fixed.
2071
2083
  }
2072
2084
  let sawRetryableFailure = false;
2085
+ // #2305: honour `.claude-flow/embeddings.json` instead of always loading
2086
+ // MiniLM/384 — unless the memory store already holds vectors of another
2087
+ // dimension, in which case its recorded dimension is kept (with a warning).
2088
+ // Both stores the memory path writes vectors to are checked, in the same
2089
+ // order the bridge uses, so the local chain and the bridge agree.
2090
+ const memoryDbPath = resolveDbPath();
2091
+ const embCfg = await resolveEffectiveEmbeddingConfig({
2092
+ root: process.cwd(),
2093
+ dbPaths: [memoryDbPath, path.join(path.dirname(memoryDbPath), 'agentdb-memory.db')],
2094
+ });
2095
+ // The agentic-flow and ruvector fallbacks below bundle MiniLM only; using
2096
+ // them for any other configured dimension would mix vector sizes.
2097
+ const bundledMiniLmFits = embCfg.dimension === DEFAULT_EMBEDDING_DIMENSION;
2073
2098
  try {
2074
2099
  // ADR-094: prefer @huggingface/transformers (clears protobufjs <7.5.5
2075
2100
  // critical RCE chain), fall back to legacy @xenova/transformers.
@@ -2114,7 +2139,7 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now())
2114
2139
  // (reading 'model')" on every memory store / search call.
2115
2140
  try {
2116
2141
  if (verbose) {
2117
- console.log(`Loading ONNX embedding model via ${transformersSource} (all-MiniLM-L6-v2)...`);
2142
+ console.log(`Loading ONNX embedding model via ${transformersSource} (${embCfg.model})...`);
2118
2143
  }
2119
2144
  // ADR-454: route model downloads to a user-writable cache dir —
2120
2145
  // the package-relative default is root-owned under a system-prefix
@@ -2124,17 +2149,17 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now())
2124
2149
  const env = transformersModule?.env;
2125
2150
  if (env)
2126
2151
  env.cacheDir = cacheDir;
2127
- const embedder = await pipelineFn('feature-extraction', 'Xenova/all-MiniLM-L6-v2');
2152
+ const embedder = await pipelineFn('feature-extraction', embCfg.model);
2128
2153
  embeddingModelState = {
2129
2154
  loaded: true,
2130
2155
  model: embedder,
2131
2156
  tokenizer: null,
2132
- dimensions: 384 // MiniLM-L6 produces 384-dim vectors
2157
+ dimensions: embCfg.dimension
2133
2158
  };
2134
2159
  return {
2135
2160
  success: true,
2136
- dimensions: 384,
2137
- modelName: 'Xenova/all-MiniLM-L6-v2',
2161
+ dimensions: embCfg.dimension,
2162
+ modelName: embCfg.model,
2138
2163
  loadTime: Date.now() - startTime
2139
2164
  };
2140
2165
  }
@@ -2152,7 +2177,7 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now())
2152
2177
  }
2153
2178
  // Fallback: Check for agentic-flow ReasoningBank embeddings (v3)
2154
2179
  const reasoningBank = await import('agentic-flow/reasoningbank').catch(() => null);
2155
- if (reasoningBank?.computeEmbedding) {
2180
+ if (bundledMiniLmFits && reasoningBank?.computeEmbedding) {
2156
2181
  if (verbose) {
2157
2182
  console.log('Loading agentic-flow ReasoningBank embedding model...');
2158
2183
  }
@@ -2186,7 +2211,7 @@ async function loadLocalEmbeddingChain(verbose = false, startTime = Date.now())
2186
2211
  if (onnxEmb?.embed) {
2187
2212
  // Probe embed to trigger lazy ONNX init and verify it works
2188
2213
  const probe = await onnxEmb.embed('test');
2189
- if (probe && probe.length > 0 && (Array.isArray(probe) ? probe.some((v) => v !== 0) : true)) {
2214
+ if (probe && probe.length > 0 && probe.length === embCfg.dimension && (Array.isArray(probe) ? probe.some((v) => v !== 0) : true)) {
2190
2215
  if (verbose) {
2191
2216
  console.log(`Loading ruvector ONNX embedder (all-MiniLM-L6-v2, ${probe.length}d)...`);
2192
2217
  }
@@ -20,6 +20,7 @@
20
20
  import { existsSync, mkdirSync, readdirSync, readFileSync, writeFileSync } from 'fs';
21
21
  import { dirname, join } from 'path';
22
22
  import { createRequire } from 'module';
23
+ import { getProjectRoot } from '../services/project-root.js';
23
24
  // ============================================================================
24
25
  // Types & Constants
25
26
  // ============================================================================
@@ -48,7 +49,7 @@ const DEFAULT_CONFIG = {
48
49
  inputDim: INPUT_DIM,
49
50
  outputDim: OUTPUT_DIM,
50
51
  learningRate: 0.001,
51
- weightsPath: join(process.cwd(), '.swarm', 'lora-weights.json'),
52
+ weightsPath: join(getProjectRoot(), '.swarm', 'lora-weights.json'),
52
53
  enableDropout: true,
53
54
  dropoutProb: 0.1,
54
55
  autoSaveInterval: 50,
@@ -534,7 +535,7 @@ export class LoRAAdapter {
534
535
  * and status surfaces stay consistent.
535
536
  */
536
537
  function checkpointDirs() {
537
- return [join(process.cwd(), '.claude-flow', 'neural')];
538
+ return [join(getProjectRoot(), '.claude-flow', 'neural')];
538
539
  }
539
540
  /** Compact relative-age label. Most-significant unit only. */
540
541
  export function formatCheckpointAge(ms) {
@@ -20,7 +20,8 @@
20
20
  * @module task-embedder
21
21
  */
22
22
  /**
23
- * Compute (or fetch from cache) the 384-dim MiniLM embedding for `task`.
23
+ * Compute (or fetch from cache) the embedding for `task` with the configured
24
+ * model (`.claude-flow/embeddings.json`; default 384-dim MiniLM).
24
25
  * Returns `undefined` on any failure (missing @xenova/transformers, ONNX
25
26
  * runtime error, etc.) so callers can gracefully fall back to the
26
27
  * heuristic+bandit path. Best-effort and never throws.