@bridge_gpt/mcp-server 0.2.73 → 0.2.75

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (123) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agent-launchers/prompt.js +9 -21
  4. package/build/agents.generated.js +4 -4
  5. package/build/authored-plan.js +542 -0
  6. package/build/bridge-config.js +7 -1
  7. package/build/bridge-permissions.js +11 -0
  8. package/build/command-provisioning.js +4 -3
  9. package/build/commands.generated.js +6 -6
  10. package/build/conductor/bridge-api-client.js +692 -47
  11. package/build/conductor/command-drift.js +1 -1
  12. package/build/conductor/declared-extras.js +335 -0
  13. package/build/conductor/doctor.js +2 -0
  14. package/build/conductor/driver-pass-output.js +104 -0
  15. package/build/conductor/driver-pass.js +571 -0
  16. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  17. package/build/conductor/epic-implementer-cli.js +370 -93
  18. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  19. package/build/conductor/epic-server-sfcc.js +58 -80
  20. package/build/conductor/epic-server.js +57 -4
  21. package/build/conductor/gate-discovery.js +253 -13
  22. package/build/conductor/gate-settings-review.js +58 -25
  23. package/build/conductor/launch-plan.js +58 -12
  24. package/build/conductor/open-decision-phrases.js +50 -0
  25. package/build/conductor/prerequisite-inputs.js +181 -14
  26. package/build/connect-github-api.js +18 -0
  27. package/build/connect-github.js +35 -18
  28. package/build/credential-delivery.js +280 -0
  29. package/build/credential-launch-safety.js +142 -0
  30. package/build/credential-materialization.js +91 -16
  31. package/build/credential-references-node-deps.js +29 -0
  32. package/build/credential-references.js +1394 -0
  33. package/build/credential-references.test-fixtures.js +211 -0
  34. package/build/credential-scan-conventions.js +145 -0
  35. package/build/credential-scan.js +517 -0
  36. package/build/credential-store.js +50 -0
  37. package/build/credentials-cli.js +252 -3
  38. package/build/dependency-install-declarations.js +47 -1
  39. package/build/docs.generated.js +8 -1
  40. package/build/doctor.js +41 -0
  41. package/build/drive-epic.js +684 -49
  42. package/build/epic-branch-ci-summary.js +18 -1
  43. package/build/epic-capability-statement.js +71 -3
  44. package/build/epic-ci-workflow-drift.js +52 -13
  45. package/build/epic-ci-workflow-install.js +31 -6
  46. package/build/epic-ci-workflow-v3.js +273 -0
  47. package/build/epic-ci-workflow.js +129 -7
  48. package/build/epic-implementer-bin.js +288 -83
  49. package/build/epic-implementer-bundle-cli.js +61 -0
  50. package/build/epic-implementer-claude-hook-bin.js +1 -1
  51. package/build/epic-implementer-env.js +3 -4
  52. package/build/epic-integration-pr.js +5 -2
  53. package/build/epic-launch-context.js +102 -7
  54. package/build/epic-server-record.js +30 -15
  55. package/build/executor/completion-contract.js +24 -1
  56. package/build/executor/credential-delivery-step.js +168 -0
  57. package/build/executor/deps.js +3 -1
  58. package/build/executor/env.js +39 -1
  59. package/build/executor/epic-server-context.js +23 -7
  60. package/build/executor/gate-qualification-job.js +193 -23
  61. package/build/executor/gate-qualification-tests-ran.js +232 -0
  62. package/build/executor/guarded-fast-forward-push.js +13 -8
  63. package/build/executor/job-runner.js +167 -738
  64. package/build/executor/job-type-wrappers.js +734 -0
  65. package/build/executor/permissions.js +85 -3
  66. package/build/executor/preflight.js +6 -2
  67. package/build/executor/process-containment.js +8 -1
  68. package/build/executor/prompt-spec.js +37 -3
  69. package/build/executor/required-verification.js +28 -2
  70. package/build/executor/runner.js +4 -1
  71. package/build/executor/types.js +9 -0
  72. package/build/executor/worker-database.js +6 -1
  73. package/build/executor/worker-guard-hook.js +24 -2
  74. package/build/executor-launch.js +4 -2
  75. package/build/generated/ticket-status.js +20 -0
  76. package/build/git-exclude-lock.js +187 -0
  77. package/build/index.js +589 -326
  78. package/build/install-bridge-conductor-answers.js +112 -22
  79. package/build/install-bridge-conductor-apply.js +38 -1
  80. package/build/install-bridge-conductor-assessment.js +482 -53
  81. package/build/install-bridge-conductor-compact.js +29 -2
  82. package/build/install-bridge-conductor-contracts.js +10 -1
  83. package/build/install-bridge-conductor-gate.js +379 -89
  84. package/build/install-bridge-conductor-setup.js +46 -8
  85. package/build/install-bridge-conductor-trial-report.js +170 -0
  86. package/build/install-bridge-conductor.js +925 -141
  87. package/build/install-bridge.js +88 -11
  88. package/build/install-doctor.js +38 -8
  89. package/build/install-sfcc-detection.js +120 -0
  90. package/build/install-sfcc-setup.js +185 -0
  91. package/build/mcp-grant-candidates.js +108 -96
  92. package/build/mcp-invoke.js +168 -4
  93. package/build/mcp-provisioning.js +21 -4
  94. package/build/mcp-server-invocation.js +13 -0
  95. package/build/merge-workflow-install.js +9 -1
  96. package/build/pipelines.generated.js +8 -7
  97. package/build/plan-generation.js +17 -0
  98. package/build/plane/status.js +8 -2
  99. package/build/printed-remedy-commands.js +59 -0
  100. package/build/project-root.js +40 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-state-paths.js +5 -2
  103. package/build/repository-toolchains.js +16 -7
  104. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  105. package/build/setup-epic.js +126 -16
  106. package/build/sfcc/credentials.js +3 -2
  107. package/build/sfcc/hostname.js +98 -2
  108. package/build/sfcc/tool-wrapper.js +6 -95
  109. package/build/start-tickets.js +193 -29
  110. package/build/test-support/executor-source-files.js +200 -0
  111. package/build/testing-config-client.js +25 -2
  112. package/build/third-party-mcp-targets.js +35 -4
  113. package/build/v2-readiness-requirements.js +5 -1
  114. package/build/version.generated.js +3 -3
  115. package/build/with-credentials.js +208 -0
  116. package/build/worker-guard-hook-bin.js +2 -2
  117. package/build/worktree-credential-delivery.js +340 -0
  118. package/docs/EPIC-IMPLEMENTER.md +4 -4
  119. package/docs/install/github-app.md +79 -92
  120. package/package.json +1 -1
  121. package/build/conductor/epic-reconcile.js +0 -603
  122. package/build/conductor/epic-runtime.js +0 -2020
  123. package/build/conductor/epic-state.js +0 -774
@@ -1,11 +1,14 @@
1
1
  import { writeJsonDocument, flushProcessStdout } from './conductor/json-output.js';
2
2
  import { INSTALL_ASSESSMENT_SCHEMA_VERSION, } from './install-bridge-conductor-contracts.js';
3
- import { buildInstallAssessment, buildInstallChoices, epicBranchCiStateText, indexDisplayStatus, } from './install-bridge-conductor-assessment.js';
3
+ import { buildInstallAssessment, buildInstallChoices, recommendEpicServer, buildInstallVerdict, buildProposalPresentation, classifyMergeTestProtection, dependencyInstallDetails, epicBranchCiIncludeRestsOnSetupPr, epicBranchCiStateText, indexDisplayStatus, savedStatusLabel, } from './install-bridge-conductor-assessment.js';
4
+ import { sanitizeCommandText } from './install-bridge-conductor-trial-report.js';
5
+ import { readConductorSavedTestCommands, saveConductorSavedTestCommands, } from './conductor/bridge-api-client.js';
4
6
  import { GITHUB_ACTIONS_TRIGGER_ADAPTER, recognizeAppliedEdit, selectTriggerEdit, sha256Hex, } from './ci-trigger-adapters.js';
5
7
  import { detectCiSystems } from './ci-system-detection.js';
6
- import { describeDeclinedCiChange, describeProposedCiChange } from './epic-branch-ci-summary.js';
8
+ import { presentTrialResult } from './install-bridge-conductor-trial-report.js';
9
+ import { describeDeclinedCiChange, describeProposedCiChange, describeUnopenedSetupCredit } from './epic-branch-ci-summary.js';
7
10
  import { buildCompactApply, buildCompactAssessment, buildCompactProposal } from './install-bridge-conductor-compact.js';
8
- import { decisionFor, normalizeInstallAnswers, parseAnswersText, readAnswersSource, } from './install-bridge-conductor-answers.js';
11
+ import { decisionFor, normalizeInstallAnswers, parseAnswerValue, parseAnswersText, readAnswersSource, } from './install-bridge-conductor-answers.js';
9
12
  import { applyInstallProposal, } from './install-bridge-conductor-apply.js';
10
13
  import { previewConductorSetupPolicy, applyConductorSetupPolicy, fetchConductorSetupPolicy, fetchConductorGateProfile, fetchConductorRepositoryLearning, ConductorSetupPolicyError, SETUP_POLICY_PROTOCOL } from "./conductor/bridge-api-client.js";
11
14
  import { askPlainConsent, askPlainSetupQuestion, askSetupQuestion, createPlainInputSession, setupConsentQuestion, } from "./setup-question.js";
@@ -130,7 +133,7 @@ import { withSetupProgress } from "./setup-progress.js";
130
133
  * stop; everything else it adds only warns.
131
134
  */
132
135
  import { PRINTED_INSTALL_COMMAND, PRINTED_QUALIFY_GATE_COMMAND } from "./printed-remedy-commands.js";
133
- import { collectEpicBranchCi, confirmRequestFor, planDeclarationSelections, describeGateRestoration, desiredFromStored, emptyConductorGateFlags, hasExplicitGateInput, parseLocalCommandFlag, parseEpicBranchCiDecisionFlag, parseMigrationGuardFlag, planManagedProviderGate, reportLearnedCommandTrial, describePolicyChanges, resolveConductorGate, runEpicBranchCiInspection, runGateConsequenceSummary, runClearConductorGate, runConductorGateQualification, runLearnedTestCommandTrial, runQualifyConductorGate, validateConductorGateFlags, } from "./install-bridge-conductor-gate.js";
136
+ import { collectEpicBranchCi, confirmRequestFor, planDeclarations, resolveEffectiveDependencyInstall, describeGateRestoration, desiredFromStored, emptyConductorGateFlags, hasExplicitGateInput, parseLocalCommandFlag, parseEpicBranchCiDecisionFlag, parseMigrationGuardFlag, planManagedProviderGate, reportLearnedCommandTrial, isInformationalNoCommandReason, NO_COMMAND_INFORMATION_TEXT, CANDIDATE_REJECTION_FIX, formatSetupPolicyRefusal, describePolicyChanges, resolveConductorGate, runEpicBranchCiInspection, runGateConsequenceSummary, runClearConductorGate, mapExemptionOutcomeToWriteResult, runConductorGateQualification, runLearnedTestCommandTrial, runQualifyConductorGate, validateConductorGateFlags, } from "./install-bridge-conductor-gate.js";
134
137
  import { classifyEpicPullRequestTrigger, readDefaultBranchRequiredChecksViaGh, readPullRequestBranchFilters, } from "./conductor/epic-branch-ci-inspection.js";
135
138
  import { describeGateConsequence } from "./conductor/readiness-sections.js";
136
139
  import { fetchConductorReadiness, } from "./conductor/bridge-api-client.js";
@@ -143,11 +146,17 @@ import { describeToolchainResolution, resolveRepositoryToolchains, } from "./rep
143
146
  import { detectTestCommand } from "./test-command-detection.js";
144
147
  import { TestCommandValidationError, validateTestCommand, } from "./test-command-validation.js";
145
148
  import { EPIC_CI_WORKFLOW_PATH, EPIC_IMPLEMENTER_CI_CHECK_NAME, renderEpicImplementerCiWorkflow } from "./epic-ci-workflow.js";
149
+ import { parseDependencyInstallStrict, sameDependencyInstall, } from "./dependency-install-declarations.js";
150
+ import { pyprojectPathFor, scanDeclaredExtras } from "./conductor/declared-extras.js";
151
+ import { discoverLocalTestCandidates } from "./conductor/gate-discovery.js";
152
+ import { readLearnedInstructions } from "./testing-config-client.js";
146
153
  import { normalizeStorefrontOrigin, isValidCredentialReference, isValidSfccSandboxId, sameEpicServerRecord, } from "./epic-server-record.js";
154
+ import { detectSfccRepository } from "./install-sfcc-detection.js";
155
+ import { SANDBOX_SKIPPED_LINE, WORKER_UPLOAD_ADVISORY, collectCredentialEvidence, credentialQuestionLines, credentialReferenceAdvisories, describeSfccUpload, isSfccUploadCapable, recheckSfccSandboxId, runSfccUploadCheck, sfccRecommendedDefinitionIds, suggestedCredentialEntry, } from "./install-sfcc-setup.js";
147
156
  import { CANDIDATE_EXCLUSION_TEXT, CANDIDATE_ORIGIN_LABEL, describeInventoryExclusions, GRANT_SELECTION_PROMPT, parseGrantSelection, } from "./mcp-grant-candidates.js";
148
157
  import { buildEpicCapabilityStatement } from "./epic-capability-statement.js";
149
158
  import { MCP_GRANT_MAX_SERVERS } from "./mcp-grant.js";
150
- import { advisoryFindingLines, assessIndexFreshness, assessSetupIndex, catalogLabel, NPM_SETUP_LAUNCHER, closedSetupPullRequestNotice, compareIndexedToMerge, planSetupFixes, projectSetupItems, readSetupPullRequest, renderSetupAssessment, setupItemRemedy, setupVerdictLine, unmetBlockingItems, } from "./install-bridge-conductor-setup.js";
159
+ import { advisoryFindingLines, assessIndexFreshness, assessSetupIndex, catalogLabel, NPM_SETUP_LAUNCHER, closedSetupPullRequestNotice, compareIndexedToMerge, planSetupFixes, projectSetupItems, readSetupPullRequest, renderSetupAssessment, deriveCompactReadiness, setupItemRemedy, setupVerdictLine, unmetBlockingItems, } from "./install-bridge-conductor-setup.js";
151
160
  import { CONDUCTOR_BIN_UNRESOLVED_ERROR, MANAGED_HOOK_NAMES, } from "./conductor/git-hooks.js";
152
161
  import os from "node:os";
153
162
  import path from "node:path";
@@ -220,7 +229,7 @@ export function getInstallBridgeConductorUsage() {
220
229
  " - which indexing branch to use, only when an existing different branch makes",
221
230
  " the choice unclear;",
222
231
  " - adding Bridge's own GitHub workflow, once, only for a repository with no CI of",
223
- " its own and a test command Bridge has proven (then the setup pull request has",
232
+ " its own and a test command that passed Bridge's trial run (then the setup pull request has",
224
233
  " its own consent);",
225
234
  " - storing a GitHub merge token on this computer (read with no echo).",
226
235
  "Setup never asks for a test command. The destination is displayed without a",
@@ -261,8 +270,8 @@ export function getInstallBridgeConductorUsage() {
261
270
  "stored as watched members of the gate. A red watched check stops a merge; a",
262
271
  "missing one only warns. A gate you already confirmed is kept as it is.",
263
272
  "",
264
- "Bridge's workflow is optional: for a repository with no CI of its own and a proven",
265
- "test command, setup offers it once (default no). It runs only for pull requests",
273
+ "Bridge's workflow is optional: for a repository with no CI of its own and a test",
274
+ "command that passed the trial run, setup offers it once (default no). It runs only for pull requests",
266
275
  "into epic/** branches, and its check is added to the gate only after the setup",
267
276
  "pull request is open. The pull request is built from a clean copy of your default",
268
277
  "branch, so uncommitted or unpushed changes in your folder never block it or enter it.",
@@ -274,7 +283,7 @@ export function getInstallBridgeConductorUsage() {
274
283
  "are unchanged.",
275
284
  "",
276
285
  "Options:",
277
- " --test-command <command> Offer your own test command for Bridge to prove once;",
286
+ " --test-command <command> Offer your own test command for Bridge to try once;",
278
287
  " it replaces the stored local command only if it passes.",
279
288
  " Not combinable with --remove-merge-token or",
280
289
  " --clear-gate; may be given once.",
@@ -296,7 +305,7 @@ export function getInstallBridgeConductorUsage() {
296
305
  "Explicit gate flags are the complete requested gate. Otherwise a confirmed gate",
297
306
  "already stored is used unchanged; otherwise setup decides from facts, with no",
298
307
  "question: checks your CI has really reported become watched members, and the",
299
- "server adds a proven local command. Nothing is stored until you authorize the",
308
+ "server adds a local command that passed the trial run. Nothing is stored until you authorize the",
300
309
  "combined policy change that setup previews.",
301
310
  " --provider-check <name> An exact provider-reported check name (repeatable).",
302
311
  " Admission refuses one that has never reported.",
@@ -843,6 +852,53 @@ export function parseInstallBridgeConductorArgs(argv) {
843
852
  },
844
853
  };
845
854
  }
855
+ /** Collect the snapshot. Nothing here throws, refuses, or writes. */
856
+ export async function collectEpicServerSnapshot(deps, epicDeps, repoName, inventory) {
857
+ const fs = deps.gate?.discoveryFs;
858
+ const check = epicDeps.sfccUploadCheck;
859
+ const detection = fs === undefined || check === undefined ? null : await detectSfccRepository(fs, inventory);
860
+ const readCredentials = epicDeps.readCredentialReferences;
861
+ const credentials = readCredentials === undefined ? null : await collectCredentialEvidence(() => readCredentials(repoName));
862
+ let guidancePresent = false;
863
+ try {
864
+ guidancePresent = await epicDeps.guidancePresent();
865
+ }
866
+ catch {
867
+ guidancePresent = false;
868
+ }
869
+ let existingSandbox = null;
870
+ try {
871
+ const read = await epicDeps.readRecord(repoName);
872
+ if (read.state === "ok")
873
+ existingSandbox = read.record.sfcc ?? null;
874
+ }
875
+ catch {
876
+ existingSandbox = null;
877
+ }
878
+ const uploadCheck = detection?.detected === true && check !== undefined
879
+ ? await runSfccUploadCheck(check, { approvedSandboxId: existingSandbox?.sandbox_id ?? null, credentials })
880
+ : null;
881
+ return { detection, uploadCheck, credentials, guidancePresent, existingSandbox };
882
+ }
883
+ /** The same evidence for both setup paths, so their recommendation cannot differ. */
884
+ export function epicServerDecisionEvidence(current, applicable, snapshot, sandboxRecorded) {
885
+ if (snapshot === null)
886
+ return { current, applicable };
887
+ return {
888
+ current,
889
+ applicable,
890
+ guidancePresent: snapshot.guidancePresent,
891
+ ...(snapshot.detection !== null
892
+ ? { devScript: snapshot.detection.dev_script === true, sfcc: { detected: snapshot.detection.detected, uploadCheck: snapshot.uploadCheck } }
893
+ : {}),
894
+ ...(snapshot.credentials !== null ? { credentialReferences: snapshot.credentials.rows } : {}),
895
+ ...(sandboxRecorded ? { sandboxRecorded: true } : {}),
896
+ };
897
+ }
898
+ /** The definition ids to recommend, only for a confirmed SFCC repository. */
899
+ export function sfccGrantIds(snapshot, inventory) {
900
+ return snapshot?.detection?.detected === true && inventory !== null ? sfccRecommendedDefinitionIds(inventory) : [];
901
+ }
846
902
  /** Real host-local implementations of the launch-profile seams. */
847
903
  export function createDefaultLaunchProfileDeps(env) {
848
904
  const store = createNodeEpicLaunchStoreDeps(env);
@@ -2124,6 +2180,11 @@ export async function runInstallBridgeConductorCli(argv, deps) {
2124
2180
  ...(parts.digest !== undefined ? { proposal_digest: parts.digest } : {}),
2125
2181
  ...(parts.refusal !== undefined ? { refusal: parts.refusal } : {}),
2126
2182
  ...(parts.apply !== undefined ? { apply: parts.apply } : {}),
2183
+ ...(parts.proposalPresentation !== undefined ? { proposal_presentation: parts.proposalPresentation } : {}),
2184
+ ...(parts.applyPresentation !== undefined ? { apply_presentation: parts.applyPresentation } : {}),
2185
+ ...(namedOutcome === REPOSITORY_NOT_LEARNED_OUTCOME && parts.missingLearnedFields !== undefined && parts.missingLearnedFields.length > 0
2186
+ ? { missing_learned_fields: parts.missingLearnedFields }
2187
+ : {}),
2127
2188
  };
2128
2189
  // BAPI-1653: the compact view is chosen here, at the JSON-output boundary, from the
2129
2190
  // invocation mode. A refused apply still gets the apply view.
@@ -2664,7 +2725,7 @@ async function collectSetupEvidence(deps, setup, access, readiness, inputs) {
2664
2725
  let toolchains = null;
2665
2726
  if (storedCommand !== null && inputs.githubSignIn === "signed_in") {
2666
2727
  toolchains = await inputs.readToolchains();
2667
- workflow = await assessWorkflow(setup, storedCommand, toolchains, inputs.snapshot, workflowWanted);
2728
+ workflow = await assessWorkflow(setup, storedCommand, toolchains, inputs.snapshot, workflowWanted, inputs.dependencyInstall ?? []);
2668
2729
  }
2669
2730
  // The setup pull request and, once it merged, the index.
2670
2731
  let setupPullRequest = { state: "unknown" };
@@ -2763,7 +2824,9 @@ function toolchainInspectionRemedy(resolution) {
2763
2824
  * want it is not blocked because its dependency files could not be read, since no
2764
2825
  * workflow is going to be generated from them.
2765
2826
  */
2766
- async function assessWorkflow(setup, testCommand, toolchains, snapshot, workflowWanted) {
2827
+ async function assessWorkflow(setup, testCommand, toolchains, snapshot, workflowWanted,
2828
+ /** BAPI-1677 — the sealed install entries. Never derived here. */
2829
+ dependencyInstall = []) {
2767
2830
  // No snapshot (or no way to read it) is uncertainty, never a reason to guess
2768
2831
  // the toolchains from the person's folder.
2769
2832
  if (toolchains === null || snapshot === null)
@@ -2773,7 +2836,7 @@ async function assessWorkflow(setup, testCommand, toolchains, snapshot, workflow
2773
2836
  }
2774
2837
  let result;
2775
2838
  try {
2776
- result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true, snapshot });
2839
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: true, quiet: true, snapshot, ...dependencyInstallOption(dependencyInstall) });
2777
2840
  }
2778
2841
  catch {
2779
2842
  return { state: "unknown" };
@@ -3026,9 +3089,9 @@ decision) {
3026
3089
  try {
3027
3090
  preview = await previewConductorSetupPolicy(access, request, deps.postJson);
3028
3091
  }
3029
- catch {
3092
+ catch (error) {
3030
3093
  deps.log("Deferred: combined setup policy is unavailable or unsupported. Rerun with a compatible server; ask a bootstrap administrator if this persists.");
3031
- return { status: "deferred" };
3094
+ return { status: "deferred", ...(error instanceof ConductorSetupPolicyError ? { refusal: error.reason } : {}) };
3032
3095
  }
3033
3096
  // One plain line per changed setting. The before → after JSON is a diagnostic, shown only under --verbose.
3034
3097
  const logEffects = (effects) => {
@@ -3105,7 +3168,7 @@ decision) {
3105
3168
  }
3106
3169
  if (error instanceof ConductorSetupPolicyError && ["refused", "stale", "unsupported"].includes(error.reason)) {
3107
3170
  deps.log("Deferred: policy was refused or changed. Rerun for a fresh preview.");
3108
- return { status: "deferred" };
3171
+ return { status: "deferred", refusal: error.reason };
3109
3172
  }
3110
3173
  }
3111
3174
  try {
@@ -3113,14 +3176,14 @@ decision) {
3113
3176
  }
3114
3177
  catch {
3115
3178
  deps.log("Unknown—verify before retrying: policy apply could not be confirmed. Ask the bootstrap administrator.");
3116
- return { status: "unknown" };
3179
+ return { status: "unknown", refusal: "uncertain" };
3117
3180
  }
3118
3181
  if (uncertain
3119
3182
  || (appliedState !== undefined && !policyMatches(appliedState, current.state))
3120
3183
  || !policyMatches(preview.after, current.policy) || current.state.generation <= preview.state.generation
3121
3184
  || current.state.revision < preview.state.revision) {
3122
3185
  deps.log("Unknown—verify before retrying: coherent read-back does not confirm the intended complete policy.");
3123
- return { status: "unknown" };
3186
+ return { status: "unknown", refusal: "uncertain" };
3124
3187
  }
3125
3188
  if (applyWithoutQuestion) {
3126
3189
  deps.log("Policy applied (confirmed by reading it back).");
@@ -3154,10 +3217,16 @@ function logStoredCommandAndToolchains(deps, storedCommand, toolchains) {
3154
3217
  deps.log(` ${line}`);
3155
3218
  }
3156
3219
  }
3220
+ /** The installer option for sealed entries. None means the workflow's toolchain install lines. */
3221
+ function dependencyInstallOption(entries) {
3222
+ return entries.length > 0 ? { dependencyInstall: entries } : {};
3223
+ }
3157
3224
  /** Fix: open the one setup pull request through the artifact-set installer. */
3158
3225
  async function fixSetupPullRequest(deps, setup, testCommand, toolchains, snapshot, repository,
3159
3226
  /** BAPI-1638 — the approved `setup_pr` answer, which stands in for the installer's own question. */
3160
- consent) {
3227
+ consent,
3228
+ /** BAPI-1677 — the sealed install entries, read back from the stored gate. */
3229
+ dependencyInstall = []) {
3161
3230
  deps.log("");
3162
3231
  deps.log("CI workflow");
3163
3232
  if (toolchains === null || snapshot === null) {
@@ -3175,7 +3244,7 @@ consent) {
3175
3244
  let result;
3176
3245
  try {
3177
3246
  // The setup pull request has its OWN consent: it pushes a branch and opens a PR.
3178
- result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: false, snapshot }, (promptText) => askConsent(deps, promptText, "opening the setup pull request", undefined, consent));
3247
+ result = await setup.installCiWorkflow(testCommand, toolchains.toolchains, { dryRun: false, snapshot, ...dependencyInstallOption(dependencyInstall) }, (promptText) => askConsent(deps, promptText, "opening the setup pull request", undefined, consent));
3179
3248
  }
3180
3249
  catch {
3181
3250
  deps.log(" the setup pull request could not be prepared; re-run setup.");
@@ -3629,14 +3698,42 @@ function reportCredentialEndpointUnapproved(deps) {
3629
3698
  deps.errorLog(CREDENTIAL_ENDPOINT_UNAPPROVED_OUTCOME);
3630
3699
  deps.errorLog("Your saved Bridge key has not been approved for this address yet.");
3631
3700
  }
3701
+ /** Plain labels for the ten learned instruction identifiers (BAPI-1680). */
3702
+ const LEARNED_FIELD_LABELS = {
3703
+ architecture_instructions: "Architecture instructions",
3704
+ design_principles: "Design principles",
3705
+ review_instructions: "Code review instructions",
3706
+ documentation_instructions: "Documentation instructions",
3707
+ unit_testing_instructions: "Unit testing instructions",
3708
+ e2e_testing_instructions: "End-to-end testing instructions",
3709
+ frontend_correctness_standards: "Front-end code standards",
3710
+ backend_correctness_standards: "Back-end code standards",
3711
+ template_correctness_standards: "Template standards",
3712
+ style_correctness_standards: "Code style standards",
3713
+ };
3714
+ /** A plain label for a learned field identifier; a valid unknown one reads with spaces. */
3715
+ function learnedFieldLabel(name) {
3716
+ return Object.prototype.hasOwnProperty.call(LEARNED_FIELD_LABELS, name)
3717
+ ? LEARNED_FIELD_LABELS[name]
3718
+ : name.replace(/_/g, " ");
3719
+ }
3632
3720
  /** Print the plain stop for a repository that has not been (fully) learned. */
3633
- function reportRepositoryNotLearned(deps, fieldsSet) {
3721
+ function reportRepositoryNotLearned(deps, fieldsSet, missingFields = []) {
3634
3722
  deps.errorLog(REPOSITORY_NOT_LEARNED_OUTCOME);
3635
3723
  deps.errorLog(fieldsSet > 0
3636
3724
  ? "Bridge has not finished learning this repository."
3637
3725
  : "Bridge has not learned this repository yet.");
3638
3726
  deps.errorLog(`${fieldsSet > 0 ? "Finish" : "Run"} /learn-repository in Claude Code, wait for it to finish, then run this ` +
3639
3727
  "setup again. Bridge needs your project's standards to write useful code.");
3728
+ if (missingFields.length > 0) {
3729
+ deps.errorLog("These instructions are still missing:");
3730
+ for (const name of missingFields)
3731
+ deps.errorLog(` - ${learnedFieldLabel(name)}`);
3732
+ }
3733
+ deps.errorLog("Bridge uses its stored copy of these instructions. Editing local standards files, such as " +
3734
+ "docs/standards/*.md, does not update that copy.");
3735
+ deps.errorLog("To fill in one item by hand instead, use /teach-bridge and explain it in plain words. " +
3736
+ "Then run this setup again.");
3640
3737
  }
3641
3738
  /**
3642
3739
  * Read whether the repository has been learned. Returns `true` only for a
@@ -3653,7 +3750,10 @@ async function repositoryNotLearned(deps, access) {
3653
3750
  }
3654
3751
  if (learning.learned)
3655
3752
  return false;
3656
- reportRepositoryNotLearned(deps, learning.learned_fields_set);
3753
+ reportRepositoryNotLearned(deps, learning.learned_fields_set, learning.missing_fields);
3754
+ if (learning.missing_fields.length > 0) {
3755
+ deps.installDocumentSink?.({ missingLearnedFields: [...learning.missing_fields] });
3756
+ }
3657
3757
  return true;
3658
3758
  }
3659
3759
  // ---------------------------------------------------------------------------
@@ -3680,6 +3780,171 @@ async function learnedCommandHints(setup, access) {
3680
3780
  : candidate.provenance,
3681
3781
  }));
3682
3782
  }
3783
+ /**
3784
+ * BAPI-1699 — the saved selection as assessment evidence, or `undefined`. Never throws:
3785
+ * an older server, a transport failure, an unreadable body, or a fake transport that
3786
+ * does not know the URL all mean "no saved evidence", and the plan continues unchanged.
3787
+ */
3788
+ async function readSavedTestCommandsEvidence(deps, access) {
3789
+ try {
3790
+ const read = await readConductorSavedTestCommands(access, deps.fetchJson);
3791
+ if (read.kind !== "saved")
3792
+ return undefined;
3793
+ return {
3794
+ commands: read.record.commands,
3795
+ generation: read.record.generation,
3796
+ trialState: read.trialState,
3797
+ commandsInForce: read.commandsInForce,
3798
+ setBy: read.record.set_by,
3799
+ };
3800
+ }
3801
+ catch {
3802
+ return undefined;
3803
+ }
3804
+ }
3805
+ /**
3806
+ * BAPI-1699 — whether the saved commands are, in order, the commands the stored gate already
3807
+ * runs. The comparison splits each saved line on whitespace; a quoted command that does not
3808
+ * split to the stored argv counts as different, which is the safe direction (it is offered as
3809
+ * a pending selection, never silently skipped).
3810
+ */
3811
+ export function savedCommandsEqualStoredGate(saved, stored) {
3812
+ return (saved.length === stored.length &&
3813
+ stored.every((command, index) => JSON.stringify(command.argv) === JSON.stringify(saved[index].trim().split(/\s+/))));
3814
+ }
3815
+ /**
3816
+ * BAPI-1677 — whether a test trial can be offered. The candidates are the ones the
3817
+ * client can see: file detection first, then the repository's local commands, in
3818
+ * their fixed order. With none, no trial is recommended. A failed trial stores
3819
+ * nothing, so it never stops a later offer, and a stored command is never cleared.
3820
+ */
3821
+ async function resolveTestCommandTrial(deps, setup, access, gatePlan, storedCommand) {
3822
+ const none = { eligible: false, candidates: [] };
3823
+ // BAPI-1699: one read of the saved field. A saved selection wins over every discovery
3824
+ // below, even when a local gate is already stored (a pending replacement is still offered).
3825
+ // Unsupported, failed, or unreadable reads are no evidence and change nothing else.
3826
+ const saved = await readSavedTestCommandsEvidence(deps, access);
3827
+ if (saved !== undefined && saved.trialState === "passed")
3828
+ return { eligible: false, candidates: [], saved };
3829
+ // Saved commands that already ARE the stored gate's local commands are not a replacement. An
3830
+ // unqualified stored gate keeps its own qualification flow, exactly as before saving existed.
3831
+ if (saved !== undefined && !savedCommandsEqualStoredGate(saved.commands, gatePlan.current.profile?.local_commands ?? [])) {
3832
+ return { eligible: true, candidates: saved.commands.map((command) => ({ command, source: "saved commands" })), saved };
3833
+ }
3834
+ const inferred = gatePlan.inferred;
3835
+ const storedGateRetry = inferred === undefined && gatePlan.origin === "stored" && gatePlan.current.confirmed &&
3836
+ storedCommand === null && (gatePlan.current.profile?.local_commands.length ?? 0) === 0;
3837
+ if (!storedGateRetry && inferred?.trialEligible !== true)
3838
+ return none;
3839
+ const candidates = [];
3840
+ const add = (candidate) => {
3841
+ if (!candidates.some((c) => c.command === candidate.command))
3842
+ candidates.push(candidate);
3843
+ };
3844
+ if (inferred !== undefined && storedCommand !== null)
3845
+ add({ command: storedCommand, source: "stored configuration" });
3846
+ for (const hint of await learnedCommandHints(setup, access))
3847
+ add(hint);
3848
+ const fs = deps.gate?.discoveryFs;
3849
+ if (fs !== undefined) {
3850
+ try {
3851
+ for (const local of await discoverLocalTestCandidates(fs))
3852
+ add({ command: local.argv.join(" "), source: "repository files" });
3853
+ }
3854
+ catch {
3855
+ // An unreadable file adds no candidate. It is never a stop.
3856
+ }
3857
+ }
3858
+ return { eligible: candidates.length > 0, candidates };
3859
+ }
3860
+ /** Read the stored gate once for a trial; `null` (already reported) when it cannot be read. */
3861
+ async function readGateForTrial(deps, access, policyResult) {
3862
+ let current;
3863
+ try {
3864
+ current = await fetchConductorGateProfile(access, deps.fetchJson);
3865
+ }
3866
+ catch {
3867
+ deps.log(" skipped — the stored gate could not be read, so nothing was started.");
3868
+ return null;
3869
+ }
3870
+ if ((policyResult?.status === "deferred" || policyResult?.status === "unknown") && !current.confirmed) {
3871
+ deps.log(" skipped — the gate and defaults were not stored, so there is no stored gate for a tested command to attach to.");
3872
+ return null;
3873
+ }
3874
+ return current;
3875
+ }
3876
+ /**
3877
+ * BAPI-1699 — give exactly the saved commands (one generation) their trial run through
3878
+ * the existing POST and executor path. Nothing here writes a gate or saves a command;
3879
+ * the server promotes only a passing trial of the current generation, and a replacement
3880
+ * leaves the previously qualified guard in force until it does.
3881
+ */
3882
+ async function runSavedTrial(deps, access, baseUrl, state, policyResult, commands, generation) {
3883
+ deps.log("");
3884
+ deps.log("Test command");
3885
+ const current = await readGateForTrial(deps, access, policyResult);
3886
+ if (current === null)
3887
+ return;
3888
+ const io = gateIoFor(deps);
3889
+ const trialGateDeps = deps.gate !== undefined && deps.progressTimer !== undefined && deps.gate.progressTimer === undefined
3890
+ ? { ...deps.gate, progressTimer: deps.progressTimer }
3891
+ : deps.gate;
3892
+ const result = await runLearnedTestCommandTrial(io, access, trialGateDeps, {
3893
+ baseUrl,
3894
+ current,
3895
+ expectedGeneration: generation,
3896
+ savedCommands: commands,
3897
+ });
3898
+ reportLearnedCommandTrial(io, result);
3899
+ if (result.status !== "promoted" && (current.profile?.local_commands.length ?? 0) > 0) {
3900
+ deps.log(" The guard you had before stays in force until the saved commands pass the trial run.");
3901
+ }
3902
+ state.trial = result;
3903
+ if (result.status === "uncertain")
3904
+ state.commandUncertain = true;
3905
+ if (result.status === "promoted")
3906
+ state.promotedCommands = result.commands;
3907
+ }
3908
+ /**
3909
+ * BAPI-1699 — save an approved `{"commands": [...]}` answer through the config field, then
3910
+ * try the generation the save returned. Returns `single_fallback` only when an older server
3911
+ * refused the field (400 or 404) and exactly one command was approved: the caller then uses
3912
+ * today's owner-command request. Anything else is reported here and the phase ends.
3913
+ */
3914
+ async function saveApprovedCommands(deps, access, baseUrl, state, gatePlan, policyResult, commands) {
3915
+ deps.log("");
3916
+ deps.log("Test command");
3917
+ const io = gateIoFor(deps);
3918
+ const write = await saveConductorSavedTestCommands(access, commands, io.postJson);
3919
+ switch (write.kind) {
3920
+ case "saved": {
3921
+ deps.log(` Saved ${commands.length} test command${commands.length === 1 ? "" : "s"}: ` +
3922
+ `${commands.map((c) => `\`${sanitizeCommandText(c)}\``).join(", ")} (${savedStatusLabel(write.trialState)}). ` +
3923
+ "Saving does not put them in force: they are relied on only after they pass the trial run.");
3924
+ await runSavedTrial(deps, access, baseUrl, state, policyResult, commands, write.record.generation);
3925
+ return "done";
3926
+ }
3927
+ case "unsupported":
3928
+ if (commands.length === 1)
3929
+ return "single_fallback";
3930
+ deps.log(" This Bridge server cannot save several test commands yet, so none were saved or tried. " +
3931
+ "Update the Bridge API and run setup again.");
3932
+ state.trial = { status: "unsupported" };
3933
+ return "done";
3934
+ case "refused":
3935
+ deps.log(write.reason === "unauthorized"
3936
+ ? " This key cannot save test commands (an administrator key is needed), so Bridge skipped them."
3937
+ : " Bridge's server refused the test commands, so none were saved or tried.");
3938
+ state.trial = { status: "refused", reason: write.reason };
3939
+ return "done";
3940
+ case "uncertain":
3941
+ deps.log(" Bridge cannot tell whether the test commands were saved. It will not try again on its own. " +
3942
+ "Run setup again to read what the server holds.");
3943
+ state.commandUncertain = true;
3944
+ state.trial = { status: "uncertain", reason: "request_unclear", profile: null };
3945
+ return "done";
3946
+ }
3947
+ }
3683
3948
  /**
3684
3949
  * Ask the server for the learned (or the owner's) test command and prove it.
3685
3950
  *
@@ -3699,8 +3964,27 @@ async function runTestCommandPhase(deps, options, setup, access, baseUrl, state,
3699
3964
  answer) {
3700
3965
  if (answer !== undefined && (answer.decision === "skip" || answer.decision === "keep"))
3701
3966
  return;
3702
- const ownerCommand = answer?.decision === "command" ? answer.command : options.testCommand;
3703
- const automatic = ownerCommand === undefined && gatePlan?.inferred?.trialEligible === true;
3967
+ // BAPI-1699: an approved `commands` answer is saved once through the config field, and
3968
+ // only the generation that save returned is tried. An older server falls back to today's
3969
+ // single owner command; several commands are never cut down to the first.
3970
+ let commandsAnswer = answer?.decision === "commands" ? answer.commands : undefined;
3971
+ let fallbackOwnerCommand;
3972
+ if (commandsAnswer !== undefined) {
3973
+ const saved = await saveApprovedCommands(deps, access, baseUrl, state, gatePlan, policyResult, commandsAnswer);
3974
+ if (saved !== "single_fallback")
3975
+ return;
3976
+ fallbackOwnerCommand = commandsAnswer[0];
3977
+ commandsAnswer = undefined;
3978
+ }
3979
+ const ownerCommand = fallbackOwnerCommand ?? (answer?.decision === "command" ? answer.command : options.testCommand);
3980
+ // BAPI-1699: pending saved commands are tried exactly as assessed: no model, no candidates,
3981
+ // no owner command, and no PUT. The request is bound to the assessed generation.
3982
+ const pendingSaved = gatePlan?.testCommandTrial?.saved;
3983
+ if (ownerCommand === undefined && pendingSaved !== undefined && pendingSaved.trialState !== "passed") {
3984
+ await runSavedTrial(deps, access, baseUrl, state, policyResult, pendingSaved.commands, pendingSaved.generation);
3985
+ return;
3986
+ }
3987
+ const automatic = ownerCommand === undefined && gatePlan?.testCommandTrial?.eligible === true;
3704
3988
  if (ownerCommand === undefined && !automatic)
3705
3989
  return;
3706
3990
  deps.log("");
@@ -3716,10 +4000,10 @@ answer) {
3716
4000
  // A policy change the owner deferred only holds the trial back when it WAS the gate the
3717
4001
  // command attaches to; an unrelated deferral never stops a confirmed gate's command proof.
3718
4002
  if ((policyResult?.status === "deferred" || policyResult?.status === "unknown") && !current.confirmed) {
3719
- deps.log(" skipped — the gate and defaults were not stored, so there is no stored gate to attach a proven command to.");
4003
+ deps.log(" skipped — the gate and defaults were not stored, so there is no stored gate for a tested command to attach to.");
3720
4004
  return;
3721
4005
  }
3722
- const candidates = automatic ? await learnedCommandHints(setup, access) : undefined;
4006
+ const candidates = automatic ? gatePlan?.testCommandTrial?.candidates : undefined;
3723
4007
  const io = gateIoFor(deps);
3724
4008
  const trialGateDeps = deps.gate !== undefined && deps.progressTimer !== undefined && deps.gate.progressTimer === undefined
3725
4009
  ? { ...deps.gate, progressTimer: deps.progressTimer }
@@ -3771,12 +4055,16 @@ function settleCiPlan(deps, state, gatePlan) {
3771
4055
  deps.log("");
3772
4056
  // BAPI-1654: "no CI" is said only when no CI files exist. No reported checks is not no CI.
3773
4057
  const systems = state.ciSystems ?? [];
4058
+ // BAPI-1701: a test command that was never found did not "fail a trial run"; say which it was.
4059
+ const noCommandFound = state.trial?.status === "no_command" && isInformationalNoCommandReason(state.trial.reason);
4060
+ const commandFact = noCommandFound ? "Bridge found no test command" : "no test command passed the trial run";
4061
+ const gateWord = noCommandFound ? "local test gate" : "test gate";
3774
4062
  deps.log(systems.length > 0
3775
4063
  ? `Bridge found CI configuration (${[...new Set(systems.map((s) => s.name))].join(", ")}) but no checks have ` +
3776
- "reported from it yet, and it could not prove a test command. Child pull requests will merge into the epic " +
3777
- "branch without a test gate. You review everything in the final pull request."
3778
- : "Bridge found no CI and could not prove a test command. Child pull requests will merge into the epic " +
3779
- "branch without a test gate. You review everything in the final pull request.");
4064
+ `reported from it yet, and ${commandFact}. Child pull requests will merge into the epic ` +
4065
+ `branch without a ${gateWord}. You review everything in the final pull request.`
4066
+ : `Bridge found no CI and ${noCommandFound ? "no test command" : commandFact}. Child pull requests will merge into the epic ` +
4067
+ `branch without a ${gateWord}. You review everything in the final pull request.`);
3780
4068
  }
3781
4069
  }
3782
4070
  // ---------------------------------------------------------------------------
@@ -3802,7 +4090,7 @@ async function offerManagedWorkflow(deps) {
3802
4090
  recommended: "no",
3803
4091
  recordingFlag: "no flag records this choice; rerun setup in an interactive terminal to be asked again.",
3804
4092
  evidence: [
3805
- "Bridge already runs your proven test command before each merge, so the gate works without it.",
4093
+ "Bridge already runs your test command, which passed the trial run, before each merge, so the gate works without it.",
3806
4094
  "The workflow runs the same command on GitHub, only for pull requests into epic branches.",
3807
4095
  ],
3808
4096
  consequences: [
@@ -3932,6 +4220,10 @@ setupPrDecision) {
3932
4220
  }
3933
4221
  if (profile === null || !profile.confirmed || profile.profile === null)
3934
4222
  return none;
4223
+ // BAPI-1677: the read-back is what the workflow installs, not what discovery found.
4224
+ const sealedChanged = !sameDependencyInstall(profile.profile.dependency_install ?? [], state.sealedDependencyInstall);
4225
+ const sealedDependencyInstall = profile.profile.dependency_install ?? [];
4226
+ state.sealedDependencyInstall = sealedDependencyInstall;
3935
4227
  // The command the workflow runs is the one the server proved this run, else the stored one.
3936
4228
  let command = state.promotedCommands?.length === 1 ? state.promotedCommands[0].command : null;
3937
4229
  if (command === null) {
@@ -3950,9 +4242,9 @@ setupPrDecision) {
3950
4242
  state.toolchains = toolchains;
3951
4243
  // The first read already assessed the workflow against this very command when no
3952
4244
  // trial changed it this run; only a command that may have changed is assessed again.
3953
- const assessed = state.trial === null && command === state.storedCommand && state.evidence.workflow.state !== "unknown"
4245
+ const assessed = state.trial === null && !sealedChanged && command === state.storedCommand && state.evidence.workflow.state !== "unknown"
3954
4246
  ? state.evidence.workflow
3955
- : await assessWorkflow(setup, command, toolchains, state.snapshot, true);
4247
+ : await assessWorkflow(setup, command, toolchains, state.snapshot, true, sealedDependencyInstall);
3956
4248
  state.evidence = { ...state.evidence, workflow: assessed };
3957
4249
  const localOnly = profile.profile.kind === "local" &&
3958
4250
  profile.profile.provider_checks.length === 0 &&
@@ -3992,7 +4284,7 @@ setupPrDecision) {
3992
4284
  }
3993
4285
  if (!install)
3994
4286
  return setupPrDecision === "decline" ? { status: "declined" } : none;
3995
- const outcome = await fixSetupPullRequest(deps, setup, command, toolchains, state.snapshot, state.repository, setupPrDecision === undefined ? undefined : setupPrDecision === "approve");
4287
+ const outcome = await fixSetupPullRequest(deps, setup, command, toolchains, state.snapshot, state.repository, setupPrDecision === undefined ? undefined : setupPrDecision === "approve", sealedDependencyInstall);
3996
4288
  state.evidence = { ...state.evidence, workflow: outcome.workflow };
3997
4289
  const result = outcome.result;
3998
4290
  const opened = result !== null &&
@@ -4053,7 +4345,11 @@ function renderDryRunCiPlan(deps, options, gatePlan) {
4053
4345
  deps.log(" Test command: a real run offers your --test-command to Bridge's server and proves it by running it once on " +
4054
4346
  "this computer. Dry run requested nothing and started nothing.");
4055
4347
  }
4056
- else if (gatePlan?.inferred?.trialEligible === true) {
4348
+ else if (gatePlan?.testCommandTrial?.saved !== undefined) {
4349
+ deps.log(" Test command: a real run gives the saved test commands a trial run in a clean checkout and relies on them " +
4350
+ "only once they passed the trial run. The model is not consulted. Dry run requested nothing and started nothing.");
4351
+ }
4352
+ else if (gatePlan?.testCommandTrial?.eligible === true) {
4057
4353
  deps.log(" Test command: a real run asks Bridge's server to learn it from this repository and proves it by running it " +
4058
4354
  "once on this computer, and nobody is asked for it. Dry run requested nothing and started nothing.");
4059
4355
  }
@@ -4064,7 +4360,7 @@ function renderDryRunCiPlan(deps, options, gatePlan) {
4064
4360
  "is added only if the command passes."
4065
4361
  : " CI plan: no CI reported. A local test gate is stored only if the command passes; otherwise the gate has " +
4066
4362
  "no members.");
4067
- deps.log(" Bridge's workflow: offered once, only for a proven local plan, and only added if you say yes and the setup " +
4363
+ deps.log(" Bridge's workflow: offered once, only for a local plan whose command passed the trial run, and only added if you say yes and the setup " +
4068
4364
  "pull request opens. Dry run asked nothing and opened nothing.");
4069
4365
  }
4070
4366
  }
@@ -4191,7 +4487,7 @@ async function collectCiOffer(input) {
4191
4487
  const managed = await managedWorkflowIdentity(input, "absent");
4192
4488
  if (managed !== null) {
4193
4489
  evidence.ciOffer = { identity: managed.identity, applicable: true };
4194
- return { evidence, delivery: { kind: "managed_workflow", command: managed.command, toolchains: managed.toolchains } };
4490
+ return { evidence, delivery: { kind: "managed_workflow", command: managed.command, toolchains: managed.toolchains, dependencyInstall: input.dependencyInstall ?? [] } };
4195
4491
  }
4196
4492
  return { evidence, delivery: null };
4197
4493
  }
@@ -4228,7 +4524,8 @@ async function managedWorkflowIdentity(input, wanted) {
4228
4524
  return null;
4229
4525
  let rendered;
4230
4526
  try {
4231
- rendered = renderEpicImplementerCiWorkflow(command, resolution.toolchains);
4527
+ // The same entries are delivered, so the approved hash matches the delivered bytes.
4528
+ rendered = renderEpicImplementerCiWorkflow(command, resolution.toolchains, input.dependencyInstall ?? []);
4232
4529
  }
4233
4530
  catch {
4234
4531
  return null;
@@ -4272,7 +4569,22 @@ async function collectDecisionEvidence(input) {
4272
4569
  currentKind: gatePlan.current.profile?.kind ?? null,
4273
4570
  };
4274
4571
  const stored = gatePlan?.current.profile ?? null;
4275
- const declarations = input.declarationPlan.map((entry) => ({ key: entry.key, summary: entry.summary, value: declarationValue(entry.fields) }));
4572
+ const installFacts = input.dependencyInstallFacts ?? null;
4573
+ const installDetails = installFacts === null ? undefined : dependencyInstallDetails({
4574
+ commands: input.correctedDependencyInstall === true ? input.effectiveDependencyInstall ?? [] : installFacts.planned,
4575
+ stored: installFacts.stored,
4576
+ differs: input.correctedDependencyInstall === true || installFacts.drift !== "same",
4577
+ evidence: input.correctedDependencyInstall === true ? [] : installFacts.evidence,
4578
+ limitations: installFacts.limitations,
4579
+ });
4580
+ const declarations = input.declarationPlan.map((entry) => ({
4581
+ key: entry.key,
4582
+ summary: entry.summary,
4583
+ value: declarationValue(entry.fields),
4584
+ ...(entry.key === "dependency_install" && installFacts !== null
4585
+ ? { recommendDecline: installFacts.drift === "replacing", ...(installDetails !== undefined ? { dependencyInstall: installDetails } : {}) }
4586
+ : {}),
4587
+ }));
4276
4588
  // A settled declaration still names its stored value, so a replay hashes the same.
4277
4589
  for (const [key, value] of [
4278
4590
  ["dependency_install", stored?.dependency_install],
@@ -4281,11 +4593,19 @@ async function collectDecisionEvidence(input) {
4281
4593
  ["worker_database", stored?.worker_database],
4282
4594
  ]) {
4283
4595
  const empty = value === undefined || value === null || (Array.isArray(value) && value.length === 0) || value === "unknown";
4284
- if (!empty && !declarations.some((d) => d.key === key))
4285
- declarations.push({ key, summary: [], value: declarationValue({ [declarationField(key)]: value }), applicable: false });
4596
+ if (!empty && !declarations.some((d) => d.key === key)) {
4597
+ declarations.push({
4598
+ key, summary: [], value: declarationValue({ [declarationField(key)]: value }), applicable: false,
4599
+ ...(key === "dependency_install" && installDetails !== undefined ? { dependencyInstall: installDetails } : {}),
4600
+ });
4601
+ }
4602
+ }
4603
+ // Nothing stored and nothing on offer can still have something to say, such as a failed read.
4604
+ if (installDetails !== undefined && !declarations.some((d) => d.key === "dependency_install") && installDetails.limitations.length > 0) {
4605
+ declarations.push({ key: "dependency_install", summary: [], value: null, applicable: false, dependencyInstall: installDetails });
4286
4606
  }
4287
4607
  const workflowState = state.evidence.workflow.state;
4288
- const trialEligible = gatePlan?.inferred?.trialEligible === true;
4608
+ const trialEligible = gatePlan?.testCommandTrial?.eligible === true;
4289
4609
  const recovery = state.evidence.recovery?.supported ? state.evidence.recovery.evidence : undefined;
4290
4610
  const branchQuestion = fixes.includes("reindex") && recovery !== undefined && recovery.destination_branch
4291
4611
  && (!["equal", "contains_target"].includes(recovery.configured_relation) || recovery.canonical_relation === "diverged")
@@ -4297,10 +4617,12 @@ async function collectDecisionEvidence(input) {
4297
4617
  ? { requestId: recovery.request.id, generation: recovery.retry_generation }
4298
4618
  : undefined;
4299
4619
  const label = (origin) => CANDIDATE_ORIGIN_LABEL[origin];
4620
+ const epicServerSnapshot = input.epicServerSnapshot ?? null;
4621
+ const sfccGrant = new Set(sfccGrantIds(epicServerSnapshot, grantInventory));
4300
4622
  const mcpGrant = grantInventory === null ? null : {
4301
4623
  current: state.evidence.mcpGrant?.state === "needs_action" ? state.evidence.mcpGrant.reason : state.evidence.mcpGrant?.state ?? "unknown",
4302
4624
  applicable: fixes.includes("mcp_grant"),
4303
- candidates: grantInventory.candidates.flatMap((c) => c.definitions.map((d) => ({ id: d.id, name: c.name, origins: d.origins.map(label) }))),
4625
+ candidates: grantInventory.candidates.flatMap((c) => c.definitions.map((d) => ({ id: d.id, name: c.name, origins: d.origins.map(label), ...(sfccGrant.has(d.id) ? { sfcc_recommended: true } : {}) }))),
4304
4626
  excluded: grantInventory.exclusions.map((e) => ({ name: e.name, origin: label(e.origin), reason: CANDIDATE_EXCLUSION_TEXT[e.reason] })),
4305
4627
  invalidExisting: grantInventory.existingGrant?.state === "ok"
4306
4628
  ? grantInventory.existingGrant.findings.map((f) => ({ name: f.name, reason: CANDIDATE_EXCLUSION_TEXT[f.reason] }))
@@ -4314,7 +4636,13 @@ async function collectDecisionEvidence(input) {
4314
4636
  identity,
4315
4637
  gate,
4316
4638
  declarations,
4317
- testCommand: { stored: state.storedCommand !== null, trialEligible, ownerCommandSupplied: options.testCommand !== undefined },
4639
+ testCommand: {
4640
+ stored: state.storedCommand !== null,
4641
+ trialEligible,
4642
+ candidate: gatePlan?.testCommandTrial?.candidates[0]?.command ?? null,
4643
+ ownerCommandSupplied: options.testCommand !== undefined,
4644
+ ...(gatePlan?.testCommandTrial?.saved !== undefined ? { saved: gatePlan.testCommandTrial.saved } : {}),
4645
+ },
4318
4646
  setupPr: {
4319
4647
  applicable: setupPrOffersWorkflow(input),
4320
4648
  workflowState,
@@ -4331,10 +4659,7 @@ async function collectDecisionEvidence(input) {
4331
4659
  ...(branchQuestion ? { branchQuestion } : {}), ...(retryQuestion ? { retryQuestion } : {}),
4332
4660
  },
4333
4661
  mcpGrant,
4334
- epicServer: epicServerEvidence === undefined ? null : {
4335
- current: epicServerEvidence.state === "met" ? epicServerEvidence.mode : null,
4336
- applicable: fixes.includes("epic_server"),
4337
- },
4662
+ epicServer: epicServerEvidence === undefined ? null : epicServerDecisionEvidence(epicServerEvidence.state === "met" ? epicServerEvidence.mode : null, fixes.includes("epic_server"), epicServerSnapshot, epicServerSnapshot?.existingSandbox !== null && epicServerSnapshot?.existingSandbox !== undefined),
4338
4663
  // The decision readiness reports as recorded is shown on the choice only; it never sets
4339
4664
  // `recommended` or `applicable`, so it cannot move a digest.
4340
4665
  epicBranchCi: collected === undefined || collected.status === "skipped_no_seams" ? null : {
@@ -4351,6 +4676,17 @@ async function collectDecisionEvidence(input) {
4351
4676
  ...(state.ciSystems !== undefined
4352
4677
  ? { ci_systems: state.ciSystems === null ? null : state.ciSystems.map((c) => ({ name: c.name, path: c.path })) }
4353
4678
  : {}),
4679
+ // BAPI-1667: from the same snapshot, so nothing is read or checked a second time.
4680
+ ...(epicServerSnapshot?.detection !== null && epicServerSnapshot?.detection !== undefined
4681
+ ? {
4682
+ sfcc: {
4683
+ detected: epicServerSnapshot.detection.detected,
4684
+ signals: epicServerSnapshot.detection.signals,
4685
+ dev_script: epicServerSnapshot.detection.dev_script,
4686
+ upload_check: epicServerSnapshot.uploadCheck,
4687
+ },
4688
+ }
4689
+ : {}),
4354
4690
  },
4355
4691
  };
4356
4692
  }
@@ -4363,7 +4699,7 @@ async function collectDecisionEvidence(input) {
4363
4699
  function setupPrOffersWorkflow(input) {
4364
4700
  const { options, gatePlan, state, fixes } = input;
4365
4701
  const workflowState = state.evidence.workflow.state;
4366
- const trialEligible = gatePlan?.inferred?.trialEligible === true;
4702
+ const trialEligible = gatePlan?.testCommandTrial?.eligible === true;
4367
4703
  return state.evidence.githubSignIn === "signed_in" && state.repository !== null
4368
4704
  && (fixes.includes("setup_pr") || (trialEligible && gatePlan?.inferred?.ciPlan === "none" && !hasExplicitGateInput(options.gate)
4369
4705
  && (workflowState === "absent" || workflowState === "unknown")));
@@ -4434,6 +4770,41 @@ async function collectRepositoryFacts(deps, grantInventory, readToolchains) {
4434
4770
  }
4435
4771
  return { ci_workflows: ciWorkflows, package_manager: packageManager, mcp_configs: mcpConfigs };
4436
4772
  }
4773
+ /**
4774
+ * BAPI-1677 — one plain note when the default branch, which a workflow is committed
4775
+ * onto, lacks a named lockfile or a kept extra. Only a file proven absent counts: an
4776
+ * unreadable one is unknown. A note changes nothing and stops nothing.
4777
+ */
4778
+ async function defaultBranchInstallNote(setup, snapshot, facts) {
4779
+ const read = setup.readSnapshotFile;
4780
+ if (snapshot === null || read === undefined)
4781
+ return null;
4782
+ const textOf = async (relPath) => {
4783
+ try {
4784
+ return await read(snapshot, relPath);
4785
+ }
4786
+ catch (err) {
4787
+ return err?.code === "ENOENT" ? null : undefined;
4788
+ }
4789
+ };
4790
+ const lacking = "Your default branch does not have everything these install commands use yet, so CI could fail there until it does.";
4791
+ for (const entry of facts.planned) {
4792
+ for (const lockfile of entry.lockfiles) {
4793
+ if ((await textOf(lockfile)) === null)
4794
+ return lacking;
4795
+ }
4796
+ }
4797
+ if (facts.evidence.length === 0)
4798
+ return null;
4799
+ const pyproject = await textOf(pyprojectPathFor("."));
4800
+ if (typeof pyproject !== "string")
4801
+ return pyproject === null ? lacking : null;
4802
+ const manager = facts.planned.some((e) => e.argv[0] === "poetry") ? "poetry" : "uv";
4803
+ const declared = scanDeclaredExtras(pyproject, manager);
4804
+ if (declared.status !== "known")
4805
+ return null;
4806
+ return facts.evidence.every((e) => declared.extras.includes(e.extra)) ? null : lacking;
4807
+ }
4437
4808
  /** Merge the approved declarations into the gate plan, rebuilding its PUT from the same desired gate. */
4438
4809
  function applyApprovedDeclarations(plan, approved) {
4439
4810
  if (approved.length === 0)
@@ -4447,8 +4818,46 @@ function settledGateResults(proposal) {
4447
4818
  .filter((a) => (a.key === "gate" || DECLARATION_KEYS.includes(a.key)) && a.intent === "write")
4448
4819
  .map((a) => ({ key: a.key, status: "unchanged", target: a.effect?.target ?? "repository_gate" }));
4449
4820
  }
4821
+ /** BAPI-1701: the runbook section that names the `stored_malformed: true` recovery. */
4822
+ const MALFORMED_GATE_FIX = "Ask Bridge support, or follow the operator runbook's `stored_malformed: true` recovery. " +
4823
+ "The stored value is kept as it is. Rerunning setup will not repair it.";
4824
+ /**
4825
+ * BAPI-1701: a setup that ends with no stored gate says why, with a remedy that can make progress.
4826
+ * Only an inferred plan with no write and no confirmed gate qualifies. A plan with `write: null`
4827
+ * is never read as a stored gate, and a confirmed stored gate never reaches this.
4828
+ */
4829
+ export function unresolvedGateResult(plan) {
4830
+ const inferred = plan.inferred;
4831
+ if (inferred === undefined || plan.write !== null || plan.current.confirmed)
4832
+ return null;
4833
+ const target = "repository_gate";
4834
+ if (inferred.storedUnreadable) {
4835
+ return { key: "gate", status: "unattempted", target, reason: "the stored gate could not be read, so setup left it alone", fix: MALFORMED_GATE_FIX };
4836
+ }
4837
+ if (inferred.historyUnavailable === true) {
4838
+ return {
4839
+ key: "gate",
4840
+ status: "unattempted",
4841
+ target,
4842
+ reason: "Bridge could not read this repository's CI history, so it stored no gate",
4843
+ fix: "Check GitHub access, sign-in, or the app installation for this repository, then rerun setup.",
4844
+ };
4845
+ }
4846
+ if (inferred.watchedUnsupported) {
4847
+ return {
4848
+ key: "gate",
4849
+ status: "unattempted",
4850
+ target,
4851
+ reason: "this server cannot store the watched CI checks Bridge found, so it stored no gate",
4852
+ fix: "Update the Bridge API, then rerun setup. Nothing was replaced.",
4853
+ };
4854
+ }
4855
+ return null;
4856
+ }
4450
4857
  const DECLARATION_KEYS = ["dependency_install", "ci_database", "must_order_paths", "worker_database"];
4451
- function gateWriteResults(result, proposal, plan) {
4858
+ export function gateWriteResults(result, proposal, plan,
4859
+ /** BAPI-1677 — the install commands read back after the write; `null` when they could not be confirmed. */
4860
+ installReadBack) {
4452
4861
  const readBack = result.current !== undefined ? { revision: result.current.state.revision } : undefined;
4453
4862
  const status = result.status === "completed" ? "written"
4454
4863
  : result.status === "unchanged" ? "unchanged"
@@ -4459,19 +4868,24 @@ function gateWriteResults(result, proposal, plan) {
4459
4868
  status,
4460
4869
  target: "repository_gate",
4461
4870
  ...(readBack !== undefined ? { read_back: readBack } : {}),
4462
- ...(status === "refused" ? { reason: "the policy was refused or changed after the preview", fix: "Rerun setup for a fresh proposal; nothing in the gate was written." } : {}),
4463
- ...(status === "uncertain" ? { reason: "the policy write could not be confirmed by reading it back", fix: "Read the gate with `epic-implementer doctor` before retrying; setup did not retry blindly." } : {}),
4871
+ // BAPI-1701: the validated category picks the reason and the one fix. No category keeps the bounded fallback.
4872
+ ...(status === "refused" ? formatSetupPolicyRefusal(result.refusal) : {}),
4873
+ ...(status === "uncertain" ? formatSetupPolicyRefusal(result.refusal, true) : {}),
4464
4874
  };
4465
4875
  if (proposal === null)
4466
4876
  return [gate];
4467
4877
  const declarations = plan.map((entry) => {
4468
4878
  const decision = decisionFor(proposal, entry.key);
4469
- const approved = decision?.kind === "option" && decision.option === "approve";
4879
+ const approved = (decision?.kind === "option" && decision.option === "approve") || decision?.kind === "dependency_install_entries";
4880
+ const inPlace = status === "written" || status === "unchanged";
4881
+ const install = approved && entry.key === "dependency_install" && inPlace && installReadBack !== undefined;
4470
4882
  return {
4471
4883
  key: entry.key,
4472
- status: !approved ? "declined" : status === "declined" ? "unattempted" : status,
4884
+ status: !approved ? "declined" : status === "declined" ? "unattempted" : install && installReadBack === null ? "uncertain" : status,
4473
4885
  target: `repository_gate.${entry.key}`,
4474
4886
  ...(approved && status === "declined" ? { reason: "the gate it is stored with was declined" } : {}),
4887
+ ...(install && installReadBack === null ? { reason: "the install commands could not be read back after the write", fix: "Read the gate with `epic-implementer doctor` before retrying." } : {}),
4888
+ ...(install && installReadBack !== null ? { read_back: { commands: installReadBack ?? [] } } : {}),
4475
4889
  };
4476
4890
  });
4477
4891
  return [gate, ...declarations];
@@ -4481,6 +4895,8 @@ function testCommandAnswer(d) {
4481
4895
  return undefined;
4482
4896
  if (d.kind === "command")
4483
4897
  return { decision: "command", command: d.command };
4898
+ if (d.kind === "commands")
4899
+ return { decision: "commands", commands: d.commands };
4484
4900
  if (d.kind === "option" && (d.option === "learn" || d.option === "skip" || d.option === "keep"))
4485
4901
  return { decision: d.option };
4486
4902
  return undefined;
@@ -4489,6 +4905,13 @@ function testCommandAnswer(d) {
4489
4905
  export const NO_TEST_COMMAND_REASON = "Bridge found no test command in this repository";
4490
4906
  /** BAPI-1657: the plain owner-facing reason when the server could not read the testing instructions. */
4491
4907
  export const NO_COMMAND_RETRY_REASON = "the server could not read the repository's testing instructions just now";
4908
+ /** BAPI-1701: why a found candidate was not usable, one plain line per rejection reason. */
4909
+ const NO_COMMAND_REJECTION_REASON = Object.freeze({
4910
+ working_directory_unsupported: "the test command has to run from a subdirectory, which a gate cannot do",
4911
+ not_plain_argv: "the test command is not a plain program and arguments",
4912
+ command_not_allowed: "the test command is not one Bridge allows",
4913
+ invalid_command: "the test command is not valid",
4914
+ });
4492
4915
  /**
4493
4916
  * BAPI-1657: the launcher text for an owner-run command. The detected launcher wins,
4494
4917
  * then the published package. A detection failure falls back to the published package.
@@ -4503,6 +4926,10 @@ async function detectedLauncherBase(deps, repoName) {
4503
4926
  }
4504
4927
  return (detected ?? NPM_SETUP_LAUNCHER).base;
4505
4928
  }
4929
+ /** BAPI-1701: whether this no-command reason's remedy runs `install epic-implementer --test-command`. */
4930
+ function needsLauncherRemedy(reason) {
4931
+ return reason === "working_directory_unsupported" || reason === "not_plain_argv" || reason === "command_not_allowed" || reason === "invalid_command";
4932
+ }
4506
4933
  /** The learned check's own entry, carrying child 3's phase. `null` when no trial ran and none was asked for. */
4507
4934
  export function trialWriteResult(trial, asked, launcher) {
4508
4935
  const target = "repository_gate.local_commands";
@@ -4510,34 +4937,74 @@ export function trialWriteResult(trial, asked, launcher) {
4510
4937
  return asked ? { key: "test_command", status: "unchanged", target, reason: "no trial was needed for the stored gate" } : null;
4511
4938
  const phase = "evidence" in trial && trial.evidence !== undefined ? trial.evidence.phase : null;
4512
4939
  switch (trial.status) {
4513
- case "no_command":
4514
- // BAPI-1657: the owner-facing remedy names the launcher the owner runs in their own terminal.
4940
+ case "no_command": {
4941
+ // BAPI-1701: a genuine absence is information. The local gate is simply not there; setup is not incomplete for it.
4942
+ if (isInformationalNoCommandReason(trial.reason)) {
4943
+ return { key: "test_command", status: "unchanged", target, reason: NO_COMMAND_INFORMATION_TEXT };
4944
+ }
4515
4945
  if (trial.reason === "llm_unavailable") {
4516
4946
  return { key: "test_command", status: "failed", target, reason: NO_COMMAND_RETRY_REASON, fix: "Rerun setup to try reading the repository's testing instructions again." };
4517
4947
  }
4948
+ if (trial.reason === "llm_output_invalid") {
4949
+ return {
4950
+ key: "test_command",
4951
+ status: "failed",
4952
+ target,
4953
+ reason: "the server could not turn the repository's testing instructions into a command",
4954
+ fix: "Rerun setup to try again. If it fails again, update the repository's testing instructions (run /learn-repository) so a command can be read from them.",
4955
+ };
4956
+ }
4957
+ if (trial.reason === "generation_superseded") {
4958
+ return {
4959
+ key: "test_command",
4960
+ status: "failed",
4961
+ target,
4962
+ reason: "the saved test commands changed after you approved them",
4963
+ fix: "Rerun setup to review and approve a fresh proposal; nothing was stored from the old one.",
4964
+ };
4965
+ }
4966
+ // BAPI-1657: the owner-facing remedy names the launcher the owner runs in their own terminal.
4518
4967
  return {
4519
4968
  key: "test_command",
4520
4969
  status: "failed",
4521
4970
  target,
4522
- reason: NO_TEST_COMMAND_REASON,
4523
- fix: `Child pull requests merge into the epic branch without a test gate. In your own terminal, run \`${launcher ?? NPM_SETUP_LAUNCHER.base} install epic-implementer --test-command "<your command>"\` with your test command.`,
4971
+ reason: NO_COMMAND_REJECTION_REASON[trial.reason],
4972
+ fix: `${CANDIDATE_REJECTION_FIX[trial.reason]} In your own terminal, run \`${launcher ?? NPM_SETUP_LAUNCHER.base} install epic-implementer --test-command "<your command>"\` with a command that meets this.`,
4524
4973
  };
4974
+ }
4525
4975
  case "promoted":
4526
- return { key: "test_command", status: "written", target, phase, read_back: { commands: trial.commands.map((c) => c.name) } };
4976
+ return { key: "test_command", status: "written", target, phase, read_back: { commands: trial.commands.map((c) => c.name), ran: trial.commands.map((c) => c.command) } };
4527
4977
  case "not_needed":
4528
4978
  return { key: "test_command", status: "unchanged", target };
4529
4979
  case "uncertain":
4530
4980
  return { key: "test_command", status: "uncertain", target, phase, reason: `the trial's completion is unknown (${trial.reason})`, fix: "Rerun setup to read the trial again; it is not started twice." };
4531
4981
  case "unqualified":
4532
4982
  case "stale":
4533
- case "could_not_run":
4534
- return { key: "test_command", status: "failed", target, phase, reason: `the check did not pass (${trial.status})`, fix: "Fix what the check reported above, then rerun setup." };
4983
+ case "could_not_run": {
4984
+ // BAPI-1698: the remedy names what to change for THIS result. A deterministic
4985
+ // failure never gets "rerun setup" on its own: an unchanged retry fails again.
4986
+ const presentation = presentTrialResult({
4987
+ phase,
4988
+ dependencyInstallDeclared: trial.evidence?.dependencyInstallDeclared ?? null,
4989
+ interrupted: trial.status === "could_not_run",
4990
+ commandResults: trial.evidence?.commandResults ?? null,
4991
+ });
4992
+ const fix = trial.status === "stale"
4993
+ ? "The gate changed while the trial ran; run setup again to try the current gate."
4994
+ : presentation.remedy ?? "Run setup again to read the trial result.";
4995
+ return { key: "test_command", status: "failed", target, phase, reason: `the check did not pass (${trial.status})`, fix };
4996
+ }
4535
4997
  default:
4536
4998
  return { key: "test_command", status: "failed", target, phase: null, reason: `the trial did not run (${trial.status})`, fix: "Rerun setup; if this persists, run `epic-implementer doctor`." };
4537
4999
  }
4538
5000
  }
4539
- function workflowWriteResult(outcome, asked) {
5001
+ export function workflowWriteResult(outcome, asked, decision) {
4540
5002
  const target = "github.default_branch";
5003
+ // BAPI-1678: the owner's decline stands, whatever the phase found to do. A write or a
5004
+ // failure that really happened still reports as itself below.
5005
+ if (decision === "decline" && (outcome.status === "none" || outcome.status === "unchanged")) {
5006
+ return { key: "setup_pr", status: "declined", target };
5007
+ }
4541
5008
  switch (outcome.status) {
4542
5009
  case "none":
4543
5010
  return asked ? { key: "setup_pr", status: "unchanged", target, reason: "no setup pull request was needed" } : null;
@@ -4552,9 +5019,12 @@ function workflowWriteResult(outcome, asked) {
4552
5019
  }
4553
5020
  }
4554
5021
  function fixOutcomeResult(key, target, outcome) {
4555
- return outcome.status === "failed"
4556
- ? { key, status: "failed", target, reason: outcome.reason, fix: "Fix the cause above, then rerun setup with the same answers." }
4557
- : { key, status: outcome.status, target };
5022
+ if (outcome.status === "failed") {
5023
+ return { key, status: "failed", target, reason: outcome.reason, fix: "Fix the cause above, then rerun setup with the same answers." };
5024
+ }
5025
+ // BAPI-1667: fixed advisory text only. It reports; it never changes the status.
5026
+ const advisories = [...new Set(outcome.advisories ?? [])];
5027
+ return { key, status: outcome.status, target, ...(advisories.length > 0 ? { reason: advisories.join(" ") } : {}) };
4558
5028
  }
4559
5029
  function indexProgress(index) {
4560
5030
  if (index.state === "reached")
@@ -4578,23 +5048,42 @@ function reindexWriteResult(index) {
4578
5048
  }
4579
5049
  return { key: "reindex", status: "uncertain", target, reason: "the index state could not be read", fix: "Rerun setup to read it again." };
4580
5050
  }
4581
- /** The approved epic-server answer as a record. A local mode records whether guidance is present. */
4582
- async function epicServerAnswer(epicDeps, d) {
4583
- if (d.kind === "epic_server_sfcc") {
4584
- return { decision: "record", record: { version: 1, mode: "sfcc_shared_active", sfcc: { sandbox_id: d.value.sandbox_id, credential_ref: d.value.credential_ref, storefront_origin: d.value.storefront_origin } } };
4585
- }
4586
- if (d.kind === "option" && d.option === "local") {
4587
- let present = false;
5051
+ /**
5052
+ * The approved epic-server answer as a record. A local mode records whether guidance
5053
+ * is present. BAPI-1667: a plain `local` or `none` keeps an approved sandbox, because
5054
+ * upload needs it in every mode; only a structured answer replaces it. An entered
5055
+ * sandbox id is re-checked, and a mismatch only adds an advisory.
5056
+ */
5057
+ export async function epicServerAnswer(epicDeps, d, snapshot = null) {
5058
+ const recipeOf = async () => {
4588
5059
  try {
4589
- present = await epicDeps.guidancePresent();
5060
+ return (await epicDeps.guidancePresent()) ? "present" : "absent";
4590
5061
  }
4591
5062
  catch {
4592
- present = false;
5063
+ return "absent";
4593
5064
  }
4594
- return { decision: "record", record: { version: 1, mode: "local", recipe: present ? "present" : "absent" } };
5065
+ };
5066
+ const kept = snapshot?.existingSandbox ?? null;
5067
+ if (d.kind === "epic_server_sfcc") {
5068
+ const { mode, sandbox_id, credential_ref, storefront_origin } = d.value;
5069
+ const check = epicDeps.sfccUploadCheck;
5070
+ const credentials = snapshot?.credentials ?? null;
5071
+ const mismatch = snapshot?.detection?.detected === true && check !== undefined
5072
+ ? await recheckSfccSandboxId(check, sandbox_id, { credentials })
5073
+ : [];
5074
+ const sfcc = { sandbox_id, credential_ref, ...(storefront_origin !== undefined ? { storefront_origin } : {}) };
5075
+ return {
5076
+ decision: "record",
5077
+ record: { version: 1, mode, ...(mode === "local" ? { recipe: await recipeOf() } : {}), sfcc },
5078
+ advisories: [...mismatch, ...credentialReferenceAdvisories(credentials, credential_ref)],
5079
+ };
5080
+ }
5081
+ if (d.kind === "option" && d.option === "local") {
5082
+ return { decision: "record", record: { version: 1, mode: "local", recipe: await recipeOf(), ...(kept !== null ? { sfcc: kept } : {}) } };
5083
+ }
5084
+ if (d.kind === "option" && d.option === "none") {
5085
+ return { decision: "record", record: { version: 1, mode: "none", ...(kept !== null ? { sfcc: kept } : {}) } };
4595
5086
  }
4596
- if (d.kind === "option" && d.option === "none")
4597
- return { decision: "record", record: { version: 1, mode: "none" } };
4598
5087
  return { decision: "keep" };
4599
5088
  }
4600
5089
  /**
@@ -4635,7 +5124,7 @@ function ciChangeWriteResult(actionClass, target, result) {
4635
5124
  return { key, status: "failed", target, reason: `the CI pull request could not be opened (${result.reason.replace(/_/g, " ")})`, fix: result.remediation };
4636
5125
  }
4637
5126
  }
4638
- function epicBranchWriteResults(step, report) {
5127
+ function epicBranchWriteResults(step, report, note) {
4639
5128
  if (!report)
4640
5129
  return null;
4641
5130
  const results = [];
@@ -4644,16 +5133,11 @@ function epicBranchWriteResults(step, report) {
4644
5133
  results.push(step.decision === null
4645
5134
  ? { key: "epic_branch_ci", status: "declined", target: "epic_branch_ci", reason: "no decision was recorded; runs behave as include" }
4646
5135
  : step.recorded
4647
- ? { key: "epic_branch_ci", status: step.unchanged ? "unchanged" : "written", target: "epic_branch_ci", read_back: { decision: step.decision } }
5136
+ ? { key: "epic_branch_ci", status: step.unchanged ? "unchanged" : "written", target: "epic_branch_ci", read_back: { decision: step.decision }, ...(note !== undefined ? { reason: note } : {}) }
4648
5137
  : { key: "epic_branch_ci", status: "failed", target: "epic_branch_ci", reason: "the decision could not be recorded", fix: step.manualAction ?? "Rerun setup." });
4649
5138
  const outcome = step.exemptionOutcome;
4650
5139
  if (outcome !== null) {
4651
- results.push(outcome === "applied" ? { key: "approval_exemption", status: "written", target: "github.rulesets" }
4652
- : outcome === "declined" ? { key: "approval_exemption", status: "declined", target: "github.rulesets" }
4653
- : outcome === "not_needed" ? { key: "approval_exemption", status: "unchanged", target: "github.rulesets" }
4654
- : outcome === "could_not_tell"
4655
- ? { key: "approval_exemption", status: "uncertain", target: "github.rulesets", reason: "the ruleset change could not be confirmed", fix: "Check the ruleset yourself; setup will not retry it blindly." }
4656
- : { key: "approval_exemption", status: "refused", target: "github.rulesets", reason: "the approval rule is not safe to change automatically", fix: "Follow the manual steps printed above." });
5140
+ results.push(mapExemptionOutcomeToWriteResult(outcome));
4657
5141
  }
4658
5142
  return results;
4659
5143
  }
@@ -4802,6 +5286,15 @@ async function runConvergingSetup(options, deps, setup) {
4802
5286
  // BAPI-1638: the answers path plans the gate without a terminal, so no discovered
4803
5287
  // declaration joins it unless its own answer approves it below.
4804
5288
  const planIo = options.answers !== undefined ? { ...gateIo, isTTY: false, promptLine: undefined } : gateIo;
5289
+ // BAPI-1677: one read of the learned text per run, shared by everything that needs it.
5290
+ if (deps.gate !== undefined && deps.gate.learnedInstructions === undefined) {
5291
+ let learned;
5292
+ const readLearned = () => {
5293
+ learned ??= readLearnedInstructions(setup.testingConfig(access)).catch(() => null);
5294
+ return learned;
5295
+ };
5296
+ deps = { ...deps, gate: { ...deps.gate, learnedInstructions: readLearned } };
5297
+ }
4805
5298
  const gatePhase = await resolveConductorGate(planIo, access, options.gate, deps.gate, {
4806
5299
  dryRun: options.dryRun,
4807
5300
  planningOnly: true,
@@ -4819,7 +5312,8 @@ async function runConvergingSetup(options, deps, setup) {
4819
5312
  const setupPath = collectDecisions ? "agent" : "terminal";
4820
5313
  // BAPI-1657: the gate plan is resolved above, so its planned write is known before any setup item is projected.
4821
5314
  const plannedGateWrite = gatePlan !== null && gatePlan.write !== null;
4822
- const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, snapshot, readToolchains, gateRequiresManagedCheck, plannedGateWrite, path: setupPath };
5315
+ const storedDependencyInstall = gatePlan?.current.profile?.dependency_install ?? [];
5316
+ const collectInputs = { claudeLoggedIn, githubSignIn, localRemote, snapshot, readToolchains, gateRequiresManagedCheck, plannedGateWrite, path: setupPath, dependencyInstall: storedDependencyInstall };
4823
5317
  const first = await progress("checking readiness", () => collectSetupEvidence(deps, setup, access, firstReport.readiness, { ...collectInputs, advisories }));
4824
5318
  const state = {
4825
5319
  evidence: first.evidence,
@@ -4833,7 +5327,11 @@ async function runConvergingSetup(options, deps, setup) {
4833
5327
  trial: null,
4834
5328
  promotedCommands: null,
4835
5329
  failedOperations: [],
5330
+ sealedDependencyInstall: storedDependencyInstall,
4836
5331
  };
5332
+ // BAPI-1677: whether a test trial can be offered, known before anything reads it.
5333
+ if (gatePlan !== null)
5334
+ gatePlan.testCommandTrial = await resolveTestCommandTrial(deps, setup, access, gatePlan, state.storedCommand);
4837
5335
  // BAPI-1654: which CI systems the repository's files configure, read-only, independent of the remote host.
4838
5336
  if (deps.gate?.discoveryFs !== undefined) {
4839
5337
  const detected = await detectCiSystems(deps.gate.discoveryFs);
@@ -4875,24 +5373,52 @@ async function runConvergingSetup(options, deps, setup) {
4875
5373
  ...(options.epicServerChange === true ? { epicServerChangeRequested: true } : {}),
4876
5374
  };
4877
5375
  const fixes = planSetupFixes(state.evidence, planContext);
5376
+ // BAPI-1667: one read-only snapshot for both setup paths. An ordinary interactive run
5377
+ // reads it only when it will ask a question that uses it.
5378
+ const epicServerSnapshot = setup.epicServer !== undefined && (collectDecisions || fixes.includes("epic_server") || fixes.includes("mcp_grant"))
5379
+ ? await collectEpicServerSnapshot(deps, setup.epicServer, access.repoName, grantInventory)
5380
+ : null;
4878
5381
  // ---- BAPI-1638: the decision evidence behind every open choice (read-only) ----
4879
5382
  // Collected for `--json` and `--answers` only: an ordinary interactive run asks at
4880
5383
  // each decision point exactly as before and needs no catalog.
4881
5384
  const epicBranchCiWanted = options.epicBranchCiDecision !== undefined || deps.gate?.epicBranchCi !== undefined;
4882
5385
  const epicBranchCollected = collectDecisions && epicBranchCiWanted ? await collectEpicBranchCi(deps.gate) : undefined;
4883
- const declarationPlan = collectDecisions && gatePlan !== null
4884
- ? await planDeclarationSelections(gatePlan.current, gatePlan.desired, deps.gate)
4885
- : [];
5386
+ const declarationPlanning = collectDecisions && gatePlan !== null
5387
+ ? await planDeclarations(gatePlan.current, gatePlan.desired, deps.gate)
5388
+ : { entries: [], dependencyInstall: null };
5389
+ const declarationPlan = declarationPlanning.entries;
5390
+ // BAPI-1677: the install answer is resolved here, before anything hashes the workflow,
5391
+ // so the approved hash and the delivered bytes come from one list. A refused value
5392
+ // reads as no answer; normalization refuses the whole file below.
5393
+ const dependencyAnswerParsed = answersEnvelope !== null && answersEnvelope.dependency_install !== undefined
5394
+ ? parseAnswerValue("dependency_install", answersEnvelope.dependency_install)
5395
+ : null;
5396
+ const dependencyCorrection = dependencyAnswerParsed?.ok === true && dependencyAnswerParsed.decision.kind === "dependency_install_entries"
5397
+ ? dependencyAnswerParsed.decision.entries
5398
+ : null;
5399
+ const effectiveDependencyInstall = resolveEffectiveDependencyInstall(declarationPlanning.dependencyInstall, storedDependencyInstall, dependencyCorrection !== null
5400
+ ? { entries: dependencyCorrection }
5401
+ : dependencyAnswerParsed?.ok === true ? answersEnvelope?.dependency_install : undefined);
5402
+ if (declarationPlanning.dependencyInstall !== null) {
5403
+ const note = await defaultBranchInstallNote(setup, state.snapshot, declarationPlanning.dependencyInstall);
5404
+ if (note !== null)
5405
+ declarationPlanning.dependencyInstall.limitations.push(note);
5406
+ if (parseDependencyInstallStrict(effectiveDependencyInstall) === null) {
5407
+ declarationPlanning.dependencyInstall.limitations.push("Bridge will not offer its CI workflow, because an install command cannot be written into it safely.");
5408
+ }
5409
+ }
4886
5410
  // BAPI-1654: the one CI change on offer, from the default-branch snapshot (read-only).
4887
5411
  const ciOfferCollection = collectDecisions && epicBranchCollected !== undefined
4888
5412
  ? await collectCiOffer({
4889
- setup, state, collected: epicBranchCollected, readToolchains,
5413
+ setup, state, collected: epicBranchCollected, readToolchains, dependencyInstall: effectiveDependencyInstall,
4890
5414
  })
4891
5415
  : null;
4892
5416
  const decisionEvidence = collectDecisions
4893
5417
  ? await collectDecisionEvidence({
4894
5418
  deps, options, access, gatePlan, state, fixes, grantInventory, firstReport,
4895
- declarationPlan, epicBranchCollected, readToolchains, firstItems, ciOffer: ciOfferCollection,
5419
+ declarationPlan, epicBranchCollected, readToolchains, firstItems, ciOffer: ciOfferCollection, epicServerSnapshot,
5420
+ dependencyInstallFacts: declarationPlanning.dependencyInstall, effectiveDependencyInstall,
5421
+ correctedDependencyInstall: dependencyCorrection !== null,
4896
5422
  })
4897
5423
  : null;
4898
5424
  const choices = decisionEvidence === null ? [] : buildInstallChoices(decisionEvidence);
@@ -4921,6 +5447,9 @@ async function runConvergingSetup(options, deps, setup) {
4921
5447
  items: firstItems,
4922
5448
  decisions: decisionEvidence,
4923
5449
  choices: normalized.choices,
5450
+ ...(normalized.proposal !== undefined
5451
+ ? { proposalPresentation: plannedPresentation(normalized.proposal, gatePlan, fixes.includes("gate_and_defaults"), decisionEvidence.gate?.consequence ?? "", firstReport.readiness ?? null, state.evidence) }
5452
+ : {}),
4924
5453
  ...(normalized.proposal !== undefined ? { proposal: normalized.proposal } : {}),
4925
5454
  ...(normalized.digest !== undefined ? { digest: normalized.digest } : {}),
4926
5455
  ...(!normalized.ok ? { refusal: normalized.refusal } : {}),
@@ -5032,24 +5561,53 @@ async function runConvergingSetup(options, deps, setup) {
5032
5561
  };
5033
5562
  // BAPI-1659: whether the setup pull request really opened this run. Only then may a declined CI
5034
5563
  // change say the workflow still arrives through it; an approved answer alone proves nothing.
5035
- let setupWorkflowOpened = false;
5564
+ // BAPI-1679: `opened` covers a pull request this run opened or found already open, and
5565
+ // `in_place` a workflow already identical on the default branch. A rerun must not read either as nothing.
5566
+ let setupWorkflowDelivery = "none";
5036
5567
  const operations = [
5037
5568
  {
5038
5569
  key: "gate",
5039
5570
  run: async () => {
5040
5571
  if (gatePlan === null)
5041
5572
  return null;
5042
- const approvedDeclarations = proposal === null ? [] : declarationPlan.filter((e) => optionOf(e.key) === "approve");
5573
+ // BAPI-1677: a correction replaces the planned list before the PUT is built. It is
5574
+ // validated already, and it never merges with what discovery found.
5575
+ const corrected = answerOf("dependency_install");
5576
+ const correctionEntry = corrected?.kind === "dependency_install_entries"
5577
+ ? { key: "dependency_install", proposalKeys: [], fields: { dependencyInstall: corrected.entries }, summary: [] }
5578
+ : null;
5579
+ const resultPlan = correctionEntry === null ? declarationPlan : [...declarationPlan.filter((e) => e.key !== "dependency_install"), correctionEntry];
5580
+ const approvedDeclarations = proposal === null ? [] : resultPlan.filter((e) => optionOf(e.key) === "approve" || e === correctionEntry);
5043
5581
  const gateOpen = fixes.includes("gate_and_defaults");
5044
5582
  if (!gateOpen && approvedDeclarations.length === 0) {
5045
5583
  if (proposal === null)
5046
5584
  return null;
5585
+ // BAPI-1701: no planned write is not a stored gate. An unresolved plan says why, with its own fix.
5586
+ const unresolved = unresolvedGateResult(gatePlan);
5587
+ if (unresolved !== null)
5588
+ return [unresolved];
5047
5589
  return settledGateResults(proposal);
5048
5590
  }
5049
5591
  const gateAnswer = proposal === null ? undefined : gateOpen ? (optionOf("gate") === "decline" ? "decline" : "approve") : "approve";
5050
5592
  const plan = applyApprovedDeclarations(gatePlan, approvedDeclarations);
5051
5593
  policyResult = await fixGateAndDefaults(deps, options, access, plan, reviewDefault, true, gateAnswer);
5052
- return gateWriteResults(policyResult, proposal, declarationPlan);
5594
+ // BAPI-1677: what is stored is read back; what discovery found never stands in for it.
5595
+ let installReadBack;
5596
+ const installApproved = approvedDeclarations.some((e) => e.key === "dependency_install");
5597
+ if (installApproved && (policyResult.status === "completed" || policyResult.status === "unchanged")) {
5598
+ try {
5599
+ const back = await fetchConductorGateProfile(access, deps.fetchJson);
5600
+ const entries = back.profile?.dependency_install ?? [];
5601
+ state.sealedDependencyInstall = entries;
5602
+ const wanted = approvedDeclarations.find((e) => e.key === "dependency_install")?.fields.dependencyInstall ?? [];
5603
+ installReadBack = !sameDependencyInstall(entries, wanted) ? null
5604
+ : entries.map((e) => `${e.argv.join(" ")} (in ${e.cwd}; runs again when ${e.lockfiles.join(", ")} changes)`);
5605
+ }
5606
+ catch {
5607
+ installReadBack = null;
5608
+ }
5609
+ }
5610
+ return gateWriteResults(policyResult, proposal, resultPlan, installReadBack);
5053
5611
  },
5054
5612
  },
5055
5613
  {
@@ -5061,8 +5619,18 @@ async function runConvergingSetup(options, deps, setup) {
5061
5619
  await runTestCommandPhase(deps, options, setup, access, baseUrl, state, gatePlan, policyResult, answer);
5062
5620
  settleCiPlan(deps, state, gatePlan);
5063
5621
  // BAPI-1657: only the no-command remedy needs the launcher text, so detection runs only for that outcome.
5064
- const launcher = state.trial?.status === "no_command" ? await detectedLauncherBase(deps, access.repoName) : undefined;
5065
- return trialWriteResult(state.trial, proposal !== null && answer !== undefined && answer.decision !== "skip" && answer.decision !== "keep", launcher);
5622
+ // BAPI-1701: and only for a rejected candidate. Informational and retry results name no command to enter.
5623
+ const launcher = state.trial?.status === "no_command" && needsLauncherRemedy(state.trial.reason)
5624
+ ? await detectedLauncherBase(deps, access.repoName)
5625
+ : undefined;
5626
+ const trialResult = trialWriteResult(state.trial, proposal !== null && answer !== undefined && answer.decision !== "skip" && answer.decision !== "keep", launcher);
5627
+ // BAPI-1677: a replay names what the trial proved, so the setup record reads the same. The
5628
+ // gate's local commands are that proof. The separate stored test command can still be unset.
5629
+ const proven = gatePlan?.current.profile?.local_commands.map((c) => c.argv.join(" ")) ?? [];
5630
+ const ran = proven.length > 0 ? proven : state.storedCommand !== null ? [state.storedCommand] : [];
5631
+ return trialResult?.status === "unchanged" && ran.length > 0
5632
+ ? { ...trialResult, read_back: { ran } }
5633
+ : trialResult;
5066
5634
  },
5067
5635
  },
5068
5636
  {
@@ -5083,8 +5651,14 @@ async function runConvergingSetup(options, deps, setup) {
5083
5651
  const outcome = await runWorkflowPhase(deps, options, setup, access, baseUrl, state, readToolchains, gateRequiresManagedCheck, setupPr);
5084
5652
  if (managedWorkflowInPlay(state, gateRequiresManagedCheck))
5085
5653
  await warnDefaultBranchRequiresManagedCheck(setup, state);
5086
- const written = workflowWriteResult(outcome, proposal !== null && setupPr !== undefined);
5087
- setupWorkflowOpened = written?.status === "written";
5654
+ const written = workflowWriteResult(outcome, proposal !== null && setupPr !== undefined, setupPr);
5655
+ if (written?.status === "written")
5656
+ setupWorkflowDelivery = "opened";
5657
+ else if (written?.status === "unchanged" && outcome.status === "unchanged")
5658
+ setupWorkflowDelivery = outcome.url !== undefined ? "opened" : "in_place";
5659
+ // A creation with an uncertain result is read again; an open pull request is a fact.
5660
+ else if (outcome.status === "failed" && state.evidence.workflow.state === "pr_open")
5661
+ setupWorkflowDelivery = "opened";
5088
5662
  return written;
5089
5663
  },
5090
5664
  },
@@ -5144,7 +5718,7 @@ async function runConvergingSetup(options, deps, setup) {
5144
5718
  const d = answerOf("worker_mcp_grant");
5145
5719
  const answer = proposal === null || d === undefined ? undefined
5146
5720
  : d.kind === "selection" ? { decision: "select", ids: d.ids } : { decision: "decline" };
5147
- const outcome = await fixMcpGrant(deps, setup.mcpGrant, access.repoName, grantInventory, answer);
5721
+ const outcome = await fixMcpGrant(deps, setup.mcpGrant, access.repoName, grantInventory, answer, sfccGrantIds(epicServerSnapshot, grantInventory));
5148
5722
  return fixOutcomeResult("worker_mcp_grant", "mcp_grant", outcome);
5149
5723
  },
5150
5724
  },
@@ -5158,21 +5732,36 @@ async function runConvergingSetup(options, deps, setup) {
5158
5732
  if (proposal === null || d === undefined || (d.kind === "option" && d.option === "keep"))
5159
5733
  return null;
5160
5734
  }
5161
- const answer = proposal === null || d === undefined ? undefined : await epicServerAnswer(setup.epicServer, d);
5162
- const outcome = await fixEpicServer(deps, setup.epicServer, access.repoName, answer);
5735
+ const answer = proposal === null || d === undefined ? undefined : await epicServerAnswer(setup.epicServer, d, epicServerSnapshot);
5736
+ const outcome = await fixEpicServer(deps, setup.epicServer, access.repoName, answer, epicServerSnapshot);
5163
5737
  epicServerChanged = outcome.status === "written";
5164
5738
  return fixOutcomeResult("epic_server", "epic_server_record", outcome);
5165
5739
  },
5166
5740
  },
5167
5741
  {
5168
5742
  key: "epic_branch_ci",
5169
- run: async () => {
5743
+ run: async (completed) => {
5170
5744
  // The inspection runs once on every ordinary run: an explicit flag wins, a confirmed
5171
5745
  // workflow on epic-branch PRs is recorded as include, and anything else is only reported.
5172
5746
  if (!epicBranchCiWanted)
5173
5747
  return null;
5174
- const ci = optionOf("epic_branch_ci");
5175
5748
  const exemption = optionOf("approval_exemption");
5749
+ // BAPI-1679: a recommended `include` whose only support was the setup pull request stands
5750
+ // only if that pull request delivered. A stated answer or flag is never touched, and the
5751
+ // proposal and its digest stay as approved: only what this step stores changes.
5752
+ const lostSetupCredit = proposal !== null && resolvedChoices !== undefined && setupWorkflowDelivery === "none"
5753
+ && proposal.decisions.find((d) => d.key === "epic_branch_ci")?.source === "recommended"
5754
+ && optionOf("epic_branch_ci") === "include"
5755
+ && epicBranchCiIncludeRestsOnSetupPr(resolvedChoices, optionOf, { setupSuppliesWorkflow: decisionEvidence?.epicBranchCi?.managedWorkflowViaSetupPr === true });
5756
+ const setupPrStatus = completed.get("setup_pr")?.status;
5757
+ const creditNote = lostSetupCredit
5758
+ ? describeUnopenedSetupCredit({
5759
+ confirmed: setupPrStatus !== "failed" && setupPrStatus !== "uncertain",
5760
+ coverage: decisionEvidence?.epicBranchCi?.coverage ?? null,
5761
+ integrationTarget: ciOfferCollection?.evidence.integrationTarget ?? null,
5762
+ })
5763
+ : undefined;
5764
+ const ci = lostSetupCredit ? "decline" : optionOf("epic_branch_ci");
5176
5765
  const epicBranchCi = await runEpicBranchCiInspection(gateIo, access, deps.gate, {
5177
5766
  decisionFlag: proposal !== null && (ci === "include" || ci === "decline") ? ci : options.epicBranchCiDecision ?? null,
5178
5767
  dryRun: false,
@@ -5181,6 +5770,7 @@ async function runConvergingSetup(options, deps, setup) {
5181
5770
  ...(proposal !== null ? { exemptionDecision: exemption === "approve" ? "approve" : "decline" } : {}),
5182
5771
  // On the answers path a decision readiness already reports is not written again.
5183
5772
  ...(proposal !== null ? { recordedDecision: firstReport.readiness?.epic_branch_ci?.decision ?? null } : {}),
5773
+ ...(creditNote !== undefined ? { decisionNote: creditNote } : {}),
5184
5774
  });
5185
5775
  if (epicBranchCi.manualAction !== null)
5186
5776
  state.evidence.advisories.push(epicBranchCi.manualAction);
@@ -5188,9 +5778,10 @@ async function runConvergingSetup(options, deps, setup) {
5188
5778
  await runGateConsequenceSummary(gateIo, access, deps.gate);
5189
5779
  // BAPI-1654: the plain state, in the same words the choice used.
5190
5780
  const stateText = epicBranchCiStateText(decisionEvidence?.epicBranchCi ?? null);
5191
- if (proposal !== null && stateText !== null)
5781
+ // The note already replaced it when the credit fell through: this text is from before the apply.
5782
+ if (proposal !== null && stateText !== null && creditNote === undefined)
5192
5783
  deps.log(` ${stateText}`);
5193
- return epicBranchWriteResults(epicBranchCi, proposal !== null);
5784
+ return epicBranchWriteResults(epicBranchCi, proposal !== null, creditNote);
5194
5785
  },
5195
5786
  },
5196
5787
  {
@@ -5209,7 +5800,7 @@ async function runConvergingSetup(options, deps, setup) {
5209
5800
  const text = describeDeclinedCiChange({
5210
5801
  coverage: decisionEvidence?.epicBranchCi?.coverage ?? null,
5211
5802
  integrationTarget: ciOfferCollection?.evidence.integrationTarget ?? null,
5212
- coverageViaApprovedSetup: decisionEvidence?.epicBranchCi?.managedWorkflowViaSetupPr === true && setupWorkflowOpened,
5803
+ coverageViaApprovedSetup: decisionEvidence?.epicBranchCi?.managedWorkflowViaSetupPr === true && setupWorkflowDelivery === "opened",
5213
5804
  });
5214
5805
  deps.log("");
5215
5806
  deps.log("CI change for epic branches");
@@ -5238,7 +5829,11 @@ async function runConvergingSetup(options, deps, setup) {
5238
5829
  result = await setup.installCiTriggerEdit(delivery.edit, { dryRun: false, ...snapshotOption }, approved);
5239
5830
  }
5240
5831
  else {
5241
- result = await setup.installCiWorkflow(delivery.command, delivery.toolchains, { dryRun: false, createOnly: true, ...snapshotOption }, approved);
5832
+ // BAPI-1677: a workflow never installs commands the gate did not store.
5833
+ if (!sameDependencyInstall(delivery.dependencyInstall, state.sealedDependencyInstall)) {
5834
+ return { key: "epic_ci_change", status: "unattempted", target, reason: "the install commands this workflow uses were not stored", fix: "Rerun setup; nothing was opened." };
5835
+ }
5836
+ result = await setup.installCiWorkflow(delivery.command, delivery.toolchains, { dryRun: false, createOnly: true, ...snapshotOption, ...dependencyInstallOption(delivery.dependencyInstall) }, approved);
5242
5837
  }
5243
5838
  }
5244
5839
  catch {
@@ -5322,6 +5917,7 @@ async function runConvergingSetup(options, deps, setup) {
5322
5917
  // toolchains it already has, and never repeats a trial or an offer.
5323
5918
  const closing = await progress("checking readiness", () => collectSetupEvidence(deps, setup, access, finalReadiness, {
5324
5919
  ...collectInputs,
5920
+ dependencyInstall: state.sealedDependencyInstall,
5325
5921
  // BAPI-1657: after an apply, approval has already happened, so a gate still unknown is not
5326
5922
  // "stored on approval". Only a dry run's closing preview keeps that promise.
5327
5923
  plannedGateWrite: plannedGateWrite && options.dryRun === true,
@@ -5459,16 +6055,117 @@ async function runConvergingSetup(options, deps, setup) {
5459
6055
  ...(resolvedChoices !== undefined ? { choices: resolvedChoices } : {}),
5460
6056
  ...(proposal !== null ? { proposal } : {}),
5461
6057
  ...(proposalDigest !== null ? { digest: proposalDigest } : {}),
5462
- ...(proposal !== null ? { apply: applyResult } : {}),
6058
+ ...(proposal !== null ? { apply: applyResult, applyPresentation: confirmedPresentation(finalReadiness, closing.evidence, items, unmet, applyResult) } : {}),
5463
6059
  });
5464
6060
  deps.log("");
5465
6061
  const ready = unmet.length === 0 && (proposal === null || applyResult.complete);
5466
6062
  deps.log(setupVerdictLine(items));
5467
6063
  // Exactly one next step: the first unmet blocking item's remedy, or the start command.
5468
- deps.log(`Next step: ${unmet.length === 0 ? (ready ? "Run drive-epic to start your first epic" : "Rerun setup with the same answers to finish the writes listed above") : setupItemRemedy(unmet[0])}`);
6064
+ // BAPI-1701: when nothing blocks readiness but a write did not finish, the next step is that write's own
6065
+ // fix (the gate's first), the same one the structured verdict carries. The generic rerun is only the fallback.
6066
+ const writeNextStep = unmet.length === 0 && !ready && proposal !== null
6067
+ ? applyResultNextStep(applyResult)
6068
+ : undefined;
6069
+ deps.log(writeNextStep ??
6070
+ `Next step: ${unmet.length === 0 ? (ready ? "Run drive-epic to start your first epic" : "Rerun setup with the same answers to finish the writes listed above") : setupItemRemedy(unmet[0])}`);
5469
6071
  deps.log(ready ? "complete" : "complete-with-manual-steps");
5470
6072
  return ready ? conductorInstallDoctorExitCode(finalReport) : 1;
5471
6073
  }
6074
+ /**
6075
+ * BAPI-1701: the one next step drawn from the first incomplete write's own fix, the gate's before any other.
6076
+ * `undefined` when no incomplete write carries a fix. Pure text from the result; nothing is parsed.
6077
+ */
6078
+ export function applyResultNextStep(applyResult) {
6079
+ const incomplete = applyResult.results.filter((r) => r.status === "failed" || r.status === "refused" || r.status === "uncertain" || r.status === "unattempted");
6080
+ const fix = (incomplete.find((r) => r.key === "gate" && r.fix !== undefined) ?? incomplete.find((r) => r.fix !== undefined))?.fix;
6081
+ if (fix === undefined)
6082
+ return undefined;
6083
+ const line = fix.replace(/\s+/g, " ").trim();
6084
+ return line.startsWith("Next step:") ? line : `Next step: ${line}`;
6085
+ }
6086
+ /** BAPI-1678 — a readable stored gate, with required and watched checks apart. Anything else is unknown. */
6087
+ function storedGateEvidence(profile) {
6088
+ if (profile === null || profile === undefined || profile.read_failed || profile.stored_malformed || profile.kind === null)
6089
+ return null;
6090
+ if (profile.source !== "stored" && profile.source !== "legacy")
6091
+ return null;
6092
+ return {
6093
+ kind: profile.kind,
6094
+ requiredChecks: profile.provider_checks.filter((c) => c.watched !== true).map((c) => c.name),
6095
+ watchedChecks: profile.provider_checks.filter((c) => c.watched === true).map((c) => c.name),
6096
+ };
6097
+ }
6098
+ function storedCommandEvidence(evidence, profile) {
6099
+ if ((profile?.local_commands.length ?? 0) > 0)
6100
+ return true;
6101
+ return evidence.testCommand.state === "unknown" ? null : evidence.testCommand.state === "stored";
6102
+ }
6103
+ function managedWorkflowEvidence(evidence) {
6104
+ const { state } = evidence.workflow;
6105
+ return state === "unknown" || state === "blocked" ? null : state === "installed";
6106
+ }
6107
+ /** BAPI-1678 — the proposal's wording, from evidence this run already read. No further read. */
6108
+ function plannedPresentation(proposal, gatePlan, gateWriteNeeded, plannedConsequence, readiness, evidence) {
6109
+ const stored = readiness?.gate_profile;
6110
+ const gateDecision = decisionFor(proposal, "gate");
6111
+ const approved = gatePlan !== null && gateWriteNeeded && gateDecision?.kind === "option" && gateDecision.option === "approve";
6112
+ const desired = approved ? gatePlan.desired : null;
6113
+ const gate = desired === null
6114
+ ? storedGateEvidence(stored)
6115
+ : {
6116
+ kind: desired.kind,
6117
+ requiredChecks: desired.providerChecks.filter((c) => !(desired.watchedChecks ?? []).includes(c)),
6118
+ watchedChecks: [...(desired.watchedChecks ?? [])],
6119
+ };
6120
+ // A command this gate write would add is not stored yet, and it is not proof of absence either.
6121
+ const storedCommand = storedCommandEvidence(evidence, stored);
6122
+ const localCommandStored = storedCommand !== true && (desired?.localCommands.length ?? 0) > 0 ? null : storedCommand;
6123
+ const ciFacts = readiness?.epic_branch_ci ?? null;
6124
+ const ciDecision = decisionFor(proposal, "epic_branch_ci");
6125
+ const decision = ciDecision?.kind === "decline" || (ciDecision?.kind === "option" && ciDecision.option === "decline")
6126
+ ? "decline"
6127
+ : ciDecision?.kind === "option" && ciDecision.option === "include" ? "include" : ciFacts?.decision ?? null;
6128
+ const testDecision = decisionFor(proposal, "test_command");
6129
+ const trialSelected = testDecision?.kind === "command" || (testDecision?.kind === "option" && testDecision.option === "learn");
6130
+ const consequence = desired !== null
6131
+ ? plannedConsequence
6132
+ : gate === null ? "" : describeGateConsequence({ kind: gate.kind, hasWatchedChecks: gate.watchedChecks.length > 0 }, ciFacts);
6133
+ return buildProposalPresentation({
6134
+ evidence: {
6135
+ gate,
6136
+ localCommandStored,
6137
+ managedWorkflowInstalled: managedWorkflowEvidence(evidence),
6138
+ // A stated decline is known without the server's facts. Anything else needs them.
6139
+ epicBranchCi: ciFacts !== null
6140
+ ? { decision, noCiReasons: ciFacts.no_ci_reasons }
6141
+ : decision === "decline" ? { decision, noCiReasons: [] } : null,
6142
+ },
6143
+ trialPending: trialSelected && storedCommand !== true,
6144
+ consequence,
6145
+ });
6146
+ }
6147
+ /** BAPI-1678 — the verdict, from the readiness and evidence the closing check already captured. */
6148
+ function confirmedPresentation(readiness, evidence, items, unmet, applyResult) {
6149
+ const ready = deriveCompactReadiness({ readinessObserved: readiness !== null, items });
6150
+ const stored = readiness?.gate_profile;
6151
+ const ciFacts = readiness?.epic_branch_ci ?? null;
6152
+ const protection = classifyMergeTestProtection({
6153
+ gate: storedGateEvidence(stored),
6154
+ localCommandStored: storedCommandEvidence(evidence, stored),
6155
+ managedWorkflowInstalled: managedWorkflowEvidence(evidence),
6156
+ epicBranchCi: ciFacts === null ? null : { decision: ciFacts.decision, noCiReasons: ciFacts.no_ci_reasons },
6157
+ });
6158
+ return {
6159
+ verdict: buildInstallVerdict({
6160
+ ready,
6161
+ blockers: unmet.map((item) => ({ label: item.label, fix: setupItemRemedy(item) })),
6162
+ results: applyResult.results,
6163
+ protection,
6164
+ }),
6165
+ ...(ready !== undefined ? { ready } : {}),
6166
+ ...(protection !== undefined ? { merge_test_protection: protection } : {}),
6167
+ };
6168
+ }
5472
6169
  /** The deny probe could not answer: an advisory, never readiness. */
5473
6170
  function deniesEnforcementUnknown(report) {
5474
6171
  const deny = report.legacyConductor?.deny_enforcement;
@@ -5504,7 +6201,7 @@ async function closingMcpGrantState(grantDeps, repoName, inventory) {
5504
6201
  ? { state: "met" }
5505
6202
  : { state: "needs_action", reason: "changed" };
5506
6203
  }
5507
- async function fixMcpGrant(deps, grantDeps, repoName, inventory, answer) {
6204
+ export async function fixMcpGrant(deps, grantDeps, repoName, inventory, answer, sfccRecommendedIds = []) {
5508
6205
  deps.log("");
5509
6206
  deps.log("Worker MCP servers");
5510
6207
  deps.log(` Epic Implementer workers in ${repoName} always get Bridge. You can approve extra MCP servers for them, ` +
@@ -5542,6 +6239,10 @@ async function fixMcpGrant(deps, grantDeps, repoName, inventory, answer) {
5542
6239
  deps.log(" skipped approving MCP servers: there is no interactive terminal, so this counts as declined. Nothing changed.");
5543
6240
  return { status: "declined" };
5544
6241
  }
6242
+ // BAPI-1667: a pointer to the numbers. How an answer is read does not change.
6243
+ const recommendedNumbers = offered.flatMap((candidate, index) => candidate.definitions.some((definition) => sfccRecommendedIds.includes(definition.id)) ? [index + 1] : []);
6244
+ if (recommendedNumbers.length > 0)
6245
+ deps.log(` Recommended for this SFCC repository: ${recommendedNumbers.join(", ")}`);
5545
6246
  let positions = [];
5546
6247
  if (offered.length > 0) {
5547
6248
  const answer = await deps.promptLine(GRANT_SELECTION_PROMPT);
@@ -5684,7 +6385,7 @@ const EPIC_SERVER_MODE_ANSWERS = Object.freeze({
5684
6385
  sfcc: "sfcc_shared_active",
5685
6386
  sfcc_shared_active: "sfcc_shared_active",
5686
6387
  });
5687
- async function fixEpicServer(deps, epicDeps, repoName, answer) {
6388
+ export async function fixEpicServer(deps, epicDeps, repoName, answer, snapshot = null) {
5688
6389
  deps.log("");
5689
6390
  deps.log("Epic server for UI checks");
5690
6391
  deps.log(` An Epic Implementer run in ${repoName} can get one epic server: the driver starts the epic's code with a ` +
@@ -5694,25 +6395,40 @@ async function fixEpicServer(deps, epicDeps, repoName, answer) {
5694
6395
  deps.log(" kept — nothing changed. Any earlier choice stays in force.");
5695
6396
  return { status: "declined" };
5696
6397
  }
5697
- if (answer?.decision === "record")
5698
- return writeApprovedEpicServer(deps, epicDeps, repoName, answer.record);
6398
+ if (answer?.decision === "record") {
6399
+ // The apply summary prints these from the write's `reason`, so they appear once.
6400
+ const outcome = await writeApprovedEpicServer(deps, epicDeps, repoName, answer.record);
6401
+ return outcome.status === "failed" || answer.advisories === undefined ? outcome : { ...outcome, advisories: answer.advisories };
6402
+ }
5699
6403
  if (!deps.promptLine) {
5700
6404
  deps.log(" skipped configuring the epic server: there is no interactive terminal, so this counts as declined. Nothing changed.");
5701
6405
  return { status: "declined" };
5702
6406
  }
5703
- let hasRecord = false;
6407
+ let stored = null;
5704
6408
  try {
5705
- hasRecord = (await epicDeps.readRecord(repoName)).state === "ok";
6409
+ const read = await epicDeps.readRecord(repoName);
6410
+ stored = read.state === "ok" ? read.record : null;
5706
6411
  }
5707
6412
  catch {
5708
- hasRecord = false;
5709
- }
6413
+ stored = null;
6414
+ }
6415
+ const hasRecord = stored !== null;
6416
+ const existingSandbox = stored?.sfcc ?? null;
6417
+ const recommendation = recommendEpicServer(epicServerDecisionEvidence(stored?.mode ?? null, true, snapshot, existingSandbox !== null));
6418
+ const detected = snapshot?.detection?.detected === true;
6419
+ // The worker advisory prints once, in the sandbox follow-up, so it is left out of these two lines.
6420
+ const uploadText = detected && snapshot?.uploadCheck?.state !== "possible_with_advisory" ? describeSfccUpload(snapshot?.uploadCheck ?? { state: "unknown", missing: [] }) : "";
6421
+ const canAddSandbox = detected && isSfccUploadCapable(snapshot?.uploadCheck);
6422
+ const sandboxNext = canAddSandbox ? " You can approve a sandbox next, so cartridge changes upload in this mode too." : "";
6423
+ // A recommendation other than the safe default says why, and what is still owed, up front.
6424
+ if (!hasRecord && recommendation.recommended !== "none")
6425
+ deps.log(` Recommended: ${recommendation.recommended}. ${recommendation.why.replace(` ${WORKER_UPLOAD_ADVISORY}`, "")}`);
5710
6426
  const decision = await askPlainSetupQuestion({
5711
6427
  question: `Which epic server mode should Epic Implementer runs in ${repoName} use?`,
5712
6428
  options: [
5713
- { id: "none", label: "none: no epic server. Choose this if you have no running app to test against. UI checks are handed off to you." },
5714
- { id: "local", label: "local: the driver starts this epic's code with a throwaway test login. Choose this if the app can run on this machine; workers borrow it for browser tests." },
5715
- { id: "sfcc_shared_active", label: "sfcc_shared_active: one approved shared SFCC sandbox. Choose this for SFCC storefronts; you will name the sandbox next.", aliases: ["sfcc"] },
6429
+ { id: "none", label: `none: no epic server. Choose this if you have no running app to test against. UI checks are handed off to you.${sandboxNext}` },
6430
+ { id: "local", label: `local: the driver starts this epic's code with a throwaway test login. Choose this if the app can run on this machine; workers borrow it for browser tests.${sandboxNext}` },
6431
+ { id: "sfcc_shared_active", label: `sfcc_shared_active: one approved shared SFCC sandbox. Choose this for SFCC storefronts; you will name the sandbox next.${uploadText !== "" ? ` ${uploadText}` : ""}`, aliases: ["sfcc"] },
5716
6432
  {
5717
6433
  id: "keep",
5718
6434
  label: hasRecord
@@ -5721,12 +6437,14 @@ async function fixEpicServer(deps, epicDeps, repoName, answer) {
5721
6437
  aliases: ["skip", "n", "no"],
5722
6438
  },
5723
6439
  ],
5724
- recommended: hasRecord ? "keep" : "none",
6440
+ recommended: recommendation.recommended,
5725
6441
  recordingFlag: "no flag records this choice; rerun setup in an interactive terminal.",
5726
6442
  evidence: ["A missing epic server only hands UI checks off; it never blocks a run.", "Selecting a mode records it. It does not install tools, create a sandbox, or grant an MCP server."],
5727
6443
  consequences: [hasRecord
5728
6444
  ? "keep is recommended because a choice is already stored and pressing Enter should not replace it."
5729
- : "none is recommended because it needs nothing set up and is the safe default.",
6445
+ : recommendation.recommended === "none"
6446
+ ? "none is recommended because it needs nothing set up and is the safe default."
6447
+ : `${recommendation.recommended} is recommended: ${recommendation.why}`,
5730
6448
  "Nothing changes if you stop here."],
5731
6449
  recovery: "Rerun setup to choose again. Any earlier choice stays in force until then.",
5732
6450
  }, plainTerminalFor(deps));
@@ -5746,27 +6464,93 @@ async function fixEpicServer(deps, epicDeps, repoName, answer) {
5746
6464
  }
5747
6465
  record.recipe = present ? "present" : "absent";
5748
6466
  }
5749
- else if (mode === "sfcc_shared_active") {
5750
- deps.log(" Only non-secret values are asked for here. The sandbox account's secret stays in the credential store.");
5751
- const sandboxId = (await deps.promptLine(" Approved sandbox instance id: ")).trim();
5752
- if (!isValidSfccSandboxId(sandboxId)) {
5753
- deps.log(" That is not a usable sandbox id. Nothing changed; re-run setup to try again.");
5754
- return { status: "declined" };
5755
- }
5756
- const credentialRef = (await deps.promptLine(" Credential-store reference for its sandbox-only test account: ")).trim();
5757
- if (!isValidCredentialReference(credentialRef)) {
5758
- deps.log(" That is not a usable credential-store reference. Nothing changed; re-run setup to try again.");
5759
- return { status: "declined" };
5760
- }
5761
- const origin = normalizeStorefrontOrigin((await deps.promptLine(" Approved storefront origin (for example https://sandbox.example.com): ")).trim());
5762
- if (origin === null) {
5763
- deps.log(" That is not an http or https origin without a path, query, or credentials. Nothing changed.");
5764
- return { status: "declined" };
5765
- }
5766
- record.sfcc = { sandbox_id: sandboxId, credential_ref: credentialRef, storefront_origin: origin };
5767
- }
6467
+ const sandbox = await askApprovedSandbox(deps, epicDeps, mode, existingSandbox, snapshot);
6468
+ if (sandbox === "declined")
6469
+ return { status: "declined" };
6470
+ if (sandbox !== null)
6471
+ record.sfcc = sandbox;
5768
6472
  return writeApprovedEpicServer(deps, epicDeps, repoName, record);
5769
6473
  }
6474
+ /**
6475
+ * BAPI-1667 — the sandbox follow-up, after the mode. `sfcc_shared_active` always asks
6476
+ * and needs all three fields. `local` and `none` ask when upload can work or a sandbox
6477
+ * is already recorded, and Enter keeps a recorded one or skips. A failed check is
6478
+ * never consent to drop a recorded sandbox. Returns the target to store, null for no
6479
+ * sandbox, or "declined" when an answer was unusable.
6480
+ */
6481
+ async function askApprovedSandbox(deps, epicDeps, mode, existing, snapshot) {
6482
+ const required = mode === "sfcc_shared_active";
6483
+ const detected = snapshot?.detection?.detected === true;
6484
+ if (!required && existing === null && !(detected && isSfccUploadCapable(snapshot?.uploadCheck)))
6485
+ return null;
6486
+ const promptLine = deps.promptLine;
6487
+ const credentials = snapshot?.credentials ?? null;
6488
+ deps.log(" Approved sandbox");
6489
+ deps.log(" Only non-secret values are asked for here. The sandbox account's secret stays in the credential store.");
6490
+ deps.log(" The id is the sandbox host's first DNS label (for example zzzz-001 in zzzz-001.dx.commercecloud.salesforce.com).");
6491
+ if (detected && snapshot?.uploadCheck?.state === "possible_with_advisory")
6492
+ deps.log(` ${WORKER_UPLOAD_ADVISORY}`);
6493
+ const idHint = existing !== null
6494
+ ? required ? ` [Enter keeps ${existing.sandbox_id}]` : ` [Enter keeps ${existing.sandbox_id}, "remove" drops it]`
6495
+ : required ? "" : " (Enter skips)";
6496
+ const typedId = (await promptLine(` Approved sandbox instance id${idHint}: `)).trim();
6497
+ if (!required && typedId === "") {
6498
+ if (existing !== null)
6499
+ return existing;
6500
+ deps.log(` ${SANDBOX_SKIPPED_LINE}`);
6501
+ return null;
6502
+ }
6503
+ if (!required && existing !== null && typedId === "remove") {
6504
+ deps.log(` ${SANDBOX_SKIPPED_LINE}`);
6505
+ return null;
6506
+ }
6507
+ const sandboxId = typedId === "" && existing !== null ? existing.sandbox_id : typedId;
6508
+ if (!isValidSfccSandboxId(sandboxId)) {
6509
+ deps.log(" That is not a usable sandbox id. Nothing changed; re-run setup to try again.");
6510
+ return "declined";
6511
+ }
6512
+ // After the prompt, never inside it: a mismatch advises and the id is stored as entered.
6513
+ if (typedId !== "" && detected && epicDeps.sfccUploadCheck !== undefined) {
6514
+ for (const line of await recheckSfccSandboxId(epicDeps.sfccUploadCheck, sandboxId, { credentials }))
6515
+ deps.log(` ${line}`);
6516
+ }
6517
+ const defaultRef = existing?.credential_ref ?? suggestedCredentialEntry(credentials);
6518
+ for (const line of credentialQuestionLines(credentials, defaultRef))
6519
+ deps.log(` ${line}`);
6520
+ const typedRef = (await promptLine(" Worker credential entry: ")).trim();
6521
+ const credentialRef = typedRef === "" ? defaultRef : typedRef;
6522
+ if (credentialRef === null && !required) {
6523
+ deps.log(` ${SANDBOX_SKIPPED_LINE}`);
6524
+ return null;
6525
+ }
6526
+ if (!isValidCredentialReference(credentialRef)) {
6527
+ deps.log(" That is not a usable credential reference. Nothing changed; re-run setup to try again.");
6528
+ return "declined";
6529
+ }
6530
+ // An absent or unusable record was already said once, above the question.
6531
+ if (credentials?.recordState === "ok") {
6532
+ for (const line of credentialReferenceAdvisories(credentials, credentialRef))
6533
+ deps.log(` ${line}`);
6534
+ }
6535
+ const sameSandbox = existing !== null && existing.sandbox_id === sandboxId;
6536
+ if (!required) {
6537
+ return {
6538
+ sandbox_id: sandboxId,
6539
+ credential_ref: credentialRef,
6540
+ ...(sameSandbox && existing.storefront_origin !== undefined ? { storefront_origin: existing.storefront_origin } : {}),
6541
+ };
6542
+ }
6543
+ const originDefault = sameSandbox ? existing.storefront_origin ?? null : null;
6544
+ const typedOrigin = (await promptLine(originDefault !== null
6545
+ ? ` Approved storefront origin [Enter keeps ${originDefault}]: `
6546
+ : " Approved storefront origin (for example https://sandbox.example.com): ")).trim();
6547
+ const origin = normalizeStorefrontOrigin(typedOrigin === "" && originDefault !== null ? originDefault : typedOrigin);
6548
+ if (origin === null) {
6549
+ deps.log(" That is not an http or https origin without a path, query, or credentials. Nothing changed.");
6550
+ return "declined";
6551
+ }
6552
+ return { sandbox_id: sandboxId, credential_ref: credentialRef, storefront_origin: origin };
6553
+ }
5770
6554
  /** Write one approved record through `writeEpicServerRecord`, after the no-change check. */
5771
6555
  async function writeApprovedEpicServer(deps, epicDeps, repoName, record) {
5772
6556
  try {