@mycompbox/compbox-cli 1.21.17 → 1.21.19

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 (83) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/commands/run.d.ts +4 -1
  3. package/commands/run.d.ts.map +1 -1
  4. package/commands/run.js +103 -14
  5. package/commands/run.js.map +1 -1
  6. package/commands/workspace.d.ts +41 -2
  7. package/commands/workspace.d.ts.map +1 -1
  8. package/commands/workspace.js +147 -7
  9. package/commands/workspace.js.map +1 -1
  10. package/index.js +2902 -468
  11. package/package.json +1 -1
  12. package/utils/agent-invoker.d.ts +74 -13
  13. package/utils/agent-invoker.d.ts.map +1 -1
  14. package/utils/agent-invoker.js +341 -82
  15. package/utils/agent-invoker.js.map +1 -1
  16. package/utils/agent-permissions.d.ts +44 -0
  17. package/utils/agent-permissions.d.ts.map +1 -0
  18. package/utils/agent-permissions.js +229 -0
  19. package/utils/agent-permissions.js.map +1 -0
  20. package/utils/agent-store.d.ts +119 -0
  21. package/utils/agent-store.d.ts.map +1 -0
  22. package/utils/agent-store.js +421 -0
  23. package/utils/agent-store.js.map +1 -0
  24. package/utils/agent-trial.d.ts +34 -0
  25. package/utils/agent-trial.d.ts.map +1 -0
  26. package/utils/agent-trial.js +180 -0
  27. package/utils/agent-trial.js.map +1 -0
  28. package/utils/api-client.d.ts +11 -0
  29. package/utils/api-client.d.ts.map +1 -1
  30. package/utils/api-client.js +31 -0
  31. package/utils/api-client.js.map +1 -1
  32. package/utils/belt-engine.d.ts +72 -0
  33. package/utils/belt-engine.d.ts.map +1 -0
  34. package/utils/belt-engine.js +136 -0
  35. package/utils/belt-engine.js.map +1 -0
  36. package/utils/cloud-preflight.d.ts +26 -4
  37. package/utils/cloud-preflight.d.ts.map +1 -1
  38. package/utils/cloud-preflight.js +90 -7
  39. package/utils/cloud-preflight.js.map +1 -1
  40. package/utils/custom-agent-contract.d.ts +44 -0
  41. package/utils/custom-agent-contract.d.ts.map +1 -0
  42. package/utils/custom-agent-contract.js +122 -0
  43. package/utils/custom-agent-contract.js.map +1 -0
  44. package/utils/custom-agent-permissions.d.ts +48 -0
  45. package/utils/custom-agent-permissions.d.ts.map +1 -0
  46. package/utils/custom-agent-permissions.js +109 -0
  47. package/utils/custom-agent-permissions.js.map +1 -0
  48. package/utils/custom-agent-runner.d.ts +99 -0
  49. package/utils/custom-agent-runner.d.ts.map +1 -0
  50. package/utils/custom-agent-runner.js +227 -0
  51. package/utils/custom-agent-runner.js.map +1 -0
  52. package/utils/custom-agent-sync.d.ts +59 -0
  53. package/utils/custom-agent-sync.d.ts.map +1 -0
  54. package/utils/custom-agent-sync.js +197 -0
  55. package/utils/custom-agent-sync.js.map +1 -0
  56. package/utils/key-run.d.ts +9 -0
  57. package/utils/key-run.d.ts.map +1 -1
  58. package/utils/key-run.js +18 -0
  59. package/utils/key-run.js.map +1 -1
  60. package/utils/mailbox-client.d.ts +115 -2
  61. package/utils/mailbox-client.d.ts.map +1 -1
  62. package/utils/mailbox-client.js +114 -6
  63. package/utils/mailbox-client.js.map +1 -1
  64. package/utils/merge-guard.d.ts +48 -7
  65. package/utils/merge-guard.d.ts.map +1 -1
  66. package/utils/merge-guard.js +152 -17
  67. package/utils/merge-guard.js.map +1 -1
  68. package/utils/pxpipe-savings.d.ts +12 -0
  69. package/utils/pxpipe-savings.d.ts.map +1 -0
  70. package/utils/pxpipe-savings.js +68 -0
  71. package/utils/pxpipe-savings.js.map +1 -0
  72. package/utils/run-timings.d.ts +3 -0
  73. package/utils/run-timings.d.ts.map +1 -1
  74. package/utils/run-timings.js +2 -0
  75. package/utils/run-timings.js.map +1 -1
  76. package/utils/run-workspace.d.ts +18 -0
  77. package/utils/run-workspace.d.ts.map +1 -1
  78. package/utils/run-workspace.js +46 -5
  79. package/utils/run-workspace.js.map +1 -1
  80. package/utils/wrap-up.d.ts +8 -0
  81. package/utils/wrap-up.d.ts.map +1 -1
  82. package/utils/wrap-up.js +24 -2
  83. package/utils/wrap-up.js.map +1 -1
@@ -16,6 +16,7 @@
16
16
  *
17
17
  * `start_execution` jobs run the planner/orchestrator headless (below).
18
18
  */
19
+ import { ApiClient } from './api-client.js';
19
20
  import Anthropic from "@anthropic-ai/sdk";
20
21
  import { execFile, spawn, spawnSync } from "node:child_process";
21
22
  import { planCrossPlatformSpawn, spawnCrossPlatform } from "./process-spawn.js";
@@ -24,7 +25,8 @@ import { copyFileSync, existsSync, mkdirSync, mkdtempSync } from "node:fs";
24
25
  import { mkdir, mkdtemp, realpath, rm, writeFile } from "node:fs/promises";
25
26
  import { homedir, tmpdir } from "node:os";
26
27
  import { join } from "node:path";
27
- import { resolveRouting, extractCompletionJson, looksLikeCompletionAttempt, meetsComplianceTarget, buildAuditFeedback, COMPLETION_REPAIR_INSTRUCTION, renderConversationPrompt, contentText, runConversationStep, savedContextFromRecord, isConversationChatModel, formatNeedsInputText, parseNeedsInputMarker, stripRunnerOnlyFields, } from "@mycompbox/shared";
28
+ import { readMeasuredTokensSaved } from "./pxpipe-savings.js";
29
+ import { resolveRouting, toRunRouting, extractCompletionJson, looksLikeCompletionAttempt, meetsComplianceTarget, buildAuditFeedback, COMPLETION_REPAIR_INSTRUCTION, renderConversationPrompt, contentText, runConversationStep, savedContextFromRecord, isConversationChatModel, formatNeedsInputText, parseNeedsInputMarker, stripRunnerOnlyFields, } from "@mycompbox/shared";
28
30
  // Completion parsing lives in @mycompbox/shared so CompBox's server-side
29
31
  // (API-key) interview finishes the same way; re-exported for existing callers.
30
32
  /**
@@ -42,14 +44,17 @@ import { buildJobTimings, CiWaitTracker, parseClaudeDurations, } from "./run-tim
42
44
  import { defaultPreflightExecFile, formatPreflightTurn, preflightNeedsInput, repoFromRemote, runCloudPreflight, } from "./cloud-preflight.js";
43
45
  import { claudeChildEnvPath, claudeNotFoundMessage, resolveClaudeBinary, } from "./claude-runtime.js";
44
46
  import { getBuildMaxMs, getBuildStallMs, getConfigDir, isGitRepoDir } from "./config-store.js";
45
- import { mergeGuardArgs, withMergeGuardPath } from "./merge-guard.js";
47
+ import { mergeGuardArgs, withHooksDisabled, withMergeGuardPath } from "./merge-guard.js";
48
+ import { applyAgentPermissions, permissionsFor, } from "./agent-permissions.js";
46
49
  import { keyRunArgs, keyRunEnv, parseClaudeJsonResult } from "./key-run.js";
47
50
  import { CANCEL_GRACE_MS, cancelledRunResult, groupSpawnOptions, killGroupOnAbort, killProcessGroupNow, terminateProcessGroup, } from "./process-group.js";
48
51
  import { startProgressWatcher } from "./progress-watcher.js";
49
52
  import { parseClaudeStream } from "./claude-stream.js";
50
53
  import { classifyUsageLimit } from "./usage-limit.js";
51
- import { defaultCommandRunner, } from "./run-workspace.js";
54
+ import { createGcloudConfigDir, defaultCommandRunner, withIsolatedGcloud, } from "./run-workspace.js";
52
55
  import { createWrapUp } from "./wrap-up.js";
56
+ import { BeltUnsupportedError, } from "./mailbox-client.js";
57
+ import { runBelt } from "./belt-engine.js";
53
58
  // Fable is the model CompBox agents run on (ENG-E26): it is pxpipe's 100/100
54
59
  // image reader, so routing it through the proxy cuts input tokens without
55
60
  // quality loss. Opus/Sonnet are deliberately NOT used here — pxpipe passes
@@ -111,27 +116,9 @@ export function claudeSpawnEnv(base, routing) {
111
116
  ? { ...base, ANTHROPIC_BASE_URL: routing.anthropicBaseUrl }
112
117
  : base;
113
118
  }
114
- /**
115
- * ENG-394: env that points `core.hooksPath` at `hooksDir` for every git the
116
- * child runs, so the repo's own hooks (e.g. a pre-commit running the whole
117
- * test suite) don't fire on each agent commit — the build's own checks run
118
- * them once at the end. Uses GIT_CONFIG_COUNT/KEY_n/VALUE_n (git >= 2.31),
119
- * appended after any entries already set; older git just ignores it and the
120
- * hooks run as before. A malformed existing count is left alone (git would
121
- * otherwise reject every command). Pure — unit tested.
122
- */
123
- export function withHooksDisabled(env, hooksDir) {
124
- const raw = env.GIT_CONFIG_COUNT?.trim();
125
- if (raw && !/^\d+$/.test(raw))
126
- return env;
127
- const n = raw ? Number(raw) : 0;
128
- return {
129
- ...env,
130
- GIT_CONFIG_COUNT: String(n + 1),
131
- [`GIT_CONFIG_KEY_${String(n)}`]: "core.hooksPath",
132
- [`GIT_CONFIG_VALUE_${String(n)}`]: hooksDir,
133
- };
134
- }
119
+ // withHooksDisabled (ENG-394) lives in merge-guard.ts so the custom agent
120
+ // runner can reuse it without importing this module; re-exported here.
121
+ export { withHooksDisabled };
135
122
  /**
136
123
  * ENG-394: a fresh hooks folder for one run's agent. Holds nothing except a
137
124
  * copy of the run copy's pre-push merge guard (ENG-346), when it has one, so
@@ -1033,7 +1020,9 @@ async function converseWithAttachments(job, ctx, step) {
1033
1020
  if (outcome.kind === "saved") {
1034
1021
  await ctx.mailboxClient.markRequestSaved(ctx.machineToken, job.id, outcome.saved.id);
1035
1022
  }
1036
- await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text, timer.finish(replyModel));
1023
+ // ENG-526: pass along any suggested replies the shared parser pulled from the
1024
+ // reply, so the person can tap one. postTurn leaves them out when empty.
1025
+ await ctx.mailboxClient.postTurn(ctx.machineToken, job.id, outcome.text, timer.finish(replyModel), outcome.kind === "error" ? undefined : outcome.options);
1037
1026
  return { status: "yield" };
1038
1027
  }
1039
1028
  // ---------------------------------------------------------------------
@@ -1077,20 +1066,47 @@ const ORCHESTRATOR_REVIEW_MARKER = "COMPBOX_NEEDS_HUMAN_REVIEW";
1077
1066
  * result, reports the run's usage to CompBox (best-effort), and returns the
1078
1067
  * plain text the run would otherwise have printed.
1079
1068
  */
1080
- export function takeKeyRunResult(ctx, keyRun, stdout) {
1069
+ export function takeKeyRunResult(ctx, keyRun, stdout, routing) {
1081
1070
  const parsed = parseClaudeJsonResult(stdout, keyRun.model);
1082
1071
  if (!parsed)
1083
1072
  return { text: stdout, reported: Promise.resolve() };
1073
+ const usage = routing
1074
+ ? {
1075
+ ...parsed.usage,
1076
+ routingMode: routing.mode,
1077
+ routingReason: routing.reason,
1078
+ tokensSaved: routing.tokensSaved,
1079
+ }
1080
+ : parsed.usage;
1084
1081
  const reported = ctx.mailboxClient
1085
- .reportAiUsage(ctx.machineToken, ctx.jobId, parsed.usage)
1082
+ .reportAiUsage(ctx.machineToken, ctx.jobId, usage)
1086
1083
  .catch(() => undefined);
1087
1084
  return { text: parsed.text, reported };
1088
1085
  }
1089
- async function settleKeyRun(ctx, keyRun, stdout) {
1090
- const { text, reported } = takeKeyRunResult(ctx, keyRun, stdout);
1086
+ async function settleKeyRun(ctx, keyRun, stdout, routing, startedAtMs) {
1087
+ let runRouting;
1088
+ if (routing) {
1089
+ const saved = routing.mode === "proxy" && startedAtMs !== undefined
1090
+ ? await readMeasuredTokensSaved(startedAtMs, Date.now())
1091
+ : null;
1092
+ runRouting = toRunRouting(routing, saved);
1093
+ }
1094
+ const { text, reported } = takeKeyRunResult(ctx, keyRun, stdout, runRouting);
1091
1095
  await reported;
1092
1096
  return text;
1093
1097
  }
1098
+ /** Planning stages the planner can resume from (ENG-521), in pipeline order. */
1099
+ export const PLANNER_RESUME_STAGES = ["ANALYZE", "DECOMPOSE", "DETAIL", "EVALUATE", "VERIFY"];
1100
+ const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
1101
+ /** A known planning stage name, or undefined (never interpolate anything else into the prompt). */
1102
+ export function parsePlanningStage(value) {
1103
+ return typeof value === "string" && PLANNER_RESUME_STAGES.includes(value)
1104
+ ? value
1105
+ : undefined;
1106
+ }
1107
+ function parseUuid(value) {
1108
+ return typeof value === "string" && UUID_RE.test(value) ? value : undefined;
1109
+ }
1094
1110
  /**
1095
1111
  * Build the `claude` argv for a headless planner run (H1). Pure + exported so a
1096
1112
  * unit test can assert the exact command shape: the `@planner` routing prompt,
@@ -1101,10 +1117,18 @@ async function settleKeyRun(ctx, keyRun, stdout) {
1101
1117
  * account default apply — pxpipe routing rides on ANTHROPIC_BASE_URL, not the
1102
1118
  * model name).
1103
1119
  */
1104
- export function buildPlannerArgs(epicRequestId) {
1120
+ export function buildPlannerArgs(epicRequestId, resume = {}) {
1121
+ // ENG-521: a retry resumes from the failed stage and fills in the epic an
1122
+ // earlier run already created, instead of re-planning from scratch.
1123
+ const stage = parsePlanningStage(resume.resumeFromStage);
1124
+ const epicId = parseUuid(resume.epicId);
1125
+ const resumeFlags = [
1126
+ ...(stage ? [`--resume-from ${stage}`] : []),
1127
+ ...(epicId ? [`--epic ${epicId}`] : []),
1128
+ ].join(" ");
1105
1129
  return [
1106
1130
  "-p",
1107
- `@planner --from-request ${epicRequestId} --gates=auto --non-interactive`,
1131
+ `@planner --from-request ${epicRequestId}${resumeFlags ? ` ${resumeFlags}` : ""} --gates=auto --non-interactive`,
1108
1132
  // H1: an unattended permission mode so tool use in this print-mode run never
1109
1133
  // blocks on an interactive "allow?" prompt (the interview path is safe only
1110
1134
  // because it grants ZERO tools; this path grants the full MCP surface).
@@ -1272,6 +1296,84 @@ async function fetchConvertedEpicId(apiBaseUrl, userApiToken, epicRequestId, fet
1272
1296
  return null;
1273
1297
  }
1274
1298
  }
1299
+ /** The planner pipeline stages, in order (mirrors the API's planningStageNames). */
1300
+ const PLANNING_STAGES = ["ANALYZE", "DECOMPOSE", "DETAIL", "EVALUATE", "VERIFY"];
1301
+ /** Longest failure reason the planning-progress endpoint accepts (error.message max). */
1302
+ const PLANNING_FAILURE_MESSAGE_MAX = 1000;
1303
+ function isPlanningStage(value) {
1304
+ return typeof value === "string" && PLANNING_STAGES.includes(value);
1305
+ }
1306
+ /**
1307
+ * ENG-520: the last planning stage the planner reported for an Epic Request
1308
+ * (its `planningState.currentStage`), or null when it never reported one or the
1309
+ * lookup fails. `planningState` may arrive as a JSON string or a parsed object.
1310
+ */
1311
+ export async function fetchPlanningStage(apiBaseUrl, userApiToken, epicRequestId, fetchImpl) {
1312
+ try {
1313
+ const res = await fetchImpl(`${apiBaseUrl.replace(/\/+$/, "")}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`, { headers: { Authorization: `Bearer ${userApiToken}` } });
1314
+ if (!res.ok)
1315
+ return null;
1316
+ const body = (await res.json());
1317
+ let state = body.data?.planningState;
1318
+ if (typeof state === "string") {
1319
+ try {
1320
+ state = JSON.parse(state);
1321
+ }
1322
+ catch {
1323
+ return null;
1324
+ }
1325
+ }
1326
+ if (!state || typeof state !== "object")
1327
+ return null;
1328
+ const stage = state.currentStage;
1329
+ return isPlanningStage(stage) ? stage : null;
1330
+ }
1331
+ catch {
1332
+ return null;
1333
+ }
1334
+ }
1335
+ /**
1336
+ * ENG-520: tell the server planning failed — at the stage the planner last
1337
+ * reported (ANALYZE when it never reported one) — with a readable reason, so
1338
+ * the idea doesn't sit in "planning" forever when the local planner dies.
1339
+ *
1340
+ * Best-effort: never throws. Returns whether the server accepted the report; a
1341
+ * rejected or unreachable report is logged and the runner carries on.
1342
+ */
1343
+ export async function reportPlanningFailure(apiBaseUrl, userApiToken, epicRequestId, reason, fetchImpl, knownStage) {
1344
+ try {
1345
+ const stage = knownStage ??
1346
+ (await fetchPlanningStage(apiBaseUrl, userApiToken, epicRequestId, fetchImpl)) ??
1347
+ "ANALYZE";
1348
+ const message = reason.length > PLANNING_FAILURE_MESSAGE_MAX
1349
+ ? `${reason.slice(0, PLANNING_FAILURE_MESSAGE_MAX - 1)}…`
1350
+ : reason;
1351
+ const res = await fetchImpl(`${apiBaseUrl.replace(/\/+$/, "")}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}/planning-progress`, {
1352
+ method: "PATCH",
1353
+ headers: {
1354
+ Authorization: `Bearer ${userApiToken}`,
1355
+ "Content-Type": "application/json",
1356
+ },
1357
+ body: JSON.stringify({ stage, status: "failed", error: { message } }),
1358
+ });
1359
+ if (!res.ok) {
1360
+ console.warn(` ⚠ Could not report the planning failure for ${epicRequestId} (HTTP ${String(res.status)}).`);
1361
+ return false;
1362
+ }
1363
+ return true;
1364
+ }
1365
+ catch (error) {
1366
+ console.warn(` ⚠ Could not report the planning failure for ${epicRequestId}: ${error instanceof Error ? error.message : String(error)}`);
1367
+ return false;
1368
+ }
1369
+ }
1370
+ /** Short, readable tail of the planner's stderr to append to a failure reason. */
1371
+ function plannerOutputTail(text, max = 300) {
1372
+ const trimmed = text.trim();
1373
+ if (!trimmed)
1374
+ return "";
1375
+ return trimmed.length > max ? `…${trimmed.slice(-max)}` : trimmed;
1376
+ }
1275
1377
  /**
1276
1378
  * Reduce an epic's API `complianceScore` (parsed object, or a JSON string from
1277
1379
  * older servers) to the fields the planner runner needs. Returns null when no
@@ -1392,10 +1494,12 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1392
1494
  return { status: "failed", result: { error: projectDirNotGitRepoMessage(ctx.projectDir) } };
1393
1495
  }
1394
1496
  const routing = await resolveRoutingImpl();
1497
+ const keyRunStartedAtMs = Date.now();
1395
1498
  const command = resolveClaudeBinary() ?? "claude";
1396
- const args = ctx.keyRun
1397
- ? keyRunArgs(buildPlannerArgs(ctx.epicRequestId))
1398
- : buildPlannerArgs(ctx.epicRequestId);
1499
+ // ENG-579: the planner's declared tool limits replace bypassPermissions where set.
1500
+ const args = applyAgentPermissions(ctx.keyRun
1501
+ ? keyRunArgs(buildPlannerArgs(ctx.epicRequestId, ctx))
1502
+ : buildPlannerArgs(ctx.epicRequestId, ctx), permissionsFor(deps.agentPermissions, "planner"));
1399
1503
  // pxpipe (ENG-136): inject ANTHROPIC_BASE_URL when routed. COMPBOX_NONINTERACTIVE
1400
1504
  // forces the planner's headless path even if the prompt flag were dropped. PATH
1401
1505
  // is augmented (ENG-135) so `claude` and any helpers it spawns resolve.
@@ -1418,6 +1522,10 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1418
1522
  catch {
1419
1523
  // Best-effort start turn.
1420
1524
  }
1525
+ // ENG-520: when the planner dies (non-zero exit, signal, timeout) or exits
1526
+ // before reaching VERIFY, tell the server planning failed so the idea doesn't
1527
+ // stay stuck in "planning". Set on those paths, sent after the run settles.
1528
+ let planningFailure = null;
1421
1529
  const outcome = await new Promise((resolve) => {
1422
1530
  let stdout = "";
1423
1531
  let stderr = "";
@@ -1458,6 +1566,11 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1458
1566
  };
1459
1567
  const timer = setTimeout(() => {
1460
1568
  killProcessGroupNow(child, deps.processGroup);
1569
+ if (!settled && !cancelled) {
1570
+ planningFailure = {
1571
+ reason: `The planner timed out after ${String(Math.round(timeoutMs / 60_000))} minutes and was stopped.`,
1572
+ };
1573
+ }
1461
1574
  finish({
1462
1575
  status: "failed",
1463
1576
  result: {
@@ -1476,6 +1589,13 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1476
1589
  finish(cancelledRunResult("planner"));
1477
1590
  return;
1478
1591
  }
1592
+ if (!settled) {
1593
+ planningFailure = {
1594
+ reason: error.code === "ENOENT"
1595
+ ? "The planner could not start: the Claude CLI was not found on this computer."
1596
+ : `The planner could not start: ${error.message || "spawn failed"}.`,
1597
+ };
1598
+ }
1479
1599
  finish({
1480
1600
  status: "failed",
1481
1601
  result: {
@@ -1485,10 +1605,10 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1485
1605
  },
1486
1606
  });
1487
1607
  });
1488
- child.on("close", (code) => {
1608
+ child.on("close", (code, exitSignal) => {
1489
1609
  void (async () => {
1490
1610
  if (ctx.keyRun)
1491
- stdout = await settleKeyRun(ctx, ctx.keyRun, stdout);
1611
+ stdout = await settleKeyRun(ctx, ctx.keyRun, stdout, routing, keyRunStartedAtMs);
1492
1612
  if (cancelled) {
1493
1613
  finish(cancelledRunResult("planner"));
1494
1614
  return;
@@ -1510,12 +1630,22 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1510
1630
  return;
1511
1631
  }
1512
1632
  if (code !== 0) {
1633
+ // ENG-520: a crash or kill is reported to the server as a planning failure.
1634
+ if (!settled) {
1635
+ const tail = plannerOutputTail(stderr);
1636
+ const base = code === null && exitSignal
1637
+ ? `The planner was stopped (${exitSignal}) before it finished.`
1638
+ : `The planner exited with code ${String(code ?? "null")} before it finished.`;
1639
+ planningFailure = { reason: tail ? `${base} ${tail}` : base };
1640
+ }
1513
1641
  finish({
1514
1642
  status: "failed",
1515
1643
  result: {
1516
1644
  error: stderr.trim() ||
1517
1645
  stdout.trim().slice(-PLANNER_FINAL_TURN_MAX_CHARS) ||
1518
- `The planner exited with code ${String(code ?? "null")}.`,
1646
+ (code === null && exitSignal
1647
+ ? `The planner was stopped (${exitSignal}).`
1648
+ : `The planner exited with code ${String(code ?? "null")}.`),
1519
1649
  },
1520
1650
  });
1521
1651
  return;
@@ -1525,6 +1655,15 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1525
1655
  // independent of stdout formatting.
1526
1656
  const epicId = await fetchConvertedEpicId(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicRequestId, fetchImpl);
1527
1657
  if (!epicId) {
1658
+ // ENG-520: a clean exit that never reached VERIFY means the planner
1659
+ // stopped early — report it so the idea doesn't stay "planning".
1660
+ const lastStage = await fetchPlanningStage(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicRequestId, fetchImpl);
1661
+ if (!settled && lastStage !== "VERIFY") {
1662
+ planningFailure = {
1663
+ reason: "Planner exited before finishing",
1664
+ stage: lastStage ?? "ANALYZE",
1665
+ };
1666
+ }
1528
1667
  // ENG-287-2: an unconverted ER is never a success — surface it for review.
1529
1668
  finish({
1530
1669
  status: "failed",
@@ -1558,6 +1697,12 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1558
1697
  })();
1559
1698
  });
1560
1699
  });
1700
+ // ENG-520: report the failure to the server (best-effort — never throws).
1701
+ // TS can't see the closure assignments, so read it through a typed alias.
1702
+ const failure = planningFailure;
1703
+ if (failure && outcome.status === "failed") {
1704
+ await reportPlanningFailure(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicRequestId, failure.reason, fetchImpl, failure.stage);
1705
+ }
1561
1706
  // H4: relay a FINAL turn summarizing the outcome (best-effort).
1562
1707
  try {
1563
1708
  await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, buildPlannerFinalTurn(outcome));
@@ -1642,8 +1787,10 @@ export async function invokeStartExecutionRefine(ctx, deps = {}) {
1642
1787
  return { status: "failed", result: { error: projectDirNotGitRepoMessage(ctx.projectDir) } };
1643
1788
  }
1644
1789
  const routing = await resolveRoutingImpl();
1790
+ const keyRunStartedAtMs = Date.now();
1645
1791
  const command = resolveClaudeBinary() ?? "claude";
1646
- const args = ctx.keyRun ? keyRunArgs(buildRefineArgs(ctx.epicId)) : buildRefineArgs(ctx.epicId);
1792
+ // ENG-579: the planner's declared tool limits replace bypassPermissions where set.
1793
+ const args = applyAgentPermissions(ctx.keyRun ? keyRunArgs(buildRefineArgs(ctx.epicId)) : buildRefineArgs(ctx.epicId), permissionsFor(deps.agentPermissions, "planner"));
1647
1794
  const baseEnv = buildRefineEnv(claudeSpawnEnv(process.env, routing), ctx.notes);
1648
1795
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
1649
1796
  try {
@@ -1721,7 +1868,7 @@ export async function invokeStartExecutionRefine(ctx, deps = {}) {
1721
1868
  child.on("close", (code) => {
1722
1869
  void (async () => {
1723
1870
  if (ctx.keyRun)
1724
- stdout = await settleKeyRun(ctx, ctx.keyRun, stdout);
1871
+ stdout = await settleKeyRun(ctx, ctx.keyRun, stdout, routing, keyRunStartedAtMs);
1725
1872
  if (cancelled) {
1726
1873
  finish(cancelledRunResult("planner"));
1727
1874
  return;
@@ -2067,6 +2214,26 @@ export function followUpContext(message) {
2067
2214
  ].join("\n\n");
2068
2215
  }
2069
2216
  /** Claude CLI args that resume the orchestrator's session with {@link orchestratorContinuePrompt}. */
2217
+ /**
2218
+ * ENG-591: args for one belt step's Claude turn. The first turn starts the
2219
+ * session under its known id; later turns resume it.
2220
+ */
2221
+ export function buildBeltTurnArgs(sessionId, prompt, startSession, baseBranch, fastMode) {
2222
+ if (!startSession)
2223
+ return buildOrchestratorContinueArgs(sessionId, prompt, baseBranch, fastMode);
2224
+ return [
2225
+ "-p",
2226
+ prompt,
2227
+ "--session-id",
2228
+ sessionId,
2229
+ "--append-system-prompt",
2230
+ HEADLESS_ORCHESTRATE_REMINDER,
2231
+ "--permission-mode",
2232
+ "bypassPermissions",
2233
+ ...mergeGuardArgs(baseBranch),
2234
+ ...fastModeArgs(fastMode),
2235
+ ];
2236
+ }
2070
2237
  export function buildOrchestratorContinueArgs(sessionId, prompt, baseBranch, fastMode) {
2071
2238
  return [
2072
2239
  "-p",
@@ -2433,35 +2600,14 @@ export function detectNeedsInput(stdout, stderr = "") {
2433
2600
  return { kind: "input", request };
2434
2601
  }
2435
2602
  /**
2436
- * Run the orchestrator headless for a `start_execution`/`orchestrate` job
2437
- * (ENG-165).
2438
- *
2439
- * Flow: validate the project repo (git repo → worktree-capable → test toolchain
2440
- * present) → spawn the local `claude` CLI in that repo cwd with ENG-164's MCP +
2441
- * CLAUDE.md-routing profile (H1: unattended permission mode, NOT
2442
- * `--tools ""`/`--safe-mode`) running `@orchestrator execute epic <epicId>
2443
- * --non-interactive` with `COMPBOX_NONINTERACTIVE=1` (H3 signal) and pxpipe's
2444
- * `ANTHROPIC_BASE_URL` preserved → keep the machine alive with a periodic
2445
- * heartbeat during the long run (H4) → relay a start + final turn to the mailbox
2446
- * → on a needs-review HARD-gate marker complete as a needs-review failure naming
2447
- * the gate (ENG-165-3); on a non-zero exit fail with the reason; on a clean run
2448
- * complete `{ epicId }`. Never hangs.
2603
+ * The checks every orchestrated build makes before Claude is spawned (shared by
2604
+ * the orchestrator path and the belt engine, ENG-590): the project preconditions
2605
+ * and, for a cloud build, the cloud preflight.
2449
2606
  */
2450
- export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2451
- // ENG-300: cancelled before it started — don't spawn at all.
2452
- if (ctx.signal?.aborted)
2453
- return cancelledRunResult("orchestrator");
2454
- // ENG-352: wall clock for the run's time breakdown.
2455
- const clockMs = deps.clockMs ?? Date.now;
2456
- const startedAtMs = clockMs();
2457
- const spawnImpl = deps.spawnImpl ?? spawn;
2607
+ export async function prepareOrchestrateRun(ctx, deps = {}) {
2458
2608
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
2459
2609
  const worktreeCapable = deps.worktreeCapable ?? defaultWorktreeCapable;
2460
2610
  const toolchainPresent = deps.toolchainPresent ?? defaultToolchainPresent;
2461
- const resolveRoutingImpl = deps.resolveRoutingImpl ?? resolveRouting;
2462
- const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? ORCHESTRATOR_HEARTBEAT_INTERVAL_MS;
2463
- const stallMs = deps.stallMs ?? getBuildStallMs();
2464
- const maxMs = deps.maxMs ?? getBuildMaxMs();
2465
2611
  // Preconditions (ENG-165-2 / H2). Each fails fast with actionable copy rather
2466
2612
  // than spawning into an environment where the run would stall or misbehave:
2467
2613
  // - a configured project repo (nowhere to load .mcp.json/CLAUDE.md from),
@@ -2469,17 +2615,17 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2469
2615
  // - working `git worktree` support (the orchestrator isolates workers on them),
2470
2616
  // - a JS test toolchain (phase verification runs install/build/test).
2471
2617
  if (!ctx.projectDir) {
2472
- return { status: "failed", result: { error: projectDirNotConfiguredMessage() } };
2618
+ return { ok: false, result: { status: "failed", result: { error: projectDirNotConfiguredMessage() } } };
2473
2619
  }
2474
2620
  const projectDir = ctx.projectDir;
2475
2621
  if (!isGitRepo(projectDir)) {
2476
- return { status: "failed", result: { error: orchestrateNotGitRepoMessage(projectDir) } };
2622
+ return { ok: false, result: { status: "failed", result: { error: orchestrateNotGitRepoMessage(projectDir) } } };
2477
2623
  }
2478
2624
  if (!worktreeCapable(projectDir)) {
2479
- return { status: "failed", result: { error: worktreeUnavailableMessage(projectDir) } };
2625
+ return { ok: false, result: { status: "failed", result: { error: worktreeUnavailableMessage(projectDir) } } };
2480
2626
  }
2481
2627
  if (!toolchainPresent(projectDir)) {
2482
- return { status: "failed", result: { error: toolchainMissingMessage(projectDir) } };
2628
+ return { ok: false, result: { status: "failed", result: { error: toolchainMissingMessage(projectDir) } } };
2483
2629
  }
2484
2630
  // ENG-345: a build that deploys to Google Cloud checks the cloud first. Any
2485
2631
  // gap stops it before Claude is spawned (no session, no run folder) with ONE
@@ -2488,8 +2634,16 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2488
2634
  // the preflight question itself), so the build proceeds instead of asking
2489
2635
  // the same question again.
2490
2636
  if (!ctx.fix && ctx.cloud && !ctx.resume) {
2637
+ // ENG-507: the preflight deliberately keeps the machine's own gcloud config.
2638
+ // It only reads (auth list, describe, get-iam-policy) and must see the
2639
+ // signed-in account; an isolated empty folder would always report "not signed in".
2640
+ const spendTeamId = ctx.teamId;
2491
2641
  const preflight = deps.cloudPreflight ??
2492
- ((facts, repo) => runCloudPreflight(facts, repo, { execFile: defaultPreflightExecFile, now: Date.now }));
2642
+ ((facts, repo) => runCloudPreflight(facts, repo, {
2643
+ execFile: defaultPreflightExecFile,
2644
+ now: Date.now,
2645
+ ...(spendTeamId && { spendCheck: () => new ApiClient().getProjectSpendCheck(spendTeamId) }),
2646
+ }));
2493
2647
  let checks = null;
2494
2648
  try {
2495
2649
  checks = await preflight(ctx.cloud, repoFromRemote(ctx.projectRemote));
@@ -2497,18 +2651,55 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2497
2651
  catch {
2498
2652
  checks = null; // A broken preflight never blocks the build.
2499
2653
  }
2654
+ // ENG-506: over the monthly spend limit -> refuse before anything starts.
2655
+ const overLimit = checks?.find((c) => c.check === "spend-limit" && c.status === "gap");
2656
+ if (overLimit)
2657
+ return { ok: false, result: { status: "failed", result: { error: `Cloud job not started: ${overLimit.detail}` } } };
2500
2658
  if (checks) {
2501
2659
  try {
2502
- await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, formatPreflightTurn(checks));
2660
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, formatPreflightTurn(checks, ctx.cloud.provider === "aws" ? "aws" : "gcp"));
2503
2661
  }
2504
2662
  catch {
2505
2663
  // Best-effort preflight turn.
2506
2664
  }
2507
- const request = preflightNeedsInput(checks);
2665
+ const request = preflightNeedsInput(checks, ctx.cloud.provider === "aws" ? "aws" : "gcp");
2508
2666
  if (request)
2509
- return needsInputRunResult(ctx.epicId, request);
2667
+ return { ok: false, result: needsInputRunResult(ctx.epicId, request) };
2510
2668
  }
2511
2669
  }
2670
+ return { ok: true, projectDir };
2671
+ }
2672
+ /**
2673
+ * Run the orchestrator headless for a `start_execution`/`orchestrate` job
2674
+ * (ENG-165).
2675
+ *
2676
+ * Flow: validate the project repo (git repo → worktree-capable → test toolchain
2677
+ * present) → spawn the local `claude` CLI in that repo cwd with ENG-164's MCP +
2678
+ * CLAUDE.md-routing profile (H1: unattended permission mode, NOT
2679
+ * `--tools ""`/`--safe-mode`) running `@orchestrator execute epic <epicId>
2680
+ * --non-interactive` with `COMPBOX_NONINTERACTIVE=1` (H3 signal) and pxpipe's
2681
+ * `ANTHROPIC_BASE_URL` preserved → keep the machine alive with a periodic
2682
+ * heartbeat during the long run (H4) → relay a start + final turn to the mailbox
2683
+ * → on a needs-review HARD-gate marker complete as a needs-review failure naming
2684
+ * the gate (ENG-165-3); on a non-zero exit fail with the reason; on a clean run
2685
+ * complete `{ epicId }`. Never hangs.
2686
+ */
2687
+ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2688
+ // ENG-300: cancelled before it started — don't spawn at all.
2689
+ if (ctx.signal?.aborted)
2690
+ return cancelledRunResult("orchestrator");
2691
+ // ENG-352: wall clock for the run's time breakdown.
2692
+ const clockMs = deps.clockMs ?? Date.now;
2693
+ const startedAtMs = clockMs();
2694
+ const spawnImpl = deps.spawnImpl ?? spawn;
2695
+ const resolveRoutingImpl = deps.resolveRoutingImpl ?? resolveRouting;
2696
+ const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? ORCHESTRATOR_HEARTBEAT_INTERVAL_MS;
2697
+ const stallMs = deps.stallMs ?? getBuildStallMs();
2698
+ const maxMs = deps.maxMs ?? getBuildMaxMs();
2699
+ const prepared = await prepareOrchestrateRun(ctx, deps);
2700
+ if (!prepared.ok)
2701
+ return prepared.result;
2702
+ const projectDir = prepared.projectDir;
2512
2703
  // Each run gets its own branch + worktree, so it never touches the person's
2513
2704
  // checkout and always ends as a reviewable pull request.
2514
2705
  let workspace = null;
@@ -2518,6 +2709,10 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2518
2709
  const resume = ctx.fix ? undefined : ctx.resume;
2519
2710
  let resumeSessionId;
2520
2711
  let resumeFallbackWhy = null;
2712
+ // ENG-579: what the company's agent set declares the orchestrator may do.
2713
+ const orchestratorPerms = permissionsFor(deps.agentPermissions, "orchestrator");
2714
+ const protectedBranches = orchestratorPerms?.protectedBranches ?? [];
2715
+ const agentArgs = (a) => applyAgentPermissions(ctx.keyRun ? keyRunArgs(a) : a, orchestratorPerms);
2521
2716
  if (resume) {
2522
2717
  if (!resume.sessionId || !resume.runDir) {
2523
2718
  resumeFallbackWhy = "the paused run didn't keep a session to resume";
@@ -2533,6 +2728,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2533
2728
  projectDir,
2534
2729
  runDir: resume.runDir,
2535
2730
  branch: resume.branch,
2731
+ ...(protectedBranches.length > 0 && { protectedBranches }),
2536
2732
  });
2537
2733
  if (reopened.ok) {
2538
2734
  workspace = reopened.workspace;
@@ -2548,10 +2744,16 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2548
2744
  // ENG-349: never prune a folder another in-flight job of this machine is using.
2549
2745
  const active = deps.activeRunDirs ? { activeRunDirs: [...deps.activeRunDirs] } : {};
2550
2746
  const fresh = ctx.freshBranch === true ? { fresh: true } : {};
2747
+ // ENG-579: declared protected branches join the base branch in the pre-push guard.
2748
+ const guarded = protectedBranches.length > 0 ? { protectedBranches } : {};
2551
2749
  const prepared = ctx.fix
2552
- ? await deps.workspace.prepare(projectDir, ctx.epicId, { branch: ctx.fix.branch, ...active })
2553
- : deps.activeRunDirs || ctx.freshBranch === true
2554
- ? await deps.workspace.prepare(projectDir, ctx.epicId, { ...active, ...fresh })
2750
+ ? await deps.workspace.prepare(projectDir, ctx.epicId, {
2751
+ branch: ctx.fix.branch,
2752
+ ...active,
2753
+ ...guarded,
2754
+ })
2755
+ : deps.activeRunDirs || ctx.freshBranch === true || guarded.protectedBranches
2756
+ ? await deps.workspace.prepare(projectDir, ctx.epicId, { ...active, ...fresh, ...guarded })
2555
2757
  : await deps.workspace.prepare(projectDir, ctx.epicId);
2556
2758
  if (!prepared.ok) {
2557
2759
  return { status: "failed", result: { error: prepared.error } };
@@ -2594,7 +2796,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2594
2796
  ...(attachmentsNote && { replyAttachmentsNote: attachmentsNote }),
2595
2797
  ...(ctx.checkMode && { checkMode: ctx.checkMode }),
2596
2798
  });
2597
- const args = ctx.keyRun ? keyRunArgs(runArgs) : runArgs;
2799
+ const args = agentArgs(runArgs);
2598
2800
  // pxpipe (ENG-136): inject ANTHROPIC_BASE_URL when routed. COMPBOX_NONINTERACTIVE
2599
2801
  // forces the orchestrator's headless serial-in-process path (H3) even if the
2600
2802
  // prompt flag were dropped. PATH is augmented (ENG-135) so `claude` and any
@@ -2609,13 +2811,24 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2609
2811
  // ENG-346: a gh shim that refuses merges goes first on the AGENT's PATH
2610
2812
  // (the real gh is resolved before it is prepended). The runner's own
2611
2813
  // git/gh calls (push, pull request) use its own env and never see it.
2612
- PATH: withMergeGuardPath(claudeChildEnvPath(routedEnv.PATH), deps.mergeGuardDir === undefined ? join(getConfigDir(), "merge-guard") : deps.mergeGuardDir),
2814
+ PATH: withMergeGuardPath(claudeChildEnvPath(routedEnv.PATH), deps.mergeGuardDir === undefined ? join(getConfigDir(), "merge-guard") : deps.mergeGuardDir, process.platform, orchestratorPerms?.ghDeny ?? []),
2613
2815
  };
2614
2816
  // ENG-394: the agent's commits skip the repo's own hooks (orchestrator,
2615
2817
  // conflict fix and follow-up all use this env); the run's checks cover them.
2616
2818
  const agentHooksDir = makeAgentHooksDir(runDir);
2617
2819
  if (agentHooksDir)
2618
2820
  Object.assign(baseEnv, withHooksDisabled(baseEnv, agentHooksDir));
2821
+ // ENG-507: the agent (and the conflict resolver, which reuses baseEnv) gets
2822
+ // its own gcloud config folder, so it can never switch the person's login.
2823
+ if (workspace) {
2824
+ try {
2825
+ createGcloudConfigDir(workspace.dir);
2826
+ }
2827
+ catch {
2828
+ // gcloud creates the folder itself if it's missing.
2829
+ }
2830
+ Object.assign(baseEnv, withIsolatedGcloud(baseEnv, workspace.dir));
2831
+ }
2619
2832
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
2620
2833
  // H4: relay a START turn immediately so the web shows the run began even if the
2621
2834
  // orchestrator produces no stdout for minutes. postTurn failures are swallowed.
@@ -2886,11 +3099,46 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2886
3099
  // Best-effort status turn.
2887
3100
  }
2888
3101
  const noteArgs = buildOrchestratorContinueArgs(sessionId, ownerNotePrompt(ctx.epicId, notes, ctx.deferredFeatures), workspace?.baseBranch, ctx.fastMode);
2889
- result = await runOnce(ctx.keyRun ? keyRunArgs(noteArgs) : noteArgs, deadline - Date.now());
3102
+ result = await runOnce(agentArgs(noteArgs), deadline - Date.now());
2890
3103
  }
2891
3104
  return result;
2892
3105
  };
2893
- let outcome = await runDeliveringNotes(args, maxMs);
3106
+ // ENG-591: with the org's belt-engine switch on, a build runs one Claude turn
3107
+ // per belt step in this same session. An API without belt routes falls back
3108
+ // to the old single orchestrator run.
3109
+ let outcome;
3110
+ let beltRan = false;
3111
+ let beltSteps;
3112
+ if (ctx.belt === true && !ctx.fix && sessionId) {
3113
+ const beltSessionId = sessionId;
3114
+ try {
3115
+ const belt = await runBelt({
3116
+ client: ctx.mailboxClient,
3117
+ machineToken: ctx.machineToken,
3118
+ jobId: ctx.jobId,
3119
+ epicId: ctx.epicId,
3120
+ checkMode: ctx.checkMode ?? "smart",
3121
+ deadline,
3122
+ ...(ctx.signal && { signal: ctx.signal }),
3123
+ readParts: (beltRunId) => ctx.mailboxClient.readBeltParts(ctx.machineToken, beltRunId),
3124
+ postStatus: async (message) => {
3125
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, message);
3126
+ },
3127
+ runTurn: (turn) => {
3128
+ const turnArgs = buildBeltTurnArgs(beltSessionId, turn.prompt, turn.firstTurn && !resumeSessionId, workspace?.baseBranch, ctx.fastMode);
3129
+ return runDeliveringNotes(ctx.keyRun ? keyRunArgs(turnArgs) : turnArgs, turn.budgetMs);
3130
+ },
3131
+ });
3132
+ outcome = belt.result;
3133
+ beltSteps = belt.steps;
3134
+ beltRan = true;
3135
+ }
3136
+ catch (error) {
3137
+ if (!(error instanceof BeltUnsupportedError))
3138
+ throw error;
3139
+ }
3140
+ }
3141
+ outcome ??= await runDeliveringNotes(args, maxMs);
2894
3142
  // A clean exit isn't proof the epic is finished: a headless run can end its
2895
3143
  // turn early (e.g. "waiting" on a background review, or "Next I'll…"). Check
2896
3144
  // CompBox, resume the same session while features are outstanding and new
@@ -2898,7 +3146,8 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2898
3146
  // A fix run changes one pull request, not the epic's plan, so epic progress says nothing about it.
2899
3147
  // ENG-332 (M1): set when a resume was due but 60s or less of the ceiling remained.
2900
3148
  let hitCeiling = false;
2901
- if (outcome.status === "done" && !ctx.fix) {
3149
+ // A belt run decides completion itself (every step done), so it skips the resume loop.
3150
+ if (outcome.status === "done" && !ctx.fix && !beltRan) {
2902
3151
  const readProgress = deps.epicProgress ??
2903
3152
  (async () => {
2904
3153
  try {
@@ -2936,7 +3185,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2936
3185
  }
2937
3186
  const before = progress.completedFeatures;
2938
3187
  const continueArgs = buildOrchestratorContinueArgs(sessionId, orchestratorContinuePrompt(ctx.epicId, progress.completedFeatures, progress.totalFeatures, ctx.deferredFeatures, ctx.checkMode), workspace?.baseBranch, ctx.fastMode);
2939
- outcome = await runDeliveringNotes(ctx.keyRun ? keyRunArgs(continueArgs) : continueArgs, deadline - Date.now());
3188
+ outcome = await runDeliveringNotes(agentArgs(continueArgs), deadline - Date.now());
2940
3189
  if (outcome.status !== "done")
2941
3190
  break;
2942
3191
  progress = await readProgress();
@@ -3097,6 +3346,9 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
3097
3346
  startedAtMs,
3098
3347
  endedAtMs: clockMs(),
3099
3348
  fastMode: ctx.fastMode === true ? { requested: true, used: fastModeUsed } : null,
3349
+ // ENG-591: only the orchestrate run reports a path; fix runs never use the belt.
3350
+ ...(!ctx.fix && { path: beltRan ? "belt" : "old" }),
3351
+ ...(beltSteps && { beltSteps }),
3100
3352
  });
3101
3353
  // H4: relay a FINAL turn summarizing the outcome (best-effort).
3102
3354
  try {
@@ -3114,7 +3366,14 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
3114
3366
  // Best-effort final turn.
3115
3367
  }
3116
3368
  // Attached after the final turn so a failure summary leads with the error.
3117
- outcome.result = { ...outcome.result, timings };
3369
+ // ENG-514: routing decision + measured savings (null = unknown, never fails the run).
3370
+ const runEndedAtMs = clockMs();
3371
+ const tokensSaved = routing.mode === "proxy" ? await readMeasuredTokensSaved(startedAtMs, runEndedAtMs) : null;
3372
+ outcome.result = {
3373
+ ...outcome.result,
3374
+ timings,
3375
+ routing: toRunRouting(routing, tokensSaved),
3376
+ };
3118
3377
  return outcome;
3119
3378
  }
3120
3379
  /**