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,286 @@
1
+ import fs from 'fs';
2
+ import path from 'path';
3
+ import { normalizeProjectId } from './scope';
4
+ import { getBrainHomeDir } from './brainHome';
5
+
6
+ export interface ResolveProjectIdOptions {
7
+ explicitProjectId?: string;
8
+ cwd?: string;
9
+ fallbackToDirname?: boolean;
10
+ }
11
+
12
+ /**
13
+ * Resolves the canonical project ID slug for a workspace or directory.
14
+ *
15
+ * The id names the project's ROOT folder, never whichever subfolder the agent
16
+ * happens to be in. Precedence:
17
+ * 1. Explicit project ID (validated and normalized).
18
+ * 2. .brainrc or .brain.json, found by walking up every parent of cwd (or process.cwd()).
19
+ * 3. If fallbackToDirname: the git repository root's folder name. In a git
20
+ * worktree that is the MAIN repository, not the worktree folder.
21
+ * 4. BRAIN_DEFAULT_PROJECT_ID environment variable.
22
+ * 5. If fallbackToDirname and cwd is provided: basename of cwd (sanitized).
23
+ * 6. null.
24
+ */
25
+ export function resolveCanonicalProjectId(options?: ResolveProjectIdOptions): string | null {
26
+ // 1. Explicit project ID
27
+ if (options?.explicitProjectId && typeof options.explicitProjectId === 'string') {
28
+ const trimmed = options.explicitProjectId.trim();
29
+ if (trimmed !== '') {
30
+ const norm = normalizeProjectId(trimmed);
31
+ if (norm.ok) {
32
+ return norm.projectId;
33
+ }
34
+ }
35
+ }
36
+
37
+ // 2. Walk up from options.cwd || process.cwd(), through every parent
38
+ const startDir = path.resolve(options?.cwd || process.cwd());
39
+ let currentDir = startDir;
40
+
41
+ for (;;) {
42
+ const candidates = ['.brainrc', '.brain.json'];
43
+ for (const filename of candidates) {
44
+ const candidatePath = path.join(currentDir, filename);
45
+ if (fs.existsSync(candidatePath)) {
46
+ try {
47
+ const content = fs.readFileSync(candidatePath, 'utf-8');
48
+ let slug: string | null = null;
49
+ try {
50
+ const parsed = JSON.parse(content);
51
+ if (parsed && typeof parsed === 'object') {
52
+ slug = parsed.project_id || parsed.projectId || parsed.project || null;
53
+ } else if (typeof parsed === 'string') {
54
+ slug = parsed;
55
+ }
56
+ } catch {
57
+ // Not valid JSON, try plain string
58
+ slug = content.trim();
59
+ }
60
+
61
+ if (slug && typeof slug === 'string') {
62
+ const norm = normalizeProjectId(slug.trim());
63
+ if (norm.ok) {
64
+ return norm.projectId;
65
+ }
66
+ }
67
+ } catch {
68
+ // Ignore read error and continue walking
69
+ }
70
+ }
71
+ }
72
+
73
+ const parentDir = path.dirname(currentDir);
74
+ if (parentDir === currentDir) {
75
+ // Reached filesystem root
76
+ break;
77
+ }
78
+ currentDir = parentDir;
79
+ }
80
+
81
+ // 3. Git repository root (worktrees resolve to the main repository)
82
+ if (options?.fallbackToDirname) {
83
+ const gitRoot = findGitProjectRoot(startDir);
84
+ if (gitRoot) {
85
+ const slug = slugFromFolderName(path.basename(gitRoot));
86
+ if (slug) return slug;
87
+ }
88
+ }
89
+
90
+ // 4. BRAIN_DEFAULT_PROJECT_ID environment variable
91
+ const envDefault = process.env.BRAIN_DEFAULT_PROJECT_ID;
92
+ if (envDefault && typeof envDefault === 'string' && envDefault.trim() !== '') {
93
+ const norm = normalizeProjectId(envDefault.trim());
94
+ if (norm.ok) {
95
+ return norm.projectId;
96
+ }
97
+ }
98
+
99
+ // 5. Fallback to dirname if enabled and cwd is provided
100
+ if (options?.fallbackToDirname && options?.cwd && typeof options.cwd === 'string' && options.cwd.trim() !== '') {
101
+ const slug = slugFromFolderName(path.basename(path.resolve(options.cwd)));
102
+ if (slug) return slug;
103
+ }
104
+
105
+ // 6. Otherwise return null
106
+ return null;
107
+ }
108
+
109
+ function slugFromFolderName(name: string): string | null {
110
+ const sanitized = name
111
+ .toLowerCase()
112
+ .replace(/[^a-z0-9._-]+/g, '-')
113
+ .replace(/^-+|-+$/g, '');
114
+ if (!sanitized) return null;
115
+ const norm = normalizeProjectId(sanitized);
116
+ return norm.ok ? norm.projectId : null;
117
+ }
118
+
119
+ /**
120
+ * Returns the folder that names the project for a git checkout containing
121
+ * startDir, or null if startDir is not inside one.
122
+ *
123
+ * - `.git` directory: that folder is the repository root.
124
+ * - `.git` file pointing into `<repo>/.git/worktrees/<name>`: a linked
125
+ * worktree, so the project is `<repo>`, wherever the worktree lives
126
+ * (agents put them in places like ~/.gemini/.../worktrees/<repo>/<branch>).
127
+ * - any other `.git` file (e.g. a submodule): that folder is its own project.
128
+ *
129
+ * Only the filesystem is read; no git process is spawned.
130
+ */
131
+ export function findGitProjectRoot(startDir: string): string | null {
132
+ let currentDir = path.resolve(startDir);
133
+ for (;;) {
134
+ const dotGit = path.join(currentDir, '.git');
135
+ let stat: fs.Stats | null = null;
136
+ try {
137
+ stat = fs.statSync(dotGit);
138
+ } catch {
139
+ stat = null;
140
+ }
141
+ if (stat?.isDirectory()) return currentDir;
142
+ if (stat?.isFile()) {
143
+ try {
144
+ const match = /^gitdir:\s*(.+?)\s*$/m.exec(fs.readFileSync(dotGit, 'utf-8'));
145
+ if (match) {
146
+ const gitDir = path.resolve(currentDir, match[1]);
147
+ const worktree = /^(.*)[\\/]\.git[\\/]worktrees[\\/][^\\/]+[\\/]?$/.exec(gitDir);
148
+ if (worktree && worktree[1]) return worktree[1];
149
+ }
150
+ } catch {
151
+ // unreadable .git file: treat this folder as the root
152
+ }
153
+ return currentDir;
154
+ }
155
+ const parentDir = path.dirname(currentDir);
156
+ if (parentDir === currentDir) return null;
157
+ currentDir = parentDir;
158
+ }
159
+ }
160
+
161
+ export interface ResolveSessionProjectIdOptions {
162
+ sessionId?: string | null;
163
+ cwd?: string;
164
+ explicitProjectId?: string;
165
+ /** Where session pins live. Defaults to <BRAIN_HOME>/sessions. */
166
+ pinDir?: string;
167
+ }
168
+
169
+ const PIN_MAX_AGE_MS = 14 * 24 * 60 * 60 * 1000;
170
+
171
+ /**
172
+ * Resolves the project for an event inside an agent session, and keeps it
173
+ * fixed for the rest of that session.
174
+ *
175
+ * Hooks fire with the agent's *current* directory, which moves whenever the
176
+ * agent `cd`s into a subfolder or a subagent runs elsewhere. Resolving per
177
+ * event split one session's observations across projects named after its
178
+ * subfolders. So the first resolution in a session is pinned (in
179
+ * <BRAIN_HOME>/sessions/<session id>.json) and every later event reuses it.
180
+ * A pinned null means the session was unscoped, and stays unscoped.
181
+ *
182
+ * An explicit project id always wins and is not pinned.
183
+ */
184
+ export function resolveSessionProjectId(options: ResolveSessionProjectIdOptions): string | null {
185
+ if (options.explicitProjectId && options.explicitProjectId.trim() !== '') {
186
+ return resolveCanonicalProjectId({ explicitProjectId: options.explicitProjectId });
187
+ }
188
+
189
+ const pinFile = options.sessionId ? sessionPinPath(options.sessionId, options.pinDir) : null;
190
+ if (pinFile) {
191
+ try {
192
+ const pinned = JSON.parse(fs.readFileSync(pinFile, 'utf-8'));
193
+ if (pinned && typeof pinned === 'object' && 'project_id' in pinned) {
194
+ return typeof pinned.project_id === 'string' ? pinned.project_id : null;
195
+ }
196
+ } catch {
197
+ // no pin yet (or unreadable): resolve below
198
+ }
199
+ }
200
+
201
+ const projectId = resolveCanonicalProjectId({ cwd: options.cwd, fallbackToDirname: true });
202
+
203
+ if (pinFile) {
204
+ try {
205
+ fs.mkdirSync(path.dirname(pinFile), { recursive: true });
206
+ fs.writeFileSync(
207
+ pinFile,
208
+ JSON.stringify({ project_id: projectId, cwd: options.cwd ?? null, pinned_at: new Date().toISOString() })
209
+ );
210
+ prunePins(path.dirname(pinFile));
211
+ } catch {
212
+ // pinning is best effort; the resolution itself is still correct
213
+ }
214
+ }
215
+ return projectId;
216
+ }
217
+
218
+ function sessionPinPath(sessionId: string, pinDir?: string): string | null {
219
+ const safe = String(sessionId).replace(/[^A-Za-z0-9._-]/g, '_').slice(0, 128);
220
+ if (!safe) return null;
221
+ if (pinDir) return path.join(pinDir, `${safe}.json`);
222
+ // Under test, never write into the developer's real BRAIN_HOME.
223
+ const underTest = process.env.NODE_ENV === 'test' || !!process.env.JEST_WORKER_ID;
224
+ if (underTest && !process.env.BRAIN_HOME) return null;
225
+ return path.join(getBrainHomeDir(), 'sessions', `${safe}.json`);
226
+ }
227
+
228
+ function prunePins(dir: string): void {
229
+ const cutoff = Date.now() - PIN_MAX_AGE_MS;
230
+ for (const name of fs.readdirSync(dir)) {
231
+ if (!name.endsWith('.json')) continue;
232
+ const file = path.join(dir, name);
233
+ try {
234
+ if (fs.statSync(file).mtimeMs < cutoff) fs.unlinkSync(file);
235
+ } catch {
236
+ // ignore
237
+ }
238
+ }
239
+ }
240
+
241
+ /**
242
+ * Writes a canonical .brainrc file in projectDir with { "project_id": "<slug>" }.
243
+ */
244
+ export function writeBrainRc(
245
+ projectDir: string,
246
+ projectId?: string
247
+ ): { filePath: string; projectId: string } {
248
+ const resolvedDir = path.resolve(projectDir);
249
+ let slug: string | null = null;
250
+
251
+ if (projectId && typeof projectId === 'string' && projectId.trim() !== '') {
252
+ const initialNorm = normalizeProjectId(projectId.trim());
253
+ if (initialNorm.ok) {
254
+ slug = initialNorm.projectId;
255
+ } else {
256
+ const sanitized = projectId
257
+ .trim()
258
+ .toLowerCase()
259
+ .replace(/[^a-z0-9._-]+/g, '-')
260
+ .replace(/^-+|-+$/g, '');
261
+ const sanitizedNorm = normalizeProjectId(sanitized);
262
+ if (sanitizedNorm.ok) {
263
+ slug = sanitizedNorm.projectId;
264
+ }
265
+ }
266
+ }
267
+
268
+ if (!slug) {
269
+ const basename = path.basename(resolvedDir);
270
+ const sanitized = basename
271
+ .toLowerCase()
272
+ .replace(/[^a-z0-9._-]+/g, '-')
273
+ .replace(/^-+|-+$/g, '');
274
+ const norm = normalizeProjectId(sanitized);
275
+ if (!norm.ok) {
276
+ throw new Error(`Failed to derive valid project_id for '${projectDir}': ${norm.error}`);
277
+ }
278
+ slug = norm.projectId;
279
+ }
280
+
281
+ const filePath = path.join(resolvedDir, '.brainrc');
282
+ const content = JSON.stringify({ project_id: slug }, null, 2) + '\n';
283
+ fs.writeFileSync(filePath, content, 'utf-8');
284
+
285
+ return { filePath, projectId: slug };
286
+ }
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Redacts known API keys, tokens, private keys, and embedded credential URLs
3
+ * from text before persistence or transport.
4
+ */
5
+
6
+ const SECRET_PATTERNS: Array<{ pattern: RegExp; replacement: string }> = [
7
+ // PEM private key blocks
8
+ {
9
+ pattern: /-----BEGIN (?:[A-Z0-9 ]+ )?PRIVATE KEY-----[\s\S]*?-----END (?:[A-Z0-9 ]+ )?PRIVATE KEY-----/g,
10
+ replacement: '[REDACTED_PRIVATE_KEY]',
11
+ },
12
+ // Anthropic API keys
13
+ {
14
+ pattern: /\bsk-ant-[a-zA-Z0-9_-]{20,}\b/g,
15
+ replacement: '[REDACTED_API_KEY]',
16
+ },
17
+ // OpenAI project/service/admin/classic keys
18
+ {
19
+ pattern: /\bsk-(?:proj-|svcacct-|admin-)?[a-zA-Z0-9_-]{20,}\b/g,
20
+ replacement: '[REDACTED_API_KEY]',
21
+ },
22
+ // Stripe keys
23
+ {
24
+ pattern: /\b(?:sk|rk)_(?:live|test)_[a-zA-Z0-9]{16,}\b/g,
25
+ replacement: '[REDACTED_API_KEY]',
26
+ },
27
+ // Google / Gemini / Firebase API keys
28
+ {
29
+ pattern: /\bAIza[0-9A-Za-z_-]{30,}\b/g,
30
+ replacement: '[REDACTED_API_KEY]',
31
+ },
32
+ // GitHub tokens (classic & fine-grained PAT)
33
+ {
34
+ pattern: /\bgh[pousr]_[A-Za-z0-9_]{20,}\b/g,
35
+ replacement: '[REDACTED_TOKEN]',
36
+ },
37
+ {
38
+ pattern: /\bgithub_pat_[A-Za-z0-9_]{20,}\b/g,
39
+ replacement: '[REDACTED_TOKEN]',
40
+ },
41
+ // AWS Access Key IDs
42
+ {
43
+ pattern: /\b(?:A3T[A-Z0-9]|AKIA|AGPA|AIDA|AROA|AIPA|ANPA|ANVA|ASIA)[A-Z0-9]{16}\b/g,
44
+ replacement: '[REDACTED_AWS_KEY]',
45
+ },
46
+ // Slack tokens
47
+ {
48
+ pattern: /\bxox[baprs]-[0-9A-Za-z-]{10,}\b/g,
49
+ replacement: '[REDACTED_TOKEN]',
50
+ },
51
+ // HuggingFace, npm, PyPI, Groq, Perplexity, xAI, SendGrid
52
+ {
53
+ pattern: /\b(?:hf|npm|gsk|pplx|xai)_[A-Za-z0-9]{20,}\b/g,
54
+ replacement: '[REDACTED_API_KEY]',
55
+ },
56
+ {
57
+ pattern: /\bpypi-[A-Za-z0-9_-]{20,}\b/g,
58
+ replacement: '[REDACTED_API_KEY]',
59
+ },
60
+ {
61
+ pattern: /\bSG\.[A-Za-z0-9_-]{16,}\.[A-Za-z0-9_-]{16,}\b/g,
62
+ replacement: '[REDACTED_API_KEY]',
63
+ },
64
+ // Authorization: Bearer <token>
65
+ {
66
+ pattern: /\bBearer\s+[A-Za-z0-9._~+/=-]{20,}/g,
67
+ replacement: 'Bearer [REDACTED_TOKEN]',
68
+ },
69
+ // Database / service URLs with embedded passwords (scheme://user:pass@host)
70
+ {
71
+ pattern: /\b((?:postgres(?:ql)?|mysql|mongodb(?:\+srv)?|redis|amqp):\/\/[^:\s/]+:)[^@\s]+(@)/gi,
72
+ replacement: '$1[REDACTED_PASSWORD]$2',
73
+ },
74
+ ];
75
+
76
+ export function redactSecrets(text: string): string {
77
+ let result = text;
78
+ for (const { pattern, replacement } of SECRET_PATTERNS) {
79
+ result = result.replace(pattern, replacement);
80
+ }
81
+ return result;
82
+ }
83
+
84
+ export function redactOptional(text: string | null | undefined): string | null {
85
+ if (text === undefined || text === null) return null;
86
+ return redactSecrets(text);
87
+ }
@@ -0,0 +1,121 @@
1
+ /**
2
+ * Project identity.
3
+ *
4
+ * Rule 4 makes *scope* explicit. This module makes *identity* deterministic,
5
+ * which is the other half: without it `MyProject`, `myproject` and
6
+ * `My Project` are three different projects, two clients naming the same
7
+ * project differently get silently split memory, and nothing reports it.
8
+ *
9
+ * Two rules, and the second matters more than it looks:
10
+ *
11
+ * 1. Normalise what is unambiguous — case and surrounding whitespace, and
12
+ * internal whitespace to '-'. These are spellings of one name.
13
+ *
14
+ * 2. REJECT what would require a guess. A filesystem path is the obvious
15
+ * case: turning '/home/user/Projects/Foo' into 'foo' is inference, it
16
+ * silently collides with any other repo basenamed 'Foo', and it breaks the
17
+ * moment a repo moves. Rule 4 says never guess — so the writer is told to
18
+ * send an id rather than having one derived for them. Hints say to use
19
+ * the project root folder name (.brainrc, else the git repo root — the
20
+ * main repo for a worktree), never a subfolder, so all agents come up with
21
+ * the same id.
22
+ *
23
+ * The normalised form is what gets stored and what is returned, so a client can
24
+ * see what it actually wrote.
25
+ */
26
+
27
+ export const PROJECT_ID_MAX_LENGTH = 128;
28
+
29
+ /** Lowercase alphanumerics plus dot, underscore and hyphen. */
30
+ const PROJECT_ID_ALLOWED = /^[a-z0-9._-]+$/;
31
+
32
+ export type ProjectIdResult =
33
+ | { ok: true; projectId: string }
34
+ | { ok: false; error: string };
35
+
36
+ export function normalizeProjectId(raw: unknown): ProjectIdResult {
37
+ if (typeof raw !== 'string') {
38
+ return { ok: false, error: 'project_id must be a string' };
39
+ }
40
+
41
+ const trimmed = raw.trim();
42
+ if (trimmed === '') {
43
+ return { ok: false, error: 'project_id must not be empty' };
44
+ }
45
+
46
+ // Reject rather than derive. See rule 2 in the header.
47
+ if (trimmed.includes('/') || trimmed.includes('\\')) {
48
+ return {
49
+ ok: false,
50
+ error:
51
+ `project_id '${trimmed}' looks like a path. Send a stable identifier ` +
52
+ `(e.g. 'neuralbrain'), not a filesystem path: use the project root ` +
53
+ `folder name (from .brainrc, else the git repo root; the main repo for a worktree), ` +
54
+ `never a subfolder, so all agents come up with the same id.`,
55
+ };
56
+ }
57
+
58
+ const normalized = trimmed.toLowerCase().replace(/\s+/g, '-');
59
+
60
+ if (normalized.length > PROJECT_ID_MAX_LENGTH) {
61
+ return {
62
+ ok: false,
63
+ error: `project_id must be ${PROJECT_ID_MAX_LENGTH} characters or fewer (got ${normalized.length})`,
64
+ };
65
+ }
66
+
67
+ if (!PROJECT_ID_ALLOWED.test(normalized)) {
68
+ return {
69
+ ok: false,
70
+ error:
71
+ `project_id '${trimmed}' contains unsupported characters. Allowed after ` +
72
+ `normalisation: lowercase letters, digits, '.', '_' and '-'.`,
73
+ };
74
+ }
75
+
76
+ return { ok: true, projectId: normalized };
77
+ }
78
+
79
+ export type ScopeValue = 'project' | 'global' | 'unknown';
80
+
81
+ /**
82
+ * Resolve scope and project_id together. They are a pair: `project` requires an
83
+ * id, and the other two forbid one, which is also what the table CHECK
84
+ * constraints enforce.
85
+ *
86
+ * Scope defaults to 'unknown' when the writer says nothing — never 'global'.
87
+ * Defaulting to global would put every unlabelled record into every project's
88
+ * injection — a louder version of the unscoped-records problem many memory
89
+ * systems have.
90
+ */
91
+ export function resolveScope(
92
+ rawScope: unknown,
93
+ rawProjectId: unknown
94
+ ): { ok: true; scope: ScopeValue; projectId: string | null } | { ok: false; error: string } {
95
+ let scope: ScopeValue = 'unknown';
96
+
97
+ if (rawScope !== undefined && rawScope !== null) {
98
+ if (rawScope === 'project' || rawScope === 'global' || rawScope === 'unknown') {
99
+ scope = rawScope;
100
+ } else {
101
+ return {
102
+ ok: false,
103
+ error: `Invalid scope '${String(rawScope)}'. Must be 'project', 'global', or 'unknown'`,
104
+ };
105
+ }
106
+ }
107
+
108
+ if (scope === 'project') {
109
+ const result = normalizeProjectId(rawProjectId);
110
+ if (!result.ok) {
111
+ return { ok: false, error: `${result.error} (required when scope is 'project')` };
112
+ }
113
+ return { ok: true, scope, projectId: result.projectId };
114
+ }
115
+
116
+ if (rawProjectId !== undefined && rawProjectId !== null && rawProjectId !== '') {
117
+ return { ok: false, error: `project_id must be null or omitted when scope is '${scope}'` };
118
+ }
119
+
120
+ return { ok: true, scope, projectId: null };
121
+ }