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,4 +1,35 @@
1
+ import { randomUUID } from 'crypto';
1
2
  import { getDb } from '../lib/db';
3
+ import { redactOptional, redactSecrets } from '../lib/redactSecrets';
4
+ import {
5
+ buildHierarchicalScopeSql,
6
+ classifyMatchTier,
7
+ MatchTier,
8
+ normalizeProjectId,
9
+ resolveScope,
10
+ ScopeValue,
11
+ } from '../lib/scope';
12
+ import { Database, transaction } from '../lib/sqlite';
13
+ import { enqueueForEmbedding } from './embedQueueStore';
14
+
15
+ export const STANDARD_ENTITY_TYPES = [
16
+ 'brand',
17
+ 'person',
18
+ 'asset',
19
+ 'metric',
20
+ 'document',
21
+ 'tool',
22
+ ] as const;
23
+
24
+ export const STANDARD_EDGE_RELATIONS = [
25
+ 'part_of',
26
+ 'depends_on',
27
+ 'references',
28
+ 'owns',
29
+ 'produced_by',
30
+ 'blocks',
31
+ 'related_to',
32
+ ] as const;
2
33
 
3
34
  export type GraphNodeType =
4
35
  | 'note'
@@ -7,14 +38,18 @@ export type GraphNodeType =
7
38
  | 'file'
8
39
  | 'session'
9
40
  | 'action'
10
- | 'summary';
41
+ | 'summary'
42
+ | 'observation'
43
+ | 'entity'
44
+ | 'trajectory';
11
45
 
12
- export type GraphEdgeType =
13
- | 'has_concept'
14
- | 'touches_file'
15
- | 'supersedes'
16
- | 'from_session'
17
- | 'cites_source';
46
+ /**
47
+ * Edge relation type. Includes standard structural relations
48
+ * ('has_concept' | 'touches_file' | 'supersedes' | 'from_session' | 'cites_source'),
49
+ * standard entity relations ('part_of' | 'depends_on' | 'references' | 'owns' | 'produced_by' | 'blocks' | 'related_to'),
50
+ * and custom domain-agnostic relation strings.
51
+ */
52
+ export type GraphEdgeType = string;
18
53
 
19
54
  export interface GraphNode {
20
55
  id: string;
@@ -22,6 +57,11 @@ export interface GraphNode {
22
57
  label: string;
23
58
  scope?: string | null;
24
59
  project_id?: string | null;
60
+ entity_type?: string | null;
61
+ external_ref?: string | null;
62
+ match_tier?: MatchTier;
63
+ user_id?: string | null;
64
+ agent_id?: string | null;
25
65
  meta?: Record<string, unknown>;
26
66
  }
27
67
 
@@ -29,6 +69,7 @@ export interface GraphEdge {
29
69
  source: string;
30
70
  target: string;
31
71
  type: GraphEdgeType;
72
+ meta?: Record<string, unknown>;
32
73
  }
33
74
 
34
75
  export interface KnowledgeGraph {
@@ -43,27 +84,589 @@ export interface KnowledgeGraph {
43
84
  export interface KnowledgeGraphOptions {
44
85
  projectId?: string;
45
86
  scope?: string;
87
+ includeAncestors?: boolean;
88
+ includeChildren?: boolean;
89
+ includeGlobal?: boolean;
90
+ depth?: number;
91
+ nodeId?: string;
92
+ entityType?: string;
93
+ relation?: string;
94
+ userId?: string;
46
95
  limit?: number;
47
96
  }
48
97
 
49
- function clampLimit(raw?: number): number {
98
+ export interface EntityRecord {
99
+ id: string;
100
+ scope: ScopeValue;
101
+ project_id: string | null;
102
+ user_id: string | null;
103
+ agent_id: string | null;
104
+ entity_type: string;
105
+ name: string;
106
+ description: string | null;
107
+ external_ref: string | null;
108
+ metadata_json: string | null;
109
+ created_at: number;
110
+ updated_at: number;
111
+ }
112
+
113
+ export interface UpsertEntityInput {
114
+ id?: string;
115
+ scope?: ScopeValue | string;
116
+ project_id?: string | null;
117
+ projectId?: string | null;
118
+ user_id?: string | null;
119
+ userId?: string | null;
120
+ agent_id?: string | null;
121
+ agentId?: string | null;
122
+ entity_type?: string;
123
+ entityType?: string;
124
+ name: string;
125
+ description?: string | null;
126
+ external_ref?: string | null;
127
+ externalRef?: string | null;
128
+ metadata?: Record<string, unknown> | string | null;
129
+ metadata_json?: string | null;
130
+ metadataJson?: string | null;
131
+ }
132
+
133
+ export interface ListEntitiesFilters {
134
+ projectId?: string;
135
+ scope?: string;
136
+ includeAncestors?: boolean;
137
+ includeChildren?: boolean;
138
+ includeGlobal?: boolean;
139
+ entityType?: string;
140
+ externalRef?: string;
141
+ userId?: string;
142
+ limit?: number;
143
+ }
144
+
145
+ export interface EntityEdgeRecord {
146
+ id: string;
147
+ source_type: string;
148
+ source_id: string;
149
+ target_type: string;
150
+ target_id: string;
151
+ relation: string;
152
+ metadata_json: string | null;
153
+ created_at: number;
154
+ }
155
+
156
+ export interface LinkEntitiesInput {
157
+ source_type?: string;
158
+ sourceType?: string;
159
+ source_id?: string;
160
+ sourceId?: string;
161
+ target_type?: string;
162
+ targetType?: string;
163
+ target_id?: string;
164
+ targetId?: string;
165
+ relation: string;
166
+ metadata?: Record<string, unknown> | string | null;
167
+ metadata_json?: string | null;
168
+ metadataJson?: string | null;
169
+ }
170
+
171
+ export interface UnlinkEntitiesInput {
172
+ id?: string;
173
+ source_id?: string;
174
+ sourceId?: string;
175
+ target_id?: string;
176
+ targetId?: string;
177
+ relation?: string;
178
+ }
179
+
180
+ const ENTITY_COLUMNS =
181
+ 'id, scope, project_id, user_id, agent_id, entity_type, name, description, external_ref, metadata_json, created_at, updated_at';
182
+
183
+ const KNOWN_NODE_TABLES: Record<string, string> = {
184
+ entity: 'entities',
185
+ note: 'notes',
186
+ lesson: 'notes',
187
+ action: 'actions',
188
+ session: 'sessions',
189
+ summary: 'summaries',
190
+ trajectory: 'trajectories',
191
+ observation: 'observations',
192
+ };
193
+
194
+ const SYNTHETIC_EDGE_TYPES = new Set([
195
+ 'has_concept',
196
+ 'touches_file',
197
+ 'supersedes',
198
+ 'from_session',
199
+ 'cites_source',
200
+ ]);
201
+
202
+ function makeError(code: string, message: string): Error {
203
+ const err = new Error(message);
204
+ (err as { code?: string }).code = code;
205
+ return err;
206
+ }
207
+
208
+ function optionalString(value: unknown, field: string): string | null {
209
+ if (value === undefined || value === null) return null;
210
+ if (typeof value !== 'string') {
211
+ throw makeError('SCHEMA_INVALID', `${field} must be a string`);
212
+ }
213
+ const trimmed = value.trim();
214
+ return trimmed === '' ? null : trimmed;
215
+ }
216
+
217
+ function serializeMetadata(input: {
218
+ metadata?: Record<string, unknown> | string | null;
219
+ metadata_json?: string | null;
220
+ metadataJson?: string | null;
221
+ }): string | null {
222
+ const rawJson = input.metadata_json !== undefined ? input.metadata_json : input.metadataJson;
223
+ if (rawJson !== undefined) {
224
+ return redactOptional(optionalString(rawJson, 'metadata_json'));
225
+ }
226
+ if (input.metadata === undefined || input.metadata === null) {
227
+ return null;
228
+ }
229
+ if (typeof input.metadata === 'string') {
230
+ return redactOptional(optionalString(input.metadata, 'metadata'));
231
+ }
232
+ if (typeof input.metadata === 'object' && !Array.isArray(input.metadata)) {
233
+ return redactSecrets(JSON.stringify(input.metadata));
234
+ }
235
+ throw makeError('SCHEMA_INVALID', 'metadata must be an object, JSON string, or null');
236
+ }
237
+
238
+ function tryParseJson(raw: string | null | undefined): Record<string, unknown> | undefined {
239
+ if (!raw) return undefined;
240
+ try {
241
+ const parsed = JSON.parse(raw);
242
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
243
+ return parsed as Record<string, unknown>;
244
+ }
245
+ return { value: parsed };
246
+ } catch {
247
+ return { raw };
248
+ }
249
+ }
250
+
251
+ function clampLimit(raw?: number, defaultLimit = 80, maxLimit = 200): number {
50
252
  if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) {
51
- return 80;
253
+ return defaultLimit;
254
+ }
255
+ return Math.min(Math.floor(raw), maxLimit);
256
+ }
257
+
258
+ function clampDepth(raw: unknown): number {
259
+ if (raw === undefined || raw === null || raw === '') return 1;
260
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
261
+ if (!Number.isFinite(n)) return 1;
262
+ return Math.min(3, Math.max(1, Math.floor(n)));
263
+ }
264
+
265
+ function parseOptionalBool(value: unknown): boolean | undefined {
266
+ if (typeof value === 'boolean') return value;
267
+ if (typeof value === 'string') {
268
+ const norm = value.trim().toLowerCase();
269
+ if (norm === 'true' || norm === '1') return true;
270
+ if (norm === 'false' || norm === '0') return false;
271
+ }
272
+ return undefined;
273
+ }
274
+
275
+ /**
276
+ * Create or update a persistent entity node with explicit Rule 4 scope,
277
+ * secret redaction, deduplication on (scope/project_id, entity_type, lower(name)),
278
+ * and atomic embed_queue enqueueing. Never returns the embedding BLOB.
279
+ */
280
+ export function upsertEntity(input: UpsertEntityInput): EntityRecord {
281
+ const scoped = resolveScope(input.scope, input.projectId ?? input.project_id);
282
+ if (!scoped.ok) {
283
+ throw makeError('SCHEMA_INVALID', scoped.error);
284
+ }
285
+
286
+ const rawEntityType = input.entity_type !== undefined ? input.entity_type : input.entityType;
287
+ const entityType = optionalString(rawEntityType, 'entity_type');
288
+ if (!entityType) {
289
+ throw makeError('SCHEMA_INVALID', 'entity_type is required and cannot be empty');
290
+ }
291
+
292
+ const rawName = optionalString(input.name, 'name');
293
+ if (!rawName) {
294
+ throw makeError('SCHEMA_INVALID', 'name is required and cannot be empty');
295
+ }
296
+ const name = redactSecrets(rawName);
297
+
298
+ const description = redactOptional(optionalString(input.description, 'description'));
299
+ const rawExternalRef =
300
+ input.external_ref !== undefined ? input.external_ref : input.externalRef;
301
+ const externalRef = redactOptional(optionalString(rawExternalRef, 'external_ref'));
302
+ const metadataJson = serializeMetadata(input);
303
+ const userId = optionalString(
304
+ input.user_id !== undefined ? input.user_id : input.userId,
305
+ 'user_id'
306
+ );
307
+ const agentId = optionalString(
308
+ input.agent_id !== undefined ? input.agent_id : input.agentId,
309
+ 'agent_id'
310
+ );
311
+ const providedId = optionalString(input.id, 'id');
312
+
313
+ const db = getDb();
314
+ const dedupScopeKey = scoped.projectId ?? `__SCOPE__:${scoped.scope}`;
315
+
316
+ return transaction(db, () => {
317
+ let existing: EntityRecord | undefined;
318
+ if (providedId) {
319
+ existing = db
320
+ .prepare(`SELECT ${ENTITY_COLUMNS} FROM entities WHERE id = ?`)
321
+ .get(providedId) as EntityRecord | undefined;
322
+ }
323
+ if (!existing) {
324
+ existing = db
325
+ .prepare(
326
+ `
327
+ SELECT ${ENTITY_COLUMNS}
328
+ FROM entities
329
+ WHERE COALESCE(project_id, '__SCOPE__:' || scope) = ?
330
+ AND entity_type = ?
331
+ AND lower(name) = lower(?)
332
+ LIMIT 1
333
+ `
334
+ )
335
+ .get(dedupScopeKey, entityType, name) as EntityRecord | undefined;
336
+ }
337
+
338
+ let entityId: string;
339
+ if (existing) {
340
+ entityId = existing.id;
341
+ db.prepare(
342
+ `
343
+ UPDATE entities
344
+ SET scope = ?,
345
+ project_id = ?,
346
+ entity_type = ?,
347
+ name = ?,
348
+ description = COALESCE(?, description),
349
+ external_ref = COALESCE(?, external_ref),
350
+ metadata_json = COALESCE(?, metadata_json),
351
+ user_id = COALESCE(?, user_id),
352
+ agent_id = COALESCE(?, agent_id),
353
+ updated_at = unixepoch()
354
+ WHERE id = ?
355
+ `
356
+ ).run(
357
+ scoped.scope,
358
+ scoped.projectId,
359
+ entityType,
360
+ name,
361
+ description,
362
+ externalRef,
363
+ metadataJson,
364
+ userId,
365
+ agentId,
366
+ entityId
367
+ );
368
+ } else {
369
+ entityId = providedId || `ent_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
370
+ db.prepare(
371
+ `
372
+ INSERT INTO entities (
373
+ id, scope, project_id, user_id, agent_id, entity_type, name,
374
+ description, external_ref, metadata_json, embedding
375
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
376
+ `
377
+ ).run(
378
+ entityId,
379
+ scoped.scope,
380
+ scoped.projectId,
381
+ userId,
382
+ agentId,
383
+ entityType,
384
+ name,
385
+ description,
386
+ externalRef,
387
+ metadataJson
388
+ );
389
+ }
390
+
391
+ enqueueForEmbedding(entityId, 'entity');
392
+ return db
393
+ .prepare(`SELECT ${ENTITY_COLUMNS} FROM entities WHERE id = ?`)
394
+ .get(entityId) as EntityRecord;
395
+ })();
396
+ }
397
+
398
+ /**
399
+ * Retrieve an entity by ID without returning its embedding BLOB.
400
+ */
401
+ export function getEntity(id: string): EntityRecord | undefined {
402
+ const db = getDb();
403
+ return db
404
+ .prepare(`SELECT ${ENTITY_COLUMNS} FROM entities WHERE id = ?`)
405
+ .get(id) as EntityRecord | undefined;
406
+ }
407
+
408
+ /**
409
+ * List entities with optional hierarchical project scoping, user filtering,
410
+ * entity_type, and external_ref filters. Never filters on agent_id.
411
+ */
412
+ export function listEntities(
413
+ filters?: ListEntitiesFilters
414
+ ): Array<EntityRecord & { match_tier?: MatchTier }> {
415
+ const db = getDb();
416
+ const conditions: string[] = [];
417
+ const params: unknown[] = [];
418
+
419
+ const hasProjectId = typeof filters?.projectId === 'string' && filters.projectId.trim() !== '';
420
+ const hasScope = typeof filters?.scope === 'string' && filters.scope.trim() !== '';
421
+ let normalizedQueryProjectId: string | null = null;
422
+
423
+ if (hasProjectId || hasScope) {
424
+ const scopeSql = buildHierarchicalScopeSql({
425
+ scope: hasScope ? filters!.scope : undefined,
426
+ projectId: hasProjectId ? filters!.projectId : undefined,
427
+ includeAncestors: filters?.includeAncestors ?? true,
428
+ includeChildren: filters?.includeChildren ?? false,
429
+ includeGlobal: filters?.includeGlobal ?? (hasProjectId ? true : false),
430
+ userId: filters?.userId,
431
+ });
432
+ conditions.push(scopeSql.clause);
433
+ params.push(...scopeSql.params);
434
+ normalizedQueryProjectId = scopeSql.normalizedProjectId;
435
+ } else {
436
+ if (filters?.includeGlobal === false) {
437
+ conditions.push("scope != 'global'");
438
+ }
439
+ if (typeof filters?.userId === 'string' && filters.userId.trim() !== '') {
440
+ conditions.push('user_id = ?');
441
+ params.push(filters.userId.trim());
442
+ }
443
+ }
444
+
445
+ if (typeof filters?.entityType === 'string' && filters.entityType.trim() !== '') {
446
+ conditions.push('entity_type = ?');
447
+ params.push(filters.entityType.trim());
448
+ }
449
+
450
+ if (typeof filters?.externalRef === 'string' && filters.externalRef.trim() !== '') {
451
+ conditions.push('external_ref = ?');
452
+ params.push(filters.externalRef.trim());
453
+ }
454
+
455
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
456
+ const limit = clampLimit(filters?.limit, 50, 200);
457
+ params.push(limit);
458
+
459
+ const rows = db
460
+ .prepare(
461
+ `
462
+ SELECT ${ENTITY_COLUMNS}
463
+ FROM entities
464
+ ${whereClause}
465
+ ORDER BY updated_at DESC, created_at DESC, rowid DESC
466
+ LIMIT ?
467
+ `
468
+ )
469
+ .all(...params) as EntityRecord[];
470
+
471
+ return rows.map((row) => ({
472
+ ...row,
473
+ match_tier: classifyMatchTier(row.scope, row.project_id, normalizedQueryProjectId).match_tier,
474
+ }));
475
+ }
476
+
477
+ function resolveNodeType(db: Database, id: string): string | null {
478
+ if (db.prepare('SELECT 1 FROM entities WHERE id = ?').get(id)) return 'entity';
479
+ const noteRow = db.prepare('SELECT type FROM notes WHERE id = ?').get(id) as
480
+ | { type: string }
481
+ | undefined;
482
+ if (noteRow) return noteRow.type === 'lesson' ? 'lesson' : 'note';
483
+ if (db.prepare('SELECT 1 FROM actions WHERE id = ?').get(id)) return 'action';
484
+ if (db.prepare('SELECT 1 FROM sessions WHERE id = ?').get(id)) return 'session';
485
+ if (db.prepare('SELECT 1 FROM summaries WHERE id = ?').get(id)) return 'summary';
486
+ if (db.prepare('SELECT 1 FROM trajectories WHERE id = ?').get(id)) return 'trajectory';
487
+ if (db.prepare('SELECT 1 FROM observations WHERE id = ?').get(id)) return 'observation';
488
+ return null;
489
+ }
490
+
491
+ function resolveAndValidateEndpoint(
492
+ db: Database,
493
+ explicitType: string | null,
494
+ id: string,
495
+ role: 'source' | 'target'
496
+ ): string {
497
+ if (!explicitType) {
498
+ const resolved = resolveNodeType(db, id);
499
+ if (!resolved) {
500
+ throw makeError('NOT_FOUND', `${role} record '${id}' not found`);
501
+ }
502
+ return resolved;
503
+ }
504
+
505
+ const knownTable = KNOWN_NODE_TABLES[explicitType];
506
+ if (knownTable) {
507
+ const exists = db.prepare(`SELECT 1 FROM ${knownTable} WHERE id = ?`).get(id);
508
+ if (!exists) {
509
+ throw makeError('NOT_FOUND', `${role} ${explicitType} '${id}' not found`);
510
+ }
511
+ }
512
+ return explicitType;
513
+ }
514
+
515
+ /**
516
+ * Create or update a directed relational edge between any two graph nodes
517
+ * (including cross-subproject links). Auto-resolves source_type/target_type
518
+ * when omitted and verifies internal endpoints exist.
519
+ */
520
+ export function linkEntities(input: LinkEntitiesInput): EntityEdgeRecord {
521
+ const sourceId = optionalString(
522
+ input.source_id !== undefined ? input.source_id : input.sourceId,
523
+ 'source_id'
524
+ );
525
+ if (!sourceId) {
526
+ throw makeError('SCHEMA_INVALID', 'source_id is required and cannot be empty');
527
+ }
528
+
529
+ const targetId = optionalString(
530
+ input.target_id !== undefined ? input.target_id : input.targetId,
531
+ 'target_id'
532
+ );
533
+ if (!targetId) {
534
+ throw makeError('SCHEMA_INVALID', 'target_id is required and cannot be empty');
52
535
  }
53
- return Math.min(Math.floor(raw), 200);
536
+
537
+ const relation = optionalString(input.relation, 'relation');
538
+ if (!relation) {
539
+ throw makeError('SCHEMA_INVALID', 'relation is required and cannot be empty');
540
+ }
541
+
542
+ const explicitSourceType = optionalString(
543
+ input.source_type !== undefined ? input.source_type : input.sourceType,
544
+ 'source_type'
545
+ );
546
+ const explicitTargetType = optionalString(
547
+ input.target_type !== undefined ? input.target_type : input.targetType,
548
+ 'target_type'
549
+ );
550
+ const metadataJson = serializeMetadata(input);
551
+
552
+ const db = getDb();
553
+ return transaction(db, () => {
554
+ const sourceType = resolveAndValidateEndpoint(db, explicitSourceType, sourceId, 'source');
555
+ const targetType = resolveAndValidateEndpoint(db, explicitTargetType, targetId, 'target');
556
+ const id = `edge_${randomUUID().replace(/-/g, '').slice(0, 16)}`;
557
+
558
+ db.prepare(
559
+ `
560
+ INSERT INTO entity_edges (
561
+ id, source_type, source_id, target_type, target_id, relation, metadata_json
562
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
563
+ ON CONFLICT(source_type, source_id, target_type, target_id, relation) DO UPDATE SET
564
+ metadata_json = COALESCE(excluded.metadata_json, entity_edges.metadata_json)
565
+ `
566
+ ).run(id, sourceType, sourceId, targetType, targetId, relation, metadataJson);
567
+
568
+ return db
569
+ .prepare(
570
+ `
571
+ SELECT id, source_type, source_id, target_type, target_id, relation, metadata_json, created_at
572
+ FROM entity_edges
573
+ WHERE source_type = ? AND source_id = ? AND target_type = ? AND target_id = ? AND relation = ?
574
+ `
575
+ )
576
+ .get(sourceType, sourceId, targetType, targetId, relation) as EntityEdgeRecord;
577
+ })();
578
+ }
579
+
580
+ /**
581
+ * Remove matching edges from entity_edges by edge id, source_id, and/or target_id
582
+ * (optionally narrowed by relation).
583
+ */
584
+ export function unlinkEntities(input: UnlinkEntitiesInput): { deleted: number } {
585
+ const id = optionalString(input.id, 'id');
586
+ const sourceId = optionalString(
587
+ input.source_id !== undefined ? input.source_id : input.sourceId,
588
+ 'source_id'
589
+ );
590
+ const targetId = optionalString(
591
+ input.target_id !== undefined ? input.target_id : input.targetId,
592
+ 'target_id'
593
+ );
594
+ const relation = optionalString(input.relation, 'relation');
595
+
596
+ if (!id && !sourceId && !targetId) {
597
+ throw makeError(
598
+ 'SCHEMA_INVALID',
599
+ 'At least one of id, source_id, or target_id is required to unlink edges'
600
+ );
601
+ }
602
+
603
+ const conditions: string[] = [];
604
+ const params: unknown[] = [];
605
+
606
+ if (id) {
607
+ conditions.push('id = ?');
608
+ params.push(id);
609
+ }
610
+ if (sourceId) {
611
+ conditions.push('source_id = ?');
612
+ params.push(sourceId);
613
+ }
614
+ if (targetId) {
615
+ conditions.push('target_id = ?');
616
+ params.push(targetId);
617
+ }
618
+ if (relation) {
619
+ conditions.push('relation = ?');
620
+ params.push(relation);
621
+ }
622
+
623
+ const db = getDb();
624
+ const res = db
625
+ .prepare(`DELETE FROM entity_edges WHERE ${conditions.join(' AND ')}`)
626
+ .run(...params);
627
+ return { deleted: res.changes };
54
628
  }
55
629
 
56
630
  /**
57
631
  * Parse and bound HTTP query parameters for knowledge graph endpoints.
58
632
  */
59
633
  export function parseGraphQuery(query: Record<string, unknown>): KnowledgeGraphOptions {
634
+ const rawProjectId = query.project_id ?? query.projectId;
60
635
  const projectId =
61
- typeof query.project_id === 'string'
62
- ? query.project_id
63
- : typeof query.projectId === 'string'
64
- ? query.projectId
65
- : undefined;
66
- const scope = typeof query.scope === 'string' ? query.scope : undefined;
636
+ typeof rawProjectId === 'string' && rawProjectId.trim() !== ''
637
+ ? rawProjectId.trim()
638
+ : undefined;
639
+ const scope =
640
+ typeof query.scope === 'string' && query.scope.trim() !== ''
641
+ ? query.scope.trim()
642
+ : undefined;
643
+
644
+ const includeAncestors =
645
+ parseOptionalBool(query.include_ancestors ?? query.includeAncestors) ?? true;
646
+ const includeChildren =
647
+ parseOptionalBool(query.include_children ?? query.includeChildren) ?? false;
648
+ const includeGlobal =
649
+ parseOptionalBool(query.include_global ?? query.includeGlobal) ?? false;
650
+
651
+ const rawNodeId = query.node_id ?? query.nodeId;
652
+ const nodeId =
653
+ typeof rawNodeId === 'string' && rawNodeId.trim() !== '' ? rawNodeId.trim() : undefined;
654
+
655
+ const rawEntityType = query.entity_type ?? query.entityType;
656
+ const entityType =
657
+ typeof rawEntityType === 'string' && rawEntityType.trim() !== ''
658
+ ? rawEntityType.trim()
659
+ : undefined;
660
+
661
+ const relation =
662
+ typeof query.relation === 'string' && query.relation.trim() !== ''
663
+ ? query.relation.trim()
664
+ : undefined;
665
+
666
+ const rawUserId = query.user_id ?? query.userId;
667
+ const userId =
668
+ typeof rawUserId === 'string' && rawUserId.trim() !== '' ? rawUserId.trim() : undefined;
669
+
67
670
  const rawLimit = query.limit;
68
671
  const parsedLimit =
69
672
  rawLimit !== undefined && rawLimit !== null && rawLimit !== ''
@@ -73,267 +676,845 @@ export function parseGraphQuery(query: Record<string, unknown>): KnowledgeGraphO
73
676
  return {
74
677
  projectId,
75
678
  scope,
679
+ includeAncestors,
680
+ includeChildren,
681
+ includeGlobal,
682
+ depth: clampDepth(query.depth),
683
+ nodeId,
684
+ entityType,
685
+ relation,
686
+ userId,
76
687
  limit: clampLimit(parsedLimit),
77
688
  };
78
689
  }
79
690
 
80
- function buildScopeFilter(
81
- projectId?: string,
82
- scope?: string
83
- ): { where: string; params: unknown[] } {
84
- const conditions: string[] = [];
85
- const params: unknown[] = [];
691
+ interface NoteSeedRow {
692
+ id: string;
693
+ scope: string;
694
+ project_id: string | null;
695
+ user_id: string | null;
696
+ agent_id: string | null;
697
+ session_id: string | null;
698
+ type: string;
699
+ title: string;
700
+ version: number;
701
+ supersedes: string | null;
702
+ is_latest: number;
703
+ event_at: string | null;
704
+ valid_from: string | null;
705
+ valid_until: string | null;
706
+ created_at: number;
707
+ }
708
+
709
+ interface SessionSeedRow {
710
+ id: string;
711
+ scope: string;
712
+ project_id: string | null;
713
+ user_id: string | null;
714
+ agent_id: string | null;
715
+ agent_name: string | null;
716
+ status: string;
717
+ started_at: string;
718
+ ended_at: string | null;
719
+ }
720
+
721
+ interface ActionSeedRow {
722
+ id: string;
723
+ session_id: string | null;
724
+ scope: string;
725
+ project_id: string | null;
726
+ user_id: string | null;
727
+ agent_id: string | null;
728
+ title: string;
729
+ status: string;
730
+ priority: string;
731
+ due_at: string | null;
732
+ remind_at: string | null;
733
+ recurrence: string | null;
734
+ created_at: string;
735
+ }
736
+
737
+ interface SummarySeedRow {
738
+ id: string;
739
+ scope: string;
740
+ project_id: string | null;
741
+ user_id: string | null;
742
+ agent_id: string | null;
743
+ kind: string;
744
+ outcome: string | null;
745
+ producer_tier: string;
746
+ verified: number;
747
+ created_at: number;
748
+ }
86
749
 
87
- if (projectId !== undefined) {
88
- conditions.push('project_id = ?');
89
- params.push(projectId);
750
+ interface TrajectorySeedRow {
751
+ id: string;
752
+ scope: string;
753
+ project_id: string | null;
754
+ user_id: string | null;
755
+ agent_id: string | null;
756
+ session_id: string | null;
757
+ task_type: string | null;
758
+ agent: string | null;
759
+ description: string;
760
+ success: number | null;
761
+ rollup_source: string | null;
762
+ created_at: number;
763
+ }
764
+
765
+ interface ObservationSeedRow {
766
+ id: string;
767
+ scope: string;
768
+ project_id: string | null;
769
+ user_id: string | null;
770
+ agent_id: string | null;
771
+ session_id: string | null;
772
+ kind: string;
773
+ tool_name: string | null;
774
+ file_path: string | null;
775
+ failed: number;
776
+ created_at: number;
777
+ }
778
+
779
+ function noteToGraphNode(note: NoteSeedRow, queryProjectId: string | null): GraphNode {
780
+ return {
781
+ id: note.id,
782
+ type: note.type === 'lesson' ? 'lesson' : 'note',
783
+ label: note.title,
784
+ scope: note.scope,
785
+ project_id: note.project_id,
786
+ match_tier: classifyMatchTier(note.scope, note.project_id, queryProjectId).match_tier,
787
+ user_id: note.user_id,
788
+ agent_id: note.agent_id,
789
+ meta: {
790
+ noteType: note.type,
791
+ version: note.version,
792
+ is_latest: note.is_latest,
793
+ event_at: note.event_at,
794
+ valid_from: note.valid_from,
795
+ valid_until: note.valid_until,
796
+ created_at: note.created_at,
797
+ },
798
+ };
799
+ }
800
+
801
+ function sessionToGraphNode(s: SessionSeedRow, queryProjectId: string | null): GraphNode {
802
+ return {
803
+ id: s.id,
804
+ type: 'session',
805
+ label: s.agent_name ? `${s.agent_name} (${s.status})` : s.id,
806
+ scope: s.scope,
807
+ project_id: s.project_id,
808
+ match_tier: classifyMatchTier(s.scope, s.project_id, queryProjectId).match_tier,
809
+ user_id: s.user_id,
810
+ agent_id: s.agent_id,
811
+ meta: {
812
+ status: s.status,
813
+ agent_name: s.agent_name,
814
+ started_at: s.started_at,
815
+ ended_at: s.ended_at,
816
+ },
817
+ };
818
+ }
819
+
820
+ function actionToGraphNode(a: ActionSeedRow, queryProjectId: string | null): GraphNode {
821
+ return {
822
+ id: a.id,
823
+ type: 'action',
824
+ label: a.title,
825
+ scope: a.scope,
826
+ project_id: a.project_id,
827
+ match_tier: classifyMatchTier(a.scope, a.project_id, queryProjectId).match_tier,
828
+ user_id: a.user_id,
829
+ agent_id: a.agent_id,
830
+ meta: {
831
+ status: a.status,
832
+ priority: a.priority,
833
+ due_at: a.due_at,
834
+ remind_at: a.remind_at,
835
+ recurrence: a.recurrence,
836
+ created_at: a.created_at,
837
+ },
838
+ };
839
+ }
840
+
841
+ function summaryToGraphNode(sum: SummarySeedRow, queryProjectId: string | null): GraphNode {
842
+ return {
843
+ id: sum.id,
844
+ type: 'summary',
845
+ label: `${sum.kind} (${sum.outcome ?? 'unknown'})`,
846
+ scope: sum.scope,
847
+ project_id: sum.project_id,
848
+ match_tier: classifyMatchTier(sum.scope, sum.project_id, queryProjectId).match_tier,
849
+ user_id: sum.user_id,
850
+ agent_id: sum.agent_id,
851
+ meta: {
852
+ kind: sum.kind,
853
+ outcome: sum.outcome,
854
+ producer_tier: sum.producer_tier,
855
+ verified: sum.verified,
856
+ created_at: sum.created_at,
857
+ },
858
+ };
859
+ }
860
+
861
+ function entityToGraphNode(ent: EntityRecord, queryProjectId: string | null): GraphNode {
862
+ const parsedMeta = tryParseJson(ent.metadata_json);
863
+ return {
864
+ id: ent.id,
865
+ type: 'entity',
866
+ label: ent.name,
867
+ scope: ent.scope,
868
+ project_id: ent.project_id,
869
+ entity_type: ent.entity_type,
870
+ external_ref: ent.external_ref,
871
+ match_tier: classifyMatchTier(ent.scope, ent.project_id, queryProjectId).match_tier,
872
+ user_id: ent.user_id,
873
+ agent_id: ent.agent_id,
874
+ meta: {
875
+ entity_type: ent.entity_type,
876
+ description: ent.description,
877
+ external_ref: ent.external_ref,
878
+ ...(parsedMeta ? { metadata: parsedMeta } : {}),
879
+ created_at: ent.created_at,
880
+ updated_at: ent.updated_at,
881
+ },
882
+ };
883
+ }
884
+
885
+ function trajectoryToGraphNode(traj: TrajectorySeedRow, queryProjectId: string | null): GraphNode {
886
+ const snippet = traj.description.length > 60 ? `${traj.description.slice(0, 57)}...` : traj.description;
887
+ return {
888
+ id: traj.id,
889
+ type: 'trajectory',
890
+ label: traj.task_type ? `${traj.task_type}: ${snippet}` : snippet,
891
+ scope: traj.scope,
892
+ project_id: traj.project_id,
893
+ match_tier: classifyMatchTier(traj.scope, traj.project_id, queryProjectId).match_tier,
894
+ user_id: traj.user_id,
895
+ agent_id: traj.agent_id,
896
+ meta: {
897
+ task_type: traj.task_type,
898
+ agent: traj.agent,
899
+ success: traj.success,
900
+ rollup_source: traj.rollup_source,
901
+ created_at: traj.created_at,
902
+ },
903
+ };
904
+ }
905
+
906
+ function observationToGraphNode(obs: ObservationSeedRow, queryProjectId: string | null): GraphNode {
907
+ return {
908
+ id: obs.id,
909
+ type: 'observation',
910
+ label: obs.tool_name ? `${obs.kind}: ${obs.tool_name}` : obs.kind,
911
+ scope: obs.scope,
912
+ project_id: obs.project_id,
913
+ match_tier: classifyMatchTier(obs.scope, obs.project_id, queryProjectId).match_tier,
914
+ user_id: obs.user_id,
915
+ agent_id: obs.agent_id,
916
+ meta: {
917
+ kind: obs.kind,
918
+ tool_name: obs.tool_name,
919
+ file_path: obs.file_path,
920
+ failed: obs.failed,
921
+ created_at: obs.created_at,
922
+ },
923
+ };
924
+ }
925
+
926
+ function userAllowed(rowUserId: string | null | undefined, filterUserId?: string): boolean {
927
+ if (!filterUserId) return true;
928
+ return rowUserId === null || rowUserId === undefined || rowUserId === filterUserId;
929
+ }
930
+
931
+ interface HydratedCollection {
932
+ nodes: GraphNode[];
933
+ notes: NoteSeedRow[];
934
+ actions: ActionSeedRow[];
935
+ summaries: SummarySeedRow[];
936
+ }
937
+
938
+ function hydrateNodesByIds(
939
+ db: Database,
940
+ targets: Array<{ id: string; typeHint?: string }>,
941
+ queryProjectId: string | null,
942
+ filterUserId?: string
943
+ ): HydratedCollection {
944
+ const nodes: GraphNode[] = [];
945
+ const notes: NoteSeedRow[] = [];
946
+ const actions: ActionSeedRow[] = [];
947
+ const summaries: SummarySeedRow[] = [];
948
+ if (targets.length === 0) return { nodes, notes, actions, summaries };
949
+
950
+ const grouped = new Map<string, string[]>();
951
+ const untypedIds: string[] = [];
952
+
953
+ for (const t of targets) {
954
+ if (!t.typeHint) {
955
+ untypedIds.push(t.id);
956
+ continue;
957
+ }
958
+ const bucket = t.typeHint === 'lesson' ? 'note' : t.typeHint;
959
+ const list = grouped.get(bucket) ?? [];
960
+ list.push(t.id);
961
+ grouped.set(bucket, list);
90
962
  }
91
- if (scope !== undefined) {
92
- conditions.push('scope = ?');
93
- params.push(scope);
963
+
964
+ for (const uid of untypedIds) {
965
+ const resolved = resolveNodeType(db, uid);
966
+ if (resolved) {
967
+ const bucket = resolved === 'lesson' ? 'note' : resolved;
968
+ const list = grouped.get(bucket) ?? [];
969
+ list.push(uid);
970
+ grouped.set(bucket, list);
971
+ } else if (uid.startsWith('concept:')) {
972
+ nodes.push({ id: uid, type: 'concept', label: uid.slice('concept:'.length) });
973
+ } else if (uid.startsWith('file:')) {
974
+ nodes.push({ id: uid, type: 'file', label: uid.slice('file:'.length) });
975
+ } else {
976
+ const edgeHint = db
977
+ .prepare(
978
+ `
979
+ SELECT source_type AS ext_type FROM entity_edges WHERE source_id = ?
980
+ UNION ALL
981
+ SELECT target_type AS ext_type FROM entity_edges WHERE target_id = ?
982
+ LIMIT 1
983
+ `
984
+ )
985
+ .get(uid, uid) as { ext_type: string } | undefined;
986
+ if (edgeHint && !KNOWN_NODE_TABLES[edgeHint.ext_type]) {
987
+ nodes.push({
988
+ id: uid,
989
+ type: 'entity',
990
+ label: uid,
991
+ entity_type: edgeHint.ext_type,
992
+ meta: { external_type: edgeHint.ext_type },
993
+ });
994
+ }
995
+ }
94
996
  }
95
997
 
96
- return {
97
- where: conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '',
98
- params,
998
+ const chunkedQuery = <T>(
999
+ ids: string[],
1000
+ sqlBuilder: (placeholders: string) => string
1001
+ ): T[] => {
1002
+ const results: T[] = [];
1003
+ const CHUNK = 400;
1004
+ for (let i = 0; i < ids.length; i += CHUNK) {
1005
+ const slice = ids.slice(i, i + CHUNK);
1006
+ const placeholders = slice.map(() => '?').join(',');
1007
+ results.push(...(db.prepare(sqlBuilder(placeholders)).all(...slice) as T[]));
1008
+ }
1009
+ return results;
99
1010
  };
1011
+
1012
+ const entityIds = grouped.get('entity');
1013
+ if (entityIds?.length) {
1014
+ const rows = chunkedQuery<EntityRecord>(
1015
+ entityIds,
1016
+ (ph) => `SELECT ${ENTITY_COLUMNS} FROM entities WHERE id IN (${ph})`
1017
+ );
1018
+ for (const row of rows) {
1019
+ if (!userAllowed(row.user_id, filterUserId)) continue;
1020
+ nodes.push(entityToGraphNode(row, queryProjectId));
1021
+ }
1022
+ }
1023
+
1024
+ const noteIds = grouped.get('note');
1025
+ if (noteIds?.length) {
1026
+ const rows = chunkedQuery<NoteSeedRow>(
1027
+ noteIds,
1028
+ (ph) =>
1029
+ `SELECT id, scope, project_id, user_id, agent_id, session_id, type, title, version, supersedes, is_latest, event_at, valid_from, valid_until, created_at FROM notes WHERE id IN (${ph})`
1030
+ );
1031
+ for (const row of rows) {
1032
+ if (!userAllowed(row.user_id, filterUserId)) continue;
1033
+ notes.push(row);
1034
+ nodes.push(noteToGraphNode(row, queryProjectId));
1035
+ }
1036
+ }
1037
+
1038
+ const actionIds = grouped.get('action');
1039
+ if (actionIds?.length) {
1040
+ const rows = chunkedQuery<ActionSeedRow>(
1041
+ actionIds,
1042
+ (ph) =>
1043
+ `SELECT id, session_id, scope, project_id, user_id, agent_id, title, status, priority, due_at, remind_at, recurrence, created_at FROM actions WHERE id IN (${ph})`
1044
+ );
1045
+ for (const row of rows) {
1046
+ if (!userAllowed(row.user_id, filterUserId)) continue;
1047
+ actions.push(row);
1048
+ nodes.push(actionToGraphNode(row, queryProjectId));
1049
+ }
1050
+ }
1051
+
1052
+ const sessionIds = grouped.get('session');
1053
+ if (sessionIds?.length) {
1054
+ const rows = chunkedQuery<SessionSeedRow>(
1055
+ sessionIds,
1056
+ (ph) =>
1057
+ `SELECT id, scope, project_id, user_id, agent_id, agent_name, status, started_at, ended_at FROM sessions WHERE id IN (${ph})`
1058
+ );
1059
+ for (const row of rows) {
1060
+ if (!userAllowed(row.user_id, filterUserId)) continue;
1061
+ nodes.push(sessionToGraphNode(row, queryProjectId));
1062
+ }
1063
+ }
1064
+
1065
+ const summaryIds = grouped.get('summary');
1066
+ if (summaryIds?.length) {
1067
+ const rows = chunkedQuery<SummarySeedRow>(
1068
+ summaryIds,
1069
+ (ph) =>
1070
+ `SELECT id, scope, project_id, user_id, agent_id, kind, outcome, producer_tier, verified, created_at FROM summaries WHERE id IN (${ph})`
1071
+ );
1072
+ for (const row of rows) {
1073
+ if (!userAllowed(row.user_id, filterUserId)) continue;
1074
+ summaries.push(row);
1075
+ nodes.push(summaryToGraphNode(row, queryProjectId));
1076
+ }
1077
+ }
1078
+
1079
+ const trajectoryIds = grouped.get('trajectory');
1080
+ if (trajectoryIds?.length) {
1081
+ const rows = chunkedQuery<TrajectorySeedRow>(
1082
+ trajectoryIds,
1083
+ (ph) =>
1084
+ `SELECT id, scope, project_id, user_id, agent_id, session_id, task_type, agent, description, success, rollup_source, created_at FROM trajectories WHERE id IN (${ph})`
1085
+ );
1086
+ for (const row of rows) {
1087
+ if (!userAllowed(row.user_id, filterUserId)) continue;
1088
+ nodes.push(trajectoryToGraphNode(row, queryProjectId));
1089
+ }
1090
+ }
1091
+
1092
+ const observationIds = grouped.get('observation');
1093
+ if (observationIds?.length) {
1094
+ const rows = chunkedQuery<ObservationSeedRow>(
1095
+ observationIds,
1096
+ (ph) =>
1097
+ `SELECT id, scope, project_id, user_id, agent_id, session_id, kind, tool_name, file_path, failed, created_at FROM observations WHERE id IN (${ph})`
1098
+ );
1099
+ for (const row of rows) {
1100
+ if (!userAllowed(row.user_id, filterUserId)) continue;
1101
+ nodes.push(observationToGraphNode(row, queryProjectId));
1102
+ }
1103
+ }
1104
+
1105
+ for (const [typeHint, ids] of grouped.entries()) {
1106
+ if (KNOWN_NODE_TABLES[typeHint]) continue;
1107
+ for (const id of ids) {
1108
+ if (typeHint === 'concept') {
1109
+ nodes.push({ id, type: 'concept', label: id.replace(/^concept:/, '') });
1110
+ } else if (typeHint === 'file') {
1111
+ nodes.push({ id, type: 'file', label: id.replace(/^file:/, '') });
1112
+ } else {
1113
+ nodes.push({
1114
+ id,
1115
+ type: 'entity',
1116
+ label: id,
1117
+ entity_type: typeHint,
1118
+ meta: { external_type: typeHint },
1119
+ });
1120
+ }
1121
+ }
1122
+ }
1123
+
1124
+ return { nodes, notes, actions, summaries };
100
1125
  }
101
1126
 
102
1127
  /**
103
1128
  * Build a scoped knowledge graph from notes, concepts, files, sessions,
104
- * actions, summaries, and summary citations stored in SQLite.
1129
+ * actions, summaries, entities, trajectories, observations, and entity_edges
1130
+ * stored in SQLite, with hierarchical scoping and 1..3 hop cross-subproject BFS.
105
1131
  */
106
1132
  export function getKnowledgeGraph(options: KnowledgeGraphOptions = {}): KnowledgeGraph {
107
1133
  const db = getDb();
108
1134
  const limit = clampLimit(options.limit);
1135
+ const depth = clampDepth(options.depth);
109
1136
  const projectId =
110
- typeof options.projectId === 'string' && options.projectId.trim()
1137
+ typeof options.projectId === 'string' && options.projectId.trim() !== ''
111
1138
  ? options.projectId.trim()
112
1139
  : undefined;
113
1140
  const scope =
114
- typeof options.scope === 'string' && options.scope.trim()
1141
+ typeof options.scope === 'string' && options.scope.trim() !== ''
115
1142
  ? options.scope.trim()
116
1143
  : undefined;
1144
+ const includeAncestors = options.includeAncestors ?? true;
1145
+ const includeChildren = options.includeChildren ?? false;
1146
+ const includeGlobal = options.includeGlobal ?? false;
1147
+ const nodeId =
1148
+ typeof options.nodeId === 'string' && options.nodeId.trim() !== ''
1149
+ ? options.nodeId.trim()
1150
+ : undefined;
1151
+ const entityType =
1152
+ typeof options.entityType === 'string' && options.entityType.trim() !== ''
1153
+ ? options.entityType.trim()
1154
+ : undefined;
1155
+ const relationFilter =
1156
+ typeof options.relation === 'string' && options.relation.trim() !== ''
1157
+ ? options.relation.trim()
1158
+ : undefined;
1159
+ const userId =
1160
+ typeof options.userId === 'string' && options.userId.trim() !== ''
1161
+ ? options.userId.trim()
1162
+ : undefined;
1163
+
1164
+ let normalizedProjectId: string | null = null;
1165
+ if (projectId) {
1166
+ const norm = normalizeProjectId(projectId);
1167
+ normalizedProjectId = norm.ok ? norm.projectId : projectId;
1168
+ }
117
1169
 
118
- const { where, params } = buildScopeFilter(projectId, scope);
1170
+ let where = '';
1171
+ let params: unknown[] = [];
1172
+
1173
+ if (projectId !== undefined || scope !== undefined) {
1174
+ const scopeSql = buildHierarchicalScopeSql({
1175
+ scope,
1176
+ projectId,
1177
+ includeAncestors,
1178
+ includeChildren,
1179
+ includeGlobal,
1180
+ userId,
1181
+ });
1182
+ where = `WHERE ${scopeSql.clause}`;
1183
+ params = scopeSql.params;
1184
+ normalizedProjectId = scopeSql.normalizedProjectId;
1185
+ } else if (userId !== undefined) {
1186
+ where = 'WHERE user_id = ?';
1187
+ params = [userId];
1188
+ }
119
1189
 
120
1190
  const nodeMap = new Map<string, GraphNode>();
121
1191
  const edgeKeys = new Set<string>();
122
1192
  const edges: GraphEdge[] = [];
1193
+ const maxNodes = limit * 6;
1194
+ const maxEdges = limit * 10;
123
1195
 
124
- const addNode = (node: GraphNode) => {
125
- if (!nodeMap.has(node.id)) {
126
- nodeMap.set(node.id, node);
127
- }
1196
+ const addNode = (node: GraphNode): boolean => {
1197
+ if (nodeMap.has(node.id)) return true;
1198
+ if (nodeMap.size >= maxNodes) return false;
1199
+ nodeMap.set(node.id, node);
1200
+ return true;
128
1201
  };
129
1202
 
130
- const addEdge = (source: string, target: string, type: GraphEdgeType) => {
131
- if (!nodeMap.has(source) || !nodeMap.has(target)) return;
1203
+ const addEdge = (
1204
+ source: string,
1205
+ target: string,
1206
+ type: GraphEdgeType,
1207
+ meta?: Record<string, unknown>
1208
+ ): boolean => {
1209
+ if (edges.length >= maxEdges) return false;
1210
+ if (!nodeMap.has(source) || !nodeMap.has(target)) return false;
132
1211
  const key = `${source}\0${type}\0${target}`;
133
1212
  if (!edgeKeys.has(key)) {
134
1213
  edgeKeys.add(key);
135
- edges.push({ source, target, type });
1214
+ edges.push(meta ? { source, target, type, meta } : { source, target, type });
136
1215
  }
1216
+ return true;
137
1217
  };
138
1218
 
139
- const noteRows = db
140
- .prepare(
141
- `
142
- SELECT id, scope, project_id, session_id, type, title, version, supersedes, is_latest, created_at
143
- FROM notes
144
- ${where}
145
- ORDER BY updated_at DESC
146
- LIMIT ?
147
- `
148
- )
149
- .all(...params, limit) as Array<{
150
- id: string;
151
- scope: string;
152
- project_id: string | null;
153
- session_id: string | null;
154
- type: string;
155
- title: string;
156
- version: number;
157
- supersedes: string | null;
158
- is_latest: number;
159
- created_at: number;
160
- }>;
161
-
162
- for (const note of noteRows) {
163
- const nodeType: GraphNodeType = note.type === 'lesson' ? 'lesson' : 'note';
164
- addNode({
165
- id: note.id,
166
- type: nodeType,
167
- label: note.title,
168
- scope: note.scope,
169
- project_id: note.project_id,
170
- meta: {
171
- noteType: note.type,
172
- version: note.version,
173
- is_latest: note.is_latest,
174
- created_at: note.created_at,
175
- },
176
- });
177
- }
1219
+ let seedNoteRows: NoteSeedRow[] = [];
1220
+ let seedActionRows: ActionSeedRow[] = [];
1221
+ let seedSummaryRows: SummarySeedRow[] = [];
1222
+ const allNoteRows = new Map<string, NoteSeedRow>();
1223
+ const allActionRows = new Map<string, ActionSeedRow>();
1224
+ const allSummaryRows = new Map<string, SummarySeedRow>();
178
1225
 
179
- const sessionRows = db
180
- .prepare(
181
- `
182
- SELECT id, scope, project_id, agent_name, status, started_at, ended_at
183
- FROM sessions
184
- ${where}
185
- ORDER BY started_at DESC
186
- LIMIT ?
187
- `
188
- )
189
- .all(...params, limit) as Array<{
190
- id: string;
191
- scope: string;
192
- project_id: string | null;
193
- agent_name: string | null;
194
- status: string;
195
- started_at: string;
196
- ended_at: string | null;
197
- }>;
198
-
199
- for (const s of sessionRows) {
200
- addNode({
201
- id: s.id,
202
- type: 'session',
203
- label: s.agent_name ? `${s.agent_name} (${s.status})` : s.id,
204
- scope: s.scope,
205
- project_id: s.project_id,
206
- meta: {
207
- status: s.status,
208
- agent_name: s.agent_name,
209
- started_at: s.started_at,
210
- ended_at: s.ended_at,
211
- },
212
- });
213
- }
1226
+ if (nodeId) {
1227
+ const hydratedSeed = hydrateNodesByIds(
1228
+ db,
1229
+ [{ id: nodeId }],
1230
+ normalizedProjectId,
1231
+ userId
1232
+ );
1233
+ for (const node of hydratedSeed.nodes) {
1234
+ addNode(node);
1235
+ }
1236
+ seedNoteRows = hydratedSeed.notes;
1237
+ seedActionRows = hydratedSeed.actions;
1238
+ seedSummaryRows = hydratedSeed.summaries;
1239
+ for (const n of hydratedSeed.notes) allNoteRows.set(n.id, n);
1240
+ for (const a of hydratedSeed.actions) allActionRows.set(a.id, a);
1241
+ for (const s of hydratedSeed.summaries) allSummaryRows.set(s.id, s);
1242
+ } else {
1243
+ seedNoteRows = db
1244
+ .prepare(
1245
+ `
1246
+ SELECT id, scope, project_id, user_id, agent_id, session_id, type, title,
1247
+ version, supersedes, is_latest, event_at, valid_from, valid_until, created_at
1248
+ FROM notes
1249
+ ${where}
1250
+ ORDER BY updated_at DESC
1251
+ LIMIT ?
1252
+ `
1253
+ )
1254
+ .all(...params, limit) as NoteSeedRow[];
214
1255
 
215
- const actionRows = db
216
- .prepare(
217
- `
218
- SELECT id, session_id, scope, project_id, title, status, priority, created_at
219
- FROM actions
220
- ${where}
221
- ORDER BY created_at DESC
222
- LIMIT ?
223
- `
224
- )
225
- .all(...params, limit) as Array<{
226
- id: string;
227
- session_id: string | null;
228
- scope: string;
229
- project_id: string | null;
230
- title: string;
231
- status: string;
232
- priority: string;
233
- created_at: string;
234
- }>;
235
-
236
- for (const a of actionRows) {
237
- addNode({
238
- id: a.id,
239
- type: 'action',
240
- label: a.title,
241
- scope: a.scope,
242
- project_id: a.project_id,
243
- meta: {
244
- status: a.status,
245
- priority: a.priority,
246
- created_at: a.created_at,
247
- },
248
- });
249
- }
1256
+ for (const note of seedNoteRows) {
1257
+ allNoteRows.set(note.id, note);
1258
+ addNode(noteToGraphNode(note, normalizedProjectId));
1259
+ }
250
1260
 
251
- const summaryRows = db
252
- .prepare(
253
- `
254
- SELECT id, scope, project_id, kind, outcome, producer_tier, verified, created_at
255
- FROM summaries
256
- ${where}
257
- ORDER BY created_at DESC
258
- LIMIT ?
259
- `
260
- )
261
- .all(...params, limit) as Array<{
262
- id: string;
263
- scope: string;
264
- project_id: string | null;
265
- kind: string;
266
- outcome: string | null;
267
- producer_tier: string;
268
- verified: number;
269
- created_at: number;
270
- }>;
271
-
272
- for (const sum of summaryRows) {
273
- addNode({
274
- id: sum.id,
275
- type: 'summary',
276
- label: `${sum.kind} (${sum.outcome ?? 'unknown'})`,
277
- scope: sum.scope,
278
- project_id: sum.project_id,
279
- meta: {
280
- kind: sum.kind,
281
- outcome: sum.outcome,
282
- producer_tier: sum.producer_tier,
283
- verified: sum.verified,
284
- created_at: sum.created_at,
285
- },
286
- });
1261
+ const sessionRows = db
1262
+ .prepare(
1263
+ `
1264
+ SELECT id, scope, project_id, user_id, agent_id, agent_name, status, started_at, ended_at
1265
+ FROM sessions
1266
+ ${where}
1267
+ ORDER BY started_at DESC
1268
+ LIMIT ?
1269
+ `
1270
+ )
1271
+ .all(...params, limit) as SessionSeedRow[];
1272
+
1273
+ for (const s of sessionRows) {
1274
+ addNode(sessionToGraphNode(s, normalizedProjectId));
1275
+ }
1276
+
1277
+ seedActionRows = db
1278
+ .prepare(
1279
+ `
1280
+ SELECT id, session_id, scope, project_id, user_id, agent_id, title, status,
1281
+ priority, due_at, remind_at, recurrence, created_at
1282
+ FROM actions
1283
+ ${where}
1284
+ ORDER BY created_at DESC
1285
+ LIMIT ?
1286
+ `
1287
+ )
1288
+ .all(...params, limit) as ActionSeedRow[];
1289
+
1290
+ for (const a of seedActionRows) {
1291
+ allActionRows.set(a.id, a);
1292
+ addNode(actionToGraphNode(a, normalizedProjectId));
1293
+ }
1294
+
1295
+ seedSummaryRows = db
1296
+ .prepare(
1297
+ `
1298
+ SELECT id, scope, project_id, user_id, agent_id, kind, outcome, producer_tier, verified, created_at
1299
+ FROM summaries
1300
+ ${where}
1301
+ ORDER BY created_at DESC
1302
+ LIMIT ?
1303
+ `
1304
+ )
1305
+ .all(...params, limit) as SummarySeedRow[];
1306
+
1307
+ for (const sum of seedSummaryRows) {
1308
+ allSummaryRows.set(sum.id, sum);
1309
+ addNode(summaryToGraphNode(sum, normalizedProjectId));
1310
+ }
1311
+
1312
+ const entityConditions: string[] = [];
1313
+ const entityParams: unknown[] = [...params];
1314
+ if (where) {
1315
+ entityConditions.push(where.replace(/^WHERE\s+/i, ''));
1316
+ }
1317
+ if (entityType) {
1318
+ entityConditions.push('entity_type = ?');
1319
+ entityParams.push(entityType);
1320
+ }
1321
+ const entityWhere =
1322
+ entityConditions.length > 0 ? `WHERE ${entityConditions.join(' AND ')}` : '';
1323
+
1324
+ const entityRows = db
1325
+ .prepare(
1326
+ `
1327
+ SELECT ${ENTITY_COLUMNS}
1328
+ FROM entities
1329
+ ${entityWhere}
1330
+ ORDER BY updated_at DESC, created_at DESC
1331
+ LIMIT ?
1332
+ `
1333
+ )
1334
+ .all(...entityParams, limit) as EntityRecord[];
1335
+
1336
+ for (const ent of entityRows) {
1337
+ addNode(entityToGraphNode(ent, normalizedProjectId));
1338
+ }
287
1339
  }
288
1340
 
289
- if (noteRows.length > 0) {
290
- const noteIds = noteRows.map((n) => n.id);
291
- const placeholders = noteIds.map(() => '?').join(',');
1341
+ // Multi-hop BFS traversal over entity_edges (1..depth hops across any subproject)
1342
+ let frontier = Array.from(nodeMap.keys());
1343
+ const visited = new Set<string>(frontier);
1344
+
1345
+ for (let hop = 1; hop <= depth; hop++) {
1346
+ if (frontier.length === 0 || nodeMap.size >= maxNodes || edges.length >= maxEdges) {
1347
+ break;
1348
+ }
292
1349
 
293
- const conceptRows = db
294
- .prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders})`)
295
- .all(...noteIds) as Array<{ note_id: string; concept: string }>;
1350
+ const hopEdges: EntityEdgeRecord[] = [];
1351
+ const seenEdgeIds = new Set<string>();
1352
+ const CHUNK = 400;
296
1353
 
297
- for (const row of conceptRows) {
298
- const conceptId = `concept:${row.concept}`;
299
- addNode({ id: conceptId, type: 'concept', label: row.concept });
300
- addEdge(row.note_id, conceptId, 'has_concept');
1354
+ for (let i = 0; i < frontier.length; i += CHUNK) {
1355
+ const slice = frontier.slice(i, i + CHUNK);
1356
+ const placeholders = slice.map(() => '?').join(',');
1357
+ const edgeSql = relationFilter
1358
+ ? `
1359
+ SELECT id, source_type, source_id, target_type, target_id, relation, metadata_json, created_at
1360
+ FROM entity_edges
1361
+ WHERE (source_id IN (${placeholders}) OR target_id IN (${placeholders}))
1362
+ AND relation = ?
1363
+ ORDER BY created_at DESC, id ASC
1364
+ `
1365
+ : `
1366
+ SELECT id, source_type, source_id, target_type, target_id, relation, metadata_json, created_at
1367
+ FROM entity_edges
1368
+ WHERE (source_id IN (${placeholders}) OR target_id IN (${placeholders}))
1369
+ ORDER BY created_at DESC, id ASC
1370
+ `;
1371
+ const edgeParams = relationFilter
1372
+ ? [...slice, ...slice, relationFilter]
1373
+ : [...slice, ...slice];
1374
+ const rows = db.prepare(edgeSql).all(...edgeParams) as EntityEdgeRecord[];
1375
+ for (const row of rows) {
1376
+ if (!seenEdgeIds.has(row.id)) {
1377
+ seenEdgeIds.add(row.id);
1378
+ hopEdges.push(row);
1379
+ }
1380
+ }
301
1381
  }
302
1382
 
303
- const fileRows = db
304
- .prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders})`)
305
- .all(...noteIds) as Array<{ note_id: string; file_path: string }>;
1383
+ const toHydrate: Array<{ id: string; typeHint: string }> = [];
1384
+ const queuedForHydration = new Set<string>();
306
1385
 
307
- for (const row of fileRows) {
308
- const fileId = `file:${row.file_path}`;
309
- addNode({ id: fileId, type: 'file', label: row.file_path });
310
- addEdge(row.note_id, fileId, 'touches_file');
1386
+ for (const edge of hopEdges) {
1387
+ if (!nodeMap.has(edge.source_id) && !visited.has(edge.source_id) && !queuedForHydration.has(edge.source_id)) {
1388
+ queuedForHydration.add(edge.source_id);
1389
+ visited.add(edge.source_id);
1390
+ toHydrate.push({ id: edge.source_id, typeHint: edge.source_type });
1391
+ }
1392
+ if (!nodeMap.has(edge.target_id) && !visited.has(edge.target_id) && !queuedForHydration.has(edge.target_id)) {
1393
+ queuedForHydration.add(edge.target_id);
1394
+ visited.add(edge.target_id);
1395
+ toHydrate.push({ id: edge.target_id, typeHint: edge.target_type });
1396
+ }
311
1397
  }
312
1398
 
313
- for (const note of noteRows) {
314
- if (note.supersedes) {
315
- addEdge(note.id, note.supersedes, 'supersedes');
1399
+ const nextFrontier: string[] = [];
1400
+ if (toHydrate.length > 0 && nodeMap.size < maxNodes) {
1401
+ const hydrated = hydrateNodesByIds(db, toHydrate, normalizedProjectId, userId);
1402
+ for (const node of hydrated.nodes) {
1403
+ if (!nodeMap.has(node.id) && addNode(node)) {
1404
+ nextFrontier.push(node.id);
1405
+ }
316
1406
  }
317
- if (note.session_id) {
318
- addEdge(note.id, note.session_id, 'from_session');
1407
+ for (const n of hydrated.notes) allNoteRows.set(n.id, n);
1408
+ for (const a of hydrated.actions) allActionRows.set(a.id, a);
1409
+ for (const s of hydrated.summaries) allSummaryRows.set(s.id, s);
1410
+ }
1411
+
1412
+ for (const edge of hopEdges) {
1413
+ addEdge(
1414
+ edge.source_id,
1415
+ edge.target_id,
1416
+ edge.relation,
1417
+ tryParseJson(edge.metadata_json)
1418
+ );
1419
+ }
1420
+
1421
+ frontier = nextFrontier;
1422
+ }
1423
+
1424
+ // Synthesized structural edges (preserve exact { source, target, type } shape)
1425
+ const allowEdgeType = (edgeType: string): boolean =>
1426
+ !relationFilter || relationFilter === edgeType;
1427
+
1428
+ if (seedNoteRows.length > 0 && (!relationFilter || SYNTHETIC_EDGE_TYPES.has(relationFilter))) {
1429
+ const seedNoteIds = seedNoteRows.map((n) => n.id);
1430
+ const placeholders = seedNoteIds.map(() => '?').join(',');
1431
+
1432
+ if (allowEdgeType('has_concept')) {
1433
+ const conceptRows = db
1434
+ .prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders}) LIMIT ?`)
1435
+ .all(...seedNoteIds, maxNodes) as Array<{ note_id: string; concept: string }>;
1436
+
1437
+ for (const row of conceptRows) {
1438
+ const conceptId = `concept:${row.concept}`;
1439
+ if (addNode({ id: conceptId, type: 'concept', label: row.concept })) {
1440
+ addEdge(row.note_id, conceptId, 'has_concept');
1441
+ }
1442
+ }
1443
+ }
1444
+
1445
+ if (allowEdgeType('touches_file')) {
1446
+ const fileRows = db
1447
+ .prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders}) LIMIT ?`)
1448
+ .all(...seedNoteIds, maxNodes) as Array<{ note_id: string; file_path: string }>;
1449
+
1450
+ for (const row of fileRows) {
1451
+ const fileId = `file:${row.file_path}`;
1452
+ if (addNode({ id: fileId, type: 'file', label: row.file_path })) {
1453
+ addEdge(row.note_id, fileId, 'touches_file');
1454
+ }
319
1455
  }
320
1456
  }
321
1457
  }
322
1458
 
323
- for (const action of actionRows) {
324
- if (action.session_id) {
1459
+ for (const note of allNoteRows.values()) {
1460
+ if (note.supersedes && allowEdgeType('supersedes')) {
1461
+ addEdge(note.id, note.supersedes, 'supersedes');
1462
+ }
1463
+ if (note.session_id && allowEdgeType('from_session')) {
1464
+ addEdge(note.id, note.session_id, 'from_session');
1465
+ }
1466
+ }
1467
+
1468
+ for (const action of allActionRows.values()) {
1469
+ if (action.session_id && allowEdgeType('from_session')) {
325
1470
  addEdge(action.id, action.session_id, 'from_session');
326
1471
  }
327
1472
  }
328
1473
 
329
- if (summaryRows.length > 0) {
330
- const summaryIds = summaryRows.map((s) => s.id);
1474
+ if (allSummaryRows.size > 0 && allowEdgeType('cites_source')) {
1475
+ const summaryIds = Array.from(allSummaryRows.keys());
331
1476
  const placeholders = summaryIds.map(() => '?').join(',');
332
1477
  const sourceRows = db
333
1478
  .prepare(
334
- `SELECT DISTINCT summary_id, record_id FROM summary_sources WHERE summary_id IN (${placeholders})`
1479
+ `SELECT DISTINCT summary_id, record_id, record_type FROM summary_sources WHERE summary_id IN (${placeholders}) LIMIT ?`
335
1480
  )
336
- .all(...summaryIds) as Array<{ summary_id: string; record_id: string }>;
1481
+ .all(...summaryIds, maxNodes) as Array<{
1482
+ summary_id: string;
1483
+ record_id: string;
1484
+ record_type: string;
1485
+ }>;
1486
+
1487
+ // Load cited observation nodes from seed summaries within the remaining node budget
1488
+ const seedSummaryIdSet = new Set(seedSummaryRows.map((s) => s.id));
1489
+ const remainingBudget = maxNodes - nodeMap.size;
1490
+ if (remainingBudget > 0 && seedSummaryIdSet.size > 0) {
1491
+ const citedObsIds = Array.from(
1492
+ new Set(
1493
+ sourceRows
1494
+ .filter(
1495
+ (r) =>
1496
+ seedSummaryIdSet.has(r.summary_id) &&
1497
+ r.record_type === 'observation' &&
1498
+ !nodeMap.has(r.record_id)
1499
+ )
1500
+ .map((r) => r.record_id)
1501
+ )
1502
+ ).slice(0, remainingBudget);
1503
+
1504
+ if (citedObsIds.length > 0) {
1505
+ const obsPlaceholders = citedObsIds.map(() => '?').join(',');
1506
+ const obsRows = db
1507
+ .prepare(
1508
+ `SELECT id, scope, project_id, user_id, agent_id, session_id, kind, tool_name, file_path, failed, created_at FROM observations WHERE id IN (${obsPlaceholders}) LIMIT ?`
1509
+ )
1510
+ .all(...citedObsIds, remainingBudget) as ObservationSeedRow[];
1511
+
1512
+ for (const obs of obsRows) {
1513
+ if (!userAllowed(obs.user_id, userId)) continue;
1514
+ addNode(observationToGraphNode(obs, normalizedProjectId));
1515
+ }
1516
+ }
1517
+ }
337
1518
 
338
1519
  for (const row of sourceRows) {
339
1520
  addEdge(row.summary_id, row.record_id, 'cites_source');