@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,1207 @@
1
+ /**
2
+ * The epic-server helper runtime (BAPI-1546).
3
+ *
4
+ * One helper per opted-in local run. The DRIVER proves and starts it; it then
5
+ * serves in the background, detached in its own session and process group, so
6
+ * the driver's death leaves it serving. It lives outside the engine and the
7
+ * executor job path: it never fails a job, writes run state, holds a gate, parks
8
+ * a ticket, or blocks a spawn. A crash, a hang, or a bad start only makes UI
9
+ * steps unrunnable.
10
+ *
11
+ * What the helper owns:
12
+ * - the app's process group (signalled only after a pid + start time + nonce check);
13
+ * - one serving worktree inside the run directory, detached at the served SHA,
14
+ * recreated for every head (never a worker's worktree, never Worktrunk);
15
+ * - one fixed loopback port per run, chosen free at start and never 8000;
16
+ * - a replacing environment for every recipe command (no `.env`, no ambient
17
+ * database settings);
18
+ * - optional per-turn databases (`epic-server-database.ts`).
19
+ *
20
+ * Turns are a FIFO queue of leases, each fenced by a generation. A turn: revoke
21
+ * the old lease and increment the generation, stop the app, remove the previous
22
+ * turn's resources, check out the exact requested head, prepare, provision,
23
+ * migrate, seed, start, wait for ready, then grant. The lease clock starts at the
24
+ * grant. A request whose bounded wait ends (or whose client disconnects) leaves
25
+ * the queue and can never later receive a lease.
26
+ *
27
+ * The helper replays only the validated, PROVEN recipe in the private run
28
+ * directory. It never reads repository guidance.
29
+ */
30
+ import { randomBytes } from "node:crypto";
31
+ import { execFile } from "node:child_process";
32
+ import http from "node:http";
33
+ import net from "node:net";
34
+ import path from "node:path";
35
+ import { boundedResult, ensurePrivateDirectory, epicServerLoginFilePath, epicServerLoopbackUrl, isFullCommitShaLike, isInsideDirectory, readEpicServerLiveState, readPrivateJson, removeFileQuietly, tryCreateClaim, validateEpicServerClaim, validateEpicServerOwnership, writePrivateFileAtomic, EPIC_SERVER_INSTANCE_TAG_ENV, EPIC_SERVER_OWNERSHIP_VERSION, EPIC_SERVER_STATE_VERSION, } from "./epic-server-state.js";
36
+ import { buildEpicServerCommandEnv, formatLoginFile, isOwnershipInspectionSupported, parseSeedOutput, readProcessStartTime, stopOwnedProcessGroup, verifyOwnedProcess, } from "./epic-server-processes.js";
37
+ import { dropTurnDatabase, isCurrentTurnDatabase, provisionTurnDatabase, sweepOwnLeftoverDatabases, } from "./epic-server-database.js";
38
+ import { epicServerRecipeDigest, proofCoversStart, substituteRecipeArgv, validateEpicServerProof, validateEpicServerRecipe, EPIC_SERVER_PROOF_VERSION, } from "./epic-server-recipe.js";
39
+ async function resolveCredentials(recipe, deps) {
40
+ const out = {};
41
+ for (const [name, { ref, key }] of Object.entries(recipe.credential_refs)) {
42
+ let value;
43
+ try {
44
+ value = await deps.resolveCredential(ref, key);
45
+ }
46
+ catch {
47
+ value = null;
48
+ }
49
+ if (value === null || value.length === 0)
50
+ return null;
51
+ out[name] = value;
52
+ }
53
+ return out;
54
+ }
55
+ async function runSteps(steps, cwd, env, port, ctx) {
56
+ for (const step of steps) {
57
+ const outcome = await ctx.deps.runCommand(substituteRecipeArgv(step.argv, port), {
58
+ cwd,
59
+ env,
60
+ timeoutMs: step.timeout_seconds * 1000,
61
+ captureStdout: false,
62
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
63
+ });
64
+ if (outcome.kind !== "ok")
65
+ return outcome.kind;
66
+ }
67
+ return "ok";
68
+ }
69
+ async function awaitReady(ctx, env, cwd) {
70
+ const ready = ctx.recipe.ready;
71
+ const deadline = Date.now() + ready.timeout_seconds * 1000;
72
+ const base = epicServerLoopbackUrl(ctx.port);
73
+ while (Date.now() < deadline) {
74
+ if (ctx.signal?.aborted)
75
+ return "cancelled";
76
+ if (ready.kind === "url") {
77
+ const res = await ctx.deps.http.get(`${base}${ready.path}`, Math.min(5_000, Math.max(1, deadline - Date.now())));
78
+ if (res !== null) {
79
+ if (res.status >= 200 && res.status < 300)
80
+ return "ok";
81
+ if (res.status >= 300 && res.status < 400) {
82
+ // A redirect is ready only when it stays on the run's own address.
83
+ if (res.location === null)
84
+ return "ready_redirect_refused";
85
+ let target;
86
+ try {
87
+ target = new URL(res.location, base);
88
+ }
89
+ catch {
90
+ return "ready_redirect_refused";
91
+ }
92
+ return target.origin === base ? "ok" : "ready_redirect_refused";
93
+ }
94
+ }
95
+ }
96
+ else {
97
+ const outcome = await ctx.deps.runCommand(substituteRecipeArgv(ready.argv, ctx.port), {
98
+ cwd,
99
+ env,
100
+ timeoutMs: Math.max(1, Math.min(10_000, deadline - Date.now())),
101
+ captureStdout: false,
102
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
103
+ });
104
+ if (outcome.kind === "ok")
105
+ return "ok";
106
+ if (outcome.kind === "cancelled")
107
+ return "cancelled";
108
+ }
109
+ await ctx.deps.sleep(Math.min(500, Math.max(1, deadline - Date.now())));
110
+ }
111
+ return "ready_timeout";
112
+ }
113
+ /**
114
+ * Replay the recipe against one exact head: a fresh detached serving checkout,
115
+ * the env-file guard, prepare, the optional database, migrate, seed, start, and
116
+ * ready. Ownership of every resource is recorded before it is exposed. On
117
+ * failure the partial turn is returned for teardown.
118
+ */
119
+ export async function runServingPipeline(ctx, sha, generation) {
120
+ const { deps, paths, recipe } = ctx;
121
+ const turn = { generation, sha, app: null, database: null, loginFile: null };
122
+ const fail = (reason) => ({ ok: false, reason, partial: turn });
123
+ // A fresh checkout for every head: ignored artifacts and generated files from
124
+ // an earlier turn can never reach another worker's verification.
125
+ const worktree = paths.servingWorktree;
126
+ if (!isInsideDirectory(paths.runDir, worktree))
127
+ return fail("worktree_failed");
128
+ await deps.git.removeWorktree(ctx.repoRoot, worktree, 30_000).catch(() => undefined);
129
+ await deps.fs.rm(worktree, { recursive: true, force: true }).catch(() => undefined);
130
+ await ctx.recordOwnership({ serving_worktree: worktree });
131
+ const stepMs = recipe.timing.step_seconds * 1000;
132
+ if (!(await deps.git.ensureCommit(ctx.repoRoot, sha, stepMs)))
133
+ return fail("worktree_failed");
134
+ if (!(await deps.git.addDetachedWorktree(ctx.repoRoot, worktree, sha, stepMs)))
135
+ return fail("worktree_failed");
136
+ if ((await deps.git.headOf(worktree, 10_000)) !== sha)
137
+ return fail("worktree_failed");
138
+ if (!(await deps.stripEnvFiles(worktree)))
139
+ return fail("env_file_guard_failed");
140
+ const credentials = await resolveCredentials(recipe, deps);
141
+ if (credentials === null)
142
+ return fail("credential_unavailable");
143
+ const baseEnvInput = {
144
+ helperEnv: deps.helperEnv,
145
+ inputs: recipe.inputs,
146
+ credentials,
147
+ port: ctx.port,
148
+ nonce: ctx.nonce,
149
+ };
150
+ const noDbEnv = buildEpicServerCommandEnv({ ...baseEnvInput, database: null });
151
+ const prepared = await runSteps(recipe.prepare, worktree, noDbEnv, ctx.port, ctx);
152
+ if (prepared !== "ok")
153
+ return fail(prepared === "cancelled" ? "cancelled" : "prepare_failed");
154
+ let dbSettings = null;
155
+ if (recipe.database !== null) {
156
+ if (deps.database === null)
157
+ return fail("database_unavailable");
158
+ const provisioned = await provisionTurnDatabase({ runId: ctx.runId, helperPid: ctx.helperPid, nonce: ctx.nonce, generation }, recipe.database.role, stepMs, deps.database);
159
+ if (provisioned.kind !== "ready")
160
+ return fail("database_unavailable");
161
+ turn.database = { name: provisioned.name, role: recipe.database.role };
162
+ await ctx.recordOwnership({ databases: [{ name: provisioned.name, role: recipe.database.role, generation }] });
163
+ dbSettings = provisioned.settings;
164
+ }
165
+ // Migrate and seed only ever target the helper's CURRENT per-turn database.
166
+ if (dbSettings !== null && !isCurrentTurnDatabase(dbSettings, turn.database))
167
+ return fail("database_unavailable");
168
+ const env = buildEpicServerCommandEnv({ ...baseEnvInput, database: dbSettings });
169
+ const migrated = await runSteps(recipe.migrate, worktree, env, ctx.port, ctx);
170
+ if (migrated !== "ok")
171
+ return fail(migrated === "cancelled" ? "cancelled" : "migrate_failed");
172
+ if (recipe.seed !== null) {
173
+ const seeded = await deps.runCommand(substituteRecipeArgv(recipe.seed.argv, ctx.port), {
174
+ cwd: worktree,
175
+ env,
176
+ timeoutMs: recipe.seed.timeout_seconds * 1000,
177
+ captureStdout: true,
178
+ ...(ctx.signal ? { signal: ctx.signal } : {}),
179
+ });
180
+ if (seeded.kind !== "ok")
181
+ return fail(seeded.kind === "cancelled" ? "cancelled" : "seed_failed");
182
+ const values = parseSeedOutput(seeded.stdout, recipe.seed.outputs);
183
+ if (values === null)
184
+ return fail("seed_output_invalid");
185
+ const loginFile = epicServerLoginFilePath(paths, generation);
186
+ await writePrivateFileAtomic(deps.fs, loginFile, formatLoginFile(values, recipe.seed.outputs));
187
+ turn.loginFile = loginFile;
188
+ await ctx.recordOwnership({ login_files: [loginFile] });
189
+ }
190
+ const started = deps.startApp(substituteRecipeArgv(recipe.start.argv, ctx.port), { cwd: worktree, env });
191
+ if (started === null)
192
+ return fail("start_failed");
193
+ const startedAt = await readProcessStartTime(started.pid, deps.proc);
194
+ if (startedAt === null) {
195
+ // The app died at once, or its identity cannot be read: never signalled blind.
196
+ return fail("start_failed");
197
+ }
198
+ turn.app = { pid: started.pid, started_at: startedAt, child: started.child };
199
+ await ctx.recordOwnership({ app: { pid: started.pid, started_at: startedAt } });
200
+ const ready = await awaitReady(ctx, env, worktree);
201
+ if (ready !== "ok")
202
+ return fail(ready);
203
+ return { ok: true, turn };
204
+ }
205
+ /**
206
+ * Tear one turn down: stop the app (guarded), drop its database, remove its
207
+ * login file. Returns false when any resource could not be confirmed gone, in
208
+ * which case its ownership record is kept for recovery.
209
+ */
210
+ export async function teardownTurn(ctx, turn) {
211
+ let clean = true;
212
+ const graceMs = Math.min(10_000, ctx.recipe.timing.cleanup_seconds * 1000);
213
+ if (turn.app !== null) {
214
+ const stopped = await stopOwnedProcessGroup(turn.app, ctx.nonce, graceMs, ctx.deps.proc);
215
+ if (stopped === "refused")
216
+ clean = false;
217
+ else
218
+ turn.app = null;
219
+ }
220
+ if (turn.database !== null && ctx.deps.database !== null) {
221
+ if (await dropTurnDatabase(turn.database.name, turn.database.role, ctx.recipe.timing.cleanup_seconds * 1000, ctx.deps.database)) {
222
+ turn.database = null;
223
+ }
224
+ else {
225
+ clean = false;
226
+ }
227
+ }
228
+ if (turn.loginFile !== null) {
229
+ if (await removeFileQuietly(ctx.deps.fs, turn.loginFile))
230
+ turn.loginFile = null;
231
+ else
232
+ clean = false;
233
+ }
234
+ await ctx.recordOwnership({
235
+ app: turn.app === null ? null : { pid: turn.app.pid, started_at: turn.app.started_at },
236
+ databases: turn.database === null ? [] : [{ ...turn.database, generation: turn.generation }],
237
+ login_files: turn.loginFile === null ? [] : [turn.loginFile],
238
+ });
239
+ return clean;
240
+ }
241
+ // ---------------------------------------------------------------------------
242
+ // Recipe, proof, and ownership files
243
+ // ---------------------------------------------------------------------------
244
+ export async function readRecipe(paths, fs) {
245
+ const raw = await readPrivateJson(fs, paths.recipe);
246
+ if (raw === null)
247
+ return null;
248
+ const validated = validateEpicServerRecipe(raw);
249
+ return validated.ok ? validated.recipe : null;
250
+ }
251
+ export async function readProof(paths, fs) {
252
+ return validateEpicServerProof(await readPrivateJson(fs, paths.proof));
253
+ }
254
+ export async function readOwnership(paths, fs) {
255
+ return validateEpicServerOwnership(await readPrivateJson(fs, paths.ownership));
256
+ }
257
+ function ownershipRecorder(paths, fs, base) {
258
+ let current = base;
259
+ return async (update) => {
260
+ current = { ...current, ...update };
261
+ await writePrivateFileAtomic(fs, paths.ownership, `${JSON.stringify(current)}\n`);
262
+ };
263
+ }
264
+ /** Remove the serving worktree; never anything outside the run directory. */
265
+ async function removeServingWorktree(paths, repoRoot, deps) {
266
+ if (!isInsideDirectory(paths.runDir, paths.servingWorktree))
267
+ return;
268
+ await deps.git.removeWorktree(repoRoot, paths.servingWorktree, 30_000).catch(() => undefined);
269
+ await deps.fs.rm(paths.servingWorktree, { recursive: true, force: true }).catch(() => undefined);
270
+ }
271
+ /**
272
+ * Reclaim what a helper that died without cleanup left behind, from its
273
+ * persisted ownership record. Only when the recorded helper is definitively gone
274
+ * (pid dead, or reused by a process with another start time). Each resource is
275
+ * reclaimed only on an identity match; anything unconfirmed keeps its record.
276
+ */
277
+ export async function recoverAbandonedResources(paths, deps) {
278
+ const ownership = await readOwnership(paths, deps.fs);
279
+ if (ownership === null)
280
+ return "nothing";
281
+ const helperStart = await readProcessStartTime(ownership.helper_pid, deps.proc);
282
+ if (helperStart !== null && helperStart === ownership.helper_started_at)
283
+ return "owner_live";
284
+ let clean = true;
285
+ if (ownership.app !== null) {
286
+ // A pid now held by a process with another start time is the recorded app
287
+ // gone (pid reuse): never signalled, and not a reason to keep the record
288
+ // forever. Only a live process with the recorded start time is stopped.
289
+ const appStart = await readProcessStartTime(ownership.app.pid, deps.proc);
290
+ if (appStart !== null && appStart === ownership.app.started_at) {
291
+ const stopped = await stopOwnedProcessGroup(ownership.app, ownership.instance_nonce, 10_000, deps.proc);
292
+ if (stopped === "refused")
293
+ clean = false;
294
+ }
295
+ }
296
+ if (deps.database !== null) {
297
+ for (const db of ownership.databases) {
298
+ if (!(await dropTurnDatabase(db.name, db.role, 30_000, deps.database)))
299
+ clean = false;
300
+ }
301
+ }
302
+ for (const file of ownership.login_files) {
303
+ if (!isInsideDirectory(paths.runDir, file) || !(await removeFileQuietly(deps.fs, file)))
304
+ clean = false;
305
+ }
306
+ if (ownership.serving_worktree !== null)
307
+ await removeServingWorktree(paths, ownership.repo_root, deps);
308
+ await removeFileQuietly(deps.fs, paths.state);
309
+ await removeFileQuietly(deps.fs, paths.claim);
310
+ await deps.fs.rm(paths.socketDir, { recursive: true, force: true }).catch(() => undefined);
311
+ if (clean) {
312
+ await removeFileQuietly(deps.fs, paths.ownership);
313
+ return "reclaimed";
314
+ }
315
+ return "retained";
316
+ }
317
+ /**
318
+ * Prove one recipe revision against the exact epic head: an exclusively owned
319
+ * run of the serving pipeline, fully cleaned up before returning. A matching
320
+ * live helper must be stopped (guarded) first; proof never runs a second app.
321
+ */
322
+ export async function proveRecipe(input, deps) {
323
+ const { paths } = input;
324
+ if (!isOwnershipInspectionSupported(deps.proc.platform))
325
+ return { ok: false, reason: "inspection_unsupported" };
326
+ const recipe = await readRecipe(paths, deps.fs);
327
+ if (recipe === null)
328
+ return { ok: false, reason: "recipe_invalid" };
329
+ const live = await readEpicServerLiveState(paths.state, input.runId, { fs: deps.fs, probe: { identity: async (pid) => {
330
+ const s = await readProcessStartTime(pid, deps.proc);
331
+ return s === null ? null : { startedAt: s };
332
+ } } });
333
+ if (live.state === "live")
334
+ return { ok: false, reason: "helper_running" };
335
+ await recoverAbandonedResources(paths, deps);
336
+ const nonce = deps.randomHex(32);
337
+ const selfStart = (await readProcessStartTime(deps.proc.selfPid, deps.proc)) ?? "unknown";
338
+ const claimed = await tryCreateClaim(deps.fs, paths.claim, {
339
+ epic_run_id: input.runId,
340
+ helper_pid: deps.proc.selfPid,
341
+ helper_started_at: selfStart,
342
+ instance_nonce: nonce,
343
+ created_at: deps.now().toISOString(),
344
+ });
345
+ if (!claimed)
346
+ return { ok: false, reason: "busy" };
347
+ const port = await deps.allocatePort();
348
+ if (port === null) {
349
+ await removeFileQuietly(deps.fs, paths.claim);
350
+ return { ok: false, reason: "no_port" };
351
+ }
352
+ const base = {
353
+ version: EPIC_SERVER_OWNERSHIP_VERSION,
354
+ epic_key: path.basename(path.dirname(path.dirname(paths.runDir))),
355
+ epic_run_id: input.runId,
356
+ helper_pid: deps.proc.selfPid,
357
+ helper_started_at: selfStart,
358
+ instance_nonce: nonce,
359
+ repo_root: input.repoRoot,
360
+ app: null,
361
+ serving_worktree: null,
362
+ databases: [],
363
+ login_files: [],
364
+ };
365
+ const recordOwnership = ownershipRecorder(paths, deps.fs, base);
366
+ await recordOwnership({});
367
+ const ctx = {
368
+ paths,
369
+ repoRoot: input.repoRoot,
370
+ recipe,
371
+ port,
372
+ nonce,
373
+ runId: input.runId,
374
+ helperPid: deps.proc.selfPid,
375
+ deps,
376
+ recordOwnership,
377
+ };
378
+ const proofDeadline = recipe.timing.proof_seconds * 1000;
379
+ const controller = new AbortController();
380
+ const timer = setTimeout(() => controller.abort(), proofDeadline);
381
+ timer.unref?.();
382
+ let served;
383
+ try {
384
+ served = await runServingPipeline({ ...ctx, signal: controller.signal }, input.epicHead, 0);
385
+ }
386
+ finally {
387
+ clearTimeout(timer);
388
+ }
389
+ const turn = served.ok ? served.turn : served.partial;
390
+ const clean = await teardownTurn(ctx, turn);
391
+ await removeServingWorktree(paths, input.repoRoot, deps);
392
+ if (clean)
393
+ await removeFileQuietly(deps.fs, paths.ownership);
394
+ await removeFileQuietly(deps.fs, paths.claim);
395
+ if (!served.ok)
396
+ return { ok: false, reason: served.reason };
397
+ if (!clean)
398
+ return { ok: false, reason: "cleanup_incomplete" };
399
+ const proof = {
400
+ version: EPIC_SERVER_PROOF_VERSION,
401
+ recipe_digest: epicServerRecipeDigest(recipe),
402
+ recipe_revision: recipe.revision,
403
+ epic_head: input.epicHead,
404
+ proved_at: deps.now().toISOString(),
405
+ };
406
+ await writePrivateFileAtomic(deps.fs, paths.proof, `${JSON.stringify(proof)}\n`);
407
+ return { ok: true, proof };
408
+ }
409
+ // ---------------------------------------------------------------------------
410
+ // IPC protocol
411
+ // ---------------------------------------------------------------------------
412
+ export const EPIC_SERVER_IPC_MAX_BYTES = 16 * 1024;
413
+ const TICKET_RE = /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/;
414
+ const LEASE_RE = /^esl1_[0-9]{1,9}_[0-9a-f]{32}$/;
415
+ /** True for a lease handle's well-formed shape (its binding is checked by the helper). */
416
+ export function isLeaseHandleShape(value) {
417
+ return typeof value === "string" && LEASE_RE.test(value);
418
+ }
419
+ /** Validate one IPC request. Unknown ops or fields are rejected. */
420
+ export function parseIpcRequest(raw) {
421
+ if (raw === null || typeof raw !== "object" || Array.isArray(raw))
422
+ return null;
423
+ const doc = raw;
424
+ const keys = Object.keys(doc);
425
+ switch (doc.op) {
426
+ case "acquire":
427
+ if (keys.length !== 4)
428
+ return null;
429
+ if (typeof doc.ticket !== "string" || !TICKET_RE.test(doc.ticket))
430
+ return null;
431
+ if (!isFullCommitShaLike(doc.head))
432
+ return null;
433
+ if (typeof doc.wait_seconds !== "number" || !Number.isInteger(doc.wait_seconds) || doc.wait_seconds < 1 || doc.wait_seconds > 3600) {
434
+ return null;
435
+ }
436
+ return { op: "acquire", ticket: doc.ticket, head: doc.head, wait_seconds: doc.wait_seconds };
437
+ case "release":
438
+ if (keys.length !== 2 || !isLeaseHandleShape(doc.lease))
439
+ return null;
440
+ return { op: "release", lease: doc.lease };
441
+ case "status":
442
+ if (keys.length === 1)
443
+ return { op: "status" };
444
+ if (keys.length === 2 && typeof doc.since === "number" && Number.isSafeInteger(doc.since) && doc.since >= 0) {
445
+ return { op: "status", since: doc.since };
446
+ }
447
+ return null;
448
+ case "shutdown":
449
+ if (keys.length !== 2 || typeof doc.expect_epic_run_id !== "string")
450
+ return null;
451
+ return { op: "shutdown", expect_epic_run_id: doc.expect_epic_run_id };
452
+ default:
453
+ return null;
454
+ }
455
+ }
456
+ /** Send one request and read one JSON response. Never throws; null on any failure. */
457
+ export function sendIpcRequest(socketPath, request, timeoutMs) {
458
+ return new Promise((resolve) => {
459
+ let settled = false;
460
+ let buffer = "";
461
+ const done = (value) => {
462
+ if (settled)
463
+ return;
464
+ settled = true;
465
+ clearTimeout(timer);
466
+ socket.destroy();
467
+ resolve(value);
468
+ };
469
+ const socket = net.createConnection({ path: socketPath });
470
+ const timer = setTimeout(() => done(null), Math.max(1, timeoutMs));
471
+ socket.setEncoding("utf8");
472
+ socket.on("connect", () => socket.write(`${JSON.stringify(request)}\n`));
473
+ socket.on("data", (chunk) => {
474
+ buffer += chunk;
475
+ if (buffer.length > EPIC_SERVER_IPC_MAX_BYTES)
476
+ return done(null);
477
+ const nl = buffer.indexOf("\n");
478
+ if (nl === -1)
479
+ return;
480
+ try {
481
+ const parsed = JSON.parse(buffer.slice(0, nl));
482
+ done(parsed !== null && typeof parsed === "object" && !Array.isArray(parsed) ? parsed : null);
483
+ }
484
+ catch {
485
+ done(null);
486
+ }
487
+ });
488
+ socket.on("error", () => done(null));
489
+ socket.on("close", () => done(null));
490
+ });
491
+ }
492
+ /** The queue wait a turn request gets: the larger of what the worker asked for and the recipe's turn wait. */
493
+ export function epicServerTurnWaitSeconds(requested, recipe) {
494
+ return Math.max(requested, recipe.timing.acquire_wait_seconds);
495
+ }
496
+ /** The rebuild budget once a turn reaches the front: the bound the recipe was proven under. */
497
+ export function epicServerTurnBuildSeconds(recipe) {
498
+ return recipe.timing.proof_seconds;
499
+ }
500
+ const TERMINAL_RUN_STATUSES = new Set(["done", "abandoned"]);
501
+ const RECENT_LEASE_OUTCOMES = 64;
502
+ /**
503
+ * The background helper. Owns queue order, deadlines, generations,
504
+ * cancellations, and app transitions. Every exit path goes through
505
+ * {@link EpicServerHelper.shutdown}, which is idempotent.
506
+ */
507
+ export class EpicServerHelper {
508
+ options;
509
+ server = null;
510
+ port = 0;
511
+ generation = 0;
512
+ servedSha = null;
513
+ turn = null;
514
+ lease = null;
515
+ queue = [];
516
+ recentLeases = new Map();
517
+ processing = false;
518
+ stopping = null;
519
+ timers = [];
520
+ pollTimer = null;
521
+ sockets = new Set();
522
+ ctx;
523
+ helperStartedAt = "";
524
+ constructor(options) {
525
+ this.options = options;
526
+ const { identity, paths, recipe, deps } = options;
527
+ const base = {
528
+ version: EPIC_SERVER_OWNERSHIP_VERSION,
529
+ epic_key: identity.epicKey,
530
+ epic_run_id: identity.epicRunId,
531
+ helper_pid: deps.proc.selfPid,
532
+ helper_started_at: "",
533
+ instance_nonce: identity.nonce,
534
+ repo_root: identity.repoRoot,
535
+ app: null,
536
+ serving_worktree: null,
537
+ databases: [],
538
+ login_files: [],
539
+ };
540
+ this.ownershipBase = base;
541
+ this.ctx = {
542
+ paths,
543
+ repoRoot: identity.repoRoot,
544
+ recipe,
545
+ port: 0,
546
+ nonce: identity.nonce,
547
+ runId: identity.epicRunId,
548
+ helperPid: deps.proc.selfPid,
549
+ deps,
550
+ recordOwnership: async () => undefined,
551
+ };
552
+ }
553
+ ownershipBase;
554
+ /** Bind the port and IPC endpoint, write live state, and begin serving. */
555
+ async start() {
556
+ const { deps, paths, identity, recipe } = this.options;
557
+ this.helperStartedAt = (await readProcessStartTime(deps.proc.selfPid, deps.proc)) ?? "";
558
+ if (this.helperStartedAt === "")
559
+ return false;
560
+ this.ownershipBase = { ...this.ownershipBase, helper_started_at: this.helperStartedAt };
561
+ this.ctx.recordOwnership = ownershipRecorder(paths, deps.fs, this.ownershipBase);
562
+ await this.ctx.recordOwnership({});
563
+ const port = await deps.allocatePort();
564
+ if (port === null)
565
+ return false;
566
+ this.port = port;
567
+ this.ctx.port = port;
568
+ await deps.fs.rm(paths.socketDir, { recursive: true, force: true }).catch(() => undefined);
569
+ await ensurePrivateDirectory(deps.fs, paths.socketDir);
570
+ const server = net.createServer((socket) => this.handleConnection(socket));
571
+ const listening = await new Promise((resolve) => {
572
+ server.once("error", () => resolve(false));
573
+ server.listen(paths.socket, () => resolve(true));
574
+ });
575
+ if (!listening)
576
+ return false;
577
+ this.server = server;
578
+ await deps.fs.chmod(paths.socket, 0o600).catch(() => undefined);
579
+ await this.writeState();
580
+ await this.options.journal.append("helper_started");
581
+ // Abrupt-death leftovers of THIS run's earlier helpers.
582
+ if (recipe.database !== null && deps.database !== null) {
583
+ await sweepOwnLeftoverDatabases({ runId: identity.epicRunId, helperPid: deps.proc.selfPid, nonce: identity.nonce }, recipe.database.role, recipe.timing.cleanup_seconds * 1000, { ...deps.database, isPidAlive: deps.isPidAlive }).catch(() => undefined);
584
+ }
585
+ // Maximum lifetime never extends with leases.
586
+ const lifetime = setTimeout(() => void this.shutdown("max_lifetime"), recipe.timing.max_lifetime_seconds * 1000);
587
+ lifetime.unref?.();
588
+ this.timers.push(lifetime);
589
+ this.scheduleTerminalPoll();
590
+ // Bootstrap at the proven epic head as generation 0, without a lease.
591
+ void this.bootstrap();
592
+ return true;
593
+ }
594
+ async bootstrap() {
595
+ this.processing = true;
596
+ try {
597
+ const served = await runServingPipeline(this.ctx, this.options.identity.epicHead, this.generation);
598
+ if (this.stopping)
599
+ return;
600
+ if (served.ok) {
601
+ this.turn = served.turn;
602
+ this.servedSha = served.turn.sha;
603
+ this.watchApp(served.turn);
604
+ await this.writeState();
605
+ await this.options.journal.append("bootstrap_served", { generation: this.generation, sha: served.turn.sha, outcome: "ok" });
606
+ }
607
+ else {
608
+ this.turn = served.partial;
609
+ await this.options.journal.append("bootstrap_failed", { generation: this.generation, reason: served.reason, outcome: "failed" });
610
+ await this.endTurn();
611
+ }
612
+ }
613
+ finally {
614
+ this.processing = false;
615
+ void this.processQueue();
616
+ }
617
+ }
618
+ scheduleTerminalPoll() {
619
+ const { recipe } = this.options;
620
+ const poll = setTimeout(async () => {
621
+ if (this.stopping)
622
+ return;
623
+ const status = await boundedResult(this.options.readRunStatus().catch(() => null), recipe.timing.terminal_read_seconds * 1000, null);
624
+ // A failed or unknown read is advisory: keep serving until the lifetime ends.
625
+ if (status !== null && TERMINAL_RUN_STATUSES.has(status)) {
626
+ void this.shutdown("run_terminal");
627
+ return;
628
+ }
629
+ this.scheduleTerminalPoll();
630
+ }, recipe.timing.terminal_poll_seconds * 1000);
631
+ poll.unref?.();
632
+ // One poll timer is pending at a time; it replaces the previous one.
633
+ this.pollTimer = poll;
634
+ }
635
+ async writeState() {
636
+ const { identity, paths, deps } = this.options;
637
+ const state = {
638
+ version: EPIC_SERVER_STATE_VERSION,
639
+ epic_key: identity.epicKey,
640
+ epic_run_id: identity.epicRunId,
641
+ repo_name: identity.repoName,
642
+ helper_pid: deps.proc.selfPid,
643
+ helper_started_at: this.helperStartedAt,
644
+ instance_nonce: identity.nonce,
645
+ port: this.port,
646
+ url: epicServerLoopbackUrl(this.port),
647
+ socket_path: paths.socket,
648
+ turn_wait_seconds: this.options.recipe.timing.acquire_wait_seconds,
649
+ turn_build_seconds: epicServerTurnBuildSeconds(this.options.recipe),
650
+ served_sha: this.servedSha,
651
+ generation: this.generation,
652
+ updated_at: deps.now().toISOString(),
653
+ };
654
+ await writePrivateFileAtomic(deps.fs, paths.state, `${JSON.stringify(state)}\n`).catch(() => undefined);
655
+ }
656
+ watchApp(turn) {
657
+ turn.app?.child.once("exit", () => {
658
+ if (this.turn !== turn || this.stopping)
659
+ return;
660
+ turn.app = null;
661
+ void this.onAppFailure();
662
+ });
663
+ }
664
+ async onAppFailure() {
665
+ const lease = this.lease;
666
+ await this.options.journal.append("app_exited", { generation: this.generation, reason: "app_failed" });
667
+ if (lease !== null)
668
+ this.loseLease(lease, "app_failed");
669
+ this.servedSha = null;
670
+ await this.endTurn();
671
+ await this.writeState();
672
+ void this.processQueue();
673
+ }
674
+ loseLease(lease, reason) {
675
+ clearTimeout(lease.timer);
676
+ this.rememberLease(lease.handle, "lost");
677
+ if (this.lease === lease)
678
+ this.lease = null;
679
+ void this.options.journal.append("turn_lost", { generation: lease.generation, ticket: lease.ticket, reason, outcome: "lost" });
680
+ }
681
+ rememberLease(handle, outcome) {
682
+ this.recentLeases.set(handle, outcome);
683
+ while (this.recentLeases.size > RECENT_LEASE_OUTCOMES) {
684
+ const first = this.recentLeases.keys().next().value;
685
+ if (first === undefined)
686
+ break;
687
+ this.recentLeases.delete(first);
688
+ }
689
+ }
690
+ /** Stop the app and remove the turn's database and login file. */
691
+ async endTurn() {
692
+ const turn = this.turn;
693
+ this.turn = null;
694
+ if (turn === null)
695
+ return true;
696
+ const clean = await teardownTurn(this.ctx, turn);
697
+ if (!clean)
698
+ await this.options.journal.append("serving_failed", { generation: turn.generation, reason: "cleanup_incomplete" });
699
+ return clean;
700
+ }
701
+ handleConnection(socket) {
702
+ this.sockets.add(socket);
703
+ socket.once("close", () => this.sockets.delete(socket));
704
+ let buffer = "";
705
+ let handled = false;
706
+ socket.setEncoding("utf8");
707
+ const respond = (body) => {
708
+ if (socket.destroyed)
709
+ return;
710
+ socket.end(`${JSON.stringify(body)}\n`);
711
+ };
712
+ socket.on("error", () => undefined);
713
+ socket.on("data", (chunk) => {
714
+ if (handled)
715
+ return;
716
+ buffer += chunk;
717
+ if (buffer.length > EPIC_SERVER_IPC_MAX_BYTES) {
718
+ handled = true;
719
+ respond({ ok: false, error: "request too large" });
720
+ return;
721
+ }
722
+ const nl = buffer.indexOf("\n");
723
+ if (nl === -1)
724
+ return;
725
+ handled = true;
726
+ let request = null;
727
+ try {
728
+ request = parseIpcRequest(JSON.parse(buffer.slice(0, nl)));
729
+ }
730
+ catch {
731
+ request = null;
732
+ }
733
+ if (request === null) {
734
+ respond({ ok: false, error: "malformed request" });
735
+ return;
736
+ }
737
+ void this.dispatch(request, respond, socket);
738
+ });
739
+ }
740
+ async dispatch(request, respond, socket) {
741
+ if (this.stopping && request.op !== "status") {
742
+ respond({ ok: false, error: "the epic server is stopping" });
743
+ return;
744
+ }
745
+ switch (request.op) {
746
+ case "status": {
747
+ // The driver's cursor acknowledges what it has tallied; only the helper writes the journal.
748
+ if (request.since !== undefined)
749
+ await this.options.journal.acknowledge(request.since);
750
+ const journal = await this.options.journal.read(request.since ?? 0);
751
+ respond({ ok: true, ...this.statusBody(), journal });
752
+ return;
753
+ }
754
+ case "shutdown":
755
+ if (request.expect_epic_run_id !== this.options.identity.epicRunId) {
756
+ respond({ ok: false, error: "the epic run id does not match this helper" });
757
+ return;
758
+ }
759
+ respond({ ok: true, stopping: true });
760
+ void this.shutdown("guarded_stop");
761
+ return;
762
+ case "release":
763
+ respond({ ok: true, ...(await this.release(request.lease)) });
764
+ return;
765
+ case "acquire": {
766
+ // The proven recipe sets the floor: a worker asking for less still waits the recipe's turn wait.
767
+ const waitMs = epicServerTurnWaitSeconds(request.wait_seconds, this.options.recipe) * 1000;
768
+ const entry = {
769
+ ticket: request.ticket,
770
+ head: request.head,
771
+ deadline: Date.now() + waitMs,
772
+ respond,
773
+ cancelled: false,
774
+ started: false,
775
+ };
776
+ // A disconnected client is cancelled and removed; it can never be granted later.
777
+ socket.once("close", () => {
778
+ entry.cancelled = true;
779
+ const at = this.queue.indexOf(entry);
780
+ if (at !== -1)
781
+ this.queue.splice(at, 1);
782
+ });
783
+ const timer = setTimeout(() => {
784
+ if (entry.cancelled || entry.started)
785
+ return;
786
+ entry.cancelled = true;
787
+ const at = this.queue.indexOf(entry);
788
+ if (at !== -1)
789
+ this.queue.splice(at, 1);
790
+ void this.options.journal.append("acquire_timed_out", { ticket: entry.ticket, reason: "wait_timeout" });
791
+ respond({ ok: false, outcome: "unavailable", reason: "wait_timeout" });
792
+ }, waitMs);
793
+ timer.unref?.();
794
+ socket.once("close", () => clearTimeout(timer));
795
+ this.queue.push(entry);
796
+ void this.processQueue();
797
+ return;
798
+ }
799
+ }
800
+ }
801
+ statusBody() {
802
+ return {
803
+ mode: "local",
804
+ url: epicServerLoopbackUrl(this.port),
805
+ served_sha: this.servedSha,
806
+ generation: this.generation,
807
+ lease: this.lease === null
808
+ ? null
809
+ : { ticket: this.lease.ticket, generation: this.lease.generation, expires_in_seconds: Math.max(0, Math.round((this.lease.expiresAt - Date.now()) / 1000)) },
810
+ queue_length: this.queue.length,
811
+ stopping: this.stopping !== null,
812
+ };
813
+ }
814
+ async release(handle) {
815
+ const lease = this.lease;
816
+ if (lease !== null && lease.handle === handle && Date.now() < lease.expiresAt && lease.generation === this.generation) {
817
+ clearTimeout(lease.timer);
818
+ this.lease = null;
819
+ this.rememberLease(handle, "retained");
820
+ await this.options.journal.append("turn_released", {
821
+ generation: lease.generation,
822
+ ticket: lease.ticket,
823
+ sha: lease.sha,
824
+ outcome: "retained",
825
+ reason: "released",
826
+ });
827
+ this.servedSha = null;
828
+ await this.endTurn();
829
+ await this.writeState();
830
+ void this.processQueue();
831
+ return { outcome: "retained", generation: lease.generation, served_sha: lease.sha };
832
+ }
833
+ // Never inspects or mutates a newer holder's lease.
834
+ return { outcome: "lost", reason: this.recentLeases.has(handle) && this.recentLeases.get(handle) === "retained" ? "already_released" : "fenced_or_expired" };
835
+ }
836
+ async processQueue() {
837
+ if (this.processing || this.stopping || this.lease !== null)
838
+ return;
839
+ const next = this.queue.find((e) => !e.cancelled && Date.now() < e.deadline);
840
+ if (next === undefined)
841
+ return;
842
+ this.processing = true;
843
+ try {
844
+ this.queue.splice(this.queue.indexOf(next), 1);
845
+ next.started = true;
846
+ // 1. Revoke the old turn and increment the generation.
847
+ this.generation += 1;
848
+ const generation = this.generation;
849
+ this.servedSha = null;
850
+ await this.writeState();
851
+ // 2-3. Stop the app and remove the previous turn's resources.
852
+ await this.endTurn();
853
+ // 4-7. Check out the exact head, prepare, provision, migrate, seed, start, ready.
854
+ // The rebuild has its own budget, the proven bound, not what is left of the queue wait.
855
+ const controller = new AbortController();
856
+ const timer = setTimeout(() => controller.abort(), epicServerTurnBuildSeconds(this.options.recipe) * 1000);
857
+ timer.unref?.();
858
+ let served;
859
+ try {
860
+ served = await runServingPipeline({ ...this.ctx, signal: controller.signal }, next.head, generation);
861
+ }
862
+ finally {
863
+ clearTimeout(timer);
864
+ }
865
+ if (this.stopping) {
866
+ this.turn = served.ok ? served.turn : served.partial;
867
+ return;
868
+ }
869
+ if (!served.ok) {
870
+ this.turn = served.partial;
871
+ await this.endTurn();
872
+ await this.writeState();
873
+ await this.options.journal.append("serving_failed", { generation, ticket: next.ticket, sha: next.head, reason: served.reason, outcome: "failed" });
874
+ if (!next.cancelled) {
875
+ next.cancelled = true;
876
+ next.respond({ ok: false, outcome: "unavailable", reason: served.reason === "cancelled" ? "build_timeout" : served.reason });
877
+ }
878
+ return;
879
+ }
880
+ this.turn = served.turn;
881
+ this.servedSha = served.turn.sha;
882
+ this.watchApp(served.turn);
883
+ await this.writeState();
884
+ if (next.cancelled) {
885
+ // The requester is gone: no orphaned lease. The app keeps serving with no holder.
886
+ return;
887
+ }
888
+ // 8. Grant. The lease clock starts now.
889
+ const handle = `esl1_${generation}_${this.options.deps.randomHex(16)}`;
890
+ const leaseMs = this.options.recipe.timing.lease_seconds * 1000;
891
+ const lease = {
892
+ handle,
893
+ ticket: next.ticket,
894
+ sha: next.head,
895
+ generation,
896
+ expiresAt: Date.now() + leaseMs,
897
+ timer: setTimeout(() => void this.expireLease(lease), leaseMs),
898
+ };
899
+ lease.timer.unref?.();
900
+ this.lease = lease;
901
+ next.cancelled = true;
902
+ await this.options.journal.append("turn_granted", { generation, ticket: next.ticket, sha: next.head, outcome: "ok" });
903
+ next.respond({
904
+ ok: true,
905
+ outcome: "granted",
906
+ url: epicServerLoopbackUrl(this.port),
907
+ served_sha: served.turn.sha,
908
+ generation,
909
+ login_file: served.turn.loginFile,
910
+ lease: handle,
911
+ lease_seconds: this.options.recipe.timing.lease_seconds,
912
+ });
913
+ }
914
+ finally {
915
+ this.processing = false;
916
+ if (!this.stopping && this.lease === null)
917
+ void this.processQueue();
918
+ }
919
+ }
920
+ async expireLease(lease) {
921
+ if (this.lease !== lease || this.stopping)
922
+ return;
923
+ await this.options.journal.append("lease_expired", { generation: lease.generation, ticket: lease.ticket, reason: "expired", outcome: "lost" });
924
+ this.loseLease(lease, "expired");
925
+ this.servedSha = null;
926
+ await this.endTurn();
927
+ await this.writeState();
928
+ void this.processQueue();
929
+ }
930
+ /** The one idempotent cleanup path for every exit. */
931
+ shutdown(reason) {
932
+ if (this.stopping)
933
+ return this.stopping;
934
+ this.stopping = (async () => {
935
+ const { deps, paths, identity } = this.options;
936
+ for (const t of this.timers)
937
+ clearTimeout(t);
938
+ if (this.pollTimer !== null)
939
+ clearTimeout(this.pollTimer);
940
+ for (const entry of this.queue.splice(0)) {
941
+ if (!entry.cancelled) {
942
+ entry.cancelled = true;
943
+ entry.respond({ ok: false, outcome: "unavailable", reason: "helper_stopping" });
944
+ }
945
+ }
946
+ if (this.lease !== null)
947
+ this.loseLease(this.lease, "helper_replaced");
948
+ // Wait (bounded) for an in-flight turn to settle so its resources are known.
949
+ const settleBy = Date.now() + this.options.recipe.timing.cleanup_seconds * 1000;
950
+ while (this.processing && Date.now() < settleBy)
951
+ await deps.sleep(100);
952
+ const clean = await this.endTurn();
953
+ await removeServingWorktree(paths, identity.repoRoot, deps);
954
+ // A client that connected and never finished its request must not hold
955
+ // the close open forever: every remaining connection is dropped.
956
+ const closed = new Promise((resolve) => (this.server ? this.server.close(() => resolve()) : resolve()));
957
+ for (const s of this.sockets)
958
+ s.destroy();
959
+ await closed;
960
+ await deps.fs.rm(paths.socketDir, { recursive: true, force: true }).catch(() => undefined);
961
+ await removeFileQuietly(deps.fs, paths.state);
962
+ await removeFileQuietly(deps.fs, paths.claim);
963
+ if (clean)
964
+ await removeFileQuietly(deps.fs, paths.ownership);
965
+ await this.options.journal.append("helper_stopped", { reason: clean ? reason : "cleanup_incomplete", outcome: clean ? "ok" : "failed" });
966
+ this.options.onExit(clean ? 0 : 1);
967
+ })();
968
+ return this.stopping;
969
+ }
970
+ }
971
+ function liveProbe(deps) {
972
+ return {
973
+ identity: async (pid) => {
974
+ const s = await readProcessStartTime(pid, deps.proc);
975
+ return s === null ? null : { startedAt: s };
976
+ },
977
+ };
978
+ }
979
+ /** Wait (bounded) until the run's live state names a live helper. */
980
+ async function awaitLiveState(paths, runId, deadline, deps) {
981
+ while (Date.now() < deadline) {
982
+ const live = await readEpicServerLiveState(paths.state, runId, { fs: deps.fs, probe: liveProbe(deps), budgetMs: 5_000 });
983
+ if (live.state === "live")
984
+ return live.value;
985
+ await deps.sleep(250);
986
+ }
987
+ return null;
988
+ }
989
+ /**
990
+ * Start the run's one helper, or attach to the matching live one. Never launches
991
+ * a second helper: the launch is gated by an exclusive singleton claim, and a
992
+ * concurrent start waits (bounded) for the claim holder's handshake instead.
993
+ */
994
+ export async function startEpicServerHelper(input, deps) {
995
+ const rt = deps.runtime;
996
+ const { paths } = input;
997
+ if (!isOwnershipInspectionSupported(rt.proc.platform))
998
+ return { ok: false, reason: "inspection_unsupported" };
999
+ const recipe = await readRecipe(paths, rt.fs);
1000
+ if (recipe === null)
1001
+ return { ok: false, reason: "recipe_invalid" };
1002
+ if (!proofCoversStart(await readProof(paths, rt.fs), recipe, input.epicHead))
1003
+ return { ok: false, reason: "not_proven" };
1004
+ const deadline = Date.now() + recipe.timing.start_seconds * 1000;
1005
+ const live = await readEpicServerLiveState(paths.state, input.runId, { fs: rt.fs, probe: liveProbe(rt) });
1006
+ if (live.state === "live")
1007
+ return { ok: true, attached: true, state: live.value };
1008
+ // A claim whose holder is still alive means another start is in flight.
1009
+ const rawClaim = await readPrivateJson(rt.fs, paths.claim);
1010
+ const claim = validateEpicServerClaim(rawClaim);
1011
+ if (claim !== null) {
1012
+ const holder = await readProcessStartTime(claim.helper_pid, rt.proc);
1013
+ if (holder !== null && holder === claim.helper_started_at) {
1014
+ const attached = await awaitLiveState(paths, input.runId, deadline, rt);
1015
+ return attached !== null ? { ok: true, attached: true, state: attached } : { ok: false, reason: "busy" };
1016
+ }
1017
+ }
1018
+ // The previous holder is gone: reclaim what it left, then take the claim.
1019
+ const recovery = await recoverAbandonedResources(paths, rt);
1020
+ if (recovery === "owner_live") {
1021
+ const attached = await awaitLiveState(paths, input.runId, deadline, rt);
1022
+ return attached !== null ? { ok: true, attached: true, state: attached } : { ok: false, reason: "busy" };
1023
+ }
1024
+ if (recovery === "retained")
1025
+ return { ok: false, reason: "recovery_incomplete" };
1026
+ // Remove only the stale claim read above. A claim a concurrent start has
1027
+ // taken since then is someone else's and must never be deleted here, or two
1028
+ // starts could each launch a helper.
1029
+ const currentClaim = await readPrivateJson(rt.fs, paths.claim);
1030
+ if (rawClaim !== null && currentClaim !== null && JSON.stringify(currentClaim) === JSON.stringify(rawClaim)) {
1031
+ await removeFileQuietly(rt.fs, paths.claim);
1032
+ }
1033
+ const nonce = rt.randomHex(32);
1034
+ const selfStart = (await readProcessStartTime(rt.proc.selfPid, rt.proc)) ?? "unknown";
1035
+ const claimed = await tryCreateClaim(rt.fs, paths.claim, {
1036
+ epic_run_id: input.runId,
1037
+ helper_pid: rt.proc.selfPid,
1038
+ helper_started_at: selfStart,
1039
+ instance_nonce: nonce,
1040
+ created_at: rt.now().toISOString(),
1041
+ });
1042
+ if (!claimed) {
1043
+ const attached = await awaitLiveState(paths, input.runId, deadline, rt);
1044
+ return attached !== null ? { ok: true, attached: true, state: attached } : { ok: false, reason: "busy" };
1045
+ }
1046
+ const env = {};
1047
+ for (const [k, v] of Object.entries(rt.helperEnv))
1048
+ if (typeof v === "string")
1049
+ env[k] = v;
1050
+ // The helper carries its own instance tag, never the executor's job tag.
1051
+ delete env.BRIDGE_EXECUTOR_JOB_TAG;
1052
+ delete env.BRIDGE_EXECUTOR_JOB_ID;
1053
+ env[EPIC_SERVER_INSTANCE_TAG_ENV] = nonce;
1054
+ const pid = deps.launchHelper([
1055
+ "--epic",
1056
+ input.epicKey,
1057
+ "--epic-run-id",
1058
+ input.runId,
1059
+ "--head",
1060
+ input.epicHead,
1061
+ "--repo-name",
1062
+ input.repoName,
1063
+ "--repo-root",
1064
+ input.repoRoot,
1065
+ ], env);
1066
+ if (pid === null) {
1067
+ await removeFileQuietly(rt.fs, paths.claim);
1068
+ return { ok: false, reason: "launch_failed" };
1069
+ }
1070
+ const state = await awaitLiveState(paths, input.runId, deadline, rt);
1071
+ if (state === null || state.helper_pid !== pid || state.instance_nonce !== nonce) {
1072
+ // No handshake in time: stop only the process we launched, by verified identity.
1073
+ const started = await readProcessStartTime(pid, rt.proc);
1074
+ if (started !== null)
1075
+ await stopOwnedProcessGroup({ pid, started_at: started }, nonce, 5_000, rt.proc);
1076
+ await recoverAbandonedResources(paths, rt);
1077
+ await removeFileQuietly(rt.fs, paths.claim);
1078
+ return { ok: false, reason: "handshake_timeout" };
1079
+ }
1080
+ // Re-point the claim at the helper itself.
1081
+ await writePrivateFileAtomic(rt.fs, paths.claim, `${JSON.stringify({ epic_run_id: input.runId, helper_pid: pid, helper_started_at: state.helper_started_at, instance_nonce: nonce, created_at: rt.now().toISOString() })}\n`).catch(() => undefined);
1082
+ return { ok: true, attached: false, state };
1083
+ }
1084
+ /**
1085
+ * Guarded stop. Only a helper whose live state names THIS run, and whose pid,
1086
+ * start time, and instance nonce match, is asked to shut down (over its private
1087
+ * IPC endpoint), and is signalled only if it does not exit in time. Nothing is
1088
+ * ever stopped by port. With no live helper, abandoned resources are reclaimed.
1089
+ */
1090
+ export async function stopEpicServerHelper(input, rt, timeoutMs = 30_000) {
1091
+ const { paths } = input;
1092
+ const live = await readEpicServerLiveState(paths.state, input.runId, { fs: rt.fs, probe: liveProbe(rt) });
1093
+ if (live.state !== "live") {
1094
+ const recovery = await recoverAbandonedResources(paths, rt);
1095
+ if (recovery === "reclaimed")
1096
+ return { ok: true, outcome: "reclaimed" };
1097
+ if (recovery === "retained")
1098
+ return { ok: false, reason: "recovery_incomplete" };
1099
+ if (recovery === "owner_live")
1100
+ return { ok: false, reason: "ownership_mismatch" };
1101
+ return { ok: true, outcome: "not_running" };
1102
+ }
1103
+ const state = live.value;
1104
+ const verdict = await verifyOwnedProcess({ pid: state.helper_pid, started_at: state.helper_started_at }, state.instance_nonce, rt.proc);
1105
+ if (verdict !== "match")
1106
+ return { ok: false, reason: "ownership_mismatch" };
1107
+ await sendIpcRequest(state.socket_path, { op: "shutdown", expect_epic_run_id: input.runId }, 5_000);
1108
+ const deadline = Date.now() + timeoutMs;
1109
+ while (Date.now() < deadline) {
1110
+ const now = await readProcessStartTime(state.helper_pid, rt.proc);
1111
+ if (now === null || now !== state.helper_started_at) {
1112
+ const recovery = await recoverAbandonedResources(paths, rt);
1113
+ return recovery === "retained" ? { ok: false, reason: "recovery_incomplete" } : { ok: true, outcome: "stopped" };
1114
+ }
1115
+ await rt.sleep(250);
1116
+ }
1117
+ const stopped = await stopOwnedProcessGroup({ pid: state.helper_pid, started_at: state.helper_started_at }, state.instance_nonce, 5_000, rt.proc);
1118
+ if (stopped === "refused")
1119
+ return { ok: false, reason: "stop_timeout" };
1120
+ const recovery = await recoverAbandonedResources(paths, rt);
1121
+ return recovery === "retained" ? { ok: false, reason: "recovery_incomplete" } : { ok: true, outcome: "stopped" };
1122
+ }
1123
+ // ---------------------------------------------------------------------------
1124
+ // Production seams
1125
+ // ---------------------------------------------------------------------------
1126
+ function runGit(args, timeoutMs) {
1127
+ return new Promise((resolve) => {
1128
+ execFile("git", ["-c", "core.hooksPath=/dev/null", ...args], { timeout: Math.max(1, timeoutMs), maxBuffer: 1024 * 1024, env: { PATH: process.env.PATH ?? "/usr/bin:/bin", HOME: process.env.HOME ?? "", GIT_TERMINAL_PROMPT: "0" } }, (err, stdout) => {
1129
+ const code = err ? (typeof err.code === "number" ? err.code : null) : 0;
1130
+ resolve({ code, stdout: String(stdout ?? "") });
1131
+ });
1132
+ });
1133
+ }
1134
+ export function createDefaultGitSeam() {
1135
+ return {
1136
+ ensureCommit: async (repoRoot, sha, timeoutMs) => {
1137
+ if (!isFullCommitShaLike(sha))
1138
+ return false;
1139
+ const present = await runGit(["-C", repoRoot, "cat-file", "-e", `${sha}^{commit}`], 10_000);
1140
+ if (present.code === 0)
1141
+ return true;
1142
+ const fetched = await runGit(["-C", repoRoot, "fetch", "--no-tags", "--quiet", "origin", sha], timeoutMs);
1143
+ if (fetched.code !== 0)
1144
+ return false;
1145
+ return (await runGit(["-C", repoRoot, "cat-file", "-e", `${sha}^{commit}`], 10_000)).code === 0;
1146
+ },
1147
+ addDetachedWorktree: async (repoRoot, worktreePath, sha, timeoutMs) => (await runGit(["-C", repoRoot, "worktree", "add", "--detach", "--quiet", worktreePath, sha], timeoutMs)).code === 0,
1148
+ headOf: async (worktreePath, timeoutMs) => {
1149
+ const r = await runGit(["-C", worktreePath, "rev-parse", "HEAD"], timeoutMs);
1150
+ const sha = r.stdout.trim();
1151
+ return r.code === 0 && isFullCommitShaLike(sha) ? sha : null;
1152
+ },
1153
+ removeWorktree: async (repoRoot, worktreePath, timeoutMs) => {
1154
+ await runGit(["-C", repoRoot, "worktree", "remove", "--force", worktreePath], timeoutMs);
1155
+ await runGit(["-C", repoRoot, "worktree", "prune"], timeoutMs);
1156
+ },
1157
+ };
1158
+ }
1159
+ export function createDefaultHttpProbe() {
1160
+ return {
1161
+ get: (url, timeoutMs) => new Promise((resolve) => {
1162
+ let parsed;
1163
+ try {
1164
+ parsed = new URL(url);
1165
+ }
1166
+ catch {
1167
+ resolve(null);
1168
+ return;
1169
+ }
1170
+ if (parsed.hostname !== "127.0.0.1" || parsed.protocol !== "http:") {
1171
+ resolve(null);
1172
+ return;
1173
+ }
1174
+ const req = http.get(url, { timeout: Math.max(1, timeoutMs) }, (res) => {
1175
+ const location = typeof res.headers.location === "string" ? res.headers.location : null;
1176
+ res.resume();
1177
+ resolve({ status: res.statusCode ?? 0, location });
1178
+ });
1179
+ req.on("timeout", () => {
1180
+ req.destroy();
1181
+ resolve(null);
1182
+ });
1183
+ req.on("error", () => resolve(null));
1184
+ }),
1185
+ };
1186
+ }
1187
+ /** A free loopback port, never 8000 (up to a few attempts). */
1188
+ export async function allocateLoopbackPort() {
1189
+ for (let attempt = 0; attempt < 8; attempt++) {
1190
+ const port = await new Promise((resolve) => {
1191
+ const server = net.createServer();
1192
+ server.once("error", () => resolve(null));
1193
+ server.listen(0, "127.0.0.1", () => {
1194
+ const address = server.address();
1195
+ const value = typeof address === "object" && address !== null ? address.port : null;
1196
+ server.close(() => resolve(value));
1197
+ });
1198
+ });
1199
+ if (port !== null && port !== 8000 && port > 1024)
1200
+ return port;
1201
+ }
1202
+ return null;
1203
+ }
1204
+ /** Random lowercase hex of `bytes` bytes. */
1205
+ export function defaultRandomHex(bytes) {
1206
+ return randomBytes(bytes).toString("hex");
1207
+ }