@bridge_gpt/mcp-server 0.2.72 → 0.2.73

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 (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -0,0 +1,594 @@
1
+ /**
2
+ * `epic-implementer epic-server` — the run's one epic server (BAPI-1546).
3
+ *
4
+ * A CLI-only subcommand of the existing `epic-implementer` bin (no new bin, no
5
+ * MCP tool). Driver verbs:
6
+ *
7
+ * epic-server prove --epic <KEY> --epic-run-id <id> --head <SHA>
8
+ * epic-server start --epic <KEY> --epic-run-id <id> --head <SHA>
9
+ * epic-server status --epic-run-id <id> [--since <seq>]
10
+ * epic-server stop --expect-epic-run-id <id>
11
+ *
12
+ * Worker verbs (through the own-build launcher on the worker's PATH; the run id
13
+ * comes from the executor-injected `BRIDGE_EPIC_SERVER_RUN_ID`, never an
14
+ * argument a branch could choose):
15
+ *
16
+ * epic-server turn acquire --ticket <KEY> --head <SHA> --wait <seconds>
17
+ * epic-server turn release --lease <handle>
18
+ *
19
+ * Intentional output is one JSON document on stdout; a failure is one sanitized
20
+ * line on stderr. Exit codes are 0 and 1. Nothing printed ever carries a login,
21
+ * a credential, a credential reference, a raw recipe command, or the instance
22
+ * nonce.
23
+ *
24
+ * The epic-server record (`~/.config/bridge/epic-server/<repo>.json`) has one
25
+ * reader and one writer, in `../epic-server-record.ts`; they are re-exported here.
26
+ */
27
+ import { execFileSync, spawn } from "node:child_process";
28
+ import { existsSync } from "node:fs";
29
+ import { readFile } from "node:fs/promises";
30
+ import os from "node:os";
31
+ import path from "node:path";
32
+ import { readEpicServerRecord, } from "../epic-server-record.js";
33
+ import { createDefaultEpicServerStateFs, epicServerRunPaths, findEpicServerRunPaths, isValidEpicKey, isValidEpicRunId, readEpicServerLiveState, EPIC_SERVER_RUN_ID_ENV, } from "./epic-server-state.js";
34
+ import { allocateLoopbackPort, createDefaultGitSeam, createDefaultHttpProbe, defaultRandomHex, isLeaseHandleShape, proveRecipe, readRecipe, sendIpcRequest, startEpicServerHelper, stopEpicServerHelper, EpicServerHelper, } from "./epic-server-runtime.js";
35
+ import { createDefaultEpicServerProcessDeps, readProcessStartTime, runRecipeCommand, startAppProcess, } from "./epic-server-processes.js";
36
+ import { EpicServerJournal } from "./epic-server-journal.js";
37
+ import { isFullCommitSha, proofCoversStart, validateEpicServerProof } from "./epic-server-recipe.js";
38
+ import { createDefaultWorkerDatabaseDeps } from "../executor/worker-database.js";
39
+ import { stripWorkerEnvFiles } from "../executor/env-file-guard.js";
40
+ import { resolveCredentialBundle } from "../credential-store.js";
41
+ import { fetchEpicRunState, resolveConductorBridgeApiAccess } from "./bridge-api-client.js";
42
+ import { readMcpGrant } from "../mcp-grant.js";
43
+ import { PLAYWRIGHT_PRESET_NAME } from "../mcp-presets.js";
44
+ export { readEpicServerRecord, writeEpicServerRecord, validateEpicServerRecord, } from "../epic-server-record.js";
45
+ export { SFCC_CHECK_RETRIES, SFCC_EVIDENCE_LABEL, runSfccSharedActiveCheck, buildSfccWorkerPolicyText, } from "./epic-server-sfcc.js";
46
+ /** The private helper launch action. Absent from usage. */
47
+ export const EPIC_SERVER_HELPER_ACTION = "__helper";
48
+ /** Default and ceiling for a worker's bounded turn wait. */
49
+ export const EPIC_SERVER_DEFAULT_TURN_WAIT_SECONDS = 180;
50
+ export const EPIC_SERVER_MAX_TURN_WAIT_SECONDS = 1800;
51
+ export function getEpicServerUsage() {
52
+ return [
53
+ "Usage: epic-implementer epic-server <verb> [options]",
54
+ "",
55
+ "The run's one epic server for UI checks (opt-in per repository at setup).",
56
+ "",
57
+ "Driver verbs:",
58
+ " prove --epic <KEY> --epic-run-id <id> --head <SHA> Replay the run recipe once against the epic head",
59
+ " start --epic <KEY> --epic-run-id <id> --head <SHA> Start (or attach to) the detached helper",
60
+ " status The repository's epic-server mode and Playwright grant",
61
+ " status --epic-run-id <id> [--since <seq>] Read the helper state and new journal events",
62
+ " stop --expect-epic-run-id <id> Guarded stop of this run's own helper",
63
+ "Worker verbs (run id from BRIDGE_EPIC_SERVER_RUN_ID):",
64
+ " turn acquire --ticket <KEY> --head <SHA> --wait <seconds>",
65
+ " turn release --lease <handle>",
66
+ ].join("\n");
67
+ }
68
+ const TICKET_RE = /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/;
69
+ const REPO_NAME_RE = /^[A-Za-z0-9._-]{1,100}$/;
70
+ function readFlags(argv, allowed) {
71
+ const values = new Map();
72
+ for (let i = 0; i < argv.length; i += 2) {
73
+ const flag = argv[i];
74
+ const value = argv[i + 1];
75
+ if (!allowed.includes(flag) || value === undefined || values.has(flag))
76
+ return null;
77
+ values.set(flag, value);
78
+ }
79
+ return values;
80
+ }
81
+ /** Parse argv. Error messages are fixed text; no argument is ever echoed. */
82
+ export function parseEpicServerArgs(argv) {
83
+ const bad = (message) => ({ verb: "error", message });
84
+ if (argv.length === 0 || argv[0] === "--help" || argv[0] === "-h")
85
+ return { verb: "help" };
86
+ const [verb, ...rest] = argv;
87
+ switch (verb) {
88
+ case "prove":
89
+ case "start": {
90
+ const flags = readFlags(rest, ["--epic", "--epic-run-id", "--head"]);
91
+ if (flags === null || flags.size !== 3)
92
+ return bad(`${verb} needs exactly --epic <KEY> --epic-run-id <id> --head <SHA>`);
93
+ const epicKey = flags.get("--epic");
94
+ const epicRunId = flags.get("--epic-run-id");
95
+ const head = flags.get("--head");
96
+ if (!isValidEpicKey(epicKey))
97
+ return bad("--epic is not a usable epic key");
98
+ if (!isValidEpicRunId(epicRunId))
99
+ return bad("--epic-run-id is not a usable run id");
100
+ if (!isFullCommitSha(head))
101
+ return bad("--head must be a full 40-character commit SHA");
102
+ return { verb, epicKey, epicRunId, head };
103
+ }
104
+ case "status": {
105
+ // BAPI-1613 R9: status output is always JSON, so `--json` is accepted and ignored.
106
+ const args = rest.filter((arg) => arg !== "--json");
107
+ if (args.length === 0)
108
+ return { verb: "mode" };
109
+ const flags = readFlags(args, ["--epic-run-id", "--since"]);
110
+ if (flags === null || !flags.has("--epic-run-id"))
111
+ return bad("status needs --epic-run-id <id> [--since <seq>]");
112
+ const epicRunId = flags.get("--epic-run-id");
113
+ if (!isValidEpicRunId(epicRunId))
114
+ return bad("--epic-run-id is not a usable run id");
115
+ const sinceRaw = flags.get("--since") ?? "0";
116
+ if (!/^\d{1,9}$/.test(sinceRaw))
117
+ return bad("--since must be a whole number");
118
+ return { verb: "status", epicRunId, since: Number(sinceRaw) };
119
+ }
120
+ case "stop": {
121
+ const flags = readFlags(rest, ["--expect-epic-run-id"]);
122
+ if (flags === null || flags.size !== 1)
123
+ return bad("stop needs exactly --expect-epic-run-id <id>; a bare stop is never run");
124
+ const id = flags.get("--expect-epic-run-id");
125
+ if (!isValidEpicRunId(id))
126
+ return bad("--expect-epic-run-id is not a usable run id");
127
+ return { verb: "stop", expectEpicRunId: id };
128
+ }
129
+ case "turn": {
130
+ const [sub, ...flagArgs] = rest;
131
+ if (sub === "acquire") {
132
+ const flags = readFlags(flagArgs, ["--ticket", "--head", "--wait"]);
133
+ if (flags === null || flags.size !== 3)
134
+ return bad("turn acquire needs --ticket <KEY> --head <SHA> --wait <seconds>");
135
+ const ticket = flags.get("--ticket");
136
+ const head = flags.get("--head");
137
+ const wait = flags.get("--wait");
138
+ if (!TICKET_RE.test(ticket))
139
+ return bad("--ticket is not a usable ticket key");
140
+ if (!isFullCommitSha(head))
141
+ return bad("--head must be a full 40-character commit SHA");
142
+ if (!/^\d{1,5}$/.test(wait) || Number(wait) < 1)
143
+ return bad("--wait must be a positive whole number of seconds");
144
+ return { verb: "acquire", ticket, head, waitSeconds: Math.min(Number(wait), EPIC_SERVER_MAX_TURN_WAIT_SECONDS) };
145
+ }
146
+ if (sub === "release") {
147
+ const flags = readFlags(flagArgs, ["--lease"]);
148
+ if (flags === null || flags.size !== 1)
149
+ return bad("turn release needs --lease <handle>");
150
+ const lease = flags.get("--lease");
151
+ if (!isLeaseHandleShape(lease))
152
+ return bad("--lease is not a lease handle from turn acquire");
153
+ return { verb: "release", lease };
154
+ }
155
+ return bad("turn takes acquire or release");
156
+ }
157
+ case EPIC_SERVER_HELPER_ACTION: {
158
+ const flags = readFlags(rest, ["--epic", "--epic-run-id", "--head", "--repo-name", "--repo-root"]);
159
+ if (flags === null || flags.size !== 5)
160
+ return bad("internal helper arguments are malformed");
161
+ const epicKey = flags.get("--epic");
162
+ const epicRunId = flags.get("--epic-run-id");
163
+ const head = flags.get("--head");
164
+ const repoName = flags.get("--repo-name");
165
+ const repoRoot = flags.get("--repo-root");
166
+ if (!isValidEpicKey(epicKey) || !isValidEpicRunId(epicRunId) || !isFullCommitSha(head)) {
167
+ return bad("internal helper arguments are malformed");
168
+ }
169
+ if (!REPO_NAME_RE.test(repoName) || !path.isAbsolute(repoRoot))
170
+ return bad("internal helper arguments are malformed");
171
+ return { verb: "helper", epicKey, epicRunId, head, repoName, repoRoot };
172
+ }
173
+ default:
174
+ return bad('unknown epic-server verb. Run "epic-implementer epic-server --help" for usage.');
175
+ }
176
+ }
177
+ export function createDefaultEpicServerCommandDeps() {
178
+ const fs = createDefaultEpicServerStateFs();
179
+ return {
180
+ env: process.env,
181
+ homedir: os.homedir,
182
+ tmpdir: os.tmpdir,
183
+ cwd: () => process.cwd(),
184
+ stdout: (text) => process.stdout.write(`${text}\n`),
185
+ stderr: (line) => process.stderr.write(`${line}\n`),
186
+ resolveRepoName: async () => {
187
+ try {
188
+ const access = await resolveConductorBridgeApiAccess();
189
+ return access.ok ? access.access.repoName : null;
190
+ }
191
+ catch {
192
+ return null;
193
+ }
194
+ },
195
+ resolveRepoRoot: () => {
196
+ try {
197
+ const out = execFileSync("git", ["rev-parse", "--show-toplevel"], { encoding: "utf8", timeout: 10_000, stdio: ["ignore", "pipe", "ignore"] }).trim();
198
+ return path.isAbsolute(out) ? out : null;
199
+ }
200
+ catch {
201
+ return null;
202
+ }
203
+ },
204
+ readRecord: (repoName) => readEpicServerRecord(repoName, {
205
+ env: process.env,
206
+ homedir: os.homedir,
207
+ readFile: (p) => readFile(p, "utf8"),
208
+ lstat: (p) => import("node:fs/promises").then((m) => m.lstat(p)),
209
+ }),
210
+ readPlaywrightGrant: async (repoName) => {
211
+ try {
212
+ const grant = await readMcpGrant(repoName, { env: process.env, homedir: os.homedir, readFile: (p) => readFile(p, "utf8") });
213
+ if (grant.state !== "ok")
214
+ return grant.state === "absent" ? "absent" : "unknown";
215
+ return grant.grant.servers.some((server) => server.name === PLAYWRIGHT_PRESET_NAME) ? "present" : "absent";
216
+ }
217
+ catch {
218
+ return "unknown";
219
+ }
220
+ },
221
+ runtime: () => {
222
+ const proc = createDefaultEpicServerProcessDeps();
223
+ const stateDir = path.join(os.homedir(), ".local", "state", "bapi-conductor-runs");
224
+ return {
225
+ fs,
226
+ proc,
227
+ git: createDefaultGitSeam(),
228
+ http: createDefaultHttpProbe(),
229
+ stripEnvFiles: async (worktreePath) => {
230
+ const nodeFs = await import("node:fs/promises");
231
+ const result = await stripWorkerEnvFiles(worktreePath, {
232
+ readdir: (p) => nodeFs.readdir(p),
233
+ lstat: (p) => nodeFs.lstat(p),
234
+ unlink: (p) => nodeFs.unlink(p),
235
+ });
236
+ return result.ok;
237
+ },
238
+ allocatePort: allocateLoopbackPort,
239
+ database: {
240
+ database: createDefaultWorkerDatabaseDeps({ stateDir, env: process.env }),
241
+ now: () => new Date(),
242
+ },
243
+ isPidAlive: (pid) => {
244
+ try {
245
+ process.kill(pid, 0);
246
+ return true;
247
+ }
248
+ catch (err) {
249
+ return err.code === "ESRCH" ? false : null;
250
+ }
251
+ },
252
+ resolveCredential: async (ref, key) => {
253
+ const nodeFs = await import("node:fs/promises");
254
+ const result = await resolveCredentialBundle(ref, [key], {
255
+ // The store only: an ambient value never satisfies a recipe reference.
256
+ env: {},
257
+ homedir: os.homedir,
258
+ platform: process.platform,
259
+ readFile: (p) => nodeFs.readFile(p, "utf8"),
260
+ stat: (p) => nodeFs.stat(p),
261
+ stderr: () => undefined,
262
+ });
263
+ return result.ok ? (result.values[key] ?? null) : null;
264
+ },
265
+ runCommand: runRecipeCommand,
266
+ startApp: startAppProcess,
267
+ helperEnv: process.env,
268
+ now: () => new Date(),
269
+ sleep: (ms) => new Promise((r) => setTimeout(r, ms)),
270
+ randomHex: defaultRandomHex,
271
+ };
272
+ },
273
+ launchHelper: (args, env) => {
274
+ const entry = process.argv[1];
275
+ if (typeof entry !== "string" || !path.isAbsolute(entry) || !existsSync(entry))
276
+ return null;
277
+ try {
278
+ // Its own session and process group, no inherited handles, unref'd: the
279
+ // driver's death leaves the helper serving.
280
+ // Keep whatever routed this process to `epic-server` (for example the
281
+ // `epic-implementer` token when the entry is the package's index.js).
282
+ const at = process.argv.indexOf("epic-server", 2);
283
+ const prefix = at === -1 ? [] : process.argv.slice(2, at);
284
+ const child = spawn(process.execPath, [entry, ...prefix, "epic-server", EPIC_SERVER_HELPER_ACTION, ...args], {
285
+ detached: true,
286
+ stdio: "ignore",
287
+ env,
288
+ cwd: os.homedir(),
289
+ });
290
+ child.on("error", () => undefined);
291
+ child.unref();
292
+ return typeof child.pid === "number" && child.pid > 1 ? child.pid : null;
293
+ }
294
+ catch {
295
+ return null;
296
+ }
297
+ },
298
+ readRunStatus: async (epicRunId, timeoutMs) => {
299
+ const access = await resolveConductorBridgeApiAccess();
300
+ if (!access.ok)
301
+ return null;
302
+ const body = (await fetchEpicRunState(access.access, epicRunId, undefined, undefined, timeoutMs));
303
+ const run = body && typeof body === "object" ? body.epic_run : null;
304
+ const status = run && typeof run === "object" ? run.status : null;
305
+ return typeof status === "string" ? status : null;
306
+ },
307
+ exit: (code) => process.exit(code),
308
+ };
309
+ }
310
+ // ---------------------------------------------------------------------------
311
+ // Verbs
312
+ // ---------------------------------------------------------------------------
313
+ function emit(deps, body) {
314
+ deps.stdout(JSON.stringify(body));
315
+ }
316
+ /**
317
+ * The worker-side unavailable result. It is shaped to be quoted, as is, as the
318
+ * observation of a `no_live_server` hand-off under the hand-off contract.
319
+ */
320
+ function unavailable(deps, command, head, reason) {
321
+ emit(deps, { outcome: "unavailable", cause: "no_live_server", reason, command, ...(head ? { head } : {}) });
322
+ deps.stderr(`epic-server: no_live_server (${reason}); record the step under the hand-off rules, nothing parks`);
323
+ return 1;
324
+ }
325
+ async function requireLocalMode(deps, verb) {
326
+ const repoName = await deps.resolveRepoName();
327
+ if (repoName === null) {
328
+ deps.stderr(`epic-server ${verb}: the repository identity could not be resolved; nothing was started`);
329
+ return { ok: false, code: 1 };
330
+ }
331
+ let record;
332
+ try {
333
+ record = await deps.readRecord(repoName);
334
+ }
335
+ catch {
336
+ record = { state: "unusable" };
337
+ }
338
+ if (record.state !== "ok" || record.record.mode === "none") {
339
+ deps.stderr(`epic-server ${verb}: this repository has not opted in to a local epic server; nothing was started`);
340
+ return { ok: false, code: 1 };
341
+ }
342
+ if (record.record.mode === "sfcc_shared_active") {
343
+ deps.stderr(`epic-server ${verb}: this repository uses the SFCC shared active version; there is no local helper or turn`);
344
+ return { ok: false, code: 1 };
345
+ }
346
+ return { ok: true, repoName };
347
+ }
348
+ function runPaths(deps, epicKey, epicRunId) {
349
+ return epicServerRunPaths(deps.homedir(), { epicKey, epicRunId }, deps.tmpdir());
350
+ }
351
+ async function runProve(deps, cmd) {
352
+ const mode = await requireLocalMode(deps, "prove");
353
+ if (!mode.ok)
354
+ return mode.code;
355
+ const repoRoot = deps.resolveRepoRoot();
356
+ const paths = runPaths(deps, cmd.epicKey, cmd.epicRunId);
357
+ if (repoRoot === null || paths === null) {
358
+ deps.stderr("epic-server prove: the run directory or repository root is not usable; nothing was proven");
359
+ return 1;
360
+ }
361
+ const outcome = await proveRecipe({ paths, repoRoot, epicHead: cmd.head, runId: cmd.epicRunId }, deps.runtime());
362
+ if (!outcome.ok) {
363
+ emit(deps, { outcome: "failed", verb: "prove", reason: outcome.reason });
364
+ deps.stderr(`epic-server prove: failed (${outcome.reason}); the run continues with the epic server unavailable`);
365
+ return 1;
366
+ }
367
+ emit(deps, { outcome: "proven", recipe_revision: outcome.proof.recipe_revision, epic_head: outcome.proof.epic_head });
368
+ return 0;
369
+ }
370
+ async function runStart(deps, cmd) {
371
+ const mode = await requireLocalMode(deps, "start");
372
+ if (!mode.ok)
373
+ return mode.code;
374
+ const repoRoot = deps.resolveRepoRoot();
375
+ const paths = runPaths(deps, cmd.epicKey, cmd.epicRunId);
376
+ if (repoRoot === null || paths === null) {
377
+ deps.stderr("epic-server start: the run directory or repository root is not usable; nothing was started");
378
+ return 1;
379
+ }
380
+ const outcome = await startEpicServerHelper({ paths, epicKey: cmd.epicKey, runId: cmd.epicRunId, repoName: mode.repoName, repoRoot, epicHead: cmd.head }, { runtime: deps.runtime(), launchHelper: deps.launchHelper });
381
+ if (!outcome.ok) {
382
+ emit(deps, { outcome: "failed", verb: "start", reason: outcome.reason });
383
+ deps.stderr(`epic-server start: failed (${outcome.reason}); the run continues with the epic server unavailable`);
384
+ return 1;
385
+ }
386
+ emit(deps, {
387
+ outcome: outcome.attached ? "attached" : "started",
388
+ url: outcome.state.url,
389
+ generation: outcome.state.generation,
390
+ served_sha: outcome.state.served_sha,
391
+ });
392
+ return 0;
393
+ }
394
+ /**
395
+ * The repository's mode and Playwright grant, for the driver's mode decision and
396
+ * its advisory UI readiness line. Reads the canonical record; writes nothing.
397
+ */
398
+ async function runMode(deps) {
399
+ const repoName = await deps.resolveRepoName();
400
+ if (repoName === null) {
401
+ emit(deps, { mode: "unknown", playwright_grant: "unknown" });
402
+ return 0;
403
+ }
404
+ let record;
405
+ try {
406
+ record = await deps.readRecord(repoName);
407
+ }
408
+ catch {
409
+ record = { state: "unusable" };
410
+ }
411
+ const mode = record.state === "ok" ? record.record.mode : record.state === "absent" ? "none" : "unknown";
412
+ emit(deps, { mode, playwright_grant: await deps.readPlaywrightGrant(repoName) });
413
+ return 0;
414
+ }
415
+ async function runStatus(deps, cmd) {
416
+ const rt = deps.runtime();
417
+ const paths = await findEpicServerRunPaths(deps.homedir(), cmd.epicRunId, rt.fs, deps.tmpdir());
418
+ if (paths === null) {
419
+ emit(deps, { running: false, journal: { events: [], cursor: cmd.since, more: false } });
420
+ return 0;
421
+ }
422
+ const live = await readEpicServerLiveState(paths.state, cmd.epicRunId, {
423
+ fs: rt.fs,
424
+ probe: { identity: async (pid) => {
425
+ const s = await readProcessStartTime(pid, rt.proc);
426
+ return s === null ? null : { startedAt: s };
427
+ } },
428
+ });
429
+ if (live.state === "live") {
430
+ const reply = await sendIpcRequest(live.value.socket_path, { op: "status", since: cmd.since }, 10_000);
431
+ if (reply !== null && reply.ok === true) {
432
+ const { ok: _ok, ...body } = reply;
433
+ emit(deps, { running: true, ...body });
434
+ return 0;
435
+ }
436
+ }
437
+ // Not running (or not answering): the journal file is still readable, unacknowledged.
438
+ const journal = await new EpicServerJournal(paths.journal, cmd.epicRunId, rt.fs).read(cmd.since);
439
+ emit(deps, { running: false, journal });
440
+ return 0;
441
+ }
442
+ async function runStop(deps, cmd) {
443
+ const rt = deps.runtime();
444
+ const paths = await findEpicServerRunPaths(deps.homedir(), cmd.expectEpicRunId, rt.fs, deps.tmpdir());
445
+ if (paths === null) {
446
+ emit(deps, { outcome: "not_running" });
447
+ return 0;
448
+ }
449
+ const outcome = await stopEpicServerHelper({ paths, runId: cmd.expectEpicRunId }, rt);
450
+ if (!outcome.ok) {
451
+ emit(deps, { outcome: "refused", reason: outcome.reason });
452
+ deps.stderr(`epic-server stop: refused (${outcome.reason}); nothing was signalled`);
453
+ return 1;
454
+ }
455
+ emit(deps, { outcome: outcome.outcome });
456
+ return 0;
457
+ }
458
+ async function workerRunPaths(deps) {
459
+ const runId = deps.env[EPIC_SERVER_RUN_ID_ENV];
460
+ if (!isValidEpicRunId(runId))
461
+ return null;
462
+ const paths = await findEpicServerRunPaths(deps.homedir(), runId, deps.runtime().fs, deps.tmpdir());
463
+ return paths === null ? null : { paths, runId };
464
+ }
465
+ async function runAcquire(deps, cmd) {
466
+ const command = `epic-implementer epic-server turn acquire --ticket ${cmd.ticket} --head ${cmd.head} --wait ${cmd.waitSeconds}`;
467
+ const located = await workerRunPaths(deps);
468
+ if (located === null)
469
+ return unavailable(deps, command, cmd.head, "no_epic_server_for_this_run");
470
+ const rt = deps.runtime();
471
+ const live = await readEpicServerLiveState(located.paths.state, located.runId, {
472
+ fs: rt.fs,
473
+ probe: { identity: async (pid) => {
474
+ const s = await readProcessStartTime(pid, rt.proc);
475
+ return s === null ? null : { startedAt: s };
476
+ } },
477
+ });
478
+ if (live.state !== "live")
479
+ return unavailable(deps, command, cmd.head, "helper_not_running");
480
+ // The helper waits at least the recipe's turn wait, then rebuilds under its own budget.
481
+ // Wait for both, so this client never gives up on a turn the helper would still grant.
482
+ const queueSeconds = Math.max(cmd.waitSeconds, live.value.turn_wait_seconds);
483
+ const reply = await sendIpcRequest(live.value.socket_path, { op: "acquire", ticket: cmd.ticket, head: cmd.head, wait_seconds: cmd.waitSeconds }, (queueSeconds + live.value.turn_build_seconds) * 1000 + 15_000);
484
+ if (reply === null)
485
+ return unavailable(deps, command, cmd.head, "helper_unreachable");
486
+ if (reply.ok !== true || reply.outcome !== "granted") {
487
+ const reason = typeof reply.reason === "string" && /^[a-z_]{1,40}$/.test(reply.reason) ? reply.reason : "turn_unavailable";
488
+ return unavailable(deps, command, cmd.head, reason);
489
+ }
490
+ emit(deps, {
491
+ outcome: "granted",
492
+ url: reply.url,
493
+ served_sha: reply.served_sha,
494
+ generation: reply.generation,
495
+ login_file: reply.login_file,
496
+ lease: reply.lease,
497
+ lease_seconds: reply.lease_seconds,
498
+ });
499
+ return 0;
500
+ }
501
+ async function runRelease(deps, cmd) {
502
+ const located = await workerRunPaths(deps);
503
+ const lost = (reason) => {
504
+ // A release that cannot be confirmed counts as lost: the observation does not count.
505
+ emit(deps, { outcome: "lost", reason });
506
+ return 0;
507
+ };
508
+ if (located === null)
509
+ return lost("no_epic_server_for_this_run");
510
+ const rt = deps.runtime();
511
+ const live = await readEpicServerLiveState(located.paths.state, located.runId, {
512
+ fs: rt.fs,
513
+ probe: { identity: async (pid) => {
514
+ const s = await readProcessStartTime(pid, rt.proc);
515
+ return s === null ? null : { startedAt: s };
516
+ } },
517
+ });
518
+ if (live.state !== "live")
519
+ return lost("helper_not_running");
520
+ const reply = await sendIpcRequest(live.value.socket_path, { op: "release", lease: cmd.lease }, 60_000);
521
+ if (reply === null || reply.ok !== true)
522
+ return lost("helper_unreachable");
523
+ if (reply.outcome === "retained") {
524
+ emit(deps, { outcome: "retained", generation: reply.generation, served_sha: reply.served_sha });
525
+ return 0;
526
+ }
527
+ return lost(typeof reply.reason === "string" && /^[a-z_]{1,40}$/.test(reply.reason) ? reply.reason : "fenced_or_expired");
528
+ }
529
+ /** The detached helper's main. Returns only through `deps.exit`. */
530
+ async function runHelper(deps, cmd) {
531
+ const rt = deps.runtime();
532
+ const paths = runPaths(deps, cmd.epicKey, cmd.epicRunId);
533
+ const nonce = deps.env.BRIDGE_EPIC_SERVER_INSTANCE_TAG;
534
+ if (paths === null || typeof nonce !== "string" || !/^[0-9a-f]{64}$/.test(nonce))
535
+ return 1;
536
+ const recipe = await readRecipe(paths, rt.fs);
537
+ const proof = validateEpicServerProof(await import("./epic-server-state.js").then((m) => m.readPrivateJson(rt.fs, paths.proof)));
538
+ if (recipe === null || !proofCoversStart(proof, recipe, cmd.head))
539
+ return 1;
540
+ const journal = new EpicServerJournal(paths.journal, cmd.epicRunId, rt.fs, rt.now);
541
+ const helper = new EpicServerHelper({
542
+ identity: { epicKey: cmd.epicKey, epicRunId: cmd.epicRunId, repoName: cmd.repoName, repoRoot: cmd.repoRoot, epicHead: cmd.head, nonce },
543
+ paths,
544
+ recipe,
545
+ deps: rt,
546
+ journal,
547
+ readRunStatus: () => deps.readRunStatus(cmd.epicRunId, recipe.timing.terminal_read_seconds * 1000),
548
+ onExit: (code) => deps.exit(code),
549
+ });
550
+ for (const sig of ["SIGTERM", "SIGINT", "SIGHUP"])
551
+ process.once(sig, () => void helper.shutdown("signal"));
552
+ process.on("uncaughtException", () => void helper.shutdown("signal"));
553
+ if (!(await helper.start())) {
554
+ await helper.shutdown("signal");
555
+ return 1;
556
+ }
557
+ // Keep the process alive; every exit goes through helper.shutdown → deps.exit.
558
+ return new Promise(() => undefined);
559
+ }
560
+ /** Run `epic-server`; returns the process exit code. */
561
+ export async function runEpicServerCommand(argv, deps = createDefaultEpicServerCommandDeps()) {
562
+ const cmd = parseEpicServerArgs(argv);
563
+ try {
564
+ switch (cmd.verb) {
565
+ case "help":
566
+ deps.stdout(getEpicServerUsage());
567
+ return 0;
568
+ case "error":
569
+ deps.stderr(`Error: epic-server: ${cmd.message}`);
570
+ return 1;
571
+ case "prove":
572
+ return await runProve(deps, cmd);
573
+ case "start":
574
+ return await runStart(deps, cmd);
575
+ case "status":
576
+ return await runStatus(deps, cmd);
577
+ case "mode":
578
+ return await runMode(deps);
579
+ case "stop":
580
+ return await runStop(deps, cmd);
581
+ case "acquire":
582
+ return await runAcquire(deps, cmd);
583
+ case "release":
584
+ return await runRelease(deps, cmd);
585
+ case "helper":
586
+ return await runHelper(deps, cmd);
587
+ }
588
+ }
589
+ catch {
590
+ // Fixed wording only: a thrown value may carry paths or argv.
591
+ deps.stderr("Error: epic-server failed unexpectedly; nothing further was changed. The run continues without it.");
592
+ return 1;
593
+ }
594
+ }