@bridge_gpt/mcp-server 0.2.73 → 0.2.75

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 (123) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agent-launchers/prompt.js +9 -21
  4. package/build/agents.generated.js +4 -4
  5. package/build/authored-plan.js +542 -0
  6. package/build/bridge-config.js +7 -1
  7. package/build/bridge-permissions.js +11 -0
  8. package/build/command-provisioning.js +4 -3
  9. package/build/commands.generated.js +6 -6
  10. package/build/conductor/bridge-api-client.js +692 -47
  11. package/build/conductor/command-drift.js +1 -1
  12. package/build/conductor/declared-extras.js +335 -0
  13. package/build/conductor/doctor.js +2 -0
  14. package/build/conductor/driver-pass-output.js +104 -0
  15. package/build/conductor/driver-pass.js +571 -0
  16. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  17. package/build/conductor/epic-implementer-cli.js +370 -93
  18. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  19. package/build/conductor/epic-server-sfcc.js +58 -80
  20. package/build/conductor/epic-server.js +57 -4
  21. package/build/conductor/gate-discovery.js +253 -13
  22. package/build/conductor/gate-settings-review.js +58 -25
  23. package/build/conductor/launch-plan.js +58 -12
  24. package/build/conductor/open-decision-phrases.js +50 -0
  25. package/build/conductor/prerequisite-inputs.js +181 -14
  26. package/build/connect-github-api.js +18 -0
  27. package/build/connect-github.js +35 -18
  28. package/build/credential-delivery.js +280 -0
  29. package/build/credential-launch-safety.js +142 -0
  30. package/build/credential-materialization.js +91 -16
  31. package/build/credential-references-node-deps.js +29 -0
  32. package/build/credential-references.js +1394 -0
  33. package/build/credential-references.test-fixtures.js +211 -0
  34. package/build/credential-scan-conventions.js +145 -0
  35. package/build/credential-scan.js +517 -0
  36. package/build/credential-store.js +50 -0
  37. package/build/credentials-cli.js +252 -3
  38. package/build/dependency-install-declarations.js +47 -1
  39. package/build/docs.generated.js +8 -1
  40. package/build/doctor.js +41 -0
  41. package/build/drive-epic.js +684 -49
  42. package/build/epic-branch-ci-summary.js +18 -1
  43. package/build/epic-capability-statement.js +71 -3
  44. package/build/epic-ci-workflow-drift.js +52 -13
  45. package/build/epic-ci-workflow-install.js +31 -6
  46. package/build/epic-ci-workflow-v3.js +273 -0
  47. package/build/epic-ci-workflow.js +129 -7
  48. package/build/epic-implementer-bin.js +288 -83
  49. package/build/epic-implementer-bundle-cli.js +61 -0
  50. package/build/epic-implementer-claude-hook-bin.js +1 -1
  51. package/build/epic-implementer-env.js +3 -4
  52. package/build/epic-integration-pr.js +5 -2
  53. package/build/epic-launch-context.js +102 -7
  54. package/build/epic-server-record.js +30 -15
  55. package/build/executor/completion-contract.js +24 -1
  56. package/build/executor/credential-delivery-step.js +168 -0
  57. package/build/executor/deps.js +3 -1
  58. package/build/executor/env.js +39 -1
  59. package/build/executor/epic-server-context.js +23 -7
  60. package/build/executor/gate-qualification-job.js +193 -23
  61. package/build/executor/gate-qualification-tests-ran.js +232 -0
  62. package/build/executor/guarded-fast-forward-push.js +13 -8
  63. package/build/executor/job-runner.js +167 -738
  64. package/build/executor/job-type-wrappers.js +734 -0
  65. package/build/executor/permissions.js +85 -3
  66. package/build/executor/preflight.js +6 -2
  67. package/build/executor/process-containment.js +8 -1
  68. package/build/executor/prompt-spec.js +37 -3
  69. package/build/executor/required-verification.js +28 -2
  70. package/build/executor/runner.js +4 -1
  71. package/build/executor/types.js +9 -0
  72. package/build/executor/worker-database.js +6 -1
  73. package/build/executor/worker-guard-hook.js +24 -2
  74. package/build/executor-launch.js +4 -2
  75. package/build/generated/ticket-status.js +20 -0
  76. package/build/git-exclude-lock.js +187 -0
  77. package/build/index.js +589 -326
  78. package/build/install-bridge-conductor-answers.js +112 -22
  79. package/build/install-bridge-conductor-apply.js +38 -1
  80. package/build/install-bridge-conductor-assessment.js +482 -53
  81. package/build/install-bridge-conductor-compact.js +29 -2
  82. package/build/install-bridge-conductor-contracts.js +10 -1
  83. package/build/install-bridge-conductor-gate.js +379 -89
  84. package/build/install-bridge-conductor-setup.js +46 -8
  85. package/build/install-bridge-conductor-trial-report.js +170 -0
  86. package/build/install-bridge-conductor.js +925 -141
  87. package/build/install-bridge.js +88 -11
  88. package/build/install-doctor.js +38 -8
  89. package/build/install-sfcc-detection.js +120 -0
  90. package/build/install-sfcc-setup.js +185 -0
  91. package/build/mcp-grant-candidates.js +108 -96
  92. package/build/mcp-invoke.js +168 -4
  93. package/build/mcp-provisioning.js +21 -4
  94. package/build/mcp-server-invocation.js +13 -0
  95. package/build/merge-workflow-install.js +9 -1
  96. package/build/pipelines.generated.js +8 -7
  97. package/build/plan-generation.js +17 -0
  98. package/build/plane/status.js +8 -2
  99. package/build/printed-remedy-commands.js +59 -0
  100. package/build/project-root.js +40 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-state-paths.js +5 -2
  103. package/build/repository-toolchains.js +16 -7
  104. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  105. package/build/setup-epic.js +126 -16
  106. package/build/sfcc/credentials.js +3 -2
  107. package/build/sfcc/hostname.js +98 -2
  108. package/build/sfcc/tool-wrapper.js +6 -95
  109. package/build/start-tickets.js +193 -29
  110. package/build/test-support/executor-source-files.js +200 -0
  111. package/build/testing-config-client.js +25 -2
  112. package/build/third-party-mcp-targets.js +35 -4
  113. package/build/v2-readiness-requirements.js +5 -1
  114. package/build/version.generated.js +3 -3
  115. package/build/with-credentials.js +208 -0
  116. package/build/worker-guard-hook-bin.js +2 -2
  117. package/build/worktree-credential-delivery.js +340 -0
  118. package/docs/EPIC-IMPLEMENTER.md +4 -4
  119. package/docs/install/github-app.md +79 -92
  120. package/package.json +1 -1
  121. package/build/conductor/epic-reconcile.js +0 -603
  122. package/build/conductor/epic-runtime.js +0 -2020
  123. package/build/conductor/epic-state.js +0 -774
@@ -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)",
@@ -140,6 +138,16 @@ export function getConductorUsage() {
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,",
@@ -169,6 +177,13 @@ export function getConductorUsage() {
169
177
  " A worker borrows the epic server at its own head for a bounded turn, then",
170
178
  " releases it with the lease handle acquire printed. A timeout or a missing",
171
179
  " server prints a no_live_server observation for the hand-off; nothing parks.",
180
+ " epic-server sfcc-upload --ticket <KEY> --head <SHA>",
181
+ " epic-server sfcc-upload --full --epic <KEY> --epic-run-id <id> --head <SHA>",
182
+ " epic-server sfcc-upload --check",
183
+ " Uploads committed cartridge files to the run's one shared SFCC code version,",
184
+ " in any epic-server mode (worker: changed files; --full: the driver's whole",
185
+ " tree plus a baseline; --check: read-only readiness). A failure prints a",
186
+ " no_live_server observation for the hand-off; nothing parks.",
172
187
  " prerequisite-inputs --epic-key <KEY> --child <KEY> [--child <KEY> ...] [--json]",
173
188
  " Reads stored ticket descriptions and reports, per child, cached, in_flight,",
174
189
  " scan_needed (with a private scanner input file under",
@@ -183,6 +198,10 @@ export function getConductorUsage() {
183
198
  " Release this session from supervision: done (run terminal) and handoff",
184
199
  " (report published) are checked on the server; owner only on the owner's",
185
200
  " explicit instruction. Changes nothing on the run.",
201
+ " driver-pass --epic-run-id <id> [--ticket-key <key>] [--json]",
202
+ " Read-only: report the driver's clock facts (no-progress time, job pause,",
203
+ " attach window, reconciler liveness) from the server's own clock. Decides",
204
+ " and changes nothing; unreadable facts print as unknown.",
186
205
  " driver-guard The /drive-epic-run Stop hook. Reads hook JSON on stdin, decides locally",
187
206
  " with no network call, always exits 0. Off switch: BRIDGE_EI_DRIVER_GUARD=off.",
188
207
  " declare-blocked --epic-run-id <id> --ticket-key <K>... --entry 1|2|3|4|5|wedge --requirement <text>",
@@ -277,11 +296,6 @@ export function getConductorUsage() {
277
296
  " epic-implementer resume-run --epic-run-id <id>",
278
297
  " # a cap_wall_clock pause whose cause is now cleared",
279
298
  "",
280
- "epic-tick options (retired; parsed by no live path):",
281
- " --epic-key <KEY> Epic key to supervise (required, non-empty)",
282
- " --scheduled-at <epoch> Epoch-seconds timestamp when this tick was scheduled (optional)",
283
- " --lease-ttl-seconds <n> Lease TTL in seconds (optional, default 120)",
284
- "",
285
299
  "approve-plan options:",
286
300
  " approve-plan <epic_key> --plan-version N [--json]",
287
301
  " <epic_key> Epic key (e.g. EPIC-405) (required positional)",
@@ -375,7 +389,6 @@ export { HOOK_RUNTIME_PROBE_ACTION } from "./hook-runtime-qualification.js";
375
389
  const VALID_COMMANDS = new Set([
376
390
  "emit-event",
377
391
  "supervise",
378
- "epic-tick",
379
392
  "approve-plan",
380
393
  "epic-status",
381
394
  "send-message",
@@ -418,6 +431,9 @@ const VALID_COMMANDS = new Set([
418
431
  "acknowledge-gaps",
419
432
  // BAPI-1532: CLI-only answer to a named plan failure — never an MCP tool.
420
433
  "regenerate-plan",
434
+ // BAPI-1705: CLI-only driver open-decision council pair — never MCP tools.
435
+ "reserve-council",
436
+ "record-decision",
421
437
  // BAPI-1469: CLI-only read-only bounded wait on a run's state — never an MCP tool.
422
438
  "wait-run",
423
439
  // BAPI-1557: CLI-only stored-ticket reader and private local-state writer — never an MCP tool.
@@ -429,6 +445,8 @@ const VALID_COMMANDS = new Set([
429
445
  "driver-release",
430
446
  "driver-guard",
431
447
  "declare-blocked",
448
+ // BAPI-1682: CLI-only read-only driver clock report — never an MCP tool.
449
+ "driver-pass",
432
450
  // Private, and deliberately ABSENT from the usage text: `__hook-bin` exists as
433
451
  // the bundled-artifact regression guard for BAPI-772 (mirroring `plane
434
452
  // __entrypoint`), not as a supported operator workflow.
@@ -1114,88 +1132,6 @@ export async function runGitHookCommand(argv) {
1114
1132
  }
1115
1133
  }
1116
1134
  // ---------------------------------------------------------------------------
1117
- // epic-tick
1118
- // ---------------------------------------------------------------------------
1119
- const EPIC_TICK_VALUE_FLAGS = new Set([
1120
- "--epic-key",
1121
- "--scheduled-at",
1122
- "--lease-ttl-seconds",
1123
- ]);
1124
- const EPIC_TICK_BOOL_FLAGS = new Set(["--help"]);
1125
- /**
1126
- * Parse `epic-tick` flags. `--epic-key` is required and must be non-empty /
1127
- * non-whitespace. Numeric overrides (`--scheduled-at`, `--lease-ttl-seconds`)
1128
- * are validated as non-negative integers using the shared
1129
- * {@link parsePositiveIntFlag} convention. Malformed input raises a sanitized
1130
- * {@link ConductorValidationError}.
1131
- */
1132
- export function parseEpicTickArgs(argv) {
1133
- const { values, bools } = tokenizeFlags(argv, EPIC_TICK_VALUE_FLAGS, EPIC_TICK_BOOL_FLAGS);
1134
- if (bools.has("--help")) {
1135
- return { epicKey: "", help: true };
1136
- }
1137
- const epicKeyRaw = values.get("--epic-key");
1138
- if (epicKeyRaw === undefined || epicKeyRaw.trim().length === 0) {
1139
- throw new ConductorValidationError('Flag "--epic-key" is required for epic-tick and must be non-empty.');
1140
- }
1141
- const scheduledAt = parsePositiveIntFlag(values, "--scheduled-at");
1142
- const leaseTtlSeconds = parsePositiveIntFlag(values, "--lease-ttl-seconds");
1143
- return { epicKey: epicKeyRaw.trim(), scheduledAt, leaseTtlSeconds, help: false };
1144
- }
1145
- /**
1146
- * Default the PreToolUse hook ON for epic-dispatched workers so the supervisor
1147
- * gets worker-liveness (`tool.intent`) signals without the operator having to
1148
- * export `BAPI_EPIC_IMPLEMENTER_ENABLE_PRE_TOOL_USE=1` (BAPI-441/A1 finding).
1149
- *
1150
- * Both the child-env copy and the hook registration key off this SAME
1151
- * parent-process env flag, read at dispatch time, so setting it once at the
1152
- * epic-tick boundary covers the whole tick. Only defaults when the flag is
1153
- * UNSET — an explicit "0"/"" still disables it, because `isConductorFlagEnabled`
1154
- * treats those as false. Mutates the supplied env in place (defaults to
1155
- * `process.env`) and returns it.
1156
- */
1157
- export function applyEpicTickPreToolUseDefault(env = process.env) {
1158
- if (env.BAPI_EPIC_IMPLEMENTER_ENABLE_PRE_TOOL_USE === undefined) {
1159
- env.BAPI_EPIC_IMPLEMENTER_ENABLE_PRE_TOOL_USE = "1";
1160
- }
1161
- return env;
1162
- }
1163
- /**
1164
- * Run the `epic-tick` command. Lazily imports the epic runtime so a plain
1165
- * `epic-implementer doctor` / `emit-event` invocation never eagerly resolves
1166
- * the epic/store graph.
1167
- */
1168
- export async function runEpicTickCommand(_argv) {
1169
- // BAPI-534 (Epic Conductor v2 slice 0): the v1 epic-tick path is FROZEN. This
1170
- // fail-loud guard is the FIRST executable statement — before argument parsing,
1171
- // `applyEpicTickPreToolUseDefault()`, and any lazy `import("./epic-runtime.js")`
1172
- // — so no v1 tick (or its store/supervisor graph) can ever run. Interactive
1173
- // `/start-tickets` is unaffected. `runEpicImplementerCli` catches this named
1174
- // error and formats it consistently (EPIC_TICK_V1_FROZEN → exit 1).
1175
- throw new ConductorEpicTickV1FrozenError();
1176
- }
1177
- /** @deprecated v1 epic-tick body — retained unreachable behind the freeze guard. */
1178
- export async function runEpicTickCommandLegacy(argv) {
1179
- const parsed = parseEpicTickArgs(argv);
1180
- if (parsed.help) {
1181
- console.log(getConductorUsage());
1182
- return 0;
1183
- }
1184
- // Enable supervisor worker-liveness by default for the whole tick (see the
1185
- // helper's doc comment); set before runEpicTick dispatches any worker.
1186
- applyEpicTickPreToolUseDefault();
1187
- // `runEpicTick` is imported LAZILY so the store/supervisor graph is not
1188
- // evaluated for other epic-implementer CLI commands that never need it.
1189
- const { runEpicTick, buildProductionEpicRuntimeDeps } = await import("./epic-runtime.js");
1190
- const prodDeps = await buildProductionEpicRuntimeDeps(parsed.epicKey);
1191
- const result = await runEpicTick({
1192
- epic_key: parsed.epicKey,
1193
- scheduled_at: parsed.scheduledAt !== undefined ? parsed.scheduledAt * 1000 : undefined,
1194
- lease_ttl_seconds: parsed.leaseTtlSeconds,
1195
- }, prodDeps);
1196
- return result.exit_code;
1197
- }
1198
- // ---------------------------------------------------------------------------
1199
1135
  // approve-plan
1200
1136
  // ---------------------------------------------------------------------------
1201
1137
  const APPROVE_PLAN_VALUE_FLAGS = new Set(["--plan-version"]);
@@ -1610,8 +1546,6 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1610
1546
  return await runEmitEventCommand(parsed.argv);
1611
1547
  case "supervise":
1612
1548
  return await runSuperviseCommand(parsed.argv);
1613
- case "epic-tick":
1614
- return await runEpicTickCommand(parsed.argv);
1615
1549
  case "approve-plan":
1616
1550
  return await runApprovePlanCommand(parsed.argv);
1617
1551
  case "epic-status":
@@ -1739,6 +1673,13 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1739
1673
  const { runRegeneratePlanCommand } = await import("./recovery-cli.js");
1740
1674
  return await runRegeneratePlanCommand(parsed.argv);
1741
1675
  }
1676
+ case "reserve-council": {
1677
+ // BAPI-1705: the API client is imported lazily inside the command.
1678
+ return await runReserveCouncilCommand(parsed.argv);
1679
+ }
1680
+ case "record-decision": {
1681
+ return await runRecordDecisionCommand(parsed.argv);
1682
+ }
1742
1683
  case "wait-run": {
1743
1684
  // BAPI-1469: read-only bounded wait. Lazily imported like the recovery
1744
1685
  // verbs; a module-load failure gets fixed wording, never exception text.
@@ -1812,6 +1753,26 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1812
1753
  }
1813
1754
  return await runDriverReleaseCommand(parsed.argv);
1814
1755
  }
1756
+ case "driver-pass": {
1757
+ // BAPI-1682: CLI-only, read-only, advisory. A module-load failure is
1758
+ // fail-open like the command itself: one fixed line, a full unavailable
1759
+ // result from the dependency-light output module, exit 0.
1760
+ let runDriverPassCommand;
1761
+ try {
1762
+ ({ runDriverPassCommand } = await import("./driver-pass.js"));
1763
+ }
1764
+ catch {
1765
+ console.error("driver-pass could not be loaded; no run state was read.");
1766
+ const { buildUnavailableDriverPassResult, formatDriverPassResult } = await import("./driver-pass-output.js");
1767
+ const runFlag = parsed.argv.indexOf("--epic-run-id");
1768
+ const ref = runFlag >= 0 ? parsed.argv[runFlag + 1] : undefined;
1769
+ const safeRef = typeof ref === "string" && /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/.test(ref) ? ref : "unknown";
1770
+ const result = buildUnavailableDriverPassResult(safeRef, "computation_failed");
1771
+ console.log(parsed.argv.includes("--json") ? JSON.stringify(result) : formatDriverPassResult(result));
1772
+ return 0;
1773
+ }
1774
+ return await runDriverPassCommand(parsed.argv);
1775
+ }
1815
1776
  case "declare-blocked": {
1816
1777
  let runDeclareBlockedCommand;
1817
1778
  try {
@@ -1838,3 +1799,319 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
1838
1799
  return 1;
1839
1800
  }
1840
1801
  }
1802
+ // ---------------------------------------------------------------------------
1803
+ // BAPI-1705 — reserve-council / record-decision (driver open-decision council)
1804
+ // ---------------------------------------------------------------------------
1805
+ //
1806
+ // Two CLI-only verbs the unattended driver runs around one open-decision
1807
+ // council. Stream contract: on success stdout carries exactly one JSON object
1808
+ // and stderr is empty; every failure writes only to stderr and stdout stays
1809
+ // empty. Decision text is read from a local UTF-8 file, sent only in the
1810
+ // request body, and never written to argv, stdout, stderr, or an error message.
1811
+ // The Bridge API client and zod are imported lazily, so no other command loads
1812
+ // them.
1813
+ /** Exit codes, matching `regenerate-plan`: refused parks as today; unconfirmed is re-sent unchanged. */
1814
+ export const DRIVER_COUNCIL_EXIT_OK = 0;
1815
+ export const DRIVER_COUNCIL_EXIT_FAILED = 1;
1816
+ export const DRIVER_COUNCIL_EXIT_REFUSED = 2;
1817
+ export const DRIVER_COUNCIL_EXIT_UNCONFIRMED = 3;
1818
+ /** Decision files above this many bytes are refused before any request. */
1819
+ export const DECISION_FILE_MAX_BYTES = 64 * 1024;
1820
+ const RESERVE_COUNCIL_USAGE = [
1821
+ "Usage: epic-implementer reserve-council --epic-run-id <id> --ticket-key <key> --reservation-key <key> [--json]",
1822
+ "",
1823
+ "Reserve one open-decision council for a parked child. The key is",
1824
+ "<epic_run_id>:<ticket_key>:park-<park_generation>; a repeated key returns the same",
1825
+ "row, so a restart never spends a second council. At most 2 per run.",
1826
+ "Exit codes: 0 reserved (one JSON object on stdout), 1 failed, 2 refused (the child",
1827
+ "stays parked; finish the recovery pass as today), 3 unconfirmed (re-run unchanged).",
1828
+ ].join("\n");
1829
+ const RECORD_DECISION_USAGE = [
1830
+ "Usage: epic-implementer record-decision --epic-run-id <id> --ticket-key <key> --council-row-id <n>",
1831
+ " --council-id <id> [--council-id <id>] --outcome continue|stop|split|no_valid_response",
1832
+ " [--decision-file <path>] [--json]",
1833
+ "",
1834
+ "Settle a reserved council with every council id it used (first request and any retry).",
1835
+ "continue requires --decision-file holding exactly the selected provider proposal",
1836
+ "(UTF-8, never echoed); stop, split and no_valid_response refuse it. An identical",
1837
+ "re-run is a replay and writes nothing new.",
1838
+ "Exit codes: 0 settled (one JSON object on stdout), 1 failed, 2 refused (the child",
1839
+ "stays parked), 3 unconfirmed (re-run unchanged). --json is accepted; output is always JSON.",
1840
+ ].join("\n");
1841
+ const COUNCIL_EPIC_RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
1842
+ const COUNCIL_TICKET_KEY_RE = /^[A-Z][A-Z0-9_]{0,19}-[0-9]{1,12}$/;
1843
+ const COUNCIL_RESERVATION_KEY_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]{0,299}$/;
1844
+ const COUNCIL_ROW_ID_RE = /^[1-9][0-9]{0,15}$/;
1845
+ 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}$/;
1846
+ /**
1847
+ * Tokenize council-verb flags. `repeatable` flags collect every value; any other
1848
+ * flag may appear once. Messages name the flag only — never a value — so a
1849
+ * misplaced decision never reaches stderr.
1850
+ */
1851
+ function tokenizeCouncilFlags(argv, valueFlags, repeatable) {
1852
+ const values = new Map();
1853
+ let help = false;
1854
+ for (let i = 0; i < argv.length; i += 1) {
1855
+ const token = argv[i];
1856
+ if (token === "-h" || token === "--help") {
1857
+ help = true;
1858
+ continue;
1859
+ }
1860
+ if (token === "--json") {
1861
+ // Accepted for parity with every other verb: success output is always JSON.
1862
+ continue;
1863
+ }
1864
+ if (!token.startsWith("--")) {
1865
+ throw new ConductorValidationError("Unexpected positional argument; every value must follow its flag.");
1866
+ }
1867
+ const eq = token.indexOf("=");
1868
+ const name = eq >= 0 ? token.slice(0, eq) : token;
1869
+ if (!valueFlags.has(name)) {
1870
+ const safeName = /^--[a-z][a-z0-9-]{0,40}$/.test(name) ? name : "(unrecognized)";
1871
+ throw new ConductorValidationError(`Unknown flag "${safeName}".`);
1872
+ }
1873
+ let value;
1874
+ if (eq >= 0) {
1875
+ value = token.slice(eq + 1);
1876
+ }
1877
+ else {
1878
+ const next = argv[i + 1];
1879
+ if (next === undefined)
1880
+ throw new ConductorValidationError(`Flag "${name}" requires a value.`);
1881
+ value = next;
1882
+ i += 1;
1883
+ }
1884
+ const existing = values.get(name);
1885
+ if (existing !== undefined && !repeatable.has(name)) {
1886
+ throw new ConductorValidationError(`Flag "${name}" may be given only once.`);
1887
+ }
1888
+ values.set(name, [...(existing ?? []), value]);
1889
+ }
1890
+ return { values, help };
1891
+ }
1892
+ /** Turn the first zod issue into a value-free message naming the flag. */
1893
+ function councilIssueMessage(issues) {
1894
+ const issue = issues[0];
1895
+ const key = issue && issue.path.length > 0 ? String(issue.path[0]) : "";
1896
+ const flag = {
1897
+ epicRunId: "--epic-run-id",
1898
+ ticketKey: "--ticket-key",
1899
+ reservationKey: "--reservation-key",
1900
+ councilRowId: "--council-row-id",
1901
+ councilIds: "--council-id",
1902
+ outcome: "--outcome",
1903
+ decisionFile: "--decision-file",
1904
+ };
1905
+ if (key === "decisionFile" || key === "councilIds")
1906
+ return issue.message;
1907
+ if (key in flag)
1908
+ return `Flag "${flag[key]}" is missing or invalid.`;
1909
+ return "Invalid arguments; run with --help for usage.";
1910
+ }
1911
+ function first(values, flag) {
1912
+ return values.get(flag)?.[0];
1913
+ }
1914
+ /** Parse and validate `reserve-council` flags with zod; nothing is sent. */
1915
+ export async function parseReserveCouncilArgs(argv) {
1916
+ const { values, help } = tokenizeCouncilFlags(argv, new Set(["--epic-run-id", "--ticket-key", "--reservation-key"]), new Set());
1917
+ if (help)
1918
+ return { help: true, epicRunId: "", ticketKey: "", reservationKey: "" };
1919
+ const { z } = await import("zod");
1920
+ const schema = z.object({
1921
+ epicRunId: z.string().trim().regex(COUNCIL_EPIC_RUN_ID_RE),
1922
+ ticketKey: z.string().trim().regex(COUNCIL_TICKET_KEY_RE),
1923
+ reservationKey: z.string().trim().regex(COUNCIL_RESERVATION_KEY_RE),
1924
+ });
1925
+ const result = schema.safeParse({
1926
+ epicRunId: first(values, "--epic-run-id"),
1927
+ ticketKey: first(values, "--ticket-key"),
1928
+ reservationKey: first(values, "--reservation-key"),
1929
+ });
1930
+ if (!result.success)
1931
+ throw new ConductorValidationError(councilIssueMessage(result.error.issues));
1932
+ const parsed = result.data;
1933
+ const expectedPrefix = `${parsed.epicRunId}:${parsed.ticketKey}:park-`;
1934
+ if (!parsed.reservationKey.startsWith(expectedPrefix) ||
1935
+ !/^[0-9]{1,12}$/.test(parsed.reservationKey.slice(expectedPrefix.length))) {
1936
+ throw new ConductorValidationError('Flag "--reservation-key" must be <epic_run_id>:<ticket_key>:park-<park_generation> for this run and ticket.');
1937
+ }
1938
+ return { help: false, ...parsed };
1939
+ }
1940
+ /** Parse and validate `record-decision` flags with zod; the decision file is not read here. */
1941
+ export async function parseRecordDecisionArgs(argv) {
1942
+ const { values, help } = tokenizeCouncilFlags(argv, new Set(["--epic-run-id", "--ticket-key", "--council-row-id", "--council-id", "--outcome", "--decision-file"]), new Set(["--council-id"]));
1943
+ if (help) {
1944
+ return { help: true, epicRunId: "", ticketKey: "", councilRowId: 0, councilIds: [], outcome: "stop", decisionFile: null };
1945
+ }
1946
+ const { z } = await import("zod");
1947
+ const schema = z
1948
+ .object({
1949
+ epicRunId: z.string().trim().regex(COUNCIL_EPIC_RUN_ID_RE),
1950
+ ticketKey: z.string().trim().regex(COUNCIL_TICKET_KEY_RE),
1951
+ councilRowId: z.string().trim().regex(COUNCIL_ROW_ID_RE).transform(Number).pipe(z.number().int().positive().max(Number.MAX_SAFE_INTEGER)),
1952
+ councilIds: z
1953
+ .array(z.string().trim().regex(COUNCIL_REQUEST_ID_RE, { message: 'Every "--council-id" must be a council request id (a UUID).' }))
1954
+ .min(1, { message: 'At least one "--council-id" is required: pass every council id this council used.' })
1955
+ .max(20, { message: 'Too many "--council-id" values (at most 20).' }),
1956
+ outcome: z.enum(["continue", "stop", "split", "no_valid_response"]),
1957
+ decisionFile: z.string().min(1, { message: 'Flag "--decision-file" must name a file.' }).nullable(),
1958
+ })
1959
+ .superRefine((value, ctx) => {
1960
+ if (value.outcome === "continue" && value.decisionFile === null) {
1961
+ ctx.addIssue({ code: "custom", path: ["decisionFile"], message: 'Outcome "continue" requires "--decision-file" holding the selected provider proposal.' });
1962
+ }
1963
+ if (value.outcome !== "continue" && value.decisionFile !== null) {
1964
+ ctx.addIssue({ code: "custom", path: ["decisionFile"], message: `Outcome "${value.outcome}" records no decision text; drop "--decision-file".` });
1965
+ }
1966
+ });
1967
+ const result = schema.safeParse({
1968
+ epicRunId: first(values, "--epic-run-id"),
1969
+ ticketKey: first(values, "--ticket-key"),
1970
+ councilRowId: first(values, "--council-row-id"),
1971
+ councilIds: values.get("--council-id") ?? [],
1972
+ outcome: first(values, "--outcome"),
1973
+ decisionFile: first(values, "--decision-file") ?? null,
1974
+ });
1975
+ if (!result.success)
1976
+ throw new ConductorValidationError(councilIssueMessage(result.error.issues));
1977
+ const seen = new Set();
1978
+ const councilIds = result.data.councilIds
1979
+ .map((id) => id.toLowerCase())
1980
+ .filter((id) => (seen.has(id) ? false : (seen.add(id), true)));
1981
+ return { help: false, ...result.data, councilIds };
1982
+ }
1983
+ /**
1984
+ * Read the decision file as strict UTF-8. Every failure is a fixed sentence
1985
+ * that names neither the path's contents nor any decoded text.
1986
+ */
1987
+ async function readDecisionText(path, reader) {
1988
+ let bytes;
1989
+ try {
1990
+ bytes = await reader(path);
1991
+ }
1992
+ catch {
1993
+ throw new ConductorValidationError("The decision file could not be read.");
1994
+ }
1995
+ if (bytes.byteLength > DECISION_FILE_MAX_BYTES) {
1996
+ throw new ConductorValidationError(`The decision file is larger than ${DECISION_FILE_MAX_BYTES} bytes.`);
1997
+ }
1998
+ let text;
1999
+ try {
2000
+ text = new TextDecoder("utf-8", { fatal: true }).decode(bytes);
2001
+ }
2002
+ catch {
2003
+ throw new ConductorValidationError("The decision file is not valid UTF-8.");
2004
+ }
2005
+ if (text.trim().length === 0) {
2006
+ throw new ConductorValidationError("The decision file is empty.");
2007
+ }
2008
+ return text;
2009
+ }
2010
+ async function defaultReadDecisionFile(path) {
2011
+ const { readFile } = await import("node:fs/promises");
2012
+ return readFile(path);
2013
+ }
2014
+ async function defaultCouncilAccess() {
2015
+ const { resolveConductorBridgeApiAccess } = await import("./bridge-api-client.js");
2016
+ const resolved = await resolveConductorBridgeApiAccess({ followEpicLaunchProfile: true });
2017
+ return resolved.ok ? resolved.access : null;
2018
+ }
2019
+ /** Render a non-result outcome to stderr and return its exit code. Never prints decision text. */
2020
+ function renderCouncilFailure(verb, ticketKey, outcome, writeStderr) {
2021
+ const label = `${verb} for ${ticketKey}`;
2022
+ switch (outcome.kind) {
2023
+ case "refused":
2024
+ writeStderr(`Refused: ${label} — ${outcome.errorCode} (HTTP ${outcome.status}). Nothing was written; ` +
2025
+ "the child stays parked. Finish the recovery pass as today.");
2026
+ return DRIVER_COUNCIL_EXIT_REFUSED;
2027
+ case "unsupported_server":
2028
+ writeStderr(`Failed: ${label} — the Bridge API server is too old for driver councils. Nothing was written.`);
2029
+ return DRIVER_COUNCIL_EXIT_FAILED;
2030
+ case "rejected":
2031
+ writeStderr(`Failed: ${label} — the server rejected the request (HTTP ${outcome.status}` +
2032
+ `${outcome.errorCode ? `, ${outcome.errorCode}` : ""}). Nothing was written.`);
2033
+ return DRIVER_COUNCIL_EXIT_FAILED;
2034
+ case "uncertain":
2035
+ writeStderr(`Unconfirmed: ${label} — no durable answer arrived (${outcome.reason}). ` +
2036
+ "Re-run the identical command; it is idempotent.");
2037
+ return DRIVER_COUNCIL_EXIT_UNCONFIRMED;
2038
+ }
2039
+ }
2040
+ function councilStreams(deps) {
2041
+ return {
2042
+ writeStdout: deps.writeStdout ?? ((serialized) => writeJsonDocument(serialized)),
2043
+ writeStderr: deps.writeStderr ?? ((line) => console.error(line)),
2044
+ };
2045
+ }
2046
+ function councilErrorLine(error) {
2047
+ // Only our own validation sentences are printed; anything else gets a fixed line.
2048
+ if (error instanceof ConductorValidationError)
2049
+ return `Error: ${error.message}`;
2050
+ return "Error: the request could not be completed; nothing was confirmed.";
2051
+ }
2052
+ /** `reserve-council`: reserve one logical council and print the row. */
2053
+ export async function runReserveCouncilCommand(argv, deps = {}) {
2054
+ const { writeStdout, writeStderr } = councilStreams(deps);
2055
+ try {
2056
+ const parsed = await parseReserveCouncilArgs(argv);
2057
+ if (parsed.help) {
2058
+ console.log(RESERVE_COUNCIL_USAGE);
2059
+ return DRIVER_COUNCIL_EXIT_OK;
2060
+ }
2061
+ const access = await (deps.resolveAccess ?? defaultCouncilAccess)();
2062
+ if (!access) {
2063
+ writeStderr("Error: Bridge API credentials could not be resolved. Nothing was reserved.");
2064
+ return DRIVER_COUNCIL_EXIT_FAILED;
2065
+ }
2066
+ const reserve = deps.reserve ?? (await import("./bridge-api-client.js")).reserveDriverCouncil;
2067
+ const outcome = await reserve(access, {
2068
+ epicRunId: parsed.epicRunId,
2069
+ ticketKey: parsed.ticketKey,
2070
+ reservationKey: parsed.reservationKey,
2071
+ });
2072
+ if (outcome.kind !== "result") {
2073
+ return renderCouncilFailure("reserve-council", parsed.ticketKey, outcome, writeStderr);
2074
+ }
2075
+ return (await writeStdout(JSON.stringify(outcome.result))) ? DRIVER_COUNCIL_EXIT_OK : DRIVER_COUNCIL_EXIT_FAILED;
2076
+ }
2077
+ catch (error) {
2078
+ writeStderr(councilErrorLine(error));
2079
+ return DRIVER_COUNCIL_EXIT_FAILED;
2080
+ }
2081
+ }
2082
+ /** `record-decision`: settle a reserved council and print the settled row. */
2083
+ export async function runRecordDecisionCommand(argv, deps = {}) {
2084
+ const { writeStdout, writeStderr } = councilStreams(deps);
2085
+ try {
2086
+ const parsed = await parseRecordDecisionArgs(argv);
2087
+ if (parsed.help) {
2088
+ console.log(RECORD_DECISION_USAGE);
2089
+ return DRIVER_COUNCIL_EXIT_OK;
2090
+ }
2091
+ const decisionText = parsed.decisionFile === null
2092
+ ? null
2093
+ : await readDecisionText(parsed.decisionFile, deps.readDecisionFile ?? defaultReadDecisionFile);
2094
+ const access = await (deps.resolveAccess ?? defaultCouncilAccess)();
2095
+ if (!access) {
2096
+ writeStderr("Error: Bridge API credentials could not be resolved. Nothing was recorded.");
2097
+ return DRIVER_COUNCIL_EXIT_FAILED;
2098
+ }
2099
+ const record = deps.record ?? (await import("./bridge-api-client.js")).recordDriverDecision;
2100
+ const outcome = await record(access, {
2101
+ epicRunId: parsed.epicRunId,
2102
+ ticketKey: parsed.ticketKey,
2103
+ councilRowId: parsed.councilRowId,
2104
+ councilIds: parsed.councilIds,
2105
+ outcome: parsed.outcome,
2106
+ decisionText,
2107
+ });
2108
+ if (outcome.kind !== "result") {
2109
+ return renderCouncilFailure("record-decision", parsed.ticketKey, outcome, writeStderr);
2110
+ }
2111
+ return (await writeStdout(JSON.stringify(outcome.result))) ? DRIVER_COUNCIL_EXIT_OK : DRIVER_COUNCIL_EXIT_FAILED;
2112
+ }
2113
+ catch (error) {
2114
+ writeStderr(councilErrorLine(error));
2115
+ return DRIVER_COUNCIL_EXIT_FAILED;
2116
+ }
2117
+ }