@bridge_gpt/mcp-server 0.2.74 → 0.2.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/prompt.js +9 -21
  3. package/build/agents.generated.js +2 -2
  4. package/build/authored-plan.js +542 -0
  5. package/build/bridge-permissions.js +8 -0
  6. package/build/commands.generated.js +5 -5
  7. package/build/conductor/bridge-api-client.js +666 -46
  8. package/build/conductor/epic-implementer-cli.js +337 -93
  9. package/build/conductor/gate-discovery.js +209 -9
  10. package/build/conductor/gate-settings-review.js +7 -11
  11. package/build/conductor/launch-plan.js +58 -12
  12. package/build/conductor/open-decision-phrases.js +50 -0
  13. package/build/conductor/prerequisite-inputs.js +181 -14
  14. package/build/connect-github-api.js +18 -0
  15. package/build/connect-github.js +35 -18
  16. package/build/docs.generated.js +2 -2
  17. package/build/drive-epic.js +387 -12
  18. package/build/epic-ci-workflow.js +3 -2
  19. package/build/epic-implementer-bin.js +152 -38
  20. package/build/epic-implementer-bundle-cli.js +61 -0
  21. package/build/epic-implementer-claude-hook-bin.js +1 -1
  22. package/build/epic-implementer-env.js +3 -4
  23. package/build/epic-integration-pr.js +5 -2
  24. package/build/executor/completion-contract.js +24 -1
  25. package/build/executor/gate-qualification-job.js +193 -23
  26. package/build/executor/gate-qualification-tests-ran.js +232 -0
  27. package/build/executor/job-runner.js +9 -722
  28. package/build/executor/job-type-wrappers.js +734 -0
  29. package/build/executor/preflight.js +6 -2
  30. package/build/executor/process-containment.js +8 -1
  31. package/build/executor/required-verification.js +28 -2
  32. package/build/executor/runner.js +4 -1
  33. package/build/executor/types.js +9 -0
  34. package/build/executor/worker-database.js +6 -1
  35. package/build/executor/worker-guard-hook.js +24 -2
  36. package/build/generated/ticket-status.js +20 -0
  37. package/build/index.js +391 -257
  38. package/build/install-bridge-conductor-answers.js +28 -1
  39. package/build/install-bridge-conductor-apply.js +11 -3
  40. package/build/install-bridge-conductor-assessment.js +114 -12
  41. package/build/install-bridge-conductor-compact.js +2 -0
  42. package/build/install-bridge-conductor-gate.js +257 -80
  43. package/build/install-bridge-conductor-setup.js +4 -4
  44. package/build/install-bridge-conductor-trial-report.js +170 -0
  45. package/build/install-bridge-conductor.js +303 -31
  46. package/build/pipelines.generated.js +7 -7
  47. package/build/plan-generation.js +17 -0
  48. package/build/printed-remedy-commands.js +54 -0
  49. package/build/readme.generated.js +1 -1
  50. package/build/repository-toolchains.js +11 -5
  51. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  52. package/build/setup-epic.js +10 -1
  53. package/build/test-support/executor-source-files.js +1 -1
  54. package/build/v2-readiness-requirements.js +5 -1
  55. package/build/version.generated.js +3 -3
  56. package/build/worker-guard-hook-bin.js +2 -2
  57. package/docs/EPIC-IMPLEMENTER.md +4 -4
  58. package/docs/install/github-app.md +79 -92
  59. package/package.json +1 -1
  60. package/build/conductor/epic-reconcile.js +0 -603
  61. package/build/conductor/epic-runtime.js +0 -2020
  62. package/build/conductor/epic-state.js +0 -774
@@ -0,0 +1,734 @@
1
+ import { runHeartbeatLoop } from "./heartbeat.js";
2
+ import { secretFreeErrorMessage } from "./job-errors.js";
3
+ import { buildConductorMergeAccessForExecutorJob, buildMergeLocalDepsForJob, runExecutorMergeJob, MERGE_RETRYABLE, MERGE_FAILED, MERGE_ACCESS_UNAVAILABLE, MERGE_FLOW_ERROR, MERGE_FLOW_TIMEOUT, MERGE_NO_OUTCOME, } from "./merge-job.js";
4
+ import { createProductionCiRerunDeps, runCiRerunJob } from "./ci-rerun-job.js";
5
+ import { createProductionGateQualificationDeps, runGateQualificationJob, GATE_QUALIFICATION_FAILED, GATE_QUALIFICATION_INTERRUPTED, } from "./gate-qualification-job.js";
6
+ import { runProcessWithTimeout } from "./process.js";
7
+ import { buildSmokeResult, resolveJobTimeoutSeconds } from "./results.js";
8
+ import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
9
+ /**
10
+ * Thin job-type wrappers (`merge`, `smoke`, `ci_rerun`, `gate_qualification`),
11
+ * moved out of `job-runner.ts` unchanged (BAPI-1692). `job-runner.ts` re-exports
12
+ * every export of this module, so existing importers keep working.
13
+ *
14
+ * This module takes only type imports from `job-runner.ts` (erased at compile
15
+ * time), so there is no runtime import cycle. It holds no module-level state and
16
+ * contains no worker-spawn boundary.
17
+ *
18
+ * Shared helpers: `superviseProcess`, `terminalToRunResult`,
19
+ * `sendTerminalMutationWithAuthReport`, `createFlowProcess` and
20
+ * `toWireClassification` are ALSO used by the spawn path in `job-runner.ts`. They
21
+ * are not wrapper-only code; they live here so the wrappers need no value import
22
+ * from `job-runner.ts`.
23
+ */
24
+ /** Default runtime for the no-op smoke process (ms). */
25
+ export const DEFAULT_SMOKE_DURATION_MS = 100;
26
+ export function toWireClassification(c) {
27
+ return c;
28
+ }
29
+ /**
30
+ * Default merge dispatch: resolve Bridge API access, then run the deterministic
31
+ * merge. Exported for unit tests (access-resolution failure → retryable). The
32
+ * `controls.signal` (overall-timeout abort) is threaded into local merge deps
33
+ * without changing the local `gh` credential model.
34
+ */
35
+ export async function defaultRunMergeForClaimed(job, deps, options, controls) {
36
+ const accessResult = await buildConductorMergeAccessForExecutorJob({
37
+ env: deps.env,
38
+ cwd: deps.cwd,
39
+ homedir: deps.homedir,
40
+ platform: deps.platform,
41
+ readFile: deps.readFile,
42
+ stat: deps.stat,
43
+ });
44
+ if (!accessResult.ok) {
45
+ // Access resolution feeds only the executor's read-only CI re-poll; a missing
46
+ // or temporarily-unavailable Bridge API access is transient infrastructure, so
47
+ // it is RETRYABLE (BAPI-572). The local `gh` credential model is unchanged.
48
+ return {
49
+ ok: false,
50
+ failure: {
51
+ error_kind: MERGE_RETRYABLE,
52
+ error_message: accessResult.error,
53
+ classification: "crashed",
54
+ telemetry: { failure_reason_code: MERGE_ACCESS_UNAVAILABLE },
55
+ },
56
+ };
57
+ }
58
+ return runExecutorMergeJob(job, {
59
+ access: accessResult.access,
60
+ // Thread the overall-timeout abort signal into local merge deps WITHOUT
61
+ // changing the local `gh` credential model (the signal is not a credential).
62
+ // BAPI-1453: the same signal bounds the post-`gh_pr_view_failed` permission
63
+ // probe, so it can never outlive the merge flow's own timeout.
64
+ // BAPI-1461: resolved when the job runs, with the stored-entry fallback for
65
+ // an executor started in the person's own session. A durable-host service
66
+ // executor declared itself with --scrub-inherited-github-credentials and
67
+ // never reads a stored GitHub credential.
68
+ localMergeDeps: await buildMergeLocalDepsForJob(job, deps, { allowStoredEntry: options.scrubInheritedGithubCredentials !== true }, controls?.signal),
69
+ // BAPI-951: the executor's own configured base — resolveExecutorJobBaseBranch
70
+ // (called inside runExecutorMergeJob) resolves the CHILD PR's base from the
71
+ // job's persisted run base, falling back to this value for a legacy job.
72
+ repositoryBaseBranch: options.baseBranch,
73
+ epicIntegrationAdvisoryLog: deps.errorLog,
74
+ diagnosticLog: deps.errorLog,
75
+ cwd: deps.cwd,
76
+ });
77
+ }
78
+ /** An in-memory owned process for the no-op `smoke` acceptance job. */
79
+ export function createNoopProcess(deps, durationMs, message) {
80
+ let killResolve = null;
81
+ const killed = new Promise((res) => {
82
+ killResolve = res;
83
+ });
84
+ let done = false;
85
+ async function* stdout() {
86
+ if (message)
87
+ yield message;
88
+ }
89
+ return {
90
+ pid: undefined,
91
+ stdout: stdout(),
92
+ stderr: null,
93
+ async wait() {
94
+ const natural = deps
95
+ .sleep(durationMs)
96
+ .then(() => ({ exitCode: 0, signal: null }));
97
+ const result = await Promise.race([natural, killed]);
98
+ done = true;
99
+ return result;
100
+ },
101
+ kill(signal) {
102
+ if (done)
103
+ return;
104
+ killResolve?.({ exitCode: null, signal });
105
+ },
106
+ };
107
+ }
108
+ /**
109
+ * Run the process and heartbeat loop concurrently; return the process outcome.
110
+ *
111
+ * BAPI-731: `serverStopRequested` is carried ALONGSIDE the process
112
+ * classification rather than folded into it. When the server cancels a run the
113
+ * worker is SIGKILLed, so its raw classification would read as `killed` — which
114
+ * the caller would otherwise report as a worker fault. Keeping the flag separate
115
+ * is what lets the caller report a deliberate server cancellation distinctly.
116
+ */
117
+ export async function superviseProcess(params) {
118
+ const isDoneRef = { value: false };
119
+ const heartbeatStop = new AbortController();
120
+ const heartbeatDeps = params.cancelHeartbeatSleepOnExit ? { ...params.deps, sleep: (ms) => new Promise((resolve) => {
121
+ if (heartbeatStop.signal.aborted) {
122
+ resolve();
123
+ return;
124
+ }
125
+ let timer;
126
+ const done = () => { params.deps.clearTimer(timer); heartbeatStop.signal.removeEventListener("abort", done); resolve(); };
127
+ timer = params.deps.setTimer(done, ms);
128
+ heartbeatStop.signal.addEventListener("abort", done, { once: true });
129
+ }) } : params.deps;
130
+ const hb = runHeartbeatLoop({
131
+ job: params.job,
132
+ httpClient: params.httpClient,
133
+ options: params.options,
134
+ deps: heartbeatDeps,
135
+ ownership: params.ownership,
136
+ proc: params.proc,
137
+ observation: params.observation,
138
+ collectTelemetry: params.collectTelemetry,
139
+ collectRemoteMarker: params.collectRemoteMarker,
140
+ isDone: () => isDoneRef.value,
141
+ });
142
+ const mcpSurface = params.mcpSurface;
143
+ const result = await runProcessWithTimeout(params.proc, params.timeoutSeconds, params.deps, {
144
+ termGraceMs: params.options.termGraceMs,
145
+ ...(params.terminationController
146
+ ? { terminationController: params.terminationController }
147
+ : {}),
148
+ onStdout: (chunk) => {
149
+ params.observation.recordStdout(chunk);
150
+ params.onStdoutObserved?.(chunk);
151
+ },
152
+ ...(mcpSurface
153
+ ? {
154
+ onStdoutTerminationCheck: (chunk) => {
155
+ mcpSurface.observeStdout(chunk);
156
+ return mcpSurface.shouldTerminate();
157
+ },
158
+ }
159
+ : {}),
160
+ });
161
+ isDoneRef.value = true;
162
+ heartbeatStop.abort();
163
+ const loopOutcome = await hb;
164
+ if (params.recordProcessExit !== false)
165
+ params.observation.setExitCode(result.exitCode);
166
+ if (loopOutcome.kind === "auth_fatal") {
167
+ // BAPI-1021 (AC-5): notify the runner immediately with ONLY the bounded
168
+ // identifiers — never carried onto `result` itself, so the process's own
169
+ // classification/completion handling is unaffected and the job continues
170
+ // to drain normally.
171
+ params.control?.reportAuthFatal?.({
172
+ jobId: params.job.id,
173
+ repoName: params.job.repo_name,
174
+ category: "heartbeat",
175
+ httpStatus: loopOutcome.httpStatus,
176
+ });
177
+ }
178
+ return loopOutcome.kind === "server_stop"
179
+ ? { ...result, serverStopRequested: true }
180
+ : result;
181
+ }
182
+ export function terminalToRunResult(terminal, successStatus) {
183
+ switch (terminal.outcome) {
184
+ case "success":
185
+ return { status: successStatus };
186
+ case "invalid_job_result":
187
+ return { status: "failed", reason: "invalid_job_result" };
188
+ case "stale_claim":
189
+ return { status: "abandoned", reason: "stale_claim" };
190
+ case "abandoned":
191
+ return { status: "abandoned", reason: "deadman" };
192
+ case "skipped":
193
+ return { status: "abandoned", reason: "already_abandoned" };
194
+ case "auth_fatal":
195
+ // BAPI-1021 (AC-5): a halted authentication/access condition, not an
196
+ // ordinary job failure or a lost/stale claim — `reportAuthFatal` (called
197
+ // by the wrapper below, before this mapping runs) is what actually
198
+ // notifies the runner.
199
+ return { status: "abandoned", reason: "auth_fatal" };
200
+ case "completion_evidence_refused":
201
+ // BAPI-1590: the wrapper below hands this outcome to the caller only when
202
+ // that caller opted into the immediate `/fail` fallback, and that caller
203
+ // handles it before mapping. Reaching here means it did not, so keep the
204
+ // historical reading of a refused `/complete`: a lost claim.
205
+ return { status: "abandoned", reason: "stale_claim" };
206
+ }
207
+ }
208
+ /**
209
+ * BAPI-1021 (AC-5): send a terminal mutation via
210
+ * {@link sendTerminalMutationWithRetry}, and — on an `auth_fatal` outcome —
211
+ * notify the runner exactly once via `control.reportAuthFatal`, carrying ONLY
212
+ * the job ID, repository, operation category, and HTTP status. Every other
213
+ * outcome passes through completely unchanged.
214
+ */
215
+ export async function sendTerminalMutationWithAuthReport(params, job, control) {
216
+ const { completionEvidenceFallback, ...sendParams } = params;
217
+ const terminal = await sendTerminalMutationWithRetry(sendParams);
218
+ if (terminal.outcome === "completion_evidence_refused" && completionEvidenceFallback !== true) {
219
+ params.ownership.abandoned = true;
220
+ params.ownership.abandonReason = "stale_claim";
221
+ return { outcome: "stale_claim" };
222
+ }
223
+ if (terminal.outcome === "auth_fatal") {
224
+ const notice = {
225
+ jobId: job.id,
226
+ repoName: job.repo_name,
227
+ category: params.kind,
228
+ httpStatus: terminal.httpStatus,
229
+ };
230
+ control?.reportAuthFatal?.(notice);
231
+ }
232
+ return terminal;
233
+ }
234
+ /**
235
+ * Bound on waiting for a killed `gate_qualification` body to finish its own
236
+ * teardown (terminating a running command, removing the detached checkout)
237
+ * before the terminal report is sent.
238
+ */
239
+ export const GATE_QUALIFICATION_SETTLE_MAX_MS = 180_000;
240
+ /**
241
+ * Run a deterministic `gate_qualification` job (BAPI-1391).
242
+ *
243
+ * The same lifecycle as {@link runCiRerunExecutorJob}: the payload timeout is
244
+ * resolved first, the body runs as a flow under {@link superviseProcess} (the
245
+ * one ownership, heartbeat, dead-man, and timeout protocol), and every terminal
246
+ * report goes through {@link sendTerminalMutationWithAuthReport}.
247
+ *
248
+ * The completion carries only the bounded result envelope from
249
+ * `gate-qualification-job.ts`. An inability goes to `/fail` with a closed
250
+ * error kind and fixed text; command output never reaches either.
251
+ */
252
+ export async function runGateQualificationExecutorJob(job, httpClient, options, deps, ownership, observation, seams, control) {
253
+ const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
254
+ if (!timeout.ok) {
255
+ await httpClient.fail(job, {
256
+ error_kind: "ContractError.Timeout",
257
+ error_message: timeout.error,
258
+ classification: "crashed",
259
+ });
260
+ return { status: "failed", reason: "timeout_contract" };
261
+ }
262
+ const timeoutSeconds = timeout.timeoutSeconds;
263
+ const runGateQualification = seams.runGateQualification ??
264
+ ((claimed, input) => runGateQualificationJob(claimed, input, createProductionGateQualificationDeps({
265
+ deps,
266
+ options,
267
+ registerLive: (controller) => control?.liveWorkers.register(controller),
268
+ ownershipHeld: () => !ownership.abandoned,
269
+ })));
270
+ const flow = createFlowProcess((signal) => runGateQualification(job, { timeoutSeconds, signal }), (result) => result.ok);
271
+ const procResult = await superviseProcess({
272
+ job,
273
+ httpClient,
274
+ options,
275
+ deps,
276
+ ownership,
277
+ observation,
278
+ proc: flow.proc,
279
+ timeoutSeconds,
280
+ collectTelemetry: async () => ({}),
281
+ control,
282
+ });
283
+ // A killed flow keeps running until its own `finally` has terminated any
284
+ // command and removed the detached checkout. Wait for that, bounded, so the
285
+ // terminal report never races the teardown of a checkout it describes.
286
+ let settleTimer;
287
+ try {
288
+ await Promise.race([
289
+ flow.settled,
290
+ new Promise((resolve) => {
291
+ settleTimer = deps.setTimer(resolve, GATE_QUALIFICATION_SETTLE_MAX_MS);
292
+ }),
293
+ ]);
294
+ }
295
+ finally {
296
+ if (settleTimer !== undefined)
297
+ deps.clearTimer(settleTimer);
298
+ }
299
+ if (ownership.abandoned) {
300
+ return { status: "abandoned", reason: ownership.abandonReason };
301
+ }
302
+ const sendFail = async (errorKind, message, classification) => {
303
+ const terminal = await sendTerminalMutationWithAuthReport({
304
+ kind: "fail",
305
+ send: () => httpClient.fail(job, {
306
+ error_kind: errorKind,
307
+ error_message: message,
308
+ classification,
309
+ telemetry: observation.snapshot(),
310
+ }),
311
+ deps,
312
+ options,
313
+ ownership,
314
+ log: deps.log,
315
+ }, job, control);
316
+ return terminalToRunResult(terminal, "failed");
317
+ };
318
+ if (procResult.classification === "timeout") {
319
+ return sendFail(GATE_QUALIFICATION_FAILED, "gate_qualification exceeded its job timeout", "timeout");
320
+ }
321
+ const outcome = flow.getOutcome();
322
+ if (outcome === undefined) {
323
+ // Killed without a timeout (a server stop) — the commands were cut short —
324
+ // or the body threw, which it is built never to do.
325
+ return procResult.serverStopRequested
326
+ ? sendFail(GATE_QUALIFICATION_INTERRUPTED, "gate qualification was stopped before it finished", "killed")
327
+ : sendFail(GATE_QUALIFICATION_FAILED, "gate_qualification completed without an outcome", "crashed");
328
+ }
329
+ if (outcome.ok) {
330
+ const completion = {
331
+ job_type: "gate_qualification",
332
+ exit_code: 0,
333
+ classification: "clean_exit",
334
+ // The bounded result envelope, verbatim. The backend model is
335
+ // `extra="forbid"` and recomputes the outcome against the STORED payload.
336
+ result: outcome.result,
337
+ telemetry: observation.snapshot(),
338
+ };
339
+ const terminal = await sendTerminalMutationWithAuthReport({
340
+ kind: "complete",
341
+ send: () => httpClient.complete(job, completion),
342
+ deps,
343
+ options,
344
+ ownership,
345
+ log: deps.log,
346
+ }, job, control);
347
+ return terminalToRunResult(terminal, "completed");
348
+ }
349
+ // An inability: a closed error kind and fixed text, never command output.
350
+ return sendFail(outcome.failure.errorKind, outcome.failure.message, "crashed");
351
+ }
352
+ /**
353
+ * Run a deterministic `ci_rerun` job (BAPI-1160).
354
+ *
355
+ * Supervised through the SAME ownership, heartbeat, dead-man, and timeout
356
+ * protocol as {@link runMergeJob} — via {@link createFlowProcess} — so a
357
+ * deterministic job is not a second, weaker lifecycle. The body itself spawns no
358
+ * subprocess of its own beyond the bounded `gh` invocations inside
359
+ * `ci-rerun-job.ts`, and there is NO fallback to a worker on failure.
360
+ *
361
+ * The completion carries only the job's fact envelope. It names no gate,
362
+ * requests no transition, and asserts no verdict: the reconciler re-observes the
363
+ * head independently and remains the sole transition authority (R14 rule 3).
364
+ */
365
+ export async function runCiRerunExecutorJob(job, httpClient, options, deps, ownership, observation, seams, control) {
366
+ // Resolve + enforce payload.timeout_seconds BEFORE any provider work, exactly
367
+ // as the merge branch does.
368
+ const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
369
+ if (!timeout.ok) {
370
+ await httpClient.fail(job, {
371
+ error_kind: "ContractError.Timeout",
372
+ error_message: timeout.error,
373
+ classification: "crashed",
374
+ });
375
+ return { status: "failed", reason: "timeout_contract" };
376
+ }
377
+ const runCiRerun = seams.runCiRerun ??
378
+ ((payload) => runCiRerunJob(payload, createProductionCiRerunDeps()));
379
+ const flow = createFlowProcess(() => runCiRerun(job.payload), (result) => result.ok);
380
+ const procResult = await superviseProcess({
381
+ job,
382
+ httpClient,
383
+ options,
384
+ deps,
385
+ ownership,
386
+ observation,
387
+ proc: flow.proc,
388
+ timeoutSeconds: timeout.timeoutSeconds,
389
+ collectTelemetry: async () => ({}),
390
+ control,
391
+ });
392
+ if (ownership.abandoned) {
393
+ return { status: "abandoned", reason: ownership.abandonReason };
394
+ }
395
+ if (procResult.classification === "timeout") {
396
+ const terminal = await sendTerminalMutationWithAuthReport({
397
+ kind: "fail",
398
+ send: () => httpClient.fail(job, {
399
+ error_kind: "CiRerunFailed",
400
+ error_message: "ci_rerun exceeded its job timeout",
401
+ classification: "timeout",
402
+ telemetry: observation.snapshot(),
403
+ }),
404
+ deps,
405
+ options,
406
+ ownership,
407
+ log: deps.log,
408
+ }, job, control);
409
+ return terminalToRunResult(terminal, "failed");
410
+ }
411
+ const outcome = flow.getOutcome();
412
+ if (outcome === undefined) {
413
+ const terminal = await sendTerminalMutationWithAuthReport({
414
+ kind: "fail",
415
+ send: () => httpClient.fail(job, {
416
+ error_kind: "CiRerunFailed",
417
+ error_message: "ci_rerun completed without an outcome",
418
+ classification: "crashed",
419
+ telemetry: observation.snapshot(),
420
+ }),
421
+ deps,
422
+ options,
423
+ ownership,
424
+ log: deps.log,
425
+ }, job, control);
426
+ return terminalToRunResult(terminal, "failed");
427
+ }
428
+ if (outcome.ok) {
429
+ const completion = {
430
+ job_type: "ci_rerun",
431
+ exit_code: 0,
432
+ classification: "clean_exit",
433
+ // The FACT ENVELOPE, verbatim. No gate, no transition, no verdict — the
434
+ // backend model is `extra="forbid"`, so anything else fails validation
435
+ // rather than being silently ignored.
436
+ result: outcome.result,
437
+ telemetry: observation.snapshot(),
438
+ };
439
+ const terminal = await sendTerminalMutationWithAuthReport({
440
+ kind: "complete",
441
+ send: () => httpClient.complete(job, completion),
442
+ deps,
443
+ options,
444
+ ownership,
445
+ log: deps.log,
446
+ }, job, control);
447
+ return terminalToRunResult(terminal, "completed");
448
+ }
449
+ // A refused or failed re-run. The reserved infrastructure attempt stays
450
+ // CONSUMED — see `ci-rerun-job.ts` — and the reason is a closed token, never
451
+ // provider text.
452
+ const terminal = await sendTerminalMutationWithAuthReport({
453
+ kind: "fail",
454
+ send: () => httpClient.fail(job, {
455
+ error_kind: outcome.failure.errorKind,
456
+ error_message: outcome.failure.reason,
457
+ classification: "crashed",
458
+ telemetry: observation.snapshot(),
459
+ }),
460
+ deps,
461
+ options,
462
+ ownership,
463
+ log: deps.log,
464
+ }, job, control);
465
+ return terminalToRunResult(terminal, "failed");
466
+ }
467
+ /**
468
+ * Adapt a `runMerge(...)` promise into an {@link OwnedChildProcess} so the merge
469
+ * flow is supervised by the SAME heartbeat/deadman/timeout path as spawn/smoke
470
+ * jobs even though it spawns no worker. `wait()` resolves when the merge outcome
471
+ * is available (exit_code 0 on `ok`, 1 otherwise); `kill()` aborts the internal
472
+ * {@link AbortController} (cancelling in-flight local `gh` work) and resolves the
473
+ * owned process as killed. The stored outcome/error let the runner map the
474
+ * supervised result to `/complete` or `/fail` afterwards (killed/timeout is read
475
+ * from the supervised `ProcessRunResult`/`ownership`, not from this adapter).
476
+ */
477
+ export function createMergeFlowProcess(startMerge) {
478
+ const flow = createFlowProcess(startMerge, (result) => result.ok);
479
+ return { proc: flow.proc, getOutcome: flow.getOutcome, getError: flow.getError };
480
+ }
481
+ /**
482
+ * The generic form of {@link createMergeFlowProcess} (BAPI-1152): adapt any
483
+ * in-process flow into an {@link OwnedChildProcess} so it is supervised by the
484
+ * SAME heartbeat/deadman/timeout path as a worker. `settled` resolves once the
485
+ * flow's own promise has settled — after a timeout or kill the supervised
486
+ * process resolves immediately, but the flow may still be finishing a bounded
487
+ * subprocess, and a caller that is about to reset the worktree must wait for it.
488
+ */
489
+ export function createFlowProcess(start, isOk) {
490
+ const controller = new AbortController();
491
+ let outcome;
492
+ let error;
493
+ let done = false;
494
+ let settleWait = () => { };
495
+ const waitPromise = new Promise((resolve) => {
496
+ settleWait = resolve;
497
+ });
498
+ // Start the flow immediately; capture its resolution/rejection.
499
+ const settled = start(controller.signal).then((result) => {
500
+ outcome = result;
501
+ if (!done) {
502
+ done = true;
503
+ settleWait({ exitCode: isOk(result) ? 0 : 1, signal: null });
504
+ }
505
+ }, (err) => {
506
+ error = err;
507
+ if (!done) {
508
+ done = true;
509
+ settleWait({ exitCode: 1, signal: null });
510
+ }
511
+ });
512
+ const proc = {
513
+ pid: undefined,
514
+ stdout: null,
515
+ stderr: null,
516
+ async wait() {
517
+ return waitPromise;
518
+ },
519
+ kill(signal) {
520
+ if (done)
521
+ return;
522
+ controller.abort();
523
+ done = true;
524
+ settleWait({ exitCode: null, signal });
525
+ },
526
+ };
527
+ return {
528
+ proc,
529
+ getOutcome: () => outcome,
530
+ getError: () => error,
531
+ settled,
532
+ };
533
+ }
534
+ /**
535
+ * Run a deterministic `merge` job: NO worktree ensured, NO worker spawned. Unlike
536
+ * the pre-BAPI-572 version, the merge flow now runs under the SHARED heartbeat/
537
+ * deadman/timeout supervision path (via {@link superviseProcess}) so a live merge
538
+ * heartbeats (the janitor never re-queues a healthy multi-minute merge) and the
539
+ * whole flow honors `payload.timeout_seconds`. A timeout is reported as a
540
+ * RETRYABLE failure and a late merge resolution after timeout/abandonment is
541
+ * ignored. The local merge executor's outcome otherwise drives `/complete`
542
+ * (success) or `/fail`; stale/retry/invalid terminal outcomes reuse T3a handling.
543
+ */
544
+ export async function runMergeJob(job, httpClient, options, deps, ownership, observation, seams, control) {
545
+ // Resolve + enforce payload.timeout_seconds BEFORE starting any merge work.
546
+ const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
547
+ if (!timeout.ok) {
548
+ await httpClient.fail(job, {
549
+ error_kind: "ContractError.Timeout",
550
+ error_message: timeout.error,
551
+ classification: "crashed",
552
+ });
553
+ return { status: "failed", reason: "timeout_contract" };
554
+ }
555
+ const timeoutSeconds = timeout.timeoutSeconds;
556
+ const runMerge = seams.runMerge ?? defaultRunMergeForClaimed;
557
+ const flow = createMergeFlowProcess((signal) => runMerge(job, deps, options, { signal }));
558
+ const procResult = await superviseProcess({
559
+ job,
560
+ httpClient,
561
+ options,
562
+ deps,
563
+ ownership,
564
+ observation,
565
+ proc: flow.proc,
566
+ timeoutSeconds,
567
+ collectTelemetry: async () => ({}),
568
+ control,
569
+ });
570
+ // Ownership abandonment (stale-claim / dead-man) wins: never send a terminal
571
+ // mutation for a claim we no longer own, and never process a late outcome.
572
+ if (ownership.abandoned) {
573
+ return { status: "abandoned", reason: ownership.abandonReason };
574
+ }
575
+ // Overall merge flow timed out: fail the active claim as RETRYABLE and ignore
576
+ // any later merge promise resolution (the abort has already been signalled).
577
+ if (procResult.classification === "timeout") {
578
+ const terminal = await sendTerminalMutationWithAuthReport({
579
+ kind: "fail",
580
+ send: () => httpClient.fail(job, {
581
+ error_kind: MERGE_RETRYABLE,
582
+ error_message: `merge flow timed out after ${timeoutSeconds} seconds`,
583
+ classification: "timeout",
584
+ telemetry: { failure_reason_code: MERGE_FLOW_TIMEOUT, ...observation.snapshot() },
585
+ }),
586
+ deps,
587
+ options,
588
+ ownership,
589
+ log: deps.log,
590
+ }, job, control);
591
+ return terminalToRunResult(terminal, "failed");
592
+ }
593
+ // A thrown error inside the merge flow maps to a bounded MergeFailed.
594
+ const flowError = flow.getError();
595
+ if (flowError !== undefined) {
596
+ const terminal = await sendTerminalMutationWithAuthReport({
597
+ kind: "fail",
598
+ send: () => httpClient.fail(job, {
599
+ error_kind: MERGE_FAILED,
600
+ error_message: secretFreeErrorMessage(flowError),
601
+ classification: "crashed",
602
+ telemetry: { failure_reason_code: MERGE_FLOW_ERROR, ...observation.snapshot() },
603
+ }),
604
+ deps,
605
+ options,
606
+ ownership,
607
+ log: deps.log,
608
+ }, job, control);
609
+ return terminalToRunResult(terminal, "failed");
610
+ }
611
+ const outcome = flow.getOutcome();
612
+ if (outcome === undefined) {
613
+ // Clean process result with no stored outcome — an internal invariant break;
614
+ // fail loud rather than silently reporting success.
615
+ const terminal = await sendTerminalMutationWithAuthReport({
616
+ kind: "fail",
617
+ send: () => httpClient.fail(job, {
618
+ error_kind: MERGE_FAILED,
619
+ error_message: "merge flow completed without an outcome",
620
+ classification: "crashed",
621
+ telemetry: { failure_reason_code: MERGE_NO_OUTCOME, ...observation.snapshot() },
622
+ }),
623
+ deps,
624
+ options,
625
+ ownership,
626
+ log: deps.log,
627
+ }, job, control);
628
+ return terminalToRunResult(terminal, "failed");
629
+ }
630
+ if (outcome.ok) {
631
+ const completion = {
632
+ job_type: "merge",
633
+ exit_code: 0,
634
+ classification: "clean_exit",
635
+ result: outcome.result,
636
+ telemetry: observation.snapshot(),
637
+ };
638
+ const terminal = await sendTerminalMutationWithAuthReport({
639
+ kind: "complete",
640
+ send: () => httpClient.complete(job, completion),
641
+ deps,
642
+ options,
643
+ ownership,
644
+ log: deps.log,
645
+ }, job, control);
646
+ return terminalToRunResult(terminal, "completed");
647
+ }
648
+ const terminal = await sendTerminalMutationWithAuthReport({
649
+ kind: "fail",
650
+ // BAPI-1453: MERGE the builder's telemetry with the snapshot rather than
651
+ // replacing it, so `failure_reason_code` survives. Observation state never
652
+ // carries a code, so the snapshot cannot overwrite it.
653
+ send: () => httpClient.fail(job, {
654
+ ...outcome.failure,
655
+ telemetry: { ...outcome.failure.telemetry, ...observation.snapshot() },
656
+ }),
657
+ deps,
658
+ options,
659
+ ownership,
660
+ log: deps.log,
661
+ }, job, control);
662
+ return terminalToRunResult(terminal, "failed");
663
+ }
664
+ /**
665
+ * BAPI-724 design note (deliberate, not an accidental AC-5 gap): `smoke` stays
666
+ * on this no-worktree, no-real-worker-LLM `createNoopProcess` path and does
667
+ * NOT receive MCP registration. The ratified requirement anchors MCP
668
+ * provisioning to "the executor's worktree-preparation path
669
+ * (`job-runner.ts`), alongside the existing deny-layer provisioning call"
670
+ * (which BAPI-781 moved behind the adapter's `provisionWorktreeDenyLayer` hook)
671
+ * — that call, like the new MCP provisioning call, exists ONLY inside
672
+ * `runSpawnJob`, which `smoke` never reaches (see `isSpawnJobType` /
673
+ * `job-types.ts`, and this module's own "no real worker LLM" framing of the
674
+ * acceptance spine). Converting smoke into a worktree-having, worker-spawning
675
+ * job to give it something to register MCP into would be a materially larger,
676
+ * unratified change to that architectural boundary, not a wiring task.
677
+ */
678
+ export async function runSmokeJob(job, httpClient, options, deps, ownership, observation, control) {
679
+ const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
680
+ if (!timeout.ok) {
681
+ // Consistent with runSpawnJob: a timeout-contract failure fails the job
682
+ // rather than silently substituting a default.
683
+ await httpClient.fail(job, {
684
+ error_kind: "ContractError.Timeout",
685
+ error_message: timeout.error,
686
+ classification: "crashed",
687
+ });
688
+ return { status: "failed", reason: "timeout_contract" };
689
+ }
690
+ const timeoutSeconds = timeout.timeoutSeconds;
691
+ const payload = job.payload && typeof job.payload === "object" ? job.payload : {};
692
+ const durationMs = typeof payload.duration_ms === "number" && payload.duration_ms > 0
693
+ ? payload.duration_ms
694
+ : DEFAULT_SMOKE_DURATION_MS;
695
+ const message = typeof payload.message === "string" ? payload.message : "smoke ok";
696
+ const proc = createNoopProcess(deps, durationMs, message);
697
+ const procResult = await superviseProcess({
698
+ job,
699
+ httpClient,
700
+ options,
701
+ deps,
702
+ ownership,
703
+ observation,
704
+ proc,
705
+ timeoutSeconds,
706
+ collectTelemetry: async () => ({}),
707
+ control,
708
+ });
709
+ if (ownership.abandoned) {
710
+ return { status: "abandoned", reason: ownership.abandonReason };
711
+ }
712
+ const evidence = {
713
+ message,
714
+ exit_code: procResult.exitCode,
715
+ classification: procResult.classification,
716
+ };
717
+ const result = buildSmokeResult(evidence, procResult.classification === "clean_exit" ? "pass" : "fail");
718
+ const completion = {
719
+ job_type: "smoke",
720
+ exit_code: procResult.exitCode ?? 0,
721
+ classification: toWireClassification(procResult.classification),
722
+ result,
723
+ telemetry: observation.snapshot(),
724
+ };
725
+ const terminal = await sendTerminalMutationWithAuthReport({
726
+ kind: "complete",
727
+ send: () => httpClient.complete(job, completion),
728
+ deps,
729
+ options,
730
+ ownership,
731
+ log: deps.log,
732
+ }, job, control);
733
+ return terminalToRunResult(terminal, "completed");
734
+ }