@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,607 @@
1
+ /**
2
+ * BAPI-1593 / BAPI-1595 — the launch-context file.
3
+ *
4
+ * After its readiness acquisition, the `drive-epic --dry-run` preview writes
5
+ * `<run-state dir>/<EPIC>/launch-context.json`: what the preview established, so
6
+ * the real launch of the same epic reads it instead of asking the server again.
7
+ * BAPI-1593 wrote it; BAPI-1595 corrects what it records and adds the reader
8
+ * ({@link readEpicLaunchContext}) that the launch uses.
9
+ *
10
+ * The file is an explicit allowlisted projection, never a copy of a response:
11
+ *
12
+ * - the epic key, the base branch, and the target reduced to scheme, host, and
13
+ * port (no path, query, or userinfo);
14
+ * - when it was written;
15
+ * - a fixed set of typed readiness facts, each `boolean | null` (or a bounded
16
+ * integer | null) so an unestablished fact is never written as a harmful one;
17
+ * - the mandatory-diagnostic id/verdict pairs (no diagnostic prose);
18
+ * - the verified repository identity;
19
+ * - the plan digest the SERVER validated (never a local hash standing in);
20
+ * - the escalation email transport verdict.
21
+ *
22
+ * Schema version 2 is the corrected projection. Version 1 stays readable, but its
23
+ * bring-up values were serialized as `=== true` / `0` defaults, so an observed
24
+ * negative cannot be told from a default. The reader therefore exposes version-1
25
+ * bring-up facts as unknown, and a version-1 `is_bridge: false` as unknown (the
26
+ * old classifier also said `false` for a partial checkout).
27
+ *
28
+ * Evidence that could not be established is written as
29
+ * `{ state: "unknown", reason: <closed code> }`, never omitted or defaulted.
30
+ * The file carries no credential, token, email address, command, diagnostic
31
+ * prose, or raw provider payload.
32
+ *
33
+ * Writing is best-effort and never a stop. The directory is created or tightened
34
+ * to 0700 and the file is written 0600 through an exclusively created temporary
35
+ * file renamed into place; a symlink is never followed, written through, or
36
+ * chmodded. On any failure the temporary file and any stale context are removed
37
+ * and the caller is told, so it can warn with `launch_context_write_failed`.
38
+ *
39
+ * Reading is just as defensive and never a stop. The reader derives the path from
40
+ * a validated epic key under the run-state root (it accepts no path), applies the
41
+ * writer's `lstat` safety checks, validates every field, and reuses a snapshot
42
+ * only when it is bound to THIS launch. Every other outcome is a closed category
43
+ * that invalidates reuse; none of them refuses a launch.
44
+ */
45
+ import { constants as fsConstants } from "node:fs";
46
+ import * as fsp from "node:fs/promises";
47
+ import os from "node:os";
48
+ import path from "node:path";
49
+ import { BRIDGE_RUN_STATE_DIR } from "./bridge-permissions.js";
50
+ import { READINESS_FRESH_RECONCILER_COUNT_CAP, } from "./conductor/bridge-api-client.js";
51
+ import { EMAIL_TRANSPORT_LIVE_DIAGNOSTIC_ID } from "./escalation-reachability.js";
52
+ /** The schema this writer produces (BAPI-1595: the corrected projection). */
53
+ export const LAUNCH_CONTEXT_SCHEMA_VERSION = 2;
54
+ /** The earlier, lossy schema. Still readable; its bring-up values are read as unknown. */
55
+ export const LAUNCH_CONTEXT_LEGACY_SCHEMA_VERSION = 1;
56
+ /** A snapshot at least this old is not reused (exactly ten minutes is stale). */
57
+ export const LAUNCH_CONTEXT_MAX_AGE_MS = 10 * 60 * 1000;
58
+ /** The file name under the epic's run-state directory. */
59
+ export const LAUNCH_CONTEXT_FILE_NAME = "launch-context.json";
60
+ /** The run-state directory relative to the home directory: `BRIDGE_RUN_STATE_DIR` without its `~/`. */
61
+ const RUN_STATE_DIR_FROM_HOME = path.join(...BRIDGE_RUN_STATE_DIR.replace(/^~\//, "").split("/"));
62
+ /** The one merge-execution `probe_skipped_reason` the client recognizes. */
63
+ export const LAUNCH_CONTEXT_PROBE_SKIPPED_REASON = "merge_execution_mode_not_github_actions";
64
+ const EPIC_KEY_RE = /^[A-Z][A-Z0-9_]{0,19}-\d+$/;
65
+ const DIGEST_RE = /^[A-Za-z0-9:_-]{8,128}$/;
66
+ const BRANCH_RE = /^[A-Za-z0-9._/-]{1,255}$/;
67
+ const REPO_RE = /^[A-Za-z0-9._-]{1,200}$/;
68
+ const PROVIDER_REPO_RE = /^[A-Za-z0-9._-]{1,100}\/[A-Za-z0-9._-]{1,100}$/;
69
+ const DIAGNOSTIC_ID_RE = /^[a-z0-9][a-z0-9_.-]{0,99}$/;
70
+ const DB_NAME_RE = /^[A-Za-z0-9_][A-Za-z0-9_.$-]{0,62}$/;
71
+ /** The most protected database names a document keeps (the server caps its own list at 16). */
72
+ const MAX_PROTECTED_DATABASES = 16;
73
+ /** The most diagnostic pairs a document keeps. */
74
+ const MAX_DIAGNOSTIC_RESULTS = 64;
75
+ /** The largest context file the reader will read. */
76
+ const MAX_CONTEXT_FILE_BYTES = 64 * 1024;
77
+ const unknown = (reason) => ({ state: "unknown", reason });
78
+ const known = (value) => ({ state: "known", value });
79
+ /** Reduce a base URL to scheme, host, and port; anything else is dropped. */
80
+ export function sanitizeTargetBaseUrl(raw) {
81
+ if (raw === null)
82
+ return null;
83
+ try {
84
+ const url = new URL(raw);
85
+ if (url.protocol !== "http:" && url.protocol !== "https:")
86
+ return null;
87
+ return `${url.protocol}//${url.host}`;
88
+ }
89
+ catch {
90
+ return null;
91
+ }
92
+ }
93
+ const boolOrNull = (value) => (typeof value === "boolean" ? value : null);
94
+ /** A count is kept only when it satisfies the source contract: an integer in range. */
95
+ const countOrNull = (value) => typeof value === "number" &&
96
+ Number.isSafeInteger(value) &&
97
+ value >= 0 &&
98
+ value <= READINESS_FRESH_RECONCILER_COUNT_CAP
99
+ ? value
100
+ : null;
101
+ /**
102
+ * Project the bring-up block. Booleans are accepted only when their runtime type
103
+ * is boolean, the count only inside its contract range, and a count is `null`
104
+ * when the heartbeat that produced it was not readable. Readability is kept
105
+ * independently of the values that depend on it.
106
+ */
107
+ function bringUpFacts(bringUp) {
108
+ if (bringUp === null || bringUp === undefined)
109
+ return null;
110
+ const migrationReadable = boolOrNull(bringUp.migration_readable);
111
+ const heartbeatReadable = boolOrNull(bringUp.heartbeat_readable);
112
+ return {
113
+ migration_readable: migrationReadable,
114
+ database_migration_current: boolOrNull(bringUp.database_migration_current),
115
+ heartbeat_readable: heartbeatReadable,
116
+ worker_present: boolOrNull(bringUp.worker_present),
117
+ fresh_reconciler_count: heartbeatReadable === true ? countOrNull(bringUp.fresh_reconciler_count) : null,
118
+ single_transition_authority: boolOrNull(bringUp.single_transition_authority),
119
+ };
120
+ }
121
+ /**
122
+ * Normalize the diagnostics at projection time. Only an explicitly mandatory and
123
+ * explicitly applicable diagnostic can be recorded as `failed`; anything whose
124
+ * classification was not established becomes `unknown`; advisory and inapplicable
125
+ * diagnostics are excluded from the mandatory inputs. No prose is read.
126
+ */
127
+ export function projectMandatoryDiagnostics(diagnostics) {
128
+ if (!Array.isArray(diagnostics))
129
+ return [];
130
+ const results = [];
131
+ for (const entry of diagnostics) {
132
+ if (results.length >= MAX_DIAGNOSTIC_RESULTS)
133
+ break;
134
+ if (typeof entry !== "object" || entry === null)
135
+ continue;
136
+ const established = entry.severity === "mandatory" || entry.severity === "advisory"
137
+ ? entry.applicability === "applicable" || entry.applicability === "inapplicable"
138
+ : false;
139
+ // Advisory, or explicitly inapplicable: never a mandatory-harm input.
140
+ if (established && (entry.severity === "advisory" || entry.applicability === "inapplicable"))
141
+ continue;
142
+ const id = typeof entry.id === "string" && DIAGNOSTIC_ID_RE.test(entry.id) ? entry.id : "unrecognized";
143
+ if (!established) {
144
+ results.push({ id, verdict: "unknown" });
145
+ continue;
146
+ }
147
+ results.push({
148
+ id,
149
+ verdict: entry.verdict === "passed" || entry.verdict === "failed" ? entry.verdict : "unknown",
150
+ });
151
+ }
152
+ return results;
153
+ }
154
+ function readinessFacts(report) {
155
+ const provider = typeof report.provider_repository === "string" && PROVIDER_REPO_RE.test(report.provider_repository)
156
+ ? report.provider_repository
157
+ : null;
158
+ const mode = report.resolved_merge_execution_mode;
159
+ return {
160
+ repo_name: typeof report.repo_name === "string" && REPO_RE.test(report.repo_name) ? report.repo_name : "",
161
+ is_production: boolOrNull(report.is_production),
162
+ resolved_merge_execution_mode: mode === "local" || mode === "machine_token" || mode === "github_actions" ? mode : null,
163
+ provider_repository: provider,
164
+ repo_wide_executor_live: boolOrNull(report.executor?.repo_wide_executor_live),
165
+ reconciler_stale: boolOrNull(report.reconciler?.stale),
166
+ bring_up: bringUpFacts(report.bring_up),
167
+ unattended_conductor_allowed: boolOrNull(report.unattended?.conductor_allowed),
168
+ escalation_email_available: boolOrNull(report.unattended?.escalation_email_available),
169
+ repository_readiness_confirmed: boolOrNull(report.unattended?.repository_readiness_confirmed),
170
+ merge_execution_probe_skipped_reason: report.merge_execution?.probe_skipped_reason === LAUNCH_CONTEXT_PROBE_SKIPPED_REASON
171
+ ? LAUNCH_CONTEXT_PROBE_SKIPPED_REASON
172
+ : null,
173
+ mandatory_diagnostics: projectMandatoryDiagnostics(report.diagnostics),
174
+ worker_database: projectWorkerDatabase(report.gate_profile?.worker_database),
175
+ verification_handoff_default: handoffDefaultOrNull(report.gate_profile?.verification_handoff_default),
176
+ };
177
+ }
178
+ const handoffDefaultOrNull = (value) => value === "proceed" || value === "block" ? value : null;
179
+ /** Names are kept only when each fits the identifier shape; anything else is unknown. */
180
+ export function projectWorkerDatabase(raw) {
181
+ if (!isRecord(raw))
182
+ return null;
183
+ if (raw.mode !== "none" && raw.mode !== "disposable_postgres")
184
+ return null;
185
+ const role = raw.worker_role;
186
+ if (role !== null && role !== undefined && !(typeof role === "string" && DB_NAME_RE.test(role)))
187
+ return null;
188
+ const names = raw.protected_databases ?? [];
189
+ if (!Array.isArray(names) || names.length > MAX_PROTECTED_DATABASES)
190
+ return null;
191
+ if (!names.every((name) => typeof name === "string" && DB_NAME_RE.test(name)))
192
+ return null;
193
+ return { mode: raw.mode, worker_role: role ?? null, protected_databases: [...names] };
194
+ }
195
+ /** The `escalation_email.transport_live` verdict, or a typed unknown. */
196
+ export function emailTransportVerdict(readiness) {
197
+ if (readiness === null || readiness.kind !== "ready")
198
+ return unknown("readiness_unknown");
199
+ const diagnostics = readiness.readiness.diagnostics;
200
+ if (!Array.isArray(diagnostics))
201
+ return unknown("not_reported");
202
+ const matches = diagnostics.filter((entry) => entry.id === EMAIL_TRANSPORT_LIVE_DIAGNOSTIC_ID);
203
+ if (matches.length !== 1)
204
+ return unknown("not_reported");
205
+ const verdict = matches[0].verdict;
206
+ return known(verdict === "passed" || verdict === "failed" ? verdict : "unknown");
207
+ }
208
+ /** Build the allowlisted document. Pure. */
209
+ export function buildEpicLaunchContext(evidence) {
210
+ const report = evidence.readiness?.kind === "ready" ? evidence.readiness.readiness : null;
211
+ const target = sanitizeTargetBaseUrl(evidence.targetBaseUrl);
212
+ const repoName = evidence.repoName !== null && REPO_RE.test(evidence.repoName) ? evidence.repoName : null;
213
+ const provider = report !== null && typeof report.provider_repository === "string" && PROVIDER_REPO_RE.test(report.provider_repository)
214
+ ? report.provider_repository
215
+ : null;
216
+ return {
217
+ schema_version: LAUNCH_CONTEXT_SCHEMA_VERSION,
218
+ epic_key: evidence.epicKey,
219
+ base_branch: evidence.baseBranch !== null && BRANCH_RE.test(evidence.baseBranch)
220
+ ? known(evidence.baseBranch)
221
+ : unknown("not_reported"),
222
+ target_base_url: target !== null ? known(target) : unknown("not_resolved"),
223
+ written_at: evidence.writtenAt.toISOString(),
224
+ readiness: report !== null ? known(readinessFacts(report)) : unknown("readiness_unknown"),
225
+ // The identity is the preview's VERIFIED local one. It is never filled from the
226
+ // readiness report: with no verified name the repository is unknown.
227
+ repository: repoName !== null
228
+ ? known({ repo_name: repoName, provider_repository: provider, is_bridge: evidence.isBridge })
229
+ : unknown("not_resolved"),
230
+ plan_digest: evidence.serverPlanDigest !== null && DIGEST_RE.test(evidence.serverPlanDigest)
231
+ ? known(evidence.serverPlanDigest)
232
+ : unknown("not_validated"),
233
+ escalation_email_transport: emailTransportVerdict(evidence.readiness),
234
+ };
235
+ }
236
+ export const NODE_LAUNCH_CONTEXT_FS = {
237
+ mkdir: (dir, options) => fsp.mkdir(dir, options),
238
+ lstat: (target) => fsp.lstat(target),
239
+ chmod: (target, mode) => fsp.chmod(target, mode),
240
+ open: (target, flags, mode) => fsp.open(target, flags, mode),
241
+ rename: (from, to) => fsp.rename(from, to),
242
+ unlink: (target) => fsp.unlink(target),
243
+ readText: async (target) => {
244
+ const handle = await fsp.open(target, fsConstants.O_RDONLY | (fsConstants.O_NOFOLLOW ?? 0));
245
+ try {
246
+ return await handle.readFile({ encoding: "utf8" });
247
+ }
248
+ finally {
249
+ await handle.close();
250
+ }
251
+ },
252
+ };
253
+ /** The default run-state root, resolved the way `BRIDGE_RUN_STATE_DIR` names it. */
254
+ export function defaultRunStateDir(homedir = os.homedir) {
255
+ return path.join(homedir(), RUN_STATE_DIR_FROM_HOME);
256
+ }
257
+ async function lstatOrNull(fs, target) {
258
+ try {
259
+ return await fs.lstat(target);
260
+ }
261
+ catch (err) {
262
+ if (err?.code === "ENOENT")
263
+ return null;
264
+ throw err;
265
+ }
266
+ }
267
+ async function removeIfRegularFile(fs, target) {
268
+ try {
269
+ const entry = await lstatOrNull(fs, target);
270
+ // Only a regular file is removed: a symlink or anything else is left alone.
271
+ if (entry !== null && entry.isFile() && !entry.isSymbolicLink())
272
+ await fs.unlink(target);
273
+ }
274
+ catch {
275
+ // Best effort.
276
+ }
277
+ }
278
+ /** Write the launch-context file. Never throws. */
279
+ export async function writeEpicLaunchContext(context, options = {}) {
280
+ if (!EPIC_KEY_RE.test(context.epic_key))
281
+ return { ok: false, reason: "invalid_epic_key" };
282
+ const fs = options.fs ?? NODE_LAUNCH_CONTEXT_FS;
283
+ const root = options.stateDir ?? defaultRunStateDir();
284
+ const dir = path.join(root, context.epic_key);
285
+ const destination = path.join(dir, LAUNCH_CONTEXT_FILE_NAME);
286
+ const suffix = (options.randomSuffix ?? (() => `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`))();
287
+ const temporary = path.join(dir, `.${LAUNCH_CONTEXT_FILE_NAME}.${suffix}.tmp`);
288
+ // The directory: created 0700, or an existing real directory tightened to 0700.
289
+ try {
290
+ await fs.mkdir(dir, { recursive: true, mode: 0o700 });
291
+ const entry = await fs.lstat(dir);
292
+ if (entry.isSymbolicLink() || !entry.isDirectory())
293
+ return { ok: false, reason: "unsafe_directory" };
294
+ if ((entry.mode & 0o777) !== 0o700)
295
+ await fs.chmod(dir, 0o700);
296
+ }
297
+ catch {
298
+ return { ok: false, reason: "unsafe_directory" };
299
+ }
300
+ // The destination: absent, or a regular file the rename will replace. A
301
+ // symlink (or anything else) is never written through or chmodded.
302
+ let destinationEntry;
303
+ try {
304
+ destinationEntry = await lstatOrNull(fs, destination);
305
+ }
306
+ catch {
307
+ return { ok: false, reason: "write_failed" };
308
+ }
309
+ if (destinationEntry !== null && (destinationEntry.isSymbolicLink() || !destinationEntry.isFile())) {
310
+ return { ok: false, reason: "unsafe_destination" };
311
+ }
312
+ let handle = null;
313
+ try {
314
+ handle = await fs.open(temporary, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW ?? 0), 0o600);
315
+ await handle.writeFile(`${JSON.stringify(context, null, 2)}\n`);
316
+ await handle.close();
317
+ handle = null;
318
+ await fs.chmod(temporary, 0o600);
319
+ await fs.rename(temporary, destination);
320
+ return { ok: true, path: destination };
321
+ }
322
+ catch {
323
+ if (handle !== null)
324
+ await handle.close().catch(() => undefined);
325
+ await removeIfRegularFile(fs, temporary);
326
+ // A stale context must not survive a failed write and be read as current.
327
+ await removeIfRegularFile(fs, destination);
328
+ return { ok: false, reason: "write_failed" };
329
+ }
330
+ }
331
+ const UNKNOWN_REASONS = new Set([
332
+ "readiness_unknown",
333
+ "not_reported",
334
+ "not_validated",
335
+ "not_resolved",
336
+ ]);
337
+ function isRecord(value) {
338
+ return typeof value === "object" && value !== null && !Array.isArray(value);
339
+ }
340
+ /** Validate a `{ state: known|unknown }` wrapper; the inner value is checked by `parse`. */
341
+ function parseFact(raw, parse) {
342
+ if (!isRecord(raw))
343
+ return null;
344
+ if (raw.state === "unknown") {
345
+ return typeof raw.reason === "string" && UNKNOWN_REASONS.has(raw.reason)
346
+ ? unknown(raw.reason)
347
+ : null;
348
+ }
349
+ if (raw.state !== "known")
350
+ return null;
351
+ const value = parse(raw.value);
352
+ return value === null ? null : known(value);
353
+ }
354
+ const nullableBoolean = (raw) => raw === null || typeof raw === "boolean" ? { ok: true, value: raw } : { ok: false };
355
+ function parseBringUp(raw) {
356
+ if (raw === null)
357
+ return null;
358
+ if (!isRecord(raw))
359
+ return "invalid";
360
+ const flags = ["migration_readable", "database_migration_current", "heartbeat_readable", "worker_present", "single_transition_authority"];
361
+ const out = {};
362
+ for (const key of flags) {
363
+ const parsed = nullableBoolean(raw[key]);
364
+ if (!parsed.ok)
365
+ return "invalid";
366
+ out[key] = parsed.value;
367
+ }
368
+ const count = raw.fresh_reconciler_count;
369
+ if (count !== null && countOrNull(count) === null)
370
+ return "invalid";
371
+ out.fresh_reconciler_count = count;
372
+ return out;
373
+ }
374
+ function parseDiagnostics(raw) {
375
+ if (!Array.isArray(raw) || raw.length > MAX_DIAGNOSTIC_RESULTS)
376
+ return null;
377
+ const out = [];
378
+ for (const entry of raw) {
379
+ if (!isRecord(entry))
380
+ return null;
381
+ if (typeof entry.id !== "string" || !(DIAGNOSTIC_ID_RE.test(entry.id) || entry.id === "unrecognized"))
382
+ return null;
383
+ if (entry.verdict !== "passed" && entry.verdict !== "failed" && entry.verdict !== "unknown")
384
+ return null;
385
+ out.push({ id: entry.id, verdict: entry.verdict });
386
+ }
387
+ return out;
388
+ }
389
+ function parseReadinessFacts(raw, version) {
390
+ if (!isRecord(raw))
391
+ return null;
392
+ if (typeof raw.repo_name !== "string" || !(raw.repo_name === "" || REPO_RE.test(raw.repo_name)))
393
+ return null;
394
+ const booleans = {};
395
+ for (const key of [
396
+ "is_production",
397
+ "repo_wide_executor_live",
398
+ "reconciler_stale",
399
+ "unattended_conductor_allowed",
400
+ "escalation_email_available",
401
+ ]) {
402
+ const parsed = nullableBoolean(raw[key]);
403
+ if (!parsed.ok)
404
+ return null;
405
+ booleans[key] = parsed.value;
406
+ }
407
+ const mode = raw.resolved_merge_execution_mode;
408
+ if (mode !== null && mode !== "local" && mode !== "machine_token" && mode !== "github_actions")
409
+ return null;
410
+ const provider = raw.provider_repository;
411
+ if (provider !== null && !(typeof provider === "string" && PROVIDER_REPO_RE.test(provider)))
412
+ return null;
413
+ // Fields a version-1 document does not carry are unknown, never defaulted. Its
414
+ // bring-up block is ignored altogether: it was written with `=== true` / `0`
415
+ // defaults, so an observed negative cannot be told from an unobserved fact.
416
+ let bringUp = null;
417
+ let repositoryReadinessConfirmed = null;
418
+ let probeSkipped = null;
419
+ let diagnostics = [];
420
+ if (version === 2) {
421
+ const parsedBringUp = parseBringUp(raw.bring_up ?? null);
422
+ if (parsedBringUp === "invalid")
423
+ return null;
424
+ bringUp = parsedBringUp;
425
+ const confirmed = nullableBoolean(raw.repository_readiness_confirmed);
426
+ if (!confirmed.ok)
427
+ return null;
428
+ repositoryReadinessConfirmed = confirmed.value;
429
+ const skipped = raw.merge_execution_probe_skipped_reason ?? null;
430
+ if (skipped !== null && skipped !== LAUNCH_CONTEXT_PROBE_SKIPPED_REASON)
431
+ return null;
432
+ probeSkipped = skipped;
433
+ const parsedDiagnostics = parseDiagnostics(raw.mandatory_diagnostics ?? []);
434
+ if (parsedDiagnostics === null)
435
+ return null;
436
+ diagnostics = parsedDiagnostics;
437
+ }
438
+ else if (raw.bring_up !== null && raw.bring_up !== undefined && !isRecord(raw.bring_up)) {
439
+ return null;
440
+ }
441
+ return {
442
+ repo_name: raw.repo_name,
443
+ is_production: booleans.is_production,
444
+ resolved_merge_execution_mode: mode,
445
+ provider_repository: provider,
446
+ repo_wide_executor_live: booleans.repo_wide_executor_live,
447
+ reconciler_stale: booleans.reconciler_stale,
448
+ bring_up: bringUp,
449
+ unattended_conductor_allowed: booleans.unattended_conductor_allowed,
450
+ escalation_email_available: booleans.escalation_email_available,
451
+ repository_readiness_confirmed: repositoryReadinessConfirmed,
452
+ merge_execution_probe_skipped_reason: probeSkipped,
453
+ mandatory_diagnostics: diagnostics,
454
+ // BAPI-1596: additive. A document written before these fields existed, or one
455
+ // whose value does not validate, reads them as unknown (never as `none`).
456
+ worker_database: projectWorkerDatabase(raw.worker_database),
457
+ verification_handoff_default: handoffDefaultOrNull(raw.verification_handoff_default),
458
+ };
459
+ }
460
+ function parseRepository(raw, version) {
461
+ if (!isRecord(raw))
462
+ return null;
463
+ if (typeof raw.repo_name !== "string" || !REPO_RE.test(raw.repo_name))
464
+ return null;
465
+ const provider = raw.provider_repository;
466
+ if (provider !== null && !(typeof provider === "string" && PROVIDER_REPO_RE.test(provider)))
467
+ return null;
468
+ const isBridge = raw.is_bridge;
469
+ if (isBridge !== null && typeof isBridge !== "boolean")
470
+ return null;
471
+ return {
472
+ repo_name: raw.repo_name,
473
+ provider_repository: provider,
474
+ // A version-1 `false` came from an all-markers-present test, which also said
475
+ // `false` for a PARTIAL checkout. It cannot prove a non-Bridge checkout.
476
+ is_bridge: version === 1 && isBridge === false ? null : isBridge,
477
+ };
478
+ }
479
+ /** Validate every field of a parsed document. `null` means invalid. Never throws. */
480
+ function parseLaunchContextDocument(raw) {
481
+ if (!isRecord(raw))
482
+ return null;
483
+ const version = raw.schema_version;
484
+ if (version !== LAUNCH_CONTEXT_SCHEMA_VERSION && version !== LAUNCH_CONTEXT_LEGACY_SCHEMA_VERSION) {
485
+ return typeof version === "number" ? "unsupported_schema" : null;
486
+ }
487
+ if (typeof raw.epic_key !== "string" || !EPIC_KEY_RE.test(raw.epic_key))
488
+ return null;
489
+ if (typeof raw.written_at !== "string" || Number.isNaN(Date.parse(raw.written_at)))
490
+ return null;
491
+ const baseBranch = parseFact(raw.base_branch, (v) => (typeof v === "string" && BRANCH_RE.test(v) ? v : null));
492
+ const target = parseFact(raw.target_base_url, (v) => typeof v === "string" && sanitizeTargetBaseUrl(v) === v ? v : null);
493
+ const readiness = parseFact(raw.readiness, (v) => parseReadinessFacts(v, version));
494
+ const repository = parseFact(raw.repository, (v) => parseRepository(v, version));
495
+ const planDigest = parseFact(raw.plan_digest, (v) => (typeof v === "string" && DIGEST_RE.test(v) ? v : null));
496
+ const transport = parseFact(raw.escalation_email_transport, (v) => v === "passed" || v === "failed" || v === "unknown" ? v : null);
497
+ if (!baseBranch || !target || !readiness || !repository || !planDigest || !transport)
498
+ return null;
499
+ return {
500
+ sourceVersion: version,
501
+ context: {
502
+ schema_version: LAUNCH_CONTEXT_SCHEMA_VERSION,
503
+ epic_key: raw.epic_key,
504
+ base_branch: baseBranch,
505
+ target_base_url: target,
506
+ written_at: new Date(raw.written_at).toISOString(),
507
+ readiness,
508
+ repository,
509
+ plan_digest: planDigest,
510
+ escalation_email_transport: transport,
511
+ },
512
+ };
513
+ }
514
+ /**
515
+ * Read the stored launch context for `binding.epicKey` and decide whether this
516
+ * launch may reuse it. Never throws, and never returns file contents, a path, or
517
+ * exception text.
518
+ *
519
+ * The path is derived here and nowhere else: a validated epic key under the
520
+ * run-state root. There is no parameter for a context-file path.
521
+ *
522
+ * Reuse requires every binding condition: the same epic and base branch, a
523
+ * supported schema, a valid timestamp under ten minutes old and not in the
524
+ * future, the same sanitized target URL, and the same locally verified repository
525
+ * identity. There is deliberately no HEAD binding.
526
+ */
527
+ export async function readEpicLaunchContext(binding, options = {}) {
528
+ const unusable = (reason) => ({ kind: "unusable", reason });
529
+ if (!EPIC_KEY_RE.test(binding.epicKey))
530
+ return unusable("invalid_epic_key");
531
+ const fs = options.fs ?? NODE_LAUNCH_CONTEXT_FS;
532
+ const root = options.stateDir ?? defaultRunStateDir();
533
+ const dir = path.join(root, binding.epicKey);
534
+ const destination = path.join(dir, LAUNCH_CONTEXT_FILE_NAME);
535
+ // The directory and the file are checked BEFORE any content is read.
536
+ try {
537
+ const dirEntry = await lstatOrNull(fs, dir);
538
+ if (dirEntry === null)
539
+ return unusable("missing");
540
+ if (dirEntry.isSymbolicLink() || !dirEntry.isDirectory())
541
+ return unusable("unsafe");
542
+ const fileEntry = await lstatOrNull(fs, destination);
543
+ if (fileEntry === null)
544
+ return unusable("missing");
545
+ if (fileEntry.isSymbolicLink() || !fileEntry.isFile())
546
+ return unusable("unsafe");
547
+ if (typeof fileEntry.size === "number" && fileEntry.size > MAX_CONTEXT_FILE_BYTES)
548
+ return unusable("unreadable");
549
+ }
550
+ catch {
551
+ return unusable("unreadable");
552
+ }
553
+ let text;
554
+ try {
555
+ if (fs.readText === undefined)
556
+ return unusable("unreadable");
557
+ text = await fs.readText(destination);
558
+ }
559
+ catch {
560
+ return unusable("unreadable");
561
+ }
562
+ if (text.length > MAX_CONTEXT_FILE_BYTES)
563
+ return unusable("unreadable");
564
+ let parsed;
565
+ try {
566
+ parsed = JSON.parse(text);
567
+ }
568
+ catch {
569
+ return unusable("invalid");
570
+ }
571
+ const document = parseLaunchContextDocument(parsed);
572
+ if (document === null)
573
+ return unusable("invalid");
574
+ if (document === "unsupported_schema")
575
+ return unusable("unsupported_schema");
576
+ const { context } = document;
577
+ // Age: a valid stamp, in the past, under ten minutes.
578
+ const age = binding.now.getTime() - Date.parse(context.written_at);
579
+ if (age < 0)
580
+ return unusable("future");
581
+ if (age >= LAUNCH_CONTEXT_MAX_AGE_MS)
582
+ return unusable("stale");
583
+ if (context.epic_key !== binding.epicKey)
584
+ return unusable("mismatch");
585
+ // Base branch: both sides must be established, and equal.
586
+ if (binding.baseBranch === null || context.base_branch.state !== "known")
587
+ return unusable("unbound");
588
+ if (context.base_branch.value !== binding.baseBranch)
589
+ return unusable("mismatch");
590
+ // Target: reduced the way the writer reduces it, then compared.
591
+ const target = sanitizeTargetBaseUrl(binding.targetBaseUrl);
592
+ if (target === null || context.target_base_url.state !== "known")
593
+ return unusable("unbound");
594
+ if (context.target_base_url.value !== target)
595
+ return unusable("mismatch");
596
+ // Identity: the locally verified one, against the one the preview verified.
597
+ const local = binding.repository;
598
+ if (local === null || local.repoName === null || local.isBridge === null)
599
+ return unusable("unbound");
600
+ if (context.repository.state !== "known" || context.repository.value.is_bridge === null)
601
+ return unusable("unbound");
602
+ if (context.repository.value.repo_name !== local.repoName)
603
+ return unusable("mismatch");
604
+ if (context.repository.value.is_bridge !== local.isBridge)
605
+ return unusable("mismatch");
606
+ return { kind: "usable", value: document };
607
+ }