engrm 0.1.0 → 0.2.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.
Files changed (98) hide show
  1. package/README.md +214 -73
  2. package/bin/build.mjs +97 -0
  3. package/bin/engrm.mjs +13 -0
  4. package/dist/cli.js +2712 -0
  5. package/dist/hooks/elicitation-result.js +1786 -0
  6. package/dist/hooks/post-tool-use.js +2357 -0
  7. package/dist/hooks/pre-compact.js +1321 -0
  8. package/dist/hooks/sentinel.js +1168 -0
  9. package/dist/hooks/session-start.js +1473 -0
  10. package/dist/hooks/stop.js +1834 -0
  11. package/dist/server.js +16628 -0
  12. package/package.json +29 -4
  13. package/packs/api-best-practices.json +182 -0
  14. package/packs/nextjs-patterns.json +68 -0
  15. package/packs/node-security.json +68 -0
  16. package/packs/python-django.json +68 -0
  17. package/packs/react-gotchas.json +182 -0
  18. package/packs/typescript-patterns.json +67 -0
  19. package/packs/web-security.json +182 -0
  20. package/.mcp.json +0 -9
  21. package/AUTH-DESIGN.md +0 -436
  22. package/BRIEF.md +0 -197
  23. package/CLAUDE.md +0 -44
  24. package/COMPETITIVE.md +0 -174
  25. package/CONTEXT-OPTIMIZATION.md +0 -305
  26. package/INFRASTRUCTURE.md +0 -252
  27. package/MARKET.md +0 -230
  28. package/PLAN.md +0 -278
  29. package/SENTINEL.md +0 -293
  30. package/SERVER-API-PLAN.md +0 -553
  31. package/SPEC.md +0 -843
  32. package/SWOT.md +0 -148
  33. package/SYNC-ARCHITECTURE.md +0 -294
  34. package/VIBE-CODER-STRATEGY.md +0 -250
  35. package/bun.lock +0 -375
  36. package/hooks/post-tool-use.ts +0 -144
  37. package/hooks/session-start.ts +0 -64
  38. package/hooks/stop.ts +0 -131
  39. package/mem-page.html +0 -1305
  40. package/src/capture/dedup.test.ts +0 -103
  41. package/src/capture/dedup.ts +0 -76
  42. package/src/capture/extractor.test.ts +0 -245
  43. package/src/capture/extractor.ts +0 -330
  44. package/src/capture/quality.test.ts +0 -168
  45. package/src/capture/quality.ts +0 -104
  46. package/src/capture/retrospective.test.ts +0 -115
  47. package/src/capture/retrospective.ts +0 -121
  48. package/src/capture/scanner.test.ts +0 -131
  49. package/src/capture/scanner.ts +0 -100
  50. package/src/capture/scrubber.test.ts +0 -144
  51. package/src/capture/scrubber.ts +0 -181
  52. package/src/cli.ts +0 -517
  53. package/src/config.ts +0 -238
  54. package/src/context/inject.test.ts +0 -940
  55. package/src/context/inject.ts +0 -382
  56. package/src/embeddings/backfill.ts +0 -50
  57. package/src/embeddings/embedder.test.ts +0 -76
  58. package/src/embeddings/embedder.ts +0 -139
  59. package/src/lifecycle/aging.test.ts +0 -103
  60. package/src/lifecycle/aging.ts +0 -36
  61. package/src/lifecycle/compaction.test.ts +0 -264
  62. package/src/lifecycle/compaction.ts +0 -190
  63. package/src/lifecycle/purge.test.ts +0 -100
  64. package/src/lifecycle/purge.ts +0 -37
  65. package/src/lifecycle/scheduler.test.ts +0 -120
  66. package/src/lifecycle/scheduler.ts +0 -101
  67. package/src/provisioning/browser-auth.ts +0 -172
  68. package/src/provisioning/provision.test.ts +0 -198
  69. package/src/provisioning/provision.ts +0 -94
  70. package/src/register.test.ts +0 -167
  71. package/src/register.ts +0 -178
  72. package/src/server.ts +0 -436
  73. package/src/storage/migrations.test.ts +0 -244
  74. package/src/storage/migrations.ts +0 -261
  75. package/src/storage/outbox.test.ts +0 -229
  76. package/src/storage/outbox.ts +0 -131
  77. package/src/storage/projects.test.ts +0 -137
  78. package/src/storage/projects.ts +0 -184
  79. package/src/storage/sqlite.test.ts +0 -798
  80. package/src/storage/sqlite.ts +0 -934
  81. package/src/storage/vec.test.ts +0 -198
  82. package/src/sync/auth.test.ts +0 -76
  83. package/src/sync/auth.ts +0 -68
  84. package/src/sync/client.ts +0 -183
  85. package/src/sync/engine.test.ts +0 -94
  86. package/src/sync/engine.ts +0 -127
  87. package/src/sync/pull.test.ts +0 -279
  88. package/src/sync/pull.ts +0 -170
  89. package/src/sync/push.test.ts +0 -117
  90. package/src/sync/push.ts +0 -230
  91. package/src/tools/get.ts +0 -34
  92. package/src/tools/pin.ts +0 -47
  93. package/src/tools/save.test.ts +0 -301
  94. package/src/tools/save.ts +0 -231
  95. package/src/tools/search.test.ts +0 -69
  96. package/src/tools/search.ts +0 -181
  97. package/src/tools/timeline.ts +0 -64
  98. package/tsconfig.json +0 -22
@@ -0,0 +1,1473 @@
1
+ #!/usr/bin/env node
2
+ // @bun
3
+ import { createRequire } from "node:module";
4
+ var __require = /* @__PURE__ */ createRequire(import.meta.url);
5
+
6
+ // src/config.ts
7
+ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
8
+ import { homedir, hostname } from "node:os";
9
+ import { join } from "node:path";
10
+ import { randomBytes } from "node:crypto";
11
+ var CONFIG_DIR = join(homedir(), ".engrm");
12
+ var SETTINGS_PATH = join(CONFIG_DIR, "settings.json");
13
+ var DB_PATH = join(CONFIG_DIR, "engrm.db");
14
+ function getDbPath() {
15
+ return DB_PATH;
16
+ }
17
+ function generateDeviceId() {
18
+ const host = hostname().toLowerCase().replace(/[^a-z0-9-]/g, "");
19
+ const suffix = randomBytes(4).toString("hex");
20
+ return `${host}-${suffix}`;
21
+ }
22
+ function createDefaultConfig() {
23
+ return {
24
+ candengo_url: "",
25
+ candengo_api_key: "",
26
+ site_id: "",
27
+ namespace: "",
28
+ user_id: "",
29
+ user_email: "",
30
+ device_id: generateDeviceId(),
31
+ teams: [],
32
+ sync: {
33
+ enabled: true,
34
+ interval_seconds: 30,
35
+ batch_size: 50
36
+ },
37
+ search: {
38
+ default_limit: 10,
39
+ local_boost: 1.2,
40
+ scope: "all"
41
+ },
42
+ scrubbing: {
43
+ enabled: true,
44
+ custom_patterns: [],
45
+ default_sensitivity: "shared"
46
+ },
47
+ sentinel: {
48
+ enabled: false,
49
+ mode: "advisory",
50
+ provider: "openai",
51
+ model: "gpt-4o-mini",
52
+ api_key: "",
53
+ base_url: "",
54
+ skip_patterns: [],
55
+ daily_limit: 100,
56
+ tier: "free"
57
+ },
58
+ observer: {
59
+ enabled: true,
60
+ mode: "per_event",
61
+ model: "haiku"
62
+ }
63
+ };
64
+ }
65
+ function loadConfig() {
66
+ if (!existsSync(SETTINGS_PATH)) {
67
+ throw new Error(`Config not found at ${SETTINGS_PATH}. Run 'engrm init --manual' to configure.`);
68
+ }
69
+ const raw = readFileSync(SETTINGS_PATH, "utf-8");
70
+ let parsed;
71
+ try {
72
+ parsed = JSON.parse(raw);
73
+ } catch {
74
+ throw new Error(`Invalid JSON in ${SETTINGS_PATH}`);
75
+ }
76
+ if (typeof parsed !== "object" || parsed === null) {
77
+ throw new Error(`Config at ${SETTINGS_PATH} is not a JSON object`);
78
+ }
79
+ const config = parsed;
80
+ const defaults = createDefaultConfig();
81
+ return {
82
+ candengo_url: asString(config["candengo_url"], defaults.candengo_url),
83
+ candengo_api_key: asString(config["candengo_api_key"], defaults.candengo_api_key),
84
+ site_id: asString(config["site_id"], defaults.site_id),
85
+ namespace: asString(config["namespace"], defaults.namespace),
86
+ user_id: asString(config["user_id"], defaults.user_id),
87
+ user_email: asString(config["user_email"], defaults.user_email),
88
+ device_id: asString(config["device_id"], defaults.device_id),
89
+ teams: asTeams(config["teams"], defaults.teams),
90
+ sync: {
91
+ enabled: asBool(config["sync"]?.["enabled"], defaults.sync.enabled),
92
+ interval_seconds: asNumber(config["sync"]?.["interval_seconds"], defaults.sync.interval_seconds),
93
+ batch_size: asNumber(config["sync"]?.["batch_size"], defaults.sync.batch_size)
94
+ },
95
+ search: {
96
+ default_limit: asNumber(config["search"]?.["default_limit"], defaults.search.default_limit),
97
+ local_boost: asNumber(config["search"]?.["local_boost"], defaults.search.local_boost),
98
+ scope: asScope(config["search"]?.["scope"], defaults.search.scope)
99
+ },
100
+ scrubbing: {
101
+ enabled: asBool(config["scrubbing"]?.["enabled"], defaults.scrubbing.enabled),
102
+ custom_patterns: asStringArray(config["scrubbing"]?.["custom_patterns"], defaults.scrubbing.custom_patterns),
103
+ default_sensitivity: asSensitivity(config["scrubbing"]?.["default_sensitivity"], defaults.scrubbing.default_sensitivity)
104
+ },
105
+ sentinel: {
106
+ enabled: asBool(config["sentinel"]?.["enabled"], defaults.sentinel.enabled),
107
+ mode: asSentinelMode(config["sentinel"]?.["mode"], defaults.sentinel.mode),
108
+ provider: asLlmProvider(config["sentinel"]?.["provider"], defaults.sentinel.provider),
109
+ model: asString(config["sentinel"]?.["model"], defaults.sentinel.model),
110
+ api_key: asString(config["sentinel"]?.["api_key"], defaults.sentinel.api_key),
111
+ base_url: asString(config["sentinel"]?.["base_url"], defaults.sentinel.base_url),
112
+ skip_patterns: asStringArray(config["sentinel"]?.["skip_patterns"], defaults.sentinel.skip_patterns),
113
+ daily_limit: asNumber(config["sentinel"]?.["daily_limit"], defaults.sentinel.daily_limit),
114
+ tier: asTier(config["sentinel"]?.["tier"], defaults.sentinel.tier)
115
+ },
116
+ observer: {
117
+ enabled: asBool(config["observer"]?.["enabled"], defaults.observer.enabled),
118
+ mode: asObserverMode(config["observer"]?.["mode"], defaults.observer.mode),
119
+ model: asString(config["observer"]?.["model"], defaults.observer.model)
120
+ }
121
+ };
122
+ }
123
+ function configExists() {
124
+ return existsSync(SETTINGS_PATH);
125
+ }
126
+ function asString(value, fallback) {
127
+ return typeof value === "string" ? value : fallback;
128
+ }
129
+ function asNumber(value, fallback) {
130
+ return typeof value === "number" && !Number.isNaN(value) ? value : fallback;
131
+ }
132
+ function asBool(value, fallback) {
133
+ return typeof value === "boolean" ? value : fallback;
134
+ }
135
+ function asStringArray(value, fallback) {
136
+ return Array.isArray(value) && value.every((v) => typeof v === "string") ? value : fallback;
137
+ }
138
+ function asScope(value, fallback) {
139
+ if (value === "personal" || value === "team" || value === "all")
140
+ return value;
141
+ return fallback;
142
+ }
143
+ function asSensitivity(value, fallback) {
144
+ if (value === "shared" || value === "personal" || value === "secret")
145
+ return value;
146
+ return fallback;
147
+ }
148
+ function asSentinelMode(value, fallback) {
149
+ if (value === "advisory" || value === "blocking")
150
+ return value;
151
+ return fallback;
152
+ }
153
+ function asLlmProvider(value, fallback) {
154
+ if (value === "openai" || value === "anthropic" || value === "ollama" || value === "custom")
155
+ return value;
156
+ return fallback;
157
+ }
158
+ function asTier(value, fallback) {
159
+ if (value === "free" || value === "vibe" || value === "solo" || value === "pro" || value === "team" || value === "enterprise")
160
+ return value;
161
+ return fallback;
162
+ }
163
+ function asObserverMode(value, fallback) {
164
+ if (value === "per_event" || value === "per_session")
165
+ return value;
166
+ return fallback;
167
+ }
168
+ function asTeams(value, fallback) {
169
+ if (!Array.isArray(value))
170
+ return fallback;
171
+ return value.filter((t) => typeof t === "object" && t !== null && typeof t.id === "string" && typeof t.name === "string" && typeof t.namespace === "string");
172
+ }
173
+
174
+ // src/storage/migrations.ts
175
+ var MIGRATIONS = [
176
+ {
177
+ version: 1,
178
+ description: "Initial schema: projects, observations, sessions, sync, FTS5",
179
+ sql: `
180
+ -- Projects (canonical identity across machines)
181
+ CREATE TABLE projects (
182
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
183
+ canonical_id TEXT UNIQUE NOT NULL,
184
+ name TEXT NOT NULL,
185
+ local_path TEXT,
186
+ remote_url TEXT,
187
+ first_seen_epoch INTEGER NOT NULL,
188
+ last_active_epoch INTEGER NOT NULL
189
+ );
190
+
191
+ -- Core observations table
192
+ CREATE TABLE observations (
193
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
194
+ session_id TEXT,
195
+ project_id INTEGER NOT NULL REFERENCES projects(id),
196
+ type TEXT NOT NULL CHECK (type IN (
197
+ 'bugfix', 'discovery', 'decision', 'pattern',
198
+ 'change', 'feature', 'refactor', 'digest'
199
+ )),
200
+ title TEXT NOT NULL,
201
+ narrative TEXT,
202
+ facts TEXT,
203
+ concepts TEXT,
204
+ files_read TEXT,
205
+ files_modified TEXT,
206
+ quality REAL DEFAULT 0.5 CHECK (quality BETWEEN 0.0 AND 1.0),
207
+ lifecycle TEXT DEFAULT 'active' CHECK (lifecycle IN (
208
+ 'active', 'aging', 'archived', 'purged', 'pinned'
209
+ )),
210
+ sensitivity TEXT DEFAULT 'shared' CHECK (sensitivity IN (
211
+ 'shared', 'personal', 'secret'
212
+ )),
213
+ user_id TEXT NOT NULL,
214
+ device_id TEXT NOT NULL,
215
+ agent TEXT DEFAULT 'claude-code',
216
+ created_at TEXT NOT NULL,
217
+ created_at_epoch INTEGER NOT NULL,
218
+ archived_at_epoch INTEGER,
219
+ compacted_into INTEGER REFERENCES observations(id) ON DELETE SET NULL
220
+ );
221
+
222
+ -- Session tracking
223
+ CREATE TABLE sessions (
224
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
225
+ session_id TEXT UNIQUE NOT NULL,
226
+ project_id INTEGER REFERENCES projects(id),
227
+ user_id TEXT NOT NULL,
228
+ device_id TEXT NOT NULL,
229
+ agent TEXT DEFAULT 'claude-code',
230
+ status TEXT DEFAULT 'active' CHECK (status IN ('active', 'completed')),
231
+ observation_count INTEGER DEFAULT 0,
232
+ started_at_epoch INTEGER,
233
+ completed_at_epoch INTEGER
234
+ );
235
+
236
+ -- Session summaries (generated on Stop hook)
237
+ CREATE TABLE session_summaries (
238
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
239
+ session_id TEXT UNIQUE NOT NULL,
240
+ project_id INTEGER REFERENCES projects(id),
241
+ user_id TEXT NOT NULL,
242
+ request TEXT,
243
+ investigated TEXT,
244
+ learned TEXT,
245
+ completed TEXT,
246
+ next_steps TEXT,
247
+ created_at_epoch INTEGER
248
+ );
249
+
250
+ -- Sync outbox (offline-first queue)
251
+ CREATE TABLE sync_outbox (
252
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
253
+ record_type TEXT NOT NULL CHECK (record_type IN ('observation', 'summary')),
254
+ record_id INTEGER NOT NULL,
255
+ status TEXT DEFAULT 'pending' CHECK (status IN (
256
+ 'pending', 'syncing', 'synced', 'failed'
257
+ )),
258
+ retry_count INTEGER DEFAULT 0,
259
+ max_retries INTEGER DEFAULT 10,
260
+ last_error TEXT,
261
+ created_at_epoch INTEGER NOT NULL,
262
+ synced_at_epoch INTEGER,
263
+ next_retry_epoch INTEGER
264
+ );
265
+
266
+ -- Sync high-water mark and lifecycle job tracking
267
+ CREATE TABLE sync_state (
268
+ key TEXT PRIMARY KEY,
269
+ value TEXT NOT NULL
270
+ );
271
+
272
+ -- FTS5 for local offline search (external content mode)
273
+ CREATE VIRTUAL TABLE observations_fts USING fts5(
274
+ title, narrative, facts, concepts,
275
+ content=observations,
276
+ content_rowid=id
277
+ );
278
+
279
+ -- Indexes: observations
280
+ CREATE INDEX idx_observations_project ON observations(project_id);
281
+ CREATE INDEX idx_observations_project_lifecycle ON observations(project_id, lifecycle);
282
+ CREATE INDEX idx_observations_type ON observations(type);
283
+ CREATE INDEX idx_observations_created ON observations(created_at_epoch);
284
+ CREATE INDEX idx_observations_session ON observations(session_id);
285
+ CREATE INDEX idx_observations_lifecycle ON observations(lifecycle);
286
+ CREATE INDEX idx_observations_quality ON observations(quality);
287
+ CREATE INDEX idx_observations_user ON observations(user_id);
288
+
289
+ -- Indexes: sessions
290
+ CREATE INDEX idx_sessions_project ON sessions(project_id);
291
+
292
+ -- Indexes: sync outbox
293
+ CREATE INDEX idx_outbox_status ON sync_outbox(status, next_retry_epoch);
294
+ CREATE INDEX idx_outbox_record ON sync_outbox(record_type, record_id);
295
+ `
296
+ },
297
+ {
298
+ version: 2,
299
+ description: "Add superseded_by for knowledge supersession",
300
+ sql: `
301
+ ALTER TABLE observations ADD COLUMN superseded_by INTEGER REFERENCES observations(id) ON DELETE SET NULL;
302
+ CREATE INDEX idx_observations_superseded ON observations(superseded_by);
303
+ `
304
+ },
305
+ {
306
+ version: 3,
307
+ description: "Add remote_source_id for pull deduplication",
308
+ sql: `
309
+ ALTER TABLE observations ADD COLUMN remote_source_id TEXT;
310
+ CREATE UNIQUE INDEX idx_observations_remote_source ON observations(remote_source_id) WHERE remote_source_id IS NOT NULL;
311
+ `
312
+ },
313
+ {
314
+ version: 4,
315
+ description: "Add sqlite-vec for local semantic search",
316
+ sql: `
317
+ CREATE VIRTUAL TABLE vec_observations USING vec0(
318
+ observation_id INTEGER PRIMARY KEY,
319
+ embedding float[384]
320
+ );
321
+ `,
322
+ condition: (db) => isVecExtensionLoaded(db)
323
+ },
324
+ {
325
+ version: 5,
326
+ description: "Session metrics and security findings",
327
+ sql: `
328
+ ALTER TABLE sessions ADD COLUMN files_touched_count INTEGER DEFAULT 0;
329
+ ALTER TABLE sessions ADD COLUMN searches_performed INTEGER DEFAULT 0;
330
+ ALTER TABLE sessions ADD COLUMN tool_calls_count INTEGER DEFAULT 0;
331
+
332
+ CREATE TABLE security_findings (
333
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
334
+ session_id TEXT,
335
+ project_id INTEGER NOT NULL REFERENCES projects(id),
336
+ finding_type TEXT NOT NULL,
337
+ severity TEXT NOT NULL DEFAULT 'medium' CHECK (severity IN ('critical', 'high', 'medium', 'low')),
338
+ pattern_name TEXT NOT NULL,
339
+ file_path TEXT,
340
+ snippet TEXT,
341
+ tool_name TEXT,
342
+ user_id TEXT NOT NULL,
343
+ device_id TEXT NOT NULL,
344
+ created_at_epoch INTEGER NOT NULL
345
+ );
346
+
347
+ CREATE INDEX idx_security_findings_session ON security_findings(session_id);
348
+ CREATE INDEX idx_security_findings_project ON security_findings(project_id, created_at_epoch);
349
+ CREATE INDEX idx_security_findings_severity ON security_findings(severity);
350
+ `
351
+ },
352
+ {
353
+ version: 6,
354
+ description: "Add risk_score, expand observation types to include standard",
355
+ sql: `
356
+ ALTER TABLE sessions ADD COLUMN risk_score INTEGER;
357
+
358
+ -- Recreate observations table with expanded type CHECK to include 'standard'
359
+ -- SQLite doesn't support ALTER CHECK, so we recreate the table
360
+ CREATE TABLE observations_new (
361
+ id INTEGER PRIMARY KEY AUTOINCREMENT,
362
+ session_id TEXT,
363
+ project_id INTEGER NOT NULL REFERENCES projects(id),
364
+ type TEXT NOT NULL CHECK (type IN (
365
+ 'bugfix', 'discovery', 'decision', 'pattern',
366
+ 'change', 'feature', 'refactor', 'digest', 'standard'
367
+ )),
368
+ title TEXT NOT NULL,
369
+ narrative TEXT,
370
+ facts TEXT,
371
+ concepts TEXT,
372
+ files_read TEXT,
373
+ files_modified TEXT,
374
+ quality REAL DEFAULT 0.5 CHECK (quality BETWEEN 0.0 AND 1.0),
375
+ lifecycle TEXT DEFAULT 'active' CHECK (lifecycle IN (
376
+ 'active', 'aging', 'archived', 'purged', 'pinned'
377
+ )),
378
+ sensitivity TEXT DEFAULT 'shared' CHECK (sensitivity IN (
379
+ 'shared', 'personal', 'secret'
380
+ )),
381
+ user_id TEXT NOT NULL,
382
+ device_id TEXT NOT NULL,
383
+ agent TEXT DEFAULT 'claude-code',
384
+ created_at TEXT NOT NULL,
385
+ created_at_epoch INTEGER NOT NULL,
386
+ archived_at_epoch INTEGER,
387
+ compacted_into INTEGER REFERENCES observations(id) ON DELETE SET NULL,
388
+ superseded_by INTEGER REFERENCES observations(id) ON DELETE SET NULL,
389
+ remote_source_id TEXT
390
+ );
391
+
392
+ INSERT INTO observations_new SELECT * FROM observations;
393
+
394
+ DROP TABLE observations;
395
+ ALTER TABLE observations_new RENAME TO observations;
396
+
397
+ -- Recreate indexes
398
+ CREATE INDEX idx_observations_project ON observations(project_id);
399
+ CREATE INDEX idx_observations_project_lifecycle ON observations(project_id, lifecycle);
400
+ CREATE INDEX idx_observations_type ON observations(type);
401
+ CREATE INDEX idx_observations_created ON observations(created_at_epoch);
402
+ CREATE INDEX idx_observations_session ON observations(session_id);
403
+ CREATE INDEX idx_observations_lifecycle ON observations(lifecycle);
404
+ CREATE INDEX idx_observations_quality ON observations(quality);
405
+ CREATE INDEX idx_observations_user ON observations(user_id);
406
+ CREATE INDEX idx_observations_superseded ON observations(superseded_by);
407
+ CREATE UNIQUE INDEX idx_observations_remote_source ON observations(remote_source_id) WHERE remote_source_id IS NOT NULL;
408
+
409
+ -- Recreate FTS5 (external content mode — must rebuild after table recreation)
410
+ DROP TABLE IF EXISTS observations_fts;
411
+ CREATE VIRTUAL TABLE observations_fts USING fts5(
412
+ title, narrative, facts, concepts,
413
+ content=observations,
414
+ content_rowid=id
415
+ );
416
+ -- Rebuild FTS index
417
+ INSERT INTO observations_fts(observations_fts) VALUES('rebuild');
418
+ `
419
+ },
420
+ {
421
+ version: 7,
422
+ description: "Add packs_installed table for help pack tracking",
423
+ sql: `
424
+ CREATE TABLE IF NOT EXISTS packs_installed (
425
+ name TEXT PRIMARY KEY,
426
+ installed_at INTEGER NOT NULL,
427
+ observation_count INTEGER DEFAULT 0
428
+ );
429
+ `
430
+ }
431
+ ];
432
+ function isVecExtensionLoaded(db) {
433
+ try {
434
+ db.exec("SELECT vec_version()");
435
+ return true;
436
+ } catch {
437
+ return false;
438
+ }
439
+ }
440
+ function runMigrations(db) {
441
+ const currentVersion = db.query("PRAGMA user_version").get();
442
+ let version = currentVersion.user_version;
443
+ for (const migration of MIGRATIONS) {
444
+ if (migration.version <= version)
445
+ continue;
446
+ if (migration.condition && !migration.condition(db)) {
447
+ continue;
448
+ }
449
+ db.exec("BEGIN TRANSACTION");
450
+ try {
451
+ db.exec(migration.sql);
452
+ db.exec(`PRAGMA user_version = ${migration.version}`);
453
+ db.exec("COMMIT");
454
+ version = migration.version;
455
+ } catch (error) {
456
+ db.exec("ROLLBACK");
457
+ throw new Error(`Migration ${migration.version} (${migration.description}) failed: ${error instanceof Error ? error.message : String(error)}`);
458
+ }
459
+ }
460
+ }
461
+ var LATEST_SCHEMA_VERSION = MIGRATIONS.filter((m) => !m.condition).reduce((max, m) => Math.max(max, m.version), 0);
462
+
463
+ // src/storage/sqlite.ts
464
+ var IS_BUN = typeof globalThis.Bun !== "undefined";
465
+ function openDatabase(dbPath) {
466
+ if (IS_BUN) {
467
+ return openBunDatabase(dbPath);
468
+ }
469
+ return openNodeDatabase(dbPath);
470
+ }
471
+ function openBunDatabase(dbPath) {
472
+ const { Database } = __require("bun:sqlite");
473
+ if (process.platform === "darwin") {
474
+ const { existsSync: existsSync2 } = __require("node:fs");
475
+ const paths = [
476
+ "/opt/homebrew/opt/sqlite/lib/libsqlite3.dylib",
477
+ "/usr/local/opt/sqlite3/lib/libsqlite3.dylib"
478
+ ];
479
+ for (const p of paths) {
480
+ if (existsSync2(p)) {
481
+ try {
482
+ Database.setCustomSQLite(p);
483
+ } catch {}
484
+ break;
485
+ }
486
+ }
487
+ }
488
+ const db = new Database(dbPath);
489
+ return db;
490
+ }
491
+ function openNodeDatabase(dbPath) {
492
+ const BetterSqlite3 = __require("better-sqlite3");
493
+ const raw = new BetterSqlite3(dbPath);
494
+ return {
495
+ query(sql) {
496
+ const stmt = raw.prepare(sql);
497
+ return {
498
+ get(...params) {
499
+ return stmt.get(...params);
500
+ },
501
+ all(...params) {
502
+ return stmt.all(...params);
503
+ },
504
+ run(...params) {
505
+ return stmt.run(...params);
506
+ }
507
+ };
508
+ },
509
+ exec(sql) {
510
+ raw.exec(sql);
511
+ },
512
+ close() {
513
+ raw.close();
514
+ }
515
+ };
516
+ }
517
+
518
+ class MemDatabase {
519
+ db;
520
+ vecAvailable;
521
+ constructor(dbPath) {
522
+ this.db = openDatabase(dbPath);
523
+ this.db.exec("PRAGMA journal_mode = WAL");
524
+ this.db.exec("PRAGMA foreign_keys = ON");
525
+ this.vecAvailable = this.loadVecExtension();
526
+ runMigrations(this.db);
527
+ }
528
+ loadVecExtension() {
529
+ try {
530
+ const sqliteVec = __require("sqlite-vec");
531
+ sqliteVec.load(this.db);
532
+ return true;
533
+ } catch {
534
+ return false;
535
+ }
536
+ }
537
+ close() {
538
+ this.db.close();
539
+ }
540
+ upsertProject(project) {
541
+ const now = Math.floor(Date.now() / 1000);
542
+ const existing = this.db.query("SELECT * FROM projects WHERE canonical_id = ?").get(project.canonical_id);
543
+ if (existing) {
544
+ this.db.query(`UPDATE projects SET
545
+ local_path = COALESCE(?, local_path),
546
+ remote_url = COALESCE(?, remote_url),
547
+ last_active_epoch = ?
548
+ WHERE id = ?`).run(project.local_path ?? null, project.remote_url ?? null, now, existing.id);
549
+ return {
550
+ ...existing,
551
+ local_path: project.local_path ?? existing.local_path,
552
+ remote_url: project.remote_url ?? existing.remote_url,
553
+ last_active_epoch: now
554
+ };
555
+ }
556
+ const result = this.db.query(`INSERT INTO projects (canonical_id, name, local_path, remote_url, first_seen_epoch, last_active_epoch)
557
+ VALUES (?, ?, ?, ?, ?, ?)`).run(project.canonical_id, project.name, project.local_path ?? null, project.remote_url ?? null, now, now);
558
+ return this.db.query("SELECT * FROM projects WHERE id = ?").get(Number(result.lastInsertRowid));
559
+ }
560
+ getProjectByCanonicalId(canonicalId) {
561
+ return this.db.query("SELECT * FROM projects WHERE canonical_id = ?").get(canonicalId) ?? null;
562
+ }
563
+ getProjectById(id) {
564
+ return this.db.query("SELECT * FROM projects WHERE id = ?").get(id) ?? null;
565
+ }
566
+ insertObservation(obs) {
567
+ const now = Math.floor(Date.now() / 1000);
568
+ const createdAt = new Date().toISOString();
569
+ const result = this.db.query(`INSERT INTO observations (
570
+ session_id, project_id, type, title, narrative, facts, concepts,
571
+ files_read, files_modified, quality, lifecycle, sensitivity,
572
+ user_id, device_id, agent, created_at, created_at_epoch
573
+ ) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(obs.session_id ?? null, obs.project_id, obs.type, obs.title, obs.narrative ?? null, obs.facts ?? null, obs.concepts ?? null, obs.files_read ?? null, obs.files_modified ?? null, obs.quality, obs.lifecycle ?? "active", obs.sensitivity ?? "shared", obs.user_id, obs.device_id, obs.agent ?? "claude-code", createdAt, now);
574
+ const id = Number(result.lastInsertRowid);
575
+ const row = this.getObservationById(id);
576
+ this.ftsInsert(row);
577
+ if (obs.session_id) {
578
+ this.db.query("UPDATE sessions SET observation_count = observation_count + 1 WHERE session_id = ?").run(obs.session_id);
579
+ }
580
+ return row;
581
+ }
582
+ getObservationById(id) {
583
+ return this.db.query("SELECT * FROM observations WHERE id = ?").get(id) ?? null;
584
+ }
585
+ getObservationsByIds(ids) {
586
+ if (ids.length === 0)
587
+ return [];
588
+ const placeholders = ids.map(() => "?").join(",");
589
+ return this.db.query(`SELECT * FROM observations WHERE id IN (${placeholders}) ORDER BY created_at_epoch DESC`).all(...ids);
590
+ }
591
+ getRecentObservations(projectId, sincEpoch, limit = 50) {
592
+ return this.db.query(`SELECT * FROM observations
593
+ WHERE project_id = ? AND created_at_epoch > ?
594
+ ORDER BY created_at_epoch DESC
595
+ LIMIT ?`).all(projectId, sincEpoch, limit);
596
+ }
597
+ searchFts(query, projectId, lifecycles = ["active", "aging", "pinned"], limit = 20) {
598
+ const lifecyclePlaceholders = lifecycles.map(() => "?").join(",");
599
+ if (projectId !== null) {
600
+ return this.db.query(`SELECT o.id, observations_fts.rank
601
+ FROM observations_fts
602
+ JOIN observations o ON o.id = observations_fts.rowid
603
+ WHERE observations_fts MATCH ?
604
+ AND o.project_id = ?
605
+ AND o.lifecycle IN (${lifecyclePlaceholders})
606
+ ORDER BY observations_fts.rank
607
+ LIMIT ?`).all(query, projectId, ...lifecycles, limit);
608
+ }
609
+ return this.db.query(`SELECT o.id, observations_fts.rank
610
+ FROM observations_fts
611
+ JOIN observations o ON o.id = observations_fts.rowid
612
+ WHERE observations_fts MATCH ?
613
+ AND o.lifecycle IN (${lifecyclePlaceholders})
614
+ ORDER BY observations_fts.rank
615
+ LIMIT ?`).all(query, ...lifecycles, limit);
616
+ }
617
+ getTimeline(anchorId, projectId, depthBefore = 3, depthAfter = 3) {
618
+ const anchor = this.getObservationById(anchorId);
619
+ if (!anchor)
620
+ return [];
621
+ const projectFilter = projectId !== null ? "AND project_id = ?" : "";
622
+ const projectParams = projectId !== null ? [projectId] : [];
623
+ const before = this.db.query(`SELECT * FROM observations
624
+ WHERE created_at_epoch < ? ${projectFilter}
625
+ AND lifecycle IN ('active', 'aging', 'pinned')
626
+ ORDER BY created_at_epoch DESC
627
+ LIMIT ?`).all(anchor.created_at_epoch, ...projectParams, depthBefore);
628
+ const after = this.db.query(`SELECT * FROM observations
629
+ WHERE created_at_epoch > ? ${projectFilter}
630
+ AND lifecycle IN ('active', 'aging', 'pinned')
631
+ ORDER BY created_at_epoch ASC
632
+ LIMIT ?`).all(anchor.created_at_epoch, ...projectParams, depthAfter);
633
+ return [...before.reverse(), anchor, ...after];
634
+ }
635
+ pinObservation(id, pinned) {
636
+ const obs = this.getObservationById(id);
637
+ if (!obs)
638
+ return false;
639
+ if (pinned) {
640
+ if (obs.lifecycle !== "active" && obs.lifecycle !== "aging")
641
+ return false;
642
+ this.db.query("UPDATE observations SET lifecycle = 'pinned' WHERE id = ?").run(id);
643
+ } else {
644
+ if (obs.lifecycle !== "pinned")
645
+ return false;
646
+ this.db.query("UPDATE observations SET lifecycle = 'active' WHERE id = ?").run(id);
647
+ }
648
+ return true;
649
+ }
650
+ getActiveObservationCount(userId) {
651
+ if (userId) {
652
+ const result2 = this.db.query(`SELECT COUNT(*) as count FROM observations
653
+ WHERE lifecycle IN ('active', 'aging')
654
+ AND sensitivity != 'secret'
655
+ AND user_id = ?`).get(userId);
656
+ return result2?.count ?? 0;
657
+ }
658
+ const result = this.db.query(`SELECT COUNT(*) as count FROM observations
659
+ WHERE lifecycle IN ('active', 'aging')
660
+ AND sensitivity != 'secret'`).get();
661
+ return result?.count ?? 0;
662
+ }
663
+ supersedeObservation(oldId, newId) {
664
+ if (oldId === newId)
665
+ return false;
666
+ const replacement = this.getObservationById(newId);
667
+ if (!replacement)
668
+ return false;
669
+ let targetId = oldId;
670
+ const visited = new Set;
671
+ for (let depth = 0;depth < 10; depth++) {
672
+ const target2 = this.getObservationById(targetId);
673
+ if (!target2)
674
+ return false;
675
+ if (target2.superseded_by === null)
676
+ break;
677
+ if (target2.superseded_by === newId)
678
+ return true;
679
+ visited.add(targetId);
680
+ targetId = target2.superseded_by;
681
+ if (visited.has(targetId))
682
+ return false;
683
+ }
684
+ const target = this.getObservationById(targetId);
685
+ if (!target)
686
+ return false;
687
+ if (target.superseded_by !== null)
688
+ return false;
689
+ if (targetId === newId)
690
+ return false;
691
+ const now = Math.floor(Date.now() / 1000);
692
+ this.db.query(`UPDATE observations
693
+ SET superseded_by = ?, lifecycle = 'archived', archived_at_epoch = ?
694
+ WHERE id = ?`).run(newId, now, targetId);
695
+ this.ftsDelete(target);
696
+ this.vecDelete(targetId);
697
+ return true;
698
+ }
699
+ isSuperseded(id) {
700
+ const obs = this.getObservationById(id);
701
+ return obs !== null && obs.superseded_by !== null;
702
+ }
703
+ upsertSession(sessionId, projectId, userId, deviceId, agent = "claude-code") {
704
+ const existing = this.db.query("SELECT * FROM sessions WHERE session_id = ?").get(sessionId);
705
+ if (existing)
706
+ return existing;
707
+ const now = Math.floor(Date.now() / 1000);
708
+ this.db.query(`INSERT INTO sessions (session_id, project_id, user_id, device_id, agent, started_at_epoch)
709
+ VALUES (?, ?, ?, ?, ?, ?)`).run(sessionId, projectId, userId, deviceId, agent, now);
710
+ return this.db.query("SELECT * FROM sessions WHERE session_id = ?").get(sessionId);
711
+ }
712
+ completeSession(sessionId) {
713
+ const now = Math.floor(Date.now() / 1000);
714
+ this.db.query("UPDATE sessions SET status = 'completed', completed_at_epoch = ? WHERE session_id = ?").run(now, sessionId);
715
+ }
716
+ addToOutbox(recordType, recordId) {
717
+ const now = Math.floor(Date.now() / 1000);
718
+ this.db.query(`INSERT INTO sync_outbox (record_type, record_id, created_at_epoch)
719
+ VALUES (?, ?, ?)`).run(recordType, recordId, now);
720
+ }
721
+ getSyncState(key) {
722
+ const row = this.db.query("SELECT value FROM sync_state WHERE key = ?").get(key);
723
+ return row?.value ?? null;
724
+ }
725
+ setSyncState(key, value) {
726
+ this.db.query("INSERT INTO sync_state (key, value) VALUES (?, ?) ON CONFLICT(key) DO UPDATE SET value = ?").run(key, value, value);
727
+ }
728
+ ftsInsert(obs) {
729
+ this.db.query(`INSERT INTO observations_fts (rowid, title, narrative, facts, concepts)
730
+ VALUES (?, ?, ?, ?, ?)`).run(obs.id, obs.title, obs.narrative, obs.facts, obs.concepts);
731
+ }
732
+ ftsDelete(obs) {
733
+ this.db.query(`INSERT INTO observations_fts (observations_fts, rowid, title, narrative, facts, concepts)
734
+ VALUES ('delete', ?, ?, ?, ?, ?)`).run(obs.id, obs.title, obs.narrative, obs.facts, obs.concepts);
735
+ }
736
+ vecInsert(observationId, embedding) {
737
+ if (!this.vecAvailable)
738
+ return;
739
+ this.db.query("INSERT OR REPLACE INTO vec_observations (observation_id, embedding) VALUES (?, ?)").run(observationId, new Uint8Array(embedding.buffer));
740
+ }
741
+ vecDelete(observationId) {
742
+ if (!this.vecAvailable)
743
+ return;
744
+ this.db.query("DELETE FROM vec_observations WHERE observation_id = ?").run(observationId);
745
+ }
746
+ searchVec(queryEmbedding, projectId, lifecycles = ["active", "aging", "pinned"], limit = 20) {
747
+ if (!this.vecAvailable)
748
+ return [];
749
+ const lifecyclePlaceholders = lifecycles.map(() => "?").join(",");
750
+ const embeddingBlob = new Uint8Array(queryEmbedding.buffer);
751
+ if (projectId !== null) {
752
+ return this.db.query(`SELECT v.observation_id, v.distance
753
+ FROM vec_observations v
754
+ JOIN observations o ON o.id = v.observation_id
755
+ WHERE v.embedding MATCH ?
756
+ AND k = ?
757
+ AND o.project_id = ?
758
+ AND o.lifecycle IN (${lifecyclePlaceholders})
759
+ AND o.superseded_by IS NULL`).all(embeddingBlob, limit, projectId, ...lifecycles);
760
+ }
761
+ return this.db.query(`SELECT v.observation_id, v.distance
762
+ FROM vec_observations v
763
+ JOIN observations o ON o.id = v.observation_id
764
+ WHERE v.embedding MATCH ?
765
+ AND k = ?
766
+ AND o.lifecycle IN (${lifecyclePlaceholders})
767
+ AND o.superseded_by IS NULL`).all(embeddingBlob, limit, ...lifecycles);
768
+ }
769
+ getUnembeddedCount() {
770
+ if (!this.vecAvailable)
771
+ return 0;
772
+ const result = this.db.query(`SELECT COUNT(*) as count FROM observations o
773
+ WHERE o.lifecycle IN ('active', 'aging', 'pinned')
774
+ AND o.superseded_by IS NULL
775
+ AND NOT EXISTS (
776
+ SELECT 1 FROM vec_observations v WHERE v.observation_id = o.id
777
+ )`).get();
778
+ return result?.count ?? 0;
779
+ }
780
+ getUnembeddedObservations(limit = 100) {
781
+ if (!this.vecAvailable)
782
+ return [];
783
+ return this.db.query(`SELECT o.* FROM observations o
784
+ WHERE o.lifecycle IN ('active', 'aging', 'pinned')
785
+ AND o.superseded_by IS NULL
786
+ AND NOT EXISTS (
787
+ SELECT 1 FROM vec_observations v WHERE v.observation_id = o.id
788
+ )
789
+ ORDER BY o.created_at_epoch DESC
790
+ LIMIT ?`).all(limit);
791
+ }
792
+ insertSessionSummary(summary) {
793
+ const now = Math.floor(Date.now() / 1000);
794
+ const result = this.db.query(`INSERT INTO session_summaries (session_id, project_id, user_id, request, investigated, learned, completed, next_steps, created_at_epoch)
795
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(summary.session_id, summary.project_id, summary.user_id, summary.request, summary.investigated, summary.learned, summary.completed, summary.next_steps, now);
796
+ const id = Number(result.lastInsertRowid);
797
+ return this.db.query("SELECT * FROM session_summaries WHERE id = ?").get(id);
798
+ }
799
+ getSessionSummary(sessionId) {
800
+ return this.db.query("SELECT * FROM session_summaries WHERE session_id = ?").get(sessionId) ?? null;
801
+ }
802
+ getRecentSummaries(projectId, limit = 5) {
803
+ return this.db.query(`SELECT * FROM session_summaries
804
+ WHERE project_id = ?
805
+ ORDER BY created_at_epoch DESC, id DESC
806
+ LIMIT ?`).all(projectId, limit);
807
+ }
808
+ incrementSessionMetrics(sessionId, increments) {
809
+ const sets = [];
810
+ const params = [];
811
+ if (increments.files) {
812
+ sets.push("files_touched_count = files_touched_count + ?");
813
+ params.push(increments.files);
814
+ }
815
+ if (increments.searches) {
816
+ sets.push("searches_performed = searches_performed + ?");
817
+ params.push(increments.searches);
818
+ }
819
+ if (increments.toolCalls) {
820
+ sets.push("tool_calls_count = tool_calls_count + ?");
821
+ params.push(increments.toolCalls);
822
+ }
823
+ if (sets.length === 0)
824
+ return;
825
+ params.push(sessionId);
826
+ this.db.query(`UPDATE sessions SET ${sets.join(", ")} WHERE session_id = ?`).run(...params);
827
+ }
828
+ getSessionMetrics(sessionId) {
829
+ return this.db.query("SELECT * FROM sessions WHERE session_id = ?").get(sessionId) ?? null;
830
+ }
831
+ insertSecurityFinding(finding) {
832
+ const now = Math.floor(Date.now() / 1000);
833
+ const result = this.db.query(`INSERT INTO security_findings (session_id, project_id, finding_type, severity, pattern_name, file_path, snippet, tool_name, user_id, device_id, created_at_epoch)
834
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`).run(finding.session_id ?? null, finding.project_id, finding.finding_type, finding.severity, finding.pattern_name, finding.file_path ?? null, finding.snippet ?? null, finding.tool_name ?? null, finding.user_id, finding.device_id, now);
835
+ const id = Number(result.lastInsertRowid);
836
+ return this.db.query("SELECT * FROM security_findings WHERE id = ?").get(id);
837
+ }
838
+ getSecurityFindings(projectId, options = {}) {
839
+ const limit = options.limit ?? 50;
840
+ if (options.severity) {
841
+ return this.db.query(`SELECT * FROM security_findings
842
+ WHERE project_id = ? AND severity = ?
843
+ ORDER BY created_at_epoch DESC
844
+ LIMIT ?`).all(projectId, options.severity, limit);
845
+ }
846
+ return this.db.query(`SELECT * FROM security_findings
847
+ WHERE project_id = ?
848
+ ORDER BY created_at_epoch DESC
849
+ LIMIT ?`).all(projectId, limit);
850
+ }
851
+ getSecurityFindingsCount(projectId) {
852
+ const rows = this.db.query(`SELECT severity, COUNT(*) as count FROM security_findings
853
+ WHERE project_id = ?
854
+ GROUP BY severity`).all(projectId);
855
+ const counts = {
856
+ critical: 0,
857
+ high: 0,
858
+ medium: 0,
859
+ low: 0
860
+ };
861
+ for (const row of rows) {
862
+ counts[row.severity] = row.count;
863
+ }
864
+ return counts;
865
+ }
866
+ setSessionRiskScore(sessionId, score) {
867
+ this.db.query("UPDATE sessions SET risk_score = ? WHERE session_id = ?").run(score, sessionId);
868
+ }
869
+ getObservationsBySession(sessionId) {
870
+ return this.db.query(`SELECT * FROM observations WHERE session_id = ? ORDER BY created_at_epoch ASC`).all(sessionId);
871
+ }
872
+ getInstalledPacks() {
873
+ try {
874
+ const rows = this.db.query("SELECT name FROM packs_installed").all();
875
+ return rows.map((r) => r.name);
876
+ } catch {
877
+ return [];
878
+ }
879
+ }
880
+ markPackInstalled(name, observationCount) {
881
+ const now = Math.floor(Date.now() / 1000);
882
+ this.db.query("INSERT OR REPLACE INTO packs_installed (name, installed_at, observation_count) VALUES (?, ?, ?)").run(name, now, observationCount);
883
+ }
884
+ }
885
+
886
+ // src/storage/projects.ts
887
+ import { execSync } from "node:child_process";
888
+ import { existsSync as existsSync2, readFileSync as readFileSync2 } from "node:fs";
889
+ import { basename, join as join2 } from "node:path";
890
+ function normaliseGitRemoteUrl(remoteUrl) {
891
+ let url = remoteUrl.trim();
892
+ url = url.replace(/^(?:https?|ssh|git):\/\//, "");
893
+ url = url.replace(/^[^@]+@/, "");
894
+ url = url.replace(/^([^/:]+):(?!\d)/, "$1/");
895
+ url = url.replace(/\.git$/, "");
896
+ url = url.replace(/\/+$/, "");
897
+ const slashIndex = url.indexOf("/");
898
+ if (slashIndex !== -1) {
899
+ const host = url.substring(0, slashIndex).toLowerCase();
900
+ const path = url.substring(slashIndex);
901
+ url = host + path;
902
+ } else {
903
+ url = url.toLowerCase();
904
+ }
905
+ return url;
906
+ }
907
+ function projectNameFromCanonicalId(canonicalId) {
908
+ const parts = canonicalId.split("/");
909
+ return parts[parts.length - 1] ?? canonicalId;
910
+ }
911
+ function getGitRemoteUrl(directory) {
912
+ try {
913
+ const url = execSync("git remote get-url origin", {
914
+ cwd: directory,
915
+ encoding: "utf-8",
916
+ timeout: 5000,
917
+ stdio: ["pipe", "pipe", "pipe"]
918
+ }).trim();
919
+ return url || null;
920
+ } catch {
921
+ try {
922
+ const remotes = execSync("git remote", {
923
+ cwd: directory,
924
+ encoding: "utf-8",
925
+ timeout: 5000,
926
+ stdio: ["pipe", "pipe", "pipe"]
927
+ }).trim().split(`
928
+ `).filter(Boolean);
929
+ if (remotes.length === 0)
930
+ return null;
931
+ const url = execSync(`git remote get-url ${remotes[0]}`, {
932
+ cwd: directory,
933
+ encoding: "utf-8",
934
+ timeout: 5000,
935
+ stdio: ["pipe", "pipe", "pipe"]
936
+ }).trim();
937
+ return url || null;
938
+ } catch {
939
+ return null;
940
+ }
941
+ }
942
+ }
943
+ function readProjectConfigFile(directory) {
944
+ const configPath = join2(directory, ".engrm.json");
945
+ if (!existsSync2(configPath))
946
+ return null;
947
+ try {
948
+ const raw = readFileSync2(configPath, "utf-8");
949
+ const parsed = JSON.parse(raw);
950
+ if (typeof parsed["project_id"] !== "string" || !parsed["project_id"]) {
951
+ return null;
952
+ }
953
+ return {
954
+ project_id: parsed["project_id"],
955
+ name: typeof parsed["name"] === "string" ? parsed["name"] : undefined
956
+ };
957
+ } catch {
958
+ return null;
959
+ }
960
+ }
961
+ function detectProject(directory) {
962
+ const remoteUrl = getGitRemoteUrl(directory);
963
+ if (remoteUrl) {
964
+ const canonicalId = normaliseGitRemoteUrl(remoteUrl);
965
+ return {
966
+ canonical_id: canonicalId,
967
+ name: projectNameFromCanonicalId(canonicalId),
968
+ remote_url: remoteUrl,
969
+ local_path: directory
970
+ };
971
+ }
972
+ const configFile = readProjectConfigFile(directory);
973
+ if (configFile) {
974
+ return {
975
+ canonical_id: configFile.project_id,
976
+ name: configFile.name ?? projectNameFromCanonicalId(configFile.project_id),
977
+ remote_url: null,
978
+ local_path: directory
979
+ };
980
+ }
981
+ const dirName = basename(directory);
982
+ return {
983
+ canonical_id: `local/${dirName}`,
984
+ name: dirName,
985
+ remote_url: null,
986
+ local_path: directory
987
+ };
988
+ }
989
+
990
+ // src/context/inject.ts
991
+ var RECENCY_WINDOW_SECONDS = 30 * 86400;
992
+ function computeBlendedScore(quality, createdAtEpoch, nowEpoch) {
993
+ const age = nowEpoch - createdAtEpoch;
994
+ const recencyNorm = Math.max(0, Math.min(1, 1 - age / RECENCY_WINDOW_SECONDS));
995
+ return quality * 0.6 + recencyNorm * 0.4;
996
+ }
997
+ function estimateTokens(text) {
998
+ if (!text)
999
+ return 0;
1000
+ return Math.ceil(text.length / 4);
1001
+ }
1002
+ function buildSessionContext(db, cwd, options = {}) {
1003
+ const opts = typeof options === "number" ? { maxCount: options } : options;
1004
+ const tokenBudget = opts.tokenBudget ?? 800;
1005
+ const maxCount = opts.maxCount;
1006
+ const detected = detectProject(cwd);
1007
+ const project = db.getProjectByCanonicalId(detected.canonical_id);
1008
+ if (!project) {
1009
+ return {
1010
+ project_name: detected.name,
1011
+ canonical_id: detected.canonical_id,
1012
+ observations: [],
1013
+ session_count: 0,
1014
+ total_active: 0
1015
+ };
1016
+ }
1017
+ const totalActive = (db.db.query(`SELECT COUNT(*) as c FROM observations
1018
+ WHERE project_id = ? AND lifecycle IN ('active', 'aging', 'pinned')
1019
+ AND superseded_by IS NULL`).get(project.id) ?? { c: 0 }).c;
1020
+ const MAX_PINNED = 5;
1021
+ const pinned = db.db.query(`SELECT * FROM observations
1022
+ WHERE project_id = ? AND lifecycle = 'pinned'
1023
+ AND superseded_by IS NULL
1024
+ ORDER BY quality DESC, created_at_epoch DESC
1025
+ LIMIT ?`).all(project.id, MAX_PINNED);
1026
+ const candidateLimit = maxCount ?? 50;
1027
+ const candidates = db.db.query(`SELECT * FROM observations
1028
+ WHERE project_id = ? AND lifecycle IN ('active', 'aging')
1029
+ AND quality >= 0.3
1030
+ AND superseded_by IS NULL
1031
+ ORDER BY quality DESC, created_at_epoch DESC
1032
+ LIMIT ?`).all(project.id, candidateLimit);
1033
+ let crossProjectCandidates = [];
1034
+ if (opts.scope === "all") {
1035
+ const crossLimit = Math.max(10, Math.floor(candidateLimit / 3));
1036
+ const rawCross = db.db.query(`SELECT * FROM observations
1037
+ WHERE project_id != ? AND lifecycle IN ('active', 'aging')
1038
+ AND quality >= 0.5
1039
+ AND superseded_by IS NULL
1040
+ ORDER BY quality DESC, created_at_epoch DESC
1041
+ LIMIT ?`).all(project.id, crossLimit);
1042
+ const projectNameCache = new Map;
1043
+ crossProjectCandidates = rawCross.map((obs) => {
1044
+ if (!projectNameCache.has(obs.project_id)) {
1045
+ const proj = db.getProjectById(obs.project_id);
1046
+ if (proj)
1047
+ projectNameCache.set(obs.project_id, proj.name);
1048
+ }
1049
+ return { ...obs, _source_project: projectNameCache.get(obs.project_id) };
1050
+ });
1051
+ }
1052
+ const seenIds = new Set(pinned.map((o) => o.id));
1053
+ const deduped = candidates.filter((o) => !seenIds.has(o.id));
1054
+ for (const obs of crossProjectCandidates) {
1055
+ if (!seenIds.has(obs.id)) {
1056
+ seenIds.add(obs.id);
1057
+ deduped.push(obs);
1058
+ }
1059
+ }
1060
+ const nowEpoch = Math.floor(Date.now() / 1000);
1061
+ const sorted = [...deduped].sort((a, b) => {
1062
+ const boostA = a.type === "digest" ? 0.15 : 0;
1063
+ const boostB = b.type === "digest" ? 0.15 : 0;
1064
+ const scoreA = computeBlendedScore(a.quality, a.created_at_epoch, nowEpoch) + boostA;
1065
+ const scoreB = computeBlendedScore(b.quality, b.created_at_epoch, nowEpoch) + boostB;
1066
+ return scoreB - scoreA;
1067
+ });
1068
+ if (maxCount !== undefined) {
1069
+ const remaining = Math.max(0, maxCount - pinned.length);
1070
+ const all = [...pinned, ...sorted.slice(0, remaining)];
1071
+ return {
1072
+ project_name: project.name,
1073
+ canonical_id: project.canonical_id,
1074
+ observations: all.map(toContextObservation),
1075
+ session_count: all.length,
1076
+ total_active: totalActive
1077
+ };
1078
+ }
1079
+ let remainingBudget = tokenBudget - 30;
1080
+ const selected = [];
1081
+ for (const obs of pinned) {
1082
+ const cost = estimateObservationTokens(obs, selected.length);
1083
+ remainingBudget -= cost;
1084
+ selected.push(obs);
1085
+ }
1086
+ for (const obs of sorted) {
1087
+ const cost = estimateObservationTokens(obs, selected.length);
1088
+ if (remainingBudget - cost < 0 && selected.length > 0)
1089
+ break;
1090
+ remainingBudget -= cost;
1091
+ selected.push(obs);
1092
+ }
1093
+ const summaries = db.getRecentSummaries(project.id, 2);
1094
+ let securityFindings = [];
1095
+ try {
1096
+ const weekAgo = Math.floor(Date.now() / 1000) - 7 * 86400;
1097
+ securityFindings = db.db.query(`SELECT * FROM security_findings
1098
+ WHERE project_id = ? AND created_at_epoch > ?
1099
+ ORDER BY severity DESC, created_at_epoch DESC
1100
+ LIMIT ?`).all(project.id, weekAgo, 10);
1101
+ } catch {}
1102
+ return {
1103
+ project_name: project.name,
1104
+ canonical_id: project.canonical_id,
1105
+ observations: selected.map(toContextObservation),
1106
+ session_count: selected.length,
1107
+ total_active: totalActive,
1108
+ summaries: summaries.length > 0 ? summaries : undefined,
1109
+ securityFindings: securityFindings.length > 0 ? securityFindings : undefined
1110
+ };
1111
+ }
1112
+ function estimateObservationTokens(obs, index) {
1113
+ const DETAILED_THRESHOLD = 3;
1114
+ const titleCost = estimateTokens(`- **[${obs.type}]** ${obs.title} (2026-01-01, q=0.5)`);
1115
+ if (index >= DETAILED_THRESHOLD) {
1116
+ return titleCost;
1117
+ }
1118
+ const detailText = formatObservationDetail(obs);
1119
+ return titleCost + estimateTokens(detailText);
1120
+ }
1121
+ function formatContextForInjection(context) {
1122
+ if (context.observations.length === 0) {
1123
+ return `Project: ${context.project_name} (no prior observations)`;
1124
+ }
1125
+ const DETAILED_COUNT = 3;
1126
+ const lines = [
1127
+ `## Project Memory: ${context.project_name}`,
1128
+ `${context.session_count} relevant observation(s) from prior sessions:`,
1129
+ ""
1130
+ ];
1131
+ for (let i = 0;i < context.observations.length; i++) {
1132
+ const obs = context.observations[i];
1133
+ const date = obs.created_at.split("T")[0];
1134
+ const fromLabel = obs.source_project ? ` [from: ${obs.source_project}]` : "";
1135
+ lines.push(`- **[${obs.type}]** ${obs.title} (${date}, q=${obs.quality.toFixed(1)})${fromLabel}`);
1136
+ if (i < DETAILED_COUNT) {
1137
+ const detail = formatObservationDetailFromContext(obs);
1138
+ if (detail) {
1139
+ lines.push(detail);
1140
+ }
1141
+ }
1142
+ }
1143
+ if (context.summaries && context.summaries.length > 0) {
1144
+ lines.push("");
1145
+ lines.push("Lessons from recent sessions:");
1146
+ for (const summary of context.summaries) {
1147
+ if (summary.request) {
1148
+ lines.push(`- Request: ${summary.request}`);
1149
+ }
1150
+ if (summary.learned) {
1151
+ lines.push(` Learned: ${truncateText(summary.learned, 100)}`);
1152
+ }
1153
+ if (summary.next_steps) {
1154
+ lines.push(` Next: ${truncateText(summary.next_steps, 80)}`);
1155
+ }
1156
+ }
1157
+ }
1158
+ if (context.securityFindings && context.securityFindings.length > 0) {
1159
+ lines.push("");
1160
+ lines.push("Security findings (recent):");
1161
+ for (const finding of context.securityFindings) {
1162
+ const date = new Date(finding.created_at_epoch * 1000).toISOString().split("T")[0];
1163
+ const file = finding.file_path ? ` in ${finding.file_path}` : finding.tool_name ? ` via ${finding.tool_name}` : "";
1164
+ lines.push(`- [${finding.severity.toUpperCase()}] ${finding.pattern_name}${file} (${date})`);
1165
+ }
1166
+ }
1167
+ const remaining = context.total_active - context.session_count;
1168
+ if (remaining > 0) {
1169
+ lines.push("");
1170
+ lines.push(`${remaining} more observation(s) available via search tool.`);
1171
+ }
1172
+ return lines.join(`
1173
+ `);
1174
+ }
1175
+ function truncateText(text, maxLen) {
1176
+ if (text.length <= maxLen)
1177
+ return text;
1178
+ return text.slice(0, maxLen - 3) + "...";
1179
+ }
1180
+ function formatObservationDetailFromContext(obs) {
1181
+ if (obs.facts) {
1182
+ const bullets = parseFacts(obs.facts);
1183
+ if (bullets.length > 0) {
1184
+ return bullets.slice(0, 4).map((f) => ` - ${f}`).join(`
1185
+ `);
1186
+ }
1187
+ }
1188
+ if (obs.narrative) {
1189
+ const snippet = obs.narrative.length > 120 ? obs.narrative.slice(0, 117) + "..." : obs.narrative;
1190
+ return ` ${snippet}`;
1191
+ }
1192
+ return null;
1193
+ }
1194
+ function formatObservationDetail(obs) {
1195
+ if (obs.facts) {
1196
+ const bullets = parseFacts(obs.facts);
1197
+ if (bullets.length > 0) {
1198
+ return bullets.slice(0, 4).map((f) => ` - ${f}`).join(`
1199
+ `);
1200
+ }
1201
+ }
1202
+ if (obs.narrative) {
1203
+ const snippet = obs.narrative.length > 120 ? obs.narrative.slice(0, 117) + "..." : obs.narrative;
1204
+ return ` ${snippet}`;
1205
+ }
1206
+ return "";
1207
+ }
1208
+ function parseFacts(facts) {
1209
+ if (!facts)
1210
+ return [];
1211
+ try {
1212
+ const parsed = JSON.parse(facts);
1213
+ if (Array.isArray(parsed)) {
1214
+ return parsed.filter((f) => typeof f === "string" && f.length > 0);
1215
+ }
1216
+ } catch {
1217
+ if (facts.trim().length > 0) {
1218
+ return [facts.trim()];
1219
+ }
1220
+ }
1221
+ return [];
1222
+ }
1223
+ function toContextObservation(obs) {
1224
+ return {
1225
+ id: obs.id,
1226
+ type: obs.type,
1227
+ title: obs.title,
1228
+ narrative: obs.narrative,
1229
+ facts: obs.facts,
1230
+ quality: obs.quality,
1231
+ created_at: obs.created_at,
1232
+ ...obs._source_project ? { source_project: obs._source_project } : {}
1233
+ };
1234
+ }
1235
+
1236
+ // src/telemetry/stack-detect.ts
1237
+ import { existsSync as existsSync3 } from "node:fs";
1238
+ import { join as join3, extname } from "node:path";
1239
+ var EXTENSION_MAP = {
1240
+ ".tsx": "react",
1241
+ ".jsx": "react",
1242
+ ".ts": "typescript",
1243
+ ".js": "javascript",
1244
+ ".py": "python",
1245
+ ".rs": "rust",
1246
+ ".go": "go",
1247
+ ".java": "java",
1248
+ ".kt": "kotlin",
1249
+ ".swift": "swift",
1250
+ ".rb": "ruby",
1251
+ ".php": "php",
1252
+ ".cs": "csharp",
1253
+ ".cpp": "cpp",
1254
+ ".c": "c",
1255
+ ".zig": "zig",
1256
+ ".ex": "elixir",
1257
+ ".exs": "elixir",
1258
+ ".erl": "erlang",
1259
+ ".hs": "haskell",
1260
+ ".lua": "lua",
1261
+ ".dart": "dart",
1262
+ ".scala": "scala",
1263
+ ".clj": "clojure",
1264
+ ".vue": "vue",
1265
+ ".svelte": "svelte",
1266
+ ".astro": "astro"
1267
+ };
1268
+ var CONFIG_FILE_STACKS = [
1269
+ ["next.config.js", "nextjs"],
1270
+ ["next.config.mjs", "nextjs"],
1271
+ ["next.config.ts", "nextjs"],
1272
+ ["nuxt.config.ts", "nuxt"],
1273
+ ["nuxt.config.js", "nuxt"],
1274
+ ["vite.config.ts", "vite"],
1275
+ ["vite.config.js", "vite"],
1276
+ ["vite.config.mjs", "vite"],
1277
+ ["svelte.config.js", "svelte"],
1278
+ ["astro.config.mjs", "astro"],
1279
+ ["remix.config.js", "remix"],
1280
+ ["angular.json", "angular"],
1281
+ ["tailwind.config.js", "tailwind"],
1282
+ ["tailwind.config.ts", "tailwind"],
1283
+ ["postcss.config.js", "postcss"],
1284
+ ["webpack.config.js", "webpack"],
1285
+ ["tsconfig.json", "typescript"],
1286
+ ["Cargo.toml", "rust"],
1287
+ ["go.mod", "go"],
1288
+ ["pyproject.toml", "python"],
1289
+ ["setup.py", "python"],
1290
+ ["requirements.txt", "python"],
1291
+ ["Pipfile", "python"],
1292
+ ["manage.py", "django"],
1293
+ ["Gemfile", "ruby"],
1294
+ ["composer.json", "php"],
1295
+ ["pom.xml", "java"],
1296
+ ["build.gradle", "gradle"],
1297
+ ["build.gradle.kts", "gradle"],
1298
+ ["Package.swift", "swift"],
1299
+ ["pubspec.yaml", "flutter"],
1300
+ ["mix.exs", "elixir"],
1301
+ ["deno.json", "deno"],
1302
+ ["bun.lock", "bun"],
1303
+ ["bun.lockb", "bun"],
1304
+ ["docker-compose.yml", "docker"],
1305
+ ["docker-compose.yaml", "docker"],
1306
+ ["Dockerfile", "docker"],
1307
+ [".prisma/schema.prisma", "prisma"],
1308
+ ["prisma/schema.prisma", "prisma"],
1309
+ ["drizzle.config.ts", "drizzle"]
1310
+ ];
1311
+ var PATH_PATTERN_STACKS = [
1312
+ ["/__tests__/", "jest"],
1313
+ ["/.storybook/", "storybook"],
1314
+ ["/cypress/", "cypress"],
1315
+ ["/playwright/", "playwright"],
1316
+ ["/terraform/", "terraform"],
1317
+ ["/k8s/", "kubernetes"],
1318
+ ["/helm/", "helm"]
1319
+ ];
1320
+ function detectStacks(filePaths) {
1321
+ const stacks = new Set;
1322
+ for (const fp of filePaths) {
1323
+ const ext = extname(fp).toLowerCase();
1324
+ if (ext && EXTENSION_MAP[ext]) {
1325
+ stacks.add(EXTENSION_MAP[ext]);
1326
+ }
1327
+ for (const [pattern, stack] of PATH_PATTERN_STACKS) {
1328
+ if (fp.includes(pattern)) {
1329
+ stacks.add(stack);
1330
+ }
1331
+ }
1332
+ }
1333
+ return Array.from(stacks).sort();
1334
+ }
1335
+ function detectStacksFromProject(projectRoot, filePaths = []) {
1336
+ const stacks = new Set(detectStacks(filePaths));
1337
+ for (const [configFile, stack] of CONFIG_FILE_STACKS) {
1338
+ try {
1339
+ if (existsSync3(join3(projectRoot, configFile))) {
1340
+ stacks.add(stack);
1341
+ }
1342
+ } catch {}
1343
+ }
1344
+ const sorted = Array.from(stacks).sort();
1345
+ const frameworks = ["nextjs", "nuxt", "remix", "angular", "django", "flutter", "svelte", "astro"];
1346
+ const primary = sorted.find((s) => frameworks.includes(s)) ?? sorted[0] ?? "unknown";
1347
+ return { stacks: sorted, primary };
1348
+ }
1349
+
1350
+ // src/packs/recommender.ts
1351
+ import { existsSync as existsSync4, readdirSync, readFileSync as readFileSync3 } from "node:fs";
1352
+ import { join as join4, basename as basename3, dirname } from "node:path";
1353
+ import { fileURLToPath } from "node:url";
1354
+ var STACK_PACK_MAP = {
1355
+ typescript: ["typescript-patterns"],
1356
+ react: ["react-gotchas"],
1357
+ nextjs: ["nextjs-patterns"],
1358
+ python: ["python-django"],
1359
+ django: ["python-django"],
1360
+ javascript: ["node-security"],
1361
+ bun: ["node-security"]
1362
+ };
1363
+ function getPacksDir() {
1364
+ const thisDir = dirname(fileURLToPath(import.meta.url));
1365
+ return join4(thisDir, "../../packs");
1366
+ }
1367
+ function listAvailablePacks() {
1368
+ const dir = getPacksDir();
1369
+ if (!existsSync4(dir))
1370
+ return [];
1371
+ return readdirSync(dir).filter((f) => f.endsWith(".json")).map((f) => basename3(f, ".json"));
1372
+ }
1373
+ function loadPack(name) {
1374
+ const packPath = join4(getPacksDir(), `${name}.json`);
1375
+ if (!existsSync4(packPath))
1376
+ return null;
1377
+ try {
1378
+ const raw = readFileSync3(packPath, "utf-8");
1379
+ return JSON.parse(raw);
1380
+ } catch {
1381
+ return null;
1382
+ }
1383
+ }
1384
+ function recommendPacks(stacks, installedPacks) {
1385
+ const installed = new Set(installedPacks);
1386
+ const available = listAvailablePacks();
1387
+ const availableSet = new Set(available);
1388
+ const seen = new Set;
1389
+ const recommendations = [];
1390
+ for (const stack of stacks) {
1391
+ const packNames = STACK_PACK_MAP[stack] ?? [];
1392
+ for (const packName of packNames) {
1393
+ if (seen.has(packName) || installed.has(packName) || !availableSet.has(packName)) {
1394
+ continue;
1395
+ }
1396
+ seen.add(packName);
1397
+ const pack = loadPack(packName);
1398
+ if (!pack)
1399
+ continue;
1400
+ const matchedStacks = stacks.filter((s) => STACK_PACK_MAP[s]?.includes(packName));
1401
+ recommendations.push({
1402
+ name: packName,
1403
+ description: pack.description,
1404
+ observationCount: pack.observations.length,
1405
+ matchedStacks
1406
+ });
1407
+ }
1408
+ }
1409
+ return recommendations;
1410
+ }
1411
+
1412
+ // hooks/session-start.ts
1413
+ async function main() {
1414
+ const chunks = [];
1415
+ for await (const chunk of process.stdin) {
1416
+ chunks.push(typeof chunk === "string" ? chunk : Buffer.from(chunk).toString());
1417
+ }
1418
+ const raw = chunks.join("");
1419
+ if (!raw.trim())
1420
+ process.exit(0);
1421
+ let event;
1422
+ try {
1423
+ event = JSON.parse(raw);
1424
+ } catch {
1425
+ process.exit(0);
1426
+ }
1427
+ if (!configExists())
1428
+ process.exit(0);
1429
+ let config;
1430
+ let db;
1431
+ try {
1432
+ config = loadConfig();
1433
+ db = new MemDatabase(getDbPath());
1434
+ } catch {
1435
+ process.exit(0);
1436
+ }
1437
+ try {
1438
+ const context = buildSessionContext(db, event.cwd, {
1439
+ tokenBudget: 800,
1440
+ scope: config.search.scope
1441
+ });
1442
+ if (context && context.observations.length > 0) {
1443
+ console.log(formatContextForInjection(context));
1444
+ const parts = [];
1445
+ parts.push(`${context.session_count} observation(s)`);
1446
+ if (context.securityFindings && context.securityFindings.length > 0) {
1447
+ parts.push(`${context.securityFindings.length} security finding(s)`);
1448
+ }
1449
+ const remaining = context.total_active - context.session_count;
1450
+ if (remaining > 0) {
1451
+ parts.push(`${remaining} more searchable`);
1452
+ }
1453
+ console.error(`Engrm: ${parts.join(" \xB7 ")} \u2014 memory loaded`);
1454
+ }
1455
+ try {
1456
+ const { stacks } = detectStacksFromProject(event.cwd);
1457
+ if (stacks.length > 0) {
1458
+ const installed = db.getInstalledPacks();
1459
+ const recs = recommendPacks(stacks, installed);
1460
+ if (recs.length > 0) {
1461
+ const names = recs.map((r) => `\`${r.name}\``).join(", ");
1462
+ console.log(`
1463
+ Help packs available for your stack: ${names}. ` + `Use the install_pack tool to load curated observations.`);
1464
+ }
1465
+ }
1466
+ } catch {}
1467
+ } finally {
1468
+ db.close();
1469
+ }
1470
+ }
1471
+ main().catch(() => {
1472
+ process.exit(0);
1473
+ });