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,1046 @@
1
+ "use strict";
2
+ var __importDefault = (this && this.__importDefault) || function (mod) {
3
+ return (mod && mod.__esModule) ? mod : { "default": mod };
4
+ };
5
+ Object.defineProperty(exports, "__esModule", { value: true });
6
+ exports.AGENTMEMORY_BLOCK_END = exports.AGENTMEMORY_BLOCK_START = exports.BRAIN_BLOCK_END = exports.BRAIN_BLOCK_START = void 0;
7
+ exports.generateBrainRuleBlock = generateBrainRuleBlock;
8
+ exports.generateBrainSkillContent = generateBrainSkillContent;
9
+ exports.upsertBrainRuleBlock = upsertBrainRuleBlock;
10
+ exports.resolveApiKey = resolveApiKey;
11
+ exports.resolveApiUrl = resolveApiUrl;
12
+ exports.formatNodeHookCommand = formatNodeHookCommand;
13
+ exports.installRuntimeHooks = installRuntimeHooks;
14
+ exports.installAgentIntegration = installAgentIntegration;
15
+ exports.parseCliArgs = parseCliArgs;
16
+ exports.printInstallAgentReport = printInstallAgentReport;
17
+ const fs_1 = __importDefault(require("fs"));
18
+ const path_1 = __importDefault(require("path"));
19
+ const os_1 = __importDefault(require("os"));
20
+ const dotenv_1 = __importDefault(require("dotenv"));
21
+ const scope_1 = require("../lib/scope");
22
+ const brainHome_1 = require("../lib/brainHome");
23
+ exports.BRAIN_BLOCK_START = '<!-- neuralbrain:start -->';
24
+ exports.BRAIN_BLOCK_END = '<!-- neuralbrain:end -->';
25
+ exports.AGENTMEMORY_BLOCK_START = '<!-- agentmemory:start -->';
26
+ exports.AGENTMEMORY_BLOCK_END = '<!-- agentmemory:end -->';
27
+ const BRAIN_BLOCK_REGEX = /<!-- neuralbrain:start -->[\s\S]*?<!-- neuralbrain:end -->/;
28
+ const AGENTMEMORY_BLOCK_REGEX = /<!-- agentmemory:start -->[\s\S]*?<!-- agentmemory:end -->/;
29
+ /**
30
+ * Generates the standardized instruction block teaching agents how to use neuralbrain.
31
+ */
32
+ function generateBrainRuleBlock(defaultProjectId) {
33
+ const projectScopeDesc = defaultProjectId
34
+ ? `Use for repository-specific knowledge. You MUST supply project_id: the name of the project's ROOT folder: the folder with .brainrc, otherwise the git repository root (for a worktree, the main repository), otherwise the folder the session started in. Never a subfolder you are working in, never a filesystem path (current default: '${defaultProjectId}').`
35
+ : `Use for repository-specific knowledge. You MUST supply project_id: the name of the project's ROOT folder: the folder with .brainrc, otherwise the git repository root (for a worktree, the main repository), otherwise the folder the session started in. Never a subfolder you are working in, never a filesystem path. If the root is ambiguous, run \`neuralbrain init\` there rather than guessing.`;
36
+ const exampleProjectId = defaultProjectId || 'my-project';
37
+ return [
38
+ exports.BRAIN_BLOCK_START,
39
+ '## Persistent Memory (neuralbrain)',
40
+ '',
41
+ 'You have persistent memory via the `neuralbrain` MCP server.',
42
+ 'Available tools: `brain_search`, `brain_save`, `brain_recent_failures`, `brain_consolidate_candidates`, `brain_submit_summary`.',
43
+ '',
44
+ '### Workflow & Rules',
45
+ '- **At the start of a task or session**:',
46
+ ' - Call `brain_recent_failures` to check for active failure patterns or bugs in this project.',
47
+ ' - Call `brain_search` with your task context to load relevant past architectural decisions, patterns, and conventions (default `record_types`: `["note", "trajectory"]`).',
48
+ ' - **When to also search `summary` (`record_types: ["note", "trajectory", "summary"]` or `["summary"]`)**:',
49
+ ' - Resuming work on a file or feature where you need to see what a previous session changed (`files_touched` and literal claims).',
50
+ ' - Debugging a recurring or historical error (`error_verbatim` across past sessions).',
51
+ ' - Default `brain_search` returns nothing because no curated `note` was saved yet.',
52
+ ' - If `SessionStart` / `/inject` shows a `CONSOLIDATION REMINDER`, let the user know and suggest they start a new session with an example prompt (e.g., `"Consolidate the brain observations for this project."`).',
53
+ '- **When to save notes (`brain_save`) — DO NOT wait until session end**:',
54
+ ' - **Bug / root cause fixed** (`type: "bug"` or `"lesson"`): You diagnosed a non-obvious error, race condition, or config mismatch.',
55
+ ' - **Architectural or design decision** (`type: "architecture"`): You or the user chose a pattern, library, schema, or trade-off.',
56
+ ' - **Gotcha / environment quirk** (`type: "fact"` or `"lesson"`): You hit an undocumented API behavior, build/deploy constraint, or silent failure.',
57
+ ' - **Project convention or workflow** (`type: "pattern"` or `"workflow"`): You discovered or established a repo-specific convention or command sequence.',
58
+ ' - **User correction or preference** (`type: "preference"` or `"lesson"`): The user corrected your approach or stated how they want things done.',
59
+ ' - **Before concluding any non-trivial task**, ask yourself: *"What would save the next agent 10 minutes?"* If anything qualifies, call `brain_save` before your final response.',
60
+ ' - **What NOT to save**: Routine file reads, obvious edits, or raw tool logs (observations are captured automatically).',
61
+ '- **Example `brain_save` call**:',
62
+ ` \`brain_save({ type: "bug", title: "Cloud Functions require explicit CORS origin", content: "Firebase callable/HTTP functions fail preflight in staging unless...", scope: "project", project_id: "${exampleProjectId}", files: ["functions/src/index.ts"], concepts: ["cors", "firebase"] })\``,
63
+ '- **Scope Discipline (Rule 4)**: Explicit scope is mandatory (`project`, `global`, or `unknown`):',
64
+ ` - \`scope: "project"\`: ${projectScopeDesc}`,
65
+ ' - `scope: "global"`: Use ONLY for universal truths across all projects, environments, and languages.',
66
+ ' - `scope: "unknown"`: Default fallback only when project scope is genuinely unknown.',
67
+ exports.BRAIN_BLOCK_END,
68
+ ].join('\n');
69
+ }
70
+ /**
71
+ * Generates the standardized brain-memory SKILL.md content for Antigravity.
72
+ */
73
+ function generateBrainSkillContent() {
74
+ return [
75
+ '---',
76
+ 'name: brain-memory',
77
+ 'description: Persistent memory and failure pattern injection via neuralbrain. Use to search past learnings, record durable project insights, and check known failure patterns.',
78
+ '---',
79
+ '',
80
+ '# neuralbrain Persistent Memory',
81
+ '',
82
+ '## At Task Start',
83
+ '1. Check `brain_recent_failures` to avoid repeating known mistakes.',
84
+ '2. Search prior solutions, conventions, and architecture with `brain_search` (defaults to `record_types: ["note", "trajectory"]`).',
85
+ '3. Include `"summary"` in `record_types` (e.g. `record_types: ["note", "trajectory", "summary"]`) when resuming work on a file, debugging a recurring error, or when no curated `note` exists yet.',
86
+ '4. If `CONSOLIDATION REMINDER` appears in session context, let the user know and suggest they start a new session with an example prompt (e.g., `"Consolidate the brain observations for this project."`).',
87
+ '',
88
+ '## When to Save Notes (`brain_save`)',
89
+ 'Tool-call observations are captured automatically as telemetry, **not** as notes. Call `brain_save` immediately (or before finishing your task) whenever you:',
90
+ '- Fix a non-trivial bug or uncover a subtle root cause (`type: "bug"` or `"lesson"`).',
91
+ '- Make or change an architectural/design decision (`type: "architecture"`).',
92
+ '- Discover an undocumented gotcha, environment constraint, or API quirk (`type: "fact"` or `"lesson"`).',
93
+ '- Establish or uncover a project convention or workflow (`type: "pattern"` or `"workflow"`).',
94
+ '- Receive a correction or preference from the user (`type: "preference"` or `"lesson"`).',
95
+ '',
96
+ 'Keep notes concise and factual, include `files` and `concepts`, and always pass explicit `scope` (`"project"` with `project_id` folder slug, `"global"`, or `"unknown"`).',
97
+ '',
98
+ '## Consolidation (`brain_consolidate_candidates` / `brain_submit_summary`)',
99
+ 'When asked by the user to consolidate observations for a project, call `brain_consolidate_candidates` and submit strictly literal, observation-cited extractions via `brain_submit_summary`. Always redact any API keys, tokens, passwords, or other sensitive info before submitting.',
100
+ '',
101
+ ].join('\n');
102
+ }
103
+ /**
104
+ * Idempotently updates or appends the neuralbrain rule block in markdown documentation.
105
+ * Replaces any existing neuralbrain block in place.
106
+ * If replaceAgentMemory is true, replaces legacy agentmemory blocks.
107
+ * Otherwise appends cleanly to the end of the file.
108
+ */
109
+ function upsertBrainRuleBlock(markdownContent, defaultProjectId, replaceAgentMemory = false) {
110
+ const block = generateBrainRuleBlock(defaultProjectId);
111
+ if (BRAIN_BLOCK_REGEX.test(markdownContent)) {
112
+ return markdownContent.replace(BRAIN_BLOCK_REGEX, block);
113
+ }
114
+ if (replaceAgentMemory && AGENTMEMORY_BLOCK_REGEX.test(markdownContent)) {
115
+ return markdownContent.replace(AGENTMEMORY_BLOCK_REGEX, block);
116
+ }
117
+ const trimmed = markdownContent.trimEnd();
118
+ if (!trimmed) {
119
+ return `${block}\n`;
120
+ }
121
+ return `${trimmed}\n\n${block}\n`;
122
+ }
123
+ /**
124
+ * Parses an environment file into key-value pairs without modifying process.env.
125
+ */
126
+ function parseEnvFile(filePath) {
127
+ if (!fs_1.default.existsSync(filePath)) {
128
+ return {};
129
+ }
130
+ try {
131
+ const raw = fs_1.default.readFileSync(filePath, 'utf8');
132
+ return dotenv_1.default.parse(raw);
133
+ }
134
+ catch {
135
+ return {};
136
+ }
137
+ }
138
+ /**
139
+ * Returns prioritized candidates for .env file lookups.
140
+ */
141
+ function getEnvCandidates(brainRepoDir, projectDir, homeDir) {
142
+ const candidates = [];
143
+ if (projectDir) {
144
+ candidates.push(path_1.default.join(projectDir, '.env.local'));
145
+ candidates.push(path_1.default.join(projectDir, '.env'));
146
+ }
147
+ candidates.push(path_1.default.join(brainRepoDir, '.env.local'));
148
+ candidates.push(path_1.default.join(brainRepoDir, '.env'));
149
+ candidates.push(...(0, brainHome_1.getBrainEnvCandidates)(homeDir));
150
+ return candidates;
151
+ }
152
+ /**
153
+ * Resolves optional API key in prioritized order:
154
+ * 1. options.apiKey (programmatic option)
155
+ * 2. process.env.BRAIN_API_KEY
156
+ * 3. Parsed from ${projectDir}/.env, ${brainRepoDir}/.env, or ~/.neuralbrain/.env (.env.local has priority)
157
+ * 4. ~/.neuralbrain/data/api-key.txt or <brainRepoDir>/data/api-key.txt
158
+ */
159
+ function resolveApiKey(options, brainRepoDir, projectDir, homeDir) {
160
+ if (options.apiKey && options.apiKey.trim()) {
161
+ return options.apiKey.trim();
162
+ }
163
+ if (process.env.BRAIN_API_KEY && process.env.BRAIN_API_KEY.trim()) {
164
+ return process.env.BRAIN_API_KEY.trim();
165
+ }
166
+ for (const envPath of getEnvCandidates(brainRepoDir, projectDir, homeDir)) {
167
+ const parsed = parseEnvFile(envPath);
168
+ if (parsed.BRAIN_API_KEY && parsed.BRAIN_API_KEY.trim()) {
169
+ return parsed.BRAIN_API_KEY.trim();
170
+ }
171
+ }
172
+ const keyFileCandidates = [
173
+ path_1.default.join((0, brainHome_1.getBrainDataDir)(homeDir), 'api-key.txt'),
174
+ path_1.default.join(brainRepoDir, 'data', 'api-key.txt'),
175
+ ];
176
+ for (const keyFilePath of keyFileCandidates) {
177
+ if (fs_1.default.existsSync(keyFilePath)) {
178
+ try {
179
+ const content = fs_1.default.readFileSync(keyFilePath, 'utf8').trim();
180
+ if (content) {
181
+ return content;
182
+ }
183
+ }
184
+ catch {
185
+ // Ignore file read errors
186
+ }
187
+ }
188
+ }
189
+ return undefined;
190
+ }
191
+ /**
192
+ * Resolves API URL in prioritized order:
193
+ * 1. options.apiUrl (programmatic option)
194
+ * 2. process.env.BRAIN_API_URL
195
+ * 3. Parsed from ${projectDir}/.env, ${brainRepoDir}/.env, or ~/.neuralbrain/.env (BRAIN_API_URL, or http://127.0.0.1:${PORT})
196
+ * 4. process.env.PORT
197
+ * 5. Default 'http://127.0.0.1:3737'
198
+ */
199
+ function resolveApiUrl(options, brainRepoDir, projectDir, homeDir) {
200
+ if (options.apiUrl && options.apiUrl.trim()) {
201
+ return options.apiUrl.trim();
202
+ }
203
+ if (process.env.BRAIN_API_URL && process.env.BRAIN_API_URL.trim()) {
204
+ return process.env.BRAIN_API_URL.trim();
205
+ }
206
+ for (const envPath of getEnvCandidates(brainRepoDir, projectDir, homeDir)) {
207
+ const parsed = parseEnvFile(envPath);
208
+ if (parsed.BRAIN_API_URL && parsed.BRAIN_API_URL.trim()) {
209
+ return parsed.BRAIN_API_URL.trim();
210
+ }
211
+ if (parsed.PORT && parsed.PORT.trim()) {
212
+ const portNum = parseInt(parsed.PORT.trim(), 10);
213
+ if (!Number.isNaN(portNum) && portNum > 0) {
214
+ return `http://127.0.0.1:${portNum}`;
215
+ }
216
+ }
217
+ }
218
+ if (process.env.PORT && process.env.PORT.trim()) {
219
+ const portNum = parseInt(process.env.PORT.trim(), 10);
220
+ if (!Number.isNaN(portNum) && portNum > 0) {
221
+ return `http://127.0.0.1:${portNum}`;
222
+ }
223
+ }
224
+ return 'http://127.0.0.1:3737';
225
+ }
226
+ /**
227
+ * Derives and normalizes a canonical project_id slug from options or directory path.
228
+ */
229
+ function resolveProjectSlug(rawDir, explicitId) {
230
+ if (explicitId && explicitId.trim()) {
231
+ const res = (0, scope_1.normalizeProjectId)(explicitId);
232
+ if (!res.ok) {
233
+ throw new Error(`Invalid explicit projectId '${explicitId}': ${res.error}`);
234
+ }
235
+ return res.projectId;
236
+ }
237
+ const folderName = path_1.default.basename(path_1.default.resolve(rawDir));
238
+ const directRes = (0, scope_1.normalizeProjectId)(folderName);
239
+ if (directRes.ok) {
240
+ return directRes.projectId;
241
+ }
242
+ // Attempt sanitizing non-standard folder names (e.g. spaces, special chars)
243
+ const sanitized = folderName
244
+ .trim()
245
+ .toLowerCase()
246
+ .replace(/[^a-z0-9._-]+/g, '-')
247
+ .replace(/^-+|-+$/g, '');
248
+ const sanitizedRes = (0, scope_1.normalizeProjectId)(sanitized);
249
+ if (sanitizedRes.ok) {
250
+ return sanitizedRes.projectId;
251
+ }
252
+ throw new Error(`Could not determine canonical project_id from directory '${rawDir}' (folder '${folderName}'): ${directRes.error}`);
253
+ }
254
+ function isClaudeHookRegistered(list, scriptName) {
255
+ return list.some((item) => {
256
+ if (typeof item === 'string')
257
+ return item.includes(scriptName);
258
+ if (item && typeof item.command === 'string')
259
+ return item.command.includes(scriptName);
260
+ if (item && Array.isArray(item.hooks)) {
261
+ return item.hooks.some((h) => h && typeof h.command === 'string' && h.command.includes(scriptName));
262
+ }
263
+ return false;
264
+ });
265
+ }
266
+ /**
267
+ * Formats a `node <scriptPath>` hook command, quoting the script path when it
268
+ * contains whitespace (e.g., Windows user directories like `C:\Users\John Doe\...`).
269
+ */
270
+ function formatNodeHookCommand(scriptPath) {
271
+ return /\s/.test(scriptPath) ? `node "${scriptPath}"` : `node ${scriptPath}`;
272
+ }
273
+ function installRuntimeHooks(homeDir, brainRepoDir, dryRun, report) {
274
+ const installedHooksDir = (0, brainHome_1.getBrainHooksDir)(homeDir);
275
+ const installedHooksLibDir = path_1.default.join(installedHooksDir, 'lib');
276
+ const hookFiles = ['sessionStart.js', 'postToolUse.js', 'sessionStop.js'];
277
+ for (const file of hookFiles) {
278
+ let srcPath = path_1.default.join(brainRepoDir, 'plugin', 'hooks', file);
279
+ if (!fs_1.default.existsSync(srcPath)) {
280
+ const fallback = path_1.default.resolve(__dirname, '../../plugin/hooks', file);
281
+ if (fs_1.default.existsSync(fallback))
282
+ srcPath = fallback;
283
+ }
284
+ if (fs_1.default.existsSync(srcPath)) {
285
+ const content = fs_1.default.readFileSync(srcPath, 'utf8');
286
+ safeWriteFile(path_1.default.join(installedHooksDir, file), content, dryRun, report);
287
+ if (!dryRun) {
288
+ try {
289
+ fs_1.default.chmodSync(path_1.default.join(installedHooksDir, file), 0o755);
290
+ }
291
+ catch {
292
+ // Ignore chmod errors on systems that don't support it
293
+ }
294
+ }
295
+ }
296
+ }
297
+ // Copy helper libraries to hooks/lib/
298
+ const libFiles = ['projectSlug.js', 'spool.js', 'scope.js', 'brainHome.js', 'logger.js'];
299
+ for (const file of libFiles) {
300
+ let srcPath = path_1.default.join(brainRepoDir, 'dist', 'lib', file);
301
+ if (!fs_1.default.existsSync(srcPath)) {
302
+ const fallback = path_1.default.resolve(__dirname, '../lib', file);
303
+ if (fs_1.default.existsSync(fallback)) {
304
+ srcPath = fallback;
305
+ }
306
+ else {
307
+ const distFallback = path_1.default.resolve(__dirname, '../../dist/lib', file);
308
+ if (fs_1.default.existsSync(distFallback))
309
+ srcPath = distFallback;
310
+ }
311
+ }
312
+ if (fs_1.default.existsSync(srcPath)) {
313
+ const content = fs_1.default.readFileSync(srcPath, 'utf8');
314
+ safeWriteFile(path_1.default.join(installedHooksLibDir, file), content, dryRun, report);
315
+ }
316
+ }
317
+ // Also copy dist/mcp/server.js to ~/.neuralbrain/mcp/
318
+ const installedMcpDir = (0, brainHome_1.getBrainMcpDir)(homeDir);
319
+ let mcpSrc = path_1.default.join(brainRepoDir, 'dist', 'mcp', 'server.js');
320
+ if (!fs_1.default.existsSync(mcpSrc)) {
321
+ const fallback = path_1.default.resolve(__dirname, '../mcp/server.js');
322
+ if (fs_1.default.existsSync(fallback)) {
323
+ mcpSrc = fallback;
324
+ }
325
+ else {
326
+ const distFallback = path_1.default.resolve(__dirname, '../../dist/mcp/server.js');
327
+ if (fs_1.default.existsSync(distFallback))
328
+ mcpSrc = distFallback;
329
+ }
330
+ }
331
+ if (fs_1.default.existsSync(mcpSrc)) {
332
+ const content = fs_1.default.readFileSync(mcpSrc, 'utf8');
333
+ safeWriteFile(path_1.default.join(installedMcpDir, 'server.js'), content, dryRun, report);
334
+ }
335
+ return installedHooksDir;
336
+ }
337
+ /**
338
+ * Resolves the source skills directory from brainRepoDir/plugin/skills (or fallback).
339
+ */
340
+ function resolveSourceSkillsDir(brainRepoDir) {
341
+ const candidate = path_1.default.join(brainRepoDir, 'plugin', 'skills');
342
+ if (fs_1.default.existsSync(candidate) && fs_1.default.statSync(candidate).isDirectory()) {
343
+ return candidate;
344
+ }
345
+ const fallback = path_1.default.resolve(__dirname, '../../plugin/skills');
346
+ if (fs_1.default.existsSync(fallback) && fs_1.default.statSync(fallback).isDirectory()) {
347
+ return fallback;
348
+ }
349
+ return null;
350
+ }
351
+ /**
352
+ * Copies all skill directories from sourceSkillsDir into canonicalDestDir idempotently,
353
+ * returning the list of installed skill names.
354
+ */
355
+ function syncCanonicalSkills(brainRepoDir, canonicalDestDir, dryRun, report) {
356
+ const sourceSkillsDir = resolveSourceSkillsDir(brainRepoDir);
357
+ if (!sourceSkillsDir) {
358
+ // Fallback for mock test directories that lack plugin/skills/
359
+ safeWriteFile(path_1.default.join(canonicalDestDir, 'brain-memory', 'SKILL.md'), generateBrainSkillContent(), dryRun, report);
360
+ return ['brain-memory'];
361
+ }
362
+ const skillDirs = fs_1.default
363
+ .readdirSync(sourceSkillsDir, { withFileTypes: true })
364
+ .filter((d) => d.isDirectory())
365
+ .map((d) => d.name)
366
+ .sort();
367
+ for (const skillName of skillDirs) {
368
+ const srcSkillPath = path_1.default.join(sourceSkillsDir, skillName);
369
+ const destSkillPath = path_1.default.join(canonicalDestDir, skillName);
370
+ const files = fs_1.default.readdirSync(srcSkillPath, { withFileTypes: true }).filter((f) => f.isFile());
371
+ for (const file of files) {
372
+ const content = fs_1.default.readFileSync(path_1.default.join(srcSkillPath, file.name), 'utf8');
373
+ safeWriteFile(path_1.default.join(destSkillPath, file.name), content, dryRun, report);
374
+ }
375
+ }
376
+ return skillDirs;
377
+ }
378
+ /**
379
+ * Creates or verifies a symlink from linkSkillsDir/<skillName> -> canonicalSkillsDir/<skillName>.
380
+ * Falls back to copying files if symlinks are not supported.
381
+ */
382
+ function linkSkillsIntoTarget(skillNames, canonicalSkillsDir, linkSkillsDir, dryRun, report) {
383
+ for (const skillName of skillNames) {
384
+ const canonicalDir = path_1.default.join(canonicalSkillsDir, skillName);
385
+ const linkPath = path_1.default.join(linkSkillsDir, skillName);
386
+ let alreadyLinked = false;
387
+ let exists = false;
388
+ try {
389
+ const stat = fs_1.default.lstatSync(linkPath);
390
+ exists = true;
391
+ if (stat.isSymbolicLink()) {
392
+ const target = path_1.default.resolve(path_1.default.dirname(linkPath), fs_1.default.readlinkSync(linkPath));
393
+ if (target === path_1.default.resolve(canonicalDir)) {
394
+ alreadyLinked = true;
395
+ }
396
+ }
397
+ }
398
+ catch {
399
+ exists = false;
400
+ }
401
+ if (alreadyLinked) {
402
+ report.skippedFiles.push(linkPath);
403
+ continue;
404
+ }
405
+ if (exists) {
406
+ report.modifiedFiles.push(linkPath);
407
+ }
408
+ else {
409
+ report.createdFiles.push(linkPath);
410
+ }
411
+ if (dryRun) {
412
+ continue;
413
+ }
414
+ fs_1.default.mkdirSync(path_1.default.dirname(linkPath), { recursive: true });
415
+ if (exists) {
416
+ fs_1.default.rmSync(linkPath, { recursive: true, force: true });
417
+ }
418
+ try {
419
+ fs_1.default.symlinkSync(canonicalDir, linkPath, 'dir');
420
+ }
421
+ catch {
422
+ // Fallback to copying if symlinks are restricted
423
+ if (fs_1.default.existsSync(canonicalDir)) {
424
+ const files = fs_1.default.readdirSync(canonicalDir, { withFileTypes: true }).filter((f) => f.isFile());
425
+ for (const file of files) {
426
+ const content = fs_1.default.readFileSync(path_1.default.join(canonicalDir, file.name), 'utf8');
427
+ fs_1.default.mkdirSync(linkPath, { recursive: true });
428
+ fs_1.default.writeFileSync(path_1.default.join(linkPath, file.name), content, 'utf8');
429
+ }
430
+ }
431
+ }
432
+ }
433
+ }
434
+ function safeReadJson(filePath) {
435
+ if (!fs_1.default.existsSync(filePath)) {
436
+ return null;
437
+ }
438
+ try {
439
+ const raw = fs_1.default.readFileSync(filePath, 'utf8');
440
+ return JSON.parse(raw);
441
+ }
442
+ catch {
443
+ return null;
444
+ }
445
+ }
446
+ function safeWriteFile(filePath, content, dryRun, report) {
447
+ const exists = fs_1.default.existsSync(filePath);
448
+ if (exists) {
449
+ try {
450
+ const existingContent = fs_1.default.readFileSync(filePath, 'utf8');
451
+ if (existingContent === content) {
452
+ report.skippedFiles.push(filePath);
453
+ return;
454
+ }
455
+ }
456
+ catch {
457
+ // Fall through to write
458
+ }
459
+ report.modifiedFiles.push(filePath);
460
+ }
461
+ else {
462
+ report.createdFiles.push(filePath);
463
+ }
464
+ if (!dryRun) {
465
+ const dir = path_1.default.dirname(filePath);
466
+ if (!fs_1.default.existsSync(dir)) {
467
+ fs_1.default.mkdirSync(dir, { recursive: true });
468
+ }
469
+ fs_1.default.writeFileSync(filePath, content, 'utf8');
470
+ }
471
+ }
472
+ function safeWriteJson(filePath, data, dryRun, report) {
473
+ const content = JSON.stringify(data, null, 2) + '\n';
474
+ safeWriteFile(filePath, content, dryRun, report);
475
+ }
476
+ /**
477
+ * Safely merges neuralbrain MCP server into an existing or new MCP config object.
478
+ */
479
+ function mergeMcpConfig(existingConfig, serverDef, replaceAgentMemory) {
480
+ const config = existingConfig && typeof existingConfig === 'object' ? { ...existingConfig } : {};
481
+ if (!config.mcpServers || typeof config.mcpServers !== 'object') {
482
+ config.mcpServers = {};
483
+ }
484
+ else {
485
+ config.mcpServers = { ...config.mcpServers };
486
+ }
487
+ config.mcpServers['neuralbrain'] = serverDef;
488
+ if (replaceAgentMemory && config.mcpServers['agentmemory']) {
489
+ delete config.mcpServers['agentmemory'];
490
+ }
491
+ return config;
492
+ }
493
+ /**
494
+ * Installs and configures multi-agent integration for neuralbrain.
495
+ */
496
+ function installAgentIntegration(options = {}) {
497
+ const homeDir = path_1.default.resolve(options.homeDir || os_1.default.homedir());
498
+ const brainRepoDir = path_1.default.resolve(options.brainRepoDir || path_1.default.resolve(__dirname, '../..'));
499
+ const projectDir = options.projectDir ? path_1.default.resolve(options.projectDir) : undefined;
500
+ const apiUrl = resolveApiUrl(options, brainRepoDir, projectDir, homeDir);
501
+ const apiKey = resolveApiKey(options, brainRepoDir, projectDir, homeDir);
502
+ const replaceAgentMemory = Boolean(options.replaceAgentMemory);
503
+ const enableHooks = options.enableHooks !== false;
504
+ const dryRun = Boolean(options.dryRun);
505
+ // Target selection logic:
506
+ // - If options.targets is explicitly passed, honor it.
507
+ // - Else if projectDir is provided: default to ['project'] ONLY (or add globals if options.global is true).
508
+ // - Else: default to global agents ['antigravity', 'claude', 'cursor'].
509
+ let requestedTargets;
510
+ if (options.targets && options.targets.length > 0) {
511
+ requestedTargets = options.targets;
512
+ }
513
+ else if (projectDir) {
514
+ requestedTargets = options.global
515
+ ? ['antigravity', 'claude', 'cursor', 'project']
516
+ : ['project'];
517
+ }
518
+ else {
519
+ requestedTargets = ['antigravity', 'claude', 'cursor'];
520
+ }
521
+ const report = {
522
+ success: true,
523
+ dryRun,
524
+ configuredTargets: [],
525
+ createdFiles: [],
526
+ modifiedFiles: [],
527
+ skippedFiles: [],
528
+ warnings: [],
529
+ };
530
+ if (options.apiKey) {
531
+ report.warnings.push('API key was provided directly. Setting BRAIN_API_KEY in .env is recommended to prevent credential leakage in command history or process listings.');
532
+ }
533
+ const globalMcpServerDef = {
534
+ command: 'neuralbrain',
535
+ args: ['mcp'],
536
+ env: {
537
+ BRAIN_API_URL: apiUrl,
538
+ ...(apiKey ? { BRAIN_API_KEY: apiKey } : {}),
539
+ },
540
+ };
541
+ const installedHooksDir = (0, brainHome_1.getBrainHooksDir)(homeDir);
542
+ const hasGlobalTargets = requestedTargets.some((t) => t !== 'project');
543
+ if (enableHooks && hasGlobalTargets) {
544
+ installRuntimeHooks(homeDir, brainRepoDir, dryRun, report);
545
+ }
546
+ const globalCanonicalSkillsDir = path_1.default.join(homeDir, '.agents', 'skills');
547
+ const globalSkillNames = hasGlobalTargets
548
+ ? syncCanonicalSkills(brainRepoDir, globalCanonicalSkillsDir, dryRun, report)
549
+ : [];
550
+ // ---------------------------------------------------------------------------
551
+ // Target 1: Antigravity (Global)
552
+ // ---------------------------------------------------------------------------
553
+ if (requestedTargets.includes('antigravity')) {
554
+ const pluginDir = path_1.default.join(homeDir, '.gemini', 'config', 'plugins', 'neuralbrain');
555
+ // 1. plugin.json
556
+ const pluginManifestPath = path_1.default.join(pluginDir, 'plugin.json');
557
+ safeWriteJson(pluginManifestPath, {
558
+ name: 'neuralbrain',
559
+ displayName: 'neuralbrain',
560
+ version: '0.0.2',
561
+ description: 'neuralbrain persistent memory service integration for Antigravity',
562
+ }, dryRun, report);
563
+ // 2. mcp_config.json in plugin (Streamable HTTP /mcp endpoint, not stdio)
564
+ const mcpUrl = `${apiUrl.replace(/\/+$/, '')}/mcp`;
565
+ const antigravityMcpServerDef = {
566
+ serverUrl: mcpUrl,
567
+ ...(apiKey ? { headers: { Authorization: `Bearer ${apiKey}` } } : {}),
568
+ };
569
+ const pluginMcpPath = path_1.default.join(pluginDir, 'mcp_config.json');
570
+ safeWriteJson(pluginMcpPath, {
571
+ mcpServers: {
572
+ neuralbrain: antigravityMcpServerDef,
573
+ },
574
+ }, dryRun, report);
575
+ // 3. hooks.json in plugin
576
+ const pluginHooksPath = path_1.default.join(pluginDir, 'hooks.json');
577
+ const sessionStartHook = formatNodeHookCommand(path_1.default.join(installedHooksDir, 'sessionStart.js'));
578
+ const postToolUseHook = formatNodeHookCommand(path_1.default.join(installedHooksDir, 'postToolUse.js'));
579
+ const sessionStopHook = formatNodeHookCommand(path_1.default.join(installedHooksDir, 'sessionStop.js'));
580
+ safeWriteJson(pluginHooksPath, {
581
+ neuralbrain: {
582
+ enabled: enableHooks,
583
+ SessionStart: [
584
+ {
585
+ type: 'command',
586
+ command: sessionStartHook,
587
+ timeout: 30,
588
+ },
589
+ ],
590
+ PostToolUse: [
591
+ {
592
+ matcher: '*',
593
+ hooks: [
594
+ {
595
+ type: 'command',
596
+ command: postToolUseHook,
597
+ timeout: 30,
598
+ },
599
+ ],
600
+ },
601
+ ],
602
+ Stop: [
603
+ {
604
+ type: 'command',
605
+ command: sessionStopHook,
606
+ timeout: 30,
607
+ },
608
+ ],
609
+ },
610
+ }, dryRun, report);
611
+ // 4. rules/AGENTS.md in plugin
612
+ const pluginRulesPath = path_1.default.join(pluginDir, 'rules', 'AGENTS.md');
613
+ const pluginRulesExisting = fs_1.default.existsSync(pluginRulesPath)
614
+ ? fs_1.default.readFileSync(pluginRulesPath, 'utf8')
615
+ : '';
616
+ safeWriteFile(pluginRulesPath, upsertBrainRuleBlock(pluginRulesExisting, undefined, false), dryRun, report);
617
+ // 5. Link canonical skills into plugin/skills/
618
+ linkSkillsIntoTarget(globalSkillNames, globalCanonicalSkillsDir, path_1.default.join(pluginDir, 'skills'), dryRun, report);
619
+ // 6. Global GEMINI.md
620
+ const geminiMdPath = path_1.default.join(homeDir, '.gemini', 'GEMINI.md');
621
+ const existingGeminiMd = fs_1.default.existsSync(geminiMdPath) ? fs_1.default.readFileSync(geminiMdPath, 'utf8') : '';
622
+ const updatedGeminiMd = upsertBrainRuleBlock(existingGeminiMd, undefined, replaceAgentMemory);
623
+ safeWriteFile(geminiMdPath, updatedGeminiMd, dryRun, report);
624
+ report.configuredTargets.push('antigravity');
625
+ }
626
+ // ---------------------------------------------------------------------------
627
+ // Target 2: Claude Code (Global)
628
+ // ---------------------------------------------------------------------------
629
+ if (requestedTargets.includes('claude')) {
630
+ // 1. ~/.claude.json
631
+ const claudeJsonPath = path_1.default.join(homeDir, '.claude.json');
632
+ const existingClaudeJson = safeReadJson(claudeJsonPath) || { mcpServers: {} };
633
+ const mergedClaudeJson = mergeMcpConfig(existingClaudeJson, globalMcpServerDef, replaceAgentMemory);
634
+ safeWriteJson(claudeJsonPath, mergedClaudeJson, dryRun, report);
635
+ // 2. ~/.claude/settings.json (hooks)
636
+ if (enableHooks) {
637
+ const settingsPath = path_1.default.join(homeDir, '.claude', 'settings.json');
638
+ const settings = safeReadJson(settingsPath) || {};
639
+ if (!settings.hooks || typeof settings.hooks !== 'object') {
640
+ settings.hooks = {};
641
+ }
642
+ const hookEvents = [
643
+ { event: 'SessionStart', script: 'sessionStart.js', matcher: '' },
644
+ { event: 'PostToolUse', script: 'postToolUse.js', matcher: '*' },
645
+ { event: 'Stop', script: 'sessionStop.js', matcher: '' },
646
+ { event: 'SessionEnd', script: 'sessionStop.js', matcher: '' },
647
+ ];
648
+ for (const { event, script, matcher } of hookEvents) {
649
+ const cmd = formatNodeHookCommand(path_1.default.join(installedHooksDir, script));
650
+ const list = Array.isArray(settings.hooks[event]) ? settings.hooks[event] : [];
651
+ const existingIdx = list.findIndex((item) => {
652
+ if (typeof item === 'string')
653
+ return item.includes(script);
654
+ if (item && typeof item.command === 'string')
655
+ return item.command.includes(script);
656
+ if (item && Array.isArray(item.hooks)) {
657
+ return item.hooks.some((h) => h && typeof h.command === 'string' && h.command.includes(script));
658
+ }
659
+ return false;
660
+ });
661
+ const hookEntry = {
662
+ matcher,
663
+ hooks: [
664
+ {
665
+ type: 'command',
666
+ command: cmd,
667
+ timeout: 30,
668
+ },
669
+ ],
670
+ };
671
+ if (existingIdx >= 0) {
672
+ list[existingIdx] = hookEntry;
673
+ }
674
+ else {
675
+ list.push(hookEntry);
676
+ }
677
+ settings.hooks[event] = list;
678
+ }
679
+ safeWriteJson(settingsPath, settings, dryRun, report);
680
+ }
681
+ // 3. ~/.claude/CLAUDE.md
682
+ const claudeMdPath = path_1.default.join(homeDir, '.claude', 'CLAUDE.md');
683
+ const existingClaudeMd = fs_1.default.existsSync(claudeMdPath) ? fs_1.default.readFileSync(claudeMdPath, 'utf8') : '';
684
+ const updatedClaudeMd = upsertBrainRuleBlock(existingClaudeMd, undefined, replaceAgentMemory);
685
+ safeWriteFile(claudeMdPath, updatedClaudeMd, dryRun, report);
686
+ // 3. Symlink skills into ~/.claude/skills/ only if ~/.claude exists
687
+ if (fs_1.default.existsSync(path_1.default.join(homeDir, '.claude'))) {
688
+ linkSkillsIntoTarget(globalSkillNames, globalCanonicalSkillsDir, path_1.default.join(homeDir, '.claude', 'skills'), dryRun, report);
689
+ }
690
+ report.configuredTargets.push('claude');
691
+ }
692
+ // ---------------------------------------------------------------------------
693
+ // Target 3: Cursor (Global)
694
+ // ---------------------------------------------------------------------------
695
+ if (requestedTargets.includes('cursor')) {
696
+ const cursorMcpPath = path_1.default.join(homeDir, '.cursor', 'mcp.json');
697
+ const existingCursorJson = safeReadJson(cursorMcpPath) || { mcpServers: {} };
698
+ const mergedCursorJson = mergeMcpConfig(existingCursorJson, globalMcpServerDef, replaceAgentMemory);
699
+ safeWriteJson(cursorMcpPath, mergedCursorJson, dryRun, report);
700
+ report.configuredTargets.push('cursor');
701
+ }
702
+ // ---------------------------------------------------------------------------
703
+ // Target 4: Workspace Project Directory
704
+ // ---------------------------------------------------------------------------
705
+ if (requestedTargets.includes('project')) {
706
+ if (projectDir) {
707
+ const normalizedSlug = resolveProjectSlug(projectDir, options.projectId);
708
+ report.projectId = normalizedSlug;
709
+ const projectMcpServerDef = {
710
+ command: 'neuralbrain',
711
+ args: ['mcp'],
712
+ env: {
713
+ BRAIN_API_URL: apiUrl,
714
+ BRAIN_DEFAULT_PROJECT_ID: normalizedSlug,
715
+ ...(apiKey ? { BRAIN_API_KEY: apiKey } : {}),
716
+ },
717
+ };
718
+ // 1. Write <projectDir>/.brainrc
719
+ const brainrcPath = path_1.default.join(projectDir, '.brainrc');
720
+ safeWriteJson(brainrcPath, { project_id: normalizedSlug }, dryRun, report);
721
+ // 2. Project-level Claude Code: <projectDir>/.mcp.json and <projectDir>/.claude/settings.json
722
+ const projectClaudeMcpPath = path_1.default.join(projectDir, '.mcp.json');
723
+ const existingClaudeMcp = safeReadJson(projectClaudeMcpPath) || { mcpServers: {} };
724
+ const mergedClaudeMcp = mergeMcpConfig(existingClaudeMcp, projectMcpServerDef, replaceAgentMemory);
725
+ safeWriteJson(projectClaudeMcpPath, mergedClaudeMcp, dryRun, report);
726
+ if (enableHooks) {
727
+ const projectClaudeSettingsPath = path_1.default.join(projectDir, '.claude', 'settings.json');
728
+ const projectClaudeSettings = safeReadJson(projectClaudeSettingsPath) || {};
729
+ if (!projectClaudeSettings.hooks || typeof projectClaudeSettings.hooks !== 'object') {
730
+ projectClaudeSettings.hooks = {};
731
+ }
732
+ const hookEvents = [
733
+ { event: 'SessionStart', script: 'sessionStart.js', matcher: '' },
734
+ { event: 'PostToolUse', script: 'postToolUse.js', matcher: '*' },
735
+ { event: 'Stop', script: 'sessionStop.js', matcher: '' },
736
+ { event: 'SessionEnd', script: 'sessionStop.js', matcher: '' },
737
+ ];
738
+ for (const { event, script, matcher } of hookEvents) {
739
+ const cmd = formatNodeHookCommand(path_1.default.join(installedHooksDir, script));
740
+ const list = Array.isArray(projectClaudeSettings.hooks[event])
741
+ ? projectClaudeSettings.hooks[event]
742
+ : [];
743
+ const existingIdx = list.findIndex((item) => {
744
+ if (typeof item === 'string')
745
+ return item.includes(script);
746
+ if (item && typeof item.command === 'string')
747
+ return item.command.includes(script);
748
+ if (item && Array.isArray(item.hooks)) {
749
+ return item.hooks.some((h) => h && typeof h.command === 'string' && h.command.includes(script));
750
+ }
751
+ return false;
752
+ });
753
+ const hookEntry = {
754
+ matcher,
755
+ hooks: [
756
+ {
757
+ type: 'command',
758
+ command: cmd,
759
+ timeout: 30,
760
+ },
761
+ ],
762
+ };
763
+ if (existingIdx >= 0) {
764
+ list[existingIdx] = hookEntry;
765
+ }
766
+ else {
767
+ list.push(hookEntry);
768
+ }
769
+ projectClaudeSettings.hooks[event] = list;
770
+ }
771
+ safeWriteJson(projectClaudeSettingsPath, projectClaudeSettings, dryRun, report);
772
+ }
773
+ // 3. Project-level Antigravity: <projectDir>/.gemini/hooks.json and skills/brain-memory/SKILL.md
774
+ if (enableHooks) {
775
+ const projectGeminiHooksPath = path_1.default.join(projectDir, '.gemini', 'hooks.json');
776
+ const sessionStartHook = formatNodeHookCommand(path_1.default.join(installedHooksDir, 'sessionStart.js'));
777
+ const postToolUseHook = formatNodeHookCommand(path_1.default.join(installedHooksDir, 'postToolUse.js'));
778
+ const sessionStopHook = formatNodeHookCommand(path_1.default.join(installedHooksDir, 'sessionStop.js'));
779
+ const existingProjectHooksRaw = safeReadJson(projectGeminiHooksPath);
780
+ const existingProjectHooks = existingProjectHooksRaw &&
781
+ typeof existingProjectHooksRaw === 'object' &&
782
+ !Array.isArray(existingProjectHooksRaw)
783
+ ? existingProjectHooksRaw
784
+ : {};
785
+ safeWriteJson(projectGeminiHooksPath, {
786
+ ...existingProjectHooks,
787
+ neuralbrain: {
788
+ enabled: true,
789
+ SessionStart: [
790
+ {
791
+ type: 'command',
792
+ command: sessionStartHook,
793
+ timeout: 30,
794
+ },
795
+ ],
796
+ PostToolUse: [
797
+ {
798
+ matcher: '*',
799
+ hooks: [
800
+ {
801
+ type: 'command',
802
+ command: postToolUseHook,
803
+ timeout: 30,
804
+ },
805
+ ],
806
+ },
807
+ ],
808
+ Stop: [
809
+ {
810
+ type: 'command',
811
+ command: sessionStopHook,
812
+ timeout: 30,
813
+ },
814
+ ],
815
+ },
816
+ }, dryRun, report);
817
+ }
818
+ const projectCanonicalSkillsDir = path_1.default.join(projectDir, '.agents', 'skills');
819
+ const projectSkillNames = syncCanonicalSkills(brainRepoDir, projectCanonicalSkillsDir, dryRun, report);
820
+ linkSkillsIntoTarget(projectSkillNames, projectCanonicalSkillsDir, path_1.default.join(projectDir, '.gemini', 'skills'), dryRun, report);
821
+ if (fs_1.default.existsSync(path_1.default.join(projectDir, '.claude'))) {
822
+ linkSkillsIntoTarget(projectSkillNames, projectCanonicalSkillsDir, path_1.default.join(projectDir, '.claude', 'skills'), dryRun, report);
823
+ }
824
+ // 4. Project-level Cursor: <projectDir>/.cursor/mcp.json
825
+ const projectCursorMcpPath = path_1.default.join(projectDir, '.cursor', 'mcp.json');
826
+ const existingCursorMcp = safeReadJson(projectCursorMcpPath) || { mcpServers: {} };
827
+ const mergedCursorMcp = mergeMcpConfig(existingCursorMcp, projectMcpServerDef, replaceAgentMemory);
828
+ safeWriteJson(projectCursorMcpPath, mergedCursorMcp, dryRun, report);
829
+ // 5. Project-level Rules (<projectDir>/CLAUDE.md / AGENTS.md)
830
+ const isBrainRepo = projectDir === brainRepoDir;
831
+ if (!isBrainRepo) {
832
+ const projectClaudeMd = path_1.default.join(projectDir, 'CLAUDE.md');
833
+ const projectAgentsMd = path_1.default.join(projectDir, 'AGENTS.md');
834
+ const hasClaudeMd = fs_1.default.existsSync(projectClaudeMd);
835
+ const hasAgentsMd = fs_1.default.existsSync(projectAgentsMd);
836
+ if (hasClaudeMd) {
837
+ const content = fs_1.default.readFileSync(projectClaudeMd, 'utf8');
838
+ const updated = upsertBrainRuleBlock(content, normalizedSlug, replaceAgentMemory);
839
+ safeWriteFile(projectClaudeMd, updated, dryRun, report);
840
+ }
841
+ if (hasAgentsMd) {
842
+ const content = fs_1.default.readFileSync(projectAgentsMd, 'utf8');
843
+ const updated = upsertBrainRuleBlock(content, normalizedSlug, replaceAgentMemory);
844
+ safeWriteFile(projectAgentsMd, updated, dryRun, report);
845
+ }
846
+ // If neither exists, create CLAUDE.md with canonical project rule block
847
+ if (!hasClaudeMd && !hasAgentsMd) {
848
+ const newClaudeMd = upsertBrainRuleBlock('', normalizedSlug, replaceAgentMemory);
849
+ safeWriteFile(projectClaudeMd, newClaudeMd, dryRun, report);
850
+ }
851
+ }
852
+ report.configuredTargets.push('project');
853
+ }
854
+ else {
855
+ if (options.targets && options.targets.includes('project')) {
856
+ report.warnings.push('Target "project" was requested, but no options.projectDir was provided.');
857
+ }
858
+ }
859
+ }
860
+ return report;
861
+ }
862
+ // -----------------------------------------------------------------------------
863
+ // CLI Argument Parsing & Runner
864
+ // -----------------------------------------------------------------------------
865
+ function parseCliArgs(argv) {
866
+ const options = {};
867
+ for (let i = 0; i < argv.length; i++) {
868
+ const arg = argv[i];
869
+ if (arg === '--help' || arg === '-h') {
870
+ printUsage();
871
+ process.exit(0);
872
+ }
873
+ if (arg === '--project-dir') {
874
+ options.projectDir = argv[++i];
875
+ continue;
876
+ }
877
+ if (arg === '--project-id') {
878
+ options.projectId = argv[++i];
879
+ continue;
880
+ }
881
+ if (arg === '--global') {
882
+ options.global = true;
883
+ continue;
884
+ }
885
+ if (arg === '--api-key') {
886
+ options.apiKey = argv[++i];
887
+ console.warn('\n[SECURITY WARNING] Passing --api-key on the command line can expose secrets in shell history (~/.bash_history) and process tables (ps aux).' +
888
+ '\nRecommended: Set BRAIN_API_KEY in your .env file instead and run `npm run install-agent`.\n');
889
+ continue;
890
+ }
891
+ if (arg === '--api-url') {
892
+ options.apiUrl = argv[++i];
893
+ continue;
894
+ }
895
+ if (arg === '--no-hooks') {
896
+ options.enableHooks = false;
897
+ continue;
898
+ }
899
+ if (arg === '--keep-agentmemory') {
900
+ options.replaceAgentMemory = false;
901
+ continue;
902
+ }
903
+ if (arg === '--replace-agentmemory') {
904
+ options.replaceAgentMemory = true;
905
+ continue;
906
+ }
907
+ if (arg === '--dry-run') {
908
+ options.dryRun = true;
909
+ continue;
910
+ }
911
+ if (arg === '--target' || arg === '--targets') {
912
+ const rawTargets = (argv[++i] || '').split(',').map((t) => t.trim().toLowerCase());
913
+ const validTargets = [];
914
+ for (const t of rawTargets) {
915
+ if (t === 'antigravity' || t === 'claude' || t === 'cursor' || t === 'project') {
916
+ validTargets.push(t);
917
+ }
918
+ else if (t) {
919
+ console.warn(`[WARN] Unknown target '${t}' ignored.`);
920
+ }
921
+ }
922
+ options.targets = validTargets;
923
+ continue;
924
+ }
925
+ throw new Error(`Unknown argument: ${arg}`);
926
+ }
927
+ return options;
928
+ }
929
+ function printUsage() {
930
+ console.log(`
931
+ Usage: npm run install-agent -- [options]
932
+
933
+ Configures coding agents (Antigravity, Claude Code, Cursor, Workspace Projects)
934
+ to use neuralbrain persistent memory.
935
+
936
+ Modes of Operation:
937
+ 1. Global Install (default when --project-dir is omitted):
938
+ Installs globally to base agent configurations:
939
+ - Antigravity plugin: ~/.gemini/config/plugins/neuralbrain/
940
+ - Global Rules: ~/.gemini/GEMINI.md
941
+ - Claude Code: ~/.claude.json, ~/.claude/settings.json, ~/.claude/CLAUDE.md
942
+ - Cursor: ~/.cursor/mcp.json
943
+
944
+ 2. Project-Level Install (when --project-dir <path> is provided):
945
+ Installs ONLY to the specific project workspace, touching ZERO global files:
946
+ - Project ID: <projectDir>/.brainrc
947
+ - Project Claude MCP: <projectDir>/.mcp.json
948
+ - Project Claude: <projectDir>/.claude/settings.json
949
+ - Project Gemini: <projectDir>/.gemini/hooks.json, .gemini/skills/brain-memory/
950
+ - Project Cursor: <projectDir>/.cursor/mcp.json
951
+ - Project Rules: <projectDir>/CLAUDE.md / AGENTS.md
952
+
953
+ 3. Dual Install (--global with --project-dir <path>):
954
+ Installs both global agent configurations and project-level workspace files.
955
+
956
+ Security Recommendation:
957
+ Set BRAIN_API_KEY and BRAIN_API_URL in your .env file instead of passing keys
958
+ via command-line arguments to avoid leaking credentials into shell history
959
+ (~/.bash_history) or process listings (ps aux).
960
+ Then simply run:
961
+ npm run install-agent
962
+ or:
963
+ npm run install-agent -- --project-dir /path/to/project
964
+
965
+ Options:
966
+ --project-dir <path> Target project workspace to initialize .brainrc & rules
967
+ --project-id <slug> Explicit canonical project slug (defaults to folder name)
968
+ --global Force global installation alongside --project-dir
969
+ --api-key <key> API key (Warning: Prefer setting BRAIN_API_KEY in .env)
970
+ --api-url <url> Brain API service URL (defaults to .env or http://127.0.0.1:3737)
971
+ --target <list> Explicit targets: antigravity, claude, cursor, project
972
+ --no-hooks Do not configure lifecycle hooks in plugin / settings
973
+ --replace-agentmemory Replace legacy agentmemory MCP configs and rule blocks
974
+ --keep-agentmemory Preserve legacy agentmemory MCP configs and rule blocks (default)
975
+ --dry-run Simulate actions without writing files to disk
976
+ -h, --help Show this help message
977
+ `);
978
+ }
979
+ /**
980
+ * Prints a human-readable summary of an installAgentIntegration run.
981
+ */
982
+ function printInstallAgentReport(report) {
983
+ console.log('\n===================================================================');
984
+ console.log(' neuralbrain Multi-Agent Installer');
985
+ console.log('===================================================================');
986
+ console.log(`Dry Run: ${report.dryRun ? 'YES (No files modified)' : 'NO'}`);
987
+ console.log(`Configured Targets: ${report.configuredTargets.join(', ') || 'none'}`);
988
+ if (report.projectId) {
989
+ console.log(`Project ID: ${report.projectId}`);
990
+ }
991
+ if (report.createdFiles.length > 0) {
992
+ console.log('\nCreated Files:');
993
+ for (const file of report.createdFiles) {
994
+ console.log(` + ${file}`);
995
+ }
996
+ }
997
+ if (report.modifiedFiles.length > 0) {
998
+ console.log('\nModified Files:');
999
+ for (const file of report.modifiedFiles) {
1000
+ console.log(` * ${file}`);
1001
+ }
1002
+ }
1003
+ if (report.skippedFiles.length > 0) {
1004
+ console.log(`\nUnchanged Files (${report.skippedFiles.length}):`);
1005
+ for (const file of report.skippedFiles) {
1006
+ console.log(` = ${file}`);
1007
+ }
1008
+ }
1009
+ if (report.warnings.length > 0) {
1010
+ console.log('\nWarnings:');
1011
+ for (const w of report.warnings) {
1012
+ console.log(` ! ${w}`);
1013
+ }
1014
+ }
1015
+ console.log('\nNext Steps:');
1016
+ console.log(' 1. Ensure the brain service is running: neuralbrain start (check with neuralbrain status)');
1017
+ if (report.configuredTargets.includes('antigravity')) {
1018
+ console.log(' 2. For Antigravity: The neuralbrain plugin is ready under ~/.gemini/config/plugins/');
1019
+ }
1020
+ if (report.configuredTargets.includes('claude')) {
1021
+ console.log(' 3. For Claude Code: MCP server and hooks configured in ~/.claude.json & ~/.claude/');
1022
+ }
1023
+ if (report.configuredTargets.includes('cursor')) {
1024
+ console.log(' 4. For Cursor: MCP server registered in ~/.cursor/mcp.json');
1025
+ }
1026
+ if (report.configuredTargets.includes('project')) {
1027
+ console.log(' 5. Project Workspace: Fully initialized with hooks, skills, and .brainrc');
1028
+ }
1029
+ console.log('===================================================================\n');
1030
+ }
1031
+ function main() {
1032
+ try {
1033
+ const options = parseCliArgs(process.argv.slice(2));
1034
+ const report = installAgentIntegration(options);
1035
+ printInstallAgentReport(report);
1036
+ }
1037
+ catch (error) {
1038
+ console.error('\n[ERROR] Multi-Agent Installation failed:');
1039
+ console.error(error?.message || error);
1040
+ process.exit(1);
1041
+ }
1042
+ }
1043
+ if (require.main === module) {
1044
+ main();
1045
+ }
1046
+ //# sourceMappingURL=installAgent.js.map