@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
@@ -124,6 +124,11 @@ function normalizeAutoUpdate(raw) {
124
124
  const userAU = raw.autoUpdate ?? {};
125
125
  raw.autoUpdate = { ...defaultAU, ...userAU };
126
126
  }
127
+ function normalizeOrchestration(raw) {
128
+ const defaultOrg = DEFAULT_CONFIG.orchestration;
129
+ const userOrg = raw.orchestration ?? {};
130
+ raw.orchestration = { ...defaultOrg, ...userOrg };
131
+ }
127
132
  async function loadConfig() {
128
133
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
129
134
  await ensurePrivateDir(dir);
@@ -148,10 +153,15 @@ async function loadConfig() {
148
153
  normalizeScalingRoadmap(migratedCfg);
149
154
  normalizeSessionLifecycle(migratedCfg);
150
155
  normalizeAutoUpdate(migratedCfg);
156
+ normalizeOrchestration(migratedCfg);
151
157
  const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
152
158
  if (config.dbPath.startsWith("~")) {
153
159
  config.dbPath = config.dbPath.replace(/^~/, os.homedir());
154
160
  }
161
+ const envDbPath = path.join(dir, "memories.db");
162
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync2(config.dbPath) && existsSync2(envDbPath)) {
163
+ config.dbPath = envDbPath;
164
+ }
155
165
  return config;
156
166
  } catch {
157
167
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
@@ -223,6 +233,10 @@ var init_config = __esm({
223
233
  checkOnBoot: true,
224
234
  autoInstall: false,
225
235
  checkIntervalMs: 24 * 60 * 60 * 1e3
236
+ },
237
+ orchestration: {
238
+ phase: "phase_1_coo",
239
+ phaseSetBy: "default"
226
240
  }
227
241
  };
228
242
  CONFIG_MIGRATIONS = [
@@ -1669,6 +1683,9 @@ function getClient() {
1669
1683
  if (_daemonClient && _daemonClient._isDaemonActive()) {
1670
1684
  return _daemonClient;
1671
1685
  }
1686
+ if (!_resilientClient) {
1687
+ return _adapterClient;
1688
+ }
1672
1689
  return _resilientClient;
1673
1690
  }
1674
1691
  async function initDaemonClient() {
@@ -2701,6 +2718,127 @@ async function ensureSchema() {
2701
2718
  VALUES (new.rowid, new.content, new.subject, new.predicate, new.object);
2702
2719
  END;
2703
2720
  `);
2721
+ await client.executeMultiple(`
2722
+ CREATE TABLE IF NOT EXISTS agent_sessions (
2723
+ id TEXT PRIMARY KEY,
2724
+ agent_id TEXT NOT NULL,
2725
+ project_name TEXT,
2726
+ started_at TEXT NOT NULL,
2727
+ last_event_at TEXT NOT NULL,
2728
+ event_count INTEGER NOT NULL DEFAULT 0,
2729
+ properties TEXT DEFAULT '{}'
2730
+ );
2731
+
2732
+ CREATE INDEX IF NOT EXISTS idx_agent_sessions_agent_time
2733
+ ON agent_sessions(agent_id, started_at);
2734
+
2735
+ CREATE TABLE IF NOT EXISTS agent_goals (
2736
+ id TEXT PRIMARY KEY,
2737
+ statement TEXT NOT NULL,
2738
+ owner_agent_id TEXT,
2739
+ project_name TEXT,
2740
+ status TEXT NOT NULL DEFAULT 'open',
2741
+ priority INTEGER NOT NULL DEFAULT 5,
2742
+ success_criteria TEXT,
2743
+ parent_goal_id TEXT,
2744
+ due_at TEXT,
2745
+ achieved_at TEXT,
2746
+ supersedes_id TEXT,
2747
+ created_at TEXT NOT NULL,
2748
+ updated_at TEXT NOT NULL,
2749
+ source_memory_id TEXT
2750
+ );
2751
+
2752
+ CREATE INDEX IF NOT EXISTS idx_agent_goals_project_status
2753
+ ON agent_goals(project_name, status, priority);
2754
+
2755
+ CREATE TABLE IF NOT EXISTS agent_events (
2756
+ id TEXT PRIMARY KEY,
2757
+ event_type TEXT NOT NULL,
2758
+ occurred_at TEXT NOT NULL,
2759
+ sequence_index INTEGER NOT NULL,
2760
+ actor_agent_id TEXT,
2761
+ agent_role TEXT,
2762
+ project_name TEXT,
2763
+ session_id TEXT,
2764
+ task_id TEXT,
2765
+ goal_id TEXT,
2766
+ parent_event_id TEXT,
2767
+ intention TEXT,
2768
+ outcome TEXT,
2769
+ evidence_memory_id TEXT,
2770
+ impact TEXT,
2771
+ payload TEXT DEFAULT '{}',
2772
+ created_at TEXT NOT NULL
2773
+ );
2774
+
2775
+ CREATE INDEX IF NOT EXISTS idx_agent_events_time
2776
+ ON agent_events(occurred_at, sequence_index);
2777
+
2778
+ CREATE INDEX IF NOT EXISTS idx_agent_events_session_seq
2779
+ ON agent_events(session_id, sequence_index);
2780
+
2781
+ CREATE INDEX IF NOT EXISTS idx_agent_events_goal_time
2782
+ ON agent_events(goal_id, occurred_at);
2783
+
2784
+ CREATE INDEX IF NOT EXISTS idx_agent_events_memory
2785
+ ON agent_events(evidence_memory_id);
2786
+
2787
+ CREATE TABLE IF NOT EXISTS agent_goal_links (
2788
+ id TEXT PRIMARY KEY,
2789
+ goal_id TEXT NOT NULL,
2790
+ link_type TEXT NOT NULL,
2791
+ target_id TEXT NOT NULL,
2792
+ target_type TEXT NOT NULL,
2793
+ created_at TEXT NOT NULL
2794
+ );
2795
+
2796
+ CREATE INDEX IF NOT EXISTS idx_agent_goal_links_goal
2797
+ ON agent_goal_links(goal_id, target_type);
2798
+
2799
+ CREATE TABLE IF NOT EXISTS agent_semantic_labels (
2800
+ id TEXT PRIMARY KEY,
2801
+ source_memory_id TEXT NOT NULL,
2802
+ event_id TEXT,
2803
+ labeler TEXT NOT NULL,
2804
+ schema_version INTEGER NOT NULL DEFAULT 1,
2805
+ confidence REAL NOT NULL DEFAULT 0,
2806
+ labels TEXT NOT NULL,
2807
+ created_at TEXT NOT NULL,
2808
+ updated_at TEXT NOT NULL
2809
+ );
2810
+
2811
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_memory
2812
+ ON agent_semantic_labels(source_memory_id, labeler);
2813
+
2814
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_event
2815
+ ON agent_semantic_labels(event_id);
2816
+
2817
+ CREATE TABLE IF NOT EXISTS agent_reflection_checkpoints (
2818
+ id TEXT PRIMARY KEY,
2819
+ project_name TEXT,
2820
+ session_id TEXT,
2821
+ window_start_at TEXT NOT NULL,
2822
+ window_end_at TEXT NOT NULL,
2823
+ event_count INTEGER NOT NULL DEFAULT 0,
2824
+ goal_count INTEGER NOT NULL DEFAULT 0,
2825
+ success_count INTEGER NOT NULL DEFAULT 0,
2826
+ failure_count INTEGER NOT NULL DEFAULT 0,
2827
+ risk_count INTEGER NOT NULL DEFAULT 0,
2828
+ summary TEXT NOT NULL,
2829
+ learnings TEXT NOT NULL DEFAULT '[]',
2830
+ next_actions TEXT NOT NULL DEFAULT '[]',
2831
+ evidence_event_ids TEXT NOT NULL DEFAULT '[]',
2832
+ confidence REAL NOT NULL DEFAULT 0,
2833
+ created_at TEXT NOT NULL
2834
+ );
2835
+
2836
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_project_time
2837
+ ON agent_reflection_checkpoints(project_name, window_end_at);
2838
+
2839
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_session_time
2840
+ ON agent_reflection_checkpoints(session_id, window_end_at);
2841
+ `);
2704
2842
  try {
2705
2843
  await client.execute({
2706
2844
  sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
@@ -2864,7 +3002,7 @@ __export(shard_manager_exports, {
2864
3002
  shardExists: () => shardExists
2865
3003
  });
2866
3004
  import path7 from "path";
2867
- import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync2 } from "fs";
3005
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync3 } from "fs";
2868
3006
  import { createClient as createClient2 } from "@libsql/client";
2869
3007
  function initShardManager(encryptionKey) {
2870
3008
  _encryptionKey = encryptionKey;
@@ -2928,7 +3066,7 @@ async function auditShardHealth(options = {}) {
2928
3066
  const shards = [];
2929
3067
  for (const name of names) {
2930
3068
  const dbPath = path7.join(SHARDS_DIR, `${name}.db`);
2931
- const stat = statSync2(dbPath);
3069
+ const stat = statSync3(dbPath);
2932
3070
  const item = {
2933
3071
  name,
2934
3072
  path: dbPath,
@@ -3181,7 +3319,7 @@ async function getReadyShardClient(projectName) {
3181
3319
  _shardLastAccess.delete(safeName);
3182
3320
  const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
3183
3321
  if (existsSync7(dbPath)) {
3184
- const stat = statSync2(dbPath);
3322
+ const stat = statSync3(dbPath);
3185
3323
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3186
3324
  const archivedPath = path7.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
3187
3325
  renameSync3(dbPath, archivedPath);
@@ -3301,6 +3439,12 @@ var init_platform_procedures = __esm({
3301
3439
  priority: "p0",
3302
3440
  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."
3303
3441
  },
3442
+ {
3443
+ title: "Customer orchestration maturity \u2014 recommend, never trap",
3444
+ domain: "workflow",
3445
+ priority: "p1",
3446
+ 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."
3447
+ },
3304
3448
  {
3305
3449
  title: "Single dispatch path \u2014 create_task only",
3306
3450
  domain: "workflow",
@@ -3359,6 +3503,12 @@ var init_platform_procedures = __esm({
3359
3503
  priority: "p0",
3360
3504
  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."
3361
3505
  },
3506
+ {
3507
+ title: "Commit discipline \u2014 never leave verified work floating",
3508
+ domain: "workflow",
3509
+ priority: "p1",
3510
+ 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."
3511
+ },
3362
3512
  {
3363
3513
  title: "Desktop and TUI are the same product",
3364
3514
  domain: "architecture",
@@ -3676,6 +3826,274 @@ var init_memory_cards = __esm({
3676
3826
  }
3677
3827
  });
3678
3828
 
3829
+ // src/lib/agentic-ontology.ts
3830
+ var agentic_ontology_exports = {};
3831
+ __export(agentic_ontology_exports, {
3832
+ clean: () => clean,
3833
+ extractGoalCandidates: () => extractGoalCandidates,
3834
+ inferIntention: () => inferIntention,
3835
+ inferOntologyEventType: () => inferOntologyEventType,
3836
+ inferOutcome: () => inferOutcome,
3837
+ inferSemanticLabel: () => inferSemanticLabel,
3838
+ insertOntologyForBatch: () => insertOntologyForBatch,
3839
+ insertOntologyForMemory: () => insertOntologyForMemory,
3840
+ ontologyPayload: () => ontologyPayload,
3841
+ stableId: () => stableId2
3842
+ });
3843
+ import { createHash as createHash3 } from "crypto";
3844
+ function stableId2(...parts) {
3845
+ return createHash3("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
3846
+ }
3847
+ function clean(text, max = 240) {
3848
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
3849
+ }
3850
+ function inferOntologyEventType(row) {
3851
+ const lower = row.raw_text.toLowerCase();
3852
+ if (row.has_error) return "error";
3853
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
3854
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
3855
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
3856
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
3857
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
3858
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
3859
+ return "memory_observation";
3860
+ }
3861
+ function inferIntention(row) {
3862
+ if (row.intent) return clean(row.intent, 220);
3863
+ const text = clean(row.raw_text, 1e3);
3864
+ const patterns = [
3865
+ /(?: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,
3866
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
3867
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
3868
+ ];
3869
+ for (const p of patterns) {
3870
+ const m = text.match(p);
3871
+ if (m?.[1]) return clean(m[1], 220);
3872
+ }
3873
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
3874
+ return `${row.tool_name} during ${row.project_name}`;
3875
+ }
3876
+ return null;
3877
+ }
3878
+ function inferOutcome(row) {
3879
+ if (row.outcome) return clean(row.outcome, 220);
3880
+ if (row.has_error) return "error";
3881
+ const lower = row.raw_text.toLowerCase();
3882
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
3883
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
3884
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
3885
+ return null;
3886
+ }
3887
+ function extractGoalCandidates(row) {
3888
+ const text = clean(row.raw_text, 1600);
3889
+ const patterns = [
3890
+ /(?: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,
3891
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
3892
+ ];
3893
+ const out = [];
3894
+ for (const pattern of patterns) {
3895
+ for (const m of text.matchAll(pattern)) {
3896
+ const candidate = clean(m[1] ?? "", 220);
3897
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
3898
+ if (out.length >= 3) return out;
3899
+ }
3900
+ }
3901
+ return out;
3902
+ }
3903
+ function uniq(values, max = 6) {
3904
+ const out = [];
3905
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
3906
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
3907
+ if (out.length >= max) break;
3908
+ }
3909
+ return out;
3910
+ }
3911
+ function extractMatches(text, patterns, max = 5) {
3912
+ const out = [];
3913
+ for (const pattern of patterns) {
3914
+ for (const match of text.matchAll(pattern)) {
3915
+ const value = match[1] ?? match[0];
3916
+ if (value) out.push(value);
3917
+ if (out.length >= max) return uniq(out, max);
3918
+ }
3919
+ }
3920
+ return uniq(out, max);
3921
+ }
3922
+ function inferSemanticLabel(row) {
3923
+ const text = clean(row.raw_text, 2400);
3924
+ const eventType = inferOntologyEventType(row);
3925
+ const intention = inferIntention(row);
3926
+ const outcome = inferOutcome(row);
3927
+ const goals = extractGoalCandidates(row);
3928
+ const milestones = extractMatches(text, [
3929
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
3930
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
3931
+ ]);
3932
+ const problems = extractMatches(text, [
3933
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
3934
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
3935
+ ]);
3936
+ const decisions = extractMatches(text, [
3937
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
3938
+ ]);
3939
+ const temporalAnchors = extractMatches(text, [
3940
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
3941
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
3942
+ ], 8);
3943
+ const nextActions = extractMatches(text, [
3944
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
3945
+ ]);
3946
+ const actors = uniq([
3947
+ row.agent_id,
3948
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
3949
+ ], 6);
3950
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
3951
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
3952
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
3953
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
3954
+ return {
3955
+ labeler: "deterministic",
3956
+ schemaVersion: 1,
3957
+ eventType,
3958
+ intention,
3959
+ outcome,
3960
+ impact,
3961
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
3962
+ goals,
3963
+ milestones,
3964
+ problems,
3965
+ decisions,
3966
+ actors,
3967
+ temporalAnchors,
3968
+ successSignals,
3969
+ failureSignals,
3970
+ nextActions,
3971
+ summary: clean(text, 280)
3972
+ };
3973
+ }
3974
+ function ontologyPayload(row) {
3975
+ const semantic = inferSemanticLabel(row);
3976
+ return {
3977
+ tool_name: row.tool_name,
3978
+ memory_version: row.version ?? null,
3979
+ domain: row.domain ?? null,
3980
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
3981
+ semantic
3982
+ };
3983
+ }
3984
+ function safeJson(value) {
3985
+ try {
3986
+ return JSON.parse(value);
3987
+ } catch {
3988
+ return value.slice(0, 1e3);
3989
+ }
3990
+ }
3991
+ async function resolveClient(client) {
3992
+ if (client) return client;
3993
+ const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3994
+ return getClient2();
3995
+ }
3996
+ async function insertOntologyForMemory(row, client) {
3997
+ const db = await resolveClient(client);
3998
+ const occurredAt = row.timestamp;
3999
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
4000
+ const eventType = inferOntologyEventType(row);
4001
+ const intention = inferIntention(row);
4002
+ const outcome = inferOutcome(row);
4003
+ const eventId = stableId2("event", row.id);
4004
+ const now = (/* @__PURE__ */ new Date()).toISOString();
4005
+ await db.execute({
4006
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
4007
+ VALUES (?, ?, ?, ?, ?, 1, ?)
4008
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
4009
+ event_count = event_count + 1`,
4010
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
4011
+ });
4012
+ await db.execute({
4013
+ sql: `INSERT OR IGNORE INTO agent_events
4014
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
4015
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
4016
+ impact, payload, created_at)
4017
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
4018
+ args: [
4019
+ eventId,
4020
+ eventType,
4021
+ occurredAt,
4022
+ sequence,
4023
+ row.agent_id,
4024
+ row.agent_role,
4025
+ row.project_name,
4026
+ row.session_id,
4027
+ row.task_id ?? null,
4028
+ intention,
4029
+ outcome,
4030
+ row.id,
4031
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
4032
+ JSON.stringify(ontologyPayload(row)),
4033
+ now
4034
+ ]
4035
+ });
4036
+ const semantic = inferSemanticLabel(row);
4037
+ await db.execute({
4038
+ sql: `INSERT INTO agent_semantic_labels
4039
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
4040
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
4041
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
4042
+ labels = excluded.labels, updated_at = excluded.updated_at`,
4043
+ args: [
4044
+ stableId2("semantic", row.id, semantic.labeler, semantic.schemaVersion),
4045
+ row.id,
4046
+ eventId,
4047
+ semantic.labeler,
4048
+ semantic.schemaVersion,
4049
+ semantic.confidence,
4050
+ JSON.stringify(semantic),
4051
+ now,
4052
+ now
4053
+ ]
4054
+ });
4055
+ for (const statement of extractGoalCandidates(row)) {
4056
+ const goalId = stableId2("goal", row.project_name, statement.toLowerCase());
4057
+ await db.execute({
4058
+ sql: `INSERT INTO agent_goals
4059
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
4060
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
4061
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
4062
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
4063
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
4064
+ });
4065
+ await db.execute({
4066
+ sql: `INSERT OR IGNORE INTO agent_goal_links
4067
+ (id, goal_id, link_type, target_id, target_type, created_at)
4068
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
4069
+ args: [stableId2("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
4070
+ });
4071
+ await db.execute({
4072
+ sql: `INSERT OR IGNORE INTO agent_goal_links
4073
+ (id, goal_id, link_type, target_id, target_type, created_at)
4074
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
4075
+ args: [stableId2("goal_link", goalId, eventId, "event"), goalId, eventId, now]
4076
+ });
4077
+ }
4078
+ }
4079
+ async function insertOntologyForBatch(rows, client) {
4080
+ const db = await resolveClient(client);
4081
+ let count = 0;
4082
+ for (const row of rows) {
4083
+ try {
4084
+ await insertOntologyForMemory(row, db);
4085
+ count++;
4086
+ } catch {
4087
+ }
4088
+ }
4089
+ return count;
4090
+ }
4091
+ var init_agentic_ontology = __esm({
4092
+ "src/lib/agentic-ontology.ts"() {
4093
+ "use strict";
4094
+ }
4095
+ });
4096
+
3679
4097
  // src/bin/exe-assign.ts
3680
4098
  init_employees();
3681
4099
 
@@ -3828,11 +4246,12 @@ init_database();
3828
4246
 
3829
4247
  // src/lib/keychain.ts
3830
4248
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3831
- import { existsSync as existsSync6 } from "fs";
4249
+ import { existsSync as existsSync6, statSync as statSync2 } from "fs";
3832
4250
  import { execSync as execSync2 } from "child_process";
3833
4251
  import path6 from "path";
3834
4252
  import os5 from "os";
3835
- var SERVICE = "exe-mem";
4253
+ var SERVICE = "exe-os";
4254
+ var LEGACY_SERVICE = "exe-mem";
3836
4255
  var ACCOUNT = "master-key";
3837
4256
  function getKeyDir() {
3838
4257
  return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
@@ -3840,29 +4259,79 @@ function getKeyDir() {
3840
4259
  function getKeyPath() {
3841
4260
  return path6.join(getKeyDir(), "master.key");
3842
4261
  }
3843
- function macKeychainGet() {
4262
+ function nativeKeychainAllowed() {
4263
+ return process.env.EXE_OS_DISABLE_NATIVE_KEYCHAIN !== "1";
4264
+ }
4265
+ var linuxSecretAvailability = null;
4266
+ function linuxSecretAvailable() {
4267
+ if (!nativeKeychainAllowed()) return false;
4268
+ if (process.platform !== "linux") return false;
4269
+ if (linuxSecretAvailability !== null) return linuxSecretAvailability;
4270
+ try {
4271
+ execSync2("command -v secret-tool >/dev/null 2>&1", { timeout: 1e3 });
4272
+ } catch {
4273
+ linuxSecretAvailability = false;
4274
+ return false;
4275
+ }
4276
+ try {
4277
+ execSync2("secret-tool search --all exe-os probe >/dev/null 2>&1", { timeout: 1e3 });
4278
+ linuxSecretAvailability = true;
4279
+ } catch {
4280
+ linuxSecretAvailability = false;
4281
+ }
4282
+ return linuxSecretAvailability;
4283
+ }
4284
+ function isRootOnlyTrustedServerKeyFile(keyPath) {
4285
+ if (process.platform !== "linux") return false;
4286
+ try {
4287
+ const uid = typeof os5.userInfo().uid === "number" ? os5.userInfo().uid : -1;
4288
+ const st = statSync2(keyPath);
4289
+ if (!st.isFile() || (st.mode & 63) !== 0) return false;
4290
+ if (uid === 0) return true;
4291
+ const exeOsDir = process.env.EXE_OS_DIR;
4292
+ return Boolean(exeOsDir && path6.resolve(keyPath).startsWith(path6.resolve(exeOsDir) + path6.sep));
4293
+ } catch {
4294
+ return false;
4295
+ }
4296
+ }
4297
+ function macKeychainGet(service = SERVICE) {
4298
+ if (!nativeKeychainAllowed()) return null;
3844
4299
  if (process.platform !== "darwin") return null;
3845
4300
  try {
3846
4301
  return execSync2(
3847
- `security find-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w 2>/dev/null`,
4302
+ `security find-generic-password -s "${service}" -a "${ACCOUNT}" -w 2>/dev/null`,
3848
4303
  { encoding: "utf-8", timeout: 5e3 }
3849
4304
  ).trim();
3850
4305
  } catch {
3851
4306
  return null;
3852
4307
  }
3853
4308
  }
3854
- function macKeychainSet(value) {
4309
+ function macKeychainSet(value, service = SERVICE) {
4310
+ if (!nativeKeychainAllowed()) return false;
3855
4311
  if (process.platform !== "darwin") return false;
3856
4312
  try {
3857
4313
  try {
3858
4314
  execSync2(
3859
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
4315
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3860
4316
  { timeout: 5e3 }
3861
4317
  );
3862
4318
  } catch {
3863
4319
  }
3864
4320
  execSync2(
3865
- `security add-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w "${value}"`,
4321
+ `security add-generic-password -s "${service}" -a "${ACCOUNT}" -w "${value}"`,
4322
+ { timeout: 5e3 }
4323
+ );
4324
+ return true;
4325
+ } catch {
4326
+ return false;
4327
+ }
4328
+ }
4329
+ function macKeychainDelete(service = SERVICE) {
4330
+ if (!nativeKeychainAllowed()) return false;
4331
+ if (process.platform !== "darwin") return false;
4332
+ try {
4333
+ execSync2(
4334
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3866
4335
  { timeout: 5e3 }
3867
4336
  );
3868
4337
  return true;
@@ -3870,22 +4339,35 @@ function macKeychainSet(value) {
3870
4339
  return false;
3871
4340
  }
3872
4341
  }
3873
- function linuxSecretGet() {
3874
- if (process.platform !== "linux") return null;
4342
+ function linuxSecretGet(service = SERVICE) {
4343
+ if (!linuxSecretAvailable()) return null;
3875
4344
  try {
3876
4345
  return execSync2(
3877
- `secret-tool lookup service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
4346
+ `secret-tool lookup service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3878
4347
  { encoding: "utf-8", timeout: 5e3 }
3879
4348
  ).trim();
3880
4349
  } catch {
3881
4350
  return null;
3882
4351
  }
3883
4352
  }
3884
- function linuxSecretSet(value) {
4353
+ function linuxSecretSet(value, service = SERVICE) {
4354
+ if (!linuxSecretAvailable()) return false;
4355
+ try {
4356
+ execSync2(
4357
+ `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${service}" account "${ACCOUNT}" 2>/dev/null`,
4358
+ { timeout: 5e3 }
4359
+ );
4360
+ return true;
4361
+ } catch {
4362
+ return false;
4363
+ }
4364
+ }
4365
+ function linuxSecretDelete(service = SERVICE) {
4366
+ if (!nativeKeychainAllowed()) return false;
3885
4367
  if (process.platform !== "linux") return false;
3886
4368
  try {
3887
4369
  execSync2(
3888
- `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${SERVICE}" account "${ACCOUNT}"`,
4370
+ `secret-tool clear service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3889
4371
  { timeout: 5e3 }
3890
4372
  );
3891
4373
  return true;
@@ -3894,6 +4376,7 @@ function linuxSecretSet(value) {
3894
4376
  }
3895
4377
  }
3896
4378
  async function tryKeytar() {
4379
+ if (!nativeKeychainAllowed()) return null;
3897
4380
  try {
3898
4381
  return await import("keytar");
3899
4382
  } catch {
@@ -3968,7 +4451,19 @@ async function writeMachineBoundFileFallback(b64) {
3968
4451
  return "plaintext";
3969
4452
  }
3970
4453
  async function getMasterKey() {
3971
- const nativeValue = macKeychainGet() ?? linuxSecretGet();
4454
+ let nativeValue = macKeychainGet() ?? linuxSecretGet();
4455
+ if (!nativeValue) {
4456
+ const legacyValue = macKeychainGet(LEGACY_SERVICE) ?? linuxSecretGet(LEGACY_SERVICE);
4457
+ if (legacyValue) {
4458
+ const migrated = macKeychainSet(legacyValue) || linuxSecretSet(legacyValue);
4459
+ if (migrated) {
4460
+ macKeychainDelete(LEGACY_SERVICE);
4461
+ linuxSecretDelete(LEGACY_SERVICE);
4462
+ process.stderr.write("[keychain] Migrated keychain service from exe-mem to exe-os.\n");
4463
+ }
4464
+ nativeValue = legacyValue;
4465
+ }
4466
+ }
3972
4467
  if (nativeValue) {
3973
4468
  return Buffer.from(nativeValue, "base64");
3974
4469
  }
@@ -3976,12 +4471,17 @@ async function getMasterKey() {
3976
4471
  if (keytar) {
3977
4472
  try {
3978
4473
  const keytarValue = await keytar.getPassword(SERVICE, ACCOUNT);
3979
- if (keytarValue) {
3980
- const migrated = macKeychainSet(keytarValue) || linuxSecretSet(keytarValue);
4474
+ const legacyKeytarValue = keytarValue ?? await keytar.getPassword(LEGACY_SERVICE, ACCOUNT);
4475
+ if (legacyKeytarValue) {
4476
+ const migrated = macKeychainSet(legacyKeytarValue) || linuxSecretSet(legacyKeytarValue);
3981
4477
  if (migrated) {
3982
4478
  process.stderr.write("[keychain] Migrated key from keytar to native keychain.\n");
4479
+ try {
4480
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
4481
+ } catch {
4482
+ }
3983
4483
  }
3984
- return Buffer.from(keytarValue, "base64");
4484
+ return Buffer.from(legacyKeytarValue, "base64");
3985
4485
  }
3986
4486
  } catch {
3987
4487
  }
@@ -4006,7 +4506,7 @@ async function getMasterKey() {
4006
4506
  const decrypted = decryptWithMachineKey(content, machineKey);
4007
4507
  if (!decrypted) {
4008
4508
  process.stderr.write(
4009
- "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase: exe-os link import\n"
4509
+ "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase during setup: exe-os setup\n"
4010
4510
  );
4011
4511
  return null;
4012
4512
  }
@@ -4015,6 +4515,9 @@ async function getMasterKey() {
4015
4515
  b64Value = content;
4016
4516
  }
4017
4517
  const key = Buffer.from(b64Value, "base64");
4518
+ if (!content.startsWith(ENCRYPTED_PREFIX) && isRootOnlyTrustedServerKeyFile(keyPath)) {
4519
+ return key;
4520
+ }
4018
4521
  const migrated = macKeychainSet(b64Value) || linuxSecretSet(b64Value);
4019
4522
  if (migrated) {
4020
4523
  process.stderr.write("[keychain] Migrated key from file to native keychain.\n");
@@ -4617,6 +5120,11 @@ async function flushBatch() {
4617
5120
  await insertMemoryCardsForBatch2(batch);
4618
5121
  } catch {
4619
5122
  }
5123
+ try {
5124
+ const { insertOntologyForBatch: insertOntologyForBatch2 } = await Promise.resolve().then(() => (init_agentic_ontology(), agentic_ontology_exports));
5125
+ await insertOntologyForBatch2(batch);
5126
+ } catch {
5127
+ }
4620
5128
  schedulePostWriteMemoryHygiene(batch.map((row) => row.id));
4621
5129
  _pendingRecords.splice(0, batch.length);
4622
5130
  try {