neuralbrain 0.0.1 → 0.1.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 (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +3 -2
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
package/src/lib/spool.ts CHANGED
@@ -5,6 +5,8 @@ import { createHash } from 'crypto';
5
5
  import { logger } from './logger';
6
6
  import { getDefaultSpoolDir } from './brainHome';
7
7
 
8
+ export const MAX_SPOOL_ATTEMPTS = 5;
9
+
8
10
  export interface SpoolEntry {
9
11
  id: string;
10
12
  endpoint: string;
@@ -32,7 +34,7 @@ function resolveSpoolDir(): string {
32
34
  return getDefaultSpoolDir();
33
35
  }
34
36
 
35
- function getSpoolFilePath(): string {
37
+ function getSpoolFilePath(): string | null {
36
38
  const dir = resolveSpoolDir();
37
39
  if (!fs.existsSync(dir)) {
38
40
  try {
@@ -44,11 +46,74 @@ function getSpoolFilePath(): string {
44
46
  }
45
47
  } catch (err) {
46
48
  logger.error({ dir, error: err instanceof Error ? err.message : String(err) }, 'failed to create spool directory');
49
+ return null;
47
50
  }
48
51
  }
49
52
  return path.join(dir, 'spool.jsonl');
50
53
  }
51
54
 
55
+ function getLockFilePath(filePath: string): string {
56
+ return path.join(path.dirname(filePath), 'spool.lock');
57
+ }
58
+
59
+ function tryAcquireLock(lockPath: string, staleMs = 30_000): boolean {
60
+ try {
61
+ const fd = fs.openSync(lockPath, 'wx', 0o600);
62
+ fs.closeSync(fd);
63
+ return true;
64
+ } catch (err: any) {
65
+ if (err?.code !== 'EEXIST') {
66
+ return false;
67
+ }
68
+ try {
69
+ const stat = fs.statSync(lockPath);
70
+ if (Date.now() - stat.mtimeMs > staleMs) {
71
+ fs.rmSync(lockPath, { force: true });
72
+ const fd = fs.openSync(lockPath, 'wx', 0o600);
73
+ fs.closeSync(fd);
74
+ return true;
75
+ }
76
+ } catch {
77
+ // Lock was released or removed concurrently
78
+ }
79
+ return false;
80
+ }
81
+ }
82
+
83
+ function sleepSync(ms: number): void {
84
+ try {
85
+ Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, ms);
86
+ } catch {
87
+ // Fallback if SharedArrayBuffer is unavailable
88
+ }
89
+ }
90
+
91
+ function acquireSpoolLockSync(lockPath: string, timeoutMs = 500): boolean {
92
+ const deadline = Date.now() + timeoutMs;
93
+ while (Date.now() < deadline) {
94
+ if (tryAcquireLock(lockPath)) return true;
95
+ sleepSync(10);
96
+ }
97
+ return tryAcquireLock(lockPath);
98
+ }
99
+
100
+ async function acquireSpoolLockAsync(lockPath: string, timeoutMs = 2000): Promise<boolean> {
101
+ const deadline = Date.now() + timeoutMs;
102
+ while (Date.now() < deadline) {
103
+ if (tryAcquireLock(lockPath)) return true;
104
+ await new Promise((resolve) => setTimeout(resolve, 15));
105
+ }
106
+ return tryAcquireLock(lockPath);
107
+ }
108
+
109
+ function releaseSpoolLock(lockPath: string): void {
110
+ try {
111
+ fs.rmSync(lockPath, { force: true });
112
+ } catch {
113
+ // ignore
114
+ }
115
+ }
116
+
52
117
  function getMaxBytes(): number {
53
118
  const val = process.env.BRAIN_SPOOL_MAX_BYTES;
54
119
  const parsed = val ? parseInt(val, 10) : NaN;
@@ -131,6 +196,9 @@ function getActiveIds(filePath: string): Set<string> {
131
196
 
132
197
  export function readSpool(): SpoolEntry[] {
133
198
  const filePath = getSpoolFilePath();
199
+ if (!filePath) {
200
+ return [];
201
+ }
134
202
  if (!fs.existsSync(filePath)) {
135
203
  activeSpoolCache = { filePath, mtimeMs: 0, size: 0, ids: new Set() };
136
204
  return [];
@@ -153,7 +221,7 @@ export function readSpool(): SpoolEntry[] {
153
221
  for (const line of lines) {
154
222
  try {
155
223
  const entry = JSON.parse(line) as SpoolEntry;
156
- if (entry.timestamp < cutoff) {
224
+ if (entry.timestamp < cutoff || (entry.attempts ?? 0) >= MAX_SPOOL_ATTEMPTS) {
157
225
  expiredCount++;
158
226
  } else {
159
227
  validEntries.push(entry);
@@ -163,7 +231,7 @@ export function readSpool(): SpoolEntry[] {
163
231
  }
164
232
  }
165
233
 
166
- // If expired or corrupted lines were found, prune the file
234
+ // If expired, exhausted, or corrupted lines were found, prune the file
167
235
  if (expiredCount > 0) {
168
236
  writeSpoolEntries(validEntries);
169
237
  } else {
@@ -175,6 +243,9 @@ export function readSpool(): SpoolEntry[] {
175
243
 
176
244
  function writeSpoolEntries(entries: SpoolEntry[]): void {
177
245
  const filePath = getSpoolFilePath();
246
+ if (!filePath) {
247
+ return;
248
+ }
178
249
  const dir = path.dirname(filePath);
179
250
 
180
251
  if (entries.length === 0) {
@@ -203,63 +274,72 @@ function writeSpoolEntries(entries: SpoolEntry[]): void {
203
274
  export function appendSpool(endpoint: string, payload: unknown): boolean {
204
275
  const id = computeEntryId(endpoint, payload);
205
276
  const filePath = getSpoolFilePath();
206
-
207
- // Fast in-memory deduplication check (CR-14)
208
- const activeIds = getActiveIds(filePath);
209
- if (activeIds.has(id)) {
210
- logger.debug({ id, endpoint }, 'duplicate entry already in spool, skipping append');
211
- return true;
277
+ if (!filePath) {
278
+ return false;
212
279
  }
213
280
 
214
- const newEntry: SpoolEntry = {
215
- id,
216
- endpoint,
217
- payload,
218
- timestamp: Math.floor(Date.now() / 1000),
219
- attempts: 0,
220
- };
281
+ const lockPath = getLockFilePath(filePath);
282
+ const locked = acquireSpoolLockSync(lockPath);
283
+ try {
284
+ // Fast in-memory deduplication check (CR-14)
285
+ const activeIds = getActiveIds(filePath);
286
+ if (activeIds.has(id)) {
287
+ logger.debug({ id, endpoint }, 'duplicate entry already in spool, skipping append');
288
+ return true;
289
+ }
221
290
 
222
- const line = JSON.stringify(newEntry) + '\n';
223
- const lineBytes = Buffer.byteLength(line, 'utf-8');
291
+ const newEntry: SpoolEntry = {
292
+ id,
293
+ endpoint,
294
+ payload,
295
+ timestamp: Math.floor(Date.now() / 1000),
296
+ attempts: 0,
297
+ };
224
298
 
225
- let currentBytes = 0;
226
- if (fs.existsSync(filePath)) {
227
- try {
228
- currentBytes = fs.statSync(filePath).size;
229
- } catch {
230
- currentBytes = 0;
299
+ const line = JSON.stringify(newEntry) + '\n';
300
+ const lineBytes = Buffer.byteLength(line, 'utf-8');
301
+
302
+ let currentBytes = 0;
303
+ if (fs.existsSync(filePath)) {
304
+ try {
305
+ currentBytes = fs.statSync(filePath).size;
306
+ } catch {
307
+ currentBytes = 0;
308
+ }
231
309
  }
232
- }
233
310
 
234
- const maxBytes = getMaxBytes();
235
- if (currentBytes + lineBytes > maxBytes) {
236
- logger.warn({ currentBytes, lineBytes, maxBytes }, 'spool file full, rejecting write');
237
- return false;
238
- }
311
+ const maxBytes = getMaxBytes();
312
+ if (currentBytes + lineBytes > maxBytes) {
313
+ logger.warn({ currentBytes, lineBytes, maxBytes }, 'spool file full, rejecting write');
314
+ return false;
315
+ }
239
316
 
240
- fs.appendFileSync(filePath, line, { encoding: 'utf-8', mode: 0o600 });
317
+ fs.appendFileSync(filePath, line, { encoding: 'utf-8', mode: 0o600 });
241
318
 
242
- try {
243
- const stat = fs.statSync(filePath);
244
- activeIds.add(id);
245
- activeSpoolCache = {
246
- filePath,
247
- mtimeMs: stat.mtimeMs,
248
- size: stat.size,
249
- ids: activeIds,
250
- };
251
- } catch {
252
- activeIds.add(id);
253
- }
319
+ try {
320
+ const stat = fs.statSync(filePath);
321
+ activeIds.add(id);
322
+ activeSpoolCache = {
323
+ filePath,
324
+ mtimeMs: stat.mtimeMs,
325
+ size: stat.size,
326
+ ids: activeIds,
327
+ };
328
+ } catch {
329
+ activeIds.add(id);
330
+ }
254
331
 
255
- return true;
332
+ return true;
333
+ } finally {
334
+ if (locked) releaseSpoolLock(lockPath);
335
+ }
256
336
  }
257
337
 
258
338
  let flushMutex: Promise<unknown> = Promise.resolve();
259
339
 
260
340
  export function flushSpool(
261
341
  sendFn: (endpoint: string, payload: unknown) => Promise<boolean>
262
- ): Promise<{ flushed: number; remaining: number; droppedExpired: number }> {
342
+ ): Promise<{ flushed: number; remaining: number; droppedExpired: number; droppedMaxAttempts: number }> {
263
343
  const next = flushMutex.then(() => doFlushSpool(sendFn));
264
344
  flushMutex = next.catch(() => {});
265
345
  return next;
@@ -267,10 +347,10 @@ export function flushSpool(
267
347
 
268
348
  async function doFlushSpool(
269
349
  sendFn: (endpoint: string, payload: unknown) => Promise<boolean>
270
- ): Promise<{ flushed: number; remaining: number; droppedExpired: number }> {
350
+ ): Promise<{ flushed: number; remaining: number; droppedExpired: number; droppedMaxAttempts: number }> {
271
351
  const filePath = getSpoolFilePath();
272
- if (!fs.existsSync(filePath)) {
273
- return { flushed: 0, remaining: 0, droppedExpired: 0 };
352
+ if (!filePath || !fs.existsSync(filePath)) {
353
+ return { flushed: 0, remaining: 0, droppedExpired: 0, droppedMaxAttempts: 0 };
274
354
  }
275
355
 
276
356
  const rawContent = fs.readFileSync(filePath, 'utf-8');
@@ -281,12 +361,15 @@ async function doFlushSpool(
281
361
 
282
362
  const validEntries: SpoolEntry[] = [];
283
363
  let droppedExpired = 0;
364
+ let droppedMaxAttempts = 0;
284
365
 
285
366
  for (const line of rawLines) {
286
367
  try {
287
368
  const entry = JSON.parse(line) as SpoolEntry;
288
369
  if (entry.timestamp < cutoff) {
289
370
  droppedExpired++;
371
+ } else if ((entry.attempts ?? 0) >= MAX_SPOOL_ATTEMPTS) {
372
+ droppedMaxAttempts++;
290
373
  } else {
291
374
  validEntries.push(entry);
292
375
  }
@@ -306,43 +389,70 @@ async function doFlushSpool(
306
389
  if (success) {
307
390
  flushed++;
308
391
  } else {
309
- entry.attempts = (entry.attempts ?? 0) + 1;
310
- remainingEntries.push(entry);
392
+ const nextAttempts = (entry.attempts ?? 0) + 1;
393
+ if (nextAttempts < MAX_SPOOL_ATTEMPTS) {
394
+ entry.attempts = nextAttempts;
395
+ remainingEntries.push(entry);
396
+ } else {
397
+ droppedMaxAttempts++;
398
+ logger.warn(
399
+ { id: entry.id, endpoint: entry.endpoint, attempts: nextAttempts },
400
+ 'spool entry exceeded max attempts, dropping'
401
+ );
402
+ }
311
403
  }
312
404
  } catch {
313
- entry.attempts = (entry.attempts ?? 0) + 1;
314
- remainingEntries.push(entry);
405
+ const nextAttempts = (entry.attempts ?? 0) + 1;
406
+ if (nextAttempts < MAX_SPOOL_ATTEMPTS) {
407
+ entry.attempts = nextAttempts;
408
+ remainingEntries.push(entry);
409
+ } else {
410
+ droppedMaxAttempts++;
411
+ logger.warn(
412
+ { id: entry.id, endpoint: entry.endpoint, attempts: nextAttempts },
413
+ 'spool entry exceeded max attempts, dropping'
414
+ );
415
+ }
315
416
  }
316
417
  }
317
418
 
318
- // Re-read file to capture entries appended concurrently during network I/O
319
- const newlyAppended: SpoolEntry[] = [];
320
- if (fs.existsSync(filePath)) {
321
- try {
322
- const currentContent = fs.readFileSync(filePath, 'utf-8');
323
- const currentLines = currentContent.split('\n').filter((l) => l.trim().length > 0);
324
- for (const line of currentLines) {
325
- try {
326
- const entry = JSON.parse(line) as SpoolEntry;
327
- if (!snapshotIds.has(entry.id) && entry.timestamp >= cutoff) {
328
- newlyAppended.push(entry);
419
+ // Advisory lock around read-merge-rename window so concurrent hook appends aren't overwritten
420
+ const lockPath = getLockFilePath(filePath);
421
+ const locked = await acquireSpoolLockAsync(lockPath);
422
+ let finalRemaining: SpoolEntry[];
423
+ try {
424
+ // Re-read file to capture entries appended concurrently during network I/O
425
+ const newlyAppended: SpoolEntry[] = [];
426
+ if (fs.existsSync(filePath)) {
427
+ try {
428
+ const currentContent = fs.readFileSync(filePath, 'utf-8');
429
+ const currentLines = currentContent.split('\n').filter((l) => l.trim().length > 0);
430
+ for (const line of currentLines) {
431
+ try {
432
+ const entry = JSON.parse(line) as SpoolEntry;
433
+ if (!snapshotIds.has(entry.id) && entry.timestamp >= cutoff) {
434
+ newlyAppended.push(entry);
435
+ }
436
+ } catch {
437
+ // ignore corrupted lines
329
438
  }
330
- } catch {
331
- // ignore corrupted lines
332
439
  }
440
+ } catch {
441
+ // ignore read error
333
442
  }
334
- } catch {
335
- // ignore read error
336
443
  }
337
- }
338
444
 
339
- const finalRemaining = [...remainingEntries, ...newlyAppended];
340
- writeSpoolEntries(finalRemaining);
445
+ finalRemaining = [...remainingEntries, ...newlyAppended];
446
+ writeSpoolEntries(finalRemaining);
447
+ } finally {
448
+ if (locked) releaseSpoolLock(lockPath);
449
+ }
341
450
 
342
451
  return {
343
452
  flushed,
344
453
  remaining: finalRemaining.length,
345
454
  droppedExpired,
455
+ droppedMaxAttempts,
346
456
  };
347
457
  }
348
458
 
@@ -351,7 +461,7 @@ export function getSpoolStats(): SpoolStats {
351
461
  const filePath = getSpoolFilePath();
352
462
 
353
463
  let bytes = 0;
354
- if (fs.existsSync(filePath)) {
464
+ if (filePath && fs.existsSync(filePath)) {
355
465
  bytes = fs.statSync(filePath).size;
356
466
  }
357
467
 
@@ -0,0 +1,181 @@
1
+ /**
2
+ * Read-only store inspections shared by the service (`GET /diagnostics/store`)
3
+ * and by `neuralbrain doctor` when the service is stopped.
4
+ *
5
+ * Every function here takes the connection it inspects and only issues SELECTs
6
+ * and PRAGMA reads, so the doctor can run them against a `readOnly` handle
7
+ * without ever becoming a second writer (CLAUDE.md, "One Process, One
8
+ * Connection").
9
+ */
10
+ import type { Database } from './sqlite';
11
+
12
+ export interface DatabaseHealth {
13
+ ok: boolean;
14
+ journal_mode: string;
15
+ error?: string;
16
+ }
17
+
18
+ export interface SchemaAlignment {
19
+ aligned: boolean;
20
+ issues: string[];
21
+ }
22
+
23
+ export interface StoreCounts {
24
+ dead_letters: number;
25
+ unknown_scope_notes: number;
26
+ notes: number;
27
+ trajectories: number;
28
+ observations: number;
29
+ }
30
+
31
+ export function inspectDatabaseHealth(db: Database): DatabaseHealth {
32
+ try {
33
+ const row = db.prepare('SELECT 1 as val').get() as { val: number } | undefined;
34
+ const pragmaRow = db.prepare('PRAGMA journal_mode').get() as { journal_mode: string } | undefined;
35
+ const journalMode = pragmaRow?.journal_mode || 'unknown';
36
+ if (row?.val !== 1) {
37
+ return { ok: false, journal_mode: journalMode, error: 'Database query returned unexpected result' };
38
+ }
39
+ return { ok: true, journal_mode: journalMode };
40
+ } catch (err) {
41
+ return {
42
+ ok: false,
43
+ journal_mode: 'unknown',
44
+ error: err instanceof Error ? err.message : String(err),
45
+ };
46
+ }
47
+ }
48
+
49
+ /**
50
+ * Verifies the relational shape the stores depend on.
51
+ *
52
+ * `checkForeignKeys` is on for the service's own connection, where
53
+ * `PRAGMA foreign_keys` is the setting every write runs under. It is off for a
54
+ * doctor's read-only handle: the pragma is per-connection, so reading it there
55
+ * would describe the doctor's connection, not the store.
56
+ */
57
+ export function inspectSchemaAlignment(
58
+ db: Database,
59
+ options: { checkForeignKeys?: boolean } = {}
60
+ ): SchemaAlignment {
61
+ const issues: string[] = [];
62
+
63
+ if (options.checkForeignKeys !== false) {
64
+ const fkRow = db.prepare('PRAGMA foreign_keys').get() as { foreign_keys?: number } | undefined;
65
+ if (fkRow?.foreign_keys !== 1) {
66
+ issues.push('PRAGMA foreign_keys is not active');
67
+ }
68
+ }
69
+
70
+ const getTableColumns = (tableName: string): Map<string, { name: string; notnull: number; type: string }> => {
71
+ const rows = db.prepare(`PRAGMA table_info(${tableName})`).all() as Array<{
72
+ name: string;
73
+ notnull: number;
74
+ type: string;
75
+ }>;
76
+ return new Map(rows.map((r) => [r.name, r]));
77
+ };
78
+
79
+ for (const table of ['trajectories', 'trajectory_archive']) {
80
+ const cols = getTableColumns(table);
81
+ if (cols.size === 0) {
82
+ issues.push(`table ${table} does not exist`);
83
+ continue;
84
+ }
85
+ const successCol = cols.get('success');
86
+ if (!successCol) issues.push(`${table}.success missing`);
87
+ else if (successCol.notnull !== 0) issues.push(`${table}.success is not nullable (notnull=1)`);
88
+
89
+ const projCol = cols.get('project_id');
90
+ if (!projCol) issues.push(`${table}.project_id missing`);
91
+ else if (projCol.notnull !== 0) issues.push(`${table}.project_id is not nullable (notnull=1)`);
92
+
93
+ for (const col of ['session_id', 'rollup_source', 'tool_calls']) {
94
+ if (!cols.has(col)) issues.push(`${table}.${col} missing`);
95
+ }
96
+ }
97
+
98
+ for (const table of ['observations', 'observations_archive']) {
99
+ const cols = getTableColumns(table);
100
+ if (cols.size === 0) {
101
+ issues.push(`table ${table} does not exist`);
102
+ continue;
103
+ }
104
+ const projCol = cols.get('project_id');
105
+ if (!projCol) issues.push(`${table}.project_id missing`);
106
+ else if (projCol.notnull !== 0) issues.push(`${table}.project_id is not nullable (notnull=1)`);
107
+
108
+ for (const col of ['event_at', 'condensed_text', 'resolved_dates_json', 'signal_tags']) {
109
+ if (!cols.has(col)) issues.push(`${table}.${col} missing`);
110
+ }
111
+ }
112
+
113
+ for (const table of ['entities', 'entity_edges']) {
114
+ if (getTableColumns(table).size === 0) {
115
+ issues.push(`table ${table} does not exist`);
116
+ }
117
+ }
118
+
119
+ const requiredFtsTables = [
120
+ 'fts_notes',
121
+ 'fts_trajectories',
122
+ 'fts_observations',
123
+ 'fts_summaries',
124
+ 'fts_entities',
125
+ 'fts_actions',
126
+ ];
127
+ const ftsRows = db
128
+ .prepare(
129
+ "SELECT name, sql FROM sqlite_master WHERE type = 'table' AND name IN ('fts_notes', 'fts_trajectories', 'fts_observations', 'fts_summaries', 'fts_entities', 'fts_actions')"
130
+ )
131
+ .all() as Array<{ name: string; sql?: string }>;
132
+ const ftsMap = new Map(ftsRows.map((r) => [r.name, r.sql || '']));
133
+ for (const ftsName of requiredFtsTables) {
134
+ if (!ftsMap.has(ftsName)) {
135
+ issues.push(`FTS5 table ${ftsName} does not exist`);
136
+ }
137
+ }
138
+ const ftsObsSql = ftsMap.get('fts_observations');
139
+ if (ftsObsSql !== undefined && !ftsObsSql.includes('condensed_text')) {
140
+ issues.push('fts_observations.condensed_text missing');
141
+ }
142
+
143
+ const actionCols = getTableColumns('actions');
144
+ if (actionCols.size === 0) {
145
+ issues.push('table actions does not exist');
146
+ } else {
147
+ for (const col of ['due_at', 'remind_at', 'recurrence', 'last_reminded_at', 'snooze_until', 'user_id']) {
148
+ if (!actionCols.has(col)) issues.push(`actions.${col} missing`);
149
+ }
150
+ }
151
+
152
+ const noteCols = getTableColumns('notes');
153
+ if (noteCols.size === 0) {
154
+ issues.push('table notes does not exist');
155
+ } else {
156
+ for (const col of ['event_at', 'valid_from', 'valid_until', 'user_id']) {
157
+ if (!noteCols.has(col)) issues.push(`notes.${col} missing`);
158
+ }
159
+ }
160
+
161
+ return { aligned: issues.length === 0, issues };
162
+ }
163
+
164
+ /** Row counts for the doctor's operational metrics. A missing table counts as 0. */
165
+ export function countStoreRecords(db: Database): StoreCounts {
166
+ const count = (sql: string): number => {
167
+ try {
168
+ const row = db.prepare(sql).get() as { count: number } | undefined;
169
+ return Number(row?.count ?? 0);
170
+ } catch {
171
+ return 0;
172
+ }
173
+ };
174
+ return {
175
+ dead_letters: count('SELECT COUNT(*) as count FROM dead_letters'),
176
+ unknown_scope_notes: count("SELECT COUNT(*) as count FROM notes WHERE scope = 'unknown'"),
177
+ notes: count('SELECT COUNT(*) as count FROM notes'),
178
+ trajectories: count('SELECT COUNT(*) as count FROM trajectories'),
179
+ observations: count('SELECT COUNT(*) as count FROM observations'),
180
+ };
181
+ }