@bridge_gpt/mcp-server 0.2.74 → 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.
- package/README.md +14 -7
- package/build/agent-launchers/prompt.js +9 -21
- package/build/agents.generated.js +2 -2
- package/build/authored-plan.js +542 -0
- package/build/bridge-permissions.js +8 -0
- package/build/commands.generated.js +5 -5
- package/build/conductor/bridge-api-client.js +666 -46
- package/build/conductor/epic-implementer-cli.js +337 -93
- package/build/conductor/gate-discovery.js +209 -9
- package/build/conductor/gate-settings-review.js +7 -11
- package/build/conductor/launch-plan.js +58 -12
- package/build/conductor/open-decision-phrases.js +50 -0
- package/build/conductor/prerequisite-inputs.js +181 -14
- package/build/connect-github-api.js +18 -0
- package/build/connect-github.js +35 -18
- package/build/docs.generated.js +2 -2
- package/build/drive-epic.js +387 -12
- package/build/epic-ci-workflow.js +3 -2
- package/build/epic-implementer-bin.js +152 -38
- package/build/epic-implementer-bundle-cli.js +61 -0
- package/build/epic-implementer-claude-hook-bin.js +1 -1
- package/build/epic-implementer-env.js +3 -4
- package/build/epic-integration-pr.js +5 -2
- package/build/executor/completion-contract.js +24 -1
- package/build/executor/gate-qualification-job.js +193 -23
- package/build/executor/gate-qualification-tests-ran.js +232 -0
- package/build/executor/job-runner.js +9 -722
- package/build/executor/job-type-wrappers.js +734 -0
- package/build/executor/preflight.js +6 -2
- package/build/executor/process-containment.js +8 -1
- package/build/executor/required-verification.js +28 -2
- package/build/executor/runner.js +4 -1
- package/build/executor/types.js +9 -0
- package/build/executor/worker-database.js +6 -1
- package/build/executor/worker-guard-hook.js +24 -2
- package/build/generated/ticket-status.js +20 -0
- package/build/index.js +391 -257
- package/build/install-bridge-conductor-answers.js +28 -1
- package/build/install-bridge-conductor-apply.js +11 -3
- package/build/install-bridge-conductor-assessment.js +114 -12
- package/build/install-bridge-conductor-compact.js +2 -0
- package/build/install-bridge-conductor-gate.js +257 -80
- package/build/install-bridge-conductor-setup.js +4 -4
- package/build/install-bridge-conductor-trial-report.js +170 -0
- package/build/install-bridge-conductor.js +303 -31
- package/build/pipelines.generated.js +7 -7
- package/build/plan-generation.js +17 -0
- package/build/printed-remedy-commands.js +54 -0
- package/build/readme.generated.js +1 -1
- package/build/repository-toolchains.js +11 -5
- package/build/scripts/saved-commands-config-field-driver.js +65 -0
- package/build/setup-epic.js +10 -1
- package/build/test-support/executor-source-files.js +1 -1
- package/build/v2-readiness-requirements.js +5 -1
- package/build/version.generated.js +3 -3
- package/build/worker-guard-hook-bin.js +2 -2
- package/docs/EPIC-IMPLEMENTER.md +4 -4
- package/docs/install/github-app.md +79 -92
- package/package.json +1 -1
- package/build/conductor/epic-reconcile.js +0 -603
- package/build/conductor/epic-runtime.js +0 -2020
- 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,
|
|
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,",
|
|
@@ -288,11 +296,6 @@ export function getConductorUsage() {
|
|
|
288
296
|
" epic-implementer resume-run --epic-run-id <id>",
|
|
289
297
|
" # a cap_wall_clock pause whose cause is now cleared",
|
|
290
298
|
"",
|
|
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
299
|
"approve-plan options:",
|
|
297
300
|
" approve-plan <epic_key> --plan-version N [--json]",
|
|
298
301
|
" <epic_key> Epic key (e.g. EPIC-405) (required positional)",
|
|
@@ -386,7 +389,6 @@ export { HOOK_RUNTIME_PROBE_ACTION } from "./hook-runtime-qualification.js";
|
|
|
386
389
|
const VALID_COMMANDS = new Set([
|
|
387
390
|
"emit-event",
|
|
388
391
|
"supervise",
|
|
389
|
-
"epic-tick",
|
|
390
392
|
"approve-plan",
|
|
391
393
|
"epic-status",
|
|
392
394
|
"send-message",
|
|
@@ -429,6 +431,9 @@ const VALID_COMMANDS = new Set([
|
|
|
429
431
|
"acknowledge-gaps",
|
|
430
432
|
// BAPI-1532: CLI-only answer to a named plan failure — never an MCP tool.
|
|
431
433
|
"regenerate-plan",
|
|
434
|
+
// BAPI-1705: CLI-only driver open-decision council pair — never MCP tools.
|
|
435
|
+
"reserve-council",
|
|
436
|
+
"record-decision",
|
|
432
437
|
// BAPI-1469: CLI-only read-only bounded wait on a run's state — never an MCP tool.
|
|
433
438
|
"wait-run",
|
|
434
439
|
// BAPI-1557: CLI-only stored-ticket reader and private local-state writer — never an MCP tool.
|
|
@@ -1127,88 +1132,6 @@ export async function runGitHookCommand(argv) {
|
|
|
1127
1132
|
}
|
|
1128
1133
|
}
|
|
1129
1134
|
// ---------------------------------------------------------------------------
|
|
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
1135
|
// approve-plan
|
|
1213
1136
|
// ---------------------------------------------------------------------------
|
|
1214
1137
|
const APPROVE_PLAN_VALUE_FLAGS = new Set(["--plan-version"]);
|
|
@@ -1623,8 +1546,6 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
|
|
|
1623
1546
|
return await runEmitEventCommand(parsed.argv);
|
|
1624
1547
|
case "supervise":
|
|
1625
1548
|
return await runSuperviseCommand(parsed.argv);
|
|
1626
|
-
case "epic-tick":
|
|
1627
|
-
return await runEpicTickCommand(parsed.argv);
|
|
1628
1549
|
case "approve-plan":
|
|
1629
1550
|
return await runApprovePlanCommand(parsed.argv);
|
|
1630
1551
|
case "epic-status":
|
|
@@ -1752,6 +1673,13 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
|
|
|
1752
1673
|
const { runRegeneratePlanCommand } = await import("./recovery-cli.js");
|
|
1753
1674
|
return await runRegeneratePlanCommand(parsed.argv);
|
|
1754
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
|
+
}
|
|
1755
1683
|
case "wait-run": {
|
|
1756
1684
|
// BAPI-1469: read-only bounded wait. Lazily imported like the recovery
|
|
1757
1685
|
// verbs; a module-load failure gets fixed wording, never exception text.
|
|
@@ -1871,3 +1799,319 @@ export async function runEpicImplementerCli(argv, likelyTestsDeps) {
|
|
|
1871
1799
|
return 1;
|
|
1872
1800
|
}
|
|
1873
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
|
+
}
|