@bridge_gpt/mcp-server 0.2.75 → 0.2.76

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 (64) hide show
  1. package/README.md +5 -5
  2. package/build/agents.generated.js +4 -4
  3. package/build/codex-auto-recovery.js +25 -7
  4. package/build/commands.generated.js +6 -6
  5. package/build/conductor/bridge-api-client.js +141 -6
  6. package/build/conductor/declare-blocked.js +4 -0
  7. package/build/conductor/driver-pass.js +8 -0
  8. package/build/conductor/epic-implementer-cli.js +4 -3
  9. package/build/conductor/epic-server-journal.js +13 -0
  10. package/build/conductor/epic-server-recipe.js +15 -5
  11. package/build/conductor/epic-server-runtime.js +163 -45
  12. package/build/conductor/epic-server.js +13 -6
  13. package/build/conductor/install-doctor.js +30 -2
  14. package/build/conductor/local-merge.js +54 -12
  15. package/build/conductor/pr-ci-producer.js +12 -3
  16. package/build/conductor/readiness-sections.js +46 -13
  17. package/build/conductor/readiness.js +3 -40
  18. package/build/conductor/recovery-cli.js +12 -12
  19. package/build/conductor/repository-workflow-remedy.js +147 -7
  20. package/build/conductor/ui-readiness.js +224 -0
  21. package/build/conductor/wait-run-attention.js +9 -4
  22. package/build/conductor/wait-run-cli.js +9 -2
  23. package/build/docs.generated.js +2 -2
  24. package/build/drive-epic.js +402 -27
  25. package/build/epic-implementer-bin.js +62 -42
  26. package/build/epic-launch-context.js +8 -1
  27. package/build/epic-shared/cut-protocol.js +55 -3
  28. package/build/executor/failure-reason-codes.js +2 -0
  29. package/build/executor/integration-job.js +56 -2
  30. package/build/executor/job-runner.js +4 -1
  31. package/build/executor/merge-job.js +45 -1
  32. package/build/executor/permissions.js +187 -2
  33. package/build/executor/provider-checks.js +28 -5
  34. package/build/executor/reconcile-overlap-job.js +70 -17
  35. package/build/executor/required-work-ledger.js +7 -2
  36. package/build/executor/resume-pre-spawn.js +32 -8
  37. package/build/executor/runner.js +26 -4
  38. package/build/executor/worktree.js +12 -1
  39. package/build/index.js +376 -434
  40. package/build/init.js +16 -0
  41. package/build/install-bridge-conductor-answers.js +4 -0
  42. package/build/install-bridge-conductor-apply.js +10 -0
  43. package/build/install-bridge-conductor-assessment.js +71 -0
  44. package/build/install-bridge-conductor-contracts.js +9 -1
  45. package/build/install-bridge-conductor-setup.js +103 -3
  46. package/build/install-bridge-conductor.js +437 -93
  47. package/build/mcp-host-config.js +54 -37
  48. package/build/phase-context-git-probe.js +16 -0
  49. package/build/pipelines.generated.js +9 -9
  50. package/build/plan-execution-ledger.js +27 -0
  51. package/build/plane/plane-freshness.js +43 -26
  52. package/build/printed-remedy-commands.js +8 -0
  53. package/build/readme.generated.js +1 -1
  54. package/build/secret-redaction.js +3 -0
  55. package/build/setup-epic.js +41 -8
  56. package/build/test-support/create-preview-world.js +232 -0
  57. package/build/ticket-delivery.js +65 -0
  58. package/build/v2-readiness-requirements.js +8 -3
  59. package/build/version.generated.js +3 -3
  60. package/build/worktree-core.js +51 -7
  61. package/docs/EPIC-IMPLEMENTER.md +79 -0
  62. package/docs/epic-implementer/getting-started.md +1 -1
  63. package/package.json +1 -1
  64. package/pipelines/implement-ticket.json +2 -2
@@ -913,22 +913,110 @@ export async function fetchEffectiveSupervisorConfig(access, epicKey, fetchImpl
913
913
  const parsed = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
914
914
  return parsed;
915
915
  }
916
+ /** Server bounds on the `required_checks` query value (BAPI-1527). */
917
+ export const POLL_CI_CHECKS_MAX_REQUIRED_NAMES = 64;
918
+ export const POLL_CI_CHECKS_MAX_REQUIRED_NAME_LENGTH = 200;
919
+ /** The fixed unresolved-cache reason the poll route returns without the fallback. */
920
+ const CI_CHECKS_UNRESOLVED_REASON = "CI checks not yet resolved";
921
+ /** True when `requiredChecks` satisfies the route's array, string, and size contract. */
922
+ function isValidRequiredChecksList(requiredChecks) {
923
+ return (Array.isArray(requiredChecks) &&
924
+ requiredChecks.length <= POLL_CI_CHECKS_MAX_REQUIRED_NAMES &&
925
+ requiredChecks.every((name) => typeof name === "string" && name.length <= POLL_CI_CHECKS_MAX_REQUIRED_NAME_LENGTH));
926
+ }
916
927
  /**
917
928
  * Poll CI checks for a commit through the existing `/poll-ci-checks` endpoint.
918
929
  * Validates `commitRef` with {@link normalizeSha} and rejects BEFORE issuing the
919
930
  * request when it is not a valid SHA. Returns the endpoint response verbatim —
920
931
  * the client never invents `pr_number`/`head_sha` fields.
921
- */
922
- export async function pollCiChecksForCommit(access, commitRef, fetchImpl = globalThis.fetch) {
932
+ *
933
+ * BAPI-1527: the optional trailing `requiredChecks` opts into the route's
934
+ * read-only fallback for a repository whose CI check configuration was never
935
+ * resolved. It is encoded as a JSON array in `required_checks`; an explicit `[]`
936
+ * is sent as `[]`, never omitted. A value that breaks the route's bounds throws
937
+ * `invalid-input` before any request. When the route reports a transient polling
938
+ * failure for an opted-in call, this throws a fixed-text `server` error so the
939
+ * caller keeps its retryable `ci_poll_*` handling; a configuration-unavailable
940
+ * response is returned for {@link classifyCiPollAvailability} to read.
941
+ */
942
+ export async function pollCiChecksForCommit(access, commitRef, fetchImpl = globalThis.fetch, requiredChecks) {
923
943
  const sha = normalizeSha(commitRef);
924
944
  if (sha === null) {
925
945
  throw new ConductorBridgeApiError("invalid-input");
926
946
  }
927
- const url = buildConductorJiraUrl(access.baseUrl, "/poll-ci-checks", {
947
+ if (requiredChecks !== undefined && !isValidRequiredChecksList(requiredChecks)) {
948
+ throw new ConductorBridgeApiError("invalid-input");
949
+ }
950
+ const params = {
928
951
  repo_name: access.repoName,
929
952
  commit_ref: sha,
930
- });
931
- return fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
953
+ };
954
+ if (requiredChecks !== undefined) {
955
+ params.required_checks = JSON.stringify(requiredChecks);
956
+ }
957
+ const url = buildConductorJiraUrl(access.baseUrl, "/poll-ci-checks", params);
958
+ const response = await fetchConductorJsonWithTimeout(url, conductorGetHeaders(access), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
959
+ if (requiredChecks !== undefined && readUnavailabilityKind(response) === "transient") {
960
+ // Fixed text only: no upstream reason or body is carried forward.
961
+ throw new CiPollTransientUnavailableError();
962
+ }
963
+ return response;
964
+ }
965
+ /**
966
+ * BAPI-1527: the route answered an opted-in poll with `unavailability_kind:
967
+ * "transient"` (an exception while it polled the provider). It is an ordinary
968
+ * `server` error to every caller, so readers that stop on a thrown poll keep
969
+ * doing so. The local merge wait alone tells it apart from a real 5xx or network
970
+ * failure: before the opt-in, the same exception came back as a plain
971
+ * not-green envelope and the wait kept polling, so it still does (decision A,
972
+ * never an earlier park).
973
+ */
974
+ export class CiPollTransientUnavailableError extends ConductorBridgeApiError {
975
+ constructor() {
976
+ super("server");
977
+ }
978
+ }
979
+ /** The `unavailability_kind` of a poll envelope, or `undefined` when absent or unknown. */
980
+ function readUnavailabilityKind(response) {
981
+ if (response === null || typeof response !== "object")
982
+ return undefined;
983
+ const kind = response.unavailability_kind;
984
+ return kind === "configuration" || kind === "transient" ? kind : undefined;
985
+ }
986
+ /**
987
+ * Classify a poll response's availability. `configuration_unavailable` means the
988
+ * required-check configuration or provider access could not be read — the
989
+ * route's fixed `unavailability_kind: "configuration"` or its legacy fixed
990
+ * unresolved-cache reason. It is evidence of a missing capability, never of a
991
+ * failed check, so a `detail: null` body must not be read as red CI.
992
+ */
993
+ export function classifyCiPollAvailability(response) {
994
+ if (response === null || typeof response !== "object")
995
+ return "unavailable_other";
996
+ const obj = response;
997
+ if (obj.available === true)
998
+ return "available";
999
+ if (obj.available !== false)
1000
+ return "unavailable_other";
1001
+ if (readUnavailabilityKind(obj) === "configuration" || obj.reason === CI_CHECKS_UNRESOLVED_REASON) {
1002
+ return "configuration_unavailable";
1003
+ }
1004
+ return "unavailable_other";
1005
+ }
1006
+ /**
1007
+ * True when a successful poll came from the route's required-checks fallback and
1008
+ * observed no check at all. Distinguishes "nothing reported yet" from red CI.
1009
+ */
1010
+ export function isFallbackWithNoObservedChecks(response) {
1011
+ if (response === null || typeof response !== "object")
1012
+ return false;
1013
+ const detail = response.detail;
1014
+ if (detail === null || typeof detail !== "object")
1015
+ return false;
1016
+ const d = detail;
1017
+ return (d.evaluation_source === "required_checks_fallback" &&
1018
+ Array.isArray(d.checks) &&
1019
+ d.checks.length === 0);
932
1020
  }
933
1021
  // ---------------------------------------------------------------------------
934
1022
  // Conductor BAPI-440: PR review status GET client
@@ -1658,7 +1746,7 @@ export async function createEpicRunWithDisposition(access, request, fetchImpl =
1658
1746
  // `ConductorMutationOutcomeUnknownError`; the caller re-reads, never re-sends.
1659
1747
  let response;
1660
1748
  try {
1661
- response = await fetchConductorJsonWithMethodStatusAndTimeout("POST", url, conductorPostHeaders(access), JSON.stringify(body), CONDUCTOR_FETCH_TIMEOUT_MS, fetchImpl);
1749
+ response = await fetchConductorJsonWithMethodStatusAndTimeout("POST", url, conductorPostHeaders(access), JSON.stringify(body), CONDUCTOR_READINESS_FETCH_TIMEOUT_MS, fetchImpl);
1662
1750
  }
1663
1751
  catch (err) {
1664
1752
  rethrowMutationFailure("create", err);
@@ -3926,6 +4014,27 @@ export function parseReadinessPrerequisites(raw) {
3926
4014
  }
3927
4015
  return result;
3928
4016
  }
4017
+ /** BAPI-1526 — the four forecast outcomes the server may report. */
4018
+ export const MERGE_FORECAST_OUTCOMES = [
4019
+ "auto_merge_kept",
4020
+ "merge_approval_required",
4021
+ "not_requested",
4022
+ "unknown",
4023
+ ];
4024
+ /** BAPI-1526 — the closed first-approval stamp reason tokens (`gate_profile.py`). */
4025
+ export const MERGE_FORECAST_REASON_IDS = [
4026
+ "local_gate_verification_disabled",
4027
+ "local_gate_direct_to_base",
4028
+ "none_profile_requires_merge_approval",
4029
+ "operator_no_ci_gate_override",
4030
+ "operator_ci_key_kept",
4031
+ "plan_node_required_checks_gate_the_run",
4032
+ "repository_policy_auto_merge_kept_without_ci",
4033
+ "epic_branch_ci_declined",
4034
+ "epic_branch_auto_merge_kept",
4035
+ "no_automated_check",
4036
+ "watched_checks_only",
4037
+ ];
3929
4038
  export const ESCALATION_CHANNELS = ["webhook", "email", "none", "unknown"];
3930
4039
  export const WEBHOOK_LAST_DELIVERIES = ["failed", "handed_off", "queued", "unknown"];
3931
4040
  /** BAPI-1452 — the three supported merge execution modes, as the server reports them. */
@@ -4316,6 +4425,32 @@ export function parseConductorReadinessResponse(body) {
4316
4425
  })(),
4317
4426
  ...parseLaunchMergeFacts(root),
4318
4427
  ...parseEscalationObservations(root),
4428
+ ...(() => {
4429
+ const forecast = parseMergeForecast(root.merge_forecast);
4430
+ return forecast === undefined ? {} : { merge_forecast: forecast };
4431
+ })(),
4432
+ };
4433
+ }
4434
+ /**
4435
+ * BAPI-1526 — parse the optional advisory forecast. Absent, `null`, or malformed
4436
+ * (an unknown outcome, a non-array, an unknown reason, or too many reasons) is
4437
+ * `undefined`, never an error: losing the readiness read over an advisory field
4438
+ * would be the wrong trade.
4439
+ */
4440
+ export function parseMergeForecast(value) {
4441
+ if (value === null || typeof value !== "object" || Array.isArray(value))
4442
+ return undefined;
4443
+ const o = value;
4444
+ if (!MERGE_FORECAST_OUTCOMES.includes(o.outcome))
4445
+ return undefined;
4446
+ const raw = o.reason_ids === undefined ? [] : o.reason_ids;
4447
+ if (!Array.isArray(raw) || raw.length > MERGE_FORECAST_REASON_IDS.length)
4448
+ return undefined;
4449
+ if (!raw.every((r) => MERGE_FORECAST_REASON_IDS.includes(r)))
4450
+ return undefined;
4451
+ return {
4452
+ outcome: o.outcome,
4453
+ reason_ids: [...raw],
4319
4454
  };
4320
4455
  }
4321
4456
  /**
@@ -117,6 +117,10 @@ export function getDeclareBlockedUsage() {
117
117
  " run-wide blocked, escalated nothing can progress; keep the normal waiter running",
118
118
  " scope unknown supervision continues",
119
119
  "--entry wedge needs --evidence, --tried, --alternatives and --fixer-outcome.",
120
+ `Limits: --requirement ${DECLARE_BLOCKED_LIMITS.requirement}, --evidence ${DECLARE_BLOCKED_LIMITS.evidence}, ` +
121
+ `--tried ${DECLARE_BLOCKED_LIMITS.tried}, --alternatives ${DECLARE_BLOCKED_LIMITS.alternatives}, ` +
122
+ `--fixer-outcome ${DECLARE_BLOCKED_LIMITS.fixerOutcome} characters each; ` +
123
+ `at most ${DECLARE_BLOCKED_LIMITS.tickets} --ticket-key arguments.`,
120
124
  ].join("\n");
121
125
  }
122
126
  const VALUE_FLAGS = new Set([
@@ -182,8 +182,16 @@ function readJobs(block) {
182
182
  * dropped. An accepted job keeps its own timestamp distinctions (missing, null, malformed,
183
183
  * valid), so an unreadable `created_at` stays attributable to its ticket. State jobs need no
184
184
  * heartbeat; that evidence belongs to explain's outstanding jobs.
185
+ *
186
+ * BAPI-1733: one other shape is readable. A block whose `state` is `"unknown"` and whose
187
+ * `empty_reason` is exactly `"no_jobs"` is the server's confirmation that both job sources read
188
+ * clean and the whole run has no jobs, so it reads as an empty map. Bare `unknown`, any other
189
+ * marker, and every other non-available block stay unreadable.
185
190
  */
186
191
  export function readStateJobs(block) {
192
+ if (isRecord(block) && block.state === "unknown" && block.empty_reason === "no_jobs") {
193
+ return new Map();
194
+ }
187
195
  if (!isRecord(block) || block.state !== "available" || !Array.isArray(block.jobs))
188
196
  return "unreadable";
189
197
  const byTicket = new Map();
@@ -131,7 +131,7 @@ export function getConductorUsage() {
131
131
  " returns to evaluation with NO new wait, job, or repair allowance.",
132
132
  " rerun-ci --epic-run-id <id> --ticket-key <key> --binding <token> [--json]",
133
133
  " Ask CI to re-run a ticket's FAILED checks at its bound head (guided: copy",
134
- " the command explain-run rendered). Charges NO allowance and never re-runs",
134
+ " the command the `explain_run` MCP tool rendered). Charges NO allowance and never re-runs",
135
135
  " claude-review. A re-run is not a verdict: after CI is green, use resume-ci.",
136
136
  " regenerate-plan --epic-run-id <id> --ticket-key <key> --route test|implementation --reason <text> [--json]",
137
137
  " Answer a child parked on a NAMED plan failure with ONE forced plan",
@@ -155,7 +155,7 @@ export function getConductorUsage() {
155
155
  " epic-head commit: the PR leaves draft only when both holds are clear.",
156
156
  " acknowledge-gaps --epic-run-id <id> --digest <CURRENT_DIGEST> --reason <text> [--json]",
157
157
  " The OWNER's one acknowledgement of the run's carried-gap list, by its",
158
- " current digest (from the PR report or explain-run). Never run by the",
158
+ " current digest (from the PR report or the `explain_run` MCP tool). Never run by the",
159
159
  " driver or a worker; it verifies, readies and merges nothing.",
160
160
  " wait-run --epic-run-id <id> [--ticket-key <key>] [--since <token>] [--timeout <seconds>]",
161
161
  " [--until change|attention] [--json] [--watch [--max-minutes <minutes>]]",
@@ -208,6 +208,7 @@ export function getConductorUsage() {
208
208
  " [--evidence <text>] [--tried <verbs>] [--alternatives <text>] [--fixer-outcome <text>]",
209
209
  " Advisory blocker check: not a blocker yet (run <command>), accepted and",
210
210
  " escalated, run-wide blocked, or scope unknown. Never releases supervision.",
211
+ " Limits: epic-implementer declare-blocked --help",
211
212
  "",
212
213
  "supervise options:",
213
214
  " --run-id <id> Run/session identifier to supervise (required)",
@@ -359,7 +360,7 @@ export function getConductorUsage() {
359
360
  " epic-implementer resume-ci --epic-run-id 3f9c2b7e-... --ticket-key PROJ-852",
360
361
  " # CI failed on infrastructure: re-run it (never claude-review); then resume-ci once green:",
361
362
  " epic-implementer rerun-ci --epic-run-id 3f9c2b7e-... --ticket-key PROJ-852 --binding <token>",
362
- " # A child parked on a named plan failure (see explain-run for the route and reason):",
363
+ " # A child parked on a named plan failure (see the `explain_run` MCP tool, not a CLI verb, for the route and reason):",
363
364
  " epic-implementer regenerate-plan --epic-run-id 3f9c2b7e-... --ticket-key PROJ-852 \\",
364
365
  " --route implementation --reason \"The test plan named a target that is not indexed\"",
365
366
  " # The owner accepted the risk of a step a worker could not verify (verification incomplete):",
@@ -59,6 +59,9 @@ export const EPIC_SERVER_REASONS = [
59
59
  "ready_timeout",
60
60
  "ready_redirect_refused",
61
61
  "credential_unavailable",
62
+ // BAPI-1733: the app exited before it became ready (a serving failure). Distinct
63
+ // from the post-ready "app_failed" reason, which the "app_exited" EVENT carries.
64
+ "app_exited",
62
65
  "expired",
63
66
  "fenced",
64
67
  "app_failed",
@@ -74,6 +77,7 @@ export const EPIC_SERVER_JOURNAL_MAX_EVENTS = 500;
74
77
  export const EPIC_SERVER_JOURNAL_MAX_READ = 100;
75
78
  const TICKET_RE = /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/;
76
79
  const SHA_RE = /^[0-9a-f]{40}$/;
80
+ const EXIT_SIGNAL_RE = /^SIG[A-Z0-9]{1,10}$/;
77
81
  const RUN_ID_RE = /^[A-Za-z0-9][A-Za-z0-9_-]{7,63}$/;
78
82
  /** Build one sanitized entry. Fields outside the closed shapes are dropped. */
79
83
  export function buildJournalEntry(runId, seq, at, event, fields = {}) {
@@ -98,6 +102,13 @@ export function buildJournalEntry(runId, seq, at, event, fields = {}) {
98
102
  entry.reason = fields.reason;
99
103
  if (typeof fields.count === "number" && Number.isSafeInteger(fields.count) && fields.count >= 0)
100
104
  entry.count = fields.count;
105
+ // Exit facts are kept only in their closed shapes; anything else is dropped,
106
+ // never coerced, and a raw process error is never accepted here at all.
107
+ if (typeof fields.exit_code === "number" && Number.isSafeInteger(fields.exit_code) && fields.exit_code >= 0 && fields.exit_code <= 255) {
108
+ entry.exit_code = fields.exit_code;
109
+ }
110
+ if (typeof fields.exit_signal === "string" && EXIT_SIGNAL_RE.test(fields.exit_signal))
111
+ entry.exit_signal = fields.exit_signal;
101
112
  return entry;
102
113
  }
103
114
  /** Validate one parsed entry; anything outside the closed shape is null. */
@@ -123,6 +134,8 @@ export function validateJournalEntry(raw) {
123
134
  outcome: doc.outcome,
124
135
  reason: doc.reason,
125
136
  count: doc.count,
137
+ exit_code: doc.exit_code,
138
+ exit_signal: doc.exit_signal,
126
139
  });
127
140
  if (typeof doc.sha12 === "string" && /^[0-9a-f]{12}$/.test(doc.sha12))
128
141
  rebuilt.sha12 = doc.sha12;
@@ -88,6 +88,16 @@ function hasControlChars(value) {
88
88
  }
89
89
  return false;
90
90
  }
91
+ const SAFE_ENTRY_LABEL_RE = /^[A-Za-z_][A-Za-z0-9_]{0,63}$/;
92
+ /**
93
+ * BAPI-1733 — a diagnostic label for one `inputs` / `credential_refs` entry. The
94
+ * entry name appears only when it is a plain identifier; anything else (punctuation,
95
+ * newlines, over-long text) is replaced so a name can never carry a value or
96
+ * injected text into an error.
97
+ */
98
+ function entryLabel(section, name) {
99
+ return `${section}.${SAFE_ENTRY_LABEL_RE.test(name) ? name : "an entry"}`;
100
+ }
91
101
  /** True for a name a recipe may set in a command environment. */
92
102
  export function isRecipeEnvName(name) {
93
103
  if (!ENV_NAME_RE.test(name) || RESERVED_ENV_NAMES.has(name))
@@ -292,9 +302,9 @@ export function validateEpicServerRecipe(raw) {
292
302
  }
293
303
  for (const [name, value] of Object.entries(raw.inputs)) {
294
304
  if (!isRecipeEnvName(name))
295
- return { ok: false, error: "inputs: a name is reserved or unusable" };
305
+ return { ok: false, error: `${entryLabel("inputs", name)}: the name is reserved or unusable` };
296
306
  if (typeof value !== "string" || value.length > MAX_ENV_VALUE_CHARS || value.includes("\0") || hasControlChars(value)) {
297
- return { ok: false, error: "inputs: a value is unusable" };
307
+ return { ok: false, error: `${entryLabel("inputs", name)}: the value is unusable` };
298
308
  }
299
309
  inputs[name] = value;
300
310
  }
@@ -306,13 +316,13 @@ export function validateEpicServerRecipe(raw) {
306
316
  }
307
317
  for (const [name, value] of Object.entries(raw.credential_refs)) {
308
318
  if (!isRecipeEnvName(name) || name in inputs)
309
- return { ok: false, error: "credential_refs: a name is reserved or unusable" };
319
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: the name is reserved or unusable` };
310
320
  if (!isPlainObject(value) || !isValidCredentialReference(value.ref) || typeof value.key !== "string" || !/^[A-Za-z_][A-Za-z0-9_]{0,63}$/.test(value.key)) {
311
- return { ok: false, error: "credential_refs: each entry needs a ref and a key name" };
321
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: each entry needs a ref and a key name` };
312
322
  }
313
323
  if (Object.keys(value).some((k) => k !== "ref" && k !== "key")) {
314
324
  // A raw secret value never belongs here.
315
- return { ok: false, error: "credential_refs: an entry holds more than a reference" };
325
+ return { ok: false, error: `${entryLabel("credential_refs", name)}: an entry holds more than a reference` };
316
326
  }
317
327
  credentialRefs[name] = { ref: value.ref, key: value.key };
318
328
  }
@@ -36,6 +36,56 @@ import { boundedResult, ensurePrivateDirectory, epicServerLoginFilePath, epicSer
36
36
  import { buildEpicServerCommandEnv, formatLoginFile, isOwnershipInspectionSupported, parseSeedOutput, readProcessStartTime, stopOwnedProcessGroup, verifyOwnedProcess, } from "./epic-server-processes.js";
37
37
  import { dropTurnDatabase, isCurrentTurnDatabase, provisionTurnDatabase, sweepOwnLeftoverDatabases, } from "./epic-server-database.js";
38
38
  import { epicServerRecipeDigest, proofCoversStart, substituteRecipeArgv, validateEpicServerProof, validateEpicServerRecipe, EPIC_SERVER_PROOF_VERSION, } from "./epic-server-recipe.js";
39
+ function watchStartupExit(child) {
40
+ let latched = null;
41
+ let resolveExit = () => undefined;
42
+ const exited = new Promise((resolve) => {
43
+ resolveExit = resolve;
44
+ });
45
+ const latch = (exit) => {
46
+ if (latched !== null)
47
+ return;
48
+ latched = exit;
49
+ resolveExit(exit);
50
+ };
51
+ const onExit = (code, signal) => {
52
+ child.off("error", onError);
53
+ latch({ code: typeof code === "number" ? code : null, signal: typeof signal === "string" ? signal : null });
54
+ };
55
+ // A spawn error carries raw text that may hold secrets: it is never retained.
56
+ const onError = () => {
57
+ child.off("exit", onExit);
58
+ latch({ code: null, signal: null });
59
+ };
60
+ child.once("exit", onExit);
61
+ child.once("error", onError);
62
+ // An exit that completed before the listeners attached is seeded from the child.
63
+ if (typeof child.exitCode === "number" || typeof child.signalCode === "string") {
64
+ child.off("exit", onExit);
65
+ child.off("error", onError);
66
+ latch({
67
+ code: typeof child.exitCode === "number" ? child.exitCode : null,
68
+ signal: typeof child.signalCode === "string" ? child.signalCode : null,
69
+ });
70
+ }
71
+ return {
72
+ latched: () => latched,
73
+ exited,
74
+ dispose: () => {
75
+ child.off("exit", onExit);
76
+ child.off("error", onError);
77
+ },
78
+ };
79
+ }
80
+ /** Race a promise against app exit; the loser's eventual rejection is always handled. */
81
+ async function raceStartupExit(work, watcher) {
82
+ work.catch(() => undefined);
83
+ const winner = await Promise.race([
84
+ work.then((value) => ({ exited: false, value })),
85
+ watcher.exited.then(() => ({ exited: true })),
86
+ ]);
87
+ return winner;
88
+ }
39
89
  async function resolveCredentials(recipe, deps) {
40
90
  const out = {};
41
91
  for (const [name, { ref, key }] of Object.entries(recipe.credential_refs)) {
@@ -66,49 +116,80 @@ async function runSteps(steps, cwd, env, port, ctx) {
66
116
  }
67
117
  return "ok";
68
118
  }
69
- async function awaitReady(ctx, env, cwd) {
119
+ async function awaitReady(ctx, env, cwd, watcher) {
70
120
  const ready = ctx.recipe.ready;
71
121
  const deadline = Date.now() + ready.timeout_seconds * 1000;
72
122
  const base = epicServerLoopbackUrl(ctx.port);
123
+ const exitedResult = () => {
124
+ const exit = watcher.latched();
125
+ return exit === null ? null : { outcome: "app_exited", exit };
126
+ };
73
127
  while (Date.now() < deadline) {
74
128
  if (ctx.signal?.aborted)
75
- return "cancelled";
129
+ return { outcome: "cancelled" };
130
+ const early = exitedResult();
131
+ if (early !== null)
132
+ return early;
76
133
  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())));
134
+ const probe = await raceStartupExit(ctx.deps.http.get(`${base}${ready.path}`, Math.min(5_000, Math.max(1, deadline - Date.now()))), watcher);
135
+ if (probe.exited)
136
+ return exitedResult() ?? { outcome: "app_exited" };
137
+ const res = probe.value;
78
138
  if (res !== null) {
79
139
  if (res.status >= 200 && res.status < 300)
80
- return "ok";
140
+ return exitedResult() ?? { outcome: "ok" };
81
141
  if (res.status >= 300 && res.status < 400) {
82
142
  // A redirect is ready only when it stays on the run's own address.
83
143
  if (res.location === null)
84
- return "ready_redirect_refused";
144
+ return { outcome: "ready_redirect_refused" };
85
145
  let target;
86
146
  try {
87
147
  target = new URL(res.location, base);
88
148
  }
89
149
  catch {
90
- return "ready_redirect_refused";
150
+ return { outcome: "ready_redirect_refused" };
91
151
  }
92
- return target.origin === base ? "ok" : "ready_redirect_refused";
152
+ return target.origin === base ? (exitedResult() ?? { outcome: "ok" }) : { outcome: "ready_redirect_refused" };
93
153
  }
94
154
  }
95
155
  }
96
156
  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";
157
+ // Each probe gets its own signal, chained to the run's, so app exit can stop
158
+ // a pending command without being mistaken for a cancellation.
159
+ const probeController = new AbortController();
160
+ const onParentAbort = () => probeController.abort();
161
+ if (ctx.signal?.aborted)
162
+ probeController.abort();
163
+ else
164
+ ctx.signal?.addEventListener("abort", onParentAbort, { once: true });
165
+ try {
166
+ const probe = await raceStartupExit(ctx.deps.runCommand(substituteRecipeArgv(ready.argv, ctx.port), {
167
+ cwd,
168
+ env,
169
+ timeoutMs: Math.max(1, Math.min(10_000, deadline - Date.now())),
170
+ captureStdout: false,
171
+ signal: probeController.signal,
172
+ }), watcher);
173
+ if (probe.exited) {
174
+ probeController.abort();
175
+ return exitedResult() ?? { outcome: "app_exited" };
176
+ }
177
+ const outcome = probe.value;
178
+ if (outcome.kind === "ok")
179
+ return exitedResult() ?? { outcome: "ok" };
180
+ if (outcome.kind === "cancelled") {
181
+ return exitedResult() ?? { outcome: "cancelled" };
182
+ }
183
+ }
184
+ finally {
185
+ ctx.signal?.removeEventListener("abort", onParentAbort);
186
+ }
108
187
  }
109
- await ctx.deps.sleep(Math.min(500, Math.max(1, deadline - Date.now())));
188
+ const slept = await raceStartupExit(ctx.deps.sleep(Math.min(500, Math.max(1, deadline - Date.now()))), watcher);
189
+ if (slept.exited)
190
+ return exitedResult() ?? { outcome: "app_exited" };
110
191
  }
111
- return "ready_timeout";
192
+ return exitedResult() ?? { outcome: "ready_timeout" };
112
193
  }
113
194
  /**
114
195
  * Replay the recipe against one exact head: a fresh detached serving checkout,
@@ -119,7 +200,12 @@ async function awaitReady(ctx, env, cwd) {
119
200
  export async function runServingPipeline(ctx, sha, generation) {
120
201
  const { deps, paths, recipe } = ctx;
121
202
  const turn = { generation, sha, app: null, database: null, loginFile: null };
122
- const fail = (reason) => ({ ok: false, reason, partial: turn });
203
+ const fail = (reason, exit) => ({
204
+ ok: false,
205
+ reason,
206
+ partial: turn,
207
+ ...(exit !== undefined ? { exit } : {}),
208
+ });
123
209
  // A fresh checkout for every head: ignored artifacts and generated files from
124
210
  // an earlier turn can never reach another worker's verification.
125
211
  const worktree = paths.servingWorktree;
@@ -190,17 +276,27 @@ export async function runServingPipeline(ctx, sha, generation) {
190
276
  const started = deps.startApp(substituteRecipeArgv(recipe.start.argv, ctx.port), { cwd: worktree, env });
191
277
  if (started === null)
192
278
  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");
279
+ // Latch termination from the moment the child exists, before any await, so no
280
+ // exit shape between here and readiness can be missed.
281
+ const watcher = watchStartupExit(started.child);
282
+ try {
283
+ const startedAt = await readProcessStartTime(started.pid, deps.proc);
284
+ if (startedAt === null) {
285
+ // The app died at once, or its identity cannot be read: never signalled blind.
286
+ return fail("start_failed");
287
+ }
288
+ turn.app = { pid: started.pid, started_at: startedAt, child: started.child };
289
+ await ctx.recordOwnership({ app: { pid: started.pid, started_at: startedAt } });
290
+ const ready = await awaitReady(ctx, env, worktree, watcher);
291
+ if (ready.outcome !== "ok")
292
+ return fail(ready.outcome, ready.exit);
293
+ return { ok: true, turn };
294
+ }
295
+ finally {
296
+ // Success, failure, and cancellation all hand over cleanly: the post-ready
297
+ // `watchApp` listener (or `teardownTurn`) takes it from here.
298
+ watcher.dispose();
197
299
  }
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
300
  }
205
301
  /**
206
302
  * Tear one turn down: stop the app (guarded), drop its database, remove its
@@ -238,15 +334,12 @@ export async function teardownTurn(ctx, turn) {
238
334
  });
239
335
  return clean;
240
336
  }
241
- // ---------------------------------------------------------------------------
242
- // Recipe, proof, and ownership files
243
- // ---------------------------------------------------------------------------
244
337
  export async function readRecipe(paths, fs) {
245
338
  const raw = await readPrivateJson(fs, paths.recipe);
246
339
  if (raw === null)
247
- return null;
340
+ return { ok: false, detail: "recipe file is missing or unreadable" };
248
341
  const validated = validateEpicServerRecipe(raw);
249
- return validated.ok ? validated.recipe : null;
342
+ return validated.ok ? { ok: true, recipe: validated.recipe } : { ok: false, detail: validated.error };
250
343
  }
251
344
  export async function readProof(paths, fs) {
252
345
  return validateEpicServerProof(await readPrivateJson(fs, paths.proof));
@@ -314,6 +407,14 @@ export async function recoverAbandonedResources(paths, deps) {
314
407
  }
315
408
  return "retained";
316
409
  }
410
+ /** Format startup-exit evidence. Explicit null checks keep exit code 0 from being lost. */
411
+ function formatStartupExit(exit) {
412
+ if (exit !== undefined && exit.code !== null)
413
+ return `app exited with code ${exit.code}`;
414
+ if (exit !== undefined && exit.signal !== null)
415
+ return `app exited on signal ${exit.signal}`;
416
+ return "app exited without an exit code or signal";
417
+ }
317
418
  /**
318
419
  * Prove one recipe revision against the exact epic head: an exclusively owned
319
420
  * run of the serving pipeline, fully cleaned up before returning. A matching
@@ -323,9 +424,10 @@ export async function proveRecipe(input, deps) {
323
424
  const { paths } = input;
324
425
  if (!isOwnershipInspectionSupported(deps.proc.platform))
325
426
  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" };
427
+ const recipeRead = await readRecipe(paths, deps.fs);
428
+ if (!recipeRead.ok)
429
+ return { ok: false, reason: "recipe_invalid", detail: recipeRead.detail };
430
+ const recipe = recipeRead.recipe;
329
431
  const live = await readEpicServerLiveState(paths.state, input.runId, { fs: deps.fs, probe: { identity: async (pid) => {
330
432
  const s = await readProcessStartTime(pid, deps.proc);
331
433
  return s === null ? null : { startedAt: s };
@@ -392,8 +494,11 @@ export async function proveRecipe(input, deps) {
392
494
  if (clean)
393
495
  await removeFileQuietly(deps.fs, paths.ownership);
394
496
  await removeFileQuietly(deps.fs, paths.claim);
395
- if (!served.ok)
396
- return { ok: false, reason: served.reason };
497
+ if (!served.ok) {
498
+ return served.reason === "app_exited"
499
+ ? { ok: false, reason: served.reason, detail: formatStartupExit(served.exit) }
500
+ : { ok: false, reason: served.reason };
501
+ }
397
502
  if (!clean)
398
503
  return { ok: false, reason: "cleanup_incomplete" };
399
504
  const proof = {
@@ -870,7 +975,19 @@ export class EpicServerHelper {
870
975
  this.turn = served.partial;
871
976
  await this.endTurn();
872
977
  await this.writeState();
873
- await this.options.journal.append("serving_failed", { generation, ticket: next.ticket, sha: next.head, reason: served.reason, outcome: "failed" });
978
+ await this.options.journal.append("serving_failed", {
979
+ generation,
980
+ ticket: next.ticket,
981
+ sha: next.head,
982
+ reason: served.reason,
983
+ outcome: "failed",
984
+ ...(served.reason === "app_exited" && served.exit !== undefined
985
+ ? {
986
+ ...(served.exit.code !== null ? { exit_code: served.exit.code } : {}),
987
+ ...(served.exit.signal !== null ? { exit_signal: served.exit.signal } : {}),
988
+ }
989
+ : {}),
990
+ });
874
991
  if (!next.cancelled) {
875
992
  next.cancelled = true;
876
993
  next.respond({ ok: false, outcome: "unavailable", reason: served.reason === "cancelled" ? "build_timeout" : served.reason });
@@ -996,9 +1113,10 @@ export async function startEpicServerHelper(input, deps) {
996
1113
  const { paths } = input;
997
1114
  if (!isOwnershipInspectionSupported(rt.proc.platform))
998
1115
  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" };
1116
+ const recipeRead = await readRecipe(paths, rt.fs);
1117
+ if (!recipeRead.ok)
1118
+ return { ok: false, reason: "recipe_invalid", detail: recipeRead.detail };
1119
+ const recipe = recipeRead.recipe;
1002
1120
  if (!proofCoversStart(await readProof(paths, rt.fs), recipe, input.epicHead))
1003
1121
  return { ok: false, reason: "not_proven" };
1004
1122
  const deadline = Date.now() + recipe.timing.start_seconds * 1000;