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,1187 @@
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
+ function formatContext(data) {
432
+ let output = "";
433
+ if (data.summaries && data.summaries.length > 0) {
434
+ output += "## Sessioni Precedenti\n\n";
435
+ data.summaries.slice(0, 3).forEach((sum) => {
436
+ if (sum.learned) output += `- **Appreso**: ${sum.learned}
437
+ `;
438
+ if (sum.completed) output += `- **Completato**: ${sum.completed}
439
+ `;
440
+ if (sum.next_steps) output += `- **Prossimi passi**: ${sum.next_steps}
441
+ `;
442
+ output += "\n";
443
+ });
444
+ }
445
+ if (data.observations && data.observations.length > 0) {
446
+ output += "## Osservazioni Recenti\n\n";
447
+ data.observations.slice(0, 10).forEach((obs) => {
448
+ const text = obs.text ? obs.text.substring(0, 150) : "";
449
+ output += `- **[${obs.type || "obs"}] ${obs.title}**: ${text}
450
+ `;
451
+ });
452
+ output += "\n";
453
+ }
454
+ return output;
455
+ }
456
+ async function runHook(name, handler) {
457
+ try {
458
+ const input = await readStdin();
459
+ await handler(input);
460
+ process.exit(0);
461
+ } catch (error) {
462
+ process.stderr.write(`[contextkit:${name}] Errore: ${error}
463
+ `);
464
+ process.exit(0);
465
+ }
466
+ }
467
+
468
+ // src/shims/bun-sqlite.ts
469
+ import BetterSqlite3 from "better-sqlite3";
470
+ var Database = class {
471
+ _db;
472
+ constructor(path, options) {
473
+ this._db = new BetterSqlite3(path, {
474
+ // better-sqlite3 crea il file di default (non serve 'create')
475
+ readonly: options?.readwrite === false ? true : false
476
+ });
477
+ }
478
+ /**
479
+ * Esegui una query SQL senza risultati
480
+ */
481
+ run(sql, params) {
482
+ const stmt = this._db.prepare(sql);
483
+ const result = params ? stmt.run(...params) : stmt.run();
484
+ return result;
485
+ }
486
+ /**
487
+ * Prepara una query con interfaccia compatibile bun:sqlite
488
+ */
489
+ query(sql) {
490
+ return new BunQueryCompat(this._db, sql);
491
+ }
492
+ /**
493
+ * Crea una transazione
494
+ */
495
+ transaction(fn) {
496
+ return this._db.transaction(fn);
497
+ }
498
+ /**
499
+ * Chiudi la connessione
500
+ */
501
+ close() {
502
+ this._db.close();
503
+ }
504
+ };
505
+ var BunQueryCompat = class {
506
+ _db;
507
+ _sql;
508
+ constructor(db, sql) {
509
+ this._db = db;
510
+ this._sql = sql;
511
+ }
512
+ /**
513
+ * Restituisce tutte le righe
514
+ */
515
+ all(...params) {
516
+ const stmt = this._db.prepare(this._sql);
517
+ return params.length > 0 ? stmt.all(...params) : stmt.all();
518
+ }
519
+ /**
520
+ * Restituisce la prima riga o null
521
+ */
522
+ get(...params) {
523
+ const stmt = this._db.prepare(this._sql);
524
+ return params.length > 0 ? stmt.get(...params) : stmt.get();
525
+ }
526
+ /**
527
+ * Esegui senza risultati
528
+ */
529
+ run(...params) {
530
+ const stmt = this._db.prepare(this._sql);
531
+ return params.length > 0 ? stmt.run(...params) : stmt.run();
532
+ }
533
+ };
534
+
535
+ // src/shared/paths.ts
536
+ import { join as join2, dirname, basename } from "path";
537
+ import { homedir as homedir2 } from "os";
538
+ import { mkdirSync as mkdirSync2 } from "fs";
539
+ import { fileURLToPath } from "url";
540
+
541
+ // src/utils/logger.ts
542
+ import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
543
+ import { join } from "path";
544
+ import { homedir } from "os";
545
+ var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
546
+ LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
547
+ LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
548
+ LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
549
+ LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
550
+ LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
551
+ return LogLevel2;
552
+ })(LogLevel || {});
553
+ var DEFAULT_DATA_DIR = join(homedir(), ".contextkit");
554
+ var Logger = class {
555
+ level = null;
556
+ useColor;
557
+ logFilePath = null;
558
+ logFileInitialized = false;
559
+ constructor() {
560
+ this.useColor = process.stdout.isTTY ?? false;
561
+ }
562
+ /**
563
+ * Initialize log file path and ensure directory exists (lazy initialization)
564
+ */
565
+ ensureLogFileInitialized() {
566
+ if (this.logFileInitialized) return;
567
+ this.logFileInitialized = true;
568
+ try {
569
+ const logsDir = join(DEFAULT_DATA_DIR, "logs");
570
+ if (!existsSync(logsDir)) {
571
+ mkdirSync(logsDir, { recursive: true });
572
+ }
573
+ const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
574
+ this.logFilePath = join(logsDir, `contextkit-${date}.log`);
575
+ } catch (error) {
576
+ console.error("[LOGGER] Failed to initialize log file:", error);
577
+ this.logFilePath = null;
578
+ }
579
+ }
580
+ /**
581
+ * Lazy-load log level from settings file
582
+ */
583
+ getLevel() {
584
+ if (this.level === null) {
585
+ try {
586
+ const settingsPath = join(DEFAULT_DATA_DIR, "settings.json");
587
+ if (existsSync(settingsPath)) {
588
+ const settingsData = readFileSync(settingsPath, "utf-8");
589
+ const settings = JSON.parse(settingsData);
590
+ const envLevel = (settings.CONTEXTKIT_LOG_LEVEL || "INFO").toUpperCase();
591
+ this.level = LogLevel[envLevel] ?? 1 /* INFO */;
592
+ } else {
593
+ this.level = 1 /* INFO */;
594
+ }
595
+ } catch (error) {
596
+ this.level = 1 /* INFO */;
597
+ }
598
+ }
599
+ return this.level;
600
+ }
601
+ /**
602
+ * Create correlation ID for tracking an observation through the pipeline
603
+ */
604
+ correlationId(sessionId, observationNum) {
605
+ return `obs-${sessionId}-${observationNum}`;
606
+ }
607
+ /**
608
+ * Create session correlation ID
609
+ */
610
+ sessionId(sessionId) {
611
+ return `session-${sessionId}`;
612
+ }
613
+ /**
614
+ * Format data for logging - create compact summaries instead of full dumps
615
+ */
616
+ formatData(data) {
617
+ if (data === null || data === void 0) return "";
618
+ if (typeof data === "string") return data;
619
+ if (typeof data === "number") return data.toString();
620
+ if (typeof data === "boolean") return data.toString();
621
+ if (typeof data === "object") {
622
+ if (data instanceof Error) {
623
+ return this.getLevel() === 0 /* DEBUG */ ? `${data.message}
624
+ ${data.stack}` : data.message;
625
+ }
626
+ if (Array.isArray(data)) {
627
+ return `[${data.length} items]`;
628
+ }
629
+ const keys = Object.keys(data);
630
+ if (keys.length === 0) return "{}";
631
+ if (keys.length <= 3) {
632
+ return JSON.stringify(data);
633
+ }
634
+ return `{${keys.length} keys: ${keys.slice(0, 3).join(", ")}...}`;
635
+ }
636
+ return String(data);
637
+ }
638
+ /**
639
+ * Format timestamp in local timezone (YYYY-MM-DD HH:MM:SS.mmm)
640
+ */
641
+ formatTimestamp(date) {
642
+ const year = date.getFullYear();
643
+ const month = String(date.getMonth() + 1).padStart(2, "0");
644
+ const day = String(date.getDate()).padStart(2, "0");
645
+ const hours = String(date.getHours()).padStart(2, "0");
646
+ const minutes = String(date.getMinutes()).padStart(2, "0");
647
+ const seconds = String(date.getSeconds()).padStart(2, "0");
648
+ const ms = String(date.getMilliseconds()).padStart(3, "0");
649
+ return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
650
+ }
651
+ /**
652
+ * Core logging method
653
+ */
654
+ log(level, component, message, context, data) {
655
+ if (level < this.getLevel()) return;
656
+ this.ensureLogFileInitialized();
657
+ const timestamp = this.formatTimestamp(/* @__PURE__ */ new Date());
658
+ const levelStr = LogLevel[level].padEnd(5);
659
+ const componentStr = component.padEnd(6);
660
+ let correlationStr = "";
661
+ if (context?.correlationId) {
662
+ correlationStr = `[${context.correlationId}] `;
663
+ } else if (context?.sessionId) {
664
+ correlationStr = `[session-${context.sessionId}] `;
665
+ }
666
+ let dataStr = "";
667
+ if (data !== void 0 && data !== null) {
668
+ if (data instanceof Error) {
669
+ dataStr = this.getLevel() === 0 /* DEBUG */ ? `
670
+ ${data.message}
671
+ ${data.stack}` : ` ${data.message}`;
672
+ } else if (this.getLevel() === 0 /* DEBUG */ && typeof data === "object") {
673
+ dataStr = "\n" + JSON.stringify(data, null, 2);
674
+ } else {
675
+ dataStr = " " + this.formatData(data);
676
+ }
677
+ }
678
+ let contextStr = "";
679
+ if (context) {
680
+ const { sessionId, memorySessionId, correlationId, ...rest } = context;
681
+ if (Object.keys(rest).length > 0) {
682
+ const pairs = Object.entries(rest).map(([k, v]) => `${k}=${v}`);
683
+ contextStr = ` {${pairs.join(", ")}}`;
684
+ }
685
+ }
686
+ const logLine = `[${timestamp}] [${levelStr}] [${componentStr}] ${correlationStr}${message}${contextStr}${dataStr}`;
687
+ if (this.logFilePath) {
688
+ try {
689
+ appendFileSync(this.logFilePath, logLine + "\n", "utf8");
690
+ } catch (error) {
691
+ process.stderr.write(`[LOGGER] Failed to write to log file: ${error}
692
+ `);
693
+ }
694
+ } else {
695
+ process.stderr.write(logLine + "\n");
696
+ }
697
+ }
698
+ // Public logging methods
699
+ debug(component, message, context, data) {
700
+ this.log(0 /* DEBUG */, component, message, context, data);
701
+ }
702
+ info(component, message, context, data) {
703
+ this.log(1 /* INFO */, component, message, context, data);
704
+ }
705
+ warn(component, message, context, data) {
706
+ this.log(2 /* WARN */, component, message, context, data);
707
+ }
708
+ error(component, message, context, data) {
709
+ this.log(3 /* ERROR */, component, message, context, data);
710
+ }
711
+ /**
712
+ * Log data flow: input → processing
713
+ */
714
+ dataIn(component, message, context, data) {
715
+ this.info(component, `\u2192 ${message}`, context, data);
716
+ }
717
+ /**
718
+ * Log data flow: processing → output
719
+ */
720
+ dataOut(component, message, context, data) {
721
+ this.info(component, `\u2190 ${message}`, context, data);
722
+ }
723
+ /**
724
+ * Log successful completion
725
+ */
726
+ success(component, message, context, data) {
727
+ this.info(component, `\u2713 ${message}`, context, data);
728
+ }
729
+ /**
730
+ * Log failure
731
+ */
732
+ failure(component, message, context, data) {
733
+ this.error(component, `\u2717 ${message}`, context, data);
734
+ }
735
+ /**
736
+ * Log timing information
737
+ */
738
+ timing(component, message, durationMs, context) {
739
+ this.info(component, `\u23F1 ${message}`, context, { duration: `${durationMs}ms` });
740
+ }
741
+ /**
742
+ * Happy Path Error - logs when the expected "happy path" fails but we have a fallback
743
+ */
744
+ happyPathError(component, message, context, data, fallback = "") {
745
+ const stack = new Error().stack || "";
746
+ const stackLines = stack.split("\n");
747
+ const callerLine = stackLines[2] || "";
748
+ const callerMatch = callerLine.match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/);
749
+ const location = callerMatch ? `${callerMatch[1].split("/").pop()}:${callerMatch[2]}` : "unknown";
750
+ const enhancedContext = {
751
+ ...context,
752
+ location
753
+ };
754
+ this.warn(component, `[HAPPY-PATH] ${message}`, enhancedContext, data);
755
+ return fallback;
756
+ }
757
+ };
758
+ var logger = new Logger();
759
+
760
+ // src/shared/paths.ts
761
+ function getDirname() {
762
+ if (typeof __dirname !== "undefined") {
763
+ return __dirname;
764
+ }
765
+ return dirname(fileURLToPath(import.meta.url));
766
+ }
767
+ var _dirname = getDirname();
768
+ var DATA_DIR = process.env.CONTEXTKIT_DATA_DIR || join2(homedir2(), ".contextkit");
769
+ var KIRO_CONFIG_DIR = process.env.KIRO_CONFIG_DIR || join2(homedir2(), ".kiro");
770
+ var PLUGIN_ROOT = join2(KIRO_CONFIG_DIR, "plugins", "contextkit");
771
+ var ARCHIVES_DIR = join2(DATA_DIR, "archives");
772
+ var LOGS_DIR = join2(DATA_DIR, "logs");
773
+ var TRASH_DIR = join2(DATA_DIR, "trash");
774
+ var BACKUPS_DIR = join2(DATA_DIR, "backups");
775
+ var MODES_DIR = join2(DATA_DIR, "modes");
776
+ var USER_SETTINGS_PATH = join2(DATA_DIR, "settings.json");
777
+ var DB_PATH = join2(DATA_DIR, "contextkit.db");
778
+ var VECTOR_DB_DIR = join2(DATA_DIR, "vector-db");
779
+ var OBSERVER_SESSIONS_DIR = join2(DATA_DIR, "observer-sessions");
780
+ var KIRO_SETTINGS_PATH = join2(KIRO_CONFIG_DIR, "settings.json");
781
+ var KIRO_CONTEXT_PATH = join2(KIRO_CONFIG_DIR, "context.md");
782
+ function ensureDir(dirPath) {
783
+ mkdirSync2(dirPath, { recursive: true });
784
+ }
785
+
786
+ // src/services/sqlite/Database.ts
787
+ var SQLITE_MMAP_SIZE_BYTES = 256 * 1024 * 1024;
788
+ var SQLITE_CACHE_SIZE_PAGES = 1e4;
789
+ var ContextKitDatabase = class {
790
+ db;
791
+ constructor(dbPath = DB_PATH) {
792
+ if (dbPath !== ":memory:") {
793
+ ensureDir(DATA_DIR);
794
+ }
795
+ this.db = new Database(dbPath, { create: true, readwrite: true });
796
+ this.db.run("PRAGMA journal_mode = WAL");
797
+ this.db.run("PRAGMA synchronous = NORMAL");
798
+ this.db.run("PRAGMA foreign_keys = ON");
799
+ this.db.run("PRAGMA temp_store = memory");
800
+ this.db.run(`PRAGMA mmap_size = ${SQLITE_MMAP_SIZE_BYTES}`);
801
+ this.db.run(`PRAGMA cache_size = ${SQLITE_CACHE_SIZE_PAGES}`);
802
+ const migrationRunner = new MigrationRunner(this.db);
803
+ migrationRunner.runAllMigrations();
804
+ }
805
+ /**
806
+ * Close the database connection
807
+ */
808
+ close() {
809
+ this.db.close();
810
+ }
811
+ };
812
+ var MigrationRunner = class {
813
+ db;
814
+ constructor(db) {
815
+ this.db = db;
816
+ }
817
+ runAllMigrations() {
818
+ this.db.run(`
819
+ CREATE TABLE IF NOT EXISTS schema_versions (
820
+ id INTEGER PRIMARY KEY,
821
+ version INTEGER UNIQUE NOT NULL,
822
+ applied_at TEXT NOT NULL
823
+ )
824
+ `);
825
+ const versionQuery = this.db.query("SELECT MAX(version) as version FROM schema_versions");
826
+ const result = versionQuery.get();
827
+ const currentVersion = result?.version || 0;
828
+ const migrations = this.getMigrations();
829
+ for (const migration of migrations) {
830
+ if (migration.version > currentVersion) {
831
+ logger.info("DB", `Applying migration ${migration.version}`);
832
+ const transaction = this.db.transaction(() => {
833
+ migration.up(this.db);
834
+ const insert = this.db.query("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)");
835
+ insert.run(migration.version, (/* @__PURE__ */ new Date()).toISOString());
836
+ });
837
+ transaction();
838
+ logger.info("DB", `Migration ${migration.version} applied successfully`);
839
+ }
840
+ }
841
+ }
842
+ getMigrations() {
843
+ return [
844
+ {
845
+ version: 1,
846
+ up: (db) => {
847
+ db.run(`
848
+ CREATE TABLE IF NOT EXISTS sessions (
849
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
850
+ content_session_id TEXT NOT NULL UNIQUE,
851
+ project TEXT NOT NULL,
852
+ user_prompt TEXT NOT NULL,
853
+ memory_session_id TEXT,
854
+ status TEXT DEFAULT 'active',
855
+ started_at TEXT NOT NULL,
856
+ started_at_epoch INTEGER NOT NULL,
857
+ completed_at TEXT,
858
+ completed_at_epoch INTEGER
859
+ )
860
+ `);
861
+ db.run(`
862
+ CREATE TABLE IF NOT EXISTS observations (
863
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
864
+ memory_session_id TEXT NOT NULL,
865
+ project TEXT NOT NULL,
866
+ type TEXT NOT NULL,
867
+ title TEXT NOT NULL,
868
+ subtitle TEXT,
869
+ text TEXT,
870
+ narrative TEXT,
871
+ facts TEXT,
872
+ concepts TEXT,
873
+ files_read TEXT,
874
+ files_modified TEXT,
875
+ prompt_number INTEGER NOT NULL,
876
+ created_at TEXT NOT NULL,
877
+ created_at_epoch INTEGER NOT NULL
878
+ )
879
+ `);
880
+ db.run(`
881
+ CREATE TABLE IF NOT EXISTS summaries (
882
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
883
+ session_id TEXT NOT NULL,
884
+ project TEXT NOT NULL,
885
+ request TEXT,
886
+ investigated TEXT,
887
+ learned TEXT,
888
+ completed TEXT,
889
+ next_steps TEXT,
890
+ notes TEXT,
891
+ created_at TEXT NOT NULL,
892
+ created_at_epoch INTEGER NOT NULL
893
+ )
894
+ `);
895
+ db.run(`
896
+ CREATE TABLE IF NOT EXISTS prompts (
897
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
898
+ content_session_id TEXT NOT NULL,
899
+ project TEXT NOT NULL,
900
+ prompt_number INTEGER NOT NULL,
901
+ prompt_text TEXT NOT NULL,
902
+ created_at TEXT NOT NULL,
903
+ created_at_epoch INTEGER NOT NULL
904
+ )
905
+ `);
906
+ db.run(`
907
+ CREATE TABLE IF NOT EXISTS pending_messages (
908
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
909
+ content_session_id TEXT NOT NULL,
910
+ type TEXT NOT NULL,
911
+ data TEXT NOT NULL,
912
+ created_at TEXT NOT NULL,
913
+ created_at_epoch INTEGER NOT NULL
914
+ )
915
+ `);
916
+ db.run("CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project)");
917
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project)");
918
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_session ON observations(memory_session_id)");
919
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_session ON summaries(session_id)");
920
+ db.run("CREATE INDEX IF NOT EXISTS idx_prompts_session ON prompts(content_session_id)");
921
+ }
922
+ },
923
+ {
924
+ version: 2,
925
+ up: (db) => {
926
+ db.run(`
927
+ CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
928
+ title, text, narrative, concepts,
929
+ content='observations',
930
+ content_rowid='id'
931
+ )
932
+ `);
933
+ db.run(`
934
+ CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
935
+ INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
936
+ VALUES (new.id, new.title, new.text, new.narrative, new.concepts);
937
+ END
938
+ `);
939
+ db.run(`
940
+ CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
941
+ INSERT INTO observations_fts(observations_fts, rowid, title, text, narrative, concepts)
942
+ VALUES ('delete', old.id, old.title, old.text, old.narrative, old.concepts);
943
+ END
944
+ `);
945
+ db.run(`
946
+ CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
947
+ INSERT INTO observations_fts(observations_fts, rowid, title, text, narrative, concepts)
948
+ VALUES ('delete', old.id, old.title, old.text, old.narrative, old.concepts);
949
+ INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
950
+ VALUES (new.id, new.title, new.text, new.narrative, new.concepts);
951
+ END
952
+ `);
953
+ db.run(`
954
+ INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
955
+ SELECT id, title, text, narrative, concepts FROM observations
956
+ `);
957
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type)");
958
+ db.run("CREATE INDEX IF NOT EXISTS idx_observations_epoch ON observations(created_at_epoch)");
959
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_project ON summaries(project)");
960
+ db.run("CREATE INDEX IF NOT EXISTS idx_summaries_epoch ON summaries(created_at_epoch)");
961
+ db.run("CREATE INDEX IF NOT EXISTS idx_prompts_project ON prompts(project)");
962
+ }
963
+ }
964
+ ];
965
+ }
966
+ };
967
+
968
+ // src/services/sqlite/index.ts
969
+ init_Sessions();
970
+ init_Observations();
971
+ init_Summaries();
972
+ init_Prompts();
973
+ init_Search();
974
+
975
+ // src/sdk/index.ts
976
+ var ContextKitSDK = class {
977
+ db;
978
+ project;
979
+ constructor(config = {}) {
980
+ this.db = new ContextKitDatabase(config.dataDir);
981
+ this.project = config.project || this.detectProject();
982
+ }
983
+ detectProject() {
984
+ try {
985
+ const { execSync } = __require("child_process");
986
+ const gitRoot = execSync("git rev-parse --show-toplevel", {
987
+ cwd: process.cwd(),
988
+ encoding: "utf8",
989
+ stdio: ["pipe", "pipe", "ignore"]
990
+ }).trim();
991
+ return gitRoot.split("/").pop() || "default";
992
+ } catch {
993
+ return "default";
994
+ }
995
+ }
996
+ /**
997
+ * Get context for the current project
998
+ */
999
+ async getContext() {
1000
+ const { getObservationsByProject: getObservationsByProject2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
1001
+ const { getSummariesByProject: getSummariesByProject2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
1002
+ const { getPromptsByProject: getPromptsByProject2 } = await Promise.resolve().then(() => (init_Prompts(), Prompts_exports));
1003
+ return {
1004
+ project: this.project,
1005
+ relevantObservations: getObservationsByProject2(this.db.db, this.project, 20),
1006
+ relevantSummaries: getSummariesByProject2(this.db.db, this.project, 5),
1007
+ recentPrompts: getPromptsByProject2(this.db.db, this.project, 10)
1008
+ };
1009
+ }
1010
+ /**
1011
+ * Store a new observation
1012
+ */
1013
+ async storeObservation(data) {
1014
+ const { createObservation: createObservation2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
1015
+ return createObservation2(
1016
+ this.db.db,
1017
+ "sdk-" + Date.now(),
1018
+ this.project,
1019
+ data.type,
1020
+ data.title,
1021
+ null,
1022
+ // subtitle
1023
+ data.content,
1024
+ null,
1025
+ // narrative
1026
+ null,
1027
+ // facts
1028
+ data.concepts?.join(", ") || null,
1029
+ data.files?.join(", ") || null,
1030
+ // files_read
1031
+ data.files?.join(", ") || null,
1032
+ // files_modified
1033
+ 0
1034
+ // prompt_number
1035
+ );
1036
+ }
1037
+ /**
1038
+ * Store a session summary
1039
+ */
1040
+ async storeSummary(data) {
1041
+ const { createSummary: createSummary2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
1042
+ return createSummary2(
1043
+ this.db.db,
1044
+ "sdk-" + Date.now(),
1045
+ this.project,
1046
+ data.request || null,
1047
+ null,
1048
+ data.learned || null,
1049
+ data.completed || null,
1050
+ data.nextSteps || null,
1051
+ null
1052
+ );
1053
+ }
1054
+ /**
1055
+ * Search across all stored context
1056
+ */
1057
+ async search(query) {
1058
+ const { searchObservations: searchObservations2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
1059
+ const { searchSummaries: searchSummaries2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
1060
+ return {
1061
+ observations: searchObservations2(this.db.db, query, this.project),
1062
+ summaries: searchSummaries2(this.db.db, query, this.project)
1063
+ };
1064
+ }
1065
+ /**
1066
+ * Get recent observations
1067
+ */
1068
+ async getRecentObservations(limit = 10) {
1069
+ const { getObservationsByProject: getObservationsByProject2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
1070
+ return getObservationsByProject2(this.db.db, this.project, limit);
1071
+ }
1072
+ /**
1073
+ * Get recent summaries
1074
+ */
1075
+ async getRecentSummaries(limit = 5) {
1076
+ const { getSummariesByProject: getSummariesByProject2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
1077
+ return getSummariesByProject2(this.db.db, this.project, limit);
1078
+ }
1079
+ /**
1080
+ * Ricerca avanzata con FTS5 e filtri
1081
+ */
1082
+ async searchAdvanced(query, filters = {}) {
1083
+ const { searchObservationsFTS: searchObservationsFTS2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1084
+ const { searchSummariesFiltered: searchSummariesFiltered2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1085
+ const projectFilters = { ...filters, project: filters.project || this.project };
1086
+ return {
1087
+ observations: searchObservationsFTS2(this.db.db, query, projectFilters),
1088
+ summaries: searchSummariesFiltered2(this.db.db, query, projectFilters)
1089
+ };
1090
+ }
1091
+ /**
1092
+ * Recupera osservazioni per ID (batch)
1093
+ */
1094
+ async getObservationsByIds(ids) {
1095
+ const { getObservationsByIds: getObservationsByIds2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1096
+ return getObservationsByIds2(this.db.db, ids);
1097
+ }
1098
+ /**
1099
+ * Timeline: contesto cronologico attorno a un'osservazione
1100
+ */
1101
+ async getTimeline(anchorId, depthBefore = 5, depthAfter = 5) {
1102
+ const { getTimeline: getTimeline2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
1103
+ return getTimeline2(this.db.db, anchorId, depthBefore, depthAfter);
1104
+ }
1105
+ /**
1106
+ * Crea o recupera una sessione per il progetto corrente
1107
+ */
1108
+ async getOrCreateSession(contentSessionId) {
1109
+ const { getSessionByContentId: getSessionByContentId2, createSession: createSession2 } = await Promise.resolve().then(() => (init_Sessions(), Sessions_exports));
1110
+ let session = getSessionByContentId2(this.db.db, contentSessionId);
1111
+ if (!session) {
1112
+ const id = createSession2(this.db.db, contentSessionId, this.project, "");
1113
+ session = {
1114
+ id,
1115
+ content_session_id: contentSessionId,
1116
+ project: this.project,
1117
+ user_prompt: "",
1118
+ memory_session_id: null,
1119
+ status: "active",
1120
+ started_at: (/* @__PURE__ */ new Date()).toISOString(),
1121
+ started_at_epoch: Date.now(),
1122
+ completed_at: null,
1123
+ completed_at_epoch: null
1124
+ };
1125
+ }
1126
+ return session;
1127
+ }
1128
+ /**
1129
+ * Salva un prompt utente
1130
+ */
1131
+ async storePrompt(contentSessionId, promptNumber, text) {
1132
+ const { createPrompt: createPrompt2 } = await Promise.resolve().then(() => (init_Prompts(), Prompts_exports));
1133
+ return createPrompt2(this.db.db, contentSessionId, this.project, promptNumber, text);
1134
+ }
1135
+ /**
1136
+ * Completa una sessione
1137
+ */
1138
+ async completeSession(sessionId) {
1139
+ const { completeSession: completeSession2 } = await Promise.resolve().then(() => (init_Sessions(), Sessions_exports));
1140
+ completeSession2(this.db.db, sessionId);
1141
+ }
1142
+ /**
1143
+ * Getter per il nome progetto corrente
1144
+ */
1145
+ getProject() {
1146
+ return this.project;
1147
+ }
1148
+ /**
1149
+ * Getter per accesso diretto al database (per route API)
1150
+ */
1151
+ getDb() {
1152
+ return this.db.db;
1153
+ }
1154
+ /**
1155
+ * Close database connection
1156
+ */
1157
+ close() {
1158
+ this.db.close();
1159
+ }
1160
+ };
1161
+ function createContextKit(config) {
1162
+ return new ContextKitSDK(config);
1163
+ }
1164
+
1165
+ // src/hooks/agentSpawn.ts
1166
+ runHook("agentSpawn", async (input) => {
1167
+ const project = detectProject(input.cwd);
1168
+ const sdk = createContextKit({ project });
1169
+ try {
1170
+ const ctx = await sdk.getContext();
1171
+ if (ctx.relevantObservations.length === 0 && ctx.relevantSummaries.length === 0) {
1172
+ return;
1173
+ }
1174
+ let output = "# ContextKit: Contesto Sessioni Precedenti\n\n";
1175
+ output += formatContext({
1176
+ observations: ctx.relevantObservations,
1177
+ summaries: ctx.relevantSummaries,
1178
+ prompts: ctx.recentPrompts
1179
+ });
1180
+ output += `
1181
+ > Progetto: ${project} | Osservazioni: ${ctx.relevantObservations.length} | Sommari: ${ctx.relevantSummaries.length}
1182
+ `;
1183
+ process.stdout.write(output);
1184
+ } finally {
1185
+ sdk.close();
1186
+ }
1187
+ });