@askexenow/exe-os 0.9.66 → 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 (99) 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} +1523 -2275
  6. package/dist/bin/backfill-conversations.js +506 -20
  7. package/dist/bin/backfill-responses.js +506 -20
  8. package/dist/bin/backfill-vectors.js +233 -20
  9. package/dist/bin/bulk-sync-postgres.js +4876 -0
  10. package/dist/bin/cleanup-stale-review-tasks.js +507 -21
  11. package/dist/bin/cli.js +2450 -1530
  12. package/dist/bin/exe-assign.js +506 -20
  13. package/dist/bin/exe-boot.js +410 -60
  14. package/dist/bin/exe-cloud.js +795 -105
  15. package/dist/bin/exe-dispatch.js +516 -22
  16. package/dist/bin/exe-doctor.js +587 -30
  17. package/dist/bin/exe-export-behaviors.js +518 -24
  18. package/dist/bin/exe-forget.js +507 -21
  19. package/dist/bin/exe-gateway.js +571 -25
  20. package/dist/bin/exe-heartbeat.js +518 -24
  21. package/dist/bin/exe-kill.js +507 -21
  22. package/dist/bin/exe-launch-agent.js +2312 -1069
  23. package/dist/bin/exe-new-employee.js +197 -165
  24. package/dist/bin/exe-pending-messages.js +507 -21
  25. package/dist/bin/exe-pending-notifications.js +507 -21
  26. package/dist/bin/exe-pending-reviews.js +507 -21
  27. package/dist/bin/exe-rename.js +507 -21
  28. package/dist/bin/exe-review.js +507 -21
  29. package/dist/bin/exe-search.js +518 -24
  30. package/dist/bin/exe-session-cleanup.js +516 -22
  31. package/dist/bin/exe-settings.js +4 -0
  32. package/dist/bin/exe-start-codex.js +682 -143
  33. package/dist/bin/exe-start-opencode.js +627 -79
  34. package/dist/bin/exe-status.js +507 -21
  35. package/dist/bin/exe-team.js +507 -21
  36. package/dist/bin/git-sweep.js +516 -22
  37. package/dist/bin/graph-backfill.js +558 -21
  38. package/dist/bin/graph-export.js +507 -21
  39. package/dist/bin/graph-layer-benchmark.js +109 -0
  40. package/dist/bin/install.js +305 -288
  41. package/dist/bin/intercom-check.js +516 -22
  42. package/dist/bin/postgres-agentic-reflection-backfill.js +187 -0
  43. package/dist/bin/postgres-agentic-semantic-backfill.js +237 -0
  44. package/dist/bin/scan-tasks.js +516 -22
  45. package/dist/bin/setup.js +412 -62
  46. package/dist/bin/shard-migrate.js +506 -20
  47. package/dist/gateway/index.js +569 -23
  48. package/dist/hooks/bug-report-worker.js +519 -25
  49. package/dist/hooks/codex-stop-task-finalizer.js +516 -22
  50. package/dist/hooks/commit-complete.js +516 -22
  51. package/dist/hooks/error-recall.js +518 -24
  52. package/dist/hooks/ingest.js +516 -22
  53. package/dist/hooks/instructions-loaded.js +507 -21
  54. package/dist/hooks/notification.js +507 -21
  55. package/dist/hooks/post-compact.js +507 -21
  56. package/dist/hooks/post-tool-combined.js +519 -25
  57. package/dist/hooks/pre-compact.js +516 -22
  58. package/dist/hooks/pre-tool-use.js +507 -21
  59. package/dist/hooks/prompt-submit.js +519 -25
  60. package/dist/hooks/session-end.js +516 -22
  61. package/dist/hooks/session-start.js +520 -26
  62. package/dist/hooks/stop.js +517 -23
  63. package/dist/hooks/subagent-stop.js +507 -21
  64. package/dist/hooks/summary-worker.js +411 -61
  65. package/dist/index.js +569 -23
  66. package/dist/lib/cloud-sync.js +391 -53
  67. package/dist/lib/config.js +13 -1
  68. package/dist/lib/consolidation.js +1 -1
  69. package/dist/lib/database.js +124 -0
  70. package/dist/lib/db.js +124 -0
  71. package/dist/lib/device-registry.js +124 -0
  72. package/dist/lib/embedder.js +13 -1
  73. package/dist/lib/exe-daemon.js +2184 -561
  74. package/dist/lib/hybrid-search.js +518 -24
  75. package/dist/lib/identity.js +3 -0
  76. package/dist/lib/keychain.js +178 -22
  77. package/dist/lib/messaging.js +3 -0
  78. package/dist/lib/reminders.js +3 -0
  79. package/dist/lib/schedules.js +233 -20
  80. package/dist/lib/skill-learning.js +16 -1
  81. package/dist/lib/store.js +506 -20
  82. package/dist/lib/tasks.js +16 -1
  83. package/dist/lib/tmux-routing.js +16 -1
  84. package/dist/lib/token-spend.js +3 -0
  85. package/dist/mcp/server.js +1757 -428
  86. package/dist/mcp/tools/complete-reminder.js +3 -0
  87. package/dist/mcp/tools/create-reminder.js +3 -0
  88. package/dist/mcp/tools/create-task.js +16 -1
  89. package/dist/mcp/tools/deactivate-behavior.js +3 -0
  90. package/dist/mcp/tools/list-reminders.js +3 -0
  91. package/dist/mcp/tools/list-tasks.js +3 -0
  92. package/dist/mcp/tools/send-message.js +3 -0
  93. package/dist/mcp/tools/update-task.js +16 -1
  94. package/dist/runtime/index.js +516 -22
  95. package/dist/tui/App.js +594 -29
  96. package/package.json +8 -5
  97. package/src/commands/exe/cloud.md +6 -10
  98. package/stack.release.json +3 -3
  99. package/src/commands/exe/link.md +0 -18
@@ -549,6 +549,10 @@ async function loadConfig() {
549
549
  if (config2.dbPath.startsWith("~")) {
550
550
  config2.dbPath = config2.dbPath.replace(/^~/, os.homedir());
551
551
  }
552
+ const envDbPath = path.join(dir, "memories.db");
553
+ if (process.env.EXE_OS_DIR && config2.dbPath !== envDbPath && !existsSync2(config2.dbPath) && existsSync2(envDbPath)) {
554
+ config2.dbPath = envDbPath;
555
+ }
552
556
  return config2;
553
557
  } catch {
554
558
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
@@ -569,7 +573,15 @@ function loadConfigSync() {
569
573
  normalizeSessionLifecycle(migratedCfg);
570
574
  normalizeAutoUpdate(migratedCfg);
571
575
  normalizeOrchestration(migratedCfg);
572
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
576
+ const config2 = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
577
+ if (config2.dbPath.startsWith("~")) {
578
+ config2.dbPath = config2.dbPath.replace(/^~/, os.homedir());
579
+ }
580
+ const envDbPath = path.join(dir, "memories.db");
581
+ if (process.env.EXE_OS_DIR && config2.dbPath !== envDbPath && !existsSync2(config2.dbPath) && existsSync2(envDbPath)) {
582
+ config2.dbPath = envDbPath;
583
+ }
584
+ return config2;
573
585
  } catch {
574
586
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
575
587
  }
@@ -2391,6 +2403,9 @@ function getClient() {
2391
2403
  if (_daemonClient && _daemonClient._isDaemonActive()) {
2392
2404
  return _daemonClient;
2393
2405
  }
2406
+ if (!_resilientClient) {
2407
+ return _adapterClient;
2408
+ }
2394
2409
  return _resilientClient;
2395
2410
  }
2396
2411
  async function initDaemonClient() {
@@ -3423,6 +3438,127 @@ async function ensureSchema() {
3423
3438
  VALUES (new.rowid, new.content, new.subject, new.predicate, new.object);
3424
3439
  END;
3425
3440
  `);
3441
+ await client.executeMultiple(`
3442
+ CREATE TABLE IF NOT EXISTS agent_sessions (
3443
+ id TEXT PRIMARY KEY,
3444
+ agent_id TEXT NOT NULL,
3445
+ project_name TEXT,
3446
+ started_at TEXT NOT NULL,
3447
+ last_event_at TEXT NOT NULL,
3448
+ event_count INTEGER NOT NULL DEFAULT 0,
3449
+ properties TEXT DEFAULT '{}'
3450
+ );
3451
+
3452
+ CREATE INDEX IF NOT EXISTS idx_agent_sessions_agent_time
3453
+ ON agent_sessions(agent_id, started_at);
3454
+
3455
+ CREATE TABLE IF NOT EXISTS agent_goals (
3456
+ id TEXT PRIMARY KEY,
3457
+ statement TEXT NOT NULL,
3458
+ owner_agent_id TEXT,
3459
+ project_name TEXT,
3460
+ status TEXT NOT NULL DEFAULT 'open',
3461
+ priority INTEGER NOT NULL DEFAULT 5,
3462
+ success_criteria TEXT,
3463
+ parent_goal_id TEXT,
3464
+ due_at TEXT,
3465
+ achieved_at TEXT,
3466
+ supersedes_id TEXT,
3467
+ created_at TEXT NOT NULL,
3468
+ updated_at TEXT NOT NULL,
3469
+ source_memory_id TEXT
3470
+ );
3471
+
3472
+ CREATE INDEX IF NOT EXISTS idx_agent_goals_project_status
3473
+ ON agent_goals(project_name, status, priority);
3474
+
3475
+ CREATE TABLE IF NOT EXISTS agent_events (
3476
+ id TEXT PRIMARY KEY,
3477
+ event_type TEXT NOT NULL,
3478
+ occurred_at TEXT NOT NULL,
3479
+ sequence_index INTEGER NOT NULL,
3480
+ actor_agent_id TEXT,
3481
+ agent_role TEXT,
3482
+ project_name TEXT,
3483
+ session_id TEXT,
3484
+ task_id TEXT,
3485
+ goal_id TEXT,
3486
+ parent_event_id TEXT,
3487
+ intention TEXT,
3488
+ outcome TEXT,
3489
+ evidence_memory_id TEXT,
3490
+ impact TEXT,
3491
+ payload TEXT DEFAULT '{}',
3492
+ created_at TEXT NOT NULL
3493
+ );
3494
+
3495
+ CREATE INDEX IF NOT EXISTS idx_agent_events_time
3496
+ ON agent_events(occurred_at, sequence_index);
3497
+
3498
+ CREATE INDEX IF NOT EXISTS idx_agent_events_session_seq
3499
+ ON agent_events(session_id, sequence_index);
3500
+
3501
+ CREATE INDEX IF NOT EXISTS idx_agent_events_goal_time
3502
+ ON agent_events(goal_id, occurred_at);
3503
+
3504
+ CREATE INDEX IF NOT EXISTS idx_agent_events_memory
3505
+ ON agent_events(evidence_memory_id);
3506
+
3507
+ CREATE TABLE IF NOT EXISTS agent_goal_links (
3508
+ id TEXT PRIMARY KEY,
3509
+ goal_id TEXT NOT NULL,
3510
+ link_type TEXT NOT NULL,
3511
+ target_id TEXT NOT NULL,
3512
+ target_type TEXT NOT NULL,
3513
+ created_at TEXT NOT NULL
3514
+ );
3515
+
3516
+ CREATE INDEX IF NOT EXISTS idx_agent_goal_links_goal
3517
+ ON agent_goal_links(goal_id, target_type);
3518
+
3519
+ CREATE TABLE IF NOT EXISTS agent_semantic_labels (
3520
+ id TEXT PRIMARY KEY,
3521
+ source_memory_id TEXT NOT NULL,
3522
+ event_id TEXT,
3523
+ labeler TEXT NOT NULL,
3524
+ schema_version INTEGER NOT NULL DEFAULT 1,
3525
+ confidence REAL NOT NULL DEFAULT 0,
3526
+ labels TEXT NOT NULL,
3527
+ created_at TEXT NOT NULL,
3528
+ updated_at TEXT NOT NULL
3529
+ );
3530
+
3531
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_memory
3532
+ ON agent_semantic_labels(source_memory_id, labeler);
3533
+
3534
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_event
3535
+ ON agent_semantic_labels(event_id);
3536
+
3537
+ CREATE TABLE IF NOT EXISTS agent_reflection_checkpoints (
3538
+ id TEXT PRIMARY KEY,
3539
+ project_name TEXT,
3540
+ session_id TEXT,
3541
+ window_start_at TEXT NOT NULL,
3542
+ window_end_at TEXT NOT NULL,
3543
+ event_count INTEGER NOT NULL DEFAULT 0,
3544
+ goal_count INTEGER NOT NULL DEFAULT 0,
3545
+ success_count INTEGER NOT NULL DEFAULT 0,
3546
+ failure_count INTEGER NOT NULL DEFAULT 0,
3547
+ risk_count INTEGER NOT NULL DEFAULT 0,
3548
+ summary TEXT NOT NULL,
3549
+ learnings TEXT NOT NULL DEFAULT '[]',
3550
+ next_actions TEXT NOT NULL DEFAULT '[]',
3551
+ evidence_event_ids TEXT NOT NULL DEFAULT '[]',
3552
+ confidence REAL NOT NULL DEFAULT 0,
3553
+ created_at TEXT NOT NULL
3554
+ );
3555
+
3556
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_project_time
3557
+ ON agent_reflection_checkpoints(project_name, window_end_at);
3558
+
3559
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_session_time
3560
+ ON agent_reflection_checkpoints(session_id, window_end_at);
3561
+ `);
3426
3562
  try {
3427
3563
  await client.execute({
3428
3564
  sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
@@ -3640,7 +3776,7 @@ var init_embedder = __esm({
3640
3776
 
3641
3777
  // src/lib/keychain.ts
3642
3778
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3643
- import { existsSync as existsSync7 } from "fs";
3779
+ import { existsSync as existsSync7, statSync as statSync2 } from "fs";
3644
3780
  import { execSync as execSync2 } from "child_process";
3645
3781
  import path7 from "path";
3646
3782
  import os5 from "os";
@@ -3650,29 +3786,78 @@ function getKeyDir() {
3650
3786
  function getKeyPath() {
3651
3787
  return path7.join(getKeyDir(), "master.key");
3652
3788
  }
3653
- function macKeychainGet() {
3789
+ function nativeKeychainAllowed() {
3790
+ return process.env.EXE_OS_DISABLE_NATIVE_KEYCHAIN !== "1";
3791
+ }
3792
+ function linuxSecretAvailable() {
3793
+ if (!nativeKeychainAllowed()) return false;
3794
+ if (process.platform !== "linux") return false;
3795
+ if (linuxSecretAvailability !== null) return linuxSecretAvailability;
3796
+ try {
3797
+ execSync2("command -v secret-tool >/dev/null 2>&1", { timeout: 1e3 });
3798
+ } catch {
3799
+ linuxSecretAvailability = false;
3800
+ return false;
3801
+ }
3802
+ try {
3803
+ execSync2("secret-tool search --all exe-os probe >/dev/null 2>&1", { timeout: 1e3 });
3804
+ linuxSecretAvailability = true;
3805
+ } catch {
3806
+ linuxSecretAvailability = false;
3807
+ }
3808
+ return linuxSecretAvailability;
3809
+ }
3810
+ function isRootOnlyTrustedServerKeyFile(keyPath) {
3811
+ if (process.platform !== "linux") return false;
3812
+ try {
3813
+ const uid = typeof os5.userInfo().uid === "number" ? os5.userInfo().uid : -1;
3814
+ const st = statSync2(keyPath);
3815
+ if (!st.isFile() || (st.mode & 63) !== 0) return false;
3816
+ if (uid === 0) return true;
3817
+ const exeOsDir = process.env.EXE_OS_DIR;
3818
+ return Boolean(exeOsDir && path7.resolve(keyPath).startsWith(path7.resolve(exeOsDir) + path7.sep));
3819
+ } catch {
3820
+ return false;
3821
+ }
3822
+ }
3823
+ function macKeychainGet(service = SERVICE) {
3824
+ if (!nativeKeychainAllowed()) return null;
3654
3825
  if (process.platform !== "darwin") return null;
3655
3826
  try {
3656
3827
  return execSync2(
3657
- `security find-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w 2>/dev/null`,
3828
+ `security find-generic-password -s "${service}" -a "${ACCOUNT}" -w 2>/dev/null`,
3658
3829
  { encoding: "utf-8", timeout: 5e3 }
3659
3830
  ).trim();
3660
3831
  } catch {
3661
3832
  return null;
3662
3833
  }
3663
3834
  }
3664
- function macKeychainSet(value) {
3835
+ function macKeychainSet(value, service = SERVICE) {
3836
+ if (!nativeKeychainAllowed()) return false;
3665
3837
  if (process.platform !== "darwin") return false;
3666
3838
  try {
3667
3839
  try {
3668
3840
  execSync2(
3669
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
3841
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3670
3842
  { timeout: 5e3 }
3671
3843
  );
3672
3844
  } catch {
3673
3845
  }
3674
3846
  execSync2(
3675
- `security add-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w "${value}"`,
3847
+ `security add-generic-password -s "${service}" -a "${ACCOUNT}" -w "${value}"`,
3848
+ { timeout: 5e3 }
3849
+ );
3850
+ return true;
3851
+ } catch {
3852
+ return false;
3853
+ }
3854
+ }
3855
+ function macKeychainDelete(service = SERVICE) {
3856
+ if (!nativeKeychainAllowed()) return false;
3857
+ if (process.platform !== "darwin") return false;
3858
+ try {
3859
+ execSync2(
3860
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3676
3861
  { timeout: 5e3 }
3677
3862
  );
3678
3863
  return true;
@@ -3680,22 +3865,35 @@ function macKeychainSet(value) {
3680
3865
  return false;
3681
3866
  }
3682
3867
  }
3683
- function linuxSecretGet() {
3684
- if (process.platform !== "linux") return null;
3868
+ function linuxSecretGet(service = SERVICE) {
3869
+ if (!linuxSecretAvailable()) return null;
3685
3870
  try {
3686
3871
  return execSync2(
3687
- `secret-tool lookup service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
3872
+ `secret-tool lookup service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3688
3873
  { encoding: "utf-8", timeout: 5e3 }
3689
3874
  ).trim();
3690
3875
  } catch {
3691
3876
  return null;
3692
3877
  }
3693
3878
  }
3694
- function linuxSecretSet(value) {
3879
+ function linuxSecretSet(value, service = SERVICE) {
3880
+ if (!linuxSecretAvailable()) return false;
3881
+ try {
3882
+ execSync2(
3883
+ `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3884
+ { timeout: 5e3 }
3885
+ );
3886
+ return true;
3887
+ } catch {
3888
+ return false;
3889
+ }
3890
+ }
3891
+ function linuxSecretDelete(service = SERVICE) {
3892
+ if (!nativeKeychainAllowed()) return false;
3695
3893
  if (process.platform !== "linux") return false;
3696
3894
  try {
3697
3895
  execSync2(
3698
- `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${SERVICE}" account "${ACCOUNT}"`,
3896
+ `secret-tool clear service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3699
3897
  { timeout: 5e3 }
3700
3898
  );
3701
3899
  return true;
@@ -3704,6 +3902,7 @@ function linuxSecretSet(value) {
3704
3902
  }
3705
3903
  }
3706
3904
  async function tryKeytar() {
3905
+ if (!nativeKeychainAllowed()) return null;
3707
3906
  try {
3708
3907
  return await import("keytar");
3709
3908
  } catch {
@@ -3777,7 +3976,19 @@ async function writeMachineBoundFileFallback(b64) {
3777
3976
  return "plaintext";
3778
3977
  }
3779
3978
  async function getMasterKey() {
3780
- const nativeValue = macKeychainGet() ?? linuxSecretGet();
3979
+ let nativeValue = macKeychainGet() ?? linuxSecretGet();
3980
+ if (!nativeValue) {
3981
+ const legacyValue = macKeychainGet(LEGACY_SERVICE) ?? linuxSecretGet(LEGACY_SERVICE);
3982
+ if (legacyValue) {
3983
+ const migrated = macKeychainSet(legacyValue) || linuxSecretSet(legacyValue);
3984
+ if (migrated) {
3985
+ macKeychainDelete(LEGACY_SERVICE);
3986
+ linuxSecretDelete(LEGACY_SERVICE);
3987
+ process.stderr.write("[keychain] Migrated keychain service from exe-mem to exe-os.\n");
3988
+ }
3989
+ nativeValue = legacyValue;
3990
+ }
3991
+ }
3781
3992
  if (nativeValue) {
3782
3993
  return Buffer.from(nativeValue, "base64");
3783
3994
  }
@@ -3785,12 +3996,17 @@ async function getMasterKey() {
3785
3996
  if (keytar) {
3786
3997
  try {
3787
3998
  const keytarValue = await keytar.getPassword(SERVICE, ACCOUNT);
3788
- if (keytarValue) {
3789
- const migrated = macKeychainSet(keytarValue) || linuxSecretSet(keytarValue);
3999
+ const legacyKeytarValue = keytarValue ?? await keytar.getPassword(LEGACY_SERVICE, ACCOUNT);
4000
+ if (legacyKeytarValue) {
4001
+ const migrated = macKeychainSet(legacyKeytarValue) || linuxSecretSet(legacyKeytarValue);
3790
4002
  if (migrated) {
3791
4003
  process.stderr.write("[keychain] Migrated key from keytar to native keychain.\n");
4004
+ try {
4005
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
4006
+ } catch {
4007
+ }
3792
4008
  }
3793
- return Buffer.from(keytarValue, "base64");
4009
+ return Buffer.from(legacyKeytarValue, "base64");
3794
4010
  }
3795
4011
  } catch {
3796
4012
  }
@@ -3815,7 +4031,7 @@ async function getMasterKey() {
3815
4031
  const decrypted = decryptWithMachineKey(content, machineKey);
3816
4032
  if (!decrypted) {
3817
4033
  process.stderr.write(
3818
- "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase: exe-os link import\n"
4034
+ "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase during setup: exe-os setup\n"
3819
4035
  );
3820
4036
  return null;
3821
4037
  }
@@ -3824,6 +4040,9 @@ async function getMasterKey() {
3824
4040
  b64Value = content;
3825
4041
  }
3826
4042
  const key = Buffer.from(b64Value, "base64");
4043
+ if (!content.startsWith(ENCRYPTED_PREFIX) && isRootOnlyTrustedServerKeyFile(keyPath)) {
4044
+ return key;
4045
+ }
3827
4046
  const migrated = macKeychainSet(b64Value) || linuxSecretSet(b64Value);
3828
4047
  if (migrated) {
3829
4048
  process.stderr.write("[keychain] Migrated key from file to native keychain.\n");
@@ -3851,12 +4070,14 @@ async function getMasterKey() {
3851
4070
  return null;
3852
4071
  }
3853
4072
  }
3854
- var SERVICE, ACCOUNT, ENCRYPTED_PREFIX;
4073
+ var SERVICE, LEGACY_SERVICE, ACCOUNT, linuxSecretAvailability, ENCRYPTED_PREFIX;
3855
4074
  var init_keychain = __esm({
3856
4075
  "src/lib/keychain.ts"() {
3857
4076
  "use strict";
3858
- SERVICE = "exe-mem";
4077
+ SERVICE = "exe-os";
4078
+ LEGACY_SERVICE = "exe-mem";
3859
4079
  ACCOUNT = "master-key";
4080
+ linuxSecretAvailability = null;
3860
4081
  ENCRYPTED_PREFIX = "enc:";
3861
4082
  }
3862
4083
  });
@@ -4071,7 +4292,7 @@ __export(shard_manager_exports, {
4071
4292
  shardExists: () => shardExists
4072
4293
  });
4073
4294
  import path8 from "path";
4074
- import { existsSync as existsSync8, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync2 } from "fs";
4295
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync3 } from "fs";
4075
4296
  import { createClient as createClient2 } from "@libsql/client";
4076
4297
  function initShardManager(encryptionKey) {
4077
4298
  _encryptionKey = encryptionKey;
@@ -4135,7 +4356,7 @@ async function auditShardHealth(options = {}) {
4135
4356
  const shards = [];
4136
4357
  for (const name of names) {
4137
4358
  const dbPath = path8.join(SHARDS_DIR, `${name}.db`);
4138
- const stat = statSync2(dbPath);
4359
+ const stat = statSync3(dbPath);
4139
4360
  const item = {
4140
4361
  name,
4141
4362
  path: dbPath,
@@ -4388,7 +4609,7 @@ async function getReadyShardClient(projectName) {
4388
4609
  _shardLastAccess.delete(safeName);
4389
4610
  const dbPath = path8.join(SHARDS_DIR, `${safeName}.db`);
4390
4611
  if (existsSync8(dbPath)) {
4391
- const stat = statSync2(dbPath);
4612
+ const stat = statSync3(dbPath);
4392
4613
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
4393
4614
  const archivedPath = path8.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
4394
4615
  renameSync3(dbPath, archivedPath);
@@ -4895,6 +5116,274 @@ var init_memory_cards = __esm({
4895
5116
  }
4896
5117
  });
4897
5118
 
5119
+ // src/lib/agentic-ontology.ts
5120
+ var agentic_ontology_exports = {};
5121
+ __export(agentic_ontology_exports, {
5122
+ clean: () => clean,
5123
+ extractGoalCandidates: () => extractGoalCandidates,
5124
+ inferIntention: () => inferIntention,
5125
+ inferOntologyEventType: () => inferOntologyEventType,
5126
+ inferOutcome: () => inferOutcome,
5127
+ inferSemanticLabel: () => inferSemanticLabel,
5128
+ insertOntologyForBatch: () => insertOntologyForBatch,
5129
+ insertOntologyForMemory: () => insertOntologyForMemory,
5130
+ ontologyPayload: () => ontologyPayload,
5131
+ stableId: () => stableId2
5132
+ });
5133
+ import { createHash as createHash3 } from "crypto";
5134
+ function stableId2(...parts) {
5135
+ return createHash3("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
5136
+ }
5137
+ function clean(text, max = 240) {
5138
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
5139
+ }
5140
+ function inferOntologyEventType(row) {
5141
+ const lower = row.raw_text.toLowerCase();
5142
+ if (row.has_error) return "error";
5143
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
5144
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
5145
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
5146
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
5147
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
5148
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
5149
+ return "memory_observation";
5150
+ }
5151
+ function inferIntention(row) {
5152
+ if (row.intent) return clean(row.intent, 220);
5153
+ const text = clean(row.raw_text, 1e3);
5154
+ const patterns = [
5155
+ /(?: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,
5156
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
5157
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
5158
+ ];
5159
+ for (const p of patterns) {
5160
+ const m = text.match(p);
5161
+ if (m?.[1]) return clean(m[1], 220);
5162
+ }
5163
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
5164
+ return `${row.tool_name} during ${row.project_name}`;
5165
+ }
5166
+ return null;
5167
+ }
5168
+ function inferOutcome(row) {
5169
+ if (row.outcome) return clean(row.outcome, 220);
5170
+ if (row.has_error) return "error";
5171
+ const lower = row.raw_text.toLowerCase();
5172
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
5173
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
5174
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
5175
+ return null;
5176
+ }
5177
+ function extractGoalCandidates(row) {
5178
+ const text = clean(row.raw_text, 1600);
5179
+ const patterns = [
5180
+ /(?: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,
5181
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
5182
+ ];
5183
+ const out = [];
5184
+ for (const pattern of patterns) {
5185
+ for (const m of text.matchAll(pattern)) {
5186
+ const candidate = clean(m[1] ?? "", 220);
5187
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
5188
+ if (out.length >= 3) return out;
5189
+ }
5190
+ }
5191
+ return out;
5192
+ }
5193
+ function uniq(values, max = 6) {
5194
+ const out = [];
5195
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
5196
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
5197
+ if (out.length >= max) break;
5198
+ }
5199
+ return out;
5200
+ }
5201
+ function extractMatches(text, patterns, max = 5) {
5202
+ const out = [];
5203
+ for (const pattern of patterns) {
5204
+ for (const match of text.matchAll(pattern)) {
5205
+ const value = match[1] ?? match[0];
5206
+ if (value) out.push(value);
5207
+ if (out.length >= max) return uniq(out, max);
5208
+ }
5209
+ }
5210
+ return uniq(out, max);
5211
+ }
5212
+ function inferSemanticLabel(row) {
5213
+ const text = clean(row.raw_text, 2400);
5214
+ const eventType = inferOntologyEventType(row);
5215
+ const intention = inferIntention(row);
5216
+ const outcome = inferOutcome(row);
5217
+ const goals = extractGoalCandidates(row);
5218
+ const milestones = extractMatches(text, [
5219
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
5220
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
5221
+ ]);
5222
+ const problems = extractMatches(text, [
5223
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
5224
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
5225
+ ]);
5226
+ const decisions = extractMatches(text, [
5227
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
5228
+ ]);
5229
+ const temporalAnchors = extractMatches(text, [
5230
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
5231
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
5232
+ ], 8);
5233
+ const nextActions = extractMatches(text, [
5234
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
5235
+ ]);
5236
+ const actors = uniq([
5237
+ row.agent_id,
5238
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
5239
+ ], 6);
5240
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
5241
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
5242
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
5243
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
5244
+ return {
5245
+ labeler: "deterministic",
5246
+ schemaVersion: 1,
5247
+ eventType,
5248
+ intention,
5249
+ outcome,
5250
+ impact,
5251
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
5252
+ goals,
5253
+ milestones,
5254
+ problems,
5255
+ decisions,
5256
+ actors,
5257
+ temporalAnchors,
5258
+ successSignals,
5259
+ failureSignals,
5260
+ nextActions,
5261
+ summary: clean(text, 280)
5262
+ };
5263
+ }
5264
+ function ontologyPayload(row) {
5265
+ const semantic = inferSemanticLabel(row);
5266
+ return {
5267
+ tool_name: row.tool_name,
5268
+ memory_version: row.version ?? null,
5269
+ domain: row.domain ?? null,
5270
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
5271
+ semantic
5272
+ };
5273
+ }
5274
+ function safeJson(value) {
5275
+ try {
5276
+ return JSON.parse(value);
5277
+ } catch {
5278
+ return value.slice(0, 1e3);
5279
+ }
5280
+ }
5281
+ async function resolveClient(client) {
5282
+ if (client) return client;
5283
+ const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
5284
+ return getClient2();
5285
+ }
5286
+ async function insertOntologyForMemory(row, client) {
5287
+ const db = await resolveClient(client);
5288
+ const occurredAt = row.timestamp;
5289
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
5290
+ const eventType = inferOntologyEventType(row);
5291
+ const intention = inferIntention(row);
5292
+ const outcome = inferOutcome(row);
5293
+ const eventId = stableId2("event", row.id);
5294
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5295
+ await db.execute({
5296
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
5297
+ VALUES (?, ?, ?, ?, ?, 1, ?)
5298
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
5299
+ event_count = event_count + 1`,
5300
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
5301
+ });
5302
+ await db.execute({
5303
+ sql: `INSERT OR IGNORE INTO agent_events
5304
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
5305
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
5306
+ impact, payload, created_at)
5307
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
5308
+ args: [
5309
+ eventId,
5310
+ eventType,
5311
+ occurredAt,
5312
+ sequence,
5313
+ row.agent_id,
5314
+ row.agent_role,
5315
+ row.project_name,
5316
+ row.session_id,
5317
+ row.task_id ?? null,
5318
+ intention,
5319
+ outcome,
5320
+ row.id,
5321
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
5322
+ JSON.stringify(ontologyPayload(row)),
5323
+ now
5324
+ ]
5325
+ });
5326
+ const semantic = inferSemanticLabel(row);
5327
+ await db.execute({
5328
+ sql: `INSERT INTO agent_semantic_labels
5329
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
5330
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
5331
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
5332
+ labels = excluded.labels, updated_at = excluded.updated_at`,
5333
+ args: [
5334
+ stableId2("semantic", row.id, semantic.labeler, semantic.schemaVersion),
5335
+ row.id,
5336
+ eventId,
5337
+ semantic.labeler,
5338
+ semantic.schemaVersion,
5339
+ semantic.confidence,
5340
+ JSON.stringify(semantic),
5341
+ now,
5342
+ now
5343
+ ]
5344
+ });
5345
+ for (const statement of extractGoalCandidates(row)) {
5346
+ const goalId = stableId2("goal", row.project_name, statement.toLowerCase());
5347
+ await db.execute({
5348
+ sql: `INSERT INTO agent_goals
5349
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
5350
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
5351
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
5352
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
5353
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
5354
+ });
5355
+ await db.execute({
5356
+ sql: `INSERT OR IGNORE INTO agent_goal_links
5357
+ (id, goal_id, link_type, target_id, target_type, created_at)
5358
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
5359
+ args: [stableId2("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
5360
+ });
5361
+ await db.execute({
5362
+ sql: `INSERT OR IGNORE INTO agent_goal_links
5363
+ (id, goal_id, link_type, target_id, target_type, created_at)
5364
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
5365
+ args: [stableId2("goal_link", goalId, eventId, "event"), goalId, eventId, now]
5366
+ });
5367
+ }
5368
+ }
5369
+ async function insertOntologyForBatch(rows, client) {
5370
+ const db = await resolveClient(client);
5371
+ let count = 0;
5372
+ for (const row of rows) {
5373
+ try {
5374
+ await insertOntologyForMemory(row, db);
5375
+ count++;
5376
+ } catch {
5377
+ }
5378
+ }
5379
+ return count;
5380
+ }
5381
+ var init_agentic_ontology = __esm({
5382
+ "src/lib/agentic-ontology.ts"() {
5383
+ "use strict";
5384
+ }
5385
+ });
5386
+
4898
5387
  // src/lib/store.ts
4899
5388
  var store_exports = {};
4900
5389
  __export(store_exports, {
@@ -5238,6 +5727,11 @@ async function flushBatch() {
5238
5727
  await insertMemoryCardsForBatch2(batch);
5239
5728
  } catch {
5240
5729
  }
5730
+ try {
5731
+ const { insertOntologyForBatch: insertOntologyForBatch2 } = await Promise.resolve().then(() => (init_agentic_ontology(), agentic_ontology_exports));
5732
+ await insertOntologyForBatch2(batch);
5733
+ } catch {
5734
+ }
5241
5735
  schedulePostWriteMemoryHygiene(batch.map((row) => row.id));
5242
5736
  _pendingRecords.splice(0, batch.length);
5243
5737
  try {
@@ -5843,6 +6337,7 @@ __export(graph_rag_exports, {
5843
6337
  extractBatch: () => extractBatch,
5844
6338
  extractFromCode: () => extractFromCode,
5845
6339
  extractFromMemory: () => extractFromMemory,
6340
+ extractHeuristicMemoryGraph: () => extractHeuristicMemoryGraph,
5846
6341
  mergeEntities: () => mergeEntities,
5847
6342
  normalizeEntityName: () => normalizeEntityName,
5848
6343
  registerAlias: () => registerAlias,
@@ -5998,6 +6493,57 @@ function extractFromCode(source, filePath) {
5998
6493
  }
5999
6494
  return { entities, relationships, hyperedges: [] };
6000
6495
  }
6496
+ function pushUniqueEntity(entities, seen, name, type) {
6497
+ const normalized = normalizeEntityName(name);
6498
+ if (!normalized || normalized.length < 2) return;
6499
+ const key = `${normalized.toLowerCase()}::${type.toLowerCase()}`;
6500
+ if (seen.has(key)) return;
6501
+ seen.add(key);
6502
+ entities.push({ name: normalized.slice(0, 160), type });
6503
+ }
6504
+ function pushHeuristicRelationship(relationships, source, sourceType, target, targetType, relationship, confidence = 0.6) {
6505
+ if (!source || !target || source === target) return;
6506
+ relationships.push({
6507
+ source,
6508
+ sourceType,
6509
+ target,
6510
+ targetType,
6511
+ relationship,
6512
+ confidence,
6513
+ confidenceLabel: "inferred"
6514
+ });
6515
+ }
6516
+ function extractHeuristicMemoryGraph(content, agentId) {
6517
+ const entities = [];
6518
+ const relationships = [];
6519
+ const seen = /* @__PURE__ */ new Set();
6520
+ pushUniqueEntity(entities, seen, agentId, "person");
6521
+ const toolMatch = content.match(/^(Bash|Read|Edit|Write|Grep|Glob|AssistantResponse|Tool|Ran|Wrote|Edited):/m);
6522
+ if (toolMatch?.[1]) {
6523
+ pushUniqueEntity(entities, seen, toolMatch[1], "tool");
6524
+ pushHeuristicRelationship(relationships, agentId, "person", toolMatch[1], "tool", "uses", 0.75);
6525
+ }
6526
+ const repoMatches = [...content.matchAll(/\/Users\/[^/\s]+\/([A-Za-z0-9_.-]+)|\/opt\/([A-Za-z0-9_.-]+)/g)].map((m) => m[1] ?? m[2]).filter((repo) => Boolean(repo)).slice(0, 6);
6527
+ for (const repo of repoMatches) {
6528
+ pushUniqueEntity(entities, seen, repo, "project");
6529
+ pushHeuristicRelationship(relationships, agentId, "person", repo, "project", "worked_on", 0.7);
6530
+ }
6531
+ const pathMatches = new Set(
6532
+ (content.match(/(?:\/[\w .@-]+)+(?:\.[A-Za-z0-9]{1,10})|(?:[\w@.-]+\/)+[\w@.-]+\.(?:ts|tsx|js|jsx|json|md|yml|yaml|sql|py|go|rs|sh|css|html)/g) ?? []).slice(0, 10)
6533
+ );
6534
+ for (const filePath of pathMatches) {
6535
+ pushUniqueEntity(entities, seen, filePath, "file");
6536
+ pushHeuristicRelationship(relationships, agentId, "person", filePath, "file", "uses", 0.65);
6537
+ }
6538
+ const backtickTerms = [...content.matchAll(/`([^`\n]{2,80})`/g)].map((m) => m[1]).slice(0, 10);
6539
+ for (const term of backtickTerms) {
6540
+ if (!term || term.length < 2) continue;
6541
+ const type = term.includes("/") || /\.[A-Za-z0-9]{1,10}$/.test(term) ? "file" : "concept";
6542
+ pushUniqueEntity(entities, seen, term, type);
6543
+ pushHeuristicRelationship(relationships, agentId, "person", term, type, "uses", 0.55);
6544
+ }
6545
+ return { entities, relationships, hyperedges: [] };
6546
+ }
6001
6547
  async function extractFromMemory(content, agentId, model = "claude-haiku-4-5-20251001", filePath) {
6002
6548
  if (content.length < 50) {
6003
6549
  return { entities: [], relationships: [], hyperedges: [] };
@@ -6053,7 +6599,7 @@ async function extractFromMemory(content, agentId, model = "claude-haiku-4-5-202
6053
6599
  `
6054
6600
  );
6055
6601
  }
6056
- return { entities: [], relationships: [], hyperedges: [] };
6602
+ return extractHeuristicMemoryGraph(content, agentId);
6057
6603
  }
6058
6604
  async function storeExtraction(client, extraction, memoryId, timestamp) {
6059
6605
  let entitiesStored = 0;