neuralbrain 0.0.0-stage → 0.0.2

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 (293) hide show
  1. package/.dockerignore +11 -0
  2. package/.env.example +245 -0
  3. package/Dockerfile +65 -0
  4. package/LICENSE +44 -0
  5. package/README.md +312 -2
  6. package/dist/ai/chat.d.ts +45 -0
  7. package/dist/ai/chat.d.ts.map +1 -0
  8. package/dist/ai/chat.js +153 -0
  9. package/dist/ai/chat.js.map +1 -0
  10. package/dist/ai/circuitBreaker.d.ts +35 -0
  11. package/dist/ai/circuitBreaker.d.ts.map +1 -0
  12. package/dist/ai/circuitBreaker.js +95 -0
  13. package/dist/ai/circuitBreaker.js.map +1 -0
  14. package/dist/ai/config.d.ts +88 -0
  15. package/dist/ai/config.d.ts.map +1 -0
  16. package/dist/ai/config.js +255 -0
  17. package/dist/ai/config.js.map +1 -0
  18. package/dist/ai/vendors.d.ts +58 -0
  19. package/dist/ai/vendors.d.ts.map +1 -0
  20. package/dist/ai/vendors.js +223 -0
  21. package/dist/ai/vendors.js.map +1 -0
  22. package/dist/app.d.ts +4 -0
  23. package/dist/app.d.ts.map +1 -0
  24. package/dist/app.js +1013 -0
  25. package/dist/app.js.map +1 -0
  26. package/dist/cli.d.ts +133 -0
  27. package/dist/cli.d.ts.map +1 -0
  28. package/dist/cli.js +912 -0
  29. package/dist/cli.js.map +1 -0
  30. package/dist/consolidation/candidates.d.ts +34 -0
  31. package/dist/consolidation/candidates.d.ts.map +1 -0
  32. package/dist/consolidation/candidates.js +150 -0
  33. package/dist/consolidation/candidates.js.map +1 -0
  34. package/dist/consolidation/fixtures.d.ts +25 -0
  35. package/dist/consolidation/fixtures.d.ts.map +1 -0
  36. package/dist/consolidation/fixtures.js +400 -0
  37. package/dist/consolidation/fixtures.js.map +1 -0
  38. package/dist/consolidation/gate.d.ts +39 -0
  39. package/dist/consolidation/gate.d.ts.map +1 -0
  40. package/dist/consolidation/gate.js +286 -0
  41. package/dist/consolidation/gate.js.map +1 -0
  42. package/dist/consolidation/runner.d.ts +63 -0
  43. package/dist/consolidation/runner.d.ts.map +1 -0
  44. package/dist/consolidation/runner.js +171 -0
  45. package/dist/consolidation/runner.js.map +1 -0
  46. package/dist/dashboard/clientScript.d.ts +2 -0
  47. package/dist/dashboard/clientScript.d.ts.map +1 -0
  48. package/dist/dashboard/clientScript.js +4212 -0
  49. package/dist/dashboard/clientScript.js.map +1 -0
  50. package/dist/dashboard/html.d.ts +2 -0
  51. package/dist/dashboard/html.d.ts.map +1 -0
  52. package/dist/dashboard/html.js +554 -0
  53. package/dist/dashboard/html.js.map +1 -0
  54. package/dist/dashboard/styles.d.ts +2 -0
  55. package/dist/dashboard/styles.d.ts.map +1 -0
  56. package/dist/dashboard/styles.js +1283 -0
  57. package/dist/dashboard/styles.js.map +1 -0
  58. package/dist/index.d.ts +3 -0
  59. package/dist/index.d.ts.map +1 -0
  60. package/dist/index.js +124 -0
  61. package/dist/index.js.map +1 -0
  62. package/dist/learning/embedWorker.d.ts +58 -0
  63. package/dist/learning/embedWorker.d.ts.map +1 -0
  64. package/dist/learning/embedWorker.js +552 -0
  65. package/dist/learning/embedWorker.js.map +1 -0
  66. package/dist/learning/embedding.d.ts +52 -0
  67. package/dist/learning/embedding.d.ts.map +1 -0
  68. package/dist/learning/embedding.js +511 -0
  69. package/dist/learning/embedding.js.map +1 -0
  70. package/dist/learning/engine.d.ts +20 -0
  71. package/dist/learning/engine.d.ts.map +1 -0
  72. package/dist/learning/engine.js +69 -0
  73. package/dist/learning/engine.js.map +1 -0
  74. package/dist/learning/search.d.ts +4 -0
  75. package/dist/learning/search.d.ts.map +1 -0
  76. package/dist/learning/search.js +509 -0
  77. package/dist/learning/search.js.map +1 -0
  78. package/dist/learning/storeMeta.d.ts +11 -0
  79. package/dist/learning/storeMeta.d.ts.map +1 -0
  80. package/dist/learning/storeMeta.js +100 -0
  81. package/dist/learning/storeMeta.js.map +1 -0
  82. package/dist/learning/types.d.ts +101 -0
  83. package/dist/learning/types.d.ts.map +1 -0
  84. package/dist/learning/types.js +3 -0
  85. package/dist/learning/types.js.map +1 -0
  86. package/dist/lib/brainHome.d.ts +28 -0
  87. package/dist/lib/brainHome.d.ts.map +1 -0
  88. package/dist/lib/brainHome.js +104 -0
  89. package/dist/lib/brainHome.js.map +1 -0
  90. package/dist/lib/db.d.ts +10 -0
  91. package/dist/lib/db.d.ts.map +1 -0
  92. package/dist/lib/db.js +589 -0
  93. package/dist/lib/db.js.map +1 -0
  94. package/dist/lib/logger.d.ts +3 -0
  95. package/dist/lib/logger.d.ts.map +1 -0
  96. package/dist/lib/logger.js +11 -0
  97. package/dist/lib/logger.js.map +1 -0
  98. package/dist/lib/projectSlug.d.ts +61 -0
  99. package/dist/lib/projectSlug.d.ts.map +1 -0
  100. package/dist/lib/projectSlug.js +273 -0
  101. package/dist/lib/projectSlug.js.map +1 -0
  102. package/dist/lib/redactSecrets.d.ts +7 -0
  103. package/dist/lib/redactSecrets.d.ts.map +1 -0
  104. package/dist/lib/redactSecrets.js +90 -0
  105. package/dist/lib/redactSecrets.js.map +1 -0
  106. package/dist/lib/scope.d.ts +54 -0
  107. package/dist/lib/scope.d.ts.map +1 -0
  108. package/dist/lib/scope.js +103 -0
  109. package/dist/lib/scope.js.map +1 -0
  110. package/dist/lib/spool.d.ts +23 -0
  111. package/dist/lib/spool.d.ts.map +1 -0
  112. package/dist/lib/spool.js +317 -0
  113. package/dist/lib/spool.js.map +1 -0
  114. package/dist/lib/sqlite.d.ts +50 -0
  115. package/dist/lib/sqlite.d.ts.map +1 -0
  116. package/dist/lib/sqlite.js +130 -0
  117. package/dist/lib/sqlite.js.map +1 -0
  118. package/dist/lib/tls.d.ts +34 -0
  119. package/dist/lib/tls.d.ts.map +1 -0
  120. package/dist/lib/tls.js +212 -0
  121. package/dist/lib/tls.js.map +1 -0
  122. package/dist/mcp/server.d.ts +231 -0
  123. package/dist/mcp/server.d.ts.map +1 -0
  124. package/dist/mcp/server.js +615 -0
  125. package/dist/mcp/server.js.map +1 -0
  126. package/dist/memory/actionStore.d.ts +75 -0
  127. package/dist/memory/actionStore.d.ts.map +1 -0
  128. package/dist/memory/actionStore.js +239 -0
  129. package/dist/memory/actionStore.js.map +1 -0
  130. package/dist/memory/deadLetterStore.d.ts +30 -0
  131. package/dist/memory/deadLetterStore.d.ts.map +1 -0
  132. package/dist/memory/deadLetterStore.js +91 -0
  133. package/dist/memory/deadLetterStore.js.map +1 -0
  134. package/dist/memory/embedQueueStore.d.ts +32 -0
  135. package/dist/memory/embedQueueStore.d.ts.map +1 -0
  136. package/dist/memory/embedQueueStore.js +143 -0
  137. package/dist/memory/embedQueueStore.js.map +1 -0
  138. package/dist/memory/failurePatternStore.d.ts +37 -0
  139. package/dist/memory/failurePatternStore.d.ts.map +1 -0
  140. package/dist/memory/failurePatternStore.js +179 -0
  141. package/dist/memory/failurePatternStore.js.map +1 -0
  142. package/dist/memory/graphStore.d.ts +38 -0
  143. package/dist/memory/graphStore.d.ts.map +1 -0
  144. package/dist/memory/graphStore.js +229 -0
  145. package/dist/memory/graphStore.js.map +1 -0
  146. package/dist/memory/noteStore.d.ts +58 -0
  147. package/dist/memory/noteStore.d.ts.map +1 -0
  148. package/dist/memory/noteStore.js +280 -0
  149. package/dist/memory/noteStore.js.map +1 -0
  150. package/dist/memory/observationStore.d.ts +40 -0
  151. package/dist/memory/observationStore.d.ts.map +1 -0
  152. package/dist/memory/observationStore.js +213 -0
  153. package/dist/memory/observationStore.js.map +1 -0
  154. package/dist/memory/projectRename.d.ts +14 -0
  155. package/dist/memory/projectRename.d.ts.map +1 -0
  156. package/dist/memory/projectRename.js +105 -0
  157. package/dist/memory/projectRename.js.map +1 -0
  158. package/dist/memory/rollupSweeper.d.ts +36 -0
  159. package/dist/memory/rollupSweeper.d.ts.map +1 -0
  160. package/dist/memory/rollupSweeper.js +235 -0
  161. package/dist/memory/rollupSweeper.js.map +1 -0
  162. package/dist/memory/sessionStore.d.ts +81 -0
  163. package/dist/memory/sessionStore.d.ts.map +1 -0
  164. package/dist/memory/sessionStore.js +285 -0
  165. package/dist/memory/sessionStore.js.map +1 -0
  166. package/dist/memory/trajectoryStore.d.ts +86 -0
  167. package/dist/memory/trajectoryStore.d.ts.map +1 -0
  168. package/dist/memory/trajectoryStore.js +528 -0
  169. package/dist/memory/trajectoryStore.js.map +1 -0
  170. package/dist/middleware/auth.d.ts +30 -0
  171. package/dist/middleware/auth.d.ts.map +1 -0
  172. package/dist/middleware/auth.js +387 -0
  173. package/dist/middleware/auth.js.map +1 -0
  174. package/dist/middleware/rateLimiter.d.ts +13 -0
  175. package/dist/middleware/rateLimiter.d.ts.map +1 -0
  176. package/dist/middleware/rateLimiter.js +153 -0
  177. package/dist/middleware/rateLimiter.js.map +1 -0
  178. package/dist/middleware/tracing.d.ts +15 -0
  179. package/dist/middleware/tracing.d.ts.map +1 -0
  180. package/dist/middleware/tracing.js +53 -0
  181. package/dist/middleware/tracing.js.map +1 -0
  182. package/dist/routes/dashboard.d.ts +2 -0
  183. package/dist/routes/dashboard.d.ts.map +1 -0
  184. package/dist/routes/dashboard.js +443 -0
  185. package/dist/routes/dashboard.js.map +1 -0
  186. package/dist/routes/learning.d.ts +2 -0
  187. package/dist/routes/learning.d.ts.map +1 -0
  188. package/dist/routes/learning.js +46 -0
  189. package/dist/routes/learning.js.map +1 -0
  190. package/dist/routes/mcp.d.ts +8 -0
  191. package/dist/routes/mcp.d.ts.map +1 -0
  192. package/dist/routes/mcp.js +316 -0
  193. package/dist/routes/mcp.js.map +1 -0
  194. package/dist/routes/memories.d.ts +2 -0
  195. package/dist/routes/memories.d.ts.map +1 -0
  196. package/dist/routes/memories.js +33 -0
  197. package/dist/routes/memories.js.map +1 -0
  198. package/dist/scripts/createApiKey.d.ts +2 -0
  199. package/dist/scripts/createApiKey.d.ts.map +1 -0
  200. package/dist/scripts/createApiKey.js +78 -0
  201. package/dist/scripts/createApiKey.js.map +1 -0
  202. package/dist/scripts/doctor.d.ts +24 -0
  203. package/dist/scripts/doctor.d.ts.map +1 -0
  204. package/dist/scripts/doctor.js +332 -0
  205. package/dist/scripts/doctor.js.map +1 -0
  206. package/dist/scripts/installAgent.d.ts +80 -0
  207. package/dist/scripts/installAgent.d.ts.map +1 -0
  208. package/dist/scripts/installAgent.js +1046 -0
  209. package/dist/scripts/installAgent.js.map +1 -0
  210. package/dist/scripts/migrateAgentMemory.d.ts +16 -0
  211. package/dist/scripts/migrateAgentMemory.d.ts.map +1 -0
  212. package/dist/scripts/migrateAgentMemory.js +209 -0
  213. package/dist/scripts/migrateAgentMemory.js.map +1 -0
  214. package/dist/scripts/smokeTest.d.ts +16 -0
  215. package/dist/scripts/smokeTest.d.ts.map +1 -0
  216. package/dist/scripts/smokeTest.js +150 -0
  217. package/dist/scripts/smokeTest.js.map +1 -0
  218. package/docker-compose.qdrant-port.yml +7 -0
  219. package/docker-compose.yml +107 -0
  220. package/npm-shrinkwrap.json +7635 -0
  221. package/package.json +107 -4
  222. package/plugin/hooks/postToolUse.js +513 -0
  223. package/plugin/hooks/sessionStart.js +416 -0
  224. package/plugin/hooks/sessionStop.js +346 -0
  225. package/plugin/hooks.json +30 -0
  226. package/plugin/mcp_config.json +13 -0
  227. package/plugin/plugin.json +15 -0
  228. package/plugin/rules/AGENTS.md +66 -0
  229. package/plugin/skills/brain-memory/REFERENCE.md +64 -0
  230. package/plugin/skills/brain-memory/SKILL.md +68 -0
  231. package/plugin/skills/brain-memory/TROUBLESHOOTING.md +24 -0
  232. package/plugin/skills/digest/SKILL.md +54 -0
  233. package/plugin/skills/digest/TROUBLESHOOTING.md +24 -0
  234. package/plugin/skills/handoff/SKILL.md +59 -0
  235. package/plugin/skills/handoff/TROUBLESHOOTING.md +24 -0
  236. package/plugin/skills/save/SKILL.md +76 -0
  237. package/plugin/skills/save/TROUBLESHOOTING.md +24 -0
  238. package/plugin/skills/search/SKILL.md +60 -0
  239. package/plugin/skills/search/TROUBLESHOOTING.md +24 -0
  240. package/src/ai/chat.ts +214 -0
  241. package/src/ai/circuitBreaker.ts +120 -0
  242. package/src/ai/config.ts +311 -0
  243. package/src/ai/vendors.ts +292 -0
  244. package/src/app.ts +1150 -0
  245. package/src/cli.ts +1080 -0
  246. package/src/consolidation/candidates.ts +219 -0
  247. package/src/consolidation/fixtures.ts +461 -0
  248. package/src/consolidation/gate.ts +408 -0
  249. package/src/consolidation/runner.ts +220 -0
  250. package/src/dashboard/clientScript.ts +4208 -0
  251. package/src/dashboard/html.ts +550 -0
  252. package/src/dashboard/styles.ts +1279 -0
  253. package/src/index.ts +139 -0
  254. package/src/learning/embedWorker.ts +651 -0
  255. package/src/learning/embedding.ts +522 -0
  256. package/src/learning/engine.ts +86 -0
  257. package/src/learning/search.ts +568 -0
  258. package/src/learning/storeMeta.ts +147 -0
  259. package/src/learning/types.ts +111 -0
  260. package/src/lib/brainHome.ts +101 -0
  261. package/src/lib/db.ts +627 -0
  262. package/src/lib/logger.ts +7 -0
  263. package/src/lib/projectSlug.ts +286 -0
  264. package/src/lib/redactSecrets.ts +87 -0
  265. package/src/lib/scope.ts +121 -0
  266. package/src/lib/spool.ts +372 -0
  267. package/src/lib/sqlite.ts +158 -0
  268. package/src/lib/tls.ts +252 -0
  269. package/src/mcp/server.ts +793 -0
  270. package/src/memory/actionStore.ts +378 -0
  271. package/src/memory/deadLetterStore.ts +141 -0
  272. package/src/memory/embedQueueStore.ts +176 -0
  273. package/src/memory/failurePatternStore.ts +221 -0
  274. package/src/memory/graphStore.ts +352 -0
  275. package/src/memory/noteStore.ts +403 -0
  276. package/src/memory/observationStore.ts +303 -0
  277. package/src/memory/projectRename.ts +147 -0
  278. package/src/memory/rollupSweeper.ts +309 -0
  279. package/src/memory/sessionStore.ts +410 -0
  280. package/src/memory/trajectoryStore.ts +775 -0
  281. package/src/middleware/auth.ts +450 -0
  282. package/src/middleware/rateLimiter.ts +186 -0
  283. package/src/middleware/tracing.ts +70 -0
  284. package/src/routes/dashboard.ts +496 -0
  285. package/src/routes/learning.ts +51 -0
  286. package/src/routes/mcp.ts +349 -0
  287. package/src/routes/memories.ts +33 -0
  288. package/src/scripts/createApiKey.ts +109 -0
  289. package/src/scripts/doctor.ts +359 -0
  290. package/src/scripts/installAgent.ts +1278 -0
  291. package/src/scripts/migrateAgentMemory.ts +263 -0
  292. package/src/scripts/smokeTest.ts +189 -0
  293. package/tsconfig.json +21 -0
@@ -0,0 +1,372 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import os from 'os';
4
+ import { createHash } from 'crypto';
5
+ import { logger } from './logger';
6
+ import { getDefaultSpoolDir } from './brainHome';
7
+
8
+ export interface SpoolEntry {
9
+ id: string;
10
+ endpoint: string;
11
+ payload: unknown;
12
+ timestamp: number; // unix epoch in seconds
13
+ attempts?: number;
14
+ }
15
+
16
+ export interface SpoolStats {
17
+ count: number;
18
+ bytes: number;
19
+ maxBytes: number;
20
+ maxAgeHours: number;
21
+ oldestTimestamp: number | null;
22
+ }
23
+
24
+ function resolveSpoolDir(): string {
25
+ const envPath = process.env.BRAIN_SPOOL_PATH?.trim();
26
+ if (envPath) {
27
+ if (envPath.startsWith('~/')) {
28
+ return path.join(os.homedir(), envPath.slice(2));
29
+ }
30
+ return path.resolve(envPath);
31
+ }
32
+ return getDefaultSpoolDir();
33
+ }
34
+
35
+ function getSpoolFilePath(): string {
36
+ const dir = resolveSpoolDir();
37
+ if (!fs.existsSync(dir)) {
38
+ try {
39
+ fs.mkdirSync(dir, { recursive: true, mode: 0o700 });
40
+ try {
41
+ fs.chmodSync(dir, 0o700);
42
+ } catch {
43
+ // ignore chmod failure on platforms that don't support posix permissions
44
+ }
45
+ } catch (err) {
46
+ logger.error({ dir, error: err instanceof Error ? err.message : String(err) }, 'failed to create spool directory');
47
+ }
48
+ }
49
+ return path.join(dir, 'spool.jsonl');
50
+ }
51
+
52
+ function getMaxBytes(): number {
53
+ const val = process.env.BRAIN_SPOOL_MAX_BYTES;
54
+ const parsed = val ? parseInt(val, 10) : NaN;
55
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 5242880; // default 5 MB
56
+ }
57
+
58
+ function getMaxAgeHours(): number {
59
+ const val = process.env.BRAIN_SPOOL_MAX_AGE_HOURS;
60
+ const parsed = val ? parseInt(val, 10) : NaN;
61
+ return Number.isFinite(parsed) && parsed > 0 ? parsed : 168; // default 7 days
62
+ }
63
+
64
+ function computeEntryId(endpoint: string, payload: unknown): string {
65
+ if (payload && typeof payload === 'object' && 'id' in payload && typeof (payload as any).id === 'string') {
66
+ return `${endpoint}:${(payload as any).id}`;
67
+ }
68
+ const payloadStr = JSON.stringify(payload);
69
+ const hash = createHash('sha256').update(`${endpoint}:${payloadStr}`).digest('hex').slice(0, 24);
70
+ return `${endpoint}:${hash}`;
71
+ }
72
+
73
+ interface SpoolCache {
74
+ filePath: string;
75
+ mtimeMs: number;
76
+ size: number;
77
+ ids: Set<string>;
78
+ }
79
+
80
+ let activeSpoolCache: SpoolCache | null = null;
81
+
82
+ function updateIdCache(filePath: string, entries: SpoolEntry[]): void {
83
+ try {
84
+ if (fs.existsSync(filePath)) {
85
+ const stat = fs.statSync(filePath);
86
+ activeSpoolCache = {
87
+ filePath,
88
+ mtimeMs: stat.mtimeMs,
89
+ size: stat.size,
90
+ ids: new Set(entries.map((e) => e.id)),
91
+ };
92
+ return;
93
+ }
94
+ } catch {
95
+ // ignore
96
+ }
97
+ activeSpoolCache = {
98
+ filePath,
99
+ mtimeMs: 0,
100
+ size: 0,
101
+ ids: new Set(entries.map((e) => e.id)),
102
+ };
103
+ }
104
+
105
+ function getActiveIds(filePath: string): Set<string> {
106
+ if (!fs.existsSync(filePath)) {
107
+ activeSpoolCache = { filePath, mtimeMs: 0, size: 0, ids: new Set() };
108
+ return activeSpoolCache.ids;
109
+ }
110
+
111
+ try {
112
+ const stat = fs.statSync(filePath);
113
+ if (
114
+ activeSpoolCache &&
115
+ activeSpoolCache.filePath === filePath &&
116
+ activeSpoolCache.mtimeMs === stat.mtimeMs &&
117
+ activeSpoolCache.size === stat.size
118
+ ) {
119
+ return activeSpoolCache.ids;
120
+ }
121
+ } catch {
122
+ // ignore stat error and reload
123
+ }
124
+
125
+ const entries = readSpool();
126
+ if (!activeSpoolCache || activeSpoolCache.filePath !== filePath) {
127
+ updateIdCache(filePath, entries);
128
+ }
129
+ return activeSpoolCache?.ids ?? new Set(entries.map((e) => e.id));
130
+ }
131
+
132
+ export function readSpool(): SpoolEntry[] {
133
+ const filePath = getSpoolFilePath();
134
+ if (!fs.existsSync(filePath)) {
135
+ activeSpoolCache = { filePath, mtimeMs: 0, size: 0, ids: new Set() };
136
+ return [];
137
+ }
138
+
139
+ const content = fs.readFileSync(filePath, 'utf-8');
140
+ if (!content.trim()) {
141
+ activeSpoolCache = { filePath, mtimeMs: 0, size: 0, ids: new Set() };
142
+ return [];
143
+ }
144
+
145
+ const lines = content.split('\n').filter((l) => l.trim().length > 0);
146
+ const now = Math.floor(Date.now() / 1000);
147
+ const maxAgeHours = getMaxAgeHours();
148
+ const cutoff = now - maxAgeHours * 3600;
149
+
150
+ const validEntries: SpoolEntry[] = [];
151
+ let expiredCount = 0;
152
+
153
+ for (const line of lines) {
154
+ try {
155
+ const entry = JSON.parse(line) as SpoolEntry;
156
+ if (entry.timestamp < cutoff) {
157
+ expiredCount++;
158
+ } else {
159
+ validEntries.push(entry);
160
+ }
161
+ } catch {
162
+ expiredCount++;
163
+ }
164
+ }
165
+
166
+ // If expired or corrupted lines were found, prune the file
167
+ if (expiredCount > 0) {
168
+ writeSpoolEntries(validEntries);
169
+ } else {
170
+ updateIdCache(filePath, validEntries);
171
+ }
172
+
173
+ return validEntries;
174
+ }
175
+
176
+ function writeSpoolEntries(entries: SpoolEntry[]): void {
177
+ const filePath = getSpoolFilePath();
178
+ const dir = path.dirname(filePath);
179
+
180
+ if (entries.length === 0) {
181
+ if (fs.existsSync(filePath)) {
182
+ const tmpPath = path.join(
183
+ dir,
184
+ `.spool.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`
185
+ );
186
+ fs.writeFileSync(tmpPath, '', { encoding: 'utf-8', mode: 0o600 });
187
+ fs.renameSync(tmpPath, filePath);
188
+ }
189
+ updateIdCache(filePath, entries);
190
+ return;
191
+ }
192
+
193
+ const content = entries.map((e) => JSON.stringify(e)).join('\n') + '\n';
194
+ const tmpPath = path.join(
195
+ dir,
196
+ `.spool.tmp.${process.pid}.${Date.now()}.${Math.random().toString(36).slice(2)}`
197
+ );
198
+ fs.writeFileSync(tmpPath, content, { encoding: 'utf-8', mode: 0o600 });
199
+ fs.renameSync(tmpPath, filePath);
200
+ updateIdCache(filePath, entries);
201
+ }
202
+
203
+ export function appendSpool(endpoint: string, payload: unknown): boolean {
204
+ const id = computeEntryId(endpoint, payload);
205
+ 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;
212
+ }
213
+
214
+ const newEntry: SpoolEntry = {
215
+ id,
216
+ endpoint,
217
+ payload,
218
+ timestamp: Math.floor(Date.now() / 1000),
219
+ attempts: 0,
220
+ };
221
+
222
+ const line = JSON.stringify(newEntry) + '\n';
223
+ const lineBytes = Buffer.byteLength(line, 'utf-8');
224
+
225
+ let currentBytes = 0;
226
+ if (fs.existsSync(filePath)) {
227
+ try {
228
+ currentBytes = fs.statSync(filePath).size;
229
+ } catch {
230
+ currentBytes = 0;
231
+ }
232
+ }
233
+
234
+ const maxBytes = getMaxBytes();
235
+ if (currentBytes + lineBytes > maxBytes) {
236
+ logger.warn({ currentBytes, lineBytes, maxBytes }, 'spool file full, rejecting write');
237
+ return false;
238
+ }
239
+
240
+ fs.appendFileSync(filePath, line, { encoding: 'utf-8', mode: 0o600 });
241
+
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
+ }
254
+
255
+ return true;
256
+ }
257
+
258
+ let flushMutex: Promise<unknown> = Promise.resolve();
259
+
260
+ export function flushSpool(
261
+ sendFn: (endpoint: string, payload: unknown) => Promise<boolean>
262
+ ): Promise<{ flushed: number; remaining: number; droppedExpired: number }> {
263
+ const next = flushMutex.then(() => doFlushSpool(sendFn));
264
+ flushMutex = next.catch(() => {});
265
+ return next;
266
+ }
267
+
268
+ async function doFlushSpool(
269
+ sendFn: (endpoint: string, payload: unknown) => Promise<boolean>
270
+ ): Promise<{ flushed: number; remaining: number; droppedExpired: number }> {
271
+ const filePath = getSpoolFilePath();
272
+ if (!fs.existsSync(filePath)) {
273
+ return { flushed: 0, remaining: 0, droppedExpired: 0 };
274
+ }
275
+
276
+ const rawContent = fs.readFileSync(filePath, 'utf-8');
277
+ const rawLines = rawContent.split('\n').filter((l) => l.trim().length > 0);
278
+ const now = Math.floor(Date.now() / 1000);
279
+ const maxAgeHours = getMaxAgeHours();
280
+ const cutoff = now - maxAgeHours * 3600;
281
+
282
+ const validEntries: SpoolEntry[] = [];
283
+ let droppedExpired = 0;
284
+
285
+ for (const line of rawLines) {
286
+ try {
287
+ const entry = JSON.parse(line) as SpoolEntry;
288
+ if (entry.timestamp < cutoff) {
289
+ droppedExpired++;
290
+ } else {
291
+ validEntries.push(entry);
292
+ }
293
+ } catch {
294
+ droppedExpired++;
295
+ }
296
+ }
297
+
298
+ const snapshotIds = new Set(validEntries.map((e) => e.id));
299
+
300
+ let flushed = 0;
301
+ const remainingEntries: SpoolEntry[] = [];
302
+
303
+ for (const entry of validEntries) {
304
+ try {
305
+ const success = await sendFn(entry.endpoint, entry.payload);
306
+ if (success) {
307
+ flushed++;
308
+ } else {
309
+ entry.attempts = (entry.attempts ?? 0) + 1;
310
+ remainingEntries.push(entry);
311
+ }
312
+ } catch {
313
+ entry.attempts = (entry.attempts ?? 0) + 1;
314
+ remainingEntries.push(entry);
315
+ }
316
+ }
317
+
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);
329
+ }
330
+ } catch {
331
+ // ignore corrupted lines
332
+ }
333
+ }
334
+ } catch {
335
+ // ignore read error
336
+ }
337
+ }
338
+
339
+ const finalRemaining = [...remainingEntries, ...newlyAppended];
340
+ writeSpoolEntries(finalRemaining);
341
+
342
+ return {
343
+ flushed,
344
+ remaining: finalRemaining.length,
345
+ droppedExpired,
346
+ };
347
+ }
348
+
349
+ export function getSpoolStats(): SpoolStats {
350
+ const entries = readSpool();
351
+ const filePath = getSpoolFilePath();
352
+
353
+ let bytes = 0;
354
+ if (fs.existsSync(filePath)) {
355
+ bytes = fs.statSync(filePath).size;
356
+ }
357
+
358
+ let oldestTimestamp: number | null = null;
359
+ for (const entry of entries) {
360
+ if (oldestTimestamp === null || entry.timestamp < oldestTimestamp) {
361
+ oldestTimestamp = entry.timestamp;
362
+ }
363
+ }
364
+
365
+ return {
366
+ count: entries.length,
367
+ bytes,
368
+ maxBytes: getMaxBytes(),
369
+ maxAgeHours: getMaxAgeHours(),
370
+ oldestTimestamp,
371
+ };
372
+ }
@@ -0,0 +1,158 @@
1
+ /**
2
+ * Thin layer over Node's built-in `node:sqlite`.
3
+ *
4
+ * The brain used to depend on better-sqlite3, a native addon that needs an
5
+ * install script to fetch or compile its binary. npm 11 blocks dependency
6
+ * install scripts by default, so that made a plain `npm install` produce a
7
+ * service that could not open its own database. `node:sqlite` ships with Node,
8
+ * so there is nothing to build.
9
+ *
10
+ * `node:sqlite` has no `transaction()` or `pragma()` helpers, so the two that
11
+ * the stores relied on are reproduced here with better-sqlite3's semantics.
12
+ */
13
+ import { DatabaseSync, SQLInputValue, StatementSync } from 'node:sqlite';
14
+
15
+ /**
16
+ * The slice of the API the stores use, typed the way better-sqlite3 typed it:
17
+ * bind values are `unknown` and rows come back as `unknown`, so each store
18
+ * keeps casting rows to its own record type. node:sqlite's own typings are
19
+ * stricter (SQLInputValue / Record<string, SQLOutputValue>) and would need a
20
+ * cast at every call site for no runtime difference.
21
+ */
22
+ export interface RunResult {
23
+ changes: number;
24
+ lastInsertRowid: number | bigint;
25
+ }
26
+
27
+ export interface Statement {
28
+ run(...params: unknown[]): RunResult;
29
+ get(...params: unknown[]): unknown;
30
+ all(...params: unknown[]): unknown[];
31
+ iterate(...params: unknown[]): IterableIterator<unknown>;
32
+ }
33
+
34
+ export interface Database {
35
+ prepare(sql: string): Statement;
36
+ exec(sql: string): void;
37
+ close(): void;
38
+ readonly isOpen: boolean;
39
+ readonly isTransaction: boolean;
40
+ }
41
+
42
+ /**
43
+ * better-sqlite3 waits up to 5 s for a lock by default; node:sqlite fails at
44
+ * once. Keep the old behaviour so WAL contention (a read-only diagnosis
45
+ * connection, a checkpoint) waits instead of surfacing as an error.
46
+ */
47
+ export const BUSY_TIMEOUT_MS = 5000;
48
+
49
+ export interface OpenOptions {
50
+ readOnly?: boolean;
51
+ }
52
+
53
+ export function openDatabase(filename: string, options: OpenOptions = {}): Database {
54
+ const raw = new DatabaseSync(filename, {
55
+ readOnly: options.readOnly ?? false,
56
+ timeout: BUSY_TIMEOUT_MS,
57
+ });
58
+ return {
59
+ prepare: (sql: string) => wrapStatement(raw.prepare(sql)),
60
+ exec: (sql: string) => raw.exec(sql),
61
+ close: () => raw.close(),
62
+ get isOpen() {
63
+ return raw.isOpen;
64
+ },
65
+ get isTransaction() {
66
+ return raw.isTransaction;
67
+ },
68
+ };
69
+ }
70
+
71
+ /**
72
+ * node:sqlite returns BLOB columns as Uint8Array; better-sqlite3 returned
73
+ * Buffer. Rows (note embeddings included) reach API responses, where the two
74
+ * serialise differently, and the stores type those columns as Buffer. Convert
75
+ * on the way out: Buffer.from(arrayBuffer, offset, length) is a view over the
76
+ * same memory, not a copy.
77
+ */
78
+ function toBuffer(value: unknown): unknown {
79
+ return value instanceof Uint8Array && !Buffer.isBuffer(value)
80
+ ? Buffer.from(value.buffer, value.byteOffset, value.byteLength)
81
+ : value;
82
+ }
83
+
84
+ function normalizeRow(row: unknown): unknown {
85
+ if (!row || typeof row !== 'object') return row;
86
+ const obj = row as Record<string, unknown>;
87
+ for (const key of Object.keys(obj)) {
88
+ const value = obj[key];
89
+ if (value instanceof Uint8Array) obj[key] = toBuffer(value);
90
+ }
91
+ return obj;
92
+ }
93
+
94
+ function wrapStatement(stmt: StatementSync): Statement {
95
+ const params = (args: unknown[]) => args as SQLInputValue[];
96
+ return {
97
+ run: (...args: unknown[]) => stmt.run(...params(args)) as RunResult,
98
+ get: (...args: unknown[]) => normalizeRow(stmt.get(...params(args))),
99
+ all: (...args: unknown[]) => stmt.all(...params(args)).map(normalizeRow),
100
+ iterate: function* (...args: unknown[]) {
101
+ for (const row of stmt.iterate(...params(args))) yield normalizeRow(row);
102
+ },
103
+ };
104
+ }
105
+
106
+ /** Runs `PRAGMA <statement>` (e.g. `pragma(db, 'foreign_keys = ON')`). */
107
+ export function pragma(db: Database, statement: string): void {
108
+ db.exec(`PRAGMA ${statement}`);
109
+ }
110
+
111
+ let savepointSeq = 0;
112
+
113
+ /**
114
+ * Wraps `fn` so each call runs in a transaction, matching better-sqlite3's
115
+ * `db.transaction(fn)`:
116
+ *
117
+ * - At top level the call runs inside BEGIN ... COMMIT and rolls back if `fn`
118
+ * throws.
119
+ * - Called while a transaction is already open, it runs inside a SAVEPOINT, so
120
+ * a failure rolls back only this call and the outer transaction carries on.
121
+ * observationStore relies on this: one malformed observation is
122
+ * dead-lettered without discarding the rest of its batch (rule 3).
123
+ * - `fn` must be synchronous; a transaction cannot span an await.
124
+ */
125
+ export function transaction<A extends unknown[], R>(db: Database, fn: (...args: A) => R): (...args: A) => R {
126
+ return (...args: A): R => {
127
+ if (db.isTransaction) {
128
+ const name = `nb_sp_${++savepointSeq}`;
129
+ db.exec(`SAVEPOINT ${name}`);
130
+ try {
131
+ const result = assertSync(fn(...args));
132
+ db.exec(`RELEASE ${name}`);
133
+ return result;
134
+ } catch (err) {
135
+ db.exec(`ROLLBACK TO ${name}`);
136
+ db.exec(`RELEASE ${name}`);
137
+ throw err;
138
+ }
139
+ }
140
+
141
+ db.exec('BEGIN');
142
+ try {
143
+ const result = assertSync(fn(...args));
144
+ db.exec('COMMIT');
145
+ return result;
146
+ } catch (err) {
147
+ if (db.isTransaction) db.exec('ROLLBACK');
148
+ throw err;
149
+ }
150
+ };
151
+ }
152
+
153
+ function assertSync<R>(result: R): R {
154
+ if (result && typeof (result as { then?: unknown }).then === 'function') {
155
+ throw new TypeError('Transaction function cannot return a promise');
156
+ }
157
+ return result;
158
+ }