@mycompbox/compbox-cli 1.21.18 → 1.21.20

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 (91) hide show
  1. package/.tsbuildinfo +1 -1
  2. package/agents/internal/feature-worker.md +311 -0
  3. package/agents/orchestrator.md +1203 -0
  4. package/agents/planner.md +694 -0
  5. package/agents/request-formulator.md +450 -0
  6. package/commands/run.d.ts +4 -1
  7. package/commands/run.d.ts.map +1 -1
  8. package/commands/run.js +116 -15
  9. package/commands/run.js.map +1 -1
  10. package/commands/workspace.d.ts +41 -2
  11. package/commands/workspace.d.ts.map +1 -1
  12. package/commands/workspace.js +148 -7
  13. package/commands/workspace.js.map +1 -1
  14. package/index.js +3193 -453
  15. package/package.json +1 -1
  16. package/utils/agent-invoker.d.ts +157 -13
  17. package/utils/agent-invoker.d.ts.map +1 -1
  18. package/utils/agent-invoker.js +587 -87
  19. package/utils/agent-invoker.js.map +1 -1
  20. package/utils/agent-permissions.d.ts +44 -0
  21. package/utils/agent-permissions.d.ts.map +1 -0
  22. package/utils/agent-permissions.js +229 -0
  23. package/utils/agent-permissions.js.map +1 -0
  24. package/utils/agent-store.d.ts +141 -0
  25. package/utils/agent-store.d.ts.map +1 -0
  26. package/utils/agent-store.js +493 -0
  27. package/utils/agent-store.js.map +1 -0
  28. package/utils/agent-trial.d.ts +34 -0
  29. package/utils/agent-trial.d.ts.map +1 -0
  30. package/utils/agent-trial.js +180 -0
  31. package/utils/agent-trial.js.map +1 -0
  32. package/utils/api-client.d.ts +11 -0
  33. package/utils/api-client.d.ts.map +1 -1
  34. package/utils/api-client.js +31 -0
  35. package/utils/api-client.js.map +1 -1
  36. package/utils/belt-engine.d.ts +72 -0
  37. package/utils/belt-engine.d.ts.map +1 -0
  38. package/utils/belt-engine.js +136 -0
  39. package/utils/belt-engine.js.map +1 -0
  40. package/utils/bundled-agents.d.ts +29 -0
  41. package/utils/bundled-agents.d.ts.map +1 -0
  42. package/utils/bundled-agents.js +73 -0
  43. package/utils/bundled-agents.js.map +1 -0
  44. package/utils/cloud-preflight.d.ts +26 -4
  45. package/utils/cloud-preflight.d.ts.map +1 -1
  46. package/utils/cloud-preflight.js +90 -7
  47. package/utils/cloud-preflight.js.map +1 -1
  48. package/utils/custom-agent-contract.d.ts +44 -0
  49. package/utils/custom-agent-contract.d.ts.map +1 -0
  50. package/utils/custom-agent-contract.js +122 -0
  51. package/utils/custom-agent-contract.js.map +1 -0
  52. package/utils/custom-agent-permissions.d.ts +48 -0
  53. package/utils/custom-agent-permissions.d.ts.map +1 -0
  54. package/utils/custom-agent-permissions.js +109 -0
  55. package/utils/custom-agent-permissions.js.map +1 -0
  56. package/utils/custom-agent-runner.d.ts +99 -0
  57. package/utils/custom-agent-runner.d.ts.map +1 -0
  58. package/utils/custom-agent-runner.js +227 -0
  59. package/utils/custom-agent-runner.js.map +1 -0
  60. package/utils/custom-agent-sync.d.ts +59 -0
  61. package/utils/custom-agent-sync.d.ts.map +1 -0
  62. package/utils/custom-agent-sync.js +197 -0
  63. package/utils/custom-agent-sync.js.map +1 -0
  64. package/utils/key-run.d.ts +9 -0
  65. package/utils/key-run.d.ts.map +1 -1
  66. package/utils/key-run.js +18 -0
  67. package/utils/key-run.js.map +1 -1
  68. package/utils/mailbox-client.d.ts +115 -2
  69. package/utils/mailbox-client.d.ts.map +1 -1
  70. package/utils/mailbox-client.js +114 -6
  71. package/utils/mailbox-client.js.map +1 -1
  72. package/utils/merge-guard.d.ts +48 -7
  73. package/utils/merge-guard.d.ts.map +1 -1
  74. package/utils/merge-guard.js +152 -17
  75. package/utils/merge-guard.js.map +1 -1
  76. package/utils/pxpipe-savings.d.ts +12 -0
  77. package/utils/pxpipe-savings.d.ts.map +1 -0
  78. package/utils/pxpipe-savings.js +68 -0
  79. package/utils/pxpipe-savings.js.map +1 -0
  80. package/utils/run-timings.d.ts +3 -0
  81. package/utils/run-timings.d.ts.map +1 -1
  82. package/utils/run-timings.js +2 -0
  83. package/utils/run-timings.js.map +1 -1
  84. package/utils/run-workspace.d.ts +18 -0
  85. package/utils/run-workspace.d.ts.map +1 -1
  86. package/utils/run-workspace.js +46 -5
  87. package/utils/run-workspace.js.map +1 -1
  88. package/utils/wrap-up.d.ts +8 -0
  89. package/utils/wrap-up.d.ts.map +1 -1
  90. package/utils/wrap-up.js +24 -2
  91. package/utils/wrap-up.js.map +1 -1
@@ -16,15 +16,17 @@
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";
22
- import { randomUUID } from "node:crypto";
23
- import { copyFileSync, existsSync, mkdirSync, mkdtempSync } from "node:fs";
23
+ import { createHash, randomUUID } from "node:crypto";
24
+ import { copyFileSync, existsSync, mkdirSync, mkdtempSync, readdirSync, readFileSync, renameSync, writeFileSync } 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,217 @@ 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
+ }
1110
+ /**
1111
+ * Split a Markdown agent file into its YAML frontmatter and body. Handles CRLF
1112
+ * line endings, quoted values and indented continuation lines (the built-in
1113
+ * agents wrap long `description:` values). A file without frontmatter is all body.
1114
+ */
1115
+ export function parseAgentFile(content) {
1116
+ const text = content.replace(/^\uFEFF/, "").replace(/\r\n?/g, "\n");
1117
+ const fields = {};
1118
+ if (!text.startsWith("---\n"))
1119
+ return { fields, body: text.trim() };
1120
+ const end = text.indexOf("\n---", 4);
1121
+ if (end === -1)
1122
+ return { fields, body: text.trim() };
1123
+ const afterFence = text.indexOf("\n", end + 4);
1124
+ const body = afterFence === -1 ? "" : text.slice(afterFence + 1);
1125
+ let key = null;
1126
+ for (const line of text.slice(4, end).split("\n")) {
1127
+ const m = /^([A-Za-z_][\w-]*):\s*(.*)$/.exec(line);
1128
+ if (m && !/^\s/.test(line)) {
1129
+ key = m[1] ?? null;
1130
+ if (key)
1131
+ fields[key] = (m[2] ?? "").trim();
1132
+ }
1133
+ else if (key && line.trim() !== "") {
1134
+ fields[key] = `${fields[key] ?? ""} ${line.trim()}`.trim();
1135
+ }
1136
+ }
1137
+ for (const [k, v] of Object.entries(fields)) {
1138
+ const q = /^"(.*)"$/s.exec(v) ?? /^'(.*)'$/s.exec(v);
1139
+ fields[k] = q?.[1] ?? v;
1140
+ }
1141
+ return { fields, body: body.trim() };
1142
+ }
1143
+ /** Comma/space separated `tools:` value (or a `[a, b]` list) → tool names. */
1144
+ function parseToolsField(value) {
1145
+ if (!value)
1146
+ return undefined;
1147
+ const tools = value
1148
+ .replace(/^\[|\]$/g, "")
1149
+ .split(/[,\s]+/)
1150
+ .map((t) => t.replace(/^["']|["']$/g, "").trim())
1151
+ .filter(Boolean);
1152
+ return tools.length > 0 ? tools : undefined;
1153
+ }
1154
+ export function buildAgentDefinitionArgs(agentDir, mainAgent, existingSystemPrompt, opts = {}) {
1155
+ const mainPath = join(agentDir, `${mainAgent}.md`);
1156
+ if (!existsSync(mainPath)) {
1157
+ throw new Error(`The ${mainAgent} agent file is missing from the agent set (${mainPath}).`);
1158
+ }
1159
+ const main = parseAgentFile(readFileSync(mainPath, "utf8"));
1160
+ const systemPrompt = [main.body, existingSystemPrompt?.trim()]
1161
+ .filter((s) => Boolean(s))
1162
+ .join("\n\n");
1163
+ const agents = {};
1164
+ const addFrom = (dir) => {
1165
+ if (!existsSync(dir))
1166
+ return;
1167
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
1168
+ if (!entry.isFile() || !entry.name.endsWith(".md"))
1169
+ continue;
1170
+ const name = entry.name.slice(0, -".md".length);
1171
+ if (dir === agentDir && name === mainAgent)
1172
+ continue;
1173
+ const parsed = parseAgentFile(readFileSync(join(dir, entry.name), "utf8"));
1174
+ if (!parsed.body)
1175
+ continue;
1176
+ const tools = parseToolsField(parsed.fields.tools);
1177
+ agents[name] = {
1178
+ description: [parsed.fields.description, parsed.fields.name].find(Boolean) ?? name,
1179
+ prompt: parsed.body,
1180
+ ...(tools && { tools }),
1181
+ ...(parsed.fields.model && { model: parsed.fields.model }),
1182
+ };
1183
+ }
1184
+ };
1185
+ addFrom(agentDir);
1186
+ addFrom(join(agentDir, "internal"));
1187
+ const spill = opts.spillDir ?? join(tmpdir(), "compbox-agent-args");
1188
+ const max = opts.maxInlineChars ?? AGENT_ARG_MAX_INLINE_CHARS;
1189
+ const out = [];
1190
+ if (systemPrompt) {
1191
+ out.push(...(systemPrompt.length > max
1192
+ ? ["--append-system-prompt-file", spillAgentArg(spill, systemPrompt, "md")]
1193
+ : ["--append-system-prompt", systemPrompt]));
1194
+ }
1195
+ if (Object.keys(agents).length > 0) {
1196
+ const json = JSON.stringify(agents);
1197
+ // `claude --agents` takes a file path in --print mode (every headless run).
1198
+ out.push("--agents", json.length > max ? spillAgentArg(spill, json, "json") : json);
1199
+ }
1200
+ return out;
1201
+ }
1202
+ /**
1203
+ * Longest value passed inline. Windows caps a whole command line near 32K
1204
+ * characters, so anything larger goes through a file instead.
1205
+ */
1206
+ export const AGENT_ARG_MAX_INLINE_CHARS = 24_000;
1207
+ /**
1208
+ * Write an oversized agent argument to a content-addressed file outside the
1209
+ * repo (never `./.claude`) and return its path. Same content → same file, so
1210
+ * repeated runs reuse it instead of piling up copies.
1211
+ */
1212
+ function spillAgentArg(dir, content, ext) {
1213
+ mkdirSync(dir, { recursive: true, mode: 0o700 });
1214
+ const hash = createHash("sha256").update(content).digest("hex").slice(0, 32);
1215
+ const file = join(dir, `${hash}.${ext}`);
1216
+ if (!existsSync(file)) {
1217
+ const tmp = `${file}.${String(process.pid)}.${randomUUID()}.tmp`;
1218
+ writeFileSync(tmp, content, { mode: 0o600 });
1219
+ renameSync(tmp, file);
1220
+ }
1221
+ return file;
1222
+ }
1223
+ /**
1224
+ * ENG-657: add the agent definitions to an already-built `claude` argv. Any
1225
+ * existing `--append-system-prompt` values (e.g. the headless reminder) are
1226
+ * folded into the single system prompt the helper builds. Without an agent
1227
+ * set (`agentDir` undefined) the args are returned unchanged.
1228
+ */
1229
+ export function withAgentDefinitions(args, agentDir, mainAgent, opts = {}) {
1230
+ if (!agentDir)
1231
+ return args;
1232
+ const kept = [];
1233
+ const existing = [];
1234
+ let takeNext = false;
1235
+ for (const [i, a] of args.entries()) {
1236
+ if (takeNext) {
1237
+ existing.push(a);
1238
+ takeNext = false;
1239
+ }
1240
+ else if (a === "--append-system-prompt" && i + 1 < args.length) {
1241
+ takeNext = true;
1242
+ }
1243
+ else {
1244
+ kept.push(a);
1245
+ }
1246
+ }
1247
+ return [
1248
+ ...kept,
1249
+ ...buildAgentDefinitionArgs(agentDir, mainAgent, existing.join("\n\n") || undefined, opts),
1250
+ ];
1251
+ }
1252
+ /**
1253
+ * ENG-658: check, before anything is spawned, that the main agent's definition
1254
+ * exists in the laid-out agent set and has a non-empty body. Returns a readable
1255
+ * error naming the missing file and where the set came from, or null when the
1256
+ * definition is usable (or when no agent set is in use).
1257
+ */
1258
+ export function missingAgentDefinitionMessage(agentDir, mainAgent, source) {
1259
+ if (!agentDir)
1260
+ return null;
1261
+ const rel = `${mainAgent}.md`;
1262
+ const where = source ? ` (agent set source: ${source})` : "";
1263
+ const fix = "Reinstall the CompBox CLI, or reconnect so the agent set can be downloaded again.";
1264
+ const mainPath = join(agentDir, rel);
1265
+ if (!existsSync(mainPath)) {
1266
+ return `Built-in agent definition missing: ${rel}${where}. Expected it at ${mainPath}. ${fix}`;
1267
+ }
1268
+ let body;
1269
+ try {
1270
+ body = parseAgentFile(readFileSync(mainPath, "utf8")).body;
1271
+ }
1272
+ catch (error) {
1273
+ return `Built-in agent definition unreadable: ${rel}${where}: ${error instanceof Error ? error.message : String(error)}. ${fix}`;
1274
+ }
1275
+ if (!body.trim()) {
1276
+ return `Built-in agent definition is empty: ${rel}${where}. ${fix}`;
1277
+ }
1278
+ return null;
1279
+ }
1094
1280
  /**
1095
1281
  * Build the `claude` argv for a headless planner run (H1). Pure + exported so a
1096
1282
  * unit test can assert the exact command shape: the `@planner` routing prompt,
@@ -1101,10 +1287,18 @@ async function settleKeyRun(ctx, keyRun, stdout) {
1101
1287
  * account default apply — pxpipe routing rides on ANTHROPIC_BASE_URL, not the
1102
1288
  * model name).
1103
1289
  */
1104
- export function buildPlannerArgs(epicRequestId) {
1290
+ export function buildPlannerArgs(epicRequestId, resume = {}) {
1291
+ // ENG-521: a retry resumes from the failed stage and fills in the epic an
1292
+ // earlier run already created, instead of re-planning from scratch.
1293
+ const stage = parsePlanningStage(resume.resumeFromStage);
1294
+ const epicId = parseUuid(resume.epicId);
1295
+ const resumeFlags = [
1296
+ ...(stage ? [`--resume-from ${stage}`] : []),
1297
+ ...(epicId ? [`--epic ${epicId}`] : []),
1298
+ ].join(" ");
1105
1299
  return [
1106
1300
  "-p",
1107
- `@planner --from-request ${epicRequestId} --gates=auto --non-interactive`,
1301
+ `@planner --from-request ${epicRequestId}${resumeFlags ? ` ${resumeFlags}` : ""} --gates=auto --non-interactive`,
1108
1302
  // H1: an unattended permission mode so tool use in this print-mode run never
1109
1303
  // blocks on an interactive "allow?" prompt (the interview path is safe only
1110
1304
  // because it grants ZERO tools; this path grants the full MCP surface).
@@ -1272,6 +1466,125 @@ async function fetchConvertedEpicId(apiBaseUrl, userApiToken, epicRequestId, fet
1272
1466
  return null;
1273
1467
  }
1274
1468
  }
1469
+ /** The planner pipeline stages, in order (mirrors the API's planningStageNames). */
1470
+ const PLANNING_STAGES = ["ANALYZE", "DECOMPOSE", "DETAIL", "EVALUATE", "VERIFY"];
1471
+ /** Longest failure reason the planning-progress endpoint accepts (error.message max). */
1472
+ const PLANNING_FAILURE_MESSAGE_MAX = 1000;
1473
+ function isPlanningStage(value) {
1474
+ return typeof value === "string" && PLANNING_STAGES.includes(value);
1475
+ }
1476
+ /**
1477
+ * ENG-520: the last planning stage the planner reported for an Epic Request
1478
+ * (its `planningState.currentStage`), or null when it never reported one or the
1479
+ * lookup fails. `planningState` may arrive as a JSON string or a parsed object.
1480
+ */
1481
+ export async function fetchPlanningStage(apiBaseUrl, userApiToken, epicRequestId, fetchImpl) {
1482
+ try {
1483
+ const res = await fetchImpl(`${apiBaseUrl.replace(/\/+$/, "")}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}`, { headers: { Authorization: `Bearer ${userApiToken}` } });
1484
+ if (!res.ok)
1485
+ return null;
1486
+ const body = (await res.json());
1487
+ let state = body.data?.planningState;
1488
+ if (typeof state === "string") {
1489
+ try {
1490
+ state = JSON.parse(state);
1491
+ }
1492
+ catch {
1493
+ return null;
1494
+ }
1495
+ }
1496
+ if (!state || typeof state !== "object")
1497
+ return null;
1498
+ const stage = state.currentStage;
1499
+ return isPlanningStage(stage) ? stage : null;
1500
+ }
1501
+ catch {
1502
+ return null;
1503
+ }
1504
+ }
1505
+ /**
1506
+ * ENG-520: tell the server planning failed — at the stage the planner last
1507
+ * reported (ANALYZE when it never reported one) — with a readable reason, so
1508
+ * the idea doesn't sit in "planning" forever when the local planner dies.
1509
+ *
1510
+ * Best-effort: never throws. Returns whether the server accepted the report; a
1511
+ * rejected or unreachable report is logged and the runner carries on.
1512
+ */
1513
+ export async function reportPlanningFailure(apiBaseUrl, userApiToken, epicRequestId, reason, fetchImpl, knownStage) {
1514
+ try {
1515
+ const stage = knownStage ??
1516
+ (await fetchPlanningStage(apiBaseUrl, userApiToken, epicRequestId, fetchImpl)) ??
1517
+ "ANALYZE";
1518
+ const message = reason.length > PLANNING_FAILURE_MESSAGE_MAX
1519
+ ? `${reason.slice(0, PLANNING_FAILURE_MESSAGE_MAX - 1)}…`
1520
+ : reason;
1521
+ const res = await fetchImpl(`${apiBaseUrl.replace(/\/+$/, "")}/api/v1/epic-requests/${encodeURIComponent(epicRequestId)}/planning-progress`, {
1522
+ method: "PATCH",
1523
+ headers: {
1524
+ Authorization: `Bearer ${userApiToken}`,
1525
+ "Content-Type": "application/json",
1526
+ },
1527
+ body: JSON.stringify({ stage, status: "failed", error: { message } }),
1528
+ });
1529
+ if (!res.ok) {
1530
+ console.warn(` ⚠ Could not report the planning failure for ${epicRequestId} (HTTP ${String(res.status)}).`);
1531
+ return false;
1532
+ }
1533
+ return true;
1534
+ }
1535
+ catch (error) {
1536
+ console.warn(` ⚠ Could not report the planning failure for ${epicRequestId}: ${error instanceof Error ? error.message : String(error)}`);
1537
+ return false;
1538
+ }
1539
+ }
1540
+ /** Short, readable tail of the planner's stderr to append to a failure reason. */
1541
+ function plannerOutputTail(text, max = 300) {
1542
+ const trimmed = text.trim();
1543
+ if (!trimmed)
1544
+ return "";
1545
+ return trimmed.length > max ? `…${trimmed.slice(-max)}` : trimmed;
1546
+ }
1547
+ /** ENG-658: how much planner stderr is kept for failure messages (bytes, tail). */
1548
+ export const PLANNER_STDERR_TAIL_MAX = 4096;
1549
+ /** ENG-658: append a chunk to a stderr buffer, keeping only the last `max` chars. */
1550
+ export function appendBoundedTail(buf, chunk, max = PLANNER_STDERR_TAIL_MAX) {
1551
+ const next = buf + chunk;
1552
+ return next.length > max ? next.slice(-max) : next;
1553
+ }
1554
+ /**
1555
+ * ENG-658: a readable reason for a planner run that ended without an epic —
1556
+ * exit code, elapsed time, the tail of stderr and the first stdout lines, plus
1557
+ * a hint when the planner never reported a planning stage (which usually means
1558
+ * Claude did not load the planner agent at all).
1559
+ */
1560
+ export function describePlannerNoEpic(opts) {
1561
+ const exit = opts.signal
1562
+ ? `stopped by ${opts.signal}`
1563
+ : `exit code ${String(opts.code ?? "null")}`;
1564
+ const secs = Math.max(0, Math.round(opts.elapsedMs / 1000));
1565
+ const parts = [
1566
+ `The planner finished but no epic was produced (${exit}, after ${String(secs)}s).`,
1567
+ ];
1568
+ if (!opts.reportedStage) {
1569
+ parts.push("The planner never reported a planning stage — Claude probably did not load the planner agent.");
1570
+ }
1571
+ else {
1572
+ parts.push(`Last reported stage: ${opts.reportedStage}.`);
1573
+ }
1574
+ const err = plannerOutputTail(opts.stderr);
1575
+ if (err)
1576
+ parts.push(`stderr: ${err}`);
1577
+ const head = opts.stdout
1578
+ .split(/\r?\n/)
1579
+ .map((l) => l.trim())
1580
+ .filter(Boolean)
1581
+ .slice(0, 20)
1582
+ .join(" | ");
1583
+ if (head)
1584
+ parts.push(`stdout: ${head.length > 300 ? `${head.slice(0, 300)}…` : head}`);
1585
+ parts.push("It may need human review.");
1586
+ return parts.join(" ");
1587
+ }
1275
1588
  /**
1276
1589
  * Reduce an epic's API `complianceScore` (parsed object, or a JSON string from
1277
1590
  * older servers) to the fields the planner runner needs. Returns null when no
@@ -1391,11 +1704,18 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1391
1704
  if (!isGitRepo(ctx.projectDir)) {
1392
1705
  return { status: "failed", result: { error: projectDirNotGitRepoMessage(ctx.projectDir) } };
1393
1706
  }
1707
+ // ENG-658: a missing/empty planner definition fails before anything spawns.
1708
+ const missingPlanner = missingAgentDefinitionMessage(deps.agentDir, "planner", deps.agentSource);
1709
+ if (missingPlanner) {
1710
+ return { status: "failed", result: { error: missingPlanner } };
1711
+ }
1394
1712
  const routing = await resolveRoutingImpl();
1713
+ const keyRunStartedAtMs = Date.now();
1395
1714
  const command = resolveClaudeBinary() ?? "claude";
1396
- const args = ctx.keyRun
1397
- ? keyRunArgs(buildPlannerArgs(ctx.epicRequestId))
1398
- : buildPlannerArgs(ctx.epicRequestId);
1715
+ // ENG-579: the planner's declared tool limits replace bypassPermissions where set.
1716
+ // ENG-657: the verified agent set's planner + sub-agents go in explicitly.
1717
+ const plannerArgs = withAgentDefinitions(buildPlannerArgs(ctx.epicRequestId, ctx), deps.agentDir, "planner");
1718
+ const args = applyAgentPermissions(ctx.keyRun ? keyRunArgs(plannerArgs) : plannerArgs, permissionsFor(deps.agentPermissions, "planner"));
1399
1719
  // pxpipe (ENG-136): inject ANTHROPIC_BASE_URL when routed. COMPBOX_NONINTERACTIVE
1400
1720
  // forces the planner's headless path even if the prompt flag were dropped. PATH
1401
1721
  // is augmented (ENG-135) so `claude` and any helpers it spawns resolve.
@@ -1418,6 +1738,10 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1418
1738
  catch {
1419
1739
  // Best-effort start turn.
1420
1740
  }
1741
+ // ENG-520: when the planner dies (non-zero exit, signal, timeout) or exits
1742
+ // before reaching VERIFY, tell the server planning failed so the idea doesn't
1743
+ // stay stuck in "planning". Set on those paths, sent after the run settles.
1744
+ let planningFailure = null;
1421
1745
  const outcome = await new Promise((resolve) => {
1422
1746
  let stdout = "";
1423
1747
  let stderr = "";
@@ -1458,6 +1782,11 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1458
1782
  };
1459
1783
  const timer = setTimeout(() => {
1460
1784
  killProcessGroupNow(child, deps.processGroup);
1785
+ if (!settled && !cancelled) {
1786
+ planningFailure = {
1787
+ reason: `The planner timed out after ${String(Math.round(timeoutMs / 60_000))} minutes and was stopped.`,
1788
+ };
1789
+ }
1461
1790
  finish({
1462
1791
  status: "failed",
1463
1792
  result: {
@@ -1469,13 +1798,20 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1469
1798
  stdout += chunk.toString("utf-8");
1470
1799
  });
1471
1800
  child.stderr.on("data", (chunk) => {
1472
- stderr += chunk.toString("utf-8");
1801
+ stderr = appendBoundedTail(stderr, chunk.toString("utf-8"));
1473
1802
  });
1474
1803
  child.on("error", (error) => {
1475
1804
  if (cancelled) {
1476
1805
  finish(cancelledRunResult("planner"));
1477
1806
  return;
1478
1807
  }
1808
+ if (!settled) {
1809
+ planningFailure = {
1810
+ reason: error.code === "ENOENT"
1811
+ ? "The planner could not start: the Claude CLI was not found on this computer."
1812
+ : `The planner could not start: ${error.message || "spawn failed"}.`,
1813
+ };
1814
+ }
1479
1815
  finish({
1480
1816
  status: "failed",
1481
1817
  result: {
@@ -1485,10 +1821,10 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1485
1821
  },
1486
1822
  });
1487
1823
  });
1488
- child.on("close", (code) => {
1824
+ child.on("close", (code, exitSignal) => {
1489
1825
  void (async () => {
1490
1826
  if (ctx.keyRun)
1491
- stdout = await settleKeyRun(ctx, ctx.keyRun, stdout);
1827
+ stdout = await settleKeyRun(ctx, ctx.keyRun, stdout, routing, keyRunStartedAtMs);
1492
1828
  if (cancelled) {
1493
1829
  finish(cancelledRunResult("planner"));
1494
1830
  return;
@@ -1510,12 +1846,22 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1510
1846
  return;
1511
1847
  }
1512
1848
  if (code !== 0) {
1849
+ // ENG-520: a crash or kill is reported to the server as a planning failure.
1850
+ if (!settled) {
1851
+ const tail = plannerOutputTail(stderr);
1852
+ const base = code === null && exitSignal
1853
+ ? `The planner was stopped (${exitSignal}) before it finished.`
1854
+ : `The planner exited with code ${String(code ?? "null")} before it finished.`;
1855
+ planningFailure = { reason: tail ? `${base} ${tail}` : base };
1856
+ }
1513
1857
  finish({
1514
1858
  status: "failed",
1515
1859
  result: {
1516
1860
  error: stderr.trim() ||
1517
1861
  stdout.trim().slice(-PLANNER_FINAL_TURN_MAX_CHARS) ||
1518
- `The planner exited with code ${String(code ?? "null")}.`,
1862
+ (code === null && exitSignal
1863
+ ? `The planner was stopped (${exitSignal}).`
1864
+ : `The planner exited with code ${String(code ?? "null")}.`),
1519
1865
  },
1520
1866
  });
1521
1867
  return;
@@ -1525,13 +1871,30 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1525
1871
  // independent of stdout formatting.
1526
1872
  const epicId = await fetchConvertedEpicId(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicRequestId, fetchImpl);
1527
1873
  if (!epicId) {
1874
+ // ENG-520: a clean exit that never reached VERIFY means the planner
1875
+ // stopped early — report it so the idea doesn't stay "planning".
1876
+ const lastStage = await fetchPlanningStage(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicRequestId, fetchImpl);
1877
+ const noEpicReason = describePlannerNoEpic({
1878
+ code,
1879
+ signal: exitSignal ?? null,
1880
+ elapsedMs: Date.now() - keyRunStartedAtMs,
1881
+ stdout,
1882
+ stderr,
1883
+ reportedStage: lastStage,
1884
+ });
1885
+ if (!settled && lastStage !== "VERIFY") {
1886
+ planningFailure = {
1887
+ reason: noEpicReason,
1888
+ stage: lastStage ?? "ANALYZE",
1889
+ };
1890
+ }
1528
1891
  // ENG-287-2: an unconverted ER is never a success — surface it for review.
1529
1892
  finish({
1530
1893
  status: "failed",
1531
1894
  result: {
1532
1895
  needsHumanReview: true,
1533
1896
  stage: "VERIFY",
1534
- error: "The planner finished but no epic was produced (the Epic Request was not converted to an epic). It may need human review.",
1897
+ error: noEpicReason,
1535
1898
  },
1536
1899
  });
1537
1900
  return;
@@ -1558,6 +1921,12 @@ export async function invokeStartExecutionPlan(ctx, deps = {}) {
1558
1921
  })();
1559
1922
  });
1560
1923
  });
1924
+ // ENG-520: report the failure to the server (best-effort — never throws).
1925
+ // TS can't see the closure assignments, so read it through a typed alias.
1926
+ const failure = planningFailure;
1927
+ if (failure && outcome.status === "failed") {
1928
+ await reportPlanningFailure(ctx.apiBaseUrl, ctx.userApiToken, ctx.epicRequestId, failure.reason, fetchImpl, failure.stage);
1929
+ }
1561
1930
  // H4: relay a FINAL turn summarizing the outcome (best-effort).
1562
1931
  try {
1563
1932
  await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, buildPlannerFinalTurn(outcome));
@@ -1641,9 +2010,18 @@ export async function invokeStartExecutionRefine(ctx, deps = {}) {
1641
2010
  if (!isGitRepo(ctx.projectDir)) {
1642
2011
  return { status: "failed", result: { error: projectDirNotGitRepoMessage(ctx.projectDir) } };
1643
2012
  }
2013
+ // ENG-658: a missing/empty planner definition fails before anything spawns.
2014
+ const missingPlanner = missingAgentDefinitionMessage(deps.agentDir, "planner", deps.agentSource);
2015
+ if (missingPlanner) {
2016
+ return { status: "failed", result: { error: missingPlanner } };
2017
+ }
1644
2018
  const routing = await resolveRoutingImpl();
2019
+ const keyRunStartedAtMs = Date.now();
1645
2020
  const command = resolveClaudeBinary() ?? "claude";
1646
- const args = ctx.keyRun ? keyRunArgs(buildRefineArgs(ctx.epicId)) : buildRefineArgs(ctx.epicId);
2021
+ // ENG-579: the planner's declared tool limits replace bypassPermissions where set.
2022
+ // ENG-657: the verified agent set's planner + sub-agents go in explicitly.
2023
+ const refineArgs = withAgentDefinitions(buildRefineArgs(ctx.epicId), deps.agentDir, "planner");
2024
+ const args = applyAgentPermissions(ctx.keyRun ? keyRunArgs(refineArgs) : refineArgs, permissionsFor(deps.agentPermissions, "planner"));
1647
2025
  const baseEnv = buildRefineEnv(claudeSpawnEnv(process.env, routing), ctx.notes);
1648
2026
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
1649
2027
  try {
@@ -1702,7 +2080,7 @@ export async function invokeStartExecutionRefine(ctx, deps = {}) {
1702
2080
  stdout += chunk.toString("utf-8");
1703
2081
  });
1704
2082
  child.stderr.on("data", (chunk) => {
1705
- stderr += chunk.toString("utf-8");
2083
+ stderr = appendBoundedTail(stderr, chunk.toString("utf-8"));
1706
2084
  });
1707
2085
  child.on("error", (error) => {
1708
2086
  if (cancelled) {
@@ -1721,7 +2099,7 @@ export async function invokeStartExecutionRefine(ctx, deps = {}) {
1721
2099
  child.on("close", (code) => {
1722
2100
  void (async () => {
1723
2101
  if (ctx.keyRun)
1724
- stdout = await settleKeyRun(ctx, ctx.keyRun, stdout);
2102
+ stdout = await settleKeyRun(ctx, ctx.keyRun, stdout, routing, keyRunStartedAtMs);
1725
2103
  if (cancelled) {
1726
2104
  finish(cancelledRunResult("planner"));
1727
2105
  return;
@@ -2067,6 +2445,26 @@ export function followUpContext(message) {
2067
2445
  ].join("\n\n");
2068
2446
  }
2069
2447
  /** Claude CLI args that resume the orchestrator's session with {@link orchestratorContinuePrompt}. */
2448
+ /**
2449
+ * ENG-591: args for one belt step's Claude turn. The first turn starts the
2450
+ * session under its known id; later turns resume it.
2451
+ */
2452
+ export function buildBeltTurnArgs(sessionId, prompt, startSession, baseBranch, fastMode) {
2453
+ if (!startSession)
2454
+ return buildOrchestratorContinueArgs(sessionId, prompt, baseBranch, fastMode);
2455
+ return [
2456
+ "-p",
2457
+ prompt,
2458
+ "--session-id",
2459
+ sessionId,
2460
+ "--append-system-prompt",
2461
+ HEADLESS_ORCHESTRATE_REMINDER,
2462
+ "--permission-mode",
2463
+ "bypassPermissions",
2464
+ ...mergeGuardArgs(baseBranch),
2465
+ ...fastModeArgs(fastMode),
2466
+ ];
2467
+ }
2070
2468
  export function buildOrchestratorContinueArgs(sessionId, prompt, baseBranch, fastMode) {
2071
2469
  return [
2072
2470
  "-p",
@@ -2433,35 +2831,14 @@ export function detectNeedsInput(stdout, stderr = "") {
2433
2831
  return { kind: "input", request };
2434
2832
  }
2435
2833
  /**
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.
2834
+ * The checks every orchestrated build makes before Claude is spawned (shared by
2835
+ * the orchestrator path and the belt engine, ENG-590): the project preconditions
2836
+ * and, for a cloud build, the cloud preflight.
2449
2837
  */
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;
2838
+ export async function prepareOrchestrateRun(ctx, deps = {}) {
2458
2839
  const isGitRepo = deps.isGitRepo ?? isGitRepoDir;
2459
2840
  const worktreeCapable = deps.worktreeCapable ?? defaultWorktreeCapable;
2460
2841
  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
2842
  // Preconditions (ENG-165-2 / H2). Each fails fast with actionable copy rather
2466
2843
  // than spawning into an environment where the run would stall or misbehave:
2467
2844
  // - a configured project repo (nowhere to load .mcp.json/CLAUDE.md from),
@@ -2469,17 +2846,22 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2469
2846
  // - working `git worktree` support (the orchestrator isolates workers on them),
2470
2847
  // - a JS test toolchain (phase verification runs install/build/test).
2471
2848
  if (!ctx.projectDir) {
2472
- return { status: "failed", result: { error: projectDirNotConfiguredMessage() } };
2849
+ return { ok: false, result: { status: "failed", result: { error: projectDirNotConfiguredMessage() } } };
2473
2850
  }
2474
2851
  const projectDir = ctx.projectDir;
2475
2852
  if (!isGitRepo(projectDir)) {
2476
- return { status: "failed", result: { error: orchestrateNotGitRepoMessage(projectDir) } };
2853
+ return { ok: false, result: { status: "failed", result: { error: orchestrateNotGitRepoMessage(projectDir) } } };
2477
2854
  }
2478
2855
  if (!worktreeCapable(projectDir)) {
2479
- return { status: "failed", result: { error: worktreeUnavailableMessage(projectDir) } };
2856
+ return { ok: false, result: { status: "failed", result: { error: worktreeUnavailableMessage(projectDir) } } };
2480
2857
  }
2481
2858
  if (!toolchainPresent(projectDir)) {
2482
- return { status: "failed", result: { error: toolchainMissingMessage(projectDir) } };
2859
+ return { ok: false, result: { status: "failed", result: { error: toolchainMissingMessage(projectDir) } } };
2860
+ }
2861
+ // ENG-658: a missing/empty orchestrator definition fails before anything spawns.
2862
+ const missingOrchestrator = missingAgentDefinitionMessage(deps.agentDir, "orchestrator", deps.agentSource);
2863
+ if (missingOrchestrator) {
2864
+ return { ok: false, result: { status: "failed", result: { error: missingOrchestrator } } };
2483
2865
  }
2484
2866
  // ENG-345: a build that deploys to Google Cloud checks the cloud first. Any
2485
2867
  // gap stops it before Claude is spawned (no session, no run folder) with ONE
@@ -2488,8 +2870,16 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2488
2870
  // the preflight question itself), so the build proceeds instead of asking
2489
2871
  // the same question again.
2490
2872
  if (!ctx.fix && ctx.cloud && !ctx.resume) {
2873
+ // ENG-507: the preflight deliberately keeps the machine's own gcloud config.
2874
+ // It only reads (auth list, describe, get-iam-policy) and must see the
2875
+ // signed-in account; an isolated empty folder would always report "not signed in".
2876
+ const spendTeamId = ctx.teamId;
2491
2877
  const preflight = deps.cloudPreflight ??
2492
- ((facts, repo) => runCloudPreflight(facts, repo, { execFile: defaultPreflightExecFile, now: Date.now }));
2878
+ ((facts, repo) => runCloudPreflight(facts, repo, {
2879
+ execFile: defaultPreflightExecFile,
2880
+ now: Date.now,
2881
+ ...(spendTeamId && { spendCheck: () => new ApiClient().getProjectSpendCheck(spendTeamId) }),
2882
+ }));
2493
2883
  let checks = null;
2494
2884
  try {
2495
2885
  checks = await preflight(ctx.cloud, repoFromRemote(ctx.projectRemote));
@@ -2497,18 +2887,55 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2497
2887
  catch {
2498
2888
  checks = null; // A broken preflight never blocks the build.
2499
2889
  }
2890
+ // ENG-506: over the monthly spend limit -> refuse before anything starts.
2891
+ const overLimit = checks?.find((c) => c.check === "spend-limit" && c.status === "gap");
2892
+ if (overLimit)
2893
+ return { ok: false, result: { status: "failed", result: { error: `Cloud job not started: ${overLimit.detail}` } } };
2500
2894
  if (checks) {
2501
2895
  try {
2502
- await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, formatPreflightTurn(checks));
2896
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, formatPreflightTurn(checks, ctx.cloud.provider === "aws" ? "aws" : "gcp"));
2503
2897
  }
2504
2898
  catch {
2505
2899
  // Best-effort preflight turn.
2506
2900
  }
2507
- const request = preflightNeedsInput(checks);
2901
+ const request = preflightNeedsInput(checks, ctx.cloud.provider === "aws" ? "aws" : "gcp");
2508
2902
  if (request)
2509
- return needsInputRunResult(ctx.epicId, request);
2903
+ return { ok: false, result: needsInputRunResult(ctx.epicId, request) };
2510
2904
  }
2511
2905
  }
2906
+ return { ok: true, projectDir };
2907
+ }
2908
+ /**
2909
+ * Run the orchestrator headless for a `start_execution`/`orchestrate` job
2910
+ * (ENG-165).
2911
+ *
2912
+ * Flow: validate the project repo (git repo → worktree-capable → test toolchain
2913
+ * present) → spawn the local `claude` CLI in that repo cwd with ENG-164's MCP +
2914
+ * CLAUDE.md-routing profile (H1: unattended permission mode, NOT
2915
+ * `--tools ""`/`--safe-mode`) running `@orchestrator execute epic <epicId>
2916
+ * --non-interactive` with `COMPBOX_NONINTERACTIVE=1` (H3 signal) and pxpipe's
2917
+ * `ANTHROPIC_BASE_URL` preserved → keep the machine alive with a periodic
2918
+ * heartbeat during the long run (H4) → relay a start + final turn to the mailbox
2919
+ * → on a needs-review HARD-gate marker complete as a needs-review failure naming
2920
+ * the gate (ENG-165-3); on a non-zero exit fail with the reason; on a clean run
2921
+ * complete `{ epicId }`. Never hangs.
2922
+ */
2923
+ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2924
+ // ENG-300: cancelled before it started — don't spawn at all.
2925
+ if (ctx.signal?.aborted)
2926
+ return cancelledRunResult("orchestrator");
2927
+ // ENG-352: wall clock for the run's time breakdown.
2928
+ const clockMs = deps.clockMs ?? Date.now;
2929
+ const startedAtMs = clockMs();
2930
+ const spawnImpl = deps.spawnImpl ?? spawn;
2931
+ const resolveRoutingImpl = deps.resolveRoutingImpl ?? resolveRouting;
2932
+ const heartbeatIntervalMs = deps.heartbeatIntervalMs ?? ORCHESTRATOR_HEARTBEAT_INTERVAL_MS;
2933
+ const stallMs = deps.stallMs ?? getBuildStallMs();
2934
+ const maxMs = deps.maxMs ?? getBuildMaxMs();
2935
+ const prepared = await prepareOrchestrateRun(ctx, deps);
2936
+ if (!prepared.ok)
2937
+ return prepared.result;
2938
+ const projectDir = prepared.projectDir;
2512
2939
  // Each run gets its own branch + worktree, so it never touches the person's
2513
2940
  // checkout and always ends as a reviewable pull request.
2514
2941
  let workspace = null;
@@ -2518,6 +2945,15 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2518
2945
  const resume = ctx.fix ? undefined : ctx.resume;
2519
2946
  let resumeSessionId;
2520
2947
  let resumeFallbackWhy = null;
2948
+ // ENG-579: what the company's agent set declares the orchestrator may do.
2949
+ const orchestratorPerms = permissionsFor(deps.agentPermissions, "orchestrator");
2950
+ const protectedBranches = orchestratorPerms?.protectedBranches ?? [];
2951
+ // ENG-657: every orchestrator turn (first, note, continue) carries the
2952
+ // verified agent set's orchestrator + sub-agent definitions.
2953
+ const agentArgs = (a) => {
2954
+ const withDefs = withAgentDefinitions(a, deps.agentDir, "orchestrator");
2955
+ return applyAgentPermissions(ctx.keyRun ? keyRunArgs(withDefs) : withDefs, orchestratorPerms);
2956
+ };
2521
2957
  if (resume) {
2522
2958
  if (!resume.sessionId || !resume.runDir) {
2523
2959
  resumeFallbackWhy = "the paused run didn't keep a session to resume";
@@ -2533,6 +2969,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2533
2969
  projectDir,
2534
2970
  runDir: resume.runDir,
2535
2971
  branch: resume.branch,
2972
+ ...(protectedBranches.length > 0 && { protectedBranches }),
2536
2973
  });
2537
2974
  if (reopened.ok) {
2538
2975
  workspace = reopened.workspace;
@@ -2548,10 +2985,16 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2548
2985
  // ENG-349: never prune a folder another in-flight job of this machine is using.
2549
2986
  const active = deps.activeRunDirs ? { activeRunDirs: [...deps.activeRunDirs] } : {};
2550
2987
  const fresh = ctx.freshBranch === true ? { fresh: true } : {};
2988
+ // ENG-579: declared protected branches join the base branch in the pre-push guard.
2989
+ const guarded = protectedBranches.length > 0 ? { protectedBranches } : {};
2551
2990
  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 })
2991
+ ? await deps.workspace.prepare(projectDir, ctx.epicId, {
2992
+ branch: ctx.fix.branch,
2993
+ ...active,
2994
+ ...guarded,
2995
+ })
2996
+ : deps.activeRunDirs || ctx.freshBranch === true || guarded.protectedBranches
2997
+ ? await deps.workspace.prepare(projectDir, ctx.epicId, { ...active, ...fresh, ...guarded })
2555
2998
  : await deps.workspace.prepare(projectDir, ctx.epicId);
2556
2999
  if (!prepared.ok) {
2557
3000
  return { status: "failed", result: { error: prepared.error } };
@@ -2594,7 +3037,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2594
3037
  ...(attachmentsNote && { replyAttachmentsNote: attachmentsNote }),
2595
3038
  ...(ctx.checkMode && { checkMode: ctx.checkMode }),
2596
3039
  });
2597
- const args = ctx.keyRun ? keyRunArgs(runArgs) : runArgs;
3040
+ const args = agentArgs(runArgs);
2598
3041
  // pxpipe (ENG-136): inject ANTHROPIC_BASE_URL when routed. COMPBOX_NONINTERACTIVE
2599
3042
  // forces the orchestrator's headless serial-in-process path (H3) even if the
2600
3043
  // prompt flag were dropped. PATH is augmented (ENG-135) so `claude` and any
@@ -2609,13 +3052,24 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2609
3052
  // ENG-346: a gh shim that refuses merges goes first on the AGENT's PATH
2610
3053
  // (the real gh is resolved before it is prepended). The runner's own
2611
3054
  // 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),
3055
+ PATH: withMergeGuardPath(claudeChildEnvPath(routedEnv.PATH), deps.mergeGuardDir === undefined ? join(getConfigDir(), "merge-guard") : deps.mergeGuardDir, process.platform, orchestratorPerms?.ghDeny ?? []),
2613
3056
  };
2614
3057
  // ENG-394: the agent's commits skip the repo's own hooks (orchestrator,
2615
3058
  // conflict fix and follow-up all use this env); the run's checks cover them.
2616
3059
  const agentHooksDir = makeAgentHooksDir(runDir);
2617
3060
  if (agentHooksDir)
2618
3061
  Object.assign(baseEnv, withHooksDisabled(baseEnv, agentHooksDir));
3062
+ // ENG-507: the agent (and the conflict resolver, which reuses baseEnv) gets
3063
+ // its own gcloud config folder, so it can never switch the person's login.
3064
+ if (workspace) {
3065
+ try {
3066
+ createGcloudConfigDir(workspace.dir);
3067
+ }
3068
+ catch {
3069
+ // gcloud creates the folder itself if it's missing.
3070
+ }
3071
+ Object.assign(baseEnv, withIsolatedGcloud(baseEnv, workspace.dir));
3072
+ }
2619
3073
  const childEnv = ctx.keyRun ? keyRunEnv(baseEnv, ctx.keyRun) : baseEnv;
2620
3074
  // H4: relay a START turn immediately so the web shows the run began even if the
2621
3075
  // orchestrator produces no stdout for minutes. postTurn failures are swallowed.
@@ -2886,11 +3340,46 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2886
3340
  // Best-effort status turn.
2887
3341
  }
2888
3342
  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());
3343
+ result = await runOnce(agentArgs(noteArgs), deadline - Date.now());
2890
3344
  }
2891
3345
  return result;
2892
3346
  };
2893
- let outcome = await runDeliveringNotes(args, maxMs);
3347
+ // ENG-591: with the org's belt-engine switch on, a build runs one Claude turn
3348
+ // per belt step in this same session. An API without belt routes falls back
3349
+ // to the old single orchestrator run.
3350
+ let outcome;
3351
+ let beltRan = false;
3352
+ let beltSteps;
3353
+ if (ctx.belt === true && !ctx.fix && sessionId) {
3354
+ const beltSessionId = sessionId;
3355
+ try {
3356
+ const belt = await runBelt({
3357
+ client: ctx.mailboxClient,
3358
+ machineToken: ctx.machineToken,
3359
+ jobId: ctx.jobId,
3360
+ epicId: ctx.epicId,
3361
+ checkMode: ctx.checkMode ?? "smart",
3362
+ deadline,
3363
+ ...(ctx.signal && { signal: ctx.signal }),
3364
+ readParts: (beltRunId) => ctx.mailboxClient.readBeltParts(ctx.machineToken, beltRunId),
3365
+ postStatus: async (message) => {
3366
+ await ctx.mailboxClient.postTurn(ctx.machineToken, ctx.jobId, message);
3367
+ },
3368
+ runTurn: (turn) => {
3369
+ const turnArgs = buildBeltTurnArgs(beltSessionId, turn.prompt, turn.firstTurn && !resumeSessionId, workspace?.baseBranch, ctx.fastMode);
3370
+ return runDeliveringNotes(ctx.keyRun ? keyRunArgs(turnArgs) : turnArgs, turn.budgetMs);
3371
+ },
3372
+ });
3373
+ outcome = belt.result;
3374
+ beltSteps = belt.steps;
3375
+ beltRan = true;
3376
+ }
3377
+ catch (error) {
3378
+ if (!(error instanceof BeltUnsupportedError))
3379
+ throw error;
3380
+ }
3381
+ }
3382
+ outcome ??= await runDeliveringNotes(args, maxMs);
2894
3383
  // A clean exit isn't proof the epic is finished: a headless run can end its
2895
3384
  // turn early (e.g. "waiting" on a background review, or "Next I'll…"). Check
2896
3385
  // CompBox, resume the same session while features are outstanding and new
@@ -2898,7 +3387,8 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2898
3387
  // A fix run changes one pull request, not the epic's plan, so epic progress says nothing about it.
2899
3388
  // ENG-332 (M1): set when a resume was due but 60s or less of the ceiling remained.
2900
3389
  let hitCeiling = false;
2901
- if (outcome.status === "done" && !ctx.fix) {
3390
+ // A belt run decides completion itself (every step done), so it skips the resume loop.
3391
+ if (outcome.status === "done" && !ctx.fix && !beltRan) {
2902
3392
  const readProgress = deps.epicProgress ??
2903
3393
  (async () => {
2904
3394
  try {
@@ -2936,7 +3426,7 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
2936
3426
  }
2937
3427
  const before = progress.completedFeatures;
2938
3428
  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());
3429
+ outcome = await runDeliveringNotes(agentArgs(continueArgs), deadline - Date.now());
2940
3430
  if (outcome.status !== "done")
2941
3431
  break;
2942
3432
  progress = await readProgress();
@@ -3097,6 +3587,9 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
3097
3587
  startedAtMs,
3098
3588
  endedAtMs: clockMs(),
3099
3589
  fastMode: ctx.fastMode === true ? { requested: true, used: fastModeUsed } : null,
3590
+ // ENG-591: only the orchestrate run reports a path; fix runs never use the belt.
3591
+ ...(!ctx.fix && { path: beltRan ? "belt" : "old" }),
3592
+ ...(beltSteps && { beltSteps }),
3100
3593
  });
3101
3594
  // H4: relay a FINAL turn summarizing the outcome (best-effort).
3102
3595
  try {
@@ -3114,7 +3607,14 @@ export async function invokeStartExecutionOrchestrate(ctx, deps = {}) {
3114
3607
  // Best-effort final turn.
3115
3608
  }
3116
3609
  // Attached after the final turn so a failure summary leads with the error.
3117
- outcome.result = { ...outcome.result, timings };
3610
+ // ENG-514: routing decision + measured savings (null = unknown, never fails the run).
3611
+ const runEndedAtMs = clockMs();
3612
+ const tokensSaved = routing.mode === "proxy" ? await readMeasuredTokensSaved(startedAtMs, runEndedAtMs) : null;
3613
+ outcome.result = {
3614
+ ...outcome.result,
3615
+ timings,
3616
+ routing: toRunRouting(routing, tokensSaved),
3617
+ };
3118
3618
  return outcome;
3119
3619
  }
3120
3620
  /**