@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
@@ -204,6 +204,11 @@ function normalizeAutoUpdate(raw) {
204
204
  const userAU = raw.autoUpdate ?? {};
205
205
  raw.autoUpdate = { ...defaultAU, ...userAU };
206
206
  }
207
+ function normalizeOrchestration(raw) {
208
+ const defaultOrg = DEFAULT_CONFIG.orchestration;
209
+ const userOrg = raw.orchestration ?? {};
210
+ raw.orchestration = { ...defaultOrg, ...userOrg };
211
+ }
207
212
  async function loadConfig() {
208
213
  const dir = process.env.EXE_OS_DIR ?? process.env.EXE_MEM_DIR ?? EXE_AI_DIR;
209
214
  await ensurePrivateDir(dir);
@@ -228,10 +233,15 @@ async function loadConfig() {
228
233
  normalizeScalingRoadmap(migratedCfg);
229
234
  normalizeSessionLifecycle(migratedCfg);
230
235
  normalizeAutoUpdate(migratedCfg);
236
+ normalizeOrchestration(migratedCfg);
231
237
  const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
232
238
  if (config.dbPath.startsWith("~")) {
233
239
  config.dbPath = config.dbPath.replace(/^~/, os.homedir());
234
240
  }
241
+ const envDbPath = path.join(dir, "memories.db");
242
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync2(config.dbPath) && existsSync2(envDbPath)) {
243
+ config.dbPath = envDbPath;
244
+ }
235
245
  return config;
236
246
  } catch {
237
247
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
@@ -251,7 +261,16 @@ function loadConfigSync() {
251
261
  normalizeScalingRoadmap(migratedCfg);
252
262
  normalizeSessionLifecycle(migratedCfg);
253
263
  normalizeAutoUpdate(migratedCfg);
254
- return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
264
+ normalizeOrchestration(migratedCfg);
265
+ const config = { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db"), ...migratedCfg };
266
+ if (config.dbPath.startsWith("~")) {
267
+ config.dbPath = config.dbPath.replace(/^~/, os.homedir());
268
+ }
269
+ const envDbPath = path.join(dir, "memories.db");
270
+ if (process.env.EXE_OS_DIR && config.dbPath !== envDbPath && !existsSync2(config.dbPath) && existsSync2(envDbPath)) {
271
+ config.dbPath = envDbPath;
272
+ }
273
+ return config;
255
274
  } catch {
256
275
  return { ...DEFAULT_CONFIG, dbPath: path.join(dir, "memories.db") };
257
276
  }
@@ -272,6 +291,7 @@ async function loadConfigFrom(configPath) {
272
291
  normalizeScalingRoadmap(migratedCfg);
273
292
  normalizeSessionLifecycle(migratedCfg);
274
293
  normalizeAutoUpdate(migratedCfg);
294
+ normalizeOrchestration(migratedCfg);
275
295
  return { ...DEFAULT_CONFIG, ...migratedCfg };
276
296
  } catch {
277
297
  return { ...DEFAULT_CONFIG };
@@ -343,6 +363,10 @@ var init_config = __esm({
343
363
  checkOnBoot: true,
344
364
  autoInstall: false,
345
365
  checkIntervalMs: 24 * 60 * 60 * 1e3
366
+ },
367
+ orchestration: {
368
+ phase: "phase_1_coo",
369
+ phaseSetBy: "default"
346
370
  }
347
371
  };
348
372
  CONFIG_MIGRATIONS = [
@@ -2134,6 +2158,9 @@ function getClient() {
2134
2158
  if (_daemonClient && _daemonClient._isDaemonActive()) {
2135
2159
  return _daemonClient;
2136
2160
  }
2161
+ if (!_resilientClient) {
2162
+ return _adapterClient;
2163
+ }
2137
2164
  return _resilientClient;
2138
2165
  }
2139
2166
  async function initDaemonClient() {
@@ -3166,6 +3193,127 @@ async function ensureSchema() {
3166
3193
  VALUES (new.rowid, new.content, new.subject, new.predicate, new.object);
3167
3194
  END;
3168
3195
  `);
3196
+ await client.executeMultiple(`
3197
+ CREATE TABLE IF NOT EXISTS agent_sessions (
3198
+ id TEXT PRIMARY KEY,
3199
+ agent_id TEXT NOT NULL,
3200
+ project_name TEXT,
3201
+ started_at TEXT NOT NULL,
3202
+ last_event_at TEXT NOT NULL,
3203
+ event_count INTEGER NOT NULL DEFAULT 0,
3204
+ properties TEXT DEFAULT '{}'
3205
+ );
3206
+
3207
+ CREATE INDEX IF NOT EXISTS idx_agent_sessions_agent_time
3208
+ ON agent_sessions(agent_id, started_at);
3209
+
3210
+ CREATE TABLE IF NOT EXISTS agent_goals (
3211
+ id TEXT PRIMARY KEY,
3212
+ statement TEXT NOT NULL,
3213
+ owner_agent_id TEXT,
3214
+ project_name TEXT,
3215
+ status TEXT NOT NULL DEFAULT 'open',
3216
+ priority INTEGER NOT NULL DEFAULT 5,
3217
+ success_criteria TEXT,
3218
+ parent_goal_id TEXT,
3219
+ due_at TEXT,
3220
+ achieved_at TEXT,
3221
+ supersedes_id TEXT,
3222
+ created_at TEXT NOT NULL,
3223
+ updated_at TEXT NOT NULL,
3224
+ source_memory_id TEXT
3225
+ );
3226
+
3227
+ CREATE INDEX IF NOT EXISTS idx_agent_goals_project_status
3228
+ ON agent_goals(project_name, status, priority);
3229
+
3230
+ CREATE TABLE IF NOT EXISTS agent_events (
3231
+ id TEXT PRIMARY KEY,
3232
+ event_type TEXT NOT NULL,
3233
+ occurred_at TEXT NOT NULL,
3234
+ sequence_index INTEGER NOT NULL,
3235
+ actor_agent_id TEXT,
3236
+ agent_role TEXT,
3237
+ project_name TEXT,
3238
+ session_id TEXT,
3239
+ task_id TEXT,
3240
+ goal_id TEXT,
3241
+ parent_event_id TEXT,
3242
+ intention TEXT,
3243
+ outcome TEXT,
3244
+ evidence_memory_id TEXT,
3245
+ impact TEXT,
3246
+ payload TEXT DEFAULT '{}',
3247
+ created_at TEXT NOT NULL
3248
+ );
3249
+
3250
+ CREATE INDEX IF NOT EXISTS idx_agent_events_time
3251
+ ON agent_events(occurred_at, sequence_index);
3252
+
3253
+ CREATE INDEX IF NOT EXISTS idx_agent_events_session_seq
3254
+ ON agent_events(session_id, sequence_index);
3255
+
3256
+ CREATE INDEX IF NOT EXISTS idx_agent_events_goal_time
3257
+ ON agent_events(goal_id, occurred_at);
3258
+
3259
+ CREATE INDEX IF NOT EXISTS idx_agent_events_memory
3260
+ ON agent_events(evidence_memory_id);
3261
+
3262
+ CREATE TABLE IF NOT EXISTS agent_goal_links (
3263
+ id TEXT PRIMARY KEY,
3264
+ goal_id TEXT NOT NULL,
3265
+ link_type TEXT NOT NULL,
3266
+ target_id TEXT NOT NULL,
3267
+ target_type TEXT NOT NULL,
3268
+ created_at TEXT NOT NULL
3269
+ );
3270
+
3271
+ CREATE INDEX IF NOT EXISTS idx_agent_goal_links_goal
3272
+ ON agent_goal_links(goal_id, target_type);
3273
+
3274
+ CREATE TABLE IF NOT EXISTS agent_semantic_labels (
3275
+ id TEXT PRIMARY KEY,
3276
+ source_memory_id TEXT NOT NULL,
3277
+ event_id TEXT,
3278
+ labeler TEXT NOT NULL,
3279
+ schema_version INTEGER NOT NULL DEFAULT 1,
3280
+ confidence REAL NOT NULL DEFAULT 0,
3281
+ labels TEXT NOT NULL,
3282
+ created_at TEXT NOT NULL,
3283
+ updated_at TEXT NOT NULL
3284
+ );
3285
+
3286
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_memory
3287
+ ON agent_semantic_labels(source_memory_id, labeler);
3288
+
3289
+ CREATE INDEX IF NOT EXISTS idx_agent_semantic_labels_event
3290
+ ON agent_semantic_labels(event_id);
3291
+
3292
+ CREATE TABLE IF NOT EXISTS agent_reflection_checkpoints (
3293
+ id TEXT PRIMARY KEY,
3294
+ project_name TEXT,
3295
+ session_id TEXT,
3296
+ window_start_at TEXT NOT NULL,
3297
+ window_end_at TEXT NOT NULL,
3298
+ event_count INTEGER NOT NULL DEFAULT 0,
3299
+ goal_count INTEGER NOT NULL DEFAULT 0,
3300
+ success_count INTEGER NOT NULL DEFAULT 0,
3301
+ failure_count INTEGER NOT NULL DEFAULT 0,
3302
+ risk_count INTEGER NOT NULL DEFAULT 0,
3303
+ summary TEXT NOT NULL,
3304
+ learnings TEXT NOT NULL DEFAULT '[]',
3305
+ next_actions TEXT NOT NULL DEFAULT '[]',
3306
+ evidence_event_ids TEXT NOT NULL DEFAULT '[]',
3307
+ confidence REAL NOT NULL DEFAULT 0,
3308
+ created_at TEXT NOT NULL
3309
+ );
3310
+
3311
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_project_time
3312
+ ON agent_reflection_checkpoints(project_name, window_end_at);
3313
+
3314
+ CREATE INDEX IF NOT EXISTS idx_agent_reflection_session_time
3315
+ ON agent_reflection_checkpoints(session_id, window_end_at);
3316
+ `);
3169
3317
  try {
3170
3318
  await client.execute({
3171
3319
  sql: `ALTER TABLE memories ADD COLUMN tier INTEGER DEFAULT 3`,
@@ -3315,7 +3463,7 @@ var init_database = __esm({
3315
3463
 
3316
3464
  // src/lib/keychain.ts
3317
3465
  import { readFile as readFile3, writeFile as writeFile3, unlink, mkdir as mkdir3, chmod as chmod2 } from "fs/promises";
3318
- import { existsSync as existsSync7 } from "fs";
3466
+ import { existsSync as existsSync7, statSync as statSync2 } from "fs";
3319
3467
  import { execSync as execSync2 } from "child_process";
3320
3468
  import path7 from "path";
3321
3469
  import os5 from "os";
@@ -3325,29 +3473,65 @@ function getKeyDir() {
3325
3473
  function getKeyPath() {
3326
3474
  return path7.join(getKeyDir(), "master.key");
3327
3475
  }
3328
- function macKeychainGet() {
3476
+ function nativeKeychainAllowed() {
3477
+ return process.env.EXE_OS_DISABLE_NATIVE_KEYCHAIN !== "1";
3478
+ }
3479
+ function linuxSecretAvailable() {
3480
+ if (!nativeKeychainAllowed()) return false;
3481
+ if (process.platform !== "linux") return false;
3482
+ if (linuxSecretAvailability !== null) return linuxSecretAvailability;
3483
+ try {
3484
+ execSync2("command -v secret-tool >/dev/null 2>&1", { timeout: 1e3 });
3485
+ } catch {
3486
+ linuxSecretAvailability = false;
3487
+ return false;
3488
+ }
3489
+ try {
3490
+ execSync2("secret-tool search --all exe-os probe >/dev/null 2>&1", { timeout: 1e3 });
3491
+ linuxSecretAvailability = true;
3492
+ } catch {
3493
+ linuxSecretAvailability = false;
3494
+ }
3495
+ return linuxSecretAvailability;
3496
+ }
3497
+ function isRootOnlyTrustedServerKeyFile(keyPath) {
3498
+ if (process.platform !== "linux") return false;
3499
+ try {
3500
+ const uid = typeof os5.userInfo().uid === "number" ? os5.userInfo().uid : -1;
3501
+ const st = statSync2(keyPath);
3502
+ if (!st.isFile() || (st.mode & 63) !== 0) return false;
3503
+ if (uid === 0) return true;
3504
+ const exeOsDir = process.env.EXE_OS_DIR;
3505
+ return Boolean(exeOsDir && path7.resolve(keyPath).startsWith(path7.resolve(exeOsDir) + path7.sep));
3506
+ } catch {
3507
+ return false;
3508
+ }
3509
+ }
3510
+ function macKeychainGet(service = SERVICE) {
3511
+ if (!nativeKeychainAllowed()) return null;
3329
3512
  if (process.platform !== "darwin") return null;
3330
3513
  try {
3331
3514
  return execSync2(
3332
- `security find-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w 2>/dev/null`,
3515
+ `security find-generic-password -s "${service}" -a "${ACCOUNT}" -w 2>/dev/null`,
3333
3516
  { encoding: "utf-8", timeout: 5e3 }
3334
3517
  ).trim();
3335
3518
  } catch {
3336
3519
  return null;
3337
3520
  }
3338
3521
  }
3339
- function macKeychainSet(value) {
3522
+ function macKeychainSet(value, service = SERVICE) {
3523
+ if (!nativeKeychainAllowed()) return false;
3340
3524
  if (process.platform !== "darwin") return false;
3341
3525
  try {
3342
3526
  try {
3343
3527
  execSync2(
3344
- `security delete-generic-password -s "${SERVICE}" -a "${ACCOUNT}" 2>/dev/null`,
3528
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3345
3529
  { timeout: 5e3 }
3346
3530
  );
3347
3531
  } catch {
3348
3532
  }
3349
3533
  execSync2(
3350
- `security add-generic-password -s "${SERVICE}" -a "${ACCOUNT}" -w "${value}"`,
3534
+ `security add-generic-password -s "${service}" -a "${ACCOUNT}" -w "${value}"`,
3351
3535
  { timeout: 5e3 }
3352
3536
  );
3353
3537
  return true;
@@ -3355,22 +3539,48 @@ function macKeychainSet(value) {
3355
3539
  return false;
3356
3540
  }
3357
3541
  }
3358
- function linuxSecretGet() {
3359
- if (process.platform !== "linux") return null;
3542
+ function macKeychainDelete(service = SERVICE) {
3543
+ if (!nativeKeychainAllowed()) return false;
3544
+ if (process.platform !== "darwin") return false;
3545
+ try {
3546
+ execSync2(
3547
+ `security delete-generic-password -s "${service}" -a "${ACCOUNT}" 2>/dev/null`,
3548
+ { timeout: 5e3 }
3549
+ );
3550
+ return true;
3551
+ } catch {
3552
+ return false;
3553
+ }
3554
+ }
3555
+ function linuxSecretGet(service = SERVICE) {
3556
+ if (!linuxSecretAvailable()) return null;
3360
3557
  try {
3361
3558
  return execSync2(
3362
- `secret-tool lookup service "${SERVICE}" account "${ACCOUNT}" 2>/dev/null`,
3559
+ `secret-tool lookup service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3363
3560
  { encoding: "utf-8", timeout: 5e3 }
3364
3561
  ).trim();
3365
3562
  } catch {
3366
3563
  return null;
3367
3564
  }
3368
3565
  }
3369
- function linuxSecretSet(value) {
3566
+ function linuxSecretSet(value, service = SERVICE) {
3567
+ if (!linuxSecretAvailable()) return false;
3568
+ try {
3569
+ execSync2(
3570
+ `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3571
+ { timeout: 5e3 }
3572
+ );
3573
+ return true;
3574
+ } catch {
3575
+ return false;
3576
+ }
3577
+ }
3578
+ function linuxSecretDelete(service = SERVICE) {
3579
+ if (!nativeKeychainAllowed()) return false;
3370
3580
  if (process.platform !== "linux") return false;
3371
3581
  try {
3372
3582
  execSync2(
3373
- `echo -n "${value}" | secret-tool store --label="exe-os master key" service "${SERVICE}" account "${ACCOUNT}"`,
3583
+ `secret-tool clear service "${service}" account "${ACCOUNT}" 2>/dev/null`,
3374
3584
  { timeout: 5e3 }
3375
3585
  );
3376
3586
  return true;
@@ -3379,6 +3589,7 @@ function linuxSecretSet(value) {
3379
3589
  }
3380
3590
  }
3381
3591
  async function tryKeytar() {
3592
+ if (!nativeKeychainAllowed()) return null;
3382
3593
  try {
3383
3594
  return await import("keytar");
3384
3595
  } catch {
@@ -3452,7 +3663,19 @@ async function writeMachineBoundFileFallback(b64) {
3452
3663
  return "plaintext";
3453
3664
  }
3454
3665
  async function getMasterKey() {
3455
- const nativeValue = macKeychainGet() ?? linuxSecretGet();
3666
+ let nativeValue = macKeychainGet() ?? linuxSecretGet();
3667
+ if (!nativeValue) {
3668
+ const legacyValue = macKeychainGet(LEGACY_SERVICE) ?? linuxSecretGet(LEGACY_SERVICE);
3669
+ if (legacyValue) {
3670
+ const migrated = macKeychainSet(legacyValue) || linuxSecretSet(legacyValue);
3671
+ if (migrated) {
3672
+ macKeychainDelete(LEGACY_SERVICE);
3673
+ linuxSecretDelete(LEGACY_SERVICE);
3674
+ process.stderr.write("[keychain] Migrated keychain service from exe-mem to exe-os.\n");
3675
+ }
3676
+ nativeValue = legacyValue;
3677
+ }
3678
+ }
3456
3679
  if (nativeValue) {
3457
3680
  return Buffer.from(nativeValue, "base64");
3458
3681
  }
@@ -3460,12 +3683,17 @@ async function getMasterKey() {
3460
3683
  if (keytar) {
3461
3684
  try {
3462
3685
  const keytarValue = await keytar.getPassword(SERVICE, ACCOUNT);
3463
- if (keytarValue) {
3464
- const migrated = macKeychainSet(keytarValue) || linuxSecretSet(keytarValue);
3686
+ const legacyKeytarValue = keytarValue ?? await keytar.getPassword(LEGACY_SERVICE, ACCOUNT);
3687
+ if (legacyKeytarValue) {
3688
+ const migrated = macKeychainSet(legacyKeytarValue) || linuxSecretSet(legacyKeytarValue);
3465
3689
  if (migrated) {
3466
3690
  process.stderr.write("[keychain] Migrated key from keytar to native keychain.\n");
3691
+ try {
3692
+ await keytar.deletePassword(LEGACY_SERVICE, ACCOUNT);
3693
+ } catch {
3694
+ }
3467
3695
  }
3468
- return Buffer.from(keytarValue, "base64");
3696
+ return Buffer.from(legacyKeytarValue, "base64");
3469
3697
  }
3470
3698
  } catch {
3471
3699
  }
@@ -3490,7 +3718,7 @@ async function getMasterKey() {
3490
3718
  const decrypted = decryptWithMachineKey(content, machineKey);
3491
3719
  if (!decrypted) {
3492
3720
  process.stderr.write(
3493
- "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase: exe-os link import\n"
3721
+ "[keychain] Key decryption failed \u2014 machine may have changed.\n Use your 24-word recovery phrase during setup: exe-os setup\n"
3494
3722
  );
3495
3723
  return null;
3496
3724
  }
@@ -3499,6 +3727,9 @@ async function getMasterKey() {
3499
3727
  b64Value = content;
3500
3728
  }
3501
3729
  const key = Buffer.from(b64Value, "base64");
3730
+ if (!content.startsWith(ENCRYPTED_PREFIX) && isRootOnlyTrustedServerKeyFile(keyPath)) {
3731
+ return key;
3732
+ }
3502
3733
  const migrated = macKeychainSet(b64Value) || linuxSecretSet(b64Value);
3503
3734
  if (migrated) {
3504
3735
  process.stderr.write("[keychain] Migrated key from file to native keychain.\n");
@@ -3526,12 +3757,14 @@ async function getMasterKey() {
3526
3757
  return null;
3527
3758
  }
3528
3759
  }
3529
- var SERVICE, ACCOUNT, ENCRYPTED_PREFIX;
3760
+ var SERVICE, LEGACY_SERVICE, ACCOUNT, linuxSecretAvailability, ENCRYPTED_PREFIX;
3530
3761
  var init_keychain = __esm({
3531
3762
  "src/lib/keychain.ts"() {
3532
3763
  "use strict";
3533
- SERVICE = "exe-mem";
3764
+ SERVICE = "exe-os";
3765
+ LEGACY_SERVICE = "exe-mem";
3534
3766
  ACCOUNT = "master-key";
3767
+ linuxSecretAvailability = null;
3535
3768
  ENCRYPTED_PREFIX = "enc:";
3536
3769
  }
3537
3770
  });
@@ -3801,7 +4034,7 @@ __export(shard_manager_exports, {
3801
4034
  shardExists: () => shardExists
3802
4035
  });
3803
4036
  import path8 from "path";
3804
- import { existsSync as existsSync8, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync2 } from "fs";
4037
+ import { existsSync as existsSync8, mkdirSync as mkdirSync2, readdirSync, renameSync as renameSync3, statSync as statSync3 } from "fs";
3805
4038
  import { createClient as createClient2 } from "@libsql/client";
3806
4039
  function initShardManager(encryptionKey) {
3807
4040
  _encryptionKey = encryptionKey;
@@ -3865,7 +4098,7 @@ async function auditShardHealth(options = {}) {
3865
4098
  const shards = [];
3866
4099
  for (const name of names) {
3867
4100
  const dbPath = path8.join(SHARDS_DIR, `${name}.db`);
3868
- const stat = statSync2(dbPath);
4101
+ const stat = statSync3(dbPath);
3869
4102
  const item = {
3870
4103
  name,
3871
4104
  path: dbPath,
@@ -4118,7 +4351,7 @@ async function getReadyShardClient(projectName) {
4118
4351
  _shardLastAccess.delete(safeName);
4119
4352
  const dbPath = path8.join(SHARDS_DIR, `${safeName}.db`);
4120
4353
  if (existsSync8(dbPath)) {
4121
- const stat = statSync2(dbPath);
4354
+ const stat = statSync3(dbPath);
4122
4355
  const stamp = (/* @__PURE__ */ new Date()).toISOString().replace(/[:.]/g, "-");
4123
4356
  const archivedPath = path8.join(SHARDS_DIR, `${safeName}.db.broken-${stamp}`);
4124
4357
  renameSync3(dbPath, archivedPath);
@@ -4238,6 +4471,12 @@ var init_platform_procedures = __esm({
4238
4471
  priority: "p0",
4239
4472
  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."
4240
4473
  },
4474
+ {
4475
+ title: "Customer orchestration maturity \u2014 recommend, never trap",
4476
+ domain: "workflow",
4477
+ priority: "p1",
4478
+ 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."
4479
+ },
4241
4480
  {
4242
4481
  title: "Single dispatch path \u2014 create_task only",
4243
4482
  domain: "workflow",
@@ -4296,6 +4535,12 @@ var init_platform_procedures = __esm({
4296
4535
  priority: "p0",
4297
4536
  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."
4298
4537
  },
4538
+ {
4539
+ title: "Commit discipline \u2014 never leave verified work floating",
4540
+ domain: "workflow",
4541
+ priority: "p1",
4542
+ 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."
4543
+ },
4299
4544
  {
4300
4545
  title: "Desktop and TUI are the same product",
4301
4546
  domain: "architecture",
@@ -4613,6 +4858,274 @@ var init_memory_cards = __esm({
4613
4858
  }
4614
4859
  });
4615
4860
 
4861
+ // src/lib/agentic-ontology.ts
4862
+ var agentic_ontology_exports = {};
4863
+ __export(agentic_ontology_exports, {
4864
+ clean: () => clean,
4865
+ extractGoalCandidates: () => extractGoalCandidates,
4866
+ inferIntention: () => inferIntention,
4867
+ inferOntologyEventType: () => inferOntologyEventType,
4868
+ inferOutcome: () => inferOutcome,
4869
+ inferSemanticLabel: () => inferSemanticLabel,
4870
+ insertOntologyForBatch: () => insertOntologyForBatch,
4871
+ insertOntologyForMemory: () => insertOntologyForMemory,
4872
+ ontologyPayload: () => ontologyPayload,
4873
+ stableId: () => stableId2
4874
+ });
4875
+ import { createHash as createHash3 } from "crypto";
4876
+ function stableId2(...parts) {
4877
+ return createHash3("sha256").update(parts.map((p) => String(p ?? "")).join("::")).digest("hex").slice(0, 32);
4878
+ }
4879
+ function clean(text, max = 240) {
4880
+ return text.replace(/\u0000/g, "").replace(/```[\s\S]*?```/g, " ").replace(/\s+/g, " ").trim().slice(0, max);
4881
+ }
4882
+ function inferOntologyEventType(row) {
4883
+ const lower = row.raw_text.toLowerCase();
4884
+ if (row.has_error) return "error";
4885
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published)\b/.test(lower)) return "milestone";
4886
+ if (/\b(blocked|failed|error|bug|regression|broken)\b/.test(lower)) return "problem";
4887
+ if (/\b(decided|decision|adr|we chose|approved|rejected)\b/.test(lower)) return "decision";
4888
+ if (/\b(goal|need to|we need|want to|trying to|objective)\b/.test(lower)) return "goal_signal";
4889
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) return "tool_action";
4890
+ if (row.tool_name.startsWith("memory_card")) return "memory_card";
4891
+ return "memory_observation";
4892
+ }
4893
+ function inferIntention(row) {
4894
+ if (row.intent) return clean(row.intent, 220);
4895
+ const text = clean(row.raw_text, 1e3);
4896
+ const patterns = [
4897
+ /(?: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,
4898
+ /(?:so that|in order to)\s+([^.!?\n]{8,220})/i,
4899
+ /(?:task|plan):\s*([^.!?\n]{8,220})/i
4900
+ ];
4901
+ for (const p of patterns) {
4902
+ const m = text.match(p);
4903
+ if (m?.[1]) return clean(m[1], 220);
4904
+ }
4905
+ if (["Bash", "Read", "Edit", "Write", "Grep", "Glob"].includes(row.tool_name)) {
4906
+ return `${row.tool_name} during ${row.project_name}`;
4907
+ }
4908
+ return null;
4909
+ }
4910
+ function inferOutcome(row) {
4911
+ if (row.outcome) return clean(row.outcome, 220);
4912
+ if (row.has_error) return "error";
4913
+ const lower = row.raw_text.toLowerCase();
4914
+ if (/\b(done|complete|completed|fixed|resolved|shipped|deployed|pushed|published|passed)\b/.test(lower)) return "success_signal";
4915
+ if (/\b(blocked|failed|error|regression|broken|not working|could not)\b/.test(lower)) return "failure_signal";
4916
+ if (/\b(warning|risk|concern|caveat)\b/.test(lower)) return "risk_signal";
4917
+ return null;
4918
+ }
4919
+ function extractGoalCandidates(row) {
4920
+ const text = clean(row.raw_text, 1600);
4921
+ const patterns = [
4922
+ /(?: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,
4923
+ /(?:success means|success criteria|so that)\s+([^.!?\n]{12,220})/gi
4924
+ ];
4925
+ const out = [];
4926
+ for (const pattern of patterns) {
4927
+ for (const m of text.matchAll(pattern)) {
4928
+ const candidate = clean(m[1] ?? "", 220);
4929
+ if (candidate.length >= 12 && !out.some((x) => x.toLowerCase() === candidate.toLowerCase())) out.push(candidate);
4930
+ if (out.length >= 3) return out;
4931
+ }
4932
+ }
4933
+ return out;
4934
+ }
4935
+ function uniq(values, max = 6) {
4936
+ const out = [];
4937
+ for (const value of values.map((v) => clean(v, 220)).filter(Boolean)) {
4938
+ if (!out.some((x) => x.toLowerCase() === value.toLowerCase())) out.push(value);
4939
+ if (out.length >= max) break;
4940
+ }
4941
+ return out;
4942
+ }
4943
+ function extractMatches(text, patterns, max = 5) {
4944
+ const out = [];
4945
+ for (const pattern of patterns) {
4946
+ for (const match of text.matchAll(pattern)) {
4947
+ const value = match[1] ?? match[0];
4948
+ if (value) out.push(value);
4949
+ if (out.length >= max) return uniq(out, max);
4950
+ }
4951
+ }
4952
+ return uniq(out, max);
4953
+ }
4954
+ function inferSemanticLabel(row) {
4955
+ const text = clean(row.raw_text, 2400);
4956
+ const eventType = inferOntologyEventType(row);
4957
+ const intention = inferIntention(row);
4958
+ const outcome = inferOutcome(row);
4959
+ const goals = extractGoalCandidates(row);
4960
+ const milestones = extractMatches(text, [
4961
+ /\b(?:completed|finished|fixed|resolved|shipped|deployed|published|pushed|passed)\b([^.!?\n]{0,180})/gi,
4962
+ /(?:milestone|done):\s*([^.!?\n]{8,220})/gi
4963
+ ]);
4964
+ const problems = extractMatches(text, [
4965
+ /\b(?:blocked by|failed because|bug|regression|broken|not working|error)\b([^.!?\n]{0,180})/gi,
4966
+ /(?:problem|issue|risk):\s*([^.!?\n]{8,220})/gi
4967
+ ]);
4968
+ const decisions = extractMatches(text, [
4969
+ /(?:decided|decision|adr|we chose|approved|rejected)\s+([^.!?\n]{8,220})/gi
4970
+ ]);
4971
+ const temporalAnchors = extractMatches(text, [
4972
+ /\b(\d{4}-\d{2}-\d{2}(?:[T ][0-9:.+-Z]+)?)\b/g,
4973
+ /\b(today|yesterday|tomorrow|this week|next week|last week|morning|afternoon|tonight)\b/gi
4974
+ ], 8);
4975
+ const nextActions = extractMatches(text, [
4976
+ /(?:next|todo|follow[- ]?up|remaining|need to)\s*:?\s*([^.!?\n]{8,220})/gi
4977
+ ]);
4978
+ const actors = uniq([
4979
+ row.agent_id,
4980
+ ...extractMatches(text, [/\b(?:agent|employee|owner|assignee)[:= ]+([a-zA-Z][a-zA-Z0-9_-]{1,40})/gi], 5)
4981
+ ], 6);
4982
+ const successSignals = milestones.length ? milestones : outcome === "success_signal" ? [clean(text, 180)] : [];
4983
+ const failureSignals = problems.length ? problems : outcome === "failure_signal" || row.has_error ? [clean(text, 180)] : [];
4984
+ const impact = successSignals.length && failureSignals.length ? "mixed" : failureSignals.length ? "negative" : successSignals.length ? "positive" : "neutral";
4985
+ const signalCount = goals.length + milestones.length + problems.length + decisions.length + nextActions.length;
4986
+ return {
4987
+ labeler: "deterministic",
4988
+ schemaVersion: 1,
4989
+ eventType,
4990
+ intention,
4991
+ outcome,
4992
+ impact,
4993
+ confidence: Math.min(0.95, 0.45 + signalCount * 0.08 + (intention ? 0.1 : 0) + (outcome ? 0.1 : 0)),
4994
+ goals,
4995
+ milestones,
4996
+ problems,
4997
+ decisions,
4998
+ actors,
4999
+ temporalAnchors,
5000
+ successSignals,
5001
+ failureSignals,
5002
+ nextActions,
5003
+ summary: clean(text, 280)
5004
+ };
5005
+ }
5006
+ function ontologyPayload(row) {
5007
+ const semantic = inferSemanticLabel(row);
5008
+ return {
5009
+ tool_name: row.tool_name,
5010
+ memory_version: row.version ?? null,
5011
+ domain: row.domain ?? null,
5012
+ trajectory: row.trajectory ? safeJson(row.trajectory) : null,
5013
+ semantic
5014
+ };
5015
+ }
5016
+ function safeJson(value) {
5017
+ try {
5018
+ return JSON.parse(value);
5019
+ } catch {
5020
+ return value.slice(0, 1e3);
5021
+ }
5022
+ }
5023
+ async function resolveClient(client) {
5024
+ if (client) return client;
5025
+ const { getClient: getClient2 } = await Promise.resolve().then(() => (init_database(), database_exports));
5026
+ return getClient2();
5027
+ }
5028
+ async function insertOntologyForMemory(row, client) {
5029
+ const db = await resolveClient(client);
5030
+ const occurredAt = row.timestamp;
5031
+ const sequence = Number(row.version ?? 0) || Math.floor(new Date(occurredAt).getTime() / 1e3);
5032
+ const eventType = inferOntologyEventType(row);
5033
+ const intention = inferIntention(row);
5034
+ const outcome = inferOutcome(row);
5035
+ const eventId = stableId2("event", row.id);
5036
+ const now = (/* @__PURE__ */ new Date()).toISOString();
5037
+ await db.execute({
5038
+ sql: `INSERT INTO agent_sessions (id, agent_id, project_name, started_at, last_event_at, event_count, properties)
5039
+ VALUES (?, ?, ?, ?, ?, 1, ?)
5040
+ ON CONFLICT(id) DO UPDATE SET last_event_at = MAX(last_event_at, excluded.last_event_at),
5041
+ event_count = event_count + 1`,
5042
+ args: [row.session_id, row.agent_id, row.project_name, occurredAt, occurredAt, JSON.stringify({ agent_role: row.agent_role })]
5043
+ });
5044
+ await db.execute({
5045
+ sql: `INSERT OR IGNORE INTO agent_events
5046
+ (id, event_type, occurred_at, sequence_index, actor_agent_id, agent_role, project_name,
5047
+ session_id, task_id, goal_id, parent_event_id, intention, outcome, evidence_memory_id,
5048
+ impact, payload, created_at)
5049
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, NULL, NULL, ?, ?, ?, ?, ?, ?)`,
5050
+ args: [
5051
+ eventId,
5052
+ eventType,
5053
+ occurredAt,
5054
+ sequence,
5055
+ row.agent_id,
5056
+ row.agent_role,
5057
+ row.project_name,
5058
+ row.session_id,
5059
+ row.task_id ?? null,
5060
+ intention,
5061
+ outcome,
5062
+ row.id,
5063
+ row.has_error ? "negative" : outcome === "success_signal" ? "positive" : "neutral",
5064
+ JSON.stringify(ontologyPayload(row)),
5065
+ now
5066
+ ]
5067
+ });
5068
+ const semantic = inferSemanticLabel(row);
5069
+ await db.execute({
5070
+ sql: `INSERT INTO agent_semantic_labels
5071
+ (id, source_memory_id, event_id, labeler, schema_version, confidence, labels, created_at, updated_at)
5072
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?)
5073
+ ON CONFLICT(id) DO UPDATE SET confidence = excluded.confidence,
5074
+ labels = excluded.labels, updated_at = excluded.updated_at`,
5075
+ args: [
5076
+ stableId2("semantic", row.id, semantic.labeler, semantic.schemaVersion),
5077
+ row.id,
5078
+ eventId,
5079
+ semantic.labeler,
5080
+ semantic.schemaVersion,
5081
+ semantic.confidence,
5082
+ JSON.stringify(semantic),
5083
+ now,
5084
+ now
5085
+ ]
5086
+ });
5087
+ for (const statement of extractGoalCandidates(row)) {
5088
+ const goalId = stableId2("goal", row.project_name, statement.toLowerCase());
5089
+ await db.execute({
5090
+ sql: `INSERT INTO agent_goals
5091
+ (id, statement, owner_agent_id, project_name, status, priority, success_criteria,
5092
+ parent_goal_id, due_at, achieved_at, supersedes_id, created_at, updated_at, source_memory_id)
5093
+ VALUES (?, ?, ?, ?, 'open', 5, NULL, NULL, NULL, NULL, NULL, ?, ?, ?)
5094
+ ON CONFLICT(id) DO UPDATE SET updated_at = excluded.updated_at`,
5095
+ args: [goalId, statement, row.agent_id, row.project_name, now, now, row.id]
5096
+ });
5097
+ await db.execute({
5098
+ sql: `INSERT OR IGNORE INTO agent_goal_links
5099
+ (id, goal_id, link_type, target_id, target_type, created_at)
5100
+ VALUES (?, ?, 'evidence', ?, 'memory', ?)`,
5101
+ args: [stableId2("goal_link", goalId, row.id, "memory"), goalId, row.id, now]
5102
+ });
5103
+ await db.execute({
5104
+ sql: `INSERT OR IGNORE INTO agent_goal_links
5105
+ (id, goal_id, link_type, target_id, target_type, created_at)
5106
+ VALUES (?, ?, 'event', ?, 'event', ?)`,
5107
+ args: [stableId2("goal_link", goalId, eventId, "event"), goalId, eventId, now]
5108
+ });
5109
+ }
5110
+ }
5111
+ async function insertOntologyForBatch(rows, client) {
5112
+ const db = await resolveClient(client);
5113
+ let count = 0;
5114
+ for (const row of rows) {
5115
+ try {
5116
+ await insertOntologyForMemory(row, db);
5117
+ count++;
5118
+ } catch {
5119
+ }
5120
+ }
5121
+ return count;
5122
+ }
5123
+ var init_agentic_ontology = __esm({
5124
+ "src/lib/agentic-ontology.ts"() {
5125
+ "use strict";
5126
+ }
5127
+ });
5128
+
4616
5129
  // src/lib/store.ts
4617
5130
  var store_exports = {};
4618
5131
  __export(store_exports, {
@@ -4956,6 +5469,11 @@ async function flushBatch() {
4956
5469
  await insertMemoryCardsForBatch2(batch);
4957
5470
  } catch {
4958
5471
  }
5472
+ try {
5473
+ const { insertOntologyForBatch: insertOntologyForBatch2 } = await Promise.resolve().then(() => (init_agentic_ontology(), agentic_ontology_exports));
5474
+ await insertOntologyForBatch2(batch);
5475
+ } catch {
5476
+ }
4959
5477
  schedulePostWriteMemoryHygiene(batch.map((row) => row.id));
4960
5478
  _pendingRecords.splice(0, batch.length);
4961
5479
  try {
@@ -8892,54 +9410,98 @@ async function fastDbInit() {
8892
9410
  // src/adapters/claude/hooks/bug-report-worker.ts
8893
9411
  init_database();
8894
9412
  init_tasks();
8895
- async function main() {
8896
- const toolName = process.env.BUG_TOOL_NAME ?? "unknown";
8897
- const errorText = process.env.BUG_ERROR_TEXT ?? "";
8898
- const toolInput = process.env.BUG_TOOL_INPUT ?? "{}";
8899
- const fingerprint = process.env.BUG_FINGERPRINT ?? "";
8900
- const agentId = process.env.BUG_AGENT_ID ?? "unknown";
8901
- const agentRole = process.env.BUG_AGENT_ROLE ?? "employee";
8902
- const projectName = process.env.BUG_PROJECT_NAME ?? "unknown";
8903
- await fastDbInit();
8904
- const fpPrefix = fingerprint.slice(0, 8);
8905
- const client = getClient();
8906
- const { loadEmployeesSync: loadEmployeesSync2, getEmployeeByRole: getEmployeeByRole2, getCoordinatorName: getCoordinatorName2 } = await Promise.resolve().then(() => (init_employees(), employees_exports));
8907
- const employees = loadEmployeesSync2();
8908
- const coordinatorName = getCoordinatorName2(employees);
8909
- const ctoName = getEmployeeByRole2(employees, "CTO")?.name ?? coordinatorName;
8910
- const existing = await client.execute({
8911
- sql: `SELECT id FROM tasks
8912
- WHERE assigned_to = ?
8913
- AND status IN ('open', 'in_progress')
8914
- AND title LIKE '[auto-bug]%'
8915
- AND task_file LIKE ?
8916
- LIMIT 1`,
8917
- args: [ctoName, `%${fpPrefix}%`]
9413
+
9414
+ // src/lib/bug-intake.ts
9415
+ import { createHash as createHash4, randomUUID as randomUUID4 } from "crypto";
9416
+ var BUG_INTAKE_SCHEMA_VERSION = 1;
9417
+ function firstMeaningfulLine(text) {
9418
+ return text.split("\n").find((line) => line.trim().length > 0)?.trim().slice(0, 80) ?? "unknown error";
9419
+ }
9420
+ function stableFingerprint(input) {
9421
+ const basis = [
9422
+ input.source,
9423
+ input.toolName ?? "unknown",
9424
+ firstMeaningfulLine(input.errorText ?? ""),
9425
+ input.projectName ?? "unknown"
9426
+ ].join("|");
9427
+ return createHash4("sha256").update(basis).digest("hex").slice(0, 16);
9428
+ }
9429
+ function hashLicense(licenseKey) {
9430
+ if (!licenseKey) return void 0;
9431
+ return createHash4("sha256").update(licenseKey).digest("hex").slice(0, 16);
9432
+ }
9433
+ function buildBugIntake(input) {
9434
+ const toolName = input.toolName ?? "unknown";
9435
+ const errorText = input.errorText ?? "";
9436
+ const summary = firstMeaningfulLine(errorText);
9437
+ const fingerprint = input.fingerprint && input.fingerprint.trim().length > 0 ? input.fingerprint.trim() : stableFingerprint(input);
9438
+ return {
9439
+ schemaVersion: BUG_INTAKE_SCHEMA_VERSION,
9440
+ id: randomUUID4(),
9441
+ source: input.source,
9442
+ createdAt: input.createdAt ?? (/* @__PURE__ */ new Date()).toISOString(),
9443
+ fingerprint,
9444
+ severity: input.severity ?? "p1",
9445
+ title: `[auto-bug] ${toolName}: ${summary.slice(0, 60)}`,
9446
+ summary,
9447
+ reporterAgentId: input.reporterAgentId ?? "unknown",
9448
+ reporterAgentRole: input.reporterAgentRole ?? "employee",
9449
+ projectName: input.projectName ?? "unknown",
9450
+ toolName,
9451
+ errorText,
9452
+ toolInput: input.toolInput ?? "{}",
9453
+ runtime: input.runtime,
9454
+ repo: input.repo,
9455
+ licenseKeyHash: hashLicense(input.licenseKey),
9456
+ labels: ["auto-bug", input.source, toolName].filter(Boolean)
9457
+ };
9458
+ }
9459
+ function buildBugIntakeFromEnv(env = process.env) {
9460
+ return buildBugIntake({
9461
+ source: "hook",
9462
+ toolName: env.BUG_TOOL_NAME,
9463
+ errorText: env.BUG_ERROR_TEXT,
9464
+ toolInput: env.BUG_TOOL_INPUT,
9465
+ fingerprint: env.BUG_FINGERPRINT,
9466
+ reporterAgentId: env.BUG_AGENT_ID,
9467
+ reporterAgentRole: env.BUG_AGENT_ROLE,
9468
+ projectName: env.BUG_PROJECT_NAME,
9469
+ runtime: env.EXE_RUNTIME,
9470
+ repo: env.EXE_REPO,
9471
+ licenseKey: env.EXE_LICENSE_KEY
8918
9472
  });
8919
- if (existing.rows.length > 0) {
8920
- process.stderr.write(`[bug-report-worker] Duplicate found for fingerprint ${fingerprint}, skipping
8921
- `);
8922
- return;
8923
- }
8924
- const errorSummary = errorText.split("\n").find((line) => line.trim().length > 0)?.trim().slice(0, 60) ?? "unknown error";
8925
- const context = [
9473
+ }
9474
+ function formatBugIntakeTaskContext(record) {
9475
+ return [
8926
9476
  "## Auto-detected system bug",
8927
9477
  "",
8928
- `**Detected by:** ${agentId} (${agentRole})`,
8929
- `**Tool:** ${toolName}`,
8930
- `**Timestamp:** ${(/* @__PURE__ */ new Date()).toISOString()}`,
8931
- `**Fingerprint:** ${fingerprint}`,
9478
+ `**Schema:** bug-intake/v${record.schemaVersion}`,
9479
+ `**Source:** ${record.source}`,
9480
+ `**Detected by:** ${record.reporterAgentId} (${record.reporterAgentRole})`,
9481
+ `**Tool:** ${record.toolName}`,
9482
+ `**Timestamp:** ${record.createdAt}`,
9483
+ `**Fingerprint:** ${record.fingerprint}`,
9484
+ `**Severity:** ${record.severity}`,
9485
+ record.runtime ? `**Runtime:** ${record.runtime}` : void 0,
9486
+ record.repo ? `**Repo:** ${record.repo}` : void 0,
9487
+ record.licenseKeyHash ? `**License hash:** ${record.licenseKeyHash}` : void 0,
8932
9488
  "",
8933
9489
  "## Error output",
8934
9490
  "",
8935
9491
  "```",
8936
- errorText.slice(0, 1e3),
9492
+ record.errorText.slice(0, 2e3),
8937
9493
  "```",
8938
9494
  "",
8939
9495
  "## Tool input (reproduction context)",
8940
9496
  "",
8941
9497
  "```json",
8942
- toolInput.slice(0, 500),
9498
+ record.toolInput.slice(0, 1e3),
9499
+ "```",
9500
+ "",
9501
+ "## Normalized intake JSON",
9502
+ "",
9503
+ "```json",
9504
+ JSON.stringify(record, null, 2),
8943
9505
  "```",
8944
9506
  "",
8945
9507
  "## Triage notes",
@@ -8947,19 +9509,44 @@ async function main() {
8947
9509
  "- Classification: system bug (auto-detected)",
8948
9510
  "- Review this error \u2014 fix if real, close if false positive",
8949
9511
  "- If false positive: add the error pattern to USER_ERROR_PATTERNS in error-detector.ts"
8950
- ].join("\n");
9512
+ ].filter((line) => line !== void 0).join("\n");
9513
+ }
9514
+
9515
+ // src/adapters/claude/hooks/bug-report-worker.ts
9516
+ async function main() {
9517
+ const intake = buildBugIntakeFromEnv(process.env);
9518
+ await fastDbInit();
9519
+ const client = getClient();
9520
+ const { loadEmployeesSync: loadEmployeesSync2, getEmployeeByRole: getEmployeeByRole2, getCoordinatorName: getCoordinatorName2 } = await Promise.resolve().then(() => (init_employees(), employees_exports));
9521
+ const employees = loadEmployeesSync2();
9522
+ const coordinatorName = getCoordinatorName2(employees);
9523
+ const ctoName = getEmployeeByRole2(employees, "CTO")?.name ?? coordinatorName;
9524
+ const existing = await client.execute({
9525
+ sql: `SELECT id FROM tasks
9526
+ WHERE assigned_to = ?
9527
+ AND status IN ('open', 'in_progress')
9528
+ AND title LIKE '[auto-bug]%'
9529
+ AND (context LIKE ? OR task_file LIKE ?)
9530
+ LIMIT 1`,
9531
+ args: [ctoName, `%${intake.fingerprint}%`, `%${intake.fingerprint.slice(0, 8)}%`]
9532
+ });
9533
+ if (existing.rows.length > 0) {
9534
+ process.stderr.write(`[bug-report-worker] Duplicate found for fingerprint ${intake.fingerprint}, skipping
9535
+ `);
9536
+ return;
9537
+ }
8951
9538
  await createTask({
8952
- title: `[auto-bug] ${toolName}: ${errorSummary}`,
9539
+ title: intake.title,
8953
9540
  assignedTo: ctoName,
8954
9541
  assignedBy: "system",
8955
- projectName,
8956
- priority: "p1",
8957
- context,
9542
+ projectName: intake.projectName,
9543
+ priority: intake.severity,
9544
+ context: formatBugIntakeTaskContext(intake),
8958
9545
  baseDir: process.cwd(),
8959
9546
  skipDispatch: true,
8960
9547
  reviewer: coordinatorName
8961
9548
  });
8962
- process.stderr.write(`[bug-report-worker] Created auto-bug task for ${toolName}: ${errorSummary}
9549
+ process.stderr.write(`[bug-report-worker] Created auto-bug task for ${intake.toolName}: ${intake.summary}
8963
9550
  `);
8964
9551
  }
8965
9552
  main().catch((err) => {