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