@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
package/dist/tui/App.js CHANGED
@@ -500,6 +500,11 @@ function normalizeAutoUpdate(raw) {
500
500
  const userAU = raw.autoUpdate ?? {};
501
501
  raw.autoUpdate = { ...defaultAU, ...userAU };
502
502
  }
503
+ function normalizeOrchestration(raw) {
504
+ const defaultOrg = DEFAULT_CONFIG.orchestration;
505
+ const userOrg = raw.orchestration ?? {};
506
+ raw.orchestration = { ...defaultOrg, ...userOrg };
507
+ }
503
508
  async function loadConfig() {
504
509
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
505
510
  await ensurePrivateDir(dir);
@@ -524,10 +529,15 @@ async function loadConfig() {
524
529
  normalizeScalingRoadmap(migratedCfg);
525
530
  normalizeSessionLifecycle(migratedCfg);
526
531
  normalizeAutoUpdate(migratedCfg);
532
+ normalizeOrchestration(migratedCfg);
527
533
  const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
528
534
  if (config.dbPath.startsWith("~")) {
529
535
  config.dbPath = config.dbPath.replace(/^~/, os2.homedir());
530
536
  }
537
+ const envDbPath = path2.join(dir, "memories.db");
538
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync4(config.dbPath) && existsSync4(envDbPath)) {
539
+ config.dbPath = envDbPath;
540
+ }
531
541
  return config;
532
542
  } catch {
533
543
  return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
@@ -547,7 +557,16 @@ function loadConfigSync() {
547
557
  normalizeScalingRoadmap(migratedCfg);
548
558
  normalizeSessionLifecycle(migratedCfg);
549
559
  normalizeAutoUpdate(migratedCfg);
550
- return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
560
+ normalizeOrchestration(migratedCfg);
561
+ const config = { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db"), ...migratedCfg };
562
+ if (config.dbPath.startsWith("~")) {
563
+ config.dbPath = config.dbPath.replace(/^~/, os2.homedir());
564
+ }
565
+ const envDbPath = path2.join(dir, "memories.db");
566
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync4(config.dbPath) && existsSync4(envDbPath)) {
567
+ config.dbPath = envDbPath;
568
+ }
569
+ return config;
551
570
  } catch {
552
571
  return { ...DEFAULT_CONFIG, dbPath: path2.join(dir, "memories.db") };
553
572
  }
@@ -568,6 +587,7 @@ async function loadConfigFrom(configPath) {
568
587
  normalizeScalingRoadmap(migratedCfg);
569
588
  normalizeSessionLifecycle(migratedCfg);
570
589
  normalizeAutoUpdate(migratedCfg);
590
+ normalizeOrchestration(migratedCfg);
571
591
  return { ...DEFAULT_CONFIG, ...migratedCfg };
572
592
  } catch {
573
593
  return { ...DEFAULT_CONFIG };
@@ -639,6 +659,10 @@ var init_config = __esm({
639
659
  checkOnBoot: true,
640
660
  autoInstall: false,
641
661
  checkIntervalMs: 24 * 60 * 60 * 1e3
662
+ },
663
+ orchestration: {
664
+ phase: "phase_1_coo",
665
+ phaseSetBy: "default"
642
666
  }
643
667
  };
644
668
  CONFIG_MIGRATIONS = [
@@ -2545,6 +2569,9 @@ function getClient() {
2545
2569
  if (_daemonClient && _daemonClient._isDaemonActive()) {
2546
2570
  return _daemonClient;
2547
2571
  }
2572
+ if (!_resilientClient) {
2573
+ return _adapterClient;
2574
+ }
2548
2575
  return _resilientClient;
2549
2576
  }
2550
2577
  async function initDaemonClient() {
@@ -3577,6 +3604,127 @@ async function ensureSchema() {
3577
3604
  VALUES (new.rowid, new.content, new.subject, new.predicate, new.object);
3578
3605
  END;
3579
3606
  `);
3607
+ await client.executeMultiple(`
3608
+ CREATE TABLE IF NOT EXISTS agent_sessions (
3609
+ id TEXT PRIMARY KEY,
3610
+ agent_id TEXT NOT NULL,
3611
+ project_name TEXT,
3612
+ started_at TEXT NOT NULL,
3613
+ last_event_at TEXT NOT NULL,
3614
+ event_count INTEGER NOT NULL DEFAULT 0,
3615
+ properties TEXT DEFAULT '{}'
3616
+ );
3617
+
3618
+ CREATE INDEX IF NOT EXISTS idx_agent_sessions_agent_time
3619
+ ON agent_sessions(agent_id, started_at);
3620
+
3621
+ CREATE TABLE IF NOT EXISTS agent_goals (
3622
+ id TEXT PRIMARY KEY,
3623
+ statement TEXT NOT NULL,
3624
+ owner_agent_id TEXT,
3625
+ project_name TEXT,
3626
+ status TEXT NOT NULL DEFAULT 'open',
3627
+ priority INTEGER NOT NULL DEFAULT 5,
3628
+ success_criteria TEXT,
3629
+ parent_goal_id TEXT,
3630
+ due_at TEXT,
3631
+ achieved_at TEXT,
3632
+ supersedes_id TEXT,
3633
+ created_at TEXT NOT NULL,
3634
+ updated_at TEXT NOT NULL,
3635
+ source_memory_id TEXT
3636
+ );
3637
+
3638
+ CREATE INDEX IF NOT EXISTS idx_agent_goals_project_status
3639
+ ON agent_goals(project_name, status, priority);
3640
+
3641
+ CREATE TABLE IF NOT EXISTS agent_events (
3642
+ id TEXT PRIMARY KEY,
3643
+ event_type TEXT NOT NULL,
3644
+ occurred_at TEXT NOT NULL,
3645
+ sequence_index INTEGER NOT NULL,
3646
+ actor_agent_id TEXT,
3647
+ agent_role TEXT,
3648
+ project_name TEXT,
3649
+ session_id TEXT,
3650
+ task_id TEXT,
3651
+ goal_id TEXT,
3652
+ parent_event_id TEXT,
3653
+ intention TEXT,
3654
+ outcome TEXT,
3655
+ evidence_memory_id TEXT,
3656
+ impact TEXT,
3657
+ payload TEXT DEFAULT '{}',
3658
+ created_at TEXT NOT NULL
3659
+ );
3660
+
3661
+ CREATE INDEX IF NOT EXISTS idx_agent_events_time
3662
+ ON agent_events(occurred_at, sequence_index);
3663
+
3664
+ CREATE INDEX IF NOT EXISTS idx_agent_events_session_seq
3665
+ ON agent_events(session_id, sequence_index);
3666
+
3667
+ CREATE INDEX IF NOT EXISTS idx_agent_events_goal_time
3668
+ ON agent_events(goal_id, occurred_at);
3669
+
3670
+ CREATE INDEX IF NOT EXISTS idx_agent_events_memory
3671
+ ON agent_events(evidence_memory_id);
3672
+
3673
+ CREATE TABLE IF NOT EXISTS agent_goal_links (
3674
+ id TEXT PRIMARY KEY,
3675
+ goal_id TEXT NOT NULL,
3676
+ link_type TEXT NOT NULL,
3677
+ target_id TEXT NOT NULL,
3678
+ target_type TEXT NOT NULL,
3679
+ created_at TEXT NOT NULL
3680
+ );
3681
+
3682
+ CREATE INDEX IF NOT EXISTS idx_agent_goal_links_goal
3683
+ ON agent_goal_links(goal_id, target_type);
3684
+
3685
+ CREATE TABLE IF NOT EXISTS agent_semantic_labels (
3686
+ id TEXT PRIMARY KEY,
3687
+ source_memory_id TEXT NOT NULL,
3688
+ event_id TEXT,
3689
+ labeler TEXT NOT NULL,
3690
+ schema_version INTEGER NOT NULL DEFAULT 1,
3691
+ confidence REAL NOT NULL DEFAULT 0,
3692
+ labels TEXT NOT NULL,
3693
+ created_at TEXT NOT NULL,
3694
+ updated_at TEXT NOT NULL
3695
+ );
3696
+
3697
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_memory
3698
+ ON agent_semantic_labels(source_memory_id, labeler);
3699
+
3700
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_event
3701
+ ON agent_semantic_labels(event_id);
3702
+
3703
+ CREATE TABLE IF NOT EXISTS agent_reflection_checkpoints (
3704
+ id TEXT PRIMARY KEY,
3705
+ project_name TEXT,
3706
+ session_id TEXT,
3707
+ window_start_at TEXT NOT NULL,
3708
+ window_end_at TEXT NOT NULL,
3709
+ event_count INTEGER NOT NULL DEFAULT 0,
3710
+ goal_count INTEGER NOT NULL DEFAULT 0,
3711
+ success_count INTEGER NOT NULL DEFAULT 0,
3712
+ failure_count INTEGER NOT NULL DEFAULT 0,
3713
+ risk_count INTEGER NOT NULL DEFAULT 0,
3714
+ summary TEXT NOT NULL,
3715
+ learnings TEXT NOT NULL DEFAULT '[]',
3716
+ next_actions TEXT NOT NULL DEFAULT '[]',
3717
+ evidence_event_ids TEXT NOT NULL DEFAULT '[]',
3718
+ confidence REAL NOT NULL DEFAULT 0,
3719
+ created_at TEXT NOT NULL
3720
+ );
3721
+
3722
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_project_time
3723
+ ON agent_reflection_checkpoints(project_name, window_end_at);
3724
+
3725
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_session_time
3726
+ ON agent_reflection_checkpoints(session_id, window_end_at);
3727
+ `);
3580
3728
  try {
3581
3729
  await client.execute({
3582
3730
  sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
@@ -3985,8 +4133,8 @@ async function validateLicense(apiKey, deviceId) {
3985
4133
  }
3986
4134
  function getCacheAgeMs() {
3987
4135
  try {
3988
- const { statSync: statSync3 } = __require("fs");
3989
- const s = statSync3(CACHE_PATH);
4136
+ const { statSync: statSync4 } = __require("fs");
4137
+ const s = statSync4(CACHE_PATH);
3990
4138
  return Date.now() - s.mtimeMs;
3991
4139
  } catch {
3992
4140
  return Infinity;
@@ -8707,6 +8855,12 @@ var init_platform_procedures = __esm({
8707
8855
  priority: "p0",
8708
8856
  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."
8709
8857
  },
8858
+ {
8859
+ title: "Customer orchestration maturity \u2014 recommend, never trap",
8860
+ domain: "workflow",
8861
+ priority: "p1",
8862
+ 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."
8863
+ },
8710
8864
  {
8711
8865
  title: "Single dispatch path \u2014 create_task only",
8712
8866
  domain: "workflow",
@@ -8765,6 +8919,12 @@ var init_platform_procedures = __esm({
8765
8919
  priority: "p0",
8766
8920
  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."
8767
8921
  },
8922
+ {
8923
+ title: "Commit discipline \u2014 never leave verified work floating",
8924
+ domain: "workflow",
8925
+ priority: "p1",
8926
+ 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."
8927
+ },
8768
8928
  {
8769
8929
  title: "Desktop and TUI are the same product",
8770
8930
  domain: "architecture",
@@ -10589,12 +10749,13 @@ var keychain_exports = {};
10589
10749
  __export(keychain_exports, {
10590
10750
  deleteMasterKey: () => deleteMasterKey,
10591
10751
  exportMnemonic: () => exportMnemonic,
10752
+ getKeyStorageInfo: () => getKeyStorageInfo,
10592
10753
  getMasterKey: () => getMasterKey,
10593
10754
  importMnemonic: () => importMnemonic,
10594
10755
  setMasterKey: () => setMasterKey
10595
10756
  });
10596
10757
  import { readFile as readFile4, writeFile as writeFile5, unlink, mkdir as mkdir4, chmod as chmod2 } from "fs/promises";
10597
- import { existsSync as existsSync17 } from "fs";
10758
+ import { existsSync as existsSync17, statSync as statSync2 } from "fs";
10598
10759
  import { execSync as execSync9 } from "child_process";
10599
10760
  import path27 from "path";
10600
10761
  import os13 from "os";
@@ -10604,29 +10765,65 @@ function getKeyDir() {
10604
10765
  function getKeyPath() {
10605
10766
  return path27.join(getKeyDir(), "master.key");
10606
10767
  }
10607
- function macKeychainGet() {
10768
+ function nativeKeychainAllowed() {
10769
+ return process.env.EXE_OS_DISABLE_NATIVE_KEYCHAIN !== "1";
10770
+ }
10771
+ function linuxSecretAvailable() {
10772
+ if (!nativeKeychainAllowed()) return false;
10773
+ if (process.platform !== "linux") return false;
10774
+ if (linuxSecretAvailability !== null) return linuxSecretAvailability;
10775
+ try {
10776
+ execSync9("command -v secret-tool >/dev/null 2>&1", { timeout: 1e3 });
10777
+ } catch {
10778
+ linuxSecretAvailability = false;
10779
+ return false;
10780
+ }
10781
+ try {
10782
+ execSync9("secret-tool search --all exe-os probe >/dev/null 2>&1", { timeout: 1e3 });
10783
+ linuxSecretAvailability = true;
10784
+ } catch {
10785
+ linuxSecretAvailability = false;
10786
+ }
10787
+ return linuxSecretAvailability;
10788
+ }
10789
+ function isRootOnlyTrustedServerKeyFile(keyPath) {
10790
+ if (process.platform !== "linux") return false;
10791
+ try {
10792
+ const uid = typeof os13.userInfo().uid === "number" ? os13.userInfo().uid : -1;
10793
+ const st = statSync2(keyPath);
10794
+ if (!st.isFile() || (st.mode & 63) !== 0) return false;
10795
+ if (uid === 0) return true;
10796
+ const exeOsDir = process.env.EXE_OS_DIR;
10797
+ return Boolean(exeOsDir && path27.resolve(keyPath).startsWith(path27.resolve(exeOsDir) + path27.sep));
10798
+ } catch {
10799
+ return false;
10800
+ }
10801
+ }
10802
+ function macKeychainGet(service = SERVICE) {
10803
+ if (!nativeKeychainAllowed()) return null;
10608
10804
  if (process.platform !== "darwin") return null;
10609
10805
  try {
10610
10806
  return execSync9(
10611
- `security find-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w 2>/dev/null`,
10807
+ `security find-generic-password -s "${service}" -a "${ACCOUNT}" -w 2>/dev/null`,
10612
10808
  { encoding: "utf-8", timeout: 5e3 }
10613
10809
  ).trim();
10614
10810
  } catch {
10615
10811
  return null;
10616
10812
  }
10617
10813
  }
10618
- function macKeychainSet(value) {
10814
+ function macKeychainSet(value, service = SERVICE) {
10815
+ if (!nativeKeychainAllowed()) return false;
10619
10816
  if (process.platform !== "darwin") return false;
10620
10817
  try {
10621
10818
  try {
10622
10819
  execSync9(
10623
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
10820
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
10624
10821
  { timeout: 5e3 }
10625
10822
  );
10626
10823
  } catch {
10627
10824
  }
10628
10825
  execSync9(
10629
- `security add-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w "${value}"`,
10826
+ `security add-generic-password -s "${service}" -a "${ACCOUNT}" -w "${value}"`,
10630
10827
  { timeout: 5e3 }
10631
10828
  );
10632
10829
  return true;
@@ -10634,11 +10831,12 @@ function macKeychainSet(value) {
10634
10831
  return false;
10635
10832
  }
10636
10833
  }
10637
- function macKeychainDelete() {
10834
+ function macKeychainDelete(service = SERVICE) {
10835
+ if (!nativeKeychainAllowed()) return false;
10638
10836
  if (process.platform !== "darwin") return false;
10639
10837
  try {
10640
10838
  execSync9(
10641
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
10839
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
10642
10840
  { timeout: 5e3 }
10643
10841
  );
10644
10842
  return true;
@@ -10646,22 +10844,22 @@ function macKeychainDelete() {
10646
10844
  return false;
10647
10845
  }
10648
10846
  }
10649
- function linuxSecretGet() {
10650
- if (process.platform !== "linux") return null;
10847
+ function linuxSecretGet(service = SERVICE) {
10848
+ if (!linuxSecretAvailable()) return null;
10651
10849
  try {
10652
10850
  return execSync9(
10653
- `secret-tool lookup service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
10851
+ `secret-tool lookup service "${service}" account "${ACCOUNT}" 2>/dev/null`,
10654
10852
  { encoding: "utf-8", timeout: 5e3 }
10655
10853
  ).trim();
10656
10854
  } catch {
10657
10855
  return null;
10658
10856
  }
10659
10857
  }
10660
- function linuxSecretSet(value) {
10661
- if (process.platform !== "linux") return false;
10858
+ function linuxSecretSet(value, service = SERVICE) {
10859
+ if (!linuxSecretAvailable()) return false;
10662
10860
  try {
10663
10861
  execSync9(
10664
- `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${SERVICE}" account "${ACCOUNT}"`,
10862
+ `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${service}" account "${ACCOUNT}" 2>/dev/null`,
10665
10863
  { timeout: 5e3 }
10666
10864
  );
10667
10865
  return true;
@@ -10669,11 +10867,12 @@ function linuxSecretSet(value) {
10669
10867
  return false;
10670
10868
  }
10671
10869
  }
10672
- function linuxSecretDelete() {
10870
+ function linuxSecretDelete(service = SERVICE) {
10871
+ if (!nativeKeychainAllowed()) return false;
10673
10872
  if (process.platform !== "linux") return false;
10674
10873
  try {
10675
10874
  execSync9(
10676
- `secret-tool clear service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
10875
+ `secret-tool clear service "${service}" account "${ACCOUNT}" 2>/dev/null`,
10677
10876
  { timeout: 5e3 }
10678
10877
  );
10679
10878
  return true;
@@ -10682,6 +10881,7 @@ function linuxSecretDelete() {
10682
10881
  }
10683
10882
  }
10684
10883
  async function tryKeytar() {
10884
+ if (!nativeKeychainAllowed()) return null;
10685
10885
  try {
10686
10886
  return await import("keytar");
10687
10887
  } catch {
@@ -10755,7 +10955,19 @@ async function writeMachineBoundFileFallback(b64) {
10755
10955
  return "plaintext";
10756
10956
  }
10757
10957
  async function getMasterKey() {
10758
- const nativeValue = macKeychainGet() ?? linuxSecretGet();
10958
+ let nativeValue = macKeychainGet() ?? linuxSecretGet();
10959
+ if (!nativeValue) {
10960
+ const legacyValue = macKeychainGet(LEGACY_SERVICE) ?? linuxSecretGet(LEGACY_SERVICE);
10961
+ if (legacyValue) {
10962
+ const migrated = macKeychainSet(legacyValue) || linuxSecretSet(legacyValue);
10963
+ if (migrated) {
10964
+ macKeychainDelete(LEGACY_SERVICE);
10965
+ linuxSecretDelete(LEGACY_SERVICE);
10966
+ process.stderr.write("[keychain] Migrated keychain service from exe-mem to exe-os.\n");
10967
+ }
10968
+ nativeValue = legacyValue;
10969
+ }
10970
+ }
10759
10971
  if (nativeValue) {
10760
10972
  return Buffer.from(nativeValue, "base64");
10761
10973
  }
@@ -10763,12 +10975,17 @@ async function getMasterKey() {
10763
10975
  if (keytar) {
10764
10976
  try {
10765
10977
  const keytarValue = await keytar.getPassword(SERVICE, ACCOUNT);
10766
- if (keytarValue) {
10767
- const migrated = macKeychainSet(keytarValue) || linuxSecretSet(keytarValue);
10978
+ const legacyKeytarValue = keytarValue ?? await keytar.getPassword(LEGACY_SERVICE, ACCOUNT);
10979
+ if (legacyKeytarValue) {
10980
+ const migrated = macKeychainSet(legacyKeytarValue) || linuxSecretSet(legacyKeytarValue);
10768
10981
  if (migrated) {
10769
10982
  process.stderr.write("[keychain] Migrated key from keytar to native keychain.\n");
10983
+ try {
10984
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
10985
+ } catch {
10986
+ }
10770
10987
  }
10771
- return Buffer.from(keytarValue, "base64");
10988
+ return Buffer.from(legacyKeytarValue, "base64");
10772
10989
  }
10773
10990
  } catch {
10774
10991
  }
@@ -10793,7 +11010,7 @@ async function getMasterKey() {
10793
11010
  const decrypted = decryptWithMachineKey(content, machineKey);
10794
11011
  if (!decrypted) {
10795
11012
  process.stderr.write(
10796
- "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase: exe-os link import\n"
11013
+ "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase during setup: exe-os setup\n"
10797
11014
  );
10798
11015
  return null;
10799
11016
  }
@@ -10802,6 +11019,9 @@ async function getMasterKey() {
10802
11019
  b64Value = content;
10803
11020
  }
10804
11021
  const key = Buffer.from(b64Value, "base64");
11022
+ if (!content.startsWith(ENCRYPTED_PREFIX) && isRootOnlyTrustedServerKeyFile(keyPath)) {
11023
+ return key;
11024
+ }
10805
11025
  const migrated = macKeychainSet(b64Value) || linuxSecretSet(b64Value);
10806
11026
  if (migrated) {
10807
11027
  process.stderr.write("[keychain] Migrated key from file to native keychain.\n");
@@ -10829,6 +11049,97 @@ async function getMasterKey() {
10829
11049
  return null;
10830
11050
  }
10831
11051
  }
11052
+ async function getKeyStorageInfo() {
11053
+ if (macKeychainGet()) {
11054
+ return {
11055
+ kind: "macos-keychain",
11056
+ secure: true,
11057
+ note: "stored in macOS Keychain via built-in security CLI"
11058
+ };
11059
+ }
11060
+ if (macKeychainGet(LEGACY_SERVICE)) {
11061
+ return {
11062
+ kind: "macos-keychain",
11063
+ secure: true,
11064
+ note: "stored in legacy macOS Keychain service exe-mem; next key read migrates it to exe-os"
11065
+ };
11066
+ }
11067
+ if (linuxSecretGet()) {
11068
+ return {
11069
+ kind: "linux-secret-service",
11070
+ secure: true,
11071
+ note: "stored in Linux Secret Service via secret-tool"
11072
+ };
11073
+ }
11074
+ if (linuxSecretGet(LEGACY_SERVICE)) {
11075
+ return {
11076
+ kind: "linux-secret-service",
11077
+ secure: true,
11078
+ note: "stored in legacy Linux Secret Service service exe-mem; next key read migrates it to exe-os"
11079
+ };
11080
+ }
11081
+ const keytar = await tryKeytar();
11082
+ if (keytar) {
11083
+ try {
11084
+ if (await keytar.getPassword(SERVICE, ACCOUNT)) {
11085
+ return {
11086
+ kind: "legacy-keytar",
11087
+ secure: true,
11088
+ note: "stored in legacy keytar backend; will migrate to native keychain when possible"
11089
+ };
11090
+ }
11091
+ if (await keytar.getPassword(LEGACY_SERVICE, ACCOUNT)) {
11092
+ return {
11093
+ kind: "legacy-keytar",
11094
+ secure: true,
11095
+ note: "stored in legacy keytar service exe-mem; will migrate to native exe-os keychain when possible"
11096
+ };
11097
+ }
11098
+ } catch {
11099
+ }
11100
+ }
11101
+ const keyPath = getKeyPath();
11102
+ if (!existsSync17(keyPath)) {
11103
+ return {
11104
+ kind: "missing",
11105
+ secure: false,
11106
+ path: keyPath,
11107
+ note: "no key found in OS keychain, legacy keytar, or file fallback"
11108
+ };
11109
+ }
11110
+ try {
11111
+ const content = (await readFile4(keyPath, "utf-8")).trim();
11112
+ if (content.startsWith(ENCRYPTED_PREFIX)) {
11113
+ return {
11114
+ kind: "encrypted-file",
11115
+ secure: true,
11116
+ path: keyPath,
11117
+ note: "stored in machine-bound encrypted file fallback"
11118
+ };
11119
+ }
11120
+ if (isRootOnlyTrustedServerKeyFile(keyPath)) {
11121
+ return {
11122
+ kind: "server-secret-file",
11123
+ secure: true,
11124
+ path: keyPath,
11125
+ note: "stored as root-only trusted server secret file"
11126
+ };
11127
+ }
11128
+ return {
11129
+ kind: "plaintext-file",
11130
+ secure: false,
11131
+ path: keyPath,
11132
+ note: "stored in legacy plaintext file; reading it will migrate or encrypt it"
11133
+ };
11134
+ } catch {
11135
+ return {
11136
+ kind: "missing",
11137
+ secure: false,
11138
+ path: keyPath,
11139
+ note: "key file exists but could not be read"
11140
+ };
11141
+ }
11142
+ }
10832
11143
  async function setMasterKey(key) {
10833
11144
  const b64 = key.toString("base64");
10834
11145
  if (macKeychainSet(b64) || linuxSecretSet(b64)) {
@@ -10854,10 +11165,13 @@ async function setMasterKey(key) {
10854
11165
  async function deleteMasterKey() {
10855
11166
  macKeychainDelete();
10856
11167
  linuxSecretDelete();
11168
+ macKeychainDelete(LEGACY_SERVICE);
11169
+ linuxSecretDelete(LEGACY_SERVICE);
10857
11170
  const keytar = await tryKeytar();
10858
11171
  if (keytar) {
10859
11172
  try {
10860
11173
  await keytar.deletePassword(SERVICE, ACCOUNT);
11174
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
10861
11175
  } catch {
10862
11176
  }
10863
11177
  }
@@ -10895,12 +11209,14 @@ async function importMnemonic(mnemonic) {
10895
11209
  const entropy = mnemonicToEntropy(trimmed);
10896
11210
  return Buffer.from(entropy, "hex");
10897
11211
  }
10898
- var SERVICE, ACCOUNT, ENCRYPTED_PREFIX;
11212
+ var SERVICE, LEGACY_SERVICE, ACCOUNT, linuxSecretAvailability, ENCRYPTED_PREFIX;
10899
11213
  var init_keychain = __esm({
10900
11214
  "src/lib/keychain.ts"() {
10901
11215
  "use strict";
10902
- SERVICE = "exe-mem";
11216
+ SERVICE = "exe-os";
11217
+ LEGACY_SERVICE = "exe-mem";
10903
11218
  ACCOUNT = "master-key";
11219
+ linuxSecretAvailability = null;
10904
11220
  ENCRYPTED_PREFIX = "enc:";
10905
11221
  }
10906
11222
  });
@@ -11506,7 +11822,7 @@ __export(shard_manager_exports, {
11506
11822
  shardExists: () => shardExists
11507
11823
  });
11508
11824
  import path28 from "path";
11509
- import { existsSync as existsSync18, mkdirSync as mkdirSync8, readdirSync as readdirSync4, renameSync as renameSync4, statSync as statSync2 } from "fs";
11825
+ import { existsSync as existsSync18, mkdirSync as mkdirSync8, readdirSync as readdirSync4, renameSync as renameSync4, statSync as statSync3 } from "fs";
11510
11826
  import { createClient as createClient2 } from "@libsql/client";
11511
11827
  function initShardManager(encryptionKey) {
11512
11828
  _encryptionKey = encryptionKey;
@@ -11570,7 +11886,7 @@ async function auditShardHealth(options = {}) {
11570
11886
  const shards = [];
11571
11887
  for (const name of names) {
11572
11888
  const dbPath = path28.join(SHARDS_DIR, `${name}.db`);
11573
- const stat = statSync2(dbPath);
11889
+ const stat = statSync3(dbPath);
11574
11890
  const item = {
11575
11891
  name,
11576
11892
  path: dbPath,
@@ -11823,7 +12139,7 @@ async function getReadyShardClient(projectName) {
11823
12139
  _shardLastAccess.delete(safeName);
11824
12140
  const dbPath = path28.join(SHARDS_DIR, `${safeName}.db`);
11825
12141
  if (existsSync18(dbPath)) {
11826
- const stat = statSync2(dbPath);
12142
+ const stat = statSync3(dbPath);
11827
12143
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
11828
12144
  const archivedPath = path28.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
11829
12145
  renameSync4(dbPath, archivedPath);
@@ -12063,6 +12379,274 @@ var init_memory_cards = __esm({
12063
12379
  }
12064
12380
  });
12065
12381
 
12382
+ // src/lib/agentic-ontology.ts
12383
+ var agentic_ontology_exports = {};
12384
+ __export(agentic_ontology_exports, {
12385
+ clean: () => clean,
12386
+ extractGoalCandidates: () => extractGoalCandidates,
12387
+ inferIntention: () => inferIntention,
12388
+ inferOntologyEventType: () => inferOntologyEventType,
12389
+ inferOutcome: () => inferOutcome,
12390
+ inferSemanticLabel: () => inferSemanticLabel,
12391
+ insertOntologyForBatch: () => insertOntologyForBatch,
12392
+ insertOntologyForMemory: () => insertOntologyForMemory,
12393
+ ontologyPayload: () => ontologyPayload,
12394
+ stableId: () => stableId2
12395
+ });
12396
+ import { createHash as createHash3 } from "crypto";
12397
+ function stableId2(...parts) {
12398
+ return createHash3("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
12399
+ }
12400
+ function clean(text, max = 240) {
12401
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
12402
+ }
12403
+ function inferOntologyEventType(row) {
12404
+ const lower = row.raw_text.toLowerCase();
12405
+ if (row.has_error) return "error";
12406
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
12407
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
12408
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
12409
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
12410
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
12411
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
12412
+ return "memory_observation";
12413
+ }
12414
+ function inferIntention(row) {
12415
+ if (row.intent) return clean(row.intent, 220);
12416
+ const text = clean(row.raw_text, 1e3);
12417
+ const patterns = [
12418
+ /(?: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,
12419
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
12420
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
12421
+ ];
12422
+ for (const p of patterns) {
12423
+ const m = text.match(p);
12424
+ if (m?.[1]) return clean(m[1], 220);
12425
+ }
12426
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
12427
+ return `${row.tool_name} during ${row.project_name}`;
12428
+ }
12429
+ return null;
12430
+ }
12431
+ function inferOutcome(row) {
12432
+ if (row.outcome) return clean(row.outcome, 220);
12433
+ if (row.has_error) return "error";
12434
+ const lower = row.raw_text.toLowerCase();
12435
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
12436
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
12437
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
12438
+ return null;
12439
+ }
12440
+ function extractGoalCandidates(row) {
12441
+ const text = clean(row.raw_text, 1600);
12442
+ const patterns = [
12443
+ /(?: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,
12444
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
12445
+ ];
12446
+ const out = [];
12447
+ for (const pattern of patterns) {
12448
+ for (const m of text.matchAll(pattern)) {
12449
+ const candidate = clean(m[1] ?? "", 220);
12450
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
12451
+ if (out.length >= 3) return out;
12452
+ }
12453
+ }
12454
+ return out;
12455
+ }
12456
+ function uniq(values, max = 6) {
12457
+ const out = [];
12458
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
12459
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
12460
+ if (out.length >= max) break;
12461
+ }
12462
+ return out;
12463
+ }
12464
+ function extractMatches(text, patterns, max = 5) {
12465
+ const out = [];
12466
+ for (const pattern of patterns) {
12467
+ for (const match of text.matchAll(pattern)) {
12468
+ const value = match[1] ?? match[0];
12469
+ if (value) out.push(value);
12470
+ if (out.length >= max) return uniq(out, max);
12471
+ }
12472
+ }
12473
+ return uniq(out, max);
12474
+ }
12475
+ function inferSemanticLabel(row) {
12476
+ const text = clean(row.raw_text, 2400);
12477
+ const eventType = inferOntologyEventType(row);
12478
+ const intention = inferIntention(row);
12479
+ const outcome = inferOutcome(row);
12480
+ const goals = extractGoalCandidates(row);
12481
+ const milestones = extractMatches(text, [
12482
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
12483
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
12484
+ ]);
12485
+ const problems = extractMatches(text, [
12486
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
12487
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
12488
+ ]);
12489
+ const decisions = extractMatches(text, [
12490
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
12491
+ ]);
12492
+ const temporalAnchors = extractMatches(text, [
12493
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
12494
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
12495
+ ], 8);
12496
+ const nextActions = extractMatches(text, [
12497
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
12498
+ ]);
12499
+ const actors = uniq([
12500
+ row.agent_id,
12501
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
12502
+ ], 6);
12503
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
12504
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
12505
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
12506
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
12507
+ return {
12508
+ labeler: "deterministic",
12509
+ schemaVersion: 1,
12510
+ eventType,
12511
+ intention,
12512
+ outcome,
12513
+ impact,
12514
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
12515
+ goals,
12516
+ milestones,
12517
+ problems,
12518
+ decisions,
12519
+ actors,
12520
+ temporalAnchors,
12521
+ successSignals,
12522
+ failureSignals,
12523
+ nextActions,
12524
+ summary: clean(text, 280)
12525
+ };
12526
+ }
12527
+ function ontologyPayload(row) {
12528
+ const semantic = inferSemanticLabel(row);
12529
+ return {
12530
+ tool_name: row.tool_name,
12531
+ memory_version: row.version ?? null,
12532
+ domain: row.domain ?? null,
12533
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
12534
+ semantic
12535
+ };
12536
+ }
12537
+ function safeJson(value) {
12538
+ try {
12539
+ return JSON.parse(value);
12540
+ } catch {
12541
+ return value.slice(0, 1e3);
12542
+ }
12543
+ }
12544
+ async function resolveClient(client) {
12545
+ if (client) return client;
12546
+ const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
12547
+ return getClient2();
12548
+ }
12549
+ async function insertOntologyForMemory(row, client) {
12550
+ const db = await resolveClient(client);
12551
+ const occurredAt = row.timestamp;
12552
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
12553
+ const eventType = inferOntologyEventType(row);
12554
+ const intention = inferIntention(row);
12555
+ const outcome = inferOutcome(row);
12556
+ const eventId = stableId2("event", row.id);
12557
+ const now = (/* @__PURE__ */ new Date()).toISOString();
12558
+ await db.execute({
12559
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
12560
+ VALUES (?, ?, ?, ?, ?, 1, ?)
12561
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
12562
+ event_count = event_count + 1`,
12563
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
12564
+ });
12565
+ await db.execute({
12566
+ sql: `INSERT OR IGNORE INTO agent_events
12567
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
12568
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
12569
+ impact, payload, created_at)
12570
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
12571
+ args: [
12572
+ eventId,
12573
+ eventType,
12574
+ occurredAt,
12575
+ sequence,
12576
+ row.agent_id,
12577
+ row.agent_role,
12578
+ row.project_name,
12579
+ row.session_id,
12580
+ row.task_id ?? null,
12581
+ intention,
12582
+ outcome,
12583
+ row.id,
12584
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
12585
+ JSON.stringify(ontologyPayload(row)),
12586
+ now
12587
+ ]
12588
+ });
12589
+ const semantic = inferSemanticLabel(row);
12590
+ await db.execute({
12591
+ sql: `INSERT INTO agent_semantic_labels
12592
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
12593
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
12594
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
12595
+ labels = excluded.labels, updated_at = excluded.updated_at`,
12596
+ args: [
12597
+ stableId2("semantic", row.id, semantic.labeler, semantic.schemaVersion),
12598
+ row.id,
12599
+ eventId,
12600
+ semantic.labeler,
12601
+ semantic.schemaVersion,
12602
+ semantic.confidence,
12603
+ JSON.stringify(semantic),
12604
+ now,
12605
+ now
12606
+ ]
12607
+ });
12608
+ for (const statement of extractGoalCandidates(row)) {
12609
+ const goalId = stableId2("goal", row.project_name, statement.toLowerCase());
12610
+ await db.execute({
12611
+ sql: `INSERT INTO agent_goals
12612
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
12613
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
12614
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
12615
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
12616
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
12617
+ });
12618
+ await db.execute({
12619
+ sql: `INSERT OR IGNORE INTO agent_goal_links
12620
+ (id, goal_id, link_type, target_id, target_type, created_at)
12621
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
12622
+ args: [stableId2("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
12623
+ });
12624
+ await db.execute({
12625
+ sql: `INSERT OR IGNORE INTO agent_goal_links
12626
+ (id, goal_id, link_type, target_id, target_type, created_at)
12627
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
12628
+ args: [stableId2("goal_link", goalId, eventId, "event"), goalId, eventId, now]
12629
+ });
12630
+ }
12631
+ }
12632
+ async function insertOntologyForBatch(rows, client) {
12633
+ const db = await resolveClient(client);
12634
+ let count = 0;
12635
+ for (const row of rows) {
12636
+ try {
12637
+ await insertOntologyForMemory(row, db);
12638
+ count++;
12639
+ } catch {
12640
+ }
12641
+ }
12642
+ return count;
12643
+ }
12644
+ var init_agentic_ontology = __esm({
12645
+ "src/lib/agentic-ontology.ts"() {
12646
+ "use strict";
12647
+ }
12648
+ });
12649
+
12066
12650
  // src/lib/store.ts
12067
12651
  var store_exports = {};
12068
12652
  __export(store_exports, {
@@ -12406,6 +12990,11 @@ async function flushBatch() {
12406
12990
  await insertMemoryCardsForBatch2(batch);
12407
12991
  } catch {
12408
12992
  }
12993
+ try {
12994
+ const { insertOntologyForBatch: insertOntologyForBatch2 } = await Promise.resolve().then(() => (init_agentic_ontology(), agentic_ontology_exports));
12995
+ await insertOntologyForBatch2(batch);
12996
+ } catch {
12997
+ }
12409
12998
  schedulePostWriteMemoryHygiene(batch.map((row) => row.id));
12410
12999
  _pendingRecords.splice(0, batch.length);
12411
13000
  try {