@bridge_gpt/mcp-server 0.2.71 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -1,10 +1,11 @@
1
1
  import { writeRecentlyFailedTestsFile } from "./recently-failed-tests-file.js";
2
+ import { CI_FIX_PRIOR_TEST_RUNS_PAYLOAD_KEY, ciFixTestRunsFsFromDeps, dispatchedLogicalJob, seedCiFixTestRunsFile, withCiFixTestRuns, } from "./ci-fix-test-runs.js";
2
3
  import { guardedFastForwardPush } from "./guarded-fast-forward-push.js";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
5
  import path from "node:path";
5
6
  import { findWorktreeByBranch, parseGitWorktreePorcelain } from "./worktree-inspection.js";
6
7
  import { resolveExecutorBranch, configureExecutorBranch } from "./worktree.js";
7
- import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance, renderWorkerTimeBudgetGuidance } from "./worker-verification-guidance.js";
8
+ import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance, renderWorkerPushEachCommitGuidance, renderWorkerTimeBudgetGuidance } from "./worker-verification-guidance.js";
8
9
  /**
9
10
  * Claimed-job execution engine (BAPI-534 core, BAPI-535 job behaviors; TDD §7/§8/§9).
10
11
  *
@@ -37,26 +38,32 @@ import { resolveExecutorAgentAdapter } from "../agent-launchers/executor-adapter
37
38
  import { redactAdapterDiagnostic } from "../agent-launchers/executor-adapter.js";
38
39
  import { resolveExecutorAgentId } from "./agent-identity.js";
39
40
  import { closeStdinBounded, createProcessTerminationController, runProcessWithTimeout, writeStdinBounded, } from "./process.js";
40
- import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, verificationVerdictFromFacts, } from "./completion-contract.js";
41
+ import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, unresolvedRequiredTasks, verificationVerdictFromFacts, } from "./completion-contract.js";
41
42
  import { COMPLETION_CAUSE_ERROR_KINDS, EOF_DRAIN_BOUND_MS, STDIN_CLOSE_GRACE_MS, finalizationFacts, finalizationObligations, planCompletionAllowance, readCompletionBinding, readDeclaredChecks, readOptionalWatchers, readRequiredVerification, renderApprovedVerificationGuidance, } from "./completion-supervision.js";
42
43
  import { compareFinalArtifact, createRequiredVerificationRunner, createSupervisedCommandLauncher, observeFinalArtifact, OWNERSHIP_POLL_MS, preCheckArtifactState, toCompletionCheckFact, } from "./required-verification.js";
43
44
  import { createClosureSupervisor, createRequiredWorkLedger } from "./required-work-ledger.js";
45
+ import { COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT, requiredWorkKindTokens, } from "./required-work-diagnostics.js";
44
46
  import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withExecutorJobId, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
45
47
  import { resolveCompletionEvidenceCapability } from "../agent-launchers/executor-adapter.js";
46
48
  import { autoCheckpointDirtyState, PRIOR_ATTEMPT_WIP_COMMIT_MESSAGE, prepareResumeSpawn, prepareRetainedContinuationWorktree, readContinuationBinding, verifyContinuationHeadLineage, } from "./resume-pre-spawn.js";
47
- import { buildEpicWorkaroundWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
49
+ import { buildEpicWorkaroundWorkerInstruction, buildEpicCapabilityStatementWorkerInstruction, buildEpicServerWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
50
+ import { createDefaultEpicServerContextDeps, readEpicServerWorkerContext, withEpicServerEnv, } from "./epic-server-context.js";
48
51
  /** BAPI-1399: the job type whose worker implements ticket requirements from scratch. */
49
52
  const WORKAROUND_CONTRACT_JOB_TYPES = new Set(["implement"]);
50
53
  import { defaultResolveBinPath } from "../start-tickets-conductor.js";
51
54
  /** The packaged bin basename of the deterministic worker guard (BAPI-1020). */
52
55
  const WORKER_GUARD_BIN_FILENAME = "worker-guard-hook-bin.js";
53
- import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArtifact, buildSmokeResult, commitResidue, readCompletionArtifacts, resolveJobTimeoutSeconds, } from "./results.js";
56
+ import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArtifact, readCiFixTestRunsArtifact, buildSmokeResult, commitResidue, readCompletionArtifacts, RESULT_JSONB_MAX_BYTES, resolveJobTimeoutSeconds, } from "./results.js";
54
57
  import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
55
58
  import { removeStaleVerdictArtifacts } from "./stale-artifacts.js";
56
59
  import { stripWorkerEnvFiles } from "./env-file-guard.js";
57
- import { payloadWorkerEnvOption } from "./env.js";
60
+ import { buildDependencyInstallEnv, payloadCiDatabase, payloadDependencyInstallOption, payloadPrePrChecksOption, payloadWorkerEnvOption, validateDependencyInstallDeclarations, } from "./env.js";
61
+ import { validatePrePrCheckDeclarations, withPrePrChecksSummary } from "./pre-pr-checks.js";
62
+ import { refreshDeclaredDependencies } from "./dependency-refresh.js";
63
+ import { readVerificationHints } from "./verification-hints.js";
58
64
  import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine, } from "./worker-database.js";
59
65
  import { formatWorkerCliLauncherUnavailableLine } from "./worker-cli-launcher.js";
66
+ import { formatWorkerDatabaseMalformedLine, formatWorkerDatabaseModeLine, formatWorkerDatabaseSkippedObservationLine, payloadWorkerDatabaseConfigOption, payloadWorkerDatabaseMetadata, payloadWorkerDatabaseParse, } from "./worker-database-config.js";
60
67
  import { isVerdictJobType, readVerdictArtifact } from "./verdict-artifact.js";
61
68
  import { createWorkerLogClaimId, createWorkerLogTee, closeWorkerLogTee, distinctWorkerLogSessionIds, formatWorkerLogSessionInvariantWarning, teeAsyncIterable, } from "./worker-log.js";
62
69
  import { acquireExecutorWorktreeLock, } from "./worktree-lock.js";
@@ -71,12 +78,13 @@ import { deliveryHoldOf, readFocusedPullRequest, resolveOriginBranchSha, validat
71
78
  import { DELIVERY_OUTCOME_READ_TIMEOUT_MS, fetchServerDeliveryOutcome, } from "./delivery-outcome.js";
72
79
  import { FOCUSED_REBASE_JOB_TYPE, focusedRebaseContextError, hasFocusedRebaseContext, validateFocusedRebaseContext, waitForFocusedRebase, } from "./rebase-finalization.js";
73
80
  import { ensureExecutorWorktree, finalizeRetainedExecutorWorktree, } from "./worktree.js";
74
- import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
81
+ import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, renderPrePrChecks, renderRequiredBeforePush, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
75
82
  import { CORRECTION_INTENT_CAPABILITY, isRemainingWork, validateCorrectionIntent, } from "./correction-dispatch.js";
76
83
  import { collectGitTelemetry, collectRemoteTrackingSha, createMcpSurfaceObserver, evaluatePreSpawnGitVerification, formatWorkerRateLimitAdvisory, normalizeMcpServerNames, } from "./observation.js";
77
84
  import { failureReasonCode, isFailureReasonCode } from "./failure-reason-codes.js";
78
85
  import { readCustomizedCommands, TERMINAL_CAPACITY_PROTOCOL_VERSIONS, TERMINAL_CAPACITY_RUNTIME_CONTRACTS, TERMINAL_CAPACITY_RUNTIMES, } from "./types.js";
79
86
  import { resolvePackagedRecipes } from "./packaged-recipe.js";
87
+ import { recordObservedPr, recordVerificationFacts, recordVerificationObservation, withDeliveryObservations, } from "./delivery-observations.js";
80
88
  import { probeInstalledCorrectionHook } from "./preflight.js";
81
89
  import { isRecognizedServerName, MCP_SERVER_NAME } from "../mcp-identity.js";
82
90
  /**
@@ -111,6 +119,17 @@ const DELIVERY_OUTCOME_EXCLUDED_JOB_TYPES = new Set([
111
119
  "reconcile_overlap",
112
120
  "ci_fix",
113
121
  ]);
122
+ /**
123
+ * BAPI-1563: whether a server assessment permits an implementation job to report
124
+ * success: bound, available, and the boundary outcome is `awaiting_post_pr` or
125
+ * `complete`. Permission, not proof of verification.
126
+ */
127
+ function serverOutcomePermitsSuccess(outcome) {
128
+ return (outcome !== undefined &&
129
+ outcome.bound === true &&
130
+ outcome.unavailable !== true &&
131
+ (outcome.outcome === "awaiting_post_pr" || outcome.outcome === "complete"));
132
+ }
114
133
  /** BAPI-1426: the outcome used when the read could not run or failed. */
115
134
  const DELIVERY_OUTCOME_UNAVAILABLE = { bound: "unknown", unavailable: true };
116
135
  /**
@@ -164,6 +183,16 @@ function withFailureTelemetry(snapshot, failureTelemetry) {
164
183
  return failureTelemetry ? { ...snapshot, ...failureTelemetry } : snapshot;
165
184
  }
166
185
  /** ProcessClassification maps 1:1 onto the wire ExecutorClassification. */
186
+ /**
187
+ * BAPI-1554 — `; unresolved: <sorted tokens>` for the required work an envelope
188
+ * still lists as unresolved, or the empty string when there is none (so today's
189
+ * message stays byte-for-byte). Closed tokens only: never a task id, command,
190
+ * prompt, or output.
191
+ */
192
+ function unresolvedKindsSuffix(envelope) {
193
+ const tokens = requiredWorkKindTokens(unresolvedRequiredTasks(envelope).map((task) => task.kind));
194
+ return tokens.length > 0 ? `; unresolved: ${tokens.join(", ")}` : "";
195
+ }
167
196
  function toWireClassification(c) {
168
197
  return c;
169
198
  }
@@ -277,7 +306,7 @@ function buildJobLogRegistryDeps(deps) {
277
306
  * only correct value is the one the caller threads down from the validated
278
307
  * runtime configuration.
279
308
  */
280
- function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl) {
309
+ function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl, trustedRepoName) {
281
310
  return {
282
311
  readFile: deps.readFile,
283
312
  writeFile: deps.writeFile,
@@ -286,6 +315,11 @@ function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl) {
286
315
  cwd: deps.cwd,
287
316
  mcpServerInvocation: deps.mcpServerInvocation,
288
317
  bridgeApiBaseUrl,
318
+ // BAPI-1545: the grant file lives under the operator's home. Only the one
319
+ // non-secret path variable the lookup honors is passed, never the ambient env.
320
+ env: deps.env.XDG_CONFIG_HOME !== undefined ? { XDG_CONFIG_HOME: deps.env.XDG_CONFIG_HOME } : {},
321
+ homedir: deps.homedir,
322
+ ...(trustedRepoName !== undefined ? { trustedRepoName } : {}),
289
323
  };
290
324
  }
291
325
  /**
@@ -382,10 +416,19 @@ async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, sea
382
416
  path: worktreePath,
383
417
  };
384
418
  try {
385
- const result = await provision(row, buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl));
419
+ // BAPI-1545: the claimed job's `repo_name` comes from the server's claim
420
+ // response, never from a worktree file, so it is the trusted identity the
421
+ // grant is selected by.
422
+ const result = await provision(row, buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl, job.repo_name));
386
423
  for (const warning of result.warnings ?? []) {
387
424
  deps.errorLog(`MCP provisioning warning: ${warning}`);
388
425
  }
426
+ if (result.mcpGrantRegistration !== undefined) {
427
+ // The grant path is never downgraded to a fail-open warning: a
428
+ // registration that could not be made authoritative is refused by the
429
+ // runner, so a stale or worker-edited file is never spawned.
430
+ return result.mcpGrantRegistration;
431
+ }
389
432
  if (result.status === "spawn-failed") {
390
433
  deps.errorLog(`MCP provisioning did not complete (${result.error ?? "unknown reason"}); continuing fail-open`);
391
434
  }
@@ -397,7 +440,30 @@ async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, sea
397
440
  // failure can never leak anything into the executor's own logs.
398
441
  deps.errorLog("MCP provisioning did not complete; continuing fail-open");
399
442
  }
443
+ return null;
444
+ }
445
+ /** Fixed diagnostic when no capability statement line is appended (BAPI-1545). */
446
+ export const CAPABILITY_STATEMENT_NOT_APPENDED_MESSAGE = "capability statement: none appended to the worker prompt (absent, unavailable, or unreadable)";
447
+ /**
448
+ * BAPI-1545: read and render the advisory statement. Never throws; `null` means
449
+ * append nothing.
450
+ */
451
+ async function readCapabilityStatementLine(httpClient, repoName) {
452
+ if (typeof httpClient.readEpicCapabilityStatement !== "function")
453
+ return null;
454
+ try {
455
+ const read = await httpClient.readEpicCapabilityStatement(repoName);
456
+ if (!read.ok || read.state !== "present")
457
+ return null;
458
+ return buildEpicCapabilityStatementWorkerInstruction(read.statement);
459
+ }
460
+ catch {
461
+ return null;
462
+ }
400
463
  }
464
+ /** Fixed, secret-free refusal when the grant-path registration is not authoritative. */
465
+ export const GRANT_MCP_REGISTRATION_UNVERIFIED_MESSAGE = "the MCP grant registration for this worktree could not be written and verified; " +
466
+ "refusing to spawn a worker that could load a stale or edited MCP registration";
401
467
  /**
402
468
  * Confirm the prepared worktree's own `.mcp.json` carries the Bridge shim
403
469
  * registration the worker needs, and capture the spawn contract from it
@@ -635,42 +701,96 @@ function createNoopProcess(deps, durationMs, message) {
635
701
  };
636
702
  }
637
703
  /**
638
- * Bounded newline assembly of worker stdout into whole lines for a
704
+ * Bounded newline assembly of worker stdout into logical lines for a
639
705
  * {@link RequiredWorkLedger} (BAPI-1301 covered path, BAPI-1364 legacy
640
- * observation). A line that outgrows the event bound is handed over once (the
641
- * ledger marks it `stream_oversize`) and the rest of it is discarded up to its
642
- * newline. `onLine` runs after each completed line is ingested.
706
+ * observation; one implementation serves both).
707
+ *
708
+ * A line is assembled whole until its UTF-8 size crosses {@link MAX_EVENT_BYTES}.
709
+ * From then on it is streamed to the ledger's structural reader: the buffered
710
+ * prefix (opening brace included) first, then every later segment of the same
711
+ * line through its newline, however many chunks that takes. Nothing of the tail
712
+ * is discarded, and nothing is ever reinterpreted as a new event. The reader
713
+ * decides, once, when the line ends. `onLine` runs once per completed line, never
714
+ * per chunk. A trailing fragment with no newline is finalized by `flush()` and is
715
+ * never established.
643
716
  */
644
- function createLedgerLineFeeder(ledger, onLine) {
717
+ /** Exported for the feeder's own unit tests; the runner is its only production caller. */
718
+ export function createLedgerLineFeeder(ledger, onLine) {
719
+ const WINDOW_CHARS = 64 * 1024;
645
720
  let lineBuffer = "";
646
- let discardingOversize = false;
721
+ // UTF-8 bytes of `lineBuffer`, counted incrementally; a trailing high
722
+ // surrogate is held back until its pair (or lack of one) is known.
723
+ let lineBytes = 0;
724
+ let carryHigh = false;
725
+ let streaming = false;
726
+ const resetLine = () => {
727
+ lineBuffer = "";
728
+ lineBytes = 0;
729
+ carryHigh = false;
730
+ streaming = false;
731
+ };
732
+ const streamPrefix = () => {
733
+ ledger.beginOversizeLine();
734
+ for (let i = 0; i < lineBuffer.length; i += WINDOW_CHARS) {
735
+ ledger.feedOversizeLineChunk(lineBuffer.slice(i, i + WINDOW_CHARS));
736
+ }
737
+ lineBuffer = "";
738
+ lineBytes = 0;
739
+ carryHigh = false;
740
+ streaming = true;
741
+ };
742
+ const consumeWindow = (w) => {
743
+ if (w.length === 0)
744
+ return;
745
+ if (streaming) {
746
+ ledger.feedOversizeLineChunk(w);
747
+ return;
748
+ }
749
+ const body = (carryHigh ? lineBuffer.slice(-1) : "") + w;
750
+ const endsHigh = (() => {
751
+ const c = w.charCodeAt(w.length - 1);
752
+ return c >= 0xd800 && c <= 0xdbff;
753
+ })();
754
+ lineBytes += Buffer.byteLength(endsHigh ? body.slice(0, -1) : body, "utf8");
755
+ carryHigh = endsHigh;
756
+ lineBuffer += w;
757
+ if (lineBytes + (carryHigh ? 3 : 0) > MAX_EVENT_BYTES)
758
+ streamPrefix();
759
+ };
760
+ const completeLine = () => {
761
+ if (streaming) {
762
+ ledger.endOversizeLine({ newlineTerminated: true });
763
+ }
764
+ else {
765
+ ledger.ingestLine(lineBuffer);
766
+ }
767
+ resetLine();
768
+ onLine?.();
769
+ };
647
770
  return {
648
771
  feed: (chunk) => {
649
- lineBuffer += chunk;
650
- let newline;
651
- while ((newline = lineBuffer.indexOf("\n")) >= 0) {
652
- const line = lineBuffer.slice(0, newline);
653
- lineBuffer = lineBuffer.slice(newline + 1);
654
- if (discardingOversize) {
655
- discardingOversize = false;
656
- continue;
657
- }
658
- ledger.ingestLine(line);
659
- onLine?.();
660
- }
661
- if (!discardingOversize && lineBuffer.length > MAX_EVENT_BYTES) {
662
- ledger.ingestLine(lineBuffer);
663
- lineBuffer = "";
664
- discardingOversize = true;
665
- }
666
- else if (discardingOversize) {
667
- lineBuffer = "";
772
+ let pos = 0;
773
+ while (pos < chunk.length) {
774
+ const newline = chunk.indexOf("\n", pos);
775
+ const end = newline < 0 ? chunk.length : newline;
776
+ for (let w = pos; w < end; w += WINDOW_CHARS)
777
+ consumeWindow(chunk.slice(w, Math.min(end, w + WINDOW_CHARS)));
778
+ if (newline < 0)
779
+ break;
780
+ completeLine();
781
+ pos = newline + 1;
668
782
  }
669
783
  },
670
784
  flush: () => {
671
- if (!discardingOversize && lineBuffer.length > 0)
785
+ if (streaming) {
786
+ ledger.endOversizeLine({ newlineTerminated: false });
787
+ resetLine();
788
+ onLine?.();
789
+ return;
790
+ }
791
+ if (lineBuffer.length > 0)
672
792
  ledger.ingestLine(lineBuffer);
673
- lineBuffer = "";
793
+ resetLine();
674
794
  },
675
795
  };
676
796
  }
@@ -766,6 +886,12 @@ function terminalToRunResult(terminal, successStatus) {
766
886
  // by the wrapper below, before this mapping runs) is what actually
767
887
  // notifies the runner.
768
888
  return { status: "abandoned", reason: "auth_fatal" };
889
+ case "completion_evidence_refused":
890
+ // BAPI-1590: the wrapper below hands this outcome to the caller only when
891
+ // that caller opted into the immediate `/fail` fallback, and that caller
892
+ // handles it before mapping. Reaching here means it did not, so keep the
893
+ // historical reading of a refused `/complete`: a lost claim.
894
+ return { status: "abandoned", reason: "stale_claim" };
769
895
  }
770
896
  }
771
897
  /**
@@ -776,7 +902,13 @@ function terminalToRunResult(terminal, successStatus) {
776
902
  * outcome passes through completely unchanged.
777
903
  */
778
904
  async function sendTerminalMutationWithAuthReport(params, job, control) {
779
- const terminal = await sendTerminalMutationWithRetry(params);
905
+ const { completionEvidenceFallback, ...sendParams } = params;
906
+ const terminal = await sendTerminalMutationWithRetry(sendParams);
907
+ if (terminal.outcome === "completion_evidence_refused" && completionEvidenceFallback !== true) {
908
+ params.ownership.abandoned = true;
909
+ params.ownership.abandonReason = "stale_claim";
910
+ return { outcome: "stale_claim" };
911
+ }
780
912
  if (terminal.outcome === "auth_fatal") {
781
913
  const notice = {
782
914
  jobId: job.id,
@@ -858,6 +990,12 @@ export async function runClaimedJob(job, httpClient, options, deps, _report, sea
858
990
  */
859
991
  control) {
860
992
  const { ownership, observation } = createJobRunState(options, deps);
993
+ // BAPI-1563: every terminal report of this job carries the pull request the
994
+ // executor discovered and the supplementary observations it accumulated, including
995
+ // failures emitted before finalization, from a catch block, a supervision stop or
996
+ // cleanup. Wrapped ONCE so it is structural, not a per-site duty. Serialization is
997
+ // gated on the claim's capability by the HTTP client; nothing here grants anything.
998
+ httpClient = withDeliveryObservations(httpClient);
861
999
  // BAPI-1301: a covered claim must carry an envelope on EVERY terminal report,
862
1000
  // including the many refusals that happen before a worker exists (worktree
863
1001
  // preparation, pre-spawn verification, MCP registration, …). Without one the
@@ -2082,6 +2220,27 @@ async function resumePriorAttemptUnderLock(params) {
2082
2220
  * `renderPromptSpecPrompt`, so untrusted check or ticket text is never
2083
2221
  * re-expanded and never reaches a worker for an unverified checkout.
2084
2222
  */
2223
+ /**
2224
+ * BAPI-1582 — read the worker's `ci_fix` test-run record after exit and return
2225
+ * it only when it is valid for this dispatch's logical job. Fail-open: a
2226
+ * missing, malformed, oversized, unsafe, or other-job record (or a reader that
2227
+ * throws) returns `undefined` and changes nothing else about the job.
2228
+ */
2229
+ async function readForwardableCiFixTestRuns(params) {
2230
+ const { job, ciFix, worktreePath, deps, seams } = params;
2231
+ try {
2232
+ const read = await (seams.readCiFixTestRunsArtifact ?? readCiFixTestRunsArtifact)(worktreePath, dispatchedLogicalJob(job.payload, ciFix), { readFile: deps.readFile, lstatPath: deps.lstatPath });
2233
+ if (read.status === "valid")
2234
+ return read.evidence;
2235
+ if (read.status === "invalid") {
2236
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record ${read.code}; not forwarded`);
2237
+ }
2238
+ }
2239
+ catch {
2240
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record unreadable; not forwarded`);
2241
+ }
2242
+ return undefined;
2243
+ }
2085
2244
  async function renderVerifiedCiFixPrompt(params) {
2086
2245
  const { job, ciFix, worktreePath, branch, baseBranch, deps, seams } = params;
2087
2246
  if (branch.trim() !== ciFix.expectedBranch) {
@@ -2362,8 +2521,11 @@ function withoutWorkerFinalMessageExcerpt(failure) {
2362
2521
  async function runSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver) {
2363
2522
  const originalHttp = httpClient;
2364
2523
  let diagnosticWarningSent = false;
2365
- const failWithTelemetry = async (failedJob, body) => {
2366
- let telemetry = { ...body.telemetry, ...observation.snapshot() };
2524
+ // Merge the sanitized worker diagnostics into one report's telemetry. Shared by
2525
+ // the failure and completion wrappers so both follow the same opt-out rule:
2526
+ // a report registered in the WeakSet never carries the final-message excerpt.
2527
+ const withWorkerDiagnostics = (body, base) => {
2528
+ let telemetry = base;
2367
2529
  try {
2368
2530
  const diagnostics = observation.workerDiagnostics();
2369
2531
  if (diagnostics && failuresWithoutWorkerFinalMessageExcerpt.has(body)) {
@@ -2388,11 +2550,26 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2388
2550
  catch { /* supplemental sink */ }
2389
2551
  }
2390
2552
  }
2553
+ return telemetry;
2554
+ };
2555
+ const failWithTelemetry = async (failedJob, body) => {
2556
+ const telemetry = withWorkerDiagnostics(body, { ...body.telemetry, ...observation.snapshot() });
2391
2557
  return originalHttp.fail(failedJob, { ...body, telemetry });
2392
2558
  };
2559
+ // BAPI-1649: a clean worker exit can still be recorded as a server-side failure
2560
+ // (for example a completion the server refuses), and the diagnostics must reach
2561
+ // that record. Only the diagnostics are added: the completion's other telemetry
2562
+ // and all of its evidence are sent exactly as built.
2563
+ const completeWithTelemetry = async (completedJob, completion) => {
2564
+ const telemetry = withWorkerDiagnostics(completion, { ...completion.telemetry });
2565
+ const hasDiagnostics = Object.prototype.hasOwnProperty.call(telemetry, "worker_diagnostics");
2566
+ return originalHttp.complete(completedJob, hasDiagnostics ? { ...completion, telemetry } : completion);
2567
+ };
2393
2568
  httpClient = new Proxy(originalHttp, { get(target, key) {
2394
2569
  if (key === "fail")
2395
2570
  return failWithTelemetry;
2571
+ if (key === "complete")
2572
+ return completeWithTelemetry;
2396
2573
  const value = Reflect.get(target, key);
2397
2574
  return typeof value === "function" ? value.bind(target) : value;
2398
2575
  } });
@@ -2841,6 +3018,22 @@ resolvedTimeoutSeconds) {
2841
3018
  classification: "crashed" });
2842
3019
  return { status: "failed", reason: "recently_failed_tests_file" };
2843
3020
  }
3021
+ // BAPI-1582: seed the ci_fix test-run record with this repair's logical job
3022
+ // and any valid prior runs the server restored. Fail-open telemetry: a
3023
+ // refused or failed seed is logged by fixed code and the spawn proceeds.
3024
+ if (prep.ciFix) {
3025
+ // Through the executor's injected I/O, never a second filesystem path.
3026
+ const seedFs = ciFixTestRunsFsFromDeps(deps);
3027
+ const seed = seedFs === undefined
3028
+ ? { status: "skipped", code: "fs_unavailable" }
3029
+ : await (seams.seedCiFixTestRunsFile ?? seedCiFixTestRunsFile)(worktreePath, {
3030
+ logicalJob: dispatchedLogicalJob(job.payload, prep.ciFix),
3031
+ prior: job.payload?.[CI_FIX_PRIOR_TEST_RUNS_PAYLOAD_KEY],
3032
+ }, seedFs).catch(() => ({ status: "skipped", code: "seed_threw" }));
3033
+ if (seed.status === "skipped") {
3034
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record not seeded (${seed.code})`);
3035
+ }
3036
+ }
2844
3037
  return await runPreparedSpawn({
2845
3038
  job,
2846
3039
  httpClient,
@@ -2896,6 +3089,90 @@ resolvedTimeoutSeconds) {
2896
3089
  const WORKER_RESOURCE_JOB_TYPES = new Set([
2897
3090
  "implement", "resume", "remediate", "ci_fix", "rebase",
2898
3091
  ]);
3092
+ /**
3093
+ * BAPI-1551: the pre-spawn dependency refresh, supervised exactly like
3094
+ * {@link prepareWorkerResources}: the job's lease, the server stop signal, and the
3095
+ * job timeout keep their existing outcomes, and an executor shutdown aborts the
3096
+ * install through the live-worker registry. Every refresh failure is fail-open:
3097
+ * the result carries stale records for LOCAL ENVIRONMENT LIMITS and the worker
3098
+ * still spawns. An unexpected throw from the seam degrades to "no stale records".
3099
+ */
3100
+ async function prepareDependencyRefresh(params) {
3101
+ const { job, deps } = params;
3102
+ const shutdown = new AbortController();
3103
+ const deregister = params.control?.liveWorkers.register({
3104
+ requestTermination: () => shutdown.abort(),
3105
+ });
3106
+ let phase;
3107
+ try {
3108
+ phase = await superviseDriverPhase({
3109
+ job,
3110
+ httpClient: params.httpClient,
3111
+ options: params.options,
3112
+ deps,
3113
+ ownership: params.ownership,
3114
+ observation: params.observation,
3115
+ control: params.control,
3116
+ timeoutSeconds: Math.max(1, Math.ceil(params.remainingMs() / 1000)),
3117
+ collectTelemetry: params.collectTelemetry,
3118
+ run: async (signal) => {
3119
+ // Combined by hand: `AbortSignal.any` is not available on Node 18.
3120
+ const combined = new AbortController();
3121
+ const abortCombined = () => combined.abort();
3122
+ if (signal.aborted || shutdown.signal.aborted)
3123
+ combined.abort();
3124
+ signal.addEventListener("abort", abortCombined, { once: true });
3125
+ shutdown.signal.addEventListener("abort", abortCombined, { once: true });
3126
+ const result = await params.refresh({
3127
+ jobId: String(job.id),
3128
+ entries: params.entries,
3129
+ worktreePath: params.worktreePath,
3130
+ mainCheckoutPath: deps.cwd,
3131
+ env: buildDependencyInstallEnv(deps.env, job.payload, payloadWorkerDatabaseConfigOption(job.payload)),
3132
+ remainingMs: params.remainingMs(),
3133
+ now: deps.now,
3134
+ sleep: deps.sleep,
3135
+ signal: combined.signal,
3136
+ log: (message) => deps.errorLog(message),
3137
+ platform: deps.platform,
3138
+ ...(deps.runDependencyInstall ? { runInstall: deps.runDependencyInstall } : {}),
3139
+ });
3140
+ return result.stale;
3141
+ },
3142
+ });
3143
+ }
3144
+ finally {
3145
+ deregister?.();
3146
+ }
3147
+ if (phase.kind === "abandoned") {
3148
+ return { kind: "interrupted", result: { status: "abandoned", reason: params.ownership.abandonReason } };
3149
+ }
3150
+ if (phase.kind === "server_stop") {
3151
+ await params.httpClient.fail(job, {
3152
+ error_kind: "ServerStopRequested",
3153
+ error_message: "the server requested this run stop before the worker started",
3154
+ classification: "killed",
3155
+ telemetry: params.observation.snapshot(),
3156
+ });
3157
+ params.ownership.abandoned = true;
3158
+ params.ownership.abandonReason = "server_stop";
3159
+ return { kind: "interrupted", result: { status: "abandoned", reason: "server_stop" } };
3160
+ }
3161
+ if (phase.kind === "timeout") {
3162
+ await params.httpClient.fail(job, {
3163
+ error_kind: "Timeout",
3164
+ error_message: `${job.job_type} exceeded the job timeout before the worker started`,
3165
+ classification: "timeout",
3166
+ telemetry: params.observation.snapshot(),
3167
+ });
3168
+ return { kind: "interrupted", result: { status: "failed", reason: "timeout" } };
3169
+ }
3170
+ // A shutdown during the refresh keeps the existing shutdown semantics: the
3171
+ // sticky registry terminates the worker on registration anyway.
3172
+ if (phase.kind === "error")
3173
+ return { kind: "ready", stale: [] };
3174
+ return { kind: "ready", stale: phase.value };
3175
+ }
2899
3176
  /**
2900
3177
  * BAPI-1479 — provision the job's disposable database and own-build launcher
2901
3178
  * before the worker's spawn shape is built.
@@ -2916,19 +3193,44 @@ async function prepareWorkerResources(params) {
2916
3193
  const { job, deps, lifecycle } = params;
2917
3194
  const jobId = String(job.id);
2918
3195
  const resources = deps.workerResources;
3196
+ // BAPI-1598 — the declaration is parsed once. Only an explicit, valid
3197
+ // `disposable_postgres` payload provisions anything; every other state keeps
3198
+ // the job stack-neutral and never falls back to a Bridge default.
3199
+ const parsed = payloadWorkerDatabaseParse(job.payload);
3200
+ const metadata = payloadWorkerDatabaseMetadata(job.payload);
3201
+ const declared = parsed.classification === "enabled" || parsed.classification === "disabled"
3202
+ ? parsed.config : undefined;
3203
+ const declaration = {
3204
+ workerDatabaseMode: metadata.worker_database_mode,
3205
+ ...(declared ? { workerDatabaseConfig: declared } : {}),
3206
+ };
3207
+ try {
3208
+ // An unconfigured job (no declaration) stays quiet; any declaration is recorded
3209
+ // by mode and live profile revision only.
3210
+ if (metadata.worker_database_mode !== "absent")
3211
+ deps.errorLog(formatWorkerDatabaseModeLine(jobId, metadata));
3212
+ if (parsed.classification === "malformed") {
3213
+ deps.errorLog(formatWorkerDatabaseMalformedLine(jobId, parsed.reason));
3214
+ }
3215
+ }
3216
+ catch { /* sink */ }
2919
3217
  if (!resources)
2920
- return { kind: "ready" };
3218
+ return { kind: "ready", ...declaration };
2921
3219
  let target;
3220
+ let targetRole;
2922
3221
  let disposeLauncher;
2923
3222
  let launcherDirectory;
2924
3223
  let unavailableCategory;
3224
+ let unavailableCause;
2925
3225
  let released = false;
2926
3226
  lifecycle.releaseWorkerResources = async () => {
2927
3227
  if (released)
2928
3228
  return;
2929
3229
  released = true;
2930
- if (target) {
2931
- const dropped = await resources.dropDatabase(target).catch(() => ({ kind: "failed" }));
3230
+ if (target && targetRole !== undefined) {
3231
+ const dropped = await resources
3232
+ .dropDatabase(target, targetRole)
3233
+ .catch(() => ({ kind: "failed" }));
2932
3234
  if (dropped.kind !== "dropped") {
2933
3235
  try {
2934
3236
  deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, target.name));
@@ -2965,22 +3267,30 @@ async function prepareWorkerResources(params) {
2965
3267
  signal.addEventListener("abort", abortCombined, { once: true });
2966
3268
  shutdown.signal.addEventListener("abort", abortCombined, { once: true });
2967
3269
  const cancel = combined.signal;
2968
- const provisioned = await resources
2969
- .provisionDatabase({
2970
- jobId,
2971
- worktreePath: params.worktreePath,
2972
- signal: cancel,
2973
- // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
2974
- ...payloadWorkerEnvOption(job.payload),
2975
- })
2976
- .catch(() => ({ kind: "unavailable", category: "create_failed" }));
2977
- if (provisioned.kind === "provisioned") {
3270
+ const provisioned = parsed.classification === "enabled"
3271
+ ? await resources
3272
+ .provisionDatabase({
3273
+ jobId,
3274
+ worktreePath: params.worktreePath,
3275
+ signal: cancel,
3276
+ config: parsed.config,
3277
+ // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
3278
+ ...payloadWorkerEnvOption(job.payload),
3279
+ })
3280
+ .catch(() => ({ kind: "unavailable", category: "create_failed" }))
3281
+ : undefined;
3282
+ if (provisioned === undefined) {
3283
+ // Nothing was configured to provision: no database resource, no failure to report.
3284
+ }
3285
+ else if (provisioned.kind === "provisioned") {
2978
3286
  target = provisioned.target;
3287
+ targetRole = provisioned.role;
2979
3288
  }
2980
3289
  else {
2981
3290
  unavailableCategory = provisioned.category;
3291
+ unavailableCause = "cause" in provisioned ? provisioned.cause : undefined;
2982
3292
  try {
2983
- deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category));
3293
+ deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category, unavailableCause));
2984
3294
  // A created database whose rollback failed stays for the host operator.
2985
3295
  if ("retainedName" in provisioned && provisioned.retainedName) {
2986
3296
  deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, provisioned.retainedName));
@@ -3044,9 +3354,12 @@ async function prepareWorkerResources(params) {
3044
3354
  // `kind: "error"` is an unexpected throw from the seam itself: degrade.
3045
3355
  return {
3046
3356
  kind: "ready",
3357
+ ...declaration,
3047
3358
  ...(target ? { workerDatabase: target } : {}),
3048
3359
  ...(launcherDirectory ? { workerLauncherDirectory: launcherDirectory } : {}),
3049
3360
  ...(!target && unavailableCategory ? { workerDatabaseUnavailableCategory: unavailableCategory } : {}),
3361
+ ...(!target && unavailableCategory && unavailableCause
3362
+ ? { workerDatabaseUnavailableCause: unavailableCause } : {}),
3050
3363
  };
3051
3364
  }
3052
3365
  /**
@@ -3124,6 +3437,8 @@ async function runPreparedSpawn(params) {
3124
3437
  // it repairs an existing branch whose pull request already exists, and the PR
3125
3438
  // base contract's "when you open the pull request" instruction would re-add the
3126
3439
  // new-PR step the focused prompt deliberately excludes.
3440
+ // BAPI-1546: `disabled` unless the repository opted in; then injected at spawn.
3441
+ let epicServerContext = { kind: "disabled" };
3127
3442
  let prompt = isImplementationStyleJobType(job.job_type) && !prep.ciFix && !prep.focusedRebase
3128
3443
  ? `${prep.prompt} ${renderWorkerPrBaseGuidance()}`
3129
3444
  : prep.prompt;
@@ -3139,6 +3454,37 @@ async function runPreparedSpawn(params) {
3139
3454
  // an older API) stays absent so the instruction keeps its conditional wording.
3140
3455
  const handoffEnabled = job.payload?.verification_handoff_enabled;
3141
3456
  prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key, typeof handoffEnabled === "boolean" ? handoffEnabled : undefined)}`;
3457
+ // BAPI-1545: an implement job in an epic run gets the owner's advisory
3458
+ // capability statement, read once here with a short timeout. Absent,
3459
+ // unavailable, malformed, or failed reads append nothing (the prompt stays
3460
+ // byte-identical) and log one fixed line. The job proceeds either way.
3461
+ if (job.job_type === "implement" && typeof job.epic_run_id === "string" && job.epic_run_id.length > 0) {
3462
+ const capabilityLine = await readCapabilityStatementLine(httpClient, job.repo_name);
3463
+ if (capabilityLine !== null) {
3464
+ prompt = `${prompt} ${capabilityLine}`;
3465
+ }
3466
+ else {
3467
+ deps.errorLog(CAPABILITY_STATEMENT_NOT_APPENDED_MESSAGE);
3468
+ }
3469
+ }
3470
+ // BAPI-1546: the epic-server turn paragraph, beside the workaround contract,
3471
+ // only for an opted-in repository. One bounded, fail-open read; any failure
3472
+ // is "no opt-in" (or "local, unavailable"), never a failed job or a delay.
3473
+ if (typeof job.epic_run_id === "string" && job.epic_run_id.length > 0) {
3474
+ try {
3475
+ const readContext = seams.readEpicServerContext ??
3476
+ ((repo, runId) => readEpicServerWorkerContext(repo, runId, createDefaultEpicServerContextDeps(deps.env)));
3477
+ epicServerContext = await readContext(job.repo_name, job.epic_run_id);
3478
+ }
3479
+ catch {
3480
+ epicServerContext = { kind: "disabled" };
3481
+ }
3482
+ const epicServerLine = buildEpicServerWorkerInstruction(epicServerContext, job.ticket_key);
3483
+ if (epicServerLine !== null)
3484
+ prompt = `${prompt} ${epicServerLine}`;
3485
+ else
3486
+ epicServerContext = { kind: "disabled" };
3487
+ }
3142
3488
  }
3143
3489
  // --- Timeout contract ------------------------------------------------
3144
3490
  const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
@@ -3253,7 +3599,7 @@ async function runPreparedSpawn(params) {
3253
3599
  // Trusted starter context is appended AFTER packaged-command expansion, never
3254
3600
  // inserted into command arguments or scanned through untrusted server evidence.
3255
3601
  if (job.job_type === "implement" && !isRemainingWork(job.job_type, job.payload)) {
3256
- prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha);
3602
+ prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha) + "\n\n" + renderWorkerPushEachCommitGuidance();
3257
3603
  }
3258
3604
  // The locked ci_fix renderer deferred trusted guidance. All existing prompt
3259
3605
  // additions precede comparison guidance and the final total-budget block.
@@ -3410,7 +3756,7 @@ async function runPreparedSpawn(params) {
3410
3756
  // BAPI-727: the validated endpoint travels from executor bootstrap through the
3411
3757
  // runtime options to the generated registration, so the worker's MCP server
3412
3758
  // targets the same Bridge API this executor claimed the job from.
3413
- await provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, options.resolvedBaseUrl);
3759
+ const grantRegistration = await provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, options.resolvedBaseUrl);
3414
3760
  // --- Required Bridge MCP registration (FAIL-CLOSED) -------------------
3415
3761
  // Provisioning itself stays fail-OPEN: a skipped or malformed Tier-2 target is
3416
3762
  // a warning, and every valid worktree-provisioned server is kept. The REQUIRED
@@ -3439,10 +3785,21 @@ async function runPreparedSpawn(params) {
3439
3785
  return { status: "failed", reason: "executor_adapter_unavailable" };
3440
3786
  }
3441
3787
  const registration = await verifyRegistration(worktreePath, deps, mcpScoping.value.requiredServerName);
3442
- if (!registration.ok) {
3788
+ // BAPI-1545: on the grant path the registration must ALSO be the one
3789
+ // provisioning wrote and read back: exactly Bridge plus the granted names. The
3790
+ // expected init-event set is then that verified set, so a granted server that
3791
+ // fails to connect is still expected by name (it never fails the job), and an
3792
+ // extra server cannot appear.
3793
+ const grantMismatch = grantRegistration !== null &&
3794
+ grantRegistration !== undefined &&
3795
+ (!grantRegistration.ok ||
3796
+ (registration.ok &&
3797
+ JSON.stringify([...registration.contract.expectedServerNames].sort()) !==
3798
+ JSON.stringify([...grantRegistration.expectedServerNames].sort())));
3799
+ if (!registration.ok || grantMismatch) {
3443
3800
  await httpClient.fail(job, {
3444
3801
  error_kind: RequiredMcpRegistration,
3445
- error_message: registration.message,
3802
+ error_message: registration.ok ? GRANT_MCP_REGISTRATION_UNVERIFIED_MESSAGE : registration.message,
3446
3803
  classification: "crashed",
3447
3804
  ...commitResidue(preSpawnTelemetry),
3448
3805
  telemetry: observation.snapshot(),
@@ -3633,9 +3990,44 @@ async function runPreparedSpawn(params) {
3633
3990
  // fresh resources; nothing is recovered from an earlier execution's state.
3634
3991
  // Driver-owned jobs (their worker runs a server-rendered reconciliation) and
3635
3992
  // verdict-only jobs keep the sentinel database.
3636
- let workerResources = {};
3993
+ // --- Dependency refresh (BAPI-1551) -----------------------------------
3994
+ // Runs only for a non-driver worker job whose payload OWNS `dependency_install`
3995
+ // with at least one admitted entry, after the worktree is ensured and locked
3996
+ // and BEFORE worker resources: database provisioning runs the repository's own
3997
+ // migration code, which must see the refreshed dependencies. A repository with
3998
+ // no declaration performs no new filesystem or process operation here.
3999
+ let staleDependencies = [];
4000
+ const workerResourceJob = !driver && WORKER_RESOURCE_JOB_TYPES.has(job.job_type);
4001
+ if (workerResourceJob) {
4002
+ const declared = payloadDependencyInstallOption(job.payload);
4003
+ if (Object.prototype.hasOwnProperty.call(declared, "dependencyInstall")) {
4004
+ const entries = validateDependencyInstallDeclarations(declared.dependencyInstall, (m) => deps.errorLog(m));
4005
+ if (entries.length > 0) {
4006
+ const refreshed = await prepareDependencyRefresh({
4007
+ job, httpClient, options: jobOptions, deps, ownership, observation, control,
4008
+ worktreePath, remainingMs, collectTelemetry: driverTelemetry, entries,
4009
+ refresh: seams.refreshDependencies ?? refreshDeclaredDependencies,
4010
+ });
4011
+ if (refreshed.kind === "interrupted") {
4012
+ await closeWorkerLog();
4013
+ await finalizeRegistry();
4014
+ return refreshed.result;
4015
+ }
4016
+ staleDependencies = refreshed.stale;
4017
+ }
4018
+ }
4019
+ }
4020
+ let workerResources = {
4021
+ // BAPI-1598 — the sentinel protection follows the payload's declaration for EVERY
4022
+ // job type that spawns a worker, not only those that may provision a database.
4023
+ ...payloadWorkerDatabaseConfigOption(job.payload),
4024
+ };
4025
+ // BAPI-1598: the effective mode follows the payload for EVERY job type, so a job that never
4026
+ // prepares worker resources is not told a database it never expected is missing.
4027
+ let workerDatabaseMode = payloadWorkerDatabaseMetadata(job.payload).worker_database_mode;
3637
4028
  // BAPI-1522: why no database exists (a closed category), kept OUT of the spawn input.
3638
4029
  let databaseUnavailableCategory;
4030
+ let databaseUnavailableCause;
3639
4031
  if (!driver && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)) {
3640
4032
  const prepared = await prepareWorkerResources({
3641
4033
  job, httpClient, options: jobOptions, deps, ownership, observation, control,
@@ -3646,11 +4038,36 @@ async function runPreparedSpawn(params) {
3646
4038
  await finalizeRegistry();
3647
4039
  return prepared.result;
3648
4040
  }
4041
+ workerDatabaseMode = prepared.workerDatabaseMode;
3649
4042
  workerResources = {
3650
4043
  ...(prepared.workerDatabase ? { workerDatabase: prepared.workerDatabase } : {}),
4044
+ ...(prepared.workerDatabaseConfig ? { workerDatabaseConfig: prepared.workerDatabaseConfig } : {}),
3651
4045
  ...(prepared.workerLauncherDirectory ? { workerLauncherDirectory: prepared.workerLauncherDirectory } : {}),
3652
4046
  };
3653
4047
  databaseUnavailableCategory = prepared.workerDatabaseUnavailableCategory;
4048
+ databaseUnavailableCause = prepared.workerDatabaseUnavailableCause;
4049
+ // BAPI-1609: report the provisioning outcome on every later telemetry
4050
+ // snapshot. Only a genuinely provisioned target sets it; the sentinel
4051
+ // fallback below never does.
4052
+ if (prepared.workerDatabase !== undefined)
4053
+ observation.recordWorkerDatabaseProvisioned();
4054
+ // BAPI-1563: the worker has no database. Report the fact only when CI
4055
+ // confirms it has none either (BAPI-1598): a CI-provided database means the
4056
+ // checks are delegated, and an unknown CI capability is not confirmed absence,
4057
+ // so neither records a gap. This is never a local carry-authority decision.
4058
+ if (workerResources.workerDatabase === undefined) {
4059
+ const ciDatabase = payloadCiDatabase(job.payload);
4060
+ if (ciDatabase === "none") {
4061
+ recordVerificationObservation(job, { cause: "no_database" });
4062
+ }
4063
+ else if (ciDatabase === "provided" || workerDatabaseMode !== "absent") {
4064
+ // An unconfigured job whose CI capability is also unknown has nothing to report.
4065
+ try {
4066
+ deps.errorLog(formatWorkerDatabaseSkippedObservationLine(String(job.id), ciDatabase === "provided" ? "delegated_to_ci" : "ci_database_unknown"));
4067
+ }
4068
+ catch { /* sink */ }
4069
+ }
4070
+ }
3654
4071
  }
3655
4072
  const invocation = adapter.headlessInvocation;
3656
4073
  if (invocation?.supported !== true) {
@@ -3663,6 +4080,16 @@ async function runPreparedSpawn(params) {
3663
4080
  });
3664
4081
  return { status: "failed", reason: "executor_adapter_unavailable" };
3665
4082
  }
4083
+ // BAPI-1551: the repository's always-run guards, read through the same parser
4084
+ // likely-tests uses. Read-only, never throws, and an absent or malformed file
4085
+ // or an empty `always` list renders nothing.
4086
+ let requiredReferences = [];
4087
+ if (workerResourceJob) {
4088
+ const hints = await (seams.readVerificationHints ?? deps.readVerificationHints ?? readVerificationHints)(worktreePath)
4089
+ .catch(() => ({ status: "malformed" }));
4090
+ if (hints.status === "ok")
4091
+ requiredReferences = hints.required;
4092
+ }
3666
4093
  let spawnShape;
3667
4094
  try {
3668
4095
  const alias = invocation.value.resolveModelAlias(job.payload);
@@ -3712,17 +4139,37 @@ async function runPreparedSpawn(params) {
3712
4139
  ? job.payload.reproduce_commands : undefined;
3713
4140
  const limits = renderLocalEnvironmentLimits({
3714
4141
  databaseAvailable: workerResources.workerDatabase !== undefined,
4142
+ ...(workerDatabaseMode !== undefined ? { workerDatabaseMode } : {}),
3715
4143
  ...(databaseUnavailableCategory && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3716
4144
  ? { databaseUnavailableCategory } : {}),
4145
+ ...(databaseUnavailableCause && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
4146
+ ? { databaseUnavailableCause } : {}),
3717
4147
  reproduceCommands,
3718
4148
  ...(typeof workerEnvPath === "string" ? { workerPath: workerEnvPath } : {}),
3719
4149
  worktreePath,
3720
4150
  isExecutable: seams.executableCheck ?? fileSystemExecutableCheck,
4151
+ ...(workerResourceJob ? { ciDatabase: payloadCiDatabase(job.payload) } : {}),
4152
+ ...(staleDependencies.length > 0 ? { staleDependencyCwds: staleDependencies } : {}),
3721
4153
  });
4154
+ // BAPI-1551: REQUIRED BEFORE PUSH sits immediately before LOCAL ENVIRONMENT
4155
+ // LIMITS, which stays last. With neither, the prompt is byte-identical.
4156
+ const required = renderRequiredBeforePush(requiredReferences);
4157
+ // BAPI-1582: an implement job's admitted gate-profile commands follow REQUIRED
4158
+ // BEFORE PUSH. Read only when the payload OWNS `pre_pr_checks`; no admitted
4159
+ // entry renders nothing, so the prompt stays byte-identical. Never the
4160
+ // ci_fix reproduction block.
4161
+ const prePrChecks = job.job_type === "implement"
4162
+ ? renderPrePrChecks(validatePrePrCheckDeclarations(payloadPrePrChecksOption(job.payload), deps.errorLog))
4163
+ : "";
3722
4164
  spawnShape = invocation.value.buildSpawnShape({
3723
- prompt: limits ? prompt + "\n\n" + limits : prompt,
4165
+ prompt: [prompt, required, prePrChecks, limits].filter((section) => section.length > 0).join("\n\n"),
3724
4166
  ...shapeInput,
3725
4167
  });
4168
+ // BAPI-1546: the trusted browser target (and run id for turns), injected AFTER
4169
+ // the environment builder ran, like the job tag. `disabled` leaves the shape untouched.
4170
+ if (epicServerContext.kind !== "disabled" && spawnShape.env) {
4171
+ spawnShape = { ...spawnShape, env: withEpicServerEnv(spawnShape.env, epicServerContext) };
4172
+ }
3726
4173
  assertUsableSpawnShape(spawnShape, adapter);
3727
4174
  }
3728
4175
  catch (err) {
@@ -4321,6 +4768,8 @@ async function runPreparedSpawn(params) {
4321
4768
  lstatPath: deps.lstatPath,
4322
4769
  });
4323
4770
  if ("fields" in ciResult) {
4771
+ // Includes a present normalized no_push_reason; the reader omits absent
4772
+ // diagnostics. Executor-observed identities retain precedence.
4324
4773
  genericResult = {
4325
4774
  ...ciResult.fields,
4326
4775
  ...executorResult,
@@ -4333,6 +4782,11 @@ async function runPreparedSpawn(params) {
4333
4782
  genericResult = { ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status };
4334
4783
  }
4335
4784
  }
4785
+ // BAPI-1582: optional, bounded test-run telemetry for a resumed repair.
4786
+ const ciFixTestRuns = prep.ciFix
4787
+ ? await readForwardableCiFixTestRuns({ job, ciFix: prep.ciFix, worktreePath, deps, seams })
4788
+ : undefined;
4789
+ genericResult = withCiFixTestRuns(genericResult, ciFixTestRuns, RESULT_JSONB_MAX_BYTES);
4336
4790
  // BAPI-551: a worker can exit `clean_exit` yet strand its implementation if
4337
4791
  // its push never landed on origin and no PR was opened (e.g. it backgrounded
4338
4792
  // a slow push and returned early). Convert that into a fail-loud executor
@@ -4341,20 +4795,20 @@ async function runPreparedSpawn(params) {
4341
4795
  // BAPI-1426: a managed ticket's server-confirmed delivery outcome is read
4342
4796
  // first, so an intentional held checkpoint finalizes as a `/fail` with its
4343
4797
  // completion cause instead of a missing-PR failure or a success.
4344
- const deliveryOutcome = await readDeliveryOutcomeForFinalization({
4345
- job,
4346
- branch,
4347
- deps,
4348
- seams,
4349
- remainingMs,
4350
- resolvedBaseUrl: options.resolvedBaseUrl,
4351
- });
4798
+ //
4799
+ // BAPI-1563: the assessment is read ONCE, inside finalization, after the final
4800
+ // head is proven on origin and the PR is discovered (`refreshDeliveryOutcome`),
4801
+ // never from an earlier verdict taken before the PR existed.
4352
4802
  const finalization = await validateWorkerFinalization({
4353
4803
  job,
4354
4804
  branch,
4355
4805
  worktreePath,
4356
4806
  result: genericResult,
4357
- ...(deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
4807
+ // BAPI-1563: a fresh assessment after the final head and PR are known.
4808
+ refreshDeliveryOutcome: () => readDeliveryOutcomeForFinalization({
4809
+ job, branch, deps, seams, remainingMs, resolvedBaseUrl: options.resolvedBaseUrl,
4810
+ }),
4811
+ onObservedPr: (pr) => recordObservedPr(job, pr),
4358
4812
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, remainingMs, httpClient, options: jobOptions, control }),
4359
4813
  runCommand: deps.runCommand,
4360
4814
  headSha: git.last_commit_sha,
@@ -4380,7 +4834,9 @@ async function runPreparedSpawn(params) {
4380
4834
  // finalization failure; it is never rewritten to look like a crash.
4381
4835
  ...observedExitCode(procResult.exitCode),
4382
4836
  ...commitResidue(git),
4383
- telemetry: withFailureTelemetry(observation.snapshot(), finalization.failure.telemetry),
4837
+ // BAPI-1582: a held or failed finalization still carries the
4838
+ // repair's test-run record, so a continuation can restore it.
4839
+ telemetry: withCiFixTestRuns(withFailureTelemetry(observation.snapshot(), finalization.failure.telemetry), ciFixTestRuns, RESULT_JSONB_MAX_BYTES),
4384
4840
  }),
4385
4841
  deps,
4386
4842
  options,
@@ -4448,9 +4904,12 @@ async function runPreparedSpawn(params) {
4448
4904
  // made; worker prose is never admissible here (R14 rule 3). It is omitted
4449
4905
  // rather than set to null when finalization had no PR to verify (a
4450
4906
  // non-implementation job), so the field's presence always means "verified".
4451
- const result = typeof finalization.prUrl === "string"
4907
+ const verifiedResult = typeof finalization.prUrl === "string"
4452
4908
  ? { ...genericResult, pr_url: finalization.prUrl }
4453
4909
  : genericResult;
4910
+ // BAPI-1582: an implement worker's current-head pre-PR record rides as bounded
4911
+ // telemetry, never gate evidence. Missing, stale, or oversized attaches nothing.
4912
+ const result = await attachPrePrChecksTelemetry(job, verifiedResult, worktreePath, git.last_commit_sha, deps);
4454
4913
  const completion = {
4455
4914
  job_type: job.job_type,
4456
4915
  exit_code: procResult.exitCode ?? 0,
@@ -4982,11 +5441,23 @@ async function runCoveredAttempt(params) {
4982
5441
  // BAPI-1395: a worker that ignores the stdin EOF the completion window sent is
4983
5442
  // ended through the existing termination controller, not a second kill path.
4984
5443
  let postWindowExitTimer;
5444
+ let windowLiveKinds = [];
4985
5445
  const supervisor = createClosureSupervisor({
4986
5446
  ledger,
4987
5447
  deps: stdinDeps,
4988
5448
  ...(params.windowNudge ? { buildWindowNudge: params.windowNudge } : {}),
4989
- onWindowExpiry: () => {
5449
+ onWindowExpiry: (liveKinds) => {
5450
+ // BAPI-1554: keep the closure-time snapshot of running required work for
5451
+ // the executor log and for the failure text of an already-failing attempt.
5452
+ windowLiveKinds = liveKinds;
5453
+ if (liveKinds.length > 0) {
5454
+ try {
5455
+ deps.log(`${COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT}: ${liveKinds.join(", ")}`);
5456
+ }
5457
+ catch {
5458
+ /* a log failure must never break the termination scheduling below */
5459
+ }
5460
+ }
4990
5461
  const graceMs = Math.max(0, Math.min(POST_WINDOW_EXIT_GRACE_MS, plan.workerDeadlineAtMs - deps.now()));
4991
5462
  postWindowExitTimer = deps.setTimer(() => {
4992
5463
  postWindowExitTimer = undefined;
@@ -5147,14 +5618,25 @@ async function runCoveredAttempt(params) {
5147
5618
  },
5148
5619
  };
5149
5620
  const git = observation.git();
5621
+ // BAPI-1582: set once the worker's ci_fix test-run record is read, so a held
5622
+ // or refused covered attempt still carries it for a later continuation.
5623
+ let failTestRuns;
5150
5624
  const failWith = async (failure, envelope, extra = {}) => {
5151
5625
  await finalizeRegistry();
5626
+ // BAPI-1554: the primary failure text stays first; the closure-time live-work
5627
+ // snapshot is appended only to an attempt that is failing anyway.
5628
+ const failureWithWindowDiagnostic = windowLiveKinds.length > 0
5629
+ ? {
5630
+ ...failure,
5631
+ error_message: `${failure.error_message} (${COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT}: ${windowLiveKinds.join(", ")})`,
5632
+ }
5633
+ : failure;
5152
5634
  const terminal = await sendTerminalMutationWithAuthReport({
5153
5635
  kind: "fail",
5154
5636
  send: () => httpClient.fail(job, {
5155
- ...failure,
5637
+ ...failureWithWindowDiagnostic,
5156
5638
  ...commitResidue(git),
5157
- telemetry: withFailureTelemetry(observation.snapshot(), failure.telemetry),
5639
+ telemetry: withCiFixTestRuns(withFailureTelemetry(observation.snapshot(), failure.telemetry), failTestRuns, RESULT_JSONB_MAX_BYTES),
5158
5640
  completion_contract: SUPPORTED_COMPLETION_MARKER,
5159
5641
  completion_evidence: envelope,
5160
5642
  ...extra,
@@ -5389,6 +5871,10 @@ async function runCoveredAttempt(params) {
5389
5871
  };
5390
5872
  verification = verificationVerdictFromFacts(verificationFacts, checks.length);
5391
5873
  }
5874
+ // BAPI-1563: supplementary observation causes derived from the declared-check
5875
+ // facts (timed out, could not run). Facts only: a failed or unrun check is never
5876
+ // turned into a pass here, and the server alone decides what an observation means.
5877
+ recordVerificationFacts(job, verificationFacts);
5392
5878
  // --- Phase 4: finalization (unchanged executor facts) ----------------------------
5393
5879
  const artifacts = await readCompletionArtifacts(worktreePath, deps);
5394
5880
  const executorResult = buildGenericSuccessResult({
@@ -5404,27 +5890,37 @@ async function runCoveredAttempt(params) {
5404
5890
  readFile: deps.readFile,
5405
5891
  lstatPath: deps.lstatPath,
5406
5892
  });
5893
+ // Forward the same validated optional diagnostic on this completion path.
5407
5894
  genericResult =
5408
5895
  "fields" in ciResult
5409
5896
  ? { ...ciResult.fields, ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status }
5410
5897
  : { ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status };
5411
5898
  }
5899
+ // BAPI-1582: the same optional test-run telemetry as the legacy completion path.
5900
+ const ciFixTestRuns = prep.ciFix
5901
+ ? await readForwardableCiFixTestRuns({ job, ciFix: prep.ciFix, worktreePath, deps, seams })
5902
+ : undefined;
5903
+ genericResult = withCiFixTestRuns(genericResult, ciFixTestRuns, RESULT_JSONB_MAX_BYTES);
5904
+ failTestRuns = ciFixTestRuns;
5412
5905
  // BAPI-1426: the server-confirmed delivery outcome, read under the same
5413
5906
  // absolute deadline as the finalization reads below.
5414
- const deliveryOutcome = await readDeliveryOutcomeForFinalization({
5415
- job,
5416
- branch,
5417
- deps,
5418
- seams,
5419
- remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()),
5420
- resolvedBaseUrl: options.resolvedBaseUrl,
5421
- });
5907
+ // BAPI-1563: read once, inside finalization, after the final head and the PR are
5908
+ // known (`refreshDeliveryOutcome` below), never from an earlier verdict.
5422
5909
  const finalization = await validateWorkerFinalization({
5423
5910
  job,
5424
5911
  branch,
5425
5912
  worktreePath,
5426
5913
  result: genericResult,
5427
- ...(deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
5914
+ // BAPI-1563: a fresh assessment after the final head and PR are known.
5915
+ refreshDeliveryOutcome: () => readDeliveryOutcomeForFinalization({
5916
+ job,
5917
+ branch,
5918
+ deps,
5919
+ seams,
5920
+ remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()),
5921
+ resolvedBaseUrl: options.resolvedBaseUrl,
5922
+ }),
5923
+ onObservedPr: (pr) => recordObservedPr(job, pr),
5428
5924
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, httpClient, options: jobOptions, control,
5429
5925
  remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()) }),
5430
5926
  callTimeoutMs: () => Math.min(120_000, Math.max(0, plan.deadlineAtMs - deps.now())),
@@ -5465,8 +5961,37 @@ async function runCoveredAttempt(params) {
5465
5961
  const lateStronger = await strongerOutcome();
5466
5962
  if (lateStronger)
5467
5963
  return lateStronger;
5468
- if (finalization.ok && successRefusalReason(envelope) === null) {
5469
- const result = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
5964
+ // BAPI-1563: the executor reports facts and follows the server. When the fresh
5965
+ // server assessment PERMITS publication at this head (`awaiting_post_pr` or
5966
+ // `complete`), a local verification shortfall alone (a failed, unavailable or
5967
+ // unrun declared check) does not turn the report into RequiredCheckFailed: the
5968
+ // job reports success with the discovered PR and the truthful envelope, and the
5969
+ // server decides. The envelope is not rewritten, so the shortfall is never read
5970
+ // as a pass. Any other cause (unfinished work, cleanup, permission) still fails.
5971
+ const serverPermitsPublication = finalization.ok && serverOutcomePermitsSuccess(finalization.deliveryOutcome);
5972
+ // The server accepts this shortfall success only when publication depends on the
5973
+ // carry (`api/routes/executor_jobs.py`, `publication_depends_on_carry`): the
5974
+ // boundary outcome permits publication while the evidence-only outcome does
5975
+ // not. Mirror that rule from the parsed `evidenceOutcome`. When it is absent or
5976
+ // itself permits publication (attended run, switch off, hand-off), the server
5977
+ // would refuse with 409, so keep the existing RequiredCheckFailed report.
5978
+ const evidenceOutcome = finalization.ok ? finalization.deliveryOutcome?.evidenceOutcome : undefined;
5979
+ const publicationDependsOnCarry = evidenceOutcome !== undefined && evidenceOutcome !== "awaiting_post_pr" && evidenceOutcome !== "complete";
5980
+ const verificationShortfallOnly = serverPermitsPublication && publicationDependsOnCarry && envelope.cause === "required_check_failed" && unresolvedRequiredTasks(envelope).length === 0;
5981
+ // BAPI-1590: a shortfall at a pull request the executor verified at the pushed
5982
+ // head is reported as `/complete` first and the SERVER decides; its own read of
5983
+ // the open PR is authoritative, this observation is only publication evidence.
5984
+ // Implementation-style jobs qualify only through the confirmed delivery hold that
5985
+ // finalization let through (`heldAtOpenPr`), never a bare PR number; a `ci_fix`
5986
+ // qualifies through its finalization PR number plus the server-held branch.
5987
+ // Only the two causes the server may lift qualify, and any unfinished required
5988
+ // work still fails.
5989
+ const prBackedShortfallOnly = isPrBackedShortfall(finalization, job, envelope);
5990
+ const shortfallGated = verificationShortfallOnly || prBackedShortfallOnly;
5991
+ if (finalization.ok && (successRefusalReason(envelope) === null || shortfallGated)) {
5992
+ const verifiedResult = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
5993
+ // BAPI-1582: bounded pre-PR telemetry, as on the legacy completion path.
5994
+ const result = await attachPrePrChecksTelemetry(job, verifiedResult, worktreePath, git.last_commit_sha, deps);
5470
5995
  const completion = {
5471
5996
  job_type: job.job_type,
5472
5997
  exit_code: procResult.exitCode ?? 0,
@@ -5485,9 +6010,16 @@ async function runCoveredAttempt(params) {
5485
6010
  options,
5486
6011
  ownership: reportOwnership,
5487
6012
  log: deps.log,
6013
+ // BAPI-1590: only a shortfall-gated completion falls back to `/fail`.
6014
+ completionEvidenceFallback: shortfallGated && successRefusalReason(envelope) !== null,
5488
6015
  }, job, control);
5489
- await finalizeRegistry();
5490
- return finish(terminalToRunResult(terminal, "completed"));
6016
+ // BAPI-1590: on a marked refusal the server left the job running, so fall
6017
+ // through and report the SAME envelope once as `/fail` below — no second
6018
+ // finalization, evidence regeneration, worker launch, lease wait, or abandon.
6019
+ if (terminal.outcome !== "completion_evidence_refused") {
6020
+ await finalizeRegistry();
6021
+ return finish(terminalToRunResult(terminal, "completed"));
6022
+ }
5491
6023
  }
5492
6024
  // Not a success. A completion cause (required work, cleanup, verification,
5493
6025
  // permission) outranks the finalization kind; with none, finalization keeps
@@ -5511,7 +6043,7 @@ async function runCoveredAttempt(params) {
5511
6043
  if (cause) {
5512
6044
  return finish(await failWith({
5513
6045
  error_kind: COMPLETION_CAUSE_ERROR_KINDS[cause],
5514
- error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? cause})`,
6046
+ error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? cause}${unresolvedKindsSuffix(envelope)})`,
5515
6047
  ...observedExit,
5516
6048
  }, envelope));
5517
6049
  }
@@ -5525,7 +6057,47 @@ async function runCoveredAttempt(params) {
5525
6057
  }
5526
6058
  return finish(await failWith({
5527
6059
  error_kind: COMPLETION_CAUSE_ERROR_KINDS.required_work_incomplete,
5528
- error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? "unknown"})`,
6060
+ error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? "unknown"}${unresolvedKindsSuffix(envelope)})`,
5529
6061
  ...observedExit,
5530
6062
  }, envelope));
5531
6063
  }
6064
+ /**
6065
+ * BAPI-1590 — whether a covered attempt's verification shortfall is reported as
6066
+ * `/complete` first because finalization verified a pull request at the pushed head.
6067
+ *
6068
+ * Implementation-style jobs qualify only through the confirmed delivery hold that
6069
+ * finalization let through (`heldAtOpenPr`), never a bare PR number. A `ci_fix` reads
6070
+ * no delivery outcome, so it qualifies through finalization's PR number plus the
6071
+ * server-held branch. Only the two causes the server may lift qualify
6072
+ * (`CARRY_LIFTABLE_CAUSES` in `executor_completion_contract.py`), and unfinished
6073
+ * required work never does. This is only the executor's decision to ASK: the server's
6074
+ * own provider read decides whether the success stands.
6075
+ */
6076
+ export function isPrBackedShortfall(finalization, job, envelope) {
6077
+ if (!finalization.ok)
6078
+ return false;
6079
+ const atPushedHead = finalization.heldAtOpenPr !== undefined ||
6080
+ (job.job_type === "ci_fix" &&
6081
+ typeof finalization.prNumber === "number" &&
6082
+ typeof job.expected_branch === "string" &&
6083
+ job.expected_branch.trim() !== "");
6084
+ return (atPushedHead &&
6085
+ (envelope.cause === "required_check_failed" || envelope.cause === "verification_runner_unavailable") &&
6086
+ unresolvedRequiredTasks(envelope).length === 0);
6087
+ }
6088
+ /**
6089
+ * BAPI-1582 — attach an implement worker's `pre_pr_checks_summary` when its
6090
+ * `.conductor/pre-pr-checks.json` is valid and names the final head. Telemetry
6091
+ * only: any other job type, or any read problem, returns `result` unchanged.
6092
+ */
6093
+ async function attachPrePrChecksTelemetry(job, result, worktreePath, headSha, deps) {
6094
+ if (job.job_type !== "implement")
6095
+ return result;
6096
+ return withPrePrChecksSummary(result, {
6097
+ worktreePath,
6098
+ observedHead: typeof headSha === "string" ? headSha : null,
6099
+ maxResultBytes: RESULT_JSONB_MAX_BYTES,
6100
+ deps: { readFile: deps.readFile, lstatPath: deps.lstatPath },
6101
+ errorLog: (message) => deps.errorLog(`[executor] job ${job.id}: ${message}`),
6102
+ });
6103
+ }