@askexenow/exe-os 0.8.1 → 0.8.2

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 (106) hide show
  1. package/package.json +1 -1
  2. package/dist/bin/backfill-responses.js +0 -2064
  3. package/dist/bin/backfill-vectors.js +0 -1771
  4. package/dist/bin/cleanup-stale-review-tasks.js +0 -1468
  5. package/dist/bin/cli.js +0 -21371
  6. package/dist/bin/exe-agent.js +0 -2016
  7. package/dist/bin/exe-assign.js +0 -2176
  8. package/dist/bin/exe-boot.js +0 -6332
  9. package/dist/bin/exe-call.js +0 -341
  10. package/dist/bin/exe-cloud.js +0 -861
  11. package/dist/bin/exe-dispatch.js +0 -1159
  12. package/dist/bin/exe-doctor.js +0 -1786
  13. package/dist/bin/exe-export-behaviors.js +0 -1637
  14. package/dist/bin/exe-forget.js +0 -1784
  15. package/dist/bin/exe-gateway.js +0 -8140
  16. package/dist/bin/exe-healthcheck.js +0 -207
  17. package/dist/bin/exe-heartbeat.js +0 -1778
  18. package/dist/bin/exe-kill.js +0 -1622
  19. package/dist/bin/exe-launch-agent.js +0 -1847
  20. package/dist/bin/exe-link.js +0 -192
  21. package/dist/bin/exe-new-employee.js +0 -1384
  22. package/dist/bin/exe-pending-messages.js +0 -1576
  23. package/dist/bin/exe-pending-notifications.js +0 -1450
  24. package/dist/bin/exe-pending-reviews.js +0 -1598
  25. package/dist/bin/exe-repo-drift.js +0 -95
  26. package/dist/bin/exe-review.js +0 -1742
  27. package/dist/bin/exe-search.js +0 -3116
  28. package/dist/bin/exe-session-cleanup.js +0 -3360
  29. package/dist/bin/exe-settings.js +0 -365
  30. package/dist/bin/exe-status.js +0 -1661
  31. package/dist/bin/exe-team.js +0 -1453
  32. package/dist/bin/git-sweep.js +0 -2441
  33. package/dist/bin/graph-backfill.js +0 -2111
  34. package/dist/bin/graph-export.js +0 -1747
  35. package/dist/bin/install.js +0 -661
  36. package/dist/bin/list-providers.js +0 -140
  37. package/dist/bin/scan-tasks.js +0 -2039
  38. package/dist/bin/setup.js +0 -2717
  39. package/dist/bin/shard-migrate.js +0 -1637
  40. package/dist/bin/update.js +0 -98
  41. package/dist/bin/wiki-sync.js +0 -1657
  42. package/dist/gateway/index.js +0 -9256
  43. package/dist/hooks/bug-report-worker.js +0 -2903
  44. package/dist/hooks/commit-complete.js +0 -2364
  45. package/dist/hooks/error-recall.js +0 -3327
  46. package/dist/hooks/exe-heartbeat-hook.js +0 -237
  47. package/dist/hooks/ingest-worker.js +0 -5065
  48. package/dist/hooks/ingest.js +0 -695
  49. package/dist/hooks/instructions-loaded.js +0 -2069
  50. package/dist/hooks/notification.js +0 -1915
  51. package/dist/hooks/post-compact.js +0 -1940
  52. package/dist/hooks/pre-compact.js +0 -1935
  53. package/dist/hooks/pre-tool-use.js +0 -2380
  54. package/dist/hooks/prompt-ingest-worker.js +0 -2291
  55. package/dist/hooks/prompt-submit.js +0 -5189
  56. package/dist/hooks/response-ingest-worker.js +0 -2431
  57. package/dist/hooks/session-end.js +0 -2196
  58. package/dist/hooks/session-start.js +0 -3259
  59. package/dist/hooks/stop.js +0 -2025
  60. package/dist/hooks/subagent-stop.js +0 -1915
  61. package/dist/hooks/summary-worker.js +0 -2931
  62. package/dist/index.js +0 -12327
  63. package/dist/lib/cloud-sync.js +0 -500
  64. package/dist/lib/config.js +0 -235
  65. package/dist/lib/consolidation.js +0 -481
  66. package/dist/lib/crypto.js +0 -51
  67. package/dist/lib/database.js +0 -834
  68. package/dist/lib/device-registry.js +0 -1009
  69. package/dist/lib/embedder.js +0 -645
  70. package/dist/lib/employee-templates.js +0 -570
  71. package/dist/lib/employees.js +0 -182
  72. package/dist/lib/error-detector.js +0 -156
  73. package/dist/lib/exe-daemon-client.js +0 -456
  74. package/dist/lib/exe-daemon.js +0 -8699
  75. package/dist/lib/file-grep.js +0 -215
  76. package/dist/lib/hybrid-search.js +0 -3064
  77. package/dist/lib/identity-templates.js +0 -441
  78. package/dist/lib/identity.js +0 -228
  79. package/dist/lib/keychain.js +0 -145
  80. package/dist/lib/license.js +0 -382
  81. package/dist/lib/messaging.js +0 -1389
  82. package/dist/lib/reminders.js +0 -63
  83. package/dist/lib/schedules.js +0 -1525
  84. package/dist/lib/session-registry.js +0 -52
  85. package/dist/lib/skill-learning.js +0 -488
  86. package/dist/lib/status-brief.js +0 -240
  87. package/dist/lib/store.js +0 -1740
  88. package/dist/lib/task-router.js +0 -128
  89. package/dist/lib/tasks.js +0 -2585
  90. package/dist/lib/tmux-routing.js +0 -2969
  91. package/dist/lib/tmux-status.js +0 -261
  92. package/dist/lib/tmux-transport.js +0 -83
  93. package/dist/lib/transport.js +0 -128
  94. package/dist/lib/ws-auth.js +0 -19
  95. package/dist/lib/ws-client.js +0 -160
  96. package/dist/mcp/server.js +0 -10812
  97. package/dist/mcp/tools/complete-reminder.js +0 -67
  98. package/dist/mcp/tools/create-reminder.js +0 -52
  99. package/dist/mcp/tools/create-task.js +0 -1903
  100. package/dist/mcp/tools/deactivate-behavior.js +0 -268
  101. package/dist/mcp/tools/list-reminders.js +0 -62
  102. package/dist/mcp/tools/list-tasks.js +0 -491
  103. package/dist/mcp/tools/send-message.js +0 -1395
  104. package/dist/mcp/tools/update-task.js +0 -1807
  105. package/dist/runtime/index.js +0 -7201
  106. package/dist/tui/App.js +0 -17874
@@ -1,2364 +0,0 @@
1
- var __defProp = Object.defineProperty;
2
- var __getOwnPropNames = Object.getOwnPropertyNames;
3
- var __require = /* @__PURE__ */ ((x) => typeof require !== "undefined" ? require : typeof Proxy !== "undefined" ? new Proxy(x, {
4
- get: (a, b) => (typeof require !== "undefined" ? require : a)[b]
5
- }) : x)(function(x) {
6
- if (typeof require !== "undefined") return require.apply(this, arguments);
7
- throw Error('Dynamic require of "' + x + '" is not supported');
8
- });
9
- var __esm = (fn, res) => function __init() {
10
- return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;
11
- };
12
- var __export = (target, all) => {
13
- for (var name in all)
14
- __defProp(target, name, { get: all[name], enumerable: true });
15
- };
16
-
17
- // src/types/memory.ts
18
- var EMBEDDING_DIM;
19
- var init_memory = __esm({
20
- "src/types/memory.ts"() {
21
- "use strict";
22
- EMBEDDING_DIM = 1024;
23
- }
24
- });
25
-
26
- // src/lib/database.ts
27
- var database_exports = {};
28
- __export(database_exports, {
29
- disposeDatabase: () => disposeDatabase,
30
- disposeTurso: () => disposeTurso,
31
- ensureSchema: () => ensureSchema,
32
- getClient: () => getClient,
33
- initDatabase: () => initDatabase,
34
- initTurso: () => initTurso,
35
- isInitialized: () => isInitialized
36
- });
37
- import { createClient } from "@libsql/client";
38
- async function initDatabase(config) {
39
- if (_client) {
40
- _client.close();
41
- _client = null;
42
- }
43
- const opts = {
44
- url: `file:${config.dbPath}`
45
- };
46
- if (config.encryptionKey) {
47
- opts.encryptionKey = config.encryptionKey;
48
- }
49
- _client = createClient(opts);
50
- }
51
- function isInitialized() {
52
- return _client !== null;
53
- }
54
- function getClient() {
55
- if (!_client) {
56
- throw new Error("Database client not initialized. Call initDatabase() first.");
57
- }
58
- return _client;
59
- }
60
- async function ensureSchema() {
61
- const client = getClient();
62
- await client.execute("PRAGMA journal_mode = WAL");
63
- await client.execute("PRAGMA busy_timeout = 5000");
64
- try {
65
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
66
- } catch {
67
- }
68
- await client.executeMultiple(`
69
- CREATE TABLE IF NOT EXISTS memories (
70
- id TEXT PRIMARY KEY,
71
- agent_id TEXT NOT NULL,
72
- agent_role TEXT NOT NULL,
73
- session_id TEXT NOT NULL,
74
- timestamp TEXT NOT NULL,
75
- tool_name TEXT NOT NULL,
76
- project_name TEXT NOT NULL,
77
- has_error INTEGER NOT NULL DEFAULT 0,
78
- raw_text TEXT NOT NULL,
79
- vector F32_BLOB(1024),
80
- version INTEGER NOT NULL DEFAULT 0
81
- );
82
-
83
- CREATE INDEX IF NOT EXISTS idx_memories_agent
84
- ON memories(agent_id);
85
-
86
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp
87
- ON memories(timestamp);
88
-
89
- CREATE INDEX IF NOT EXISTS idx_memories_session
90
- ON memories(session_id);
91
-
92
- CREATE INDEX IF NOT EXISTS idx_memories_project
93
- ON memories(project_name);
94
-
95
- CREATE INDEX IF NOT EXISTS idx_memories_tool
96
- ON memories(tool_name);
97
-
98
- CREATE INDEX IF NOT EXISTS idx_memories_version
99
- ON memories(version);
100
-
101
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project
102
- ON memories(agent_id, project_name);
103
- `);
104
- await client.executeMultiple(`
105
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
106
- raw_text,
107
- content='memories',
108
- content_rowid='rowid'
109
- );
110
-
111
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
112
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
113
- END;
114
-
115
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
116
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
117
- END;
118
-
119
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
120
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
121
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
122
- END;
123
- `);
124
- await client.executeMultiple(`
125
- CREATE TABLE IF NOT EXISTS sync_meta (
126
- key TEXT PRIMARY KEY,
127
- value TEXT NOT NULL
128
- );
129
- `);
130
- await client.executeMultiple(`
131
- CREATE TABLE IF NOT EXISTS tasks (
132
- id TEXT PRIMARY KEY,
133
- title TEXT NOT NULL,
134
- assigned_to TEXT NOT NULL,
135
- assigned_by TEXT NOT NULL,
136
- project_name TEXT NOT NULL,
137
- priority TEXT NOT NULL DEFAULT 'p1',
138
- status TEXT NOT NULL DEFAULT 'open',
139
- task_file TEXT,
140
- created_at TEXT NOT NULL,
141
- updated_at TEXT NOT NULL
142
- );
143
-
144
- CREATE INDEX IF NOT EXISTS idx_tasks_assignee_status
145
- ON tasks(assigned_to, status);
146
- `);
147
- await client.executeMultiple(`
148
- CREATE TABLE IF NOT EXISTS behaviors (
149
- id TEXT PRIMARY KEY,
150
- agent_id TEXT NOT NULL,
151
- project_name TEXT,
152
- domain TEXT,
153
- content TEXT NOT NULL,
154
- active INTEGER NOT NULL DEFAULT 1,
155
- created_at TEXT NOT NULL,
156
- updated_at TEXT NOT NULL
157
- );
158
-
159
- CREATE INDEX IF NOT EXISTS idx_behaviors_agent
160
- ON behaviors(agent_id, active);
161
- `);
162
- try {
163
- const existing = await client.execute({
164
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
165
- args: []
166
- });
167
- if (Number(existing.rows[0]?.cnt) === 0) {
168
- await client.executeMultiple(`
169
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
170
- VALUES
171
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Don''t ask "keep going?" \u2014 just keep executing phases/plans autonomously', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
172
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
173
- VALUES
174
- (hex(randomblob(16)), 'exe', NULL, 'tool-use', 'Always use create_task MCP tool, never write .md files directly for task creation', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
175
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
176
- VALUES
177
- (hex(randomblob(16)), 'exe', NULL, 'workflow', 'Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission', 1, '2026-03-25T00:00:00Z', '2026-03-25T00:00:00Z');
178
- `);
179
- }
180
- } catch {
181
- }
182
- try {
183
- await client.execute({
184
- sql: `ALTER TABLE behaviors ADD COLUMN priority TEXT DEFAULT 'p1'`,
185
- args: []
186
- });
187
- } catch {
188
- }
189
- try {
190
- await client.execute({
191
- sql: `ALTER TABLE tasks ADD COLUMN blocked_by TEXT`,
192
- args: []
193
- });
194
- } catch {
195
- }
196
- try {
197
- await client.execute({
198
- sql: `ALTER TABLE tasks ADD COLUMN parent_task_id TEXT`,
199
- args: []
200
- });
201
- } catch {
202
- }
203
- try {
204
- await client.execute({
205
- sql: `CREATE INDEX IF NOT EXISTS idx_tasks_parent_task_id
206
- ON tasks(parent_task_id)
207
- WHERE parent_task_id IS NOT NULL`,
208
- args: []
209
- });
210
- } catch {
211
- }
212
- try {
213
- await client.execute({
214
- sql: `UPDATE tasks SET status = 'done' WHERE status = 'completed'`,
215
- args: []
216
- });
217
- } catch {
218
- }
219
- try {
220
- await client.execute({
221
- sql: `ALTER TABLE tasks ADD COLUMN reviewer TEXT`,
222
- args: []
223
- });
224
- } catch {
225
- }
226
- try {
227
- await client.execute({
228
- sql: `ALTER TABLE tasks ADD COLUMN context TEXT`,
229
- args: []
230
- });
231
- } catch {
232
- }
233
- try {
234
- await client.execute({
235
- sql: `ALTER TABLE tasks ADD COLUMN result TEXT`,
236
- args: []
237
- });
238
- } catch {
239
- }
240
- try {
241
- await client.execute({
242
- sql: `ALTER TABLE tasks ADD COLUMN assigned_tmux TEXT`,
243
- args: []
244
- });
245
- } catch {
246
- }
247
- try {
248
- await client.execute({
249
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint TEXT`,
250
- args: []
251
- });
252
- } catch {
253
- }
254
- try {
255
- await client.execute({
256
- sql: `ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER NOT NULL DEFAULT 0`,
257
- args: []
258
- });
259
- } catch {
260
- }
261
- try {
262
- await client.execute({
263
- sql: `ALTER TABLE tasks ADD COLUMN complexity TEXT NOT NULL DEFAULT 'standard'`,
264
- args: []
265
- });
266
- } catch {
267
- }
268
- try {
269
- await client.execute({
270
- sql: `ALTER TABLE memories ADD COLUMN task_id TEXT`,
271
- args: []
272
- });
273
- } catch {
274
- }
275
- try {
276
- await client.execute({
277
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
278
- args: []
279
- });
280
- } catch {
281
- }
282
- try {
283
- await client.execute({
284
- sql: `ALTER TABLE memories ADD COLUMN author_device_id TEXT`,
285
- args: []
286
- });
287
- } catch {
288
- }
289
- try {
290
- await client.execute({
291
- sql: `ALTER TABLE memories ADD COLUMN scope TEXT NOT NULL DEFAULT 'business'`,
292
- args: []
293
- });
294
- } catch {
295
- }
296
- await client.executeMultiple(`
297
- CREATE TABLE IF NOT EXISTS consolidations (
298
- id TEXT PRIMARY KEY,
299
- consolidated_memory_id TEXT NOT NULL,
300
- source_memory_id TEXT NOT NULL,
301
- created_at TEXT NOT NULL
302
- );
303
-
304
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
305
- ON consolidations(source_memory_id);
306
-
307
- CREATE INDEX IF NOT EXISTS idx_consolidations_consolidated
308
- ON consolidations(consolidated_memory_id);
309
- `);
310
- await client.executeMultiple(`
311
- CREATE TABLE IF NOT EXISTS reminders (
312
- id TEXT PRIMARY KEY,
313
- text TEXT NOT NULL,
314
- created_at TEXT NOT NULL,
315
- due_date TEXT,
316
- completed_at TEXT
317
- );
318
- `);
319
- await client.executeMultiple(`
320
- CREATE TABLE IF NOT EXISTS notifications (
321
- id TEXT PRIMARY KEY,
322
- agent_id TEXT NOT NULL,
323
- agent_role TEXT NOT NULL,
324
- event TEXT NOT NULL,
325
- project TEXT NOT NULL,
326
- summary TEXT NOT NULL,
327
- task_file TEXT,
328
- read INTEGER NOT NULL DEFAULT 0,
329
- created_at TEXT NOT NULL
330
- );
331
-
332
- CREATE INDEX IF NOT EXISTS idx_notifications_read
333
- ON notifications(read);
334
-
335
- CREATE INDEX IF NOT EXISTS idx_notifications_agent
336
- ON notifications(agent_id);
337
-
338
- CREATE INDEX IF NOT EXISTS idx_notifications_task_file
339
- ON notifications(task_file);
340
- `);
341
- await client.executeMultiple(`
342
- CREATE TABLE IF NOT EXISTS schedules (
343
- id TEXT PRIMARY KEY,
344
- cron TEXT NOT NULL,
345
- description TEXT NOT NULL,
346
- job_type TEXT NOT NULL DEFAULT 'report',
347
- prompt TEXT,
348
- assigned_to TEXT,
349
- project_name TEXT,
350
- active INTEGER NOT NULL DEFAULT 1,
351
- use_crontab INTEGER NOT NULL DEFAULT 0,
352
- created_at TEXT NOT NULL
353
- );
354
- `);
355
- await client.executeMultiple(`
356
- CREATE TABLE IF NOT EXISTS device_registry (
357
- device_id TEXT PRIMARY KEY,
358
- friendly_name TEXT NOT NULL,
359
- hostname TEXT NOT NULL,
360
- projects TEXT NOT NULL DEFAULT '[]',
361
- agents TEXT NOT NULL DEFAULT '[]',
362
- connected INTEGER DEFAULT 0,
363
- last_seen TEXT NOT NULL
364
- );
365
- `);
366
- await client.executeMultiple(`
367
- CREATE TABLE IF NOT EXISTS messages (
368
- id TEXT PRIMARY KEY,
369
- from_agent TEXT NOT NULL,
370
- from_device TEXT NOT NULL DEFAULT 'local',
371
- target_agent TEXT NOT NULL,
372
- target_project TEXT,
373
- target_device TEXT NOT NULL DEFAULT 'local',
374
- content TEXT NOT NULL,
375
- priority TEXT DEFAULT 'normal',
376
- status TEXT DEFAULT 'pending',
377
- server_seq INTEGER,
378
- retry_count INTEGER DEFAULT 0,
379
- created_at TEXT NOT NULL,
380
- delivered_at TEXT,
381
- processed_at TEXT,
382
- failed_at TEXT,
383
- failure_reason TEXT
384
- );
385
-
386
- CREATE INDEX IF NOT EXISTS idx_messages_target
387
- ON messages(target_agent, status);
388
-
389
- CREATE INDEX IF NOT EXISTS idx_messages_conversation_order
390
- ON messages(target_agent, from_agent, server_seq);
391
- `);
392
- try {
393
- await client.execute({
394
- sql: `UPDATE memories SET project_name = 'exe-create' WHERE project_name = 'web'`,
395
- args: []
396
- });
397
- await client.execute({
398
- sql: `UPDATE memories SET project_name = 'exe-os' WHERE project_name = 'worker'`,
399
- args: []
400
- });
401
- await client.execute({
402
- sql: `UPDATE tasks SET project_name = 'exe-create' WHERE project_name = 'web'`,
403
- args: []
404
- });
405
- await client.execute({
406
- sql: `UPDATE tasks SET project_name = 'exe-os' WHERE project_name = 'worker'`,
407
- args: []
408
- });
409
- } catch {
410
- }
411
- await client.executeMultiple(`
412
- CREATE TABLE IF NOT EXISTS trajectories (
413
- id TEXT PRIMARY KEY,
414
- task_id TEXT NOT NULL,
415
- agent_id TEXT NOT NULL,
416
- project_name TEXT NOT NULL,
417
- task_title TEXT NOT NULL,
418
- signature TEXT NOT NULL,
419
- signature_hash TEXT NOT NULL,
420
- tool_count INTEGER NOT NULL,
421
- skill_id TEXT,
422
- created_at TEXT NOT NULL
423
- );
424
-
425
- CREATE INDEX IF NOT EXISTS idx_trajectories_hash
426
- ON trajectories(signature_hash);
427
-
428
- CREATE INDEX IF NOT EXISTS idx_trajectories_agent
429
- ON trajectories(agent_id);
430
- `);
431
- try {
432
- await client.execute("ALTER TABLE trajectories ADD COLUMN skill_id TEXT");
433
- } catch {
434
- }
435
- await client.executeMultiple(`
436
- CREATE TABLE IF NOT EXISTS consolidations (
437
- id TEXT PRIMARY KEY,
438
- consolidated_memory_id TEXT NOT NULL,
439
- source_memory_id TEXT NOT NULL,
440
- created_at TEXT NOT NULL
441
- );
442
-
443
- CREATE INDEX IF NOT EXISTS idx_consolidations_source
444
- ON consolidations(source_memory_id);
445
- `);
446
- await client.executeMultiple(`
447
- CREATE TABLE IF NOT EXISTS audit_trail (
448
- id INTEGER PRIMARY KEY AUTOINCREMENT,
449
- timestamp TEXT NOT NULL,
450
- session_id TEXT NOT NULL,
451
- agent_id TEXT NOT NULL,
452
- tool TEXT NOT NULL,
453
- input TEXT,
454
- decision TEXT NOT NULL,
455
- reason TEXT,
456
- is_customer_facing INTEGER NOT NULL DEFAULT 0
457
- );
458
-
459
- CREATE INDEX IF NOT EXISTS idx_audit_trail_agent
460
- ON audit_trail(agent_id, timestamp);
461
-
462
- CREATE INDEX IF NOT EXISTS idx_audit_trail_session
463
- ON audit_trail(session_id);
464
- `);
465
- try {
466
- await client.execute({
467
- sql: `ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0`,
468
- args: []
469
- });
470
- } catch {
471
- }
472
- try {
473
- await client.execute({
474
- sql: `ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5`,
475
- args: []
476
- });
477
- } catch {
478
- }
479
- try {
480
- await client.execute({
481
- sql: `ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'`,
482
- args: []
483
- });
484
- } catch {
485
- }
486
- try {
487
- await client.execute({
488
- sql: `ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7`,
489
- args: []
490
- });
491
- } catch {
492
- }
493
- try {
494
- await client.execute({
495
- sql: `ALTER TABLE memories ADD COLUMN last_accessed TEXT`,
496
- args: []
497
- });
498
- } catch {
499
- }
500
- try {
501
- await client.execute({
502
- sql: `UPDATE memories SET last_accessed = timestamp WHERE last_accessed IS NULL`,
503
- args: []
504
- });
505
- } catch {
506
- }
507
- try {
508
- await client.execute({
509
- sql: `ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0`,
510
- args: []
511
- });
512
- } catch {
513
- }
514
- try {
515
- await client.execute({
516
- sql: `ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0`,
517
- args: []
518
- });
519
- } catch {
520
- }
521
- for (const col of [
522
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
523
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT"
524
- ]) {
525
- try {
526
- await client.execute(col);
527
- } catch {
528
- }
529
- }
530
- await client.executeMultiple(`
531
- CREATE TABLE IF NOT EXISTS entities (
532
- id TEXT PRIMARY KEY,
533
- name TEXT NOT NULL,
534
- type TEXT NOT NULL,
535
- first_seen TEXT NOT NULL,
536
- last_seen TEXT NOT NULL,
537
- properties TEXT DEFAULT '{}',
538
- UNIQUE(name, type)
539
- );
540
-
541
- CREATE TABLE IF NOT EXISTS relationships (
542
- id TEXT PRIMARY KEY,
543
- source_entity_id TEXT NOT NULL,
544
- target_entity_id TEXT NOT NULL,
545
- type TEXT NOT NULL,
546
- weight REAL DEFAULT 1.0,
547
- timestamp TEXT NOT NULL,
548
- properties TEXT DEFAULT '{}',
549
- UNIQUE(source_entity_id, target_entity_id, type)
550
- );
551
-
552
- CREATE TABLE IF NOT EXISTS entity_memories (
553
- entity_id TEXT NOT NULL,
554
- memory_id TEXT NOT NULL,
555
- PRIMARY KEY (entity_id, memory_id)
556
- );
557
-
558
- CREATE TABLE IF NOT EXISTS relationship_memories (
559
- relationship_id TEXT NOT NULL,
560
- memory_id TEXT NOT NULL,
561
- PRIMARY KEY (relationship_id, memory_id)
562
- );
563
-
564
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
565
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
566
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
567
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
568
-
569
- CREATE TABLE IF NOT EXISTS hyperedges (
570
- id TEXT PRIMARY KEY,
571
- label TEXT NOT NULL,
572
- relation TEXT NOT NULL,
573
- confidence REAL DEFAULT 1.0,
574
- timestamp TEXT NOT NULL
575
- );
576
-
577
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
578
- hyperedge_id TEXT NOT NULL,
579
- entity_id TEXT NOT NULL,
580
- PRIMARY KEY (hyperedge_id, entity_id)
581
- );
582
- `);
583
- await client.executeMultiple(`
584
- CREATE TABLE IF NOT EXISTS entity_aliases (
585
- alias TEXT NOT NULL PRIMARY KEY,
586
- canonical_entity_id TEXT NOT NULL
587
- );
588
- CREATE INDEX IF NOT EXISTS idx_entity_aliases_canonical ON entity_aliases(canonical_entity_id);
589
- `);
590
- for (const col of [
591
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
592
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
593
- ]) {
594
- try {
595
- await client.execute(col);
596
- } catch {
597
- }
598
- }
599
- try {
600
- await client.execute(
601
- `CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)`
602
- );
603
- } catch {
604
- }
605
- await client.executeMultiple(`
606
- CREATE TABLE IF NOT EXISTS identity (
607
- id INTEGER PRIMARY KEY AUTOINCREMENT,
608
- agent_id TEXT NOT NULL UNIQUE,
609
- content_hash TEXT NOT NULL,
610
- updated_at TEXT NOT NULL,
611
- updated_by TEXT NOT NULL
612
- );
613
-
614
- CREATE INDEX IF NOT EXISTS idx_identity_agent ON identity(agent_id);
615
- `);
616
- await client.executeMultiple(`
617
- CREATE TABLE IF NOT EXISTS chat_history (
618
- id INTEGER PRIMARY KEY AUTOINCREMENT,
619
- session_id TEXT NOT NULL,
620
- role TEXT NOT NULL,
621
- content TEXT NOT NULL,
622
- tool_name TEXT,
623
- tool_id TEXT,
624
- is_error INTEGER NOT NULL DEFAULT 0,
625
- timestamp INTEGER NOT NULL
626
- );
627
-
628
- CREATE INDEX IF NOT EXISTS idx_chat_history_session
629
- ON chat_history(session_id, id);
630
- `);
631
- await client.executeMultiple(`
632
- CREATE TABLE IF NOT EXISTS workspaces (
633
- id TEXT PRIMARY KEY,
634
- slug TEXT NOT NULL UNIQUE,
635
- name TEXT NOT NULL,
636
- owner_agent_id TEXT,
637
- created_at TEXT NOT NULL,
638
- metadata TEXT
639
- );
640
-
641
- CREATE INDEX IF NOT EXISTS idx_workspaces_slug
642
- ON workspaces(slug);
643
- `);
644
- await client.executeMultiple(`
645
- CREATE TABLE IF NOT EXISTS documents (
646
- id TEXT PRIMARY KEY,
647
- workspace_id TEXT NOT NULL,
648
- filename TEXT NOT NULL,
649
- mime TEXT,
650
- source_type TEXT,
651
- user_id TEXT,
652
- uploaded_at TEXT NOT NULL,
653
- metadata TEXT,
654
- FOREIGN KEY (workspace_id) REFERENCES workspaces(id)
655
- );
656
-
657
- CREATE INDEX IF NOT EXISTS idx_documents_workspace
658
- ON documents(workspace_id);
659
-
660
- CREATE INDEX IF NOT EXISTS idx_documents_user
661
- ON documents(user_id);
662
- `);
663
- for (const column of [
664
- "workspace_id TEXT",
665
- "document_id TEXT",
666
- "user_id TEXT",
667
- "char_offset INTEGER",
668
- "page_number INTEGER"
669
- ]) {
670
- try {
671
- await client.execute({
672
- sql: `ALTER TABLE memories ADD COLUMN ${column}`,
673
- args: []
674
- });
675
- } catch {
676
- }
677
- }
678
- for (const col of [
679
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
680
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'"
681
- ]) {
682
- try {
683
- await client.execute(col);
684
- } catch {
685
- }
686
- }
687
- await client.executeMultiple(`
688
- CREATE INDEX IF NOT EXISTS idx_memories_workspace
689
- ON memories(workspace_id);
690
-
691
- CREATE INDEX IF NOT EXISTS idx_memories_document
692
- ON memories(document_id);
693
-
694
- CREATE INDEX IF NOT EXISTS idx_memories_user
695
- ON memories(user_id);
696
- `);
697
- await client.executeMultiple(`
698
- CREATE TABLE IF NOT EXISTS session_kills (
699
- id TEXT PRIMARY KEY,
700
- session_name TEXT NOT NULL,
701
- agent_id TEXT NOT NULL,
702
- killed_at TIMESTAMP NOT NULL,
703
- reason TEXT NOT NULL,
704
- ticks_idle INTEGER,
705
- estimated_tokens_saved INTEGER
706
- );
707
-
708
- CREATE INDEX IF NOT EXISTS idx_session_kills_killed_at
709
- ON session_kills(killed_at);
710
-
711
- CREATE INDEX IF NOT EXISTS idx_session_kills_agent
712
- ON session_kills(agent_id);
713
- `);
714
- await client.executeMultiple(`
715
- CREATE TABLE IF NOT EXISTS conversations (
716
- id TEXT PRIMARY KEY,
717
- platform TEXT NOT NULL,
718
- external_id TEXT,
719
- sender_id TEXT NOT NULL,
720
- sender_name TEXT,
721
- sender_phone TEXT,
722
- sender_email TEXT,
723
- recipient_id TEXT,
724
- channel_id TEXT NOT NULL,
725
- thread_id TEXT,
726
- reply_to_id TEXT,
727
- content_text TEXT,
728
- content_media TEXT,
729
- content_metadata TEXT,
730
- agent_response TEXT,
731
- agent_name TEXT,
732
- timestamp TEXT NOT NULL,
733
- ingested_at TEXT NOT NULL
734
- );
735
-
736
- CREATE INDEX IF NOT EXISTS idx_conversations_platform
737
- ON conversations(platform);
738
-
739
- CREATE INDEX IF NOT EXISTS idx_conversations_sender
740
- ON conversations(sender_id);
741
-
742
- CREATE INDEX IF NOT EXISTS idx_conversations_timestamp
743
- ON conversations(timestamp);
744
-
745
- CREATE INDEX IF NOT EXISTS idx_conversations_thread
746
- ON conversations(thread_id);
747
-
748
- CREATE INDEX IF NOT EXISTS idx_conversations_channel
749
- ON conversations(channel_id);
750
- `);
751
- try {
752
- await client.execute({
753
- sql: `ALTER TABLE tasks ADD COLUMN budget_tokens INTEGER`,
754
- args: []
755
- });
756
- } catch {
757
- }
758
- try {
759
- await client.execute({
760
- sql: `ALTER TABLE tasks ADD COLUMN budget_fallback_model TEXT`,
761
- args: []
762
- });
763
- } catch {
764
- }
765
- try {
766
- await client.execute({
767
- sql: `ALTER TABLE tasks ADD COLUMN tokens_used INTEGER DEFAULT 0`,
768
- args: []
769
- });
770
- } catch {
771
- }
772
- try {
773
- await client.execute({
774
- sql: `ALTER TABLE tasks ADD COLUMN tokens_warned_at INTEGER`,
775
- args: []
776
- });
777
- } catch {
778
- }
779
- await client.executeMultiple(`
780
- CREATE VIRTUAL TABLE IF NOT EXISTS conversations_fts USING fts5(
781
- content_text,
782
- sender_name,
783
- agent_response,
784
- content='conversations',
785
- content_rowid='rowid'
786
- );
787
-
788
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ai AFTER INSERT ON conversations BEGIN
789
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
790
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
791
- END;
792
-
793
- CREATE TRIGGER IF NOT EXISTS conversations_fts_ad AFTER DELETE ON conversations BEGIN
794
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
795
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
796
- END;
797
-
798
- CREATE TRIGGER IF NOT EXISTS conversations_fts_au AFTER UPDATE ON conversations BEGIN
799
- INSERT INTO conversations_fts(conversations_fts, rowid, content_text, sender_name, agent_response)
800
- VALUES('delete', old.rowid, old.content_text, old.sender_name, old.agent_response);
801
- INSERT INTO conversations_fts(rowid, content_text, sender_name, agent_response)
802
- VALUES (new.rowid, new.content_text, new.sender_name, new.agent_response);
803
- END;
804
- `);
805
- try {
806
- await client.execute({
807
- sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
808
- args: []
809
- });
810
- } catch {
811
- }
812
- try {
813
- await client.execute(
814
- `CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)`
815
- );
816
- } catch {
817
- }
818
- try {
819
- await client.execute({
820
- sql: `UPDATE memories SET tier = 1 WHERE tool_name = 'commit_to_long_term_memory' AND importance >= 8 AND tier = 3`,
821
- args: []
822
- });
823
- await client.execute({
824
- sql: `UPDATE memories SET tier = 2 WHERE tool_name IN ('store_memory', 'manual') AND importance >= 5 AND tier = 3`,
825
- args: []
826
- });
827
- } catch {
828
- }
829
- try {
830
- await client.execute({
831
- sql: `ALTER TABLE memories ADD COLUMN supersedes_id TEXT`,
832
- args: []
833
- });
834
- } catch {
835
- }
836
- try {
837
- await client.execute(
838
- `CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL`
839
- );
840
- } catch {
841
- }
842
- for (const col of [
843
- "ALTER TABLE tasks ADD COLUMN checkpoint TEXT",
844
- "ALTER TABLE tasks ADD COLUMN checkpoint_count INTEGER DEFAULT 0"
845
- ]) {
846
- try {
847
- await client.execute(col);
848
- } catch {
849
- }
850
- }
851
- }
852
- async function disposeDatabase() {
853
- if (_client) {
854
- _client.close();
855
- _client = null;
856
- }
857
- }
858
- var _client, initTurso, disposeTurso;
859
- var init_database = __esm({
860
- "src/lib/database.ts"() {
861
- "use strict";
862
- _client = null;
863
- initTurso = initDatabase;
864
- disposeTurso = disposeDatabase;
865
- }
866
- });
867
-
868
- // src/lib/keychain.ts
869
- import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
870
- import { existsSync } from "fs";
871
- import path from "path";
872
- import crypto from "crypto";
873
- function getKeyDir() {
874
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path.join(process.env.HOME ?? "/tmp", ".exe-os");
875
- }
876
- function getKeyPath() {
877
- return path.join(getKeyDir(), "master.key");
878
- }
879
- async function tryKeytar() {
880
- try {
881
- return await import("keytar");
882
- } catch {
883
- return null;
884
- }
885
- }
886
- async function getMasterKey() {
887
- const keytar = await tryKeytar();
888
- if (keytar) {
889
- try {
890
- const stored = await keytar.getPassword(SERVICE, ACCOUNT);
891
- if (stored) {
892
- return Buffer.from(stored, "base64");
893
- }
894
- } catch {
895
- }
896
- }
897
- const keyPath = getKeyPath();
898
- if (!existsSync(keyPath)) {
899
- return null;
900
- }
901
- try {
902
- const content = await readFile(keyPath, "utf-8");
903
- return Buffer.from(content.trim(), "base64");
904
- } catch {
905
- return null;
906
- }
907
- }
908
- var SERVICE, ACCOUNT;
909
- var init_keychain = __esm({
910
- "src/lib/keychain.ts"() {
911
- "use strict";
912
- SERVICE = "exe-mem";
913
- ACCOUNT = "master-key";
914
- }
915
- });
916
-
917
- // src/lib/config.ts
918
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
919
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
920
- import path2 from "path";
921
- import os from "os";
922
- function resolveDataDir() {
923
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
924
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
925
- const newDir = path2.join(os.homedir(), ".exe-os");
926
- const legacyDir = path2.join(os.homedir(), ".exe-mem");
927
- if (!existsSync2(newDir) && existsSync2(legacyDir)) {
928
- try {
929
- renameSync(legacyDir, newDir);
930
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
931
- `);
932
- } catch {
933
- return legacyDir;
934
- }
935
- }
936
- return newDir;
937
- }
938
- function migrateLegacyConfig(raw) {
939
- if ("r2" in raw) {
940
- process.stderr.write(
941
- "[exe-os] Warning: config.json contains deprecated 'r2' field from v1.0. R2 sync has been replaced in v1.1. The 'r2' field will be ignored.\n"
942
- );
943
- delete raw.r2;
944
- }
945
- if ("syncIntervalMs" in raw) {
946
- delete raw.syncIntervalMs;
947
- }
948
- return raw;
949
- }
950
- function migrateConfig(raw) {
951
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
952
- let currentVersion = fromVersion;
953
- let migrated = false;
954
- if (currentVersion > CURRENT_CONFIG_VERSION) {
955
- return { config: raw, migrated: false, fromVersion };
956
- }
957
- for (const migration of CONFIG_MIGRATIONS) {
958
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
959
- raw = migration.migrate(raw);
960
- currentVersion = migration.to;
961
- migrated = true;
962
- }
963
- }
964
- return { config: raw, migrated, fromVersion };
965
- }
966
- function normalizeScalingRoadmap(raw) {
967
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
968
- const userRoadmap = raw.scalingRoadmap ?? {};
969
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
970
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
971
- userAuto.enabled = raw.rerankerEnabled;
972
- }
973
- raw.scalingRoadmap = {
974
- ...userRoadmap,
975
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
976
- };
977
- }
978
- function normalizeSessionLifecycle(raw) {
979
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
980
- const userSL = raw.sessionLifecycle ?? {};
981
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
982
- }
983
- function normalizeAutoUpdate(raw) {
984
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
985
- const userAU = raw.autoUpdate ?? {};
986
- raw.autoUpdate = { ...defaultAU, ...userAU };
987
- }
988
- async function loadConfig() {
989
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
990
- await mkdir2(dir, { recursive: true });
991
- const configPath = path2.join(dir, "config.json");
992
- if (!existsSync2(configPath)) {
993
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
994
- }
995
- const raw = await readFile2(configPath, "utf-8");
996
- try {
997
- let parsed = JSON.parse(raw);
998
- parsed = migrateLegacyConfig(parsed);
999
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
1000
- if (migrated) {
1001
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
1002
- `);
1003
- try {
1004
- await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
1005
- } catch {
1006
- }
1007
- }
1008
- normalizeScalingRoadmap(migratedCfg);
1009
- normalizeSessionLifecycle(migratedCfg);
1010
- normalizeAutoUpdate(migratedCfg);
1011
- const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
1012
- if (config.dbPath.startsWith("~")) {
1013
- config.dbPath = config.dbPath.replace(/^~/, os.homedir());
1014
- }
1015
- return config;
1016
- } catch {
1017
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1018
- }
1019
- }
1020
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
1021
- var init_config = __esm({
1022
- "src/lib/config.ts"() {
1023
- "use strict";
1024
- EXE_AI_DIR = resolveDataDir();
1025
- DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
1026
- MODELS_DIR = path2.join(EXE_AI_DIR, "models");
1027
- CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
1028
- LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
1029
- CURRENT_CONFIG_VERSION = 1;
1030
- DEFAULT_CONFIG = {
1031
- config_version: CURRENT_CONFIG_VERSION,
1032
- dbPath: DB_PATH,
1033
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
1034
- embeddingDim: 1024,
1035
- batchSize: 20,
1036
- flushIntervalMs: 1e4,
1037
- autoIngestion: true,
1038
- autoRetrieval: true,
1039
- searchMode: "hybrid",
1040
- hookSearchMode: "hybrid",
1041
- fileGrepEnabled: true,
1042
- splashEffect: true,
1043
- consolidationEnabled: true,
1044
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
1045
- consolidationModel: "claude-haiku-4-5-20251001",
1046
- consolidationMaxCallsPerRun: 20,
1047
- selfQueryRouter: true,
1048
- selfQueryModel: "claude-haiku-4-5-20251001",
1049
- rerankerEnabled: true,
1050
- scalingRoadmap: {
1051
- rerankerAutoTrigger: {
1052
- enabled: true,
1053
- broadQueryMinCardinality: 5e4,
1054
- fetchTopK: 150,
1055
- returnTopK: 5
1056
- }
1057
- },
1058
- graphRagEnabled: true,
1059
- wikiEnabled: false,
1060
- wikiUrl: "",
1061
- wikiApiKey: "",
1062
- wikiSyncIntervalMs: 30 * 60 * 1e3,
1063
- wikiWorkspaceMapping: {
1064
- exe: "Executive",
1065
- yoshi: "Engineering",
1066
- mari: "Marketing",
1067
- tom: "Engineering",
1068
- sasha: "Production"
1069
- },
1070
- wikiAutoUpdate: true,
1071
- wikiAutoUpdateThreshold: 0.5,
1072
- wikiAutoUpdateCreateNew: true,
1073
- skillLearning: true,
1074
- skillThreshold: 3,
1075
- skillModel: "claude-haiku-4-5-20251001",
1076
- exeHeartbeat: {
1077
- enabled: true,
1078
- intervalSeconds: 60,
1079
- staleInProgressThresholdHours: 2
1080
- },
1081
- sessionLifecycle: {
1082
- idleKillEnabled: true,
1083
- idleKillTicksRequired: 3,
1084
- idleKillIntercomAckWindowMs: 1e4,
1085
- maxAutoInstances: 10
1086
- },
1087
- autoUpdate: {
1088
- checkOnBoot: true,
1089
- autoInstall: false,
1090
- checkIntervalMs: 24 * 60 * 60 * 1e3
1091
- }
1092
- };
1093
- CONFIG_MIGRATIONS = [
1094
- {
1095
- from: 0,
1096
- to: 1,
1097
- migrate: (cfg) => {
1098
- cfg.config_version = 1;
1099
- return cfg;
1100
- }
1101
- }
1102
- ];
1103
- }
1104
- });
1105
-
1106
- // src/lib/shard-manager.ts
1107
- var shard_manager_exports = {};
1108
- __export(shard_manager_exports, {
1109
- disposeShards: () => disposeShards,
1110
- ensureShardSchema: () => ensureShardSchema,
1111
- getReadyShardClient: () => getReadyShardClient,
1112
- getShardClient: () => getShardClient,
1113
- getShardsDir: () => getShardsDir,
1114
- initShardManager: () => initShardManager,
1115
- isShardingEnabled: () => isShardingEnabled,
1116
- listShards: () => listShards,
1117
- shardExists: () => shardExists
1118
- });
1119
- import path3 from "path";
1120
- import { existsSync as existsSync3, mkdirSync } from "fs";
1121
- import { createClient as createClient2 } from "@libsql/client";
1122
- function initShardManager(encryptionKey) {
1123
- _encryptionKey = encryptionKey;
1124
- if (!existsSync3(SHARDS_DIR)) {
1125
- mkdirSync(SHARDS_DIR, { recursive: true });
1126
- }
1127
- _shardingEnabled = true;
1128
- }
1129
- function isShardingEnabled() {
1130
- return _shardingEnabled;
1131
- }
1132
- function getShardsDir() {
1133
- return SHARDS_DIR;
1134
- }
1135
- function getShardClient(projectName) {
1136
- if (!_encryptionKey) {
1137
- throw new Error("Shard manager not initialized. Call initShardManager() first.");
1138
- }
1139
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1140
- if (!safeName) {
1141
- throw new Error(`Invalid project name for shard: "${projectName}"`);
1142
- }
1143
- const cached = _shards.get(safeName);
1144
- if (cached) return cached;
1145
- const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
1146
- const client = createClient2({
1147
- url: `file:${dbPath}`,
1148
- encryptionKey: _encryptionKey
1149
- });
1150
- _shards.set(safeName, client);
1151
- return client;
1152
- }
1153
- function shardExists(projectName) {
1154
- const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1155
- return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
1156
- }
1157
- function listShards() {
1158
- if (!existsSync3(SHARDS_DIR)) return [];
1159
- const { readdirSync } = __require("fs");
1160
- return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1161
- }
1162
- async function ensureShardSchema(client) {
1163
- await client.execute("PRAGMA journal_mode = WAL");
1164
- await client.execute("PRAGMA busy_timeout = 5000");
1165
- try {
1166
- await client.execute("PRAGMA libsql_vector_search_ef = 128");
1167
- } catch {
1168
- }
1169
- await client.executeMultiple(`
1170
- CREATE TABLE IF NOT EXISTS memories (
1171
- id TEXT PRIMARY KEY,
1172
- agent_id TEXT NOT NULL,
1173
- agent_role TEXT NOT NULL,
1174
- session_id TEXT NOT NULL,
1175
- timestamp TEXT NOT NULL,
1176
- tool_name TEXT NOT NULL,
1177
- project_name TEXT NOT NULL,
1178
- has_error INTEGER NOT NULL DEFAULT 0,
1179
- raw_text TEXT NOT NULL,
1180
- vector F32_BLOB(1024),
1181
- version INTEGER NOT NULL DEFAULT 0
1182
- );
1183
-
1184
- CREATE INDEX IF NOT EXISTS idx_memories_agent ON memories(agent_id);
1185
- CREATE INDEX IF NOT EXISTS idx_memories_timestamp ON memories(timestamp);
1186
- CREATE INDEX IF NOT EXISTS idx_memories_agent_project ON memories(agent_id, project_name);
1187
- `);
1188
- await client.executeMultiple(`
1189
- CREATE VIRTUAL TABLE IF NOT EXISTS memories_fts USING fts5(
1190
- raw_text,
1191
- content='memories',
1192
- content_rowid='rowid'
1193
- );
1194
-
1195
- CREATE TRIGGER IF NOT EXISTS memories_fts_ai AFTER INSERT ON memories BEGIN
1196
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1197
- END;
1198
-
1199
- CREATE TRIGGER IF NOT EXISTS memories_fts_ad AFTER DELETE ON memories BEGIN
1200
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1201
- END;
1202
-
1203
- CREATE TRIGGER IF NOT EXISTS memories_fts_au AFTER UPDATE ON memories BEGIN
1204
- INSERT INTO memories_fts(memories_fts, rowid, raw_text) VALUES('delete', old.rowid, old.raw_text);
1205
- INSERT INTO memories_fts(rowid, raw_text) VALUES (new.rowid, new.raw_text);
1206
- END;
1207
- `);
1208
- for (const col of [
1209
- "ALTER TABLE memories ADD COLUMN task_id TEXT",
1210
- "ALTER TABLE memories ADD COLUMN consolidated INTEGER NOT NULL DEFAULT 0",
1211
- "ALTER TABLE memories ADD COLUMN importance INTEGER DEFAULT 5",
1212
- "ALTER TABLE memories ADD COLUMN status TEXT DEFAULT 'active'",
1213
- "ALTER TABLE memories ADD COLUMN wiki_synced INTEGER DEFAULT 0",
1214
- "ALTER TABLE memories ADD COLUMN graph_extracted INTEGER DEFAULT 0",
1215
- "ALTER TABLE memories ADD COLUMN content_hash TEXT",
1216
- "ALTER TABLE memories ADD COLUMN graph_extracted_hash TEXT",
1217
- "ALTER TABLE memories ADD COLUMN confidence REAL DEFAULT 0.7",
1218
- "ALTER TABLE memories ADD COLUMN last_accessed TEXT",
1219
- // Wiki linkage columns (must match database.ts)
1220
- "ALTER TABLE memories ADD COLUMN workspace_id TEXT",
1221
- "ALTER TABLE memories ADD COLUMN document_id TEXT",
1222
- "ALTER TABLE memories ADD COLUMN user_id TEXT",
1223
- "ALTER TABLE memories ADD COLUMN char_offset INTEGER",
1224
- "ALTER TABLE memories ADD COLUMN page_number INTEGER",
1225
- // Source provenance columns (must match database.ts)
1226
- "ALTER TABLE memories ADD COLUMN source_path TEXT",
1227
- "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
1228
- "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
1229
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
1230
- ]) {
1231
- try {
1232
- await client.execute(col);
1233
- } catch {
1234
- }
1235
- }
1236
- for (const idx of [
1237
- "CREATE INDEX IF NOT EXISTS idx_memories_tier ON memories(tier)",
1238
- "CREATE INDEX IF NOT EXISTS idx_memories_supersedes ON memories(supersedes_id) WHERE supersedes_id IS NOT NULL"
1239
- ]) {
1240
- try {
1241
- await client.execute(idx);
1242
- } catch {
1243
- }
1244
- }
1245
- try {
1246
- await client.execute("CREATE INDEX IF NOT EXISTS idx_memories_status ON memories(status)");
1247
- } catch {
1248
- }
1249
- for (const idx of [
1250
- "CREATE INDEX IF NOT EXISTS idx_memories_workspace ON memories(workspace_id)",
1251
- "CREATE INDEX IF NOT EXISTS idx_memories_document ON memories(document_id)",
1252
- "CREATE INDEX IF NOT EXISTS idx_memories_user ON memories(user_id)"
1253
- ]) {
1254
- try {
1255
- await client.execute(idx);
1256
- } catch {
1257
- }
1258
- }
1259
- await client.executeMultiple(`
1260
- CREATE TABLE IF NOT EXISTS entities (
1261
- id TEXT PRIMARY KEY,
1262
- name TEXT NOT NULL,
1263
- type TEXT NOT NULL,
1264
- first_seen TEXT NOT NULL,
1265
- last_seen TEXT NOT NULL,
1266
- properties TEXT DEFAULT '{}',
1267
- UNIQUE(name, type)
1268
- );
1269
-
1270
- CREATE TABLE IF NOT EXISTS relationships (
1271
- id TEXT PRIMARY KEY,
1272
- source_entity_id TEXT NOT NULL,
1273
- target_entity_id TEXT NOT NULL,
1274
- type TEXT NOT NULL,
1275
- weight REAL DEFAULT 1.0,
1276
- timestamp TEXT NOT NULL,
1277
- properties TEXT DEFAULT '{}',
1278
- UNIQUE(source_entity_id, target_entity_id, type)
1279
- );
1280
-
1281
- CREATE TABLE IF NOT EXISTS entity_memories (
1282
- entity_id TEXT NOT NULL,
1283
- memory_id TEXT NOT NULL,
1284
- PRIMARY KEY (entity_id, memory_id)
1285
- );
1286
-
1287
- CREATE TABLE IF NOT EXISTS relationship_memories (
1288
- relationship_id TEXT NOT NULL,
1289
- memory_id TEXT NOT NULL,
1290
- PRIMARY KEY (relationship_id, memory_id)
1291
- );
1292
-
1293
- CREATE INDEX IF NOT EXISTS idx_entities_name ON entities(name);
1294
- CREATE INDEX IF NOT EXISTS idx_entities_type ON entities(type);
1295
- CREATE INDEX IF NOT EXISTS idx_relationships_source ON relationships(source_entity_id);
1296
- CREATE INDEX IF NOT EXISTS idx_relationships_target ON relationships(target_entity_id);
1297
- CREATE INDEX IF NOT EXISTS idx_relationships_type ON relationships(type);
1298
-
1299
- CREATE TABLE IF NOT EXISTS hyperedges (
1300
- id TEXT PRIMARY KEY,
1301
- label TEXT NOT NULL,
1302
- relation TEXT NOT NULL,
1303
- confidence REAL DEFAULT 1.0,
1304
- timestamp TEXT NOT NULL
1305
- );
1306
-
1307
- CREATE TABLE IF NOT EXISTS hyperedge_nodes (
1308
- hyperedge_id TEXT NOT NULL,
1309
- entity_id TEXT NOT NULL,
1310
- PRIMARY KEY (hyperedge_id, entity_id)
1311
- );
1312
- `);
1313
- for (const col of [
1314
- "ALTER TABLE relationships ADD COLUMN confidence REAL DEFAULT 1.0",
1315
- "ALTER TABLE relationships ADD COLUMN confidence_label TEXT DEFAULT 'extracted'"
1316
- ]) {
1317
- try {
1318
- await client.execute(col);
1319
- } catch {
1320
- }
1321
- }
1322
- }
1323
- async function getReadyShardClient(projectName) {
1324
- const client = getShardClient(projectName);
1325
- await ensureShardSchema(client);
1326
- return client;
1327
- }
1328
- function disposeShards() {
1329
- for (const [, client] of _shards) {
1330
- client.close();
1331
- }
1332
- _shards.clear();
1333
- _shardingEnabled = false;
1334
- _encryptionKey = null;
1335
- }
1336
- var SHARDS_DIR, _shards, _encryptionKey, _shardingEnabled;
1337
- var init_shard_manager = __esm({
1338
- "src/lib/shard-manager.ts"() {
1339
- "use strict";
1340
- init_config();
1341
- SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
1342
- _shards = /* @__PURE__ */ new Map();
1343
- _encryptionKey = null;
1344
- _shardingEnabled = false;
1345
- }
1346
- });
1347
-
1348
- // src/lib/store.ts
1349
- var store_exports = {};
1350
- __export(store_exports, {
1351
- attachDocumentMetadata: () => attachDocumentMetadata,
1352
- buildWikiScopeFilter: () => buildWikiScopeFilter,
1353
- classifyTier: () => classifyTier,
1354
- disposeStore: () => disposeStore,
1355
- flushBatch: () => flushBatch,
1356
- flushTier3: () => flushTier3,
1357
- getMemoryCardinality: () => getMemoryCardinality,
1358
- initStore: () => initStore,
1359
- reserveVersions: () => reserveVersions,
1360
- searchMemories: () => searchMemories,
1361
- updateMemoryStatus: () => updateMemoryStatus,
1362
- vectorToBlob: () => vectorToBlob,
1363
- writeMemory: () => writeMemory
1364
- });
1365
- async function initStore(options) {
1366
- if (_flushTimer !== null) {
1367
- clearInterval(_flushTimer);
1368
- _flushTimer = null;
1369
- }
1370
- _pendingRecords = [];
1371
- _flushing = false;
1372
- _batchSize = options?.batchSize ?? 20;
1373
- _flushIntervalMs = options?.flushIntervalMs ?? 1e4;
1374
- let dbPath = options?.dbPath;
1375
- if (!dbPath) {
1376
- const config = await loadConfig();
1377
- dbPath = config.dbPath;
1378
- }
1379
- let masterKey = options?.masterKey ?? null;
1380
- if (!masterKey) {
1381
- masterKey = await getMasterKey();
1382
- if (!masterKey) {
1383
- throw new Error(
1384
- "No encryption key found. Run /exe-setup to generate one."
1385
- );
1386
- }
1387
- }
1388
- const hexKey = masterKey.toString("hex");
1389
- await initTurso({
1390
- dbPath,
1391
- encryptionKey: hexKey
1392
- });
1393
- await ensureSchema();
1394
- try {
1395
- const { initShardManager: initShardManager2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
1396
- initShardManager2(hexKey);
1397
- } catch {
1398
- }
1399
- const client = getClient();
1400
- const vResult = await client.execute("SELECT MAX(version) as max_v FROM memories");
1401
- _nextVersion = (Number(vResult.rows[0]?.max_v) || 0) + 1;
1402
- }
1403
- function classifyTier(record) {
1404
- if (record.tool_name === "commit_to_long_term_memory" && (record.importance ?? 0) >= 8) return 1;
1405
- if (["store_memory", "manual"].includes(record.tool_name ?? "") && (record.importance ?? 0) >= 5) return 2;
1406
- return 3;
1407
- }
1408
- async function writeMemory(record) {
1409
- if (record.vector !== null && record.vector.length !== EMBEDDING_DIM) {
1410
- throw new Error(
1411
- `Expected ${EMBEDDING_DIM}-dim vector, got ${record.vector.length}`
1412
- );
1413
- }
1414
- const dbRow = {
1415
- id: record.id,
1416
- agent_id: record.agent_id,
1417
- agent_role: record.agent_role,
1418
- session_id: record.session_id,
1419
- timestamp: record.timestamp,
1420
- tool_name: record.tool_name,
1421
- project_name: record.project_name,
1422
- has_error: record.has_error ? 1 : 0,
1423
- raw_text: record.raw_text,
1424
- vector: record.vector,
1425
- version: _nextVersion++,
1426
- task_id: record.task_id ?? null,
1427
- importance: record.importance ?? 5,
1428
- status: record.status ?? "active",
1429
- confidence: record.confidence ?? 0.7,
1430
- last_accessed: record.last_accessed ?? record.timestamp,
1431
- workspace_id: record.workspace_id ?? null,
1432
- document_id: record.document_id ?? null,
1433
- user_id: record.user_id ?? null,
1434
- char_offset: record.char_offset ?? null,
1435
- page_number: record.page_number ?? null,
1436
- source_path: record.source_path ?? null,
1437
- source_type: record.source_type ?? null,
1438
- tier: record.tier ?? classifyTier(record),
1439
- supersedes_id: record.supersedes_id ?? null
1440
- };
1441
- _pendingRecords.push(dbRow);
1442
- if (_flushTimer === null) {
1443
- _flushTimer = setInterval(() => {
1444
- void flushBatch();
1445
- }, _flushIntervalMs);
1446
- if (_flushTimer && typeof _flushTimer === "object" && "unref" in _flushTimer) {
1447
- _flushTimer.unref();
1448
- }
1449
- }
1450
- if (_pendingRecords.length >= _batchSize) {
1451
- await flushBatch();
1452
- }
1453
- }
1454
- async function flushBatch() {
1455
- if (_flushing || _pendingRecords.length === 0) return 0;
1456
- _flushing = true;
1457
- try {
1458
- const batch = _pendingRecords.slice(0);
1459
- const buildStmt = (row) => {
1460
- const hasVector = row.vector !== null;
1461
- const taskId = row.task_id ?? null;
1462
- const importance = row.importance ?? 5;
1463
- const status = row.status ?? "active";
1464
- const confidence = row.confidence ?? 0.7;
1465
- const lastAccessed = row.last_accessed ?? row.timestamp;
1466
- const workspaceId = row.workspace_id ?? null;
1467
- const documentId = row.document_id ?? null;
1468
- const userId = row.user_id ?? null;
1469
- const charOffset = row.char_offset ?? null;
1470
- const pageNumber = row.page_number ?? null;
1471
- const sourcePath = row.source_path ?? null;
1472
- const sourceType = row.source_type ?? null;
1473
- const tier = row.tier ?? 3;
1474
- const supersedesId = row.supersedes_id ?? null;
1475
- return {
1476
- sql: hasVector ? `INSERT OR IGNORE INTO memories
1477
- (id, agent_id, agent_role, session_id, timestamp,
1478
- tool_name, project_name,
1479
- has_error, raw_text, vector, version, task_id, importance, status,
1480
- confidence, last_accessed,
1481
- workspace_id, document_id, user_id, char_offset, page_number,
1482
- source_path, source_type, tier, supersedes_id)
1483
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories
1484
- (id, agent_id, agent_role, session_id, timestamp,
1485
- tool_name, project_name,
1486
- has_error, raw_text, vector, version, task_id, importance, status,
1487
- confidence, last_accessed,
1488
- workspace_id, document_id, user_id, char_offset, page_number,
1489
- source_path, source_type, tier, supersedes_id)
1490
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1491
- args: hasVector ? [
1492
- row.id,
1493
- row.agent_id,
1494
- row.agent_role,
1495
- row.session_id,
1496
- row.timestamp,
1497
- row.tool_name,
1498
- row.project_name,
1499
- row.has_error,
1500
- row.raw_text,
1501
- vectorToBlob(row.vector),
1502
- row.version,
1503
- taskId,
1504
- importance,
1505
- status,
1506
- confidence,
1507
- lastAccessed,
1508
- workspaceId,
1509
- documentId,
1510
- userId,
1511
- charOffset,
1512
- pageNumber,
1513
- sourcePath,
1514
- sourceType,
1515
- tier,
1516
- supersedesId
1517
- ] : [
1518
- row.id,
1519
- row.agent_id,
1520
- row.agent_role,
1521
- row.session_id,
1522
- row.timestamp,
1523
- row.tool_name,
1524
- row.project_name,
1525
- row.has_error,
1526
- row.raw_text,
1527
- row.version,
1528
- taskId,
1529
- importance,
1530
- status,
1531
- confidence,
1532
- lastAccessed,
1533
- workspaceId,
1534
- documentId,
1535
- userId,
1536
- charOffset,
1537
- pageNumber,
1538
- sourcePath,
1539
- sourceType,
1540
- tier,
1541
- supersedesId
1542
- ]
1543
- };
1544
- };
1545
- const globalClient = getClient();
1546
- const globalStmts = batch.map(buildStmt);
1547
- await globalClient.batch(globalStmts, "write");
1548
- _pendingRecords.splice(0, batch.length);
1549
- try {
1550
- const { isShardingEnabled: isShardingEnabled2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
1551
- if (isShardingEnabled2()) {
1552
- const byProject = /* @__PURE__ */ new Map();
1553
- for (const row of batch) {
1554
- const proj = row.project_name || "unknown";
1555
- if (!byProject.has(proj)) byProject.set(proj, []);
1556
- byProject.get(proj).push(row);
1557
- }
1558
- for (const [project, rows] of byProject) {
1559
- try {
1560
- const shardClient = await getReadyShardClient2(project);
1561
- const shardStmts = rows.map(buildStmt);
1562
- await shardClient.batch(shardStmts, "write");
1563
- } catch (err) {
1564
- process.stderr.write(
1565
- `[store] Shard write failed for ${project}: ${err instanceof Error ? err.message : String(err)}
1566
- `
1567
- );
1568
- }
1569
- }
1570
- }
1571
- } catch {
1572
- }
1573
- return batch.length;
1574
- } finally {
1575
- _flushing = false;
1576
- }
1577
- }
1578
- function buildWikiScopeFilter(options, columnPrefix) {
1579
- const args = [];
1580
- let clause = "";
1581
- if (options?.workspaceId !== void 0) {
1582
- clause += ` AND ${columnPrefix}workspace_id = ?`;
1583
- args.push(options.workspaceId);
1584
- }
1585
- if (options?.userId === void 0) {
1586
- clause += ` AND ${columnPrefix}user_id IS NULL`;
1587
- } else if (options.userId === null) {
1588
- clause += ` AND ${columnPrefix}user_id IS NULL`;
1589
- } else {
1590
- clause += ` AND (${columnPrefix}user_id = ? OR ${columnPrefix}user_id IS NULL)`;
1591
- args.push(options.userId);
1592
- }
1593
- return { clause, args };
1594
- }
1595
- async function searchMemories(queryVector, agentId, options) {
1596
- let client;
1597
- try {
1598
- const { isShardingEnabled: isShardingEnabled2, shardExists: shardExists2, getReadyShardClient: getReadyShardClient2 } = await Promise.resolve().then(() => (init_shard_manager(), shard_manager_exports));
1599
- if (isShardingEnabled2() && options?.projectName && shardExists2(options.projectName)) {
1600
- client = await getReadyShardClient2(options.projectName);
1601
- } else {
1602
- client = getClient();
1603
- }
1604
- } catch {
1605
- client = getClient();
1606
- }
1607
- const limit = options?.limit ?? 10;
1608
- const statusFilter = options?.includeArchived ? "" : `
1609
- AND COALESCE(status, 'active') = 'active'`;
1610
- let sql = `SELECT id, agent_id, agent_role, session_id, timestamp,
1611
- tool_name, project_name,
1612
- has_error, raw_text, vector, importance, status,
1613
- confidence, last_accessed,
1614
- workspace_id, document_id, user_id,
1615
- char_offset, page_number,
1616
- source_path, source_type
1617
- FROM memories
1618
- WHERE agent_id = ?
1619
- AND vector IS NOT NULL${statusFilter}
1620
- AND COALESCE(confidence, 0.7) >= 0.3`;
1621
- const args = [agentId];
1622
- const scope = buildWikiScopeFilter(options, "");
1623
- sql += scope.clause;
1624
- args.push(...scope.args);
1625
- if (options?.projectName) {
1626
- sql += ` AND project_name = ?`;
1627
- args.push(options.projectName);
1628
- }
1629
- if (options?.toolName) {
1630
- sql += ` AND tool_name = ?`;
1631
- args.push(options.toolName);
1632
- }
1633
- if (options?.hasError !== void 0) {
1634
- sql += ` AND has_error = ?`;
1635
- args.push(options.hasError ? 1 : 0);
1636
- }
1637
- if (options?.since) {
1638
- sql += ` AND timestamp >= ?`;
1639
- args.push(options.since);
1640
- }
1641
- sql += ` ORDER BY vector_distance_cos(vector, vector32(?))`;
1642
- args.push(vectorToBlob(queryVector));
1643
- sql += ` LIMIT ?`;
1644
- args.push(limit);
1645
- const result = await client.execute({ sql, args });
1646
- return result.rows.map((row) => ({
1647
- id: row.id,
1648
- agent_id: row.agent_id,
1649
- agent_role: row.agent_role,
1650
- session_id: row.session_id,
1651
- timestamp: row.timestamp,
1652
- tool_name: row.tool_name,
1653
- project_name: row.project_name,
1654
- has_error: row.has_error === 1,
1655
- raw_text: row.raw_text,
1656
- vector: row.vector == null ? [] : Array.isArray(row.vector) ? row.vector : Array.from(row.vector),
1657
- importance: row.importance ?? 5,
1658
- status: row.status ?? "active",
1659
- confidence: row.confidence ?? 0.7,
1660
- last_accessed: row.last_accessed ?? row.timestamp,
1661
- workspace_id: row.workspace_id ?? null,
1662
- document_id: row.document_id ?? null,
1663
- user_id: row.user_id ?? null,
1664
- char_offset: row.char_offset ?? null,
1665
- page_number: row.page_number ?? null,
1666
- source_path: row.source_path ?? null,
1667
- source_type: row.source_type ?? null
1668
- }));
1669
- }
1670
- async function attachDocumentMetadata(records) {
1671
- const docIds = [
1672
- ...new Set(
1673
- records.map((r) => r.document_id).filter((id) => typeof id === "string" && id.length > 0)
1674
- )
1675
- ];
1676
- if (docIds.length === 0) return records;
1677
- try {
1678
- const client = getClient();
1679
- const placeholders = docIds.map(() => "?").join(",");
1680
- const result = await client.execute({
1681
- sql: `SELECT id, filename, mime, source_type, uploaded_at
1682
- FROM documents
1683
- WHERE id IN (${placeholders})`,
1684
- args: docIds
1685
- });
1686
- const byId = /* @__PURE__ */ new Map();
1687
- for (const row of result.rows) {
1688
- const id = row.id;
1689
- byId.set(id, {
1690
- document_id: id,
1691
- filename: row.filename,
1692
- mime: row.mime ?? null,
1693
- source_type: row.source_type ?? null,
1694
- uploaded_at: row.uploaded_at
1695
- });
1696
- }
1697
- for (const record of records) {
1698
- if (!record.document_id) continue;
1699
- record.document_metadata = byId.get(record.document_id) ?? null;
1700
- }
1701
- } catch {
1702
- }
1703
- return records;
1704
- }
1705
- async function flushTier3(agentId, options) {
1706
- const client = getClient();
1707
- const maxAge = options?.maxAgeHours ?? 72;
1708
- const cutoff = new Date(Date.now() - maxAge * 36e5).toISOString();
1709
- if (options?.dryRun) {
1710
- const result2 = await client.execute({
1711
- sql: `SELECT COUNT(*) as cnt FROM memories
1712
- WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
1713
- args: [agentId, cutoff]
1714
- });
1715
- return { archived: Number(result2.rows[0]?.cnt ?? 0) };
1716
- }
1717
- const result = await client.execute({
1718
- sql: `UPDATE memories SET status = 'archived'
1719
- WHERE agent_id = ? AND tier = 3 AND status = 'active' AND timestamp < ?`,
1720
- args: [agentId, cutoff]
1721
- });
1722
- return { archived: result.rowsAffected };
1723
- }
1724
- async function disposeStore() {
1725
- if (_flushTimer !== null) {
1726
- clearInterval(_flushTimer);
1727
- _flushTimer = null;
1728
- }
1729
- if (_pendingRecords.length > 0) {
1730
- await flushBatch();
1731
- }
1732
- await disposeTurso();
1733
- _pendingRecords = [];
1734
- _nextVersion = 1;
1735
- }
1736
- function vectorToBlob(vector) {
1737
- const f32 = vector instanceof Float32Array ? vector : new Float32Array(vector);
1738
- return JSON.stringify(Array.from(f32));
1739
- }
1740
- async function updateMemoryStatus(id, status) {
1741
- const client = getClient();
1742
- await client.execute({
1743
- sql: `UPDATE memories SET status = ? WHERE id = ?`,
1744
- args: [status, id]
1745
- });
1746
- }
1747
- function reserveVersions(count) {
1748
- const reserved = [];
1749
- for (let i = 0; i < count; i++) {
1750
- reserved.push(_nextVersion++);
1751
- }
1752
- return reserved;
1753
- }
1754
- async function getMemoryCardinality(agentId) {
1755
- try {
1756
- const client = getClient();
1757
- const result = await client.execute({
1758
- sql: `SELECT COUNT(*) as cnt FROM memories WHERE agent_id = ? AND COALESCE(status, 'active') = 'active'`,
1759
- args: [agentId]
1760
- });
1761
- return Number(result.rows[0]?.cnt) || 0;
1762
- } catch {
1763
- return 0;
1764
- }
1765
- }
1766
- var _pendingRecords, _batchSize, _flushIntervalMs, _flushTimer, _flushing, _nextVersion;
1767
- var init_store = __esm({
1768
- "src/lib/store.ts"() {
1769
- "use strict";
1770
- init_memory();
1771
- init_database();
1772
- init_keychain();
1773
- init_config();
1774
- _pendingRecords = [];
1775
- _batchSize = 20;
1776
- _flushIntervalMs = 1e4;
1777
- _flushTimer = null;
1778
- _flushing = false;
1779
- _nextVersion = 1;
1780
- }
1781
- });
1782
-
1783
- // src/lib/tasks-crud.ts
1784
- var tasks_crud_exports = {};
1785
- __export(tasks_crud_exports, {
1786
- TASK_ALREADY_CLAIMED_PREFIX: () => TASK_ALREADY_CLAIMED_PREFIX,
1787
- checkStaleCompletion: () => checkStaleCompletion,
1788
- createTaskCore: () => createTaskCore,
1789
- deleteTaskCore: () => deleteTaskCore,
1790
- ensureArchitectureDoc: () => ensureArchitectureDoc,
1791
- ensureGitignoreExe: () => ensureGitignoreExe,
1792
- extractParentFromContext: () => extractParentFromContext,
1793
- listTasks: () => listTasks,
1794
- resolveTask: () => resolveTask,
1795
- slugify: () => slugify,
1796
- updateTaskStatus: () => updateTaskStatus,
1797
- writeCheckpoint: () => writeCheckpoint
1798
- });
1799
- import crypto2 from "crypto";
1800
- import path4 from "path";
1801
- import { execSync as execSync2 } from "child_process";
1802
- import { mkdir as mkdir3, writeFile as writeFile3, appendFile } from "fs/promises";
1803
- import { existsSync as existsSync4, readFileSync as readFileSync2 } from "fs";
1804
- async function writeCheckpoint(input) {
1805
- const client = getClient();
1806
- const row = await resolveTask(client, input.taskId);
1807
- const taskId = String(row.id);
1808
- const now = (/* @__PURE__ */ new Date()).toISOString();
1809
- const blockedByIds = [];
1810
- if (row.blocked_by) {
1811
- blockedByIds.push(String(row.blocked_by));
1812
- }
1813
- const checkpoint = {
1814
- step: input.step,
1815
- context_summary: input.contextSummary,
1816
- files_touched: input.filesTouched ?? [],
1817
- blocked_by_ids: blockedByIds,
1818
- last_checkpoint_at: now
1819
- };
1820
- const result = await client.execute({
1821
- sql: `UPDATE tasks SET checkpoint = ?, checkpoint_count = checkpoint_count + 1, updated_at = ? WHERE id = ?`,
1822
- args: [JSON.stringify(checkpoint), now, taskId]
1823
- });
1824
- if (result.rowsAffected === 0) {
1825
- throw new Error(`Checkpoint write failed: task ${taskId} not found`);
1826
- }
1827
- const countResult = await client.execute({
1828
- sql: "SELECT checkpoint_count FROM tasks WHERE id = ?",
1829
- args: [taskId]
1830
- });
1831
- const checkpointCount = Number(countResult.rows[0]?.checkpoint_count ?? 1);
1832
- return { checkpointCount };
1833
- }
1834
- function extractParentFromContext(contextBody) {
1835
- if (!contextBody) return null;
1836
- const match = contextBody.match(
1837
- /Parent task:\s*([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/i
1838
- );
1839
- return match ? match[1].toLowerCase() : null;
1840
- }
1841
- function slugify(title) {
1842
- return title.toLowerCase().replace(/[^a-z0-9-]/g, "-").replace(/-+/g, "-").replace(/^-|-$/g, "");
1843
- }
1844
- async function resolveTask(client, identifier) {
1845
- let result = await client.execute({
1846
- sql: "SELECT * FROM tasks WHERE id = ?",
1847
- args: [identifier]
1848
- });
1849
- if (result.rows.length === 1) return result.rows[0];
1850
- result = await client.execute({
1851
- sql: "SELECT * FROM tasks WHERE task_file LIKE ?",
1852
- args: [`%${identifier}%`]
1853
- });
1854
- if (result.rows.length === 1) return result.rows[0];
1855
- if (result.rows.length > 1) {
1856
- const exact = result.rows.filter(
1857
- (r) => String(r.task_file).endsWith(`/${identifier}.md`)
1858
- );
1859
- if (exact.length === 1) return exact[0];
1860
- const candidates = exact.length > 1 ? exact : result.rows;
1861
- const active = candidates.filter(
1862
- (r) => !["done", "cancelled"].includes(String(r.status))
1863
- );
1864
- if (active.length === 1) return active[0];
1865
- const matches = (active.length > 1 ? active : candidates).map((r) => `${String(r.task_file)} (${String(r.status)}, ${String(r.id)})`).join(", ");
1866
- throw new Error(
1867
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1868
- );
1869
- }
1870
- result = await client.execute({
1871
- sql: "SELECT * FROM tasks WHERE title LIKE ?",
1872
- args: [`%${identifier}%`]
1873
- });
1874
- if (result.rows.length === 1) return result.rows[0];
1875
- if (result.rows.length > 1) {
1876
- const active = result.rows.filter(
1877
- (r) => !["done", "cancelled"].includes(String(r.status))
1878
- );
1879
- if (active.length === 1) return active[0];
1880
- const matches = (active.length > 1 ? active : result.rows).map((r) => `"${String(r.title)}" (${String(r.status)}, ${String(r.id)})`).join(", ");
1881
- throw new Error(
1882
- `Multiple tasks match "${identifier}": ${matches}. Use a UUID to disambiguate.`
1883
- );
1884
- }
1885
- throw new Error(`Task not found: ${identifier}`);
1886
- }
1887
- async function createTaskCore(input) {
1888
- const client = getClient();
1889
- const id = crypto2.randomUUID();
1890
- const now = (/* @__PURE__ */ new Date()).toISOString();
1891
- const slug = slugify(input.title);
1892
- const taskFile = input.taskFile ?? `exe/${input.assignedTo}/${slug}.md`;
1893
- let blockedById = null;
1894
- const initialStatus = input.blockedBy ? "blocked" : "open";
1895
- if (input.blockedBy) {
1896
- const blocker = await resolveTask(client, input.blockedBy);
1897
- blockedById = String(blocker.id);
1898
- }
1899
- let parentTaskId = null;
1900
- let parentRef = input.parentTaskId;
1901
- if (!parentRef) {
1902
- const extracted = extractParentFromContext(input.context);
1903
- if (extracted) {
1904
- parentRef = extracted;
1905
- process.stderr.write(
1906
- "[create_task] auto-populated parent_task_id from context body \u2014 dispatchers should pass parent_task_id explicitly\n"
1907
- );
1908
- }
1909
- }
1910
- if (parentRef) {
1911
- try {
1912
- const parent = await resolveTask(client, parentRef);
1913
- parentTaskId = String(parent.id);
1914
- } catch (err) {
1915
- if (!input.parentTaskId) {
1916
- throw new Error(
1917
- `create_task: parent reference "${parentRef}" in context body does not resolve to an existing task`
1918
- );
1919
- }
1920
- throw err;
1921
- }
1922
- }
1923
- let warning;
1924
- const dupCheck = await client.execute({
1925
- sql: "SELECT id FROM tasks WHERE title = ? AND assigned_to = ? AND status IN ('open', 'in_progress', 'blocked')",
1926
- args: [input.title, input.assignedTo]
1927
- });
1928
- if (dupCheck.rows.length > 0) {
1929
- warning = `similar active task already exists (${String(dupCheck.rows[0].id)}). Created new task anyway.`;
1930
- }
1931
- if (input.baseDir) {
1932
- try {
1933
- await mkdir3(path4.join(input.baseDir, "exe", "output"), { recursive: true });
1934
- await mkdir3(path4.join(input.baseDir, "exe", "research"), { recursive: true });
1935
- await ensureArchitectureDoc(input.baseDir, input.projectName);
1936
- await ensureGitignoreExe(input.baseDir);
1937
- } catch {
1938
- }
1939
- }
1940
- const complexity = input.complexity ?? "standard";
1941
- await client.execute({
1942
- sql: `INSERT INTO tasks (id, title, assigned_to, assigned_by, project_name, priority, status, task_file, blocked_by, parent_task_id, reviewer, context, complexity, budget_tokens, budget_fallback_model, tokens_used, tokens_warned_at, created_at, updated_at)
1943
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1944
- args: [
1945
- id,
1946
- input.title,
1947
- input.assignedTo,
1948
- input.assignedBy,
1949
- input.projectName,
1950
- input.priority,
1951
- initialStatus,
1952
- taskFile,
1953
- blockedById,
1954
- parentTaskId,
1955
- input.reviewer ?? null,
1956
- input.context,
1957
- input.budgetTokens ?? null,
1958
- input.budgetFallbackModel ?? null,
1959
- 0,
1960
- null,
1961
- complexity,
1962
- now,
1963
- now
1964
- ]
1965
- });
1966
- return {
1967
- id,
1968
- title: input.title,
1969
- assignedTo: input.assignedTo,
1970
- assignedBy: input.assignedBy,
1971
- projectName: input.projectName,
1972
- priority: input.priority,
1973
- status: initialStatus,
1974
- taskFile,
1975
- createdAt: now,
1976
- updatedAt: now,
1977
- warning,
1978
- budgetTokens: input.budgetTokens ?? null,
1979
- budgetFallbackModel: input.budgetFallbackModel ?? null,
1980
- tokensUsed: 0,
1981
- tokensWarnedAt: null
1982
- };
1983
- }
1984
- async function listTasks(input) {
1985
- const client = getClient();
1986
- const conditions = [];
1987
- const args = [];
1988
- if (input.assignedTo) {
1989
- conditions.push("assigned_to = ?");
1990
- args.push(input.assignedTo);
1991
- }
1992
- if (input.status) {
1993
- conditions.push("status = ?");
1994
- args.push(input.status);
1995
- } else {
1996
- conditions.push("status IN ('open', 'in_progress', 'blocked')");
1997
- }
1998
- if (input.projectName) {
1999
- conditions.push("project_name = ?");
2000
- args.push(input.projectName);
2001
- }
2002
- if (input.priority) {
2003
- conditions.push("priority = ?");
2004
- args.push(input.priority);
2005
- }
2006
- const where = conditions.length > 0 ? `WHERE ${conditions.join(" AND ")}` : "";
2007
- const result = await client.execute({
2008
- sql: `SELECT * FROM tasks ${where} ORDER BY CASE status WHEN 'blocked' THEN 0 WHEN 'in_progress' THEN 1 WHEN 'open' THEN 2 ELSE 3 END, priority ASC, created_at DESC`,
2009
- args
2010
- });
2011
- return result.rows.map((r) => ({
2012
- id: String(r.id),
2013
- title: String(r.title),
2014
- assignedTo: String(r.assigned_to),
2015
- assignedBy: String(r.assigned_by),
2016
- projectName: String(r.project_name),
2017
- priority: String(r.priority),
2018
- status: String(r.status),
2019
- taskFile: String(r.task_file),
2020
- createdAt: String(r.created_at),
2021
- updatedAt: String(r.updated_at),
2022
- checkpointCount: Number(r.checkpoint_count ?? 0),
2023
- budgetTokens: r.budget_tokens !== null ? Number(r.budget_tokens) : null,
2024
- budgetFallbackModel: r.budget_fallback_model !== null ? String(r.budget_fallback_model) : null,
2025
- tokensUsed: Number(r.tokens_used ?? 0),
2026
- tokensWarnedAt: r.tokens_warned_at !== null ? Number(r.tokens_warned_at) : null
2027
- }));
2028
- }
2029
- function checkStaleCompletion(taskContext, taskCreatedAt) {
2030
- if (!taskContext) return null;
2031
- if (!DELEGATION_KEYWORDS.test(taskContext)) return null;
2032
- try {
2033
- const since = new Date(taskCreatedAt).toISOString();
2034
- const branch = execSync2(
2035
- "git rev-parse --abbrev-ref HEAD 2>/dev/null",
2036
- { encoding: "utf8", timeout: 3e3 }
2037
- ).trim();
2038
- const branchArg = branch && branch !== "HEAD" ? branch : "";
2039
- const commitCount = execSync2(
2040
- `git log --oneline --since="${since}" ${branchArg} 2>/dev/null | wc -l`,
2041
- { encoding: "utf8", timeout: 5e3 }
2042
- ).trim();
2043
- const count = parseInt(commitCount, 10);
2044
- if (count === 0) {
2045
- return "WARNING: task closed with no new commits since creation. Verify work was actually produced.";
2046
- }
2047
- return null;
2048
- } catch {
2049
- return null;
2050
- }
2051
- }
2052
- async function updateTaskStatus(input) {
2053
- const client = getClient();
2054
- const now = (/* @__PURE__ */ new Date()).toISOString();
2055
- const row = await resolveTask(client, input.taskId);
2056
- const taskId = String(row.id);
2057
- const taskFile = String(row.task_file);
2058
- if (input.status === "done" && String(row.assigned_by) === "system" && taskFile.includes("review-")) {
2059
- process.stderr.write(
2060
- `[updateTask] Review task "${String(row.title)}" being marked done (assigned to ${String(row.assigned_to)})
2061
- `
2062
- );
2063
- }
2064
- if (input.status === "done") {
2065
- const existingRow = await client.execute({
2066
- sql: "SELECT context, created_at FROM tasks WHERE id = ?",
2067
- args: [taskId]
2068
- });
2069
- if (existingRow.rows.length > 0) {
2070
- const ctx = existingRow.rows[0];
2071
- const warning = checkStaleCompletion(ctx.context, ctx.created_at);
2072
- if (warning) {
2073
- input.result = input.result ? `\u26A0\uFE0F ${warning}
2074
-
2075
- ${input.result}` : `\u26A0\uFE0F ${warning}`;
2076
- process.stderr.write(`[tasks] ${warning} (task: ${taskId})
2077
- `);
2078
- }
2079
- }
2080
- }
2081
- if (input.status === "in_progress") {
2082
- const tmuxSession = process.env.TMUX_PANE ?? process.env.MY_TMUX_SESSION ?? "unknown";
2083
- const claim = await client.execute({
2084
- sql: `UPDATE tasks
2085
- SET status = 'in_progress', assigned_tmux = ?, updated_at = ?
2086
- WHERE id = ? AND status = 'open'`,
2087
- args: [tmuxSession, now, taskId]
2088
- });
2089
- if (claim.rowsAffected === 0) {
2090
- const current = await client.execute({
2091
- sql: "SELECT status, assigned_tmux FROM tasks WHERE id = ?",
2092
- args: [taskId]
2093
- });
2094
- const cur = current.rows[0];
2095
- const status = cur?.status ?? "unknown";
2096
- const claimedBy = cur?.assigned_tmux ? ` (claimed by ${cur.assigned_tmux})` : "";
2097
- throw new Error(`${TASK_ALREADY_CLAIMED_PREFIX}: task ${taskId} is ${status}${claimedBy}`);
2098
- }
2099
- try {
2100
- await writeCheckpoint({
2101
- taskId,
2102
- step: "claimed",
2103
- contextSummary: `Task claimed by session. Transitioning open \u2192 in_progress.`
2104
- });
2105
- } catch {
2106
- }
2107
- return { row, taskFile, now, taskId };
2108
- }
2109
- if (input.result) {
2110
- await client.execute({
2111
- sql: "UPDATE tasks SET status = ?, result = ?, updated_at = ? WHERE id = ?",
2112
- args: [input.status, input.result, now, taskId]
2113
- });
2114
- } else {
2115
- await client.execute({
2116
- sql: "UPDATE tasks SET status = ?, updated_at = ? WHERE id = ?",
2117
- args: [input.status, now, taskId]
2118
- });
2119
- }
2120
- try {
2121
- await writeCheckpoint({
2122
- taskId,
2123
- step: `status_transition:${input.status}`,
2124
- contextSummary: input.result ? `Transitioned to ${input.status}. Result: ${input.result.slice(0, 500)}` : `Transitioned to ${input.status}.`
2125
- });
2126
- } catch {
2127
- }
2128
- return { row, taskFile, now, taskId };
2129
- }
2130
- async function deleteTaskCore(taskId, _baseDir) {
2131
- const client = getClient();
2132
- const row = await resolveTask(client, taskId);
2133
- const id = String(row.id);
2134
- const taskFile = String(row.task_file);
2135
- const assignedTo = String(row.assigned_to);
2136
- const assignedBy = String(row.assigned_by);
2137
- await client.execute({ sql: "DELETE FROM tasks WHERE id = ?", args: [id] });
2138
- const taskSlug = taskFile.split("/").pop()?.replace(".md", "") ?? "";
2139
- return { taskFile, assignedTo, assignedBy, taskSlug };
2140
- }
2141
- async function ensureArchitectureDoc(baseDir, projectName) {
2142
- const archPath = path4.join(baseDir, "exe", "ARCHITECTURE.md");
2143
- try {
2144
- if (existsSync4(archPath)) return;
2145
- const template = [
2146
- `# ${projectName} \u2014 System Architecture`,
2147
- "",
2148
- "> Employees: read this before every task. Update it when you change system structure.",
2149
- `> Last updated: ${(/* @__PURE__ */ new Date()).toISOString().split("T")[0]}`,
2150
- "",
2151
- "## Overview",
2152
- "",
2153
- "<!-- Describe what this system does, its main components, and how they connect. -->",
2154
- "",
2155
- "## Key Components",
2156
- "",
2157
- "<!-- List the major modules, services, or subsystems. -->",
2158
- "",
2159
- "## Data Flow",
2160
- "",
2161
- "<!-- How does data move through the system? What writes where? -->",
2162
- "",
2163
- "## Invariants",
2164
- "",
2165
- "<!-- Rules that must never be violated. What breaks if these are wrong? -->",
2166
- "",
2167
- "## Dependencies",
2168
- "",
2169
- "<!-- What depends on what? If I change X, what else is affected? -->",
2170
- ""
2171
- ].join("\n");
2172
- await writeFile3(archPath, template, "utf-8");
2173
- } catch {
2174
- }
2175
- }
2176
- async function ensureGitignoreExe(baseDir) {
2177
- const gitignorePath = path4.join(baseDir, ".gitignore");
2178
- try {
2179
- if (existsSync4(gitignorePath)) {
2180
- const content = readFileSync2(gitignorePath, "utf-8");
2181
- if (/^\/?exe\/?$/m.test(content)) return;
2182
- await appendFile(gitignorePath, "\n# Employee task assignments (private)\n/exe/\n");
2183
- } else {
2184
- await writeFile3(gitignorePath, "# Employee task assignments (private)\n/exe/\n", "utf-8");
2185
- }
2186
- } catch {
2187
- }
2188
- }
2189
- var DELEGATION_KEYWORDS, TASK_ALREADY_CLAIMED_PREFIX;
2190
- var init_tasks_crud = __esm({
2191
- "src/lib/tasks-crud.ts"() {
2192
- "use strict";
2193
- init_database();
2194
- DELEGATION_KEYWORDS = /parallel|delegate|wave|tom\d*-exe/i;
2195
- TASK_ALREADY_CLAIMED_PREFIX = "TASK_ALREADY_CLAIMED";
2196
- }
2197
- });
2198
-
2199
- // src/adapters/claude/hooks/commit-complete.ts
2200
- import { execSync as execSync3 } from "child_process";
2201
-
2202
- // src/lib/git-task-sweep.ts
2203
- import { execSync } from "child_process";
2204
- var EXACT_UUID_SCORE = 1;
2205
- var TITLE_KEYWORD_SCORE = 0.5;
2206
- var FILE_PATH_SCORE = 0.3;
2207
- var MIN_KEYWORD_OVERLAP = 3;
2208
- var STOP_WORDS = /* @__PURE__ */ new Set([
2209
- "a",
2210
- "an",
2211
- "the",
2212
- "and",
2213
- "or",
2214
- "but",
2215
- "in",
2216
- "on",
2217
- "at",
2218
- "to",
2219
- "for",
2220
- "of",
2221
- "with",
2222
- "by",
2223
- "from",
2224
- "is",
2225
- "it",
2226
- "as",
2227
- "be",
2228
- "was",
2229
- "are",
2230
- "this",
2231
- "that",
2232
- "not",
2233
- "no",
2234
- "if",
2235
- "so",
2236
- "do",
2237
- "up"
2238
- ]);
2239
- function extractKeywords(text) {
2240
- return text.toLowerCase().replace(/[^a-z0-9\s-]/g, " ").split(/\s+/).filter((w) => w.length >= 3 && !STOP_WORDS.has(w));
2241
- }
2242
- function matchScore(task, commitMessage, changedFiles) {
2243
- if (task.id.length >= 8 && commitMessage.includes(task.id)) {
2244
- return EXACT_UUID_SCORE;
2245
- }
2246
- let score = 0;
2247
- const titleWords = extractKeywords(task.title);
2248
- const commitWords = new Set(extractKeywords(commitMessage));
2249
- const overlap = titleWords.filter((w) => commitWords.has(w));
2250
- if (overlap.length >= MIN_KEYWORD_OVERLAP) {
2251
- score += TITLE_KEYWORD_SCORE;
2252
- }
2253
- if (task.context && changedFiles.length > 0) {
2254
- const contextLower = task.context.toLowerCase();
2255
- const hasFileMatch = changedFiles.some(
2256
- (f) => contextLower.includes(f.toLowerCase())
2257
- );
2258
- if (hasFileMatch) {
2259
- score += FILE_PATH_SCORE;
2260
- }
2261
- }
2262
- return score;
2263
- }
2264
-
2265
- // src/adapters/claude/hooks/commit-complete.ts
2266
- var AUTO_CLOSE_THRESHOLD = 0.6;
2267
- function parseGitCommitOutput(output) {
2268
- const match = output.match(/\[(\S+)\s+([a-f0-9]{7,40})\]\s+(.+)/);
2269
- if (!match) return null;
2270
- return {
2271
- hash: match[2],
2272
- message: match[3].trim()
2273
- };
2274
- }
2275
- function getChangedFiles(hash) {
2276
- try {
2277
- const output = execSync3(
2278
- `git diff-tree --no-commit-id --name-only -r ${hash}`,
2279
- { encoding: "utf8", timeout: 5e3 }
2280
- );
2281
- return output.trim().split("\n").filter(Boolean);
2282
- } catch {
2283
- return [];
2284
- }
2285
- }
2286
- async function main() {
2287
- const commitHash = process.env.COMMIT_HASH;
2288
- const commitMessage = process.env.COMMIT_MESSAGE;
2289
- const agentId = process.env.AGENT_ID;
2290
- const projectName = process.env.PROJECT_NAME;
2291
- if (!commitHash || !commitMessage || !agentId) {
2292
- process.stderr.write("[commit-complete] Missing required env vars\n");
2293
- return;
2294
- }
2295
- const changedFiles = getChangedFiles(commitHash);
2296
- try {
2297
- const { initStore: initStore2 } = await Promise.resolve().then(() => (init_store(), store_exports));
2298
- await initStore2();
2299
- } catch {
2300
- process.stderr.write("[commit-complete] DB init failed \u2014 skipping\n");
2301
- return;
2302
- }
2303
- const { listTasks: listTasks2, updateTaskStatus: updateTaskStatus2 } = await Promise.resolve().then(() => (init_tasks_crud(), tasks_crud_exports));
2304
- const tasks = await listTasks2({
2305
- assignedTo: agentId,
2306
- status: "in_progress",
2307
- ...projectName ? { projectName } : {}
2308
- });
2309
- if (tasks.length === 0) return;
2310
- const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
2311
- const client = getClient2();
2312
- const tasksWithContext = [];
2313
- for (const t of tasks) {
2314
- let context;
2315
- try {
2316
- const result = await client.execute({
2317
- sql: "SELECT context FROM tasks WHERE id = ?",
2318
- args: [t.id]
2319
- });
2320
- context = result.rows[0]?.context ? String(result.rows[0].context) : void 0;
2321
- } catch {
2322
- }
2323
- tasksWithContext.push({
2324
- id: t.id,
2325
- title: t.title,
2326
- assignedTo: t.assignedTo,
2327
- projectName: t.projectName,
2328
- status: t.status,
2329
- context
2330
- });
2331
- }
2332
- for (const task of tasksWithContext) {
2333
- const score = matchScore(task, commitMessage, changedFiles);
2334
- if (score >= AUTO_CLOSE_THRESHOLD) {
2335
- try {
2336
- await updateTaskStatus2({
2337
- taskId: task.id,
2338
- status: "done",
2339
- result: `Auto-completed via commit ${commitHash}: ${commitMessage}`
2340
- });
2341
- process.stderr.write(
2342
- `[commit-complete] Task ${task.id} auto-closed by commit ${commitHash} (score: ${score.toFixed(2)})
2343
- `
2344
- );
2345
- } catch (err) {
2346
- process.stderr.write(
2347
- `[commit-complete] Failed to close task ${task.id}: ${err instanceof Error ? err.message : String(err)}
2348
- `
2349
- );
2350
- }
2351
- }
2352
- }
2353
- }
2354
- main().catch((err) => {
2355
- process.stderr.write(
2356
- `[commit-complete] Worker error: ${err instanceof Error ? err.message : String(err)}
2357
- `
2358
- );
2359
- });
2360
- export {
2361
- extractKeywords,
2362
- matchScore,
2363
- parseGitCommitOutput
2364
- };