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
package/src/lib/db.ts CHANGED
@@ -108,11 +108,212 @@ export function resetDb(): void {
108
108
  }
109
109
  }
110
110
 
111
+ /**
112
+ * Runs `fn` with `getDb()` pointed at a fresh, migrated database in a new temp
113
+ * directory, then restores the previous connection (open or not) and
114
+ * `DATABASE_URL`, and deletes the temp directory.
115
+ *
116
+ * This is how code outside the service exercises store logic that writes
117
+ * (the doctor's AI conformance fixtures) without becoming a second writer on
118
+ * the real database file.
119
+ */
120
+ export function withIsolatedDb<T>(fn: () => T): T {
121
+ const previousDb = _db;
122
+ const hadUrl = Object.prototype.hasOwnProperty.call(process.env, 'DATABASE_URL');
123
+ const previousUrl = process.env.DATABASE_URL;
124
+ const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'brain-isolated-'));
125
+
126
+ _db = null;
127
+ process.env.DATABASE_URL = path.join(dir, 'isolated.db');
128
+ try {
129
+ return fn();
130
+ } finally {
131
+ // fn() may have opened the throwaway connection; TS cannot see that.
132
+ const opened = _db as Database | null;
133
+ if (opened) {
134
+ try {
135
+ opened.close();
136
+ } catch {
137
+ // ignore close errors on the throwaway connection
138
+ }
139
+ }
140
+ _db = previousDb;
141
+ if (hadUrl) process.env.DATABASE_URL = previousUrl;
142
+ else delete process.env.DATABASE_URL;
143
+ fs.rmSync(dir, { recursive: true, force: true });
144
+ }
145
+ }
146
+
111
147
  export function initDb(): void {
112
148
  getDb();
113
149
  logger.info('database initialized');
114
150
  }
115
151
 
152
+ interface ColumnInfo {
153
+ name: string;
154
+ notnull: number;
155
+ }
156
+
157
+ function tableColumns(db: Database, table: string): ColumnInfo[] {
158
+ return db.prepare(`PRAGMA table_info(${table})`).all() as ColumnInfo[];
159
+ }
160
+
161
+ function ensureColumns(
162
+ db: Database,
163
+ table: string,
164
+ columns: Array<{ name: string; ddl: string; backfill?: string }>
165
+ ): void {
166
+ const existing = new Set(tableColumns(db, table).map((c) => c.name));
167
+ for (const col of columns) {
168
+ if (existing.has(col.name)) continue;
169
+ db.exec(`ALTER TABLE ${table} ADD COLUMN ${col.name} ${col.ddl}`);
170
+ if (col.backfill) db.exec(col.backfill);
171
+ logger.info({ table, column: col.name }, `${table} schema: column added`);
172
+ }
173
+ }
174
+
175
+ function rebuildTable(
176
+ db: Database,
177
+ table: string,
178
+ legacyName: string,
179
+ createDdl: string,
180
+ indexDdl?: string
181
+ ): void {
182
+ db.exec(`DROP TABLE IF EXISTS ${legacyName}`);
183
+ pragma(db, 'foreign_keys = OFF');
184
+ try {
185
+ transaction(db, () => {
186
+ db.exec(`ALTER TABLE ${table} RENAME TO ${legacyName}`);
187
+ db.exec(createDdl);
188
+ const oldCols = new Set(tableColumns(db, legacyName).map((c) => c.name));
189
+ const shared = tableColumns(db, table)
190
+ .map((c) => c.name)
191
+ .filter((name) => oldCols.has(name));
192
+ const list = shared.join(', ');
193
+ db.exec(`INSERT INTO ${table} (${list}) SELECT ${list} FROM ${legacyName}`);
194
+ db.exec(`DROP TABLE ${legacyName}`);
195
+ if (indexDdl) db.exec(indexDdl);
196
+ })();
197
+ } finally {
198
+ pragma(db, 'foreign_keys = ON');
199
+ }
200
+ }
201
+
202
+ const OBSERVATIONS_DDL = `
203
+ CREATE TABLE IF NOT EXISTS observations (
204
+ id TEXT PRIMARY KEY,
205
+ scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
206
+ project_id TEXT,
207
+ user_id TEXT,
208
+ agent_id TEXT,
209
+ note_ref TEXT, -- -> notes.id, optional
210
+ task_ref TEXT, -- provenance only, not a scope filter
211
+ session_id TEXT,
212
+ agent TEXT,
213
+ kind TEXT NOT NULL CHECK (kind IN ('tool_call','prompt','response')),
214
+ tool_name TEXT,
215
+ file_path TEXT, -- the tool's TARGET path, nothing else
216
+ input TEXT,
217
+ output TEXT,
218
+ condensed_text TEXT,
219
+ resolved_dates_json TEXT,
220
+ signal_tags TEXT,
221
+ duration_ms INTEGER NOT NULL DEFAULT 0,
222
+ failed INTEGER NOT NULL DEFAULT 0, -- set by the failure hook, never inferred
223
+ event_at TEXT, -- optional UTC ISO-8601 when event occurred
224
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
225
+ archived_at INTEGER,
226
+ CHECK ((scope = 'project') = (project_id IS NOT NULL))
227
+ );
228
+ `;
229
+
230
+ const OBSERVATIONS_INDEX_DDL = `
231
+ CREATE INDEX IF NOT EXISTS idx_obs_project ON observations(project_id);
232
+ CREATE INDEX IF NOT EXISTS idx_obs_scope ON observations(scope);
233
+ CREATE INDEX IF NOT EXISTS idx_obs_scope_proj ON observations(scope, project_id, created_at);
234
+ CREATE INDEX IF NOT EXISTS idx_obs_event_at ON observations(scope, project_id, event_at);
235
+ CREATE INDEX IF NOT EXISTS idx_obs_session ON observations(session_id);
236
+ CREATE INDEX IF NOT EXISTS idx_obs_created ON observations(created_at);
237
+ CREATE INDEX IF NOT EXISTS idx_obs_note ON observations(note_ref);
238
+ CREATE INDEX IF NOT EXISTS idx_obs_task ON observations(task_ref);
239
+ CREATE INDEX IF NOT EXISTS idx_obs_file ON observations(file_path);
240
+ CREATE INDEX IF NOT EXISTS idx_obs_failed ON observations(failed, created_at);
241
+ CREATE INDEX IF NOT EXISTS idx_observations_archived ON observations(archived_at);
242
+ `;
243
+
244
+ const OBSERVATIONS_ARCHIVE_DDL = `
245
+ CREATE TABLE IF NOT EXISTS observations_archive (
246
+ id TEXT PRIMARY KEY,
247
+ original_observation_id TEXT NOT NULL UNIQUE,
248
+ scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
249
+ project_id TEXT,
250
+ user_id TEXT,
251
+ agent_id TEXT,
252
+ note_ref TEXT,
253
+ task_ref TEXT,
254
+ session_id TEXT,
255
+ agent TEXT,
256
+ kind TEXT NOT NULL CHECK (kind IN ('tool_call','prompt','response')),
257
+ tool_name TEXT,
258
+ file_path TEXT,
259
+ input TEXT,
260
+ output TEXT,
261
+ condensed_text TEXT,
262
+ resolved_dates_json TEXT,
263
+ signal_tags TEXT,
264
+ duration_ms INTEGER NOT NULL DEFAULT 0,
265
+ failed INTEGER NOT NULL DEFAULT 0,
266
+ event_at TEXT,
267
+ created_at INTEGER NOT NULL,
268
+ archived_at INTEGER NOT NULL,
269
+ CHECK ((scope = 'project') = (project_id IS NOT NULL))
270
+ );
271
+ `;
272
+
273
+ const OBSERVATIONS_ARCHIVE_INDEX_DDL = `
274
+ CREATE INDEX IF NOT EXISTS idx_obs_arc_project ON observations_archive(project_id);
275
+ CREATE INDEX IF NOT EXISTS idx_obs_arc_scope ON observations_archive(scope);
276
+ CREATE INDEX IF NOT EXISTS idx_obs_arc_scope_proj ON observations_archive(scope, project_id);
277
+ CREATE INDEX IF NOT EXISTS idx_obs_arc_archived ON observations_archive(archived_at);
278
+ `;
279
+
280
+ function alignObservationsSchema(db: Database): void {
281
+ const targets: Array<{
282
+ table: 'observations' | 'observations_archive';
283
+ ddl: string;
284
+ indexDdl: string;
285
+ }> = [
286
+ { table: 'observations', ddl: OBSERVATIONS_DDL, indexDdl: OBSERVATIONS_INDEX_DDL },
287
+ {
288
+ table: 'observations_archive',
289
+ ddl: OBSERVATIONS_ARCHIVE_DDL,
290
+ indexDdl: OBSERVATIONS_ARCHIVE_INDEX_DDL,
291
+ },
292
+ ];
293
+
294
+ for (const { table, ddl, indexDdl } of targets) {
295
+ ensureColumns(db, table, [
296
+ { name: 'user_id', ddl: 'TEXT' },
297
+ { name: 'agent_id', ddl: 'TEXT' },
298
+ { name: 'event_at', ddl: 'TEXT' },
299
+ { name: 'condensed_text', ddl: 'TEXT' },
300
+ { name: 'resolved_dates_json', ddl: 'TEXT' },
301
+ { name: 'signal_tags', ddl: 'TEXT' },
302
+ ]);
303
+
304
+ const row = db
305
+ .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = ?")
306
+ .get(table) as { sql?: string } | undefined;
307
+
308
+ if (row?.sql && !row.sql.includes("'response'")) {
309
+ rebuildTable(db, table, `${table}_legacy_kind`, ddl, indexDdl);
310
+ logger.info({ table }, `${table} schema: kind CHECK updated to include 'response'`);
311
+ } else {
312
+ db.exec(indexDdl);
313
+ }
314
+ }
315
+ }
316
+
116
317
  /**
117
318
  * Trajectory DDL lives in constants because two things need it: the normal
118
319
  * `CREATE TABLE IF NOT EXISTS` pass, and `alignTrajectorySchema` below, which
@@ -135,6 +336,8 @@ const TRAJECTORIES_DDL = `
135
336
  id TEXT PRIMARY KEY,
136
337
  scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
137
338
  project_id TEXT,
339
+ user_id TEXT,
340
+ agent_id TEXT,
138
341
  note_ref TEXT,
139
342
  task_ref TEXT,
140
343
  session_id TEXT,
@@ -155,14 +358,15 @@ const TRAJECTORIES_DDL = `
155
358
  `;
156
359
 
157
360
  const TRAJECTORIES_INDEX_DDL = `
158
- CREATE INDEX IF NOT EXISTS idx_traj_project ON trajectories(project_id);
159
- CREATE INDEX IF NOT EXISTS idx_traj_scope ON trajectories(scope);
160
- CREATE INDEX IF NOT EXISTS idx_traj_type ON trajectories(task_type);
161
- CREATE INDEX IF NOT EXISTS idx_traj_created ON trajectories(created_at);
162
- CREATE INDEX IF NOT EXISTS idx_traj_success ON trajectories(success, created_at);
163
- CREATE INDEX IF NOT EXISTS idx_traj_note ON trajectories(note_ref);
164
- CREATE INDEX IF NOT EXISTS idx_traj_session ON trajectories(session_id);
165
- CREATE INDEX IF NOT EXISTS idx_traj_rollup ON trajectories(rollup_source);
361
+ CREATE INDEX IF NOT EXISTS idx_traj_project ON trajectories(project_id);
362
+ CREATE INDEX IF NOT EXISTS idx_traj_scope ON trajectories(scope);
363
+ CREATE INDEX IF NOT EXISTS idx_traj_scope_proj ON trajectories(scope, project_id, created_at);
364
+ CREATE INDEX IF NOT EXISTS idx_traj_type ON trajectories(task_type);
365
+ CREATE INDEX IF NOT EXISTS idx_traj_created ON trajectories(created_at);
366
+ CREATE INDEX IF NOT EXISTS idx_traj_success ON trajectories(success, created_at);
367
+ CREATE INDEX IF NOT EXISTS idx_traj_note ON trajectories(note_ref);
368
+ CREATE INDEX IF NOT EXISTS idx_traj_session ON trajectories(session_id);
369
+ CREATE INDEX IF NOT EXISTS idx_traj_rollup ON trajectories(rollup_source);
166
370
  `;
167
371
 
168
372
  /**
@@ -178,6 +382,8 @@ const TRAJECTORY_ARCHIVE_DDL = `
178
382
  original_trajectory_id TEXT NOT NULL UNIQUE,
179
383
  scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
180
384
  project_id TEXT,
385
+ user_id TEXT,
386
+ agent_id TEXT,
181
387
  note_ref TEXT,
182
388
  task_ref TEXT,
183
389
  session_id TEXT,
@@ -198,21 +404,13 @@ const TRAJECTORY_ARCHIVE_DDL = `
198
404
  `;
199
405
 
200
406
  const TRAJECTORY_ARCHIVE_INDEX_DDL = `
201
- CREATE INDEX IF NOT EXISTS idx_traj_arc_project ON trajectory_archive(project_id);
202
- CREATE INDEX IF NOT EXISTS idx_traj_arc_scope ON trajectory_archive(scope);
203
- CREATE INDEX IF NOT EXISTS idx_traj_arc_archived ON trajectory_archive(archived_at);
204
- CREATE INDEX IF NOT EXISTS idx_traj_arc_session ON trajectory_archive(session_id);
407
+ CREATE INDEX IF NOT EXISTS idx_traj_arc_project ON trajectory_archive(project_id);
408
+ CREATE INDEX IF NOT EXISTS idx_traj_arc_scope ON trajectory_archive(scope);
409
+ CREATE INDEX IF NOT EXISTS idx_traj_arc_scope_proj ON trajectory_archive(scope, project_id);
410
+ CREATE INDEX IF NOT EXISTS idx_traj_arc_archived ON trajectory_archive(archived_at);
411
+ CREATE INDEX IF NOT EXISTS idx_traj_arc_session ON trajectory_archive(session_id);
205
412
  `;
206
413
 
207
- interface ColumnInfo {
208
- name: string;
209
- notnull: number;
210
- }
211
-
212
- function tableColumns(db: Database, table: string): ColumnInfo[] {
213
- return db.prepare(`PRAGMA table_info(${table})`).all() as ColumnInfo[];
214
- }
215
-
216
414
  /**
217
415
  * Bring an already-created trajectory table up to the DDL above.
218
416
  *
@@ -230,7 +428,7 @@ function alignTrajectorySchema(
230
428
  ): void {
231
429
  // 1. Additive columns. Backfill only when the column has just appeared:
232
430
  // every pre-existing row is, by definition, an explicit rollup.
233
- const addColumns: Array<{ name: string; ddl: string; backfill?: string }> = [
431
+ ensureColumns(db, table, [
234
432
  { name: 'session_id', ddl: 'TEXT' },
235
433
  {
236
434
  name: 'rollup_source',
@@ -238,15 +436,9 @@ function alignTrajectorySchema(
238
436
  backfill: `UPDATE ${table} SET rollup_source = 'signalled' WHERE rollup_source IS NULL`,
239
437
  },
240
438
  { name: 'tool_calls', ddl: 'INTEGER NOT NULL DEFAULT 0' },
241
- ];
242
-
243
- const existing = new Set(tableColumns(db, table).map((c) => c.name));
244
- for (const col of addColumns) {
245
- if (existing.has(col.name)) continue;
246
- db.exec(`ALTER TABLE ${table} ADD COLUMN ${col.name} ${col.ddl}`);
247
- if (col.backfill) db.exec(col.backfill);
248
- logger.info({ table, column: col.name }, 'trajectory schema: column added');
249
- }
439
+ { name: 'user_id', ddl: 'TEXT' },
440
+ { name: 'agent_id', ddl: 'TEXT' },
441
+ ]);
250
442
 
251
443
  // 2. Relax success to nullable. SQLite has no "ALTER COLUMN", so this is the
252
444
  // documented rebuild: rename, recreate, copy, drop, re-index.
@@ -256,26 +448,8 @@ function alignTrajectorySchema(
256
448
  return;
257
449
  }
258
450
 
259
- const legacy = `${table}_legacy_notnull`;
260
- db.exec(`DROP TABLE IF EXISTS ${legacy}`);
261
- pragma(db, 'foreign_keys = OFF');
262
- try {
263
- transaction(db, () => {
264
- db.exec(`ALTER TABLE ${table} RENAME TO ${legacy}`);
265
- db.exec(createDdl);
266
- const oldCols = new Set(tableColumns(db, legacy).map((c) => c.name));
267
- const shared = tableColumns(db, table)
268
- .map((c) => c.name)
269
- .filter((name) => oldCols.has(name));
270
- const list = shared.join(', ');
271
- db.exec(`INSERT INTO ${table} (${list}) SELECT ${list} FROM ${legacy}`);
272
- db.exec(`DROP TABLE ${legacy}`);
273
- db.exec(indexDdl);
274
- })();
275
- logger.info({ table }, 'trajectory schema: success relaxed to nullable (NULL = unknown)');
276
- } finally {
277
- pragma(db, 'foreign_keys = ON');
278
- }
451
+ rebuildTable(db, table, `${table}_legacy_notnull`, createDdl, indexDdl);
452
+ logger.info({ table }, 'trajectory schema: success relaxed to nullable (NULL = unknown)');
279
453
  }
280
454
 
281
455
  const NOTES_DDL = `
@@ -283,6 +457,8 @@ const NOTES_DDL = `
283
457
  id TEXT PRIMARY KEY,
284
458
  scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
285
459
  project_id TEXT,
460
+ user_id TEXT,
461
+ agent_id TEXT,
286
462
  session_id TEXT,
287
463
  type TEXT NOT NULL CHECK (type IN
288
464
  ('fact','architecture','pattern','workflow','bug','preference','lesson')),
@@ -294,6 +470,9 @@ const NOTES_DDL = `
294
470
  supersedes TEXT REFERENCES notes(id),
295
471
  is_latest INTEGER NOT NULL DEFAULT 1,
296
472
  embedding BLOB,
473
+ event_at TEXT,
474
+ valid_from TEXT,
475
+ valid_until TEXT,
297
476
  created_at INTEGER NOT NULL DEFAULT (unixepoch()),
298
477
  updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
299
478
  CHECK ((scope = 'project') = (project_id IS NOT NULL))
@@ -301,58 +480,404 @@ const NOTES_DDL = `
301
480
  `;
302
481
 
303
482
  const NOTES_INDEX_DDL = `
304
- CREATE INDEX IF NOT EXISTS idx_notes_project ON notes(project_id);
305
- CREATE INDEX IF NOT EXISTS idx_notes_scope ON notes(scope);
306
- CREATE INDEX IF NOT EXISTS idx_notes_type ON notes(type);
307
- CREATE INDEX IF NOT EXISTS idx_notes_latest ON notes(is_latest, updated_at);
308
- CREATE INDEX IF NOT EXISTS idx_notes_session ON notes(session_id);
483
+ CREATE INDEX IF NOT EXISTS idx_notes_project ON notes(project_id);
484
+ CREATE INDEX IF NOT EXISTS idx_notes_scope ON notes(scope);
485
+ CREATE INDEX IF NOT EXISTS idx_notes_scope_proj ON notes(scope, project_id, is_latest, updated_at);
486
+ CREATE INDEX IF NOT EXISTS idx_notes_type ON notes(type);
487
+ CREATE INDEX IF NOT EXISTS idx_notes_latest ON notes(is_latest, updated_at);
488
+ CREATE INDEX IF NOT EXISTS idx_notes_session ON notes(session_id);
489
+ CREATE INDEX IF NOT EXISTS idx_notes_temporal ON notes(event_at, valid_from, valid_until);
490
+ CREATE INDEX IF NOT EXISTS idx_notes_user ON notes(user_id) WHERE user_id IS NOT NULL;
309
491
  `;
310
492
 
311
493
  function alignNotesSchema(db: Database): void {
312
- const existing = new Set(tableColumns(db, 'notes').map((c) => c.name));
313
- if (!existing.has('session_id')) {
314
- db.exec('ALTER TABLE notes ADD COLUMN session_id TEXT');
315
- logger.info({ table: 'notes', column: 'session_id' }, 'notes schema: column added');
316
- }
494
+ ensureColumns(db, 'notes', [
495
+ { name: 'session_id', ddl: 'TEXT' },
496
+ { name: 'user_id', ddl: 'TEXT' },
497
+ { name: 'agent_id', ddl: 'TEXT' },
498
+ { name: 'event_at', ddl: 'TEXT' },
499
+ { name: 'valid_from', ddl: 'TEXT' },
500
+ { name: 'valid_until', ddl: 'TEXT' },
501
+ ]);
317
502
 
318
503
  const row = db
319
504
  .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'notes'")
320
505
  .get() as { sql?: string } | undefined;
321
506
 
322
507
  if (row?.sql && !row.sql.includes("'lesson'")) {
323
- const legacy = 'notes_legacy_type';
324
- db.exec(`DROP TABLE IF EXISTS ${legacy}`);
325
- pragma(db, 'foreign_keys = OFF');
326
- try {
327
- transaction(db, () => {
328
- db.exec(`ALTER TABLE notes RENAME TO ${legacy}`);
329
- db.exec(NOTES_DDL);
330
- const oldCols = new Set(tableColumns(db, legacy).map((c) => c.name));
331
- const shared = tableColumns(db, 'notes')
332
- .map((c) => c.name)
333
- .filter((name) => oldCols.has(name));
334
- const list = shared.join(', ');
335
- db.exec(`INSERT INTO notes (${list}) SELECT ${list} FROM ${legacy}`);
336
- db.exec(`DROP TABLE ${legacy}`);
337
- })();
338
- logger.info({ table: 'notes' }, "notes schema: type CHECK updated to include 'lesson'");
339
- } finally {
340
- pragma(db, 'foreign_keys = ON');
341
- }
508
+ rebuildTable(db, 'notes', 'notes_legacy_type', NOTES_DDL);
509
+ logger.info({ table: 'notes' }, "notes schema: type CHECK updated to include 'lesson'");
342
510
  }
343
511
 
344
512
  db.exec(NOTES_INDEX_DDL);
345
513
  }
346
514
 
515
+ function alignSessionsSchema(db: Database): void {
516
+ ensureColumns(db, 'sessions', [
517
+ { name: 'user_id', ddl: 'TEXT' },
518
+ { name: 'agent_id', ddl: 'TEXT' },
519
+ ]);
520
+ db.exec(`
521
+ CREATE INDEX IF NOT EXISTS idx_sessions_proj_status ON sessions(project_id, status, started_at);
522
+ CREATE INDEX IF NOT EXISTS idx_sessions_scope_proj ON sessions(scope, project_id, status, started_at);
523
+ `);
524
+ }
525
+
526
+ function alignSummariesSchema(db: Database): void {
527
+ ensureColumns(db, 'summaries', [
528
+ { name: 'user_id', ddl: 'TEXT' },
529
+ { name: 'agent_id', ddl: 'TEXT' },
530
+ ]);
531
+ db.exec(`
532
+ CREATE INDEX IF NOT EXISTS idx_sum_project ON summaries(project_id);
533
+ CREATE INDEX IF NOT EXISTS idx_sum_scope_proj ON summaries(scope, project_id, is_latest, created_at);
534
+ CREATE INDEX IF NOT EXISTS idx_sum_kind ON summaries(kind, created_at);
535
+ CREATE INDEX IF NOT EXISTS idx_sum_latest ON summaries(is_latest);
536
+ CREATE INDEX IF NOT EXISTS idx_sum_producer ON summaries(producer_tier, producer_model);
537
+ `);
538
+ }
539
+
347
540
  function alignFailurePatternsSchema(db: Database): void {
348
- const existing = new Set(tableColumns(db, 'failure_patterns').map((c) => c.name));
349
- if (!existing.has('session_id')) {
350
- db.exec('ALTER TABLE failure_patterns ADD COLUMN session_id TEXT');
541
+ ensureColumns(db, 'failure_patterns', [
542
+ { name: 'session_id', ddl: 'TEXT' },
543
+ { name: 'user_id', ddl: 'TEXT' },
544
+ { name: 'agent_id', ddl: 'TEXT' },
545
+ ]);
546
+ db.exec(`
547
+ CREATE INDEX IF NOT EXISTS idx_fp_lookup ON failure_patterns(project_id, task_type, count DESC);
548
+ CREATE INDEX IF NOT EXISTS idx_fp_scope_proj ON failure_patterns(scope, project_id, task_type, count DESC);
549
+ CREATE INDEX IF NOT EXISTS idx_fp_recent ON failure_patterns(last_seen_at);
550
+ CREATE UNIQUE INDEX IF NOT EXISTS idx_fp_unique_coalesce ON failure_patterns(COALESCE(project_id, '__GLOBAL_OR_UNKNOWN__:' || scope), task_type, error_text);
551
+ `);
552
+ }
553
+
554
+ function alignActionsSchema(db: Database): void {
555
+ ensureColumns(db, 'actions', [
556
+ { name: 'user_id', ddl: 'TEXT' },
557
+ { name: 'agent_id', ddl: 'TEXT' },
558
+ { name: 'due_at', ddl: 'TEXT' },
559
+ { name: 'remind_at', ddl: 'TEXT' },
560
+ { name: 'recurrence', ddl: 'TEXT' },
561
+ { name: 'last_reminded_at', ddl: 'TEXT' },
562
+ { name: 'snooze_until', ddl: 'TEXT' },
563
+ { name: 'parent_action_id', ddl: 'TEXT' },
564
+ { name: 'embedding', ddl: 'BLOB' },
565
+ ]);
566
+ db.exec(`
567
+ CREATE INDEX IF NOT EXISTS idx_actions_proj_status ON actions(project_id, status, priority);
568
+ CREATE INDEX IF NOT EXISTS idx_actions_scope_proj ON actions(scope, project_id, status, priority);
569
+ CREATE INDEX IF NOT EXISTS idx_actions_due ON actions(status, due_at) WHERE status IN ('ready','in_progress') AND due_at IS NOT NULL;
570
+ CREATE INDEX IF NOT EXISTS idx_actions_remind ON actions(status, remind_at) WHERE status IN ('ready','in_progress') AND remind_at IS NOT NULL;
571
+ `);
572
+ }
573
+
574
+ const EMBED_QUEUE_DDL = `
575
+ CREATE TABLE IF NOT EXISTS embed_queue (
576
+ record_id TEXT NOT NULL,
577
+ record_type TEXT NOT NULL CHECK (record_type IN ('observation','trajectory','note','summary','entity','action')),
578
+ status TEXT NOT NULL DEFAULT 'pending'
579
+ CHECK (status IN ('pending','running','done','failed')),
580
+ attempts INTEGER NOT NULL DEFAULT 0,
581
+ last_error TEXT,
582
+ target TEXT NOT NULL DEFAULT 'live', -- 'live' or a re-embed collection name
583
+ queued_at INTEGER NOT NULL DEFAULT (unixepoch()),
584
+ PRIMARY KEY (record_id, record_type, target)
585
+ );
586
+ `;
587
+
588
+ const EMBED_QUEUE_INDEX_DDL = `
589
+ CREATE INDEX IF NOT EXISTS idx_eq_claim ON embed_queue(target, status, queued_at);
590
+ `;
591
+
592
+ function alignEmbedQueueSchema(db: Database): void {
593
+ const row = db
594
+ .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'embed_queue'")
595
+ .get() as { sql?: string } | undefined;
596
+
597
+ if (row?.sql && !row.sql.includes("'entity'")) {
598
+ rebuildTable(db, 'embed_queue', 'embed_queue_legacy_types', EMBED_QUEUE_DDL, EMBED_QUEUE_INDEX_DDL);
599
+ logger.info({ table: 'embed_queue' }, "embed_queue schema: record_type CHECK updated to include 'entity' and 'action'");
600
+ } else {
601
+ db.exec(EMBED_QUEUE_INDEX_DDL);
602
+ }
603
+ }
604
+
605
+ const NOTES_EXTRA_EXPR = `
606
+ TRIM(
607
+ COALESCE((SELECT GROUP_CONCAT(concept, ' ') FROM note_concepts WHERE note_id = n.id), '') ||
608
+ ' ' ||
609
+ COALESCE((SELECT GROUP_CONCAT(file_path, ' ') FROM note_files WHERE note_id = n.id), '')
610
+ )
611
+ `;
612
+
613
+ const SUMMARIES_TEXT_EXPR = `
614
+ COALESCE((SELECT GROUP_CONCAT(text, char(10)) FROM (SELECT text FROM summary_claims WHERE summary_id = s.id ORDER BY ordinal ASC)), '')
615
+ `;
616
+
617
+ /**
618
+ * Create FTS5 virtual tables, sync triggers, and run one-time backfill on
619
+ * existing databases. Must run AFTER all table rebuilds so triggers are never
620
+ * dropped by ALTER/DROP TABLE operations.
621
+ */
622
+ function alignFtsSchema(db: Database): void {
623
+ const obsFtsRow = db
624
+ .prepare("SELECT sql FROM sqlite_master WHERE type = 'table' AND name = 'fts_observations'")
625
+ .get() as { sql?: string } | undefined;
626
+
627
+ if (obsFtsRow?.sql && !obsFtsRow.sql.includes('condensed_text')) {
628
+ db.exec(`
629
+ DROP TRIGGER IF EXISTS trg_fts_observations_ai;
630
+ DROP TRIGGER IF EXISTS trg_fts_observations_au;
631
+ DROP TRIGGER IF EXISTS trg_fts_observations_ad;
632
+ DROP TABLE IF EXISTS fts_observations;
633
+ `);
351
634
  logger.info(
352
- { table: 'failure_patterns', column: 'session_id' },
353
- 'failure_patterns schema: column added'
635
+ { table: 'fts_observations' },
636
+ 'fts_observations schema: upgraded to include condensed_text'
354
637
  );
355
638
  }
639
+
640
+ db.exec(`
641
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_notes USING fts5(
642
+ record_id UNINDEXED, title, content, extra, tokenize='porter unicode61'
643
+ );
644
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_trajectories USING fts5(
645
+ record_id UNINDEXED, description, result, task_type, tokenize='porter unicode61'
646
+ );
647
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_observations USING fts5(
648
+ record_id UNINDEXED, tool_name, file_path, input, output, condensed_text, tokenize='porter unicode61'
649
+ );
650
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_summaries USING fts5(
651
+ record_id UNINDEXED, text, tokenize='porter unicode61'
652
+ );
653
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_entities USING fts5(
654
+ record_id UNINDEXED, name, entity_type, description, external_ref, tokenize='porter unicode61'
655
+ );
656
+ CREATE VIRTUAL TABLE IF NOT EXISTS fts_actions USING fts5(
657
+ record_id UNINDEXED, title, description, blocked_reason, tokenize='porter unicode61'
658
+ );
659
+
660
+ -- Drop legacy unscoped AFTER UPDATE triggers (and observations AI trigger) so existing
661
+ -- databases upgrade cleanly to column-scoped 6-column triggers.
662
+ DROP TRIGGER IF EXISTS trg_fts_notes_au;
663
+ DROP TRIGGER IF EXISTS trg_fts_trajectories_au;
664
+ DROP TRIGGER IF EXISTS trg_fts_observations_ai;
665
+ DROP TRIGGER IF EXISTS trg_fts_observations_au;
666
+ DROP TRIGGER IF EXISTS trg_fts_summaries_au;
667
+ DROP TRIGGER IF EXISTS trg_fts_summary_claims_au;
668
+ DROP TRIGGER IF EXISTS trg_fts_entities_au;
669
+ DROP TRIGGER IF EXISTS trg_fts_actions_au;
670
+
671
+ -- notes triggers
672
+ CREATE TRIGGER IF NOT EXISTS trg_fts_notes_ai AFTER INSERT ON notes BEGIN
673
+ DELETE FROM fts_notes WHERE record_id = new.id;
674
+ INSERT INTO fts_notes(record_id, title, content, extra)
675
+ SELECT n.id, COALESCE(n.title, ''), COALESCE(n.content, ''), ${NOTES_EXTRA_EXPR}
676
+ FROM notes n WHERE n.id = new.id;
677
+ END;
678
+ CREATE TRIGGER trg_fts_notes_au AFTER UPDATE OF id, title, content, type, author ON notes BEGIN
679
+ DELETE FROM fts_notes WHERE record_id = old.id;
680
+ INSERT INTO fts_notes(record_id, title, content, extra)
681
+ SELECT n.id, COALESCE(n.title, ''), COALESCE(n.content, ''), ${NOTES_EXTRA_EXPR}
682
+ FROM notes n WHERE n.id = new.id;
683
+ END;
684
+ CREATE TRIGGER IF NOT EXISTS trg_fts_notes_ad AFTER DELETE ON notes BEGIN
685
+ DELETE FROM fts_notes WHERE record_id = old.id;
686
+ END;
687
+
688
+ -- note_concepts triggers
689
+ CREATE TRIGGER IF NOT EXISTS trg_fts_note_concepts_ai AFTER INSERT ON note_concepts BEGIN
690
+ DELETE FROM fts_notes WHERE record_id = new.note_id;
691
+ INSERT INTO fts_notes(record_id, title, content, extra)
692
+ SELECT n.id, COALESCE(n.title, ''), COALESCE(n.content, ''), ${NOTES_EXTRA_EXPR}
693
+ FROM notes n WHERE n.id = new.note_id;
694
+ END;
695
+ CREATE TRIGGER IF NOT EXISTS trg_fts_note_concepts_ad AFTER DELETE ON note_concepts BEGIN
696
+ DELETE FROM fts_notes WHERE record_id = old.note_id;
697
+ INSERT INTO fts_notes(record_id, title, content, extra)
698
+ SELECT n.id, COALESCE(n.title, ''), COALESCE(n.content, ''), ${NOTES_EXTRA_EXPR}
699
+ FROM notes n WHERE n.id = old.note_id;
700
+ END;
701
+
702
+ -- note_files triggers
703
+ CREATE TRIGGER IF NOT EXISTS trg_fts_note_files_ai AFTER INSERT ON note_files BEGIN
704
+ DELETE FROM fts_notes WHERE record_id = new.note_id;
705
+ INSERT INTO fts_notes(record_id, title, content, extra)
706
+ SELECT n.id, COALESCE(n.title, ''), COALESCE(n.content, ''), ${NOTES_EXTRA_EXPR}
707
+ FROM notes n WHERE n.id = new.note_id;
708
+ END;
709
+ CREATE TRIGGER IF NOT EXISTS trg_fts_note_files_ad AFTER DELETE ON note_files BEGIN
710
+ DELETE FROM fts_notes WHERE record_id = old.note_id;
711
+ INSERT INTO fts_notes(record_id, title, content, extra)
712
+ SELECT n.id, COALESCE(n.title, ''), COALESCE(n.content, ''), ${NOTES_EXTRA_EXPR}
713
+ FROM notes n WHERE n.id = old.note_id;
714
+ END;
715
+
716
+ -- trajectories triggers
717
+ CREATE TRIGGER IF NOT EXISTS trg_fts_trajectories_ai AFTER INSERT ON trajectories BEGIN
718
+ DELETE FROM fts_trajectories WHERE record_id = new.id;
719
+ INSERT INTO fts_trajectories(record_id, description, result, task_type)
720
+ VALUES (new.id, COALESCE(new.description, ''), COALESCE(new.result, ''), COALESCE(new.task_type, ''));
721
+ END;
722
+ CREATE TRIGGER trg_fts_trajectories_au AFTER UPDATE OF id, description, result, task_type ON trajectories BEGIN
723
+ DELETE FROM fts_trajectories WHERE record_id = old.id;
724
+ INSERT INTO fts_trajectories(record_id, description, result, task_type)
725
+ VALUES (new.id, COALESCE(new.description, ''), COALESCE(new.result, ''), COALESCE(new.task_type, ''));
726
+ END;
727
+ CREATE TRIGGER IF NOT EXISTS trg_fts_trajectories_ad AFTER DELETE ON trajectories BEGIN
728
+ DELETE FROM fts_trajectories WHERE record_id = old.id;
729
+ END;
730
+
731
+ -- observations triggers
732
+ CREATE TRIGGER IF NOT EXISTS trg_fts_observations_ai AFTER INSERT ON observations BEGIN
733
+ DELETE FROM fts_observations WHERE record_id = new.id;
734
+ INSERT INTO fts_observations(record_id, tool_name, file_path, input, output, condensed_text)
735
+ VALUES (new.id, COALESCE(new.tool_name, ''), COALESCE(new.file_path, ''), COALESCE(new.input, ''), COALESCE(new.output, ''), COALESCE(new.condensed_text, ''));
736
+ END;
737
+ CREATE TRIGGER trg_fts_observations_au AFTER UPDATE OF id, tool_name, file_path, input, output, condensed_text ON observations BEGIN
738
+ DELETE FROM fts_observations WHERE record_id = old.id;
739
+ INSERT INTO fts_observations(record_id, tool_name, file_path, input, output, condensed_text)
740
+ VALUES (new.id, COALESCE(new.tool_name, ''), COALESCE(new.file_path, ''), COALESCE(new.input, ''), COALESCE(new.output, ''), COALESCE(new.condensed_text, ''));
741
+ END;
742
+ CREATE TRIGGER IF NOT EXISTS trg_fts_observations_ad AFTER DELETE ON observations BEGIN
743
+ DELETE FROM fts_observations WHERE record_id = old.id;
744
+ END;
745
+
746
+ -- summaries triggers
747
+ CREATE TRIGGER IF NOT EXISTS trg_fts_summaries_ai AFTER INSERT ON summaries BEGIN
748
+ DELETE FROM fts_summaries WHERE record_id = new.id;
749
+ INSERT INTO fts_summaries(record_id, text)
750
+ SELECT s.id, ${SUMMARIES_TEXT_EXPR}
751
+ FROM summaries s WHERE s.id = new.id;
752
+ END;
753
+ CREATE TRIGGER trg_fts_summaries_au AFTER UPDATE OF id, kind, outcome, files_touched, error_verbatim ON summaries BEGIN
754
+ DELETE FROM fts_summaries WHERE record_id = old.id;
755
+ INSERT INTO fts_summaries(record_id, text)
756
+ SELECT s.id, ${SUMMARIES_TEXT_EXPR}
757
+ FROM summaries s WHERE s.id = new.id;
758
+ END;
759
+ CREATE TRIGGER IF NOT EXISTS trg_fts_summaries_ad AFTER DELETE ON summaries BEGIN
760
+ DELETE FROM fts_summaries WHERE record_id = old.id;
761
+ END;
762
+
763
+ -- summary_claims triggers
764
+ CREATE TRIGGER IF NOT EXISTS trg_fts_summary_claims_ai AFTER INSERT ON summary_claims BEGIN
765
+ DELETE FROM fts_summaries WHERE record_id = new.summary_id;
766
+ INSERT INTO fts_summaries(record_id, text)
767
+ SELECT s.id, ${SUMMARIES_TEXT_EXPR}
768
+ FROM summaries s WHERE s.id = new.summary_id;
769
+ END;
770
+ CREATE TRIGGER trg_fts_summary_claims_au AFTER UPDATE OF summary_id, text ON summary_claims BEGIN
771
+ DELETE FROM fts_summaries WHERE record_id IN (old.summary_id, new.summary_id);
772
+ INSERT INTO fts_summaries(record_id, text)
773
+ SELECT s.id, ${SUMMARIES_TEXT_EXPR}
774
+ FROM summaries s WHERE s.id IN (old.summary_id, new.summary_id);
775
+ END;
776
+ CREATE TRIGGER IF NOT EXISTS trg_fts_summary_claims_ad AFTER DELETE ON summary_claims BEGIN
777
+ DELETE FROM fts_summaries WHERE record_id = old.summary_id;
778
+ INSERT INTO fts_summaries(record_id, text)
779
+ SELECT s.id, ${SUMMARIES_TEXT_EXPR}
780
+ FROM summaries s WHERE s.id = old.summary_id;
781
+ END;
782
+
783
+ -- entities triggers
784
+ CREATE TRIGGER IF NOT EXISTS trg_fts_entities_ai AFTER INSERT ON entities BEGIN
785
+ DELETE FROM fts_entities WHERE record_id = new.id;
786
+ INSERT INTO fts_entities(record_id, name, entity_type, description, external_ref)
787
+ VALUES (new.id, COALESCE(new.name, ''), COALESCE(new.entity_type, ''), COALESCE(new.description, ''), COALESCE(new.external_ref, ''));
788
+ END;
789
+ CREATE TRIGGER trg_fts_entities_au AFTER UPDATE OF id, name, entity_type, description, external_ref ON entities BEGIN
790
+ DELETE FROM fts_entities WHERE record_id = old.id;
791
+ INSERT INTO fts_entities(record_id, name, entity_type, description, external_ref)
792
+ VALUES (new.id, COALESCE(new.name, ''), COALESCE(new.entity_type, ''), COALESCE(new.description, ''), COALESCE(new.external_ref, ''));
793
+ END;
794
+ CREATE TRIGGER IF NOT EXISTS trg_fts_entities_ad AFTER DELETE ON entities BEGIN
795
+ DELETE FROM fts_entities WHERE record_id = old.id;
796
+ END;
797
+
798
+ -- actions triggers
799
+ CREATE TRIGGER IF NOT EXISTS trg_fts_actions_ai AFTER INSERT ON actions BEGIN
800
+ DELETE FROM fts_actions WHERE record_id = new.id;
801
+ INSERT INTO fts_actions(record_id, title, description, blocked_reason)
802
+ VALUES (new.id, COALESCE(new.title, ''), COALESCE(new.description, ''), COALESCE(new.blocked_reason, ''));
803
+ END;
804
+ CREATE TRIGGER trg_fts_actions_au AFTER UPDATE OF id, title, description, blocked_reason ON actions BEGIN
805
+ DELETE FROM fts_actions WHERE record_id = old.id;
806
+ INSERT INTO fts_actions(record_id, title, description, blocked_reason)
807
+ VALUES (new.id, COALESCE(new.title, ''), COALESCE(new.description, ''), COALESCE(new.blocked_reason, ''));
808
+ END;
809
+ CREATE TRIGGER IF NOT EXISTS trg_fts_actions_ad AFTER DELETE ON actions BEGIN
810
+ DELETE FROM fts_actions WHERE record_id = old.id;
811
+ END;
812
+ `);
813
+
814
+ const backfills: Array<{ source: string; fts: string; sql: string }> = [
815
+ {
816
+ source: 'notes',
817
+ fts: 'fts_notes',
818
+ sql: `
819
+ INSERT INTO fts_notes(record_id, title, content, extra)
820
+ SELECT n.id, COALESCE(n.title, ''), COALESCE(n.content, ''), ${NOTES_EXTRA_EXPR}
821
+ FROM notes n
822
+ `,
823
+ },
824
+ {
825
+ source: 'trajectories',
826
+ fts: 'fts_trajectories',
827
+ sql: `
828
+ INSERT INTO fts_trajectories(record_id, description, result, task_type)
829
+ SELECT id, COALESCE(description, ''), COALESCE(result, ''), COALESCE(task_type, '')
830
+ FROM trajectories
831
+ `,
832
+ },
833
+ {
834
+ source: 'observations',
835
+ fts: 'fts_observations',
836
+ sql: `
837
+ INSERT INTO fts_observations(record_id, tool_name, file_path, input, output, condensed_text)
838
+ SELECT id, COALESCE(tool_name, ''), COALESCE(file_path, ''), COALESCE(input, ''), COALESCE(output, ''), COALESCE(condensed_text, '')
839
+ FROM observations
840
+ `,
841
+ },
842
+ {
843
+ source: 'summaries',
844
+ fts: 'fts_summaries',
845
+ sql: `
846
+ INSERT INTO fts_summaries(record_id, text)
847
+ SELECT s.id, ${SUMMARIES_TEXT_EXPR}
848
+ FROM summaries s
849
+ `,
850
+ },
851
+ {
852
+ source: 'entities',
853
+ fts: 'fts_entities',
854
+ sql: `
855
+ INSERT INTO fts_entities(record_id, name, entity_type, description, external_ref)
856
+ SELECT id, COALESCE(name, ''), COALESCE(entity_type, ''), COALESCE(description, ''), COALESCE(external_ref, '')
857
+ FROM entities
858
+ `,
859
+ },
860
+ {
861
+ source: 'actions',
862
+ fts: 'fts_actions',
863
+ sql: `
864
+ INSERT INTO fts_actions(record_id, title, description, blocked_reason)
865
+ SELECT id, COALESCE(title, ''), COALESCE(description, ''), COALESCE(blocked_reason, '')
866
+ FROM actions
867
+ `,
868
+ },
869
+ ];
870
+
871
+ transaction(db, () => {
872
+ for (const item of backfills) {
873
+ const hasSrc = db.prepare(`SELECT 1 FROM ${item.source} LIMIT 1`).get();
874
+ if (!hasSrc) continue;
875
+ const hasFts = db.prepare(`SELECT 1 FROM ${item.fts} LIMIT 1`).get();
876
+ if (hasFts) continue;
877
+ db.exec(item.sql);
878
+ logger.info({ source: item.source, fts: item.fts }, 'FTS5 backfill complete');
879
+ }
880
+ })();
356
881
  }
357
882
 
358
883
  function runMigrations(db: Database): void {
@@ -373,62 +898,9 @@ function runMigrations(db: Database): void {
373
898
  set_at INTEGER NOT NULL DEFAULT (unixepoch())
374
899
  );
375
900
 
376
- -- observations
377
- CREATE TABLE IF NOT EXISTS observations (
378
- id TEXT PRIMARY KEY,
379
- scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
380
- project_id TEXT,
381
- note_ref TEXT, -- -> notes.id, optional
382
- task_ref TEXT, -- provenance only, not a scope filter
383
- session_id TEXT,
384
- agent TEXT,
385
- kind TEXT NOT NULL CHECK (kind IN ('tool_call','prompt')),
386
- tool_name TEXT,
387
- file_path TEXT, -- the tool's TARGET path, nothing else
388
- input TEXT,
389
- output TEXT,
390
- duration_ms INTEGER NOT NULL DEFAULT 0,
391
- failed INTEGER NOT NULL DEFAULT 0, -- set by the failure hook, never inferred
392
- created_at INTEGER NOT NULL DEFAULT (unixepoch()),
393
- archived_at INTEGER,
394
- CHECK ((scope = 'project') = (project_id IS NOT NULL))
395
- );
396
-
397
- CREATE INDEX IF NOT EXISTS idx_obs_project ON observations(project_id);
398
- CREATE INDEX IF NOT EXISTS idx_obs_scope ON observations(scope);
399
- CREATE INDEX IF NOT EXISTS idx_obs_session ON observations(session_id);
400
- CREATE INDEX IF NOT EXISTS idx_obs_created ON observations(created_at);
401
- CREATE INDEX IF NOT EXISTS idx_obs_note ON observations(note_ref);
402
- CREATE INDEX IF NOT EXISTS idx_obs_task ON observations(task_ref);
403
- CREATE INDEX IF NOT EXISTS idx_obs_file ON observations(file_path);
404
- CREATE INDEX IF NOT EXISTS idx_obs_failed ON observations(failed, created_at);
405
- CREATE INDEX IF NOT EXISTS idx_observations_archived ON observations(archived_at);
406
-
407
- -- observations_archive
408
- CREATE TABLE IF NOT EXISTS observations_archive (
409
- id TEXT PRIMARY KEY,
410
- original_observation_id TEXT NOT NULL UNIQUE,
411
- scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
412
- project_id TEXT,
413
- note_ref TEXT,
414
- task_ref TEXT,
415
- session_id TEXT,
416
- agent TEXT,
417
- kind TEXT NOT NULL CHECK (kind IN ('tool_call','prompt')),
418
- tool_name TEXT,
419
- file_path TEXT,
420
- input TEXT,
421
- output TEXT,
422
- duration_ms INTEGER NOT NULL DEFAULT 0,
423
- failed INTEGER NOT NULL DEFAULT 0,
424
- created_at INTEGER NOT NULL,
425
- archived_at INTEGER NOT NULL,
426
- CHECK ((scope = 'project') = (project_id IS NOT NULL))
427
- );
428
-
429
- CREATE INDEX IF NOT EXISTS idx_obs_arc_project ON observations_archive(project_id);
430
- CREATE INDEX IF NOT EXISTS idx_obs_arc_scope ON observations_archive(scope);
431
- CREATE INDEX IF NOT EXISTS idx_obs_arc_archived ON observations_archive(archived_at);
901
+ -- observations (DDL in OBSERVATIONS_DDL; see alignObservationsSchema)
902
+ ${OBSERVATIONS_DDL}
903
+ ${OBSERVATIONS_ARCHIVE_DDL}
432
904
 
433
905
  -- trajectories (DDL in TRAJECTORIES_DDL; see alignTrajectorySchema)
434
906
  ${TRAJECTORIES_DDL}
@@ -457,6 +929,8 @@ function runMigrations(db: Database): void {
457
929
  id TEXT PRIMARY KEY,
458
930
  scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
459
931
  project_id TEXT,
932
+ user_id TEXT,
933
+ agent_id TEXT,
460
934
  session_id TEXT,
461
935
  task_type TEXT NOT NULL DEFAULT 'unknown',
462
936
  error_text TEXT NOT NULL,
@@ -472,6 +946,8 @@ function runMigrations(db: Database): void {
472
946
  id TEXT PRIMARY KEY,
473
947
  scope TEXT NOT NULL DEFAULT 'unknown' CHECK(scope IN ('project','global','unknown')),
474
948
  project_id TEXT,
949
+ user_id TEXT,
950
+ agent_id TEXT,
475
951
  agent_name TEXT,
476
952
  cwd TEXT,
477
953
  status TEXT NOT NULL DEFAULT 'active' CHECK(status IN ('active','paused','completed','abandoned')),
@@ -483,20 +959,27 @@ function runMigrations(db: Database): void {
483
959
  CHECK ((scope = 'project') = (project_id IS NOT NULL))
484
960
  );
485
961
 
486
- CREATE INDEX IF NOT EXISTS idx_sessions_proj_status ON sessions(project_id, status, started_at);
487
-
488
962
  -- actions
489
963
  CREATE TABLE IF NOT EXISTS actions (
490
964
  id TEXT PRIMARY KEY,
491
965
  session_id TEXT,
492
966
  scope TEXT NOT NULL DEFAULT 'unknown' CHECK(scope IN ('project','global','unknown')),
493
967
  project_id TEXT,
968
+ user_id TEXT,
969
+ agent_id TEXT,
494
970
  title TEXT NOT NULL,
495
971
  description TEXT,
496
972
  status TEXT NOT NULL DEFAULT 'ready' CHECK(status IN ('ready','blocked','in_progress','done','dismissed')),
497
973
  priority TEXT NOT NULL DEFAULT 'normal' CHECK(priority IN ('low','normal','high','urgent')),
498
974
  blocked_reason TEXT,
499
975
  files_json TEXT,
976
+ due_at TEXT,
977
+ remind_at TEXT,
978
+ recurrence TEXT,
979
+ last_reminded_at TEXT,
980
+ snooze_until TEXT,
981
+ parent_action_id TEXT,
982
+ embedding BLOB,
500
983
  created_at TEXT NOT NULL DEFAULT (datetime('now')),
501
984
  updated_at TEXT NOT NULL DEFAULT (datetime('now')),
502
985
  resolved_at TEXT,
@@ -504,17 +987,13 @@ function runMigrations(db: Database): void {
504
987
  CHECK ((scope = 'project') = (project_id IS NOT NULL))
505
988
  );
506
989
 
507
- CREATE INDEX IF NOT EXISTS idx_actions_proj_status ON actions(project_id, status, priority);
508
-
509
- CREATE INDEX IF NOT EXISTS idx_fp_lookup ON failure_patterns(project_id, task_type, count DESC);
510
- CREATE INDEX IF NOT EXISTS idx_fp_recent ON failure_patterns(last_seen_at);
511
- CREATE UNIQUE INDEX IF NOT EXISTS idx_fp_unique_coalesce ON failure_patterns(COALESCE(project_id, '__GLOBAL_OR_UNKNOWN__:' || scope), task_type, error_text);
512
-
513
990
  -- summaries
514
991
  CREATE TABLE IF NOT EXISTS summaries (
515
992
  id TEXT PRIMARY KEY,
516
993
  scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
517
994
  project_id TEXT,
995
+ user_id TEXT,
996
+ agent_id TEXT,
518
997
  kind TEXT NOT NULL CHECK (kind IN ('session','rollup','failure_digest')),
519
998
  window_from INTEGER,
520
999
  window_to INTEGER,
@@ -543,16 +1022,52 @@ function runMigrations(db: Database): void {
543
1022
  summary_id TEXT NOT NULL REFERENCES summaries(id) ON DELETE CASCADE,
544
1023
  claim_id TEXT REFERENCES summary_claims(id) ON DELETE CASCADE,
545
1024
  record_id TEXT NOT NULL,
546
- grain TEXT NOT NULL CHECK (grain IN ('observation','trajectory','note')),
1025
+ record_type TEXT NOT NULL CHECK (record_type IN ('observation','trajectory','note')),
547
1026
  PRIMARY KEY (summary_id, claim_id, record_id)
548
1027
  );
549
1028
 
550
- CREATE INDEX IF NOT EXISTS idx_sum_project ON summaries(project_id);
551
- CREATE INDEX IF NOT EXISTS idx_sum_kind ON summaries(kind, created_at);
552
- CREATE INDEX IF NOT EXISTS idx_sum_latest ON summaries(is_latest);
553
- CREATE INDEX IF NOT EXISTS idx_sum_producer ON summaries(producer_tier, producer_model);
554
1029
  CREATE INDEX IF NOT EXISTS idx_sum_src_rec ON summary_sources(record_id);
555
1030
 
1031
+ -- entities
1032
+ CREATE TABLE IF NOT EXISTS entities (
1033
+ id TEXT PRIMARY KEY,
1034
+ scope TEXT NOT NULL CHECK (scope IN ('project','global','unknown')),
1035
+ project_id TEXT,
1036
+ user_id TEXT,
1037
+ agent_id TEXT,
1038
+ entity_type TEXT NOT NULL,
1039
+ name TEXT NOT NULL,
1040
+ description TEXT,
1041
+ external_ref TEXT,
1042
+ metadata_json TEXT,
1043
+ embedding BLOB,
1044
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
1045
+ updated_at INTEGER NOT NULL DEFAULT (unixepoch()),
1046
+ CHECK ((scope = 'project') = (project_id IS NOT NULL))
1047
+ );
1048
+
1049
+ CREATE INDEX IF NOT EXISTS idx_entities_scope_proj ON entities(scope, project_id, entity_type);
1050
+ CREATE INDEX IF NOT EXISTS idx_entities_ext_ref ON entities(external_ref) WHERE external_ref IS NOT NULL;
1051
+ CREATE INDEX IF NOT EXISTS idx_entities_user ON entities(user_id) WHERE user_id IS NOT NULL;
1052
+ CREATE INDEX IF NOT EXISTS idx_entities_dedup ON entities(COALESCE(project_id, '__SCOPE__:' || scope), entity_type, lower(name));
1053
+
1054
+ -- entity_edges
1055
+ CREATE TABLE IF NOT EXISTS entity_edges (
1056
+ id TEXT PRIMARY KEY,
1057
+ source_type TEXT NOT NULL,
1058
+ source_id TEXT NOT NULL,
1059
+ target_type TEXT NOT NULL,
1060
+ target_id TEXT NOT NULL,
1061
+ relation TEXT NOT NULL,
1062
+ metadata_json TEXT,
1063
+ created_at INTEGER NOT NULL DEFAULT (unixepoch()),
1064
+ UNIQUE (source_type, source_id, target_type, target_id, relation)
1065
+ );
1066
+
1067
+ CREATE INDEX IF NOT EXISTS idx_entity_edges_src ON entity_edges(source_id, relation);
1068
+ CREATE INDEX IF NOT EXISTS idx_entity_edges_tgt ON entity_edges(target_id, relation);
1069
+ CREATE INDEX IF NOT EXISTS idx_entity_edges_rel ON entity_edges(relation);
1070
+
556
1071
  -- consolidation_leases
557
1072
  CREATE TABLE IF NOT EXISTS consolidation_leases (
558
1073
  lease_id TEXT PRIMARY KEY,
@@ -569,20 +1084,8 @@ function runMigrations(db: Database): void {
569
1084
  CREATE INDEX IF NOT EXISTS idx_lease_expires ON consolidation_leases(expires_at);
570
1085
  CREATE INDEX IF NOT EXISTS idx_lease_session ON consolidation_leases(session_id);
571
1086
 
572
- -- embed_queue
573
- CREATE TABLE IF NOT EXISTS embed_queue (
574
- record_id TEXT NOT NULL,
575
- grain TEXT NOT NULL CHECK (grain IN ('observation','trajectory','note','summary')),
576
- status TEXT NOT NULL DEFAULT 'pending'
577
- CHECK (status IN ('pending','running','done','failed')),
578
- attempts INTEGER NOT NULL DEFAULT 0,
579
- last_error TEXT,
580
- target TEXT NOT NULL DEFAULT 'live', -- 'live' or a re-embed collection name
581
- queued_at INTEGER NOT NULL DEFAULT (unixepoch()),
582
- PRIMARY KEY (record_id, grain, target)
583
- );
584
-
585
- CREATE INDEX IF NOT EXISTS idx_eq_claim ON embed_queue(target, status, queued_at);
1087
+ -- embed_queue (DDL in EMBED_QUEUE_DDL; see alignEmbedQueueSchema)
1088
+ ${EMBED_QUEUE_DDL}
586
1089
 
587
1090
  -- dead_letters
588
1091
  CREATE TABLE IF NOT EXISTS dead_letters (
@@ -612,9 +1115,18 @@ function runMigrations(db: Database): void {
612
1115
  CREATE INDEX IF NOT EXISTS idx_api_keys_key ON api_keys(key);
613
1116
  `);
614
1117
 
615
- // The trajectory tables above are only created when absent; these two calls
616
- // are what reach a store that already has them. Both are idempotent and
617
- // also (re)create the trajectory indexes.
1118
+ // Legacy grain -> record_type rename before schema alignments/rebuilds
1119
+ for (const table of ['summary_sources', 'embed_queue'] as const) {
1120
+ const cols = db.prepare(`PRAGMA table_info(${table})`).all() as Array<{ name: string }>;
1121
+ const hasGrain = cols.some((c) => c.name === 'grain');
1122
+ const hasRecordType = cols.some((c) => c.name === 'record_type');
1123
+ if (hasGrain && !hasRecordType) {
1124
+ db.exec(`ALTER TABLE ${table} RENAME COLUMN grain TO record_type`);
1125
+ }
1126
+ }
1127
+
1128
+ // Schema alignments & rebuilds for pre-existing databases
1129
+ alignObservationsSchema(db);
618
1130
  alignTrajectorySchema(db, 'trajectories', TRAJECTORIES_DDL, TRAJECTORIES_INDEX_DDL);
619
1131
  alignTrajectorySchema(
620
1132
  db,
@@ -623,5 +1135,12 @@ function runMigrations(db: Database): void {
623
1135
  TRAJECTORY_ARCHIVE_INDEX_DDL
624
1136
  );
625
1137
  alignNotesSchema(db);
1138
+ alignSessionsSchema(db);
1139
+ alignSummariesSchema(db);
626
1140
  alignFailurePatternsSchema(db);
1141
+ alignActionsSchema(db);
1142
+ alignEmbedQueueSchema(db);
1143
+
1144
+ // Must run AFTER all table rebuilds so FTS triggers are never lost
1145
+ alignFtsSchema(db);
627
1146
  }