kiro-memory 1.6.0 → 1.7.1

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.
@@ -1,10 +1,376 @@
1
1
  import { createRequire } from 'module';const require = createRequire(import.meta.url);
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
2
4
  var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
3
5
  get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
4
6
  }) : x)(function(x) {
5
7
  if (typeof require !== "undefined") return require.apply(this, arguments);
6
8
  throw Error('Dynamic require of "' + x + '" is not supported');
7
9
  });
10
+ var __esm = (fn, res) => function __init() {
11
+ return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
12
+ };
13
+ var __export = (target, all) => {
14
+ for (var name in all)
15
+ __defProp(target, name, { get: all[name], enumerable: true });
16
+ };
17
+
18
+ // src/services/sqlite/Observations.ts
19
+ var Observations_exports = {};
20
+ __export(Observations_exports, {
21
+ consolidateObservations: () => consolidateObservations,
22
+ createObservation: () => createObservation,
23
+ deleteObservation: () => deleteObservation,
24
+ getObservationsByProject: () => getObservationsByProject,
25
+ getObservationsBySession: () => getObservationsBySession,
26
+ searchObservations: () => searchObservations,
27
+ updateLastAccessed: () => updateLastAccessed
28
+ });
29
+ function escapeLikePattern(input) {
30
+ return input.replace(/[%_\\]/g, "\\$&");
31
+ }
32
+ function createObservation(db, memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber) {
33
+ const now = /* @__PURE__ */ new Date();
34
+ const result = db.run(
35
+ `INSERT INTO observations
36
+ (memory_session_id, project, type, title, subtitle, text, narrative, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch)
37
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
38
+ [memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber, now.toISOString(), now.getTime()]
39
+ );
40
+ return Number(result.lastInsertRowid);
41
+ }
42
+ function getObservationsBySession(db, memorySessionId) {
43
+ const query = db.query(
44
+ "SELECT * FROM observations WHERE memory_session_id = ? ORDER BY prompt_number ASC"
45
+ );
46
+ return query.all(memorySessionId);
47
+ }
48
+ function getObservationsByProject(db, project, limit = 100) {
49
+ const query = db.query(
50
+ "SELECT * FROM observations WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
51
+ );
52
+ return query.all(project, limit);
53
+ }
54
+ function searchObservations(db, searchTerm, project) {
55
+ const sql = project ? `SELECT * FROM observations
56
+ WHERE project = ? AND (title LIKE ? ESCAPE '\\' OR text LIKE ? ESCAPE '\\' OR narrative LIKE ? ESCAPE '\\')
57
+ ORDER BY created_at_epoch DESC` : `SELECT * FROM observations
58
+ WHERE title LIKE ? ESCAPE '\\' OR text LIKE ? ESCAPE '\\' OR narrative LIKE ? ESCAPE '\\'
59
+ ORDER BY created_at_epoch DESC`;
60
+ const pattern = `%${escapeLikePattern(searchTerm)}%`;
61
+ const query = db.query(sql);
62
+ if (project) {
63
+ return query.all(project, pattern, pattern, pattern);
64
+ }
65
+ return query.all(pattern, pattern, pattern);
66
+ }
67
+ function deleteObservation(db, id) {
68
+ db.run("DELETE FROM observations WHERE id = ?", [id]);
69
+ }
70
+ function updateLastAccessed(db, ids) {
71
+ if (!Array.isArray(ids) || ids.length === 0) return;
72
+ const validIds = ids.filter((id) => typeof id === "number" && Number.isInteger(id) && id > 0).slice(0, 500);
73
+ if (validIds.length === 0) return;
74
+ const now = Date.now();
75
+ const placeholders = validIds.map(() => "?").join(",");
76
+ db.run(
77
+ `UPDATE observations SET last_accessed_epoch = ? WHERE id IN (${placeholders})`,
78
+ [now, ...validIds]
79
+ );
80
+ }
81
+ function consolidateObservations(db, project, options = {}) {
82
+ const minGroupSize = options.minGroupSize || 3;
83
+ const groups = db.query(`
84
+ SELECT type, files_modified, COUNT(*) as cnt, GROUP_CONCAT(id) as ids
85
+ FROM observations
86
+ WHERE project = ? AND files_modified IS NOT NULL AND files_modified != ''
87
+ GROUP BY type, files_modified
88
+ HAVING cnt >= ?
89
+ ORDER BY cnt DESC
90
+ `).all(project, minGroupSize);
91
+ if (groups.length === 0) return { merged: 0, removed: 0 };
92
+ let totalMerged = 0;
93
+ let totalRemoved = 0;
94
+ for (const group of groups) {
95
+ const obsIds = group.ids.split(",").map(Number);
96
+ const placeholders = obsIds.map(() => "?").join(",");
97
+ const observations = db.query(
98
+ `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`
99
+ ).all(...obsIds);
100
+ if (observations.length < minGroupSize) continue;
101
+ if (options.dryRun) {
102
+ totalMerged += 1;
103
+ totalRemoved += observations.length - 1;
104
+ continue;
105
+ }
106
+ const keeper = observations[0];
107
+ const others = observations.slice(1);
108
+ const uniqueTexts = /* @__PURE__ */ new Set();
109
+ if (keeper.text) uniqueTexts.add(keeper.text);
110
+ for (const obs of others) {
111
+ if (obs.text && !uniqueTexts.has(obs.text)) {
112
+ uniqueTexts.add(obs.text);
113
+ }
114
+ }
115
+ const consolidatedText = Array.from(uniqueTexts).join("\n---\n").substring(0, 1e5);
116
+ db.run(
117
+ "UPDATE observations SET text = ?, title = ? WHERE id = ?",
118
+ [consolidatedText, `[consolidato x${observations.length}] ${keeper.title}`, keeper.id]
119
+ );
120
+ const removeIds = others.map((o) => o.id);
121
+ const removePlaceholders = removeIds.map(() => "?").join(",");
122
+ db.run(`DELETE FROM observations WHERE id IN (${removePlaceholders})`, removeIds);
123
+ db.run(`DELETE FROM observation_embeddings WHERE observation_id IN (${removePlaceholders})`, removeIds);
124
+ totalMerged += 1;
125
+ totalRemoved += removeIds.length;
126
+ }
127
+ return { merged: totalMerged, removed: totalRemoved };
128
+ }
129
+ var init_Observations = __esm({
130
+ "src/services/sqlite/Observations.ts"() {
131
+ "use strict";
132
+ }
133
+ });
134
+
135
+ // src/services/sqlite/Search.ts
136
+ var Search_exports = {};
137
+ __export(Search_exports, {
138
+ getObservationsByIds: () => getObservationsByIds,
139
+ getProjectStats: () => getProjectStats,
140
+ getStaleObservations: () => getStaleObservations,
141
+ getTimeline: () => getTimeline,
142
+ markObservationsStale: () => markObservationsStale,
143
+ searchObservationsFTS: () => searchObservationsFTS,
144
+ searchObservationsFTSWithRank: () => searchObservationsFTSWithRank,
145
+ searchObservationsLIKE: () => searchObservationsLIKE,
146
+ searchSummariesFiltered: () => searchSummariesFiltered
147
+ });
148
+ import { existsSync as existsSync3, statSync } from "fs";
149
+ function escapeLikePattern3(input) {
150
+ return input.replace(/[%_\\]/g, "\\$&");
151
+ }
152
+ function sanitizeFTS5Query(query) {
153
+ const trimmed = query.length > 1e4 ? query.substring(0, 1e4) : query;
154
+ const terms = trimmed.replace(/[""]/g, "").split(/\s+/).filter((t) => t.length > 0).slice(0, 100).map((t) => `"${t}"`);
155
+ return terms.join(" ");
156
+ }
157
+ function searchObservationsFTS(db, query, filters = {}) {
158
+ const limit = filters.limit || 50;
159
+ try {
160
+ const safeQuery = sanitizeFTS5Query(query);
161
+ if (!safeQuery) return searchObservationsLIKE(db, query, filters);
162
+ let sql = `
163
+ SELECT o.* FROM observations o
164
+ JOIN observations_fts fts ON o.id = fts.rowid
165
+ WHERE observations_fts MATCH ?
166
+ `;
167
+ const params = [safeQuery];
168
+ if (filters.project) {
169
+ sql += " AND o.project = ?";
170
+ params.push(filters.project);
171
+ }
172
+ if (filters.type) {
173
+ sql += " AND o.type = ?";
174
+ params.push(filters.type);
175
+ }
176
+ if (filters.dateStart) {
177
+ sql += " AND o.created_at_epoch >= ?";
178
+ params.push(filters.dateStart);
179
+ }
180
+ if (filters.dateEnd) {
181
+ sql += " AND o.created_at_epoch <= ?";
182
+ params.push(filters.dateEnd);
183
+ }
184
+ sql += " ORDER BY rank LIMIT ?";
185
+ params.push(limit);
186
+ const stmt = db.query(sql);
187
+ return stmt.all(...params);
188
+ } catch {
189
+ return searchObservationsLIKE(db, query, filters);
190
+ }
191
+ }
192
+ function searchObservationsFTSWithRank(db, query, filters = {}) {
193
+ const limit = filters.limit || 50;
194
+ try {
195
+ const safeQuery = sanitizeFTS5Query(query);
196
+ if (!safeQuery) return [];
197
+ let sql = `
198
+ SELECT o.*, rank as fts5_rank FROM observations o
199
+ JOIN observations_fts fts ON o.id = fts.rowid
200
+ WHERE observations_fts MATCH ?
201
+ `;
202
+ const params = [safeQuery];
203
+ if (filters.project) {
204
+ sql += " AND o.project = ?";
205
+ params.push(filters.project);
206
+ }
207
+ if (filters.type) {
208
+ sql += " AND o.type = ?";
209
+ params.push(filters.type);
210
+ }
211
+ if (filters.dateStart) {
212
+ sql += " AND o.created_at_epoch >= ?";
213
+ params.push(filters.dateStart);
214
+ }
215
+ if (filters.dateEnd) {
216
+ sql += " AND o.created_at_epoch <= ?";
217
+ params.push(filters.dateEnd);
218
+ }
219
+ sql += " ORDER BY rank LIMIT ?";
220
+ params.push(limit);
221
+ const stmt = db.query(sql);
222
+ return stmt.all(...params);
223
+ } catch {
224
+ return [];
225
+ }
226
+ }
227
+ function searchObservationsLIKE(db, query, filters = {}) {
228
+ const limit = filters.limit || 50;
229
+ const pattern = `%${escapeLikePattern3(query)}%`;
230
+ let sql = `
231
+ SELECT * FROM observations
232
+ WHERE (title LIKE ? ESCAPE '\\' OR text LIKE ? ESCAPE '\\' OR narrative LIKE ? ESCAPE '\\' OR concepts LIKE ? ESCAPE '\\')
233
+ `;
234
+ const params = [pattern, pattern, pattern, pattern];
235
+ if (filters.project) {
236
+ sql += " AND project = ?";
237
+ params.push(filters.project);
238
+ }
239
+ if (filters.type) {
240
+ sql += " AND type = ?";
241
+ params.push(filters.type);
242
+ }
243
+ if (filters.dateStart) {
244
+ sql += " AND created_at_epoch >= ?";
245
+ params.push(filters.dateStart);
246
+ }
247
+ if (filters.dateEnd) {
248
+ sql += " AND created_at_epoch <= ?";
249
+ params.push(filters.dateEnd);
250
+ }
251
+ sql += " ORDER BY created_at_epoch DESC LIMIT ?";
252
+ params.push(limit);
253
+ const stmt = db.query(sql);
254
+ return stmt.all(...params);
255
+ }
256
+ function searchSummariesFiltered(db, query, filters = {}) {
257
+ const limit = filters.limit || 20;
258
+ const pattern = `%${escapeLikePattern3(query)}%`;
259
+ let sql = `
260
+ SELECT * FROM summaries
261
+ WHERE (request LIKE ? ESCAPE '\\' OR learned LIKE ? ESCAPE '\\' OR completed LIKE ? ESCAPE '\\' OR notes LIKE ? ESCAPE '\\' OR next_steps LIKE ? ESCAPE '\\')
262
+ `;
263
+ const params = [pattern, pattern, pattern, pattern, pattern];
264
+ if (filters.project) {
265
+ sql += " AND project = ?";
266
+ params.push(filters.project);
267
+ }
268
+ if (filters.dateStart) {
269
+ sql += " AND created_at_epoch >= ?";
270
+ params.push(filters.dateStart);
271
+ }
272
+ if (filters.dateEnd) {
273
+ sql += " AND created_at_epoch <= ?";
274
+ params.push(filters.dateEnd);
275
+ }
276
+ sql += " ORDER BY created_at_epoch DESC LIMIT ?";
277
+ params.push(limit);
278
+ const stmt = db.query(sql);
279
+ return stmt.all(...params);
280
+ }
281
+ function getObservationsByIds(db, ids) {
282
+ if (!Array.isArray(ids) || ids.length === 0) return [];
283
+ const validIds = ids.filter((id) => typeof id === "number" && Number.isInteger(id) && id > 0).slice(0, 500);
284
+ if (validIds.length === 0) return [];
285
+ const placeholders = validIds.map(() => "?").join(",");
286
+ const sql = `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`;
287
+ const stmt = db.query(sql);
288
+ return stmt.all(...validIds);
289
+ }
290
+ function getTimeline(db, anchorId, depthBefore = 5, depthAfter = 5) {
291
+ const anchorStmt = db.query("SELECT created_at_epoch FROM observations WHERE id = ?");
292
+ const anchor = anchorStmt.get(anchorId);
293
+ if (!anchor) return [];
294
+ const anchorEpoch = anchor.created_at_epoch;
295
+ const beforeStmt = db.query(`
296
+ SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
297
+ FROM observations
298
+ WHERE created_at_epoch < ?
299
+ ORDER BY created_at_epoch DESC
300
+ LIMIT ?
301
+ `);
302
+ const before = beforeStmt.all(anchorEpoch, depthBefore).reverse();
303
+ const selfStmt = db.query(`
304
+ SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
305
+ FROM observations WHERE id = ?
306
+ `);
307
+ const self = selfStmt.all(anchorId);
308
+ const afterStmt = db.query(`
309
+ SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
310
+ FROM observations
311
+ WHERE created_at_epoch > ?
312
+ ORDER BY created_at_epoch ASC
313
+ LIMIT ?
314
+ `);
315
+ const after = afterStmt.all(anchorEpoch, depthAfter);
316
+ return [...before, ...self, ...after];
317
+ }
318
+ function getProjectStats(db, project) {
319
+ const obsStmt = db.query("SELECT COUNT(*) as count FROM observations WHERE project = ?");
320
+ const sumStmt = db.query("SELECT COUNT(*) as count FROM summaries WHERE project = ?");
321
+ const sesStmt = db.query("SELECT COUNT(*) as count FROM sessions WHERE project = ?");
322
+ const prmStmt = db.query("SELECT COUNT(*) as count FROM prompts WHERE project = ?");
323
+ return {
324
+ observations: obsStmt.get(project)?.count || 0,
325
+ summaries: sumStmt.get(project)?.count || 0,
326
+ sessions: sesStmt.get(project)?.count || 0,
327
+ prompts: prmStmt.get(project)?.count || 0
328
+ };
329
+ }
330
+ function getStaleObservations(db, project) {
331
+ const rows = db.query(`
332
+ SELECT * FROM observations
333
+ WHERE project = ? AND files_modified IS NOT NULL AND files_modified != ''
334
+ ORDER BY created_at_epoch DESC
335
+ LIMIT 500
336
+ `).all(project);
337
+ const staleObs = [];
338
+ for (const obs of rows) {
339
+ if (!obs.files_modified) continue;
340
+ const files = obs.files_modified.split(",").map((f) => f.trim()).filter(Boolean);
341
+ let isStale = false;
342
+ for (const filepath of files) {
343
+ try {
344
+ if (!existsSync3(filepath)) continue;
345
+ const stat = statSync(filepath);
346
+ if (stat.mtimeMs > obs.created_at_epoch) {
347
+ isStale = true;
348
+ break;
349
+ }
350
+ } catch {
351
+ }
352
+ }
353
+ if (isStale) {
354
+ staleObs.push(obs);
355
+ }
356
+ }
357
+ return staleObs;
358
+ }
359
+ function markObservationsStale(db, ids, stale) {
360
+ if (!Array.isArray(ids) || ids.length === 0) return;
361
+ const validIds = ids.filter((id) => typeof id === "number" && Number.isInteger(id) && id > 0).slice(0, 500);
362
+ if (validIds.length === 0) return;
363
+ const placeholders = validIds.map(() => "?").join(",");
364
+ db.run(
365
+ `UPDATE observations SET is_stale = ? WHERE id IN (${placeholders})`,
366
+ [stale ? 1 : 0, ...validIds]
367
+ );
368
+ }
369
+ var init_Search = __esm({
370
+ "src/services/sqlite/Search.ts"() {
371
+ "use strict";
372
+ }
373
+ });
8
374
 
9
375
  // src/shims/bun-sqlite.ts
10
376
  import BetterSqlite3 from "better-sqlite3";
@@ -533,6 +899,55 @@ var MigrationRunner = class {
533
899
  `);
534
900
  db.run("CREATE UNIQUE INDEX IF NOT EXISTS idx_project_aliases_name ON project_aliases(project_name)");
535
901
  }
902
+ },
903
+ {
904
+ version: 4,
905
+ up: (db) => {
906
+ db.run(`
907
+ CREATE TABLE IF NOT EXISTS observation_embeddings (
908
+ observation_id INTEGER PRIMARY KEY,
909
+ embedding BLOB NOT NULL,
910
+ model TEXT NOT NULL,
911
+ dimensions INTEGER NOT NULL,
912
+ created_at TEXT NOT NULL,
913
+ FOREIGN KEY (observation_id) REFERENCES observations(id) ON DELETE CASCADE
914
+ )
915
+ `);
916
+ db.run("CREATE INDEX IF NOT EXISTS idx_embeddings_model ON observation_embeddings(model)");
917
+ }
918
+ },
919
+ {
920
+ version: 5,
921
+ up: (db) => {
922
+ db.run("ALTER TABLE observations ADD COLUMN last_accessed_epoch INTEGER");
923
+ db.run("ALTER TABLE observations ADD COLUMN is_stale INTEGER DEFAULT 0");
924
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_last_accessed ON observations(last_accessed_epoch)");
925
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_stale ON observations(is_stale)");
926
+ }
927
+ },
928
+ {
929
+ version: 6,
930
+ up: (db) => {
931
+ db.run(`
932
+ CREATE TABLE IF NOT EXISTS checkpoints (
933
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
934
+ session_id INTEGER NOT NULL,
935
+ project TEXT NOT NULL,
936
+ task TEXT NOT NULL,
937
+ progress TEXT,
938
+ next_steps TEXT,
939
+ open_questions TEXT,
940
+ relevant_files TEXT,
941
+ context_snapshot TEXT,
942
+ created_at TEXT NOT NULL,
943
+ created_at_epoch INTEGER NOT NULL,
944
+ FOREIGN KEY (session_id) REFERENCES sessions(id)
945
+ )
946
+ `);
947
+ db.run("CREATE INDEX IF NOT EXISTS idx_checkpoints_session ON checkpoints(session_id)");
948
+ db.run("CREATE INDEX IF NOT EXISTS idx_checkpoints_project ON checkpoints(project)");
949
+ db.run("CREATE INDEX IF NOT EXISTS idx_checkpoints_epoch ON checkpoints(created_at_epoch)");
950
+ }
536
951
  }
537
952
  ];
538
953
  }
@@ -562,61 +977,36 @@ function completeSession(db, id) {
562
977
  );
563
978
  }
564
979
 
565
- // src/services/sqlite/Observations.ts
566
- function createObservation(db, memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber) {
980
+ // src/services/sqlite/index.ts
981
+ init_Observations();
982
+
983
+ // src/services/sqlite/Summaries.ts
984
+ function escapeLikePattern2(input) {
985
+ return input.replace(/[%_\\]/g, "\\$&");
986
+ }
987
+ function createSummary(db, sessionId, project, request, investigated, learned, completed, nextSteps, notes) {
567
988
  const now = /* @__PURE__ */ new Date();
568
989
  const result = db.run(
569
- `INSERT INTO observations
570
- (memory_session_id, project, type, title, subtitle, text, narrative, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch)
571
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
572
- [memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber, now.toISOString(), now.getTime()]
990
+ `INSERT INTO summaries
991
+ (session_id, project, request, investigated, learned, completed, next_steps, notes, created_at, created_at_epoch)
992
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
993
+ [sessionId, project, request, investigated, learned, completed, nextSteps, notes, now.toISOString(), now.getTime()]
573
994
  );
574
995
  return Number(result.lastInsertRowid);
575
996
  }
576
- function getObservationsByProject(db, project, limit = 100) {
997
+ function getSummariesByProject(db, project, limit = 50) {
577
998
  const query = db.query(
578
- "SELECT * FROM observations WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
579
- );
580
- return query.all(project, limit);
581
- }
582
- function searchObservations(db, searchTerm, project) {
583
- const sql = project ? `SELECT * FROM observations
584
- WHERE project = ? AND (title LIKE ? OR text LIKE ? OR narrative LIKE ?)
585
- ORDER BY created_at_epoch DESC` : `SELECT * FROM observations
586
- WHERE title LIKE ? OR text LIKE ? OR narrative LIKE ?
587
- ORDER BY created_at_epoch DESC`;
588
- const pattern = `%${searchTerm}%`;
589
- const query = db.query(sql);
590
- if (project) {
591
- return query.all(project, pattern, pattern, pattern);
592
- }
593
- return query.all(pattern, pattern, pattern);
594
- }
595
-
596
- // src/services/sqlite/Summaries.ts
597
- function createSummary(db, sessionId, project, request, investigated, learned, completed, nextSteps, notes) {
598
- const now = /* @__PURE__ */ new Date();
599
- const result = db.run(
600
- `INSERT INTO summaries
601
- (session_id, project, request, investigated, learned, completed, next_steps, notes, created_at, created_at_epoch)
602
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
603
- [sessionId, project, request, investigated, learned, completed, nextSteps, notes, now.toISOString(), now.getTime()]
604
- );
605
- return Number(result.lastInsertRowid);
606
- }
607
- function getSummariesByProject(db, project, limit = 50) {
608
- const query = db.query(
609
- "SELECT * FROM summaries WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
999
+ "SELECT * FROM summaries WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
610
1000
  );
611
1001
  return query.all(project, limit);
612
1002
  }
613
1003
  function searchSummaries(db, searchTerm, project) {
614
- const sql = project ? `SELECT * FROM summaries
615
- WHERE project = ? AND (request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ?)
616
- ORDER BY created_at_epoch DESC` : `SELECT * FROM summaries
617
- WHERE request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ?
1004
+ const sql = project ? `SELECT * FROM summaries
1005
+ WHERE project = ? AND (request LIKE ? ESCAPE '\\' OR learned LIKE ? ESCAPE '\\' OR completed LIKE ? ESCAPE '\\' OR notes LIKE ? ESCAPE '\\')
1006
+ ORDER BY created_at_epoch DESC` : `SELECT * FROM summaries
1007
+ WHERE request LIKE ? ESCAPE '\\' OR learned LIKE ? ESCAPE '\\' OR completed LIKE ? ESCAPE '\\' OR notes LIKE ? ESCAPE '\\'
618
1008
  ORDER BY created_at_epoch DESC`;
619
- const pattern = `%${searchTerm}%`;
1009
+ const pattern = `%${escapeLikePattern2(searchTerm)}%`;
620
1010
  const query = db.query(sql);
621
1011
  if (project) {
622
1012
  return query.all(project, pattern, pattern, pattern, pattern);
@@ -642,135 +1032,641 @@ function getPromptsByProject(db, project, limit = 100) {
642
1032
  return query.all(project, limit);
643
1033
  }
644
1034
 
645
- // src/services/sqlite/Search.ts
646
- function sanitizeFTS5Query(query) {
647
- const terms = query.replace(/[""]/g, "").split(/\s+/).filter((t) => t.length > 0).map((t) => `"${t}"`);
648
- return terms.join(" ");
1035
+ // src/services/sqlite/Checkpoints.ts
1036
+ function createCheckpoint(db, sessionId, project, data) {
1037
+ const now = /* @__PURE__ */ new Date();
1038
+ const result = db.run(
1039
+ `INSERT INTO checkpoints (session_id, project, task, progress, next_steps, open_questions, relevant_files, context_snapshot, created_at, created_at_epoch)
1040
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1041
+ [
1042
+ sessionId,
1043
+ project,
1044
+ data.task,
1045
+ data.progress || null,
1046
+ data.nextSteps || null,
1047
+ data.openQuestions || null,
1048
+ data.relevantFiles || null,
1049
+ data.contextSnapshot || null,
1050
+ now.toISOString(),
1051
+ now.getTime()
1052
+ ]
1053
+ );
1054
+ return Number(result.lastInsertRowid);
649
1055
  }
650
- function searchObservationsFTS(db, query, filters = {}) {
651
- const limit = filters.limit || 50;
652
- try {
653
- const safeQuery = sanitizeFTS5Query(query);
654
- if (!safeQuery) return searchObservationsLIKE(db, query, filters);
655
- let sql = `
656
- SELECT o.* FROM observations o
657
- JOIN observations_fts fts ON o.id = fts.rowid
658
- WHERE observations_fts MATCH ?
659
- `;
660
- const params = [safeQuery];
661
- if (filters.project) {
662
- sql += " AND o.project = ?";
663
- params.push(filters.project);
1056
+ function getLatestCheckpoint(db, sessionId) {
1057
+ const query = db.query(
1058
+ "SELECT * FROM checkpoints WHERE session_id = ? ORDER BY created_at_epoch DESC LIMIT 1"
1059
+ );
1060
+ return query.get(sessionId);
1061
+ }
1062
+ function getLatestCheckpointByProject(db, project) {
1063
+ const query = db.query(
1064
+ "SELECT * FROM checkpoints WHERE project = ? ORDER BY created_at_epoch DESC LIMIT 1"
1065
+ );
1066
+ return query.get(project);
1067
+ }
1068
+
1069
+ // src/services/sqlite/Reports.ts
1070
+ function getReportData(db, project, startEpoch, endEpoch) {
1071
+ const startDate = new Date(startEpoch);
1072
+ const endDate = new Date(endEpoch);
1073
+ const days = Math.ceil((endEpoch - startEpoch) / (24 * 60 * 60 * 1e3));
1074
+ const label = days <= 7 ? "Weekly" : days <= 31 ? "Monthly" : "Custom";
1075
+ const countInRange = (table, epochCol = "created_at_epoch") => {
1076
+ const sql = project ? `SELECT COUNT(*) as count FROM ${table} WHERE project = ? AND ${epochCol} >= ? AND ${epochCol} <= ?` : `SELECT COUNT(*) as count FROM ${table} WHERE ${epochCol} >= ? AND ${epochCol} <= ?`;
1077
+ const stmt = db.query(sql);
1078
+ const row = project ? stmt.get(project, startEpoch, endEpoch) : stmt.get(startEpoch, endEpoch);
1079
+ return row?.count || 0;
1080
+ };
1081
+ const observations = countInRange("observations");
1082
+ const summaries = countInRange("summaries");
1083
+ const prompts = countInRange("prompts");
1084
+ const sessions = countInRange("sessions", "started_at_epoch");
1085
+ const timelineSql = project ? `SELECT DATE(datetime(created_at_epoch / 1000, 'unixepoch')) as day, COUNT(*) as count
1086
+ FROM observations
1087
+ WHERE project = ? AND created_at_epoch >= ? AND created_at_epoch <= ?
1088
+ GROUP BY day ORDER BY day ASC` : `SELECT DATE(datetime(created_at_epoch / 1000, 'unixepoch')) as day, COUNT(*) as count
1089
+ FROM observations
1090
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ?
1091
+ GROUP BY day ORDER BY day ASC`;
1092
+ const timelineStmt = db.query(timelineSql);
1093
+ const timeline = project ? timelineStmt.all(project, startEpoch, endEpoch) : timelineStmt.all(startEpoch, endEpoch);
1094
+ const typeSql = project ? `SELECT type, COUNT(*) as count FROM observations
1095
+ WHERE project = ? AND created_at_epoch >= ? AND created_at_epoch <= ?
1096
+ GROUP BY type ORDER BY count DESC` : `SELECT type, COUNT(*) as count FROM observations
1097
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ?
1098
+ GROUP BY type ORDER BY count DESC`;
1099
+ const typeStmt = db.query(typeSql);
1100
+ const typeDistribution = project ? typeStmt.all(project, startEpoch, endEpoch) : typeStmt.all(startEpoch, endEpoch);
1101
+ const sessionTotalSql = project ? `SELECT COUNT(*) as count FROM sessions WHERE project = ? AND started_at_epoch >= ? AND started_at_epoch <= ?` : `SELECT COUNT(*) as count FROM sessions WHERE started_at_epoch >= ? AND started_at_epoch <= ?`;
1102
+ const sessionTotal = (project ? db.query(sessionTotalSql).get(project, startEpoch, endEpoch)?.count : db.query(sessionTotalSql).get(startEpoch, endEpoch)?.count) || 0;
1103
+ const sessionCompletedSql = project ? `SELECT COUNT(*) as count FROM sessions WHERE project = ? AND started_at_epoch >= ? AND started_at_epoch <= ? AND status = 'completed'` : `SELECT COUNT(*) as count FROM sessions WHERE started_at_epoch >= ? AND started_at_epoch <= ? AND status = 'completed'`;
1104
+ const sessionCompleted = (project ? db.query(sessionCompletedSql).get(project, startEpoch, endEpoch)?.count : db.query(sessionCompletedSql).get(startEpoch, endEpoch)?.count) || 0;
1105
+ const sessionAvgSql = project ? `SELECT AVG((completed_at_epoch - started_at_epoch) / 1000.0 / 60.0) as avg_min
1106
+ FROM sessions
1107
+ WHERE project = ? AND started_at_epoch >= ? AND started_at_epoch <= ?
1108
+ AND status = 'completed' AND completed_at_epoch IS NOT NULL AND completed_at_epoch > started_at_epoch` : `SELECT AVG((completed_at_epoch - started_at_epoch) / 1000.0 / 60.0) as avg_min
1109
+ FROM sessions
1110
+ WHERE started_at_epoch >= ? AND started_at_epoch <= ?
1111
+ AND status = 'completed' AND completed_at_epoch IS NOT NULL AND completed_at_epoch > started_at_epoch`;
1112
+ const avgRow = project ? db.query(sessionAvgSql).get(project, startEpoch, endEpoch) : db.query(sessionAvgSql).get(startEpoch, endEpoch);
1113
+ const avgDurationMinutes = Math.round((avgRow?.avg_min || 0) * 10) / 10;
1114
+ const knowledgeSql = project ? `SELECT COUNT(*) as count FROM observations
1115
+ WHERE project = ? AND created_at_epoch >= ? AND created_at_epoch <= ?
1116
+ AND type IN ('constraint', 'decision', 'heuristic', 'rejected')` : `SELECT COUNT(*) as count FROM observations
1117
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ?
1118
+ AND type IN ('constraint', 'decision', 'heuristic', 'rejected')`;
1119
+ const knowledgeCount = (project ? db.query(knowledgeSql).get(project, startEpoch, endEpoch)?.count : db.query(knowledgeSql).get(startEpoch, endEpoch)?.count) || 0;
1120
+ const staleSql = project ? `SELECT COUNT(*) as count FROM observations
1121
+ WHERE project = ? AND created_at_epoch >= ? AND created_at_epoch <= ? AND is_stale = 1` : `SELECT COUNT(*) as count FROM observations
1122
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ? AND is_stale = 1`;
1123
+ const staleCount = (project ? db.query(staleSql).get(project, startEpoch, endEpoch)?.count : db.query(staleSql).get(startEpoch, endEpoch)?.count) || 0;
1124
+ const summarySql = project ? `SELECT learned, completed, next_steps FROM summaries
1125
+ WHERE project = ? AND created_at_epoch >= ? AND created_at_epoch <= ?
1126
+ ORDER BY created_at_epoch DESC` : `SELECT learned, completed, next_steps FROM summaries
1127
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ?
1128
+ ORDER BY created_at_epoch DESC`;
1129
+ const summaryRows = project ? db.query(summarySql).all(project, startEpoch, endEpoch) : db.query(summarySql).all(startEpoch, endEpoch);
1130
+ const topLearnings = [];
1131
+ const completedTasks = [];
1132
+ const nextStepsArr = [];
1133
+ for (const row of summaryRows) {
1134
+ if (row.learned) {
1135
+ const parts = row.learned.split("; ").filter(Boolean);
1136
+ topLearnings.push(...parts);
664
1137
  }
665
- if (filters.type) {
666
- sql += " AND o.type = ?";
667
- params.push(filters.type);
1138
+ if (row.completed) {
1139
+ const parts = row.completed.split("; ").filter(Boolean);
1140
+ completedTasks.push(...parts);
668
1141
  }
669
- if (filters.dateStart) {
670
- sql += " AND o.created_at_epoch >= ?";
671
- params.push(filters.dateStart);
1142
+ if (row.next_steps) {
1143
+ const parts = row.next_steps.split("; ").filter(Boolean);
1144
+ nextStepsArr.push(...parts);
672
1145
  }
673
- if (filters.dateEnd) {
674
- sql += " AND o.created_at_epoch <= ?";
675
- params.push(filters.dateEnd);
1146
+ }
1147
+ const filesSql = project ? `SELECT files_modified FROM observations
1148
+ WHERE project = ? AND created_at_epoch >= ? AND created_at_epoch <= ?
1149
+ AND files_modified IS NOT NULL AND files_modified != ''` : `SELECT files_modified FROM observations
1150
+ WHERE created_at_epoch >= ? AND created_at_epoch <= ?
1151
+ AND files_modified IS NOT NULL AND files_modified != ''`;
1152
+ const fileRows = project ? db.query(filesSql).all(project, startEpoch, endEpoch) : db.query(filesSql).all(startEpoch, endEpoch);
1153
+ const fileCounts = /* @__PURE__ */ new Map();
1154
+ for (const row of fileRows) {
1155
+ const files = row.files_modified.split(",").map((f) => f.trim()).filter(Boolean);
1156
+ for (const file of files) {
1157
+ fileCounts.set(file, (fileCounts.get(file) || 0) + 1);
676
1158
  }
677
- sql += " ORDER BY rank LIMIT ?";
678
- params.push(limit);
679
- const stmt = db.query(sql);
680
- return stmt.all(...params);
681
- } catch {
682
- return searchObservationsLIKE(db, query, filters);
683
1159
  }
1160
+ const fileHotspots = Array.from(fileCounts.entries()).map(([file, count]) => ({ file, count })).sort((a, b) => b.count - a.count).slice(0, 15);
1161
+ return {
1162
+ period: {
1163
+ start: startDate.toISOString().split("T")[0],
1164
+ end: endDate.toISOString().split("T")[0],
1165
+ days,
1166
+ label
1167
+ },
1168
+ overview: {
1169
+ observations,
1170
+ summaries,
1171
+ sessions,
1172
+ prompts,
1173
+ knowledgeCount,
1174
+ staleCount
1175
+ },
1176
+ timeline,
1177
+ typeDistribution,
1178
+ sessionStats: {
1179
+ total: sessionTotal,
1180
+ completed: sessionCompleted,
1181
+ avgDurationMinutes
1182
+ },
1183
+ topLearnings: [...new Set(topLearnings)].slice(0, 10),
1184
+ completedTasks: [...new Set(completedTasks)].slice(0, 10),
1185
+ nextSteps: [...new Set(nextStepsArr)].slice(0, 10),
1186
+ fileHotspots
1187
+ };
684
1188
  }
685
- function searchObservationsLIKE(db, query, filters = {}) {
686
- const limit = filters.limit || 50;
687
- const pattern = `%${query}%`;
688
- let sql = `
689
- SELECT * FROM observations
690
- WHERE (title LIKE ? OR text LIKE ? OR narrative LIKE ? OR concepts LIKE ?)
691
- `;
692
- const params = [pattern, pattern, pattern, pattern];
693
- if (filters.project) {
694
- sql += " AND project = ?";
695
- params.push(filters.project);
1189
+
1190
+ // src/services/sqlite/index.ts
1191
+ init_Search();
1192
+
1193
+ // src/sdk/index.ts
1194
+ init_Observations();
1195
+ init_Search();
1196
+
1197
+ // src/services/search/EmbeddingService.ts
1198
+ var EmbeddingService = class {
1199
+ provider = null;
1200
+ model = null;
1201
+ initialized = false;
1202
+ initializing = null;
1203
+ /**
1204
+ * Inizializza il servizio di embedding.
1205
+ * Tenta fastembed, poi @huggingface/transformers, poi fallback a null.
1206
+ */
1207
+ async initialize() {
1208
+ if (this.initialized) return this.provider !== null;
1209
+ if (this.initializing) return this.initializing;
1210
+ this.initializing = this._doInitialize();
1211
+ const result = await this.initializing;
1212
+ this.initializing = null;
1213
+ return result;
696
1214
  }
697
- if (filters.type) {
698
- sql += " AND type = ?";
699
- params.push(filters.type);
1215
+ async _doInitialize() {
1216
+ try {
1217
+ const fastembed = await import("fastembed");
1218
+ const EmbeddingModel = fastembed.EmbeddingModel || fastembed.default?.EmbeddingModel;
1219
+ const FlagEmbedding = fastembed.FlagEmbedding || fastembed.default?.FlagEmbedding;
1220
+ if (FlagEmbedding && EmbeddingModel) {
1221
+ this.model = await FlagEmbedding.init({
1222
+ model: EmbeddingModel.BGESmallENV15
1223
+ });
1224
+ this.provider = "fastembed";
1225
+ this.initialized = true;
1226
+ logger.info("EMBEDDING", "Inizializzato con fastembed (BGE-small-en-v1.5)");
1227
+ return true;
1228
+ }
1229
+ } catch (error) {
1230
+ logger.debug("EMBEDDING", `fastembed non disponibile: ${error}`);
1231
+ }
1232
+ try {
1233
+ const transformers = await import("@huggingface/transformers");
1234
+ const pipeline = transformers.pipeline || transformers.default?.pipeline;
1235
+ if (pipeline) {
1236
+ this.model = await pipeline("feature-extraction", "Xenova/all-MiniLM-L6-v2", {
1237
+ quantized: true
1238
+ });
1239
+ this.provider = "transformers";
1240
+ this.initialized = true;
1241
+ logger.info("EMBEDDING", "Inizializzato con @huggingface/transformers (all-MiniLM-L6-v2)");
1242
+ return true;
1243
+ }
1244
+ } catch (error) {
1245
+ logger.debug("EMBEDDING", `@huggingface/transformers non disponibile: ${error}`);
1246
+ }
1247
+ this.provider = null;
1248
+ this.initialized = true;
1249
+ logger.warn("EMBEDDING", "Nessun provider embedding disponibile, ricerca semantica disabilitata");
1250
+ return false;
700
1251
  }
701
- if (filters.dateStart) {
702
- sql += " AND created_at_epoch >= ?";
703
- params.push(filters.dateStart);
1252
+ /**
1253
+ * Genera embedding per un singolo testo.
1254
+ * Ritorna Float32Array con 384 dimensioni, o null se non disponibile.
1255
+ */
1256
+ async embed(text) {
1257
+ if (!this.initialized) await this.initialize();
1258
+ if (!this.provider || !this.model) return null;
1259
+ try {
1260
+ const truncated = text.substring(0, 2e3);
1261
+ if (this.provider === "fastembed") {
1262
+ return await this._embedFastembed(truncated);
1263
+ } else if (this.provider === "transformers") {
1264
+ return await this._embedTransformers(truncated);
1265
+ }
1266
+ } catch (error) {
1267
+ logger.error("EMBEDDING", `Errore generazione embedding: ${error}`);
1268
+ }
1269
+ return null;
704
1270
  }
705
- if (filters.dateEnd) {
706
- sql += " AND created_at_epoch <= ?";
707
- params.push(filters.dateEnd);
1271
+ /**
1272
+ * Genera embeddings in batch.
1273
+ */
1274
+ async embedBatch(texts) {
1275
+ if (!this.initialized) await this.initialize();
1276
+ if (!this.provider || !this.model) return texts.map(() => null);
1277
+ const results = [];
1278
+ for (const text of texts) {
1279
+ try {
1280
+ const embedding = await this.embed(text);
1281
+ results.push(embedding);
1282
+ } catch {
1283
+ results.push(null);
1284
+ }
1285
+ }
1286
+ return results;
708
1287
  }
709
- sql += " ORDER BY created_at_epoch DESC LIMIT ?";
710
- params.push(limit);
711
- const stmt = db.query(sql);
712
- return stmt.all(...params);
1288
+ /**
1289
+ * Verifica se il servizio è disponibile.
1290
+ */
1291
+ isAvailable() {
1292
+ return this.initialized && this.provider !== null;
1293
+ }
1294
+ /**
1295
+ * Nome del provider attivo.
1296
+ */
1297
+ getProvider() {
1298
+ return this.provider;
1299
+ }
1300
+ /**
1301
+ * Dimensioni del vettore embedding.
1302
+ */
1303
+ getDimensions() {
1304
+ return 384;
1305
+ }
1306
+ // --- Provider specifici ---
1307
+ async _embedFastembed(text) {
1308
+ const embeddings = this.model.embed([text], 1);
1309
+ for await (const batch of embeddings) {
1310
+ if (batch && batch.length > 0) {
1311
+ const vec = batch[0];
1312
+ return vec instanceof Float32Array ? vec : new Float32Array(vec);
1313
+ }
1314
+ }
1315
+ return null;
1316
+ }
1317
+ async _embedTransformers(text) {
1318
+ const output = await this.model(text, {
1319
+ pooling: "mean",
1320
+ normalize: true
1321
+ });
1322
+ if (output?.data) {
1323
+ return output.data instanceof Float32Array ? output.data : new Float32Array(output.data);
1324
+ }
1325
+ return null;
1326
+ }
1327
+ };
1328
+ var embeddingService = null;
1329
+ function getEmbeddingService() {
1330
+ if (!embeddingService) {
1331
+ embeddingService = new EmbeddingService();
1332
+ }
1333
+ return embeddingService;
713
1334
  }
714
- function searchSummariesFiltered(db, query, filters = {}) {
715
- const limit = filters.limit || 20;
716
- const pattern = `%${query}%`;
717
- let sql = `
718
- SELECT * FROM summaries
719
- WHERE (request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ? OR next_steps LIKE ?)
720
- `;
721
- const params = [pattern, pattern, pattern, pattern, pattern];
722
- if (filters.project) {
723
- sql += " AND project = ?";
724
- params.push(filters.project);
1335
+
1336
+ // src/services/search/VectorSearch.ts
1337
+ function cosineSimilarity(a, b) {
1338
+ if (a.length !== b.length) return 0;
1339
+ let dotProduct = 0;
1340
+ let normA = 0;
1341
+ let normB = 0;
1342
+ for (let i = 0; i < a.length; i++) {
1343
+ dotProduct += a[i] * b[i];
1344
+ normA += a[i] * a[i];
1345
+ normB += b[i] * b[i];
1346
+ }
1347
+ const denominator = Math.sqrt(normA) * Math.sqrt(normB);
1348
+ if (denominator === 0) return 0;
1349
+ return dotProduct / denominator;
1350
+ }
1351
+ function float32ToBuffer(arr) {
1352
+ return Buffer.from(arr.buffer, arr.byteOffset, arr.byteLength);
1353
+ }
1354
+ function bufferToFloat32(buf) {
1355
+ const arrayBuffer = buf.buffer.slice(buf.byteOffset, buf.byteOffset + buf.byteLength);
1356
+ return new Float32Array(arrayBuffer);
1357
+ }
1358
+ var VectorSearch = class {
1359
+ /**
1360
+ * Ricerca semantica: calcola cosine similarity tra query e tutti gli embeddings.
1361
+ */
1362
+ async search(db, queryEmbedding, options = {}) {
1363
+ const limit = options.limit || 10;
1364
+ const threshold = options.threshold || 0.3;
1365
+ try {
1366
+ let sql = `
1367
+ SELECT e.observation_id, e.embedding,
1368
+ o.title, o.text, o.type, o.project, o.created_at, o.created_at_epoch
1369
+ FROM observation_embeddings e
1370
+ JOIN observations o ON o.id = e.observation_id
1371
+ `;
1372
+ const params = [];
1373
+ if (options.project) {
1374
+ sql += " WHERE o.project = ?";
1375
+ params.push(options.project);
1376
+ }
1377
+ const rows = db.query(sql).all(...params);
1378
+ const scored = [];
1379
+ for (const row of rows) {
1380
+ const embedding = bufferToFloat32(row.embedding);
1381
+ const similarity = cosineSimilarity(queryEmbedding, embedding);
1382
+ if (similarity >= threshold) {
1383
+ scored.push({
1384
+ id: row.observation_id,
1385
+ observationId: row.observation_id,
1386
+ similarity,
1387
+ title: row.title,
1388
+ text: row.text,
1389
+ type: row.type,
1390
+ project: row.project,
1391
+ created_at: row.created_at,
1392
+ created_at_epoch: row.created_at_epoch
1393
+ });
1394
+ }
1395
+ }
1396
+ scored.sort((a, b) => b.similarity - a.similarity);
1397
+ return scored.slice(0, limit);
1398
+ } catch (error) {
1399
+ logger.error("VECTOR", `Errore ricerca vettoriale: ${error}`);
1400
+ return [];
1401
+ }
725
1402
  }
726
- if (filters.dateStart) {
727
- sql += " AND created_at_epoch >= ?";
728
- params.push(filters.dateStart);
1403
+ /**
1404
+ * Salva embedding per un'osservazione.
1405
+ */
1406
+ async storeEmbedding(db, observationId, embedding, model) {
1407
+ try {
1408
+ const blob = float32ToBuffer(embedding);
1409
+ db.query(`
1410
+ INSERT OR REPLACE INTO observation_embeddings
1411
+ (observation_id, embedding, model, dimensions, created_at)
1412
+ VALUES (?, ?, ?, ?, ?)
1413
+ `).run(
1414
+ observationId,
1415
+ blob,
1416
+ model,
1417
+ embedding.length,
1418
+ (/* @__PURE__ */ new Date()).toISOString()
1419
+ );
1420
+ logger.debug("VECTOR", `Embedding salvato per osservazione ${observationId}`);
1421
+ } catch (error) {
1422
+ logger.error("VECTOR", `Errore salvataggio embedding: ${error}`);
1423
+ }
729
1424
  }
730
- if (filters.dateEnd) {
731
- sql += " AND created_at_epoch <= ?";
732
- params.push(filters.dateEnd);
1425
+ /**
1426
+ * Genera embeddings per osservazioni che non li hanno ancora.
1427
+ */
1428
+ async backfillEmbeddings(db, batchSize = 50) {
1429
+ const embeddingService2 = getEmbeddingService();
1430
+ if (!await embeddingService2.initialize()) {
1431
+ logger.warn("VECTOR", "Embedding service non disponibile, backfill saltato");
1432
+ return 0;
1433
+ }
1434
+ const rows = db.query(`
1435
+ SELECT o.id, o.title, o.text, o.narrative, o.concepts
1436
+ FROM observations o
1437
+ LEFT JOIN observation_embeddings e ON e.observation_id = o.id
1438
+ WHERE e.observation_id IS NULL
1439
+ ORDER BY o.created_at_epoch DESC
1440
+ LIMIT ?
1441
+ `).all(batchSize);
1442
+ if (rows.length === 0) return 0;
1443
+ let count = 0;
1444
+ const model = embeddingService2.getProvider() || "unknown";
1445
+ for (const row of rows) {
1446
+ const parts = [row.title];
1447
+ if (row.text) parts.push(row.text);
1448
+ if (row.narrative) parts.push(row.narrative);
1449
+ if (row.concepts) parts.push(row.concepts);
1450
+ const fullText = parts.join(" ").substring(0, 2e3);
1451
+ const embedding = await embeddingService2.embed(fullText);
1452
+ if (embedding) {
1453
+ await this.storeEmbedding(db, row.id, embedding, model);
1454
+ count++;
1455
+ }
1456
+ }
1457
+ logger.info("VECTOR", `Backfill completato: ${count}/${rows.length} embeddings generati`);
1458
+ return count;
733
1459
  }
734
- sql += " ORDER BY created_at_epoch DESC LIMIT ?";
735
- params.push(limit);
736
- const stmt = db.query(sql);
737
- return stmt.all(...params);
1460
+ /**
1461
+ * Statistiche sugli embeddings.
1462
+ */
1463
+ getStats(db) {
1464
+ try {
1465
+ const totalRow = db.query("SELECT COUNT(*) as count FROM observations").get();
1466
+ const embeddedRow = db.query("SELECT COUNT(*) as count FROM observation_embeddings").get();
1467
+ const total = totalRow?.count || 0;
1468
+ const embedded = embeddedRow?.count || 0;
1469
+ const percentage = total > 0 ? Math.round(embedded / total * 100) : 0;
1470
+ return { total, embedded, percentage };
1471
+ } catch {
1472
+ return { total: 0, embedded: 0, percentage: 0 };
1473
+ }
1474
+ }
1475
+ };
1476
+ var vectorSearch = null;
1477
+ function getVectorSearch() {
1478
+ if (!vectorSearch) {
1479
+ vectorSearch = new VectorSearch();
1480
+ }
1481
+ return vectorSearch;
738
1482
  }
739
- function getObservationsByIds(db, ids) {
740
- if (ids.length === 0) return [];
741
- const placeholders = ids.map(() => "?").join(",");
742
- const sql = `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`;
743
- const stmt = db.query(sql);
744
- return stmt.all(...ids);
1483
+
1484
+ // src/services/search/ScoringEngine.ts
1485
+ var SEARCH_WEIGHTS = {
1486
+ semantic: 0.4,
1487
+ fts5: 0.3,
1488
+ recency: 0.2,
1489
+ projectMatch: 0.1
1490
+ };
1491
+ var CONTEXT_WEIGHTS = {
1492
+ semantic: 0,
1493
+ fts5: 0,
1494
+ recency: 0.7,
1495
+ projectMatch: 0.3
1496
+ };
1497
+ function recencyScore(createdAtEpoch, halfLifeHours = 168) {
1498
+ if (!createdAtEpoch || createdAtEpoch <= 0) return 0;
1499
+ const nowMs = Date.now();
1500
+ const ageMs = nowMs - createdAtEpoch;
1501
+ if (ageMs <= 0) return 1;
1502
+ const ageHours = ageMs / (1e3 * 60 * 60);
1503
+ return Math.exp(-ageHours * Math.LN2 / halfLifeHours);
745
1504
  }
746
- function getTimeline(db, anchorId, depthBefore = 5, depthAfter = 5) {
747
- const anchorStmt = db.query("SELECT created_at_epoch FROM observations WHERE id = ?");
748
- const anchor = anchorStmt.get(anchorId);
749
- if (!anchor) return [];
750
- const anchorEpoch = anchor.created_at_epoch;
751
- const beforeStmt = db.query(`
752
- SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
753
- FROM observations
754
- WHERE created_at_epoch < ?
755
- ORDER BY created_at_epoch DESC
756
- LIMIT ?
757
- `);
758
- const before = beforeStmt.all(anchorEpoch, depthBefore).reverse();
759
- const selfStmt = db.query(`
760
- SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
761
- FROM observations WHERE id = ?
762
- `);
763
- const self = selfStmt.all(anchorId);
764
- const afterStmt = db.query(`
765
- SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
766
- FROM observations
767
- WHERE created_at_epoch > ?
768
- ORDER BY created_at_epoch ASC
769
- LIMIT ?
770
- `);
771
- const after = afterStmt.all(anchorEpoch, depthAfter);
772
- return [...before, ...self, ...after];
1505
+ function normalizeFTS5Rank(rank, allRanks) {
1506
+ if (allRanks.length === 0) return 0;
1507
+ if (allRanks.length === 1) return 1;
1508
+ const minRank = Math.min(...allRanks);
1509
+ const maxRank = Math.max(...allRanks);
1510
+ if (minRank === maxRank) return 1;
1511
+ return (maxRank - rank) / (maxRank - minRank);
1512
+ }
1513
+ function projectMatchScore(itemProject, targetProject) {
1514
+ if (!itemProject || !targetProject) return 0;
1515
+ return itemProject.toLowerCase() === targetProject.toLowerCase() ? 1 : 0;
1516
+ }
1517
+ function computeCompositeScore(signals, weights) {
1518
+ return signals.semantic * weights.semantic + signals.fts5 * weights.fts5 + signals.recency * weights.recency + signals.projectMatch * weights.projectMatch;
773
1519
  }
1520
+ var KNOWLEDGE_TYPE_BOOST = {
1521
+ constraint: 1.3,
1522
+ decision: 1.25,
1523
+ heuristic: 1.15,
1524
+ rejected: 1.1
1525
+ };
1526
+ function knowledgeTypeBoost(type) {
1527
+ return KNOWLEDGE_TYPE_BOOST[type] ?? 1;
1528
+ }
1529
+
1530
+ // src/services/search/HybridSearch.ts
1531
+ var HybridSearch = class {
1532
+ embeddingInitialized = false;
1533
+ /**
1534
+ * Inizializza il servizio di embedding (lazy, non bloccante)
1535
+ */
1536
+ async initialize() {
1537
+ try {
1538
+ const embeddingService2 = getEmbeddingService();
1539
+ await embeddingService2.initialize();
1540
+ this.embeddingInitialized = embeddingService2.isAvailable();
1541
+ logger.info("SEARCH", `HybridSearch inizializzato (embedding: ${this.embeddingInitialized ? "attivo" : "disattivato"})`);
1542
+ } catch (error) {
1543
+ logger.warn("SEARCH", "Inizializzazione embedding fallita, uso solo FTS5", {}, error);
1544
+ this.embeddingInitialized = false;
1545
+ }
1546
+ }
1547
+ /**
1548
+ * Ricerca ibrida con scoring a 4 segnali
1549
+ */
1550
+ async search(db, query, options = {}) {
1551
+ const limit = options.limit || 10;
1552
+ const weights = options.weights || SEARCH_WEIGHTS;
1553
+ const targetProject = options.project || "";
1554
+ const rawItems = /* @__PURE__ */ new Map();
1555
+ if (this.embeddingInitialized) {
1556
+ try {
1557
+ const embeddingService2 = getEmbeddingService();
1558
+ const queryEmbedding = await embeddingService2.embed(query);
1559
+ if (queryEmbedding) {
1560
+ const vectorSearch2 = getVectorSearch();
1561
+ const vectorResults = await vectorSearch2.search(db, queryEmbedding, {
1562
+ project: options.project,
1563
+ limit: limit * 2,
1564
+ // Prendiamo piu risultati per il ranking
1565
+ threshold: 0.3
1566
+ });
1567
+ for (const hit of vectorResults) {
1568
+ rawItems.set(String(hit.observationId), {
1569
+ id: String(hit.observationId),
1570
+ title: hit.title,
1571
+ content: hit.text || "",
1572
+ type: hit.type,
1573
+ project: hit.project,
1574
+ created_at: hit.created_at,
1575
+ created_at_epoch: hit.created_at_epoch,
1576
+ semanticScore: hit.similarity,
1577
+ fts5Rank: null,
1578
+ source: "vector"
1579
+ });
1580
+ }
1581
+ logger.debug("SEARCH", `Vector search: ${vectorResults.length} risultati`);
1582
+ }
1583
+ } catch (error) {
1584
+ logger.warn("SEARCH", "Ricerca vettoriale fallita, uso solo keyword", {}, error);
1585
+ }
1586
+ }
1587
+ try {
1588
+ const { searchObservationsFTSWithRank: searchObservationsFTSWithRank2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1589
+ const keywordResults = searchObservationsFTSWithRank2(db, query, {
1590
+ project: options.project,
1591
+ limit: limit * 2
1592
+ });
1593
+ for (const obs of keywordResults) {
1594
+ const id = String(obs.id);
1595
+ const existing = rawItems.get(id);
1596
+ if (existing) {
1597
+ existing.fts5Rank = obs.fts5_rank;
1598
+ existing.source = "vector";
1599
+ } else {
1600
+ rawItems.set(id, {
1601
+ id,
1602
+ title: obs.title,
1603
+ content: obs.text || obs.narrative || "",
1604
+ type: obs.type,
1605
+ project: obs.project,
1606
+ created_at: obs.created_at,
1607
+ created_at_epoch: obs.created_at_epoch,
1608
+ semanticScore: 0,
1609
+ fts5Rank: obs.fts5_rank,
1610
+ source: "keyword"
1611
+ });
1612
+ }
1613
+ }
1614
+ logger.debug("SEARCH", `Keyword search: ${keywordResults.length} risultati`);
1615
+ } catch (error) {
1616
+ logger.error("SEARCH", "Ricerca keyword fallita", {}, error);
1617
+ }
1618
+ if (rawItems.size === 0) return [];
1619
+ const allFTS5Ranks = Array.from(rawItems.values()).filter((item) => item.fts5Rank !== null).map((item) => item.fts5Rank);
1620
+ const scored = [];
1621
+ for (const item of rawItems.values()) {
1622
+ const signals = {
1623
+ semantic: item.semanticScore,
1624
+ fts5: item.fts5Rank !== null ? normalizeFTS5Rank(item.fts5Rank, allFTS5Ranks) : 0,
1625
+ recency: recencyScore(item.created_at_epoch),
1626
+ projectMatch: targetProject ? projectMatchScore(item.project, targetProject) : 0
1627
+ };
1628
+ const score = computeCompositeScore(signals, weights);
1629
+ const isHybrid = item.semanticScore > 0 && item.fts5Rank !== null;
1630
+ const hybridBoost = isHybrid ? 1.15 : 1;
1631
+ const finalScore = Math.min(1, score * hybridBoost * knowledgeTypeBoost(item.type));
1632
+ scored.push({
1633
+ id: item.id,
1634
+ title: item.title,
1635
+ content: item.content,
1636
+ type: item.type,
1637
+ project: item.project,
1638
+ created_at: item.created_at,
1639
+ created_at_epoch: item.created_at_epoch,
1640
+ score: finalScore,
1641
+ source: isHybrid ? "hybrid" : item.source,
1642
+ signals
1643
+ });
1644
+ }
1645
+ scored.sort((a, b) => b.score - a.score);
1646
+ const finalResults = scored.slice(0, limit);
1647
+ if (finalResults.length > 0) {
1648
+ try {
1649
+ const { updateLastAccessed: updateLastAccessed3 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
1650
+ const ids = finalResults.map((r) => parseInt(r.id, 10)).filter((id) => id > 0);
1651
+ if (ids.length > 0) {
1652
+ updateLastAccessed3(db, ids);
1653
+ }
1654
+ } catch {
1655
+ }
1656
+ }
1657
+ return finalResults;
1658
+ }
1659
+ };
1660
+ var hybridSearch = null;
1661
+ function getHybridSearch() {
1662
+ if (!hybridSearch) {
1663
+ hybridSearch = new HybridSearch();
1664
+ }
1665
+ return hybridSearch;
1666
+ }
1667
+
1668
+ // src/types/worker-types.ts
1669
+ var KNOWLEDGE_TYPES = ["constraint", "decision", "heuristic", "rejected"];
774
1670
 
775
1671
  // src/sdk/index.ts
776
1672
  var KiroMemorySDK = class {
@@ -804,11 +1700,62 @@ var KiroMemorySDK = class {
804
1700
  recentPrompts: getPromptsByProject(this.db.db, this.project, 10)
805
1701
  };
806
1702
  }
1703
+ /**
1704
+ * Valida input per storeObservation
1705
+ */
1706
+ validateObservationInput(data) {
1707
+ if (!data.type || typeof data.type !== "string" || data.type.length > 100) {
1708
+ throw new Error("type \xE8 obbligatorio (stringa, max 100 caratteri)");
1709
+ }
1710
+ if (!data.title || typeof data.title !== "string" || data.title.length > 500) {
1711
+ throw new Error("title \xE8 obbligatorio (stringa, max 500 caratteri)");
1712
+ }
1713
+ if (!data.content || typeof data.content !== "string" || data.content.length > 1e5) {
1714
+ throw new Error("content \xE8 obbligatorio (stringa, max 100KB)");
1715
+ }
1716
+ }
1717
+ /**
1718
+ * Valida input per storeSummary
1719
+ */
1720
+ validateSummaryInput(data) {
1721
+ const MAX = 5e4;
1722
+ for (const [key, val] of Object.entries(data)) {
1723
+ if (val !== void 0 && val !== null) {
1724
+ if (typeof val !== "string") throw new Error(`${key} deve essere una stringa`);
1725
+ if (val.length > MAX) throw new Error(`${key} troppo grande (max 50KB)`);
1726
+ }
1727
+ }
1728
+ }
1729
+ /**
1730
+ * Genera e salva embedding per un'osservazione (fire-and-forget, non blocca)
1731
+ */
1732
+ async generateEmbeddingAsync(observationId, title, content, concepts) {
1733
+ try {
1734
+ const embeddingService2 = getEmbeddingService();
1735
+ if (!embeddingService2.isAvailable()) return;
1736
+ const parts = [title, content];
1737
+ if (concepts?.length) parts.push(concepts.join(", "));
1738
+ const fullText = parts.join(" ").substring(0, 2e3);
1739
+ const embedding = await embeddingService2.embed(fullText);
1740
+ if (embedding) {
1741
+ const vectorSearch2 = getVectorSearch();
1742
+ await vectorSearch2.storeEmbedding(
1743
+ this.db.db,
1744
+ observationId,
1745
+ embedding,
1746
+ embeddingService2.getProvider() || "unknown"
1747
+ );
1748
+ }
1749
+ } catch (error) {
1750
+ logger.debug("SDK", `Embedding generation fallita per obs ${observationId}: ${error}`);
1751
+ }
1752
+ }
807
1753
  /**
808
1754
  * Store a new observation
809
1755
  */
810
1756
  async storeObservation(data) {
811
- return createObservation(
1757
+ this.validateObservationInput(data);
1758
+ const observationId = createObservation(
812
1759
  this.db.db,
813
1760
  "sdk-" + Date.now(),
814
1761
  this.project,
@@ -829,11 +1776,76 @@ var KiroMemorySDK = class {
829
1776
  0
830
1777
  // prompt_number
831
1778
  );
1779
+ this.generateEmbeddingAsync(observationId, data.title, data.content, data.concepts).catch(() => {
1780
+ });
1781
+ return observationId;
1782
+ }
1783
+ /**
1784
+ * Salva conoscenza strutturata (constraint, decision, heuristic, rejected).
1785
+ * Usa il campo `type` per il knowledgeType e `facts` per i metadati JSON.
1786
+ */
1787
+ async storeKnowledge(data) {
1788
+ if (!KNOWLEDGE_TYPES.includes(data.knowledgeType)) {
1789
+ throw new Error(`knowledgeType non valido: ${data.knowledgeType}. Valori ammessi: ${KNOWLEDGE_TYPES.join(", ")}`);
1790
+ }
1791
+ this.validateObservationInput({ type: data.knowledgeType, title: data.title, content: data.content });
1792
+ const metadata = (() => {
1793
+ switch (data.knowledgeType) {
1794
+ case "constraint":
1795
+ return {
1796
+ knowledgeType: "constraint",
1797
+ severity: data.metadata?.severity || "soft",
1798
+ reason: data.metadata?.reason
1799
+ };
1800
+ case "decision":
1801
+ return {
1802
+ knowledgeType: "decision",
1803
+ alternatives: data.metadata?.alternatives,
1804
+ reason: data.metadata?.reason
1805
+ };
1806
+ case "heuristic":
1807
+ return {
1808
+ knowledgeType: "heuristic",
1809
+ context: data.metadata?.context,
1810
+ confidence: data.metadata?.confidence
1811
+ };
1812
+ case "rejected":
1813
+ return {
1814
+ knowledgeType: "rejected",
1815
+ reason: data.metadata?.reason || "",
1816
+ alternatives: data.metadata?.alternatives
1817
+ };
1818
+ }
1819
+ })();
1820
+ const observationId = createObservation(
1821
+ this.db.db,
1822
+ "sdk-" + Date.now(),
1823
+ data.project || this.project,
1824
+ data.knowledgeType,
1825
+ // type = knowledgeType
1826
+ data.title,
1827
+ null,
1828
+ // subtitle
1829
+ data.content,
1830
+ null,
1831
+ // narrative
1832
+ JSON.stringify(metadata),
1833
+ // facts = metadati JSON
1834
+ data.concepts?.join(", ") || null,
1835
+ data.files?.join(", ") || null,
1836
+ data.files?.join(", ") || null,
1837
+ 0
1838
+ // prompt_number
1839
+ );
1840
+ this.generateEmbeddingAsync(observationId, data.title, data.content, data.concepts).catch(() => {
1841
+ });
1842
+ return observationId;
832
1843
  }
833
1844
  /**
834
1845
  * Store a session summary
835
1846
  */
836
1847
  async storeSummary(data) {
1848
+ this.validateSummaryInput(data);
837
1849
  return createSummary(
838
1850
  this.db.db,
839
1851
  "sdk-" + Date.now(),
@@ -929,6 +1941,227 @@ var KiroMemorySDK = class {
929
1941
  getProject() {
930
1942
  return this.project;
931
1943
  }
1944
+ /**
1945
+ * Ricerca ibrida: vector search + keyword FTS5
1946
+ * Richiede inizializzazione HybridSearch (embedding service)
1947
+ */
1948
+ async hybridSearch(query, options = {}) {
1949
+ const hybridSearch2 = getHybridSearch();
1950
+ return hybridSearch2.search(this.db.db, query, {
1951
+ project: this.project,
1952
+ limit: options.limit || 10
1953
+ });
1954
+ }
1955
+ /**
1956
+ * Ricerca solo semantica (vector search)
1957
+ * Ritorna risultati basati su similarità coseno con gli embeddings
1958
+ */
1959
+ async semanticSearch(query, options = {}) {
1960
+ const embeddingService2 = getEmbeddingService();
1961
+ if (!embeddingService2.isAvailable()) {
1962
+ await embeddingService2.initialize();
1963
+ }
1964
+ if (!embeddingService2.isAvailable()) return [];
1965
+ const queryEmbedding = await embeddingService2.embed(query);
1966
+ if (!queryEmbedding) return [];
1967
+ const vectorSearch2 = getVectorSearch();
1968
+ const results = await vectorSearch2.search(this.db.db, queryEmbedding, {
1969
+ project: this.project,
1970
+ limit: options.limit || 10,
1971
+ threshold: options.threshold || 0.3
1972
+ });
1973
+ return results.map((r) => ({
1974
+ id: String(r.observationId),
1975
+ title: r.title,
1976
+ content: r.text || "",
1977
+ type: r.type,
1978
+ project: r.project,
1979
+ created_at: r.created_at,
1980
+ created_at_epoch: r.created_at_epoch,
1981
+ score: r.similarity,
1982
+ source: "vector",
1983
+ signals: {
1984
+ semantic: r.similarity,
1985
+ fts5: 0,
1986
+ recency: recencyScore(r.created_at_epoch),
1987
+ projectMatch: projectMatchScore(r.project, this.project)
1988
+ }
1989
+ }));
1990
+ }
1991
+ /**
1992
+ * Genera embeddings per osservazioni che non li hanno ancora
1993
+ */
1994
+ async backfillEmbeddings(batchSize = 50) {
1995
+ const vectorSearch2 = getVectorSearch();
1996
+ return vectorSearch2.backfillEmbeddings(this.db.db, batchSize);
1997
+ }
1998
+ /**
1999
+ * Statistiche sugli embeddings nel database
2000
+ */
2001
+ getEmbeddingStats() {
2002
+ const vectorSearch2 = getVectorSearch();
2003
+ return vectorSearch2.getStats(this.db.db);
2004
+ }
2005
+ /**
2006
+ * Inizializza il servizio di embedding (lazy, chiamare prima di hybridSearch)
2007
+ */
2008
+ async initializeEmbeddings() {
2009
+ const hybridSearch2 = getHybridSearch();
2010
+ await hybridSearch2.initialize();
2011
+ return getEmbeddingService().isAvailable();
2012
+ }
2013
+ /**
2014
+ * Contesto smart con ranking a 4 segnali e budget token.
2015
+ *
2016
+ * Se query presente: usa HybridSearch con SEARCH_WEIGHTS.
2017
+ * Se senza query: ranking per recency + project match (CONTEXT_WEIGHTS).
2018
+ */
2019
+ async getSmartContext(options = {}) {
2020
+ const tokenBudget = options.tokenBudget || parseInt(process.env.KIRO_MEMORY_CONTEXT_TOKENS || "0", 10) || 2e3;
2021
+ const summaries = getSummariesByProject(this.db.db, this.project, 5);
2022
+ let items;
2023
+ if (options.query) {
2024
+ const hybridSearch2 = getHybridSearch();
2025
+ const results = await hybridSearch2.search(this.db.db, options.query, {
2026
+ project: this.project,
2027
+ limit: 30
2028
+ });
2029
+ items = results.map((r) => ({
2030
+ id: parseInt(r.id, 10) || 0,
2031
+ title: r.title,
2032
+ content: r.content,
2033
+ type: r.type,
2034
+ project: r.project,
2035
+ created_at: r.created_at,
2036
+ created_at_epoch: r.created_at_epoch,
2037
+ score: r.score,
2038
+ signals: r.signals
2039
+ }));
2040
+ } else {
2041
+ const observations = getObservationsByProject(this.db.db, this.project, 30);
2042
+ items = observations.map((obs) => {
2043
+ const signals = {
2044
+ semantic: 0,
2045
+ fts5: 0,
2046
+ recency: recencyScore(obs.created_at_epoch),
2047
+ projectMatch: projectMatchScore(obs.project, this.project)
2048
+ };
2049
+ const baseScore = computeCompositeScore(signals, CONTEXT_WEIGHTS);
2050
+ const boostedScore = Math.min(1, baseScore * knowledgeTypeBoost(obs.type));
2051
+ return {
2052
+ id: obs.id,
2053
+ title: obs.title,
2054
+ content: obs.text || obs.narrative || "",
2055
+ type: obs.type,
2056
+ project: obs.project,
2057
+ created_at: obs.created_at,
2058
+ created_at_epoch: obs.created_at_epoch,
2059
+ score: boostedScore,
2060
+ signals
2061
+ };
2062
+ });
2063
+ items.sort((a, b) => b.score - a.score);
2064
+ }
2065
+ let tokensUsed = 0;
2066
+ for (const item of items) {
2067
+ tokensUsed += Math.ceil((item.title.length + item.content.length) / 4);
2068
+ if (tokensUsed > tokenBudget) break;
2069
+ }
2070
+ return {
2071
+ project: this.project,
2072
+ items,
2073
+ summaries,
2074
+ tokenBudget,
2075
+ tokensUsed: Math.min(tokensUsed, tokenBudget)
2076
+ };
2077
+ }
2078
+ /**
2079
+ * Rileva osservazioni stale (file modificati dopo la creazione) e le marca nel DB.
2080
+ * Ritorna il numero di osservazioni marcate come stale.
2081
+ */
2082
+ async detectStaleObservations() {
2083
+ const staleObs = getStaleObservations(this.db.db, this.project);
2084
+ if (staleObs.length > 0) {
2085
+ const ids = staleObs.map((o) => o.id);
2086
+ markObservationsStale(this.db.db, ids, true);
2087
+ }
2088
+ return staleObs.length;
2089
+ }
2090
+ /**
2091
+ * Consolida osservazioni duplicate sullo stesso file e tipo.
2092
+ * Raggruppa per (project, type, files_modified), mantiene la piu recente.
2093
+ */
2094
+ async consolidateObservations(options = {}) {
2095
+ return consolidateObservations(this.db.db, this.project, options);
2096
+ }
2097
+ /**
2098
+ * Statistiche decay: totale, stale, mai accedute, accedute di recente.
2099
+ */
2100
+ async getDecayStats() {
2101
+ const total = this.db.db.query(
2102
+ "SELECT COUNT(*) as count FROM observations WHERE project = ?"
2103
+ ).get(this.project)?.count || 0;
2104
+ const stale = this.db.db.query(
2105
+ "SELECT COUNT(*) as count FROM observations WHERE project = ? AND is_stale = 1"
2106
+ ).get(this.project)?.count || 0;
2107
+ const neverAccessed = this.db.db.query(
2108
+ "SELECT COUNT(*) as count FROM observations WHERE project = ? AND last_accessed_epoch IS NULL"
2109
+ ).get(this.project)?.count || 0;
2110
+ const recentThreshold = Date.now() - 48 * 60 * 60 * 1e3;
2111
+ const recentlyAccessed = this.db.db.query(
2112
+ "SELECT COUNT(*) as count FROM observations WHERE project = ? AND last_accessed_epoch > ?"
2113
+ ).get(this.project, recentThreshold)?.count || 0;
2114
+ return { total, stale, neverAccessed, recentlyAccessed };
2115
+ }
2116
+ /**
2117
+ * Crea un checkpoint strutturato per resume sessione.
2118
+ * Salva automaticamente un context_snapshot con le ultime 10 osservazioni.
2119
+ */
2120
+ async createCheckpoint(sessionId, data) {
2121
+ const recentObs = getObservationsByProject(this.db.db, this.project, 10);
2122
+ const contextSnapshot = JSON.stringify(
2123
+ recentObs.map((o) => ({ id: o.id, type: o.type, title: o.title, text: o.text?.substring(0, 200) }))
2124
+ );
2125
+ return createCheckpoint(this.db.db, sessionId, this.project, {
2126
+ task: data.task,
2127
+ progress: data.progress,
2128
+ nextSteps: data.nextSteps,
2129
+ openQuestions: data.openQuestions,
2130
+ relevantFiles: data.relevantFiles?.join(", "),
2131
+ contextSnapshot
2132
+ });
2133
+ }
2134
+ /**
2135
+ * Recupera l'ultimo checkpoint di una sessione specifica.
2136
+ */
2137
+ async getCheckpoint(sessionId) {
2138
+ return getLatestCheckpoint(this.db.db, sessionId);
2139
+ }
2140
+ /**
2141
+ * Recupera l'ultimo checkpoint per il progetto corrente.
2142
+ * Utile per resume automatico senza specificare session ID.
2143
+ */
2144
+ async getLatestProjectCheckpoint() {
2145
+ return getLatestCheckpointByProject(this.db.db, this.project);
2146
+ }
2147
+ /**
2148
+ * Genera un report di attività per il progetto corrente.
2149
+ * Aggrega osservazioni, sessioni, summaries e file per un periodo temporale.
2150
+ */
2151
+ async generateReport(options) {
2152
+ const now = /* @__PURE__ */ new Date();
2153
+ let startEpoch;
2154
+ let endEpoch = now.getTime();
2155
+ if (options?.startDate && options?.endDate) {
2156
+ startEpoch = options.startDate.getTime();
2157
+ endEpoch = options.endDate.getTime();
2158
+ } else {
2159
+ const period = options?.period || "weekly";
2160
+ const daysBack = period === "monthly" ? 30 : 7;
2161
+ startEpoch = endEpoch - daysBack * 24 * 60 * 60 * 1e3;
2162
+ }
2163
+ return getReportData(this.db.db, this.project, startEpoch, endEpoch);
2164
+ }
932
2165
  /**
933
2166
  * Getter for direct database access (for API routes)
934
2167
  */