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.
- package/LICENSE +661 -0
- package/README.md +290 -0
- package/package.json +117 -0
- package/plugin/dist/cli/contextkit.js +1259 -0
- package/plugin/dist/hooks/agentSpawn.js +1187 -0
- package/plugin/dist/hooks/kiro-hooks.js +1184 -0
- package/plugin/dist/hooks/postToolUse.js +1219 -0
- package/plugin/dist/hooks/stop.js +1163 -0
- package/plugin/dist/hooks/userPromptSubmit.js +1152 -0
- package/plugin/dist/index.js +2103 -0
- package/plugin/dist/sdk/index.js +1083 -0
- package/plugin/dist/servers/mcp-server.js +266 -0
- package/plugin/dist/services/search/ChromaManager.js +357 -0
- package/plugin/dist/services/search/HybridSearch.js +502 -0
- package/plugin/dist/services/search/index.js +511 -0
- package/plugin/dist/services/sqlite/Database.js +625 -0
- package/plugin/dist/services/sqlite/Observations.js +46 -0
- package/plugin/dist/services/sqlite/Prompts.js +39 -0
- package/plugin/dist/services/sqlite/Search.js +143 -0
- package/plugin/dist/services/sqlite/Sessions.js +60 -0
- package/plugin/dist/services/sqlite/Summaries.js +44 -0
- package/plugin/dist/services/sqlite/index.js +951 -0
- package/plugin/dist/shared/paths.js +315 -0
- package/plugin/dist/types/worker-types.js +0 -0
- package/plugin/dist/utils/logger.js +222 -0
- package/plugin/dist/viewer.html +252 -0
- package/plugin/dist/viewer.js +23965 -0
- package/plugin/dist/worker-service.js +1782 -0
|
@@ -0,0 +1,2103 @@
|
|
|
1
|
+
var __create = Object.create;
|
|
2
|
+
var __defProp = Object.defineProperty;
|
|
3
|
+
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
|
+
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
5
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
6
|
+
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
7
|
+
var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
|
|
8
|
+
get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
|
|
9
|
+
}) : x)(function(x) {
|
|
10
|
+
if (typeof require !== "undefined") return require.apply(this, arguments);
|
|
11
|
+
throw Error('Dynamic require of "' + x + '" is not supported');
|
|
12
|
+
});
|
|
13
|
+
var __esm = (fn, res) => function __init() {
|
|
14
|
+
return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
|
|
15
|
+
};
|
|
16
|
+
var __commonJS = (cb, mod) => function __require2() {
|
|
17
|
+
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
18
|
+
};
|
|
19
|
+
var __export = (target, all) => {
|
|
20
|
+
for (var name in all)
|
|
21
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
22
|
+
};
|
|
23
|
+
var __copyProps = (to, from, except, desc) => {
|
|
24
|
+
if (from && typeof from === "object" || typeof from === "function") {
|
|
25
|
+
for (let key of __getOwnPropNames(from))
|
|
26
|
+
if (!__hasOwnProp.call(to, key) && key !== except)
|
|
27
|
+
__defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
|
|
28
|
+
}
|
|
29
|
+
return to;
|
|
30
|
+
};
|
|
31
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
32
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
33
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
34
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
35
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
36
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
37
|
+
mod
|
|
38
|
+
));
|
|
39
|
+
|
|
40
|
+
// node_modules/better-sqlite3/lib/util.js
|
|
41
|
+
var require_util = __commonJS({
|
|
42
|
+
"node_modules/better-sqlite3/lib/util.js"(exports) {
|
|
43
|
+
"use strict";
|
|
44
|
+
exports.getBooleanOption = (options, key) => {
|
|
45
|
+
let value = false;
|
|
46
|
+
if (key in options && typeof (value = options[key]) !== "boolean") {
|
|
47
|
+
throw new TypeError(`Expected the "${key}" option to be a boolean`);
|
|
48
|
+
}
|
|
49
|
+
return value;
|
|
50
|
+
};
|
|
51
|
+
exports.cppdb = /* @__PURE__ */ Symbol();
|
|
52
|
+
exports.inspect = /* @__PURE__ */ Symbol.for("nodejs.util.inspect.custom");
|
|
53
|
+
}
|
|
54
|
+
});
|
|
55
|
+
|
|
56
|
+
// node_modules/better-sqlite3/lib/sqlite-error.js
|
|
57
|
+
var require_sqlite_error = __commonJS({
|
|
58
|
+
"node_modules/better-sqlite3/lib/sqlite-error.js"(exports, module) {
|
|
59
|
+
"use strict";
|
|
60
|
+
var descriptor = { value: "SqliteError", writable: true, enumerable: false, configurable: true };
|
|
61
|
+
function SqliteError(message, code) {
|
|
62
|
+
if (new.target !== SqliteError) {
|
|
63
|
+
return new SqliteError(message, code);
|
|
64
|
+
}
|
|
65
|
+
if (typeof code !== "string") {
|
|
66
|
+
throw new TypeError("Expected second argument to be a string");
|
|
67
|
+
}
|
|
68
|
+
Error.call(this, message);
|
|
69
|
+
descriptor.value = "" + message;
|
|
70
|
+
Object.defineProperty(this, "message", descriptor);
|
|
71
|
+
Error.captureStackTrace(this, SqliteError);
|
|
72
|
+
this.code = code;
|
|
73
|
+
}
|
|
74
|
+
Object.setPrototypeOf(SqliteError, Error);
|
|
75
|
+
Object.setPrototypeOf(SqliteError.prototype, Error.prototype);
|
|
76
|
+
Object.defineProperty(SqliteError.prototype, "name", descriptor);
|
|
77
|
+
module.exports = SqliteError;
|
|
78
|
+
}
|
|
79
|
+
});
|
|
80
|
+
|
|
81
|
+
// node_modules/file-uri-to-path/index.js
|
|
82
|
+
var require_file_uri_to_path = __commonJS({
|
|
83
|
+
"node_modules/file-uri-to-path/index.js"(exports, module) {
|
|
84
|
+
var sep = __require("path").sep || "/";
|
|
85
|
+
module.exports = fileUriToPath;
|
|
86
|
+
function fileUriToPath(uri) {
|
|
87
|
+
if ("string" != typeof uri || uri.length <= 7 || "file://" != uri.substring(0, 7)) {
|
|
88
|
+
throw new TypeError("must pass in a file:// URI to convert to a file path");
|
|
89
|
+
}
|
|
90
|
+
var rest = decodeURI(uri.substring(7));
|
|
91
|
+
var firstSlash = rest.indexOf("/");
|
|
92
|
+
var host = rest.substring(0, firstSlash);
|
|
93
|
+
var path = rest.substring(firstSlash + 1);
|
|
94
|
+
if ("localhost" == host) host = "";
|
|
95
|
+
if (host) {
|
|
96
|
+
host = sep + sep + host;
|
|
97
|
+
}
|
|
98
|
+
path = path.replace(/^(.+)\|/, "$1:");
|
|
99
|
+
if (sep == "\\") {
|
|
100
|
+
path = path.replace(/\//g, "\\");
|
|
101
|
+
}
|
|
102
|
+
if (/^.+\:/.test(path)) {
|
|
103
|
+
} else {
|
|
104
|
+
path = sep + path;
|
|
105
|
+
}
|
|
106
|
+
return host + path;
|
|
107
|
+
}
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
// node_modules/bindings/bindings.js
|
|
112
|
+
var require_bindings = __commonJS({
|
|
113
|
+
"node_modules/bindings/bindings.js"(exports, module) {
|
|
114
|
+
var fs = __require("fs");
|
|
115
|
+
var path = __require("path");
|
|
116
|
+
var fileURLToPath2 = require_file_uri_to_path();
|
|
117
|
+
var join3 = path.join;
|
|
118
|
+
var dirname2 = path.dirname;
|
|
119
|
+
var exists = fs.accessSync && function(path2) {
|
|
120
|
+
try {
|
|
121
|
+
fs.accessSync(path2);
|
|
122
|
+
} catch (e) {
|
|
123
|
+
return false;
|
|
124
|
+
}
|
|
125
|
+
return true;
|
|
126
|
+
} || fs.existsSync || path.existsSync;
|
|
127
|
+
var defaults = {
|
|
128
|
+
arrow: process.env.NODE_BINDINGS_ARROW || " \u2192 ",
|
|
129
|
+
compiled: process.env.NODE_BINDINGS_COMPILED_DIR || "compiled",
|
|
130
|
+
platform: process.platform,
|
|
131
|
+
arch: process.arch,
|
|
132
|
+
nodePreGyp: "node-v" + process.versions.modules + "-" + process.platform + "-" + process.arch,
|
|
133
|
+
version: process.versions.node,
|
|
134
|
+
bindings: "bindings.node",
|
|
135
|
+
try: [
|
|
136
|
+
// node-gyp's linked version in the "build" dir
|
|
137
|
+
["module_root", "build", "bindings"],
|
|
138
|
+
// node-waf and gyp_addon (a.k.a node-gyp)
|
|
139
|
+
["module_root", "build", "Debug", "bindings"],
|
|
140
|
+
["module_root", "build", "Release", "bindings"],
|
|
141
|
+
// Debug files, for development (legacy behavior, remove for node v0.9)
|
|
142
|
+
["module_root", "out", "Debug", "bindings"],
|
|
143
|
+
["module_root", "Debug", "bindings"],
|
|
144
|
+
// Release files, but manually compiled (legacy behavior, remove for node v0.9)
|
|
145
|
+
["module_root", "out", "Release", "bindings"],
|
|
146
|
+
["module_root", "Release", "bindings"],
|
|
147
|
+
// Legacy from node-waf, node <= 0.4.x
|
|
148
|
+
["module_root", "build", "default", "bindings"],
|
|
149
|
+
// Production "Release" buildtype binary (meh...)
|
|
150
|
+
["module_root", "compiled", "version", "platform", "arch", "bindings"],
|
|
151
|
+
// node-qbs builds
|
|
152
|
+
["module_root", "addon-build", "release", "install-root", "bindings"],
|
|
153
|
+
["module_root", "addon-build", "debug", "install-root", "bindings"],
|
|
154
|
+
["module_root", "addon-build", "default", "install-root", "bindings"],
|
|
155
|
+
// node-pre-gyp path ./lib/binding/{node_abi}-{platform}-{arch}
|
|
156
|
+
["module_root", "lib", "binding", "nodePreGyp", "bindings"]
|
|
157
|
+
]
|
|
158
|
+
};
|
|
159
|
+
function bindings(opts) {
|
|
160
|
+
if (typeof opts == "string") {
|
|
161
|
+
opts = { bindings: opts };
|
|
162
|
+
} else if (!opts) {
|
|
163
|
+
opts = {};
|
|
164
|
+
}
|
|
165
|
+
Object.keys(defaults).map(function(i2) {
|
|
166
|
+
if (!(i2 in opts)) opts[i2] = defaults[i2];
|
|
167
|
+
});
|
|
168
|
+
if (!opts.module_root) {
|
|
169
|
+
opts.module_root = exports.getRoot(exports.getFileName());
|
|
170
|
+
}
|
|
171
|
+
if (path.extname(opts.bindings) != ".node") {
|
|
172
|
+
opts.bindings += ".node";
|
|
173
|
+
}
|
|
174
|
+
var requireFunc = typeof __webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
175
|
+
var tries = [], i = 0, l = opts.try.length, n, b, err;
|
|
176
|
+
for (; i < l; i++) {
|
|
177
|
+
n = join3.apply(
|
|
178
|
+
null,
|
|
179
|
+
opts.try[i].map(function(p) {
|
|
180
|
+
return opts[p] || p;
|
|
181
|
+
})
|
|
182
|
+
);
|
|
183
|
+
tries.push(n);
|
|
184
|
+
try {
|
|
185
|
+
b = opts.path ? requireFunc.resolve(n) : requireFunc(n);
|
|
186
|
+
if (!opts.path) {
|
|
187
|
+
b.path = n;
|
|
188
|
+
}
|
|
189
|
+
return b;
|
|
190
|
+
} catch (e) {
|
|
191
|
+
if (e.code !== "MODULE_NOT_FOUND" && e.code !== "QUALIFIED_PATH_RESOLUTION_FAILED" && !/not find/i.test(e.message)) {
|
|
192
|
+
throw e;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
err = new Error(
|
|
197
|
+
"Could not locate the bindings file. Tried:\n" + tries.map(function(a) {
|
|
198
|
+
return opts.arrow + a;
|
|
199
|
+
}).join("\n")
|
|
200
|
+
);
|
|
201
|
+
err.tries = tries;
|
|
202
|
+
throw err;
|
|
203
|
+
}
|
|
204
|
+
module.exports = exports = bindings;
|
|
205
|
+
exports.getFileName = function getFileName(calling_file) {
|
|
206
|
+
var origPST = Error.prepareStackTrace, origSTL = Error.stackTraceLimit, dummy = {}, fileName;
|
|
207
|
+
Error.stackTraceLimit = 10;
|
|
208
|
+
Error.prepareStackTrace = function(e, st) {
|
|
209
|
+
for (var i = 0, l = st.length; i < l; i++) {
|
|
210
|
+
fileName = st[i].getFileName();
|
|
211
|
+
if (fileName !== __filename) {
|
|
212
|
+
if (calling_file) {
|
|
213
|
+
if (fileName !== calling_file) {
|
|
214
|
+
return;
|
|
215
|
+
}
|
|
216
|
+
} else {
|
|
217
|
+
return;
|
|
218
|
+
}
|
|
219
|
+
}
|
|
220
|
+
}
|
|
221
|
+
};
|
|
222
|
+
Error.captureStackTrace(dummy);
|
|
223
|
+
dummy.stack;
|
|
224
|
+
Error.prepareStackTrace = origPST;
|
|
225
|
+
Error.stackTraceLimit = origSTL;
|
|
226
|
+
var fileSchema = "file://";
|
|
227
|
+
if (fileName.indexOf(fileSchema) === 0) {
|
|
228
|
+
fileName = fileURLToPath2(fileName);
|
|
229
|
+
}
|
|
230
|
+
return fileName;
|
|
231
|
+
};
|
|
232
|
+
exports.getRoot = function getRoot(file) {
|
|
233
|
+
var dir = dirname2(file), prev;
|
|
234
|
+
while (true) {
|
|
235
|
+
if (dir === ".") {
|
|
236
|
+
dir = process.cwd();
|
|
237
|
+
}
|
|
238
|
+
if (exists(join3(dir, "package.json")) || exists(join3(dir, "node_modules"))) {
|
|
239
|
+
return dir;
|
|
240
|
+
}
|
|
241
|
+
if (prev === dir) {
|
|
242
|
+
throw new Error(
|
|
243
|
+
'Could not find module root given file: "' + file + '". Do you have a `package.json` file? '
|
|
244
|
+
);
|
|
245
|
+
}
|
|
246
|
+
prev = dir;
|
|
247
|
+
dir = join3(dir, "..");
|
|
248
|
+
}
|
|
249
|
+
};
|
|
250
|
+
}
|
|
251
|
+
});
|
|
252
|
+
|
|
253
|
+
// node_modules/better-sqlite3/lib/methods/wrappers.js
|
|
254
|
+
var require_wrappers = __commonJS({
|
|
255
|
+
"node_modules/better-sqlite3/lib/methods/wrappers.js"(exports) {
|
|
256
|
+
"use strict";
|
|
257
|
+
var { cppdb } = require_util();
|
|
258
|
+
exports.prepare = function prepare(sql) {
|
|
259
|
+
return this[cppdb].prepare(sql, this, false);
|
|
260
|
+
};
|
|
261
|
+
exports.exec = function exec(sql) {
|
|
262
|
+
this[cppdb].exec(sql);
|
|
263
|
+
return this;
|
|
264
|
+
};
|
|
265
|
+
exports.close = function close() {
|
|
266
|
+
this[cppdb].close();
|
|
267
|
+
return this;
|
|
268
|
+
};
|
|
269
|
+
exports.loadExtension = function loadExtension(...args) {
|
|
270
|
+
this[cppdb].loadExtension(...args);
|
|
271
|
+
return this;
|
|
272
|
+
};
|
|
273
|
+
exports.defaultSafeIntegers = function defaultSafeIntegers(...args) {
|
|
274
|
+
this[cppdb].defaultSafeIntegers(...args);
|
|
275
|
+
return this;
|
|
276
|
+
};
|
|
277
|
+
exports.unsafeMode = function unsafeMode(...args) {
|
|
278
|
+
this[cppdb].unsafeMode(...args);
|
|
279
|
+
return this;
|
|
280
|
+
};
|
|
281
|
+
exports.getters = {
|
|
282
|
+
name: {
|
|
283
|
+
get: function name() {
|
|
284
|
+
return this[cppdb].name;
|
|
285
|
+
},
|
|
286
|
+
enumerable: true
|
|
287
|
+
},
|
|
288
|
+
open: {
|
|
289
|
+
get: function open() {
|
|
290
|
+
return this[cppdb].open;
|
|
291
|
+
},
|
|
292
|
+
enumerable: true
|
|
293
|
+
},
|
|
294
|
+
inTransaction: {
|
|
295
|
+
get: function inTransaction() {
|
|
296
|
+
return this[cppdb].inTransaction;
|
|
297
|
+
},
|
|
298
|
+
enumerable: true
|
|
299
|
+
},
|
|
300
|
+
readonly: {
|
|
301
|
+
get: function readonly() {
|
|
302
|
+
return this[cppdb].readonly;
|
|
303
|
+
},
|
|
304
|
+
enumerable: true
|
|
305
|
+
},
|
|
306
|
+
memory: {
|
|
307
|
+
get: function memory() {
|
|
308
|
+
return this[cppdb].memory;
|
|
309
|
+
},
|
|
310
|
+
enumerable: true
|
|
311
|
+
}
|
|
312
|
+
};
|
|
313
|
+
}
|
|
314
|
+
});
|
|
315
|
+
|
|
316
|
+
// node_modules/better-sqlite3/lib/methods/transaction.js
|
|
317
|
+
var require_transaction = __commonJS({
|
|
318
|
+
"node_modules/better-sqlite3/lib/methods/transaction.js"(exports, module) {
|
|
319
|
+
"use strict";
|
|
320
|
+
var { cppdb } = require_util();
|
|
321
|
+
var controllers = /* @__PURE__ */ new WeakMap();
|
|
322
|
+
module.exports = function transaction(fn) {
|
|
323
|
+
if (typeof fn !== "function") throw new TypeError("Expected first argument to be a function");
|
|
324
|
+
const db = this[cppdb];
|
|
325
|
+
const controller = getController(db, this);
|
|
326
|
+
const { apply } = Function.prototype;
|
|
327
|
+
const properties = {
|
|
328
|
+
default: { value: wrapTransaction(apply, fn, db, controller.default) },
|
|
329
|
+
deferred: { value: wrapTransaction(apply, fn, db, controller.deferred) },
|
|
330
|
+
immediate: { value: wrapTransaction(apply, fn, db, controller.immediate) },
|
|
331
|
+
exclusive: { value: wrapTransaction(apply, fn, db, controller.exclusive) },
|
|
332
|
+
database: { value: this, enumerable: true }
|
|
333
|
+
};
|
|
334
|
+
Object.defineProperties(properties.default.value, properties);
|
|
335
|
+
Object.defineProperties(properties.deferred.value, properties);
|
|
336
|
+
Object.defineProperties(properties.immediate.value, properties);
|
|
337
|
+
Object.defineProperties(properties.exclusive.value, properties);
|
|
338
|
+
return properties.default.value;
|
|
339
|
+
};
|
|
340
|
+
var getController = (db, self) => {
|
|
341
|
+
let controller = controllers.get(db);
|
|
342
|
+
if (!controller) {
|
|
343
|
+
const shared = {
|
|
344
|
+
commit: db.prepare("COMMIT", self, false),
|
|
345
|
+
rollback: db.prepare("ROLLBACK", self, false),
|
|
346
|
+
savepoint: db.prepare("SAVEPOINT ` _bs3. `", self, false),
|
|
347
|
+
release: db.prepare("RELEASE ` _bs3. `", self, false),
|
|
348
|
+
rollbackTo: db.prepare("ROLLBACK TO ` _bs3. `", self, false)
|
|
349
|
+
};
|
|
350
|
+
controllers.set(db, controller = {
|
|
351
|
+
default: Object.assign({ begin: db.prepare("BEGIN", self, false) }, shared),
|
|
352
|
+
deferred: Object.assign({ begin: db.prepare("BEGIN DEFERRED", self, false) }, shared),
|
|
353
|
+
immediate: Object.assign({ begin: db.prepare("BEGIN IMMEDIATE", self, false) }, shared),
|
|
354
|
+
exclusive: Object.assign({ begin: db.prepare("BEGIN EXCLUSIVE", self, false) }, shared)
|
|
355
|
+
});
|
|
356
|
+
}
|
|
357
|
+
return controller;
|
|
358
|
+
};
|
|
359
|
+
var wrapTransaction = (apply, fn, db, { begin, commit, rollback, savepoint, release, rollbackTo }) => function sqliteTransaction() {
|
|
360
|
+
let before, after, undo;
|
|
361
|
+
if (db.inTransaction) {
|
|
362
|
+
before = savepoint;
|
|
363
|
+
after = release;
|
|
364
|
+
undo = rollbackTo;
|
|
365
|
+
} else {
|
|
366
|
+
before = begin;
|
|
367
|
+
after = commit;
|
|
368
|
+
undo = rollback;
|
|
369
|
+
}
|
|
370
|
+
before.run();
|
|
371
|
+
try {
|
|
372
|
+
const result = apply.call(fn, this, arguments);
|
|
373
|
+
if (result && typeof result.then === "function") {
|
|
374
|
+
throw new TypeError("Transaction function cannot return a promise");
|
|
375
|
+
}
|
|
376
|
+
after.run();
|
|
377
|
+
return result;
|
|
378
|
+
} catch (ex) {
|
|
379
|
+
if (db.inTransaction) {
|
|
380
|
+
undo.run();
|
|
381
|
+
if (undo !== rollback) after.run();
|
|
382
|
+
}
|
|
383
|
+
throw ex;
|
|
384
|
+
}
|
|
385
|
+
};
|
|
386
|
+
}
|
|
387
|
+
});
|
|
388
|
+
|
|
389
|
+
// node_modules/better-sqlite3/lib/methods/pragma.js
|
|
390
|
+
var require_pragma = __commonJS({
|
|
391
|
+
"node_modules/better-sqlite3/lib/methods/pragma.js"(exports, module) {
|
|
392
|
+
"use strict";
|
|
393
|
+
var { getBooleanOption, cppdb } = require_util();
|
|
394
|
+
module.exports = function pragma(source, options) {
|
|
395
|
+
if (options == null) options = {};
|
|
396
|
+
if (typeof source !== "string") throw new TypeError("Expected first argument to be a string");
|
|
397
|
+
if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
|
|
398
|
+
const simple = getBooleanOption(options, "simple");
|
|
399
|
+
const stmt = this[cppdb].prepare(`PRAGMA ${source}`, this, true);
|
|
400
|
+
return simple ? stmt.pluck().get() : stmt.all();
|
|
401
|
+
};
|
|
402
|
+
}
|
|
403
|
+
});
|
|
404
|
+
|
|
405
|
+
// node_modules/better-sqlite3/lib/methods/backup.js
|
|
406
|
+
var require_backup = __commonJS({
|
|
407
|
+
"node_modules/better-sqlite3/lib/methods/backup.js"(exports, module) {
|
|
408
|
+
"use strict";
|
|
409
|
+
var fs = __require("fs");
|
|
410
|
+
var path = __require("path");
|
|
411
|
+
var { promisify } = __require("util");
|
|
412
|
+
var { cppdb } = require_util();
|
|
413
|
+
var fsAccess = promisify(fs.access);
|
|
414
|
+
module.exports = async function backup(filename, options) {
|
|
415
|
+
if (options == null) options = {};
|
|
416
|
+
if (typeof filename !== "string") throw new TypeError("Expected first argument to be a string");
|
|
417
|
+
if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
|
|
418
|
+
filename = filename.trim();
|
|
419
|
+
const attachedName = "attached" in options ? options.attached : "main";
|
|
420
|
+
const handler = "progress" in options ? options.progress : null;
|
|
421
|
+
if (!filename) throw new TypeError("Backup filename cannot be an empty string");
|
|
422
|
+
if (filename === ":memory:") throw new TypeError('Invalid backup filename ":memory:"');
|
|
423
|
+
if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
|
|
424
|
+
if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
|
|
425
|
+
if (handler != null && typeof handler !== "function") throw new TypeError('Expected the "progress" option to be a function');
|
|
426
|
+
await fsAccess(path.dirname(filename)).catch(() => {
|
|
427
|
+
throw new TypeError("Cannot save backup because the directory does not exist");
|
|
428
|
+
});
|
|
429
|
+
const isNewFile = await fsAccess(filename).then(() => false, () => true);
|
|
430
|
+
return runBackup(this[cppdb].backup(this, attachedName, filename, isNewFile), handler || null);
|
|
431
|
+
};
|
|
432
|
+
var runBackup = (backup, handler) => {
|
|
433
|
+
let rate = 0;
|
|
434
|
+
let useDefault = true;
|
|
435
|
+
return new Promise((resolve, reject) => {
|
|
436
|
+
setImmediate(function step() {
|
|
437
|
+
try {
|
|
438
|
+
const progress = backup.transfer(rate);
|
|
439
|
+
if (!progress.remainingPages) {
|
|
440
|
+
backup.close();
|
|
441
|
+
resolve(progress);
|
|
442
|
+
return;
|
|
443
|
+
}
|
|
444
|
+
if (useDefault) {
|
|
445
|
+
useDefault = false;
|
|
446
|
+
rate = 100;
|
|
447
|
+
}
|
|
448
|
+
if (handler) {
|
|
449
|
+
const ret = handler(progress);
|
|
450
|
+
if (ret !== void 0) {
|
|
451
|
+
if (typeof ret === "number" && ret === ret) rate = Math.max(0, Math.min(2147483647, Math.round(ret)));
|
|
452
|
+
else throw new TypeError("Expected progress callback to return a number or undefined");
|
|
453
|
+
}
|
|
454
|
+
}
|
|
455
|
+
setImmediate(step);
|
|
456
|
+
} catch (err) {
|
|
457
|
+
backup.close();
|
|
458
|
+
reject(err);
|
|
459
|
+
}
|
|
460
|
+
});
|
|
461
|
+
});
|
|
462
|
+
};
|
|
463
|
+
}
|
|
464
|
+
});
|
|
465
|
+
|
|
466
|
+
// node_modules/better-sqlite3/lib/methods/serialize.js
|
|
467
|
+
var require_serialize = __commonJS({
|
|
468
|
+
"node_modules/better-sqlite3/lib/methods/serialize.js"(exports, module) {
|
|
469
|
+
"use strict";
|
|
470
|
+
var { cppdb } = require_util();
|
|
471
|
+
module.exports = function serialize(options) {
|
|
472
|
+
if (options == null) options = {};
|
|
473
|
+
if (typeof options !== "object") throw new TypeError("Expected first argument to be an options object");
|
|
474
|
+
const attachedName = "attached" in options ? options.attached : "main";
|
|
475
|
+
if (typeof attachedName !== "string") throw new TypeError('Expected the "attached" option to be a string');
|
|
476
|
+
if (!attachedName) throw new TypeError('The "attached" option cannot be an empty string');
|
|
477
|
+
return this[cppdb].serialize(attachedName);
|
|
478
|
+
};
|
|
479
|
+
}
|
|
480
|
+
});
|
|
481
|
+
|
|
482
|
+
// node_modules/better-sqlite3/lib/methods/function.js
|
|
483
|
+
var require_function = __commonJS({
|
|
484
|
+
"node_modules/better-sqlite3/lib/methods/function.js"(exports, module) {
|
|
485
|
+
"use strict";
|
|
486
|
+
var { getBooleanOption, cppdb } = require_util();
|
|
487
|
+
module.exports = function defineFunction(name, options, fn) {
|
|
488
|
+
if (options == null) options = {};
|
|
489
|
+
if (typeof options === "function") {
|
|
490
|
+
fn = options;
|
|
491
|
+
options = {};
|
|
492
|
+
}
|
|
493
|
+
if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
|
|
494
|
+
if (typeof fn !== "function") throw new TypeError("Expected last argument to be a function");
|
|
495
|
+
if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
|
|
496
|
+
if (!name) throw new TypeError("User-defined function name cannot be an empty string");
|
|
497
|
+
const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
|
|
498
|
+
const deterministic = getBooleanOption(options, "deterministic");
|
|
499
|
+
const directOnly = getBooleanOption(options, "directOnly");
|
|
500
|
+
const varargs = getBooleanOption(options, "varargs");
|
|
501
|
+
let argCount = -1;
|
|
502
|
+
if (!varargs) {
|
|
503
|
+
argCount = fn.length;
|
|
504
|
+
if (!Number.isInteger(argCount) || argCount < 0) throw new TypeError("Expected function.length to be a positive integer");
|
|
505
|
+
if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
|
|
506
|
+
}
|
|
507
|
+
this[cppdb].function(fn, name, argCount, safeIntegers, deterministic, directOnly);
|
|
508
|
+
return this;
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
});
|
|
512
|
+
|
|
513
|
+
// node_modules/better-sqlite3/lib/methods/aggregate.js
|
|
514
|
+
var require_aggregate = __commonJS({
|
|
515
|
+
"node_modules/better-sqlite3/lib/methods/aggregate.js"(exports, module) {
|
|
516
|
+
"use strict";
|
|
517
|
+
var { getBooleanOption, cppdb } = require_util();
|
|
518
|
+
module.exports = function defineAggregate(name, options) {
|
|
519
|
+
if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
|
|
520
|
+
if (typeof options !== "object" || options === null) throw new TypeError("Expected second argument to be an options object");
|
|
521
|
+
if (!name) throw new TypeError("User-defined function name cannot be an empty string");
|
|
522
|
+
const start = "start" in options ? options.start : null;
|
|
523
|
+
const step = getFunctionOption(options, "step", true);
|
|
524
|
+
const inverse = getFunctionOption(options, "inverse", false);
|
|
525
|
+
const result = getFunctionOption(options, "result", false);
|
|
526
|
+
const safeIntegers = "safeIntegers" in options ? +getBooleanOption(options, "safeIntegers") : 2;
|
|
527
|
+
const deterministic = getBooleanOption(options, "deterministic");
|
|
528
|
+
const directOnly = getBooleanOption(options, "directOnly");
|
|
529
|
+
const varargs = getBooleanOption(options, "varargs");
|
|
530
|
+
let argCount = -1;
|
|
531
|
+
if (!varargs) {
|
|
532
|
+
argCount = Math.max(getLength(step), inverse ? getLength(inverse) : 0);
|
|
533
|
+
if (argCount > 0) argCount -= 1;
|
|
534
|
+
if (argCount > 100) throw new RangeError("User-defined functions cannot have more than 100 arguments");
|
|
535
|
+
}
|
|
536
|
+
this[cppdb].aggregate(start, step, inverse, result, name, argCount, safeIntegers, deterministic, directOnly);
|
|
537
|
+
return this;
|
|
538
|
+
};
|
|
539
|
+
var getFunctionOption = (options, key, required) => {
|
|
540
|
+
const value = key in options ? options[key] : null;
|
|
541
|
+
if (typeof value === "function") return value;
|
|
542
|
+
if (value != null) throw new TypeError(`Expected the "${key}" option to be a function`);
|
|
543
|
+
if (required) throw new TypeError(`Missing required option "${key}"`);
|
|
544
|
+
return null;
|
|
545
|
+
};
|
|
546
|
+
var getLength = ({ length }) => {
|
|
547
|
+
if (Number.isInteger(length) && length >= 0) return length;
|
|
548
|
+
throw new TypeError("Expected function.length to be a positive integer");
|
|
549
|
+
};
|
|
550
|
+
}
|
|
551
|
+
});
|
|
552
|
+
|
|
553
|
+
// node_modules/better-sqlite3/lib/methods/table.js
|
|
554
|
+
var require_table = __commonJS({
|
|
555
|
+
"node_modules/better-sqlite3/lib/methods/table.js"(exports, module) {
|
|
556
|
+
"use strict";
|
|
557
|
+
var { cppdb } = require_util();
|
|
558
|
+
module.exports = function defineTable(name, factory) {
|
|
559
|
+
if (typeof name !== "string") throw new TypeError("Expected first argument to be a string");
|
|
560
|
+
if (!name) throw new TypeError("Virtual table module name cannot be an empty string");
|
|
561
|
+
let eponymous = false;
|
|
562
|
+
if (typeof factory === "object" && factory !== null) {
|
|
563
|
+
eponymous = true;
|
|
564
|
+
factory = defer(parseTableDefinition(factory, "used", name));
|
|
565
|
+
} else {
|
|
566
|
+
if (typeof factory !== "function") throw new TypeError("Expected second argument to be a function or a table definition object");
|
|
567
|
+
factory = wrapFactory(factory);
|
|
568
|
+
}
|
|
569
|
+
this[cppdb].table(factory, name, eponymous);
|
|
570
|
+
return this;
|
|
571
|
+
};
|
|
572
|
+
function wrapFactory(factory) {
|
|
573
|
+
return function virtualTableFactory(moduleName, databaseName, tableName, ...args) {
|
|
574
|
+
const thisObject = {
|
|
575
|
+
module: moduleName,
|
|
576
|
+
database: databaseName,
|
|
577
|
+
table: tableName
|
|
578
|
+
};
|
|
579
|
+
const def = apply.call(factory, thisObject, args);
|
|
580
|
+
if (typeof def !== "object" || def === null) {
|
|
581
|
+
throw new TypeError(`Virtual table module "${moduleName}" did not return a table definition object`);
|
|
582
|
+
}
|
|
583
|
+
return parseTableDefinition(def, "returned", moduleName);
|
|
584
|
+
};
|
|
585
|
+
}
|
|
586
|
+
function parseTableDefinition(def, verb, moduleName) {
|
|
587
|
+
if (!hasOwnProperty.call(def, "rows")) {
|
|
588
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "rows" property`);
|
|
589
|
+
}
|
|
590
|
+
if (!hasOwnProperty.call(def, "columns")) {
|
|
591
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition without a "columns" property`);
|
|
592
|
+
}
|
|
593
|
+
const rows = def.rows;
|
|
594
|
+
if (typeof rows !== "function" || Object.getPrototypeOf(rows) !== GeneratorFunctionPrototype) {
|
|
595
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "rows" property (should be a generator function)`);
|
|
596
|
+
}
|
|
597
|
+
let columns = def.columns;
|
|
598
|
+
if (!Array.isArray(columns) || !(columns = [...columns]).every((x) => typeof x === "string")) {
|
|
599
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "columns" property (should be an array of strings)`);
|
|
600
|
+
}
|
|
601
|
+
if (columns.length !== new Set(columns).size) {
|
|
602
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate column names`);
|
|
603
|
+
}
|
|
604
|
+
if (!columns.length) {
|
|
605
|
+
throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with zero columns`);
|
|
606
|
+
}
|
|
607
|
+
let parameters;
|
|
608
|
+
if (hasOwnProperty.call(def, "parameters")) {
|
|
609
|
+
parameters = def.parameters;
|
|
610
|
+
if (!Array.isArray(parameters) || !(parameters = [...parameters]).every((x) => typeof x === "string")) {
|
|
611
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "parameters" property (should be an array of strings)`);
|
|
612
|
+
}
|
|
613
|
+
} else {
|
|
614
|
+
parameters = inferParameters(rows);
|
|
615
|
+
}
|
|
616
|
+
if (parameters.length !== new Set(parameters).size) {
|
|
617
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with duplicate parameter names`);
|
|
618
|
+
}
|
|
619
|
+
if (parameters.length > 32) {
|
|
620
|
+
throw new RangeError(`Virtual table module "${moduleName}" ${verb} a table definition with more than the maximum number of 32 parameters`);
|
|
621
|
+
}
|
|
622
|
+
for (const parameter of parameters) {
|
|
623
|
+
if (columns.includes(parameter)) {
|
|
624
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with column "${parameter}" which was ambiguously defined as both a column and parameter`);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
let safeIntegers = 2;
|
|
628
|
+
if (hasOwnProperty.call(def, "safeIntegers")) {
|
|
629
|
+
const bool = def.safeIntegers;
|
|
630
|
+
if (typeof bool !== "boolean") {
|
|
631
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "safeIntegers" property (should be a boolean)`);
|
|
632
|
+
}
|
|
633
|
+
safeIntegers = +bool;
|
|
634
|
+
}
|
|
635
|
+
let directOnly = false;
|
|
636
|
+
if (hasOwnProperty.call(def, "directOnly")) {
|
|
637
|
+
directOnly = def.directOnly;
|
|
638
|
+
if (typeof directOnly !== "boolean") {
|
|
639
|
+
throw new TypeError(`Virtual table module "${moduleName}" ${verb} a table definition with an invalid "directOnly" property (should be a boolean)`);
|
|
640
|
+
}
|
|
641
|
+
}
|
|
642
|
+
const columnDefinitions = [
|
|
643
|
+
...parameters.map(identifier).map((str) => `${str} HIDDEN`),
|
|
644
|
+
...columns.map(identifier)
|
|
645
|
+
];
|
|
646
|
+
return [
|
|
647
|
+
`CREATE TABLE x(${columnDefinitions.join(", ")});`,
|
|
648
|
+
wrapGenerator(rows, new Map(columns.map((x, i) => [x, parameters.length + i])), moduleName),
|
|
649
|
+
parameters,
|
|
650
|
+
safeIntegers,
|
|
651
|
+
directOnly
|
|
652
|
+
];
|
|
653
|
+
}
|
|
654
|
+
function wrapGenerator(generator, columnMap, moduleName) {
|
|
655
|
+
return function* virtualTable(...args) {
|
|
656
|
+
const output = args.map((x) => Buffer.isBuffer(x) ? Buffer.from(x) : x);
|
|
657
|
+
for (let i = 0; i < columnMap.size; ++i) {
|
|
658
|
+
output.push(null);
|
|
659
|
+
}
|
|
660
|
+
for (const row of generator(...args)) {
|
|
661
|
+
if (Array.isArray(row)) {
|
|
662
|
+
extractRowArray(row, output, columnMap.size, moduleName);
|
|
663
|
+
yield output;
|
|
664
|
+
} else if (typeof row === "object" && row !== null) {
|
|
665
|
+
extractRowObject(row, output, columnMap, moduleName);
|
|
666
|
+
yield output;
|
|
667
|
+
} else {
|
|
668
|
+
throw new TypeError(`Virtual table module "${moduleName}" yielded something that isn't a valid row object`);
|
|
669
|
+
}
|
|
670
|
+
}
|
|
671
|
+
};
|
|
672
|
+
}
|
|
673
|
+
function extractRowArray(row, output, columnCount, moduleName) {
|
|
674
|
+
if (row.length !== columnCount) {
|
|
675
|
+
throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an incorrect number of columns`);
|
|
676
|
+
}
|
|
677
|
+
const offset = output.length - columnCount;
|
|
678
|
+
for (let i = 0; i < columnCount; ++i) {
|
|
679
|
+
output[i + offset] = row[i];
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
function extractRowObject(row, output, columnMap, moduleName) {
|
|
683
|
+
let count = 0;
|
|
684
|
+
for (const key of Object.keys(row)) {
|
|
685
|
+
const index = columnMap.get(key);
|
|
686
|
+
if (index === void 0) {
|
|
687
|
+
throw new TypeError(`Virtual table module "${moduleName}" yielded a row with an undeclared column "${key}"`);
|
|
688
|
+
}
|
|
689
|
+
output[index] = row[key];
|
|
690
|
+
count += 1;
|
|
691
|
+
}
|
|
692
|
+
if (count !== columnMap.size) {
|
|
693
|
+
throw new TypeError(`Virtual table module "${moduleName}" yielded a row with missing columns`);
|
|
694
|
+
}
|
|
695
|
+
}
|
|
696
|
+
function inferParameters({ length }) {
|
|
697
|
+
if (!Number.isInteger(length) || length < 0) {
|
|
698
|
+
throw new TypeError("Expected function.length to be a positive integer");
|
|
699
|
+
}
|
|
700
|
+
const params = [];
|
|
701
|
+
for (let i = 0; i < length; ++i) {
|
|
702
|
+
params.push(`$${i + 1}`);
|
|
703
|
+
}
|
|
704
|
+
return params;
|
|
705
|
+
}
|
|
706
|
+
var { hasOwnProperty } = Object.prototype;
|
|
707
|
+
var { apply } = Function.prototype;
|
|
708
|
+
var GeneratorFunctionPrototype = Object.getPrototypeOf(function* () {
|
|
709
|
+
});
|
|
710
|
+
var identifier = (str) => `"${str.replace(/"/g, '""')}"`;
|
|
711
|
+
var defer = (x) => () => x;
|
|
712
|
+
}
|
|
713
|
+
});
|
|
714
|
+
|
|
715
|
+
// node_modules/better-sqlite3/lib/methods/inspect.js
|
|
716
|
+
var require_inspect = __commonJS({
|
|
717
|
+
"node_modules/better-sqlite3/lib/methods/inspect.js"(exports, module) {
|
|
718
|
+
"use strict";
|
|
719
|
+
var DatabaseInspection = function Database2() {
|
|
720
|
+
};
|
|
721
|
+
module.exports = function inspect(depth, opts) {
|
|
722
|
+
return Object.assign(new DatabaseInspection(), this);
|
|
723
|
+
};
|
|
724
|
+
}
|
|
725
|
+
});
|
|
726
|
+
|
|
727
|
+
// node_modules/better-sqlite3/lib/database.js
|
|
728
|
+
var require_database = __commonJS({
|
|
729
|
+
"node_modules/better-sqlite3/lib/database.js"(exports, module) {
|
|
730
|
+
"use strict";
|
|
731
|
+
var fs = __require("fs");
|
|
732
|
+
var path = __require("path");
|
|
733
|
+
var util = require_util();
|
|
734
|
+
var SqliteError = require_sqlite_error();
|
|
735
|
+
var DEFAULT_ADDON;
|
|
736
|
+
function Database2(filenameGiven, options) {
|
|
737
|
+
if (new.target == null) {
|
|
738
|
+
return new Database2(filenameGiven, options);
|
|
739
|
+
}
|
|
740
|
+
let buffer;
|
|
741
|
+
if (Buffer.isBuffer(filenameGiven)) {
|
|
742
|
+
buffer = filenameGiven;
|
|
743
|
+
filenameGiven = ":memory:";
|
|
744
|
+
}
|
|
745
|
+
if (filenameGiven == null) filenameGiven = "";
|
|
746
|
+
if (options == null) options = {};
|
|
747
|
+
if (typeof filenameGiven !== "string") throw new TypeError("Expected first argument to be a string");
|
|
748
|
+
if (typeof options !== "object") throw new TypeError("Expected second argument to be an options object");
|
|
749
|
+
if ("readOnly" in options) throw new TypeError('Misspelled option "readOnly" should be "readonly"');
|
|
750
|
+
if ("memory" in options) throw new TypeError('Option "memory" was removed in v7.0.0 (use ":memory:" filename instead)');
|
|
751
|
+
const filename = filenameGiven.trim();
|
|
752
|
+
const anonymous = filename === "" || filename === ":memory:";
|
|
753
|
+
const readonly = util.getBooleanOption(options, "readonly");
|
|
754
|
+
const fileMustExist = util.getBooleanOption(options, "fileMustExist");
|
|
755
|
+
const timeout = "timeout" in options ? options.timeout : 5e3;
|
|
756
|
+
const verbose = "verbose" in options ? options.verbose : null;
|
|
757
|
+
const nativeBinding = "nativeBinding" in options ? options.nativeBinding : null;
|
|
758
|
+
if (readonly && anonymous && !buffer) throw new TypeError("In-memory/temporary databases cannot be readonly");
|
|
759
|
+
if (!Number.isInteger(timeout) || timeout < 0) throw new TypeError('Expected the "timeout" option to be a positive integer');
|
|
760
|
+
if (timeout > 2147483647) throw new RangeError('Option "timeout" cannot be greater than 2147483647');
|
|
761
|
+
if (verbose != null && typeof verbose !== "function") throw new TypeError('Expected the "verbose" option to be a function');
|
|
762
|
+
if (nativeBinding != null && typeof nativeBinding !== "string" && typeof nativeBinding !== "object") throw new TypeError('Expected the "nativeBinding" option to be a string or addon object');
|
|
763
|
+
let addon;
|
|
764
|
+
if (nativeBinding == null) {
|
|
765
|
+
addon = DEFAULT_ADDON || (DEFAULT_ADDON = require_bindings()("better_sqlite3.node"));
|
|
766
|
+
} else if (typeof nativeBinding === "string") {
|
|
767
|
+
const requireFunc = typeof __non_webpack_require__ === "function" ? __non_webpack_require__ : __require;
|
|
768
|
+
addon = requireFunc(path.resolve(nativeBinding).replace(/(\.node)?$/, ".node"));
|
|
769
|
+
} else {
|
|
770
|
+
addon = nativeBinding;
|
|
771
|
+
}
|
|
772
|
+
if (!addon.isInitialized) {
|
|
773
|
+
addon.setErrorConstructor(SqliteError);
|
|
774
|
+
addon.isInitialized = true;
|
|
775
|
+
}
|
|
776
|
+
if (!anonymous && !filename.startsWith("file:") && !fs.existsSync(path.dirname(filename))) {
|
|
777
|
+
throw new TypeError("Cannot open database because the directory does not exist");
|
|
778
|
+
}
|
|
779
|
+
Object.defineProperties(this, {
|
|
780
|
+
[util.cppdb]: { value: new addon.Database(filename, filenameGiven, anonymous, readonly, fileMustExist, timeout, verbose || null, buffer || null) },
|
|
781
|
+
...wrappers.getters
|
|
782
|
+
});
|
|
783
|
+
}
|
|
784
|
+
var wrappers = require_wrappers();
|
|
785
|
+
Database2.prototype.prepare = wrappers.prepare;
|
|
786
|
+
Database2.prototype.transaction = require_transaction();
|
|
787
|
+
Database2.prototype.pragma = require_pragma();
|
|
788
|
+
Database2.prototype.backup = require_backup();
|
|
789
|
+
Database2.prototype.serialize = require_serialize();
|
|
790
|
+
Database2.prototype.function = require_function();
|
|
791
|
+
Database2.prototype.aggregate = require_aggregate();
|
|
792
|
+
Database2.prototype.table = require_table();
|
|
793
|
+
Database2.prototype.loadExtension = wrappers.loadExtension;
|
|
794
|
+
Database2.prototype.exec = wrappers.exec;
|
|
795
|
+
Database2.prototype.close = wrappers.close;
|
|
796
|
+
Database2.prototype.defaultSafeIntegers = wrappers.defaultSafeIntegers;
|
|
797
|
+
Database2.prototype.unsafeMode = wrappers.unsafeMode;
|
|
798
|
+
Database2.prototype[util.inspect] = require_inspect();
|
|
799
|
+
module.exports = Database2;
|
|
800
|
+
}
|
|
801
|
+
});
|
|
802
|
+
|
|
803
|
+
// node_modules/better-sqlite3/lib/index.js
|
|
804
|
+
var require_lib = __commonJS({
|
|
805
|
+
"node_modules/better-sqlite3/lib/index.js"(exports, module) {
|
|
806
|
+
"use strict";
|
|
807
|
+
module.exports = require_database();
|
|
808
|
+
module.exports.SqliteError = require_sqlite_error();
|
|
809
|
+
}
|
|
810
|
+
});
|
|
811
|
+
|
|
812
|
+
// src/services/sqlite/Sessions.ts
|
|
813
|
+
var Sessions_exports = {};
|
|
814
|
+
__export(Sessions_exports, {
|
|
815
|
+
completeSession: () => completeSession,
|
|
816
|
+
createSession: () => createSession,
|
|
817
|
+
failSession: () => failSession,
|
|
818
|
+
getActiveSessions: () => getActiveSessions,
|
|
819
|
+
getSessionByContentId: () => getSessionByContentId,
|
|
820
|
+
getSessionById: () => getSessionById,
|
|
821
|
+
getSessionsByProject: () => getSessionsByProject,
|
|
822
|
+
updateSessionMemoryId: () => updateSessionMemoryId
|
|
823
|
+
});
|
|
824
|
+
function createSession(db, contentSessionId, project, userPrompt) {
|
|
825
|
+
const now = /* @__PURE__ */ new Date();
|
|
826
|
+
const result = db.run(
|
|
827
|
+
`INSERT INTO sessions (content_session_id, project, user_prompt, status, started_at, started_at_epoch)
|
|
828
|
+
VALUES (?, ?, ?, 'active', ?, ?)`,
|
|
829
|
+
[contentSessionId, project, userPrompt, now.toISOString(), now.getTime()]
|
|
830
|
+
);
|
|
831
|
+
return Number(result.lastInsertRowid);
|
|
832
|
+
}
|
|
833
|
+
function getSessionByContentId(db, contentSessionId) {
|
|
834
|
+
const query = db.query("SELECT * FROM sessions WHERE content_session_id = ?");
|
|
835
|
+
return query.get(contentSessionId);
|
|
836
|
+
}
|
|
837
|
+
function getSessionById(db, id) {
|
|
838
|
+
const query = db.query("SELECT * FROM sessions WHERE id = ?");
|
|
839
|
+
return query.get(id);
|
|
840
|
+
}
|
|
841
|
+
function updateSessionMemoryId(db, id, memorySessionId) {
|
|
842
|
+
db.run(
|
|
843
|
+
"UPDATE sessions SET memory_session_id = ? WHERE id = ?",
|
|
844
|
+
[memorySessionId, id]
|
|
845
|
+
);
|
|
846
|
+
}
|
|
847
|
+
function completeSession(db, id) {
|
|
848
|
+
const now = /* @__PURE__ */ new Date();
|
|
849
|
+
db.run(
|
|
850
|
+
`UPDATE sessions
|
|
851
|
+
SET status = 'completed', completed_at = ?, completed_at_epoch = ?
|
|
852
|
+
WHERE id = ?`,
|
|
853
|
+
[now.toISOString(), now.getTime(), id]
|
|
854
|
+
);
|
|
855
|
+
}
|
|
856
|
+
function failSession(db, id) {
|
|
857
|
+
const now = /* @__PURE__ */ new Date();
|
|
858
|
+
db.run(
|
|
859
|
+
`UPDATE sessions
|
|
860
|
+
SET status = 'failed', completed_at = ?, completed_at_epoch = ?
|
|
861
|
+
WHERE id = ?`,
|
|
862
|
+
[now.toISOString(), now.getTime(), id]
|
|
863
|
+
);
|
|
864
|
+
}
|
|
865
|
+
function getActiveSessions(db) {
|
|
866
|
+
const query = db.query("SELECT * FROM sessions WHERE status = 'active' ORDER BY started_at_epoch DESC");
|
|
867
|
+
return query.all();
|
|
868
|
+
}
|
|
869
|
+
function getSessionsByProject(db, project, limit = 100) {
|
|
870
|
+
const query = db.query("SELECT * FROM sessions WHERE project = ? ORDER BY started_at_epoch DESC LIMIT ?");
|
|
871
|
+
return query.all(project, limit);
|
|
872
|
+
}
|
|
873
|
+
var init_Sessions = __esm({
|
|
874
|
+
"src/services/sqlite/Sessions.ts"() {
|
|
875
|
+
"use strict";
|
|
876
|
+
}
|
|
877
|
+
});
|
|
878
|
+
|
|
879
|
+
// src/services/sqlite/Observations.ts
|
|
880
|
+
var Observations_exports = {};
|
|
881
|
+
__export(Observations_exports, {
|
|
882
|
+
createObservation: () => createObservation,
|
|
883
|
+
deleteObservation: () => deleteObservation,
|
|
884
|
+
getObservationsByProject: () => getObservationsByProject,
|
|
885
|
+
getObservationsBySession: () => getObservationsBySession,
|
|
886
|
+
searchObservations: () => searchObservations
|
|
887
|
+
});
|
|
888
|
+
function createObservation(db, memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber) {
|
|
889
|
+
const now = /* @__PURE__ */ new Date();
|
|
890
|
+
const result = db.run(
|
|
891
|
+
`INSERT INTO observations
|
|
892
|
+
(memory_session_id, project, type, title, subtitle, text, narrative, facts, concepts, files_read, files_modified, prompt_number, created_at, created_at_epoch)
|
|
893
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
894
|
+
[memorySessionId, project, type, title, subtitle, text, narrative, facts, concepts, filesRead, filesModified, promptNumber, now.toISOString(), now.getTime()]
|
|
895
|
+
);
|
|
896
|
+
return Number(result.lastInsertRowid);
|
|
897
|
+
}
|
|
898
|
+
function getObservationsBySession(db, memorySessionId) {
|
|
899
|
+
const query = db.query(
|
|
900
|
+
"SELECT * FROM observations WHERE memory_session_id = ? ORDER BY prompt_number ASC"
|
|
901
|
+
);
|
|
902
|
+
return query.all(memorySessionId);
|
|
903
|
+
}
|
|
904
|
+
function getObservationsByProject(db, project, limit = 100) {
|
|
905
|
+
const query = db.query(
|
|
906
|
+
"SELECT * FROM observations WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
|
|
907
|
+
);
|
|
908
|
+
return query.all(project, limit);
|
|
909
|
+
}
|
|
910
|
+
function searchObservations(db, searchTerm, project) {
|
|
911
|
+
const sql = project ? `SELECT * FROM observations
|
|
912
|
+
WHERE project = ? AND (title LIKE ? OR text LIKE ? OR narrative LIKE ?)
|
|
913
|
+
ORDER BY created_at_epoch DESC` : `SELECT * FROM observations
|
|
914
|
+
WHERE title LIKE ? OR text LIKE ? OR narrative LIKE ?
|
|
915
|
+
ORDER BY created_at_epoch DESC`;
|
|
916
|
+
const pattern = `%${searchTerm}%`;
|
|
917
|
+
const query = db.query(sql);
|
|
918
|
+
if (project) {
|
|
919
|
+
return query.all(project, pattern, pattern, pattern);
|
|
920
|
+
}
|
|
921
|
+
return query.all(pattern, pattern, pattern);
|
|
922
|
+
}
|
|
923
|
+
function deleteObservation(db, id) {
|
|
924
|
+
db.run("DELETE FROM observations WHERE id = ?", [id]);
|
|
925
|
+
}
|
|
926
|
+
var init_Observations = __esm({
|
|
927
|
+
"src/services/sqlite/Observations.ts"() {
|
|
928
|
+
"use strict";
|
|
929
|
+
}
|
|
930
|
+
});
|
|
931
|
+
|
|
932
|
+
// src/services/sqlite/Summaries.ts
|
|
933
|
+
var Summaries_exports = {};
|
|
934
|
+
__export(Summaries_exports, {
|
|
935
|
+
createSummary: () => createSummary,
|
|
936
|
+
deleteSummary: () => deleteSummary,
|
|
937
|
+
getSummariesByProject: () => getSummariesByProject,
|
|
938
|
+
getSummaryBySession: () => getSummaryBySession,
|
|
939
|
+
searchSummaries: () => searchSummaries
|
|
940
|
+
});
|
|
941
|
+
function createSummary(db, sessionId, project, request, investigated, learned, completed, nextSteps, notes) {
|
|
942
|
+
const now = /* @__PURE__ */ new Date();
|
|
943
|
+
const result = db.run(
|
|
944
|
+
`INSERT INTO summaries
|
|
945
|
+
(session_id, project, request, investigated, learned, completed, next_steps, notes, created_at, created_at_epoch)
|
|
946
|
+
VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
|
|
947
|
+
[sessionId, project, request, investigated, learned, completed, nextSteps, notes, now.toISOString(), now.getTime()]
|
|
948
|
+
);
|
|
949
|
+
return Number(result.lastInsertRowid);
|
|
950
|
+
}
|
|
951
|
+
function getSummaryBySession(db, sessionId) {
|
|
952
|
+
const query = db.query("SELECT * FROM summaries WHERE session_id = ? ORDER BY created_at_epoch DESC LIMIT 1");
|
|
953
|
+
return query.get(sessionId);
|
|
954
|
+
}
|
|
955
|
+
function getSummariesByProject(db, project, limit = 50) {
|
|
956
|
+
const query = db.query(
|
|
957
|
+
"SELECT * FROM summaries WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
|
|
958
|
+
);
|
|
959
|
+
return query.all(project, limit);
|
|
960
|
+
}
|
|
961
|
+
function searchSummaries(db, searchTerm, project) {
|
|
962
|
+
const sql = project ? `SELECT * FROM summaries
|
|
963
|
+
WHERE project = ? AND (request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ?)
|
|
964
|
+
ORDER BY created_at_epoch DESC` : `SELECT * FROM summaries
|
|
965
|
+
WHERE request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ?
|
|
966
|
+
ORDER BY created_at_epoch DESC`;
|
|
967
|
+
const pattern = `%${searchTerm}%`;
|
|
968
|
+
const query = db.query(sql);
|
|
969
|
+
if (project) {
|
|
970
|
+
return query.all(project, pattern, pattern, pattern, pattern);
|
|
971
|
+
}
|
|
972
|
+
return query.all(pattern, pattern, pattern, pattern);
|
|
973
|
+
}
|
|
974
|
+
function deleteSummary(db, id) {
|
|
975
|
+
db.run("DELETE FROM summaries WHERE id = ?", [id]);
|
|
976
|
+
}
|
|
977
|
+
var init_Summaries = __esm({
|
|
978
|
+
"src/services/sqlite/Summaries.ts"() {
|
|
979
|
+
"use strict";
|
|
980
|
+
}
|
|
981
|
+
});
|
|
982
|
+
|
|
983
|
+
// src/services/sqlite/Prompts.ts
|
|
984
|
+
var Prompts_exports = {};
|
|
985
|
+
__export(Prompts_exports, {
|
|
986
|
+
createPrompt: () => createPrompt,
|
|
987
|
+
deletePrompt: () => deletePrompt,
|
|
988
|
+
getLatestPrompt: () => getLatestPrompt,
|
|
989
|
+
getPromptsByProject: () => getPromptsByProject,
|
|
990
|
+
getPromptsBySession: () => getPromptsBySession
|
|
991
|
+
});
|
|
992
|
+
function createPrompt(db, contentSessionId, project, promptNumber, promptText) {
|
|
993
|
+
const now = /* @__PURE__ */ new Date();
|
|
994
|
+
const result = db.run(
|
|
995
|
+
`INSERT INTO prompts
|
|
996
|
+
(content_session_id, project, prompt_number, prompt_text, created_at, created_at_epoch)
|
|
997
|
+
VALUES (?, ?, ?, ?, ?, ?)`,
|
|
998
|
+
[contentSessionId, project, promptNumber, promptText, now.toISOString(), now.getTime()]
|
|
999
|
+
);
|
|
1000
|
+
return Number(result.lastInsertRowid);
|
|
1001
|
+
}
|
|
1002
|
+
function getPromptsBySession(db, contentSessionId) {
|
|
1003
|
+
const query = db.query(
|
|
1004
|
+
"SELECT * FROM prompts WHERE content_session_id = ? ORDER BY prompt_number ASC"
|
|
1005
|
+
);
|
|
1006
|
+
return query.all(contentSessionId);
|
|
1007
|
+
}
|
|
1008
|
+
function getPromptsByProject(db, project, limit = 100) {
|
|
1009
|
+
const query = db.query(
|
|
1010
|
+
"SELECT * FROM prompts WHERE project = ? ORDER BY created_at_epoch DESC LIMIT ?"
|
|
1011
|
+
);
|
|
1012
|
+
return query.all(project, limit);
|
|
1013
|
+
}
|
|
1014
|
+
function getLatestPrompt(db, contentSessionId) {
|
|
1015
|
+
const query = db.query(
|
|
1016
|
+
"SELECT * FROM prompts WHERE content_session_id = ? ORDER BY prompt_number DESC LIMIT 1"
|
|
1017
|
+
);
|
|
1018
|
+
return query.get(contentSessionId);
|
|
1019
|
+
}
|
|
1020
|
+
function deletePrompt(db, id) {
|
|
1021
|
+
db.run("DELETE FROM prompts WHERE id = ?", [id]);
|
|
1022
|
+
}
|
|
1023
|
+
var init_Prompts = __esm({
|
|
1024
|
+
"src/services/sqlite/Prompts.ts"() {
|
|
1025
|
+
"use strict";
|
|
1026
|
+
}
|
|
1027
|
+
});
|
|
1028
|
+
|
|
1029
|
+
// src/services/sqlite/Search.ts
|
|
1030
|
+
var Search_exports = {};
|
|
1031
|
+
__export(Search_exports, {
|
|
1032
|
+
getObservationsByIds: () => getObservationsByIds,
|
|
1033
|
+
getProjectStats: () => getProjectStats,
|
|
1034
|
+
getTimeline: () => getTimeline,
|
|
1035
|
+
searchObservationsFTS: () => searchObservationsFTS,
|
|
1036
|
+
searchObservationsLIKE: () => searchObservationsLIKE,
|
|
1037
|
+
searchSummariesFiltered: () => searchSummariesFiltered
|
|
1038
|
+
});
|
|
1039
|
+
function searchObservationsFTS(db, query, filters = {}) {
|
|
1040
|
+
const limit = filters.limit || 50;
|
|
1041
|
+
try {
|
|
1042
|
+
let sql = `
|
|
1043
|
+
SELECT o.* FROM observations o
|
|
1044
|
+
JOIN observations_fts fts ON o.id = fts.rowid
|
|
1045
|
+
WHERE observations_fts MATCH ?
|
|
1046
|
+
`;
|
|
1047
|
+
const params = [query];
|
|
1048
|
+
if (filters.project) {
|
|
1049
|
+
sql += " AND o.project = ?";
|
|
1050
|
+
params.push(filters.project);
|
|
1051
|
+
}
|
|
1052
|
+
if (filters.type) {
|
|
1053
|
+
sql += " AND o.type = ?";
|
|
1054
|
+
params.push(filters.type);
|
|
1055
|
+
}
|
|
1056
|
+
if (filters.dateStart) {
|
|
1057
|
+
sql += " AND o.created_at_epoch >= ?";
|
|
1058
|
+
params.push(filters.dateStart);
|
|
1059
|
+
}
|
|
1060
|
+
if (filters.dateEnd) {
|
|
1061
|
+
sql += " AND o.created_at_epoch <= ?";
|
|
1062
|
+
params.push(filters.dateEnd);
|
|
1063
|
+
}
|
|
1064
|
+
sql += " ORDER BY rank LIMIT ?";
|
|
1065
|
+
params.push(limit);
|
|
1066
|
+
const stmt = db.query(sql);
|
|
1067
|
+
return stmt.all(...params);
|
|
1068
|
+
} catch {
|
|
1069
|
+
return searchObservationsLIKE(db, query, filters);
|
|
1070
|
+
}
|
|
1071
|
+
}
|
|
1072
|
+
function searchObservationsLIKE(db, query, filters = {}) {
|
|
1073
|
+
const limit = filters.limit || 50;
|
|
1074
|
+
const pattern = `%${query}%`;
|
|
1075
|
+
let sql = `
|
|
1076
|
+
SELECT * FROM observations
|
|
1077
|
+
WHERE (title LIKE ? OR text LIKE ? OR narrative LIKE ? OR concepts LIKE ?)
|
|
1078
|
+
`;
|
|
1079
|
+
const params = [pattern, pattern, pattern, pattern];
|
|
1080
|
+
if (filters.project) {
|
|
1081
|
+
sql += " AND project = ?";
|
|
1082
|
+
params.push(filters.project);
|
|
1083
|
+
}
|
|
1084
|
+
if (filters.type) {
|
|
1085
|
+
sql += " AND type = ?";
|
|
1086
|
+
params.push(filters.type);
|
|
1087
|
+
}
|
|
1088
|
+
if (filters.dateStart) {
|
|
1089
|
+
sql += " AND created_at_epoch >= ?";
|
|
1090
|
+
params.push(filters.dateStart);
|
|
1091
|
+
}
|
|
1092
|
+
if (filters.dateEnd) {
|
|
1093
|
+
sql += " AND created_at_epoch <= ?";
|
|
1094
|
+
params.push(filters.dateEnd);
|
|
1095
|
+
}
|
|
1096
|
+
sql += " ORDER BY created_at_epoch DESC LIMIT ?";
|
|
1097
|
+
params.push(limit);
|
|
1098
|
+
const stmt = db.query(sql);
|
|
1099
|
+
return stmt.all(...params);
|
|
1100
|
+
}
|
|
1101
|
+
function searchSummariesFiltered(db, query, filters = {}) {
|
|
1102
|
+
const limit = filters.limit || 20;
|
|
1103
|
+
const pattern = `%${query}%`;
|
|
1104
|
+
let sql = `
|
|
1105
|
+
SELECT * FROM summaries
|
|
1106
|
+
WHERE (request LIKE ? OR learned LIKE ? OR completed LIKE ? OR notes LIKE ? OR next_steps LIKE ?)
|
|
1107
|
+
`;
|
|
1108
|
+
const params = [pattern, pattern, pattern, pattern, pattern];
|
|
1109
|
+
if (filters.project) {
|
|
1110
|
+
sql += " AND project = ?";
|
|
1111
|
+
params.push(filters.project);
|
|
1112
|
+
}
|
|
1113
|
+
if (filters.dateStart) {
|
|
1114
|
+
sql += " AND created_at_epoch >= ?";
|
|
1115
|
+
params.push(filters.dateStart);
|
|
1116
|
+
}
|
|
1117
|
+
if (filters.dateEnd) {
|
|
1118
|
+
sql += " AND created_at_epoch <= ?";
|
|
1119
|
+
params.push(filters.dateEnd);
|
|
1120
|
+
}
|
|
1121
|
+
sql += " ORDER BY created_at_epoch DESC LIMIT ?";
|
|
1122
|
+
params.push(limit);
|
|
1123
|
+
const stmt = db.query(sql);
|
|
1124
|
+
return stmt.all(...params);
|
|
1125
|
+
}
|
|
1126
|
+
function getObservationsByIds(db, ids) {
|
|
1127
|
+
if (ids.length === 0) return [];
|
|
1128
|
+
const placeholders = ids.map(() => "?").join(",");
|
|
1129
|
+
const sql = `SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`;
|
|
1130
|
+
const stmt = db.query(sql);
|
|
1131
|
+
return stmt.all(...ids);
|
|
1132
|
+
}
|
|
1133
|
+
function getTimeline(db, anchorId, depthBefore = 5, depthAfter = 5) {
|
|
1134
|
+
const anchorStmt = db.query("SELECT created_at_epoch FROM observations WHERE id = ?");
|
|
1135
|
+
const anchor = anchorStmt.get(anchorId);
|
|
1136
|
+
if (!anchor) return [];
|
|
1137
|
+
const anchorEpoch = anchor.created_at_epoch;
|
|
1138
|
+
const beforeStmt = db.query(`
|
|
1139
|
+
SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
|
|
1140
|
+
FROM observations
|
|
1141
|
+
WHERE created_at_epoch < ?
|
|
1142
|
+
ORDER BY created_at_epoch DESC
|
|
1143
|
+
LIMIT ?
|
|
1144
|
+
`);
|
|
1145
|
+
const before = beforeStmt.all(anchorEpoch, depthBefore).reverse();
|
|
1146
|
+
const selfStmt = db.query(`
|
|
1147
|
+
SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
|
|
1148
|
+
FROM observations WHERE id = ?
|
|
1149
|
+
`);
|
|
1150
|
+
const self = selfStmt.all(anchorId);
|
|
1151
|
+
const afterStmt = db.query(`
|
|
1152
|
+
SELECT id, 'observation' as type, title, text as content, project, created_at, created_at_epoch
|
|
1153
|
+
FROM observations
|
|
1154
|
+
WHERE created_at_epoch > ?
|
|
1155
|
+
ORDER BY created_at_epoch ASC
|
|
1156
|
+
LIMIT ?
|
|
1157
|
+
`);
|
|
1158
|
+
const after = afterStmt.all(anchorEpoch, depthAfter);
|
|
1159
|
+
return [...before, ...self, ...after];
|
|
1160
|
+
}
|
|
1161
|
+
function getProjectStats(db, project) {
|
|
1162
|
+
const obsStmt = db.query("SELECT COUNT(*) as count FROM observations WHERE project = ?");
|
|
1163
|
+
const sumStmt = db.query("SELECT COUNT(*) as count FROM summaries WHERE project = ?");
|
|
1164
|
+
const sesStmt = db.query("SELECT COUNT(*) as count FROM sessions WHERE project = ?");
|
|
1165
|
+
const prmStmt = db.query("SELECT COUNT(*) as count FROM prompts WHERE project = ?");
|
|
1166
|
+
return {
|
|
1167
|
+
observations: obsStmt.get(project)?.count || 0,
|
|
1168
|
+
summaries: sumStmt.get(project)?.count || 0,
|
|
1169
|
+
sessions: sesStmt.get(project)?.count || 0,
|
|
1170
|
+
prompts: prmStmt.get(project)?.count || 0
|
|
1171
|
+
};
|
|
1172
|
+
}
|
|
1173
|
+
var init_Search = __esm({
|
|
1174
|
+
"src/services/sqlite/Search.ts"() {
|
|
1175
|
+
"use strict";
|
|
1176
|
+
}
|
|
1177
|
+
});
|
|
1178
|
+
|
|
1179
|
+
// src/shims/bun-sqlite.ts
|
|
1180
|
+
var import_better_sqlite3 = __toESM(require_lib());
|
|
1181
|
+
var Database = class {
|
|
1182
|
+
_db;
|
|
1183
|
+
constructor(path, options) {
|
|
1184
|
+
this._db = new import_better_sqlite3.default(path, {
|
|
1185
|
+
// better-sqlite3 crea il file di default (non serve 'create')
|
|
1186
|
+
readonly: options?.readwrite === false ? true : false
|
|
1187
|
+
});
|
|
1188
|
+
}
|
|
1189
|
+
/**
|
|
1190
|
+
* Esegui una query SQL senza risultati
|
|
1191
|
+
*/
|
|
1192
|
+
run(sql, params) {
|
|
1193
|
+
const stmt = this._db.prepare(sql);
|
|
1194
|
+
const result = params ? stmt.run(...params) : stmt.run();
|
|
1195
|
+
return result;
|
|
1196
|
+
}
|
|
1197
|
+
/**
|
|
1198
|
+
* Prepara una query con interfaccia compatibile bun:sqlite
|
|
1199
|
+
*/
|
|
1200
|
+
query(sql) {
|
|
1201
|
+
return new BunQueryCompat(this._db, sql);
|
|
1202
|
+
}
|
|
1203
|
+
/**
|
|
1204
|
+
* Crea una transazione
|
|
1205
|
+
*/
|
|
1206
|
+
transaction(fn) {
|
|
1207
|
+
return this._db.transaction(fn);
|
|
1208
|
+
}
|
|
1209
|
+
/**
|
|
1210
|
+
* Chiudi la connessione
|
|
1211
|
+
*/
|
|
1212
|
+
close() {
|
|
1213
|
+
this._db.close();
|
|
1214
|
+
}
|
|
1215
|
+
};
|
|
1216
|
+
var BunQueryCompat = class {
|
|
1217
|
+
_db;
|
|
1218
|
+
_sql;
|
|
1219
|
+
constructor(db, sql) {
|
|
1220
|
+
this._db = db;
|
|
1221
|
+
this._sql = sql;
|
|
1222
|
+
}
|
|
1223
|
+
/**
|
|
1224
|
+
* Restituisce tutte le righe
|
|
1225
|
+
*/
|
|
1226
|
+
all(...params) {
|
|
1227
|
+
const stmt = this._db.prepare(this._sql);
|
|
1228
|
+
return params.length > 0 ? stmt.all(...params) : stmt.all();
|
|
1229
|
+
}
|
|
1230
|
+
/**
|
|
1231
|
+
* Restituisce la prima riga o null
|
|
1232
|
+
*/
|
|
1233
|
+
get(...params) {
|
|
1234
|
+
const stmt = this._db.prepare(this._sql);
|
|
1235
|
+
return params.length > 0 ? stmt.get(...params) : stmt.get();
|
|
1236
|
+
}
|
|
1237
|
+
/**
|
|
1238
|
+
* Esegui senza risultati
|
|
1239
|
+
*/
|
|
1240
|
+
run(...params) {
|
|
1241
|
+
const stmt = this._db.prepare(this._sql);
|
|
1242
|
+
return params.length > 0 ? stmt.run(...params) : stmt.run();
|
|
1243
|
+
}
|
|
1244
|
+
};
|
|
1245
|
+
|
|
1246
|
+
// src/shared/paths.ts
|
|
1247
|
+
import { join as join2, dirname, basename } from "path";
|
|
1248
|
+
import { homedir as homedir2 } from "os";
|
|
1249
|
+
import { mkdirSync as mkdirSync2 } from "fs";
|
|
1250
|
+
import { fileURLToPath } from "url";
|
|
1251
|
+
|
|
1252
|
+
// src/utils/logger.ts
|
|
1253
|
+
import { appendFileSync, existsSync, mkdirSync, readFileSync } from "fs";
|
|
1254
|
+
import { join } from "path";
|
|
1255
|
+
import { homedir } from "os";
|
|
1256
|
+
var LogLevel = /* @__PURE__ */ ((LogLevel2) => {
|
|
1257
|
+
LogLevel2[LogLevel2["DEBUG"] = 0] = "DEBUG";
|
|
1258
|
+
LogLevel2[LogLevel2["INFO"] = 1] = "INFO";
|
|
1259
|
+
LogLevel2[LogLevel2["WARN"] = 2] = "WARN";
|
|
1260
|
+
LogLevel2[LogLevel2["ERROR"] = 3] = "ERROR";
|
|
1261
|
+
LogLevel2[LogLevel2["SILENT"] = 4] = "SILENT";
|
|
1262
|
+
return LogLevel2;
|
|
1263
|
+
})(LogLevel || {});
|
|
1264
|
+
var DEFAULT_DATA_DIR = join(homedir(), ".contextkit");
|
|
1265
|
+
var Logger = class {
|
|
1266
|
+
level = null;
|
|
1267
|
+
useColor;
|
|
1268
|
+
logFilePath = null;
|
|
1269
|
+
logFileInitialized = false;
|
|
1270
|
+
constructor() {
|
|
1271
|
+
this.useColor = process.stdout.isTTY ?? false;
|
|
1272
|
+
}
|
|
1273
|
+
/**
|
|
1274
|
+
* Initialize log file path and ensure directory exists (lazy initialization)
|
|
1275
|
+
*/
|
|
1276
|
+
ensureLogFileInitialized() {
|
|
1277
|
+
if (this.logFileInitialized) return;
|
|
1278
|
+
this.logFileInitialized = true;
|
|
1279
|
+
try {
|
|
1280
|
+
const logsDir = join(DEFAULT_DATA_DIR, "logs");
|
|
1281
|
+
if (!existsSync(logsDir)) {
|
|
1282
|
+
mkdirSync(logsDir, { recursive: true });
|
|
1283
|
+
}
|
|
1284
|
+
const date = (/* @__PURE__ */ new Date()).toISOString().split("T")[0];
|
|
1285
|
+
this.logFilePath = join(logsDir, `contextkit-${date}.log`);
|
|
1286
|
+
} catch (error) {
|
|
1287
|
+
console.error("[LOGGER] Failed to initialize log file:", error);
|
|
1288
|
+
this.logFilePath = null;
|
|
1289
|
+
}
|
|
1290
|
+
}
|
|
1291
|
+
/**
|
|
1292
|
+
* Lazy-load log level from settings file
|
|
1293
|
+
*/
|
|
1294
|
+
getLevel() {
|
|
1295
|
+
if (this.level === null) {
|
|
1296
|
+
try {
|
|
1297
|
+
const settingsPath = join(DEFAULT_DATA_DIR, "settings.json");
|
|
1298
|
+
if (existsSync(settingsPath)) {
|
|
1299
|
+
const settingsData = readFileSync(settingsPath, "utf-8");
|
|
1300
|
+
const settings = JSON.parse(settingsData);
|
|
1301
|
+
const envLevel = (settings.CONTEXTKIT_LOG_LEVEL || "INFO").toUpperCase();
|
|
1302
|
+
this.level = LogLevel[envLevel] ?? 1 /* INFO */;
|
|
1303
|
+
} else {
|
|
1304
|
+
this.level = 1 /* INFO */;
|
|
1305
|
+
}
|
|
1306
|
+
} catch (error) {
|
|
1307
|
+
this.level = 1 /* INFO */;
|
|
1308
|
+
}
|
|
1309
|
+
}
|
|
1310
|
+
return this.level;
|
|
1311
|
+
}
|
|
1312
|
+
/**
|
|
1313
|
+
* Create correlation ID for tracking an observation through the pipeline
|
|
1314
|
+
*/
|
|
1315
|
+
correlationId(sessionId, observationNum) {
|
|
1316
|
+
return `obs-${sessionId}-${observationNum}`;
|
|
1317
|
+
}
|
|
1318
|
+
/**
|
|
1319
|
+
* Create session correlation ID
|
|
1320
|
+
*/
|
|
1321
|
+
sessionId(sessionId) {
|
|
1322
|
+
return `session-${sessionId}`;
|
|
1323
|
+
}
|
|
1324
|
+
/**
|
|
1325
|
+
* Format data for logging - create compact summaries instead of full dumps
|
|
1326
|
+
*/
|
|
1327
|
+
formatData(data) {
|
|
1328
|
+
if (data === null || data === void 0) return "";
|
|
1329
|
+
if (typeof data === "string") return data;
|
|
1330
|
+
if (typeof data === "number") return data.toString();
|
|
1331
|
+
if (typeof data === "boolean") return data.toString();
|
|
1332
|
+
if (typeof data === "object") {
|
|
1333
|
+
if (data instanceof Error) {
|
|
1334
|
+
return this.getLevel() === 0 /* DEBUG */ ? `${data.message}
|
|
1335
|
+
${data.stack}` : data.message;
|
|
1336
|
+
}
|
|
1337
|
+
if (Array.isArray(data)) {
|
|
1338
|
+
return `[${data.length} items]`;
|
|
1339
|
+
}
|
|
1340
|
+
const keys = Object.keys(data);
|
|
1341
|
+
if (keys.length === 0) return "{}";
|
|
1342
|
+
if (keys.length <= 3) {
|
|
1343
|
+
return JSON.stringify(data);
|
|
1344
|
+
}
|
|
1345
|
+
return `{${keys.length} keys: ${keys.slice(0, 3).join(", ")}...}`;
|
|
1346
|
+
}
|
|
1347
|
+
return String(data);
|
|
1348
|
+
}
|
|
1349
|
+
/**
|
|
1350
|
+
* Format timestamp in local timezone (YYYY-MM-DD HH:MM:SS.mmm)
|
|
1351
|
+
*/
|
|
1352
|
+
formatTimestamp(date) {
|
|
1353
|
+
const year = date.getFullYear();
|
|
1354
|
+
const month = String(date.getMonth() + 1).padStart(2, "0");
|
|
1355
|
+
const day = String(date.getDate()).padStart(2, "0");
|
|
1356
|
+
const hours = String(date.getHours()).padStart(2, "0");
|
|
1357
|
+
const minutes = String(date.getMinutes()).padStart(2, "0");
|
|
1358
|
+
const seconds = String(date.getSeconds()).padStart(2, "0");
|
|
1359
|
+
const ms = String(date.getMilliseconds()).padStart(3, "0");
|
|
1360
|
+
return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}.${ms}`;
|
|
1361
|
+
}
|
|
1362
|
+
/**
|
|
1363
|
+
* Core logging method
|
|
1364
|
+
*/
|
|
1365
|
+
log(level, component, message, context, data) {
|
|
1366
|
+
if (level < this.getLevel()) return;
|
|
1367
|
+
this.ensureLogFileInitialized();
|
|
1368
|
+
const timestamp = this.formatTimestamp(/* @__PURE__ */ new Date());
|
|
1369
|
+
const levelStr = LogLevel[level].padEnd(5);
|
|
1370
|
+
const componentStr = component.padEnd(6);
|
|
1371
|
+
let correlationStr = "";
|
|
1372
|
+
if (context?.correlationId) {
|
|
1373
|
+
correlationStr = `[${context.correlationId}] `;
|
|
1374
|
+
} else if (context?.sessionId) {
|
|
1375
|
+
correlationStr = `[session-${context.sessionId}] `;
|
|
1376
|
+
}
|
|
1377
|
+
let dataStr = "";
|
|
1378
|
+
if (data !== void 0 && data !== null) {
|
|
1379
|
+
if (data instanceof Error) {
|
|
1380
|
+
dataStr = this.getLevel() === 0 /* DEBUG */ ? `
|
|
1381
|
+
${data.message}
|
|
1382
|
+
${data.stack}` : ` ${data.message}`;
|
|
1383
|
+
} else if (this.getLevel() === 0 /* DEBUG */ && typeof data === "object") {
|
|
1384
|
+
dataStr = "\n" + JSON.stringify(data, null, 2);
|
|
1385
|
+
} else {
|
|
1386
|
+
dataStr = " " + this.formatData(data);
|
|
1387
|
+
}
|
|
1388
|
+
}
|
|
1389
|
+
let contextStr = "";
|
|
1390
|
+
if (context) {
|
|
1391
|
+
const { sessionId, memorySessionId, correlationId, ...rest } = context;
|
|
1392
|
+
if (Object.keys(rest).length > 0) {
|
|
1393
|
+
const pairs = Object.entries(rest).map(([k, v]) => `${k}=${v}`);
|
|
1394
|
+
contextStr = ` {${pairs.join(", ")}}`;
|
|
1395
|
+
}
|
|
1396
|
+
}
|
|
1397
|
+
const logLine = `[${timestamp}] [${levelStr}] [${componentStr}] ${correlationStr}${message}${contextStr}${dataStr}`;
|
|
1398
|
+
if (this.logFilePath) {
|
|
1399
|
+
try {
|
|
1400
|
+
appendFileSync(this.logFilePath, logLine + "\n", "utf8");
|
|
1401
|
+
} catch (error) {
|
|
1402
|
+
process.stderr.write(`[LOGGER] Failed to write to log file: ${error}
|
|
1403
|
+
`);
|
|
1404
|
+
}
|
|
1405
|
+
} else {
|
|
1406
|
+
process.stderr.write(logLine + "\n");
|
|
1407
|
+
}
|
|
1408
|
+
}
|
|
1409
|
+
// Public logging methods
|
|
1410
|
+
debug(component, message, context, data) {
|
|
1411
|
+
this.log(0 /* DEBUG */, component, message, context, data);
|
|
1412
|
+
}
|
|
1413
|
+
info(component, message, context, data) {
|
|
1414
|
+
this.log(1 /* INFO */, component, message, context, data);
|
|
1415
|
+
}
|
|
1416
|
+
warn(component, message, context, data) {
|
|
1417
|
+
this.log(2 /* WARN */, component, message, context, data);
|
|
1418
|
+
}
|
|
1419
|
+
error(component, message, context, data) {
|
|
1420
|
+
this.log(3 /* ERROR */, component, message, context, data);
|
|
1421
|
+
}
|
|
1422
|
+
/**
|
|
1423
|
+
* Log data flow: input → processing
|
|
1424
|
+
*/
|
|
1425
|
+
dataIn(component, message, context, data) {
|
|
1426
|
+
this.info(component, `\u2192 ${message}`, context, data);
|
|
1427
|
+
}
|
|
1428
|
+
/**
|
|
1429
|
+
* Log data flow: processing → output
|
|
1430
|
+
*/
|
|
1431
|
+
dataOut(component, message, context, data) {
|
|
1432
|
+
this.info(component, `\u2190 ${message}`, context, data);
|
|
1433
|
+
}
|
|
1434
|
+
/**
|
|
1435
|
+
* Log successful completion
|
|
1436
|
+
*/
|
|
1437
|
+
success(component, message, context, data) {
|
|
1438
|
+
this.info(component, `\u2713 ${message}`, context, data);
|
|
1439
|
+
}
|
|
1440
|
+
/**
|
|
1441
|
+
* Log failure
|
|
1442
|
+
*/
|
|
1443
|
+
failure(component, message, context, data) {
|
|
1444
|
+
this.error(component, `\u2717 ${message}`, context, data);
|
|
1445
|
+
}
|
|
1446
|
+
/**
|
|
1447
|
+
* Log timing information
|
|
1448
|
+
*/
|
|
1449
|
+
timing(component, message, durationMs, context) {
|
|
1450
|
+
this.info(component, `\u23F1 ${message}`, context, { duration: `${durationMs}ms` });
|
|
1451
|
+
}
|
|
1452
|
+
/**
|
|
1453
|
+
* Happy Path Error - logs when the expected "happy path" fails but we have a fallback
|
|
1454
|
+
*/
|
|
1455
|
+
happyPathError(component, message, context, data, fallback = "") {
|
|
1456
|
+
const stack = new Error().stack || "";
|
|
1457
|
+
const stackLines = stack.split("\n");
|
|
1458
|
+
const callerLine = stackLines[2] || "";
|
|
1459
|
+
const callerMatch = callerLine.match(/at\s+(?:.*\s+)?\(?([^:]+):(\d+):(\d+)\)?/);
|
|
1460
|
+
const location = callerMatch ? `${callerMatch[1].split("/").pop()}:${callerMatch[2]}` : "unknown";
|
|
1461
|
+
const enhancedContext = {
|
|
1462
|
+
...context,
|
|
1463
|
+
location
|
|
1464
|
+
};
|
|
1465
|
+
this.warn(component, `[HAPPY-PATH] ${message}`, enhancedContext, data);
|
|
1466
|
+
return fallback;
|
|
1467
|
+
}
|
|
1468
|
+
};
|
|
1469
|
+
var logger = new Logger();
|
|
1470
|
+
|
|
1471
|
+
// src/shared/paths.ts
|
|
1472
|
+
function getDirname() {
|
|
1473
|
+
if (typeof __dirname !== "undefined") {
|
|
1474
|
+
return __dirname;
|
|
1475
|
+
}
|
|
1476
|
+
return dirname(fileURLToPath(import.meta.url));
|
|
1477
|
+
}
|
|
1478
|
+
var _dirname = getDirname();
|
|
1479
|
+
var DATA_DIR = process.env.CONTEXTKIT_DATA_DIR || join2(homedir2(), ".contextkit");
|
|
1480
|
+
var KIRO_CONFIG_DIR = process.env.KIRO_CONFIG_DIR || join2(homedir2(), ".kiro");
|
|
1481
|
+
var PLUGIN_ROOT = join2(KIRO_CONFIG_DIR, "plugins", "contextkit");
|
|
1482
|
+
var ARCHIVES_DIR = join2(DATA_DIR, "archives");
|
|
1483
|
+
var LOGS_DIR = join2(DATA_DIR, "logs");
|
|
1484
|
+
var TRASH_DIR = join2(DATA_DIR, "trash");
|
|
1485
|
+
var BACKUPS_DIR = join2(DATA_DIR, "backups");
|
|
1486
|
+
var MODES_DIR = join2(DATA_DIR, "modes");
|
|
1487
|
+
var USER_SETTINGS_PATH = join2(DATA_DIR, "settings.json");
|
|
1488
|
+
var DB_PATH = join2(DATA_DIR, "contextkit.db");
|
|
1489
|
+
var VECTOR_DB_DIR = join2(DATA_DIR, "vector-db");
|
|
1490
|
+
var OBSERVER_SESSIONS_DIR = join2(DATA_DIR, "observer-sessions");
|
|
1491
|
+
var KIRO_SETTINGS_PATH = join2(KIRO_CONFIG_DIR, "settings.json");
|
|
1492
|
+
var KIRO_CONTEXT_PATH = join2(KIRO_CONFIG_DIR, "context.md");
|
|
1493
|
+
function ensureDir(dirPath) {
|
|
1494
|
+
mkdirSync2(dirPath, { recursive: true });
|
|
1495
|
+
}
|
|
1496
|
+
|
|
1497
|
+
// src/services/sqlite/Database.ts
|
|
1498
|
+
var SQLITE_MMAP_SIZE_BYTES = 256 * 1024 * 1024;
|
|
1499
|
+
var SQLITE_CACHE_SIZE_PAGES = 1e4;
|
|
1500
|
+
var dbInstance = null;
|
|
1501
|
+
var ContextKitDatabase = class {
|
|
1502
|
+
db;
|
|
1503
|
+
constructor(dbPath = DB_PATH) {
|
|
1504
|
+
if (dbPath !== ":memory:") {
|
|
1505
|
+
ensureDir(DATA_DIR);
|
|
1506
|
+
}
|
|
1507
|
+
this.db = new Database(dbPath, { create: true, readwrite: true });
|
|
1508
|
+
this.db.run("PRAGMA journal_mode = WAL");
|
|
1509
|
+
this.db.run("PRAGMA synchronous = NORMAL");
|
|
1510
|
+
this.db.run("PRAGMA foreign_keys = ON");
|
|
1511
|
+
this.db.run("PRAGMA temp_store = memory");
|
|
1512
|
+
this.db.run(`PRAGMA mmap_size = ${SQLITE_MMAP_SIZE_BYTES}`);
|
|
1513
|
+
this.db.run(`PRAGMA cache_size = ${SQLITE_CACHE_SIZE_PAGES}`);
|
|
1514
|
+
const migrationRunner = new MigrationRunner(this.db);
|
|
1515
|
+
migrationRunner.runAllMigrations();
|
|
1516
|
+
}
|
|
1517
|
+
/**
|
|
1518
|
+
* Close the database connection
|
|
1519
|
+
*/
|
|
1520
|
+
close() {
|
|
1521
|
+
this.db.close();
|
|
1522
|
+
}
|
|
1523
|
+
};
|
|
1524
|
+
var DatabaseManager = class _DatabaseManager {
|
|
1525
|
+
static instance;
|
|
1526
|
+
db = null;
|
|
1527
|
+
migrations = [];
|
|
1528
|
+
static getInstance() {
|
|
1529
|
+
if (!_DatabaseManager.instance) {
|
|
1530
|
+
_DatabaseManager.instance = new _DatabaseManager();
|
|
1531
|
+
}
|
|
1532
|
+
return _DatabaseManager.instance;
|
|
1533
|
+
}
|
|
1534
|
+
/**
|
|
1535
|
+
* Register a migration to be run during initialization
|
|
1536
|
+
*/
|
|
1537
|
+
registerMigration(migration) {
|
|
1538
|
+
this.migrations.push(migration);
|
|
1539
|
+
this.migrations.sort((a, b) => a.version - b.version);
|
|
1540
|
+
}
|
|
1541
|
+
/**
|
|
1542
|
+
* Initialize database connection with optimized settings
|
|
1543
|
+
*/
|
|
1544
|
+
async initialize() {
|
|
1545
|
+
if (this.db) {
|
|
1546
|
+
return this.db;
|
|
1547
|
+
}
|
|
1548
|
+
ensureDir(DATA_DIR);
|
|
1549
|
+
this.db = new Database(DB_PATH, { create: true, readwrite: true });
|
|
1550
|
+
this.db.run("PRAGMA journal_mode = WAL");
|
|
1551
|
+
this.db.run("PRAGMA synchronous = NORMAL");
|
|
1552
|
+
this.db.run("PRAGMA foreign_keys = ON");
|
|
1553
|
+
this.db.run("PRAGMA temp_store = memory");
|
|
1554
|
+
this.db.run(`PRAGMA mmap_size = ${SQLITE_MMAP_SIZE_BYTES}`);
|
|
1555
|
+
this.db.run(`PRAGMA cache_size = ${SQLITE_CACHE_SIZE_PAGES}`);
|
|
1556
|
+
this.initializeSchemaVersions();
|
|
1557
|
+
await this.runMigrations();
|
|
1558
|
+
dbInstance = this.db;
|
|
1559
|
+
return this.db;
|
|
1560
|
+
}
|
|
1561
|
+
/**
|
|
1562
|
+
* Get the current database connection
|
|
1563
|
+
*/
|
|
1564
|
+
getConnection() {
|
|
1565
|
+
if (!this.db) {
|
|
1566
|
+
throw new Error("Database not initialized. Call initialize() first.");
|
|
1567
|
+
}
|
|
1568
|
+
return this.db;
|
|
1569
|
+
}
|
|
1570
|
+
/**
|
|
1571
|
+
* Execute a function within a transaction
|
|
1572
|
+
*/
|
|
1573
|
+
withTransaction(fn) {
|
|
1574
|
+
const db = this.getConnection();
|
|
1575
|
+
const transaction = db.transaction(fn);
|
|
1576
|
+
return transaction(db);
|
|
1577
|
+
}
|
|
1578
|
+
/**
|
|
1579
|
+
* Close the database connection
|
|
1580
|
+
*/
|
|
1581
|
+
close() {
|
|
1582
|
+
if (this.db) {
|
|
1583
|
+
this.db.close();
|
|
1584
|
+
this.db = null;
|
|
1585
|
+
dbInstance = null;
|
|
1586
|
+
}
|
|
1587
|
+
}
|
|
1588
|
+
/**
|
|
1589
|
+
* Initialize the schema_versions table
|
|
1590
|
+
*/
|
|
1591
|
+
initializeSchemaVersions() {
|
|
1592
|
+
if (!this.db) return;
|
|
1593
|
+
this.db.run(`
|
|
1594
|
+
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
1595
|
+
id INTEGER PRIMARY KEY,
|
|
1596
|
+
version INTEGER UNIQUE NOT NULL,
|
|
1597
|
+
applied_at TEXT NOT NULL
|
|
1598
|
+
)
|
|
1599
|
+
`);
|
|
1600
|
+
}
|
|
1601
|
+
/**
|
|
1602
|
+
* Run all pending migrations
|
|
1603
|
+
*/
|
|
1604
|
+
async runMigrations() {
|
|
1605
|
+
if (!this.db) return;
|
|
1606
|
+
const query = this.db.query("SELECT version FROM schema_versions ORDER BY version");
|
|
1607
|
+
const appliedVersions = query.all().map((row) => row.version);
|
|
1608
|
+
const maxApplied = appliedVersions.length > 0 ? Math.max(...appliedVersions) : 0;
|
|
1609
|
+
for (const migration of this.migrations) {
|
|
1610
|
+
if (migration.version > maxApplied) {
|
|
1611
|
+
logger.info("DB", `Applying migration ${migration.version}`);
|
|
1612
|
+
const transaction = this.db.transaction(() => {
|
|
1613
|
+
migration.up(this.db);
|
|
1614
|
+
const insertQuery = this.db.query("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)");
|
|
1615
|
+
insertQuery.run(migration.version, (/* @__PURE__ */ new Date()).toISOString());
|
|
1616
|
+
});
|
|
1617
|
+
transaction();
|
|
1618
|
+
logger.info("DB", `Migration ${migration.version} applied successfully`);
|
|
1619
|
+
}
|
|
1620
|
+
}
|
|
1621
|
+
}
|
|
1622
|
+
/**
|
|
1623
|
+
* Get current schema version
|
|
1624
|
+
*/
|
|
1625
|
+
getCurrentVersion() {
|
|
1626
|
+
if (!this.db) return 0;
|
|
1627
|
+
const query = this.db.query("SELECT MAX(version) as version FROM schema_versions");
|
|
1628
|
+
const result = query.get();
|
|
1629
|
+
return result?.version || 0;
|
|
1630
|
+
}
|
|
1631
|
+
};
|
|
1632
|
+
var MigrationRunner = class {
|
|
1633
|
+
db;
|
|
1634
|
+
constructor(db) {
|
|
1635
|
+
this.db = db;
|
|
1636
|
+
}
|
|
1637
|
+
runAllMigrations() {
|
|
1638
|
+
this.db.run(`
|
|
1639
|
+
CREATE TABLE IF NOT EXISTS schema_versions (
|
|
1640
|
+
id INTEGER PRIMARY KEY,
|
|
1641
|
+
version INTEGER UNIQUE NOT NULL,
|
|
1642
|
+
applied_at TEXT NOT NULL
|
|
1643
|
+
)
|
|
1644
|
+
`);
|
|
1645
|
+
const versionQuery = this.db.query("SELECT MAX(version) as version FROM schema_versions");
|
|
1646
|
+
const result = versionQuery.get();
|
|
1647
|
+
const currentVersion = result?.version || 0;
|
|
1648
|
+
const migrations = this.getMigrations();
|
|
1649
|
+
for (const migration of migrations) {
|
|
1650
|
+
if (migration.version > currentVersion) {
|
|
1651
|
+
logger.info("DB", `Applying migration ${migration.version}`);
|
|
1652
|
+
const transaction = this.db.transaction(() => {
|
|
1653
|
+
migration.up(this.db);
|
|
1654
|
+
const insert = this.db.query("INSERT INTO schema_versions (version, applied_at) VALUES (?, ?)");
|
|
1655
|
+
insert.run(migration.version, (/* @__PURE__ */ new Date()).toISOString());
|
|
1656
|
+
});
|
|
1657
|
+
transaction();
|
|
1658
|
+
logger.info("DB", `Migration ${migration.version} applied successfully`);
|
|
1659
|
+
}
|
|
1660
|
+
}
|
|
1661
|
+
}
|
|
1662
|
+
getMigrations() {
|
|
1663
|
+
return [
|
|
1664
|
+
{
|
|
1665
|
+
version: 1,
|
|
1666
|
+
up: (db) => {
|
|
1667
|
+
db.run(`
|
|
1668
|
+
CREATE TABLE IF NOT EXISTS sessions (
|
|
1669
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1670
|
+
content_session_id TEXT NOT NULL UNIQUE,
|
|
1671
|
+
project TEXT NOT NULL,
|
|
1672
|
+
user_prompt TEXT NOT NULL,
|
|
1673
|
+
memory_session_id TEXT,
|
|
1674
|
+
status TEXT DEFAULT 'active',
|
|
1675
|
+
started_at TEXT NOT NULL,
|
|
1676
|
+
started_at_epoch INTEGER NOT NULL,
|
|
1677
|
+
completed_at TEXT,
|
|
1678
|
+
completed_at_epoch INTEGER
|
|
1679
|
+
)
|
|
1680
|
+
`);
|
|
1681
|
+
db.run(`
|
|
1682
|
+
CREATE TABLE IF NOT EXISTS observations (
|
|
1683
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1684
|
+
memory_session_id TEXT NOT NULL,
|
|
1685
|
+
project TEXT NOT NULL,
|
|
1686
|
+
type TEXT NOT NULL,
|
|
1687
|
+
title TEXT NOT NULL,
|
|
1688
|
+
subtitle TEXT,
|
|
1689
|
+
text TEXT,
|
|
1690
|
+
narrative TEXT,
|
|
1691
|
+
facts TEXT,
|
|
1692
|
+
concepts TEXT,
|
|
1693
|
+
files_read TEXT,
|
|
1694
|
+
files_modified TEXT,
|
|
1695
|
+
prompt_number INTEGER NOT NULL,
|
|
1696
|
+
created_at TEXT NOT NULL,
|
|
1697
|
+
created_at_epoch INTEGER NOT NULL
|
|
1698
|
+
)
|
|
1699
|
+
`);
|
|
1700
|
+
db.run(`
|
|
1701
|
+
CREATE TABLE IF NOT EXISTS summaries (
|
|
1702
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1703
|
+
session_id TEXT NOT NULL,
|
|
1704
|
+
project TEXT NOT NULL,
|
|
1705
|
+
request TEXT,
|
|
1706
|
+
investigated TEXT,
|
|
1707
|
+
learned TEXT,
|
|
1708
|
+
completed TEXT,
|
|
1709
|
+
next_steps TEXT,
|
|
1710
|
+
notes TEXT,
|
|
1711
|
+
created_at TEXT NOT NULL,
|
|
1712
|
+
created_at_epoch INTEGER NOT NULL
|
|
1713
|
+
)
|
|
1714
|
+
`);
|
|
1715
|
+
db.run(`
|
|
1716
|
+
CREATE TABLE IF NOT EXISTS prompts (
|
|
1717
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1718
|
+
content_session_id TEXT NOT NULL,
|
|
1719
|
+
project TEXT NOT NULL,
|
|
1720
|
+
prompt_number INTEGER NOT NULL,
|
|
1721
|
+
prompt_text TEXT NOT NULL,
|
|
1722
|
+
created_at TEXT NOT NULL,
|
|
1723
|
+
created_at_epoch INTEGER NOT NULL
|
|
1724
|
+
)
|
|
1725
|
+
`);
|
|
1726
|
+
db.run(`
|
|
1727
|
+
CREATE TABLE IF NOT EXISTS pending_messages (
|
|
1728
|
+
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
|
1729
|
+
content_session_id TEXT NOT NULL,
|
|
1730
|
+
type TEXT NOT NULL,
|
|
1731
|
+
data TEXT NOT NULL,
|
|
1732
|
+
created_at TEXT NOT NULL,
|
|
1733
|
+
created_at_epoch INTEGER NOT NULL
|
|
1734
|
+
)
|
|
1735
|
+
`);
|
|
1736
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_sessions_project ON sessions(project)");
|
|
1737
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_observations_project ON observations(project)");
|
|
1738
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_observations_session ON observations(memory_session_id)");
|
|
1739
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_summaries_session ON summaries(session_id)");
|
|
1740
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_prompts_session ON prompts(content_session_id)");
|
|
1741
|
+
}
|
|
1742
|
+
},
|
|
1743
|
+
{
|
|
1744
|
+
version: 2,
|
|
1745
|
+
up: (db) => {
|
|
1746
|
+
db.run(`
|
|
1747
|
+
CREATE VIRTUAL TABLE IF NOT EXISTS observations_fts USING fts5(
|
|
1748
|
+
title, text, narrative, concepts,
|
|
1749
|
+
content='observations',
|
|
1750
|
+
content_rowid='id'
|
|
1751
|
+
)
|
|
1752
|
+
`);
|
|
1753
|
+
db.run(`
|
|
1754
|
+
CREATE TRIGGER IF NOT EXISTS observations_ai AFTER INSERT ON observations BEGIN
|
|
1755
|
+
INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
|
|
1756
|
+
VALUES (new.id, new.title, new.text, new.narrative, new.concepts);
|
|
1757
|
+
END
|
|
1758
|
+
`);
|
|
1759
|
+
db.run(`
|
|
1760
|
+
CREATE TRIGGER IF NOT EXISTS observations_ad AFTER DELETE ON observations BEGIN
|
|
1761
|
+
INSERT INTO observations_fts(observations_fts, rowid, title, text, narrative, concepts)
|
|
1762
|
+
VALUES ('delete', old.id, old.title, old.text, old.narrative, old.concepts);
|
|
1763
|
+
END
|
|
1764
|
+
`);
|
|
1765
|
+
db.run(`
|
|
1766
|
+
CREATE TRIGGER IF NOT EXISTS observations_au AFTER UPDATE ON observations BEGIN
|
|
1767
|
+
INSERT INTO observations_fts(observations_fts, rowid, title, text, narrative, concepts)
|
|
1768
|
+
VALUES ('delete', old.id, old.title, old.text, old.narrative, old.concepts);
|
|
1769
|
+
INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
|
|
1770
|
+
VALUES (new.id, new.title, new.text, new.narrative, new.concepts);
|
|
1771
|
+
END
|
|
1772
|
+
`);
|
|
1773
|
+
db.run(`
|
|
1774
|
+
INSERT INTO observations_fts(rowid, title, text, narrative, concepts)
|
|
1775
|
+
SELECT id, title, text, narrative, concepts FROM observations
|
|
1776
|
+
`);
|
|
1777
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_observations_type ON observations(type)");
|
|
1778
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_observations_epoch ON observations(created_at_epoch)");
|
|
1779
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_summaries_project ON summaries(project)");
|
|
1780
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_summaries_epoch ON summaries(created_at_epoch)");
|
|
1781
|
+
db.run("CREATE INDEX IF NOT EXISTS idx_prompts_project ON prompts(project)");
|
|
1782
|
+
}
|
|
1783
|
+
}
|
|
1784
|
+
];
|
|
1785
|
+
}
|
|
1786
|
+
};
|
|
1787
|
+
function getDatabase() {
|
|
1788
|
+
if (!dbInstance) {
|
|
1789
|
+
throw new Error("Database not initialized. Call DatabaseManager.getInstance().initialize() first.");
|
|
1790
|
+
}
|
|
1791
|
+
return dbInstance;
|
|
1792
|
+
}
|
|
1793
|
+
async function initializeDatabase() {
|
|
1794
|
+
const manager = DatabaseManager.getInstance();
|
|
1795
|
+
return await manager.initialize();
|
|
1796
|
+
}
|
|
1797
|
+
|
|
1798
|
+
// src/services/sqlite/index.ts
|
|
1799
|
+
init_Sessions();
|
|
1800
|
+
init_Observations();
|
|
1801
|
+
init_Summaries();
|
|
1802
|
+
init_Prompts();
|
|
1803
|
+
init_Search();
|
|
1804
|
+
|
|
1805
|
+
// src/sdk/index.ts
|
|
1806
|
+
var ContextKitSDK = class {
|
|
1807
|
+
db;
|
|
1808
|
+
project;
|
|
1809
|
+
constructor(config = {}) {
|
|
1810
|
+
this.db = new ContextKitDatabase(config.dataDir);
|
|
1811
|
+
this.project = config.project || this.detectProject();
|
|
1812
|
+
}
|
|
1813
|
+
detectProject() {
|
|
1814
|
+
try {
|
|
1815
|
+
const { execSync } = __require("child_process");
|
|
1816
|
+
const gitRoot = execSync("git rev-parse --show-toplevel", {
|
|
1817
|
+
cwd: process.cwd(),
|
|
1818
|
+
encoding: "utf8",
|
|
1819
|
+
stdio: ["pipe", "pipe", "ignore"]
|
|
1820
|
+
}).trim();
|
|
1821
|
+
return gitRoot.split("/").pop() || "default";
|
|
1822
|
+
} catch {
|
|
1823
|
+
return "default";
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
/**
|
|
1827
|
+
* Get context for the current project
|
|
1828
|
+
*/
|
|
1829
|
+
async getContext() {
|
|
1830
|
+
const { getObservationsByProject: getObservationsByProject2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
|
|
1831
|
+
const { getSummariesByProject: getSummariesByProject2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
|
|
1832
|
+
const { getPromptsByProject: getPromptsByProject2 } = await Promise.resolve().then(() => (init_Prompts(), Prompts_exports));
|
|
1833
|
+
return {
|
|
1834
|
+
project: this.project,
|
|
1835
|
+
relevantObservations: getObservationsByProject2(this.db.db, this.project, 20),
|
|
1836
|
+
relevantSummaries: getSummariesByProject2(this.db.db, this.project, 5),
|
|
1837
|
+
recentPrompts: getPromptsByProject2(this.db.db, this.project, 10)
|
|
1838
|
+
};
|
|
1839
|
+
}
|
|
1840
|
+
/**
|
|
1841
|
+
* Store a new observation
|
|
1842
|
+
*/
|
|
1843
|
+
async storeObservation(data) {
|
|
1844
|
+
const { createObservation: createObservation2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
|
|
1845
|
+
return createObservation2(
|
|
1846
|
+
this.db.db,
|
|
1847
|
+
"sdk-" + Date.now(),
|
|
1848
|
+
this.project,
|
|
1849
|
+
data.type,
|
|
1850
|
+
data.title,
|
|
1851
|
+
null,
|
|
1852
|
+
// subtitle
|
|
1853
|
+
data.content,
|
|
1854
|
+
null,
|
|
1855
|
+
// narrative
|
|
1856
|
+
null,
|
|
1857
|
+
// facts
|
|
1858
|
+
data.concepts?.join(", ") || null,
|
|
1859
|
+
data.files?.join(", ") || null,
|
|
1860
|
+
// files_read
|
|
1861
|
+
data.files?.join(", ") || null,
|
|
1862
|
+
// files_modified
|
|
1863
|
+
0
|
|
1864
|
+
// prompt_number
|
|
1865
|
+
);
|
|
1866
|
+
}
|
|
1867
|
+
/**
|
|
1868
|
+
* Store a session summary
|
|
1869
|
+
*/
|
|
1870
|
+
async storeSummary(data) {
|
|
1871
|
+
const { createSummary: createSummary2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
|
|
1872
|
+
return createSummary2(
|
|
1873
|
+
this.db.db,
|
|
1874
|
+
"sdk-" + Date.now(),
|
|
1875
|
+
this.project,
|
|
1876
|
+
data.request || null,
|
|
1877
|
+
null,
|
|
1878
|
+
data.learned || null,
|
|
1879
|
+
data.completed || null,
|
|
1880
|
+
data.nextSteps || null,
|
|
1881
|
+
null
|
|
1882
|
+
);
|
|
1883
|
+
}
|
|
1884
|
+
/**
|
|
1885
|
+
* Search across all stored context
|
|
1886
|
+
*/
|
|
1887
|
+
async search(query) {
|
|
1888
|
+
const { searchObservations: searchObservations2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
|
|
1889
|
+
const { searchSummaries: searchSummaries2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
|
|
1890
|
+
return {
|
|
1891
|
+
observations: searchObservations2(this.db.db, query, this.project),
|
|
1892
|
+
summaries: searchSummaries2(this.db.db, query, this.project)
|
|
1893
|
+
};
|
|
1894
|
+
}
|
|
1895
|
+
/**
|
|
1896
|
+
* Get recent observations
|
|
1897
|
+
*/
|
|
1898
|
+
async getRecentObservations(limit = 10) {
|
|
1899
|
+
const { getObservationsByProject: getObservationsByProject2 } = await Promise.resolve().then(() => (init_Observations(), Observations_exports));
|
|
1900
|
+
return getObservationsByProject2(this.db.db, this.project, limit);
|
|
1901
|
+
}
|
|
1902
|
+
/**
|
|
1903
|
+
* Get recent summaries
|
|
1904
|
+
*/
|
|
1905
|
+
async getRecentSummaries(limit = 5) {
|
|
1906
|
+
const { getSummariesByProject: getSummariesByProject2 } = await Promise.resolve().then(() => (init_Summaries(), Summaries_exports));
|
|
1907
|
+
return getSummariesByProject2(this.db.db, this.project, limit);
|
|
1908
|
+
}
|
|
1909
|
+
/**
|
|
1910
|
+
* Ricerca avanzata con FTS5 e filtri
|
|
1911
|
+
*/
|
|
1912
|
+
async searchAdvanced(query, filters = {}) {
|
|
1913
|
+
const { searchObservationsFTS: searchObservationsFTS2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
|
|
1914
|
+
const { searchSummariesFiltered: searchSummariesFiltered2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
|
|
1915
|
+
const projectFilters = { ...filters, project: filters.project || this.project };
|
|
1916
|
+
return {
|
|
1917
|
+
observations: searchObservationsFTS2(this.db.db, query, projectFilters),
|
|
1918
|
+
summaries: searchSummariesFiltered2(this.db.db, query, projectFilters)
|
|
1919
|
+
};
|
|
1920
|
+
}
|
|
1921
|
+
/**
|
|
1922
|
+
* Recupera osservazioni per ID (batch)
|
|
1923
|
+
*/
|
|
1924
|
+
async getObservationsByIds(ids) {
|
|
1925
|
+
const { getObservationsByIds: getObservationsByIds2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
|
|
1926
|
+
return getObservationsByIds2(this.db.db, ids);
|
|
1927
|
+
}
|
|
1928
|
+
/**
|
|
1929
|
+
* Timeline: contesto cronologico attorno a un'osservazione
|
|
1930
|
+
*/
|
|
1931
|
+
async getTimeline(anchorId, depthBefore = 5, depthAfter = 5) {
|
|
1932
|
+
const { getTimeline: getTimeline2 } = await Promise.resolve().then(() => (init_Search(), Search_exports));
|
|
1933
|
+
return getTimeline2(this.db.db, anchorId, depthBefore, depthAfter);
|
|
1934
|
+
}
|
|
1935
|
+
/**
|
|
1936
|
+
* Crea o recupera una sessione per il progetto corrente
|
|
1937
|
+
*/
|
|
1938
|
+
async getOrCreateSession(contentSessionId) {
|
|
1939
|
+
const { getSessionByContentId: getSessionByContentId2, createSession: createSession2 } = await Promise.resolve().then(() => (init_Sessions(), Sessions_exports));
|
|
1940
|
+
let session = getSessionByContentId2(this.db.db, contentSessionId);
|
|
1941
|
+
if (!session) {
|
|
1942
|
+
const id = createSession2(this.db.db, contentSessionId, this.project, "");
|
|
1943
|
+
session = {
|
|
1944
|
+
id,
|
|
1945
|
+
content_session_id: contentSessionId,
|
|
1946
|
+
project: this.project,
|
|
1947
|
+
user_prompt: "",
|
|
1948
|
+
memory_session_id: null,
|
|
1949
|
+
status: "active",
|
|
1950
|
+
started_at: (/* @__PURE__ */ new Date()).toISOString(),
|
|
1951
|
+
started_at_epoch: Date.now(),
|
|
1952
|
+
completed_at: null,
|
|
1953
|
+
completed_at_epoch: null
|
|
1954
|
+
};
|
|
1955
|
+
}
|
|
1956
|
+
return session;
|
|
1957
|
+
}
|
|
1958
|
+
/**
|
|
1959
|
+
* Salva un prompt utente
|
|
1960
|
+
*/
|
|
1961
|
+
async storePrompt(contentSessionId, promptNumber, text) {
|
|
1962
|
+
const { createPrompt: createPrompt2 } = await Promise.resolve().then(() => (init_Prompts(), Prompts_exports));
|
|
1963
|
+
return createPrompt2(this.db.db, contentSessionId, this.project, promptNumber, text);
|
|
1964
|
+
}
|
|
1965
|
+
/**
|
|
1966
|
+
* Completa una sessione
|
|
1967
|
+
*/
|
|
1968
|
+
async completeSession(sessionId) {
|
|
1969
|
+
const { completeSession: completeSession2 } = await Promise.resolve().then(() => (init_Sessions(), Sessions_exports));
|
|
1970
|
+
completeSession2(this.db.db, sessionId);
|
|
1971
|
+
}
|
|
1972
|
+
/**
|
|
1973
|
+
* Getter per il nome progetto corrente
|
|
1974
|
+
*/
|
|
1975
|
+
getProject() {
|
|
1976
|
+
return this.project;
|
|
1977
|
+
}
|
|
1978
|
+
/**
|
|
1979
|
+
* Getter per accesso diretto al database (per route API)
|
|
1980
|
+
*/
|
|
1981
|
+
getDb() {
|
|
1982
|
+
return this.db.db;
|
|
1983
|
+
}
|
|
1984
|
+
/**
|
|
1985
|
+
* Close database connection
|
|
1986
|
+
*/
|
|
1987
|
+
close() {
|
|
1988
|
+
this.db.close();
|
|
1989
|
+
}
|
|
1990
|
+
};
|
|
1991
|
+
function createContextKit(config) {
|
|
1992
|
+
return new ContextKitSDK(config);
|
|
1993
|
+
}
|
|
1994
|
+
|
|
1995
|
+
// src/index.ts
|
|
1996
|
+
init_Search();
|
|
1997
|
+
|
|
1998
|
+
// src/hooks/utils.ts
|
|
1999
|
+
async function readStdin() {
|
|
2000
|
+
return new Promise((resolve, reject) => {
|
|
2001
|
+
let data = "";
|
|
2002
|
+
process.stdin.setEncoding("utf8");
|
|
2003
|
+
process.stdin.on("data", (chunk) => {
|
|
2004
|
+
data += chunk;
|
|
2005
|
+
});
|
|
2006
|
+
process.stdin.on("end", () => {
|
|
2007
|
+
try {
|
|
2008
|
+
if (!data.trim()) {
|
|
2009
|
+
resolve({
|
|
2010
|
+
hook_event_name: "agentSpawn",
|
|
2011
|
+
cwd: process.cwd()
|
|
2012
|
+
});
|
|
2013
|
+
return;
|
|
2014
|
+
}
|
|
2015
|
+
resolve(JSON.parse(data));
|
|
2016
|
+
} catch (err) {
|
|
2017
|
+
reject(new Error(`Errore parsing stdin JSON: ${err}`));
|
|
2018
|
+
}
|
|
2019
|
+
});
|
|
2020
|
+
process.stdin.on("error", reject);
|
|
2021
|
+
setTimeout(() => {
|
|
2022
|
+
if (!data.trim()) {
|
|
2023
|
+
resolve({
|
|
2024
|
+
hook_event_name: "agentSpawn",
|
|
2025
|
+
cwd: process.cwd()
|
|
2026
|
+
});
|
|
2027
|
+
}
|
|
2028
|
+
}, 5e3);
|
|
2029
|
+
});
|
|
2030
|
+
}
|
|
2031
|
+
function detectProject(cwd) {
|
|
2032
|
+
try {
|
|
2033
|
+
const { execSync } = __require("child_process");
|
|
2034
|
+
const gitRoot = execSync("git rev-parse --show-toplevel", {
|
|
2035
|
+
cwd,
|
|
2036
|
+
encoding: "utf8",
|
|
2037
|
+
stdio: ["pipe", "pipe", "ignore"]
|
|
2038
|
+
}).trim();
|
|
2039
|
+
return gitRoot.split("/").pop() || "default";
|
|
2040
|
+
} catch {
|
|
2041
|
+
return cwd.split("/").pop() || "default";
|
|
2042
|
+
}
|
|
2043
|
+
}
|
|
2044
|
+
function formatContext(data) {
|
|
2045
|
+
let output = "";
|
|
2046
|
+
if (data.summaries && data.summaries.length > 0) {
|
|
2047
|
+
output += "## Sessioni Precedenti\n\n";
|
|
2048
|
+
data.summaries.slice(0, 3).forEach((sum) => {
|
|
2049
|
+
if (sum.learned) output += `- **Appreso**: ${sum.learned}
|
|
2050
|
+
`;
|
|
2051
|
+
if (sum.completed) output += `- **Completato**: ${sum.completed}
|
|
2052
|
+
`;
|
|
2053
|
+
if (sum.next_steps) output += `- **Prossimi passi**: ${sum.next_steps}
|
|
2054
|
+
`;
|
|
2055
|
+
output += "\n";
|
|
2056
|
+
});
|
|
2057
|
+
}
|
|
2058
|
+
if (data.observations && data.observations.length > 0) {
|
|
2059
|
+
output += "## Osservazioni Recenti\n\n";
|
|
2060
|
+
data.observations.slice(0, 10).forEach((obs) => {
|
|
2061
|
+
const text = obs.text ? obs.text.substring(0, 150) : "";
|
|
2062
|
+
output += `- **[${obs.type || "obs"}] ${obs.title}**: ${text}
|
|
2063
|
+
`;
|
|
2064
|
+
});
|
|
2065
|
+
output += "\n";
|
|
2066
|
+
}
|
|
2067
|
+
return output;
|
|
2068
|
+
}
|
|
2069
|
+
async function runHook(name, handler) {
|
|
2070
|
+
try {
|
|
2071
|
+
const input = await readStdin();
|
|
2072
|
+
await handler(input);
|
|
2073
|
+
process.exit(0);
|
|
2074
|
+
} catch (error) {
|
|
2075
|
+
process.stderr.write(`[contextkit:${name}] Errore: ${error}
|
|
2076
|
+
`);
|
|
2077
|
+
process.exit(0);
|
|
2078
|
+
}
|
|
2079
|
+
}
|
|
2080
|
+
|
|
2081
|
+
// src/index.ts
|
|
2082
|
+
var VERSION = "1.0.0";
|
|
2083
|
+
export {
|
|
2084
|
+
ContextKitDatabase,
|
|
2085
|
+
ContextKitSDK,
|
|
2086
|
+
DatabaseManager,
|
|
2087
|
+
LogLevel,
|
|
2088
|
+
VERSION,
|
|
2089
|
+
createContextKit,
|
|
2090
|
+
detectProject,
|
|
2091
|
+
formatContext,
|
|
2092
|
+
getDatabase,
|
|
2093
|
+
getObservationsByIds,
|
|
2094
|
+
getProjectStats,
|
|
2095
|
+
getTimeline,
|
|
2096
|
+
initializeDatabase,
|
|
2097
|
+
logger,
|
|
2098
|
+
readStdin,
|
|
2099
|
+
runHook,
|
|
2100
|
+
searchObservationsFTS,
|
|
2101
|
+
searchObservationsLIKE,
|
|
2102
|
+
searchSummariesFiltered
|
|
2103
|
+
};
|