claude-flow 3.74.1 → 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 (91) 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
@@ -0,0 +1,250 @@
1
+ /**
2
+ * embedding-config.ts — one place that decides which embedding model the
3
+ * memory path loads and what dimension its vectors have (#2305).
4
+ *
5
+ * `embeddings init` (commands/embeddings.ts) and the `embeddings_init` MCP
6
+ * tool write `<project>/.claude-flow/embeddings.json` with `{ model,
7
+ * dimension, ... }`. Before this module only those two files read it: the
8
+ * memory path, the AgentDB bridge and the router's task embedder all loaded
9
+ * 'Xenova/all-MiniLM-L6-v2' and assumed 384 dimensions regardless of what the
10
+ * user configured.
11
+ *
12
+ * Precedence: `.claude-flow/embeddings.json` → defaults (MiniLM / 384). There
13
+ * is no embedding-model environment override in this codebase today, so none
14
+ * is invented here.
15
+ *
16
+ * Safety: a store that already holds vectors keeps its recorded dimension.
17
+ * When the configured dimension differs, `resolveEffectiveEmbeddingConfig()`
18
+ * returns the recorded shape and warns once — it never mixes dimensions in one
19
+ * store and never rebuilds or rewrites existing vectors.
20
+ */
21
+ import * as fs from 'node:fs';
22
+ import * as path from 'node:path';
23
+ import { readFileMaybeEncrypted } from '../fs-secure.js';
24
+ import { resolveAgentdbBetterSqlite3 } from './shared-sqlite.js';
25
+ export const DEFAULT_EMBEDDING_MODEL = 'Xenova/all-MiniLM-L6-v2';
26
+ export const DEFAULT_EMBEDDING_DIMENSION = 384;
27
+ /** Same directory + file name commands/embeddings.ts and embeddings-tools.ts write. */
28
+ export const EMBEDDINGS_CONFIG_DIR = '.claude-flow';
29
+ export const EMBEDDINGS_CONFIG_FILE = 'embeddings.json';
30
+ /** Output dimension of models the CLI offers (`embeddings init`, `init --embedding-model`). */
31
+ const KNOWN_MODELS = [
32
+ { id: DEFAULT_EMBEDDING_MODEL, dimension: DEFAULT_EMBEDDING_DIMENSION },
33
+ { id: 'Xenova/all-mpnet-base-v2', dimension: 768 },
34
+ { id: 'Xenova/bge-small-en-v1.5', dimension: 384 },
35
+ ];
36
+ const configCache = new Map();
37
+ const effectiveCache = new Map();
38
+ const warned = new Set();
39
+ function warnOnce(key, message) {
40
+ if (warned.has(key))
41
+ return;
42
+ warned.add(key);
43
+ console.warn(message);
44
+ }
45
+ function knownDimension(model) {
46
+ const base = model.split('/').pop()?.toLowerCase() ?? '';
47
+ return KNOWN_MODELS.find((m) => m.id.split('/').pop().toLowerCase() === base)?.dimension;
48
+ }
49
+ /**
50
+ * `embeddings init` records the bare name it was given (default
51
+ * `all-MiniLM-L6-v2`), while the MCP tool records `Xenova/...`. The
52
+ * transformers pipeline needs the namespaced id, so bare names get `Xenova/`.
53
+ */
54
+ export function normalizeEmbeddingModel(model) {
55
+ const trimmed = model.trim();
56
+ return trimmed.includes('/') ? trimmed : `Xenova/${trimmed}`;
57
+ }
58
+ function defaults(configPath) {
59
+ return {
60
+ model: DEFAULT_EMBEDDING_MODEL,
61
+ dimension: DEFAULT_EMBEDDING_DIMENSION,
62
+ source: 'default',
63
+ configPath,
64
+ };
65
+ }
66
+ function isPositiveInt(v) {
67
+ return typeof v === 'number' && Number.isInteger(v) && v > 0;
68
+ }
69
+ function readConfigFile(configPath) {
70
+ if (!fs.existsSync(configPath))
71
+ return defaults(configPath);
72
+ let parsed;
73
+ try {
74
+ parsed = JSON.parse(fs.readFileSync(configPath, 'utf-8'));
75
+ }
76
+ catch (err) {
77
+ warnOnce(`malformed:${configPath}`, `[embeddings] ${configPath} is not valid JSON (${err instanceof Error ? err.message : String(err)}); ` +
78
+ `using the default embedding model ${DEFAULT_EMBEDDING_MODEL} (${DEFAULT_EMBEDDING_DIMENSION}-dim).`);
79
+ return defaults(configPath);
80
+ }
81
+ const obj = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
82
+ ? parsed
83
+ : null;
84
+ const rawModel = obj && typeof obj.model === 'string' && obj.model.trim() ? obj.model : null;
85
+ if (!rawModel) {
86
+ warnOnce(`nomodel:${configPath}`, `[embeddings] ${configPath} has no "model" string; ` +
87
+ `using the default embedding model ${DEFAULT_EMBEDDING_MODEL} (${DEFAULT_EMBEDDING_DIMENSION}-dim).`);
88
+ return defaults(configPath);
89
+ }
90
+ const model = normalizeEmbeddingModel(rawModel);
91
+ const dimension = isPositiveInt(obj.dimension) ? obj.dimension : knownDimension(model);
92
+ if (dimension === undefined) {
93
+ warnOnce(`nodim:${configPath}`, `[embeddings] ${configPath} sets model "${rawModel}" without a valid "dimension", and its ` +
94
+ `dimension is not known; using the default embedding model ${DEFAULT_EMBEDDING_MODEL} ` +
95
+ `(${DEFAULT_EMBEDDING_DIMENSION}-dim).`);
96
+ return defaults(configPath);
97
+ }
98
+ return { model, dimension, source: 'config', configPath };
99
+ }
100
+ /**
101
+ * Resolve the configured embedding model + dimension for a project root
102
+ * (default: cwd, which is where `embeddings init` writes its config).
103
+ * Cached per root; never throws.
104
+ */
105
+ export function resolveEmbeddingConfig(root = process.cwd()) {
106
+ const configPath = path.join(path.resolve(root), EMBEDDINGS_CONFIG_DIR, EMBEDDINGS_CONFIG_FILE);
107
+ const cached = configCache.get(configPath);
108
+ if (cached)
109
+ return cached;
110
+ const resolved = readConfigFile(configPath);
111
+ configCache.set(configPath, resolved);
112
+ return resolved;
113
+ }
114
+ /** Pick a model that produces `dimension`-dim vectors, preferring what the store recorded. */
115
+ function modelForRecorded(recorded, configured) {
116
+ const recordedModel = recorded.model ? normalizeEmbeddingModel(recorded.model) : null;
117
+ if (recordedModel && knownDimension(recordedModel) === recorded.dimension)
118
+ return recordedModel;
119
+ // KNOWN_MODELS lists the default first, so a 384-dim store maps to MiniLM.
120
+ const known = KNOWN_MODELS.find((m) => m.dimension === recorded.dimension);
121
+ return known?.id ?? recordedModel ?? configured.model;
122
+ }
123
+ /**
124
+ * Keep an existing store's recorded dimension when it differs from the
125
+ * configured one. Warns once per store; returns the configured value
126
+ * untouched when there is nothing recorded or the dimensions agree.
127
+ */
128
+ export function reconcileWithRecordedShape(configured, recorded, storeLabel) {
129
+ if (!recorded || !isPositiveInt(recorded.dimension) || recorded.dimension === configured.dimension) {
130
+ return configured;
131
+ }
132
+ const model = modelForRecorded(recorded, configured);
133
+ warnOnce(`mismatch:${storeLabel}`, `[embeddings] ${storeLabel} already holds ${recorded.dimension}-dim vectors, but the configured ` +
134
+ `embedding model ${configured.model} produces ${configured.dimension}-dim vectors ` +
135
+ `(${configured.configPath}). Keeping ${recorded.dimension} dimensions (${model}) for this store so ` +
136
+ `vectors are not mixed; nothing was rebuilt. To switch models, start a new memory store.`);
137
+ return { model, dimension: recorded.dimension, source: 'recorded', configPath: configured.configPath };
138
+ }
139
+ /** The most recently written real (non-hash) vector. */
140
+ const RECORDED_SHAPE_SQL = `
141
+ SELECT embedding_dimensions, embedding_model FROM memory_entries
142
+ WHERE embedding IS NOT NULL AND embedding_dimensions > 0
143
+ AND COALESCE(embedding_model, '') NOT LIKE '%hash%'
144
+ ORDER BY rowid DESC LIMIT 1
145
+ `;
146
+ function toShape(dim, model) {
147
+ const dimension = Number(dim);
148
+ if (!isPositiveInt(dimension))
149
+ return null;
150
+ return { dimension, model: model == null ? null : String(model) };
151
+ }
152
+ /**
153
+ * Readonly native open: cheap, no whole-file load. Uses the better-sqlite3
154
+ * copy AgentDB uses (#3693), so closing it cannot strip AgentDB's WAL.
155
+ * Fails (→ sql.js) on an encrypted file or when no native driver exists.
156
+ */
157
+ function readShapeNative(dbPath) {
158
+ const Database = resolveAgentdbBetterSqlite3();
159
+ if (!Database)
160
+ return { ok: false };
161
+ let db;
162
+ try {
163
+ db = new Database(dbPath, { readonly: true, fileMustExist: true });
164
+ const row = db.prepare(RECORDED_SHAPE_SQL).get();
165
+ return { ok: true, shape: row ? toShape(row.embedding_dimensions, row.embedding_model) : null };
166
+ }
167
+ catch {
168
+ return { ok: false };
169
+ }
170
+ finally {
171
+ try {
172
+ db?.close();
173
+ }
174
+ catch { /* best-effort */ }
175
+ }
176
+ }
177
+ async function readShapeSqlJs(dbPath) {
178
+ const initSqlJs = (await import('sql.js')).default;
179
+ const SQL = await initSqlJs();
180
+ const db = new SQL.Database(readFileMaybeEncrypted(dbPath, null));
181
+ try {
182
+ const row = db.exec(RECORDED_SHAPE_SQL)[0]?.values?.[0];
183
+ return row ? toShape(row[0], row[1]) : null;
184
+ }
185
+ finally {
186
+ db.close();
187
+ }
188
+ }
189
+ /**
190
+ * Default reader: the most recently written real (non-hash) vector in
191
+ * `memory_entries`. A store with no such vector records nothing, so a fresh
192
+ * or empty database follows the configuration.
193
+ */
194
+ export const readRecordedEmbeddingShape = async (dbPath) => {
195
+ if (dbPath === ':memory:' || !fs.existsSync(dbPath))
196
+ return null;
197
+ const native = readShapeNative(dbPath);
198
+ if (native.ok)
199
+ return native.shape;
200
+ try {
201
+ return await readShapeSqlJs(dbPath);
202
+ }
203
+ catch {
204
+ // Unreadable / legacy schema — nothing recorded we can trust.
205
+ return null;
206
+ }
207
+ };
208
+ /**
209
+ * The embedding config to actually use: the configured model, unless one of
210
+ * the stores in `dbPaths` already holds vectors of another dimension. The
211
+ * memory path writes the same vectors to memory.db and (through the AgentDB
212
+ * bridge) agentdb-memory.db, so callers pass both and every caller converges
213
+ * on one answer: the first store with recorded vectors wins. Cached per
214
+ * (root, dbPaths).
215
+ */
216
+ export function resolveEffectiveEmbeddingConfig(options = {}) {
217
+ const root = path.resolve(options.root ?? process.cwd());
218
+ const dbPaths = (options.dbPaths ?? [])
219
+ .filter((p) => typeof p === 'string' && p.length > 0 && p !== ':memory:')
220
+ .map((p) => path.resolve(p));
221
+ const key = `${root}\0${dbPaths.join('\0')}`;
222
+ const cached = effectiveCache.get(key);
223
+ if (cached)
224
+ return cached;
225
+ const configured = resolveEmbeddingConfig(root);
226
+ const reader = options.readRecordedShape ?? readRecordedEmbeddingShape;
227
+ const pending = (async () => {
228
+ for (const dbPath of dbPaths) {
229
+ let recorded = null;
230
+ try {
231
+ recorded = await reader(dbPath);
232
+ }
233
+ catch {
234
+ recorded = null;
235
+ }
236
+ if (recorded)
237
+ return reconcileWithRecordedShape(configured, recorded, dbPath);
238
+ }
239
+ return configured;
240
+ })();
241
+ effectiveCache.set(key, pending);
242
+ return pending;
243
+ }
244
+ /** Test seam: forget cached resolutions and emitted warnings. */
245
+ export function _resetEmbeddingConfigCache() {
246
+ configCache.clear();
247
+ effectiveCache.clear();
248
+ warned.clear();
249
+ }
250
+ //# sourceMappingURL=embedding-config.js.map
@@ -32,6 +32,7 @@
32
32
  */
33
33
  import * as fs from 'fs';
34
34
  import * as path from 'path';
35
+ import { getProjectRoot } from '../services/project-root.js';
35
36
  // ============================================================================
36
37
  // Default Configuration
37
38
  // ============================================================================
@@ -40,7 +41,7 @@ const DEFAULT_EWC_CONFIG = {
40
41
  maxPatterns: 1000,
41
42
  fisherDecayRate: 0.01,
42
43
  importanceThreshold: 0.3,
43
- storagePath: path.join(process.cwd(), '.swarm', 'ewc-fisher.json'),
44
+ storagePath: path.join(getProjectRoot(), '.swarm', 'ewc-fisher.json'),
44
45
  onlineMode: true,
45
46
  dimensions: 384
46
47
  };
@@ -158,6 +158,10 @@ declare class LocalReasoningBank {
158
158
  private deletedIds;
159
159
  /** A local clear() must remove disk entries too. */
160
160
  private clearRequested;
161
+ /** Message of the most recent failed flush; null after a successful one (#4880). */
162
+ private lastFlushError;
163
+ /** Time (ms epoch) of the most recent flush attempt that had something to write. */
164
+ private lastFlushAt;
161
165
  constructor(options: {
162
166
  maxSize: number;
163
167
  persistence?: boolean;
@@ -179,8 +183,22 @@ declare class LocalReasoningBank {
179
183
  * patterns this process changed, so a long-lived daemon cannot erase patterns
180
184
  * written by another hook/process (#4735). Deletions and clear() are carried
181
185
  * as tombstones; the write itself is temp-file + rename.
186
+ *
187
+ * Returns true when the patterns are on disk (or there was nothing to
188
+ * write) and false when the write failed. A failed flush leaves the bank
189
+ * dirty so the next flush retries, and records the error for
190
+ * getPersistenceStatus() (#4880). Never throws: the debounce timer and exit
191
+ * paths rely on that.
182
192
  */
183
- flushToDisk(): void;
193
+ flushToDisk(): boolean;
194
+ /**
195
+ * Read-only view of the persistence state (#4880).
196
+ */
197
+ getFlushState(): {
198
+ dirty: boolean;
199
+ lastFlushError: string | null;
200
+ lastFlushAt: number | null;
201
+ };
184
202
  /**
185
203
  * Store a pattern - O(1)
186
204
  * Deduplicates by content: if a pattern with the same content already
@@ -393,8 +411,10 @@ export declare function getPatternsByType(type: string): Promise<Pattern[]>;
393
411
  /**
394
412
  * Flush patterns to disk immediately
395
413
  * Call this at the end of training to ensure all patterns are saved
414
+ *
415
+ * @returns false when the patterns could not be written (#4880)
396
416
  */
397
- export declare function flushPatterns(): void;
417
+ export declare function flushPatterns(): boolean;
398
418
  /**
399
419
  * Compact patterns by removing duplicates/similar patterns
400
420
  * @param threshold Similarity threshold (0-1), patterns above this are considered duplicates
@@ -431,6 +451,12 @@ export declare function getPersistenceStatus(): {
431
451
  statsFile: string;
432
452
  patternsExist: boolean;
433
453
  statsExist: boolean;
454
+ /** Patterns changed in memory that are not on disk yet (#4880). */
455
+ dirty: boolean;
456
+ /** Error from the most recent failed pattern flush; null after a success. */
457
+ lastFlushError: string | null;
458
+ /** Time (ms epoch) of the most recent pattern flush attempt. */
459
+ lastFlushAt: number | null;
434
460
  };
435
461
  export {};
436
462
  //# sourceMappingURL=intelligence.d.ts.map
@@ -343,6 +343,10 @@ class LocalReasoningBank {
343
343
  deletedIds = new Set();
344
344
  /** A local clear() must remove disk entries too. */
345
345
  clearRequested = false;
346
+ /** Message of the most recent failed flush; null after a successful one (#4880). */
347
+ lastFlushError = null;
348
+ /** Time (ms epoch) of the most recent flush attempt that had something to write. */
349
+ lastFlushAt = null;
346
350
  constructor(options) {
347
351
  this.maxSize = options.maxSize;
348
352
  this.persistenceEnabled = options.persistence !== false;
@@ -442,10 +446,17 @@ class LocalReasoningBank {
442
446
  * patterns this process changed, so a long-lived daemon cannot erase patterns
443
447
  * written by another hook/process (#4735). Deletions and clear() are carried
444
448
  * as tombstones; the write itself is temp-file + rename.
449
+ *
450
+ * Returns true when the patterns are on disk (or there was nothing to
451
+ * write) and false when the write failed. A failed flush leaves the bank
452
+ * dirty so the next flush retries, and records the error for
453
+ * getPersistenceStatus() (#4880). Never throws: the debounce timer and exit
454
+ * paths rely on that.
445
455
  */
446
456
  flushToDisk() {
447
457
  if (!this.persistenceEnabled || !this.dirty)
448
- return;
458
+ return true;
459
+ this.lastFlushAt = Date.now();
449
460
  try {
450
461
  ensureDataDir();
451
462
  const path = getPatternsPath();
@@ -495,8 +506,20 @@ class LocalReasoningBank {
495
506
  }
496
507
  catch (error) {
497
508
  // Log but don't throw - persistence failures shouldn't break training.
509
+ this.lastFlushError = error instanceof Error ? error.message : String(error);
498
510
  console.error('Failed to persist patterns:', error);
499
511
  }
512
+ // `dirty` is cleared only after the rename succeeded, so any path that did
513
+ // not complete the write reads as a failure here.
514
+ if (!this.dirty)
515
+ this.lastFlushError = null;
516
+ return !this.dirty;
517
+ }
518
+ /**
519
+ * Read-only view of the persistence state (#4880).
520
+ */
521
+ getFlushState() {
522
+ return { dirty: this.dirty, lastFlushError: this.lastFlushError, lastFlushAt: this.lastFlushAt };
500
523
  }
501
524
  /**
502
525
  * Store a pattern - O(1)
@@ -1158,9 +1181,11 @@ export async function recordTrajectory(steps, verdict) {
1158
1181
  // #4283: the bank's own save is debounced, and the one-shot bins exit as
1159
1182
  // soon as the command resolves, so write the patterns now. Otherwise
1160
1183
  // stats.json counts patterns that never reach patterns.json.
1161
- reasoningBank?.flushToDisk();
1184
+ // #4880: a failed write (e.g. ENOSPC) returns false instead of claiming
1185
+ // success for patterns that exist only in memory.
1186
+ const persisted = reasoningBank ? reasoningBank.flushToDisk() : true;
1162
1187
  savePersistedStats();
1163
- return true;
1188
+ return persisted;
1164
1189
  }
1165
1190
  catch {
1166
1191
  return false;
@@ -1429,12 +1454,13 @@ export async function getPatternsByType(type) {
1429
1454
  /**
1430
1455
  * Flush patterns to disk immediately
1431
1456
  * Call this at the end of training to ensure all patterns are saved
1457
+ *
1458
+ * @returns false when the patterns could not be written (#4880)
1432
1459
  */
1433
1460
  export function flushPatterns() {
1434
- if (reasoningBank) {
1435
- reasoningBank.flushToDisk();
1436
- }
1461
+ const persisted = reasoningBank ? reasoningBank.flushToDisk() : true;
1437
1462
  savePersistedStats();
1463
+ return persisted;
1438
1464
  }
1439
1465
  /**
1440
1466
  * Compact patterns by removing duplicates/similar patterns
@@ -1537,13 +1563,17 @@ export function getPersistenceStatus() {
1537
1563
  const dataDir = getDataDir();
1538
1564
  const patternsFile = getPatternsPath();
1539
1565
  const statsFile = getStatsPath();
1566
+ const flush = reasoningBank
1567
+ ? reasoningBank.getFlushState()
1568
+ : { dirty: false, lastFlushError: null, lastFlushAt: null };
1540
1569
  return {
1541
1570
  enabled: true,
1542
1571
  dataDir,
1543
1572
  patternsFile,
1544
1573
  statsFile,
1545
1574
  patternsExist: existsSync(patternsFile),
1546
- statsExist: existsSync(statsFile)
1575
+ statsExist: existsSync(statsFile),
1576
+ ...flush,
1547
1577
  };
1548
1578
  }
1549
1579
  //# sourceMappingURL=intelligence.js.map
@@ -392,6 +392,12 @@ export declare function bridgeStorePattern(options: {
392
392
  } | null>;
393
393
  /**
394
394
  * Search patterns via ReasoningBank controller.
395
+ *
396
+ * Returns null when no registry is available. With `controller:
397
+ * 'reasoningBank'`, an empty `results` and no `error` means the controller
398
+ * ran and found nothing. #4714: when the controller throws, returns a
399
+ * non-array, or the substring scan fails, the result carries `error` so the
400
+ * caller cannot mistake the failure for a no-match.
395
401
  */
396
402
  export declare function bridgeSearchPatterns(options: {
397
403
  query: string;
@@ -405,6 +411,7 @@ export declare function bridgeSearchPatterns(options: {
405
411
  score: number;
406
412
  }>;
407
413
  controller: string;
414
+ error?: string;
408
415
  } | null>;
409
416
  /**
410
417
  * Record task feedback for learning via ReasoningBank or LearningSystem.
@@ -758,4 +765,39 @@ export declare function getMemoryBridgeStats(options?: {
758
765
  source: string;
759
766
  reachable: boolean;
760
767
  }>;
768
+ /** Page through every persisted hierarchical-memory entry (#4712). */
769
+ export declare function bridgeHierarchicalList(params: {
770
+ tier?: string;
771
+ status?: string;
772
+ limit?: number;
773
+ cursor?: string;
774
+ }): Promise<any>;
775
+ /** Exact read of one hierarchical-memory entry by its stable id (#4712). */
776
+ export declare function bridgeHierarchicalGet(params: {
777
+ id: string;
778
+ includeInactive?: boolean;
779
+ }): Promise<any>;
780
+ /** Page through ReasoningBank patterns, newest first (#4707). */
781
+ export declare function bridgeListPatterns(params: {
782
+ taskType?: string;
783
+ limit?: number;
784
+ offset?: number;
785
+ }): Promise<any>;
786
+ /** Page through SkillLibrary skills, newest first (#4707). */
787
+ export declare function bridgeListSkills(params: {
788
+ minSuccessRate?: number;
789
+ limit?: number;
790
+ offset?: number;
791
+ }): Promise<any>;
792
+ /** Exact read of one skill by its numeric id (#4707). */
793
+ export declare function bridgeGetSkill(params: {
794
+ id: number;
795
+ }): Promise<any>;
796
+ /**
797
+ * Count-only view of the hierarchical store (#4707). `tiers` is the
798
+ * in-memory tier map sizes from getTierStats(); `persistedRows` is the
799
+ * tiered_memory row count from countPersisted() (null on a volatile store).
800
+ * They measure different things and are reported side by side.
801
+ */
802
+ export declare function bridgeHierarchicalStats(): Promise<any>;
761
803
  //# sourceMappingURL=memory-bridge.d.ts.map