@askexenow/exe-os 0.9.65 → 0.9.67

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 (113) hide show
  1. package/deploy/stack-manifests/v0.9.json +54 -5
  2. package/dist/bin/age-ontology-load.js +61 -0
  3. package/dist/bin/agentic-ontology-backfill.js +4708 -0
  4. package/dist/bin/agentic-reflection-backfill.js +4144 -0
  5. package/dist/bin/{exe-link.js → agentic-semantic-label.js} +1532 -2173
  6. package/dist/bin/backfill-conversations.js +528 -20
  7. package/dist/bin/backfill-responses.js +528 -20
  8. package/dist/bin/backfill-vectors.js +255 -20
  9. package/dist/bin/bulk-sync-postgres.js +4876 -0
  10. package/dist/bin/cleanup-stale-review-tasks.js +529 -21
  11. package/dist/bin/cli.js +3471 -1491
  12. package/dist/bin/exe-agent-config.js +4 -0
  13. package/dist/bin/exe-agent.js +16 -0
  14. package/dist/bin/exe-assign.js +528 -20
  15. package/dist/bin/exe-boot.js +492 -54
  16. package/dist/bin/exe-call.js +16 -0
  17. package/dist/bin/exe-cloud.js +7415 -518
  18. package/dist/bin/exe-dispatch.js +540 -22
  19. package/dist/bin/exe-doctor.js +3404 -1225
  20. package/dist/bin/exe-export-behaviors.js +542 -24
  21. package/dist/bin/exe-forget.js +529 -21
  22. package/dist/bin/exe-gateway.js +595 -25
  23. package/dist/bin/exe-heartbeat.js +541 -24
  24. package/dist/bin/exe-kill.js +529 -21
  25. package/dist/bin/exe-launch-agent.js +2334 -1067
  26. package/dist/bin/exe-new-employee.js +324 -166
  27. package/dist/bin/exe-pending-messages.js +529 -21
  28. package/dist/bin/exe-pending-notifications.js +529 -21
  29. package/dist/bin/exe-pending-reviews.js +529 -21
  30. package/dist/bin/exe-rename.js +529 -21
  31. package/dist/bin/exe-review.js +529 -21
  32. package/dist/bin/exe-search.js +542 -24
  33. package/dist/bin/exe-session-cleanup.js +540 -22
  34. package/dist/bin/exe-settings.js +14 -0
  35. package/dist/bin/exe-start-codex.js +817 -144
  36. package/dist/bin/exe-start-opencode.js +776 -80
  37. package/dist/bin/exe-status.js +529 -21
  38. package/dist/bin/exe-team.js +529 -21
  39. package/dist/bin/git-sweep.js +540 -22
  40. package/dist/bin/graph-backfill.js +580 -21
  41. package/dist/bin/graph-export.js +529 -21
  42. package/dist/bin/graph-layer-benchmark.js +109 -0
  43. package/dist/bin/install.js +420 -289
  44. package/dist/bin/intercom-check.js +540 -22
  45. package/dist/bin/postgres-agentic-reflection-backfill.js +187 -0
  46. package/dist/bin/postgres-agentic-semantic-backfill.js +237 -0
  47. package/dist/bin/scan-tasks.js +540 -22
  48. package/dist/bin/setup.js +790 -206
  49. package/dist/bin/shard-migrate.js +528 -20
  50. package/dist/bin/update.js +4 -0
  51. package/dist/gateway/index.js +593 -23
  52. package/dist/hooks/bug-report-worker.js +651 -64
  53. package/dist/hooks/codex-stop-task-finalizer.js +540 -22
  54. package/dist/hooks/commit-complete.js +540 -22
  55. package/dist/hooks/error-recall.js +542 -24
  56. package/dist/hooks/exe-heartbeat-hook.js +4 -0
  57. package/dist/hooks/ingest-worker.js +4 -0
  58. package/dist/hooks/ingest.js +539 -22
  59. package/dist/hooks/instructions-loaded.js +529 -21
  60. package/dist/hooks/notification.js +529 -21
  61. package/dist/hooks/post-compact.js +529 -21
  62. package/dist/hooks/post-tool-combined.js +543 -25
  63. package/dist/hooks/pre-compact.js +772 -127
  64. package/dist/hooks/pre-tool-use.js +529 -21
  65. package/dist/hooks/prompt-submit.js +543 -25
  66. package/dist/hooks/session-end.js +673 -140
  67. package/dist/hooks/session-start.js +662 -26
  68. package/dist/hooks/stop.js +540 -23
  69. package/dist/hooks/subagent-stop.js +529 -21
  70. package/dist/hooks/summary-worker.js +571 -126
  71. package/dist/index.js +593 -23
  72. package/dist/lib/agent-config.js +4 -0
  73. package/dist/lib/cloud-sync.js +408 -47
  74. package/dist/lib/config.js +25 -1
  75. package/dist/lib/consolidation.js +5 -1
  76. package/dist/lib/database.js +128 -0
  77. package/dist/lib/db-daemon-client.js +4 -0
  78. package/dist/lib/db.js +128 -0
  79. package/dist/lib/device-registry.js +128 -0
  80. package/dist/lib/embedder.js +25 -1
  81. package/dist/lib/employee-templates.js +16 -0
  82. package/dist/lib/employees.js +4 -0
  83. package/dist/lib/exe-daemon-client.js +4 -0
  84. package/dist/lib/exe-daemon.js +3158 -930
  85. package/dist/lib/hybrid-search.js +542 -24
  86. package/dist/lib/identity.js +7 -0
  87. package/dist/lib/keychain.js +178 -22
  88. package/dist/lib/license.js +4 -0
  89. package/dist/lib/messaging.js +7 -0
  90. package/dist/lib/reminders.js +7 -0
  91. package/dist/lib/schedules.js +255 -20
  92. package/dist/lib/skill-learning.js +28 -1
  93. package/dist/lib/status-brief.js +39 -0
  94. package/dist/lib/store.js +528 -20
  95. package/dist/lib/task-router.js +4 -0
  96. package/dist/lib/tasks.js +28 -1
  97. package/dist/lib/tmux-routing.js +28 -1
  98. package/dist/lib/token-spend.js +7 -0
  99. package/dist/mcp/server.js +2739 -813
  100. package/dist/mcp/tools/complete-reminder.js +7 -0
  101. package/dist/mcp/tools/create-reminder.js +7 -0
  102. package/dist/mcp/tools/create-task.js +28 -1
  103. package/dist/mcp/tools/deactivate-behavior.js +7 -0
  104. package/dist/mcp/tools/list-reminders.js +7 -0
  105. package/dist/mcp/tools/list-tasks.js +7 -0
  106. package/dist/mcp/tools/send-message.js +7 -0
  107. package/dist/mcp/tools/update-task.js +28 -1
  108. package/dist/runtime/index.js +540 -22
  109. package/dist/tui/App.js +618 -29
  110. package/package.json +9 -5
  111. package/src/commands/exe/cloud.md +11 -8
  112. package/stack.release.json +3 -3
  113. package/src/commands/exe/link.md +0 -17
@@ -149,6 +149,11 @@ function normalizeAutoUpdate(raw) {
149
149
  const userAU = raw.autoUpdate ?? {};
150
150
  raw.autoUpdate = { ...defaultAU, ...userAU };
151
151
  }
152
+ function normalizeOrchestration(raw) {
153
+ const defaultOrg = DEFAULT_CONFIG.orchestration;
154
+ const userOrg = raw.orchestration ?? {};
155
+ raw.orchestration = { ...defaultOrg, ...userOrg };
156
+ }
152
157
  async function loadConfig() {
153
158
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
154
159
  await ensurePrivateDir(dir);
@@ -173,10 +178,15 @@ async function loadConfig() {
173
178
  normalizeScalingRoadmap(migratedCfg);
174
179
  normalizeSessionLifecycle(migratedCfg);
175
180
  normalizeAutoUpdate(migratedCfg);
181
+ normalizeOrchestration(migratedCfg);
176
182
  const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
177
183
  if (config.dbPath.startsWith("~")) {
178
184
  config.dbPath = config.dbPath.replace(/^~/, os.homedir());
179
185
  }
186
+ const envDbPath = path.join(dir, "memories.db");
187
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync2(config.dbPath) && existsSync2(envDbPath)) {
188
+ config.dbPath = envDbPath;
189
+ }
180
190
  return config;
181
191
  } catch {
182
192
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
@@ -196,7 +206,16 @@ function loadConfigSync() {
196
206
  normalizeScalingRoadmap(migratedCfg);
197
207
  normalizeSessionLifecycle(migratedCfg);
198
208
  normalizeAutoUpdate(migratedCfg);
199
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
209
+ normalizeOrchestration(migratedCfg);
210
+ const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
211
+ if (config.dbPath.startsWith("~")) {
212
+ config.dbPath = config.dbPath.replace(/^~/, os.homedir());
213
+ }
214
+ const envDbPath = path.join(dir, "memories.db");
215
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync2(config.dbPath) && existsSync2(envDbPath)) {
216
+ config.dbPath = envDbPath;
217
+ }
218
+ return config;
200
219
  } catch {
201
220
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
202
221
  }
@@ -217,6 +236,7 @@ async function loadConfigFrom(configPath) {
217
236
  normalizeScalingRoadmap(migratedCfg);
218
237
  normalizeSessionLifecycle(migratedCfg);
219
238
  normalizeAutoUpdate(migratedCfg);
239
+ normalizeOrchestration(migratedCfg);
220
240
  return { ...DEFAULT_CONFIG, ...migratedCfg };
221
241
  } catch {
222
242
  return { ...DEFAULT_CONFIG };
@@ -288,6 +308,10 @@ var init_config = __esm({
288
308
  checkOnBoot: true,
289
309
  autoInstall: false,
290
310
  checkIntervalMs: 24 * 60 * 60 * 1e3
311
+ },
312
+ orchestration: {
313
+ phase: "phase_1_coo",
314
+ phaseSetBy: "default"
291
315
  }
292
316
  };
293
317
  CONFIG_MIGRATIONS = [
@@ -2315,6 +2339,9 @@ function getClient() {
2315
2339
  if (_daemonClient && _daemonClient._isDaemonActive()) {
2316
2340
  return _daemonClient;
2317
2341
  }
2342
+ if (!_resilientClient) {
2343
+ return _adapterClient;
2344
+ }
2318
2345
  return _resilientClient;
2319
2346
  }
2320
2347
  async function initDaemonClient() {
@@ -3347,6 +3374,127 @@ async function ensureSchema() {
3347
3374
  VALUES (new.rowid, new.content, new.subject, new.predicate, new.object);
3348
3375
  END;
3349
3376
  `);
3377
+ await client.executeMultiple(`
3378
+ CREATE TABLE IF NOT EXISTS agent_sessions (
3379
+ id TEXT PRIMARY KEY,
3380
+ agent_id TEXT NOT NULL,
3381
+ project_name TEXT,
3382
+ started_at TEXT NOT NULL,
3383
+ last_event_at TEXT NOT NULL,
3384
+ event_count INTEGER NOT NULL DEFAULT 0,
3385
+ properties TEXT DEFAULT '{}'
3386
+ );
3387
+
3388
+ CREATE INDEX IF NOT EXISTS idx_agent_sessions_agent_time
3389
+ ON agent_sessions(agent_id, started_at);
3390
+
3391
+ CREATE TABLE IF NOT EXISTS agent_goals (
3392
+ id TEXT PRIMARY KEY,
3393
+ statement TEXT NOT NULL,
3394
+ owner_agent_id TEXT,
3395
+ project_name TEXT,
3396
+ status TEXT NOT NULL DEFAULT 'open',
3397
+ priority INTEGER NOT NULL DEFAULT 5,
3398
+ success_criteria TEXT,
3399
+ parent_goal_id TEXT,
3400
+ due_at TEXT,
3401
+ achieved_at TEXT,
3402
+ supersedes_id TEXT,
3403
+ created_at TEXT NOT NULL,
3404
+ updated_at TEXT NOT NULL,
3405
+ source_memory_id TEXT
3406
+ );
3407
+
3408
+ CREATE INDEX IF NOT EXISTS idx_agent_goals_project_status
3409
+ ON agent_goals(project_name, status, priority);
3410
+
3411
+ CREATE TABLE IF NOT EXISTS agent_events (
3412
+ id TEXT PRIMARY KEY,
3413
+ event_type TEXT NOT NULL,
3414
+ occurred_at TEXT NOT NULL,
3415
+ sequence_index INTEGER NOT NULL,
3416
+ actor_agent_id TEXT,
3417
+ agent_role TEXT,
3418
+ project_name TEXT,
3419
+ session_id TEXT,
3420
+ task_id TEXT,
3421
+ goal_id TEXT,
3422
+ parent_event_id TEXT,
3423
+ intention TEXT,
3424
+ outcome TEXT,
3425
+ evidence_memory_id TEXT,
3426
+ impact TEXT,
3427
+ payload TEXT DEFAULT '{}',
3428
+ created_at TEXT NOT NULL
3429
+ );
3430
+
3431
+ CREATE INDEX IF NOT EXISTS idx_agent_events_time
3432
+ ON agent_events(occurred_at, sequence_index);
3433
+
3434
+ CREATE INDEX IF NOT EXISTS idx_agent_events_session_seq
3435
+ ON agent_events(session_id, sequence_index);
3436
+
3437
+ CREATE INDEX IF NOT EXISTS idx_agent_events_goal_time
3438
+ ON agent_events(goal_id, occurred_at);
3439
+
3440
+ CREATE INDEX IF NOT EXISTS idx_agent_events_memory
3441
+ ON agent_events(evidence_memory_id);
3442
+
3443
+ CREATE TABLE IF NOT EXISTS agent_goal_links (
3444
+ id TEXT PRIMARY KEY,
3445
+ goal_id TEXT NOT NULL,
3446
+ link_type TEXT NOT NULL,
3447
+ target_id TEXT NOT NULL,
3448
+ target_type TEXT NOT NULL,
3449
+ created_at TEXT NOT NULL
3450
+ );
3451
+
3452
+ CREATE INDEX IF NOT EXISTS idx_agent_goal_links_goal
3453
+ ON agent_goal_links(goal_id, target_type);
3454
+
3455
+ CREATE TABLE IF NOT EXISTS agent_semantic_labels (
3456
+ id TEXT PRIMARY KEY,
3457
+ source_memory_id TEXT NOT NULL,
3458
+ event_id TEXT,
3459
+ labeler TEXT NOT NULL,
3460
+ schema_version INTEGER NOT NULL DEFAULT 1,
3461
+ confidence REAL NOT NULL DEFAULT 0,
3462
+ labels TEXT NOT NULL,
3463
+ created_at TEXT NOT NULL,
3464
+ updated_at TEXT NOT NULL
3465
+ );
3466
+
3467
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_memory
3468
+ ON agent_semantic_labels(source_memory_id, labeler);
3469
+
3470
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_event
3471
+ ON agent_semantic_labels(event_id);
3472
+
3473
+ CREATE TABLE IF NOT EXISTS agent_reflection_checkpoints (
3474
+ id TEXT PRIMARY KEY,
3475
+ project_name TEXT,
3476
+ session_id TEXT,
3477
+ window_start_at TEXT NOT NULL,
3478
+ window_end_at TEXT NOT NULL,
3479
+ event_count INTEGER NOT NULL DEFAULT 0,
3480
+ goal_count INTEGER NOT NULL DEFAULT 0,
3481
+ success_count INTEGER NOT NULL DEFAULT 0,
3482
+ failure_count INTEGER NOT NULL DEFAULT 0,
3483
+ risk_count INTEGER NOT NULL DEFAULT 0,
3484
+ summary TEXT NOT NULL,
3485
+ learnings TEXT NOT NULL DEFAULT '[]',
3486
+ next_actions TEXT NOT NULL DEFAULT '[]',
3487
+ evidence_event_ids TEXT NOT NULL DEFAULT '[]',
3488
+ confidence REAL NOT NULL DEFAULT 0,
3489
+ created_at TEXT NOT NULL
3490
+ );
3491
+
3492
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_project_time
3493
+ ON agent_reflection_checkpoints(project_name, window_end_at);
3494
+
3495
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_session_time
3496
+ ON agent_reflection_checkpoints(session_id, window_end_at);
3497
+ `);
3350
3498
  try {
3351
3499
  await client.execute({
3352
3500
  sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
@@ -6934,39 +7082,75 @@ var init_task_scope = __esm({
6934
7082
 
6935
7083
  // src/lib/keychain.ts
6936
7084
  import { readFile as readFile4, writeFile as writeFile5, unlink, mkdir as mkdir4, chmod as chmod2 } from "fs/promises";
6937
- import { existsSync as existsSync17 } from "fs";
7085
+ import { existsSync as existsSync18, statSync as statSync3 } from "fs";
6938
7086
  import { execSync as execSync8 } from "child_process";
6939
- import path21 from "path";
7087
+ import path22 from "path";
6940
7088
  import os13 from "os";
6941
7089
  function getKeyDir() {
6942
- return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path21.join(os13.homedir(), ".exe-os");
7090
+ return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path22.join(os13.homedir(), ".exe-os");
6943
7091
  }
6944
7092
  function getKeyPath() {
6945
- return path21.join(getKeyDir(), "master.key");
7093
+ return path22.join(getKeyDir(), "master.key");
7094
+ }
7095
+ function nativeKeychainAllowed() {
7096
+ return process.env.EXE_OS_DISABLE_NATIVE_KEYCHAIN !== "1";
7097
+ }
7098
+ function linuxSecretAvailable() {
7099
+ if (!nativeKeychainAllowed()) return false;
7100
+ if (process.platform !== "linux") return false;
7101
+ if (linuxSecretAvailability !== null) return linuxSecretAvailability;
7102
+ try {
7103
+ execSync8("command -v secret-tool >/dev/null 2>&1", { timeout: 1e3 });
7104
+ } catch {
7105
+ linuxSecretAvailability = false;
7106
+ return false;
7107
+ }
7108
+ try {
7109
+ execSync8("secret-tool search --all exe-os probe >/dev/null 2>&1", { timeout: 1e3 });
7110
+ linuxSecretAvailability = true;
7111
+ } catch {
7112
+ linuxSecretAvailability = false;
7113
+ }
7114
+ return linuxSecretAvailability;
6946
7115
  }
6947
- function macKeychainGet() {
7116
+ function isRootOnlyTrustedServerKeyFile(keyPath) {
7117
+ if (process.platform !== "linux") return false;
7118
+ try {
7119
+ const uid = typeof os13.userInfo().uid === "number" ? os13.userInfo().uid : -1;
7120
+ const st = statSync3(keyPath);
7121
+ if (!st.isFile() || (st.mode & 63) !== 0) return false;
7122
+ if (uid === 0) return true;
7123
+ const exeOsDir = process.env.EXE_OS_DIR;
7124
+ return Boolean(exeOsDir && path22.resolve(keyPath).startsWith(path22.resolve(exeOsDir) + path22.sep));
7125
+ } catch {
7126
+ return false;
7127
+ }
7128
+ }
7129
+ function macKeychainGet(service = SERVICE) {
7130
+ if (!nativeKeychainAllowed()) return null;
6948
7131
  if (process.platform !== "darwin") return null;
6949
7132
  try {
6950
7133
  return execSync8(
6951
- `security find-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w 2>/dev/null`,
7134
+ `security find-generic-password -s "${service}" -a "${ACCOUNT}" -w 2>/dev/null`,
6952
7135
  { encoding: "utf-8", timeout: 5e3 }
6953
7136
  ).trim();
6954
7137
  } catch {
6955
7138
  return null;
6956
7139
  }
6957
7140
  }
6958
- function macKeychainSet(value) {
7141
+ function macKeychainSet(value, service = SERVICE) {
7142
+ if (!nativeKeychainAllowed()) return false;
6959
7143
  if (process.platform !== "darwin") return false;
6960
7144
  try {
6961
7145
  try {
6962
7146
  execSync8(
6963
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
7147
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
6964
7148
  { timeout: 5e3 }
6965
7149
  );
6966
7150
  } catch {
6967
7151
  }
6968
7152
  execSync8(
6969
- `security add-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w "${value}"`,
7153
+ `security add-generic-password -s "${service}" -a "${ACCOUNT}" -w "${value}"`,
6970
7154
  { timeout: 5e3 }
6971
7155
  );
6972
7156
  return true;
@@ -6974,22 +7158,48 @@ function macKeychainSet(value) {
6974
7158
  return false;
6975
7159
  }
6976
7160
  }
6977
- function linuxSecretGet() {
6978
- if (process.platform !== "linux") return null;
7161
+ function macKeychainDelete(service = SERVICE) {
7162
+ if (!nativeKeychainAllowed()) return false;
7163
+ if (process.platform !== "darwin") return false;
7164
+ try {
7165
+ execSync8(
7166
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
7167
+ { timeout: 5e3 }
7168
+ );
7169
+ return true;
7170
+ } catch {
7171
+ return false;
7172
+ }
7173
+ }
7174
+ function linuxSecretGet(service = SERVICE) {
7175
+ if (!linuxSecretAvailable()) return null;
6979
7176
  try {
6980
7177
  return execSync8(
6981
- `secret-tool lookup service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
7178
+ `secret-tool lookup service "${service}" account "${ACCOUNT}" 2>/dev/null`,
6982
7179
  { encoding: "utf-8", timeout: 5e3 }
6983
7180
  ).trim();
6984
7181
  } catch {
6985
7182
  return null;
6986
7183
  }
6987
7184
  }
6988
- function linuxSecretSet(value) {
7185
+ function linuxSecretSet(value, service = SERVICE) {
7186
+ if (!linuxSecretAvailable()) return false;
7187
+ try {
7188
+ execSync8(
7189
+ `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${service}" account "${ACCOUNT}" 2>/dev/null`,
7190
+ { timeout: 5e3 }
7191
+ );
7192
+ return true;
7193
+ } catch {
7194
+ return false;
7195
+ }
7196
+ }
7197
+ function linuxSecretDelete(service = SERVICE) {
7198
+ if (!nativeKeychainAllowed()) return false;
6989
7199
  if (process.platform !== "linux") return false;
6990
7200
  try {
6991
7201
  execSync8(
6992
- `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${SERVICE}" account "${ACCOUNT}"`,
7202
+ `secret-tool clear service "${service}" account "${ACCOUNT}" 2>/dev/null`,
6993
7203
  { timeout: 5e3 }
6994
7204
  );
6995
7205
  return true;
@@ -6998,6 +7208,7 @@ function linuxSecretSet(value) {
6998
7208
  }
6999
7209
  }
7000
7210
  async function tryKeytar() {
7211
+ if (!nativeKeychainAllowed()) return null;
7001
7212
  try {
7002
7213
  return await import("keytar");
7003
7214
  } catch {
@@ -7071,7 +7282,19 @@ async function writeMachineBoundFileFallback(b64) {
7071
7282
  return "plaintext";
7072
7283
  }
7073
7284
  async function getMasterKey() {
7074
- const nativeValue = macKeychainGet() ?? linuxSecretGet();
7285
+ let nativeValue = macKeychainGet() ?? linuxSecretGet();
7286
+ if (!nativeValue) {
7287
+ const legacyValue = macKeychainGet(LEGACY_SERVICE) ?? linuxSecretGet(LEGACY_SERVICE);
7288
+ if (legacyValue) {
7289
+ const migrated = macKeychainSet(legacyValue) || linuxSecretSet(legacyValue);
7290
+ if (migrated) {
7291
+ macKeychainDelete(LEGACY_SERVICE);
7292
+ linuxSecretDelete(LEGACY_SERVICE);
7293
+ process.stderr.write("[keychain] Migrated keychain service from exe-mem to exe-os.\n");
7294
+ }
7295
+ nativeValue = legacyValue;
7296
+ }
7297
+ }
7075
7298
  if (nativeValue) {
7076
7299
  return Buffer.from(nativeValue, "base64");
7077
7300
  }
@@ -7079,18 +7302,23 @@ async function getMasterKey() {
7079
7302
  if (keytar) {
7080
7303
  try {
7081
7304
  const keytarValue = await keytar.getPassword(SERVICE, ACCOUNT);
7082
- if (keytarValue) {
7083
- const migrated = macKeychainSet(keytarValue) || linuxSecretSet(keytarValue);
7305
+ const legacyKeytarValue = keytarValue ?? await keytar.getPassword(LEGACY_SERVICE, ACCOUNT);
7306
+ if (legacyKeytarValue) {
7307
+ const migrated = macKeychainSet(legacyKeytarValue) || linuxSecretSet(legacyKeytarValue);
7084
7308
  if (migrated) {
7085
7309
  process.stderr.write("[keychain] Migrated key from keytar to native keychain.\n");
7310
+ try {
7311
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
7312
+ } catch {
7313
+ }
7086
7314
  }
7087
- return Buffer.from(keytarValue, "base64");
7315
+ return Buffer.from(legacyKeytarValue, "base64");
7088
7316
  }
7089
7317
  } catch {
7090
7318
  }
7091
7319
  }
7092
7320
  const keyPath = getKeyPath();
7093
- if (!existsSync17(keyPath)) {
7321
+ if (!existsSync18(keyPath)) {
7094
7322
  process.stderr.write(
7095
7323
  `[keychain] Key not found at ${keyPath} (HOME=${os13.homedir()}, EXE_OS_DIR=${process.env.EXE_OS_DIR ?? "unset"})
7096
7324
  `
@@ -7109,7 +7337,7 @@ async function getMasterKey() {
7109
7337
  const decrypted = decryptWithMachineKey(content, machineKey);
7110
7338
  if (!decrypted) {
7111
7339
  process.stderr.write(
7112
- "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase: exe-os link import\n"
7340
+ "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase during setup: exe-os setup\n"
7113
7341
  );
7114
7342
  return null;
7115
7343
  }
@@ -7118,6 +7346,9 @@ async function getMasterKey() {
7118
7346
  b64Value = content;
7119
7347
  }
7120
7348
  const key = Buffer.from(b64Value, "base64");
7349
+ if (!content.startsWith(ENCRYPTED_PREFIX) && isRootOnlyTrustedServerKeyFile(keyPath)) {
7350
+ return key;
7351
+ }
7121
7352
  const migrated = macKeychainSet(b64Value) || linuxSecretSet(b64Value);
7122
7353
  if (migrated) {
7123
7354
  process.stderr.write("[keychain] Migrated key from file to native keychain.\n");
@@ -7145,12 +7376,14 @@ async function getMasterKey() {
7145
7376
  return null;
7146
7377
  }
7147
7378
  }
7148
- var SERVICE, ACCOUNT, ENCRYPTED_PREFIX;
7379
+ var SERVICE, LEGACY_SERVICE, ACCOUNT, linuxSecretAvailability, ENCRYPTED_PREFIX;
7149
7380
  var init_keychain = __esm({
7150
7381
  "src/lib/keychain.ts"() {
7151
7382
  "use strict";
7152
- SERVICE = "exe-mem";
7383
+ SERVICE = "exe-os";
7384
+ LEGACY_SERVICE = "exe-mem";
7153
7385
  ACCOUNT = "master-key";
7386
+ linuxSecretAvailability = null;
7154
7387
  ENCRYPTED_PREFIX = "enc:";
7155
7388
  }
7156
7389
  });
@@ -7364,12 +7597,12 @@ __export(shard_manager_exports, {
7364
7597
  listShards: () => listShards,
7365
7598
  shardExists: () => shardExists
7366
7599
  });
7367
- import path22 from "path";
7368
- import { existsSync as existsSync18, mkdirSync as mkdirSync10, readdirSync as readdirSync5, renameSync as renameSync4, statSync as statSync2 } from "fs";
7600
+ import path23 from "path";
7601
+ import { existsSync as existsSync19, mkdirSync as mkdirSync10, readdirSync as readdirSync5, renameSync as renameSync5, statSync as statSync4 } from "fs";
7369
7602
  import { createClient as createClient2 } from "@libsql/client";
7370
7603
  function initShardManager(encryptionKey) {
7371
7604
  _encryptionKey = encryptionKey;
7372
- if (!existsSync18(SHARDS_DIR)) {
7605
+ if (!existsSync19(SHARDS_DIR)) {
7373
7606
  mkdirSync10(SHARDS_DIR, { recursive: true });
7374
7607
  }
7375
7608
  _shardingEnabled = true;
@@ -7399,7 +7632,7 @@ function getShardClient(projectName) {
7399
7632
  while (_shards.size >= MAX_OPEN_SHARDS) {
7400
7633
  evictLRU();
7401
7634
  }
7402
- const dbPath = path22.join(SHARDS_DIR, `${safeName}.db`);
7635
+ const dbPath = path23.join(SHARDS_DIR, `${safeName}.db`);
7403
7636
  const client = createClient2({
7404
7637
  url: `file:${dbPath}`,
7405
7638
  encryptionKey: _encryptionKey
@@ -7410,13 +7643,13 @@ function getShardClient(projectName) {
7410
7643
  }
7411
7644
  function shardExists(projectName) {
7412
7645
  const safeName = safeShardName(projectName);
7413
- return existsSync18(path22.join(SHARDS_DIR, `${safeName}.db`));
7646
+ return existsSync19(path23.join(SHARDS_DIR, `${safeName}.db`));
7414
7647
  }
7415
7648
  function safeShardName(projectName) {
7416
7649
  return projectName.replace(/[^a-zA-Z0-9_-]/g, "_");
7417
7650
  }
7418
7651
  function listShards() {
7419
- if (!existsSync18(SHARDS_DIR)) return [];
7652
+ if (!existsSync19(SHARDS_DIR)) return [];
7420
7653
  return readdirSync5(SHARDS_DIR).filter((f) => f.endsWith(".db")).map((f) => f.replace(".db", ""));
7421
7654
  }
7422
7655
  async function auditShardHealth(options = {}) {
@@ -7428,8 +7661,8 @@ async function auditShardHealth(options = {}) {
7428
7661
  const names = listShards();
7429
7662
  const shards = [];
7430
7663
  for (const name of names) {
7431
- const dbPath = path22.join(SHARDS_DIR, `${name}.db`);
7432
- const stat = statSync2(dbPath);
7664
+ const dbPath = path23.join(SHARDS_DIR, `${name}.db`);
7665
+ const stat = statSync4(dbPath);
7433
7666
  const item = {
7434
7667
  name,
7435
7668
  path: dbPath,
@@ -7463,8 +7696,8 @@ async function auditShardHealth(options = {}) {
7463
7696
  _shards.delete(name);
7464
7697
  _shardLastAccess.delete(name);
7465
7698
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
7466
- const archivedPath = path22.join(SHARDS_DIR, `${name}.db.broken-${stamp}`);
7467
- renameSync4(dbPath, archivedPath);
7699
+ const archivedPath = path23.join(SHARDS_DIR, `${name}.db.broken-${stamp}`);
7700
+ renameSync5(dbPath, archivedPath);
7468
7701
  item.archivedPath = archivedPath;
7469
7702
  }
7470
7703
  } finally {
@@ -7680,12 +7913,12 @@ async function getReadyShardClient(projectName) {
7680
7913
  client.close();
7681
7914
  _shards.delete(safeName);
7682
7915
  _shardLastAccess.delete(safeName);
7683
- const dbPath = path22.join(SHARDS_DIR, `${safeName}.db`);
7684
- if (existsSync18(dbPath)) {
7685
- const stat = statSync2(dbPath);
7916
+ const dbPath = path23.join(SHARDS_DIR, `${safeName}.db`);
7917
+ if (existsSync19(dbPath)) {
7918
+ const stat = statSync4(dbPath);
7686
7919
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
7687
- const archivedPath = path22.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
7688
- renameSync4(dbPath, archivedPath);
7920
+ const archivedPath = path23.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
7921
+ renameSync5(dbPath, archivedPath);
7689
7922
  process.stderr.write(
7690
7923
  `[shard-manager] Archived unreadable shard ${safeName}: ${archivedPath} (${stat.size} bytes, mtime ${stat.mtime.toISOString()})
7691
7924
  `
@@ -7752,7 +7985,7 @@ var init_shard_manager = __esm({
7752
7985
  "src/lib/shard-manager.ts"() {
7753
7986
  "use strict";
7754
7987
  init_config();
7755
- SHARDS_DIR = path22.join(EXE_AI_DIR, "shards");
7988
+ SHARDS_DIR = path23.join(EXE_AI_DIR, "shards");
7756
7989
  SHARD_IDLE_MS = 5 * 60 * 1e3;
7757
7990
  MAX_OPEN_SHARDS = 10;
7758
7991
  EVICTION_INTERVAL_MS = 60 * 1e3;
@@ -7802,6 +8035,12 @@ var init_platform_procedures = __esm({
7802
8035
  priority: "p0",
7803
8036
  content: "Founder -> coordinator (the executive agent, internally routed as 'COO') -> CTO/CMO. CTO -> engineers. CMO -> content production. Never skip levels: the coordinator 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."
7804
8037
  },
8038
+ {
8039
+ title: "Customer orchestration maturity \u2014 recommend, never trap",
8040
+ domain: "workflow",
8041
+ priority: "p1",
8042
+ content: "New customers start best in Phase 1: founder \u2194 coordinator/Chief of Staff, building company context. Suggest Phase 2 executives when domain work repeats; suggest Phase 3 parallel execution only when review/permission gates are ready. This is guidance, not a blocker: users may jump phases anytime. Never overwrite their phase, role titles, identities, or custom org design."
8043
+ },
7805
8044
  {
7806
8045
  title: "Single dispatch path \u2014 create_task only",
7807
8046
  domain: "workflow",
@@ -7860,6 +8099,12 @@ var init_platform_procedures = __esm({
7860
8099
  priority: "p0",
7861
8100
  content: "exe-build-adv is MANDATORY for ALL work touching 3+ files. Run /exe-build-adv --auto BEFORE implementation. Pipeline: Spec \u2192 AC \u2192 Tests \u2192 Evaluate \u2192 Fix. No multi-file feature ships without pipeline artifacts. No exceptions \u2014 managers reject work without them."
7862
8101
  },
8102
+ {
8103
+ title: "Commit discipline \u2014 never leave verified work floating",
8104
+ domain: "workflow",
8105
+ priority: "p1",
8106
+ content: "After any code-change batch passes typecheck/tests/build, run git status, summarize changed files, and commit with a clear message before ending the session. If work must remain uncommitted for review/dogfood, explicitly say so, list the files, and state the blocker. Never imply work is complete while verified changes are still floating locally."
8107
+ },
7863
8108
  {
7864
8109
  title: "Desktop and TUI are the same product",
7865
8110
  domain: "architecture",
@@ -8177,6 +8422,274 @@ var init_memory_cards = __esm({
8177
8422
  }
8178
8423
  });
8179
8424
 
8425
+ // src/lib/agentic-ontology.ts
8426
+ var agentic_ontology_exports = {};
8427
+ __export(agentic_ontology_exports, {
8428
+ clean: () => clean,
8429
+ extractGoalCandidates: () => extractGoalCandidates,
8430
+ inferIntention: () => inferIntention,
8431
+ inferOntologyEventType: () => inferOntologyEventType,
8432
+ inferOutcome: () => inferOutcome,
8433
+ inferSemanticLabel: () => inferSemanticLabel,
8434
+ insertOntologyForBatch: () => insertOntologyForBatch,
8435
+ insertOntologyForMemory: () => insertOntologyForMemory,
8436
+ ontologyPayload: () => ontologyPayload,
8437
+ stableId: () => stableId2
8438
+ });
8439
+ import { createHash as createHash3 } from "crypto";
8440
+ function stableId2(...parts) {
8441
+ return createHash3("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
8442
+ }
8443
+ function clean(text, max = 240) {
8444
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
8445
+ }
8446
+ function inferOntologyEventType(row) {
8447
+ const lower = row.raw_text.toLowerCase();
8448
+ if (row.has_error) return "error";
8449
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
8450
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
8451
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
8452
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
8453
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
8454
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
8455
+ return "memory_observation";
8456
+ }
8457
+ function inferIntention(row) {
8458
+ if (row.intent) return clean(row.intent, 220);
8459
+ const text = clean(row.raw_text, 1e3);
8460
+ const patterns = [
8461
+ /(?:we need to|need to|let'?s|i want to|we should|goal is to|objective is to|trying to)\s+([^.!?\n]{8,220})/i,
8462
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
8463
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
8464
+ ];
8465
+ for (const p of patterns) {
8466
+ const m = text.match(p);
8467
+ if (m?.[1]) return clean(m[1], 220);
8468
+ }
8469
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
8470
+ return `${row.tool_name} during ${row.project_name}`;
8471
+ }
8472
+ return null;
8473
+ }
8474
+ function inferOutcome(row) {
8475
+ if (row.outcome) return clean(row.outcome, 220);
8476
+ if (row.has_error) return "error";
8477
+ const lower = row.raw_text.toLowerCase();
8478
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
8479
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
8480
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
8481
+ return null;
8482
+ }
8483
+ function extractGoalCandidates(row) {
8484
+ const text = clean(row.raw_text, 1600);
8485
+ const patterns = [
8486
+ /(?:we need to|need to|i want to|we should|goal is to|objective is to|trying to|let'?s)\s+([^.!?\n]{12,220})/gi,
8487
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
8488
+ ];
8489
+ const out = [];
8490
+ for (const pattern of patterns) {
8491
+ for (const m of text.matchAll(pattern)) {
8492
+ const candidate = clean(m[1] ?? "", 220);
8493
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
8494
+ if (out.length >= 3) return out;
8495
+ }
8496
+ }
8497
+ return out;
8498
+ }
8499
+ function uniq(values, max = 6) {
8500
+ const out = [];
8501
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
8502
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
8503
+ if (out.length >= max) break;
8504
+ }
8505
+ return out;
8506
+ }
8507
+ function extractMatches(text, patterns, max = 5) {
8508
+ const out = [];
8509
+ for (const pattern of patterns) {
8510
+ for (const match of text.matchAll(pattern)) {
8511
+ const value = match[1] ?? match[0];
8512
+ if (value) out.push(value);
8513
+ if (out.length >= max) return uniq(out, max);
8514
+ }
8515
+ }
8516
+ return uniq(out, max);
8517
+ }
8518
+ function inferSemanticLabel(row) {
8519
+ const text = clean(row.raw_text, 2400);
8520
+ const eventType = inferOntologyEventType(row);
8521
+ const intention = inferIntention(row);
8522
+ const outcome = inferOutcome(row);
8523
+ const goals = extractGoalCandidates(row);
8524
+ const milestones = extractMatches(text, [
8525
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
8526
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
8527
+ ]);
8528
+ const problems = extractMatches(text, [
8529
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
8530
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
8531
+ ]);
8532
+ const decisions = extractMatches(text, [
8533
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
8534
+ ]);
8535
+ const temporalAnchors = extractMatches(text, [
8536
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
8537
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
8538
+ ], 8);
8539
+ const nextActions = extractMatches(text, [
8540
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
8541
+ ]);
8542
+ const actors = uniq([
8543
+ row.agent_id,
8544
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
8545
+ ], 6);
8546
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
8547
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
8548
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
8549
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
8550
+ return {
8551
+ labeler: "deterministic",
8552
+ schemaVersion: 1,
8553
+ eventType,
8554
+ intention,
8555
+ outcome,
8556
+ impact,
8557
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
8558
+ goals,
8559
+ milestones,
8560
+ problems,
8561
+ decisions,
8562
+ actors,
8563
+ temporalAnchors,
8564
+ successSignals,
8565
+ failureSignals,
8566
+ nextActions,
8567
+ summary: clean(text, 280)
8568
+ };
8569
+ }
8570
+ function ontologyPayload(row) {
8571
+ const semantic = inferSemanticLabel(row);
8572
+ return {
8573
+ tool_name: row.tool_name,
8574
+ memory_version: row.version ?? null,
8575
+ domain: row.domain ?? null,
8576
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
8577
+ semantic
8578
+ };
8579
+ }
8580
+ function safeJson(value) {
8581
+ try {
8582
+ return JSON.parse(value);
8583
+ } catch {
8584
+ return value.slice(0, 1e3);
8585
+ }
8586
+ }
8587
+ async function resolveClient(client) {
8588
+ if (client) return client;
8589
+ const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
8590
+ return getClient2();
8591
+ }
8592
+ async function insertOntologyForMemory(row, client) {
8593
+ const db = await resolveClient(client);
8594
+ const occurredAt = row.timestamp;
8595
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
8596
+ const eventType = inferOntologyEventType(row);
8597
+ const intention = inferIntention(row);
8598
+ const outcome = inferOutcome(row);
8599
+ const eventId = stableId2("event", row.id);
8600
+ const now = (/* @__PURE__ */ new Date()).toISOString();
8601
+ await db.execute({
8602
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
8603
+ VALUES (?, ?, ?, ?, ?, 1, ?)
8604
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
8605
+ event_count = event_count + 1`,
8606
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
8607
+ });
8608
+ await db.execute({
8609
+ sql: `INSERT OR IGNORE INTO agent_events
8610
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
8611
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
8612
+ impact, payload, created_at)
8613
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
8614
+ args: [
8615
+ eventId,
8616
+ eventType,
8617
+ occurredAt,
8618
+ sequence,
8619
+ row.agent_id,
8620
+ row.agent_role,
8621
+ row.project_name,
8622
+ row.session_id,
8623
+ row.task_id ?? null,
8624
+ intention,
8625
+ outcome,
8626
+ row.id,
8627
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
8628
+ JSON.stringify(ontologyPayload(row)),
8629
+ now
8630
+ ]
8631
+ });
8632
+ const semantic = inferSemanticLabel(row);
8633
+ await db.execute({
8634
+ sql: `INSERT INTO agent_semantic_labels
8635
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
8636
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
8637
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
8638
+ labels = excluded.labels, updated_at = excluded.updated_at`,
8639
+ args: [
8640
+ stableId2("semantic", row.id, semantic.labeler, semantic.schemaVersion),
8641
+ row.id,
8642
+ eventId,
8643
+ semantic.labeler,
8644
+ semantic.schemaVersion,
8645
+ semantic.confidence,
8646
+ JSON.stringify(semantic),
8647
+ now,
8648
+ now
8649
+ ]
8650
+ });
8651
+ for (const statement of extractGoalCandidates(row)) {
8652
+ const goalId = stableId2("goal", row.project_name, statement.toLowerCase());
8653
+ await db.execute({
8654
+ sql: `INSERT INTO agent_goals
8655
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
8656
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
8657
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
8658
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
8659
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
8660
+ });
8661
+ await db.execute({
8662
+ sql: `INSERT OR IGNORE INTO agent_goal_links
8663
+ (id, goal_id, link_type, target_id, target_type, created_at)
8664
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
8665
+ args: [stableId2("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
8666
+ });
8667
+ await db.execute({
8668
+ sql: `INSERT OR IGNORE INTO agent_goal_links
8669
+ (id, goal_id, link_type, target_id, target_type, created_at)
8670
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
8671
+ args: [stableId2("goal_link", goalId, eventId, "event"), goalId, eventId, now]
8672
+ });
8673
+ }
8674
+ }
8675
+ async function insertOntologyForBatch(rows, client) {
8676
+ const db = await resolveClient(client);
8677
+ let count = 0;
8678
+ for (const row of rows) {
8679
+ try {
8680
+ await insertOntologyForMemory(row, db);
8681
+ count++;
8682
+ } catch {
8683
+ }
8684
+ }
8685
+ return count;
8686
+ }
8687
+ var init_agentic_ontology = __esm({
8688
+ "src/lib/agentic-ontology.ts"() {
8689
+ "use strict";
8690
+ }
8691
+ });
8692
+
8180
8693
  // src/lib/store.ts
8181
8694
  var store_exports = {};
8182
8695
  __export(store_exports, {
@@ -8520,6 +9033,11 @@ async function flushBatch() {
8520
9033
  await insertMemoryCardsForBatch2(batch);
8521
9034
  } catch {
8522
9035
  }
9036
+ try {
9037
+ const { insertOntologyForBatch: insertOntologyForBatch2 } = await Promise.resolve().then(() => (init_agentic_ontology(), agentic_ontology_exports));
9038
+ await insertOntologyForBatch2(batch);
9039
+ } catch {
9040
+ }
8523
9041
  schedulePostWriteMemoryHygiene(batch.map((row) => row.id));
8524
9042
  _pendingRecords.splice(0, batch.length);
8525
9043
  try {
@@ -8867,78 +9385,6 @@ var init_fast_db_init = __esm({
8867
9385
  }
8868
9386
  });
8869
9387
 
8870
- // src/lib/memory-queue.ts
8871
- import { appendFileSync as appendFileSync2, readFileSync as readFileSync15, renameSync as renameSync5, unlinkSync as unlinkSync9, existsSync as existsSync19, statSync as statSync3 } from "fs";
8872
- import path23 from "path";
8873
- function enqueueMemory(entry) {
8874
- appendFileSync2(QUEUE_PATH2, JSON.stringify(entry) + "\n");
8875
- }
8876
- var QUEUE_PATH2, PROCESSING_PATH, TTL_MS2;
8877
- var init_memory_queue = __esm({
8878
- "src/lib/memory-queue.ts"() {
8879
- "use strict";
8880
- init_config();
8881
- QUEUE_PATH2 = path23.join(EXE_AI_DIR, "memory-queue.jsonl");
8882
- PROCESSING_PATH = QUEUE_PATH2 + ".processing";
8883
- TTL_MS2 = 24 * 60 * 60 * 1e3;
8884
- }
8885
- });
8886
-
8887
- // src/lib/memory-queue-client.ts
8888
- var memory_queue_client_exports = {};
8889
- __export(memory_queue_client_exports, {
8890
- batchWriteMemoryViaDaemon: () => batchWriteMemoryViaDaemon,
8891
- writeMemoryViaDaemon: () => writeMemoryViaDaemon
8892
- });
8893
- async function writeMemoryViaDaemon(entry) {
8894
- if (process.env.EXE_IS_DAEMON === "1") {
8895
- enqueueMemory(entry);
8896
- return false;
8897
- }
8898
- if (!isClientConnected()) {
8899
- enqueueMemory(entry);
8900
- return false;
8901
- }
8902
- try {
8903
- const response = await sendDaemonRequest({
8904
- type: "write-memory",
8905
- entry
8906
- });
8907
- if (response.ok) return true;
8908
- enqueueMemory(entry);
8909
- return false;
8910
- } catch {
8911
- enqueueMemory(entry);
8912
- return false;
8913
- }
8914
- }
8915
- async function batchWriteMemoryViaDaemon(entries) {
8916
- if (entries.length === 0) return 0;
8917
- if (process.env.EXE_IS_DAEMON === "1" || !isClientConnected()) {
8918
- for (const entry of entries) enqueueMemory(entry);
8919
- return 0;
8920
- }
8921
- try {
8922
- const response = await sendDaemonRequest({
8923
- type: "batch-write-memory",
8924
- entries
8925
- });
8926
- if (response.ok) return response.count ?? entries.length;
8927
- for (const entry of entries) enqueueMemory(entry);
8928
- return 0;
8929
- } catch {
8930
- for (const entry of entries) enqueueMemory(entry);
8931
- return 0;
8932
- }
8933
- }
8934
- var init_memory_queue_client = __esm({
8935
- "src/lib/memory-queue-client.ts"() {
8936
- "use strict";
8937
- init_exe_daemon_client();
8938
- init_memory_queue();
8939
- }
8940
- });
8941
-
8942
9388
  // src/lib/git-staleness.ts
8943
9389
  var git_staleness_exports = {};
8944
9390
  __export(git_staleness_exports, {
@@ -9486,6 +9932,119 @@ function buildAutoCheckpoint(input2) {
9486
9932
  };
9487
9933
  }
9488
9934
 
9935
+ // src/lib/memory-queue-client.ts
9936
+ init_exe_daemon_client();
9937
+
9938
+ // src/lib/memory-queue.ts
9939
+ init_config();
9940
+ import { appendFileSync as appendFileSync2, readFileSync as readFileSync15, renameSync as renameSync4, unlinkSync as unlinkSync9, existsSync as existsSync17, statSync as statSync2 } from "fs";
9941
+ import path21 from "path";
9942
+ var QUEUE_PATH2 = path21.join(EXE_AI_DIR, "memory-queue.jsonl");
9943
+ var PROCESSING_PATH = QUEUE_PATH2 + ".processing";
9944
+ var TTL_MS2 = 24 * 60 * 60 * 1e3;
9945
+ function enqueueMemory(entry) {
9946
+ appendFileSync2(QUEUE_PATH2, JSON.stringify(entry) + "\n");
9947
+ }
9948
+
9949
+ // src/lib/memory-queue-client.ts
9950
+ async function writeMemoryViaDaemon(entry) {
9951
+ if (process.env.EXE_IS_DAEMON === "1") {
9952
+ enqueueMemory(entry);
9953
+ return false;
9954
+ }
9955
+ if (!isClientConnected()) {
9956
+ enqueueMemory(entry);
9957
+ return false;
9958
+ }
9959
+ try {
9960
+ const response = await sendDaemonRequest({
9961
+ type: "write-memory",
9962
+ entry
9963
+ });
9964
+ if (response.ok) return true;
9965
+ enqueueMemory(entry);
9966
+ return false;
9967
+ } catch {
9968
+ enqueueMemory(entry);
9969
+ return false;
9970
+ }
9971
+ }
9972
+
9973
+ // src/lib/checkpoint-orchestrator.ts
9974
+ function toolNameForReason(reason) {
9975
+ switch (reason) {
9976
+ case "periodic":
9977
+ return "auto-summary";
9978
+ case "session-end":
9979
+ return "SessionEnd";
9980
+ case "pre-compact":
9981
+ return "pre-compact-hook";
9982
+ case "capacity-signal":
9983
+ return "auto-checkpoint";
9984
+ }
9985
+ }
9986
+ function importanceForReason(reason, override) {
9987
+ if (override !== void 0) return override;
9988
+ switch (reason) {
9989
+ case "periodic":
9990
+ return 7;
9991
+ case "session-end":
9992
+ case "pre-compact":
9993
+ case "capacity-signal":
9994
+ return 8;
9995
+ }
9996
+ }
9997
+ function buildContinuityCheckpoint(input2) {
9998
+ const { checkpointText, decisionTexts } = buildAutoCheckpoint({
9999
+ agentId: input2.agentId,
10000
+ agentRole: input2.agentRole,
10001
+ sessionId: input2.sessionId,
10002
+ projectName: input2.projectName,
10003
+ reason: input2.reason,
10004
+ memories: input2.memories ?? [],
10005
+ tasks: input2.tasks ?? [],
10006
+ maxSamples: input2.maxSamples
10007
+ });
10008
+ const extra = input2.extraSections?.filter((section) => section.trim().length > 0) ?? [];
10009
+ return {
10010
+ checkpointText: extra.length > 0 ? `${checkpointText}
10011
+
10012
+ ${extra.join("\n\n")}` : checkpointText,
10013
+ decisionTexts
10014
+ };
10015
+ }
10016
+ async function writeContinuityCheckpoint(input2) {
10017
+ const result = buildContinuityCheckpoint(input2);
10018
+ const now = (/* @__PURE__ */ new Date()).toISOString();
10019
+ await writeMemoryViaDaemon({
10020
+ raw_text: result.checkpointText,
10021
+ agent_id: input2.agentId,
10022
+ agent_role: input2.agentRole,
10023
+ session_id: input2.sessionId,
10024
+ tool_name: toolNameForReason(input2.reason),
10025
+ project_name: input2.projectName,
10026
+ timestamp: now,
10027
+ importance: importanceForReason(input2.reason, input2.importance),
10028
+ task_id: input2.taskId,
10029
+ memory_type: "checkpoint"
10030
+ });
10031
+ const decisionLimit = input2.reason === "periodic" ? 3 : 5;
10032
+ for (const decisionText of result.decisionTexts.slice(0, decisionLimit)) {
10033
+ await writeMemoryViaDaemon({
10034
+ raw_text: decisionText,
10035
+ agent_id: input2.agentId,
10036
+ agent_role: input2.agentRole,
10037
+ session_id: input2.sessionId,
10038
+ tool_name: "auto-decision",
10039
+ project_name: input2.projectName,
10040
+ timestamp: (/* @__PURE__ */ new Date()).toISOString(),
10041
+ importance: 8,
10042
+ memory_type: "decision"
10043
+ });
10044
+ }
10045
+ return result;
10046
+ }
10047
+
9489
10048
  // src/adapters/claude/hooks/session-end.ts
9490
10049
  if (!process.env.AGENT_ID) {
9491
10050
  process.env.AGENT_ID = "default";
@@ -9535,7 +10094,7 @@ Orphaned tasks at session end: ${orphanResult.rows.map((r) => `"${String(r.title
9535
10094
  ORDER BY priority ASC, updated_at DESC LIMIT 10`,
9536
10095
  args: [agent.agentId, ...seScope.args]
9537
10096
  });
9538
- const { checkpointText, decisionTexts } = buildAutoCheckpoint({
10097
+ await writeContinuityCheckpoint({
9539
10098
  agentId: agent.agentId,
9540
10099
  agentRole: agent.agentRole,
9541
10100
  sessionId: data.session_id,
@@ -9543,35 +10102,9 @@ Orphaned tasks at session end: ${orphanResult.rows.map((r) => `"${String(r.title
9543
10102
  reason: "session-end",
9544
10103
  memories: recent.rows,
9545
10104
  tasks: taskRows.rows,
9546
- maxSamples: 12
10105
+ maxSamples: 12,
10106
+ extraSections: orphanInfo ? [`## Session-End Warnings${orphanInfo}`] : []
9547
10107
  });
9548
- const { writeMemoryViaDaemon: writeMemoryViaDaemon2 } = await Promise.resolve().then(() => (init_memory_queue_client(), memory_queue_client_exports));
9549
- await writeMemoryViaDaemon2({
9550
- raw_text: `${checkpointText}${orphanInfo ? `
9551
-
9552
- ## Session-End Warnings${orphanInfo}` : ""}`,
9553
- agent_id: agent.agentId,
9554
- agent_role: agent.agentRole,
9555
- session_id: data.session_id,
9556
- tool_name: "SessionEnd",
9557
- project_name: projectName,
9558
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9559
- importance: 8,
9560
- memory_type: "checkpoint"
9561
- });
9562
- for (const decisionText of decisionTexts.slice(0, 5)) {
9563
- await writeMemoryViaDaemon2({
9564
- raw_text: decisionText,
9565
- agent_id: agent.agentId,
9566
- agent_role: agent.agentRole,
9567
- session_id: data.session_id,
9568
- tool_name: "auto-decision",
9569
- project_name: projectName,
9570
- timestamp: (/* @__PURE__ */ new Date()).toISOString(),
9571
- importance: 8,
9572
- memory_type: "decision"
9573
- });
9574
- }
9575
10108
  try {
9576
10109
  const { clearSessionFileReads: clearSessionFileReads2 } = await Promise.resolve().then(() => (init_git_staleness(), git_staleness_exports));
9577
10110
  await clearSessionFileReads2(data.session_id);