@bridge_gpt/mcp-server 0.2.72 → 0.2.74

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 (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -18,19 +18,23 @@
18
18
  *
19
19
  * ## Read-only until it is not
20
20
  *
21
- * The ENTIRE preflight — local checks, the remote default-branch head, every
21
+ * The ENTIRE preflight — executable checks, the remote default-branch head, every
22
22
  * managed file's content on that head, the open managed pull request, and the
23
23
  * managed remote branch — completes before the first fetch, file write, commit,
24
24
  * push, or pull request. Nothing here can partially install.
25
25
  *
26
- * ## The person's checkout is never touched
26
+ * ## The person's checkout is never touched, and never in the way
27
27
  *
28
28
  * All branch and file work happens in a temporary, DETACHED `git worktree`
29
- * created from the verified default-branch head, outside the person's checkout,
30
- * and removed on every exit path. The person's HEAD, index, and working files
31
- * are unchanged at the end: no checkout, switch, reset, or stash ever runs
32
- * against them. Content is classified from the default branch, not from
33
- * whatever the person has checked out.
29
+ * created from the verified remote default-branch head, outside the person's
30
+ * checkout, and removed on every exit path. The person's HEAD, index, and
31
+ * working files are unchanged at the end: no checkout, switch, reset, or stash
32
+ * ever runs against them. Content is classified from the default branch, not
33
+ * from whatever the person has checked out, so uncommitted or unpushed local
34
+ * changes can neither block the install nor leak into it. A caller that needs
35
+ * facts about that same head (the toolchains the CI workflow installs) captures
36
+ * the default-branch snapshot first ({@link captureDefaultBranchSnapshot}) and
37
+ * passes it back, so the proposal and the worktree share one SHA.
34
38
  *
35
39
  * ## Content states, and why `identical` is not the only no-op
36
40
  *
@@ -46,8 +50,10 @@
46
50
  * A re-run that finds an open managed pull request whose contents match the
47
51
  * proposal reports it and writes nothing. One whose contents differ is reported
48
52
  * for manual reconciliation. A pushed managed branch with no open pull request
49
- * (left by an earlier `pr_open_failed`) is reported with a fixed next step; it
50
- * is never reused, overwritten, or deleted automatically.
53
+ * (left by an earlier `pr_open_failed`) whose managed files match the proposal
54
+ * needs only its pull request: the branch is not pushed again. One whose files
55
+ * differ is reported with a fixed next step; it is never overwritten or deleted
56
+ * automatically.
51
57
  *
52
58
  * ## Secret discipline
53
59
  *
@@ -65,7 +71,6 @@ import { MERGE_WORKFLOW_API_KEY_SECRET_NAME, } from "./merge-workflow-config.js"
65
71
  import { MERGE_WORKFLOW_CLASSIFICATION_TEXT, classifyMergeWorkflowContent, } from "./merge-workflow-drift.js";
66
72
  import { MERGE_WORKFLOW_CODEOWNERS_RELPATH, MERGE_WORKFLOW_GUIDANCE_RELPATH, MERGE_WORKFLOW_MANAGED_RELPATHS, MergeWorkflowCodeOwnerError, renderMergeWorkflowCodeownersFragment, renderMergeWorkflowGuidance, validateMergeWorkflowCodeOwner, } from "./merge-workflow-codeowners.js";
67
73
  import { renderEpicImplementerMergeWorkflow } from "./merge-workflow.js";
68
- import { MCP_INSTALL_STATE_RELPATH } from "./mcp-install-state.js";
69
74
  // ---------------------------------------------------------------------------
70
75
  // Managed identity (merge-workflow set)
71
76
  // ---------------------------------------------------------------------------
@@ -99,8 +104,6 @@ export const MERGE_WORKFLOW_INSTALL_FAILURE_REASONS = [
99
104
  "gh_unavailable",
100
105
  /** The requested directory is not the root of the active git worktree. */
101
106
  "not_repository_root",
102
- /** The worktree or index carries uncommitted changes. */
103
- "worktree_not_clean",
104
107
  /** The repository default branch could not be resolved, or the two sources disagreed. */
105
108
  "default_branch_unresolved",
106
109
  /** The push remote is missing, or is not a canonical github.com repository. */
@@ -141,6 +144,8 @@ export const MERGE_WORKFLOW_INSTALL_FAILURE_REASONS = [
141
144
  // --- BAPI-1536 -----------------------------------------------------------
142
145
  /** The CI workflow's toolchain set is outside the closed vocabulary. */
143
146
  "toolchains_invalid",
147
+ /** BAPI-1677 — an approved install command cannot be written into the CI workflow safely. */
148
+ "dependency_install_invalid",
144
149
  /** A pull request from an earlier published renderer version's managed branch is still open. */
145
150
  "historical_managed_pr_open",
146
151
  ];
@@ -192,7 +197,6 @@ const REMEDIATION = {
192
197
  git_unavailable: "Install git and re-run; this command creates the branch with your own git.",
193
198
  gh_unavailable: "Install the GitHub CLI (`gh`) and authenticate it; this command opens the pull request as you.",
194
199
  not_repository_root: "Run this command from the root of the repository that should receive the workflow.",
195
- worktree_not_clean: "Commit or set aside your local changes first; this command refuses to stage anything it did not generate.",
196
200
  default_branch_unresolved: "Check that the repository has a default branch and that `gh` can read it, then re-run.",
197
201
  remote_not_github: "Point the push remote at a github.com repository; this feature is GitHub.com-only.",
198
202
  repository_identity_mismatch: "Make the local remote and the `gh` default repository agree, then re-run.",
@@ -210,8 +214,9 @@ const REMEDIATION = {
210
214
  default_branch_moved: "The default branch changed while this command ran; re-run it to review the new proposal.",
211
215
  managed_state_changed: "Another managed branch or pull request appeared while this command ran; review it, then re-run.",
212
216
  worktree_failed: "A temporary git worktree could not be created; check free disk space and `git worktree list`, then re-run.",
213
- test_command_invalid: "Save a valid test command through Bridge setup, then re-run.",
217
+ test_command_invalid: "Give a valid one-line test command with --test-command, then re-run setup; Bridge proves it before it is used.",
214
218
  toolchains_invalid: "Re-run setup so the repository's dependency files are inspected again; nothing was written.",
219
+ dependency_install_invalid: "Correct the install commands through setup, without a credential, token, environment reference, or expression; nothing was written.",
215
220
  historical_managed_pr_open: "An earlier Bridge setup pull request is still open for this workflow; merge or close it, then re-run. Bridge does not close or rewrite it.",
216
221
  };
217
222
  /** The remediation sentence for a reason. */
@@ -249,11 +254,6 @@ async function captureRawStdout(run, args) {
249
254
  return null;
250
255
  }
251
256
  }
252
- /** Whether a porcelain-v1 status line names exactly the install manifest. */
253
- function isInstallStateLine(line) {
254
- // `XY <path>`: two status columns, a space, then the path.
255
- return line.length > 3 && line.slice(3) === MCP_INSTALL_STATE_RELPATH;
256
- }
257
257
  /** Split `gh api --include` output into its status code and RAW body. */
258
258
  function parseIncludedResponse(stdout) {
259
259
  const status = /^HTTP\/[0-9.]+ (\d{3})\b/.exec(stdout);
@@ -268,7 +268,8 @@ function parseIncludedResponse(stdout) {
268
268
  cut = lf + 2;
269
269
  else
270
270
  return null;
271
- return { status: Number(status[1]), body: stdout.slice(cut) };
271
+ const contentType = /^content-type:[ \t]*([^;\r\n]*)/im.exec(stdout.slice(0, cut));
272
+ return { status: Number(status[1]), contentType: contentType ? contentType[1].trim().toLowerCase() : null, body: stdout.slice(cut) };
272
273
  }
273
274
  /**
274
275
  * Read one file's RAW bytes from the remote at an immutable commit, through
@@ -293,6 +294,10 @@ async function readRemoteFile(deps, repository, sha, relPath) {
293
294
  const parsed = parseIncludedResponse(result.stdout ?? "");
294
295
  if (!parsed)
295
296
  return { kind: "unverifiable" };
297
+ // Asked for raw bytes, GitHub answers a folder with 200 and a JSON listing. A real
298
+ // file, JSON included, comes back as application/vnd.github.raw.
299
+ if (parsed.status === 200 && parsed.contentType === "application/json")
300
+ return { kind: "unverifiable" };
296
301
  if (parsed.status === 200 && result.status === 0)
297
302
  return { kind: "present", content: parsed.body };
298
303
  if (parsed.status === 404)
@@ -402,6 +407,41 @@ async function prContentMatchesProposal(deps, repository, pr, proposals) {
402
407
  }
403
408
  return true;
404
409
  }
410
+ /** GitHub's compare endpoint lists at most this many files; a full page may be truncated. */
411
+ const COMPARE_FILE_LIMIT = 300;
412
+ /**
413
+ * The files a pushed branch changes against the default-branch head the install
414
+ * was classified at, through `gh api` compare. `null` when the answer is not a
415
+ * clean, complete list: an uncertain read never authorizes opening a pull request.
416
+ */
417
+ async function readBranchChangedFiles(deps, repository, baseSha, headSha) {
418
+ let result;
419
+ try {
420
+ result = await deps.runGh([
421
+ "api",
422
+ `repos/${repository}/compare/${baseSha}...${headSha}`,
423
+ "--jq",
424
+ "[.files[].filename]",
425
+ ]);
426
+ }
427
+ catch {
428
+ return null;
429
+ }
430
+ if (result.status !== 0)
431
+ return null;
432
+ let parsed;
433
+ try {
434
+ parsed = JSON.parse((result.stdout ?? "").trim());
435
+ }
436
+ catch {
437
+ return null;
438
+ }
439
+ if (!Array.isArray(parsed) || !parsed.every((f) => typeof f === "string"))
440
+ return null;
441
+ if (parsed.length >= COMPARE_FILE_LIMIT)
442
+ return null;
443
+ return parsed;
444
+ }
405
445
  function compareUrl(repository, defaultBranch, branch) {
406
446
  return `https://github.com/${repository}/compare/${encodeURI(defaultBranch)}...${encodeURI(branch)}`;
407
447
  }
@@ -457,21 +497,7 @@ async function classifyAtRemote(deps, descriptor, repository, sha, quiet) {
457
497
  proposals,
458
498
  };
459
499
  }
460
- /**
461
- * Run the complete read-only preflight for an artifact set.
462
- *
463
- * Every check here is a read: executables, repository root, clean worktree,
464
- * default branch, remote and `gh` identity, set-specific options, the remote
465
- * default-branch head (via `ls-remote`, no fetch), and each managed file's raw
466
- * bytes at that head (via `gh api`). Nothing it calls creates a branch, writes a
467
- * file, touches install state, fetches, commits, pushes, or opens a pull request.
468
- */
469
- export async function runArtifactSetPreflight(descriptor, deps) {
470
- // Managed paths are constants; this guards a future edit, not today's input.
471
- for (const artifact of descriptor.artifacts) {
472
- if (!isSafeManagedRelPath(artifact.relPath))
473
- return { ok: false, result: fail("write_failed") };
474
- }
500
+ async function readLocalIdentity(deps) {
475
501
  if (!(await commandSucceeds(deps.runGit, ["--version"]))) {
476
502
  return { ok: false, result: fail("git_unavailable") };
477
503
  }
@@ -487,24 +513,6 @@ export async function runArtifactSetPreflight(descriptor, deps) {
487
513
  return { ok: false, result: fail("not_repository_root") };
488
514
  }
489
515
  deps.log(` repository root: ${normalizedRoot}`);
490
- // A clean worktree is still required, so the person is not surprised by a
491
- // proposal built while their own changes are in flight.
492
- //
493
- // `--untracked-files=all` rather than the default: git otherwise COLLAPSES an
494
- // untracked directory to a single `?? .bridge/` entry. The output is read RAW
495
- // (untrimmed) because the first status column is significant, and exactly one
496
- // path — the install manifest, by full name — is tolerated.
497
- const status = await captureRawStdout(deps.runGit, ["status", "--porcelain", "--untracked-files=all"]);
498
- if (status === null)
499
- return { ok: false, result: fail("git_failed") };
500
- const dirty = status
501
- .split("\n")
502
- .map((line) => line.replace(/\r$/, ""))
503
- .filter((line) => line.trim().length > 0)
504
- .filter((line) => !isInstallStateLine(line));
505
- if (dirty.length > 0)
506
- return { ok: false, result: fail("worktree_not_clean") };
507
- deps.log(" worktree: clean");
508
516
  const ghDefaultBranch = await captureStdout(deps.runGh, [
509
517
  "repo",
510
518
  "view",
@@ -538,6 +546,85 @@ export async function runArtifactSetPreflight(descriptor, deps) {
538
546
  return { ok: false, result: fail("repository_identity_mismatch") };
539
547
  }
540
548
  deps.log(` gh: authenticated for ${ghRepository}`);
549
+ return {
550
+ ok: true,
551
+ identity: {
552
+ repositoryRoot: normalizedRoot,
553
+ defaultBranch: ghDefaultBranch,
554
+ remoteName,
555
+ repository: ghRepository,
556
+ },
557
+ };
558
+ }
559
+ /** The default branch head from the remote (`ls-remote`, no fetch), or the refusal. */
560
+ async function readDefaultBranchHead(deps, identity) {
561
+ const sha = await readRemoteBranchSha(deps, identity.remoteName, identity.defaultBranch);
562
+ if (sha === undefined)
563
+ return { ok: false, result: fail("remote_state_unverifiable") };
564
+ if (sha === null)
565
+ return { ok: false, result: fail("default_branch_unresolved") };
566
+ return { ok: true, sha };
567
+ }
568
+ /**
569
+ * Capture the remote default branch as one immutable snapshot. Read-only, and the
570
+ * one owner of how that head is resolved: the preflight below reads it through
571
+ * the same functions rather than a second resolver.
572
+ */
573
+ export async function captureDefaultBranchSnapshot(deps) {
574
+ const local = await readLocalIdentity(deps);
575
+ if (!local.ok)
576
+ return local;
577
+ const head = await readDefaultBranchHead(deps, local.identity);
578
+ if (!head.ok)
579
+ return head;
580
+ return { ok: true, snapshot: { ...local.identity, defaultBranchSha: head.sha } };
581
+ }
582
+ /**
583
+ * Read one file's RAW bytes at the snapshot's immutable commit.
584
+ *
585
+ * Shaped for {@link resolveRepositoryToolchains}'s reader: a confirmed 404 throws
586
+ * an `ENOENT` error (the file is absent), and anything else that is not a clean
587
+ * 200 throws a different error (the file could not be read), so an unreadable
588
+ * file is never mistaken for an absent one.
589
+ */
590
+ export async function readSnapshotFile(deps, snapshot, relPath) {
591
+ if (!isSafeManagedRelPath(relPath))
592
+ throw new Error("snapshot_path_refused");
593
+ const file = await readRemoteFile(deps, snapshot.repository, snapshot.defaultBranchSha, relPath);
594
+ if (file.kind === "present")
595
+ return file.content;
596
+ if (file.kind === "absent")
597
+ throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
598
+ throw new Error("snapshot_read_failed");
599
+ }
600
+ /**
601
+ * Run the complete read-only preflight for an artifact set.
602
+ *
603
+ * Every check here is a read: executables, repository root, default branch,
604
+ * remote and `gh` identity, set-specific options, the remote default-branch head
605
+ * (via `ls-remote`, no fetch), and each managed file's raw bytes at that head
606
+ * (via `gh api`). Nothing it calls creates a branch, writes a file, touches
607
+ * install state, fetches, commits, pushes, or opens a pull request. The person's
608
+ * working tree is not consulted: uncommitted or unpushed changes there neither
609
+ * block this preflight nor reach what it classifies.
610
+ *
611
+ * With a `snapshot`, the head is the snapshot's rather than a fresh read, and the
612
+ * repository and default branch must still be the ones it observed.
613
+ */
614
+ export async function runArtifactSetPreflight(descriptor, deps, snapshot) {
615
+ // Managed paths are constants; this guards a future edit, not today's input.
616
+ for (const artifact of descriptor.artifacts) {
617
+ if (!isSafeManagedRelPath(artifact.relPath))
618
+ return { ok: false, result: fail("write_failed") };
619
+ }
620
+ const local = await readLocalIdentity(deps);
621
+ if (!local.ok)
622
+ return { ok: false, result: local.result };
623
+ const { identity } = local;
624
+ if (snapshot !== undefined &&
625
+ (snapshot.repository !== identity.repository || snapshot.defaultBranch !== identity.defaultBranch)) {
626
+ return { ok: false, result: fail("default_branch_moved") };
627
+ }
541
628
  if (descriptor.validateOptions) {
542
629
  const checked = descriptor.validateOptions();
543
630
  if (!checked.ok)
@@ -547,25 +634,30 @@ export async function runArtifactSetPreflight(descriptor, deps) {
547
634
  }
548
635
  // The default branch head, read from the remote. A managed branch is never
549
636
  // the default branch; that is enforced again at push time.
550
- if (descriptor.installBranch === ghDefaultBranch || descriptor.upgradeBranch === ghDefaultBranch) {
637
+ if (descriptor.installBranch === identity.defaultBranch || descriptor.upgradeBranch === identity.defaultBranch) {
551
638
  return { ok: false, result: fail("default_branch_unresolved") };
552
639
  }
553
- const defaultBranchSha = await readRemoteBranchSha(deps, remoteName, ghDefaultBranch);
554
- if (defaultBranchSha === undefined)
555
- return { ok: false, result: fail("remote_state_unverifiable") };
556
- if (defaultBranchSha === null)
557
- return { ok: false, result: fail("default_branch_unresolved") };
558
- const classified = await classifyAtRemote(deps, descriptor, ghRepository, defaultBranchSha, false);
640
+ let defaultBranchSha;
641
+ if (snapshot !== undefined) {
642
+ defaultBranchSha = snapshot.defaultBranchSha;
643
+ }
644
+ else {
645
+ const head = await readDefaultBranchHead(deps, identity);
646
+ if (!head.ok)
647
+ return { ok: false, result: head.result };
648
+ defaultBranchSha = head.sha;
649
+ }
650
+ const classified = await classifyAtRemote(deps, descriptor, identity.repository, defaultBranchSha, false);
559
651
  if (!classified.ok)
560
652
  return { ok: false, result: classified.result };
561
653
  return {
562
654
  ok: true,
563
655
  preflight: {
564
- repositoryRoot: normalizedRoot,
565
- defaultBranch: ghDefaultBranch,
656
+ repositoryRoot: identity.repositoryRoot,
657
+ defaultBranch: identity.defaultBranch,
566
658
  defaultBranchSha,
567
- remoteName,
568
- repository: ghRepository,
659
+ remoteName: identity.remoteName,
660
+ repository: identity.repository,
569
661
  classification: classified.classification,
570
662
  proposals: classified.proposals,
571
663
  },
@@ -573,35 +665,80 @@ export async function runArtifactSetPreflight(descriptor, deps) {
573
665
  }
574
666
  /**
575
667
  * Inspect the managed pull request and branch for `branch`. Read-only.
576
- * Returns `null` when the way is clear, or the outcome to report.
577
668
  */
578
669
  async function inspectManagedState(deps, descriptor, preflight, branch, upgrade) {
579
670
  const managedPaths = descriptor.artifacts.map((a) => a.relPath);
671
+ const report = (result) => ({ state: "report", result });
580
672
  const lookup = await findExistingManagedPr(deps, preflight.repository, branch);
581
673
  if (lookup.kind === "lookup_failed")
582
- return fail("remote_state_unverifiable", { branch });
674
+ return report(fail("remote_state_unverifiable", { branch }));
583
675
  if (lookup.kind === "found") {
584
676
  if (!existingPrIsExpected(lookup.pr, branch, preflight.defaultBranch, managedPaths)) {
585
- return fail("existing_pr_unverifiable", { branch });
677
+ return report(fail("existing_pr_unverifiable", { branch }));
586
678
  }
587
679
  const matches = await prContentMatchesProposal(deps, preflight.repository, lookup.pr, preflight.proposals);
588
680
  if (matches === null)
589
- return fail("existing_pr_unverifiable", { branch, prUrl: lookup.pr.url });
681
+ return report(fail("existing_pr_unverifiable", { branch, prUrl: lookup.pr.url }));
590
682
  if (!matches)
591
- return fail("existing_pr_differs", { branch, prUrl: lookup.pr.url });
592
- return { outcome: "existing-pr", branch, prUrl: lookup.pr.url, upgrade, warnings: [] };
683
+ return report(fail("existing_pr_differs", { branch, prUrl: lookup.pr.url }));
684
+ return report({ outcome: "existing-pr", branch, prUrl: lookup.pr.url, upgrade, warnings: [] });
593
685
  }
594
686
  // Independently of PR discovery: a pushed managed branch with no open PR.
595
687
  const branchSha = await readRemoteBranchSha(deps, preflight.remoteName, branch);
596
688
  if (branchSha === undefined)
597
- return fail("remote_state_unverifiable", { branch });
689
+ return report(fail("remote_state_unverifiable", { branch }));
598
690
  if (branchSha !== null) {
599
- return fail("managed_branch_without_pr", {
691
+ // Matching content needs only its pull request; differing content is never
692
+ // reused, overwritten, or deleted.
693
+ const matches = await prContentMatchesProposal(deps, preflight.repository, { url: "", headRefName: branch, headRefOid: branchSha, baseRefName: "", isCrossRepository: null, files: [] }, preflight.proposals);
694
+ if (matches === null)
695
+ return report(fail("remote_state_unverifiable", { branch }));
696
+ if (matches) {
697
+ // The same rule the open-PR path enforces: ONLY managed files may differ from
698
+ // the default branch, or the consent shown would not describe the pull request.
699
+ const changed = await readBranchChangedFiles(deps, preflight.repository, preflight.defaultBranchSha, branchSha);
700
+ if (changed === null)
701
+ return report(fail("remote_state_unverifiable", { branch }));
702
+ const managed = new Set(managedPaths);
703
+ if (changed.length > 0 && changed.every((f) => managed.has(f)))
704
+ return { state: "branch_ready", sha: branchSha };
705
+ }
706
+ return report(fail("managed_branch_without_pr", {
707
+ branch,
708
+ compareUrl: compareUrl(preflight.repository, preflight.defaultBranch, branch),
709
+ }));
710
+ }
711
+ return { state: "clear" };
712
+ }
713
+ /** Open the setup pull request from `branch` into the default branch with the customer's own `gh`. */
714
+ async function openArtifactSetPullRequest(deps, descriptor, preflight, branch, upgrade, managedPaths) {
715
+ const prUrl = await captureStdout(deps.runGh, [
716
+ "pr",
717
+ "create",
718
+ "--repo",
719
+ preflight.repository,
720
+ "--base",
721
+ preflight.defaultBranch,
722
+ "--head",
723
+ branch,
724
+ "--title",
725
+ upgrade ? descriptor.upgradePrTitle : descriptor.installPrTitle,
726
+ "--body",
727
+ descriptor.renderPrBody(upgrade),
728
+ ]);
729
+ if (!prUrl) {
730
+ return fail("pr_open_failed", {
600
731
  branch,
601
732
  compareUrl: compareUrl(preflight.repository, preflight.defaultBranch, branch),
602
733
  });
603
734
  }
604
- return null;
735
+ return {
736
+ outcome: upgrade ? "upgrade-pr-opened" : "installed-pr-opened",
737
+ branch,
738
+ prUrl,
739
+ artifacts: managedPaths,
740
+ warnings: [],
741
+ };
605
742
  }
606
743
  // ---------------------------------------------------------------------------
607
744
  // Merge-workflow descriptor
@@ -685,7 +822,9 @@ export function buildMergeWorkflowArtifactSet(codeOwner) {
685
822
  }
686
823
  return { ok: true, progress: [` code owner: ${owner}`] };
687
824
  },
688
- consentPrompt: (plan) => `Create branch ${plan.branch}, write ${plan.artifacts.length} files, commit, push, and open a pull request? [y/N] `,
825
+ consentPrompt: (plan) => plan.branchReuse === true
826
+ ? `Open a pull request from the existing branch ${plan.branch}? [y/N] `
827
+ : `Create branch ${plan.branch}, write ${plan.artifacts.length} files, commit, push, and open a pull request? [y/N] `,
689
828
  artifacts: [
690
829
  {
691
830
  relPath: MERGE_WORKFLOW_PATH,
@@ -724,6 +863,10 @@ export async function runMergeWorkflowPreflight(deps, options) {
724
863
  /** How many times consent is asked before a still-moving default branch stops the run. */
725
864
  const MAX_CONSENT_ROUNDS = 3;
726
865
  function defaultConsentPrompt(plan) {
866
+ if (plan.branchReuse === true) {
867
+ return (`Open a pull request from the existing branch ${plan.branch} into ${plan.defaultBranch} ` +
868
+ `(${plan.artifacts.join(", ")}; nothing is pushed)? [y/N] `);
869
+ }
727
870
  return (`Create branch ${plan.branch} from ${plan.defaultBranch} in a temporary worktree, write ` +
728
871
  `${plan.artifacts.join(", ")}, commit "${plan.commitSubject}", push to ` +
729
872
  `${plan.remoteName}/${plan.branch}, and open a pull request into ${plan.defaultBranch}? [y/N] `);
@@ -775,7 +918,7 @@ async function pathIsSafeInWorktree(deps, worktree, relPath) {
775
918
  * branch to tidy up is a destructive act taken on incomplete information.
776
919
  */
777
920
  export async function installArtifactSet(descriptor, options, deps) {
778
- const pre = await runArtifactSetPreflight(descriptor, deps);
921
+ const pre = await runArtifactSetPreflight(descriptor, deps, options.snapshot);
779
922
  if (!pre.ok)
780
923
  return pre.result;
781
924
  let preflight = pre.preflight;
@@ -799,6 +942,7 @@ export async function installArtifactSet(descriptor, options, deps) {
799
942
  let upgrade = false;
800
943
  let branch = "";
801
944
  let commitSubject = "";
945
+ let reusableBranch = false;
802
946
  // Consent covers one plan at one default-branch head. When the default branch
803
947
  // moves after consent and the plan changes, the new plan is shown and consent
804
948
  // is asked again; a branch that keeps moving stops with default_branch_moved.
@@ -807,8 +951,9 @@ export async function installArtifactSet(descriptor, options, deps) {
807
951
  branch = upgrade ? descriptor.upgradeBranch : descriptor.installBranch;
808
952
  commitSubject = upgrade ? descriptor.upgradeCommitSubject : descriptor.installCommitSubject;
809
953
  const managed = await inspectManagedState(deps, descriptor, preflight, branch, upgrade);
810
- if (managed)
811
- return managed;
954
+ if (managed.state === "report")
955
+ return managed.result;
956
+ reusableBranch = managed.state === "branch_ready";
812
957
  const plan = {
813
958
  branch,
814
959
  upgrade,
@@ -816,16 +961,19 @@ export async function installArtifactSet(descriptor, options, deps) {
816
961
  commitSubject,
817
962
  remoteName: preflight.remoteName,
818
963
  defaultBranch: preflight.defaultBranch,
964
+ ...(reusableBranch ? { branchReuse: true } : {}),
819
965
  };
820
966
  deps.log("");
821
967
  if (round > 0)
822
968
  deps.log(`${preflight.defaultBranch} moved since you approved, and the plan changed.`);
823
969
  deps.log(upgrade ? "Planned upgrade:" : "Planned installation:");
824
- deps.log(` branch: ${branch}`);
970
+ deps.log(` branch: ${branch}${reusableBranch ? " (already pushed with these files; it is not pushed again)" : ""}`);
825
971
  for (const relPath of managedPaths)
826
972
  deps.log(` file: ${relPath}`);
827
- deps.log(` commit: ${commitSubject}`);
828
- deps.log(` push: ${preflight.remoteName}/${branch} (your git identity)`);
973
+ if (!reusableBranch) {
974
+ deps.log(` commit: ${commitSubject}`);
975
+ deps.log(` push: ${preflight.remoteName}/${branch} (your git identity)`);
976
+ }
829
977
  deps.log(` pull request: into ${preflight.defaultBranch} (your gh identity)`);
830
978
  if (options.dryRun) {
831
979
  deps.log("");
@@ -850,6 +998,10 @@ export async function installArtifactSet(descriptor, options, deps) {
850
998
  return fail("git_failed", { branch });
851
999
  if (fetchedSha === preflight.defaultBranchSha)
852
1000
  break;
1001
+ // The caller derived its inputs from one snapshot head: a different head is
1002
+ // a different build, so the run stops and is re-run from a fresh snapshot.
1003
+ if (options.snapshot !== undefined)
1004
+ return fail("default_branch_moved", { branch });
853
1005
  // The default branch moved: re-inspect at the fetched head. An unchanged
854
1006
  // plan proceeds from the new head under the consent already given.
855
1007
  const again = await classifyAtRemote(deps, descriptor, preflight.repository, fetchedSha, true);
@@ -867,6 +1019,10 @@ export async function installArtifactSet(descriptor, options, deps) {
867
1019
  if (round + 1 >= MAX_CONSENT_ROUNDS)
868
1020
  return fail("default_branch_moved", { branch });
869
1021
  }
1022
+ // A pushed managed branch whose files already match needs only its pull request.
1023
+ if (reusableBranch) {
1024
+ return await openArtifactSetPullRequest(deps, descriptor, preflight, branch, upgrade, managedPaths);
1025
+ }
870
1026
  const makeTempDir = deps.makeTempDir ?? (() => mkdtemp(join(tmpdir(), `bridge-${descriptor.setName}-`)));
871
1027
  const removeDir = deps.removeDir ?? ((dir) => rm(dir, { recursive: true, force: true }));
872
1028
  let tempRoot;
@@ -932,9 +1088,12 @@ export async function installArtifactSet(descriptor, options, deps) {
932
1088
  }
933
1089
  // Immediately before push: nobody else created the managed branch or PR.
934
1090
  const raced = await inspectManagedState(deps, descriptor, preflight, branch, upgrade);
935
- if (raced) {
936
- if (raced.outcome === "failed" && raced.reason === "remote_state_unverifiable")
937
- return raced;
1091
+ if (raced.state !== "clear") {
1092
+ if (raced.state === "report" &&
1093
+ raced.result.outcome === "failed" &&
1094
+ raced.result.reason === "remote_state_unverifiable") {
1095
+ return raced.result;
1096
+ }
938
1097
  return fail("managed_state_changed", { branch });
939
1098
  }
940
1099
  if (branch === preflight.defaultBranch)
@@ -948,33 +1107,7 @@ export async function installArtifactSet(descriptor, options, deps) {
948
1107
  ]))) {
949
1108
  return fail("git_failed", { branch });
950
1109
  }
951
- const prUrl = await captureStdout(deps.runGh, [
952
- "pr",
953
- "create",
954
- "--repo",
955
- preflight.repository,
956
- "--base",
957
- preflight.defaultBranch,
958
- "--head",
959
- branch,
960
- "--title",
961
- upgrade ? descriptor.upgradePrTitle : descriptor.installPrTitle,
962
- "--body",
963
- descriptor.renderPrBody(upgrade),
964
- ]);
965
- if (!prUrl) {
966
- return fail("pr_open_failed", {
967
- branch,
968
- compareUrl: compareUrl(preflight.repository, preflight.defaultBranch, branch),
969
- });
970
- }
971
- return {
972
- outcome: upgrade ? "upgrade-pr-opened" : "installed-pr-opened",
973
- branch,
974
- prUrl,
975
- artifacts: managedPaths,
976
- warnings: [],
977
- };
1110
+ return await openArtifactSetPullRequest(deps, descriptor, preflight, branch, upgrade, managedPaths);
978
1111
  };
979
1112
  let result;
980
1113
  try {