neuralbrain 0.0.1 → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (226) hide show
  1. package/.env.example +2 -2
  2. package/README.md +19 -4
  3. package/dist/ai/chat.d.ts +1 -2
  4. package/dist/ai/chat.d.ts.map +1 -1
  5. package/dist/ai/chat.js +1 -2
  6. package/dist/ai/chat.js.map +1 -1
  7. package/dist/ai/config.d.ts +1 -1
  8. package/dist/ai/config.js +2 -2
  9. package/dist/ai/config.js.map +1 -1
  10. package/dist/app.d.ts +1 -0
  11. package/dist/app.d.ts.map +1 -1
  12. package/dist/app.js +417 -50
  13. package/dist/app.js.map +1 -1
  14. package/dist/cli.d.ts +53 -2
  15. package/dist/cli.d.ts.map +1 -1
  16. package/dist/cli.js +437 -37
  17. package/dist/cli.js.map +1 -1
  18. package/dist/consolidation/candidates.d.ts.map +1 -1
  19. package/dist/consolidation/candidates.js +19 -4
  20. package/dist/consolidation/candidates.js.map +1 -1
  21. package/dist/consolidation/fixtures.js +1 -1
  22. package/dist/consolidation/fixtures.js.map +1 -1
  23. package/dist/consolidation/gate.d.ts.map +1 -1
  24. package/dist/consolidation/gate.js +145 -109
  25. package/dist/consolidation/gate.js.map +1 -1
  26. package/dist/consolidation/runner.d.ts +6 -0
  27. package/dist/consolidation/runner.d.ts.map +1 -1
  28. package/dist/consolidation/runner.js +22 -2
  29. package/dist/consolidation/runner.js.map +1 -1
  30. package/dist/dashboard/clientScript.d.ts +1 -1
  31. package/dist/dashboard/clientScript.d.ts.map +1 -1
  32. package/dist/dashboard/clientScript.js +3774 -905
  33. package/dist/dashboard/clientScript.js.map +1 -1
  34. package/dist/dashboard/html.d.ts.map +1 -1
  35. package/dist/dashboard/html.js +605 -101
  36. package/dist/dashboard/html.js.map +1 -1
  37. package/dist/dashboard/styles.d.ts +1 -1
  38. package/dist/dashboard/styles.d.ts.map +1 -1
  39. package/dist/dashboard/styles.js +1591 -359
  40. package/dist/dashboard/styles.js.map +1 -1
  41. package/dist/learning/embedWorker.d.ts +13 -0
  42. package/dist/learning/embedWorker.d.ts.map +1 -1
  43. package/dist/learning/embedWorker.js +329 -59
  44. package/dist/learning/embedWorker.js.map +1 -1
  45. package/dist/learning/embedding.d.ts +1 -0
  46. package/dist/learning/embedding.d.ts.map +1 -1
  47. package/dist/learning/embedding.js +101 -26
  48. package/dist/learning/embedding.js.map +1 -1
  49. package/dist/learning/engine.js +1 -1
  50. package/dist/learning/engine.js.map +1 -1
  51. package/dist/learning/search.d.ts +17 -1
  52. package/dist/learning/search.d.ts.map +1 -1
  53. package/dist/learning/search.js +2094 -354
  54. package/dist/learning/search.js.map +1 -1
  55. package/dist/learning/storeMeta.d.ts +9 -0
  56. package/dist/learning/storeMeta.d.ts.map +1 -1
  57. package/dist/learning/storeMeta.js +30 -24
  58. package/dist/learning/storeMeta.js.map +1 -1
  59. package/dist/learning/types.d.ts +57 -8
  60. package/dist/learning/types.d.ts.map +1 -1
  61. package/dist/lib/condenser.d.ts +112 -0
  62. package/dist/lib/condenser.d.ts.map +1 -0
  63. package/dist/lib/condenser.js +1337 -0
  64. package/dist/lib/condenser.js.map +1 -0
  65. package/dist/lib/db.d.ts +10 -0
  66. package/dist/lib/db.d.ts.map +1 -1
  67. package/dist/lib/db.js +654 -167
  68. package/dist/lib/db.js.map +1 -1
  69. package/dist/lib/logger.d.ts.map +1 -1
  70. package/dist/lib/logger.js +3 -2
  71. package/dist/lib/logger.js.map +1 -1
  72. package/dist/lib/projectSlug.d.ts +12 -5
  73. package/dist/lib/projectSlug.d.ts.map +1 -1
  74. package/dist/lib/projectSlug.js +62 -23
  75. package/dist/lib/projectSlug.js.map +1 -1
  76. package/dist/lib/recurrence.d.ts +16 -0
  77. package/dist/lib/recurrence.d.ts.map +1 -0
  78. package/dist/lib/recurrence.js +293 -0
  79. package/dist/lib/recurrence.js.map +1 -0
  80. package/dist/lib/scope.d.ts +36 -1
  81. package/dist/lib/scope.d.ts.map +1 -1
  82. package/dist/lib/scope.js +183 -19
  83. package/dist/lib/scope.js.map +1 -1
  84. package/dist/lib/signalTags.d.ts +39 -0
  85. package/dist/lib/signalTags.d.ts.map +1 -0
  86. package/dist/lib/signalTags.js +203 -0
  87. package/dist/lib/signalTags.js.map +1 -0
  88. package/dist/lib/spool.d.ts +2 -0
  89. package/dist/lib/spool.d.ts.map +1 -1
  90. package/dist/lib/spool.js +176 -65
  91. package/dist/lib/spool.js.map +1 -1
  92. package/dist/lib/storeDiagnostics.d.ts +41 -0
  93. package/dist/lib/storeDiagnostics.d.ts.map +1 -0
  94. package/dist/lib/storeDiagnostics.js +148 -0
  95. package/dist/lib/storeDiagnostics.js.map +1 -0
  96. package/dist/lib/temporal.d.ts +44 -0
  97. package/dist/lib/temporal.d.ts.map +1 -0
  98. package/dist/lib/temporal.js +1063 -0
  99. package/dist/lib/temporal.js.map +1 -0
  100. package/dist/mcp/server.d.ts +93 -3
  101. package/dist/mcp/server.d.ts.map +1 -1
  102. package/dist/mcp/server.js +499 -68
  103. package/dist/mcp/server.js.map +1 -1
  104. package/dist/memory/actionStore.d.ts +94 -3
  105. package/dist/memory/actionStore.d.ts.map +1 -1
  106. package/dist/memory/actionStore.js +412 -124
  107. package/dist/memory/actionStore.js.map +1 -1
  108. package/dist/memory/deadLetterStore.d.ts.map +1 -1
  109. package/dist/memory/deadLetterStore.js +4 -2
  110. package/dist/memory/deadLetterStore.js.map +1 -1
  111. package/dist/memory/embedQueueStore.d.ts +19 -8
  112. package/dist/memory/embedQueueStore.d.ts.map +1 -1
  113. package/dist/memory/embedQueueStore.js +55 -25
  114. package/dist/memory/embedQueueStore.js.map +1 -1
  115. package/dist/memory/failurePatternStore.d.ts +17 -1
  116. package/dist/memory/failurePatternStore.d.ts.map +1 -1
  117. package/dist/memory/failurePatternStore.js +54 -31
  118. package/dist/memory/failurePatternStore.js.map +1 -1
  119. package/dist/memory/graphStore.d.ts +133 -3
  120. package/dist/memory/graphStore.d.ts.map +1 -1
  121. package/dist/memory/graphStore.js +980 -155
  122. package/dist/memory/graphStore.js.map +1 -1
  123. package/dist/memory/noteStore.d.ts +27 -2
  124. package/dist/memory/noteStore.d.ts.map +1 -1
  125. package/dist/memory/noteStore.js +89 -26
  126. package/dist/memory/noteStore.js.map +1 -1
  127. package/dist/memory/observationStore.d.ts +11 -1
  128. package/dist/memory/observationStore.d.ts.map +1 -1
  129. package/dist/memory/observationStore.js +90 -15
  130. package/dist/memory/observationStore.js.map +1 -1
  131. package/dist/memory/projectRename.d.ts.map +1 -1
  132. package/dist/memory/projectRename.js +5 -1
  133. package/dist/memory/projectRename.js.map +1 -1
  134. package/dist/memory/rollupSweeper.d.ts.map +1 -1
  135. package/dist/memory/rollupSweeper.js +43 -23
  136. package/dist/memory/rollupSweeper.js.map +1 -1
  137. package/dist/memory/sessionStore.d.ts +25 -7
  138. package/dist/memory/sessionStore.d.ts.map +1 -1
  139. package/dist/memory/sessionStore.js +145 -33
  140. package/dist/memory/sessionStore.js.map +1 -1
  141. package/dist/memory/trajectoryStore.d.ts +8 -0
  142. package/dist/memory/trajectoryStore.d.ts.map +1 -1
  143. package/dist/memory/trajectoryStore.js +196 -130
  144. package/dist/memory/trajectoryStore.js.map +1 -1
  145. package/dist/middleware/rateLimiter.d.ts.map +1 -1
  146. package/dist/middleware/rateLimiter.js +24 -1
  147. package/dist/middleware/rateLimiter.js.map +1 -1
  148. package/dist/routes/dashboard.d.ts.map +1 -1
  149. package/dist/routes/dashboard.js +181 -8
  150. package/dist/routes/dashboard.js.map +1 -1
  151. package/dist/routes/mcp.d.ts.map +1 -1
  152. package/dist/routes/mcp.js +173 -21
  153. package/dist/routes/mcp.js.map +1 -1
  154. package/dist/routes/memories.js +9 -1
  155. package/dist/routes/memories.js.map +1 -1
  156. package/dist/scripts/doctor.d.ts +26 -2
  157. package/dist/scripts/doctor.d.ts.map +1 -1
  158. package/dist/scripts/doctor.js +371 -259
  159. package/dist/scripts/doctor.js.map +1 -1
  160. package/dist/scripts/installAgent.d.ts.map +1 -1
  161. package/dist/scripts/installAgent.js +101 -19
  162. package/dist/scripts/installAgent.js.map +1 -1
  163. package/dist/scripts/migrateAgentMemory.js +2 -2
  164. package/dist/scripts/smokeTest.js +1 -1
  165. package/dist/scripts/smokeTest.js.map +1 -1
  166. package/docker-compose.yml +1 -1
  167. package/npm-shrinkwrap.json +2 -2
  168. package/package.json +3 -2
  169. package/plugin/hooks/postToolUse.js +155 -50
  170. package/plugin/hooks/sessionStart.js +179 -27
  171. package/plugin/hooks/sessionStop.js +152 -37
  172. package/plugin/plugin.json +1 -1
  173. package/plugin/rules/AGENTS.md +10 -8
  174. package/plugin/skills/brain-memory/REFERENCE.md +15 -14
  175. package/plugin/skills/brain-memory/SKILL.md +2 -2
  176. package/plugin/skills/digest/SKILL.md +1 -1
  177. package/plugin/skills/handoff/SKILL.md +1 -1
  178. package/plugin/skills/save/SKILL.md +2 -2
  179. package/plugin/skills/search/SKILL.md +2 -2
  180. package/src/ai/chat.ts +1 -2
  181. package/src/ai/config.ts +2 -2
  182. package/src/app.ts +475 -54
  183. package/src/cli.ts +500 -38
  184. package/src/consolidation/candidates.ts +22 -4
  185. package/src/consolidation/fixtures.ts +1 -1
  186. package/src/consolidation/gate.ts +177 -140
  187. package/src/consolidation/runner.ts +26 -2
  188. package/src/dashboard/clientScript.ts +3774 -905
  189. package/src/dashboard/html.ts +605 -101
  190. package/src/dashboard/styles.ts +1591 -359
  191. package/src/learning/embedWorker.ts +350 -70
  192. package/src/learning/embedding.ts +141 -28
  193. package/src/learning/engine.ts +1 -1
  194. package/src/learning/search.ts +2533 -397
  195. package/src/learning/storeMeta.ts +36 -29
  196. package/src/learning/types.ts +66 -8
  197. package/src/lib/condenser.ts +1515 -0
  198. package/src/lib/db.ts +690 -171
  199. package/src/lib/logger.ts +4 -2
  200. package/src/lib/projectSlug.ts +77 -23
  201. package/src/lib/recurrence.ts +382 -0
  202. package/src/lib/scope.ts +220 -22
  203. package/src/lib/signalTags.ts +257 -0
  204. package/src/lib/spool.ts +181 -71
  205. package/src/lib/storeDiagnostics.ts +181 -0
  206. package/src/lib/temporal.ts +1250 -0
  207. package/src/mcp/server.ts +559 -88
  208. package/src/memory/actionStore.ts +642 -171
  209. package/src/memory/deadLetterStore.ts +4 -2
  210. package/src/memory/embedQueueStore.ts +63 -27
  211. package/src/memory/failurePatternStore.ts +84 -31
  212. package/src/memory/graphStore.ts +1396 -215
  213. package/src/memory/noteStore.ts +151 -30
  214. package/src/memory/observationStore.ts +117 -17
  215. package/src/memory/projectRename.ts +6 -2
  216. package/src/memory/rollupSweeper.ts +46 -23
  217. package/src/memory/sessionStore.ts +197 -38
  218. package/src/memory/trajectoryStore.ts +260 -140
  219. package/src/middleware/rateLimiter.ts +24 -1
  220. package/src/routes/dashboard.ts +194 -9
  221. package/src/routes/mcp.ts +185 -26
  222. package/src/routes/memories.ts +8 -1
  223. package/src/scripts/doctor.ts +461 -262
  224. package/src/scripts/installAgent.ts +106 -19
  225. package/src/scripts/migrateAgentMemory.ts +2 -2
  226. package/src/scripts/smokeTest.ts +1 -1
@@ -1,3 +1,4 @@
1
+ import crypto from 'crypto';
1
2
  import { Router, Request, Response, NextFunction } from 'express';
2
3
  import { getDb } from '../lib/db';
3
4
  import { logger } from '../lib/logger';
@@ -8,7 +9,15 @@ import { drainEmbedQueue, getReembedStatus, probeQdrant } from '../learning/embe
8
9
  import { listNotes } from '../memory/noteStore';
9
10
  import { listTrajectories } from '../memory/trajectoryStore';
10
11
  import { listObservations } from '../memory/observationStore';
11
- import { getKnowledgeGraph, parseGraphQuery } from '../memory/graphStore';
12
+ import {
13
+ getKnowledgeGraph,
14
+ linkEntities,
15
+ listEntities,
16
+ parseGraphQuery,
17
+ unlinkEntities,
18
+ upsertEntity,
19
+ } from '../memory/graphStore';
20
+ import { getDueActions } from '../memory/actionStore';
12
21
  import { migrateAgentMemoryNotes } from '../scripts/migrateAgentMemory';
13
22
  import {
14
23
  hasActiveApiKeys,
@@ -23,6 +32,50 @@ import { dashboardJs } from '../dashboard/clientScript';
23
32
 
24
33
  export const dashboardRouter = Router();
25
34
 
35
+ // In-memory idempotency key deduplication cache (prevents double-submit on retried mutations)
36
+ const IDEMPOTENCY_TTL_MS = 5 * 60 * 1000;
37
+ const IDEMPOTENCY_MAX_ENTRIES = 500;
38
+ const idempotencyCache = new Map<string, { status: number; body: unknown; expiresAt: number }>();
39
+
40
+ function checkIdempotencyKey(req: Request, res: Response, next: NextFunction) {
41
+ if (!['POST', 'PUT', 'PATCH', 'DELETE'].includes(req.method) || req.path === '/api/session') {
42
+ return next();
43
+ }
44
+
45
+ const rawKey = req.headers['idempotency-key'];
46
+ const idempotencyKey = typeof rawKey === 'string' ? rawKey.trim() : '';
47
+ if (!idempotencyKey) {
48
+ return next();
49
+ }
50
+
51
+ const now = Date.now();
52
+ const cacheKey = `${req.method}:${req.path}:${idempotencyKey}`;
53
+ const cached = idempotencyCache.get(cacheKey);
54
+ if (cached && cached.expiresAt > now) {
55
+ res.setHeader('X-Idempotency-Replayed', 'true');
56
+ return res.status(cached.status).json(cached.body);
57
+ }
58
+ if (cached) {
59
+ idempotencyCache.delete(cacheKey);
60
+ }
61
+
62
+ const originalJson = res.json.bind(res);
63
+ res.json = ((body: unknown) => {
64
+ if (idempotencyCache.size >= IDEMPOTENCY_MAX_ENTRIES) {
65
+ const oldestKey = idempotencyCache.keys().next().value;
66
+ if (oldestKey) idempotencyCache.delete(oldestKey);
67
+ }
68
+ idempotencyCache.set(cacheKey, {
69
+ status: res.statusCode || 200,
70
+ body,
71
+ expiresAt: Date.now() + IDEMPOTENCY_TTL_MS,
72
+ });
73
+ return originalJson(body);
74
+ }) as Response['json'];
75
+
76
+ next();
77
+ }
78
+
26
79
  // Strict Security Headers Middleware for all /dashboard endpoints
27
80
  dashboardRouter.use((_req: Request, res: Response, next: NextFunction) => {
28
81
  res.setHeader(
@@ -35,6 +88,7 @@ dashboardRouter.use((_req: Request, res: Response, next: NextFunction) => {
35
88
  res.setHeader('Cache-Control', 'no-store');
36
89
  next();
37
90
  });
91
+ dashboardRouter.use(checkIdempotencyKey);
38
92
 
39
93
  // ---------------------------------------------------------------------------
40
94
  // HTML & Static Assets (Served directly from compiled TypeScript modules)
@@ -80,12 +134,25 @@ dashboardRouter.post('/api/session', (req: Request, res: Response) => {
80
134
 
81
135
  const hashedKey = hashApiKey(rawKey);
82
136
  const db = getDb();
83
- const keyRecord = db
137
+ const activeKeys = db
84
138
  .prepare(
85
- `SELECT id, name, key FROM api_keys
86
- WHERE (key = ? OR key = ?) AND revoked_at IS NULL AND (expires_at IS NULL OR expires_at > datetime('now'))`
139
+ `SELECT id, name, key FROM api_keys
140
+ WHERE revoked_at IS NULL AND (expires_at IS NULL OR expires_at > datetime('now'))`
87
141
  )
88
- .get(hashedKey, rawKey) as { id: string; name: string; key: string } | undefined;
142
+ .all() as Array<{ id: string; name: string; key: string }>;
143
+
144
+ const hashedBuf = Buffer.from(hashedKey, 'utf8');
145
+ const rawBuf = Buffer.from(rawKey, 'utf8');
146
+ const keyRecord = activeKeys.find((rec) => {
147
+ const candidateBuf = Buffer.from(rec.key, 'utf8');
148
+ if (candidateBuf.length === hashedBuf.length && crypto.timingSafeEqual(candidateBuf, hashedBuf)) {
149
+ return true;
150
+ }
151
+ if (candidateBuf.length === rawBuf.length && crypto.timingSafeEqual(candidateBuf, rawBuf)) {
152
+ return true;
153
+ }
154
+ return false;
155
+ });
89
156
 
90
157
  if (!keyRecord) {
91
158
  res.status(401).json({ error: { code: 'UNAUTHORIZED', message: 'Invalid or expired API key' } });
@@ -266,16 +333,19 @@ dashboardRouter.get('/api/stats', async (_req: Request, res: Response, next: Nex
266
333
  project_id,
267
334
  COALESCE(SUM(CASE WHEN source = 'note' THEN 1 ELSE 0 END), 0) as notes_count,
268
335
  COALESCE(SUM(CASE WHEN source = 'trajectory' THEN 1 ELSE 0 END), 0) as trajectories_count,
269
- COALESCE(SUM(CASE WHEN source = 'observation' THEN 1 ELSE 0 END), 0) as observations_count
336
+ COALESCE(SUM(CASE WHEN source = 'observation' THEN 1 ELSE 0 END), 0) as observations_count,
337
+ COALESCE(SUM(CASE WHEN source = 'entity' THEN 1 ELSE 0 END), 0) as entities_count
270
338
  FROM (
271
339
  SELECT project_id, 'note' as source FROM notes WHERE project_id IS NOT NULL
272
340
  UNION ALL
273
341
  SELECT project_id, 'trajectory' as source FROM trajectories WHERE project_id IS NOT NULL
274
342
  UNION ALL
275
343
  SELECT project_id, 'observation' as source FROM observations WHERE project_id IS NOT NULL
344
+ UNION ALL
345
+ SELECT project_id, 'entity' as source FROM entities WHERE project_id IS NOT NULL
276
346
  )
277
347
  GROUP BY project_id
278
- ORDER BY (notes_count + trajectories_count + observations_count) DESC
348
+ ORDER BY (notes_count + trajectories_count + observations_count + entities_count) DESC
279
349
  `)
280
350
  .all() as any[];
281
351
 
@@ -303,7 +373,9 @@ dashboardRouter.get('/api/stats', async (_req: Request, res: Response, next: Nex
303
373
 
304
374
  // 9. Extractive Summaries with claims and sources (batched to eliminate N+1 queries)
305
375
  const rawSummaries = db
306
- .prepare('SELECT * FROM summaries ORDER BY created_at DESC LIMIT 15')
376
+ .prepare(
377
+ 'SELECT id, scope, project_id, kind, window_from, window_to, outcome, producer_tier, producer_model, prompt_version, verified, version, supersedes, is_latest, sources_expired, created_at FROM summaries ORDER BY created_at DESC LIMIT 15'
378
+ )
307
379
  .all() as any[];
308
380
 
309
381
  let summaries: any[] = [];
@@ -317,7 +389,7 @@ dashboardRouter.get('/api/stats', async (_req: Request, res: Response, next: Nex
317
389
  .all(...summaryIds) as any[];
318
390
  const allSources = db
319
391
  .prepare(
320
- `SELECT summary_id, claim_id, record_id, grain FROM summary_sources WHERE summary_id IN (${placeholders})`
392
+ `SELECT summary_id, claim_id, record_id, record_type FROM summary_sources WHERE summary_id IN (${placeholders})`
321
393
  )
322
394
  .all(...summaryIds) as any[];
323
395
 
@@ -410,6 +482,23 @@ dashboardRouter.get('/api/stats', async (_req: Request, res: Response, next: Nex
410
482
  .get() as any;
411
483
  const lessonsCount = lessonsRow?.count ?? 0;
412
484
 
485
+ const entitiesRow = db
486
+ .prepare(`SELECT COUNT(*) as count FROM entities`)
487
+ .get() as any;
488
+ const entitiesCount = entitiesRow?.count ?? 0;
489
+
490
+ const nowIso = new Date().toISOString();
491
+ const dueActionsRow = db
492
+ .prepare(`
493
+ SELECT COUNT(*) as count
494
+ FROM actions
495
+ WHERE status IN ('ready', 'in_progress')
496
+ AND ((remind_at IS NOT NULL AND remind_at <= ?) OR (due_at IS NOT NULL AND due_at <= ?))
497
+ AND (snooze_until IS NULL OR snooze_until <= ?)
498
+ `)
499
+ .get(nowIso, nowIso, nowIso) as any;
500
+ const dueActionsCount = dueActionsRow?.count ?? 0;
501
+
413
502
  res.json({
414
503
  health,
415
504
  counts,
@@ -426,12 +515,33 @@ dashboardRouter.get('/api/stats', async (_req: Request, res: Response, next: Nex
426
515
  sessions,
427
516
  actions,
428
517
  lessonsCount,
518
+ entities_count: entitiesCount,
519
+ due_actions_count: dueActionsCount,
429
520
  });
430
521
  } catch (err) {
431
522
  next(err);
432
523
  }
433
524
  });
434
525
 
526
+ function parseOptionalBoolQuery(raw: unknown): boolean | undefined {
527
+ if (raw === true || raw === 'true' || raw === '1') return true;
528
+ if (raw === false || raw === 'false' || raw === '0') return false;
529
+ return undefined;
530
+ }
531
+
532
+ function parseOptionalStringQuery(raw: unknown): string | undefined {
533
+ if (typeof raw !== 'string') return undefined;
534
+ const trimmed = raw.trim();
535
+ return trimmed === '' ? undefined : trimmed;
536
+ }
537
+
538
+ function parseBoundedLimitQuery(raw: unknown, defaultLimit = 50, maxLimit = 200): number {
539
+ if (raw === undefined || raw === null || raw === '') return defaultLimit;
540
+ const parsed = parseInt(String(raw), 10);
541
+ if (!Number.isFinite(parsed) || parsed <= 0) return defaultLimit;
542
+ return Math.min(parsed, maxLimit);
543
+ }
544
+
435
545
  // GET /dashboard/api/graph: Knowledge graph nodes & edges
436
546
  dashboardRouter.get('/api/graph', (req: Request, res: Response, next: NextFunction) => {
437
547
  try {
@@ -442,6 +552,47 @@ dashboardRouter.get('/api/graph', (req: Request, res: Response, next: NextFuncti
442
552
  }
443
553
  });
444
554
 
555
+ // GET /dashboard/api/graph/entities: List entities with hierarchical scoping
556
+ dashboardRouter.get('/api/graph/entities', (req: Request, res: Response, next: NextFunction) => {
557
+ try {
558
+ const q = req.query as Record<string, unknown>;
559
+ const entities = listEntities({
560
+ projectId: parseOptionalStringQuery(q.project_id ?? q.projectId),
561
+ scope: parseOptionalStringQuery(q.scope),
562
+ includeAncestors: parseOptionalBoolQuery(q.include_ancestors ?? q.includeAncestors),
563
+ includeChildren: parseOptionalBoolQuery(q.include_children ?? q.includeChildren),
564
+ includeGlobal: parseOptionalBoolQuery(q.include_global ?? q.includeGlobal),
565
+ entityType: parseOptionalStringQuery(q.entity_type ?? q.entityType),
566
+ externalRef: parseOptionalStringQuery(q.external_ref ?? q.externalRef),
567
+ userId: parseOptionalStringQuery(q.user_id ?? q.userId),
568
+ limit: parseBoundedLimitQuery(q.limit, 50, 200),
569
+ });
570
+ res.json({ entities });
571
+ } catch (err) {
572
+ next(err);
573
+ }
574
+ });
575
+
576
+ // GET /dashboard/api/actions/due: Due/overdue reminders across project hierarchy
577
+ dashboardRouter.get('/api/actions/due', (req: Request, res: Response, next: NextFunction) => {
578
+ try {
579
+ const q = req.query as Record<string, unknown>;
580
+ const actions = getDueActions({
581
+ projectId: parseOptionalStringQuery(q.project_id ?? q.projectId),
582
+ includeAncestors: parseOptionalBoolQuery(q.include_ancestors ?? q.includeAncestors),
583
+ includeChildren: parseOptionalBoolQuery(q.include_children ?? q.includeChildren),
584
+ includeGlobal: parseOptionalBoolQuery(q.include_global ?? q.includeGlobal),
585
+ before: parseOptionalStringQuery(q.before),
586
+ userId: parseOptionalStringQuery(q.user_id ?? q.userId),
587
+ unremindedOnly: parseOptionalBoolQuery(q.unreminded_only ?? q.unremindedOnly),
588
+ limit: parseBoundedLimitQuery(q.limit, 50, 200),
589
+ });
590
+ res.json({ actions });
591
+ } catch (err) {
592
+ next(err);
593
+ }
594
+ });
595
+
445
596
  function checkDashboardCsrf(req: Request, res: Response, next: NextFunction) {
446
597
  const origin = req.headers.origin;
447
598
  const host = req.headers.host;
@@ -472,6 +623,40 @@ function checkDashboardCsrf(req: Request, res: Response, next: NextFunction) {
472
623
  next();
473
624
  }
474
625
 
626
+ // POST /dashboard/api/graph/entities: Upsert an entity node
627
+ dashboardRouter.post('/api/graph/entities', checkDashboardCsrf, (req: Request, res: Response, next: NextFunction) => {
628
+ try {
629
+ const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {};
630
+ const entity = upsertEntity(body);
631
+ res.status(201).json({ entity });
632
+ } catch (err) {
633
+ next(err);
634
+ }
635
+ });
636
+
637
+ // POST /dashboard/api/graph/edges: Link two graph nodes
638
+ dashboardRouter.post('/api/graph/edges', checkDashboardCsrf, (req: Request, res: Response, next: NextFunction) => {
639
+ try {
640
+ const body = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {};
641
+ const edge = linkEntities(body);
642
+ res.status(201).json({ edge });
643
+ } catch (err) {
644
+ next(err);
645
+ }
646
+ });
647
+
648
+ // DELETE /dashboard/api/graph/edges: Unlink graph edges by id, source_id, target_id, and/or relation
649
+ dashboardRouter.delete('/api/graph/edges', checkDashboardCsrf, (req: Request, res: Response, next: NextFunction) => {
650
+ try {
651
+ const rawBody = req.body && typeof req.body === 'object' && !Array.isArray(req.body) ? req.body : {};
652
+ const input = { ...(req.query as Record<string, unknown>), ...rawBody };
653
+ const result = unlinkEntities(input);
654
+ res.json(result);
655
+ } catch (err) {
656
+ next(err);
657
+ }
658
+ });
659
+
475
660
  // POST /dashboard/api/migrate: Imports notes from an existing agentmemory store
476
661
  dashboardRouter.post('/api/migrate', checkDashboardCsrf, async (_req: Request, res: Response, next: NextFunction) => {
477
662
  try {
package/src/routes/mcp.ts CHANGED
@@ -8,15 +8,21 @@ import { createNote } from '../memory/noteStore';
8
8
  import { getFailurePatterns } from '../memory/failurePatternStore';
9
9
  import { getConsolidationCandidates } from '../consolidation/candidates';
10
10
  import { verifyAndStoreSummary } from '../consolidation/gate';
11
- import { createAction, listActions, updateAction } from '../memory/actionStore';
11
+ import { createAction, getDueActions, listActions, updateAction } from '../memory/actionStore';
12
12
  import { endSession, getSessionDetails, getSessionReplay, listSessions } from '../memory/sessionStore';
13
- import { getKnowledgeGraph, parseGraphQuery } from '../memory/graphStore';
13
+ import {
14
+ getKnowledgeGraph,
15
+ linkEntities,
16
+ parseGraphQuery,
17
+ unlinkEntities,
18
+ upsertEntity,
19
+ } from '../memory/graphStore';
14
20
 
15
21
  export const mcpRouter = Router();
16
22
 
17
23
  function jsonText(data: unknown, isError = false) {
18
24
  return {
19
- content: [{ type: 'text' as const, text: JSON.stringify(data, null, 2) }],
25
+ content: [{ type: 'text' as const, text: JSON.stringify(data) }],
20
26
  ...(isError ? { isError: true } : {}),
21
27
  };
22
28
  }
@@ -35,27 +41,37 @@ function errorResult(err: unknown) {
35
41
  );
36
42
  }
37
43
 
38
- function assertScopeAndProject(
44
+ function clampLimit(raw: number | undefined, defaultLimit: number, maxLimit = 200): number {
45
+ if (raw === undefined || !Number.isFinite(raw)) return defaultLimit;
46
+ return Math.max(1, Math.min(Math.trunc(raw), maxLimit));
47
+ }
48
+
49
+ function validateScopeAndProject(
39
50
  scope: string | undefined,
40
51
  projectId: string | undefined,
41
52
  defaultProjectId: string | undefined
42
- ): string | undefined {
53
+ ): { effectiveProjectId?: string; error?: { code: string; message: string } } {
43
54
  if (!scope || (scope !== 'project' && scope !== 'global' && scope !== 'unknown')) {
44
- const err = new Error("SCOPE_REQUIRED: Scope is required and must be 'project', 'global', or 'unknown'");
45
- (err as any).code = 'SCOPE_REQUIRED';
46
- throw err;
55
+ return {
56
+ error: {
57
+ code: 'SCOPE_REQUIRED',
58
+ message: "SCOPE_REQUIRED: Scope is required and must be 'project', 'global', or 'unknown'",
59
+ },
60
+ };
47
61
  }
48
62
 
49
63
  const effectiveProjectId = projectId || (scope === 'project' ? defaultProjectId : undefined);
50
64
  if (scope === 'project' && !effectiveProjectId) {
51
- const err = new Error(
52
- "SCHEMA_INVALID: project_id is required when scope is 'project' (use the project root folder name, e.g. 'neuralbrain' — from .brainrc or the git repo root, not a subfolder or filesystem path)"
53
- );
54
- (err as any).code = 'SCHEMA_INVALID';
55
- throw err;
65
+ return {
66
+ error: {
67
+ code: 'SCHEMA_INVALID',
68
+ message:
69
+ "SCHEMA_INVALID: project_id is required when scope is 'project' (use the project_id in .brainrc if present, else the git repo root folder name, e.g. 'neuralbrain' or 'acme/socials/calendar', not a subfolder or filesystem path)",
70
+ },
71
+ };
56
72
  }
57
73
 
58
- return effectiveProjectId;
74
+ return { effectiveProjectId };
59
75
  }
60
76
 
61
77
  /**
@@ -72,6 +88,10 @@ export function createDirectBrainMcpHandlers(
72
88
  const filters: Record<string, any> = {};
73
89
  if (args.type && args.type.length > 0) filters.type = args.type;
74
90
  if (args.file_path) filters.file_path = args.file_path;
91
+ if (args.entity_type) filters.entity_type = args.entity_type;
92
+ if (args.memory_layer) filters.memory_layer = args.memory_layer;
93
+ if (args.signal_tag) filters.signal_tag = args.signal_tag;
94
+ if (args.user_id) filters.user_id = args.user_id;
75
95
 
76
96
  const requestedTypes =
77
97
  args.record_types && args.record_types.length > 0 ? args.record_types : args.grains;
@@ -80,8 +100,24 @@ export function createDirectBrainMcpHandlers(
80
100
  record_types: (requestedTypes && requestedTypes.length > 0
81
101
  ? requestedTypes
82
102
  : ['note', 'trajectory']) as any,
103
+ include_ancestors: args.include_ancestors !== false,
104
+ include_children: Boolean(args.include_children),
83
105
  include_global: args.include_global !== false,
84
- limit: args.limit ?? 10,
106
+ include_history: Boolean(args.include_history),
107
+ include_sources: Boolean(args.include_sources),
108
+ ...(args.user_id !== undefined ? { user_id: args.user_id } : {}),
109
+ ...(args.after !== undefined ? { after: args.after } : {}),
110
+ ...(args.before !== undefined ? { before: args.before } : {}),
111
+ ...(args.as_of !== undefined ? { as_of: args.as_of } : {}),
112
+ ...(args.reference_date !== undefined ? { reference_date: args.reference_date } : {}),
113
+ ...(args.temporal_bias !== undefined ? { temporal_bias: args.temporal_bias } : {}),
114
+ ...(args.snippet_mode !== undefined ? { snippet_mode: args.snippet_mode } : {}),
115
+ ...(args.max_record_chars !== undefined ? { max_record_chars: args.max_record_chars } : {}),
116
+ ...(args.kind_weights !== undefined ? { kind_weights: args.kind_weights } : {}),
117
+ ...(args.max_kind_share !== undefined ? { max_kind_share: args.max_kind_share } : {}),
118
+ ...(args.sources_limit !== undefined ? { sources_limit: clampLimit(args.sources_limit, 20, 100) } : {}),
119
+ ...(args.sources_offset !== undefined ? { sources_offset: Math.max(0, Math.trunc(args.sources_offset)) } : {}),
120
+ limit: clampLimit(args.limit, 10, 100),
85
121
  ...(targetProjectId ? { project_id: targetProjectId, scope: 'project' as const } : {}),
86
122
  ...(Object.keys(filters).length > 0 ? { filters } : {}),
87
123
  });
@@ -92,7 +128,11 @@ export function createDirectBrainMcpHandlers(
92
128
  },
93
129
 
94
130
  brainSave: async (args) => {
95
- const effectiveProjectId = assertScopeAndProject(args.scope, args.project_id, defaultProjectId);
131
+ const check = validateScopeAndProject(args.scope, args.project_id, defaultProjectId);
132
+ if (check.error) {
133
+ return jsonText({ error: check.error }, true);
134
+ }
135
+ const effectiveProjectId = check.effectiveProjectId;
96
136
  try {
97
137
  const created = createNote({
98
138
  type: args.type,
@@ -105,6 +145,11 @@ export function createDirectBrainMcpHandlers(
105
145
  files: args.files || [],
106
146
  supersedes: args.supersedes || null,
107
147
  ...(args.session_id !== undefined ? { session_id: args.session_id } : {}),
148
+ ...(args.user_id !== undefined ? { user_id: args.user_id } : {}),
149
+ ...(args.agent_id !== undefined ? { agent_id: args.agent_id } : {}),
150
+ ...(args.event_at !== undefined ? { event_at: args.event_at } : {}),
151
+ ...(args.valid_from !== undefined ? { valid_from: args.valid_from } : {}),
152
+ ...(args.valid_until !== undefined ? { valid_until: args.valid_until } : {}),
108
153
  });
109
154
  return jsonText(created);
110
155
  } catch (err) {
@@ -118,10 +163,21 @@ export function createDirectBrainMcpHandlers(
118
163
  const patterns = getFailurePatterns({
119
164
  projectId: targetProjectId,
120
165
  taskType: args?.task_type,
121
- includeGlobal: true,
122
- limit: args?.limit,
166
+ includeAncestors: args?.include_ancestors !== false,
167
+ includeChildren: Boolean(args?.include_children),
168
+ includeGlobal: args?.include_global !== false,
169
+ userId: args?.user_id,
170
+ limit: clampLimit(args?.limit, 5, 200),
123
171
  });
124
- return jsonText(patterns);
172
+ const result = patterns.map((p) => ({
173
+ task_type: p.task_type,
174
+ error_text: p.error_text,
175
+ count: p.count,
176
+ last_seen_at: p.last_seen_at,
177
+ project_id: p.project_id ?? null,
178
+ match_tier: p.match_tier ?? null,
179
+ }));
180
+ return jsonText(result);
125
181
  } catch (err) {
126
182
  return errorResult(err);
127
183
  }
@@ -132,7 +188,7 @@ export function createDirectBrainMcpHandlers(
132
188
  const targetProjectId = args?.project_id || defaultProjectId;
133
189
  const result = getConsolidationCandidates({
134
190
  projectId: targetProjectId,
135
- limit: args?.limit,
191
+ limit: args?.limit !== undefined ? clampLimit(args.limit, 5, 200) : undefined,
136
192
  });
137
193
  return jsonText(result);
138
194
  } catch (err) {
@@ -167,18 +223,28 @@ export function createDirectBrainMcpHandlers(
167
223
  },
168
224
 
169
225
  brainActionAdd: async (args) => {
170
- const effectiveProjectId = assertScopeAndProject(args.scope, args.project_id, defaultProjectId);
226
+ const check = validateScopeAndProject(args.scope, args.project_id, defaultProjectId);
227
+ if (check.error) {
228
+ return jsonText({ error: check.error }, true);
229
+ }
230
+ const effectiveProjectId = check.effectiveProjectId;
171
231
  try {
172
232
  const action = createAction({
173
233
  title: args.title,
174
234
  scope: args.scope as 'project' | 'global' | 'unknown',
175
235
  ...(args.description !== undefined ? { description: args.description } : {}),
176
236
  ...(effectiveProjectId ? { project_id: effectiveProjectId } : {}),
237
+ ...(args.user_id !== undefined ? { user_id: args.user_id } : {}),
238
+ ...(args.agent_id !== undefined ? { agent_id: args.agent_id } : {}),
177
239
  ...(args.session_id !== undefined ? { session_id: args.session_id } : {}),
178
240
  ...(args.status !== undefined ? { status: args.status } : {}),
179
241
  ...(args.priority !== undefined ? { priority: args.priority } : {}),
180
242
  ...(args.blocked_reason !== undefined ? { blocked_reason: args.blocked_reason } : {}),
181
243
  ...(args.files !== undefined ? { files: args.files } : {}),
244
+ ...(args.due_at !== undefined ? { due_at: args.due_at } : {}),
245
+ ...(args.remind_at !== undefined ? { remind_at: args.remind_at } : {}),
246
+ ...(args.recurrence !== undefined ? { recurrence: args.recurrence } : {}),
247
+ ...(args.snooze_until !== undefined ? { snooze_until: args.snooze_until } : {}),
182
248
  });
183
249
  return jsonText({ action });
184
250
  } catch (err) {
@@ -191,9 +257,14 @@ export function createDirectBrainMcpHandlers(
191
257
  const targetProjectId = args.project_id || defaultProjectId;
192
258
  const actions = listActions({
193
259
  projectId: targetProjectId,
260
+ includeAncestors: args.include_ancestors !== false,
261
+ includeChildren: Boolean(args.include_children),
194
262
  includeGlobal: args.include_global !== false,
263
+ dueOnly: Boolean(args.due_only),
264
+ before: args.before,
265
+ userId: args.user_id,
195
266
  status: args.status,
196
- limit: args.limit,
267
+ limit: args.limit !== undefined ? clampLimit(args.limit, 50, 200) : undefined,
197
268
  });
198
269
  return jsonText({ actions });
199
270
  } catch (err) {
@@ -212,6 +283,12 @@ export function createDirectBrainMcpHandlers(
212
283
  ...(args.resolved_by_session_id !== undefined
213
284
  ? { resolved_by_session_id: args.resolved_by_session_id }
214
285
  : {}),
286
+ ...(args.due_at !== undefined ? { due_at: args.due_at } : {}),
287
+ ...(args.remind_at !== undefined ? { remind_at: args.remind_at } : {}),
288
+ ...(args.recurrence !== undefined ? { recurrence: args.recurrence } : {}),
289
+ ...(args.snooze_until !== undefined ? { snooze_until: args.snooze_until } : {}),
290
+ ...(args.user_id !== undefined ? { user_id: args.user_id } : {}),
291
+ ...(args.agent_id !== undefined ? { agent_id: args.agent_id } : {}),
215
292
  });
216
293
  if (!action) {
217
294
  return jsonText(
@@ -230,6 +307,24 @@ export function createDirectBrainMcpHandlers(
230
307
  }
231
308
  },
232
309
 
310
+ brainActionDue: async (args = {}) => {
311
+ try {
312
+ const targetProjectId = args.project_id || defaultProjectId;
313
+ const actions = getDueActions({
314
+ projectId: targetProjectId,
315
+ includeAncestors: args.include_ancestors !== false,
316
+ includeChildren: Boolean(args.include_children),
317
+ includeGlobal: args.include_global !== false,
318
+ before: args.before,
319
+ userId: args.user_id,
320
+ limit: args.limit !== undefined ? clampLimit(args.limit, 50, 200) : undefined,
321
+ });
322
+ return jsonText({ actions });
323
+ } catch (err) {
324
+ return errorResult(err);
325
+ }
326
+ },
327
+
233
328
  brainSessions: async (args = {}) => {
234
329
  try {
235
330
  const mode = args.mode || 'list';
@@ -261,11 +356,18 @@ export function createDirectBrainMcpHandlers(
261
356
  }
262
357
 
263
358
  const targetProjectId = args.project_id || defaultProjectId;
359
+ const includeGlobal = targetProjectId
360
+ ? (args.include_global === true)
361
+ : args.include_global;
264
362
  const sessions = listSessions({
265
363
  projectId: targetProjectId,
364
+ includeAncestors: args.include_ancestors !== false,
365
+ includeChildren: Boolean(args.include_children),
366
+ includeGlobal,
367
+ userId: args.user_id,
266
368
  status: args.status,
267
369
  agentName: args.agent_name,
268
- limit: args.limit,
370
+ limit: args.limit !== undefined ? clampLimit(args.limit, 50, 200) : undefined,
269
371
  });
270
372
  return jsonText({ sessions });
271
373
  } catch (err) {
@@ -300,12 +402,65 @@ export function createDirectBrainMcpHandlers(
300
402
 
301
403
  brainGraph: async (args = {}) => {
302
404
  try {
303
- const targetProjectId = args.project_id || defaultProjectId;
405
+ const mode = args.mode || 'query';
406
+
407
+ if (mode === 'upsert_entity') {
408
+ const check = validateScopeAndProject(args.scope, args.project_id, defaultProjectId);
409
+ if (check.error) {
410
+ return jsonText({ error: check.error }, true);
411
+ }
412
+ const entity = upsertEntity({
413
+ id: args.entity_id ?? args.id,
414
+ scope: args.scope,
415
+ project_id: check.effectiveProjectId ?? null,
416
+ entity_type: args.entity_type,
417
+ name: args.name ?? '',
418
+ description: args.description,
419
+ external_ref: args.external_ref,
420
+ metadata: args.metadata,
421
+ user_id: args.user_id,
422
+ agent_id: args.agent_id,
423
+ });
424
+ return jsonText({ entity });
425
+ }
426
+
427
+ if (mode === 'link') {
428
+ const edge = linkEntities({
429
+ source_type: args.source_type,
430
+ source_id: args.source_id,
431
+ target_type: args.target_type,
432
+ target_id: args.target_id,
433
+ relation: args.relation ?? '',
434
+ metadata: args.metadata,
435
+ });
436
+ return jsonText({ edge });
437
+ }
438
+
439
+ if (mode === 'unlink') {
440
+ const result = unlinkEntities({
441
+ id: args.id,
442
+ source_id: args.source_id,
443
+ target_id: args.target_id,
444
+ relation: args.relation,
445
+ });
446
+ return jsonText(result);
447
+ }
448
+
449
+ const targetProjectId =
450
+ args.project_id || (args.scope === 'global' || args.scope === 'unknown' ? undefined : defaultProjectId);
304
451
  const graph = getKnowledgeGraph(
305
452
  parseGraphQuery({
306
453
  ...(targetProjectId ? { project_id: targetProjectId } : {}),
307
454
  ...(args.scope ? { scope: args.scope } : {}),
308
- ...(args.limit !== undefined ? { limit: args.limit } : {}),
455
+ ...(args.include_ancestors !== undefined ? { include_ancestors: args.include_ancestors } : {}),
456
+ ...(args.include_children !== undefined ? { include_children: args.include_children } : {}),
457
+ ...(args.include_global !== undefined ? { include_global: args.include_global } : {}),
458
+ ...(args.depth !== undefined ? { depth: args.depth } : {}),
459
+ ...(args.node_id ? { node_id: args.node_id } : {}),
460
+ ...(args.entity_type ? { entity_type: args.entity_type } : {}),
461
+ ...(args.relation ? { relation: args.relation } : {}),
462
+ ...(args.user_id ? { user_id: args.user_id } : {}),
463
+ ...(args.limit !== undefined ? { limit: clampLimit(args.limit, 50, 200) } : {}),
309
464
  })
310
465
  );
311
466
  return jsonText(graph);
@@ -316,9 +471,13 @@ export function createDirectBrainMcpHandlers(
316
471
  };
317
472
  }
318
473
 
474
+ const cachedDefaultProjectId = resolveCanonicalProjectId({ fallbackToDirname: false }) ?? undefined;
475
+ const cachedDirectHandlers = createDirectBrainMcpHandlers(cachedDefaultProjectId);
476
+
319
477
  mcpRouter.all('/', async (req: Request, res: Response) => {
320
478
  const server = createBrainMcpServer({
321
- handlers: createDirectBrainMcpHandlers(),
479
+ defaultProjectId: cachedDefaultProjectId,
480
+ handlers: cachedDirectHandlers,
322
481
  });
323
482
 
324
483
  const transport = new StreamableHTTPServerTransport({
@@ -3,6 +3,13 @@ import { getTrajectory, getSwarmTrajectories, runCleanup } from '../memory/traje
3
3
 
4
4
  export const memoriesRouter = Router();
5
5
 
6
+ function parseBoundedLimit(raw: unknown, defaultLimit = 50, maxLimit = 200): number {
7
+ if (raw === undefined || raw === null || raw === '') return defaultLimit;
8
+ const parsed = parseInt(String(raw), 10);
9
+ if (!Number.isFinite(parsed) || parsed <= 0) return defaultLimit;
10
+ return Math.min(parsed, maxLimit);
11
+ }
12
+
6
13
  // GET /memories/trajectories/:id
7
14
  memoriesRouter.get('/trajectories/:id', (req: Request, res: Response) => {
8
15
  const id = Array.isArray(req.params.id) ? req.params.id[0] : req.params.id;
@@ -21,7 +28,7 @@ memoriesRouter.get('/trajectories/:id', (req: Request, res: Response) => {
21
28
 
22
29
  // GET /memories/swarms/:swarmId/trajectories
23
30
  memoriesRouter.get('/swarms/:swarmId/trajectories', (req: Request, res: Response) => {
24
- const limit = Math.min(parseInt(String(req.query.limit ?? '50'), 10), 200);
31
+ const limit = parseBoundedLimit(req.query.limit, 50, 200);
25
32
  const records = getSwarmTrajectories(String(req.params.swarmId), limit);
26
33
  res.json(records);
27
34
  });