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,24 +1,410 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.STANDARD_EDGE_RELATIONS = exports.STANDARD_ENTITY_TYPES = void 0;
4
+ exports.upsertEntity = upsertEntity;
5
+ exports.getEntity = getEntity;
6
+ exports.listEntities = listEntities;
7
+ exports.linkEntities = linkEntities;
8
+ exports.unlinkEntities = unlinkEntities;
3
9
  exports.parseGraphQuery = parseGraphQuery;
4
10
  exports.getKnowledgeGraph = getKnowledgeGraph;
11
+ const crypto_1 = require("crypto");
5
12
  const db_1 = require("../lib/db");
6
- function clampLimit(raw) {
13
+ const redactSecrets_1 = require("../lib/redactSecrets");
14
+ const scope_1 = require("../lib/scope");
15
+ const sqlite_1 = require("../lib/sqlite");
16
+ const embedQueueStore_1 = require("./embedQueueStore");
17
+ exports.STANDARD_ENTITY_TYPES = [
18
+ 'brand',
19
+ 'person',
20
+ 'asset',
21
+ 'metric',
22
+ 'document',
23
+ 'tool',
24
+ ];
25
+ exports.STANDARD_EDGE_RELATIONS = [
26
+ 'part_of',
27
+ 'depends_on',
28
+ 'references',
29
+ 'owns',
30
+ 'produced_by',
31
+ 'blocks',
32
+ 'related_to',
33
+ ];
34
+ const ENTITY_COLUMNS = 'id, scope, project_id, user_id, agent_id, entity_type, name, description, external_ref, metadata_json, created_at, updated_at';
35
+ const KNOWN_NODE_TABLES = {
36
+ entity: 'entities',
37
+ note: 'notes',
38
+ lesson: 'notes',
39
+ action: 'actions',
40
+ session: 'sessions',
41
+ summary: 'summaries',
42
+ trajectory: 'trajectories',
43
+ observation: 'observations',
44
+ };
45
+ const SYNTHETIC_EDGE_TYPES = new Set([
46
+ 'has_concept',
47
+ 'touches_file',
48
+ 'supersedes',
49
+ 'from_session',
50
+ 'cites_source',
51
+ ]);
52
+ function makeError(code, message) {
53
+ const err = new Error(message);
54
+ err.code = code;
55
+ return err;
56
+ }
57
+ function optionalString(value, field) {
58
+ if (value === undefined || value === null)
59
+ return null;
60
+ if (typeof value !== 'string') {
61
+ throw makeError('SCHEMA_INVALID', `${field} must be a string`);
62
+ }
63
+ const trimmed = value.trim();
64
+ return trimmed === '' ? null : trimmed;
65
+ }
66
+ function serializeMetadata(input) {
67
+ const rawJson = input.metadata_json !== undefined ? input.metadata_json : input.metadataJson;
68
+ if (rawJson !== undefined) {
69
+ return (0, redactSecrets_1.redactOptional)(optionalString(rawJson, 'metadata_json'));
70
+ }
71
+ if (input.metadata === undefined || input.metadata === null) {
72
+ return null;
73
+ }
74
+ if (typeof input.metadata === 'string') {
75
+ return (0, redactSecrets_1.redactOptional)(optionalString(input.metadata, 'metadata'));
76
+ }
77
+ if (typeof input.metadata === 'object' && !Array.isArray(input.metadata)) {
78
+ return (0, redactSecrets_1.redactSecrets)(JSON.stringify(input.metadata));
79
+ }
80
+ throw makeError('SCHEMA_INVALID', 'metadata must be an object, JSON string, or null');
81
+ }
82
+ function tryParseJson(raw) {
83
+ if (!raw)
84
+ return undefined;
85
+ try {
86
+ const parsed = JSON.parse(raw);
87
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
88
+ return parsed;
89
+ }
90
+ return { value: parsed };
91
+ }
92
+ catch {
93
+ return { raw };
94
+ }
95
+ }
96
+ function clampLimit(raw, defaultLimit = 80, maxLimit = 200) {
7
97
  if (typeof raw !== 'number' || !Number.isFinite(raw) || raw <= 0) {
8
- return 80;
98
+ return defaultLimit;
9
99
  }
10
- return Math.min(Math.floor(raw), 200);
100
+ return Math.min(Math.floor(raw), maxLimit);
101
+ }
102
+ function clampDepth(raw) {
103
+ if (raw === undefined || raw === null || raw === '')
104
+ return 1;
105
+ const n = typeof raw === 'number' ? raw : parseInt(String(raw), 10);
106
+ if (!Number.isFinite(n))
107
+ return 1;
108
+ return Math.min(3, Math.max(1, Math.floor(n)));
109
+ }
110
+ function parseOptionalBool(value) {
111
+ if (typeof value === 'boolean')
112
+ return value;
113
+ if (typeof value === 'string') {
114
+ const norm = value.trim().toLowerCase();
115
+ if (norm === 'true' || norm === '1')
116
+ return true;
117
+ if (norm === 'false' || norm === '0')
118
+ return false;
119
+ }
120
+ return undefined;
121
+ }
122
+ /**
123
+ * Create or update a persistent entity node with explicit Rule 4 scope,
124
+ * secret redaction, deduplication on (scope/project_id, entity_type, lower(name)),
125
+ * and atomic embed_queue enqueueing. Never returns the embedding BLOB.
126
+ */
127
+ function upsertEntity(input) {
128
+ const scoped = (0, scope_1.resolveScope)(input.scope, input.projectId ?? input.project_id);
129
+ if (!scoped.ok) {
130
+ throw makeError('SCHEMA_INVALID', scoped.error);
131
+ }
132
+ const rawEntityType = input.entity_type !== undefined ? input.entity_type : input.entityType;
133
+ const entityType = optionalString(rawEntityType, 'entity_type');
134
+ if (!entityType) {
135
+ throw makeError('SCHEMA_INVALID', 'entity_type is required and cannot be empty');
136
+ }
137
+ const rawName = optionalString(input.name, 'name');
138
+ if (!rawName) {
139
+ throw makeError('SCHEMA_INVALID', 'name is required and cannot be empty');
140
+ }
141
+ const name = (0, redactSecrets_1.redactSecrets)(rawName);
142
+ const description = (0, redactSecrets_1.redactOptional)(optionalString(input.description, 'description'));
143
+ const rawExternalRef = input.external_ref !== undefined ? input.external_ref : input.externalRef;
144
+ const externalRef = (0, redactSecrets_1.redactOptional)(optionalString(rawExternalRef, 'external_ref'));
145
+ const metadataJson = serializeMetadata(input);
146
+ const userId = optionalString(input.user_id !== undefined ? input.user_id : input.userId, 'user_id');
147
+ const agentId = optionalString(input.agent_id !== undefined ? input.agent_id : input.agentId, 'agent_id');
148
+ const providedId = optionalString(input.id, 'id');
149
+ const db = (0, db_1.getDb)();
150
+ const dedupScopeKey = scoped.projectId ?? `__SCOPE__:${scoped.scope}`;
151
+ return (0, sqlite_1.transaction)(db, () => {
152
+ let existing;
153
+ if (providedId) {
154
+ existing = db
155
+ .prepare(`SELECT ${ENTITY_COLUMNS} FROM entities WHERE id = ?`)
156
+ .get(providedId);
157
+ }
158
+ if (!existing) {
159
+ existing = db
160
+ .prepare(`
161
+ SELECT ${ENTITY_COLUMNS}
162
+ FROM entities
163
+ WHERE COALESCE(project_id, '__SCOPE__:' || scope) = ?
164
+ AND entity_type = ?
165
+ AND lower(name) = lower(?)
166
+ LIMIT 1
167
+ `)
168
+ .get(dedupScopeKey, entityType, name);
169
+ }
170
+ let entityId;
171
+ if (existing) {
172
+ entityId = existing.id;
173
+ db.prepare(`
174
+ UPDATE entities
175
+ SET scope = ?,
176
+ project_id = ?,
177
+ entity_type = ?,
178
+ name = ?,
179
+ description = COALESCE(?, description),
180
+ external_ref = COALESCE(?, external_ref),
181
+ metadata_json = COALESCE(?, metadata_json),
182
+ user_id = COALESCE(?, user_id),
183
+ agent_id = COALESCE(?, agent_id),
184
+ updated_at = unixepoch()
185
+ WHERE id = ?
186
+ `).run(scoped.scope, scoped.projectId, entityType, name, description, externalRef, metadataJson, userId, agentId, entityId);
187
+ }
188
+ else {
189
+ entityId = providedId || `ent_${(0, crypto_1.randomUUID)().replace(/-/g, '').slice(0, 16)}`;
190
+ db.prepare(`
191
+ INSERT INTO entities (
192
+ id, scope, project_id, user_id, agent_id, entity_type, name,
193
+ description, external_ref, metadata_json, embedding
194
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, NULL)
195
+ `).run(entityId, scoped.scope, scoped.projectId, userId, agentId, entityType, name, description, externalRef, metadataJson);
196
+ }
197
+ (0, embedQueueStore_1.enqueueForEmbedding)(entityId, 'entity');
198
+ return db
199
+ .prepare(`SELECT ${ENTITY_COLUMNS} FROM entities WHERE id = ?`)
200
+ .get(entityId);
201
+ })();
202
+ }
203
+ /**
204
+ * Retrieve an entity by ID without returning its embedding BLOB.
205
+ */
206
+ function getEntity(id) {
207
+ const db = (0, db_1.getDb)();
208
+ return db
209
+ .prepare(`SELECT ${ENTITY_COLUMNS} FROM entities WHERE id = ?`)
210
+ .get(id);
211
+ }
212
+ /**
213
+ * List entities with optional hierarchical project scoping, user filtering,
214
+ * entity_type, and external_ref filters. Never filters on agent_id.
215
+ */
216
+ function listEntities(filters) {
217
+ const db = (0, db_1.getDb)();
218
+ const conditions = [];
219
+ const params = [];
220
+ const hasProjectId = typeof filters?.projectId === 'string' && filters.projectId.trim() !== '';
221
+ const hasScope = typeof filters?.scope === 'string' && filters.scope.trim() !== '';
222
+ let normalizedQueryProjectId = null;
223
+ if (hasProjectId || hasScope) {
224
+ const scopeSql = (0, scope_1.buildHierarchicalScopeSql)({
225
+ scope: hasScope ? filters.scope : undefined,
226
+ projectId: hasProjectId ? filters.projectId : undefined,
227
+ includeAncestors: filters?.includeAncestors ?? true,
228
+ includeChildren: filters?.includeChildren ?? false,
229
+ includeGlobal: filters?.includeGlobal ?? (hasProjectId ? true : false),
230
+ userId: filters?.userId,
231
+ });
232
+ conditions.push(scopeSql.clause);
233
+ params.push(...scopeSql.params);
234
+ normalizedQueryProjectId = scopeSql.normalizedProjectId;
235
+ }
236
+ else {
237
+ if (filters?.includeGlobal === false) {
238
+ conditions.push("scope != 'global'");
239
+ }
240
+ if (typeof filters?.userId === 'string' && filters.userId.trim() !== '') {
241
+ conditions.push('user_id = ?');
242
+ params.push(filters.userId.trim());
243
+ }
244
+ }
245
+ if (typeof filters?.entityType === 'string' && filters.entityType.trim() !== '') {
246
+ conditions.push('entity_type = ?');
247
+ params.push(filters.entityType.trim());
248
+ }
249
+ if (typeof filters?.externalRef === 'string' && filters.externalRef.trim() !== '') {
250
+ conditions.push('external_ref = ?');
251
+ params.push(filters.externalRef.trim());
252
+ }
253
+ const whereClause = conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '';
254
+ const limit = clampLimit(filters?.limit, 50, 200);
255
+ params.push(limit);
256
+ const rows = db
257
+ .prepare(`
258
+ SELECT ${ENTITY_COLUMNS}
259
+ FROM entities
260
+ ${whereClause}
261
+ ORDER BY updated_at DESC, created_at DESC, rowid DESC
262
+ LIMIT ?
263
+ `)
264
+ .all(...params);
265
+ return rows.map((row) => ({
266
+ ...row,
267
+ match_tier: (0, scope_1.classifyMatchTier)(row.scope, row.project_id, normalizedQueryProjectId).match_tier,
268
+ }));
269
+ }
270
+ function resolveNodeType(db, id) {
271
+ if (db.prepare('SELECT 1 FROM entities WHERE id = ?').get(id))
272
+ return 'entity';
273
+ const noteRow = db.prepare('SELECT type FROM notes WHERE id = ?').get(id);
274
+ if (noteRow)
275
+ return noteRow.type === 'lesson' ? 'lesson' : 'note';
276
+ if (db.prepare('SELECT 1 FROM actions WHERE id = ?').get(id))
277
+ return 'action';
278
+ if (db.prepare('SELECT 1 FROM sessions WHERE id = ?').get(id))
279
+ return 'session';
280
+ if (db.prepare('SELECT 1 FROM summaries WHERE id = ?').get(id))
281
+ return 'summary';
282
+ if (db.prepare('SELECT 1 FROM trajectories WHERE id = ?').get(id))
283
+ return 'trajectory';
284
+ if (db.prepare('SELECT 1 FROM observations WHERE id = ?').get(id))
285
+ return 'observation';
286
+ return null;
287
+ }
288
+ function resolveAndValidateEndpoint(db, explicitType, id, role) {
289
+ if (!explicitType) {
290
+ const resolved = resolveNodeType(db, id);
291
+ if (!resolved) {
292
+ throw makeError('NOT_FOUND', `${role} record '${id}' not found`);
293
+ }
294
+ return resolved;
295
+ }
296
+ const knownTable = KNOWN_NODE_TABLES[explicitType];
297
+ if (knownTable) {
298
+ const exists = db.prepare(`SELECT 1 FROM ${knownTable} WHERE id = ?`).get(id);
299
+ if (!exists) {
300
+ throw makeError('NOT_FOUND', `${role} ${explicitType} '${id}' not found`);
301
+ }
302
+ }
303
+ return explicitType;
304
+ }
305
+ /**
306
+ * Create or update a directed relational edge between any two graph nodes
307
+ * (including cross-subproject links). Auto-resolves source_type/target_type
308
+ * when omitted and verifies internal endpoints exist.
309
+ */
310
+ function linkEntities(input) {
311
+ const sourceId = optionalString(input.source_id !== undefined ? input.source_id : input.sourceId, 'source_id');
312
+ if (!sourceId) {
313
+ throw makeError('SCHEMA_INVALID', 'source_id is required and cannot be empty');
314
+ }
315
+ const targetId = optionalString(input.target_id !== undefined ? input.target_id : input.targetId, 'target_id');
316
+ if (!targetId) {
317
+ throw makeError('SCHEMA_INVALID', 'target_id is required and cannot be empty');
318
+ }
319
+ const relation = optionalString(input.relation, 'relation');
320
+ if (!relation) {
321
+ throw makeError('SCHEMA_INVALID', 'relation is required and cannot be empty');
322
+ }
323
+ const explicitSourceType = optionalString(input.source_type !== undefined ? input.source_type : input.sourceType, 'source_type');
324
+ const explicitTargetType = optionalString(input.target_type !== undefined ? input.target_type : input.targetType, 'target_type');
325
+ const metadataJson = serializeMetadata(input);
326
+ const db = (0, db_1.getDb)();
327
+ return (0, sqlite_1.transaction)(db, () => {
328
+ const sourceType = resolveAndValidateEndpoint(db, explicitSourceType, sourceId, 'source');
329
+ const targetType = resolveAndValidateEndpoint(db, explicitTargetType, targetId, 'target');
330
+ const id = `edge_${(0, crypto_1.randomUUID)().replace(/-/g, '').slice(0, 16)}`;
331
+ db.prepare(`
332
+ INSERT INTO entity_edges (
333
+ id, source_type, source_id, target_type, target_id, relation, metadata_json
334
+ ) VALUES (?, ?, ?, ?, ?, ?, ?)
335
+ ON CONFLICT(source_type, source_id, target_type, target_id, relation) DO UPDATE SET
336
+ metadata_json = COALESCE(excluded.metadata_json, entity_edges.metadata_json)
337
+ `).run(id, sourceType, sourceId, targetType, targetId, relation, metadataJson);
338
+ return db
339
+ .prepare(`
340
+ SELECT id, source_type, source_id, target_type, target_id, relation, metadata_json, created_at
341
+ FROM entity_edges
342
+ WHERE source_type = ? AND source_id = ? AND target_type = ? AND target_id = ? AND relation = ?
343
+ `)
344
+ .get(sourceType, sourceId, targetType, targetId, relation);
345
+ })();
346
+ }
347
+ /**
348
+ * Remove matching edges from entity_edges by edge id, source_id, and/or target_id
349
+ * (optionally narrowed by relation).
350
+ */
351
+ function unlinkEntities(input) {
352
+ const id = optionalString(input.id, 'id');
353
+ const sourceId = optionalString(input.source_id !== undefined ? input.source_id : input.sourceId, 'source_id');
354
+ const targetId = optionalString(input.target_id !== undefined ? input.target_id : input.targetId, 'target_id');
355
+ const relation = optionalString(input.relation, 'relation');
356
+ if (!id && !sourceId && !targetId) {
357
+ throw makeError('SCHEMA_INVALID', 'At least one of id, source_id, or target_id is required to unlink edges');
358
+ }
359
+ const conditions = [];
360
+ const params = [];
361
+ if (id) {
362
+ conditions.push('id = ?');
363
+ params.push(id);
364
+ }
365
+ if (sourceId) {
366
+ conditions.push('source_id = ?');
367
+ params.push(sourceId);
368
+ }
369
+ if (targetId) {
370
+ conditions.push('target_id = ?');
371
+ params.push(targetId);
372
+ }
373
+ if (relation) {
374
+ conditions.push('relation = ?');
375
+ params.push(relation);
376
+ }
377
+ const db = (0, db_1.getDb)();
378
+ const res = db
379
+ .prepare(`DELETE FROM entity_edges WHERE ${conditions.join(' AND ')}`)
380
+ .run(...params);
381
+ return { deleted: res.changes };
11
382
  }
12
383
  /**
13
384
  * Parse and bound HTTP query parameters for knowledge graph endpoints.
14
385
  */
15
386
  function parseGraphQuery(query) {
16
- const projectId = typeof query.project_id === 'string'
17
- ? query.project_id
18
- : typeof query.projectId === 'string'
19
- ? query.projectId
20
- : undefined;
21
- const scope = typeof query.scope === 'string' ? query.scope : undefined;
387
+ const rawProjectId = query.project_id ?? query.projectId;
388
+ const projectId = typeof rawProjectId === 'string' && rawProjectId.trim() !== ''
389
+ ? rawProjectId.trim()
390
+ : undefined;
391
+ const scope = typeof query.scope === 'string' && query.scope.trim() !== ''
392
+ ? query.scope.trim()
393
+ : undefined;
394
+ const includeAncestors = parseOptionalBool(query.include_ancestors ?? query.includeAncestors) ?? true;
395
+ const includeChildren = parseOptionalBool(query.include_children ?? query.includeChildren) ?? false;
396
+ const includeGlobal = parseOptionalBool(query.include_global ?? query.includeGlobal) ?? false;
397
+ const rawNodeId = query.node_id ?? query.nodeId;
398
+ const nodeId = typeof rawNodeId === 'string' && rawNodeId.trim() !== '' ? rawNodeId.trim() : undefined;
399
+ const rawEntityType = query.entity_type ?? query.entityType;
400
+ const entityType = typeof rawEntityType === 'string' && rawEntityType.trim() !== ''
401
+ ? rawEntityType.trim()
402
+ : undefined;
403
+ const relation = typeof query.relation === 'string' && query.relation.trim() !== ''
404
+ ? query.relation.trim()
405
+ : undefined;
406
+ const rawUserId = query.user_id ?? query.userId;
407
+ const userId = typeof rawUserId === 'string' && rawUserId.trim() !== '' ? rawUserId.trim() : undefined;
22
408
  const rawLimit = query.limit;
23
409
  const parsedLimit = rawLimit !== undefined && rawLimit !== null && rawLimit !== ''
24
410
  ? parseInt(String(rawLimit), 10)
@@ -26,192 +412,631 @@ function parseGraphQuery(query) {
26
412
  return {
27
413
  projectId,
28
414
  scope,
415
+ includeAncestors,
416
+ includeChildren,
417
+ includeGlobal,
418
+ depth: clampDepth(query.depth),
419
+ nodeId,
420
+ entityType,
421
+ relation,
422
+ userId,
29
423
  limit: clampLimit(parsedLimit),
30
424
  };
31
425
  }
32
- function buildScopeFilter(projectId, scope) {
33
- const conditions = [];
34
- const params = [];
35
- if (projectId !== undefined) {
36
- conditions.push('project_id = ?');
37
- params.push(projectId);
426
+ function noteToGraphNode(note, queryProjectId) {
427
+ return {
428
+ id: note.id,
429
+ type: note.type === 'lesson' ? 'lesson' : 'note',
430
+ label: note.title,
431
+ scope: note.scope,
432
+ project_id: note.project_id,
433
+ match_tier: (0, scope_1.classifyMatchTier)(note.scope, note.project_id, queryProjectId).match_tier,
434
+ user_id: note.user_id,
435
+ agent_id: note.agent_id,
436
+ meta: {
437
+ noteType: note.type,
438
+ version: note.version,
439
+ is_latest: note.is_latest,
440
+ event_at: note.event_at,
441
+ valid_from: note.valid_from,
442
+ valid_until: note.valid_until,
443
+ created_at: note.created_at,
444
+ },
445
+ };
446
+ }
447
+ function sessionToGraphNode(s, queryProjectId) {
448
+ return {
449
+ id: s.id,
450
+ type: 'session',
451
+ label: s.agent_name ? `${s.agent_name} (${s.status})` : s.id,
452
+ scope: s.scope,
453
+ project_id: s.project_id,
454
+ match_tier: (0, scope_1.classifyMatchTier)(s.scope, s.project_id, queryProjectId).match_tier,
455
+ user_id: s.user_id,
456
+ agent_id: s.agent_id,
457
+ meta: {
458
+ status: s.status,
459
+ agent_name: s.agent_name,
460
+ started_at: s.started_at,
461
+ ended_at: s.ended_at,
462
+ },
463
+ };
464
+ }
465
+ function actionToGraphNode(a, queryProjectId) {
466
+ return {
467
+ id: a.id,
468
+ type: 'action',
469
+ label: a.title,
470
+ scope: a.scope,
471
+ project_id: a.project_id,
472
+ match_tier: (0, scope_1.classifyMatchTier)(a.scope, a.project_id, queryProjectId).match_tier,
473
+ user_id: a.user_id,
474
+ agent_id: a.agent_id,
475
+ meta: {
476
+ status: a.status,
477
+ priority: a.priority,
478
+ due_at: a.due_at,
479
+ remind_at: a.remind_at,
480
+ recurrence: a.recurrence,
481
+ created_at: a.created_at,
482
+ },
483
+ };
484
+ }
485
+ function summaryToGraphNode(sum, queryProjectId) {
486
+ return {
487
+ id: sum.id,
488
+ type: 'summary',
489
+ label: `${sum.kind} (${sum.outcome ?? 'unknown'})`,
490
+ scope: sum.scope,
491
+ project_id: sum.project_id,
492
+ match_tier: (0, scope_1.classifyMatchTier)(sum.scope, sum.project_id, queryProjectId).match_tier,
493
+ user_id: sum.user_id,
494
+ agent_id: sum.agent_id,
495
+ meta: {
496
+ kind: sum.kind,
497
+ outcome: sum.outcome,
498
+ producer_tier: sum.producer_tier,
499
+ verified: sum.verified,
500
+ created_at: sum.created_at,
501
+ },
502
+ };
503
+ }
504
+ function entityToGraphNode(ent, queryProjectId) {
505
+ const parsedMeta = tryParseJson(ent.metadata_json);
506
+ return {
507
+ id: ent.id,
508
+ type: 'entity',
509
+ label: ent.name,
510
+ scope: ent.scope,
511
+ project_id: ent.project_id,
512
+ entity_type: ent.entity_type,
513
+ external_ref: ent.external_ref,
514
+ match_tier: (0, scope_1.classifyMatchTier)(ent.scope, ent.project_id, queryProjectId).match_tier,
515
+ user_id: ent.user_id,
516
+ agent_id: ent.agent_id,
517
+ meta: {
518
+ entity_type: ent.entity_type,
519
+ description: ent.description,
520
+ external_ref: ent.external_ref,
521
+ ...(parsedMeta ? { metadata: parsedMeta } : {}),
522
+ created_at: ent.created_at,
523
+ updated_at: ent.updated_at,
524
+ },
525
+ };
526
+ }
527
+ function trajectoryToGraphNode(traj, queryProjectId) {
528
+ const snippet = traj.description.length > 60 ? `${traj.description.slice(0, 57)}...` : traj.description;
529
+ return {
530
+ id: traj.id,
531
+ type: 'trajectory',
532
+ label: traj.task_type ? `${traj.task_type}: ${snippet}` : snippet,
533
+ scope: traj.scope,
534
+ project_id: traj.project_id,
535
+ match_tier: (0, scope_1.classifyMatchTier)(traj.scope, traj.project_id, queryProjectId).match_tier,
536
+ user_id: traj.user_id,
537
+ agent_id: traj.agent_id,
538
+ meta: {
539
+ task_type: traj.task_type,
540
+ agent: traj.agent,
541
+ success: traj.success,
542
+ rollup_source: traj.rollup_source,
543
+ created_at: traj.created_at,
544
+ },
545
+ };
546
+ }
547
+ function observationToGraphNode(obs, queryProjectId) {
548
+ return {
549
+ id: obs.id,
550
+ type: 'observation',
551
+ label: obs.tool_name ? `${obs.kind}: ${obs.tool_name}` : obs.kind,
552
+ scope: obs.scope,
553
+ project_id: obs.project_id,
554
+ match_tier: (0, scope_1.classifyMatchTier)(obs.scope, obs.project_id, queryProjectId).match_tier,
555
+ user_id: obs.user_id,
556
+ agent_id: obs.agent_id,
557
+ meta: {
558
+ kind: obs.kind,
559
+ tool_name: obs.tool_name,
560
+ file_path: obs.file_path,
561
+ failed: obs.failed,
562
+ created_at: obs.created_at,
563
+ },
564
+ };
565
+ }
566
+ function userAllowed(rowUserId, filterUserId) {
567
+ if (!filterUserId)
568
+ return true;
569
+ return rowUserId === null || rowUserId === undefined || rowUserId === filterUserId;
570
+ }
571
+ function hydrateNodesByIds(db, targets, queryProjectId, filterUserId) {
572
+ const nodes = [];
573
+ const notes = [];
574
+ const actions = [];
575
+ const summaries = [];
576
+ if (targets.length === 0)
577
+ return { nodes, notes, actions, summaries };
578
+ const grouped = new Map();
579
+ const untypedIds = [];
580
+ for (const t of targets) {
581
+ if (!t.typeHint) {
582
+ untypedIds.push(t.id);
583
+ continue;
584
+ }
585
+ const bucket = t.typeHint === 'lesson' ? 'note' : t.typeHint;
586
+ const list = grouped.get(bucket) ?? [];
587
+ list.push(t.id);
588
+ grouped.set(bucket, list);
38
589
  }
39
- if (scope !== undefined) {
40
- conditions.push('scope = ?');
41
- params.push(scope);
590
+ for (const uid of untypedIds) {
591
+ const resolved = resolveNodeType(db, uid);
592
+ if (resolved) {
593
+ const bucket = resolved === 'lesson' ? 'note' : resolved;
594
+ const list = grouped.get(bucket) ?? [];
595
+ list.push(uid);
596
+ grouped.set(bucket, list);
597
+ }
598
+ else if (uid.startsWith('concept:')) {
599
+ nodes.push({ id: uid, type: 'concept', label: uid.slice('concept:'.length) });
600
+ }
601
+ else if (uid.startsWith('file:')) {
602
+ nodes.push({ id: uid, type: 'file', label: uid.slice('file:'.length) });
603
+ }
604
+ else {
605
+ const edgeHint = db
606
+ .prepare(`
607
+ SELECT source_type AS ext_type FROM entity_edges WHERE source_id = ?
608
+ UNION ALL
609
+ SELECT target_type AS ext_type FROM entity_edges WHERE target_id = ?
610
+ LIMIT 1
611
+ `)
612
+ .get(uid, uid);
613
+ if (edgeHint && !KNOWN_NODE_TABLES[edgeHint.ext_type]) {
614
+ nodes.push({
615
+ id: uid,
616
+ type: 'entity',
617
+ label: uid,
618
+ entity_type: edgeHint.ext_type,
619
+ meta: { external_type: edgeHint.ext_type },
620
+ });
621
+ }
622
+ }
42
623
  }
43
- return {
44
- where: conditions.length > 0 ? `WHERE ${conditions.join(' AND ')}` : '',
45
- params,
624
+ const chunkedQuery = (ids, sqlBuilder) => {
625
+ const results = [];
626
+ const CHUNK = 400;
627
+ for (let i = 0; i < ids.length; i += CHUNK) {
628
+ const slice = ids.slice(i, i + CHUNK);
629
+ const placeholders = slice.map(() => '?').join(',');
630
+ results.push(...db.prepare(sqlBuilder(placeholders)).all(...slice));
631
+ }
632
+ return results;
46
633
  };
634
+ const entityIds = grouped.get('entity');
635
+ if (entityIds?.length) {
636
+ const rows = chunkedQuery(entityIds, (ph) => `SELECT ${ENTITY_COLUMNS} FROM entities WHERE id IN (${ph})`);
637
+ for (const row of rows) {
638
+ if (!userAllowed(row.user_id, filterUserId))
639
+ continue;
640
+ nodes.push(entityToGraphNode(row, queryProjectId));
641
+ }
642
+ }
643
+ const noteIds = grouped.get('note');
644
+ if (noteIds?.length) {
645
+ const rows = chunkedQuery(noteIds, (ph) => `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})`);
646
+ for (const row of rows) {
647
+ if (!userAllowed(row.user_id, filterUserId))
648
+ continue;
649
+ notes.push(row);
650
+ nodes.push(noteToGraphNode(row, queryProjectId));
651
+ }
652
+ }
653
+ const actionIds = grouped.get('action');
654
+ if (actionIds?.length) {
655
+ const rows = chunkedQuery(actionIds, (ph) => `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})`);
656
+ for (const row of rows) {
657
+ if (!userAllowed(row.user_id, filterUserId))
658
+ continue;
659
+ actions.push(row);
660
+ nodes.push(actionToGraphNode(row, queryProjectId));
661
+ }
662
+ }
663
+ const sessionIds = grouped.get('session');
664
+ if (sessionIds?.length) {
665
+ const rows = chunkedQuery(sessionIds, (ph) => `SELECT id, scope, project_id, user_id, agent_id, agent_name, status, started_at, ended_at FROM sessions WHERE id IN (${ph})`);
666
+ for (const row of rows) {
667
+ if (!userAllowed(row.user_id, filterUserId))
668
+ continue;
669
+ nodes.push(sessionToGraphNode(row, queryProjectId));
670
+ }
671
+ }
672
+ const summaryIds = grouped.get('summary');
673
+ if (summaryIds?.length) {
674
+ const rows = chunkedQuery(summaryIds, (ph) => `SELECT id, scope, project_id, user_id, agent_id, kind, outcome, producer_tier, verified, created_at FROM summaries WHERE id IN (${ph})`);
675
+ for (const row of rows) {
676
+ if (!userAllowed(row.user_id, filterUserId))
677
+ continue;
678
+ summaries.push(row);
679
+ nodes.push(summaryToGraphNode(row, queryProjectId));
680
+ }
681
+ }
682
+ const trajectoryIds = grouped.get('trajectory');
683
+ if (trajectoryIds?.length) {
684
+ const rows = chunkedQuery(trajectoryIds, (ph) => `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})`);
685
+ for (const row of rows) {
686
+ if (!userAllowed(row.user_id, filterUserId))
687
+ continue;
688
+ nodes.push(trajectoryToGraphNode(row, queryProjectId));
689
+ }
690
+ }
691
+ const observationIds = grouped.get('observation');
692
+ if (observationIds?.length) {
693
+ const rows = chunkedQuery(observationIds, (ph) => `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})`);
694
+ for (const row of rows) {
695
+ if (!userAllowed(row.user_id, filterUserId))
696
+ continue;
697
+ nodes.push(observationToGraphNode(row, queryProjectId));
698
+ }
699
+ }
700
+ for (const [typeHint, ids] of grouped.entries()) {
701
+ if (KNOWN_NODE_TABLES[typeHint])
702
+ continue;
703
+ for (const id of ids) {
704
+ if (typeHint === 'concept') {
705
+ nodes.push({ id, type: 'concept', label: id.replace(/^concept:/, '') });
706
+ }
707
+ else if (typeHint === 'file') {
708
+ nodes.push({ id, type: 'file', label: id.replace(/^file:/, '') });
709
+ }
710
+ else {
711
+ nodes.push({
712
+ id,
713
+ type: 'entity',
714
+ label: id,
715
+ entity_type: typeHint,
716
+ meta: { external_type: typeHint },
717
+ });
718
+ }
719
+ }
720
+ }
721
+ return { nodes, notes, actions, summaries };
47
722
  }
48
723
  /**
49
724
  * Build a scoped knowledge graph from notes, concepts, files, sessions,
50
- * actions, summaries, and summary citations stored in SQLite.
725
+ * actions, summaries, entities, trajectories, observations, and entity_edges
726
+ * stored in SQLite, with hierarchical scoping and 1..3 hop cross-subproject BFS.
51
727
  */
52
728
  function getKnowledgeGraph(options = {}) {
53
729
  const db = (0, db_1.getDb)();
54
730
  const limit = clampLimit(options.limit);
55
- const projectId = typeof options.projectId === 'string' && options.projectId.trim()
731
+ const depth = clampDepth(options.depth);
732
+ const projectId = typeof options.projectId === 'string' && options.projectId.trim() !== ''
56
733
  ? options.projectId.trim()
57
734
  : undefined;
58
- const scope = typeof options.scope === 'string' && options.scope.trim()
735
+ const scope = typeof options.scope === 'string' && options.scope.trim() !== ''
59
736
  ? options.scope.trim()
60
737
  : undefined;
61
- const { where, params } = buildScopeFilter(projectId, scope);
738
+ const includeAncestors = options.includeAncestors ?? true;
739
+ const includeChildren = options.includeChildren ?? false;
740
+ const includeGlobal = options.includeGlobal ?? false;
741
+ const nodeId = typeof options.nodeId === 'string' && options.nodeId.trim() !== ''
742
+ ? options.nodeId.trim()
743
+ : undefined;
744
+ const entityType = typeof options.entityType === 'string' && options.entityType.trim() !== ''
745
+ ? options.entityType.trim()
746
+ : undefined;
747
+ const relationFilter = typeof options.relation === 'string' && options.relation.trim() !== ''
748
+ ? options.relation.trim()
749
+ : undefined;
750
+ const userId = typeof options.userId === 'string' && options.userId.trim() !== ''
751
+ ? options.userId.trim()
752
+ : undefined;
753
+ let normalizedProjectId = null;
754
+ if (projectId) {
755
+ const norm = (0, scope_1.normalizeProjectId)(projectId);
756
+ normalizedProjectId = norm.ok ? norm.projectId : projectId;
757
+ }
758
+ let where = '';
759
+ let params = [];
760
+ if (projectId !== undefined || scope !== undefined) {
761
+ const scopeSql = (0, scope_1.buildHierarchicalScopeSql)({
762
+ scope,
763
+ projectId,
764
+ includeAncestors,
765
+ includeChildren,
766
+ includeGlobal,
767
+ userId,
768
+ });
769
+ where = `WHERE ${scopeSql.clause}`;
770
+ params = scopeSql.params;
771
+ normalizedProjectId = scopeSql.normalizedProjectId;
772
+ }
773
+ else if (userId !== undefined) {
774
+ where = 'WHERE user_id = ?';
775
+ params = [userId];
776
+ }
62
777
  const nodeMap = new Map();
63
778
  const edgeKeys = new Set();
64
779
  const edges = [];
780
+ const maxNodes = limit * 6;
781
+ const maxEdges = limit * 10;
65
782
  const addNode = (node) => {
66
- if (!nodeMap.has(node.id)) {
67
- nodeMap.set(node.id, node);
68
- }
783
+ if (nodeMap.has(node.id))
784
+ return true;
785
+ if (nodeMap.size >= maxNodes)
786
+ return false;
787
+ nodeMap.set(node.id, node);
788
+ return true;
69
789
  };
70
- const addEdge = (source, target, type) => {
790
+ const addEdge = (source, target, type, meta) => {
791
+ if (edges.length >= maxEdges)
792
+ return false;
71
793
  if (!nodeMap.has(source) || !nodeMap.has(target))
72
- return;
794
+ return false;
73
795
  const key = `${source}\0${type}\0${target}`;
74
796
  if (!edgeKeys.has(key)) {
75
797
  edgeKeys.add(key);
76
- edges.push({ source, target, type });
798
+ edges.push(meta ? { source, target, type, meta } : { source, target, type });
77
799
  }
800
+ return true;
78
801
  };
79
- const noteRows = db
80
- .prepare(`
81
- SELECT id, scope, project_id, session_id, type, title, version, supersedes, is_latest, created_at
82
- FROM notes
83
- ${where}
84
- ORDER BY updated_at DESC
85
- LIMIT ?
86
- `)
87
- .all(...params, limit);
88
- for (const note of noteRows) {
89
- const nodeType = note.type === 'lesson' ? 'lesson' : 'note';
90
- addNode({
91
- id: note.id,
92
- type: nodeType,
93
- label: note.title,
94
- scope: note.scope,
95
- project_id: note.project_id,
96
- meta: {
97
- noteType: note.type,
98
- version: note.version,
99
- is_latest: note.is_latest,
100
- created_at: note.created_at,
101
- },
102
- });
103
- }
104
- const sessionRows = db
105
- .prepare(`
106
- SELECT id, scope, project_id, agent_name, status, started_at, ended_at
107
- FROM sessions
108
- ${where}
109
- ORDER BY started_at DESC
110
- LIMIT ?
111
- `)
112
- .all(...params, limit);
113
- for (const s of sessionRows) {
114
- addNode({
115
- id: s.id,
116
- type: 'session',
117
- label: s.agent_name ? `${s.agent_name} (${s.status})` : s.id,
118
- scope: s.scope,
119
- project_id: s.project_id,
120
- meta: {
121
- status: s.status,
122
- agent_name: s.agent_name,
123
- started_at: s.started_at,
124
- ended_at: s.ended_at,
125
- },
126
- });
802
+ let seedNoteRows = [];
803
+ let seedActionRows = [];
804
+ let seedSummaryRows = [];
805
+ const allNoteRows = new Map();
806
+ const allActionRows = new Map();
807
+ const allSummaryRows = new Map();
808
+ if (nodeId) {
809
+ const hydratedSeed = hydrateNodesByIds(db, [{ id: nodeId }], normalizedProjectId, userId);
810
+ for (const node of hydratedSeed.nodes) {
811
+ addNode(node);
812
+ }
813
+ seedNoteRows = hydratedSeed.notes;
814
+ seedActionRows = hydratedSeed.actions;
815
+ seedSummaryRows = hydratedSeed.summaries;
816
+ for (const n of hydratedSeed.notes)
817
+ allNoteRows.set(n.id, n);
818
+ for (const a of hydratedSeed.actions)
819
+ allActionRows.set(a.id, a);
820
+ for (const s of hydratedSeed.summaries)
821
+ allSummaryRows.set(s.id, s);
127
822
  }
128
- const actionRows = db
129
- .prepare(`
130
- SELECT id, session_id, scope, project_id, title, status, priority, created_at
131
- FROM actions
132
- ${where}
133
- ORDER BY created_at DESC
134
- LIMIT ?
135
- `)
136
- .all(...params, limit);
137
- for (const a of actionRows) {
138
- addNode({
139
- id: a.id,
140
- type: 'action',
141
- label: a.title,
142
- scope: a.scope,
143
- project_id: a.project_id,
144
- meta: {
145
- status: a.status,
146
- priority: a.priority,
147
- created_at: a.created_at,
148
- },
149
- });
823
+ else {
824
+ seedNoteRows = db
825
+ .prepare(`
826
+ SELECT id, scope, project_id, user_id, agent_id, session_id, type, title,
827
+ version, supersedes, is_latest, event_at, valid_from, valid_until, created_at
828
+ FROM notes
829
+ ${where}
830
+ ORDER BY updated_at DESC
831
+ LIMIT ?
832
+ `)
833
+ .all(...params, limit);
834
+ for (const note of seedNoteRows) {
835
+ allNoteRows.set(note.id, note);
836
+ addNode(noteToGraphNode(note, normalizedProjectId));
837
+ }
838
+ const sessionRows = db
839
+ .prepare(`
840
+ SELECT id, scope, project_id, user_id, agent_id, agent_name, status, started_at, ended_at
841
+ FROM sessions
842
+ ${where}
843
+ ORDER BY started_at DESC
844
+ LIMIT ?
845
+ `)
846
+ .all(...params, limit);
847
+ for (const s of sessionRows) {
848
+ addNode(sessionToGraphNode(s, normalizedProjectId));
849
+ }
850
+ seedActionRows = db
851
+ .prepare(`
852
+ SELECT id, session_id, scope, project_id, user_id, agent_id, title, status,
853
+ priority, due_at, remind_at, recurrence, created_at
854
+ FROM actions
855
+ ${where}
856
+ ORDER BY created_at DESC
857
+ LIMIT ?
858
+ `)
859
+ .all(...params, limit);
860
+ for (const a of seedActionRows) {
861
+ allActionRows.set(a.id, a);
862
+ addNode(actionToGraphNode(a, normalizedProjectId));
863
+ }
864
+ seedSummaryRows = db
865
+ .prepare(`
866
+ SELECT id, scope, project_id, user_id, agent_id, kind, outcome, producer_tier, verified, created_at
867
+ FROM summaries
868
+ ${where}
869
+ ORDER BY created_at DESC
870
+ LIMIT ?
871
+ `)
872
+ .all(...params, limit);
873
+ for (const sum of seedSummaryRows) {
874
+ allSummaryRows.set(sum.id, sum);
875
+ addNode(summaryToGraphNode(sum, normalizedProjectId));
876
+ }
877
+ const entityConditions = [];
878
+ const entityParams = [...params];
879
+ if (where) {
880
+ entityConditions.push(where.replace(/^WHERE\s+/i, ''));
881
+ }
882
+ if (entityType) {
883
+ entityConditions.push('entity_type = ?');
884
+ entityParams.push(entityType);
885
+ }
886
+ const entityWhere = entityConditions.length > 0 ? `WHERE ${entityConditions.join(' AND ')}` : '';
887
+ const entityRows = db
888
+ .prepare(`
889
+ SELECT ${ENTITY_COLUMNS}
890
+ FROM entities
891
+ ${entityWhere}
892
+ ORDER BY updated_at DESC, created_at DESC
893
+ LIMIT ?
894
+ `)
895
+ .all(...entityParams, limit);
896
+ for (const ent of entityRows) {
897
+ addNode(entityToGraphNode(ent, normalizedProjectId));
898
+ }
150
899
  }
151
- const summaryRows = db
152
- .prepare(`
153
- SELECT id, scope, project_id, kind, outcome, producer_tier, verified, created_at
154
- FROM summaries
155
- ${where}
156
- ORDER BY created_at DESC
157
- LIMIT ?
158
- `)
159
- .all(...params, limit);
160
- for (const sum of summaryRows) {
161
- addNode({
162
- id: sum.id,
163
- type: 'summary',
164
- label: `${sum.kind} (${sum.outcome ?? 'unknown'})`,
165
- scope: sum.scope,
166
- project_id: sum.project_id,
167
- meta: {
168
- kind: sum.kind,
169
- outcome: sum.outcome,
170
- producer_tier: sum.producer_tier,
171
- verified: sum.verified,
172
- created_at: sum.created_at,
173
- },
174
- });
900
+ // Multi-hop BFS traversal over entity_edges (1..depth hops across any subproject)
901
+ let frontier = Array.from(nodeMap.keys());
902
+ const visited = new Set(frontier);
903
+ for (let hop = 1; hop <= depth; hop++) {
904
+ if (frontier.length === 0 || nodeMap.size >= maxNodes || edges.length >= maxEdges) {
905
+ break;
906
+ }
907
+ const hopEdges = [];
908
+ const seenEdgeIds = new Set();
909
+ const CHUNK = 400;
910
+ for (let i = 0; i < frontier.length; i += CHUNK) {
911
+ const slice = frontier.slice(i, i + CHUNK);
912
+ const placeholders = slice.map(() => '?').join(',');
913
+ const edgeSql = relationFilter
914
+ ? `
915
+ SELECT id, source_type, source_id, target_type, target_id, relation, metadata_json, created_at
916
+ FROM entity_edges
917
+ WHERE (source_id IN (${placeholders}) OR target_id IN (${placeholders}))
918
+ AND relation = ?
919
+ ORDER BY created_at DESC, id ASC
920
+ `
921
+ : `
922
+ SELECT id, source_type, source_id, target_type, target_id, relation, metadata_json, created_at
923
+ FROM entity_edges
924
+ WHERE (source_id IN (${placeholders}) OR target_id IN (${placeholders}))
925
+ ORDER BY created_at DESC, id ASC
926
+ `;
927
+ const edgeParams = relationFilter
928
+ ? [...slice, ...slice, relationFilter]
929
+ : [...slice, ...slice];
930
+ const rows = db.prepare(edgeSql).all(...edgeParams);
931
+ for (const row of rows) {
932
+ if (!seenEdgeIds.has(row.id)) {
933
+ seenEdgeIds.add(row.id);
934
+ hopEdges.push(row);
935
+ }
936
+ }
937
+ }
938
+ const toHydrate = [];
939
+ const queuedForHydration = new Set();
940
+ for (const edge of hopEdges) {
941
+ if (!nodeMap.has(edge.source_id) && !visited.has(edge.source_id) && !queuedForHydration.has(edge.source_id)) {
942
+ queuedForHydration.add(edge.source_id);
943
+ visited.add(edge.source_id);
944
+ toHydrate.push({ id: edge.source_id, typeHint: edge.source_type });
945
+ }
946
+ if (!nodeMap.has(edge.target_id) && !visited.has(edge.target_id) && !queuedForHydration.has(edge.target_id)) {
947
+ queuedForHydration.add(edge.target_id);
948
+ visited.add(edge.target_id);
949
+ toHydrate.push({ id: edge.target_id, typeHint: edge.target_type });
950
+ }
951
+ }
952
+ const nextFrontier = [];
953
+ if (toHydrate.length > 0 && nodeMap.size < maxNodes) {
954
+ const hydrated = hydrateNodesByIds(db, toHydrate, normalizedProjectId, userId);
955
+ for (const node of hydrated.nodes) {
956
+ if (!nodeMap.has(node.id) && addNode(node)) {
957
+ nextFrontier.push(node.id);
958
+ }
959
+ }
960
+ for (const n of hydrated.notes)
961
+ allNoteRows.set(n.id, n);
962
+ for (const a of hydrated.actions)
963
+ allActionRows.set(a.id, a);
964
+ for (const s of hydrated.summaries)
965
+ allSummaryRows.set(s.id, s);
966
+ }
967
+ for (const edge of hopEdges) {
968
+ addEdge(edge.source_id, edge.target_id, edge.relation, tryParseJson(edge.metadata_json));
969
+ }
970
+ frontier = nextFrontier;
175
971
  }
176
- if (noteRows.length > 0) {
177
- const noteIds = noteRows.map((n) => n.id);
178
- const placeholders = noteIds.map(() => '?').join(',');
179
- const conceptRows = db
180
- .prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders})`)
181
- .all(...noteIds);
182
- for (const row of conceptRows) {
183
- const conceptId = `concept:${row.concept}`;
184
- addNode({ id: conceptId, type: 'concept', label: row.concept });
185
- addEdge(row.note_id, conceptId, 'has_concept');
186
- }
187
- const fileRows = db
188
- .prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders})`)
189
- .all(...noteIds);
190
- for (const row of fileRows) {
191
- const fileId = `file:${row.file_path}`;
192
- addNode({ id: fileId, type: 'file', label: row.file_path });
193
- addEdge(row.note_id, fileId, 'touches_file');
194
- }
195
- for (const note of noteRows) {
196
- if (note.supersedes) {
197
- addEdge(note.id, note.supersedes, 'supersedes');
972
+ // Synthesized structural edges (preserve exact { source, target, type } shape)
973
+ const allowEdgeType = (edgeType) => !relationFilter || relationFilter === edgeType;
974
+ if (seedNoteRows.length > 0 && (!relationFilter || SYNTHETIC_EDGE_TYPES.has(relationFilter))) {
975
+ const seedNoteIds = seedNoteRows.map((n) => n.id);
976
+ const placeholders = seedNoteIds.map(() => '?').join(',');
977
+ if (allowEdgeType('has_concept')) {
978
+ const conceptRows = db
979
+ .prepare(`SELECT note_id, concept FROM note_concepts WHERE note_id IN (${placeholders}) LIMIT ?`)
980
+ .all(...seedNoteIds, maxNodes);
981
+ for (const row of conceptRows) {
982
+ const conceptId = `concept:${row.concept}`;
983
+ if (addNode({ id: conceptId, type: 'concept', label: row.concept })) {
984
+ addEdge(row.note_id, conceptId, 'has_concept');
985
+ }
198
986
  }
199
- if (note.session_id) {
200
- addEdge(note.id, note.session_id, 'from_session');
987
+ }
988
+ if (allowEdgeType('touches_file')) {
989
+ const fileRows = db
990
+ .prepare(`SELECT note_id, file_path FROM note_files WHERE note_id IN (${placeholders}) LIMIT ?`)
991
+ .all(...seedNoteIds, maxNodes);
992
+ for (const row of fileRows) {
993
+ const fileId = `file:${row.file_path}`;
994
+ if (addNode({ id: fileId, type: 'file', label: row.file_path })) {
995
+ addEdge(row.note_id, fileId, 'touches_file');
996
+ }
201
997
  }
202
998
  }
203
999
  }
204
- for (const action of actionRows) {
205
- if (action.session_id) {
1000
+ for (const note of allNoteRows.values()) {
1001
+ if (note.supersedes && allowEdgeType('supersedes')) {
1002
+ addEdge(note.id, note.supersedes, 'supersedes');
1003
+ }
1004
+ if (note.session_id && allowEdgeType('from_session')) {
1005
+ addEdge(note.id, note.session_id, 'from_session');
1006
+ }
1007
+ }
1008
+ for (const action of allActionRows.values()) {
1009
+ if (action.session_id && allowEdgeType('from_session')) {
206
1010
  addEdge(action.id, action.session_id, 'from_session');
207
1011
  }
208
1012
  }
209
- if (summaryRows.length > 0) {
210
- const summaryIds = summaryRows.map((s) => s.id);
1013
+ if (allSummaryRows.size > 0 && allowEdgeType('cites_source')) {
1014
+ const summaryIds = Array.from(allSummaryRows.keys());
211
1015
  const placeholders = summaryIds.map(() => '?').join(',');
212
1016
  const sourceRows = db
213
- .prepare(`SELECT DISTINCT summary_id, record_id FROM summary_sources WHERE summary_id IN (${placeholders})`)
214
- .all(...summaryIds);
1017
+ .prepare(`SELECT DISTINCT summary_id, record_id, record_type FROM summary_sources WHERE summary_id IN (${placeholders}) LIMIT ?`)
1018
+ .all(...summaryIds, maxNodes);
1019
+ // Load cited observation nodes from seed summaries within the remaining node budget
1020
+ const seedSummaryIdSet = new Set(seedSummaryRows.map((s) => s.id));
1021
+ const remainingBudget = maxNodes - nodeMap.size;
1022
+ if (remainingBudget > 0 && seedSummaryIdSet.size > 0) {
1023
+ const citedObsIds = Array.from(new Set(sourceRows
1024
+ .filter((r) => seedSummaryIdSet.has(r.summary_id) &&
1025
+ r.record_type === 'observation' &&
1026
+ !nodeMap.has(r.record_id))
1027
+ .map((r) => r.record_id))).slice(0, remainingBudget);
1028
+ if (citedObsIds.length > 0) {
1029
+ const obsPlaceholders = citedObsIds.map(() => '?').join(',');
1030
+ const obsRows = db
1031
+ .prepare(`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 ?`)
1032
+ .all(...citedObsIds, remainingBudget);
1033
+ for (const obs of obsRows) {
1034
+ if (!userAllowed(obs.user_id, userId))
1035
+ continue;
1036
+ addNode(observationToGraphNode(obs, normalizedProjectId));
1037
+ }
1038
+ }
1039
+ }
215
1040
  for (const row of sourceRows) {
216
1041
  addEdge(row.summary_id, row.record_id, 'cites_source');
217
1042
  }