dual-brain 0.2.30 → 0.3.1

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 (312) hide show
  1. package/.dual-brain/docs/claude-code-extension-points.md +32 -0
  2. package/.dual-brain/docs/data-tools-capabilities.md +181 -0
  3. package/.dual-brain/docs/ecosystem-tools.md +91 -0
  4. package/.dual-brain/docs/panel-handoff.md +124 -0
  5. package/.dual-brain/docs/ruflo-analysis.md +48 -0
  6. package/bin/dual-brain.mjs +56 -56
  7. package/dist/mcp-server/index.d.ts +27 -0
  8. package/dist/mcp-server/index.js +359 -0
  9. package/dist/mcp-server/index.js.map +1 -0
  10. package/dist/src/agent-protocol.d.ts +163 -0
  11. package/dist/src/agent-protocol.js +368 -0
  12. package/dist/src/agent-protocol.js.map +1 -0
  13. package/dist/src/agents/registry.d.ts +52 -0
  14. package/dist/src/agents/registry.js +393 -0
  15. package/dist/src/agents/registry.js.map +1 -0
  16. package/dist/src/awareness.d.ts +93 -0
  17. package/dist/src/awareness.js +406 -0
  18. package/dist/src/awareness.js.map +1 -0
  19. package/dist/src/brief.d.ts +48 -0
  20. package/dist/src/brief.js +179 -0
  21. package/dist/src/brief.js.map +1 -0
  22. package/dist/src/calibration.d.ts +32 -0
  23. package/dist/src/calibration.js +133 -0
  24. package/dist/src/calibration.js.map +1 -0
  25. package/dist/src/checkpoint.d.ts +33 -0
  26. package/dist/src/checkpoint.js +99 -0
  27. package/dist/src/checkpoint.js.map +1 -0
  28. package/dist/src/ci-triage.d.ts +33 -0
  29. package/dist/src/ci-triage.js +193 -0
  30. package/dist/src/ci-triage.js.map +1 -0
  31. package/dist/src/cognitive-loop.d.ts +56 -0
  32. package/dist/src/cognitive-loop.js +495 -0
  33. package/dist/src/cognitive-loop.js.map +1 -0
  34. package/dist/src/collaboration.d.ts +147 -0
  35. package/dist/src/collaboration.js +438 -0
  36. package/dist/src/collaboration.js.map +1 -0
  37. package/dist/src/context-intel.d.ts +47 -0
  38. package/dist/src/context-intel.js +156 -0
  39. package/dist/src/context-intel.js.map +1 -0
  40. package/dist/src/context.d.ts +53 -0
  41. package/dist/src/context.js +332 -0
  42. package/dist/src/context.js.map +1 -0
  43. package/dist/src/continuity.d.ts +89 -0
  44. package/dist/src/continuity.js +230 -0
  45. package/dist/src/continuity.js.map +1 -0
  46. package/dist/src/cost-tracker.d.ts +47 -0
  47. package/dist/src/cost-tracker.js +170 -0
  48. package/dist/src/cost-tracker.js.map +1 -0
  49. package/dist/src/debrief.d.ts +53 -0
  50. package/dist/src/debrief.js +222 -0
  51. package/dist/src/debrief.js.map +1 -0
  52. package/dist/src/decide.d.ts +96 -0
  53. package/dist/src/decide.js +744 -0
  54. package/dist/src/decide.js.map +1 -0
  55. package/dist/src/decompose.d.ts +39 -0
  56. package/dist/src/decompose.js +218 -0
  57. package/dist/src/decompose.js.map +1 -0
  58. package/dist/src/detect.d.ts +91 -0
  59. package/dist/src/detect.js +544 -0
  60. package/dist/src/detect.js.map +1 -0
  61. package/dist/src/dispatch.d.ts +154 -0
  62. package/dist/src/dispatch.js +1306 -0
  63. package/dist/src/dispatch.js.map +1 -0
  64. package/dist/src/doctor.d.ts +421 -0
  65. package/dist/src/doctor.js +1689 -0
  66. package/dist/src/doctor.js.map +1 -0
  67. package/dist/src/engine.d.ts +70 -0
  68. package/dist/src/engine.js +155 -0
  69. package/dist/src/engine.js.map +1 -0
  70. package/dist/src/envelope.d.ts +36 -0
  71. package/dist/src/envelope.js +80 -0
  72. package/dist/src/envelope.js.map +1 -0
  73. package/dist/src/failure-memory.d.ts +55 -0
  74. package/dist/src/failure-memory.js +175 -0
  75. package/dist/src/failure-memory.js.map +1 -0
  76. package/dist/src/fx.d.ts +87 -0
  77. package/dist/src/fx.js +272 -0
  78. package/dist/src/fx.js.map +1 -0
  79. package/dist/src/governance.d.ts +93 -0
  80. package/dist/src/governance.js +261 -0
  81. package/dist/src/governance.js.map +1 -0
  82. package/dist/src/handoff.d.ts +11 -0
  83. package/dist/src/handoff.js +90 -0
  84. package/dist/src/handoff.js.map +1 -0
  85. package/dist/src/head-protocol.d.ts +76 -0
  86. package/dist/src/head-protocol.js +109 -0
  87. package/dist/src/head-protocol.js.map +1 -0
  88. package/dist/src/head.d.ts +222 -0
  89. package/dist/src/head.js +765 -0
  90. package/dist/src/head.js.map +1 -0
  91. package/dist/src/health.d.ts +132 -0
  92. package/dist/src/health.js +435 -0
  93. package/dist/src/health.js.map +1 -0
  94. package/dist/src/inbox.d.ts +70 -0
  95. package/dist/src/inbox.js +218 -0
  96. package/dist/src/inbox.js.map +1 -0
  97. package/dist/src/index.d.ts +33 -0
  98. package/dist/src/index.js +38 -0
  99. package/dist/src/index.js.map +1 -0
  100. package/dist/src/install-hooks.d.ts +13 -0
  101. package/dist/src/install-hooks.js +88 -0
  102. package/dist/src/install-hooks.js.map +1 -0
  103. package/dist/src/integrity.d.ts +59 -0
  104. package/dist/src/integrity.js +206 -0
  105. package/dist/src/integrity.js.map +1 -0
  106. package/dist/src/intelligence.d.ts +104 -0
  107. package/dist/src/intelligence.js +391 -0
  108. package/dist/src/intelligence.js.map +1 -0
  109. package/dist/src/ledger.d.ts +54 -0
  110. package/dist/src/ledger.js +179 -0
  111. package/dist/src/ledger.js.map +1 -0
  112. package/dist/src/living-docs.d.ts +14 -0
  113. package/dist/src/living-docs.js +197 -0
  114. package/dist/src/living-docs.js.map +1 -0
  115. package/dist/src/memory-tiers.d.ts +37 -0
  116. package/dist/src/memory-tiers.js +160 -0
  117. package/dist/src/memory-tiers.js.map +1 -0
  118. package/dist/src/model-profiles.d.ts +65 -0
  119. package/dist/src/model-profiles.js +568 -0
  120. package/dist/src/model-profiles.js.map +1 -0
  121. package/dist/src/models.d.ts +58 -0
  122. package/dist/src/models.js +327 -0
  123. package/dist/src/models.js.map +1 -0
  124. package/dist/src/narrative.d.ts +54 -0
  125. package/dist/src/narrative.js +163 -0
  126. package/dist/src/narrative.js.map +1 -0
  127. package/dist/src/nextstep.d.ts +16 -0
  128. package/dist/src/nextstep.js +103 -0
  129. package/dist/src/nextstep.js.map +1 -0
  130. package/dist/src/observer.d.ts +18 -0
  131. package/dist/src/observer.js +251 -0
  132. package/dist/src/observer.js.map +1 -0
  133. package/dist/src/outcome.d.ts +110 -0
  134. package/dist/src/outcome.js +377 -0
  135. package/dist/src/outcome.js.map +1 -0
  136. package/dist/src/pipeline.d.ts +167 -0
  137. package/dist/src/pipeline.js +1503 -0
  138. package/dist/src/pipeline.js.map +1 -0
  139. package/dist/src/playbook.d.ts +59 -0
  140. package/dist/src/playbook.js +238 -0
  141. package/dist/src/playbook.js.map +1 -0
  142. package/dist/src/pr-agent.d.ts +97 -0
  143. package/dist/src/pr-agent.js +195 -0
  144. package/dist/src/pr-agent.js.map +1 -0
  145. package/dist/src/predictive.d.ts +57 -0
  146. package/dist/src/predictive.js +230 -0
  147. package/dist/src/predictive.js.map +1 -0
  148. package/dist/src/profile.d.ts +294 -0
  149. package/dist/src/profile.js +1347 -0
  150. package/dist/src/profile.js.map +1 -0
  151. package/dist/src/prompt-audit.d.ts +22 -0
  152. package/dist/src/prompt-audit.js +194 -0
  153. package/dist/src/prompt-audit.js.map +1 -0
  154. package/dist/src/prompt-intel.d.ts +12 -0
  155. package/dist/src/prompt-intel.js +321 -0
  156. package/dist/src/prompt-intel.js.map +1 -0
  157. package/dist/src/provider-context.d.ts +121 -0
  158. package/dist/src/provider-context.js +222 -0
  159. package/dist/src/provider-context.js.map +1 -0
  160. package/dist/src/provider-manager.d.ts +92 -0
  161. package/dist/src/provider-manager.js +428 -0
  162. package/dist/src/provider-manager.js.map +1 -0
  163. package/dist/src/receipt.d.ts +87 -0
  164. package/dist/src/receipt.js +326 -0
  165. package/dist/src/receipt.js.map +1 -0
  166. package/dist/src/recommendations.d.ts +13 -0
  167. package/dist/src/recommendations.js +291 -0
  168. package/dist/src/recommendations.js.map +1 -0
  169. package/dist/src/redact.d.ts +15 -0
  170. package/dist/src/redact.js +129 -0
  171. package/dist/src/redact.js.map +1 -0
  172. package/dist/src/replit.d.ts +397 -0
  173. package/dist/src/replit.js +1160 -0
  174. package/dist/src/replit.js.map +1 -0
  175. package/dist/src/repo.d.ts +149 -0
  176. package/dist/src/repo.js +416 -0
  177. package/dist/src/repo.js.map +1 -0
  178. package/dist/src/revert.d.ts +30 -0
  179. package/dist/src/revert.js +166 -0
  180. package/dist/src/revert.js.map +1 -0
  181. package/dist/src/room.d.ts +102 -0
  182. package/dist/src/room.js +212 -0
  183. package/dist/src/room.js.map +1 -0
  184. package/dist/src/routing-advisor.d.ts +57 -0
  185. package/dist/src/routing-advisor.js +221 -0
  186. package/dist/src/routing-advisor.js.map +1 -0
  187. package/dist/src/self-correct.d.ts +40 -0
  188. package/dist/src/self-correct.js +137 -0
  189. package/dist/src/self-correct.js.map +1 -0
  190. package/dist/src/session-lock.d.ts +35 -0
  191. package/dist/src/session-lock.js +134 -0
  192. package/dist/src/session-lock.js.map +1 -0
  193. package/dist/src/session.d.ts +267 -0
  194. package/dist/src/session.js +1660 -0
  195. package/dist/src/session.js.map +1 -0
  196. package/dist/src/settings-tui.d.ts +5 -0
  197. package/dist/src/settings-tui.js +422 -0
  198. package/dist/src/settings-tui.js.map +1 -0
  199. package/dist/src/setup-flow.d.ts +63 -0
  200. package/dist/src/setup-flow.js +233 -0
  201. package/dist/src/setup-flow.js.map +1 -0
  202. package/dist/src/signal.d.ts +19 -0
  203. package/dist/src/signal.js +122 -0
  204. package/dist/src/signal.js.map +1 -0
  205. package/dist/src/simmer.d.ts +85 -0
  206. package/dist/src/simmer.js +224 -0
  207. package/dist/src/simmer.js.map +1 -0
  208. package/dist/src/state-export.d.ts +129 -0
  209. package/dist/src/state-export.js +233 -0
  210. package/dist/src/state-export.js.map +1 -0
  211. package/dist/src/strategy.d.ts +54 -0
  212. package/dist/src/strategy.js +95 -0
  213. package/dist/src/strategy.js.map +1 -0
  214. package/dist/src/subscription.d.ts +40 -0
  215. package/dist/src/subscription.js +189 -0
  216. package/dist/src/subscription.js.map +1 -0
  217. package/dist/src/templates.d.ts +208 -0
  218. package/dist/src/templates.js +238 -0
  219. package/dist/src/templates.js.map +1 -0
  220. package/dist/src/test.d.ts +9 -0
  221. package/dist/src/test.js +1173 -0
  222. package/dist/src/test.js.map +1 -0
  223. package/dist/src/think-engine.d.ts +67 -0
  224. package/dist/src/think-engine.js +412 -0
  225. package/dist/src/think-engine.js.map +1 -0
  226. package/dist/src/tui.d.ts +71 -0
  227. package/dist/src/tui.js +242 -0
  228. package/dist/src/tui.js.map +1 -0
  229. package/dist/src/types.d.ts +177 -0
  230. package/dist/src/types.js +6 -0
  231. package/dist/src/types.js.map +1 -0
  232. package/dist/src/update-check.d.ts +7 -0
  233. package/dist/src/update-check.js +36 -0
  234. package/dist/src/update-check.js.map +1 -0
  235. package/dist/src/wave-planner.d.ts +30 -0
  236. package/dist/src/wave-planner.js +281 -0
  237. package/dist/src/wave-planner.js.map +1 -0
  238. package/hooks/head-guard.sh +41 -0
  239. package/hooks/precompact.mjs +3 -3
  240. package/hooks/session-end.mjs +3 -3
  241. package/hooks/task-classifier.mjs +328 -0
  242. package/hooks/vibe-router.mjs +387 -0
  243. package/install.mjs +2 -2
  244. package/package.json +29 -153
  245. package/src/agents/registry.mjs +0 -405
  246. package/src/awareness.mjs +0 -425
  247. package/src/brief.mjs +0 -266
  248. package/src/calibration.mjs +0 -148
  249. package/src/checkpoint.mjs +0 -109
  250. package/src/ci-triage.mjs +0 -191
  251. package/src/cognitive-loop.mjs +0 -562
  252. package/src/collaboration.mjs +0 -545
  253. package/src/context-intel.mjs +0 -158
  254. package/src/context.mjs +0 -389
  255. package/src/continuity.mjs +0 -298
  256. package/src/cost-tracker.mjs +0 -184
  257. package/src/debrief.mjs +0 -228
  258. package/src/decide.mjs +0 -1099
  259. package/src/decompose.mjs +0 -331
  260. package/src/detect.mjs +0 -702
  261. package/src/dispatch.mjs +0 -1447
  262. package/src/doctor.mjs +0 -1607
  263. package/src/envelope.mjs +0 -139
  264. package/src/failure-memory.mjs +0 -178
  265. package/src/fx.mjs +0 -276
  266. package/src/governance.mjs +0 -279
  267. package/src/handoff.mjs +0 -87
  268. package/src/head-protocol.mjs +0 -128
  269. package/src/head.mjs +0 -952
  270. package/src/health.mjs +0 -528
  271. package/src/inbox.mjs +0 -195
  272. package/src/index.mjs +0 -44
  273. package/src/install-hooks.mjs +0 -100
  274. package/src/integrity.mjs +0 -245
  275. package/src/intelligence.mjs +0 -447
  276. package/src/ledger.mjs +0 -196
  277. package/src/living-docs.mjs +0 -210
  278. package/src/memory-tiers.mjs +0 -193
  279. package/src/models.mjs +0 -363
  280. package/src/narrative.mjs +0 -169
  281. package/src/nextstep.mjs +0 -100
  282. package/src/observer.mjs +0 -241
  283. package/src/outcome.mjs +0 -400
  284. package/src/pipeline.mjs +0 -1711
  285. package/src/playbook.mjs +0 -257
  286. package/src/pr-agent.mjs +0 -214
  287. package/src/predictive.mjs +0 -250
  288. package/src/profile.mjs +0 -1411
  289. package/src/prompt-audit.mjs +0 -231
  290. package/src/prompt-intel.mjs +0 -325
  291. package/src/provider-context.mjs +0 -257
  292. package/src/receipt.mjs +0 -344
  293. package/src/recommendations.mjs +0 -296
  294. package/src/redact.mjs +0 -192
  295. package/src/replit.mjs +0 -1210
  296. package/src/repo.mjs +0 -445
  297. package/src/revert.mjs +0 -149
  298. package/src/routing-advisor.mjs +0 -204
  299. package/src/self-correct.mjs +0 -147
  300. package/src/session-lock.mjs +0 -160
  301. package/src/session.mjs +0 -1655
  302. package/src/settings-tui.mjs +0 -373
  303. package/src/setup-flow.mjs +0 -223
  304. package/src/signal.mjs +0 -115
  305. package/src/simmer.mjs +0 -241
  306. package/src/strategy.mjs +0 -235
  307. package/src/subscription.mjs +0 -212
  308. package/src/templates.mjs +0 -260
  309. package/src/think-engine.mjs +0 -428
  310. package/src/tui.mjs +0 -276
  311. package/src/update-check.mjs +0 -35
  312. package/src/wave-planner.mjs +0 -294
@@ -0,0 +1,1306 @@
1
+ #!/usr/bin/env node
2
+ // dispatch.ts — Dispatch/execution module for dual-brain.
3
+ // Takes a routing decision and launches the agent via Claude CLI or Codex CLI.
4
+ // CLI: node src/dispatch.ts --dry-run --provider claude --model sonnet --prompt "fix the bug"
5
+ // node src/dispatch.ts --detect-runtime
6
+ // Exports: dispatch, buildCommand, detectRuntime, compressResult, dispatchDualBrain,
7
+ // validateDispatch, checkWorktreeClean, getRetryBudget,
8
+ // isInsideClaude, buildNativeDispatch, normalizeResult
9
+ import { spawn } from 'node:child_process';
10
+ import { mkdirSync, appendFileSync, existsSync, readFileSync } from 'node:fs';
11
+ import { join, dirname } from 'node:path';
12
+ import { fileURLToPath } from 'node:url';
13
+ import { createHash } from 'node:crypto';
14
+ // @ts-ignore
15
+ import { markHot, markDegraded, markHealthy, recordDispatch } from './health.js';
16
+ // @ts-ignore
17
+ import { redact } from './redact.js';
18
+ import { getFailoverOrder } from './decide.js';
19
+ import { getTemplate, renderPrompt, quickRender } from './templates.js';
20
+ import { shapeForRole } from './context-intel.js';
21
+ // @ts-ignore
22
+ import { buildContextPack } from './context.js';
23
+ // @ts-ignore
24
+ import { scoreTask, computeRequiredTier } from './governance.js';
25
+ // ─── Constants ────────────────────────────────────────────────────────────────
26
+ const __dirname = dirname(fileURLToPath(import.meta.url));
27
+ const USAGE_DIR = join(__dirname, '..', '.dualbrain', 'usage');
28
+ const TIER_TIMEOUT_MS = { search: 60_000, execute: 120_000, think: 180_000 };
29
+ const CLAUDE_MODEL_IDS = { opus: 'claude-opus-4-6', sonnet: 'claude-sonnet-4-6', haiku: 'claude-haiku-4-5-20251001' };
30
+ // ─── Specialist prompt loader ─────────────────────────────────────────────────
31
+ const SPECIALISTS_DIR = join(__dirname, '..', 'agents', 'specialists');
32
+ /**
33
+ * Load specialist registry from agents/specialists/registry.json.
34
+ * Returns null if registry is missing or malformed.
35
+ */
36
+ function _loadSpecialistRegistry() {
37
+ try {
38
+ const raw = readFileSync(join(SPECIALISTS_DIR, 'registry.json'), 'utf8');
39
+ return JSON.parse(raw);
40
+ }
41
+ catch {
42
+ return null;
43
+ }
44
+ }
45
+ /**
46
+ * Read agents/specialists/_base.md and agents/specialists/{specialist}.md,
47
+ * concatenate them (base first, specialist second). Falls back gracefully:
48
+ * - If base is missing, only specialist content is returned.
49
+ * - If specialist file is missing, only base content is returned.
50
+ * - If both are missing, returns an empty string.
51
+ */
52
+ function loadSpecialistPrompt(specialist) {
53
+ if (!specialist || specialist === 'generic')
54
+ return '';
55
+ const tryRead = (filePath) => {
56
+ try {
57
+ return readFileSync(filePath, 'utf8').trim();
58
+ }
59
+ catch {
60
+ return '';
61
+ }
62
+ };
63
+ const registry = _loadSpecialistRegistry();
64
+ const entry = registry?.specialists?.[specialist];
65
+ const promptFile = entry?.prompt_file ?? `${specialist}.md`;
66
+ const base = tryRead(join(SPECIALISTS_DIR, '_base.md'));
67
+ const specific = tryRead(join(SPECIALISTS_DIR, promptFile));
68
+ const parts = [base, specific].filter(Boolean);
69
+ return parts.join('\n\n');
70
+ }
71
+ // ─── Median dispatch time tracker (in-process, for slow-response detection) ──
72
+ // Rolling window of recent dispatch durations keyed by "provider:modelClass"
73
+ const _durationHistory = new Map();
74
+ const DURATION_WINDOW = 10; // keep last N durations per model class
75
+ function recordDuration(provider, model, durationMs) {
76
+ const k = `${provider}:${model}`;
77
+ if (!_durationHistory.has(k))
78
+ _durationHistory.set(k, []);
79
+ const arr = _durationHistory.get(k);
80
+ arr.push(durationMs);
81
+ if (arr.length > DURATION_WINDOW)
82
+ arr.shift();
83
+ }
84
+ function medianDuration(provider, model) {
85
+ const k = `${provider}:${model}`;
86
+ const arr = _durationHistory.get(k);
87
+ if (!arr || arr.length < 3)
88
+ return null; // not enough data
89
+ const sorted = [...arr].sort((a, b) => a - b);
90
+ const mid = Math.floor(sorted.length / 2);
91
+ return sorted.length % 2 === 0
92
+ ? (sorted[mid - 1] + sorted[mid]) / 2
93
+ : sorted[mid];
94
+ }
95
+ // Rate-limit error keywords
96
+ const RATE_LIMIT_PATTERNS = /rate.?limit|quota|capacity|too many requests|overloaded|throttl/i;
97
+ // ─── Auto-heal failover helpers ───────────────────────────────────────────────
98
+ const FAILOVER_LOG_DIR = join(__dirname, '..', '.dualbrain', 'audit');
99
+ /** Retryable exit-code-1 patterns: rate limits, quota, capacity, timeouts */
100
+ const RETRYABLE_PATTERNS = /rate.?limit|429|quota.?exceeded|capacity|overloaded|timeout/i;
101
+ /** Non-retryable patterns: auth failures, bad input, user cancellation */
102
+ const NON_RETRYABLE_PATTERNS = /unauthorized|forbidden|invalid.?api.?key|authentication|bad.?request|cancelled|canceled/i;
103
+ /**
104
+ * Decide if a subprocess result is a retryable failure.
105
+ * Must be exit code 1 (or non-zero) AND match retryable keywords AND NOT match
106
+ * non-retryable keywords.
107
+ */
108
+ function isRetryableFailure({ exitCode, stderr, stdout }) {
109
+ if (exitCode === 0)
110
+ return false;
111
+ const errText = `${stderr} ${stdout}`.slice(0, 1000);
112
+ if (NON_RETRYABLE_PATTERNS.test(errText))
113
+ return false;
114
+ return RETRYABLE_PATTERNS.test(errText);
115
+ }
116
+ /**
117
+ * Append a failover event to .dualbrain/audit/failover.jsonl.
118
+ */
119
+ function logFailover({ from, to, reason, attempt }) {
120
+ try {
121
+ mkdirSync(FAILOVER_LOG_DIR, { recursive: true });
122
+ appendFileSync(join(FAILOVER_LOG_DIR, 'failover.jsonl'), JSON.stringify({ ts: new Date().toISOString(), from, to, reason, attempt }) + '\n');
123
+ }
124
+ catch { }
125
+ }
126
+ // ─── Native Claude Code detection ────────────────────────────────────────────
127
+ /**
128
+ * Detect whether we are running inside Claude Code (as a subagent or tool call).
129
+ * Checks the CLAUDE_CODE env var or the presence of .claude/settings.json in the project root.
130
+ */
131
+ function isInsideClaude() {
132
+ if (process.env.CLAUDE_CODE)
133
+ return true;
134
+ // Walk up from __dirname (src/) to find .claude/settings.json in project root
135
+ const projectRoot = join(__dirname, '..');
136
+ return existsSync(join(projectRoot, '.claude', 'settings.json'));
137
+ }
138
+ // ─── Tier defaults for maxTurns ──────────────────────────────────────────────
139
+ const TIER_MAX_TURNS = { search: 5, execute: 15, think: 10 };
140
+ // ─── Agent model mapper ───────────────────────────────────────────────────────
141
+ /**
142
+ * Map a model alias or model ID to the canonical agent model name (haiku|sonnet|opus).
143
+ * Falls back to tier-based defaults when no match is found.
144
+ */
145
+ function mapToAgentModel(modelAlias, tier) {
146
+ if (!modelAlias) {
147
+ const tierDefaults = { search: 'haiku', execute: 'sonnet', think: 'opus' };
148
+ return tierDefaults[tier ?? ''] ?? 'sonnet';
149
+ }
150
+ const lower = String(modelAlias).toLowerCase();
151
+ if (lower === 'haiku' || lower.startsWith('claude-3-haiku') || lower.includes('haiku'))
152
+ return 'haiku';
153
+ if (lower === 'opus' || lower.startsWith('claude-opus') || lower.includes('opus'))
154
+ return 'opus';
155
+ if (lower === 'sonnet' || lower.startsWith('claude-sonnet') || lower.includes('sonnet'))
156
+ return 'sonnet';
157
+ // Tier-based fallback
158
+ const tierDefaults = { search: 'haiku', execute: 'sonnet', think: 'opus' };
159
+ return tierDefaults[tier ?? ''] ?? 'sonnet';
160
+ }
161
+ // ─── Native dispatch builder ──────────────────────────────────────────────────
162
+ /**
163
+ * Build a structured native Agent tool call descriptor instead of a shell command.
164
+ * The caller (CLI or plugin) is responsible for invoking the Agent tool with this object.
165
+ */
166
+ function buildNativeDispatch(decision, prompt, options = {}) {
167
+ const tier = decision.tier ?? 'execute';
168
+ const model = mapToAgentModel(decision.model, tier);
169
+ return {
170
+ type: 'native-agent',
171
+ description: `dual-brain ${tier}: ${String(prompt).slice(0, 50)}`,
172
+ model,
173
+ prompt,
174
+ isolation: options.worktree ? 'worktree' : undefined,
175
+ maxTurns: options.maxTurns ?? TIER_MAX_TURNS[tier] ?? 15,
176
+ disallowedTools: tier === 'search' ? ['Edit', 'Write', 'NotebookEdit'] : [],
177
+ background: false,
178
+ };
179
+ }
180
+ // ─── Result normalizer ────────────────────────────────────────────────────────
181
+ /**
182
+ * Normalize a raw result from either a native Agent call or subprocess stdout
183
+ * into a common result shape.
184
+ */
185
+ function normalizeResult(rawResult, dispatchType) {
186
+ const raw = rawResult ?? {};
187
+ // Determine raw output string regardless of dispatch type
188
+ let rawOutput = '';
189
+ if (typeof rawResult === 'string') {
190
+ rawOutput = rawResult;
191
+ }
192
+ else if (typeof raw.stdout === 'string') {
193
+ rawOutput = raw.stdout;
194
+ }
195
+ else if (typeof raw.output === 'string') {
196
+ rawOutput = raw.output;
197
+ }
198
+ else if (typeof raw.result === 'string') {
199
+ rawOutput = raw.result;
200
+ }
201
+ else {
202
+ try {
203
+ rawOutput = JSON.stringify(raw);
204
+ }
205
+ catch {
206
+ rawOutput = String(raw);
207
+ }
208
+ }
209
+ // Determine status
210
+ let status = 'success';
211
+ if (dispatchType === 'subprocess') {
212
+ const exitCode = typeof raw.exitCode === 'number' ? raw.exitCode : (raw.code ?? null);
213
+ if (exitCode !== null) {
214
+ status = exitCode === 0 ? 'success' : 'failure';
215
+ }
216
+ else if (raw.status === 'failed' || raw.status === 'error') {
217
+ status = 'failure';
218
+ }
219
+ else if (raw.status === 'partial') {
220
+ status = 'partial';
221
+ }
222
+ }
223
+ else {
224
+ // native-agent
225
+ if (raw.status === 'failed' || raw.status === 'error' || raw.error) {
226
+ status = 'failure';
227
+ }
228
+ else if (raw.status === 'partial') {
229
+ status = 'partial';
230
+ }
231
+ }
232
+ // Extract fields from raw
233
+ const provider = raw.provider ?? (dispatchType === 'native-agent' ? 'claude' : 'unknown');
234
+ const model = raw.model ?? (raw.agentModel ?? 'unknown');
235
+ const tier = raw.tier ?? 'execute';
236
+ // Files changed / found — best-effort extraction from raw output
237
+ const filesChangedSet = new Set();
238
+ const filesFoundSet = new Set();
239
+ if (Array.isArray(raw.filesChanged))
240
+ raw.filesChanged.forEach(f => filesChangedSet.add(f));
241
+ if (Array.isArray(raw.filesFound))
242
+ raw.filesFound.forEach(f => filesFoundSet.add(f));
243
+ // Scan rawOutput for file hints
244
+ const changeMatches = rawOutput.matchAll(/(?:changed|edited|wrote|created|modified)\s+([^\s,]+\.[a-z]{1,6})/gi);
245
+ for (const m of changeMatches)
246
+ filesChangedSet.add(m[1]);
247
+ const foundMatches = rawOutput.matchAll(/(?:found|located|in)\s+([^\s,]+\.[a-z]{1,6})/gi);
248
+ for (const m of foundMatches)
249
+ filesFoundSet.add(m[1]);
250
+ // Tests run
251
+ let testsRun = raw.testsRun ?? 0;
252
+ if (testsRun === 0) {
253
+ const testMatch = rawOutput.match(/(\d+)\s+(?:tests?|specs?)\s+(?:passed|run|ran)/i);
254
+ if (testMatch)
255
+ testsRun = parseInt(testMatch[1], 10);
256
+ }
257
+ // Edge cases
258
+ const edgeCases = Array.isArray(raw.edgeCases) ? raw.edgeCases : [];
259
+ // Token usage
260
+ const rawTokensUsed = raw.tokensUsed;
261
+ const rawUsage = raw.usage;
262
+ const tokensUsed = {
263
+ input: rawTokensUsed?.input ?? rawUsage?.inputTokens ?? rawUsage?.input_tokens ?? 0,
264
+ output: rawTokensUsed?.output ?? rawUsage?.outputTokens ?? rawUsage?.output_tokens ?? 0,
265
+ };
266
+ // Errors
267
+ const errors = [];
268
+ if (Array.isArray(raw.errors))
269
+ errors.push(...raw.errors);
270
+ if (typeof raw.error === 'string' && raw.error)
271
+ errors.push(raw.error);
272
+ if (typeof raw.stderr === 'string' && raw.stderr)
273
+ errors.push(raw.stderr.slice(0, 200));
274
+ return {
275
+ status,
276
+ provider,
277
+ model,
278
+ tier,
279
+ filesChanged: [...filesChangedSet],
280
+ filesFound: [...filesFoundSet],
281
+ testsRun,
282
+ edgeCases,
283
+ tokensUsed,
284
+ errors,
285
+ rawOutput: rawOutput.slice(0, 2000),
286
+ };
287
+ }
288
+ // ─── Runtime detection (cached) ───────────────────────────────────────────────
289
+ let _runtimeCache = null;
290
+ async function detectRuntime() {
291
+ if (_runtimeCache)
292
+ return _runtimeCache;
293
+ const check = (cmd) => new Promise((resolve) => {
294
+ const p = spawn(cmd, ['--version'], { stdio: 'pipe' });
295
+ p.on('error', () => resolve(false));
296
+ p.on('close', (code) => resolve(code === 0));
297
+ setTimeout(() => { try {
298
+ p.kill();
299
+ }
300
+ catch { } resolve(false); }, 3000);
301
+ });
302
+ const [claudeAvailable, codexAvailable] = await Promise.all([
303
+ check('claude'),
304
+ check('codex'),
305
+ ]);
306
+ const runtime = claudeAvailable && codexAvailable ? 'claude-code'
307
+ : claudeAvailable ? 'claude-code'
308
+ : codexAvailable ? 'codex-cli'
309
+ : 'none';
310
+ _runtimeCache = { claudeAvailable, codexAvailable, runtime };
311
+ return _runtimeCache;
312
+ }
313
+ // ─── Feature 1: Model validation + graceful fallback ─────────────────────────
314
+ /** Valid CLI model flags per provider */
315
+ const VALID_MODELS = {
316
+ claude: ['opus', 'sonnet', 'haiku'],
317
+ openai: ['o4-mini', 'o3', 'o1', 'o1-mini', 'gpt-4o', 'gpt-4o-mini', 'gpt-4.1', 'gpt-4.1-mini', 'gpt-4-turbo'],
318
+ };
319
+ /** Safest default model for a given provider + tier */
320
+ function _safeModel(provider, tier) {
321
+ if (provider === 'claude') {
322
+ return tier === 'search' ? 'haiku' : 'sonnet';
323
+ }
324
+ return 'o4-mini';
325
+ }
326
+ /**
327
+ * Validate a routing decision against CLI availability and valid model lists.
328
+ * Returns either a (possibly corrected) decision object, or an error sentinel
329
+ * `{ _error: string }` when no CLI is available at all.
330
+ */
331
+ function validateDispatch(decision, rt) {
332
+ let provider = decision.provider ?? 'claude';
333
+ let model = decision.model;
334
+ const tier = decision.tier ?? 'execute';
335
+ // ── CLI availability ──────────────────────────────────────────────────────
336
+ const claudeOk = rt.claudeAvailable;
337
+ const codexOk = rt.codexAvailable;
338
+ if (!claudeOk && !codexOk) {
339
+ return { _error: 'No AI CLI available. Install claude or codex CLI.' };
340
+ }
341
+ if (provider === 'claude' && !claudeOk && codexOk) {
342
+ process.stderr.write('[dual-brain] Claude unavailable, falling back to OpenAI (codex)\n');
343
+ provider = 'openai';
344
+ }
345
+ else if (provider === 'openai' && !codexOk && claudeOk) {
346
+ process.stderr.write('[dual-brain] OpenAI unavailable, falling back to Claude (claude)\n');
347
+ provider = 'claude';
348
+ }
349
+ // ── Model validation ──────────────────────────────────────────────────────
350
+ const validList = VALID_MODELS[provider] ?? [];
351
+ if (model && !validList.includes(model)) {
352
+ const safe = _safeModel(provider, tier);
353
+ process.stderr.write(`[dual-brain] Model "${model}" not valid for ${provider} CLI; defaulting to "${safe}"\n`);
354
+ model = safe;
355
+ }
356
+ return { ...decision, provider, model };
357
+ }
358
+ // ─── Feature 2: Dirty-worktree guard ─────────────────────────────────────────
359
+ /**
360
+ * Simple glob match:
361
+ * - `dir/*` -> prefix match on `dir/`
362
+ * - `*.ext` -> suffix match on `.ext`
363
+ * - otherwise -> exact match
364
+ */
365
+ function _globMatch(pattern, filePath) {
366
+ if (pattern.endsWith('/*')) {
367
+ const prefix = pattern.slice(0, -1); // 'src/auth/'
368
+ return filePath.startsWith(prefix);
369
+ }
370
+ if (pattern.startsWith('*.')) {
371
+ const suffix = pattern.slice(1); // '.mjs'
372
+ return filePath.endsWith(suffix);
373
+ }
374
+ return filePath === pattern;
375
+ }
376
+ /**
377
+ * Check whether dirty worktree files overlap with the agent's ownership globs.
378
+ */
379
+ async function checkWorktreeClean(owns, cwd) {
380
+ if (!owns || owns.length === 0)
381
+ return { safe: true };
382
+ const dirty = await new Promise((resolve) => {
383
+ const proc = spawn('git', ['status', '--porcelain', '-u'], {
384
+ cwd: cwd || process.cwd(),
385
+ stdio: ['ignore', 'pipe', 'pipe'],
386
+ });
387
+ let out = '';
388
+ proc.stdout.on('data', (d) => { out += d; });
389
+ proc.on('close', () => {
390
+ // Each line: "XY path" — grab the path part (columns 4+, after "XY ")
391
+ const files = out.split('\n')
392
+ .map(l => l.slice(3).trim())
393
+ .filter(Boolean);
394
+ resolve(files);
395
+ });
396
+ proc.on('error', () => resolve([])); // git not available -> skip guard
397
+ });
398
+ if (dirty.length === 0)
399
+ return { safe: true };
400
+ const conflicts = dirty.filter(f => owns.some(pattern => _globMatch(pattern, f)));
401
+ if (conflicts.length > 0)
402
+ return { safe: false, conflicts };
403
+ return { safe: true };
404
+ }
405
+ // ─── Feature 3: Retry budget ──────────────────────────────────────────────────
406
+ /** Per-prompt retry count (keyed by first 16 hex chars of SHA-256 of prompt) */
407
+ const _retryCount = new Map();
408
+ /** Recent dispatch timestamps for the 5-minute window rate-limit */
409
+ const _recentDispatches = [];
410
+ const MAX_RETRIES_PER_TASK = 2;
411
+ const MAX_DISPATCHES_PER_5MIN = 5;
412
+ const WINDOW_MS = 5 * 60 * 1000;
413
+ function _promptKey(prompt) {
414
+ return createHash('sha256').update(String(prompt)).digest('hex').slice(0, 16);
415
+ }
416
+ /**
417
+ * Check whether this dispatch is within budget.
418
+ */
419
+ function _checkRetryBudget(prompt) {
420
+ const now = Date.now();
421
+ // Evict dispatch timestamps older than 5 minutes
422
+ while (_recentDispatches.length > 0 && now - _recentDispatches[0] > WINDOW_MS) {
423
+ _recentDispatches.shift();
424
+ }
425
+ if (_recentDispatches.length >= MAX_DISPATCHES_PER_5MIN) {
426
+ return { allowed: false, reason: 'Retry budget exhausted. Wait or adjust task.' };
427
+ }
428
+ const key = _promptKey(prompt);
429
+ const count = _retryCount.get(key) ?? 0;
430
+ if (count > MAX_RETRIES_PER_TASK) {
431
+ return { allowed: false, reason: 'Retry budget exhausted. Wait or adjust task.' };
432
+ }
433
+ return { allowed: true };
434
+ }
435
+ function _recordDispatchBudget(prompt) {
436
+ _recentDispatches.push(Date.now());
437
+ const key = _promptKey(prompt);
438
+ _retryCount.set(key, (_retryCount.get(key) ?? 0) + 1);
439
+ }
440
+ /**
441
+ * Return current retry budget state for status display.
442
+ */
443
+ function getRetryBudget() {
444
+ const now = Date.now();
445
+ const active = _recentDispatches.filter(t => now - t <= WINDOW_MS).length;
446
+ return {
447
+ perTaskRetries: Object.fromEntries(_retryCount),
448
+ recentDispatches: active,
449
+ windowMs: WINDOW_MS,
450
+ maxPerTask: MAX_RETRIES_PER_TASK,
451
+ maxPerWindow: MAX_DISPATCHES_PER_5MIN,
452
+ };
453
+ }
454
+ // ─── Preflight auth check ─────────────────────────────────────────────────────
455
+ /**
456
+ * Verify a provider CLI is present and (optionally) responds to --version.
457
+ * Uses `which` for the fast path and a 3s-capped --version call to confirm.
458
+ */
459
+ async function preflightAuth(provider, _cwd) {
460
+ const bin = provider === 'openai' ? 'codex' : 'claude';
461
+ // Fast path: check binary existence with `which`
462
+ const whichResult = await new Promise((resolve) => {
463
+ const p = spawn('which', [bin], { stdio: 'pipe' });
464
+ p.on('error', () => resolve(false));
465
+ p.on('close', (code) => resolve(code === 0));
466
+ setTimeout(() => { try {
467
+ p.kill();
468
+ }
469
+ catch { } resolve(false); }, 2000);
470
+ });
471
+ if (!whichResult) {
472
+ const installHint = provider === 'openai'
473
+ ? 'Install: npm install -g @openai/codex'
474
+ : 'Install: npm install -g @anthropic-ai/claude-code';
475
+ return {
476
+ ready: false,
477
+ provider,
478
+ error: `${bin} CLI not found in PATH`,
479
+ suggestion: installHint,
480
+ };
481
+ }
482
+ // Version check: confirms the binary actually runs (catches broken installs)
483
+ const versionOk = await new Promise((resolve) => {
484
+ const p = spawn(bin, ['--version'], { stdio: 'pipe' });
485
+ p.on('error', () => resolve(false));
486
+ p.on('close', (code) => resolve(code === 0));
487
+ setTimeout(() => { try {
488
+ p.kill();
489
+ }
490
+ catch { } resolve(false); }, 3000);
491
+ });
492
+ if (!versionOk) {
493
+ const loginHint = provider === 'openai' ? 'Run: codex login' : 'Run: claude login';
494
+ return {
495
+ ready: false,
496
+ provider,
497
+ error: `${bin} --version failed (auth may have expired)`,
498
+ suggestion: loginHint,
499
+ };
500
+ }
501
+ return { ready: true, provider };
502
+ }
503
+ // ─── Command builder ──────────────────────────────────────────────────────────
504
+ function buildCommand(decision, prompt, files = [], _cwd) {
505
+ const provider = decision?.provider ?? 'claude';
506
+ const modelAlias = decision?.model ?? 'sonnet';
507
+ const effort = decision?.effort ?? null;
508
+ const sandbox = decision?.sandbox ?? 'danger-full-access';
509
+ if (provider === 'claude') {
510
+ const modelId = CLAUDE_MODEL_IDS[modelAlias] ?? modelAlias;
511
+ const cmd = ['claude', '--model', modelId, '--print', '--output-format', 'json', '-p', prompt];
512
+ if (effort)
513
+ cmd.push('--effort', effort);
514
+ return cmd;
515
+ }
516
+ // openai / codex
517
+ const cmd = ['codex', 'exec', '-m', modelAlias, '-s', sandbox, prompt];
518
+ if (effort)
519
+ cmd.push('-c', `reasoning.effort="${effort}"`);
520
+ return cmd;
521
+ }
522
+ // ─── Usage recorder ───────────────────────────────────────────────────────────
523
+ function recordUsage(entry) {
524
+ try {
525
+ mkdirSync(USAGE_DIR, { recursive: true });
526
+ const date = new Date().toISOString().slice(0, 10);
527
+ appendFileSync(join(USAGE_DIR, `${date}.jsonl`), JSON.stringify({ timestamp: new Date().toISOString(), ...entry }) + '\n');
528
+ }
529
+ catch { }
530
+ }
531
+ // ─── Result compressor ────────────────────────────────────────────────────────
532
+ function compressResult(rawOutput = '', maxLength = 300) {
533
+ if (!rawOutput)
534
+ return '(no output)';
535
+ // Try JSON parse first (claude --output-format json)
536
+ try {
537
+ const parsed = JSON.parse(rawOutput);
538
+ const text = parsed?.result ?? parsed?.content ?? parsed?.message ?? JSON.stringify(parsed);
539
+ return String(text).slice(0, maxLength);
540
+ }
541
+ catch { }
542
+ // Strip code blocks
543
+ let cleaned = rawOutput
544
+ .replace(/```[\s\S]*?```/g, '[code block]')
545
+ .replace(/^\s+at\s+.+$/gm, '') // stack trace lines
546
+ .replace(/\n{3,}/g, '\n\n') // collapse blank lines
547
+ .trim();
548
+ // Extract first 2 meaningful sentences
549
+ const sentences = cleaned.match(/[^.!?\n]+[.!?\n]+/g) ?? [cleaned];
550
+ const meaningful = sentences.filter(s => s.trim().length > 15).slice(0, 2);
551
+ const head = meaningful.join(' ').trim() || cleaned.slice(0, maxLength);
552
+ // Append file-change hints if present
553
+ const fileHints = rawOutput.match(/(?:changed|edited|wrote|created|modified)\s+([^\s,]+\.[a-z]+)/gi) ?? [];
554
+ const suffix = fileHints.length ? ` | files: ${[...new Set(fileHints)].slice(0, 3).join(', ')}` : '';
555
+ return (head + suffix).slice(0, maxLength);
556
+ }
557
+ // ─── Core runner ──────────────────────────────────────────────────────────────
558
+ function runProcess(cmd, cwd, timeoutMs, env) {
559
+ return new Promise((resolve) => {
560
+ const [bin, ...args] = cmd;
561
+ const start = Date.now();
562
+ let stdout = '';
563
+ let stderr = '';
564
+ const spawnEnv = env ? { ...process.env, ...env } : undefined;
565
+ const proc = spawn(bin, args, { cwd, stdio: ['ignore', 'pipe', 'pipe'], ...(spawnEnv ? { env: spawnEnv } : {}) });
566
+ proc.stdout.on('data', (d) => { stdout += d; });
567
+ proc.stderr.on('data', (d) => { stderr += d; });
568
+ const killer = setTimeout(() => {
569
+ try {
570
+ proc.kill('SIGTERM');
571
+ }
572
+ catch { }
573
+ setTimeout(() => { try {
574
+ proc.kill('SIGKILL');
575
+ }
576
+ catch { } }, 5000);
577
+ }, timeoutMs);
578
+ proc.on('close', (code) => {
579
+ clearTimeout(killer);
580
+ resolve({ exitCode: code ?? 1, stdout: stdout.trim(), stderr: stderr.trim(), durationMs: Date.now() - start });
581
+ });
582
+ proc.on('error', (err) => {
583
+ clearTimeout(killer);
584
+ resolve({ exitCode: 1, stdout: '', stderr: err.message, durationMs: Date.now() - start });
585
+ });
586
+ });
587
+ }
588
+ // ─── Template-based prompt rendering ─────────────────────────────────────────
589
+ function _renderTemplatedPrompt(prompt, decision, context = {}) {
590
+ const tierStr = decision.tier ?? 'execute';
591
+ const tier = tierStr;
592
+ const template = getTemplate(tier);
593
+ if (!template)
594
+ return prompt;
595
+ if (decision.contract) {
596
+ const rendered = renderPrompt(tier, decision.contract, context);
597
+ if (rendered.valid)
598
+ return rendered.prompt ?? prompt;
599
+ }
600
+ const rendered = quickRender(tier, prompt, {
601
+ scope: decision.owns || decision.scope || [],
602
+ files: decision.files || [],
603
+ risk: decision.risk || 'medium',
604
+ criteria: decision.acceptanceCriteria || [],
605
+ nonGoals: decision.nonGoals || [],
606
+ context: decision.taskContext || '',
607
+ });
608
+ return rendered.valid ? rendered.prompt ?? prompt : prompt;
609
+ }
610
+ // ─── Dispatch marker ─────────────────────────────────────────────────────────
611
+ // Prepend a marker to every prompt that goes through the official dispatch pipeline.
612
+ // The enforce-tier hook checks for this marker to distinguish legitimate dispatches
613
+ // from raw Agent calls made by the HEAD that bypass the dual-brain pipeline.
614
+ // Format: <!-- dual-brain-dispatch:<runId>|tier:<tier>|model:<model>|risk:<risk>|req:<requiredTier> -->
615
+ // runId is a short timestamp-based ID; governance fields enable over-provisioning validation.
616
+ let _dispatchRunId = null;
617
+ function _getDispatchRunId() {
618
+ if (!_dispatchRunId) {
619
+ // Generate once per process: timestamp + random suffix
620
+ _dispatchRunId = Date.now().toString(36) + Math.random().toString(36).slice(2, 6);
621
+ }
622
+ return _dispatchRunId;
623
+ }
624
+ function _prependDispatchMarker(prompt, decision = {}) {
625
+ const runId = _getDispatchRunId();
626
+ const tier = decision.tier || 'execute';
627
+ const model = decision.model || 'sonnet';
628
+ const risk = decision.risk || 'medium';
629
+ const requiredTier = decision._requiredTier || '';
630
+ const marker = `<!-- dual-brain-dispatch:${runId}|tier:${tier}|model:${model}|risk:${risk}|req:${requiredTier} -->`;
631
+ return `${marker}\n${prompt}`;
632
+ }
633
+ // ─── Related session age label ────────────────────────────────────────────────
634
+ /**
635
+ * Human-readable age label for a related session date string.
636
+ */
637
+ function _relatedSessionAge(isoDate) {
638
+ const diff = Date.now() - Date.parse(isoDate);
639
+ const mins = Math.floor(diff / 60000);
640
+ if (mins < 60)
641
+ return `${mins}m ago`;
642
+ const hours = Math.floor(mins / 60);
643
+ if (hours < 24)
644
+ return `${hours}h ago`;
645
+ const days = Math.floor(hours / 24);
646
+ return `${days}d ago`;
647
+ }
648
+ // ─── Main dispatch ────────────────────────────────────────────────────────────
649
+ async function dispatch(input = {}) {
650
+ const { files = [], cwd = process.cwd(), dryRun = false, verbose = false } = input;
651
+ let decision = input.decision ?? {};
652
+ let prompt = input.prompt;
653
+ if (!prompt)
654
+ throw new Error('prompt is required');
655
+ // Safety gate: redact secrets before anything reaches a subprocess or log
656
+ prompt = redact(prompt);
657
+ // ── Template-based prompt rendering ─────────────────────────────────────────
658
+ // When a tier and/or contract are present, render through templates.mjs for
659
+ // structured, typed prompts. Falls back to raw prompt when no template matches.
660
+ prompt = _renderTemplatedPrompt(prompt, decision);
661
+ // ── Context intelligence: model-specific prompt shaping ─────────────────────
662
+ // When we have files and a target model, shape the prompt context for optimal
663
+ // model consumption. This adds structured context without replacing the template output.
664
+ if (files.length > 0 || decision.tier) {
665
+ try {
666
+ const pack = await buildContextPack(prompt, files, cwd);
667
+ const role = decision.tier === 'think' ? 'thinker'
668
+ : decision.tier === 'review' ? 'reviewer'
669
+ : 'worker';
670
+ const targetModel = decision.model || 'sonnet';
671
+ const tokenBudget = role === 'thinker' ? 3000
672
+ : role === 'reviewer' ? 4000
673
+ : 8000;
674
+ const { shaped, tokenEstimate } = shapeForRole(pack, role, targetModel, tokenBudget);
675
+ if (shaped && tokenEstimate > 0) {
676
+ prompt = `${shaped}\n\n---\n\n${prompt}`;
677
+ if (verbose)
678
+ process.stderr.write(`[dual-brain] context-intel: ${role} packet shaped for ${targetModel} (~${tokenEstimate} tokens)\n`);
679
+ }
680
+ }
681
+ catch { /* non-blocking — context shaping failure never prevents dispatch */ }
682
+ }
683
+ // ── End context intelligence ─────────────────────────────────────────────────
684
+ // ── Resume brief injection ───────────────────────────────────────────────────
685
+ // Inject the last session's receipt as context when no situationBrief is already set.
686
+ // This closes the receipt -> brief -> next session loop automatically.
687
+ // Falls back to continuity.mjs handoffs when receipt.mjs returns nothing.
688
+ if (!input.situationBrief) {
689
+ try {
690
+ // @ts-ignore
691
+ const { buildResumeBrief } = await import('./receipt.js');
692
+ const brief = buildResumeBrief(cwd);
693
+ if (brief) {
694
+ input = { ...input, situationBrief: brief };
695
+ }
696
+ }
697
+ catch { /* non-blocking */ }
698
+ // Provider-aware continuity fallback: adapts resume format for target provider
699
+ if (!input.situationBrief) {
700
+ try {
701
+ // @ts-ignore
702
+ const { buildProviderResumeBrief } = await import('./provider-context.js');
703
+ const targetProvider = decision.provider || 'claude';
704
+ const providerBrief = buildProviderResumeBrief(cwd, targetProvider);
705
+ if (providerBrief) {
706
+ input = { ...input, situationBrief: providerBrief };
707
+ }
708
+ }
709
+ catch { /* non-blocking */ }
710
+ // Legacy fallback: continuity.mjs handoff (provider-unaware)
711
+ if (!input.situationBrief) {
712
+ try {
713
+ // @ts-ignore
714
+ const { buildResumeBrief: buildHandoffBrief } = await import('./continuity.js');
715
+ const handoffBrief = buildHandoffBrief(cwd);
716
+ if (handoffBrief) {
717
+ input = { ...input, situationBrief: handoffBrief };
718
+ }
719
+ }
720
+ catch { /* non-blocking */ }
721
+ }
722
+ }
723
+ }
724
+ // ── End resume brief injection ───────────────────────────────────────────────
725
+ // ── Related session context injection ────────────────────────────────────────
726
+ // Find past sessions related to this task and prepend a context block.
727
+ // Only injected when confidence is high (score > 5). Fast: index-only, no JSONL parsing.
728
+ if (!input._skipRelatedContext) {
729
+ try {
730
+ // @ts-ignore
731
+ const { findRelatedSessions } = await import('./session.js');
732
+ const related = findRelatedSessions(prompt, files, cwd);
733
+ const highConfidence = related.filter(r => r.score > 5);
734
+ if (highConfidence.length > 0) {
735
+ const lines = highConfidence.map(r => {
736
+ const dateLabel = r.date ? _relatedSessionAge(r.date) : null;
737
+ const datePart = dateLabel ? `, ${dateLabel}` : '';
738
+ const msgPart = r.messageCount && r.messageCount > 0 ? `, ${r.messageCount} messages` : '';
739
+ const fileList = r.matchedFiles.length > 0
740
+ ? `: touched ${r.matchedFiles.map(f => f.split('/').pop()).join(', ')}`
741
+ : '';
742
+ return `- "${r.smartName}"${datePart}${msgPart}${fileList}`;
743
+ });
744
+ const contextBlock = `[Prior context from related sessions:]\n${lines.join('\n')}\n[End prior context]\n\n`;
745
+ prompt = contextBlock + prompt;
746
+ if (verbose)
747
+ process.stderr.write(`[dual-brain] injected related session context (${highConfidence.length} sessions)\n`);
748
+ }
749
+ }
750
+ catch { /* non-fatal — never block dispatch */ }
751
+ }
752
+ // ── End related session context ──────────────────────────────────────────────
753
+ // Stamp the prompt with the dispatch marker so enforce-tier.mjs can recognise
754
+ // that this agent call came through the official pipeline.
755
+ // Compute required tier for governance validation
756
+ try {
757
+ const scores = scoreTask({ intent: decision.tier, risk: decision.risk, files, objective: prompt.slice(0, 200) });
758
+ decision = { ...decision, _requiredTier: computeRequiredTier(scores) };
759
+ }
760
+ catch { /* non-blocking */ }
761
+ prompt = _prependDispatchMarker(prompt, decision);
762
+ // ── Situation brief injection ────────────────────────────────────────────────
763
+ // Prepend a compact project-state summary when provided by the pipeline.
764
+ // This gives every dispatched agent immediate context about the project reality.
765
+ const situationBrief = typeof input.situationBrief === 'string' && input.situationBrief.trim()
766
+ ? input.situationBrief.trim()
767
+ : null;
768
+ if (situationBrief) {
769
+ prompt = `[SITUATION BRIEF]\n${situationBrief}\n[END BRIEF]\n\n${prompt}`;
770
+ }
771
+ // ── End situation brief ──────────────────────────────────────────────────────
772
+ // ── Specialist prompt injection ──────────────────────────────────────────────
773
+ const specialist = decision.specialist && decision.specialist !== 'generic'
774
+ ? decision.specialist
775
+ : null;
776
+ if (specialist) {
777
+ const specialistPrompt = loadSpecialistPrompt(specialist);
778
+ if (specialistPrompt) {
779
+ prompt = `${specialistPrompt}\n\n---\n\n${prompt}`;
780
+ if (verbose)
781
+ process.stderr.write(`[dual-brain] specialist: ${specialist}\n`);
782
+ }
783
+ // Apply tier_bias from registry if decision didn't already pin a tier
784
+ if (!decision.tier) {
785
+ const registry = _loadSpecialistRegistry();
786
+ const tierBias = registry?.specialists?.[specialist]?.tier_bias;
787
+ if (tierBias) {
788
+ decision = { ...decision, tier: tierBias };
789
+ if (verbose)
790
+ process.stderr.write(`[dual-brain] specialist tier_bias applied: ${tierBias}\n`);
791
+ }
792
+ }
793
+ }
794
+ // ── End specialist injection ─────────────────────────────────────────────────
795
+ // ── Plugin hint injection (Codex path) ──────────────────────────────────────
796
+ // When dispatching to OpenAI/Codex, check if any Codex plugins match the task
797
+ // and append an advisory hint so the agent can choose to use them.
798
+ // Uses dynamic import so failure is always non-fatal.
799
+ const targetProvider = decision.provider ?? 'claude';
800
+ if (targetProvider === 'openai') {
801
+ try {
802
+ // @ts-ignore
803
+ const { matchPluginsForTask } = await import('./replit.js');
804
+ const matched = matchPluginsForTask(prompt, undefined, cwd);
805
+ if (matched.length > 0) {
806
+ const pluginNames = matched.slice(0, 3).map(m => m.plugin.id).join(', ');
807
+ const hint = `\n\n[Available Codex plugins for this task: ${pluginNames}. Consider using the matching plugin for direct API access.]`;
808
+ prompt = prompt + hint;
809
+ if (verbose)
810
+ process.stderr.write(`[dual-brain] plugin hint injected: ${pluginNames}\n`);
811
+ }
812
+ }
813
+ catch { /* non-fatal — never block dispatch */ }
814
+ }
815
+ // ── End plugin hint injection ────────────────────────────────────────────────
816
+ const tier = decision.tier ?? 'execute';
817
+ const timeoutMs = TIER_TIMEOUT_MS[tier] ?? 120_000;
818
+ // ── Feature 3: Retry budget check ────────────────────────────────────────
819
+ const budget = _checkRetryBudget(prompt);
820
+ if (!budget.allowed) {
821
+ return {
822
+ status: 'error',
823
+ provider: decision.provider ?? 'claude',
824
+ model: decision.model ?? 'sonnet',
825
+ command: null,
826
+ exitCode: null,
827
+ summary: budget.reason,
828
+ durationMs: 0,
829
+ usage: null,
830
+ error: budget.reason,
831
+ };
832
+ }
833
+ // ── Feature 1: Validate dispatch (CLI availability + model) ──────────────
834
+ const rt = await detectRuntime();
835
+ const validated = validateDispatch({ ...decision, tier }, rt);
836
+ if (validated._error) {
837
+ return {
838
+ status: 'error',
839
+ provider: decision.provider ?? 'claude',
840
+ model: decision.model ?? 'sonnet',
841
+ command: null,
842
+ exitCode: null,
843
+ summary: validated._error,
844
+ durationMs: 0,
845
+ usage: null,
846
+ error: validated._error,
847
+ };
848
+ }
849
+ const effectiveProvider = validated.provider;
850
+ let effectiveModel = validated.model ?? decision.model ?? 'sonnet';
851
+ let effectiveDecision = { ...validated };
852
+ // modelSuggestion influence: if the pipeline provided a model suggestion from models.mjs,
853
+ // apply it when the current model is a tier default/fallback (not an explicit override).
854
+ // The suggestion is advisory — it only applies when the decision didn't pin a specific model.
855
+ if (input.modelSuggestion?.model && effectiveProvider === 'claude') {
856
+ const TIER_DEFAULTS = new Set(['haiku', 'sonnet', 'opus']);
857
+ const decisionModelExplicit = decision._explicit?.model ?? false;
858
+ const isDefault = !decisionModelExplicit && TIER_DEFAULTS.has(effectiveModel);
859
+ if (isDefault) {
860
+ const suggestedAlias = mapToAgentModel(input.modelSuggestion.model, effectiveDecision.tier ?? 'execute');
861
+ const validList = VALID_MODELS[effectiveProvider] ?? [];
862
+ if (validList.includes(suggestedAlias)) {
863
+ effectiveModel = suggestedAlias;
864
+ effectiveDecision = { ...effectiveDecision, model: suggestedAlias };
865
+ if (verbose)
866
+ process.stderr.write(`\x1b[2m[dual-brain] modelSuggestion applied: ${suggestedAlias} (${input.modelSuggestion.reason})\x1b[0m\n`);
867
+ }
868
+ }
869
+ }
870
+ // ── Preflight auth check ─────────────────────────────────────────────────
871
+ // Verify the target provider CLI is present and responsive before dispatching.
872
+ // Runs after model/provider resolution so we check the effective provider.
873
+ const preflight = await preflightAuth(effectiveProvider, cwd);
874
+ if (!preflight.ready) {
875
+ // Check if the other provider is available as a fallback
876
+ const otherProvider = effectiveProvider === 'claude' ? 'openai' : 'claude';
877
+ const otherPreflight = await preflightAuth(otherProvider, cwd);
878
+ const fallbackNote = otherPreflight.ready
879
+ ? ` Fallback available: ${otherProvider}.`
880
+ : '';
881
+ const errMsg = `${preflight.error}. ${preflight.suggestion}${fallbackNote}`;
882
+ return {
883
+ status: 'error',
884
+ provider: effectiveProvider,
885
+ model: effectiveModel,
886
+ command: null,
887
+ exitCode: null,
888
+ summary: errMsg,
889
+ durationMs: 0,
890
+ usage: null,
891
+ error: errMsg,
892
+ authVerified: false,
893
+ suggestion: preflight.suggestion,
894
+ };
895
+ }
896
+ // ── End preflight auth check ─────────────────────────────────────────────
897
+ // ── Feature 2: Dirty-worktree guard for execute-tier dispatches ──────────
898
+ if (tier === 'execute' && decision.owns && !decision._force) {
899
+ const wtCheck = await checkWorktreeClean(decision.owns, cwd);
900
+ if (!wtCheck.safe) {
901
+ const msg = `Uncommitted changes conflict with agent scope: ${wtCheck.conflicts.join(', ')}. Commit or stash before dispatching.`;
902
+ return {
903
+ status: 'error',
904
+ provider: effectiveProvider,
905
+ model: effectiveModel,
906
+ command: null,
907
+ exitCode: null,
908
+ summary: msg,
909
+ durationMs: 0,
910
+ usage: null,
911
+ error: msg,
912
+ };
913
+ }
914
+ }
915
+ // ── Worktree isolation decision ──────────────────────────────────────────────
916
+ // Compute whether this dispatch should run in an isolated worktree based on
917
+ // risk level, file-edit volume, and security/auth signals in the prompt.
918
+ const SECURITY_PATTERN = /\b(auth|secret|token|credential|password|key|oauth|jwt|session|permission|role|acl)\b/i;
919
+ const decisionRisk = (decision.risk ?? 'low').toLowerCase();
920
+ const decisionFilesEst = decision.filesEstimate ?? 0;
921
+ const riskIsElevated = decisionRisk === 'medium' || decisionRisk === 'high' || decisionRisk === 'critical';
922
+ const manyFiles = decisionFilesEst >= 3;
923
+ const hasSecurity = SECURITY_PATTERN.test(prompt);
924
+ const useWorktree = input.useWorktree ?? (riskIsElevated || manyFiles || hasSecurity);
925
+ // Propagate useWorktree onto effectiveDecision so callers can inspect it
926
+ if (useWorktree) {
927
+ effectiveDecision = { ...effectiveDecision, useWorktree: true };
928
+ }
929
+ // ── End worktree isolation decision ─────────────────────────────────────────
930
+ // ── Native Claude Code dispatch ──────────────────────────────────────────────
931
+ // When running inside Claude Code AND the provider is claude, execute via the
932
+ // claude CLI directly (foreground subprocess) so results are captured and returned.
933
+ // DUAL_BRAIN_DISPATCH=1 is set so the enforce-tier hook allows this agent call.
934
+ if (isInsideClaude() && effectiveProvider === 'claude') {
935
+ const nativeDescriptor = buildNativeDispatch(effectiveDecision, prompt, { worktree: useWorktree, maxTurns: input.maxTurns });
936
+ const command = buildCommand(effectiveDecision, prompt, files, cwd);
937
+ if (dryRun) {
938
+ return {
939
+ status: 'dry-run',
940
+ provider: effectiveProvider,
941
+ model: effectiveModel,
942
+ specialist: specialist ?? 'generic',
943
+ command,
944
+ nativeDispatch: nativeDescriptor,
945
+ exitCode: null,
946
+ summary: null,
947
+ durationMs: 0,
948
+ usage: null,
949
+ error: null,
950
+ authVerified: true,
951
+ };
952
+ }
953
+ _recordDispatchBudget(prompt);
954
+ const dispatchEnv = { DUAL_BRAIN_DISPATCH: '1' };
955
+ // ── Auto-heal failover retry loop (native Claude path) ────────────────
956
+ const MAX_FAILOVER_ATTEMPTS = 2;
957
+ let currentProvider = effectiveProvider;
958
+ let currentModel = effectiveModel;
959
+ let currentDecision = effectiveDecision;
960
+ let currentCommand = command;
961
+ let lastRaw = { exitCode: 1, stdout: '', stderr: '', durationMs: 0 };
962
+ for (let attempt = 0; attempt <= MAX_FAILOVER_ATTEMPTS; attempt++) {
963
+ lastRaw = await runProcess(currentCommand, cwd, timeoutMs, dispatchEnv);
964
+ if (lastRaw.exitCode === 0 || !isRetryableFailure(lastRaw) || attempt === MAX_FAILOVER_ATTEMPTS)
965
+ break;
966
+ const failoverList = getFailoverOrder({ provider: currentProvider, model: currentModel, tier }, input.profile ?? {});
967
+ if (failoverList.length === 0)
968
+ break;
969
+ const next = failoverList[0];
970
+ const reason = `${lastRaw.stderr || lastRaw.stdout}`.slice(0, 120);
971
+ logFailover({ from: `${currentProvider}/${currentModel}`, to: `${next.provider}/${next.model}`, reason, attempt: attempt + 1 });
972
+ process.stderr.write(`\x1b[2m[dual-brain] Provider busy, failing over to ${next.label}...\x1b[0m\n`);
973
+ markHot(currentProvider, currentModel, cwd);
974
+ currentProvider = next.provider;
975
+ currentModel = next.model;
976
+ currentDecision = { ...currentDecision, provider: currentProvider, model: currentModel };
977
+ currentCommand = buildCommand(currentDecision, prompt, files, cwd);
978
+ }
979
+ const { exitCode, stdout, stderr, durationMs } = lastRaw;
980
+ // ── End failover loop ────────────────────────────────────────────────
981
+ // Extract token usage from JSON output if available
982
+ let usage = null;
983
+ try {
984
+ const parsed = JSON.parse(stdout);
985
+ if (parsed?.usage) {
986
+ usage = { inputTokens: parsed.usage.input_tokens ?? 0, outputTokens: parsed.usage.output_tokens ?? 0 };
987
+ }
988
+ }
989
+ catch { }
990
+ const success = exitCode === 0;
991
+ const errorText = (stderr || stdout).slice(0, 500);
992
+ const summary = success ? compressResult(stdout) : compressResult(stderr || stdout);
993
+ // ── Health tracking ────────────────────────────────────────────────────
994
+ if (success) {
995
+ recordDuration(currentProvider, currentModel, durationMs);
996
+ const median = medianDuration(currentProvider, currentModel);
997
+ if (median !== null && durationMs > median * 3) {
998
+ markDegraded(currentProvider, currentModel, cwd);
999
+ }
1000
+ else {
1001
+ markHealthy(currentProvider, currentModel, cwd);
1002
+ }
1003
+ const totalTokens = (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0);
1004
+ recordDispatch(currentProvider, currentModel, totalTokens, cwd);
1005
+ }
1006
+ else {
1007
+ if (RATE_LIMIT_PATTERNS.test(errorText)) {
1008
+ markHot(currentProvider, currentModel, cwd);
1009
+ }
1010
+ }
1011
+ // ── End health tracking ────────────────────────────────────────────────
1012
+ recordUsage({
1013
+ provider: currentProvider,
1014
+ model: currentModel,
1015
+ tier,
1016
+ durationMs,
1017
+ inputTokens: usage?.inputTokens ?? null,
1018
+ outputTokens: usage?.outputTokens ?? null,
1019
+ success,
1020
+ });
1021
+ // ── Auto-review annotation ────────────────────────────────────────────────
1022
+ // When execution changed files at medium+ risk, stamp result with a pending
1023
+ // review note. The opposite provider from the one that did the work reviews
1024
+ // it (true dual-brain). Non-blocking — does not delay the return value.
1025
+ let autoReview;
1026
+ if (success && (decision.risk === 'medium' || decision.risk === 'high' || decision.risk === 'critical')) {
1027
+ try {
1028
+ const reviewProvider = currentProvider === 'claude' ? 'openai' : 'claude';
1029
+ autoReview = { triggered: true, provider: reviewProvider, status: 'pending' };
1030
+ }
1031
+ catch {
1032
+ autoReview = { triggered: false, reason: 'review-dispatch-failed' };
1033
+ }
1034
+ }
1035
+ else {
1036
+ autoReview = { triggered: false, reason: success ? 'low-risk' : 'dispatch-failed' };
1037
+ }
1038
+ // ── End auto-review annotation ────────────────────────────────────────────
1039
+ const nativeResult = {
1040
+ status: success ? 'completed' : 'failed',
1041
+ type: 'native-agent',
1042
+ provider: currentProvider,
1043
+ model: currentModel,
1044
+ specialist: specialist ?? 'generic',
1045
+ command: currentCommand,
1046
+ nativeDispatch: nativeDescriptor,
1047
+ exitCode,
1048
+ summary,
1049
+ durationMs,
1050
+ usage,
1051
+ worktreeUsed: useWorktree,
1052
+ autoReview,
1053
+ authVerified: true,
1054
+ error: success ? null : errorText.slice(0, 200),
1055
+ };
1056
+ try {
1057
+ const outcomeModule = await import('./outcome.js');
1058
+ outcomeModule.recordDispatchOutcome(input, nativeResult);
1059
+ }
1060
+ catch { /* never block */ }
1061
+ // ── Self-correction: intelligent retry after failover exhaustion ──────────
1062
+ if (!success) {
1063
+ const attemptNumber = input._retryAttempt || 1;
1064
+ try {
1065
+ const selfCorrectModule = await import('./self-correct.js');
1066
+ const retry = selfCorrectModule.shouldRetry(nativeResult, decision, attemptNumber);
1067
+ if (retry.retry && retry.decision) {
1068
+ if (verbose)
1069
+ process.stderr.write(`[dual-brain] self-correct: ${retry.strategy} (attempt ${attemptNumber + 1}, reason: ${retry.reason})\n`);
1070
+ return dispatch({
1071
+ ...input,
1072
+ decision: retry.decision,
1073
+ _retryAttempt: attemptNumber + 1,
1074
+ _skipPreDispatchThink: retry.strategy !== 'rethink',
1075
+ _skipRelatedContext: true,
1076
+ });
1077
+ }
1078
+ else if (verbose) {
1079
+ process.stderr.write(`[dual-brain] self-correct: giving up (${retry.reason})\n`);
1080
+ }
1081
+ }
1082
+ catch { /* non-blocking — if self-correct fails, return original failure */ }
1083
+ }
1084
+ // ── End self-correction ───────────────────────────────────────────────────
1085
+ return nativeResult;
1086
+ }
1087
+ const command = buildCommand(effectiveDecision, prompt, files, cwd);
1088
+ if (dryRun) {
1089
+ return { status: 'dry-run', provider: effectiveProvider, model: effectiveModel, specialist: specialist ?? 'generic', command, exitCode: null, summary: null, durationMs: 0, usage: null, error: null, authVerified: true };
1090
+ }
1091
+ // Record this dispatch against the budget
1092
+ _recordDispatchBudget(prompt);
1093
+ // ── Auto-heal failover retry loop (subprocess path) ──────────────────────
1094
+ const MAX_FAILOVER_ATTEMPTS_SUB = 2;
1095
+ let subProvider = effectiveProvider;
1096
+ let subModel = effectiveModel;
1097
+ let subDecision = effectiveDecision;
1098
+ let subCommand = command;
1099
+ let subRaw = { exitCode: 1, stdout: '', stderr: '', durationMs: 0 };
1100
+ for (let attempt = 0; attempt <= MAX_FAILOVER_ATTEMPTS_SUB; attempt++) {
1101
+ subRaw = await runProcess(subCommand, cwd, timeoutMs);
1102
+ if (subRaw.exitCode === 0 || !isRetryableFailure(subRaw) || attempt === MAX_FAILOVER_ATTEMPTS_SUB)
1103
+ break;
1104
+ const failoverList = getFailoverOrder({ provider: subProvider, model: subModel, tier }, input.profile ?? {});
1105
+ if (failoverList.length === 0)
1106
+ break;
1107
+ const next = failoverList[0];
1108
+ const reason = `${subRaw.stderr || subRaw.stdout}`.slice(0, 120);
1109
+ logFailover({ from: `${subProvider}/${subModel}`, to: `${next.provider}/${next.model}`, reason, attempt: attempt + 1 });
1110
+ process.stderr.write(`\x1b[2m[dual-brain] Provider busy, failing over to ${next.label}...\x1b[0m\n`);
1111
+ markHot(subProvider, subModel, cwd);
1112
+ subProvider = next.provider;
1113
+ subModel = next.model;
1114
+ subDecision = { ...subDecision, provider: subProvider, model: subModel };
1115
+ subCommand = buildCommand(subDecision, prompt, files, cwd);
1116
+ }
1117
+ const { exitCode, stdout, stderr, durationMs } = subRaw;
1118
+ // ── End failover loop ──────────────────────────────────────────────────────
1119
+ // Extract token usage from JSON output if available
1120
+ let usage = null;
1121
+ try {
1122
+ const parsed = JSON.parse(stdout);
1123
+ if (parsed?.usage) {
1124
+ usage = { inputTokens: parsed.usage.input_tokens ?? 0, outputTokens: parsed.usage.output_tokens ?? 0 };
1125
+ }
1126
+ }
1127
+ catch { }
1128
+ const success = exitCode === 0;
1129
+ const errorText = (stderr || stdout).slice(0, 500);
1130
+ const summary = success ? compressResult(stdout) : compressResult(stderr || stdout);
1131
+ // ── Health tracking ──────────────────────────────────────────────────────
1132
+ if (success) {
1133
+ recordDuration(subProvider, subModel, durationMs);
1134
+ const median = medianDuration(subProvider, subModel);
1135
+ if (median !== null && durationMs > median * 3) {
1136
+ markDegraded(subProvider, subModel, cwd);
1137
+ }
1138
+ else {
1139
+ markHealthy(subProvider, subModel, cwd);
1140
+ }
1141
+ const totalTokens = (usage?.inputTokens ?? 0) + (usage?.outputTokens ?? 0);
1142
+ recordDispatch(subProvider, subModel, totalTokens, cwd);
1143
+ }
1144
+ else {
1145
+ if (RATE_LIMIT_PATTERNS.test(errorText)) {
1146
+ markHot(subProvider, subModel, cwd);
1147
+ }
1148
+ }
1149
+ // ── End health tracking ──────────────────────────────────────────────────
1150
+ recordUsage({
1151
+ provider: subProvider,
1152
+ model: subModel,
1153
+ tier,
1154
+ durationMs,
1155
+ inputTokens: usage?.inputTokens ?? null,
1156
+ outputTokens: usage?.outputTokens ?? null,
1157
+ success,
1158
+ });
1159
+ // ── Auto-review annotation ──────────────────────────────────────────────────
1160
+ // When execution changed files at medium+ risk, stamp result with a pending
1161
+ // review note. The opposite provider from the one that did the work reviews
1162
+ // it (true dual-brain). Non-blocking — does not delay the return value.
1163
+ let autoReview;
1164
+ if (success && (decision.risk === 'medium' || decision.risk === 'high' || decision.risk === 'critical')) {
1165
+ try {
1166
+ const reviewProvider = subProvider === 'claude' ? 'openai' : 'claude';
1167
+ autoReview = { triggered: true, provider: reviewProvider, status: 'pending' };
1168
+ }
1169
+ catch {
1170
+ autoReview = { triggered: false, reason: 'review-dispatch-failed' };
1171
+ }
1172
+ }
1173
+ else {
1174
+ autoReview = { triggered: false, reason: success ? 'low-risk' : 'dispatch-failed' };
1175
+ }
1176
+ // ── End auto-review annotation ──────────────────────────────────────────────
1177
+ const subResult = {
1178
+ status: success ? 'completed' : 'failed',
1179
+ provider: subProvider,
1180
+ model: subModel,
1181
+ specialist: specialist ?? 'generic',
1182
+ command: subCommand,
1183
+ exitCode,
1184
+ summary,
1185
+ durationMs,
1186
+ usage,
1187
+ worktreeUsed: useWorktree,
1188
+ autoReview,
1189
+ authVerified: true,
1190
+ error: success ? null : errorText.slice(0, 200),
1191
+ };
1192
+ try {
1193
+ const outcomeModule2 = await import('./outcome.js');
1194
+ outcomeModule2.recordDispatchOutcome(input, subResult);
1195
+ }
1196
+ catch { /* never block */ }
1197
+ // ── Self-correction: intelligent retry after failover exhaustion ──────────
1198
+ if (!success) {
1199
+ const attemptNumber = input._retryAttempt || 1;
1200
+ try {
1201
+ const selfCorrectModule2 = await import('./self-correct.js');
1202
+ const retry = selfCorrectModule2.shouldRetry(subResult, decision, attemptNumber);
1203
+ if (retry.retry && retry.decision) {
1204
+ if (verbose)
1205
+ process.stderr.write(`[dual-brain] self-correct: ${retry.strategy} (attempt ${attemptNumber + 1}, reason: ${retry.reason})\n`);
1206
+ return dispatch({
1207
+ ...input,
1208
+ decision: retry.decision,
1209
+ _retryAttempt: attemptNumber + 1,
1210
+ _skipPreDispatchThink: retry.strategy !== 'rethink',
1211
+ _skipRelatedContext: true,
1212
+ });
1213
+ }
1214
+ else if (verbose) {
1215
+ process.stderr.write(`[dual-brain] self-correct: giving up (${retry.reason})\n`);
1216
+ }
1217
+ }
1218
+ catch { /* non-blocking — if self-correct fails, return original failure */ }
1219
+ }
1220
+ // ── End self-correction ───────────────────────────────────────────────────
1221
+ return subResult;
1222
+ }
1223
+ // ─── Dual-brain dispatch (parallel) ───────────────────────────────────────────
1224
+ async function dispatchDualBrain(input = {}) {
1225
+ const { files = [], cwd = process.cwd(), dryRun = false, verbose = false } = input;
1226
+ let decision = input.decision ?? {};
1227
+ let prompt = input.prompt;
1228
+ if (!prompt)
1229
+ throw new Error('prompt is required');
1230
+ // Safety gate: redact secrets before sending to either provider
1231
+ prompt = redact(prompt);
1232
+ // Stamp with dispatch marker so enforce-tier.mjs allows this Agent call
1233
+ // Compute required tier for governance validation
1234
+ try {
1235
+ const scores = scoreTask({ intent: decision.tier, risk: decision.risk, files, objective: prompt.slice(0, 200) });
1236
+ decision = { ...decision, _requiredTier: computeRequiredTier(scores) };
1237
+ }
1238
+ catch { /* non-blocking */ }
1239
+ prompt = _prependDispatchMarker(prompt, decision);
1240
+ // ── Situation brief injection ────────────────────────────────────────────────
1241
+ const _dualBrainBrief = typeof input.situationBrief === 'string' && input.situationBrief.trim()
1242
+ ? input.situationBrief.trim()
1243
+ : null;
1244
+ if (_dualBrainBrief) {
1245
+ prompt = `[SITUATION BRIEF]\n${_dualBrainBrief}\n[END BRIEF]\n\n${prompt}`;
1246
+ }
1247
+ // ── End situation brief ──────────────────────────────────────────────────────
1248
+ // Feature 1: Validate both sub-decisions before spawning anything
1249
+ const rt = await detectRuntime();
1250
+ const tier = decision.tier ?? 'execute';
1251
+ const claudeDecision = { ...decision, provider: 'claude', model: decision.model ?? 'sonnet', tier };
1252
+ const _oaiDefault = tier === 'think' ? 'o3' : tier === 'search' ? 'gpt-4o-mini' : 'gpt-4o';
1253
+ const openaiDecision = { ...decision, provider: 'openai', model: decision.openaiModel ?? _oaiDefault, tier };
1254
+ const validatedClaude = validateDispatch(claudeDecision, rt);
1255
+ const validatedOpenai = validateDispatch(openaiDecision, rt);
1256
+ const [claudeResult, openaiResult] = await Promise.all([
1257
+ validatedClaude._error
1258
+ ? Promise.resolve({ status: 'error', provider: 'claude', model: claudeDecision.model, command: null, exitCode: null, summary: validatedClaude._error, durationMs: 0, usage: null, error: validatedClaude._error })
1259
+ : dispatch({ decision: validatedClaude, prompt, files, cwd, dryRun, verbose }),
1260
+ validatedOpenai._error
1261
+ ? Promise.resolve({ status: 'error', provider: 'openai', model: openaiDecision.model, command: null, exitCode: null, summary: validatedOpenai._error, durationMs: 0, usage: null, error: validatedOpenai._error })
1262
+ : dispatch({ decision: validatedOpenai, prompt, files, cwd, dryRun, verbose }),
1263
+ ]);
1264
+ return {
1265
+ tier,
1266
+ claude: claudeResult,
1267
+ openai: openaiResult,
1268
+ consensus: claudeResult.status === 'completed' && openaiResult.status === 'completed'
1269
+ ? 'both-passed'
1270
+ : claudeResult.status === 'failed' && openaiResult.status === 'failed'
1271
+ ? 'both-failed'
1272
+ : 'split',
1273
+ };
1274
+ }
1275
+ // ─── CLI ──────────────────────────────────────────────────────────────────────
1276
+ if (process.argv[1] && new URL(import.meta.url).pathname === process.argv[1]) {
1277
+ const args = process.argv.slice(2);
1278
+ const flag = (name) => { const i = args.indexOf(name); return i !== -1 ? (args[i + 1] ?? true) : null; };
1279
+ if (args.includes('--detect-runtime')) {
1280
+ const rt = await detectRuntime();
1281
+ console.log(JSON.stringify(rt, null, 2));
1282
+ process.exit(0);
1283
+ }
1284
+ const prompt = flag('--prompt') || args.find(a => !a.startsWith('--'));
1285
+ if (!prompt) {
1286
+ console.error('Usage: node src/dispatch.ts --prompt "..." [--provider claude|openai] [--model sonnet] [--tier execute] [--dry-run]');
1287
+ console.error(' node src/dispatch.ts --detect-runtime');
1288
+ process.exit(1);
1289
+ }
1290
+ const decision = {
1291
+ provider: flag('--provider') || 'claude',
1292
+ model: flag('--model') || 'sonnet',
1293
+ tier: flag('--tier') || 'execute',
1294
+ effort: flag('--effort') || null,
1295
+ };
1296
+ try {
1297
+ const result = await dispatch({ decision, prompt: prompt, dryRun: args.includes('--dry-run') });
1298
+ console.log(JSON.stringify(result, null, 2));
1299
+ }
1300
+ catch (err) {
1301
+ console.error('dispatch error:', err.message);
1302
+ process.exit(1);
1303
+ }
1304
+ }
1305
+ export { dispatch, buildCommand, detectRuntime, compressResult, dispatchDualBrain, validateDispatch, checkWorktreeClean, getRetryBudget, isInsideClaude, buildNativeDispatch, normalizeResult, loadSpecialistPrompt, preflightAuth };
1306
+ //# sourceMappingURL=dispatch.js.map