@askexenow/exe-os 0.8.80 → 0.8.82

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 (110) hide show
  1. package/dist/bin/backfill-conversations.js +359 -267
  2. package/dist/bin/backfill-responses.js +357 -265
  3. package/dist/bin/backfill-vectors.js +339 -264
  4. package/dist/bin/cleanup-stale-review-tasks.js +315 -256
  5. package/dist/bin/cli.js +494 -240
  6. package/dist/bin/exe-agent.js +141 -46
  7. package/dist/bin/exe-assign.js +151 -63
  8. package/dist/bin/exe-boot.js +294 -115
  9. package/dist/bin/exe-call.js +76 -51
  10. package/dist/bin/exe-cloud.js +58 -45
  11. package/dist/bin/exe-dispatch.js +434 -277
  12. package/dist/bin/exe-doctor.js +317 -246
  13. package/dist/bin/exe-export-behaviors.js +328 -248
  14. package/dist/bin/exe-forget.js +314 -231
  15. package/dist/bin/exe-gateway.js +2676 -1402
  16. package/dist/bin/exe-heartbeat.js +329 -264
  17. package/dist/bin/exe-kill.js +324 -244
  18. package/dist/bin/exe-launch-agent.js +574 -463
  19. package/dist/bin/exe-link.js +1055 -95
  20. package/dist/bin/exe-new-employee.js +49 -54
  21. package/dist/bin/exe-pending-messages.js +310 -253
  22. package/dist/bin/exe-pending-notifications.js +299 -228
  23. package/dist/bin/exe-pending-reviews.js +314 -245
  24. package/dist/bin/exe-rename.js +259 -195
  25. package/dist/bin/exe-review.js +140 -64
  26. package/dist/bin/exe-search.js +543 -356
  27. package/dist/bin/exe-session-cleanup.js +463 -382
  28. package/dist/bin/exe-settings.js +129 -99
  29. package/dist/bin/exe-start.sh +6 -6
  30. package/dist/bin/exe-status.js +95 -36
  31. package/dist/bin/exe-team.js +116 -51
  32. package/dist/bin/git-sweep.js +482 -307
  33. package/dist/bin/graph-backfill.js +357 -245
  34. package/dist/bin/graph-export.js +324 -244
  35. package/dist/bin/install.js +33 -10
  36. package/dist/bin/scan-tasks.js +481 -307
  37. package/dist/bin/setup.js +1147 -140
  38. package/dist/bin/shard-migrate.js +321 -241
  39. package/dist/bin/update.js +1 -7
  40. package/dist/bin/wiki-sync.js +318 -238
  41. package/dist/gateway/index.js +2656 -1383
  42. package/dist/hooks/bug-report-worker.js +641 -472
  43. package/dist/hooks/commit-complete.js +482 -307
  44. package/dist/hooks/error-recall.js +363 -135
  45. package/dist/hooks/exe-heartbeat-hook.js +97 -27
  46. package/dist/hooks/ingest-worker.js +584 -397
  47. package/dist/hooks/ingest.js +123 -58
  48. package/dist/hooks/instructions-loaded.js +212 -82
  49. package/dist/hooks/notification.js +200 -70
  50. package/dist/hooks/post-compact.js +199 -81
  51. package/dist/hooks/pre-compact.js +352 -140
  52. package/dist/hooks/pre-tool-use.js +416 -278
  53. package/dist/hooks/prompt-ingest-worker.js +376 -299
  54. package/dist/hooks/prompt-submit.js +414 -188
  55. package/dist/hooks/response-ingest-worker.js +408 -338
  56. package/dist/hooks/session-end.js +209 -83
  57. package/dist/hooks/session-start.js +382 -158
  58. package/dist/hooks/stop.js +209 -83
  59. package/dist/hooks/subagent-stop.js +209 -85
  60. package/dist/hooks/summary-worker.js +606 -510
  61. package/dist/index.js +2133 -855
  62. package/dist/lib/cloud-sync.js +1175 -184
  63. package/dist/lib/config.js +1 -9
  64. package/dist/lib/consolidation.js +71 -34
  65. package/dist/lib/database.js +166 -14
  66. package/dist/lib/device-registry.js +189 -117
  67. package/dist/lib/embedder.js +6 -10
  68. package/dist/lib/employee-templates.js +134 -39
  69. package/dist/lib/employees.js +30 -7
  70. package/dist/lib/exe-daemon-client.js +5 -7
  71. package/dist/lib/exe-daemon.js +514 -152
  72. package/dist/lib/hybrid-search.js +543 -356
  73. package/dist/lib/identity-templates.js +15 -15
  74. package/dist/lib/identity.js +19 -15
  75. package/dist/lib/license.js +1 -7
  76. package/dist/lib/messaging.js +157 -135
  77. package/dist/lib/reminders.js +97 -0
  78. package/dist/lib/schedules.js +302 -231
  79. package/dist/lib/skill-learning.js +33 -27
  80. package/dist/lib/status-brief.js +11 -14
  81. package/dist/lib/store.js +326 -237
  82. package/dist/lib/task-router.js +105 -1
  83. package/dist/lib/tasks.js +233 -116
  84. package/dist/lib/tmux-routing.js +173 -56
  85. package/dist/lib/ws-client.js +13 -3
  86. package/dist/mcp/server.js +2009 -1015
  87. package/dist/mcp/tools/complete-reminder.js +97 -0
  88. package/dist/mcp/tools/create-reminder.js +97 -0
  89. package/dist/mcp/tools/create-task.js +426 -262
  90. package/dist/mcp/tools/deactivate-behavior.js +119 -44
  91. package/dist/mcp/tools/list-reminders.js +97 -0
  92. package/dist/mcp/tools/list-tasks.js +56 -57
  93. package/dist/mcp/tools/send-message.js +206 -143
  94. package/dist/mcp/tools/update-task.js +259 -85
  95. package/dist/runtime/index.js +495 -316
  96. package/dist/tui/App.js +1128 -919
  97. package/package.json +2 -10
  98. package/src/commands/exe/afk.md +8 -8
  99. package/src/commands/exe/assign.md +1 -1
  100. package/src/commands/exe/build-adv.md +1 -1
  101. package/src/commands/exe/call.md +10 -10
  102. package/src/commands/exe/employee-heartbeat.md +9 -6
  103. package/src/commands/exe/heartbeat.md +5 -5
  104. package/src/commands/exe/intercom.md +26 -15
  105. package/src/commands/exe/launch.md +2 -2
  106. package/src/commands/exe/new-employee.md +1 -1
  107. package/src/commands/exe/review.md +2 -2
  108. package/src/commands/exe/schedule.md +1 -1
  109. package/src/commands/exe/sessions.md +2 -2
  110. package/src/commands/exe.md +22 -20
@@ -48,7 +48,7 @@ function wrapWithRetry(client) {
48
48
  return (sql) => retryOnBusy(() => target.execute(sql), "execute");
49
49
  }
50
50
  if (prop === "batch") {
51
- return (stmts) => retryOnBusy(() => target.batch(stmts), "batch");
51
+ return (stmts, mode) => retryOnBusy(() => target.batch(stmts, mode), "batch");
52
52
  }
53
53
  return Reflect.get(target, prop, receiver);
54
54
  }
@@ -64,6 +64,226 @@ var init_db_retry = __esm({
64
64
  }
65
65
  });
66
66
 
67
+ // src/lib/config.ts
68
+ import { readFile, writeFile, mkdir, chmod } from "fs/promises";
69
+ import { readFileSync, existsSync, renameSync } from "fs";
70
+ import path from "path";
71
+ import os from "os";
72
+ function resolveDataDir() {
73
+ if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
74
+ if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
75
+ const newDir = path.join(os.homedir(), ".exe-os");
76
+ const legacyDir = path.join(os.homedir(), ".exe-mem");
77
+ if (!existsSync(newDir) && existsSync(legacyDir)) {
78
+ try {
79
+ renameSync(legacyDir, newDir);
80
+ process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
81
+ `);
82
+ } catch {
83
+ return legacyDir;
84
+ }
85
+ }
86
+ return newDir;
87
+ }
88
+ function migrateLegacyConfig(raw) {
89
+ if ("r2" in raw) {
90
+ process.stderr.write(
91
+ "[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"
92
+ );
93
+ delete raw.r2;
94
+ }
95
+ if ("syncIntervalMs" in raw) {
96
+ delete raw.syncIntervalMs;
97
+ }
98
+ return raw;
99
+ }
100
+ function migrateConfig(raw) {
101
+ const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
102
+ let currentVersion = fromVersion;
103
+ let migrated = false;
104
+ if (currentVersion > CURRENT_CONFIG_VERSION) {
105
+ return { config: raw, migrated: false, fromVersion };
106
+ }
107
+ for (const migration of CONFIG_MIGRATIONS) {
108
+ if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
109
+ raw = migration.migrate(raw);
110
+ currentVersion = migration.to;
111
+ migrated = true;
112
+ }
113
+ }
114
+ return { config: raw, migrated, fromVersion };
115
+ }
116
+ function normalizeScalingRoadmap(raw) {
117
+ const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
118
+ const userRoadmap = raw.scalingRoadmap ?? {};
119
+ const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
120
+ if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
121
+ userAuto.enabled = raw.rerankerEnabled;
122
+ }
123
+ raw.scalingRoadmap = {
124
+ ...userRoadmap,
125
+ rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
126
+ };
127
+ }
128
+ function normalizeSessionLifecycle(raw) {
129
+ const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
130
+ const userSL = raw.sessionLifecycle ?? {};
131
+ raw.sessionLifecycle = { ...defaultSL, ...userSL };
132
+ }
133
+ function normalizeAutoUpdate(raw) {
134
+ const defaultAU = DEFAULT_CONFIG.autoUpdate;
135
+ const userAU = raw.autoUpdate ?? {};
136
+ raw.autoUpdate = { ...defaultAU, ...userAU };
137
+ }
138
+ async function loadConfig() {
139
+ const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
140
+ await mkdir(dir, { recursive: true });
141
+ const configPath = path.join(dir, "config.json");
142
+ if (!existsSync(configPath)) {
143
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
144
+ }
145
+ const raw = await readFile(configPath, "utf-8");
146
+ try {
147
+ let parsed = JSON.parse(raw);
148
+ parsed = migrateLegacyConfig(parsed);
149
+ const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
150
+ if (migrated) {
151
+ process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
152
+ `);
153
+ try {
154
+ await writeFile(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
155
+ } catch {
156
+ }
157
+ }
158
+ normalizeScalingRoadmap(migratedCfg);
159
+ normalizeSessionLifecycle(migratedCfg);
160
+ normalizeAutoUpdate(migratedCfg);
161
+ const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
162
+ if (config.dbPath.startsWith("~")) {
163
+ config.dbPath = config.dbPath.replace(/^~/, os.homedir());
164
+ }
165
+ return config;
166
+ } catch {
167
+ return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
168
+ }
169
+ }
170
+ var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
171
+ var init_config = __esm({
172
+ "src/lib/config.ts"() {
173
+ "use strict";
174
+ EXE_AI_DIR = resolveDataDir();
175
+ DB_PATH = path.join(EXE_AI_DIR, "memories.db");
176
+ MODELS_DIR = path.join(EXE_AI_DIR, "models");
177
+ CONFIG_PATH = path.join(EXE_AI_DIR, "config.json");
178
+ LEGACY_LANCE_PATH = path.join(EXE_AI_DIR, "local.lance");
179
+ CURRENT_CONFIG_VERSION = 1;
180
+ DEFAULT_CONFIG = {
181
+ config_version: CURRENT_CONFIG_VERSION,
182
+ dbPath: DB_PATH,
183
+ modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
184
+ embeddingDim: 1024,
185
+ batchSize: 20,
186
+ flushIntervalMs: 1e4,
187
+ autoIngestion: true,
188
+ autoRetrieval: true,
189
+ searchMode: "hybrid",
190
+ hookSearchMode: "hybrid",
191
+ fileGrepEnabled: true,
192
+ splashEffect: true,
193
+ consolidationEnabled: true,
194
+ consolidationIntervalMs: 6 * 60 * 60 * 1e3,
195
+ consolidationModel: "claude-haiku-4-5-20251001",
196
+ consolidationMaxCallsPerRun: 20,
197
+ selfQueryRouter: true,
198
+ selfQueryModel: "claude-haiku-4-5-20251001",
199
+ rerankerEnabled: true,
200
+ scalingRoadmap: {
201
+ rerankerAutoTrigger: {
202
+ enabled: true,
203
+ broadQueryMinCardinality: 5e4,
204
+ fetchTopK: 150,
205
+ returnTopK: 5
206
+ }
207
+ },
208
+ graphRagEnabled: true,
209
+ wikiEnabled: false,
210
+ wikiUrl: "",
211
+ wikiApiKey: "",
212
+ wikiSyncIntervalMs: 30 * 60 * 1e3,
213
+ wikiWorkspaceMapping: {},
214
+ wikiAutoUpdate: true,
215
+ wikiAutoUpdateThreshold: 0.5,
216
+ wikiAutoUpdateCreateNew: true,
217
+ skillLearning: true,
218
+ skillThreshold: 3,
219
+ skillModel: "claude-haiku-4-5-20251001",
220
+ exeHeartbeat: {
221
+ enabled: true,
222
+ intervalSeconds: 60,
223
+ staleInProgressThresholdHours: 2
224
+ },
225
+ sessionLifecycle: {
226
+ idleKillEnabled: true,
227
+ idleKillTicksRequired: 3,
228
+ idleKillIntercomAckWindowMs: 1e4,
229
+ maxAutoInstances: 10
230
+ },
231
+ autoUpdate: {
232
+ checkOnBoot: true,
233
+ autoInstall: false,
234
+ checkIntervalMs: 24 * 60 * 60 * 1e3
235
+ }
236
+ };
237
+ CONFIG_MIGRATIONS = [
238
+ {
239
+ from: 0,
240
+ to: 1,
241
+ migrate: (cfg) => {
242
+ cfg.config_version = 1;
243
+ return cfg;
244
+ }
245
+ }
246
+ ];
247
+ }
248
+ });
249
+
250
+ // src/lib/employees.ts
251
+ import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2 } from "fs/promises";
252
+ import { existsSync as existsSync2, symlinkSync, readlinkSync, readFileSync as readFileSync2, renameSync as renameSync2, unlinkSync, writeFileSync } from "fs";
253
+ import { execSync } from "child_process";
254
+ import path2 from "path";
255
+ import os2 from "os";
256
+ function normalizeRole(role) {
257
+ return (role ?? "").trim().toLowerCase();
258
+ }
259
+ function isCoordinatorRole(role) {
260
+ return normalizeRole(role) === normalizeRole(COORDINATOR_ROLE);
261
+ }
262
+ function getCoordinatorEmployee(employees) {
263
+ return employees.find((e) => isCoordinatorRole(e.role));
264
+ }
265
+ function getCoordinatorName(employees = loadEmployeesSync()) {
266
+ return getCoordinatorEmployee(employees)?.name ?? DEFAULT_COORDINATOR_TEMPLATE_NAME;
267
+ }
268
+ function loadEmployeesSync(employeesPath = EMPLOYEES_PATH) {
269
+ if (!existsSync2(employeesPath)) return [];
270
+ try {
271
+ return JSON.parse(readFileSync2(employeesPath, "utf-8"));
272
+ } catch {
273
+ return [];
274
+ }
275
+ }
276
+ var EMPLOYEES_PATH, DEFAULT_COORDINATOR_TEMPLATE_NAME, COORDINATOR_ROLE;
277
+ var init_employees = __esm({
278
+ "src/lib/employees.ts"() {
279
+ "use strict";
280
+ init_config();
281
+ EMPLOYEES_PATH = path2.join(EXE_AI_DIR, "exe-employees.json");
282
+ DEFAULT_COORDINATOR_TEMPLATE_NAME = "exe";
283
+ COORDINATOR_ROLE = "COO";
284
+ }
285
+ });
286
+
67
287
  // src/lib/database.ts
68
288
  import { createClient } from "@libsql/client";
69
289
  async function initDatabase(config) {
@@ -197,22 +417,24 @@ async function ensureSchema() {
197
417
  ON behaviors(agent_id, active);
198
418
  `);
199
419
  try {
420
+ const coordinatorName = getCoordinatorName();
200
421
  const existing = await client.execute({
201
- sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = 'exe'",
202
- args: []
422
+ sql: "SELECT COUNT(*) as cnt FROM behaviors WHERE agent_id = ?",
423
+ args: [coordinatorName]
203
424
  });
204
425
  if (Number(existing.rows[0]?.cnt) === 0) {
205
- await client.executeMultiple(`
206
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
207
- VALUES
208
- (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');
209
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
210
- VALUES
211
- (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');
212
- INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
213
- VALUES
214
- (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');
215
- `);
426
+ const seededAt = "2026-03-25T00:00:00Z";
427
+ for (const [domain, content] of [
428
+ ["workflow", `Don't ask "keep going?" \u2014 just keep executing phases/plans autonomously`],
429
+ ["tool-use", "Always use create_task MCP tool, never write .md files directly for task creation"],
430
+ ["workflow", "Auto-start reviewing when idle and reviews are pending \u2014 never ask founder for permission"]
431
+ ]) {
432
+ await client.execute({
433
+ sql: `INSERT INTO behaviors (id, agent_id, project_name, domain, content, active, created_at, updated_at)
434
+ VALUES (hex(randomblob(16)), ?, NULL, ?, ?, 1, ?, ?)`,
435
+ args: [coordinatorName, domain, content, seededAt, seededAt]
436
+ });
437
+ }
216
438
  }
217
439
  } catch {
218
440
  }
@@ -904,6 +1126,39 @@ async function ensureSchema() {
904
1126
  } catch {
905
1127
  }
906
1128
  }
1129
+ try {
1130
+ await client.execute({
1131
+ sql: `ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0`,
1132
+ args: []
1133
+ });
1134
+ } catch {
1135
+ }
1136
+ try {
1137
+ await client.execute(
1138
+ `CREATE INDEX IF NOT EXISTS idx_memories_draft ON memories(draft) WHERE draft = 1`
1139
+ );
1140
+ } catch {
1141
+ }
1142
+ try {
1143
+ await client.execute({
1144
+ sql: `ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'`,
1145
+ args: []
1146
+ });
1147
+ } catch {
1148
+ }
1149
+ try {
1150
+ await client.execute(
1151
+ `CREATE INDEX IF NOT EXISTS idx_memories_type ON memories(memory_type)`
1152
+ );
1153
+ } catch {
1154
+ }
1155
+ try {
1156
+ await client.execute({
1157
+ sql: `ALTER TABLE memories ADD COLUMN trajectory TEXT`,
1158
+ args: []
1159
+ });
1160
+ } catch {
1161
+ }
907
1162
  }
908
1163
  async function disposeDatabase() {
909
1164
  if (_client) {
@@ -917,6 +1172,7 @@ var init_database = __esm({
917
1172
  "src/lib/database.ts"() {
918
1173
  "use strict";
919
1174
  init_db_retry();
1175
+ init_employees();
920
1176
  _client = null;
921
1177
  _resilientClient = null;
922
1178
  initTurso = initDatabase;
@@ -924,195 +1180,6 @@ var init_database = __esm({
924
1180
  }
925
1181
  });
926
1182
 
927
- // src/lib/config.ts
928
- import { readFile as readFile2, writeFile as writeFile2, mkdir as mkdir2, chmod as chmod2 } from "fs/promises";
929
- import { readFileSync, existsSync as existsSync2, renameSync } from "fs";
930
- import path2 from "path";
931
- import os2 from "os";
932
- function resolveDataDir() {
933
- if (process.env.EXE_OS_DIR) return process.env.EXE_OS_DIR;
934
- if (process.env.EXE_MEM_DIR) return process.env.EXE_MEM_DIR;
935
- const newDir = path2.join(os2.homedir(), ".exe-os");
936
- const legacyDir = path2.join(os2.homedir(), ".exe-mem");
937
- if (!existsSync2(newDir) && existsSync2(legacyDir)) {
938
- try {
939
- renameSync(legacyDir, newDir);
940
- process.stderr.write(`[exe-os] Migrated data directory: ~/.exe-mem \u2192 ~/.exe-os
941
- `);
942
- } catch {
943
- return legacyDir;
944
- }
945
- }
946
- return newDir;
947
- }
948
- function migrateLegacyConfig(raw) {
949
- if ("r2" in raw) {
950
- process.stderr.write(
951
- "[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"
952
- );
953
- delete raw.r2;
954
- }
955
- if ("syncIntervalMs" in raw) {
956
- delete raw.syncIntervalMs;
957
- }
958
- return raw;
959
- }
960
- function migrateConfig(raw) {
961
- const fromVersion = typeof raw.config_version === "number" ? raw.config_version : 0;
962
- let currentVersion = fromVersion;
963
- let migrated = false;
964
- if (currentVersion > CURRENT_CONFIG_VERSION) {
965
- return { config: raw, migrated: false, fromVersion };
966
- }
967
- for (const migration of CONFIG_MIGRATIONS) {
968
- if (currentVersion === migration.from && migration.to <= CURRENT_CONFIG_VERSION) {
969
- raw = migration.migrate(raw);
970
- currentVersion = migration.to;
971
- migrated = true;
972
- }
973
- }
974
- return { config: raw, migrated, fromVersion };
975
- }
976
- function normalizeScalingRoadmap(raw) {
977
- const defaultAuto = DEFAULT_CONFIG.scalingRoadmap.rerankerAutoTrigger;
978
- const userRoadmap = raw.scalingRoadmap ?? {};
979
- const userAuto = userRoadmap.rerankerAutoTrigger ?? {};
980
- if (userAuto.enabled === void 0 && raw.rerankerEnabled !== void 0) {
981
- userAuto.enabled = raw.rerankerEnabled;
982
- }
983
- raw.scalingRoadmap = {
984
- ...userRoadmap,
985
- rerankerAutoTrigger: { ...defaultAuto, ...userAuto }
986
- };
987
- }
988
- function normalizeSessionLifecycle(raw) {
989
- const defaultSL = DEFAULT_CONFIG.sessionLifecycle;
990
- const userSL = raw.sessionLifecycle ?? {};
991
- raw.sessionLifecycle = { ...defaultSL, ...userSL };
992
- }
993
- function normalizeAutoUpdate(raw) {
994
- const defaultAU = DEFAULT_CONFIG.autoUpdate;
995
- const userAU = raw.autoUpdate ?? {};
996
- raw.autoUpdate = { ...defaultAU, ...userAU };
997
- }
998
- async function loadConfig() {
999
- const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
1000
- await mkdir2(dir, { recursive: true });
1001
- const configPath = path2.join(dir, "config.json");
1002
- if (!existsSync2(configPath)) {
1003
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1004
- }
1005
- const raw = await readFile2(configPath, "utf-8");
1006
- try {
1007
- let parsed = JSON.parse(raw);
1008
- parsed = migrateLegacyConfig(parsed);
1009
- const { config: migratedCfg, migrated, fromVersion } = migrateConfig(parsed);
1010
- if (migrated) {
1011
- process.stderr.write(`[exe-os] Config migrated from v${fromVersion} to v${migratedCfg.config_version}
1012
- `);
1013
- try {
1014
- await writeFile2(configPath, JSON.stringify(migratedCfg, null, 2) + "\n");
1015
- } catch {
1016
- }
1017
- }
1018
- normalizeScalingRoadmap(migratedCfg);
1019
- normalizeSessionLifecycle(migratedCfg);
1020
- normalizeAutoUpdate(migratedCfg);
1021
- const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
1022
- if (config.dbPath.startsWith("~")) {
1023
- config.dbPath = config.dbPath.replace(/^~/, os2.homedir());
1024
- }
1025
- return config;
1026
- } catch {
1027
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
1028
- }
1029
- }
1030
- var EXE_AI_DIR, DB_PATH, MODELS_DIR, CONFIG_PATH, LEGACY_LANCE_PATH, CURRENT_CONFIG_VERSION, DEFAULT_CONFIG, CONFIG_MIGRATIONS;
1031
- var init_config = __esm({
1032
- "src/lib/config.ts"() {
1033
- "use strict";
1034
- EXE_AI_DIR = resolveDataDir();
1035
- DB_PATH = path2.join(EXE_AI_DIR, "memories.db");
1036
- MODELS_DIR = path2.join(EXE_AI_DIR, "models");
1037
- CONFIG_PATH = path2.join(EXE_AI_DIR, "config.json");
1038
- LEGACY_LANCE_PATH = path2.join(EXE_AI_DIR, "local.lance");
1039
- CURRENT_CONFIG_VERSION = 1;
1040
- DEFAULT_CONFIG = {
1041
- config_version: CURRENT_CONFIG_VERSION,
1042
- dbPath: DB_PATH,
1043
- modelFile: "jina-embeddings-v5-small-q4_k_m.gguf",
1044
- embeddingDim: 1024,
1045
- batchSize: 20,
1046
- flushIntervalMs: 1e4,
1047
- autoIngestion: true,
1048
- autoRetrieval: true,
1049
- searchMode: "hybrid",
1050
- hookSearchMode: "hybrid",
1051
- fileGrepEnabled: true,
1052
- splashEffect: true,
1053
- consolidationEnabled: true,
1054
- consolidationIntervalMs: 6 * 60 * 60 * 1e3,
1055
- consolidationModel: "claude-haiku-4-5-20251001",
1056
- consolidationMaxCallsPerRun: 20,
1057
- selfQueryRouter: true,
1058
- selfQueryModel: "claude-haiku-4-5-20251001",
1059
- rerankerEnabled: true,
1060
- scalingRoadmap: {
1061
- rerankerAutoTrigger: {
1062
- enabled: true,
1063
- broadQueryMinCardinality: 5e4,
1064
- fetchTopK: 150,
1065
- returnTopK: 5
1066
- }
1067
- },
1068
- graphRagEnabled: true,
1069
- wikiEnabled: false,
1070
- wikiUrl: "",
1071
- wikiApiKey: "",
1072
- wikiSyncIntervalMs: 30 * 60 * 1e3,
1073
- wikiWorkspaceMapping: {
1074
- exe: "Executive",
1075
- yoshi: "Engineering",
1076
- mari: "Marketing",
1077
- tom: "Engineering",
1078
- sasha: "Production"
1079
- },
1080
- wikiAutoUpdate: true,
1081
- wikiAutoUpdateThreshold: 0.5,
1082
- wikiAutoUpdateCreateNew: true,
1083
- skillLearning: true,
1084
- skillThreshold: 3,
1085
- skillModel: "claude-haiku-4-5-20251001",
1086
- exeHeartbeat: {
1087
- enabled: true,
1088
- intervalSeconds: 60,
1089
- staleInProgressThresholdHours: 2
1090
- },
1091
- sessionLifecycle: {
1092
- idleKillEnabled: true,
1093
- idleKillTicksRequired: 3,
1094
- idleKillIntercomAckWindowMs: 1e4,
1095
- maxAutoInstances: 10
1096
- },
1097
- autoUpdate: {
1098
- checkOnBoot: true,
1099
- autoInstall: false,
1100
- checkIntervalMs: 24 * 60 * 60 * 1e3
1101
- }
1102
- };
1103
- CONFIG_MIGRATIONS = [
1104
- {
1105
- from: 0,
1106
- to: 1,
1107
- migrate: (cfg) => {
1108
- cfg.config_version = 1;
1109
- return cfg;
1110
- }
1111
- }
1112
- ];
1113
- }
1114
- });
1115
-
1116
1183
  // src/lib/shard-manager.ts
1117
1184
  var shard_manager_exports = {};
1118
1185
  __export(shard_manager_exports, {
@@ -1126,12 +1193,12 @@ __export(shard_manager_exports, {
1126
1193
  listShards: () => listShards,
1127
1194
  shardExists: () => shardExists
1128
1195
  });
1129
- import path3 from "path";
1130
- import { existsSync as existsSync3, mkdirSync, readdirSync } from "fs";
1196
+ import path4 from "path";
1197
+ import { existsSync as existsSync4, mkdirSync, readdirSync } from "fs";
1131
1198
  import { createClient as createClient2 } from "@libsql/client";
1132
1199
  function initShardManager(encryptionKey) {
1133
1200
  _encryptionKey = encryptionKey;
1134
- if (!existsSync3(SHARDS_DIR)) {
1201
+ if (!existsSync4(SHARDS_DIR)) {
1135
1202
  mkdirSync(SHARDS_DIR, { recursive: true });
1136
1203
  }
1137
1204
  _shardingEnabled = true;
@@ -1152,7 +1219,7 @@ function getShardClient(projectName) {
1152
1219
  }
1153
1220
  const cached = _shards.get(safeName);
1154
1221
  if (cached) return cached;
1155
- const dbPath = path3.join(SHARDS_DIR, `${safeName}.db`);
1222
+ const dbPath = path4.join(SHARDS_DIR, `${safeName}.db`);
1156
1223
  const client = createClient2({
1157
1224
  url: `file:${dbPath}`,
1158
1225
  encryptionKey: _encryptionKey
@@ -1162,10 +1229,10 @@ function getShardClient(projectName) {
1162
1229
  }
1163
1230
  function shardExists(projectName) {
1164
1231
  const safeName = projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
1165
- return existsSync3(path3.join(SHARDS_DIR, `${safeName}.db`));
1232
+ return existsSync4(path4.join(SHARDS_DIR, `${safeName}.db`));
1166
1233
  }
1167
1234
  function listShards() {
1168
- if (!existsSync3(SHARDS_DIR)) return [];
1235
+ if (!existsSync4(SHARDS_DIR)) return [];
1169
1236
  return readdirSync(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
1170
1237
  }
1171
1238
  async function ensureShardSchema(client) {
@@ -1235,7 +1302,11 @@ async function ensureShardSchema(client) {
1235
1302
  "ALTER TABLE memories ADD COLUMN source_path TEXT",
1236
1303
  "ALTER TABLE memories ADD COLUMN source_type TEXT DEFAULT 'text'",
1237
1304
  "ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3",
1238
- "ALTER TABLE memories ADD COLUMN supersedes_id TEXT"
1305
+ "ALTER TABLE memories ADD COLUMN supersedes_id TEXT",
1306
+ // MS-11: draft staging, MS-6a: memory_type, MS-7: trajectory
1307
+ "ALTER TABLE memories ADD COLUMN draft INTEGER DEFAULT 0",
1308
+ "ALTER TABLE memories ADD COLUMN memory_type TEXT DEFAULT 'raw'",
1309
+ "ALTER TABLE memories ADD COLUMN trajectory TEXT"
1239
1310
  ]) {
1240
1311
  try {
1241
1312
  await client.execute(col);
@@ -1347,7 +1418,7 @@ var init_shard_manager = __esm({
1347
1418
  "src/lib/shard-manager.ts"() {
1348
1419
  "use strict";
1349
1420
  init_config();
1350
- SHARDS_DIR = path3.join(EXE_AI_DIR, "shards");
1421
+ SHARDS_DIR = path4.join(EXE_AI_DIR, "shards");
1351
1422
  _shards = /* @__PURE__ */ new Map();
1352
1423
  _encryptionKey = null;
1353
1424
  _shardingEnabled = false;
@@ -1365,26 +1436,26 @@ var init_platform_procedures = __esm({
1365
1436
  title: "What is exe-os \u2014 the operating model every agent must understand",
1366
1437
  domain: "architecture",
1367
1438
  priority: "p0",
1368
- content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO (exe), CTO (yoshi), CMO (mari), engineers (tom), content (sasha). Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
1439
+ content: "Exe OS is an AI employee operating system. A founder runs 5-10 AI agents as a real org: COO, CTO, CMO, engineers, and content production specialists. Each agent has identity, expertise, and experience layers \u2014 persistent memory that makes them better over time. All data is local-first, E2EE, owned by the user. The MCP server is the ONLY data interface \u2014 never access the DB directly."
1369
1440
  },
1370
1441
  {
1371
1442
  title: "Mode 1 \u2014 how exe-os runs inside Claude Code",
1372
1443
  domain: "architecture",
1373
1444
  priority: "p0",
1374
- content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code. The founder opens CC, runs /exe to boot the COO. exe manages employees in tmux sessions. Each exeN is a separate CC window/project. Employees (yoshi, tom, mari) run in their own tmux panes via create_task auto-spawn. The founder talks to exe; exe orchestrates the team. CC is the shell, exe-os is the brain."
1445
+ content: "Mode 1: exe-os runs AS hooks + MCP + skills inside Claude Code. The founder opens CC and boots the COO. The COO manages employees in tmux sessions. Each coordinator session is a separate CC window/project. Employees run in their own tmux panes via create_task auto-spawn. The founder talks to the COO; the COO orchestrates the team. CC is the shell, exe-os is the brain."
1375
1446
  },
1376
1447
  {
1377
- title: "Sessions explained \u2014 what exeN means and how projects work",
1448
+ title: "Sessions explained \u2014 coordinator session names and projects",
1378
1449
  domain: "architecture",
1379
1450
  priority: "p0",
1380
- content: "Each exeN (exe1, exe2, exe3) is an isolated project session. exe1 might be exe-os development, exe2 might be exe-wiki. Each session spawns its own employees: exe1\u2192yoshi-exe1\u2192tom-exe1. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
1451
+ content: "Each coordinator session is an isolated project session. One might be exe-os development, another might be exe-wiki. Each session spawns its own employees using {employee}-{coordinatorSession}. Sessions share the same memory DB but tasks are scoped to the session that created them. A founder can run multiple projects simultaneously. Sessions never interfere with each other."
1381
1452
  },
1382
1453
  // --- Hierarchy and dispatch ---
1383
1454
  {
1384
1455
  title: "Chain of command \u2014 who talks to whom",
1385
1456
  domain: "workflow",
1386
1457
  priority: "p0",
1387
- content: "Founder \u2192 exe (COO) \u2192 yoshi (CTO) / mari (CMO). Yoshi \u2192 tom (engineer). Mari \u2192 sasha (content). Never skip levels: exe never assigns directly to tom. Tom never reports directly to exe. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
1458
+ content: "Founder -> COO -> CTO/CMO. CTO -> engineers. CMO -> content production. Never skip levels: the COO does not bypass managers for specialist work. Specialists report to their manager. If you need cross-team info, use ask_team_memory \u2014 don't read other agents' task folders. Each level owns dispatch downward and review upward."
1388
1459
  },
1389
1460
  {
1390
1461
  title: "Single dispatch path \u2014 create_task only",
@@ -1394,30 +1465,30 @@ var init_platform_procedures = __esm({
1394
1465
  },
1395
1466
  // --- Session isolation ---
1396
1467
  {
1397
- title: "Session scoping \u2014 stay in your exe boundary",
1468
+ title: "Session scoping \u2014 stay in your coordinator boundary",
1398
1469
  domain: "security",
1399
1470
  priority: "p0",
1400
- content: "Session scoping is mandatory. Managers dispatch to workers within their own exe session ONLY. exe1\u2192yoshi-exe1\u2192tom-exe1. exe2\u2192yoshi-exe2\u2192tom2-exe2. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating exe session."
1471
+ content: "Session scoping is mandatory. Managers dispatch to workers within their own coordinator session ONLY. Employee sessions use {employee}-{coordinatorSession}. Cross-session dispatch is blocked by the system. Verify session names before dispatch. Tasks are scoped to the creating coordinator session."
1401
1472
  },
1402
1473
  {
1403
1474
  title: "Session isolation \u2014 never touch another session's work",
1404
1475
  domain: "workflow",
1405
1476
  priority: "p0",
1406
- content: `Sessions are isolated. exeN owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another exe session. (2) Never review work from a different session \u2014 report "belongs to exeN" and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: yoshi-exe1 works ONLY on exe1 tasks. Cross-session work is a system violation.`
1477
+ content: "Sessions are isolated. A coordinator session owns ONLY tasks it dispatched. (1) Never close/update/cancel tasks from another coordinator session. (2) Never review work from a different session \u2014 report that it belongs to another session and skip. (3) Ignore other sessions' items in list_tasks results. (4) Employees inherit session: employee sessions work ONLY on their parent coordinator session's tasks. Cross-session work is a system violation."
1407
1478
  },
1408
1479
  // --- Engineering: session scoping in code ---
1409
1480
  {
1410
1481
  title: "Three-dimensional scoping \u2014 session, project, role \u2014 enforced in every query",
1411
1482
  domain: "architecture",
1412
1483
  priority: "p0",
1413
- content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching current exeN. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ exe sessions simultaneously."
1484
+ content: "Every DB query, notification, review count, and task operation MUST be scoped on 3 dimensions: (1) Session \u2014 filter by session_scope matching the current coordinator session. (2) Project \u2014 filter by project_name. (3) Role \u2014 agents only see data at their hierarchy level. When writing ANY function that touches tasks, reviews, messages, or notifications: always accept a sessionScope parameter and pass it to the SQL WHERE clause. Unscoped queries are bugs. Test by running 2+ coordinator sessions simultaneously."
1414
1485
  },
1415
1486
  // --- Hard constraints ---
1416
1487
  {
1417
1488
  title: "What you CANNOT do in exe-os \u2014 hard constraints",
1418
1489
  domain: "security",
1419
1490
  priority: "p0",
1420
- content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 exe reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
1491
+ content: "NEVER: (1) Access the database directly \u2014 it's SQLCipher encrypted, always fails. Use MCP tools only. (2) Manually spawn tmux sessions \u2014 create_task handles it. (3) Run git checkout main \u2014 agents work in worktrees. (4) Modify another agent's in-progress task. (5) Push to remote \u2014 the COO reviews and pushes. (6) Skip update_task(done) \u2014 it's the ONLY way your work gets reviewed. (7) Run git init."
1421
1492
  },
1422
1493
  // --- Operations ---
1423
1494
  {
@@ -1539,17 +1610,17 @@ ${p.content}`).join("\n\n");
1539
1610
  init_database();
1540
1611
 
1541
1612
  // src/lib/keychain.ts
1542
- import { readFile, writeFile, unlink, mkdir, chmod } from "fs/promises";
1543
- import { existsSync } from "fs";
1544
- import path from "path";
1545
- import os from "os";
1613
+ import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
1614
+ import { existsSync as existsSync3 } from "fs";
1615
+ import path3 from "path";
1616
+ import os3 from "os";
1546
1617
  var SERVICE = "exe-mem";
1547
1618
  var ACCOUNT = "master-key";
1548
1619
  function getKeyDir() {
1549
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path.join(os.homedir(), ".exe-os");
1620
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path3.join(os3.homedir(), ".exe-os");
1550
1621
  }
1551
1622
  function getKeyPath() {
1552
- return path.join(getKeyDir(), "master.key");
1623
+ return path3.join(getKeyDir(), "master.key");
1553
1624
  }
1554
1625
  async function tryKeytar() {
1555
1626
  try {
@@ -1570,11 +1641,11 @@ async function getMasterKey() {
1570
1641
  }
1571
1642
  }
1572
1643
  const keyPath = getKeyPath();
1573
- if (!existsSync(keyPath)) {
1644
+ if (!existsSync3(keyPath)) {
1574
1645
  return null;
1575
1646
  }
1576
1647
  try {
1577
- const content = await readFile(keyPath, "utf-8");
1648
+ const content = await readFile3(keyPath, "utf-8");
1578
1649
  return Buffer.from(content.trim(), "base64");
1579
1650
  } catch {
1580
1651
  return null;
@@ -1738,6 +1809,9 @@ async function flushBatch() {
1738
1809
  const sourceType = row.source_type ?? null;
1739
1810
  const tier = row.tier ?? 3;
1740
1811
  const supersedesId = row.supersedes_id ?? null;
1812
+ const draft = row.draft ? 1 : 0;
1813
+ const memoryType = row.memory_type ?? "raw";
1814
+ const trajectory = row.trajectory ?? null;
1741
1815
  return {
1742
1816
  sql: hasVector ? `INSERT OR IGNORE INTO memories
1743
1817
  (id, agent_id, agent_role, session_id, timestamp,
@@ -1745,15 +1819,15 @@ async function flushBatch() {
1745
1819
  has_error, raw_text, vector, version, task_id, importance, status,
1746
1820
  confidence, last_accessed,
1747
1821
  workspace_id, document_id, user_id, char_offset, page_number,
1748
- source_path, source_type, tier, supersedes_id)
1749
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories
1822
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory)
1823
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, vector32(?), ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)` : `INSERT OR IGNORE INTO memories
1750
1824
  (id, agent_id, agent_role, session_id, timestamp,
1751
1825
  tool_name, project_name,
1752
1826
  has_error, raw_text, vector, version, task_id, importance, status,
1753
1827
  confidence, last_accessed,
1754
1828
  workspace_id, document_id, user_id, char_offset, page_number,
1755
- source_path, source_type, tier, supersedes_id)
1756
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1829
+ source_path, source_type, tier, supersedes_id, draft, memory_type, trajectory)
1830
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)`,
1757
1831
  args: hasVector ? [
1758
1832
  row.id,
1759
1833
  row.agent_id,
@@ -1779,7 +1853,10 @@ async function flushBatch() {
1779
1853
  sourcePath,
1780
1854
  sourceType,
1781
1855
  tier,
1782
- supersedesId
1856
+ supersedesId,
1857
+ draft,
1858
+ memoryType,
1859
+ trajectory
1783
1860
  ] : [
1784
1861
  row.id,
1785
1862
  row.agent_id,
@@ -1804,7 +1881,10 @@ async function flushBatch() {
1804
1881
  sourcePath,
1805
1882
  sourceType,
1806
1883
  tier,
1807
- supersedesId
1884
+ supersedesId,
1885
+ draft,
1886
+ memoryType,
1887
+ trajectory
1808
1888
  ]
1809
1889
  };
1810
1890
  };
@@ -2273,17 +2353,32 @@ async function storeExtraction(client, extraction, memoryId, timestamp) {
2273
2353
  const id = aliasTarget ?? entityId(e.name, e.type);
2274
2354
  const normalizedName = normalizeEntityName(e.name);
2275
2355
  try {
2356
+ const newProps = e.properties ?? {};
2357
+ let mergedPropsJson = JSON.stringify(newProps);
2358
+ if (newProps.provenance) {
2359
+ const existing = await client.execute({
2360
+ sql: "SELECT properties FROM entities WHERE id = ?",
2361
+ args: [aliasTarget ?? id]
2362
+ });
2363
+ const existingProps = existing.rows.length > 0 ? JSON.parse(String(existing.rows[0].properties ?? "{}")) : {};
2364
+ const existingProvenance = Array.isArray(existingProps.provenance) ? existingProps.provenance : existingProps.provenance ? [existingProps.provenance] : [];
2365
+ mergedPropsJson = JSON.stringify({
2366
+ ...existingProps,
2367
+ ...newProps,
2368
+ provenance: [...existingProvenance, newProps.provenance]
2369
+ });
2370
+ }
2276
2371
  if (aliasTarget) {
2277
2372
  await client.execute({
2278
- sql: `UPDATE entities SET last_seen = ? WHERE id = ?`,
2279
- args: [timestamp, aliasTarget]
2373
+ sql: `UPDATE entities SET last_seen = ?, properties = ? WHERE id = ?`,
2374
+ args: [timestamp, mergedPropsJson, aliasTarget]
2280
2375
  });
2281
2376
  } else {
2282
2377
  await client.execute({
2283
- sql: `INSERT INTO entities (id, name, type, first_seen, last_seen)
2284
- VALUES (?, ?, ?, ?, ?)
2285
- ON CONFLICT(name, type) DO UPDATE SET last_seen = ?`,
2286
- args: [id, normalizedName, e.type, timestamp, timestamp, timestamp]
2378
+ sql: `INSERT INTO entities (id, name, type, first_seen, last_seen, properties)
2379
+ VALUES (?, ?, ?, ?, ?, ?)
2380
+ ON CONFLICT(name, type) DO UPDATE SET last_seen = ?, properties = ?`,
2381
+ args: [id, normalizedName, e.type, timestamp, timestamp, mergedPropsJson, timestamp, mergedPropsJson]
2287
2382
  });
2288
2383
  }
2289
2384
  await client.execute({
@@ -2312,12 +2407,27 @@ async function storeExtraction(client, extraction, memoryId, timestamp) {
2312
2407
  VALUES (?, ?, ?, ?, ?)`,
2313
2408
  args: [targetId, r.target, r.targetType, timestamp, timestamp]
2314
2409
  });
2410
+ const relProps = r.properties ?? {};
2411
+ let relPropsJson = JSON.stringify(relProps);
2412
+ if (relProps.provenance) {
2413
+ const existingRels = await client.execute({
2414
+ sql: "SELECT properties FROM relationships WHERE source_entity_id = ? AND target_entity_id = ? AND type = ?",
2415
+ args: [sourceId, targetId, r.relationship]
2416
+ });
2417
+ const existingRelProps = existingRels.rows.length > 0 ? JSON.parse(String(existingRels.rows[0].properties ?? "{}")) : {};
2418
+ const existingProvenance = Array.isArray(existingRelProps.provenance) ? existingRelProps.provenance : existingRelProps.provenance ? [existingRelProps.provenance] : [];
2419
+ relPropsJson = JSON.stringify({
2420
+ ...existingRelProps,
2421
+ ...relProps,
2422
+ provenance: [...existingProvenance, relProps.provenance]
2423
+ });
2424
+ }
2315
2425
  await client.execute({
2316
- sql: `INSERT INTO relationships (id, source_entity_id, target_entity_id, type, weight, timestamp, confidence, confidence_label)
2317
- VALUES (?, ?, ?, ?, 1.0, ?, ?, ?)
2426
+ sql: `INSERT INTO relationships (id, source_entity_id, target_entity_id, type, weight, timestamp, confidence, confidence_label, properties)
2427
+ VALUES (?, ?, ?, ?, 1.0, ?, ?, ?, ?)
2318
2428
  ON CONFLICT(source_entity_id, target_entity_id, type)
2319
2429
  DO UPDATE SET weight = MIN(weight + 0.1, 2.0), timestamp = ?,
2320
- confidence = MAX(confidence, ?), confidence_label = ?`,
2430
+ confidence = MAX(confidence, ?), confidence_label = ?, properties = ?`,
2321
2431
  args: [
2322
2432
  relId,
2323
2433
  sourceId,
@@ -2326,9 +2436,11 @@ async function storeExtraction(client, extraction, memoryId, timestamp) {
2326
2436
  timestamp,
2327
2437
  r.confidence,
2328
2438
  r.confidenceLabel,
2439
+ relPropsJson,
2329
2440
  timestamp,
2330
2441
  r.confidence,
2331
- r.confidenceLabel
2442
+ r.confidenceLabel,
2443
+ relPropsJson
2332
2444
  ]
2333
2445
  });
2334
2446
  const existingRel = await client.execute({