kiro-memory 1.0.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.
@@ -0,0 +1,1163 @@
1
+ #!/usr/bin/env node
2
+ var __defProp = Object.defineProperty;
3
+ var __getOwnPropNames = Object.getOwnPropertyNames;
4
+ var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
5
+ get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
6
+ }) : x)(function(x) {
7
+ if (typeof require !== "undefined") return require.apply(this, arguments);
8
+ throw Error('Dynamic require of "' + x + '" is not supported');
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/Sessions.ts
19
+ var Sessions_exports = {};
20
+ __export(Sessions_exports, {
21
+ completeSession: () => completeSession,
22
+ createSession: () => createSession,
23
+ failSession: () => failSession,
24
+ getActiveSessions: () => getActiveSessions,
25
+ getSessionByContentId: () => getSessionByContentId,
26
+ getSessionById: () => getSessionById,
27
+ getSessionsByProject: () => getSessionsByProject,
28
+ updateSessionMemoryId: () => updateSessionMemoryId
29
+ });
30
+ function createSession(db, contentSessionId, project, userPrompt) {
31
+ const now = /* @__PURE__ */ new Date();
32
+ const result = db.run(
33
+ `INSERT INTO sessions (content_session_id, project, user_prompt, status, started_at, started_at_epoch)
34
+ VALUES (?, ?, ?, 'active', ?, ?)`,
35
+ [contentSessionId, project, userPrompt, now.toISOString(), now.getTime()]
36
+ );
37
+ return Number(result.lastInsertRowid);
38
+ }
39
+ function getSessionByContentId(db, contentSessionId) {
40
+ const query = db.query("SELECT * FROM sessions WHERE content_session_id = ?");
41
+ return query.get(contentSessionId);
42
+ }
43
+ function getSessionById(db, id) {
44
+ const query = db.query("SELECT * FROM sessions WHERE id = ?");
45
+ return query.get(id);
46
+ }
47
+ function updateSessionMemoryId(db, id, memorySessionId) {
48
+ db.run(
49
+ "UPDATE sessions SET memory_session_id = ? WHERE id = ?",
50
+ [memorySessionId, id]
51
+ );
52
+ }
53
+ function completeSession(db, id) {
54
+ const now = /* @__PURE__ */ new Date();
55
+ db.run(
56
+ `UPDATE sessions
57
+ SET status = 'completed', completed_at = ?, completed_at_epoch = ?
58
+ WHERE id = ?`,
59
+ [now.toISOString(), now.getTime(), id]
60
+ );
61
+ }
62
+ function failSession(db, id) {
63
+ const now = /* @__PURE__ */ new Date();
64
+ db.run(
65
+ `UPDATE sessions
66
+ SET status = 'failed', completed_at = ?, completed_at_epoch = ?
67
+ WHERE id = ?`,
68
+ [now.toISOString(), now.getTime(), id]
69
+ );
70
+ }
71
+ function getActiveSessions(db) {
72
+ const query = db.query("SELECT * FROM sessions WHERE status = 'active' ORDER BY started_at_epoch DESC");
73
+ return query.all();
74
+ }
75
+ function getSessionsByProject(db, project, limit = 100) {
76
+ const query = db.query("SELECT * FROM sessions WHERE project = ? ORDER BY started_at_epoch DESC LIMIT ?");
77
+ return query.all(project, limit);
78
+ }
79
+ var init_Sessions = __esm({
80
+ "src/services/sqlite/Sessions.ts"() {
81
+ "use strict";
82
+ }
83
+ });
84
+
85
+ // src/services/sqlite/Observations.ts
86
+ var Observations_exports = {};
87
+ __export(Observations_exports, {
88
+ createObservation: () => createObservation,
89
+ deleteObservation: () => deleteObservation,
90
+ getObservationsByProject: () => getObservationsByProject,
91
+ getObservationsBySession: () => getObservationsBySession,
92
+ searchObservations: () => searchObservations
93
+ });
94
+ function createObservation(db, memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber) {
95
+ const now = /* @__PURE__ */ new Date();
96
+ const result = db.run(
97
+ `INSERT INTO observations
98
+ (memory_session_id, project, type, title, subtitle, text, narrative, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch)
99
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
100
+ [memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber, now.toISOString(), now.getTime()]
101
+ );
102
+ return Number(result.lastInsertRowid);
103
+ }
104
+ function getObservationsBySession(db, memorySessionId) {
105
+ const query = db.query(
106
+ "SELECT * FROM observations WHERE memory_session_id = ? ORDER BY prompt_number ASC"
107
+ );
108
+ return query.all(memorySessionId);
109
+ }
110
+ function getObservationsByProject(db, project, limit = 100) {
111
+ const query = db.query(
112
+ "SELECT * FROM observations WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
113
+ );
114
+ return query.all(project, limit);
115
+ }
116
+ function searchObservations(db, searchTerm, project) {
117
+ const sql = project ? `SELECT * FROM observations
118
+ WHERE project = ? AND (title LIKE ? OR text LIKE ? OR narrative LIKE ?)
119
+ ORDER BY created_at_epoch DESC` : `SELECT * FROM observations
120
+ WHERE title LIKE ? OR text LIKE ? OR narrative LIKE ?
121
+ ORDER BY created_at_epoch DESC`;
122
+ const pattern = `%${searchTerm}%`;
123
+ const query = db.query(sql);
124
+ if (project) {
125
+ return query.all(project, pattern, pattern, pattern);
126
+ }
127
+ return query.all(pattern, pattern, pattern);
128
+ }
129
+ function deleteObservation(db, id) {
130
+ db.run("DELETE FROM observations WHERE id = ?", [id]);
131
+ }
132
+ var init_Observations = __esm({
133
+ "src/services/sqlite/Observations.ts"() {
134
+ "use strict";
135
+ }
136
+ });
137
+
138
+ // src/services/sqlite/Summaries.ts
139
+ var Summaries_exports = {};
140
+ __export(Summaries_exports, {
141
+ createSummary: () => createSummary,
142
+ deleteSummary: () => deleteSummary,
143
+ getSummariesByProject: () => getSummariesByProject,
144
+ getSummaryBySession: () => getSummaryBySession,
145
+ searchSummaries: () => searchSummaries
146
+ });
147
+ function createSummary(db, sessionId, project, request, investigated, learned, completed, nextSteps, notes) {
148
+ const now = /* @__PURE__ */ new Date();
149
+ const result = db.run(
150
+ `INSERT INTO summaries
151
+ (session_id, project, request, investigated, learned, completed, next_steps, notes, created_at, created_at_epoch)
152
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
153
+ [sessionId, project, request, investigated, learned, completed, nextSteps, notes, now.toISOString(), now.getTime()]
154
+ );
155
+ return Number(result.lastInsertRowid);
156
+ }
157
+ function getSummaryBySession(db, sessionId) {
158
+ const query = db.query("SELECT * FROM summaries WHERE session_id = ? ORDER BY created_at_epoch DESC LIMIT 1");
159
+ return query.get(sessionId);
160
+ }
161
+ function getSummariesByProject(db, project, limit = 50) {
162
+ const query = db.query(
163
+ "SELECT * FROM summaries WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
164
+ );
165
+ return query.all(project, limit);
166
+ }
167
+ function searchSummaries(db, searchTerm, project) {
168
+ const sql = project ? `SELECT * FROM summaries
169
+ WHERE project = ? AND (request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ?)
170
+ ORDER BY created_at_epoch DESC` : `SELECT * FROM summaries
171
+ WHERE request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ?
172
+ ORDER BY created_at_epoch DESC`;
173
+ const pattern = `%${searchTerm}%`;
174
+ const query = db.query(sql);
175
+ if (project) {
176
+ return query.all(project, pattern, pattern, pattern, pattern);
177
+ }
178
+ return query.all(pattern, pattern, pattern, pattern);
179
+ }
180
+ function deleteSummary(db, id) {
181
+ db.run("DELETE FROM summaries WHERE id = ?", [id]);
182
+ }
183
+ var init_Summaries = __esm({
184
+ "src/services/sqlite/Summaries.ts"() {
185
+ "use strict";
186
+ }
187
+ });
188
+
189
+ // src/services/sqlite/Prompts.ts
190
+ var Prompts_exports = {};
191
+ __export(Prompts_exports, {
192
+ createPrompt: () => createPrompt,
193
+ deletePrompt: () => deletePrompt,
194
+ getLatestPrompt: () => getLatestPrompt,
195
+ getPromptsByProject: () => getPromptsByProject,
196
+ getPromptsBySession: () => getPromptsBySession
197
+ });
198
+ function createPrompt(db, contentSessionId, project, promptNumber, promptText) {
199
+ const now = /* @__PURE__ */ new Date();
200
+ const result = db.run(
201
+ `INSERT INTO prompts
202
+ (content_session_id, project, prompt_number, prompt_text, created_at, created_at_epoch)
203
+ VALUES (?, ?, ?, ?, ?, ?)`,
204
+ [contentSessionId, project, promptNumber, promptText, now.toISOString(), now.getTime()]
205
+ );
206
+ return Number(result.lastInsertRowid);
207
+ }
208
+ function getPromptsBySession(db, contentSessionId) {
209
+ const query = db.query(
210
+ "SELECT * FROM prompts WHERE content_session_id = ? ORDER BY prompt_number ASC"
211
+ );
212
+ return query.all(contentSessionId);
213
+ }
214
+ function getPromptsByProject(db, project, limit = 100) {
215
+ const query = db.query(
216
+ "SELECT * FROM prompts WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
217
+ );
218
+ return query.all(project, limit);
219
+ }
220
+ function getLatestPrompt(db, contentSessionId) {
221
+ const query = db.query(
222
+ "SELECT * FROM prompts WHERE content_session_id = ? ORDER BY prompt_number DESC LIMIT 1"
223
+ );
224
+ return query.get(contentSessionId);
225
+ }
226
+ function deletePrompt(db, id) {
227
+ db.run("DELETE FROM prompts WHERE id = ?", [id]);
228
+ }
229
+ var init_Prompts = __esm({
230
+ "src/services/sqlite/Prompts.ts"() {
231
+ "use strict";
232
+ }
233
+ });
234
+
235
+ // src/services/sqlite/Search.ts
236
+ var Search_exports = {};
237
+ __export(Search_exports, {
238
+ getObservationsByIds: () => getObservationsByIds,
239
+ getProjectStats: () => getProjectStats,
240
+ getTimeline: () => getTimeline,
241
+ searchObservationsFTS: () => searchObservationsFTS,
242
+ searchObservationsLIKE: () => searchObservationsLIKE,
243
+ searchSummariesFiltered: () => searchSummariesFiltered
244
+ });
245
+ function searchObservationsFTS(db, query, filters = {}) {
246
+ const limit = filters.limit || 50;
247
+ try {
248
+ let sql = `
249
+ SELECT o.* FROM observations o
250
+ JOIN observations_fts fts ON o.id = fts.rowid
251
+ WHERE observations_fts MATCH ?
252
+ `;
253
+ const params = [query];
254
+ if (filters.project) {
255
+ sql += " AND o.project = ?";
256
+ params.push(filters.project);
257
+ }
258
+ if (filters.type) {
259
+ sql += " AND o.type = ?";
260
+ params.push(filters.type);
261
+ }
262
+ if (filters.dateStart) {
263
+ sql += " AND o.created_at_epoch >= ?";
264
+ params.push(filters.dateStart);
265
+ }
266
+ if (filters.dateEnd) {
267
+ sql += " AND o.created_at_epoch <= ?";
268
+ params.push(filters.dateEnd);
269
+ }
270
+ sql += " ORDER BY rank LIMIT ?";
271
+ params.push(limit);
272
+ const stmt = db.query(sql);
273
+ return stmt.all(...params);
274
+ } catch {
275
+ return searchObservationsLIKE(db, query, filters);
276
+ }
277
+ }
278
+ function searchObservationsLIKE(db, query, filters = {}) {
279
+ const limit = filters.limit || 50;
280
+ const pattern = `%${query}%`;
281
+ let sql = `
282
+ SELECT * FROM observations
283
+ WHERE (title LIKE ? OR text LIKE ? OR narrative LIKE ? OR concepts LIKE ?)
284
+ `;
285
+ const params = [pattern, pattern, pattern, pattern];
286
+ if (filters.project) {
287
+ sql += " AND project = ?";
288
+ params.push(filters.project);
289
+ }
290
+ if (filters.type) {
291
+ sql += " AND type = ?";
292
+ params.push(filters.type);
293
+ }
294
+ if (filters.dateStart) {
295
+ sql += " AND created_at_epoch >= ?";
296
+ params.push(filters.dateStart);
297
+ }
298
+ if (filters.dateEnd) {
299
+ sql += " AND created_at_epoch <= ?";
300
+ params.push(filters.dateEnd);
301
+ }
302
+ sql += " ORDER BY created_at_epoch DESC LIMIT ?";
303
+ params.push(limit);
304
+ const stmt = db.query(sql);
305
+ return stmt.all(...params);
306
+ }
307
+ function searchSummariesFiltered(db, query, filters = {}) {
308
+ const limit = filters.limit || 20;
309
+ const pattern = `%${query}%`;
310
+ let sql = `
311
+ SELECT * FROM summaries
312
+ WHERE (request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ? OR next_steps LIKE ?)
313
+ `;
314
+ const params = [pattern, pattern, pattern, pattern, pattern];
315
+ if (filters.project) {
316
+ sql += " AND project = ?";
317
+ params.push(filters.project);
318
+ }
319
+ if (filters.dateStart) {
320
+ sql += " AND created_at_epoch >= ?";
321
+ params.push(filters.dateStart);
322
+ }
323
+ if (filters.dateEnd) {
324
+ sql += " AND created_at_epoch <= ?";
325
+ params.push(filters.dateEnd);
326
+ }
327
+ sql += " ORDER BY created_at_epoch DESC LIMIT ?";
328
+ params.push(limit);
329
+ const stmt = db.query(sql);
330
+ return stmt.all(...params);
331
+ }
332
+ function getObservationsByIds(db, ids) {
333
+ if (ids.length === 0) return [];
334
+ const placeholders = ids.map(() => "?").join(",");
335
+ const sql = `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`;
336
+ const stmt = db.query(sql);
337
+ return stmt.all(...ids);
338
+ }
339
+ function getTimeline(db, anchorId, depthBefore = 5, depthAfter = 5) {
340
+ const anchorStmt = db.query("SELECT created_at_epoch FROM observations WHERE id = ?");
341
+ const anchor = anchorStmt.get(anchorId);
342
+ if (!anchor) return [];
343
+ const anchorEpoch = anchor.created_at_epoch;
344
+ const beforeStmt = db.query(`
345
+ SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
346
+ FROM observations
347
+ WHERE created_at_epoch < ?
348
+ ORDER BY created_at_epoch DESC
349
+ LIMIT ?
350
+ `);
351
+ const before = beforeStmt.all(anchorEpoch, depthBefore).reverse();
352
+ const selfStmt = db.query(`
353
+ SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
354
+ FROM observations WHERE id = ?
355
+ `);
356
+ const self = selfStmt.all(anchorId);
357
+ const afterStmt = db.query(`
358
+ SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
359
+ FROM observations
360
+ WHERE created_at_epoch > ?
361
+ ORDER BY created_at_epoch ASC
362
+ LIMIT ?
363
+ `);
364
+ const after = afterStmt.all(anchorEpoch, depthAfter);
365
+ return [...before, ...self, ...after];
366
+ }
367
+ function getProjectStats(db, project) {
368
+ const obsStmt = db.query("SELECT COUNT(*) as count FROM observations WHERE project = ?");
369
+ const sumStmt = db.query("SELECT COUNT(*) as count FROM summaries WHERE project = ?");
370
+ const sesStmt = db.query("SELECT COUNT(*) as count FROM sessions WHERE project = ?");
371
+ const prmStmt = db.query("SELECT COUNT(*) as count FROM prompts WHERE project = ?");
372
+ return {
373
+ observations: obsStmt.get(project)?.count || 0,
374
+ summaries: sumStmt.get(project)?.count || 0,
375
+ sessions: sesStmt.get(project)?.count || 0,
376
+ prompts: prmStmt.get(project)?.count || 0
377
+ };
378
+ }
379
+ var init_Search = __esm({
380
+ "src/services/sqlite/Search.ts"() {
381
+ "use strict";
382
+ }
383
+ });
384
+
385
+ // src/hooks/utils.ts
386
+ async function readStdin() {
387
+ return new Promise((resolve, reject) => {
388
+ let data = "";
389
+ process.stdin.setEncoding("utf8");
390
+ process.stdin.on("data", (chunk) => {
391
+ data += chunk;
392
+ });
393
+ process.stdin.on("end", () => {
394
+ try {
395
+ if (!data.trim()) {
396
+ resolve({
397
+ hook_event_name: "agentSpawn",
398
+ cwd: process.cwd()
399
+ });
400
+ return;
401
+ }
402
+ resolve(JSON.parse(data));
403
+ } catch (err) {
404
+ reject(new Error(`Errore parsing stdin JSON: ${err}`));
405
+ }
406
+ });
407
+ process.stdin.on("error", reject);
408
+ setTimeout(() => {
409
+ if (!data.trim()) {
410
+ resolve({
411
+ hook_event_name: "agentSpawn",
412
+ cwd: process.cwd()
413
+ });
414
+ }
415
+ }, 5e3);
416
+ });
417
+ }
418
+ function detectProject(cwd) {
419
+ try {
420
+ const { execSync } = __require("child_process");
421
+ const gitRoot = execSync("git rev-parse --show-toplevel", {
422
+ cwd,
423
+ encoding: "utf8",
424
+ stdio: ["pipe", "pipe", "ignore"]
425
+ }).trim();
426
+ return gitRoot.split("/").pop() || "default";
427
+ } catch {
428
+ return cwd.split("/").pop() || "default";
429
+ }
430
+ }
431
+ async function runHook(name, handler) {
432
+ try {
433
+ const input = await readStdin();
434
+ await handler(input);
435
+ process.exit(0);
436
+ } catch (error) {
437
+ process.stderr.write(`[contextkit:${name}] Errore: ${error}
438
+ `);
439
+ process.exit(0);
440
+ }
441
+ }
442
+
443
+ // src/shims/bun-sqlite.ts
444
+ import BetterSqlite3 from "better-sqlite3";
445
+ var Database = class {
446
+ _db;
447
+ constructor(path, options) {
448
+ this._db = new BetterSqlite3(path, {
449
+ // better-sqlite3 crea il file di default (non serve 'create')
450
+ readonly: options?.readwrite === false ? true : false
451
+ });
452
+ }
453
+ /**
454
+ * Esegui una query SQL senza risultati
455
+ */
456
+ run(sql, params) {
457
+ const stmt = this._db.prepare(sql);
458
+ const result = params ? stmt.run(...params) : stmt.run();
459
+ return result;
460
+ }
461
+ /**
462
+ * Prepara una query con interfaccia compatibile bun:sqlite
463
+ */
464
+ query(sql) {
465
+ return new BunQueryCompat(this._db, sql);
466
+ }
467
+ /**
468
+ * Crea una transazione
469
+ */
470
+ transaction(fn) {
471
+ return this._db.transaction(fn);
472
+ }
473
+ /**
474
+ * Chiudi la connessione
475
+ */
476
+ close() {
477
+ this._db.close();
478
+ }
479
+ };
480
+ var BunQueryCompat = class {
481
+ _db;
482
+ _sql;
483
+ constructor(db, sql) {
484
+ this._db = db;
485
+ this._sql = sql;
486
+ }
487
+ /**
488
+ * Restituisce tutte le righe
489
+ */
490
+ all(...params) {
491
+ const stmt = this._db.prepare(this._sql);
492
+ return params.length > 0 ? stmt.all(...params) : stmt.all();
493
+ }
494
+ /**
495
+ * Restituisce la prima riga o null
496
+ */
497
+ get(...params) {
498
+ const stmt = this._db.prepare(this._sql);
499
+ return params.length > 0 ? stmt.get(...params) : stmt.get();
500
+ }
501
+ /**
502
+ * Esegui senza risultati
503
+ */
504
+ run(...params) {
505
+ const stmt = this._db.prepare(this._sql);
506
+ return params.length > 0 ? stmt.run(...params) : stmt.run();
507
+ }
508
+ };
509
+
510
+ // src/shared/paths.ts
511
+ import { join as join2, dirname, basename } from "path";
512
+ import { homedir as homedir2 } from "os";
513
+ import { mkdirSync as mkdirSync2 } from "fs";
514
+ import { fileURLToPath } from "url";
515
+
516
+ // src/utils/logger.ts
517
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
518
+ import { join } from "path";
519
+ import { homedir } from "os";
520
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
521
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
522
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
523
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
524
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
525
+ LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
526
+ return LogLevel2;
527
+ })(LogLevel || {});
528
+ var DEFAULT_DATA_DIR = join(homedir(), ".contextkit");
529
+ var Logger = class {
530
+ level = null;
531
+ useColor;
532
+ logFilePath = null;
533
+ logFileInitialized = false;
534
+ constructor() {
535
+ this.useColor = process.stdout.isTTY ?? false;
536
+ }
537
+ /**
538
+ * Initialize log file path and ensure directory exists (lazy initialization)
539
+ */
540
+ ensureLogFileInitialized() {
541
+ if (this.logFileInitialized) return;
542
+ this.logFileInitialized = true;
543
+ try {
544
+ const logsDir = join(DEFAULT_DATA_DIR, "logs");
545
+ if (!existsSync(logsDir)) {
546
+ mkdirSync(logsDir, { recursive: true });
547
+ }
548
+ const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
549
+ this.logFilePath = join(logsDir, `contextkit-${date}.log`);
550
+ } catch (error) {
551
+ console.error("[LOGGER] Failed to initialize log file:", error);
552
+ this.logFilePath = null;
553
+ }
554
+ }
555
+ /**
556
+ * Lazy-load log level from settings file
557
+ */
558
+ getLevel() {
559
+ if (this.level === null) {
560
+ try {
561
+ const settingsPath = join(DEFAULT_DATA_DIR, "settings.json");
562
+ if (existsSync(settingsPath)) {
563
+ const settingsData = readFileSync(settingsPath, "utf-8");
564
+ const settings = JSON.parse(settingsData);
565
+ const envLevel = (settings.CONTEXTKIT_LOG_LEVEL || "INFO").toUpperCase();
566
+ this.level = LogLevel[envLevel] ?? 1 /* INFO */;
567
+ } else {
568
+ this.level = 1 /* INFO */;
569
+ }
570
+ } catch (error) {
571
+ this.level = 1 /* INFO */;
572
+ }
573
+ }
574
+ return this.level;
575
+ }
576
+ /**
577
+ * Create correlation ID for tracking an observation through the pipeline
578
+ */
579
+ correlationId(sessionId, observationNum) {
580
+ return `obs-${sessionId}-${observationNum}`;
581
+ }
582
+ /**
583
+ * Create session correlation ID
584
+ */
585
+ sessionId(sessionId) {
586
+ return `session-${sessionId}`;
587
+ }
588
+ /**
589
+ * Format data for logging - create compact summaries instead of full dumps
590
+ */
591
+ formatData(data) {
592
+ if (data === null || data === void 0) return "";
593
+ if (typeof data === "string") return data;
594
+ if (typeof data === "number") return data.toString();
595
+ if (typeof data === "boolean") return data.toString();
596
+ if (typeof data === "object") {
597
+ if (data instanceof Error) {
598
+ return this.getLevel() === 0 /* DEBUG */ ? `${data.message}
599
+ ${data.stack}` : data.message;
600
+ }
601
+ if (Array.isArray(data)) {
602
+ return `[${data.length} items]`;
603
+ }
604
+ const keys = Object.keys(data);
605
+ if (keys.length === 0) return "{}";
606
+ if (keys.length <= 3) {
607
+ return JSON.stringify(data);
608
+ }
609
+ return `{${keys.length} keys: ${keys.slice(0, 3).join(", ")}...}`;
610
+ }
611
+ return String(data);
612
+ }
613
+ /**
614
+ * Format timestamp in local timezone (YYYY-MM-DD HH:MM:SS.mmm)
615
+ */
616
+ formatTimestamp(date) {
617
+ const year = date.getFullYear();
618
+ const month = String(date.getMonth() + 1).padStart(2, "0");
619
+ const day = String(date.getDate()).padStart(2, "0");
620
+ const hours = String(date.getHours()).padStart(2, "0");
621
+ const minutes = String(date.getMinutes()).padStart(2, "0");
622
+ const seconds = String(date.getSeconds()).padStart(2, "0");
623
+ const ms = String(date.getMilliseconds()).padStart(3, "0");
624
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
625
+ }
626
+ /**
627
+ * Core logging method
628
+ */
629
+ log(level, component, message, context, data) {
630
+ if (level < this.getLevel()) return;
631
+ this.ensureLogFileInitialized();
632
+ const timestamp = this.formatTimestamp(/* @__PURE__ */ new Date());
633
+ const levelStr = LogLevel[level].padEnd(5);
634
+ const componentStr = component.padEnd(6);
635
+ let correlationStr = "";
636
+ if (context?.correlationId) {
637
+ correlationStr = `[${context.correlationId}] `;
638
+ } else if (context?.sessionId) {
639
+ correlationStr = `[session-${context.sessionId}] `;
640
+ }
641
+ let dataStr = "";
642
+ if (data !== void 0 && data !== null) {
643
+ if (data instanceof Error) {
644
+ dataStr = this.getLevel() === 0 /* DEBUG */ ? `
645
+ ${data.message}
646
+ ${data.stack}` : ` ${data.message}`;
647
+ } else if (this.getLevel() === 0 /* DEBUG */ && typeof data === "object") {
648
+ dataStr = "\n" + JSON.stringify(data, null, 2);
649
+ } else {
650
+ dataStr = " " + this.formatData(data);
651
+ }
652
+ }
653
+ let contextStr = "";
654
+ if (context) {
655
+ const { sessionId, memorySessionId, correlationId, ...rest } = context;
656
+ if (Object.keys(rest).length > 0) {
657
+ const pairs = Object.entries(rest).map(([k, v]) => `${k}=${v}`);
658
+ contextStr = ` {${pairs.join(", ")}}`;
659
+ }
660
+ }
661
+ const logLine = `[${timestamp}] [${levelStr}] [${componentStr}] ${correlationStr}${message}${contextStr}${dataStr}`;
662
+ if (this.logFilePath) {
663
+ try {
664
+ appendFileSync(this.logFilePath, logLine + "\n", "utf8");
665
+ } catch (error) {
666
+ process.stderr.write(`[LOGGER] Failed to write to log file: ${error}
667
+ `);
668
+ }
669
+ } else {
670
+ process.stderr.write(logLine + "\n");
671
+ }
672
+ }
673
+ // Public logging methods
674
+ debug(component, message, context, data) {
675
+ this.log(0 /* DEBUG */, component, message, context, data);
676
+ }
677
+ info(component, message, context, data) {
678
+ this.log(1 /* INFO */, component, message, context, data);
679
+ }
680
+ warn(component, message, context, data) {
681
+ this.log(2 /* WARN */, component, message, context, data);
682
+ }
683
+ error(component, message, context, data) {
684
+ this.log(3 /* ERROR */, component, message, context, data);
685
+ }
686
+ /**
687
+ * Log data flow: input → processing
688
+ */
689
+ dataIn(component, message, context, data) {
690
+ this.info(component, `\u2192 ${message}`, context, data);
691
+ }
692
+ /**
693
+ * Log data flow: processing → output
694
+ */
695
+ dataOut(component, message, context, data) {
696
+ this.info(component, `\u2190 ${message}`, context, data);
697
+ }
698
+ /**
699
+ * Log successful completion
700
+ */
701
+ success(component, message, context, data) {
702
+ this.info(component, `\u2713 ${message}`, context, data);
703
+ }
704
+ /**
705
+ * Log failure
706
+ */
707
+ failure(component, message, context, data) {
708
+ this.error(component, `\u2717 ${message}`, context, data);
709
+ }
710
+ /**
711
+ * Log timing information
712
+ */
713
+ timing(component, message, durationMs, context) {
714
+ this.info(component, `\u23F1 ${message}`, context, { duration: `${durationMs}ms` });
715
+ }
716
+ /**
717
+ * Happy Path Error - logs when the expected "happy path" fails but we have a fallback
718
+ */
719
+ happyPathError(component, message, context, data, fallback = "") {
720
+ const stack = new Error().stack || "";
721
+ const stackLines = stack.split("\n");
722
+ const callerLine = stackLines[2] || "";
723
+ const callerMatch = callerLine.match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/);
724
+ const location = callerMatch ? `${callerMatch[1].split("/").pop()}:${callerMatch[2]}` : "unknown";
725
+ const enhancedContext = {
726
+ ...context,
727
+ location
728
+ };
729
+ this.warn(component, `[HAPPY-PATH] ${message}`, enhancedContext, data);
730
+ return fallback;
731
+ }
732
+ };
733
+ var logger = new Logger();
734
+
735
+ // src/shared/paths.ts
736
+ function getDirname() {
737
+ if (typeof __dirname !== "undefined") {
738
+ return __dirname;
739
+ }
740
+ return dirname(fileURLToPath(import.meta.url));
741
+ }
742
+ var _dirname = getDirname();
743
+ var DATA_DIR = process.env.CONTEXTKIT_DATA_DIR || join2(homedir2(), ".contextkit");
744
+ var KIRO_CONFIG_DIR = process.env.KIRO_CONFIG_DIR || join2(homedir2(), ".kiro");
745
+ var PLUGIN_ROOT = join2(KIRO_CONFIG_DIR, "plugins", "contextkit");
746
+ var ARCHIVES_DIR = join2(DATA_DIR, "archives");
747
+ var LOGS_DIR = join2(DATA_DIR, "logs");
748
+ var TRASH_DIR = join2(DATA_DIR, "trash");
749
+ var BACKUPS_DIR = join2(DATA_DIR, "backups");
750
+ var MODES_DIR = join2(DATA_DIR, "modes");
751
+ var USER_SETTINGS_PATH = join2(DATA_DIR, "settings.json");
752
+ var DB_PATH = join2(DATA_DIR, "contextkit.db");
753
+ var VECTOR_DB_DIR = join2(DATA_DIR, "vector-db");
754
+ var OBSERVER_SESSIONS_DIR = join2(DATA_DIR, "observer-sessions");
755
+ var KIRO_SETTINGS_PATH = join2(KIRO_CONFIG_DIR, "settings.json");
756
+ var KIRO_CONTEXT_PATH = join2(KIRO_CONFIG_DIR, "context.md");
757
+ function ensureDir(dirPath) {
758
+ mkdirSync2(dirPath, { recursive: true });
759
+ }
760
+
761
+ // src/services/sqlite/Database.ts
762
+ var SQLITE_MMAP_SIZE_BYTES = 256 * 1024 * 1024;
763
+ var SQLITE_CACHE_SIZE_PAGES = 1e4;
764
+ var ContextKitDatabase = class {
765
+ db;
766
+ constructor(dbPath = DB_PATH) {
767
+ if (dbPath !== ":memory:") {
768
+ ensureDir(DATA_DIR);
769
+ }
770
+ this.db = new Database(dbPath, { create: true, readwrite: true });
771
+ this.db.run("PRAGMA journal_mode = WAL");
772
+ this.db.run("PRAGMA synchronous = NORMAL");
773
+ this.db.run("PRAGMA foreign_keys = ON");
774
+ this.db.run("PRAGMA temp_store = memory");
775
+ this.db.run(`PRAGMA mmap_size = ${SQLITE_MMAP_SIZE_BYTES}`);
776
+ this.db.run(`PRAGMA cache_size = ${SQLITE_CACHE_SIZE_PAGES}`);
777
+ const migrationRunner = new MigrationRunner(this.db);
778
+ migrationRunner.runAllMigrations();
779
+ }
780
+ /**
781
+ * Close the database connection
782
+ */
783
+ close() {
784
+ this.db.close();
785
+ }
786
+ };
787
+ var MigrationRunner = class {
788
+ db;
789
+ constructor(db) {
790
+ this.db = db;
791
+ }
792
+ runAllMigrations() {
793
+ this.db.run(`
794
+ CREATE TABLE IF NOT EXISTS schema_versions (
795
+ id INTEGER PRIMARY KEY,
796
+ version INTEGER UNIQUE NOT NULL,
797
+ applied_at TEXT NOT NULL
798
+ )
799
+ `);
800
+ const versionQuery = this.db.query("SELECT MAX(version) as version FROM schema_versions");
801
+ const result = versionQuery.get();
802
+ const currentVersion = result?.version || 0;
803
+ const migrations = this.getMigrations();
804
+ for (const migration of migrations) {
805
+ if (migration.version > currentVersion) {
806
+ logger.info("DB", `Applying migration ${migration.version}`);
807
+ const transaction = this.db.transaction(() => {
808
+ migration.up(this.db);
809
+ const insert = this.db.query("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)");
810
+ insert.run(migration.version, (/* @__PURE__ */ new Date()).toISOString());
811
+ });
812
+ transaction();
813
+ logger.info("DB", `Migration ${migration.version} applied successfully`);
814
+ }
815
+ }
816
+ }
817
+ getMigrations() {
818
+ return [
819
+ {
820
+ version: 1,
821
+ up: (db) => {
822
+ db.run(`
823
+ CREATE TABLE IF NOT EXISTS sessions (
824
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
825
+ content_session_id TEXT NOT NULL UNIQUE,
826
+ project TEXT NOT NULL,
827
+ user_prompt TEXT NOT NULL,
828
+ memory_session_id TEXT,
829
+ status TEXT DEFAULT 'active',
830
+ started_at TEXT NOT NULL,
831
+ started_at_epoch INTEGER NOT NULL,
832
+ completed_at TEXT,
833
+ completed_at_epoch INTEGER
834
+ )
835
+ `);
836
+ db.run(`
837
+ CREATE TABLE IF NOT EXISTS observations (
838
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
839
+ memory_session_id TEXT NOT NULL,
840
+ project TEXT NOT NULL,
841
+ type TEXT NOT NULL,
842
+ title TEXT NOT NULL,
843
+ subtitle TEXT,
844
+ text TEXT,
845
+ narrative TEXT,
846
+ facts TEXT,
847
+ concepts TEXT,
848
+ files_read TEXT,
849
+ files_modified TEXT,
850
+ prompt_number INTEGER NOT NULL,
851
+ created_at TEXT NOT NULL,
852
+ created_at_epoch INTEGER NOT NULL
853
+ )
854
+ `);
855
+ db.run(`
856
+ CREATE TABLE IF NOT EXISTS summaries (
857
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
858
+ session_id TEXT NOT NULL,
859
+ project TEXT NOT NULL,
860
+ request TEXT,
861
+ investigated TEXT,
862
+ learned TEXT,
863
+ completed TEXT,
864
+ next_steps TEXT,
865
+ notes TEXT,
866
+ created_at TEXT NOT NULL,
867
+ created_at_epoch INTEGER NOT NULL
868
+ )
869
+ `);
870
+ db.run(`
871
+ CREATE TABLE IF NOT EXISTS prompts (
872
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
873
+ content_session_id TEXT NOT NULL,
874
+ project TEXT NOT NULL,
875
+ prompt_number INTEGER NOT NULL,
876
+ prompt_text TEXT NOT NULL,
877
+ created_at TEXT NOT NULL,
878
+ created_at_epoch INTEGER NOT NULL
879
+ )
880
+ `);
881
+ db.run(`
882
+ CREATE TABLE IF NOT EXISTS pending_messages (
883
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
884
+ content_session_id TEXT NOT NULL,
885
+ type TEXT NOT NULL,
886
+ data TEXT NOT NULL,
887
+ created_at TEXT NOT NULL,
888
+ created_at_epoch INTEGER NOT NULL
889
+ )
890
+ `);
891
+ db.run("CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project)");
892
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project)");
893
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_session ON observations(memory_session_id)");
894
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_session ON summaries(session_id)");
895
+ db.run("CREATE INDEX IF NOT EXISTS idx_prompts_session ON prompts(content_session_id)");
896
+ }
897
+ },
898
+ {
899
+ version: 2,
900
+ up: (db) => {
901
+ db.run(`
902
+ CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
903
+ title, text, narrative, concepts,
904
+ content='observations',
905
+ content_rowid='id'
906
+ )
907
+ `);
908
+ db.run(`
909
+ CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
910
+ INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
911
+ VALUES (new.id, new.title, new.text, new.narrative, new.concepts);
912
+ END
913
+ `);
914
+ db.run(`
915
+ CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
916
+ INSERT INTO observations_fts(observations_fts, rowid, title, text, narrative, concepts)
917
+ VALUES ('delete', old.id, old.title, old.text, old.narrative, old.concepts);
918
+ END
919
+ `);
920
+ db.run(`
921
+ CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
922
+ INSERT INTO observations_fts(observations_fts, rowid, title, text, narrative, concepts)
923
+ VALUES ('delete', old.id, old.title, old.text, old.narrative, old.concepts);
924
+ INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
925
+ VALUES (new.id, new.title, new.text, new.narrative, new.concepts);
926
+ END
927
+ `);
928
+ db.run(`
929
+ INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
930
+ SELECT id, title, text, narrative, concepts FROM observations
931
+ `);
932
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type)");
933
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_epoch ON observations(created_at_epoch)");
934
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_project ON summaries(project)");
935
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_epoch ON summaries(created_at_epoch)");
936
+ db.run("CREATE INDEX IF NOT EXISTS idx_prompts_project ON prompts(project)");
937
+ }
938
+ }
939
+ ];
940
+ }
941
+ };
942
+
943
+ // src/services/sqlite/index.ts
944
+ init_Sessions();
945
+ init_Observations();
946
+ init_Summaries();
947
+ init_Prompts();
948
+ init_Search();
949
+
950
+ // src/sdk/index.ts
951
+ var ContextKitSDK = class {
952
+ db;
953
+ project;
954
+ constructor(config = {}) {
955
+ this.db = new ContextKitDatabase(config.dataDir);
956
+ this.project = config.project || this.detectProject();
957
+ }
958
+ detectProject() {
959
+ try {
960
+ const { execSync } = __require("child_process");
961
+ const gitRoot = execSync("git rev-parse --show-toplevel", {
962
+ cwd: process.cwd(),
963
+ encoding: "utf8",
964
+ stdio: ["pipe", "pipe", "ignore"]
965
+ }).trim();
966
+ return gitRoot.split("/").pop() || "default";
967
+ } catch {
968
+ return "default";
969
+ }
970
+ }
971
+ /**
972
+ * Get context for the current project
973
+ */
974
+ async getContext() {
975
+ const { getObservationsByProject: getObservationsByProject2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
976
+ const { getSummariesByProject: getSummariesByProject2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
977
+ const { getPromptsByProject: getPromptsByProject2 } = await Promise.resolve().then(() => (init_Prompts(), Prompts_exports));
978
+ return {
979
+ project: this.project,
980
+ relevantObservations: getObservationsByProject2(this.db.db, this.project, 20),
981
+ relevantSummaries: getSummariesByProject2(this.db.db, this.project, 5),
982
+ recentPrompts: getPromptsByProject2(this.db.db, this.project, 10)
983
+ };
984
+ }
985
+ /**
986
+ * Store a new observation
987
+ */
988
+ async storeObservation(data) {
989
+ const { createObservation: createObservation2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
990
+ return createObservation2(
991
+ this.db.db,
992
+ "sdk-" + Date.now(),
993
+ this.project,
994
+ data.type,
995
+ data.title,
996
+ null,
997
+ // subtitle
998
+ data.content,
999
+ null,
1000
+ // narrative
1001
+ null,
1002
+ // facts
1003
+ data.concepts?.join(", ") || null,
1004
+ data.files?.join(", ") || null,
1005
+ // files_read
1006
+ data.files?.join(", ") || null,
1007
+ // files_modified
1008
+ 0
1009
+ // prompt_number
1010
+ );
1011
+ }
1012
+ /**
1013
+ * Store a session summary
1014
+ */
1015
+ async storeSummary(data) {
1016
+ const { createSummary: createSummary2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
1017
+ return createSummary2(
1018
+ this.db.db,
1019
+ "sdk-" + Date.now(),
1020
+ this.project,
1021
+ data.request || null,
1022
+ null,
1023
+ data.learned || null,
1024
+ data.completed || null,
1025
+ data.nextSteps || null,
1026
+ null
1027
+ );
1028
+ }
1029
+ /**
1030
+ * Search across all stored context
1031
+ */
1032
+ async search(query) {
1033
+ const { searchObservations: searchObservations2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
1034
+ const { searchSummaries: searchSummaries2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
1035
+ return {
1036
+ observations: searchObservations2(this.db.db, query, this.project),
1037
+ summaries: searchSummaries2(this.db.db, query, this.project)
1038
+ };
1039
+ }
1040
+ /**
1041
+ * Get recent observations
1042
+ */
1043
+ async getRecentObservations(limit = 10) {
1044
+ const { getObservationsByProject: getObservationsByProject2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
1045
+ return getObservationsByProject2(this.db.db, this.project, limit);
1046
+ }
1047
+ /**
1048
+ * Get recent summaries
1049
+ */
1050
+ async getRecentSummaries(limit = 5) {
1051
+ const { getSummariesByProject: getSummariesByProject2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
1052
+ return getSummariesByProject2(this.db.db, this.project, limit);
1053
+ }
1054
+ /**
1055
+ * Ricerca avanzata con FTS5 e filtri
1056
+ */
1057
+ async searchAdvanced(query, filters = {}) {
1058
+ const { searchObservationsFTS: searchObservationsFTS2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1059
+ const { searchSummariesFiltered: searchSummariesFiltered2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1060
+ const projectFilters = { ...filters, project: filters.project || this.project };
1061
+ return {
1062
+ observations: searchObservationsFTS2(this.db.db, query, projectFilters),
1063
+ summaries: searchSummariesFiltered2(this.db.db, query, projectFilters)
1064
+ };
1065
+ }
1066
+ /**
1067
+ * Recupera osservazioni per ID (batch)
1068
+ */
1069
+ async getObservationsByIds(ids) {
1070
+ const { getObservationsByIds: getObservationsByIds2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1071
+ return getObservationsByIds2(this.db.db, ids);
1072
+ }
1073
+ /**
1074
+ * Timeline: contesto cronologico attorno a un'osservazione
1075
+ */
1076
+ async getTimeline(anchorId, depthBefore = 5, depthAfter = 5) {
1077
+ const { getTimeline: getTimeline2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1078
+ return getTimeline2(this.db.db, anchorId, depthBefore, depthAfter);
1079
+ }
1080
+ /**
1081
+ * Crea o recupera una sessione per il progetto corrente
1082
+ */
1083
+ async getOrCreateSession(contentSessionId) {
1084
+ const { getSessionByContentId: getSessionByContentId2, createSession: createSession2 } = await Promise.resolve().then(() => (init_Sessions(), Sessions_exports));
1085
+ let session = getSessionByContentId2(this.db.db, contentSessionId);
1086
+ if (!session) {
1087
+ const id = createSession2(this.db.db, contentSessionId, this.project, "");
1088
+ session = {
1089
+ id,
1090
+ content_session_id: contentSessionId,
1091
+ project: this.project,
1092
+ user_prompt: "",
1093
+ memory_session_id: null,
1094
+ status: "active",
1095
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
1096
+ started_at_epoch: Date.now(),
1097
+ completed_at: null,
1098
+ completed_at_epoch: null
1099
+ };
1100
+ }
1101
+ return session;
1102
+ }
1103
+ /**
1104
+ * Salva un prompt utente
1105
+ */
1106
+ async storePrompt(contentSessionId, promptNumber, text) {
1107
+ const { createPrompt: createPrompt2 } = await Promise.resolve().then(() => (init_Prompts(), Prompts_exports));
1108
+ return createPrompt2(this.db.db, contentSessionId, this.project, promptNumber, text);
1109
+ }
1110
+ /**
1111
+ * Completa una sessione
1112
+ */
1113
+ async completeSession(sessionId) {
1114
+ const { completeSession: completeSession2 } = await Promise.resolve().then(() => (init_Sessions(), Sessions_exports));
1115
+ completeSession2(this.db.db, sessionId);
1116
+ }
1117
+ /**
1118
+ * Getter per il nome progetto corrente
1119
+ */
1120
+ getProject() {
1121
+ return this.project;
1122
+ }
1123
+ /**
1124
+ * Getter per accesso diretto al database (per route API)
1125
+ */
1126
+ getDb() {
1127
+ return this.db.db;
1128
+ }
1129
+ /**
1130
+ * Close database connection
1131
+ */
1132
+ close() {
1133
+ this.db.close();
1134
+ }
1135
+ };
1136
+ function createContextKit(config) {
1137
+ return new ContextKitSDK(config);
1138
+ }
1139
+
1140
+ // src/hooks/stop.ts
1141
+ runHook("stop", async (input) => {
1142
+ const project = detectProject(input.cwd);
1143
+ const sdk = createContextKit({ project });
1144
+ try {
1145
+ const recentObs = await sdk.getRecentObservations(20);
1146
+ const oneHourAgo = Date.now() - 60 * 60 * 1e3;
1147
+ const sessionObs = recentObs.filter((o) => o.created_at_epoch > oneHourAgo);
1148
+ if (sessionObs.length === 0) return;
1149
+ const completed = sessionObs.map((o) => o.title).slice(0, 10).join("; ");
1150
+ const filesModified = [...new Set(
1151
+ sessionObs.filter((o) => o.files_modified).map((o) => o.files_modified).flatMap((f) => f.split(",").map((s) => s.trim()))
1152
+ )];
1153
+ const learned = sessionObs.filter((o) => o.type === "research" || o.type === "code-intelligence").map((o) => o.text?.substring(0, 100)).filter(Boolean).slice(0, 5).join("; ");
1154
+ await sdk.storeSummary({
1155
+ request: `Sessione ${project} - ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
1156
+ completed: completed || void 0,
1157
+ learned: learned || void 0,
1158
+ nextSteps: filesModified.length > 0 ? `File modificati: ${filesModified.join(", ")}` : void 0
1159
+ });
1160
+ } finally {
1161
+ sdk.close();
1162
+ }
1163
+ });