@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
@@ -188,6 +188,11 @@ function normalizeAutoUpdate(raw) {
188
188
  const userAU = raw.autoUpdate ?? {};
189
189
  raw.autoUpdate = { ...defaultAU, ...userAU };
190
190
  }
191
+ function normalizeOrchestration(raw) {
192
+ const defaultOrg = DEFAULT_CONFIG.orchestration;
193
+ const userOrg = raw.orchestration ?? {};
194
+ raw.orchestration = { ...defaultOrg, ...userOrg };
195
+ }
191
196
  async function loadConfig() {
192
197
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
193
198
  await ensurePrivateDir(dir);
@@ -212,10 +217,15 @@ async function loadConfig() {
212
217
  normalizeScalingRoadmap(migratedCfg);
213
218
  normalizeSessionLifecycle(migratedCfg);
214
219
  normalizeAutoUpdate(migratedCfg);
220
+ normalizeOrchestration(migratedCfg);
215
221
  const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
216
222
  if (config.dbPath.startsWith("~")) {
217
223
  config.dbPath = config.dbPath.replace(/^~/, os.homedir());
218
224
  }
225
+ const envDbPath = path.join(dir, "memories.db");
226
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync2(config.dbPath) && existsSync2(envDbPath)) {
227
+ config.dbPath = envDbPath;
228
+ }
219
229
  return config;
220
230
  } catch {
221
231
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
@@ -287,6 +297,10 @@ var init_config = __esm({
287
297
  checkOnBoot: true,
288
298
  autoInstall: false,
289
299
  checkIntervalMs: 24 * 60 * 60 * 1e3
300
+ },
301
+ orchestration: {
302
+ phase: "phase_1_coo",
303
+ phaseSetBy: "default"
290
304
  }
291
305
  };
292
306
  CONFIG_MIGRATIONS = [
@@ -1659,6 +1673,9 @@ function getClient() {
1659
1673
  if (_daemonClient && _daemonClient._isDaemonActive()) {
1660
1674
  return _daemonClient;
1661
1675
  }
1676
+ if (!_resilientClient) {
1677
+ return _adapterClient;
1678
+ }
1662
1679
  return _resilientClient;
1663
1680
  }
1664
1681
  async function initDaemonClient() {
@@ -2691,6 +2708,127 @@ async function ensureSchema() {
2691
2708
  VALUES (new.rowid, new.content, new.subject, new.predicate, new.object);
2692
2709
  END;
2693
2710
  `);
2711
+ await client.executeMultiple(`
2712
+ CREATE TABLE IF NOT EXISTS agent_sessions (
2713
+ id TEXT PRIMARY KEY,
2714
+ agent_id TEXT NOT NULL,
2715
+ project_name TEXT,
2716
+ started_at TEXT NOT NULL,
2717
+ last_event_at TEXT NOT NULL,
2718
+ event_count INTEGER NOT NULL DEFAULT 0,
2719
+ properties TEXT DEFAULT '{}'
2720
+ );
2721
+
2722
+ CREATE INDEX IF NOT EXISTS idx_agent_sessions_agent_time
2723
+ ON agent_sessions(agent_id, started_at);
2724
+
2725
+ CREATE TABLE IF NOT EXISTS agent_goals (
2726
+ id TEXT PRIMARY KEY,
2727
+ statement TEXT NOT NULL,
2728
+ owner_agent_id TEXT,
2729
+ project_name TEXT,
2730
+ status TEXT NOT NULL DEFAULT 'open',
2731
+ priority INTEGER NOT NULL DEFAULT 5,
2732
+ success_criteria TEXT,
2733
+ parent_goal_id TEXT,
2734
+ due_at TEXT,
2735
+ achieved_at TEXT,
2736
+ supersedes_id TEXT,
2737
+ created_at TEXT NOT NULL,
2738
+ updated_at TEXT NOT NULL,
2739
+ source_memory_id TEXT
2740
+ );
2741
+
2742
+ CREATE INDEX IF NOT EXISTS idx_agent_goals_project_status
2743
+ ON agent_goals(project_name, status, priority);
2744
+
2745
+ CREATE TABLE IF NOT EXISTS agent_events (
2746
+ id TEXT PRIMARY KEY,
2747
+ event_type TEXT NOT NULL,
2748
+ occurred_at TEXT NOT NULL,
2749
+ sequence_index INTEGER NOT NULL,
2750
+ actor_agent_id TEXT,
2751
+ agent_role TEXT,
2752
+ project_name TEXT,
2753
+ session_id TEXT,
2754
+ task_id TEXT,
2755
+ goal_id TEXT,
2756
+ parent_event_id TEXT,
2757
+ intention TEXT,
2758
+ outcome TEXT,
2759
+ evidence_memory_id TEXT,
2760
+ impact TEXT,
2761
+ payload TEXT DEFAULT '{}',
2762
+ created_at TEXT NOT NULL
2763
+ );
2764
+
2765
+ CREATE INDEX IF NOT EXISTS idx_agent_events_time
2766
+ ON agent_events(occurred_at, sequence_index);
2767
+
2768
+ CREATE INDEX IF NOT EXISTS idx_agent_events_session_seq
2769
+ ON agent_events(session_id, sequence_index);
2770
+
2771
+ CREATE INDEX IF NOT EXISTS idx_agent_events_goal_time
2772
+ ON agent_events(goal_id, occurred_at);
2773
+
2774
+ CREATE INDEX IF NOT EXISTS idx_agent_events_memory
2775
+ ON agent_events(evidence_memory_id);
2776
+
2777
+ CREATE TABLE IF NOT EXISTS agent_goal_links (
2778
+ id TEXT PRIMARY KEY,
2779
+ goal_id TEXT NOT NULL,
2780
+ link_type TEXT NOT NULL,
2781
+ target_id TEXT NOT NULL,
2782
+ target_type TEXT NOT NULL,
2783
+ created_at TEXT NOT NULL
2784
+ );
2785
+
2786
+ CREATE INDEX IF NOT EXISTS idx_agent_goal_links_goal
2787
+ ON agent_goal_links(goal_id, target_type);
2788
+
2789
+ CREATE TABLE IF NOT EXISTS agent_semantic_labels (
2790
+ id TEXT PRIMARY KEY,
2791
+ source_memory_id TEXT NOT NULL,
2792
+ event_id TEXT,
2793
+ labeler TEXT NOT NULL,
2794
+ schema_version INTEGER NOT NULL DEFAULT 1,
2795
+ confidence REAL NOT NULL DEFAULT 0,
2796
+ labels TEXT NOT NULL,
2797
+ created_at TEXT NOT NULL,
2798
+ updated_at TEXT NOT NULL
2799
+ );
2800
+
2801
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_memory
2802
+ ON agent_semantic_labels(source_memory_id, labeler);
2803
+
2804
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_event
2805
+ ON agent_semantic_labels(event_id);
2806
+
2807
+ CREATE TABLE IF NOT EXISTS agent_reflection_checkpoints (
2808
+ id TEXT PRIMARY KEY,
2809
+ project_name TEXT,
2810
+ session_id TEXT,
2811
+ window_start_at TEXT NOT NULL,
2812
+ window_end_at TEXT NOT NULL,
2813
+ event_count INTEGER NOT NULL DEFAULT 0,
2814
+ goal_count INTEGER NOT NULL DEFAULT 0,
2815
+ success_count INTEGER NOT NULL DEFAULT 0,
2816
+ failure_count INTEGER NOT NULL DEFAULT 0,
2817
+ risk_count INTEGER NOT NULL DEFAULT 0,
2818
+ summary TEXT NOT NULL,
2819
+ learnings TEXT NOT NULL DEFAULT '[]',
2820
+ next_actions TEXT NOT NULL DEFAULT '[]',
2821
+ evidence_event_ids TEXT NOT NULL DEFAULT '[]',
2822
+ confidence REAL NOT NULL DEFAULT 0,
2823
+ created_at TEXT NOT NULL
2824
+ );
2825
+
2826
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_project_time
2827
+ ON agent_reflection_checkpoints(project_name, window_end_at);
2828
+
2829
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_session_time
2830
+ ON agent_reflection_checkpoints(session_id, window_end_at);
2831
+ `);
2694
2832
  try {
2695
2833
  await client.execute({
2696
2834
  sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
@@ -2854,7 +2992,7 @@ __export(shard_manager_exports, {
2854
2992
  shardExists: () => shardExists
2855
2993
  });
2856
2994
  import path7 from "path";
2857
- import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync2 } from "fs";
2995
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync3 } from "fs";
2858
2996
  import { createClient as createClient2 } from "@libsql/client";
2859
2997
  function initShardManager(encryptionKey) {
2860
2998
  _encryptionKey = encryptionKey;
@@ -2918,7 +3056,7 @@ async function auditShardHealth(options = {}) {
2918
3056
  const shards = [];
2919
3057
  for (const name of names) {
2920
3058
  const dbPath = path7.join(SHARDS_DIR, `${name}.db`);
2921
- const stat2 = statSync2(dbPath);
3059
+ const stat2 = statSync3(dbPath);
2922
3060
  const item = {
2923
3061
  name,
2924
3062
  path: dbPath,
@@ -3171,7 +3309,7 @@ async function getReadyShardClient(projectName) {
3171
3309
  _shardLastAccess.delete(safeName);
3172
3310
  const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
3173
3311
  if (existsSync7(dbPath)) {
3174
- const stat2 = statSync2(dbPath);
3312
+ const stat2 = statSync3(dbPath);
3175
3313
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3176
3314
  const archivedPath = path7.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
3177
3315
  renameSync3(dbPath, archivedPath);
@@ -3291,6 +3429,12 @@ var init_platform_procedures = __esm({
3291
3429
  priority: "p0",
3292
3430
  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."
3293
3431
  },
3432
+ {
3433
+ title: "Customer orchestration maturity \u2014 recommend, never trap",
3434
+ domain: "workflow",
3435
+ priority: "p1",
3436
+ 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."
3437
+ },
3294
3438
  {
3295
3439
  title: "Single dispatch path \u2014 create_task only",
3296
3440
  domain: "workflow",
@@ -3349,6 +3493,12 @@ var init_platform_procedures = __esm({
3349
3493
  priority: "p0",
3350
3494
  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."
3351
3495
  },
3496
+ {
3497
+ title: "Commit discipline \u2014 never leave verified work floating",
3498
+ domain: "workflow",
3499
+ priority: "p1",
3500
+ 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."
3501
+ },
3352
3502
  {
3353
3503
  title: "Desktop and TUI are the same product",
3354
3504
  domain: "architecture",
@@ -3666,6 +3816,274 @@ var init_memory_cards = __esm({
3666
3816
  }
3667
3817
  });
3668
3818
 
3819
+ // src/lib/agentic-ontology.ts
3820
+ var agentic_ontology_exports = {};
3821
+ __export(agentic_ontology_exports, {
3822
+ clean: () => clean,
3823
+ extractGoalCandidates: () => extractGoalCandidates,
3824
+ inferIntention: () => inferIntention,
3825
+ inferOntologyEventType: () => inferOntologyEventType,
3826
+ inferOutcome: () => inferOutcome,
3827
+ inferSemanticLabel: () => inferSemanticLabel,
3828
+ insertOntologyForBatch: () => insertOntologyForBatch,
3829
+ insertOntologyForMemory: () => insertOntologyForMemory,
3830
+ ontologyPayload: () => ontologyPayload,
3831
+ stableId: () => stableId2
3832
+ });
3833
+ import { createHash as createHash3 } from "crypto";
3834
+ function stableId2(...parts) {
3835
+ return createHash3("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
3836
+ }
3837
+ function clean(text, max = 240) {
3838
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
3839
+ }
3840
+ function inferOntologyEventType(row) {
3841
+ const lower = row.raw_text.toLowerCase();
3842
+ if (row.has_error) return "error";
3843
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
3844
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
3845
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
3846
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
3847
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
3848
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
3849
+ return "memory_observation";
3850
+ }
3851
+ function inferIntention(row) {
3852
+ if (row.intent) return clean(row.intent, 220);
3853
+ const text = clean(row.raw_text, 1e3);
3854
+ const patterns = [
3855
+ /(?: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,
3856
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
3857
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
3858
+ ];
3859
+ for (const p of patterns) {
3860
+ const m = text.match(p);
3861
+ if (m?.[1]) return clean(m[1], 220);
3862
+ }
3863
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
3864
+ return `${row.tool_name} during ${row.project_name}`;
3865
+ }
3866
+ return null;
3867
+ }
3868
+ function inferOutcome(row) {
3869
+ if (row.outcome) return clean(row.outcome, 220);
3870
+ if (row.has_error) return "error";
3871
+ const lower = row.raw_text.toLowerCase();
3872
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
3873
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
3874
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
3875
+ return null;
3876
+ }
3877
+ function extractGoalCandidates(row) {
3878
+ const text = clean(row.raw_text, 1600);
3879
+ const patterns = [
3880
+ /(?: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,
3881
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
3882
+ ];
3883
+ const out = [];
3884
+ for (const pattern of patterns) {
3885
+ for (const m of text.matchAll(pattern)) {
3886
+ const candidate = clean(m[1] ?? "", 220);
3887
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
3888
+ if (out.length >= 3) return out;
3889
+ }
3890
+ }
3891
+ return out;
3892
+ }
3893
+ function uniq(values, max = 6) {
3894
+ const out = [];
3895
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
3896
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
3897
+ if (out.length >= max) break;
3898
+ }
3899
+ return out;
3900
+ }
3901
+ function extractMatches(text, patterns, max = 5) {
3902
+ const out = [];
3903
+ for (const pattern of patterns) {
3904
+ for (const match of text.matchAll(pattern)) {
3905
+ const value = match[1] ?? match[0];
3906
+ if (value) out.push(value);
3907
+ if (out.length >= max) return uniq(out, max);
3908
+ }
3909
+ }
3910
+ return uniq(out, max);
3911
+ }
3912
+ function inferSemanticLabel(row) {
3913
+ const text = clean(row.raw_text, 2400);
3914
+ const eventType = inferOntologyEventType(row);
3915
+ const intention = inferIntention(row);
3916
+ const outcome = inferOutcome(row);
3917
+ const goals = extractGoalCandidates(row);
3918
+ const milestones = extractMatches(text, [
3919
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
3920
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
3921
+ ]);
3922
+ const problems = extractMatches(text, [
3923
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
3924
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
3925
+ ]);
3926
+ const decisions = extractMatches(text, [
3927
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
3928
+ ]);
3929
+ const temporalAnchors = extractMatches(text, [
3930
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
3931
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
3932
+ ], 8);
3933
+ const nextActions = extractMatches(text, [
3934
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
3935
+ ]);
3936
+ const actors = uniq([
3937
+ row.agent_id,
3938
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
3939
+ ], 6);
3940
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
3941
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
3942
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
3943
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
3944
+ return {
3945
+ labeler: "deterministic",
3946
+ schemaVersion: 1,
3947
+ eventType,
3948
+ intention,
3949
+ outcome,
3950
+ impact,
3951
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
3952
+ goals,
3953
+ milestones,
3954
+ problems,
3955
+ decisions,
3956
+ actors,
3957
+ temporalAnchors,
3958
+ successSignals,
3959
+ failureSignals,
3960
+ nextActions,
3961
+ summary: clean(text, 280)
3962
+ };
3963
+ }
3964
+ function ontologyPayload(row) {
3965
+ const semantic = inferSemanticLabel(row);
3966
+ return {
3967
+ tool_name: row.tool_name,
3968
+ memory_version: row.version ?? null,
3969
+ domain: row.domain ?? null,
3970
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
3971
+ semantic
3972
+ };
3973
+ }
3974
+ function safeJson(value) {
3975
+ try {
3976
+ return JSON.parse(value);
3977
+ } catch {
3978
+ return value.slice(0, 1e3);
3979
+ }
3980
+ }
3981
+ async function resolveClient(client) {
3982
+ if (client) return client;
3983
+ const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3984
+ return getClient2();
3985
+ }
3986
+ async function insertOntologyForMemory(row, client) {
3987
+ const db = await resolveClient(client);
3988
+ const occurredAt = row.timestamp;
3989
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
3990
+ const eventType = inferOntologyEventType(row);
3991
+ const intention = inferIntention(row);
3992
+ const outcome = inferOutcome(row);
3993
+ const eventId = stableId2("event", row.id);
3994
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3995
+ await db.execute({
3996
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
3997
+ VALUES (?, ?, ?, ?, ?, 1, ?)
3998
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
3999
+ event_count = event_count + 1`,
4000
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
4001
+ });
4002
+ await db.execute({
4003
+ sql: `INSERT OR IGNORE INTO agent_events
4004
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
4005
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
4006
+ impact, payload, created_at)
4007
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
4008
+ args: [
4009
+ eventId,
4010
+ eventType,
4011
+ occurredAt,
4012
+ sequence,
4013
+ row.agent_id,
4014
+ row.agent_role,
4015
+ row.project_name,
4016
+ row.session_id,
4017
+ row.task_id ?? null,
4018
+ intention,
4019
+ outcome,
4020
+ row.id,
4021
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
4022
+ JSON.stringify(ontologyPayload(row)),
4023
+ now
4024
+ ]
4025
+ });
4026
+ const semantic = inferSemanticLabel(row);
4027
+ await db.execute({
4028
+ sql: `INSERT INTO agent_semantic_labels
4029
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
4030
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
4031
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
4032
+ labels = excluded.labels, updated_at = excluded.updated_at`,
4033
+ args: [
4034
+ stableId2("semantic", row.id, semantic.labeler, semantic.schemaVersion),
4035
+ row.id,
4036
+ eventId,
4037
+ semantic.labeler,
4038
+ semantic.schemaVersion,
4039
+ semantic.confidence,
4040
+ JSON.stringify(semantic),
4041
+ now,
4042
+ now
4043
+ ]
4044
+ });
4045
+ for (const statement of extractGoalCandidates(row)) {
4046
+ const goalId = stableId2("goal", row.project_name, statement.toLowerCase());
4047
+ await db.execute({
4048
+ sql: `INSERT INTO agent_goals
4049
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
4050
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
4051
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
4052
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
4053
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
4054
+ });
4055
+ await db.execute({
4056
+ sql: `INSERT OR IGNORE INTO agent_goal_links
4057
+ (id, goal_id, link_type, target_id, target_type, created_at)
4058
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
4059
+ args: [stableId2("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
4060
+ });
4061
+ await db.execute({
4062
+ sql: `INSERT OR IGNORE INTO agent_goal_links
4063
+ (id, goal_id, link_type, target_id, target_type, created_at)
4064
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
4065
+ args: [stableId2("goal_link", goalId, eventId, "event"), goalId, eventId, now]
4066
+ });
4067
+ }
4068
+ }
4069
+ async function insertOntologyForBatch(rows, client) {
4070
+ const db = await resolveClient(client);
4071
+ let count = 0;
4072
+ for (const row of rows) {
4073
+ try {
4074
+ await insertOntologyForMemory(row, db);
4075
+ count++;
4076
+ } catch {
4077
+ }
4078
+ }
4079
+ return count;
4080
+ }
4081
+ var init_agentic_ontology = __esm({
4082
+ "src/lib/agentic-ontology.ts"() {
4083
+ "use strict";
4084
+ }
4085
+ });
4086
+
3669
4087
  // src/bin/backfill-conversations.ts
3670
4088
  import crypto2 from "crypto";
3671
4089
  import { createReadStream } from "fs";
@@ -3681,11 +4099,12 @@ init_database();
3681
4099
 
3682
4100
  // src/lib/keychain.ts
3683
4101
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3684
- import { existsSync as existsSync6 } from "fs";
4102
+ import { existsSync as existsSync6, statSync as statSync2 } from "fs";
3685
4103
  import { execSync as execSync2 } from "child_process";
3686
4104
  import path6 from "path";
3687
4105
  import os5 from "os";
3688
- var SERVICE = "exe-mem";
4106
+ var SERVICE = "exe-os";
4107
+ var LEGACY_SERVICE = "exe-mem";
3689
4108
  var ACCOUNT = "master-key";
3690
4109
  function getKeyDir() {
3691
4110
  return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
@@ -3693,29 +4112,66 @@ function getKeyDir() {
3693
4112
  function getKeyPath() {
3694
4113
  return path6.join(getKeyDir(), "master.key");
3695
4114
  }
3696
- function macKeychainGet() {
4115
+ function nativeKeychainAllowed() {
4116
+ return process.env.EXE_OS_DISABLE_NATIVE_KEYCHAIN !== "1";
4117
+ }
4118
+ var linuxSecretAvailability = null;
4119
+ function linuxSecretAvailable() {
4120
+ if (!nativeKeychainAllowed()) return false;
4121
+ if (process.platform !== "linux") return false;
4122
+ if (linuxSecretAvailability !== null) return linuxSecretAvailability;
4123
+ try {
4124
+ execSync2("command -v secret-tool >/dev/null 2>&1", { timeout: 1e3 });
4125
+ } catch {
4126
+ linuxSecretAvailability = false;
4127
+ return false;
4128
+ }
4129
+ try {
4130
+ execSync2("secret-tool search --all exe-os probe >/dev/null 2>&1", { timeout: 1e3 });
4131
+ linuxSecretAvailability = true;
4132
+ } catch {
4133
+ linuxSecretAvailability = false;
4134
+ }
4135
+ return linuxSecretAvailability;
4136
+ }
4137
+ function isRootOnlyTrustedServerKeyFile(keyPath) {
4138
+ if (process.platform !== "linux") return false;
4139
+ try {
4140
+ const uid = typeof os5.userInfo().uid === "number" ? os5.userInfo().uid : -1;
4141
+ const st = statSync2(keyPath);
4142
+ if (!st.isFile() || (st.mode & 63) !== 0) return false;
4143
+ if (uid === 0) return true;
4144
+ const exeOsDir = process.env.EXE_OS_DIR;
4145
+ return Boolean(exeOsDir && path6.resolve(keyPath).startsWith(path6.resolve(exeOsDir) + path6.sep));
4146
+ } catch {
4147
+ return false;
4148
+ }
4149
+ }
4150
+ function macKeychainGet(service = SERVICE) {
4151
+ if (!nativeKeychainAllowed()) return null;
3697
4152
  if (process.platform !== "darwin") return null;
3698
4153
  try {
3699
4154
  return execSync2(
3700
- `security find-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w 2>/dev/null`,
4155
+ `security find-generic-password -s "${service}" -a "${ACCOUNT}" -w 2>/dev/null`,
3701
4156
  { encoding: "utf-8", timeout: 5e3 }
3702
4157
  ).trim();
3703
4158
  } catch {
3704
4159
  return null;
3705
4160
  }
3706
4161
  }
3707
- function macKeychainSet(value) {
4162
+ function macKeychainSet(value, service = SERVICE) {
4163
+ if (!nativeKeychainAllowed()) return false;
3708
4164
  if (process.platform !== "darwin") return false;
3709
4165
  try {
3710
4166
  try {
3711
4167
  execSync2(
3712
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
4168
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3713
4169
  { timeout: 5e3 }
3714
4170
  );
3715
4171
  } catch {
3716
4172
  }
3717
4173
  execSync2(
3718
- `security add-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w "${value}"`,
4174
+ `security add-generic-password -s "${service}" -a "${ACCOUNT}" -w "${value}"`,
3719
4175
  { timeout: 5e3 }
3720
4176
  );
3721
4177
  return true;
@@ -3723,22 +4179,48 @@ function macKeychainSet(value) {
3723
4179
  return false;
3724
4180
  }
3725
4181
  }
3726
- function linuxSecretGet() {
3727
- if (process.platform !== "linux") return null;
4182
+ function macKeychainDelete(service = SERVICE) {
4183
+ if (!nativeKeychainAllowed()) return false;
4184
+ if (process.platform !== "darwin") return false;
4185
+ try {
4186
+ execSync2(
4187
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
4188
+ { timeout: 5e3 }
4189
+ );
4190
+ return true;
4191
+ } catch {
4192
+ return false;
4193
+ }
4194
+ }
4195
+ function linuxSecretGet(service = SERVICE) {
4196
+ if (!linuxSecretAvailable()) return null;
3728
4197
  try {
3729
4198
  return execSync2(
3730
- `secret-tool lookup service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
4199
+ `secret-tool lookup service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3731
4200
  { encoding: "utf-8", timeout: 5e3 }
3732
4201
  ).trim();
3733
4202
  } catch {
3734
4203
  return null;
3735
4204
  }
3736
4205
  }
3737
- function linuxSecretSet(value) {
4206
+ function linuxSecretSet(value, service = SERVICE) {
4207
+ if (!linuxSecretAvailable()) return false;
4208
+ try {
4209
+ execSync2(
4210
+ `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${service}" account "${ACCOUNT}" 2>/dev/null`,
4211
+ { timeout: 5e3 }
4212
+ );
4213
+ return true;
4214
+ } catch {
4215
+ return false;
4216
+ }
4217
+ }
4218
+ function linuxSecretDelete(service = SERVICE) {
4219
+ if (!nativeKeychainAllowed()) return false;
3738
4220
  if (process.platform !== "linux") return false;
3739
4221
  try {
3740
4222
  execSync2(
3741
- `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${SERVICE}" account "${ACCOUNT}"`,
4223
+ `secret-tool clear service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3742
4224
  { timeout: 5e3 }
3743
4225
  );
3744
4226
  return true;
@@ -3747,6 +4229,7 @@ function linuxSecretSet(value) {
3747
4229
  }
3748
4230
  }
3749
4231
  async function tryKeytar() {
4232
+ if (!nativeKeychainAllowed()) return null;
3750
4233
  try {
3751
4234
  return await import("keytar");
3752
4235
  } catch {
@@ -3821,7 +4304,19 @@ async function writeMachineBoundFileFallback(b64) {
3821
4304
  return "plaintext";
3822
4305
  }
3823
4306
  async function getMasterKey() {
3824
- const nativeValue = macKeychainGet() ?? linuxSecretGet();
4307
+ let nativeValue = macKeychainGet() ?? linuxSecretGet();
4308
+ if (!nativeValue) {
4309
+ const legacyValue = macKeychainGet(LEGACY_SERVICE) ?? linuxSecretGet(LEGACY_SERVICE);
4310
+ if (legacyValue) {
4311
+ const migrated = macKeychainSet(legacyValue) || linuxSecretSet(legacyValue);
4312
+ if (migrated) {
4313
+ macKeychainDelete(LEGACY_SERVICE);
4314
+ linuxSecretDelete(LEGACY_SERVICE);
4315
+ process.stderr.write("[keychain] Migrated keychain service from exe-mem to exe-os.\n");
4316
+ }
4317
+ nativeValue = legacyValue;
4318
+ }
4319
+ }
3825
4320
  if (nativeValue) {
3826
4321
  return Buffer.from(nativeValue, "base64");
3827
4322
  }
@@ -3829,12 +4324,17 @@ async function getMasterKey() {
3829
4324
  if (keytar) {
3830
4325
  try {
3831
4326
  const keytarValue = await keytar.getPassword(SERVICE, ACCOUNT);
3832
- if (keytarValue) {
3833
- const migrated = macKeychainSet(keytarValue) || linuxSecretSet(keytarValue);
4327
+ const legacyKeytarValue = keytarValue ?? await keytar.getPassword(LEGACY_SERVICE, ACCOUNT);
4328
+ if (legacyKeytarValue) {
4329
+ const migrated = macKeychainSet(legacyKeytarValue) || linuxSecretSet(legacyKeytarValue);
3834
4330
  if (migrated) {
3835
4331
  process.stderr.write("[keychain] Migrated key from keytar to native keychain.\n");
4332
+ try {
4333
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
4334
+ } catch {
4335
+ }
3836
4336
  }
3837
- return Buffer.from(keytarValue, "base64");
4337
+ return Buffer.from(legacyKeytarValue, "base64");
3838
4338
  }
3839
4339
  } catch {
3840
4340
  }
@@ -3859,7 +4359,7 @@ async function getMasterKey() {
3859
4359
  const decrypted = decryptWithMachineKey(content, machineKey);
3860
4360
  if (!decrypted) {
3861
4361
  process.stderr.write(
3862
- "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase: exe-os link import\n"
4362
+ "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase during setup: exe-os setup\n"
3863
4363
  );
3864
4364
  return null;
3865
4365
  }
@@ -3868,6 +4368,9 @@ async function getMasterKey() {
3868
4368
  b64Value = content;
3869
4369
  }
3870
4370
  const key = Buffer.from(b64Value, "base64");
4371
+ if (!content.startsWith(ENCRYPTED_PREFIX) && isRootOnlyTrustedServerKeyFile(keyPath)) {
4372
+ return key;
4373
+ }
3871
4374
  const migrated = macKeychainSet(b64Value) || linuxSecretSet(b64Value);
3872
4375
  if (migrated) {
3873
4376
  process.stderr.write("[keychain] Migrated key from file to native keychain.\n");
@@ -4470,6 +4973,11 @@ async function flushBatch() {
4470
4973
  await insertMemoryCardsForBatch2(batch);
4471
4974
  } catch {
4472
4975
  }
4976
+ try {
4977
+ const { insertOntologyForBatch: insertOntologyForBatch2 } = await Promise.resolve().then(() => (init_agentic_ontology(), agentic_ontology_exports));
4978
+ await insertOntologyForBatch2(batch);
4979
+ } catch {
4980
+ }
4473
4981
  schedulePostWriteMemoryHygiene(batch.map((row) => row.id));
4474
4982
  _pendingRecords.splice(0, batch.length);
4475
4983
  try {