@bridge_gpt/mcp-server 0.2.74 → 0.2.76

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 (102) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/prompt.js +9 -21
  3. package/build/agents.generated.js +6 -6
  4. package/build/authored-plan.js +542 -0
  5. package/build/bridge-permissions.js +8 -0
  6. package/build/codex-auto-recovery.js +25 -7
  7. package/build/commands.generated.js +7 -7
  8. package/build/conductor/bridge-api-client.js +807 -52
  9. package/build/conductor/declare-blocked.js +4 -0
  10. package/build/conductor/driver-pass.js +8 -0
  11. package/build/conductor/epic-implementer-cli.js +341 -96
  12. package/build/conductor/epic-server-journal.js +13 -0
  13. package/build/conductor/epic-server-recipe.js +15 -5
  14. package/build/conductor/epic-server-runtime.js +163 -45
  15. package/build/conductor/epic-server.js +13 -6
  16. package/build/conductor/gate-discovery.js +209 -9
  17. package/build/conductor/gate-settings-review.js +7 -11
  18. package/build/conductor/install-doctor.js +30 -2
  19. package/build/conductor/launch-plan.js +58 -12
  20. package/build/conductor/local-merge.js +54 -12
  21. package/build/conductor/open-decision-phrases.js +50 -0
  22. package/build/conductor/pr-ci-producer.js +12 -3
  23. package/build/conductor/prerequisite-inputs.js +181 -14
  24. package/build/conductor/readiness-sections.js +46 -13
  25. package/build/conductor/readiness.js +3 -40
  26. package/build/conductor/recovery-cli.js +12 -12
  27. package/build/conductor/repository-workflow-remedy.js +147 -7
  28. package/build/conductor/ui-readiness.js +224 -0
  29. package/build/conductor/wait-run-attention.js +9 -4
  30. package/build/conductor/wait-run-cli.js +9 -2
  31. package/build/connect-github-api.js +18 -0
  32. package/build/connect-github.js +35 -18
  33. package/build/docs.generated.js +3 -3
  34. package/build/drive-epic.js +787 -37
  35. package/build/epic-ci-workflow.js +3 -2
  36. package/build/epic-implementer-bin.js +200 -66
  37. package/build/epic-implementer-bundle-cli.js +61 -0
  38. package/build/epic-implementer-claude-hook-bin.js +1 -1
  39. package/build/epic-implementer-env.js +3 -4
  40. package/build/epic-integration-pr.js +5 -2
  41. package/build/epic-launch-context.js +8 -1
  42. package/build/epic-shared/cut-protocol.js +55 -3
  43. package/build/executor/completion-contract.js +24 -1
  44. package/build/executor/failure-reason-codes.js +2 -0
  45. package/build/executor/gate-qualification-job.js +193 -23
  46. package/build/executor/gate-qualification-tests-ran.js +232 -0
  47. package/build/executor/integration-job.js +56 -2
  48. package/build/executor/job-runner.js +13 -723
  49. package/build/executor/job-type-wrappers.js +734 -0
  50. package/build/executor/merge-job.js +45 -1
  51. package/build/executor/permissions.js +187 -2
  52. package/build/executor/preflight.js +6 -2
  53. package/build/executor/process-containment.js +8 -1
  54. package/build/executor/provider-checks.js +28 -5
  55. package/build/executor/reconcile-overlap-job.js +70 -17
  56. package/build/executor/required-verification.js +28 -2
  57. package/build/executor/required-work-ledger.js +7 -2
  58. package/build/executor/resume-pre-spawn.js +32 -8
  59. package/build/executor/runner.js +30 -5
  60. package/build/executor/types.js +9 -0
  61. package/build/executor/worker-database.js +6 -1
  62. package/build/executor/worker-guard-hook.js +24 -2
  63. package/build/executor/worktree.js +12 -1
  64. package/build/generated/ticket-status.js +20 -0
  65. package/build/index.js +627 -551
  66. package/build/init.js +16 -0
  67. package/build/install-bridge-conductor-answers.js +32 -1
  68. package/build/install-bridge-conductor-apply.js +21 -3
  69. package/build/install-bridge-conductor-assessment.js +185 -12
  70. package/build/install-bridge-conductor-compact.js +2 -0
  71. package/build/install-bridge-conductor-contracts.js +9 -1
  72. package/build/install-bridge-conductor-gate.js +257 -80
  73. package/build/install-bridge-conductor-setup.js +106 -6
  74. package/build/install-bridge-conductor-trial-report.js +170 -0
  75. package/build/install-bridge-conductor.js +740 -124
  76. package/build/mcp-host-config.js +54 -37
  77. package/build/phase-context-git-probe.js +16 -0
  78. package/build/pipelines.generated.js +15 -15
  79. package/build/plan-execution-ledger.js +27 -0
  80. package/build/plan-generation.js +17 -0
  81. package/build/plane/plane-freshness.js +43 -26
  82. package/build/printed-remedy-commands.js +62 -0
  83. package/build/readme.generated.js +1 -1
  84. package/build/repository-toolchains.js +11 -5
  85. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  86. package/build/secret-redaction.js +3 -0
  87. package/build/setup-epic.js +51 -9
  88. package/build/test-support/create-preview-world.js +232 -0
  89. package/build/test-support/executor-source-files.js +1 -1
  90. package/build/ticket-delivery.js +65 -0
  91. package/build/v2-readiness-requirements.js +13 -4
  92. package/build/version.generated.js +3 -3
  93. package/build/worker-guard-hook-bin.js +2 -2
  94. package/build/worktree-core.js +51 -7
  95. package/docs/EPIC-IMPLEMENTER.md +83 -4
  96. package/docs/epic-implementer/getting-started.md +1 -1
  97. package/docs/install/github-app.md +79 -92
  98. package/package.json +1 -1
  99. package/pipelines/implement-ticket.json +2 -2
  100. package/build/conductor/epic-reconcile.js +0 -603
  101. package/build/conductor/epic-runtime.js +0 -2020
  102. package/build/conductor/epic-state.js +0 -774
@@ -117,6 +117,10 @@ export function getDeclareBlockedUsage() {
117
117
  " run-wide blocked, escalated nothing can progress; keep the normal waiter running",
118
118
  " scope unknown supervision continues",
119
119
  "--entry wedge needs --evidence, --tried, --alternatives and --fixer-outcome.",
120
+ `Limits: --requirement ${DECLARE_BLOCKED_LIMITS.requirement}, --evidence ${DECLARE_BLOCKED_LIMITS.evidence}, ` +
121
+ `--tried ${DECLARE_BLOCKED_LIMITS.tried}, --alternatives ${DECLARE_BLOCKED_LIMITS.alternatives}, ` +
122
+ `--fixer-outcome ${DECLARE_BLOCKED_LIMITS.fixerOutcome} characters each; ` +
123
+ `at most ${DECLARE_BLOCKED_LIMITS.tickets} --ticket-key arguments.`,
120
124
  ].join("\n");
121
125
  }
122
126
  const VALUE_FLAGS = new Set([
@@ -182,8 +182,16 @@ function readJobs(block) {
182
182
  * dropped. An accepted job keeps its own timestamp distinctions (missing, null, malformed,
183
183
  * valid), so an unreadable `created_at` stays attributable to its ticket. State jobs need no
184
184
  * heartbeat; that evidence belongs to explain's outstanding jobs.
185
+ *
186
+ * BAPI-1733: one other shape is readable. A block whose `state` is `"unknown"` and whose
187
+ * `empty_reason` is exactly `"no_jobs"` is the server's confirmation that both job sources read
188
+ * clean and the whole run has no jobs, so it reads as an empty map. Bare `unknown`, any other
189
+ * marker, and every other non-available block stay unreadable.
185
190
  */
186
191
  export function readStateJobs(block) {
192
+ if (isRecord(block) && block.state === "unknown" && block.empty_reason === "no_jobs") {
193
+ return new Map();
194
+ }
187
195
  if (!isRecord(block) || block.state !== "available" || !Array.isArray(block.jobs))
188
196
  return "unreadable";
189
197
  const byTicket = new Map();
@@ -23,7 +23,7 @@
23
23
  */
24
24
  import { readFileSync, unlinkSync } from "node:fs";
25
25
  import { createRequire } from "node:module";
26
- import { ConductorValidationError, ConductorEpicTickV1FrozenError, toConductorErrorEnvelope, } from "./errors.js";
26
+ import { ConductorValidationError, toConductorErrorEnvelope, } from "./errors.js";
27
27
  import { emitConductorEvent, purgeConductorLedger, sendWorkerMessage, checkWorkerMessages, } from "./store.js";
28
28
  import { isDuplicateConstraintError } from "./producer-ledger.js";
29
29
  import { SEMANTIC_EVENT_TYPES } from "./taxonomy.js";
@@ -74,8 +74,6 @@ export function getConductorUsage() {
74
74
  "Commands:",
75
75
  " emit-event Append one semantic event to the ledger",
76
76
  " supervise --run-id <id> Run the foreground, run-scoped supervisor loop",
77
- " epic-tick RETIRED (v1): always exits 1 with EPIC_TICK_V1_FROZEN; the",
78
- " server-side reconciler replaced it",
79
77
  " epic-status Print read-only health summary of an Epic Run",
80
78
  " send-message Enqueue ONE typed supervisor->worker relay message (idempotent)",
81
79
  " check-messages Read + ACK pending relay messages for a worker (no redelivery)",
@@ -133,13 +131,23 @@ export function getConductorUsage() {
133
131
  " returns to evaluation with NO new wait, job, or repair allowance.",
134
132
  " rerun-ci --epic-run-id <id> --ticket-key <key> --binding <token> [--json]",
135
133
  " Ask CI to re-run a ticket's FAILED checks at its bound head (guided: copy",
136
- " the command explain-run rendered). Charges NO allowance and never re-runs",
134
+ " the command the `explain_run` MCP tool rendered). Charges NO allowance and never re-runs",
137
135
  " claude-review. A re-run is not a verdict: after CI is green, use resume-ci.",
138
136
  " regenerate-plan --epic-run-id <id> --ticket-key <key> --route test|implementation --reason <text> [--json]",
139
137
  " Answer a child parked on a NAMED plan failure with ONE forced plan",
140
138
  " regeneration on the chosen route. Success means the override and gate",
141
139
  " reset committed, not that a usable plan exists. Prints \"server too old\"",
142
140
  " and exits nonzero on a server without the route; no fallback is tried.",
141
+ " reserve-council --epic-run-id <id> --ticket-key <key> --reservation-key <key>",
142
+ " Reserve ONE open-decision council for a parked child (unattended driver",
143
+ " only; at most 2 per run). Key: <epic_run_id>:<ticket_key>:park-<park_generation>.",
144
+ " A repeated key returns the same row. Prints one JSON object on success.",
145
+ " record-decision --epic-run-id <id> --ticket-key <key> --council-row-id <n>",
146
+ " --council-id <id> [--council-id <id>] --outcome continue|stop|split|no_valid_response",
147
+ " [--decision-file <path>]",
148
+ " Settle a reserved council with EVERY council id it used. continue needs",
149
+ " --decision-file (UTF-8, the selected provider proposal; never echoed);",
150
+ " other outcomes refuse it. A settled continue resets the child's gate.",
143
151
  " resolve-handoff --epic-run-id <id> --ticket-key <key> --steps 27,36 --kind verified|risk_accepted",
144
152
  " --evidence <ref> --reason <text> [--json]",
145
153
  " Record the OWNER's decision on verification hand-offs (a human decision,",
@@ -147,7 +155,7 @@ export function getConductorUsage() {
147
155
  " epic-head commit: the PR leaves draft only when both holds are clear.",
148
156
  " acknowledge-gaps --epic-run-id <id> --digest <CURRENT_DIGEST> --reason <text> [--json]",
149
157
  " The OWNER's one acknowledgement of the run's carried-gap list, by its",
150
- " current digest (from the PR report or explain-run). Never run by the",
158
+ " current digest (from the PR report or the `explain_run` MCP tool). Never run by the",
151
159
  " driver or a worker; it verifies, readies and merges nothing.",
152
160
  " wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>]",
153
161
  " [--until change|attention] [--json] [--watch [--max-minutes <minutes>]]",
@@ -200,6 +208,7 @@ export function getConductorUsage() {
200
208
  " [--evidence <text>] [--tried <verbs>] [--alternatives <text>] [--fixer-outcome <text>]",
201
209
  " Advisory blocker check: not a blocker yet (run <command>), accepted and",
202
210
  " escalated, run-wide blocked, or scope unknown. Never releases supervision.",
211
+ " Limits: epic-implementer declare-blocked --help",
203
212
  "",
204
213
  "supervise options:",
205
214
  " --run-id <id> Run/session identifier to supervise (required)",
@@ -288,11 +297,6 @@ export function getConductorUsage() {
288
297
  " epic-implementer resume-run --epic-run-id <id>",
289
298
  " # a cap_wall_clock pause whose cause is now cleared",
290
299
  "",
291
- "epic-tick options (retired; parsed by no live path):",
292
- " --epic-key <KEY> Epic key to supervise (required, non-empty)",
293
- " --scheduled-at <epoch> Epoch-seconds timestamp when this tick was scheduled (optional)",
294
- " --lease-ttl-seconds <n> Lease TTL in seconds (optional, default 120)",
295
- "",
296
300
  "approve-plan options:",
297
301
  " approve-plan <epic_key> --plan-version N [--json]",
298
302
  " <epic_key> Epic key (e.g. EPIC-405) (required positional)",
@@ -356,7 +360,7 @@ export function getConductorUsage() {
356
360
  " epic-implementer resume-ci --epic-run-id 3f9c2b7e-... --ticket-key PROJ-852",
357
361
  " # CI failed on infrastructure: re-run it (never claude-review); then resume-ci once green:",
358
362
  " epic-implementer rerun-ci --epic-run-id 3f9c2b7e-... --ticket-key PROJ-852 --binding <token>",
359
- " # A child parked on a named plan failure (see explain-run for the route and reason):",
363
+ " # A child parked on a named plan failure (see the `explain_run` MCP tool, not a CLI verb, for the route and reason):",
360
364
  " epic-implementer regenerate-plan --epic-run-id 3f9c2b7e-... --ticket-key PROJ-852 \\",
361
365
  " --route implementation --reason \"The test plan named a target that is not indexed\"",
362
366
  " # The owner accepted the risk of a step a worker could not verify (verification incomplete):",
@@ -386,7 +390,6 @@ export { HOOK_RUNTIME_PROBE_ACTION } from "./hook-runtime-qualification.js";
386
390
  const VALID_COMMANDS = new Set([
387
391
  "emit-event",
388
392
  "supervise",
389
- "epic-tick",
390
393
  "approve-plan",
391
394
  "epic-status",
392
395
  "send-message",
@@ -429,6 +432,9 @@ const VALID_COMMANDS = new Set([
429
432
  "acknowledge-gaps",
430
433
  // BAPI-1532: CLI-only answer to a named plan failure — never an MCP tool.
431
434
  "regenerate-plan",
435
+ // BAPI-1705: CLI-only driver open-decision council pair — never MCP tools.
436
+ "reserve-council",
437
+ "record-decision",
432
438
  // BAPI-1469: CLI-only read-only bounded wait on a run's state — never an MCP tool.
433
439
  "wait-run",
434
440
  // BAPI-1557: CLI-only stored-ticket reader and private local-state writer — never an MCP tool.
@@ -1127,88 +1133,6 @@ export async function runGitHookCommand(argv) {
1127
1133
  }
1128
1134
  }
1129
1135
  // ---------------------------------------------------------------------------
1130
- // epic-tick
1131
- // ---------------------------------------------------------------------------
1132
- const EPIC_TICK_VALUE_FLAGS = new Set([
1133
- "--epic-key",
1134
- "--scheduled-at",
1135
- "--lease-ttl-seconds",
1136
- ]);
1137
- const EPIC_TICK_BOOL_FLAGS = new Set(["--help"]);
1138
- /**
1139
- * Parse `epic-tick` flags. `--epic-key` is required and must be non-empty /
1140
- * non-whitespace. Numeric overrides (`--scheduled-at`, `--lease-ttl-seconds`)
1141
- * are validated as non-negative integers using the shared
1142
- * {@link parsePositiveIntFlag} convention. Malformed input raises a sanitized
1143
- * {@link ConductorValidationError}.
1144
- */
1145
- export function parseEpicTickArgs(argv) {
1146
- const { values, bools } = tokenizeFlags(argv, EPIC_TICK_VALUE_FLAGS, EPIC_TICK_BOOL_FLAGS);
1147
- if (bools.has("--help")) {
1148
- return { epicKey: "", help: true };
1149
- }
1150
- const epicKeyRaw = values.get("--epic-key");
1151
- if (epicKeyRaw === undefined || epicKeyRaw.trim().length === 0) {
1152
- throw new ConductorValidationError('Flag "--epic-key" is required for epic-tick and must be non-empty.');
1153
- }
1154
- const scheduledAt = parsePositiveIntFlag(values, "--scheduled-at");
1155
- const leaseTtlSeconds = parsePositiveIntFlag(values, "--lease-ttl-seconds");
1156
- return { epicKey: epicKeyRaw.trim(), scheduledAt, leaseTtlSeconds, help: false };
1157
- }
1158
- /**
1159
- * Default the PreToolUse hook ON for epic-dispatched workers so the supervisor
1160
- * gets worker-liveness (`tool.intent`) signals without the operator having to
1161
- * export `BAPI_EPIC_IMPLEMENTER_ENABLE_PRE_TOOL_USE=1` (BAPI-441/A1 finding).
1162
- *
1163
- * Both the child-env copy and the hook registration key off this SAME
1164
- * parent-process env flag, read at dispatch time, so setting it once at the
1165
- * epic-tick boundary covers the whole tick. Only defaults when the flag is
1166
- * UNSET — an explicit "0"/"" still disables it, because `isConductorFlagEnabled`
1167
- * treats those as false. Mutates the supplied env in place (defaults to
1168
- * `process.env`) and returns it.
1169
- */
1170
- export function applyEpicTickPreToolUseDefault(env = process.env) {
1171
- if (env.BAPI_EPIC_IMPLEMENTER_ENABLE_PRE_TOOL_USE === undefined) {
1172
- env.BAPI_EPIC_IMPLEMENTER_ENABLE_PRE_TOOL_USE = "1";
1173
- }
1174
- return env;
1175
- }
1176
- /**
1177
- * Run the `epic-tick` command. Lazily imports the epic runtime so a plain
1178
- * `epic-implementer doctor` / `emit-event` invocation never eagerly resolves
1179
- * the epic/store graph.
1180
- */
1181
- export async function runEpicTickCommand(_argv) {
1182
- // BAPI-534 (Epic Conductor v2 slice 0): the v1 epic-tick path is FROZEN. This
1183
- // fail-loud guard is the FIRST executable statement — before argument parsing,
1184
- // `applyEpicTickPreToolUseDefault()`, and any lazy `import("./epic-runtime.js")`
1185
- // — so no v1 tick (or its store/supervisor graph) can ever run. Interactive
1186
- // `/start-tickets` is unaffected. `runEpicImplementerCli` catches this named
1187
- // error and formats it consistently (EPIC_TICK_V1_FROZEN → exit 1).
1188
- throw new ConductorEpicTickV1FrozenError();
1189
- }
1190
- /** @deprecated v1 epic-tick body — retained unreachable behind the freeze guard. */
1191
- export async function runEpicTickCommandLegacy(argv) {
1192
- const parsed = parseEpicTickArgs(argv);
1193
- if (parsed.help) {
1194
- console.log(getConductorUsage());
1195
- return 0;
1196
- }
1197
- // Enable supervisor worker-liveness by default for the whole tick (see the
1198
- // helper's doc comment); set before runEpicTick dispatches any worker.
1199
- applyEpicTickPreToolUseDefault();
1200
- // `runEpicTick` is imported LAZILY so the store/supervisor graph is not
1201
- // evaluated for other epic-implementer CLI commands that never need it.
1202
- const { runEpicTick, buildProductionEpicRuntimeDeps } = await import("./epic-runtime.js");
1203
- const prodDeps = await buildProductionEpicRuntimeDeps(parsed.epicKey);
1204
- const result = await runEpicTick({
1205
- epic_key: parsed.epicKey,
1206
- scheduled_at: parsed.scheduledAt !== undefined ? parsed.scheduledAt * 1000 : undefined,
1207
- lease_ttl_seconds: parsed.leaseTtlSeconds,
1208
- }, prodDeps);
1209
- return result.exit_code;
1210
- }
1211
- // ---------------------------------------------------------------------------
1212
1136
  // approve-plan
1213
1137
  // ---------------------------------------------------------------------------
1214
1138
  const APPROVE_PLAN_VALUE_FLAGS = new Set(["--plan-version"]);
@@ -1623,8 +1547,6 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1623
1547
  return await runEmitEventCommand(parsed.argv);
1624
1548
  case "supervise":
1625
1549
  return await runSuperviseCommand(parsed.argv);
1626
- case "epic-tick":
1627
- return await runEpicTickCommand(parsed.argv);
1628
1550
  case "approve-plan":
1629
1551
  return await runApprovePlanCommand(parsed.argv);
1630
1552
  case "epic-status":
@@ -1752,6 +1674,13 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1752
1674
  const { runRegeneratePlanCommand } = await import("./recovery-cli.js");
1753
1675
  return await runRegeneratePlanCommand(parsed.argv);
1754
1676
  }
1677
+ case "reserve-council": {
1678
+ // BAPI-1705: the API client is imported lazily inside the command.
1679
+ return await runReserveCouncilCommand(parsed.argv);
1680
+ }
1681
+ case "record-decision": {
1682
+ return await runRecordDecisionCommand(parsed.argv);
1683
+ }
1755
1684
  case "wait-run": {
1756
1685
  // BAPI-1469: read-only bounded wait. Lazily imported like the recovery
1757
1686
  // verbs; a module-load failure gets fixed wording, never exception text.
@@ -1871,3 +1800,319 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1871
1800
  return 1;
1872
1801
  }
1873
1802
  }
1803
+ // ---------------------------------------------------------------------------
1804
+ // BAPI-1705 — reserve-council / record-decision (driver open-decision council)
1805
+ // ---------------------------------------------------------------------------
1806
+ //
1807
+ // Two CLI-only verbs the unattended driver runs around one open-decision
1808
+ // council. Stream contract: on success stdout carries exactly one JSON object
1809
+ // and stderr is empty; every failure writes only to stderr and stdout stays
1810
+ // empty. Decision text is read from a local UTF-8 file, sent only in the
1811
+ // request body, and never written to argv, stdout, stderr, or an error message.
1812
+ // The Bridge API client and zod are imported lazily, so no other command loads
1813
+ // them.
1814
+ /** Exit codes, matching `regenerate-plan`: refused parks as today; unconfirmed is re-sent unchanged. */
1815
+ export const DRIVER_COUNCIL_EXIT_OK = 0;
1816
+ export const DRIVER_COUNCIL_EXIT_FAILED = 1;
1817
+ export const DRIVER_COUNCIL_EXIT_REFUSED = 2;
1818
+ export const DRIVER_COUNCIL_EXIT_UNCONFIRMED = 3;
1819
+ /** Decision files above this many bytes are refused before any request. */
1820
+ export const DECISION_FILE_MAX_BYTES = 64 * 1024;
1821
+ const RESERVE_COUNCIL_USAGE = [
1822
+ "Usage: epic-implementer reserve-council --epic-run-id <id> --ticket-key <key> --reservation-key <key> [--json]",
1823
+ "",
1824
+ "Reserve one open-decision council for a parked child. The key is",
1825
+ "<epic_run_id>:<ticket_key>:park-<park_generation>; a repeated key returns the same",
1826
+ "row, so a restart never spends a second council. At most 2 per run.",
1827
+ "Exit codes: 0 reserved (one JSON object on stdout), 1 failed, 2 refused (the child",
1828
+ "stays parked; finish the recovery pass as today), 3 unconfirmed (re-run unchanged).",
1829
+ ].join("\n");
1830
+ const RECORD_DECISION_USAGE = [
1831
+ "Usage: epic-implementer record-decision --epic-run-id <id> --ticket-key <key> --council-row-id <n>",
1832
+ " --council-id <id> [--council-id <id>] --outcome continue|stop|split|no_valid_response",
1833
+ " [--decision-file <path>] [--json]",
1834
+ "",
1835
+ "Settle a reserved council with every council id it used (first request and any retry).",
1836
+ "continue requires --decision-file holding exactly the selected provider proposal",
1837
+ "(UTF-8, never echoed); stop, split and no_valid_response refuse it. An identical",
1838
+ "re-run is a replay and writes nothing new.",
1839
+ "Exit codes: 0 settled (one JSON object on stdout), 1 failed, 2 refused (the child",
1840
+ "stays parked), 3 unconfirmed (re-run unchanged). --json is accepted; output is always JSON.",
1841
+ ].join("\n");
1842
+ const COUNCIL_EPIC_RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
1843
+ const COUNCIL_TICKET_KEY_RE = /^[A-Z][A-Z0-9_]{0,19}-[0-9]{1,12}$/;
1844
+ const COUNCIL_RESERVATION_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,299}$/;
1845
+ const COUNCIL_ROW_ID_RE = /^[1-9][0-9]{0,15}$/;
1846
+ const COUNCIL_REQUEST_ID_RE = /^[0-9A-Fa-f]{8}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{4}-[0-9A-Fa-f]{12}$/;
1847
+ /**
1848
+ * Tokenize council-verb flags. `repeatable` flags collect every value; any other
1849
+ * flag may appear once. Messages name the flag only — never a value — so a
1850
+ * misplaced decision never reaches stderr.
1851
+ */
1852
+ function tokenizeCouncilFlags(argv, valueFlags, repeatable) {
1853
+ const values = new Map();
1854
+ let help = false;
1855
+ for (let i = 0; i < argv.length; i += 1) {
1856
+ const token = argv[i];
1857
+ if (token === "-h" || token === "--help") {
1858
+ help = true;
1859
+ continue;
1860
+ }
1861
+ if (token === "--json") {
1862
+ // Accepted for parity with every other verb: success output is always JSON.
1863
+ continue;
1864
+ }
1865
+ if (!token.startsWith("--")) {
1866
+ throw new ConductorValidationError("Unexpected positional argument; every value must follow its flag.");
1867
+ }
1868
+ const eq = token.indexOf("=");
1869
+ const name = eq >= 0 ? token.slice(0, eq) : token;
1870
+ if (!valueFlags.has(name)) {
1871
+ const safeName = /^--[a-z][a-z0-9-]{0,40}$/.test(name) ? name : "(unrecognized)";
1872
+ throw new ConductorValidationError(`Unknown flag "${safeName}".`);
1873
+ }
1874
+ let value;
1875
+ if (eq >= 0) {
1876
+ value = token.slice(eq + 1);
1877
+ }
1878
+ else {
1879
+ const next = argv[i + 1];
1880
+ if (next === undefined)
1881
+ throw new ConductorValidationError(`Flag "${name}" requires a value.`);
1882
+ value = next;
1883
+ i += 1;
1884
+ }
1885
+ const existing = values.get(name);
1886
+ if (existing !== undefined && !repeatable.has(name)) {
1887
+ throw new ConductorValidationError(`Flag "${name}" may be given only once.`);
1888
+ }
1889
+ values.set(name, [...(existing ?? []), value]);
1890
+ }
1891
+ return { values, help };
1892
+ }
1893
+ /** Turn the first zod issue into a value-free message naming the flag. */
1894
+ function councilIssueMessage(issues) {
1895
+ const issue = issues[0];
1896
+ const key = issue && issue.path.length > 0 ? String(issue.path[0]) : "";
1897
+ const flag = {
1898
+ epicRunId: "--epic-run-id",
1899
+ ticketKey: "--ticket-key",
1900
+ reservationKey: "--reservation-key",
1901
+ councilRowId: "--council-row-id",
1902
+ councilIds: "--council-id",
1903
+ outcome: "--outcome",
1904
+ decisionFile: "--decision-file",
1905
+ };
1906
+ if (key === "decisionFile" || key === "councilIds")
1907
+ return issue.message;
1908
+ if (key in flag)
1909
+ return `Flag "${flag[key]}" is missing or invalid.`;
1910
+ return "Invalid arguments; run with --help for usage.";
1911
+ }
1912
+ function first(values, flag) {
1913
+ return values.get(flag)?.[0];
1914
+ }
1915
+ /** Parse and validate `reserve-council` flags with zod; nothing is sent. */
1916
+ export async function parseReserveCouncilArgs(argv) {
1917
+ const { values, help } = tokenizeCouncilFlags(argv, new Set(["--epic-run-id", "--ticket-key", "--reservation-key"]), new Set());
1918
+ if (help)
1919
+ return { help: true, epicRunId: "", ticketKey: "", reservationKey: "" };
1920
+ const { z } = await import("zod");
1921
+ const schema = z.object({
1922
+ epicRunId: z.string().trim().regex(COUNCIL_EPIC_RUN_ID_RE),
1923
+ ticketKey: z.string().trim().regex(COUNCIL_TICKET_KEY_RE),
1924
+ reservationKey: z.string().trim().regex(COUNCIL_RESERVATION_KEY_RE),
1925
+ });
1926
+ const result = schema.safeParse({
1927
+ epicRunId: first(values, "--epic-run-id"),
1928
+ ticketKey: first(values, "--ticket-key"),
1929
+ reservationKey: first(values, "--reservation-key"),
1930
+ });
1931
+ if (!result.success)
1932
+ throw new ConductorValidationError(councilIssueMessage(result.error.issues));
1933
+ const parsed = result.data;
1934
+ const expectedPrefix = `${parsed.epicRunId}:${parsed.ticketKey}:park-`;
1935
+ if (!parsed.reservationKey.startsWith(expectedPrefix) ||
1936
+ !/^[0-9]{1,12}$/.test(parsed.reservationKey.slice(expectedPrefix.length))) {
1937
+ throw new ConductorValidationError('Flag "--reservation-key" must be <epic_run_id>:<ticket_key>:park-<park_generation> for this run and ticket.');
1938
+ }
1939
+ return { help: false, ...parsed };
1940
+ }
1941
+ /** Parse and validate `record-decision` flags with zod; the decision file is not read here. */
1942
+ export async function parseRecordDecisionArgs(argv) {
1943
+ const { values, help } = tokenizeCouncilFlags(argv, new Set(["--epic-run-id", "--ticket-key", "--council-row-id", "--council-id", "--outcome", "--decision-file"]), new Set(["--council-id"]));
1944
+ if (help) {
1945
+ return { help: true, epicRunId: "", ticketKey: "", councilRowId: 0, councilIds: [], outcome: "stop", decisionFile: null };
1946
+ }
1947
+ const { z } = await import("zod");
1948
+ const schema = z
1949
+ .object({
1950
+ epicRunId: z.string().trim().regex(COUNCIL_EPIC_RUN_ID_RE),
1951
+ ticketKey: z.string().trim().regex(COUNCIL_TICKET_KEY_RE),
1952
+ councilRowId: z.string().trim().regex(COUNCIL_ROW_ID_RE).transform(Number).pipe(z.number().int().positive().max(Number.MAX_SAFE_INTEGER)),
1953
+ councilIds: z
1954
+ .array(z.string().trim().regex(COUNCIL_REQUEST_ID_RE, { message: 'Every "--council-id" must be a council request id (a UUID).' }))
1955
+ .min(1, { message: 'At least one "--council-id" is required: pass every council id this council used.' })
1956
+ .max(20, { message: 'Too many "--council-id" values (at most 20).' }),
1957
+ outcome: z.enum(["continue", "stop", "split", "no_valid_response"]),
1958
+ decisionFile: z.string().min(1, { message: 'Flag "--decision-file" must name a file.' }).nullable(),
1959
+ })
1960
+ .superRefine((value, ctx) => {
1961
+ if (value.outcome === "continue" && value.decisionFile === null) {
1962
+ ctx.addIssue({ code: "custom", path: ["decisionFile"], message: 'Outcome "continue" requires "--decision-file" holding the selected provider proposal.' });
1963
+ }
1964
+ if (value.outcome !== "continue" && value.decisionFile !== null) {
1965
+ ctx.addIssue({ code: "custom", path: ["decisionFile"], message: `Outcome "${value.outcome}" records no decision text; drop "--decision-file".` });
1966
+ }
1967
+ });
1968
+ const result = schema.safeParse({
1969
+ epicRunId: first(values, "--epic-run-id"),
1970
+ ticketKey: first(values, "--ticket-key"),
1971
+ councilRowId: first(values, "--council-row-id"),
1972
+ councilIds: values.get("--council-id") ?? [],
1973
+ outcome: first(values, "--outcome"),
1974
+ decisionFile: first(values, "--decision-file") ?? null,
1975
+ });
1976
+ if (!result.success)
1977
+ throw new ConductorValidationError(councilIssueMessage(result.error.issues));
1978
+ const seen = new Set();
1979
+ const councilIds = result.data.councilIds
1980
+ .map((id) => id.toLowerCase())
1981
+ .filter((id) => (seen.has(id) ? false : (seen.add(id), true)));
1982
+ return { help: false, ...result.data, councilIds };
1983
+ }
1984
+ /**
1985
+ * Read the decision file as strict UTF-8. Every failure is a fixed sentence
1986
+ * that names neither the path's contents nor any decoded text.
1987
+ */
1988
+ async function readDecisionText(path, reader) {
1989
+ let bytes;
1990
+ try {
1991
+ bytes = await reader(path);
1992
+ }
1993
+ catch {
1994
+ throw new ConductorValidationError("The decision file could not be read.");
1995
+ }
1996
+ if (bytes.byteLength > DECISION_FILE_MAX_BYTES) {
1997
+ throw new ConductorValidationError(`The decision file is larger than ${DECISION_FILE_MAX_BYTES} bytes.`);
1998
+ }
1999
+ let text;
2000
+ try {
2001
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2002
+ }
2003
+ catch {
2004
+ throw new ConductorValidationError("The decision file is not valid UTF-8.");
2005
+ }
2006
+ if (text.trim().length === 0) {
2007
+ throw new ConductorValidationError("The decision file is empty.");
2008
+ }
2009
+ return text;
2010
+ }
2011
+ async function defaultReadDecisionFile(path) {
2012
+ const { readFile } = await import("node:fs/promises");
2013
+ return readFile(path);
2014
+ }
2015
+ async function defaultCouncilAccess() {
2016
+ const { resolveConductorBridgeApiAccess } = await import("./bridge-api-client.js");
2017
+ const resolved = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
2018
+ return resolved.ok ? resolved.access : null;
2019
+ }
2020
+ /** Render a non-result outcome to stderr and return its exit code. Never prints decision text. */
2021
+ function renderCouncilFailure(verb, ticketKey, outcome, writeStderr) {
2022
+ const label = `${verb} for ${ticketKey}`;
2023
+ switch (outcome.kind) {
2024
+ case "refused":
2025
+ writeStderr(`Refused: ${label} — ${outcome.errorCode} (HTTP ${outcome.status}). Nothing was written; ` +
2026
+ "the child stays parked. Finish the recovery pass as today.");
2027
+ return DRIVER_COUNCIL_EXIT_REFUSED;
2028
+ case "unsupported_server":
2029
+ writeStderr(`Failed: ${label} — the Bridge API server is too old for driver councils. Nothing was written.`);
2030
+ return DRIVER_COUNCIL_EXIT_FAILED;
2031
+ case "rejected":
2032
+ writeStderr(`Failed: ${label} — the server rejected the request (HTTP ${outcome.status}` +
2033
+ `${outcome.errorCode ? `, ${outcome.errorCode}` : ""}). Nothing was written.`);
2034
+ return DRIVER_COUNCIL_EXIT_FAILED;
2035
+ case "uncertain":
2036
+ writeStderr(`Unconfirmed: ${label} — no durable answer arrived (${outcome.reason}). ` +
2037
+ "Re-run the identical command; it is idempotent.");
2038
+ return DRIVER_COUNCIL_EXIT_UNCONFIRMED;
2039
+ }
2040
+ }
2041
+ function councilStreams(deps) {
2042
+ return {
2043
+ writeStdout: deps.writeStdout ?? ((serialized) => writeJsonDocument(serialized)),
2044
+ writeStderr: deps.writeStderr ?? ((line) => console.error(line)),
2045
+ };
2046
+ }
2047
+ function councilErrorLine(error) {
2048
+ // Only our own validation sentences are printed; anything else gets a fixed line.
2049
+ if (error instanceof ConductorValidationError)
2050
+ return `Error: ${error.message}`;
2051
+ return "Error: the request could not be completed; nothing was confirmed.";
2052
+ }
2053
+ /** `reserve-council`: reserve one logical council and print the row. */
2054
+ export async function runReserveCouncilCommand(argv, deps = {}) {
2055
+ const { writeStdout, writeStderr } = councilStreams(deps);
2056
+ try {
2057
+ const parsed = await parseReserveCouncilArgs(argv);
2058
+ if (parsed.help) {
2059
+ console.log(RESERVE_COUNCIL_USAGE);
2060
+ return DRIVER_COUNCIL_EXIT_OK;
2061
+ }
2062
+ const access = await (deps.resolveAccess ?? defaultCouncilAccess)();
2063
+ if (!access) {
2064
+ writeStderr("Error: Bridge API credentials could not be resolved. Nothing was reserved.");
2065
+ return DRIVER_COUNCIL_EXIT_FAILED;
2066
+ }
2067
+ const reserve = deps.reserve ?? (await import("./bridge-api-client.js")).reserveDriverCouncil;
2068
+ const outcome = await reserve(access, {
2069
+ epicRunId: parsed.epicRunId,
2070
+ ticketKey: parsed.ticketKey,
2071
+ reservationKey: parsed.reservationKey,
2072
+ });
2073
+ if (outcome.kind !== "result") {
2074
+ return renderCouncilFailure("reserve-council", parsed.ticketKey, outcome, writeStderr);
2075
+ }
2076
+ return (await writeStdout(JSON.stringify(outcome.result))) ? DRIVER_COUNCIL_EXIT_OK : DRIVER_COUNCIL_EXIT_FAILED;
2077
+ }
2078
+ catch (error) {
2079
+ writeStderr(councilErrorLine(error));
2080
+ return DRIVER_COUNCIL_EXIT_FAILED;
2081
+ }
2082
+ }
2083
+ /** `record-decision`: settle a reserved council and print the settled row. */
2084
+ export async function runRecordDecisionCommand(argv, deps = {}) {
2085
+ const { writeStdout, writeStderr } = councilStreams(deps);
2086
+ try {
2087
+ const parsed = await parseRecordDecisionArgs(argv);
2088
+ if (parsed.help) {
2089
+ console.log(RECORD_DECISION_USAGE);
2090
+ return DRIVER_COUNCIL_EXIT_OK;
2091
+ }
2092
+ const decisionText = parsed.decisionFile === null
2093
+ ? null
2094
+ : await readDecisionText(parsed.decisionFile, deps.readDecisionFile ?? defaultReadDecisionFile);
2095
+ const access = await (deps.resolveAccess ?? defaultCouncilAccess)();
2096
+ if (!access) {
2097
+ writeStderr("Error: Bridge API credentials could not be resolved. Nothing was recorded.");
2098
+ return DRIVER_COUNCIL_EXIT_FAILED;
2099
+ }
2100
+ const record = deps.record ?? (await import("./bridge-api-client.js")).recordDriverDecision;
2101
+ const outcome = await record(access, {
2102
+ epicRunId: parsed.epicRunId,
2103
+ ticketKey: parsed.ticketKey,
2104
+ councilRowId: parsed.councilRowId,
2105
+ councilIds: parsed.councilIds,
2106
+ outcome: parsed.outcome,
2107
+ decisionText,
2108
+ });
2109
+ if (outcome.kind !== "result") {
2110
+ return renderCouncilFailure("record-decision", parsed.ticketKey, outcome, writeStderr);
2111
+ }
2112
+ return (await writeStdout(JSON.stringify(outcome.result))) ? DRIVER_COUNCIL_EXIT_OK : DRIVER_COUNCIL_EXIT_FAILED;
2113
+ }
2114
+ catch (error) {
2115
+ writeStderr(councilErrorLine(error));
2116
+ return DRIVER_COUNCIL_EXIT_FAILED;
2117
+ }
2118
+ }
@@ -59,6 +59,9 @@ export const EPIC_SERVER_REASONS = [
59
59
  "ready_timeout",
60
60
  "ready_redirect_refused",
61
61
  "credential_unavailable",
62
+ // BAPI-1733: the app exited before it became ready (a serving failure). Distinct
63
+ // from the post-ready "app_failed" reason, which the "app_exited" EVENT carries.
64
+ "app_exited",
62
65
  "expired",
63
66
  "fenced",
64
67
  "app_failed",
@@ -74,6 +77,7 @@ export const EPIC_SERVER_JOURNAL_MAX_EVENTS = 500;
74
77
  export const EPIC_SERVER_JOURNAL_MAX_READ = 100;
75
78
  const TICKET_RE = /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/;
76
79
  const SHA_RE = /^[0-9a-f]{40}$/;
80
+ const EXIT_SIGNAL_RE = /^SIG[A-Z0-9]{1,10}$/;
77
81
  const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/;
78
82
  /** Build one sanitized entry. Fields outside the closed shapes are dropped. */
79
83
  export function buildJournalEntry(runId, seq, at, event, fields = {}) {
@@ -98,6 +102,13 @@ export function buildJournalEntry(runId, seq, at, event, fields = {}) {
98
102
  entry.reason = fields.reason;
99
103
  if (typeof fields.count === "number" && Number.isSafeInteger(fields.count) && fields.count >= 0)
100
104
  entry.count = fields.count;
105
+ // Exit facts are kept only in their closed shapes; anything else is dropped,
106
+ // never coerced, and a raw process error is never accepted here at all.
107
+ if (typeof fields.exit_code === "number" && Number.isSafeInteger(fields.exit_code) && fields.exit_code >= 0 && fields.exit_code <= 255) {
108
+ entry.exit_code = fields.exit_code;
109
+ }
110
+ if (typeof fields.exit_signal === "string" && EXIT_SIGNAL_RE.test(fields.exit_signal))
111
+ entry.exit_signal = fields.exit_signal;
101
112
  return entry;
102
113
  }
103
114
  /** Validate one parsed entry; anything outside the closed shape is null. */
@@ -123,6 +134,8 @@ export function validateJournalEntry(raw) {
123
134
  outcome: doc.outcome,
124
135
  reason: doc.reason,
125
136
  count: doc.count,
137
+ exit_code: doc.exit_code,
138
+ exit_signal: doc.exit_signal,
126
139
  });
127
140
  if (typeof doc.sha12 === "string" && /^[0-9a-f]{12}$/.test(doc.sha12))
128
141
  rebuilt.sha12 = doc.sha12;
@@ -88,6 +88,16 @@ function hasControlChars(value) {
88
88
  }
89
89
  return false;
90
90
  }
91
+ const SAFE_ENTRY_LABEL_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
92
+ /**
93
+ * BAPI-1733 — a diagnostic label for one `inputs` / `credential_refs` entry. The
94
+ * entry name appears only when it is a plain identifier; anything else (punctuation,
95
+ * newlines, over-long text) is replaced so a name can never carry a value or
96
+ * injected text into an error.
97
+ */
98
+ function entryLabel(section, name) {
99
+ return `${section}.${SAFE_ENTRY_LABEL_RE.test(name) ? name : "an entry"}`;
100
+ }
91
101
  /** True for a name a recipe may set in a command environment. */
92
102
  export function isRecipeEnvName(name) {
93
103
  if (!ENV_NAME_RE.test(name) || RESERVED_ENV_NAMES.has(name))
@@ -292,9 +302,9 @@ export function validateEpicServerRecipe(raw) {
292
302
  }
293
303
  for (const [name, value] of Object.entries(raw.inputs)) {
294
304
  if (!isRecipeEnvName(name))
295
- return { ok: false, error: "inputs: a name is reserved or unusable" };
305
+ return { ok: false, error: `${entryLabel("inputs", name)}: the name is reserved or unusable` };
296
306
  if (typeof value !== "string" || value.length > MAX_ENV_VALUE_CHARS || value.includes("\0") || hasControlChars(value)) {
297
- return { ok: false, error: "inputs: a value is unusable" };
307
+ return { ok: false, error: `${entryLabel("inputs", name)}: the value is unusable` };
298
308
  }
299
309
  inputs[name] = value;
300
310
  }
@@ -306,13 +316,13 @@ export function validateEpicServerRecipe(raw) {
306
316
  }
307
317
  for (const [name, value] of Object.entries(raw.credential_refs)) {
308
318
  if (!isRecipeEnvName(name) || name in inputs)
309
- return { ok: false, error: "credential_refs: a name is reserved or unusable" };
319
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: the name is reserved or unusable` };
310
320
  if (!isPlainObject(value) || !isValidCredentialReference(value.ref) || typeof value.key !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(value.key)) {
311
- return { ok: false, error: "credential_refs: each entry needs a ref and a key name" };
321
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: each entry needs a ref and a key name` };
312
322
  }
313
323
  if (Object.keys(value).some((k) => k !== "ref" && k !== "key")) {
314
324
  // A raw secret value never belongs here.
315
- return { ok: false, error: "credential_refs: an entry holds more than a reference" };
325
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: an entry holds more than a reference` };
316
326
  }
317
327
  credentialRefs[name] = { ref: value.ref, key: value.key };
318
328
  }