neuralbrain 0.0.2 → 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 +1 -1
  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,7 +1,12 @@
1
1
  import { randomUUID } from 'crypto';
2
2
  import { getDb } from '../lib/db';
3
- import { logger } from '../lib/logger';
4
- import { resolveScope } from '../lib/scope';
3
+ import { normalizeUtcIso } from '../lib/recurrence';
4
+ import {
5
+ buildHierarchicalScopeSql,
6
+ classifyMatchTier,
7
+ MatchTier,
8
+ resolveScope,
9
+ } from '../lib/scope';
5
10
  import { redactSecrets } from '../lib/redactSecrets';
6
11
  import { enqueueForEmbedding } from './embedQueueStore';
7
12
  import { transaction } from '../lib/sqlite';
@@ -14,6 +19,8 @@ export interface NoteRecord {
14
19
  id: string;
15
20
  scope: NoteScope;
16
21
  project_id: string | null;
22
+ user_id: string | null;
23
+ agent_id: string | null;
17
24
  session_id: string | null;
18
25
  type: NoteType;
19
26
  title: string;
@@ -23,11 +30,20 @@ export interface NoteRecord {
23
30
  version: number;
24
31
  supersedes: string | null;
25
32
  is_latest: number;
26
- embedding: Buffer | null;
33
+ event_at: string | null;
34
+ valid_from: string | null;
35
+ valid_until: string | null;
27
36
  created_at: number;
28
37
  updated_at: number;
38
+ match_tier?: MatchTier;
29
39
  }
30
40
 
41
+ export const NOTE_COLUMNS =
42
+ 'id, scope, project_id, user_id, agent_id, session_id, type, title, content, author, author_kind, version, supersedes, is_latest, event_at, valid_from, valid_until, created_at, updated_at';
43
+ const NOTE_COLUMNS_ALIASED = NOTE_COLUMNS.split(', ')
44
+ .map((c) => `n.${c}`)
45
+ .join(', ');
46
+
31
47
  export interface NoteWithRelations extends NoteRecord {
32
48
  concepts: string[];
33
49
  files: string[];
@@ -38,6 +54,10 @@ export interface CreateNoteInput {
38
54
  scope: NoteScope;
39
55
  projectId?: string | null;
40
56
  project_id?: string | null;
57
+ userId?: string | null;
58
+ user_id?: string | null;
59
+ agentId?: string | null;
60
+ agent_id?: string | null;
41
61
  sessionId?: string | null;
42
62
  session_id?: string | null;
43
63
  type: NoteType;
@@ -48,6 +68,12 @@ export interface CreateNoteInput {
48
68
  concepts?: string[];
49
69
  files?: string[];
50
70
  supersedes?: string | null;
71
+ eventAt?: string | Date | null;
72
+ event_at?: string | Date | null;
73
+ validFrom?: string | Date | null;
74
+ valid_from?: string | Date | null;
75
+ validUntil?: string | Date | null;
76
+ valid_until?: string | Date | null;
51
77
  createdAt?: number;
52
78
  updatedAt?: number;
53
79
  }
@@ -62,6 +88,16 @@ const VALID_TYPES = new Set<NoteType>([
62
88
  'lesson',
63
89
  ]);
64
90
 
91
+ function optionalString(value: unknown, field: string): string | null {
92
+ if (value === undefined || value === null) return null;
93
+ if (typeof value !== 'string') {
94
+ const err = new Error(`${field} must be a string`);
95
+ (err as any).code = 'SCHEMA_INVALID';
96
+ throw err;
97
+ }
98
+ return value.trim() || null;
99
+ }
100
+
65
101
  export function createNote(input: CreateNoteInput): NoteWithRelations {
66
102
  if (!input.scope) {
67
103
  const err = new Error("Scope is required and must be 'project', 'global', or 'unknown'");
@@ -105,6 +141,24 @@ export function createNote(input: CreateNoteInput): NoteWithRelations {
105
141
  throw err;
106
142
  }
107
143
 
144
+ const userId = optionalString(input.userId !== undefined ? input.userId : input.user_id, 'user_id');
145
+ const agentId = optionalString(
146
+ input.agentId !== undefined ? input.agentId : input.agent_id,
147
+ 'agent_id'
148
+ );
149
+ const eventAt = normalizeUtcIso(
150
+ input.eventAt !== undefined ? input.eventAt : input.event_at,
151
+ 'event_at'
152
+ );
153
+ const validFrom = normalizeUtcIso(
154
+ input.validFrom !== undefined ? input.validFrom : input.valid_from,
155
+ 'valid_from'
156
+ );
157
+ const validUntil = normalizeUtcIso(
158
+ input.validUntil !== undefined ? input.validUntil : input.valid_until,
159
+ 'valid_until'
160
+ );
161
+
108
162
  const db = getDb();
109
163
  const id = input.id?.trim() || `note_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
110
164
  const sessionId = (input.sessionId ?? input.session_id)?.trim() || null;
@@ -139,13 +193,15 @@ export function createNote(input: CreateNoteInput): NoteWithRelations {
139
193
 
140
194
  db.prepare(`
141
195
  INSERT INTO notes (
142
- id, scope, project_id, session_id, type, title, content, author, author_kind,
143
- version, supersedes, is_latest, embedding, created_at, updated_at
144
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, ?, ?)
196
+ id, scope, project_id, user_id, agent_id, session_id, type, title, content, author, author_kind,
197
+ version, supersedes, is_latest, embedding, event_at, valid_from, valid_until, created_at, updated_at
198
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, 1, NULL, ?, ?, ?, ?, ?)
145
199
  `).run(
146
200
  id,
147
201
  scope,
148
202
  projectId,
203
+ userId,
204
+ agentId,
149
205
  sessionId,
150
206
  input.type,
151
207
  sanitizedTitle,
@@ -154,6 +210,9 @@ export function createNote(input: CreateNoteInput): NoteWithRelations {
154
210
  authorKind,
155
211
  version,
156
212
  supersedesId,
213
+ eventAt,
214
+ validFrom,
215
+ validUntil,
157
216
  createdAt,
158
217
  updatedAt
159
218
  );
@@ -187,6 +246,8 @@ export function createNote(input: CreateNoteInput): NoteWithRelations {
187
246
  id,
188
247
  scope,
189
248
  project_id: projectId,
249
+ user_id: userId,
250
+ agent_id: agentId,
190
251
  session_id: sessionId,
191
252
  type: input.type,
192
253
  title: sanitizedTitle,
@@ -196,7 +257,9 @@ export function createNote(input: CreateNoteInput): NoteWithRelations {
196
257
  version,
197
258
  supersedes: supersedesId,
198
259
  is_latest: 1,
199
- embedding: null,
260
+ event_at: eventAt,
261
+ valid_from: validFrom,
262
+ valid_until: validUntil,
200
263
  created_at: createdAt,
201
264
  updated_at: updatedAt,
202
265
  concepts,
@@ -209,7 +272,7 @@ export function createNote(input: CreateNoteInput): NoteWithRelations {
209
272
 
210
273
  export function getNote(id: string): NoteWithRelations | undefined {
211
274
  const db = getDb();
212
- const note = db.prepare('SELECT * FROM notes WHERE id = ?').get(id) as NoteRecord | undefined;
275
+ const note = db.prepare(`SELECT ${NOTE_COLUMNS} FROM notes WHERE id = ?`).get(id) as NoteRecord | undefined;
213
276
  if (!note) return undefined;
214
277
 
215
278
  const conceptRows = db
@@ -226,7 +289,11 @@ export function getNote(id: string): NoteWithRelations | undefined {
226
289
  };
227
290
  }
228
291
 
229
- function attachNoteRelations(notes: NoteRecord[], db: ReturnType<typeof getDb>): NoteWithRelations[] {
292
+ function attachNoteRelations(
293
+ notes: NoteRecord[],
294
+ db: ReturnType<typeof getDb>,
295
+ queryProjectId?: string | null
296
+ ): NoteWithRelations[] {
230
297
  if (notes.length === 0) return [];
231
298
 
232
299
  const noteIds = notes.map((n) => n.id);
@@ -266,38 +333,73 @@ function attachNoteRelations(notes: NoteRecord[], db: ReturnType<typeof getDb>):
266
333
 
267
334
  return notes.map((note) => ({
268
335
  ...note,
336
+ match_tier: classifyMatchTier(note.scope, note.project_id, queryProjectId).match_tier,
269
337
  concepts: conceptsByNote.get(note.id) ?? [],
270
338
  files: filesByNote.get(note.id) ?? [],
271
339
  }));
272
340
  }
273
341
 
274
- export function getNotesByFile(filePath: string, projectId?: string): NoteWithRelations[] {
342
+ export function getNotesByFile(
343
+ filePath: string,
344
+ projectId?: string,
345
+ limit = 50,
346
+ options?: {
347
+ includeAncestors?: boolean;
348
+ includeChildren?: boolean;
349
+ includeGlobal?: boolean;
350
+ userId?: string;
351
+ }
352
+ ): NoteWithRelations[] {
275
353
  const db = getDb();
276
354
  const cleanPath = filePath.trim();
355
+ const boundedLimit = Math.min(Math.max(1, Number.isFinite(limit) ? Math.floor(limit) : 50), 200);
356
+ const cleanProjectId = typeof projectId === 'string' && projectId.trim() ? projectId.trim() : undefined;
277
357
 
278
358
  let query = `
279
- SELECT n.*
359
+ SELECT ${NOTE_COLUMNS_ALIASED}
280
360
  FROM notes n
281
361
  JOIN note_files nf ON n.id = nf.note_id
282
362
  WHERE nf.file_path = ? AND n.is_latest = 1
283
363
  `;
284
364
  const params: unknown[] = [cleanPath];
285
365
 
286
- if (projectId) {
287
- query += ` AND ((n.project_id = ? AND n.scope = 'project') OR n.scope = 'global')`;
288
- params.push(projectId.trim());
366
+ let normalizedQueryProjectId: string | null = null;
367
+ if (cleanProjectId) {
368
+ const scopeSql = buildHierarchicalScopeSql({
369
+ tableAlias: 'n',
370
+ projectId: cleanProjectId,
371
+ includeAncestors: options?.includeAncestors !== false,
372
+ includeChildren: options?.includeChildren === true,
373
+ includeGlobal: options?.includeGlobal !== false,
374
+ userId: options?.userId,
375
+ });
376
+ query += ` AND ${scopeSql.clause}`;
377
+ params.push(...scopeSql.params);
378
+ normalizedQueryProjectId = scopeSql.normalizedProjectId;
379
+ } else {
380
+ if (options?.includeGlobal === false) {
381
+ query += " AND n.scope != 'global'";
382
+ }
383
+ if (typeof options?.userId === 'string' && options.userId.trim() !== '') {
384
+ query += ' AND n.user_id = ?';
385
+ params.push(options.userId.trim());
386
+ }
289
387
  }
290
388
 
291
- query += ` ORDER BY n.updated_at DESC`;
389
+ query += ` ORDER BY n.updated_at DESC LIMIT ?`;
390
+ params.push(boundedLimit);
292
391
 
293
392
  const rows = db.prepare(query).all(...params) as NoteRecord[];
294
- return attachNoteRelations(rows, db);
393
+ return attachNoteRelations(rows, db, normalizedQueryProjectId);
295
394
  }
296
395
 
297
396
  export function listNotes(filters?: {
298
397
  scope?: string;
299
398
  projectId?: string;
399
+ includeAncestors?: boolean;
400
+ includeChildren?: boolean;
300
401
  includeGlobal?: boolean;
402
+ userId?: string;
301
403
  type?: string[];
302
404
  concept?: string;
303
405
  filePath?: string;
@@ -314,18 +416,37 @@ export function listNotes(filters?: {
314
416
  conditions.push('n.is_latest = 1');
315
417
  }
316
418
 
317
- if (filters?.scope) {
318
- conditions.push('n.scope = ?');
319
- params.push(filters.scope);
320
- }
321
-
322
- if (filters?.projectId) {
323
- if (filters.includeGlobal) {
324
- conditions.push("((n.project_id = ? AND n.scope = 'project') OR n.scope = 'global')");
325
- params.push(filters.projectId.trim());
326
- } else {
327
- conditions.push("(n.project_id = ? AND n.scope = 'project')");
328
- params.push(filters.projectId.trim());
419
+ const cleanProjectId =
420
+ typeof filters?.projectId === 'string' && filters.projectId.trim()
421
+ ? filters.projectId.trim()
422
+ : undefined;
423
+ const cleanScope =
424
+ typeof filters?.scope === 'string' && filters.scope.trim() ? filters.scope.trim() : undefined;
425
+
426
+ let normalizedQueryProjectId: string | null = null;
427
+
428
+ if (cleanProjectId || cleanScope) {
429
+ const includeGlobal =
430
+ cleanScope === 'project' && !cleanProjectId ? false : Boolean(filters?.includeGlobal);
431
+ const scopeSql = buildHierarchicalScopeSql({
432
+ tableAlias: 'n',
433
+ scope: cleanScope,
434
+ projectId: cleanProjectId,
435
+ includeAncestors: filters?.includeAncestors !== false,
436
+ includeChildren: filters?.includeChildren === true,
437
+ includeGlobal,
438
+ userId: filters?.userId,
439
+ });
440
+ conditions.push(scopeSql.clause);
441
+ params.push(...scopeSql.params);
442
+ normalizedQueryProjectId = scopeSql.normalizedProjectId;
443
+ } else {
444
+ if (filters?.includeGlobal === false) {
445
+ conditions.push("n.scope != 'global'");
446
+ }
447
+ if (typeof filters?.userId === 'string' && filters.userId.trim() !== '') {
448
+ conditions.push('n.user_id = ?');
449
+ params.push(filters.userId.trim());
329
450
  }
330
451
  }
331
452
 
@@ -352,7 +473,7 @@ export function listNotes(filters?: {
352
473
 
353
474
  const rows = db
354
475
  .prepare(`
355
- SELECT n.*
476
+ SELECT ${NOTE_COLUMNS_ALIASED}
356
477
  FROM notes n
357
478
  ${whereClause}
358
479
  ORDER BY n.updated_at DESC
@@ -360,7 +481,7 @@ export function listNotes(filters?: {
360
481
  `)
361
482
  .all(...params) as NoteRecord[];
362
483
 
363
- return attachNoteRelations(rows, db);
484
+ return attachNoteRelations(rows, db, normalizedQueryProjectId);
364
485
  }
365
486
 
366
487
  export function updateNoteScope(
@@ -3,17 +3,23 @@ import { getDb } from '../lib/db';
3
3
  import { logger } from '../lib/logger';
4
4
  import { enqueueForEmbedding } from './embedQueueStore';
5
5
  import { recordDeadLetter } from './deadLetterStore';
6
- import { resolveScope } from '../lib/scope';
6
+ import { buildHierarchicalScopeSql, resolveScope } from '../lib/scope';
7
+ import { normalizeUtcIso } from '../lib/recurrence';
7
8
  import { redactOptional } from '../lib/redactSecrets';
9
+ import { condenseObservation } from '../lib/condenser';
10
+ import { extractSignalTags } from '../lib/signalTags';
11
+ import { resolveRelativeDates } from '../lib/temporal';
8
12
  import { transaction } from '../lib/sqlite';
9
13
 
10
14
  export type ObservationScope = 'project' | 'global' | 'unknown';
11
- export type ObservationKind = 'tool_call' | 'prompt';
15
+ export type ObservationKind = 'tool_call' | 'prompt' | 'response';
12
16
 
13
17
  export interface ObservationRecord {
14
18
  id: string;
15
19
  scope: ObservationScope;
16
20
  project_id: string | null;
21
+ user_id?: string | null;
22
+ agent_id?: string | null;
17
23
  note_ref: string | null;
18
24
  task_ref: string | null;
19
25
  session_id: string | null;
@@ -23,8 +29,12 @@ export interface ObservationRecord {
23
29
  file_path: string | null;
24
30
  input: string | null;
25
31
  output: string | null;
32
+ condensed_text?: string | null;
33
+ resolved_dates_json?: string | null;
34
+ signal_tags?: string | null;
26
35
  duration_ms: number;
27
36
  failed: number;
37
+ event_at: string | null;
28
38
  created_at: number;
29
39
  archived_at: number | null;
30
40
  }
@@ -43,6 +53,8 @@ interface ValidatedObservation {
43
53
  id: string;
44
54
  scope: ObservationScope;
45
55
  projectId: string | null;
56
+ userId: string | null;
57
+ agentId: string | null;
46
58
  noteRef: string | null;
47
59
  taskRef: string | null;
48
60
  sessionId: string | null;
@@ -54,10 +66,14 @@ interface ValidatedObservation {
54
66
  output: string | null;
55
67
  durationMs: number;
56
68
  failed: number;
69
+ eventAt: string | null;
57
70
  createdAt: number;
58
71
  }
59
72
 
60
- function validateObservationItem(item: unknown, index: number): { valid: true; item: ValidatedObservation } | { valid: false; error: string } {
73
+ function validateObservationItem(
74
+ item: unknown,
75
+ _index: number
76
+ ): { valid: true; item: ValidatedObservation } | { valid: false; error: string } {
61
77
  if (!item || typeof item !== 'object' || Array.isArray(item)) {
62
78
  return { valid: false, error: 'Observation item must be a non-null object' };
63
79
  }
@@ -73,9 +89,12 @@ function validateObservationItem(item: unknown, index: number): { valid: true; i
73
89
  const scope: ObservationScope = scoped.scope;
74
90
  const projectId: string | null = scoped.projectId;
75
91
 
76
- // kind must be 'tool_call' or 'prompt'
77
- if (raw.kind !== 'tool_call' && raw.kind !== 'prompt') {
78
- return { valid: false, error: `Invalid kind '${String(raw.kind)}'. Must be 'tool_call' or 'prompt'` };
92
+ // kind must be 'tool_call', 'prompt', or 'response'
93
+ if (raw.kind !== 'tool_call' && raw.kind !== 'prompt' && raw.kind !== 'response') {
94
+ return {
95
+ valid: false,
96
+ error: `Invalid kind '${String(raw.kind)}'. Must be 'tool_call', 'prompt', or 'response'`,
97
+ };
79
98
  }
80
99
  const kind = raw.kind as ObservationKind;
81
100
 
@@ -111,6 +130,8 @@ function validateObservationItem(item: unknown, index: number): { valid: true; i
111
130
  typeof val === 'string' && val.trim() !== '' ? val.trim() : null;
112
131
 
113
132
  // Optional string fields
133
+ const userId = toCleanString(raw.user_id ?? raw.userId);
134
+ const agentId = toCleanString(raw.agent_id ?? raw.agentId);
114
135
  const noteRef = toCleanString(raw.note_ref ?? raw.noteRef);
115
136
  const taskRef = toCleanString(raw.task_ref ?? raw.taskRef);
116
137
  const sessionId = toCleanString(raw.session_id ?? raw.sessionId);
@@ -122,6 +143,31 @@ function validateObservationItem(item: unknown, index: number): { valid: true; i
122
143
  const input = raw.input !== undefined && raw.input !== null ? redactOptional(String(raw.input)) : null;
123
144
  const output = raw.output !== undefined && raw.output !== null ? redactOptional(String(raw.output)) : null;
124
145
 
146
+ // event_at: optional ISO-8601 string (or Date) or finite numeric Unix epoch seconds
147
+ let eventAt: string | null = null;
148
+ const rawEventAt = raw.event_at !== undefined ? raw.event_at : raw.eventAt;
149
+ if (rawEventAt !== undefined && rawEventAt !== null) {
150
+ if (typeof rawEventAt === 'number') {
151
+ if (!Number.isFinite(rawEventAt)) {
152
+ return { valid: false, error: 'event_at must be a finite Unix epoch timestamp in seconds' };
153
+ }
154
+ const d = new Date(rawEventAt * 1000);
155
+ if (Number.isNaN(d.getTime())) {
156
+ return { valid: false, error: `event_at '${String(rawEventAt)}' is out of valid date range` };
157
+ }
158
+ eventAt = d.toISOString();
159
+ } else {
160
+ try {
161
+ eventAt = normalizeUtcIso(rawEventAt, 'event_at');
162
+ } catch (err) {
163
+ return {
164
+ valid: false,
165
+ error: err instanceof Error ? err.message : String(err),
166
+ };
167
+ }
168
+ }
169
+ }
170
+
125
171
  const rawCreatedAt = raw.created_at ?? raw.createdAt;
126
172
  const createdAt = typeof rawCreatedAt === 'number' && Number.isFinite(rawCreatedAt)
127
173
  ? Math.floor(rawCreatedAt)
@@ -133,6 +179,8 @@ function validateObservationItem(item: unknown, index: number): { valid: true; i
133
179
  id,
134
180
  scope,
135
181
  projectId,
182
+ userId,
183
+ agentId,
136
184
  noteRef,
137
185
  taskRef,
138
186
  sessionId,
@@ -144,6 +192,7 @@ function validateObservationItem(item: unknown, index: number): { valid: true; i
144
192
  output,
145
193
  durationMs,
146
194
  failed,
195
+ eventAt,
147
196
  createdAt,
148
197
  },
149
198
  };
@@ -181,10 +230,10 @@ export function captureObservations(rawItems: unknown[]): CaptureResult {
181
230
  const db = getDb();
182
231
  const insertStmt = db.prepare(`
183
232
  INSERT INTO observations (
184
- id, scope, project_id, note_ref, task_ref, session_id, agent,
185
- kind, tool_name, file_path, input, output, duration_ms, failed,
186
- created_at
187
- ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
233
+ id, scope, project_id, user_id, agent_id, note_ref, task_ref, session_id, agent,
234
+ kind, tool_name, file_path, input, output, condensed_text, resolved_dates_json, signal_tags,
235
+ duration_ms, failed, event_at, created_at
236
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
188
237
  `);
189
238
 
190
239
  const reactivateSessionStmt = db.prepare(`
@@ -198,10 +247,42 @@ export function captureObservations(rawItems: unknown[]): CaptureResult {
198
247
  // If insertSingle throws, its savepoint is rolled back without aborting the outer transaction.
199
248
  const insertSingle = transaction(db, (entry: { item: ValidatedObservation; index: number; raw: unknown }) => {
200
249
  const item = entry.item;
250
+ const anchorIso = item.eventAt ?? new Date(item.createdAt * 1000).toISOString();
251
+ const inputTemporal = item.input ? resolveRelativeDates(item.input, anchorIso) : null;
252
+ const outputTemporal = item.output ? resolveRelativeDates(item.output, anchorIso) : null;
253
+
254
+ const combinedResolved = [
255
+ ...(inputTemporal
256
+ ? inputTemporal.resolved.map((ann) => ({ field: 'input' as const, ...ann }))
257
+ : []),
258
+ ...(outputTemporal
259
+ ? outputTemporal.resolved.map((ann) => ({ field: 'output' as const, ...ann }))
260
+ : []),
261
+ ];
262
+ const resolvedDatesJson =
263
+ combinedResolved.length > 0 ? JSON.stringify(combinedResolved) : null;
264
+
265
+ // Raw item.input and item.output stay 100% verbatim in SQLite;
266
+ // inline [YYYY-MM-DD] annotations feed additive condensed_text.
267
+ const condensedText = condenseObservation({
268
+ kind: item.kind,
269
+ toolName: item.toolName,
270
+ filePath: item.filePath,
271
+ input: inputTemporal ? inputTemporal.annotatedText : item.input,
272
+ output: outputTemporal ? outputTemporal.annotatedText : item.output,
273
+ });
274
+ const tags = extractSignalTags({
275
+ kind: item.kind,
276
+ input: item.input,
277
+ output: item.output,
278
+ });
279
+ const signalTagsJson = tags.length > 0 ? JSON.stringify(tags) : null;
201
280
  insertStmt.run(
202
281
  item.id,
203
282
  item.scope,
204
283
  item.projectId,
284
+ item.userId,
285
+ item.agentId,
205
286
  item.noteRef,
206
287
  item.taskRef,
207
288
  item.sessionId,
@@ -211,8 +292,12 @@ export function captureObservations(rawItems: unknown[]): CaptureResult {
211
292
  item.filePath,
212
293
  item.input,
213
294
  item.output,
295
+ condensedText,
296
+ resolvedDatesJson,
297
+ signalTagsJson,
214
298
  item.durationMs,
215
299
  item.failed,
300
+ item.eventAt,
216
301
  item.createdAt
217
302
  );
218
303
  if (item.sessionId) {
@@ -263,6 +348,10 @@ export function listObservations(filters?: {
263
348
  scope?: string;
264
349
  sessionId?: string;
265
350
  failed?: number;
351
+ includeAncestors?: boolean;
352
+ includeChildren?: boolean;
353
+ includeGlobal?: boolean;
354
+ userId?: string;
266
355
  limit?: number;
267
356
  offset?: number;
268
357
  }): ObservationRecord[] {
@@ -270,14 +359,25 @@ export function listObservations(filters?: {
270
359
  const conditions: string[] = [];
271
360
  const queryParams: unknown[] = [];
272
361
 
273
- if (filters?.projectId) {
274
- conditions.push('project_id = ?');
275
- queryParams.push(filters.projectId);
276
- }
277
- if (filters?.scope) {
278
- conditions.push('scope = ?');
279
- queryParams.push(filters.scope);
362
+ const hasProjectId = typeof filters?.projectId === 'string' && filters.projectId.trim() !== '';
363
+ const hasScope = typeof filters?.scope === 'string' && filters.scope.trim() !== '';
364
+
365
+ if (hasProjectId || hasScope) {
366
+ const scopeSql = buildHierarchicalScopeSql({
367
+ scope: hasScope ? filters!.scope : undefined,
368
+ projectId: hasProjectId ? filters!.projectId : undefined,
369
+ includeAncestors: filters?.includeAncestors ?? true,
370
+ includeChildren: filters?.includeChildren ?? false,
371
+ includeGlobal: filters?.includeGlobal ?? false,
372
+ userId: filters?.userId,
373
+ });
374
+ conditions.push(scopeSql.clause);
375
+ queryParams.push(...scopeSql.params);
376
+ } else if (typeof filters?.userId === 'string' && filters.userId.trim() !== '') {
377
+ conditions.push('user_id = ?');
378
+ queryParams.push(filters.userId.trim());
280
379
  }
380
+
281
381
  if (filters?.sessionId) {
282
382
  conditions.push('session_id = ?');
283
383
  queryParams.push(filters.sessionId);
@@ -1,6 +1,6 @@
1
1
  import { getDb } from '../lib/db';
2
2
  import { logger } from '../lib/logger';
3
- import { normalizeProjectId } from '../lib/scope';
3
+ import { getProjectAncestors, normalizeProjectId } from '../lib/scope';
4
4
  import { getQdrantClient } from '../learning/embedWorker';
5
5
  import { getStoreMeta } from '../learning/storeMeta';
6
6
  import { transaction } from '../lib/sqlite';
@@ -22,6 +22,7 @@ const STANDARD_PROJECT_TABLES = [
22
22
  'observations_archive',
23
23
  'sessions',
24
24
  'actions',
25
+ 'entities',
25
26
  'summaries',
26
27
  'consolidation_leases',
27
28
  ] as const;
@@ -115,7 +116,10 @@ export async function renameProject(
115
116
  const collection = getStoreMeta()?.qdrant_alias || 'brain';
116
117
  try {
117
118
  await qdrant.setPayload(collection, {
118
- payload: { project_id: toId },
119
+ payload: {
120
+ project_id: toId,
121
+ project_ancestors: getProjectAncestors(toId),
122
+ },
119
123
  filter: {
120
124
  must: [{ key: 'project_id', match: { value: fromId } }],
121
125
  },