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
package/README.md CHANGED
@@ -1,3 +1,313 @@
1
- # Temporary Holding Version
1
+ # Neuralbrain
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ A memory service for coding agents. It runs on your machine, stores everything in SQLite, and talks to Claude Code, Claude Desktop, Antigravity and Cursor over HTTP and MCP.
4
+
5
+ It started as the memory subsystem of NeuralSwarm, my agent orchestrator. That version was scoped to swarms, roles and LLM providers. This one is scoped to projects, notes and tasks, so any agent can use it.
6
+
7
+ ## Why I built it
8
+
9
+ Most memory tools for agents break in the same four ways:
10
+
11
+ - **They run an LLM on every write.** The summariser hallucinates into the records. Turn compression off to stop it, and the store stops growing.
12
+ - **They guess scope.** Records get written with no project, and nothing tells "forgot to say" apart from "applies everywhere". A backfill can't recover that, and filtering by project returns nothing.
13
+ - **They drop data.** A per-session cap is meant to be relieved by consolidation. When consolidation is off, everything past the cap is thrown away.
14
+ - **You can't fix them.** There's no way to repair a record with SQL, and the health check says "6/10 passing" and "all checks passing" in the same run.
15
+
16
+ Each of those became a rule here.
17
+
18
+ ## The rules
19
+
20
+ 1. **No LLM in the capture path.** Records are typed columns. Rollups are arithmetic: count the tool calls, sum the durations, take the first prompt as the description, mark it failed if a failure hook fired. Models are only allowed to write derived records (rule 6).
21
+ 2. **SQLite is the source of truth. Qdrant is an index.** You can inspect and repair anything with SQL. If Qdrant goes away, it gets rebuilt from SQLite.
22
+ 3. **Never reject a write for capacity.** No per-session caps, no rate limit on `/capture/*`. Backpressure is fine, rejection isn't. Dead letters are only for malformed payloads, never for volume or an outage.
23
+ 4. **Scope is stated, never inferred.** Every record is `project` (with a `project_id`), `global` (on purpose) or `unknown` (the writer didn't say). Unknown records go to a repair queue on the dashboard. Nothing gets backfilled by guessing.
24
+ 5. **Three grains, one schema.**
25
+ - `observations`: tool calls and prompts, captured by hooks. High volume. Archived at 30 days, purged at 90.
26
+ - `trajectories`: task attempts with arithmetic outcomes. Low volume, kept.
27
+ - `notes`: facts, decisions, patterns, bugs, workflows, preferences and lessons. Written on purpose, edited by supersede, never auto-deleted.
28
+ 6. **Derived records are extra.** A summary is a new row that cites its sources. It never changes the rows it came from, and you can delete every summary without breaking anything.
29
+
30
+ One more: **only the service opens the database for writing.** Not a script, not a test, not me with `sqlite3`. A direct write skips the embed queue, so the row lands in SQLite but never in Qdrant and silently drops out of search. It also skips failure-pattern counting, dead-letter routing and tracing. Repairs go through `POST /maintenance/*`, the dashboard or the CLI. Read-only inspection (`?mode=ro`) is fine when the service is stopped.
31
+
32
+ ## How it fits together
33
+
34
+ ```
35
+ Agent / IDE (Claude Code, Antigravity, Cursor ...)
36
+ │ │
37
+ │ stdio MCP │ HTTP (hooks, with a local spool if the brain is down)
38
+ ▼ │
39
+ MCP server (REST client, │
40
+ no database access) │
41
+ │ HTTP │
42
+ ▼ ▼
43
+ ┌───────────────────────────────────────────────┐
44
+ │ Neuralbrain service (port 3737) │
45
+ │ capture · sessions · actions · inject · │
46
+ │ search · graph · consolidate · dashboard │
47
+ │ │
48
+ │ SQLite (WAL) ──embed queue──> Qdrant │
49
+ └───────────────────────────────────────────────┘
50
+ ```
51
+
52
+ Agents get memory two ways:
53
+
54
+ - **Push.** At task start, `GET /inject` hands the agent recent failure patterns, prior outcomes, open next actions, the last session summary, lessons and notes.
55
+ - **Pull.** Mid-task, `brain_search` runs dense vector search and BM25 together and merges them with reciprocal rank fusion.
56
+
57
+ The MCP server exposes 11 tools: `brain_search`, `brain_save`, `brain_recent_failures`, `brain_consolidate_candidates`, `brain_submit_summary`, `brain_action_add`, `brain_action_list`, `brain_action_update`, `brain_sessions`, `brain_session_end` and `brain_graph`.
58
+
59
+ ## Requirements
60
+
61
+ - Node.js 24 or newer, and npm.
62
+ - Docker with Compose v2, for the `docker` and `qdrant-docker` modes.
63
+ - OpenSSL, only if you use `--https`.
64
+ - An NVIDIA GPU with nvidia-container-toolkit, only if you use `--gpu`.
65
+
66
+ ## Install
67
+
68
+ ### Quick start
69
+
70
+ ```bash
71
+ npm install -g neuralbrain
72
+ neuralbrain install
73
+ ```
74
+
75
+ To update, run `npm install -g neuralbrain@latest`, then `neuralbrain start`.
76
+
77
+ ### From source
78
+
79
+ ```bash
80
+ git clone https://github.com/derricke/neuralbrain.git
81
+ cd neuralbrain
82
+ npm install && npm run build
83
+ node dist/cli.js install
84
+ ```
85
+
86
+ Install copies the package into npm's global folder (it packs the checkout and installs the tarball, rather than linking it), then starts the brain from that copy. After that you can move or delete the clone. To update, pull and run `node dist/cli.js install` again. Pass `--no-global` to skip the global copy and run straight from the checkout.
87
+
88
+ ### What install does
89
+
90
+ It sets up `~/.neuralbrain/` (or `$BRAIN_HOME`) and asks which mode you want:
91
+
92
+ | Mode | What runs where |
93
+ |---|---|
94
+ | `docker` | Brain and Qdrant both in Docker Compose |
95
+ | `qdrant-docker` | Qdrant in Docker, brain as a Node daemon on the host |
96
+ | `local-only` | Brain on the host, no Qdrant, `BRAIN_EMBED=none` (SQLite and BM25 only) |
97
+
98
+ The in-process embedder (`@huggingface/transformers`) is an optional dependency. Docker mode doesn't need it on the host. When the brain runs on the host with `BRAIN_EMBED=local` (the default for `qdrant-docker`), `neuralbrain start` installs it the first time if it's missing. On Linux, `npm install -g` leaves it out, because its native runtime's install script fails there.
99
+
100
+ Everything it creates lives in `~/.neuralbrain/`:
101
+
102
+ ```
103
+ data/brain.db the database
104
+ data/models/ cached embedding models
105
+ qdrant/ Qdrant storage (Docker modes)
106
+ spool/ requests queued while the brain was unreachable
107
+ .env your config
108
+ mode the mode you picked
109
+ brain.pid, brain.log host daemon (qdrant-docker and local-only)
110
+ ```
111
+
112
+ Config is read from `./.env.local`, `./.env`, `~/.neuralbrain/.env.local` and `~/.neuralbrain/.env`, in that order. Anything already set in the environment wins.
113
+
114
+ Install flags: `--mode`, `--port`, `--https`, `--gpu`, `--yes`, `--no-global`, `--no-agents`.
115
+
116
+ - `--https` (or `BRAIN_HTTPS=1`) generates a local certificate in `~/.neuralbrain/certs/` with OpenSSL and serves over HTTPS.
117
+ - `--gpu` sets `BRAIN_EMBED=local-gpu`. See [GPU embeddings](#gpu-embeddings).
118
+
119
+ ### Running it
120
+
121
+ ```bash
122
+ neuralbrain start # start whatever mode you installed
123
+ neuralbrain stop
124
+ neuralbrain status # BRAIN_HOME, mode, daemon PID, /health
125
+ neuralbrain logs
126
+ neuralbrain doctor # health checks plus the AI conformance tests
127
+ neuralbrain install-agent # wire up your agents
128
+ neuralbrain init # write .brainrc here: one project_id for this folder and below
129
+ neuralbrain mcp # run the stdio MCP server
130
+ ```
131
+
132
+ Check it's up:
133
+
134
+ ```bash
135
+ curl http://127.0.0.1:3737/health
136
+ ```
137
+
138
+ ### Without the CLI
139
+
140
+ With Docker Compose:
141
+
142
+ ```bash
143
+ cp .env.example .env
144
+ docker compose up -d --build
145
+ ```
146
+
147
+ That starts `neuralbrain` on `127.0.0.1:3737` with `neuralbrain-qdrant` on the internal Docker network (in `qdrant-docker` mode, Qdrant is published on `127.0.0.1:6333`). Data goes to `~/.neuralbrain/data` and `~/.neuralbrain/qdrant` unless you set `BRAIN_DATA_DIR` or `BRAIN_QDRANT_DIR`.
148
+
149
+ On the host:
150
+
151
+ ```bash
152
+ cp .env.example .env
153
+ npm run build
154
+ npm start # or: npm run dev
155
+ ```
156
+
157
+ For vector search, start Qdrant (`npm run qdrant:start`) and leave `BRAIN_EMBED=local`. If you don't want Qdrant, set `BRAIN_EMBED=none` and you get SQL and BM25 only.
158
+
159
+ ### API key
160
+
161
+ If `BRAIN_API_KEY` is set, the service registers it on startup. Change it and restart, and the stored key is updated; re-run `install-agent` so your agents pick it up.
162
+
163
+ If it's not set, open the dashboard at <http://127.0.0.1:3737/dashboard> and click **Claim First API Key**. To make more keys:
164
+
165
+ ```bash
166
+ npm run api-key:create
167
+ ```
168
+
169
+ ## Connecting agents
170
+
171
+ ```bash
172
+ npm run install-agent
173
+ ```
174
+
175
+ It finds Antigravity, Claude Code, Claude Desktop and Cursor and adds the MCP server and lifecycle hooks to each. It reads `BRAIN_API_KEY` and `BRAIN_API_URL` from `.env` so you don't have to pass keys on the command line. It's safe to re-run: it merges into existing MCP configs without touching your other servers, doesn't duplicate hooks, and keeps what it writes to `AGENTS.md` / `CLAUDE.md` between `<!-- neuralbrain:start -->` and `<!-- neuralbrain:end -->`.
176
+
177
+ By default it configures everything globally:
178
+
179
+ - Antigravity: `~/.gemini/config/plugins/neuralbrain` and `mcp_config.json`
180
+ - Claude Code: `~/.claude/settings.json`
181
+ - Claude Desktop: `claude_desktop_config.json`
182
+ - Cursor: `~/.cursor/mcp.json`
183
+
184
+ Other options:
185
+
186
+ ```bash
187
+ # one repo only: .claude/settings.local.json, .cursor/mcp.json, .brainrc, AGENTS.md/CLAUDE.md
188
+ npm run install-agent -- --project-dir /path/to/repo
189
+
190
+ # only some agents
191
+ npm run install-agent -- --target claude,antigravity
192
+
193
+ # show what would change without writing anything
194
+ npm run install-agent -- --dry-run
195
+ ```
196
+
197
+ ### Brain on another machine
198
+
199
+ On the server, set `HOST=0.0.0.0`. On your workstation, point `.env` at it and run `install-agent`:
200
+
201
+ ```dotenv
202
+ BRAIN_API_URL=https://brain.example.lan
203
+ BRAIN_API_KEY=your-key
204
+ ```
205
+
206
+ ## AI settings
207
+
208
+ There are two separate settings, because they fail differently.
209
+
210
+ `BRAIN_AI` controls the generative side (consolidation). It defaults to `agent`, which means the host agent writes summaries over MCP and the brain needs no model of its own. A generative model can only ever produce derived rows, which are attributed and disposable, so a fallback here is harmless.
211
+
212
+ `BRAIN_EMBED` controls embeddings. It defaults to `local`: `nomic-embed-text-v1.5` running in-process on ONNX at 512 dimensions. There's no fallback. A different model is a different vector space, so if your config doesn't match what the store was built with, vector search shuts off and tells you why, SQL and BM25 keep working, and you fix it with `POST /maintenance/reembed`.
213
+
214
+ | Tier | `BRAIN_AI` | `BRAIN_EMBED` |
215
+ |---|---|---|
216
+ | `none` | off | SQL and BM25 only |
217
+ | `agent` | **default**, host agent over MCP | n/a, agents can't produce vectors |
218
+ | `local` | n/a, no chat models in the Node process | **default**, in-process ONNX |
219
+ | `local-gpu` | n/a | GPU sidecar container |
220
+ | `remote` | OpenAI-compatible endpoint (Ollama, LM Studio, vLLM) | same |
221
+ | `vendor` | OpenAI, Anthropic or Google with an API key | same |
222
+
223
+ `BRAIN_ENDPOINT` is shared by both. Set `BRAIN_EMBED_ENDPOINT` to send embeddings somewhere else, for example a GPU box on your LAN:
224
+
225
+ ```dotenv
226
+ BRAIN_AI=agent
227
+ BRAIN_EMBED=remote
228
+ BRAIN_EMBED_ENDPOINT=http://gpu-server.lan:11434/v1
229
+ BRAIN_EMBED_MODEL=nomic-embed-text
230
+ ```
231
+
232
+ ### GPU embeddings
233
+
234
+ `local-gpu` runs nomic in a separate `embedder-gpu` container (`michaelf34/infinity:latest`, port 7997), so you don't need Ollama or LM Studio.
235
+
236
+ ```dotenv
237
+ BRAIN_EMBED=local-gpu
238
+ BRAIN_EMBED_MODEL=nomic
239
+ BRAIN_EMBED_DIM=512
240
+ ```
241
+
242
+ - You need an NVIDIA GPU, working drivers (`nvidia-smi`) and `nvidia-container-toolkit`. To check Docker can see the GPU, run this. If it prints your GPU table, you're good:
243
+
244
+ ```bash
245
+ docker run --rm --gpus all nvidia/cuda:12.4.1-base-ubuntu22.04 nvidia-smi
246
+ ```
247
+
248
+ - It only works in `docker` and `qdrant-docker` modes, where `neuralbrain start` brings up the `gpu` Compose profile. In `local-only` you run the server yourself and set `BRAIN_GPU_ENDPOINT`.
249
+ - The first start pulls the image and downloads the model. Expect 30 to 120 seconds and 1 to 2 GB of VRAM.
250
+ - Switching between `local` and `local-gpu` needs a re-embed.
251
+
252
+ More detail, including `BRAIN_GPU_PORT`, `BRAIN_GPU_IMAGE` and `BRAIN_GPU_ENGINE`, is in [docs/EMBEDDER.md](docs/EMBEDDER.md).
253
+
254
+ ### Re-embedding
255
+
256
+ If Qdrant is empty or recreated, the embed queue refills it from SQLite on its own. To force a full re-index:
257
+
258
+ ```bash
259
+ curl -X POST http://127.0.0.1:3737/maintenance/reembed \
260
+ -H "Authorization: Bearer $BRAIN_API_KEY"
261
+ ```
262
+
263
+ It builds a new collection and swaps an alias when it's done, so search never sees a mix of old and new vectors.
264
+
265
+ ## Dashboard
266
+
267
+ <http://127.0.0.1:3737/dashboard> has seven tabs:
268
+
269
+ 1. **Overview**: counts for every table, dead-letter and embed-queue depth, scope breakdown.
270
+ 2. **Long Term**: notes and lessons, their concepts and files, and the queue for fixing `unknown` scope.
271
+ 3. **Short Term**: sessions and the next-actions queue.
272
+ 4. **Observations**: raw trajectories, observations, summaries with links to their sources, and session replay.
273
+ 5. **Graph**: notes, concepts, files, sessions, actions and summaries as a graph.
274
+ 6. **Search & Inject**: run a search and see the dense, BM25 and fused scores; preview what `/inject` would send.
275
+ 7. **System & AI**: failure patterns, dead letters, and the AI conformance tests.
276
+
277
+ It doesn't use `innerHTML` or `localStorage`, and it runs under a strict CSP. Login is an `HttpOnly` cookie tied to the current API key, so rotating or revoking the key logs out every browser session.
278
+
279
+ ## Scripts
280
+
281
+ | Command | What it does |
282
+ |---|---|
283
+ | `npm run build` | compile to `dist/` |
284
+ | `npm start` | run the compiled service |
285
+ | `npm run dev` | run with auto-reload |
286
+ | `npm test` | Jest unit, integration and QA suites |
287
+ | `npm run typecheck` | `tsc --noEmit` |
288
+ | `npm run mcp` | stdio MCP server |
289
+ | `npm run install-agent` | wire up agents |
290
+ | `npm run doctor` | health checks and AI conformance tests |
291
+ | `npm run smoke` | end-to-end check against a live service and Qdrant |
292
+ | `npm run api-key:create` | make a new API key |
293
+
294
+ ## Docs
295
+
296
+ - [CLAUDE.md](CLAUDE.md) / [AGENTS.md](AGENTS.md): the rules, for agents working on this repo
297
+ - [docs/API.md](docs/API.md): HTTP endpoints
298
+ - [docs/MCP.md](docs/MCP.md): MCP tools
299
+ - [docs/SCHEMA.md](docs/SCHEMA.md): SQLite schema and Qdrant payloads
300
+ - [docs/EMBEDDER.md](docs/EMBEDDER.md): embedders, Matryoshka truncation, benchmarks, re-embed cutover
301
+ - [docs/CONSOLIDATION.md](docs/CONSOLIDATION.md) and [docs/CONTRACTS.md](docs/CONTRACTS.md): how summaries are produced and checked
302
+ - [docs/DIVERGENCES.md](docs/DIVERGENCES.md): where this differs from NeuralSwarm and why
303
+ - [.env.example](.env.example): every setting, with comments
304
+
305
+ ## License
306
+
307
+ MIT with the Commons Clause. You can use, change and share it, but you can't sell it. See [LICENSE](LICENSE).
308
+
309
+ ## Contributing
310
+
311
+ Issues and PRs are welcome. Use TypeScript, add Jest tests, and run `npm test` and `npm run typecheck` before you open a PR.
312
+
313
+ On npm 10 with an NVIDIA GPU, run `ONNXRUNTIME_NODE_INSTALL_CUDA=skip npm install`. Otherwise onnxruntime-node's install script tries to download a CUDA add-on the brain never uses.
@@ -0,0 +1,45 @@
1
+ /**
2
+ * One call site for every generative request the brain makes itself.
3
+ *
4
+ * It owns the three things a worker needs and nothing else: a request timeout,
5
+ * a circuit breaker, and an optional fallback chain. It deliberately does not
6
+ * inspect the model's text — an empty reply, a truncated reply and
7
+ * unparseable JSON are all *verification* outcomes, handled by the gate so
8
+ * they land in `dead_letters` attributed to the producer that caused them.
9
+ *
10
+ * The asymmetry with the embedder is intentional (CLAUDE.md, "A deliberate
11
+ * asymmetry"): a consolidator may fall back because every derived row records
12
+ * which producer actually wrote it and can be deleted and regenerated. The
13
+ * embedder may not, because a different vector space is not recoverable.
14
+ */
15
+ import { type GenerativeFunction, type ResolvedChatConfig } from './config';
16
+ import { type ChatReply, type GenerativeAdapter } from './vendors';
17
+ import type { GenerativeTier } from '../learning/types';
18
+ export interface ChatAttempt {
19
+ tier: GenerativeTier;
20
+ model: string | null;
21
+ ok: boolean;
22
+ error?: string;
23
+ }
24
+ export interface ChatCompletion extends ChatReply {
25
+ /** What goes into `summaries.producer_tier`. */
26
+ producer_tier: GenerativeTier;
27
+ /** What goes into `summaries.producer_model`. */
28
+ producer_model: string | null;
29
+ producer_key: string;
30
+ /** Every tier tried, in order, including the ones that failed. */
31
+ attempts: ChatAttempt[];
32
+ }
33
+ export declare function resetReasoningProbeCache(): void;
34
+ export declare function adapterFor(tier: GenerativeTier, fn: GenerativeFunction): GenerativeAdapter;
35
+ /**
36
+ * Runs the configured producer for `fn`. Throws only on transport failure —
37
+ * a dead endpoint, a timeout, an open breaker, a misconfiguration. A 200 with
38
+ * useless content comes back as a normal ChatCompletion, because the gate is
39
+ * what decides whether content is acceptable.
40
+ */
41
+ export declare function runChat(fn: GenerativeFunction, prompt: {
42
+ system: string;
43
+ user: string;
44
+ }, configOverride?: ResolvedChatConfig): Promise<ChatCompletion>;
45
+ //# sourceMappingURL=chat.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat.d.ts","sourceRoot":"","sources":["../../src/ai/chat.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;GAaG;AAIH,OAAO,EAIL,KAAK,kBAAkB,EACvB,KAAK,kBAAkB,EACxB,MAAM,UAAU,CAAC;AAOlB,OAAO,EAIL,KAAK,SAAS,EACd,KAAK,iBAAiB,EACvB,MAAM,WAAW,CAAC;AACnB,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,mBAAmB,CAAC;AAExD,MAAM,WAAW,WAAW;IAC1B,IAAI,EAAE,cAAc,CAAC;IACrB,KAAK,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,EAAE,EAAE,OAAO,CAAC;IACZ,KAAK,CAAC,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,cAAe,SAAQ,SAAS;IAC/C,gDAAgD;IAChD,aAAa,EAAE,cAAc,CAAC;IAC9B,iDAAiD;IACjD,cAAc,EAAE,MAAM,GAAG,IAAI,CAAC;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,kEAAkE;IAClE,QAAQ,EAAE,WAAW,EAAE,CAAC;CACzB;AAKD,wBAAgB,wBAAwB,IAAI,IAAI,CAE/C;AAcD,wBAAgB,UAAU,CAAC,IAAI,EAAE,cAAc,EAAE,EAAE,EAAE,kBAAkB,GAAG,iBAAiB,CAY1F;AA8DD;;;;;GAKG;AACH,wBAAsB,OAAO,CAC3B,EAAE,EAAE,kBAAkB,EACtB,MAAM,EAAE;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAA;CAAE,EACxC,cAAc,CAAC,EAAE,kBAAkB,GAClC,OAAO,CAAC,cAAc,CAAC,CAsDzB"}
@@ -0,0 +1,153 @@
1
+ "use strict";
2
+ /**
3
+ * One call site for every generative request the brain makes itself.
4
+ *
5
+ * It owns the three things a worker needs and nothing else: a request timeout,
6
+ * a circuit breaker, and an optional fallback chain. It deliberately does not
7
+ * inspect the model's text — an empty reply, a truncated reply and
8
+ * unparseable JSON are all *verification* outcomes, handled by the gate so
9
+ * they land in `dead_letters` attributed to the producer that caused them.
10
+ *
11
+ * The asymmetry with the embedder is intentional (CLAUDE.md, "A deliberate
12
+ * asymmetry"): a consolidator may fall back because every derived row records
13
+ * which producer actually wrote it and can be deleted and regenerated. The
14
+ * embedder may not, because a different vector space is not recoverable.
15
+ */
16
+ Object.defineProperty(exports, "__esModule", { value: true });
17
+ exports.resetReasoningProbeCache = resetReasoningProbeCache;
18
+ exports.adapterFor = adapterFor;
19
+ exports.runChat = runChat;
20
+ const logger_1 = require("../lib/logger");
21
+ const fixtures_1 = require("../consolidation/fixtures");
22
+ const config_1 = require("./config");
23
+ const circuitBreaker_1 = require("./circuitBreaker");
24
+ const vendors_1 = require("./vendors");
25
+ /** Memoised so the probe runs once per process, as docs/CONTRACTS.md specifies. */
26
+ let reasoningProbe = null;
27
+ function resetReasoningProbeCache() {
28
+ reasoningProbe = null;
29
+ }
30
+ async function reasoningHeadroom() {
31
+ if (!reasoningProbe) {
32
+ reasoningProbe = (0, fixtures_1.probeReasoningTokens)().catch(() => ({ probed: false, reasoningTokens: 0 }));
33
+ }
34
+ const { reasoningTokens } = await reasoningProbe;
35
+ if (reasoningTokens <= 0)
36
+ return 0;
37
+ // Budgets are sized from what the endpoint actually does, never from a
38
+ // no-think flag: on tested hardware a reasoning build burned 5,820 of a
39
+ // 6,000-token budget thinking and returned nothing.
40
+ return reasoningTokens * 2;
41
+ }
42
+ function adapterFor(tier, fn) {
43
+ const producer = (0, config_1.resolveProducer)(tier, fn);
44
+ if (producer.tier === 'remote') {
45
+ return (0, vendors_1.createRemoteAdapter)(producer.endpoint);
46
+ }
47
+ if (producer.tier === 'vendor') {
48
+ return (0, vendors_1.createVendorAdapter)(producer.vendor);
49
+ }
50
+ throw new config_1.AiConfigurationError(`tier '${tier}' has no adapter: 'none' is a finished state and 'agent' means the host agent does the ` +
51
+ 'work over MCP, so neither is something the brain can call itself.');
52
+ }
53
+ /** The model name as the provider expects it, stripped of the vendor prefix. */
54
+ function wireModel(tier, fn) {
55
+ const producer = (0, config_1.resolveProducer)(tier, fn);
56
+ const model = producer.model ?? '';
57
+ return producer.tier === 'vendor' ? model.slice(model.indexOf('/') + 1) : model;
58
+ }
59
+ async function attemptTier(tier, cfg, prompt, maxTokens) {
60
+ const producer = (0, config_1.resolveProducer)(tier, cfg.fn);
61
+ const adapter = adapterFor(tier, cfg.fn);
62
+ const breakerOptions = {
63
+ threshold: cfg.breakerThreshold,
64
+ cooldownMs: cfg.breakerCooldownMs,
65
+ };
66
+ (0, circuitBreaker_1.assertCircuitClosed)(producer.key, breakerOptions);
67
+ const controller = new AbortController();
68
+ const timer = setTimeout(() => controller.abort(), cfg.timeoutMs);
69
+ try {
70
+ const reply = await adapter.complete({
71
+ system: prompt.system,
72
+ user: prompt.user,
73
+ model: wireModel(tier, cfg.fn),
74
+ maxTokens,
75
+ signal: controller.signal,
76
+ });
77
+ (0, circuitBreaker_1.recordSuccess)(producer.key);
78
+ if (reply.reasoning_tokens > 0) {
79
+ logger_1.logger.warn({ producer: producer.key, reasoningTokens: reply.reasoning_tokens }, 'generative producer reported reasoning tokens — extraction needs no reasoning; ' +
80
+ 'prefer a non-reasoning instruct build and size BRAIN_CHAT_MAX_TOKENS accordingly');
81
+ }
82
+ return {
83
+ ...reply,
84
+ producer_tier: producer.tier,
85
+ producer_model: producer.model,
86
+ producer_key: producer.key,
87
+ attempts: [{ tier, model: producer.model, ok: true }],
88
+ };
89
+ }
90
+ catch (err) {
91
+ if (!(0, circuitBreaker_1.isCircuitOpenError)(err)) {
92
+ (0, circuitBreaker_1.recordFailure)(producer.key, err, breakerOptions);
93
+ }
94
+ throw err;
95
+ }
96
+ finally {
97
+ clearTimeout(timer);
98
+ }
99
+ }
100
+ /**
101
+ * Runs the configured producer for `fn`. Throws only on transport failure —
102
+ * a dead endpoint, a timeout, an open breaker, a misconfiguration. A 200 with
103
+ * useless content comes back as a normal ChatCompletion, because the gate is
104
+ * what decides whether content is acceptable.
105
+ */
106
+ async function runChat(fn, prompt, configOverride) {
107
+ const cfg = configOverride ?? (0, config_1.resolveChatConfig)(fn);
108
+ if (cfg.tier === 'none' || cfg.tier === 'agent') {
109
+ throw new config_1.AiConfigurationError(`generative function '${fn}' resolves to tier '${cfg.tier}', which the brain cannot call itself. ` +
110
+ "'none' is a finished state; 'agent' means the host agent does the work over MCP.");
111
+ }
112
+ const maxTokens = cfg.maxTokens + (await reasoningHeadroom());
113
+ const chain = [cfg.tier, ...cfg.fallbackTiers];
114
+ const attempts = [];
115
+ let lastError;
116
+ for (const tier of chain) {
117
+ try {
118
+ const result = await attemptTier(tier, cfg, prompt, maxTokens);
119
+ return { ...result, attempts: [...attempts, ...result.attempts] };
120
+ }
121
+ catch (err) {
122
+ lastError = err;
123
+ if (err instanceof config_1.AiConfigurationError)
124
+ throw err;
125
+ if (!(0, vendors_1.isChatTransportError)(err) && !(0, circuitBreaker_1.isCircuitOpenError)(err))
126
+ throw err;
127
+ let model = null;
128
+ try {
129
+ model = (0, config_1.resolveProducer)(tier, cfg.fn).model;
130
+ }
131
+ catch {
132
+ model = null;
133
+ }
134
+ attempts.push({
135
+ tier,
136
+ model,
137
+ ok: false,
138
+ error: err instanceof Error ? err.message : String(err),
139
+ });
140
+ logger_1.logger.warn({ fn, tier, error: err instanceof Error ? err.message : String(err) }, chain.indexOf(tier) < chain.length - 1
141
+ ? 'generative producer failed, falling back to the next tier'
142
+ : 'generative producer failed and no fallback remains');
143
+ }
144
+ }
145
+ const summary = attempts.map((a) => `${a.tier}(${a.model ?? '-'}): ${a.error}`).join('; ');
146
+ const error = new Error(`every generative producer for '${fn}' failed — ${summary}. ` +
147
+ 'Nothing was written and nothing was dead-lettered: a dependency being down is never a dead letter (rule 3).');
148
+ error.code = 'chat_unavailable';
149
+ error.attempts = attempts;
150
+ error.cause = lastError;
151
+ throw error;
152
+ }
153
+ //# sourceMappingURL=chat.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"chat.js","sourceRoot":"","sources":["../../src/ai/chat.ts"],"names":[],"mappings":";AAAA;;;;;;;;;;;;;GAaG;;AA8CH,4DAEC;AAcD,gCAYC;AAoED,0BA0DC;AAtMD,0CAAuC;AACvC,wDAAiE;AACjE,qCAMkB;AAClB,qDAK0B;AAC1B,uCAMmB;AAoBnB,mFAAmF;AACnF,IAAI,cAAc,GAAiE,IAAI,CAAC;AAExF,SAAgB,wBAAwB;IACtC,cAAc,GAAG,IAAI,CAAC;AACxB,CAAC;AAED,KAAK,UAAU,iBAAiB;IAC9B,IAAI,CAAC,cAAc,EAAE,CAAC;QACpB,cAAc,GAAG,IAAA,+BAAoB,GAAE,CAAC,KAAK,CAAC,GAAG,EAAE,CAAC,CAAC,EAAE,MAAM,EAAE,KAAK,EAAE,eAAe,EAAE,CAAC,EAAE,CAAC,CAAC,CAAC;IAC/F,CAAC;IACD,MAAM,EAAE,eAA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kC,EAAE,cAAc,OAAO,IAAI;QAC3D,6GAA6G,CAChH,CAAC;IACD,KAAa,CAAC,IAAI,GAAG,kBAAkB,CAAC;IACxC,KAAa,CAAC,QAAQ,GAAG,QAAQ,CAAC;IAClC,KAAa,CAAC,KAAK,GAAG,SAAS,CAAC;IACjC,MAAM,KAAK,CAAC;AACd,CAAC"}
@@ -0,0 +1,35 @@
1
+ /**
2
+ * A circuit breaker so a dead endpoint cannot stall the consolidation queue.
3
+ *
4
+ * A pattern worth keeping from earlier memory tools. Keyed per
5
+ * producer (tier + endpoint/vendor + model) so one dead vendor does not open
6
+ * the circuit for a healthy local endpoint.
7
+ *
8
+ * A tripped breaker is a *dependency* failure, never a dead letter: rule 3
9
+ * says dead letters are for malformed records only, never for a dependency
10
+ * being down.
11
+ */
12
+ export declare class CircuitOpenError extends Error {
13
+ readonly code = "circuit_open";
14
+ readonly retryAfterMs: number;
15
+ constructor(key: string, retryAfterMs: number);
16
+ }
17
+ export declare function isCircuitOpenError(error: unknown): error is CircuitOpenError;
18
+ export interface BreakerOptions {
19
+ threshold: number;
20
+ cooldownMs: number;
21
+ /** Injectable for tests; defaults to Date.now. */
22
+ now?: () => number;
23
+ }
24
+ /** Throws CircuitOpenError when the breaker is open and still cooling down. */
25
+ export declare function assertCircuitClosed(key: string, options: BreakerOptions): void;
26
+ export declare function recordSuccess(key: string): void;
27
+ export declare function recordFailure(key: string, error: unknown, options: BreakerOptions): void;
28
+ export declare function getBreakerStatus(): Array<{
29
+ producer: string;
30
+ open: boolean;
31
+ consecutive_failures: number;
32
+ last_error: string | null;
33
+ }>;
34
+ export declare function resetCircuitBreakers(): void;
35
+ //# sourceMappingURL=circuitBreaker.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"circuitBreaker.d.ts","sourceRoot":"","sources":["../../src/ai/circuitBreaker.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;GAUG;AAIH,qBAAa,gBAAiB,SAAQ,KAAK;IACzC,QAAQ,CAAC,IAAI,kBAAkB;IAC/B,QAAQ,CAAC,YAAY,EAAE,MAAM,CAAC;gBAElB,GAAG,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM;CAQ9C;AAED,wBAAgB,kBAAkB,CAAC,KAAK,EAAE,OAAO,GAAG,KAAK,IAAI,gBAAgB,CAE5E;AAmBD,MAAM,WAAW,cAAc;IAC7B,SAAS,EAAE,MAAM,CAAC;IAClB,UAAU,EAAE,MAAM,CAAC;IACnB,kDAAkD;IAClD,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB;AAED,+EAA+E;AAC/E,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,MAAM,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CAe9E;AAED,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,GAAG,IAAI,CAQ/C;AAED,wBAAgB,aAAa,CAAC,GAAG,EAAE,MAAM,EAAE,KAAK,EAAE,OAAO,EAAE,OAAO,EAAE,cAAc,GAAG,IAAI,CAiBxF;AAED,wBAAgB,gBAAgB,IAAI,KAAK,CAAC;IACxC,QAAQ,EAAE,MAAM,CAAC;IACjB,IAAI,EAAE,OAAO,CAAC;IACd,oBAAoB,EAAE,MAAM,CAAC;IAC7B,UAAU,EAAE,MAAM,GAAG,IAAI,CAAC;CAC3B,CAAC,CAOD;AAED,wBAAgB,oBAAoB,IAAI,IAAI,CAE3C"}
@@ -0,0 +1,95 @@
1
+ "use strict";
2
+ /**
3
+ * A circuit breaker so a dead endpoint cannot stall the consolidation queue.
4
+ *
5
+ * A pattern worth keeping from earlier memory tools. Keyed per
6
+ * producer (tier + endpoint/vendor + model) so one dead vendor does not open
7
+ * the circuit for a healthy local endpoint.
8
+ *
9
+ * A tripped breaker is a *dependency* failure, never a dead letter: rule 3
10
+ * says dead letters are for malformed records only, never for a dependency
11
+ * being down.
12
+ */
13
+ Object.defineProperty(exports, "__esModule", { value: true });
14
+ exports.CircuitOpenError = void 0;
15
+ exports.isCircuitOpenError = isCircuitOpenError;
16
+ exports.assertCircuitClosed = assertCircuitClosed;
17
+ exports.recordSuccess = recordSuccess;
18
+ exports.recordFailure = recordFailure;
19
+ exports.getBreakerStatus = getBreakerStatus;
20
+ exports.resetCircuitBreakers = resetCircuitBreakers;
21
+ const logger_1 = require("../lib/logger");
22
+ class CircuitOpenError extends Error {
23
+ code = 'circuit_open';
24
+ retryAfterMs;
25
+ constructor(key, retryAfterMs) {
26
+ super(`circuit breaker open for producer '${key}' — retry in ${retryAfterMs}ms. ` +
27
+ 'No record was written and nothing was dead-lettered; this is a dependency failure.');
28
+ this.name = 'CircuitOpenError';
29
+ this.retryAfterMs = retryAfterMs;
30
+ }
31
+ }
32
+ exports.CircuitOpenError = CircuitOpenError;
33
+ function isCircuitOpenError(error) {
34
+ return error instanceof CircuitOpenError;
35
+ }
36
+ const breakers = new Map();
37
+ function stateFor(key) {
38
+ let state = breakers.get(key);
39
+ if (!state) {
40
+ state = { consecutiveFailures: 0, openedAt: null, lastError: null };
41
+ breakers.set(key, state);
42
+ }
43
+ return state;
44
+ }
45
+ /** Throws CircuitOpenError when the breaker is open and still cooling down. */
46
+ function assertCircuitClosed(key, options) {
47
+ const state = stateFor(key);
48
+ if (state.openedAt === null)
49
+ return;
50
+ const now = (options.now ?? Date.now)();
51
+ const elapsed = now - state.openedAt;
52
+ if (elapsed < options.cooldownMs) {
53
+ throw new CircuitOpenError(key, options.cooldownMs - elapsed);
54
+ }
55
+ // Cooldown elapsed: half-open. One request is allowed through; its result
56
+ // either closes the breaker or re-opens it.
57
+ state.openedAt = null;
58
+ state.consecutiveFailures = options.threshold - 1;
59
+ logger_1.logger.info({ producer: key }, 'circuit breaker half-open, allowing one probe request');
60
+ }
61
+ function recordSuccess(key) {
62
+ const state = stateFor(key);
63
+ if (state.consecutiveFailures > 0 || state.openedAt !== null) {
64
+ logger_1.logger.info({ producer: key }, 'circuit breaker closed after successful request');
65
+ }
66
+ state.consecutiveFailures = 0;
67
+ state.openedAt = null;
68
+ state.lastError = null;
69
+ }
70
+ function recordFailure(key, error, options) {
71
+ const state = stateFor(key);
72
+ state.consecutiveFailures += 1;
73
+ state.lastError = error instanceof Error ? error.message : String(error);
74
+ if (state.consecutiveFailures >= options.threshold && state.openedAt === null) {
75
+ state.openedAt = (options.now ?? Date.now)();
76
+ logger_1.logger.error({
77
+ producer: key,
78
+ consecutiveFailures: state.consecutiveFailures,
79
+ cooldownMs: options.cooldownMs,
80
+ lastError: state.lastError,
81
+ }, 'circuit breaker opened for generative producer');
82
+ }
83
+ }
84
+ function getBreakerStatus() {
85
+ return Array.from(breakers.entries()).map(([producer, state]) => ({
86
+ producer,
87
+ open: state.openedAt !== null,
88
+ consecutive_failures: state.consecutiveFailures,
89
+ last_error: state.lastError,
90
+ }));
91
+ }
92
+ function resetCircuitBreakers() {
93
+ breakers.clear();
94
+ }
95
+ //# sourceMappingURL=circuitBreaker.js.map