@bridge_gpt/mcp-server 0.2.69 → 0.2.71

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 (164) hide show
  1. package/README.md +140 -292
  2. package/build/agent-launchers/claude-executor-adapter.js +27 -5
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +15 -5
  5. package/build/artifact-diff.js +110 -0
  6. package/build/bin-entrypoint.js +36 -0
  7. package/build/bounded-wait.js +9 -1
  8. package/build/bridge-permissions.js +36 -9
  9. package/build/claude-review-workflow-drift.js +3 -3
  10. package/build/codex-bridge-profile.js +1 -1
  11. package/build/commands.generated.js +6 -6
  12. package/build/conductor/bridge-api-client.js +858 -21
  13. package/build/conductor/bring-up-facts.js +9 -9
  14. package/build/conductor/command-drift-production.js +7 -2
  15. package/build/conductor/doctor.js +472 -18
  16. package/build/conductor/epic-child-continuation.js +54 -3
  17. package/build/conductor/epic-implementer-cli.js +136 -34
  18. package/build/conductor/epic-runtime.js +2 -2
  19. package/build/conductor/epic-state.js +1 -1
  20. package/build/conductor/gate-discovery.js +524 -10
  21. package/build/conductor/gate-settings-review.js +451 -0
  22. package/build/conductor/hook-runtime-qualification.js +1 -1
  23. package/build/conductor/install-doctor.js +4 -2
  24. package/build/conductor/launch-need-probes.js +342 -0
  25. package/build/conductor/launch-plan.js +145 -0
  26. package/build/conductor/local-merge.js +241 -56
  27. package/build/conductor/merge-credential.js +172 -0
  28. package/build/conductor/merge-execution-eligibility.js +1 -1
  29. package/build/conductor/merged-child-check.js +95 -0
  30. package/build/conductor/plan-trim.js +30 -0
  31. package/build/conductor/pr-ci-producer.js +1 -1
  32. package/build/conductor/precheck-timings.js +14 -0
  33. package/build/conductor/preview-observations.js +10 -0
  34. package/build/conductor/readiness-cli.js +11 -6
  35. package/build/conductor/readiness-prerequisites.js +41 -0
  36. package/build/conductor/readiness-sections.js +348 -55
  37. package/build/conductor/readiness.js +99 -87
  38. package/build/conductor/recovery-cli.js +665 -23
  39. package/build/conductor/recovery-operations.js +350 -8
  40. package/build/conductor/repair-contract.js +47 -2
  41. package/build/conductor/repository-workflow-remedy.js +8 -6
  42. package/build/conductor/stored-merge-credential.js +76 -0
  43. package/build/conductor/stored-merge-token-probe.js +28 -0
  44. package/build/conductor/temporary-plan.js +50 -0
  45. package/build/conductor/wait-run-cli.js +759 -0
  46. package/build/conductor/worker-database-doctor-inspector.js +49 -0
  47. package/build/conductor-bin.js +2 -2
  48. package/build/conductor-claude-hook-bin.js +2 -2
  49. package/build/conductor-claude-hook-removed-stub-bin.js +2 -5
  50. package/build/conductor-removed-stub-bin.js +2 -5
  51. package/build/credential-store.js +356 -13
  52. package/build/docs.generated.js +26 -13
  53. package/build/doctor.js +94 -32
  54. package/build/drive-epic-help.js +212 -0
  55. package/build/drive-epic.js +1989 -379
  56. package/build/epic-ci-workflow-drift.js +125 -0
  57. package/build/epic-ci-workflow-install.js +240 -0
  58. package/build/epic-ci-workflow-v1.js +132 -0
  59. package/build/epic-ci-workflow.js +318 -0
  60. package/build/epic-contract-context.js +326 -0
  61. package/build/epic-implementer-bin.js +58 -42
  62. package/build/epic-implementer-claude-hook-bin.js +2 -2
  63. package/build/escalation-reachability.js +134 -0
  64. package/build/executor/ci-rerun-job.js +220 -14
  65. package/build/executor/cleanup-report.js +99 -0
  66. package/build/executor/cli.js +12 -1
  67. package/build/executor/completion-contract.js +66 -11
  68. package/build/executor/completion-supervision.js +99 -0
  69. package/build/executor/delivery-outcome.js +179 -0
  70. package/build/executor/deps.js +3 -0
  71. package/build/executor/env.js +276 -1
  72. package/build/executor/failure-reason-codes.js +126 -0
  73. package/build/executor/gate-qualification-job.js +20 -5
  74. package/build/executor/heartbeat.js +38 -0
  75. package/build/executor/http-client.js +72 -0
  76. package/build/executor/integration-job.js +298 -5
  77. package/build/executor/job-errors.js +36 -6
  78. package/build/executor/job-runner.js +830 -45
  79. package/build/executor/likely-tests.js +42 -3
  80. package/build/executor/merge-job.js +145 -2
  81. package/build/executor/observation.js +73 -4
  82. package/build/executor/permissions.js +193 -97
  83. package/build/executor/preflight.js +19 -3
  84. package/build/executor/process-containment.js +46 -2
  85. package/build/executor/prompt-spec.js +113 -9
  86. package/build/executor/rebase-finalization.js +38 -3
  87. package/build/executor/reconcile-overlap-job.js +41 -8
  88. package/build/executor/required-work-ledger.js +236 -81
  89. package/build/executor/resume-pre-spawn.js +38 -1
  90. package/build/executor/runner.js +91 -3
  91. package/build/executor/test-clock.js +8 -0
  92. package/build/executor/types.js +37 -2
  93. package/build/executor/worker-cli-launcher.js +259 -0
  94. package/build/executor/worker-command.js +177 -5
  95. package/build/executor/worker-database-target.js +91 -0
  96. package/build/executor/worker-database.js +927 -0
  97. package/build/executor/worker-finalization.js +106 -0
  98. package/build/executor/worker-guard-hook.js +203 -0
  99. package/build/executor/worker-resources.js +58 -0
  100. package/build/executor/worker-verification-guidance.js +44 -2
  101. package/build/executor/worktree.js +303 -15
  102. package/build/executor-launch.js +11 -1
  103. package/build/generated-assets-doctor.js +9 -1
  104. package/build/generated-assets-health.js +13 -4
  105. package/build/generated-assets-legacy.js +39 -0
  106. package/build/generated-assets-paths.js +12 -1
  107. package/build/generated-assets-repair.js +4 -1
  108. package/build/generated-assets-test-support.js +12 -0
  109. package/build/github-remote.js +33 -0
  110. package/build/github-sign-in.js +62 -0
  111. package/build/index.js +1133 -546
  112. package/build/init.js +39 -1
  113. package/build/install-bridge-conductor-gate.js +270 -11
  114. package/build/install-bridge-conductor-setup.js +427 -0
  115. package/build/install-bridge-conductor.js +1545 -268
  116. package/build/install-bridge.js +376 -60
  117. package/build/mcp-install-state.js +8 -2
  118. package/build/merge-pull-request.js +6 -0
  119. package/build/merge-workflow-install.js +782 -344
  120. package/build/phase-result-artifacts.js +75 -20
  121. package/build/pipeline-orchestrator.js +247 -4
  122. package/build/pipelines.generated.js +35 -35
  123. package/build/plan-discovery.js +15 -2
  124. package/build/plan-execution-ledger.js +321 -17
  125. package/build/plan-phase-routing.js +48 -13
  126. package/build/plane/cli.js +105 -51
  127. package/build/plane/defaults.js +3 -0
  128. package/build/plane/plane-freshness.js +298 -0
  129. package/build/plane/preflight.js +19 -0
  130. package/build/plane/schema-compatibility.js +137 -0
  131. package/build/plane/shutdown-deps.js +38 -0
  132. package/build/plane/shutdown.js +83 -8
  133. package/build/plane/terminal-run-cleanup.js +303 -0
  134. package/build/printed-remedy-commands.js +33 -4
  135. package/build/readiness-check.js +6 -2
  136. package/build/readiness-prerequisites.generated.js +532 -0
  137. package/build/readme.generated.js +1 -1
  138. package/build/repository-toolchains.js +581 -0
  139. package/build/setup-epic.js +421 -34
  140. package/build/shared-resources.generated.js +5 -0
  141. package/build/start-tickets.js +28 -15
  142. package/build/test-command-detection.js +284 -0
  143. package/build/test-command-validation.js +73 -0
  144. package/build/testing-config-client.js +150 -0
  145. package/build/ticket-delivery-artifacts.js +265 -0
  146. package/build/ticket-delivery-enrollment.js +369 -0
  147. package/build/ticket-delivery.js +205 -0
  148. package/build/ticket-review-summary.js +14 -0
  149. package/build/upgrade-cli.js +13 -0
  150. package/build/v2-readiness-requirements.js +552 -0
  151. package/build/version.generated.js +3 -3
  152. package/build/worker-guard-hook-bin.js +2 -2
  153. package/build/worktree-core.js +22 -7
  154. package/docs/BRIDGE-DIRECTORY-README.md +48 -0
  155. package/docs/EPIC-IMPLEMENTER-INSTALL.md +12 -867
  156. package/docs/EPIC-IMPLEMENTER.md +142 -63
  157. package/docs/epic-implementer/getting-started.md +187 -0
  158. package/docs/epic-implementer/self-hosting.md +133 -0
  159. package/package.json +4 -4
  160. package/pipelines/idea-to-ticket.json +1 -1
  161. package/pipelines/implement-ticket.json +8 -8
  162. package/pipelines/review-ticket.json +2 -2
  163. package/design-assets/favicon/favicon-32x32.png +0 -0
  164. package/design-assets/just-logo-rough-draft.png +0 -0
@@ -1,5 +1,5 @@
1
1
  /**
2
- * `conductor` operator recovery and repair verbs — fourteen CLI-only commands.
2
+ * `conductor` operator recovery and repair verbs — sixteen CLI-only commands.
3
3
  *
4
4
  * The four BAPI-872 recovery verbs: `stop-run`, `abandon-run`, `unpark`,
5
5
  * `adopt-current-head-and-unpark`. The six run-addressed repair verbs: BAPI-1154's
@@ -7,10 +7,12 @@
7
7
  * `scope-catch-up`, `patch-policy`, `resume-run`. BAPI-1300's parked-child
8
8
  * continuation pair: `continue-child` and the read-only `continuation-receipt`.
9
9
  * BAPI-1326's allowance-preserving CI resume: `resume-ci`. BAPI-1388's guided
10
- * provider re-run of failed CI workflow runs: `rerun-ci`.
10
+ * provider re-run of failed CI workflow runs: `rerun-ci`. BAPI-1494's owner
11
+ * decision on verification hand-offs: `resolve-handoff`. BAPI-1532's answer to a
12
+ * named plan failure, one forced regeneration on a chosen route: `regenerate-plan`.
11
13
  *
12
14
  * CLI-only by design — this is an explicit ticket non-goal, not an oversight:
13
- * none of these fourteen command names is ever registered as an MCP tool, tool
15
+ * none of these sixteen command names is ever registered as an MCP tool, tool
14
16
  * description, or generated tool-schema input (`index-static.test.ts` guards
15
17
  * this). They exist so an operator (or `plane down`, via
16
18
  * `recovery-operations.ts`) can recover a stuck run or ticket WITHOUT
@@ -26,7 +28,9 @@
26
28
  */
27
29
  import { readFile } from "node:fs/promises";
28
30
  import { ConductorValidationError, toConductorErrorEnvelope } from "./errors.js";
29
- import { DRIVER_CONTEXT_MAX_BYTES, POLICY_PATCH_MAX_BYTES, RESUME_RUN_UNCONFIRMED_MESSAGE, } from "./repair-contract.js";
31
+ import { nodeGithubMergeCredentialReadDeps, readLocalGithubRemote } from "./stored-merge-credential.js";
32
+ import { DRIVER_CONTEXT_MAX_BYTES, HANDOFF_RESOLUTION_EVIDENCE_REF_MAX_CHARS, HANDOFF_RESOLUTION_KIND_LABELS, HANDOFF_RESOLUTION_KINDS, HANDOFF_RESOLUTION_MAX_STEPS, HANDOFF_RESOLUTION_REASON_MAX_CHARS, POLICY_PATCH_MAX_BYTES, RESUME_RUN_UNCONFIRMED_MESSAGE, } from "./repair-contract.js";
33
+ import { CONTINUATION_CI_WAITING_REASONS, continuationDispatchedJob, } from "./epic-child-continuation.js";
30
34
  import { decodeGuidedBinding, GuidedBindingError, } from "./guided-repair.js";
31
35
  // ---------------------------------------------------------------------------
32
36
  // Flag parsing
@@ -121,8 +125,28 @@ function parseRunRecoveryArgs(argv) {
121
125
  }
122
126
  return { epicRunId: epicRunId.trim(), json: bools.has("--json"), help: false };
123
127
  }
128
+ /**
129
+ * BAPI-1537 — the operation-id shape the server accepts (`api/models/epic_run.py`
130
+ * `EXTERNAL_REPAIR_OPERATION_ID_PATTERN`): 1-128 characters of `[A-Za-z0-9._:-]`,
131
+ * case-sensitive. Checked here so a malformed id never reaches the network.
132
+ */
133
+ const EXTERNAL_REPAIR_OPERATION_ID_RE = /^[A-Za-z0-9._:-]{1,128}$/;
134
+ function parseExternalRepairOperationId(values) {
135
+ if (!values.has("--external-repair"))
136
+ return undefined;
137
+ const raw = values.get("--external-repair") ?? "";
138
+ // A following flag is not a value: `--external-repair --json` names no id.
139
+ if (raw.startsWith("--")) {
140
+ throw new ConductorValidationError('Flag "--external-repair" requires a value.');
141
+ }
142
+ const id = raw.trim();
143
+ if (!EXTERNAL_REPAIR_OPERATION_ID_RE.test(id)) {
144
+ throw new ConductorValidationError('"--external-repair" must be 1-128 characters of letters, digits, ".", "_", ":" or "-".');
145
+ }
146
+ return id;
147
+ }
124
148
  function parseTicketRecoveryArgs(argv) {
125
- const { values, bools } = tokenizeRecoveryFlags(argv, new Set([...TICKET_VALUE_FLAGS, "--reason", "--cleanup-resolution"]), RECOVERY_BOOL_FLAGS);
149
+ const { values, bools } = tokenizeRecoveryFlags(argv, new Set([...TICKET_VALUE_FLAGS, "--reason", "--cleanup-resolution", "--external-repair"]), RECOVERY_BOOL_FLAGS);
126
150
  if (bools.has("--help")) {
127
151
  return { epicRunId: "", ticketKey: "", json: bools.has("--json"), help: true };
128
152
  }
@@ -134,6 +158,7 @@ function parseTicketRecoveryArgs(argv) {
134
158
  if (ticketKey === undefined || ticketKey.trim().length === 0) {
135
159
  throw new ConductorValidationError('Flag "--ticket-key" is required and must be non-empty.');
136
160
  }
161
+ const externalRepairOperationId = parseExternalRepairOperationId(values);
137
162
  return {
138
163
  epicRunId: epicRunId.trim(),
139
164
  ticketKey: ticketKey.trim(),
@@ -141,6 +166,7 @@ function parseTicketRecoveryArgs(argv) {
141
166
  ...(values.get("--cleanup-resolution") ? {
142
167
  cleanupResolution: values.get("--cleanup-resolution"),
143
168
  } : {}),
169
+ ...(externalRepairOperationId !== undefined ? { externalRepairOperationId } : {}),
144
170
  json: bools.has("--json"),
145
171
  help: false,
146
172
  };
@@ -274,7 +300,7 @@ const UNPARK_USAGE = [
274
300
  "its own if the ticket changes concurrently — never accepts a version counter.",
275
301
  ].join("\n");
276
302
  const ADOPT_CURRENT_HEAD_USAGE = [
277
- "Usage: epic-implementer adopt-current-head-and-unpark --epic-run-id <id> --ticket-key <key> [--json]",
303
+ "Usage: epic-implementer adopt-current-head-and-unpark --epic-run-id <id> --ticket-key <key> [--external-repair <operation-id>] [--json]",
278
304
  "",
279
305
  "Recover a ticket parked because a human/external push drifted the PR head",
280
306
  "off its anchored commit: adopt the CURRENT PR head and unpark in one step.",
@@ -287,6 +313,15 @@ const ADOPT_CURRENT_HEAD_USAGE = [
287
313
  "resumes the ticket at CI. No worker is started and nothing is marked passed —",
288
314
  "CI and review must pass again on the accepted head. A repeat of the same",
289
315
  "request reports the recorded result instead of adopting twice.",
316
+ "",
317
+ "--external-repair <operation-id> adopts fast-forward repair commits pushed to",
318
+ "the ticket's own branch while no engine job ran (for example a checkpoint-only",
319
+ "park with no PR). The server proves the repair is safe — no live job, fast-",
320
+ "forward ancestry, the right PR base and head, and a head no other ticket owns —",
321
+ "then rebinds the head and unparks. The ticket still passes CI, review, and the",
322
+ "engine merge at that head. The id is a correlation label (1-128 characters of",
323
+ "letters, digits, '.', '_', ':' or '-'); the same id replays its recorded result.",
324
+ "Only the run's supervisor/driver uses it. Not accepted by unpark.",
290
325
  ].join("\n");
291
326
  /** BAPI-1310 (E1): the fixed allowance sentence the adoption result carries. */
292
327
  const REVIEW_HEAD_ALLOWANCE_LINE = "Allowance effect: repair allowances preserved; acceptance does not grant another repair.";
@@ -308,12 +343,32 @@ function renderReviewHeadRecovery(ticketKey, epicRunId, recovery) {
308
343
  console.log(` WARNING: ${REVIEW_HEAD_HELD_WARNING}.`);
309
344
  }
310
345
  }
346
+ /** BAPI-1537: render an external-repair receipt (committed or replayed) to stdout. */
347
+ function renderExternalRepair(ticketKey, epicRunId, receipt) {
348
+ const outcome = receipt.result === "replayed"
349
+ ? "replayed — this operation already committed; nothing changed now"
350
+ : "committed";
351
+ console.log(`Ticket ${ticketKey} (run ${epicRunId}): external repair ${receipt.operation_id} adopted — ${outcome}.`);
352
+ console.log(` Previous expected head: ${receipt.previous_expected_head_sha ?? "unbound"}`);
353
+ console.log(` Comparison base: ${receipt.comparison_base_sha}`);
354
+ console.log(` Adopted head: ${receipt.adopted_head_sha}`);
355
+ console.log(` Restored to: ${receipt.restored_status}`);
356
+ console.log(` Current gate: ${receipt.current_gate ?? "unavailable"}`);
357
+ console.log(" The ticket must still pass attach, CI, review, and the engine merge at the adopted head; nothing was marked passed.");
358
+ if (receipt.held_by_run_control) {
359
+ console.log(" WARNING: Head adopted; run remains held by run control.");
360
+ }
361
+ }
311
362
  export function renderTicketRecoveryResult(result, json) {
312
363
  if (json) {
313
364
  console.log(JSON.stringify(result));
314
365
  return result.ok ? 0 : 1;
315
366
  }
316
367
  if (result.ok) {
368
+ if (result.externalRepair) {
369
+ renderExternalRepair(result.ticketKey, result.epicRunId, result.externalRepair);
370
+ return 0;
371
+ }
317
372
  if (result.reviewHeadRecovery) {
318
373
  renderReviewHeadRecovery(result.ticketKey, result.epicRunId, result.reviewHeadRecovery);
319
374
  return 0;
@@ -341,6 +396,9 @@ export function renderTicketRecoveryResult(result, json) {
341
396
  export async function runUnparkCommand(argv) {
342
397
  try {
343
398
  const parsed = parseTicketRecoveryArgs(argv);
399
+ if (parsed.externalRepairOperationId !== undefined) {
400
+ throw new ConductorValidationError("--external-repair applies only to adopt-current-head-and-unpark.");
401
+ }
344
402
  if (parsed.cleanupResolution !== undefined &&
345
403
  !["confirmed", "risk_accepted"].includes(parsed.cleanupResolution)) {
346
404
  throw new ConductorValidationError("--cleanup-resolution must be confirmed or risk_accepted.");
@@ -386,6 +444,9 @@ export async function runAdoptCurrentHeadAndUnparkCommand(argv) {
386
444
  const result = await adoptCurrentHeadAndUnparkWithRetry(access, {
387
445
  epicRunId: parsed.epicRunId,
388
446
  ticketKey: parsed.ticketKey,
447
+ ...(parsed.externalRepairOperationId !== undefined
448
+ ? { externalRepairOperationId: parsed.externalRepairOperationId }
449
+ : {}),
389
450
  });
390
451
  return renderTicketRecoveryResult(result, parsed.json);
391
452
  }
@@ -995,6 +1056,196 @@ export async function runRerunCiCommand(argv) {
995
1056
  return RERUN_CI_EXIT_FAILED;
996
1057
  }
997
1058
  }
1059
+ // ---------------------------------------------------------------------------
1060
+ // BAPI-1494 — resolve-handoff
1061
+ // ---------------------------------------------------------------------------
1062
+ const RESOLVE_HANDOFF_VALUE_FLAGS = new Set([
1063
+ "--epic-run-id",
1064
+ "--ticket-key",
1065
+ "--steps",
1066
+ "--kind",
1067
+ "--evidence",
1068
+ "--reason",
1069
+ ]);
1070
+ /** Exit codes: 0 recorded (or an identical replay), 1 refused or failed. */
1071
+ export const RESOLVE_HANDOFF_EXIT_OK = 0;
1072
+ export const RESOLVE_HANDOFF_EXIT_FAILED = 1;
1073
+ /** The paired-record instruction every success ends with. */
1074
+ export const RESOLVE_HANDOFF_PAIRED_RECORD_INSTRUCTION = "Release from draft also needs the paired .bridge/epic-workarounds/<KEY>.md record " +
1075
+ "removed in a new epic-head commit. The integration PR leaves draft only when both " +
1076
+ "holds are clear: the hand-off ledger hold and the workaround-folder hold.";
1077
+ const RESOLVE_HANDOFF_USAGE = [
1078
+ "Usage: epic-implementer resolve-handoff --epic-run-id <id> --ticket-key <key> --steps 27,36",
1079
+ " --kind verified|risk_accepted --evidence <ref> --reason <text> [--json]",
1080
+ "",
1081
+ "Record the run owner's decision on a ticket's verification hand-offs: steps a worker",
1082
+ "could not verify unattended. An unresolved hand-off holds the integration PR in draft.",
1083
+ "",
1084
+ " --kind verified the owner completed the verification of the affected criteria",
1085
+ " --kind risk_accepted verification is still incomplete; the owner accepts the risk",
1086
+ "",
1087
+ "This records a HUMAN decision. Run it only with the owner's named steps, kind, evidence",
1088
+ "and reason; it is never an automatic in-run recovery, and workers cannot run it. The",
1089
+ "server records your verified API-key identity as the actor; you cannot supply one.",
1090
+ "--evidence is stored as a reference (at most 500 characters) and is never fetched.",
1091
+ "--reason is at most 2000 characters.",
1092
+ "",
1093
+ RESOLVE_HANDOFF_PAIRED_RECORD_INSTRUCTION,
1094
+ "",
1095
+ "Exit codes: 0 recorded (or the same decision already recorded); 1 refused or failed.",
1096
+ ].join("\n");
1097
+ /** Character count in code points, the way the server's validation counts. */
1098
+ function codePointLength(value) {
1099
+ return [...value].length;
1100
+ }
1101
+ function parseHandoffSteps(raw) {
1102
+ const parts = raw.split(",");
1103
+ const steps = [];
1104
+ for (const part of parts) {
1105
+ const token = part.trim();
1106
+ if (!/^[1-9][0-9]*$/.test(token)) {
1107
+ throw new ConductorValidationError("--steps must be a comma-separated list of positive integers (for example 27,36).");
1108
+ }
1109
+ const step = Number(token);
1110
+ if (!Number.isSafeInteger(step)) {
1111
+ throw new ConductorValidationError("--steps holds a step id that is too large.");
1112
+ }
1113
+ if (steps.includes(step)) {
1114
+ throw new ConductorValidationError(`--steps names step ${step} more than once.`);
1115
+ }
1116
+ steps.push(step);
1117
+ }
1118
+ if (steps.length > HANDOFF_RESOLUTION_MAX_STEPS) {
1119
+ throw new ConductorValidationError(`--steps may name at most ${HANDOFF_RESOLUTION_MAX_STEPS} steps.`);
1120
+ }
1121
+ return steps;
1122
+ }
1123
+ function boundedText(values, flag, max) {
1124
+ const value = requireFlag(values, flag);
1125
+ if (codePointLength(value) > max) {
1126
+ throw new ConductorValidationError(`Flag "${flag}" must be at most ${max} characters.`);
1127
+ }
1128
+ return value;
1129
+ }
1130
+ export function parseResolveHandoffArgs(argv) {
1131
+ const { values, bools } = tokenizeRecoveryFlags(argv, RESOLVE_HANDOFF_VALUE_FLAGS, RECOVERY_BOOL_FLAGS);
1132
+ if (bools.has("--help")) {
1133
+ return {
1134
+ epicRunId: "",
1135
+ ticketKey: "",
1136
+ steps: [],
1137
+ kind: "verified",
1138
+ evidenceRef: "",
1139
+ reason: "",
1140
+ json: bools.has("--json"),
1141
+ help: true,
1142
+ };
1143
+ }
1144
+ const kind = requireFlag(values, "--kind");
1145
+ if (!HANDOFF_RESOLUTION_KINDS.includes(kind)) {
1146
+ throw new ConductorValidationError('--kind must be "verified" or "risk_accepted".');
1147
+ }
1148
+ return {
1149
+ epicRunId: requireFlag(values, "--epic-run-id"),
1150
+ ticketKey: requireFlag(values, "--ticket-key"),
1151
+ steps: parseHandoffSteps(requireFlag(values, "--steps")),
1152
+ kind: kind,
1153
+ evidenceRef: boundedText(values, "--evidence", HANDOFF_RESOLUTION_EVIDENCE_REF_MAX_CHARS),
1154
+ reason: boundedText(values, "--reason", HANDOFF_RESOLUTION_REASON_MAX_CHARS),
1155
+ json: bools.has("--json"),
1156
+ help: false,
1157
+ };
1158
+ }
1159
+ /**
1160
+ * Exported for tests: render one `resolve-handoff` outcome. Success goes to stdout
1161
+ * and every failure to stderr (`--json` included). `risk_accepted` always reads
1162
+ * "risk accepted" — never verified or passed.
1163
+ */
1164
+ export function renderResolveHandoffOutcome(outcome, parsed, json) {
1165
+ const label = `ticket ${parsed.ticketKey} (run ${parsed.epicRunId})`;
1166
+ const pairedRecord = RESOLVE_HANDOFF_PAIRED_RECORD_INSTRUCTION.replace("<KEY>", parsed.ticketKey);
1167
+ if (outcome.ok) {
1168
+ const result = outcome.result;
1169
+ const decision = HANDOFF_RESOLUTION_KIND_LABELS[parsed.kind];
1170
+ if (result.committed && !result.event_recorded) {
1171
+ console.error(`Warning: resolve-handoff for ${label} COMMITTED, but its operator_verb_applied ` +
1172
+ "audit event was not recorded. The decision stands.");
1173
+ }
1174
+ if (json) {
1175
+ console.log(JSON.stringify({
1176
+ ok: true,
1177
+ outcome: result.committed ? "committed" : "replayed",
1178
+ decision,
1179
+ result,
1180
+ next_action: pairedRecord,
1181
+ }));
1182
+ return RESOLVE_HANDOFF_EXIT_OK;
1183
+ }
1184
+ const lines = [
1185
+ result.committed
1186
+ ? `resolve-handoff — ${label}: decision recorded (${decision})`
1187
+ : `resolve-handoff — ${label}: this decision was already recorded; nothing was written`,
1188
+ ...result.resolutions.map((res) => ` steps ${res.steps.join(", ")}: ${HANDOFF_RESOLUTION_KIND_LABELS[res.kind]} by ` +
1189
+ `${res.actor} at epic head \`${res.epic_head_sha}\` (binding ${res.binding_attempt_id}, ` +
1190
+ `evidence revision ${res.evidence_revision}); evidence: ${res.evidence_ref}`),
1191
+ ` unresolved hand-offs left on this ticket: ${result.remaining_unresolved}`,
1192
+ ` event recorded: ${result.committed ? String(result.event_recorded) : "not applicable (replay)"}`,
1193
+ ` next action: ${pairedRecord}`,
1194
+ ];
1195
+ console.log(lines.join("\n"));
1196
+ return RESOLVE_HANDOFF_EXIT_OK;
1197
+ }
1198
+ if (outcome.kind === "refused") {
1199
+ if (json) {
1200
+ console.error(JSON.stringify({
1201
+ ok: false,
1202
+ outcome: "refused",
1203
+ code: outcome.code,
1204
+ message: outcome.message,
1205
+ nothing_written: true,
1206
+ }));
1207
+ }
1208
+ else {
1209
+ console.error(`Refused: resolve-handoff for ${label} — ${outcome.code}: ${outcome.message} ` +
1210
+ "Nothing was written.");
1211
+ }
1212
+ return RESOLVE_HANDOFF_EXIT_FAILED;
1213
+ }
1214
+ if (json) {
1215
+ console.error(JSON.stringify({ ok: false, outcome: "unavailable", message: outcome.message }));
1216
+ }
1217
+ else {
1218
+ console.error(`Failed: resolve-handoff for ${label} — ${outcome.message}. Whether the decision was ` +
1219
+ "recorded is unconfirmed; read `epic-implementer explain-run` before retrying.");
1220
+ }
1221
+ return RESOLVE_HANDOFF_EXIT_FAILED;
1222
+ }
1223
+ export async function runResolveHandoffCommand(argv) {
1224
+ try {
1225
+ const parsed = parseResolveHandoffArgs(argv);
1226
+ if (parsed.help) {
1227
+ console.log(RESOLVE_HANDOFF_USAGE);
1228
+ return 0;
1229
+ }
1230
+ const access = await resolveRecoveryAccess(parsed.json);
1231
+ if (!access)
1232
+ return RESOLVE_HANDOFF_EXIT_FAILED;
1233
+ const { resolveHandoffRepair } = await import("./recovery-operations.js");
1234
+ const outcome = await resolveHandoffRepair(access, {
1235
+ epicRunId: parsed.epicRunId,
1236
+ ticketKey: parsed.ticketKey,
1237
+ steps: parsed.steps,
1238
+ kind: parsed.kind,
1239
+ evidenceRef: parsed.evidenceRef,
1240
+ reason: parsed.reason,
1241
+ });
1242
+ return renderResolveHandoffOutcome(outcome, parsed, parsed.json);
1243
+ }
1244
+ catch (error) {
1245
+ console.error(`Error: ${toConductorErrorEnvelope(error).message}`);
1246
+ return RESOLVE_HANDOFF_EXIT_FAILED;
1247
+ }
1248
+ }
998
1249
  const MERGE_CHILD_USAGE = [
999
1250
  "Usage: epic-implementer merge-child --epic-run-id <id> --pr <number> [--json]",
1000
1251
  "",
@@ -1020,9 +1271,14 @@ export async function runMergeChildCommand(argv) {
1020
1271
  if (!access)
1021
1272
  return 1;
1022
1273
  const { mergeChildRepair } = await import("./recovery-operations.js");
1023
- const outcome = await mergeChildRepair(access, {
1024
- epicRunId: parsed.epicRunId,
1025
- prNumber: parsed.prNumber,
1274
+ // BAPI-1461: this verb runs in the person's own session, so a merge token
1275
+ // stored once for this repository is the last rung after the env keys.
1276
+ const outcome = await mergeChildRepair(access, { epicRunId: parsed.epicRunId, prNumber: parsed.prNumber }, {
1277
+ storedMergeCredential: {
1278
+ allowStoredEntry: true,
1279
+ localRemote: await readLocalGithubRemote(process.cwd()),
1280
+ storeDeps: nodeGithubMergeCredentialReadDeps(process.env),
1281
+ },
1026
1282
  });
1027
1283
  return renderRepairResult(outcome, {
1028
1284
  verb: "merge-child",
@@ -1336,11 +1592,17 @@ export async function runResumeRunCommand(argv) {
1336
1592
  // ---------------------------------------------------------------------------
1337
1593
  // continue-child / continuation-receipt (BAPI-1300)
1338
1594
  // ---------------------------------------------------------------------------
1339
- const CONTINUE_CHILD_VALUE_FLAGS = new Set(["--epic-run-id", "--ticket-key", "--reason", "--worker-exit-proof"]);
1595
+ const CONTINUE_CHILD_VALUE_FLAGS = new Set([
1596
+ "--epic-run-id",
1597
+ "--ticket-key",
1598
+ "--reason",
1599
+ "--worker-exit-proof",
1600
+ "--context-file",
1601
+ ]);
1340
1602
  const CONTINUATION_RECEIPT_VALUE_FLAGS = new Set(["--epic-run-id", "--ticket-key", "--request-id"]);
1341
1603
  const MAX_REASON_CHARS = 500;
1342
1604
  const CONTINUE_CHILD_USAGE = [
1343
- "Usage: epic-implementer continue-child --epic-run-id <id> --ticket-key <key> [--reason <text> --worker-exit-proof exited|fenced] [--json]",
1605
+ "Usage: epic-implementer continue-child --epic-run-id <id> --ticket-key <key> [--reason <text> --worker-exit-proof exited|fenced] [--context-file <path>] [--json]",
1344
1606
  "",
1345
1607
  "Continue a parked child's CURRENT park episode without resetting it: the same",
1346
1608
  "attempt resumes on its retained work with only the allowance it has left (no",
@@ -1351,6 +1613,18 @@ const CONTINUE_CHILD_USAGE = [
1351
1613
  "committed. Re-running continue-child reuses the SAME request (it never",
1352
1614
  "approves a new head or episode); continuation-receipt looks the receipt up.",
1353
1615
  "Never accepts a version counter or a park generation.",
1616
+ "",
1617
+ "--context-file (CI-repair continuations only): driver context for the repair",
1618
+ "worker, sent beside --reason (never merged into it). It must be non-empty UTF-8",
1619
+ `text of at most DRIVER_CONTEXT_MAX_BYTES (${DRIVER_CONTEXT_MAX_BYTES} bytes); it is`,
1620
+ "rejected, never truncated, and is never printed, logged, or echoed. A re-run of",
1621
+ "a pending request must pass the same file. A server that does not support it",
1622
+ "rejects the request (exit 1); it is never retried without the context.",
1623
+ "",
1624
+ "When CI is already green at the bound head, the server resumes the child",
1625
+ "without a repair: no job is dispatched and no allowance is charged (exit 0).",
1626
+ "While CI is still running or unreadable, nothing is written; re-run the same",
1627
+ "command later — it re-sends the SAME request.",
1354
1628
  ].join("\n");
1355
1629
  const CONTINUATION_RECEIPT_USAGE = [
1356
1630
  "Usage: epic-implementer continuation-receipt --epic-run-id <id> --ticket-key <key> [--request-id <id>] [--json]",
@@ -1381,12 +1655,14 @@ function parseContinuationArgs(argv, valueFlags) {
1381
1655
  if (requestId !== undefined && !/^[A-Za-z0-9][A-Za-z0-9._:-]{7,63}$/.test(requestId)) {
1382
1656
  throw new ConductorValidationError('Flag "--request-id" is not a valid request id.');
1383
1657
  }
1658
+ const contextFile = values.has("--context-file") ? requireFlag(values, "--context-file") : undefined;
1384
1659
  return {
1385
1660
  epicRunId,
1386
1661
  ticketKey,
1387
1662
  ...(reason ? { reason } : {}),
1388
1663
  ...(workerExitProof ? { workerExitProof: workerExitProof } : {}),
1389
1664
  ...(requestId ? { requestId } : {}),
1665
+ ...(contextFile !== undefined ? { contextFile } : {}),
1390
1666
  json: bools.has("--json"),
1391
1667
  help: false,
1392
1668
  };
@@ -1441,12 +1717,40 @@ function currentLine(current) {
1441
1717
  return (`Current: parked at gate ${current.parked_gate} (episode ${current.park_generation}${age}); ` +
1442
1718
  `${available}.`);
1443
1719
  }
1720
+ // BAPI-1514 — presentation of the CI-aware continuation refusals (closed codes).
1721
+ const CI_GREEN_ADOPTED_REASON = "ci_green_adopted";
1722
+ const CI_GREEN_ADOPTED_TEXT = "already resolved — resumed without repair; no repair job was dispatched and no " +
1723
+ "continuation allowance was charged";
1724
+ const CI_WAITING_TEXT = {
1725
+ ci_pending_at_bound_head: "CI is still running at the bound head.",
1726
+ ci_provider_read_unavailable: "the CI read failed or timed out.",
1727
+ ci_observation_stale: "the pull-request head moved while CI was being read.",
1728
+ };
1729
+ const CI_WAITING_WHEN = {
1730
+ ci_pending_at_bound_head: " after CI finishes",
1731
+ ci_provider_read_unavailable: " after the CI provider recovers",
1732
+ ci_observation_stale: " now (the server re-reads CI)",
1733
+ };
1734
+ const CI_ROUTE_GUIDANCE = {
1735
+ ci_route_conflict: "The pull request is conflicting, so a CI repair is the wrong exit. Resolve the conflict " +
1736
+ "instead (rebase / overlap reconciliation via dispatch-remediation). No repair was dispatched.",
1737
+ ci_route_rerun: "This is an infrastructure CI failure; the server's infrastructure re-run path owns it " +
1738
+ "(rerun-ci). No repair was dispatched.",
1739
+ ci_route_hold: "CI routing is holding; no widened repair was dispatched. Re-read the run state " +
1740
+ "(explain-run) before choosing another action.",
1741
+ driver_context_not_supported: "--context-file applies only to a CI-repair (ci_fix) continuation. Drop --context-file " +
1742
+ "and re-run with --reason only. Nothing was written.",
1743
+ };
1444
1744
  /** Exported for tests: render a `continue-child` result. Returns the exit code. */
1445
1745
  export function renderContinueChildResult(result, target, json) {
1446
1746
  const label = `Ticket ${target.ticketKey} (run ${target.epicRunId})`;
1447
1747
  if (result.kind === "decided") {
1448
1748
  const r = result.result;
1449
- const ok = r.outcome === "committed" || r.outcome === "already_continued";
1749
+ const greenAdopted = r.outcome === "refused" && r.reason_code === CI_GREEN_ADOPTED_REASON;
1750
+ const ok = r.outcome === "committed" || r.outcome === "already_continued" || greenAdopted;
1751
+ // BAPI-1514 — only a committed receipt for THIS request is a real dispatch,
1752
+ // and only that may count against an intervention budget or allowance.
1753
+ const dispatched = continuationDispatchedJob(r);
1450
1754
  if (json) {
1451
1755
  console.log(JSON.stringify({
1452
1756
  ok,
@@ -1457,6 +1761,9 @@ export function renderContinueChildResult(result, target, json) {
1457
1761
  replayed: r.replayed,
1458
1762
  retryable: r.retryable,
1459
1763
  reference_reused: result.reusedReference,
1764
+ dispatched,
1765
+ allowance_charged: dispatched,
1766
+ ...(greenAdopted ? { resolved_without_repair: true } : {}),
1460
1767
  receipt: r.receipt === null ? null : receiptSummary(r.receipt),
1461
1768
  current: currentSummary(r.current),
1462
1769
  }));
@@ -1486,7 +1793,27 @@ export function renderContinueChildResult(result, target, json) {
1486
1793
  console.error(`${label}: continuation UNSUPPORTED (${r.reason_code}) — ${r.explanation}`);
1487
1794
  return 1;
1488
1795
  default:
1796
+ if (greenAdopted) {
1797
+ console.log(`${label}: ${CI_GREEN_ADOPTED_TEXT}.`);
1798
+ if (r.current)
1799
+ console.log(currentLine(r.current));
1800
+ return 0;
1801
+ }
1802
+ if (r.reason_code !== null && CONTINUATION_CI_WAITING_REASONS.has(r.reason_code)) {
1803
+ console.error(`${label}: WAITING (${r.reason_code}) — ${CI_WAITING_TEXT[r.reason_code] ?? r.explanation}`);
1804
+ console.error(`Nothing was written: no repair job was dispatched and no continuation allowance was charged. ` +
1805
+ `Re-run the same continue-child command${CI_WAITING_WHEN[r.reason_code] ?? ""}; it re-sends ` +
1806
+ `the SAME request (${result.requestId}).`);
1807
+ if (r.current?.expected_head_sha) {
1808
+ console.error(`Bound head: ${r.current.expected_head_sha}.`);
1809
+ }
1810
+ return 1;
1811
+ }
1489
1812
  console.error(`${label}: continuation REFUSED (${r.reason_code}) — ${r.explanation}`);
1813
+ if (r.reason_code !== null && CI_ROUTE_GUIDANCE[r.reason_code] !== undefined) {
1814
+ console.error(CI_ROUTE_GUIDANCE[r.reason_code]);
1815
+ return 1;
1816
+ }
1490
1817
  if (r.retryable)
1491
1818
  console.error("This refusal is retryable; nothing was written.");
1492
1819
  return 1;
@@ -1505,6 +1832,11 @@ export function renderContinueChildResult(result, target, json) {
1505
1832
  }
1506
1833
  console.error(`${label}: request REJECTED before anything was written (status ${result.status}` +
1507
1834
  `${result.errorCode ? `, ${result.errorCode}` : ""}).`);
1835
+ if (result.driverContextSent && result.status === 422) {
1836
+ console.error("The request carried --context-file driver context. This server may not support it yet; " +
1837
+ "the request was NOT retried without it. Upgrade the server, or drop --context-file " +
1838
+ "deliberately and re-run.");
1839
+ }
1508
1840
  return 1;
1509
1841
  }
1510
1842
  if (result.kind === "not_continuable") {
@@ -1588,13 +1920,26 @@ export function renderContinuationReceiptResult(result, target, json) {
1588
1920
  console.log(currentLine(status.current));
1589
1921
  return 0;
1590
1922
  }
1591
- export async function runContinueChildCommand(argv) {
1923
+ export async function runContinueChildCommand(argv, deps = {}) {
1592
1924
  try {
1593
1925
  const parsed = parseContinueChildArgs(argv);
1594
1926
  if (parsed.help) {
1595
1927
  console.log(CONTINUE_CHILD_USAGE);
1596
1928
  return 0;
1597
1929
  }
1930
+ // BAPI-1514 — read and validate the context BEFORE credentials are resolved,
1931
+ // exactly as dispatch-remediation does, so an invalid file reaches no one.
1932
+ let driverContext;
1933
+ if (parsed.contextFile !== undefined) {
1934
+ let bytes;
1935
+ try {
1936
+ bytes = await (deps.readFile ?? ((p) => readFile(p)))(parsed.contextFile);
1937
+ }
1938
+ catch {
1939
+ throw new ConductorValidationError("--context-file could not be read; nothing was sent.");
1940
+ }
1941
+ driverContext = decodeDriverContextFile(bytes);
1942
+ }
1598
1943
  const access = await resolveRecoveryAccess(parsed.json);
1599
1944
  if (!access)
1600
1945
  return 1;
@@ -1604,6 +1949,7 @@ export async function runContinueChildCommand(argv) {
1604
1949
  ticketKey: parsed.ticketKey,
1605
1950
  ...(parsed.reason ? { reason: parsed.reason } : {}),
1606
1951
  ...(parsed.workerExitProof ? { workerExitProof: parsed.workerExitProof } : {}),
1952
+ ...(driverContext !== undefined ? { driverContext } : {}),
1607
1953
  });
1608
1954
  return renderContinueChildResult(result, parsed, parsed.json);
1609
1955
  }
@@ -1651,8 +1997,18 @@ export async function runGrantContinuationCommand(argv) {
1651
1997
  return 1;
1652
1998
  }
1653
1999
  const { requestId, outcome: result } = operation;
1654
- if (json)
1655
- console.log(JSON.stringify({ ...result, request_id: requestId }));
2000
+ if (json) {
2001
+ console.log(JSON.stringify(result.kind === "result"
2002
+ ? {
2003
+ kind: result.kind,
2004
+ committed: result.committed,
2005
+ replayed: result.replayed,
2006
+ request_id: requestId,
2007
+ source_park_generation: result.sourceParkGeneration,
2008
+ gate: result.gate,
2009
+ }
2010
+ : { ...result, request_id: requestId }));
2011
+ }
1656
2012
  else if (result.kind === "result")
1657
2013
  console.log(`Grant ${result.replayed ? "replayed" : "committed"}: ${requestId}. The child remains parked.`);
1658
2014
  else if (result.kind === "unconfirmed")
@@ -1924,8 +2280,280 @@ export async function runResumeCiCommand(argv) {
1924
2280
  return RESUME_CI_EXIT_FAILED;
1925
2281
  }
1926
2282
  }
2283
+ // ---------------------------------------------------------------------------
2284
+ // BAPI-1532 — regenerate-plan
2285
+ // ---------------------------------------------------------------------------
2286
+ const REGENERATE_PLAN_USAGE = [
2287
+ "Usage: epic-implementer regenerate-plan --epic-run-id <id> --ticket-key <key>",
2288
+ " --route <test|implementation> --reason <text> [--json]",
2289
+ "",
2290
+ "Answer a child parked on a NAMED plan failure with ONE forced plan regeneration on",
2291
+ "the route you choose. The server checks the failure reason's finite allowance, then",
2292
+ "commits the route override, the gate reset, and its audit event together.",
2293
+ "",
2294
+ "Success means the override and reset COMMITTED. It does not mean a usable plan",
2295
+ "exists: request the plan and poll get_plan until it shows plan_metadata_status: ok.",
2296
+ "",
2297
+ "The operation is pinned locally before it is sent; re-running after a lost response",
2298
+ "reuses it and reports the original result. Nothing else is tried.",
2299
+ "",
2300
+ "Exit codes: 0 committed or replayed; 2 refused or stale; 3 unconfirmed; 1 other failure.",
2301
+ ].join("\n");
2302
+ export const REGENERATE_PLAN_EXIT_OK = 0;
2303
+ export const REGENERATE_PLAN_EXIT_FAILED = 1;
2304
+ export const REGENERATE_PLAN_EXIT_REFUSED = 2;
2305
+ export const REGENERATE_PLAN_EXIT_UNCONFIRMED = 3;
2306
+ /** The fixed text a server that lacks the route is reported under. */
2307
+ export const REGENERATE_PLAN_SERVER_TOO_OLD = "server too old";
2308
+ export function parseRegeneratePlanArgs(argv) {
2309
+ const { values, bools } = tokenizeRecoveryFlags(argv, new Set([...TICKET_VALUE_FLAGS, "--route", "--reason"]), RECOVERY_BOOL_FLAGS);
2310
+ if (bools.has("--help")) {
2311
+ return { epicRunId: "", ticketKey: "", route: "test", json: bools.has("--json"), help: true };
2312
+ }
2313
+ const epicRunId = values.get("--epic-run-id");
2314
+ if (epicRunId === undefined || epicRunId.trim().length === 0) {
2315
+ throw new ConductorValidationError('Flag "--epic-run-id" is required and must be non-empty.');
2316
+ }
2317
+ const ticketKey = values.get("--ticket-key");
2318
+ if (ticketKey === undefined || ticketKey.trim().length === 0) {
2319
+ throw new ConductorValidationError('Flag "--ticket-key" is required and must be non-empty.');
2320
+ }
2321
+ const route = values.get("--route")?.trim();
2322
+ if (route !== "test" && route !== "implementation") {
2323
+ throw new ConductorValidationError('Flag "--route" is required and must be "test" or "implementation".');
2324
+ }
2325
+ const reason = values.get("--reason")?.trim();
2326
+ if (reason === undefined || reason.length === 0) {
2327
+ throw new ConductorValidationError('Flag "--reason" is required and must be non-empty.');
2328
+ }
2329
+ return {
2330
+ epicRunId: epicRunId.trim(),
2331
+ ticketKey: ticketKey.trim(),
2332
+ route,
2333
+ reason,
2334
+ json: bools.has("--json"),
2335
+ help: false,
2336
+ };
2337
+ }
2338
+ /** Fixed operator sentences, chosen by the server's structured code. */
2339
+ const REGENERATE_PLAN_REFUSAL_SENTENCES = {
2340
+ TICKET_NOT_IN_RUN: "the ticket is not part of this run",
2341
+ NOT_FOUND: "the run or ticket was not found",
2342
+ PLAN_REGEN_NOT_ELIGIBLE: "the ticket is not parked on a named plan failure at the implement gate",
2343
+ PLAN_REGEN_OPERATION_CONFLICT: "this operation already names a different regeneration",
2344
+ PLAN_REGEN_ANSWERED_CONFLICT: "this park was already answered with a different route",
2345
+ PLAN_REGEN_STALE_PARK: "the ticket is on a different park than this request was made for",
2346
+ PLAN_REGEN_ALLOWANCE_SPENT: "every regeneration this failure reason allows has been used",
2347
+ PLAN_REGEN_ROUTE_NOT_ALLOWED: "that route is not the one the next regeneration allows",
2348
+ PLAN_REGEN_RUN_NOT_ACTIVE: "the run is paused, stopped, quarantined, or not active",
2349
+ PLAN_REGEN_BUSY: "the ticket or run stayed busy for the whole bounded wait",
2350
+ PLAN_REGEN_SCHEMA_UNAVAILABLE: "the server database has not been migrated for this action yet",
2351
+ SPEC_SNAPSHOT_UNAVAILABLE: "the ticket's current specification could not be read",
2352
+ CONFLICT: "the ticket kept changing while the request was being applied",
2353
+ };
2354
+ const REGENERATE_PLAN_GUIDANCE = "Read `epic-implementer explain-run` for the ticket's current park and next action.";
2355
+ const REGENERATE_PLAN_NOT_ELIGIBLE_TEXT = {
2356
+ ticket_not_found: "the ticket is not part of this run",
2357
+ not_parked: "the ticket is not parked",
2358
+ not_implement_park: "the ticket is not parked at the implement gate",
2359
+ no_plan_failure: "the park has no named plan failure (a legacy or unrelated park)",
2360
+ park_superseded: "the plan failure was already answered or belongs to an earlier park",
2361
+ };
2362
+ /**
2363
+ * Exported for tests: render a `regenerate-plan` result.
2364
+ *
2365
+ * Committed and replayed results go to stdout with exit 0 (JSON stdout stays
2366
+ * machine-readable; progress goes to stderr). Refused, stale, unconfirmed, and
2367
+ * failed outcomes go to stderr with their own non-zero codes. No operation key,
2368
+ * row version, credential, server exception, or URL is ever printed.
2369
+ */
2370
+ export function renderRegeneratePlanResult(result, target, json) {
2371
+ const label = `ticket ${target.ticketKey} (run ${target.epicRunId})`;
2372
+ if (result.kind === "committed" || result.kind === "replayed" || result.kind === "answered_replay") {
2373
+ const r = result.result;
2374
+ if (json) {
2375
+ console.log(JSON.stringify({
2376
+ ok: true,
2377
+ outcome: result.kind,
2378
+ historical: result.kind !== "committed",
2379
+ epic_run_id: r.epic_run_id,
2380
+ ticket_key: r.ticket_key,
2381
+ accepted_route: r.accepted_route,
2382
+ answered_park_generation: r.answered_park_generation,
2383
+ ticket_status: r.ticket_status,
2384
+ plan_ready: false,
2385
+ reference_reused: result.reusedReference,
2386
+ }));
2387
+ return REGENERATE_PLAN_EXIT_OK;
2388
+ }
2389
+ if (result.kind === "committed") {
2390
+ console.log(`Committed: the ${r.accepted_route} route override and the gate reset for ${label}. ` +
2391
+ "This does NOT mean a usable plan exists.");
2392
+ console.log("Next: request the plan and poll get_plan until it shows plan_metadata_status: ok.");
2393
+ }
2394
+ else {
2395
+ console.log(`Replayed historical result: regenerate-plan for ${label} committed earlier on the ` +
2396
+ `${r.accepted_route} route. Nothing was changed by this call.`);
2397
+ console.log("This does not show that a usable plan exists.");
2398
+ }
2399
+ return REGENERATE_PLAN_EXIT_OK;
2400
+ }
2401
+ if (result.kind === "unsupported_server") {
2402
+ // The server predates the route. Nothing was written and no other mutation
2403
+ // stands in for it.
2404
+ if (json) {
2405
+ console.error(JSON.stringify({
2406
+ ok: false,
2407
+ outcome: "unsupported_server",
2408
+ message: REGENERATE_PLAN_SERVER_TOO_OLD,
2409
+ nothing_written: true,
2410
+ }));
2411
+ }
2412
+ else {
2413
+ console.error(REGENERATE_PLAN_SERVER_TOO_OLD);
2414
+ }
2415
+ return REGENERATE_PLAN_EXIT_FAILED;
2416
+ }
2417
+ if (result.kind === "refused" || result.kind === "not_eligible" ||
2418
+ result.kind === "stale_subject" || result.kind === "pinned_mismatch") {
2419
+ let code;
2420
+ let sentence;
2421
+ if (result.kind === "refused") {
2422
+ code = result.errorCode;
2423
+ sentence = REGENERATE_PLAN_REFUSAL_SENTENCES[code] ?? "the server refused the request";
2424
+ }
2425
+ else if (result.kind === "stale_subject") {
2426
+ code = "REPAIR_SUBJECT_STALE";
2427
+ sentence = "the ticket is no longer on the park this operation was made for";
2428
+ }
2429
+ else if (result.kind === "pinned_mismatch") {
2430
+ code = "PLAN_REGEN_PINNED_ROUTE";
2431
+ sentence =
2432
+ `an earlier unconfirmed regenerate-plan is pinned on the ${result.pinnedRoute} route; ` +
2433
+ "re-run it with that route";
2434
+ }
2435
+ else {
2436
+ code = "PLAN_REGEN_NOT_ELIGIBLE";
2437
+ sentence = REGENERATE_PLAN_NOT_ELIGIBLE_TEXT[result.reason] ?? "regenerate-plan does not apply";
2438
+ }
2439
+ if (json) {
2440
+ console.error(JSON.stringify({
2441
+ ok: false,
2442
+ outcome: "refused",
2443
+ refusal_code: code,
2444
+ ...(result.kind === "not_eligible" ? { local_reason: result.reason } : {}),
2445
+ message: sentence,
2446
+ guidance: REGENERATE_PLAN_GUIDANCE,
2447
+ nothing_written: true,
2448
+ }));
2449
+ return REGENERATE_PLAN_EXIT_REFUSED;
2450
+ }
2451
+ console.error(`Refused: regenerate-plan for ${label} — ${sentence}. Nothing was written.`);
2452
+ console.error(REGENERATE_PLAN_GUIDANCE);
2453
+ return REGENERATE_PLAN_EXIT_REFUSED;
2454
+ }
2455
+ if (result.kind === "unconfirmed") {
2456
+ if (json) {
2457
+ console.error(JSON.stringify({
2458
+ ok: false,
2459
+ outcome: "unconfirmed",
2460
+ transport: result.transport,
2461
+ attempts: result.attempts,
2462
+ }));
2463
+ return REGENERATE_PLAN_EXIT_UNCONFIRMED;
2464
+ }
2465
+ console.error(`Unconfirmed: regenerate-plan for ${label} — no durable answer arrived after ${result.attempts} ` +
2466
+ `attempts (${result.transport}). The regeneration may or may not have committed.`);
2467
+ console.error("Re-run the same command later: it reuses this same operation and reports its original " +
2468
+ "result. Do not use unpark or another recovery in the meantime.");
2469
+ return REGENERATE_PLAN_EXIT_UNCONFIRMED;
2470
+ }
2471
+ const message = result.kind === "unavailable" ? result.message : "the outcome could not be read";
2472
+ if (json) {
2473
+ console.error(JSON.stringify({ ok: false, outcome: "failed", message }));
2474
+ }
2475
+ else {
2476
+ console.error(`Failed: regenerate-plan for ${label} — ${message}.`);
2477
+ }
2478
+ return REGENERATE_PLAN_EXIT_FAILED;
2479
+ }
2480
+ export async function runRegeneratePlanCommand(argv) {
2481
+ try {
2482
+ const parsed = parseRegeneratePlanArgs(argv);
2483
+ if (parsed.help) {
2484
+ console.log(REGENERATE_PLAN_USAGE);
2485
+ return 0;
2486
+ }
2487
+ const access = await resolveRecoveryAccess(parsed.json);
2488
+ if (!access)
2489
+ return REGENERATE_PLAN_EXIT_FAILED;
2490
+ const { regeneratePlanOnce } = await import("./recovery-operations.js");
2491
+ if (!parsed.json) {
2492
+ // Progress goes to stderr so stdout stays the result alone.
2493
+ console.error(`Requesting plan regeneration for ticket ${parsed.ticketKey} on the ${parsed.route} route...`);
2494
+ }
2495
+ const result = await regeneratePlanOnce(access, {
2496
+ epicRunId: parsed.epicRunId,
2497
+ ticketKey: parsed.ticketKey,
2498
+ route: parsed.route,
2499
+ reason: parsed.reason ?? "",
2500
+ });
2501
+ return renderRegeneratePlanResult(result, parsed, parsed.json);
2502
+ }
2503
+ catch (error) {
2504
+ console.error(`Error: ${toConductorErrorEnvelope(error).message}`);
2505
+ return REGENERATE_PLAN_EXIT_FAILED;
2506
+ }
2507
+ }
2508
+ const ESCALATE_FALLBACK_MESSAGE = "Escalation request refused or unavailable.";
2509
+ /**
2510
+ * Build the safe failure document for `escalate`. Reads ONLY a bridge error's
2511
+ * `errorCode`, `status`, and already-redacted `bodyPreview`; every other failure
2512
+ * gets a stable local code and a fixed message. Arbitrary exception text is never
2513
+ * inspected, and no command-specific redaction is added here.
2514
+ */
2515
+ export function formatEscalateError(error) {
2516
+ // Recognized by name rather than `instanceof`: the client module is imported
2517
+ // lazily inside the command, so this formatter does not load it.
2518
+ if (error instanceof Error && error.name === "ConductorBridgeApiError") {
2519
+ const bridge = error;
2520
+ const preview = typeof bridge.bodyPreview === "string" ? bridge.bodyPreview.trim() : "";
2521
+ return {
2522
+ ok: false,
2523
+ error_code: typeof bridge.errorCode === "string" && bridge.errorCode.length > 0
2524
+ ? bridge.errorCode
2525
+ : "ESCALATE_REQUEST_FAILED",
2526
+ status: typeof bridge.status === "number" ? bridge.status : null,
2527
+ message: preview.length > 0 ? preview : ESCALATE_FALLBACK_MESSAGE,
2528
+ };
2529
+ }
2530
+ if (error instanceof ConductorValidationError) {
2531
+ return {
2532
+ ok: false,
2533
+ error_code: "ESCALATE_INVALID_ARGUMENTS",
2534
+ status: null,
2535
+ message: "Invalid escalate arguments; run with --help for usage.",
2536
+ };
2537
+ }
2538
+ return {
2539
+ ok: false,
2540
+ error_code: "ESCALATE_UNEXPECTED_FAILURE",
2541
+ status: null,
2542
+ message: ESCALATE_FALLBACK_MESSAGE,
2543
+ };
2544
+ }
1927
2545
  /** No state mutation: callers halt the affected work before asking a question. */
1928
2546
  export async function runEscalateCommand(argv, deps = {}) {
2547
+ // Captured before parsing can throw, so a malformed command line still answers
2548
+ // in the format the caller asked for.
2549
+ const json = argv.includes("--json");
2550
+ const fail = (document) => {
2551
+ if (json)
2552
+ console.log(JSON.stringify(document));
2553
+ else
2554
+ console.error(`Error: ${document.error_code}: ${document.message}`);
2555
+ return 1;
2556
+ };
1929
2557
  try {
1930
2558
  const { values, bools } = tokenizeRecoveryFlags(argv, new Set(["--epic-run-id", "--ticket-key", "--cause", "--action-needed"]), RECOVERY_BOOL_FLAGS);
1931
2559
  if (bools.has("--help")) {
@@ -1936,18 +2564,32 @@ export async function runEscalateCommand(argv, deps = {}) {
1936
2564
  ticketKey: requireFlag(values, "--ticket-key"), cause: requireFlag(values, "--cause"),
1937
2565
  actionNeeded: requireFlag(values, "--action-needed") };
1938
2566
  if (request.actionNeeded.length > 300) {
1939
- console.error("Error: action-needed exceeds 300 characters");
1940
- return 1;
2567
+ return fail({
2568
+ ok: false,
2569
+ error_code: "ESCALATE_INVALID_ARGUMENTS",
2570
+ status: null,
2571
+ message: "action-needed exceeds 300 characters",
2572
+ });
2573
+ }
2574
+ const resolveAccess = deps.resolveAccess ?? (async () => {
2575
+ const { resolveConductorBridgeApiAccess } = await import("./bridge-api-client.js");
2576
+ const resolved = await resolveConductorBridgeApiAccess();
2577
+ return resolved.ok ? resolved.access : null;
2578
+ });
2579
+ const access = await resolveAccess();
2580
+ if (!access) {
2581
+ return fail({
2582
+ ok: false,
2583
+ error_code: "ESCALATE_CREDENTIALS_UNAVAILABLE",
2584
+ status: null,
2585
+ message: "Bridge API credentials could not be resolved.",
2586
+ });
1941
2587
  }
1942
- const access = await (deps.resolveAccess ?? (() => resolveRecoveryAccess(false)))();
1943
- if (!access)
1944
- return 1;
1945
2588
  const escalate = deps.escalate ?? (await import("./bridge-api-client.js")).escalateTicket;
1946
2589
  console.log(JSON.stringify(await escalate(access, request)));
1947
2590
  return 0;
1948
2591
  }
1949
- catch {
1950
- console.error("Error: escalation request refused or unavailable");
1951
- return 1;
2592
+ catch (error) {
2593
+ return fail(formatEscalateError(error));
1952
2594
  }
1953
2595
  }