@askexenow/exe-os 0.9.66 → 0.9.67

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (99) hide show
  1. package/deploy/stack-manifests/v0.9.json +54 -5
  2. package/dist/bin/age-ontology-load.js +61 -0
  3. package/dist/bin/agentic-ontology-backfill.js +4708 -0
  4. package/dist/bin/agentic-reflection-backfill.js +4144 -0
  5. package/dist/bin/{exe-link.js → agentic-semantic-label.js} +1523 -2275
  6. package/dist/bin/backfill-conversations.js +506 -20
  7. package/dist/bin/backfill-responses.js +506 -20
  8. package/dist/bin/backfill-vectors.js +233 -20
  9. package/dist/bin/bulk-sync-postgres.js +4876 -0
  10. package/dist/bin/cleanup-stale-review-tasks.js +507 -21
  11. package/dist/bin/cli.js +2450 -1530
  12. package/dist/bin/exe-assign.js +506 -20
  13. package/dist/bin/exe-boot.js +410 -60
  14. package/dist/bin/exe-cloud.js +795 -105
  15. package/dist/bin/exe-dispatch.js +516 -22
  16. package/dist/bin/exe-doctor.js +587 -30
  17. package/dist/bin/exe-export-behaviors.js +518 -24
  18. package/dist/bin/exe-forget.js +507 -21
  19. package/dist/bin/exe-gateway.js +571 -25
  20. package/dist/bin/exe-heartbeat.js +518 -24
  21. package/dist/bin/exe-kill.js +507 -21
  22. package/dist/bin/exe-launch-agent.js +2312 -1069
  23. package/dist/bin/exe-new-employee.js +197 -165
  24. package/dist/bin/exe-pending-messages.js +507 -21
  25. package/dist/bin/exe-pending-notifications.js +507 -21
  26. package/dist/bin/exe-pending-reviews.js +507 -21
  27. package/dist/bin/exe-rename.js +507 -21
  28. package/dist/bin/exe-review.js +507 -21
  29. package/dist/bin/exe-search.js +518 -24
  30. package/dist/bin/exe-session-cleanup.js +516 -22
  31. package/dist/bin/exe-settings.js +4 -0
  32. package/dist/bin/exe-start-codex.js +682 -143
  33. package/dist/bin/exe-start-opencode.js +627 -79
  34. package/dist/bin/exe-status.js +507 -21
  35. package/dist/bin/exe-team.js +507 -21
  36. package/dist/bin/git-sweep.js +516 -22
  37. package/dist/bin/graph-backfill.js +558 -21
  38. package/dist/bin/graph-export.js +507 -21
  39. package/dist/bin/graph-layer-benchmark.js +109 -0
  40. package/dist/bin/install.js +305 -288
  41. package/dist/bin/intercom-check.js +516 -22
  42. package/dist/bin/postgres-agentic-reflection-backfill.js +187 -0
  43. package/dist/bin/postgres-agentic-semantic-backfill.js +237 -0
  44. package/dist/bin/scan-tasks.js +516 -22
  45. package/dist/bin/setup.js +412 -62
  46. package/dist/bin/shard-migrate.js +506 -20
  47. package/dist/gateway/index.js +569 -23
  48. package/dist/hooks/bug-report-worker.js +519 -25
  49. package/dist/hooks/codex-stop-task-finalizer.js +516 -22
  50. package/dist/hooks/commit-complete.js +516 -22
  51. package/dist/hooks/error-recall.js +518 -24
  52. package/dist/hooks/ingest.js +516 -22
  53. package/dist/hooks/instructions-loaded.js +507 -21
  54. package/dist/hooks/notification.js +507 -21
  55. package/dist/hooks/post-compact.js +507 -21
  56. package/dist/hooks/post-tool-combined.js +519 -25
  57. package/dist/hooks/pre-compact.js +516 -22
  58. package/dist/hooks/pre-tool-use.js +507 -21
  59. package/dist/hooks/prompt-submit.js +519 -25
  60. package/dist/hooks/session-end.js +516 -22
  61. package/dist/hooks/session-start.js +520 -26
  62. package/dist/hooks/stop.js +517 -23
  63. package/dist/hooks/subagent-stop.js +507 -21
  64. package/dist/hooks/summary-worker.js +411 -61
  65. package/dist/index.js +569 -23
  66. package/dist/lib/cloud-sync.js +391 -53
  67. package/dist/lib/config.js +13 -1
  68. package/dist/lib/consolidation.js +1 -1
  69. package/dist/lib/database.js +124 -0
  70. package/dist/lib/db.js +124 -0
  71. package/dist/lib/device-registry.js +124 -0
  72. package/dist/lib/embedder.js +13 -1
  73. package/dist/lib/exe-daemon.js +2184 -561
  74. package/dist/lib/hybrid-search.js +518 -24
  75. package/dist/lib/identity.js +3 -0
  76. package/dist/lib/keychain.js +178 -22
  77. package/dist/lib/messaging.js +3 -0
  78. package/dist/lib/reminders.js +3 -0
  79. package/dist/lib/schedules.js +233 -20
  80. package/dist/lib/skill-learning.js +16 -1
  81. package/dist/lib/store.js +506 -20
  82. package/dist/lib/tasks.js +16 -1
  83. package/dist/lib/tmux-routing.js +16 -1
  84. package/dist/lib/token-spend.js +3 -0
  85. package/dist/mcp/server.js +1757 -428
  86. package/dist/mcp/tools/complete-reminder.js +3 -0
  87. package/dist/mcp/tools/create-reminder.js +3 -0
  88. package/dist/mcp/tools/create-task.js +16 -1
  89. package/dist/mcp/tools/deactivate-behavior.js +3 -0
  90. package/dist/mcp/tools/list-reminders.js +3 -0
  91. package/dist/mcp/tools/list-tasks.js +3 -0
  92. package/dist/mcp/tools/send-message.js +3 -0
  93. package/dist/mcp/tools/update-task.js +16 -1
  94. package/dist/runtime/index.js +516 -22
  95. package/dist/tui/App.js +594 -29
  96. package/package.json +8 -5
  97. package/src/commands/exe/cloud.md +6 -10
  98. package/stack.release.json +3 -3
  99. package/src/commands/exe/link.md +0 -18
@@ -222,6 +222,10 @@ async function loadConfig() {
222
222
  if (config.dbPath.startsWith("~")) {
223
223
  config.dbPath = config.dbPath.replace(/^~/, os.homedir());
224
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
+ }
225
229
  return config;
226
230
  } catch {
227
231
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
@@ -1529,6 +1533,9 @@ function getClient() {
1529
1533
  if (_daemonClient && _daemonClient._isDaemonActive()) {
1530
1534
  return _daemonClient;
1531
1535
  }
1536
+ if (!_resilientClient) {
1537
+ return _adapterClient;
1538
+ }
1532
1539
  return _resilientClient;
1533
1540
  }
1534
1541
  async function initDaemonClient() {
@@ -2561,6 +2568,127 @@ async function ensureSchema() {
2561
2568
  VALUES (new.rowid, new.content, new.subject, new.predicate, new.object);
2562
2569
  END;
2563
2570
  `);
2571
+ await client.executeMultiple(`
2572
+ CREATE TABLE IF NOT EXISTS agent_sessions (
2573
+ id TEXT PRIMARY KEY,
2574
+ agent_id TEXT NOT NULL,
2575
+ project_name TEXT,
2576
+ started_at TEXT NOT NULL,
2577
+ last_event_at TEXT NOT NULL,
2578
+ event_count INTEGER NOT NULL DEFAULT 0,
2579
+ properties TEXT DEFAULT '{}'
2580
+ );
2581
+
2582
+ CREATE INDEX IF NOT EXISTS idx_agent_sessions_agent_time
2583
+ ON agent_sessions(agent_id, started_at);
2584
+
2585
+ CREATE TABLE IF NOT EXISTS agent_goals (
2586
+ id TEXT PRIMARY KEY,
2587
+ statement TEXT NOT NULL,
2588
+ owner_agent_id TEXT,
2589
+ project_name TEXT,
2590
+ status TEXT NOT NULL DEFAULT 'open',
2591
+ priority INTEGER NOT NULL DEFAULT 5,
2592
+ success_criteria TEXT,
2593
+ parent_goal_id TEXT,
2594
+ due_at TEXT,
2595
+ achieved_at TEXT,
2596
+ supersedes_id TEXT,
2597
+ created_at TEXT NOT NULL,
2598
+ updated_at TEXT NOT NULL,
2599
+ source_memory_id TEXT
2600
+ );
2601
+
2602
+ CREATE INDEX IF NOT EXISTS idx_agent_goals_project_status
2603
+ ON agent_goals(project_name, status, priority);
2604
+
2605
+ CREATE TABLE IF NOT EXISTS agent_events (
2606
+ id TEXT PRIMARY KEY,
2607
+ event_type TEXT NOT NULL,
2608
+ occurred_at TEXT NOT NULL,
2609
+ sequence_index INTEGER NOT NULL,
2610
+ actor_agent_id TEXT,
2611
+ agent_role TEXT,
2612
+ project_name TEXT,
2613
+ session_id TEXT,
2614
+ task_id TEXT,
2615
+ goal_id TEXT,
2616
+ parent_event_id TEXT,
2617
+ intention TEXT,
2618
+ outcome TEXT,
2619
+ evidence_memory_id TEXT,
2620
+ impact TEXT,
2621
+ payload TEXT DEFAULT '{}',
2622
+ created_at TEXT NOT NULL
2623
+ );
2624
+
2625
+ CREATE INDEX IF NOT EXISTS idx_agent_events_time
2626
+ ON agent_events(occurred_at, sequence_index);
2627
+
2628
+ CREATE INDEX IF NOT EXISTS idx_agent_events_session_seq
2629
+ ON agent_events(session_id, sequence_index);
2630
+
2631
+ CREATE INDEX IF NOT EXISTS idx_agent_events_goal_time
2632
+ ON agent_events(goal_id, occurred_at);
2633
+
2634
+ CREATE INDEX IF NOT EXISTS idx_agent_events_memory
2635
+ ON agent_events(evidence_memory_id);
2636
+
2637
+ CREATE TABLE IF NOT EXISTS agent_goal_links (
2638
+ id TEXT PRIMARY KEY,
2639
+ goal_id TEXT NOT NULL,
2640
+ link_type TEXT NOT NULL,
2641
+ target_id TEXT NOT NULL,
2642
+ target_type TEXT NOT NULL,
2643
+ created_at TEXT NOT NULL
2644
+ );
2645
+
2646
+ CREATE INDEX IF NOT EXISTS idx_agent_goal_links_goal
2647
+ ON agent_goal_links(goal_id, target_type);
2648
+
2649
+ CREATE TABLE IF NOT EXISTS agent_semantic_labels (
2650
+ id TEXT PRIMARY KEY,
2651
+ source_memory_id TEXT NOT NULL,
2652
+ event_id TEXT,
2653
+ labeler TEXT NOT NULL,
2654
+ schema_version INTEGER NOT NULL DEFAULT 1,
2655
+ confidence REAL NOT NULL DEFAULT 0,
2656
+ labels TEXT NOT NULL,
2657
+ created_at TEXT NOT NULL,
2658
+ updated_at TEXT NOT NULL
2659
+ );
2660
+
2661
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_memory
2662
+ ON agent_semantic_labels(source_memory_id, labeler);
2663
+
2664
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_event
2665
+ ON agent_semantic_labels(event_id);
2666
+
2667
+ CREATE TABLE IF NOT EXISTS agent_reflection_checkpoints (
2668
+ id TEXT PRIMARY KEY,
2669
+ project_name TEXT,
2670
+ session_id TEXT,
2671
+ window_start_at TEXT NOT NULL,
2672
+ window_end_at TEXT NOT NULL,
2673
+ event_count INTEGER NOT NULL DEFAULT 0,
2674
+ goal_count INTEGER NOT NULL DEFAULT 0,
2675
+ success_count INTEGER NOT NULL DEFAULT 0,
2676
+ failure_count INTEGER NOT NULL DEFAULT 0,
2677
+ risk_count INTEGER NOT NULL DEFAULT 0,
2678
+ summary TEXT NOT NULL,
2679
+ learnings TEXT NOT NULL DEFAULT '[]',
2680
+ next_actions TEXT NOT NULL DEFAULT '[]',
2681
+ evidence_event_ids TEXT NOT NULL DEFAULT '[]',
2682
+ confidence REAL NOT NULL DEFAULT 0,
2683
+ created_at TEXT NOT NULL
2684
+ );
2685
+
2686
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_project_time
2687
+ ON agent_reflection_checkpoints(project_name, window_end_at);
2688
+
2689
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_session_time
2690
+ ON agent_reflection_checkpoints(session_id, window_end_at);
2691
+ `);
2564
2692
  try {
2565
2693
  await client.execute({
2566
2694
  sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
@@ -2724,7 +2852,7 @@ __export(shard_manager_exports, {
2724
2852
  shardExists: () => shardExists
2725
2853
  });
2726
2854
  import path7 from "path";
2727
- import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync2 } from "fs";
2855
+ import { existsSync as existsSync7, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync3 } from "fs";
2728
2856
  import { createClient as createClient2 } from "@libsql/client";
2729
2857
  function initShardManager(encryptionKey) {
2730
2858
  _encryptionKey = encryptionKey;
@@ -2788,7 +2916,7 @@ async function auditShardHealth(options = {}) {
2788
2916
  const shards = [];
2789
2917
  for (const name of names) {
2790
2918
  const dbPath = path7.join(SHARDS_DIR, `${name}.db`);
2791
- const stat = statSync2(dbPath);
2919
+ const stat = statSync3(dbPath);
2792
2920
  const item = {
2793
2921
  name,
2794
2922
  path: dbPath,
@@ -3041,7 +3169,7 @@ async function getReadyShardClient(projectName) {
3041
3169
  _shardLastAccess.delete(safeName);
3042
3170
  const dbPath = path7.join(SHARDS_DIR, `${safeName}.db`);
3043
3171
  if (existsSync7(dbPath)) {
3044
- const stat = statSync2(dbPath);
3172
+ const stat = statSync3(dbPath);
3045
3173
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
3046
3174
  const archivedPath = path7.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
3047
3175
  renameSync3(dbPath, archivedPath);
@@ -3548,17 +3676,286 @@ var init_memory_cards = __esm({
3548
3676
  }
3549
3677
  });
3550
3678
 
3679
+ // src/lib/agentic-ontology.ts
3680
+ var agentic_ontology_exports = {};
3681
+ __export(agentic_ontology_exports, {
3682
+ clean: () => clean,
3683
+ extractGoalCandidates: () => extractGoalCandidates,
3684
+ inferIntention: () => inferIntention,
3685
+ inferOntologyEventType: () => inferOntologyEventType,
3686
+ inferOutcome: () => inferOutcome,
3687
+ inferSemanticLabel: () => inferSemanticLabel,
3688
+ insertOntologyForBatch: () => insertOntologyForBatch,
3689
+ insertOntologyForMemory: () => insertOntologyForMemory,
3690
+ ontologyPayload: () => ontologyPayload,
3691
+ stableId: () => stableId2
3692
+ });
3693
+ import { createHash as createHash3 } from "crypto";
3694
+ function stableId2(...parts) {
3695
+ return createHash3("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
3696
+ }
3697
+ function clean(text, max = 240) {
3698
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
3699
+ }
3700
+ function inferOntologyEventType(row) {
3701
+ const lower = row.raw_text.toLowerCase();
3702
+ if (row.has_error) return "error";
3703
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
3704
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
3705
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
3706
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
3707
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
3708
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
3709
+ return "memory_observation";
3710
+ }
3711
+ function inferIntention(row) {
3712
+ if (row.intent) return clean(row.intent, 220);
3713
+ const text = clean(row.raw_text, 1e3);
3714
+ const patterns = [
3715
+ /(?: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,
3716
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
3717
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
3718
+ ];
3719
+ for (const p of patterns) {
3720
+ const m = text.match(p);
3721
+ if (m?.[1]) return clean(m[1], 220);
3722
+ }
3723
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
3724
+ return `${row.tool_name} during ${row.project_name}`;
3725
+ }
3726
+ return null;
3727
+ }
3728
+ function inferOutcome(row) {
3729
+ if (row.outcome) return clean(row.outcome, 220);
3730
+ if (row.has_error) return "error";
3731
+ const lower = row.raw_text.toLowerCase();
3732
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
3733
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
3734
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
3735
+ return null;
3736
+ }
3737
+ function extractGoalCandidates(row) {
3738
+ const text = clean(row.raw_text, 1600);
3739
+ const patterns = [
3740
+ /(?: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,
3741
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
3742
+ ];
3743
+ const out = [];
3744
+ for (const pattern of patterns) {
3745
+ for (const m of text.matchAll(pattern)) {
3746
+ const candidate = clean(m[1] ?? "", 220);
3747
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
3748
+ if (out.length >= 3) return out;
3749
+ }
3750
+ }
3751
+ return out;
3752
+ }
3753
+ function uniq(values, max = 6) {
3754
+ const out = [];
3755
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
3756
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
3757
+ if (out.length >= max) break;
3758
+ }
3759
+ return out;
3760
+ }
3761
+ function extractMatches(text, patterns, max = 5) {
3762
+ const out = [];
3763
+ for (const pattern of patterns) {
3764
+ for (const match of text.matchAll(pattern)) {
3765
+ const value = match[1] ?? match[0];
3766
+ if (value) out.push(value);
3767
+ if (out.length >= max) return uniq(out, max);
3768
+ }
3769
+ }
3770
+ return uniq(out, max);
3771
+ }
3772
+ function inferSemanticLabel(row) {
3773
+ const text = clean(row.raw_text, 2400);
3774
+ const eventType = inferOntologyEventType(row);
3775
+ const intention = inferIntention(row);
3776
+ const outcome = inferOutcome(row);
3777
+ const goals = extractGoalCandidates(row);
3778
+ const milestones = extractMatches(text, [
3779
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
3780
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
3781
+ ]);
3782
+ const problems = extractMatches(text, [
3783
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
3784
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
3785
+ ]);
3786
+ const decisions = extractMatches(text, [
3787
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
3788
+ ]);
3789
+ const temporalAnchors = extractMatches(text, [
3790
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
3791
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
3792
+ ], 8);
3793
+ const nextActions = extractMatches(text, [
3794
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
3795
+ ]);
3796
+ const actors = uniq([
3797
+ row.agent_id,
3798
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
3799
+ ], 6);
3800
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
3801
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
3802
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
3803
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
3804
+ return {
3805
+ labeler: "deterministic",
3806
+ schemaVersion: 1,
3807
+ eventType,
3808
+ intention,
3809
+ outcome,
3810
+ impact,
3811
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
3812
+ goals,
3813
+ milestones,
3814
+ problems,
3815
+ decisions,
3816
+ actors,
3817
+ temporalAnchors,
3818
+ successSignals,
3819
+ failureSignals,
3820
+ nextActions,
3821
+ summary: clean(text, 280)
3822
+ };
3823
+ }
3824
+ function ontologyPayload(row) {
3825
+ const semantic = inferSemanticLabel(row);
3826
+ return {
3827
+ tool_name: row.tool_name,
3828
+ memory_version: row.version ?? null,
3829
+ domain: row.domain ?? null,
3830
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
3831
+ semantic
3832
+ };
3833
+ }
3834
+ function safeJson(value) {
3835
+ try {
3836
+ return JSON.parse(value);
3837
+ } catch {
3838
+ return value.slice(0, 1e3);
3839
+ }
3840
+ }
3841
+ async function resolveClient(client) {
3842
+ if (client) return client;
3843
+ const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
3844
+ return getClient2();
3845
+ }
3846
+ async function insertOntologyForMemory(row, client) {
3847
+ const db = await resolveClient(client);
3848
+ const occurredAt = row.timestamp;
3849
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
3850
+ const eventType = inferOntologyEventType(row);
3851
+ const intention = inferIntention(row);
3852
+ const outcome = inferOutcome(row);
3853
+ const eventId = stableId2("event", row.id);
3854
+ const now = (/* @__PURE__ */ new Date()).toISOString();
3855
+ await db.execute({
3856
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
3857
+ VALUES (?, ?, ?, ?, ?, 1, ?)
3858
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
3859
+ event_count = event_count + 1`,
3860
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
3861
+ });
3862
+ await db.execute({
3863
+ sql: `INSERT OR IGNORE INTO agent_events
3864
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
3865
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
3866
+ impact, payload, created_at)
3867
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
3868
+ args: [
3869
+ eventId,
3870
+ eventType,
3871
+ occurredAt,
3872
+ sequence,
3873
+ row.agent_id,
3874
+ row.agent_role,
3875
+ row.project_name,
3876
+ row.session_id,
3877
+ row.task_id ?? null,
3878
+ intention,
3879
+ outcome,
3880
+ row.id,
3881
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
3882
+ JSON.stringify(ontologyPayload(row)),
3883
+ now
3884
+ ]
3885
+ });
3886
+ const semantic = inferSemanticLabel(row);
3887
+ await db.execute({
3888
+ sql: `INSERT INTO agent_semantic_labels
3889
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
3890
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
3891
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
3892
+ labels = excluded.labels, updated_at = excluded.updated_at`,
3893
+ args: [
3894
+ stableId2("semantic", row.id, semantic.labeler, semantic.schemaVersion),
3895
+ row.id,
3896
+ eventId,
3897
+ semantic.labeler,
3898
+ semantic.schemaVersion,
3899
+ semantic.confidence,
3900
+ JSON.stringify(semantic),
3901
+ now,
3902
+ now
3903
+ ]
3904
+ });
3905
+ for (const statement of extractGoalCandidates(row)) {
3906
+ const goalId = stableId2("goal", row.project_name, statement.toLowerCase());
3907
+ await db.execute({
3908
+ sql: `INSERT INTO agent_goals
3909
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
3910
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
3911
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
3912
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
3913
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
3914
+ });
3915
+ await db.execute({
3916
+ sql: `INSERT OR IGNORE INTO agent_goal_links
3917
+ (id, goal_id, link_type, target_id, target_type, created_at)
3918
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
3919
+ args: [stableId2("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
3920
+ });
3921
+ await db.execute({
3922
+ sql: `INSERT OR IGNORE INTO agent_goal_links
3923
+ (id, goal_id, link_type, target_id, target_type, created_at)
3924
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
3925
+ args: [stableId2("goal_link", goalId, eventId, "event"), goalId, eventId, now]
3926
+ });
3927
+ }
3928
+ }
3929
+ async function insertOntologyForBatch(rows, client) {
3930
+ const db = await resolveClient(client);
3931
+ let count = 0;
3932
+ for (const row of rows) {
3933
+ try {
3934
+ await insertOntologyForMemory(row, db);
3935
+ count++;
3936
+ } catch {
3937
+ }
3938
+ }
3939
+ return count;
3940
+ }
3941
+ var init_agentic_ontology = __esm({
3942
+ "src/lib/agentic-ontology.ts"() {
3943
+ "use strict";
3944
+ }
3945
+ });
3946
+
3551
3947
  // src/lib/store.ts
3552
3948
  init_memory();
3553
3949
  init_database();
3554
3950
 
3555
3951
  // src/lib/keychain.ts
3556
3952
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3557
- import { existsSync as existsSync6 } from "fs";
3953
+ import { existsSync as existsSync6, statSync as statSync2 } from "fs";
3558
3954
  import { execSync as execSync2 } from "child_process";
3559
3955
  import path6 from "path";
3560
3956
  import os5 from "os";
3561
- var SERVICE = "exe-mem";
3957
+ var SERVICE = "exe-os";
3958
+ var LEGACY_SERVICE = "exe-mem";
3562
3959
  var ACCOUNT = "master-key";
3563
3960
  function getKeyDir() {
3564
3961
  return process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? path6.join(os5.homedir(), ".exe-os");
@@ -3566,29 +3963,66 @@ function getKeyDir() {
3566
3963
  function getKeyPath() {
3567
3964
  return path6.join(getKeyDir(), "master.key");
3568
3965
  }
3569
- function macKeychainGet() {
3966
+ function nativeKeychainAllowed() {
3967
+ return process.env.EXE_OS_DISABLE_NATIVE_KEYCHAIN !== "1";
3968
+ }
3969
+ var linuxSecretAvailability = null;
3970
+ function linuxSecretAvailable() {
3971
+ if (!nativeKeychainAllowed()) return false;
3972
+ if (process.platform !== "linux") return false;
3973
+ if (linuxSecretAvailability !== null) return linuxSecretAvailability;
3974
+ try {
3975
+ execSync2("command -v secret-tool >/dev/null 2>&1", { timeout: 1e3 });
3976
+ } catch {
3977
+ linuxSecretAvailability = false;
3978
+ return false;
3979
+ }
3980
+ try {
3981
+ execSync2("secret-tool search --all exe-os probe >/dev/null 2>&1", { timeout: 1e3 });
3982
+ linuxSecretAvailability = true;
3983
+ } catch {
3984
+ linuxSecretAvailability = false;
3985
+ }
3986
+ return linuxSecretAvailability;
3987
+ }
3988
+ function isRootOnlyTrustedServerKeyFile(keyPath) {
3989
+ if (process.platform !== "linux") return false;
3990
+ try {
3991
+ const uid = typeof os5.userInfo().uid === "number" ? os5.userInfo().uid : -1;
3992
+ const st = statSync2(keyPath);
3993
+ if (!st.isFile() || (st.mode & 63) !== 0) return false;
3994
+ if (uid === 0) return true;
3995
+ const exeOsDir = process.env.EXE_OS_DIR;
3996
+ return Boolean(exeOsDir && path6.resolve(keyPath).startsWith(path6.resolve(exeOsDir) + path6.sep));
3997
+ } catch {
3998
+ return false;
3999
+ }
4000
+ }
4001
+ function macKeychainGet(service = SERVICE) {
4002
+ if (!nativeKeychainAllowed()) return null;
3570
4003
  if (process.platform !== "darwin") return null;
3571
4004
  try {
3572
4005
  return execSync2(
3573
- `security find-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w 2>/dev/null`,
4006
+ `security find-generic-password -s "${service}" -a "${ACCOUNT}" -w 2>/dev/null`,
3574
4007
  { encoding: "utf-8", timeout: 5e3 }
3575
4008
  ).trim();
3576
4009
  } catch {
3577
4010
  return null;
3578
4011
  }
3579
4012
  }
3580
- function macKeychainSet(value) {
4013
+ function macKeychainSet(value, service = SERVICE) {
4014
+ if (!nativeKeychainAllowed()) return false;
3581
4015
  if (process.platform !== "darwin") return false;
3582
4016
  try {
3583
4017
  try {
3584
4018
  execSync2(
3585
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
4019
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3586
4020
  { timeout: 5e3 }
3587
4021
  );
3588
4022
  } catch {
3589
4023
  }
3590
4024
  execSync2(
3591
- `security add-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w "${value}"`,
4025
+ `security add-generic-password -s "${service}" -a "${ACCOUNT}" -w "${value}"`,
3592
4026
  { timeout: 5e3 }
3593
4027
  );
3594
4028
  return true;
@@ -3596,22 +4030,48 @@ function macKeychainSet(value) {
3596
4030
  return false;
3597
4031
  }
3598
4032
  }
3599
- function linuxSecretGet() {
3600
- if (process.platform !== "linux") return null;
4033
+ function macKeychainDelete(service = SERVICE) {
4034
+ if (!nativeKeychainAllowed()) return false;
4035
+ if (process.platform !== "darwin") return false;
4036
+ try {
4037
+ execSync2(
4038
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
4039
+ { timeout: 5e3 }
4040
+ );
4041
+ return true;
4042
+ } catch {
4043
+ return false;
4044
+ }
4045
+ }
4046
+ function linuxSecretGet(service = SERVICE) {
4047
+ if (!linuxSecretAvailable()) return null;
3601
4048
  try {
3602
4049
  return execSync2(
3603
- `secret-tool lookup service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
4050
+ `secret-tool lookup service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3604
4051
  { encoding: "utf-8", timeout: 5e3 }
3605
4052
  ).trim();
3606
4053
  } catch {
3607
4054
  return null;
3608
4055
  }
3609
4056
  }
3610
- function linuxSecretSet(value) {
4057
+ function linuxSecretSet(value, service = SERVICE) {
4058
+ if (!linuxSecretAvailable()) return false;
4059
+ try {
4060
+ execSync2(
4061
+ `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${service}" account "${ACCOUNT}" 2>/dev/null`,
4062
+ { timeout: 5e3 }
4063
+ );
4064
+ return true;
4065
+ } catch {
4066
+ return false;
4067
+ }
4068
+ }
4069
+ function linuxSecretDelete(service = SERVICE) {
4070
+ if (!nativeKeychainAllowed()) return false;
3611
4071
  if (process.platform !== "linux") return false;
3612
4072
  try {
3613
4073
  execSync2(
3614
- `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${SERVICE}" account "${ACCOUNT}"`,
4074
+ `secret-tool clear service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3615
4075
  { timeout: 5e3 }
3616
4076
  );
3617
4077
  return true;
@@ -3620,6 +4080,7 @@ function linuxSecretSet(value) {
3620
4080
  }
3621
4081
  }
3622
4082
  async function tryKeytar() {
4083
+ if (!nativeKeychainAllowed()) return null;
3623
4084
  try {
3624
4085
  return await import("keytar");
3625
4086
  } catch {
@@ -3694,7 +4155,19 @@ async function writeMachineBoundFileFallback(b64) {
3694
4155
  return "plaintext";
3695
4156
  }
3696
4157
  async function getMasterKey() {
3697
- const nativeValue = macKeychainGet() ?? linuxSecretGet();
4158
+ let nativeValue = macKeychainGet() ?? linuxSecretGet();
4159
+ if (!nativeValue) {
4160
+ const legacyValue = macKeychainGet(LEGACY_SERVICE) ?? linuxSecretGet(LEGACY_SERVICE);
4161
+ if (legacyValue) {
4162
+ const migrated = macKeychainSet(legacyValue) || linuxSecretSet(legacyValue);
4163
+ if (migrated) {
4164
+ macKeychainDelete(LEGACY_SERVICE);
4165
+ linuxSecretDelete(LEGACY_SERVICE);
4166
+ process.stderr.write("[keychain] Migrated keychain service from exe-mem to exe-os.\n");
4167
+ }
4168
+ nativeValue = legacyValue;
4169
+ }
4170
+ }
3698
4171
  if (nativeValue) {
3699
4172
  return Buffer.from(nativeValue, "base64");
3700
4173
  }
@@ -3702,12 +4175,17 @@ async function getMasterKey() {
3702
4175
  if (keytar) {
3703
4176
  try {
3704
4177
  const keytarValue = await keytar.getPassword(SERVICE, ACCOUNT);
3705
- if (keytarValue) {
3706
- const migrated = macKeychainSet(keytarValue) || linuxSecretSet(keytarValue);
4178
+ const legacyKeytarValue = keytarValue ?? await keytar.getPassword(LEGACY_SERVICE, ACCOUNT);
4179
+ if (legacyKeytarValue) {
4180
+ const migrated = macKeychainSet(legacyKeytarValue) || linuxSecretSet(legacyKeytarValue);
3707
4181
  if (migrated) {
3708
4182
  process.stderr.write("[keychain] Migrated key from keytar to native keychain.\n");
4183
+ try {
4184
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
4185
+ } catch {
4186
+ }
3709
4187
  }
3710
- return Buffer.from(keytarValue, "base64");
4188
+ return Buffer.from(legacyKeytarValue, "base64");
3711
4189
  }
3712
4190
  } catch {
3713
4191
  }
@@ -3732,7 +4210,7 @@ async function getMasterKey() {
3732
4210
  const decrypted = decryptWithMachineKey(content, machineKey);
3733
4211
  if (!decrypted) {
3734
4212
  process.stderr.write(
3735
- "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase: exe-os link import\n"
4213
+ "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase during setup: exe-os setup\n"
3736
4214
  );
3737
4215
  return null;
3738
4216
  }
@@ -3741,6 +4219,9 @@ async function getMasterKey() {
3741
4219
  b64Value = content;
3742
4220
  }
3743
4221
  const key = Buffer.from(b64Value, "base64");
4222
+ if (!content.startsWith(ENCRYPTED_PREFIX) && isRootOnlyTrustedServerKeyFile(keyPath)) {
4223
+ return key;
4224
+ }
3744
4225
  const migrated = macKeychainSet(b64Value) || linuxSecretSet(b64Value);
3745
4226
  if (migrated) {
3746
4227
  process.stderr.write("[keychain] Migrated key from file to native keychain.\n");
@@ -4107,6 +4588,11 @@ async function flushBatch() {
4107
4588
  await insertMemoryCardsForBatch2(batch);
4108
4589
  } catch {
4109
4590
  }
4591
+ try {
4592
+ const { insertOntologyForBatch: insertOntologyForBatch2 } = await Promise.resolve().then(() => (init_agentic_ontology(), agentic_ontology_exports));
4593
+ await insertOntologyForBatch2(batch);
4594
+ } catch {
4595
+ }
4110
4596
  schedulePostWriteMemoryHygiene(batch.map((row) => row.id));
4111
4597
  _pendingRecords.splice(0, batch.length);
4112
4598
  try {
@@ -4518,6 +5004,57 @@ function extractFromCode(source, filePath) {
4518
5004
  }
4519
5005
  return { entities, relationships, hyperedges: [] };
4520
5006
  }
5007
+ function pushUniqueEntity(entities, seen, name, type) {
5008
+ const normalized = normalizeEntityName(name);
5009
+ if (!normalized || normalized.length < 2) return;
5010
+ const key = `${normalized.toLowerCase()}::${type.toLowerCase()}`;
5011
+ if (seen.has(key)) return;
5012
+ seen.add(key);
5013
+ entities.push({ name: normalized.slice(0, 160), type });
5014
+ }
5015
+ function pushHeuristicRelationship(relationships, source, sourceType, target, targetType, relationship, confidence = 0.6) {
5016
+ if (!source || !target || source === target) return;
5017
+ relationships.push({
5018
+ source,
5019
+ sourceType,
5020
+ target,
5021
+ targetType,
5022
+ relationship,
5023
+ confidence,
5024
+ confidenceLabel: "inferred"
5025
+ });
5026
+ }
5027
+ function extractHeuristicMemoryGraph(content, agentId) {
5028
+ const entities = [];
5029
+ const relationships = [];
5030
+ const seen = /* @__PURE__ */ new Set();
5031
+ pushUniqueEntity(entities, seen, agentId, "person");
5032
+ const toolMatch = content.match(/^(Bash|Read|Edit|Write|Grep|Glob|AssistantResponse|Tool|Ran|Wrote|Edited):/m);
5033
+ if (toolMatch?.[1]) {
5034
+ pushUniqueEntity(entities, seen, toolMatch[1], "tool");
5035
+ pushHeuristicRelationship(relationships, agentId, "person", toolMatch[1], "tool", "uses", 0.75);
5036
+ }
5037
+ const repoMatches = [...content.matchAll(/\/Users\/[^/\s]+\/([A-Za-z0-9_.-]+)|\/opt\/([A-Za-z0-9_.-]+)/g)].map((m) => m[1] ?? m[2]).filter((repo) => Boolean(repo)).slice(0, 6);
5038
+ for (const repo of repoMatches) {
5039
+ pushUniqueEntity(entities, seen, repo, "project");
5040
+ pushHeuristicRelationship(relationships, agentId, "person", repo, "project", "worked_on", 0.7);
5041
+ }
5042
+ const pathMatches = new Set(
5043
+ (content.match(/(?:\/[\w .@-]+)+(?:\.[A-Za-z0-9]{1,10})|(?:[\w@.-]+\/)+[\w@.-]+\.(?:ts|tsx|js|jsx|json|md|yml|yaml|sql|py|go|rs|sh|css|html)/g) ?? []).slice(0, 10)
5044
+ );
5045
+ for (const filePath of pathMatches) {
5046
+ pushUniqueEntity(entities, seen, filePath, "file");
5047
+ pushHeuristicRelationship(relationships, agentId, "person", filePath, "file", "uses", 0.65);
5048
+ }
5049
+ const backtickTerms = [...content.matchAll(/`([^`\n]{2,80})`/g)].map((m) => m[1]).slice(0, 10);
5050
+ for (const term of backtickTerms) {
5051
+ if (!term || term.length < 2) continue;
5052
+ const type = term.includes("/") || /\.[A-Za-z0-9]{1,10}$/.test(term) ? "file" : "concept";
5053
+ pushUniqueEntity(entities, seen, term, type);
5054
+ pushHeuristicRelationship(relationships, agentId, "person", term, type, "uses", 0.55);
5055
+ }
5056
+ return { entities, relationships, hyperedges: [] };
5057
+ }
4521
5058
  async function extractFromMemory(content, agentId, model = "claude-haiku-4-5-20251001", filePath) {
4522
5059
  if (content.length < 50) {
4523
5060
  return { entities: [], relationships: [], hyperedges: [] };
@@ -4573,7 +5110,7 @@ async function extractFromMemory(content, agentId, model = "claude-haiku-4-5-202
4573
5110
  `
4574
5111
  );
4575
5112
  }
4576
- return { entities: [], relationships: [], hyperedges: [] };
5113
+ return extractHeuristicMemoryGraph(content, agentId);
4577
5114
  }
4578
5115
  async function storeExtraction(client, extraction, memoryId, timestamp) {
4579
5116
  let entitiesStored = 0;