@bridge_gpt/mcp-server 0.2.72 → 0.2.74

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -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
  *
@@ -33,33 +34,38 @@ import { createProductionCiRerunDeps, runCiRerunJob, } from "./ci-rerun-job.js";
33
34
  import { createProductionGateQualificationDeps, runGateQualificationJob, GATE_QUALIFICATION_FAILED, GATE_QUALIFICATION_INTERRUPTED, } from "./gate-qualification-job.js";
34
35
  import { createObservationState } from "./observation.js";
35
36
  import { getWorktreeMcpRegistrationTargets, normalizeWorktreePathForRegistration, provisionMcpRegistrationForWorktree, } from "../mcp-provisioning.js";
37
+ import { hasBridgeConsumer, legacyReferenceBackedTargets } from "../credential-delivery.js";
38
+ import { credentialNoticeLines, formatCredentialAuditLines, prepareExecutorCredentialDelivery, readExecutorCredentialApprovals, } from "./credential-delivery-step.js";
36
39
  import { resolveExecutorAgentAdapter } from "../agent-launchers/executor-adapter-registry.js";
37
40
  import { redactAdapterDiagnostic } from "../agent-launchers/executor-adapter.js";
38
41
  import { resolveExecutorAgentId } from "./agent-identity.js";
39
42
  import { closeStdinBounded, createProcessTerminationController, runProcessWithTimeout, writeStdinBounded, } from "./process.js";
40
43
  import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, unresolvedRequiredTasks, verificationVerdictFromFacts, } from "./completion-contract.js";
41
- 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";
44
+ import { COMPLETION_CAUSE_ERROR_KINDS, EOF_DRAIN_BOUND_MS, FINALIZATION_RESERVE_MS, REPORT_RESERVE_MS, STDIN_CLOSE_GRACE_MS, finalizationFacts, finalizationObligations, planCompletionAllowance, readCompletionBinding, readDeclaredChecks, readOptionalWatchers, readRequiredVerification, renderApprovedVerificationGuidance, } from "./completion-supervision.js";
42
45
  import { compareFinalArtifact, createRequiredVerificationRunner, createSupervisedCommandLauncher, observeFinalArtifact, OWNERSHIP_POLL_MS, preCheckArtifactState, toCompletionCheckFact, } from "./required-verification.js";
43
46
  import { createClosureSupervisor, createRequiredWorkLedger } from "./required-work-ledger.js";
44
47
  import { COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT, requiredWorkKindTokens, } from "./required-work-diagnostics.js";
45
48
  import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withExecutorJobId, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
46
49
  import { resolveCompletionEvidenceCapability } from "../agent-launchers/executor-adapter.js";
47
50
  import { autoCheckpointDirtyState, PRIOR_ATTEMPT_WIP_COMMIT_MESSAGE, prepareResumeSpawn, prepareRetainedContinuationWorktree, readContinuationBinding, verifyContinuationHeadLineage, } from "./resume-pre-spawn.js";
48
- import { buildEpicWorkaroundWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
51
+ import { buildEpicWorkaroundWorkerInstruction, buildCredentialNoticeWorkerInstruction, buildEpicCapabilityStatementWorkerInstruction, buildEpicServerWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
52
+ import { createDefaultEpicServerContextDeps, readEpicServerWorkerContext, withEpicServerEnv, } from "./epic-server-context.js";
49
53
  /** BAPI-1399: the job type whose worker implements ticket requirements from scratch. */
50
54
  const WORKAROUND_CONTRACT_JOB_TYPES = new Set(["implement"]);
51
55
  import { defaultResolveBinPath } from "../start-tickets-conductor.js";
52
56
  /** The packaged bin basename of the deterministic worker guard (BAPI-1020). */
53
57
  const WORKER_GUARD_BIN_FILENAME = "worker-guard-hook-bin.js";
54
- import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArtifact, buildSmokeResult, commitResidue, readCompletionArtifacts, resolveJobTimeoutSeconds, } from "./results.js";
58
+ import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArtifact, readCiFixTestRunsArtifact, buildSmokeResult, commitResidue, readCompletionArtifacts, RESULT_JSONB_MAX_BYTES, resolveJobTimeoutSeconds, } from "./results.js";
55
59
  import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
56
60
  import { removeStaleVerdictArtifacts } from "./stale-artifacts.js";
57
61
  import { stripWorkerEnvFiles } from "./env-file-guard.js";
58
- import { buildDependencyInstallEnv, payloadCiDatabase, payloadDependencyInstallOption, payloadWorkerEnvOption, validateDependencyInstallDeclarations, } from "./env.js";
62
+ import { buildDependencyInstallEnv, payloadCiDatabase, payloadDependencyInstallOption, payloadPrePrChecksOption, payloadWorkerEnvOption, validateDependencyInstallDeclarations, } from "./env.js";
63
+ import { validatePrePrCheckDeclarations, withPrePrChecksSummary } from "./pre-pr-checks.js";
59
64
  import { refreshDeclaredDependencies } from "./dependency-refresh.js";
60
65
  import { readVerificationHints } from "./verification-hints.js";
61
66
  import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine, } from "./worker-database.js";
62
67
  import { formatWorkerCliLauncherUnavailableLine } from "./worker-cli-launcher.js";
68
+ import { formatWorkerDatabaseMalformedLine, formatWorkerDatabaseModeLine, formatWorkerDatabaseSkippedObservationLine, payloadWorkerDatabaseConfigOption, payloadWorkerDatabaseMetadata, payloadWorkerDatabaseParse, } from "./worker-database-config.js";
63
69
  import { isVerdictJobType, readVerdictArtifact } from "./verdict-artifact.js";
64
70
  import { createWorkerLogClaimId, createWorkerLogTee, closeWorkerLogTee, distinctWorkerLogSessionIds, formatWorkerLogSessionInvariantWarning, teeAsyncIterable, } from "./worker-log.js";
65
71
  import { acquireExecutorWorktreeLock, } from "./worktree-lock.js";
@@ -74,7 +80,7 @@ import { deliveryHoldOf, readFocusedPullRequest, resolveOriginBranchSha, validat
74
80
  import { DELIVERY_OUTCOME_READ_TIMEOUT_MS, fetchServerDeliveryOutcome, } from "./delivery-outcome.js";
75
81
  import { FOCUSED_REBASE_JOB_TYPE, focusedRebaseContextError, hasFocusedRebaseContext, validateFocusedRebaseContext, waitForFocusedRebase, } from "./rebase-finalization.js";
76
82
  import { ensureExecutorWorktree, finalizeRetainedExecutorWorktree, } from "./worktree.js";
77
- import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, renderRequiredBeforePush, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
83
+ import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, renderPrePrChecks, renderRequiredBeforePush, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
78
84
  import { CORRECTION_INTENT_CAPABILITY, isRemainingWork, validateCorrectionIntent, } from "./correction-dispatch.js";
79
85
  import { collectGitTelemetry, collectRemoteTrackingSha, createMcpSurfaceObserver, evaluatePreSpawnGitVerification, formatWorkerRateLimitAdvisory, normalizeMcpServerNames, } from "./observation.js";
80
86
  import { failureReasonCode, isFailureReasonCode } from "./failure-reason-codes.js";
@@ -302,7 +308,7 @@ function buildJobLogRegistryDeps(deps) {
302
308
  * only correct value is the one the caller threads down from the validated
303
309
  * runtime configuration.
304
310
  */
305
- function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl) {
311
+ function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl, trustedRepoName, reference) {
306
312
  return {
307
313
  readFile: deps.readFile,
308
314
  writeFile: deps.writeFile,
@@ -311,6 +317,14 @@ function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl) {
311
317
  cwd: deps.cwd,
312
318
  mcpServerInvocation: deps.mcpServerInvocation,
313
319
  bridgeApiBaseUrl,
320
+ // BAPI-1545: the grant file lives under the operator's home. Only the one
321
+ // non-secret path variable the lookup honors is passed, never the ambient env.
322
+ env: deps.env.XDG_CONFIG_HOME !== undefined ? { XDG_CONFIG_HOME: deps.env.XDG_CONFIG_HOME } : {},
323
+ homedir: deps.homedir,
324
+ ...(trustedRepoName !== undefined ? { trustedRepoName } : {}),
325
+ // BAPI-1647: names-only reference inputs for the legacy (no-grant) path.
326
+ ...(reference?.credentialReferenceTargets ? { credentialReferenceTargets: reference.credentialReferenceTargets } : {}),
327
+ ...(reference?.bapiReferenceRepo !== undefined ? { bapiReferenceRepo: reference.bapiReferenceRepo } : {}),
314
328
  };
315
329
  }
316
330
  /**
@@ -398,8 +412,16 @@ async function reportWorkerLogSessionInvariant(tee, deps) {
398
412
  deps.errorLog(formatWorkerLogSessionInvariantWarning(sessions.length));
399
413
  }
400
414
  }
401
- async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, bridgeApiBaseUrl) {
415
+ async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, bridgeApiBaseUrl, credentialApprovals) {
402
416
  const provision = seams.provisionMcp ?? provisionMcpRegistrationForWorktree;
417
+ // BAPI-1647: from the one names-only record read made for this start.
418
+ const credentialMetadata = credentialApprovals?.state === "ok" ? credentialApprovals.metadata : null;
419
+ const reference = credentialMetadata
420
+ ? {
421
+ credentialReferenceTargets: (manifest) => legacyReferenceBackedTargets(credentialMetadata, manifest.mcp),
422
+ ...(hasBridgeConsumer(credentialMetadata) ? { bapiReferenceRepo: job.repo_name } : {}),
423
+ }
424
+ : {};
403
425
  const row = {
404
426
  key: job.ticket_key ?? String(job.id),
405
427
  branch,
@@ -407,10 +429,19 @@ async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, sea
407
429
  path: worktreePath,
408
430
  };
409
431
  try {
410
- const result = await provision(row, buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl));
432
+ // BAPI-1545: the claimed job's `repo_name` comes from the server's claim
433
+ // response, never from a worktree file, so it is the trusted identity the
434
+ // grant is selected by.
435
+ const result = await provision(row, buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl, job.repo_name, reference));
411
436
  for (const warning of result.warnings ?? []) {
412
437
  deps.errorLog(`MCP provisioning warning: ${warning}`);
413
438
  }
439
+ if (result.mcpGrantRegistration !== undefined) {
440
+ // The grant path is never downgraded to a fail-open warning: a
441
+ // registration that could not be made authoritative is refused by the
442
+ // runner, so a stale or worker-edited file is never spawned.
443
+ return result.mcpGrantRegistration;
444
+ }
414
445
  if (result.status === "spawn-failed") {
415
446
  deps.errorLog(`MCP provisioning did not complete (${result.error ?? "unknown reason"}); continuing fail-open`);
416
447
  }
@@ -422,7 +453,30 @@ async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, sea
422
453
  // failure can never leak anything into the executor's own logs.
423
454
  deps.errorLog("MCP provisioning did not complete; continuing fail-open");
424
455
  }
456
+ return null;
457
+ }
458
+ /** Fixed diagnostic when no capability statement line is appended (BAPI-1545). */
459
+ export const CAPABILITY_STATEMENT_NOT_APPENDED_MESSAGE = "capability statement: none appended to the worker prompt (absent, unavailable, or unreadable)";
460
+ /**
461
+ * BAPI-1545: read and render the advisory statement. Never throws; `null` means
462
+ * append nothing.
463
+ */
464
+ async function readCapabilityStatementLine(httpClient, repoName) {
465
+ if (typeof httpClient.readEpicCapabilityStatement !== "function")
466
+ return null;
467
+ try {
468
+ const read = await httpClient.readEpicCapabilityStatement(repoName);
469
+ if (!read.ok || read.state !== "present")
470
+ return null;
471
+ return buildEpicCapabilityStatementWorkerInstruction(read.statement);
472
+ }
473
+ catch {
474
+ return null;
475
+ }
425
476
  }
477
+ /** Fixed, secret-free refusal when the grant-path registration is not authoritative. */
478
+ export const GRANT_MCP_REGISTRATION_UNVERIFIED_MESSAGE = "the MCP grant registration for this worktree could not be written and verified; " +
479
+ "refusing to spawn a worker that could load a stale or edited MCP registration";
426
480
  /**
427
481
  * Confirm the prepared worktree's own `.mcp.json` carries the Bridge shim
428
482
  * registration the worker needs, and capture the spawn contract from it
@@ -660,42 +714,96 @@ function createNoopProcess(deps, durationMs, message) {
660
714
  };
661
715
  }
662
716
  /**
663
- * Bounded newline assembly of worker stdout into whole lines for a
717
+ * Bounded newline assembly of worker stdout into logical lines for a
664
718
  * {@link RequiredWorkLedger} (BAPI-1301 covered path, BAPI-1364 legacy
665
- * observation). A line that outgrows the event bound is handed over once (the
666
- * ledger marks it `stream_oversize`) and the rest of it is discarded up to its
667
- * newline. `onLine` runs after each completed line is ingested.
719
+ * observation; one implementation serves both).
720
+ *
721
+ * A line is assembled whole until its UTF-8 size crosses {@link MAX_EVENT_BYTES}.
722
+ * From then on it is streamed to the ledger's structural reader: the buffered
723
+ * prefix (opening brace included) first, then every later segment of the same
724
+ * line through its newline, however many chunks that takes. Nothing of the tail
725
+ * is discarded, and nothing is ever reinterpreted as a new event. The reader
726
+ * decides, once, when the line ends. `onLine` runs once per completed line, never
727
+ * per chunk. A trailing fragment with no newline is finalized by `flush()` and is
728
+ * never established.
668
729
  */
669
- function createLedgerLineFeeder(ledger, onLine) {
730
+ /** Exported for the feeder's own unit tests; the runner is its only production caller. */
731
+ export function createLedgerLineFeeder(ledger, onLine) {
732
+ const WINDOW_CHARS = 64 * 1024;
670
733
  let lineBuffer = "";
671
- let discardingOversize = false;
734
+ // UTF-8 bytes of `lineBuffer`, counted incrementally; a trailing high
735
+ // surrogate is held back until its pair (or lack of one) is known.
736
+ let lineBytes = 0;
737
+ let carryHigh = false;
738
+ let streaming = false;
739
+ const resetLine = () => {
740
+ lineBuffer = "";
741
+ lineBytes = 0;
742
+ carryHigh = false;
743
+ streaming = false;
744
+ };
745
+ const streamPrefix = () => {
746
+ ledger.beginOversizeLine();
747
+ for (let i = 0; i < lineBuffer.length; i += WINDOW_CHARS) {
748
+ ledger.feedOversizeLineChunk(lineBuffer.slice(i, i + WINDOW_CHARS));
749
+ }
750
+ lineBuffer = "";
751
+ lineBytes = 0;
752
+ carryHigh = false;
753
+ streaming = true;
754
+ };
755
+ const consumeWindow = (w) => {
756
+ if (w.length === 0)
757
+ return;
758
+ if (streaming) {
759
+ ledger.feedOversizeLineChunk(w);
760
+ return;
761
+ }
762
+ const body = (carryHigh ? lineBuffer.slice(-1) : "") + w;
763
+ const endsHigh = (() => {
764
+ const c = w.charCodeAt(w.length - 1);
765
+ return c >= 0xd800 && c <= 0xdbff;
766
+ })();
767
+ lineBytes += Buffer.byteLength(endsHigh ? body.slice(0, -1) : body, "utf8");
768
+ carryHigh = endsHigh;
769
+ lineBuffer += w;
770
+ if (lineBytes + (carryHigh ? 3 : 0) > MAX_EVENT_BYTES)
771
+ streamPrefix();
772
+ };
773
+ const completeLine = () => {
774
+ if (streaming) {
775
+ ledger.endOversizeLine({ newlineTerminated: true });
776
+ }
777
+ else {
778
+ ledger.ingestLine(lineBuffer);
779
+ }
780
+ resetLine();
781
+ onLine?.();
782
+ };
672
783
  return {
673
784
  feed: (chunk) => {
674
- lineBuffer += chunk;
675
- let newline;
676
- while ((newline = lineBuffer.indexOf("\n")) >= 0) {
677
- const line = lineBuffer.slice(0, newline);
678
- lineBuffer = lineBuffer.slice(newline + 1);
679
- if (discardingOversize) {
680
- discardingOversize = false;
681
- continue;
682
- }
683
- ledger.ingestLine(line);
684
- onLine?.();
685
- }
686
- if (!discardingOversize && lineBuffer.length > MAX_EVENT_BYTES) {
687
- ledger.ingestLine(lineBuffer);
688
- lineBuffer = "";
689
- discardingOversize = true;
690
- }
691
- else if (discardingOversize) {
692
- lineBuffer = "";
785
+ let pos = 0;
786
+ while (pos < chunk.length) {
787
+ const newline = chunk.indexOf("\n", pos);
788
+ const end = newline < 0 ? chunk.length : newline;
789
+ for (let w = pos; w < end; w += WINDOW_CHARS)
790
+ consumeWindow(chunk.slice(w, Math.min(end, w + WINDOW_CHARS)));
791
+ if (newline < 0)
792
+ break;
793
+ completeLine();
794
+ pos = newline + 1;
693
795
  }
694
796
  },
695
797
  flush: () => {
696
- if (!discardingOversize && lineBuffer.length > 0)
798
+ if (streaming) {
799
+ ledger.endOversizeLine({ newlineTerminated: false });
800
+ resetLine();
801
+ onLine?.();
802
+ return;
803
+ }
804
+ if (lineBuffer.length > 0)
697
805
  ledger.ingestLine(lineBuffer);
698
- lineBuffer = "";
806
+ resetLine();
699
807
  },
700
808
  };
701
809
  }
@@ -791,6 +899,12 @@ function terminalToRunResult(terminal, successStatus) {
791
899
  // by the wrapper below, before this mapping runs) is what actually
792
900
  // notifies the runner.
793
901
  return { status: "abandoned", reason: "auth_fatal" };
902
+ case "completion_evidence_refused":
903
+ // BAPI-1590: the wrapper below hands this outcome to the caller only when
904
+ // that caller opted into the immediate `/fail` fallback, and that caller
905
+ // handles it before mapping. Reaching here means it did not, so keep the
906
+ // historical reading of a refused `/complete`: a lost claim.
907
+ return { status: "abandoned", reason: "stale_claim" };
794
908
  }
795
909
  }
796
910
  /**
@@ -801,7 +915,13 @@ function terminalToRunResult(terminal, successStatus) {
801
915
  * outcome passes through completely unchanged.
802
916
  */
803
917
  async function sendTerminalMutationWithAuthReport(params, job, control) {
804
- const terminal = await sendTerminalMutationWithRetry(params);
918
+ const { completionEvidenceFallback, ...sendParams } = params;
919
+ const terminal = await sendTerminalMutationWithRetry(sendParams);
920
+ if (terminal.outcome === "completion_evidence_refused" && completionEvidenceFallback !== true) {
921
+ params.ownership.abandoned = true;
922
+ params.ownership.abandonReason = "stale_claim";
923
+ return { outcome: "stale_claim" };
924
+ }
805
925
  if (terminal.outcome === "auth_fatal") {
806
926
  const notice = {
807
927
  jobId: job.id,
@@ -1585,7 +1705,7 @@ async function reportDriverPhaseInterruption(phase, ctx) {
1585
1705
  if (phase.kind === "server_stop") {
1586
1706
  await ctx.httpClient.fail(ctx.job, {
1587
1707
  error_kind: "ServerStopRequested",
1588
- error_message: "the server requested this run stop; the reconciliation was stopped",
1708
+ error_message: "the server asked this job to stop (its run stopped, or its gate moved on); the reconciliation was stopped",
1589
1709
  classification: "killed",
1590
1710
  telemetry: ctx.observation.snapshot(),
1591
1711
  });
@@ -2113,6 +2233,27 @@ async function resumePriorAttemptUnderLock(params) {
2113
2233
  * `renderPromptSpecPrompt`, so untrusted check or ticket text is never
2114
2234
  * re-expanded and never reaches a worker for an unverified checkout.
2115
2235
  */
2236
+ /**
2237
+ * BAPI-1582 — read the worker's `ci_fix` test-run record after exit and return
2238
+ * it only when it is valid for this dispatch's logical job. Fail-open: a
2239
+ * missing, malformed, oversized, unsafe, or other-job record (or a reader that
2240
+ * throws) returns `undefined` and changes nothing else about the job.
2241
+ */
2242
+ async function readForwardableCiFixTestRuns(params) {
2243
+ const { job, ciFix, worktreePath, deps, seams } = params;
2244
+ try {
2245
+ const read = await (seams.readCiFixTestRunsArtifact ?? readCiFixTestRunsArtifact)(worktreePath, dispatchedLogicalJob(job.payload, ciFix), { readFile: deps.readFile, lstatPath: deps.lstatPath });
2246
+ if (read.status === "valid")
2247
+ return read.evidence;
2248
+ if (read.status === "invalid") {
2249
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record ${read.code}; not forwarded`);
2250
+ }
2251
+ }
2252
+ catch {
2253
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record unreadable; not forwarded`);
2254
+ }
2255
+ return undefined;
2256
+ }
2116
2257
  async function renderVerifiedCiFixPrompt(params) {
2117
2258
  const { job, ciFix, worktreePath, branch, baseBranch, deps, seams } = params;
2118
2259
  if (branch.trim() !== ciFix.expectedBranch) {
@@ -2302,7 +2443,7 @@ async function superviseFocusedRebaseWait(params) {
2302
2443
  await params.finalizeRegistry();
2303
2444
  await httpClient.fail(job, {
2304
2445
  error_kind: "ServerStopRequested",
2305
- error_message: "the server requested this run stop; the focused rebase wait was stopped",
2446
+ error_message: "the server asked this job to stop (its run stopped, or its gate moved on); the focused rebase wait was stopped",
2306
2447
  classification: "killed",
2307
2448
  telemetry: observation.snapshot(),
2308
2449
  });
@@ -2393,8 +2534,11 @@ function withoutWorkerFinalMessageExcerpt(failure) {
2393
2534
  async function runSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver) {
2394
2535
  const originalHttp = httpClient;
2395
2536
  let diagnosticWarningSent = false;
2396
- const failWithTelemetry = async (failedJob, body) => {
2397
- let telemetry = { ...body.telemetry, ...observation.snapshot() };
2537
+ // Merge the sanitized worker diagnostics into one report's telemetry. Shared by
2538
+ // the failure and completion wrappers so both follow the same opt-out rule:
2539
+ // a report registered in the WeakSet never carries the final-message excerpt.
2540
+ const withWorkerDiagnostics = (body, base) => {
2541
+ let telemetry = base;
2398
2542
  try {
2399
2543
  const diagnostics = observation.workerDiagnostics();
2400
2544
  if (diagnostics && failuresWithoutWorkerFinalMessageExcerpt.has(body)) {
@@ -2419,11 +2563,26 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2419
2563
  catch { /* supplemental sink */ }
2420
2564
  }
2421
2565
  }
2566
+ return telemetry;
2567
+ };
2568
+ const failWithTelemetry = async (failedJob, body) => {
2569
+ const telemetry = withWorkerDiagnostics(body, { ...body.telemetry, ...observation.snapshot() });
2422
2570
  return originalHttp.fail(failedJob, { ...body, telemetry });
2423
2571
  };
2572
+ // BAPI-1649: a clean worker exit can still be recorded as a server-side failure
2573
+ // (for example a completion the server refuses), and the diagnostics must reach
2574
+ // that record. Only the diagnostics are added: the completion's other telemetry
2575
+ // and all of its evidence are sent exactly as built.
2576
+ const completeWithTelemetry = async (completedJob, completion) => {
2577
+ const telemetry = withWorkerDiagnostics(completion, { ...completion.telemetry });
2578
+ const hasDiagnostics = Object.prototype.hasOwnProperty.call(telemetry, "worker_diagnostics");
2579
+ return originalHttp.complete(completedJob, hasDiagnostics ? { ...completion, telemetry } : completion);
2580
+ };
2424
2581
  httpClient = new Proxy(originalHttp, { get(target, key) {
2425
2582
  if (key === "fail")
2426
2583
  return failWithTelemetry;
2584
+ if (key === "complete")
2585
+ return completeWithTelemetry;
2427
2586
  const value = Reflect.get(target, key);
2428
2587
  return typeof value === "function" ? value.bind(target) : value;
2429
2588
  } });
@@ -2498,6 +2657,7 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2498
2657
  * seams gets the real operation, matching the worktree-lock fallback direction.
2499
2658
  */
2500
2659
  function excludeProvisioningDeps(deps) {
2660
+ const lock = executorExcludeLockDeps(deps);
2501
2661
  return {
2502
2662
  readFile: deps.readFile,
2503
2663
  writeFile: deps.writeFile,
@@ -2505,6 +2665,36 @@ function excludeProvisioningDeps(deps) {
2505
2665
  stat: deps.stat ?? ((filePath) => fsStat(filePath)),
2506
2666
  rename: deps.rename ?? ((from, to) => fsRename(from, to)),
2507
2667
  removeFile: deps.removeFile ?? ((filePath) => rm(filePath, { force: true })),
2668
+ ...(lock ? { excludeLock: lock } : {}),
2669
+ };
2670
+ }
2671
+ /**
2672
+ * BAPI-1647: the cross-process exclude lock, built from the executor's OWN
2673
+ * injected filesystem and clock (exclusive create, remove, mkdir, realpath,
2674
+ * mtime, sleep), so the lock never opens a file handle the runner did not hand
2675
+ * it. Absent when the deps cannot create a file exclusively.
2676
+ */
2677
+ function executorExcludeLockDeps(deps) {
2678
+ const createExclusive = deps.writeFileExclusive;
2679
+ const remove = deps.removeFile;
2680
+ if (!createExclusive || !remove)
2681
+ return undefined;
2682
+ return {
2683
+ open: async (p) => {
2684
+ await createExclusive(p, "");
2685
+ return { close: async () => undefined };
2686
+ },
2687
+ unlink: (p) => remove(p),
2688
+ mkdir: (p, o) => deps.mkdir(p, o),
2689
+ realpath: deps.realpath ?? (async (p) => path.resolve(p)),
2690
+ mtimeMs: async (p) => {
2691
+ const mtime = deps.statMtimeMs ? await deps.statMtimeMs(p) : null;
2692
+ if (mtime === null)
2693
+ throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
2694
+ return mtime;
2695
+ },
2696
+ now: deps.now,
2697
+ sleep: deps.sleep,
2508
2698
  };
2509
2699
  }
2510
2700
  async function runReservedSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control,
@@ -2872,6 +3062,22 @@ resolvedTimeoutSeconds) {
2872
3062
  classification: "crashed" });
2873
3063
  return { status: "failed", reason: "recently_failed_tests_file" };
2874
3064
  }
3065
+ // BAPI-1582: seed the ci_fix test-run record with this repair's logical job
3066
+ // and any valid prior runs the server restored. Fail-open telemetry: a
3067
+ // refused or failed seed is logged by fixed code and the spawn proceeds.
3068
+ if (prep.ciFix) {
3069
+ // Through the executor's injected I/O, never a second filesystem path.
3070
+ const seedFs = ciFixTestRunsFsFromDeps(deps);
3071
+ const seed = seedFs === undefined
3072
+ ? { status: "skipped", code: "fs_unavailable" }
3073
+ : await (seams.seedCiFixTestRunsFile ?? seedCiFixTestRunsFile)(worktreePath, {
3074
+ logicalJob: dispatchedLogicalJob(job.payload, prep.ciFix),
3075
+ prior: job.payload?.[CI_FIX_PRIOR_TEST_RUNS_PAYLOAD_KEY],
3076
+ }, seedFs).catch(() => ({ status: "skipped", code: "seed_threw" }));
3077
+ if (seed.status === "skipped") {
3078
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record not seeded (${seed.code})`);
3079
+ }
3080
+ }
2875
3081
  return await runPreparedSpawn({
2876
3082
  job,
2877
3083
  httpClient,
@@ -2966,7 +3172,7 @@ async function prepareDependencyRefresh(params) {
2966
3172
  entries: params.entries,
2967
3173
  worktreePath: params.worktreePath,
2968
3174
  mainCheckoutPath: deps.cwd,
2969
- env: buildDependencyInstallEnv(deps.env, job.payload),
3175
+ env: buildDependencyInstallEnv(deps.env, job.payload, payloadWorkerDatabaseConfigOption(job.payload)),
2970
3176
  remainingMs: params.remainingMs(),
2971
3177
  now: deps.now,
2972
3178
  sleep: deps.sleep,
@@ -2988,7 +3194,7 @@ async function prepareDependencyRefresh(params) {
2988
3194
  if (phase.kind === "server_stop") {
2989
3195
  await params.httpClient.fail(job, {
2990
3196
  error_kind: "ServerStopRequested",
2991
- error_message: "the server requested this run stop before the worker started",
3197
+ error_message: "the server asked this job to stop (its run stopped, or its gate moved on) before the worker started",
2992
3198
  classification: "killed",
2993
3199
  telemetry: params.observation.snapshot(),
2994
3200
  });
@@ -3031,9 +3237,31 @@ async function prepareWorkerResources(params) {
3031
3237
  const { job, deps, lifecycle } = params;
3032
3238
  const jobId = String(job.id);
3033
3239
  const resources = deps.workerResources;
3240
+ // BAPI-1598 — the declaration is parsed once. Only an explicit, valid
3241
+ // `disposable_postgres` payload provisions anything; every other state keeps
3242
+ // the job stack-neutral and never falls back to a Bridge default.
3243
+ const parsed = payloadWorkerDatabaseParse(job.payload);
3244
+ const metadata = payloadWorkerDatabaseMetadata(job.payload);
3245
+ const declared = parsed.classification === "enabled" || parsed.classification === "disabled"
3246
+ ? parsed.config : undefined;
3247
+ const declaration = {
3248
+ workerDatabaseMode: metadata.worker_database_mode,
3249
+ ...(declared ? { workerDatabaseConfig: declared } : {}),
3250
+ };
3251
+ try {
3252
+ // An unconfigured job (no declaration) stays quiet; any declaration is recorded
3253
+ // by mode and live profile revision only.
3254
+ if (metadata.worker_database_mode !== "absent")
3255
+ deps.errorLog(formatWorkerDatabaseModeLine(jobId, metadata));
3256
+ if (parsed.classification === "malformed") {
3257
+ deps.errorLog(formatWorkerDatabaseMalformedLine(jobId, parsed.reason));
3258
+ }
3259
+ }
3260
+ catch { /* sink */ }
3034
3261
  if (!resources)
3035
- return { kind: "ready" };
3262
+ return { kind: "ready", ...declaration };
3036
3263
  let target;
3264
+ let targetRole;
3037
3265
  let disposeLauncher;
3038
3266
  let launcherDirectory;
3039
3267
  let unavailableCategory;
@@ -3043,8 +3271,10 @@ async function prepareWorkerResources(params) {
3043
3271
  if (released)
3044
3272
  return;
3045
3273
  released = true;
3046
- if (target) {
3047
- const dropped = await resources.dropDatabase(target).catch(() => ({ kind: "failed" }));
3274
+ if (target && targetRole !== undefined) {
3275
+ const dropped = await resources
3276
+ .dropDatabase(target, targetRole)
3277
+ .catch(() => ({ kind: "failed" }));
3048
3278
  if (dropped.kind !== "dropped") {
3049
3279
  try {
3050
3280
  deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, target.name));
@@ -3081,17 +3311,24 @@ async function prepareWorkerResources(params) {
3081
3311
  signal.addEventListener("abort", abortCombined, { once: true });
3082
3312
  shutdown.signal.addEventListener("abort", abortCombined, { once: true });
3083
3313
  const cancel = combined.signal;
3084
- const provisioned = await resources
3085
- .provisionDatabase({
3086
- jobId,
3087
- worktreePath: params.worktreePath,
3088
- signal: cancel,
3089
- // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
3090
- ...payloadWorkerEnvOption(job.payload),
3091
- })
3092
- .catch(() => ({ kind: "unavailable", category: "create_failed" }));
3093
- if (provisioned.kind === "provisioned") {
3314
+ const provisioned = parsed.classification === "enabled"
3315
+ ? await resources
3316
+ .provisionDatabase({
3317
+ jobId,
3318
+ worktreePath: params.worktreePath,
3319
+ signal: cancel,
3320
+ config: parsed.config,
3321
+ // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
3322
+ ...payloadWorkerEnvOption(job.payload),
3323
+ })
3324
+ .catch(() => ({ kind: "unavailable", category: "create_failed" }))
3325
+ : undefined;
3326
+ if (provisioned === undefined) {
3327
+ // Nothing was configured to provision: no database resource, no failure to report.
3328
+ }
3329
+ else if (provisioned.kind === "provisioned") {
3094
3330
  target = provisioned.target;
3331
+ targetRole = provisioned.role;
3095
3332
  }
3096
3333
  else {
3097
3334
  unavailableCategory = provisioned.category;
@@ -3135,7 +3372,7 @@ async function prepareWorkerResources(params) {
3135
3372
  if (phase.kind === "server_stop") {
3136
3373
  await params.httpClient.fail(job, {
3137
3374
  error_kind: "ServerStopRequested",
3138
- error_message: "the server requested this run stop before the worker started",
3375
+ error_message: "the server asked this job to stop (its run stopped, or its gate moved on) before the worker started",
3139
3376
  classification: "killed",
3140
3377
  telemetry: params.observation.snapshot(),
3141
3378
  });
@@ -3161,6 +3398,7 @@ async function prepareWorkerResources(params) {
3161
3398
  // `kind: "error"` is an unexpected throw from the seam itself: degrade.
3162
3399
  return {
3163
3400
  kind: "ready",
3401
+ ...declaration,
3164
3402
  ...(target ? { workerDatabase: target } : {}),
3165
3403
  ...(launcherDirectory ? { workerLauncherDirectory: launcherDirectory } : {}),
3166
3404
  ...(!target && unavailableCategory ? { workerDatabaseUnavailableCategory: unavailableCategory } : {}),
@@ -3195,12 +3433,19 @@ export const fileSystemExecutableCheck = (candidate, options) => {
3195
3433
  function retainedHeadPublisher(params) {
3196
3434
  return async () => {
3197
3435
  const { job, branch, worktreePath, prep, deps, ownership, observation, remainingMs } = params;
3198
- if (!prep.publicationBaseline)
3436
+ const createStartSha = prep.comparisonSha ?? prep.expectedHeadSha;
3437
+ const createOnly = !prep.publicationBaseline && params.allowCreateOnly === true && prep.publicationRemoteAbsent === true;
3438
+ if (!prep.publicationBaseline && !createOnly)
3439
+ return { status: "refused", reason: "invalid_input" };
3440
+ if (createOnly && !createStartSha)
3199
3441
  return { status: "refused", reason: "invalid_input" };
3200
3442
  const phase = await superviseDriverPhase({ job, httpClient: params.httpClient, options: params.options, deps, ownership, observation, control: params.control,
3201
3443
  timeoutSeconds: Math.max(1, Math.ceil(remainingMs() / 1000)), collectTelemetry: async () => ({}),
3202
3444
  run: async (signal) => {
3203
- const result = await guardedFastForwardPush({ branch, expectedOriginSha: prep.publicationBaseline,
3445
+ const result = await guardedFastForwardPush({ branch,
3446
+ ...(createOnly ? { expectedOriginSha: null, createOnly: { startSha: createStartSha } }
3447
+ : { expectedOriginSha: prep.publicationBaseline }),
3448
+ ...(params.candidateSha !== undefined ? { candidateSha: params.candidateSha } : {}),
3204
3449
  worktreePath, runCommand: deps.runCommand, env: deps.env, remainingMs, signal,
3205
3450
  mayMutate: () => !ownership.abandoned && !signal.aborted });
3206
3451
  if (result.status === "published")
@@ -3243,6 +3488,8 @@ async function runPreparedSpawn(params) {
3243
3488
  // it repairs an existing branch whose pull request already exists, and the PR
3244
3489
  // base contract's "when you open the pull request" instruction would re-add the
3245
3490
  // new-PR step the focused prompt deliberately excludes.
3491
+ // BAPI-1546: `disabled` unless the repository opted in; then injected at spawn.
3492
+ let epicServerContext = { kind: "disabled" };
3246
3493
  let prompt = isImplementationStyleJobType(job.job_type) && !prep.ciFix && !prep.focusedRebase
3247
3494
  ? `${prep.prompt} ${renderWorkerPrBaseGuidance()}`
3248
3495
  : prep.prompt;
@@ -3258,6 +3505,37 @@ async function runPreparedSpawn(params) {
3258
3505
  // an older API) stays absent so the instruction keeps its conditional wording.
3259
3506
  const handoffEnabled = job.payload?.verification_handoff_enabled;
3260
3507
  prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key, typeof handoffEnabled === "boolean" ? handoffEnabled : undefined)}`;
3508
+ // BAPI-1545: an implement job in an epic run gets the owner's advisory
3509
+ // capability statement, read once here with a short timeout. Absent,
3510
+ // unavailable, malformed, or failed reads append nothing (the prompt stays
3511
+ // byte-identical) and log one fixed line. The job proceeds either way.
3512
+ if (job.job_type === "implement" && typeof job.epic_run_id === "string" && job.epic_run_id.length > 0) {
3513
+ const capabilityLine = await readCapabilityStatementLine(httpClient, job.repo_name);
3514
+ if (capabilityLine !== null) {
3515
+ prompt = `${prompt} ${capabilityLine}`;
3516
+ }
3517
+ else {
3518
+ deps.errorLog(CAPABILITY_STATEMENT_NOT_APPENDED_MESSAGE);
3519
+ }
3520
+ }
3521
+ // BAPI-1546: the epic-server turn paragraph, beside the workaround contract,
3522
+ // only for an opted-in repository. One bounded, fail-open read; any failure
3523
+ // is "no opt-in" (or "local, unavailable"), never a failed job or a delay.
3524
+ if (typeof job.epic_run_id === "string" && job.epic_run_id.length > 0) {
3525
+ try {
3526
+ const readContext = seams.readEpicServerContext ??
3527
+ ((repo, runId) => readEpicServerWorkerContext(repo, runId, createDefaultEpicServerContextDeps(deps.env)));
3528
+ epicServerContext = await readContext(job.repo_name, job.epic_run_id);
3529
+ }
3530
+ catch {
3531
+ epicServerContext = { kind: "disabled" };
3532
+ }
3533
+ const epicServerLine = buildEpicServerWorkerInstruction(epicServerContext, job.ticket_key);
3534
+ if (epicServerLine !== null)
3535
+ prompt = `${prompt} ${epicServerLine}`;
3536
+ else
3537
+ epicServerContext = { kind: "disabled" };
3538
+ }
3261
3539
  }
3262
3540
  // --- Timeout contract ------------------------------------------------
3263
3541
  const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
@@ -3300,6 +3578,10 @@ async function runPreparedSpawn(params) {
3300
3578
  if (remote.exitCode === 0 && fields.length === 2 && fields[1] === `refs/heads/${branch}` && /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/i.test(fields[0])) {
3301
3579
  prep.publicationBaseline = isRecoveryJobType(job.job_type) ? prep.expectedHeadSha : fields[0];
3302
3580
  }
3581
+ else if (remote.exitCode === 2 && remote.stdout.trim() === "") {
3582
+ // Confirmed absence. Any other failed or odd read stays unknown, never absence.
3583
+ prep.publicationRemoteAbsent = true;
3584
+ }
3303
3585
  }
3304
3586
  catch { /* no eligible lease baseline */ }
3305
3587
  }
@@ -3372,7 +3654,7 @@ async function runPreparedSpawn(params) {
3372
3654
  // Trusted starter context is appended AFTER packaged-command expansion, never
3373
3655
  // inserted into command arguments or scanned through untrusted server evidence.
3374
3656
  if (job.job_type === "implement" && !isRemainingWork(job.job_type, job.payload)) {
3375
- prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha);
3657
+ prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha) + "\n\n" + renderWorkerPushEachCommitGuidance();
3376
3658
  }
3377
3659
  // The locked ci_fix renderer deferred trusted guidance. All existing prompt
3378
3660
  // additions precede comparison guidance and the final total-budget block.
@@ -3456,6 +3738,19 @@ async function runPreparedSpawn(params) {
3456
3738
  // unchanged and deliberately still fail-OPEN: a provisioning hiccup shrinks
3457
3739
  // safety margin but must not kill a job. Refusing to CLAIM on unenforced deny
3458
3740
  // remains a separate, fatal preflight concern.
3741
+ // --- Referenced credentials: names-only read (fail-open, BAPI-1647) --
3742
+ // Keyed on the claimed job's `repo_name` (the server's claim response, the
3743
+ // same trusted identity the MCP grant uses), read fresh at every worker start.
3744
+ // It supplies the restricted source paths for the deny layer below and the
3745
+ // reference inputs for MCP provisioning. Never fails the job.
3746
+ const credentialEnvDeps = {
3747
+ env: deps.env,
3748
+ homedir: deps.homedir,
3749
+ platform: deps.platform,
3750
+ readFile: deps.readFile,
3751
+ runCommand: (file, args, opts) => deps.runCommand(file, args, opts),
3752
+ };
3753
+ const credentialApprovals = await readExecutorCredentialApprovals(job.repo_name, credentialEnvDeps, seams.credentialReferences);
3459
3754
  const denyCapability = adapter.denyEnforcement;
3460
3755
  const correctionWork = isRemainingWork(job.job_type, job.payload);
3461
3756
  let correctionDenyInstalled = false;
@@ -3476,6 +3771,10 @@ async function runPreparedSpawn(params) {
3476
3771
  workerBranch: branch,
3477
3772
  ...(correctionWork ? { correctionIntentVersion: 1 } : {}),
3478
3773
  workerGuardHookBinPath: correctionHookBinPath,
3774
+ // BAPI-1647: one exact Read deny rule per restricted credential source.
3775
+ ...(credentialApprovals.restrictedSourcePaths.length > 0
3776
+ ? { restrictedSourcePaths: credentialApprovals.restrictedSourcePaths }
3777
+ : {}),
3479
3778
  });
3480
3779
  // Log on WARNING PRESENCE, not on `!ok` (BAPI-815/R2). The git-exclude
3481
3780
  // hygiene step can degrade without failing the deny layer — present-but-
@@ -3529,7 +3828,7 @@ async function runPreparedSpawn(params) {
3529
3828
  // BAPI-727: the validated endpoint travels from executor bootstrap through the
3530
3829
  // runtime options to the generated registration, so the worker's MCP server
3531
3830
  // targets the same Bridge API this executor claimed the job from.
3532
- await provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, options.resolvedBaseUrl);
3831
+ const grantRegistration = await provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, options.resolvedBaseUrl, credentialApprovals.approvals);
3533
3832
  // --- Required Bridge MCP registration (FAIL-CLOSED) -------------------
3534
3833
  // Provisioning itself stays fail-OPEN: a skipped or malformed Tier-2 target is
3535
3834
  // a warning, and every valid worktree-provisioned server is kept. The REQUIRED
@@ -3558,10 +3857,21 @@ async function runPreparedSpawn(params) {
3558
3857
  return { status: "failed", reason: "executor_adapter_unavailable" };
3559
3858
  }
3560
3859
  const registration = await verifyRegistration(worktreePath, deps, mcpScoping.value.requiredServerName);
3561
- if (!registration.ok) {
3860
+ // BAPI-1545: on the grant path the registration must ALSO be the one
3861
+ // provisioning wrote and read back: exactly Bridge plus the granted names. The
3862
+ // expected init-event set is then that verified set, so a granted server that
3863
+ // fails to connect is still expected by name (it never fails the job), and an
3864
+ // extra server cannot appear.
3865
+ const grantMismatch = grantRegistration !== null &&
3866
+ grantRegistration !== undefined &&
3867
+ (!grantRegistration.ok ||
3868
+ (registration.ok &&
3869
+ JSON.stringify([...registration.contract.expectedServerNames].sort()) !==
3870
+ JSON.stringify([...grantRegistration.expectedServerNames].sort())));
3871
+ if (!registration.ok || grantMismatch) {
3562
3872
  await httpClient.fail(job, {
3563
3873
  error_kind: RequiredMcpRegistration,
3564
- error_message: registration.message,
3874
+ error_message: registration.ok ? GRANT_MCP_REGISTRATION_UNVERIFIED_MESSAGE : registration.message,
3565
3875
  classification: "crashed",
3566
3876
  ...commitResidue(preSpawnTelemetry),
3567
3877
  telemetry: observation.snapshot(),
@@ -3569,6 +3879,16 @@ async function runPreparedSpawn(params) {
3569
3879
  return { status: "failed", reason: "required_mcp_registration" };
3570
3880
  }
3571
3881
  const mcpContract = registration.contract;
3882
+ // --- Referenced credentials: file links + sandbox variables (BAPI-1647) --
3883
+ // After MCP provisioning and its verification, and before the final `.env*`
3884
+ // strip below, which is unchanged (child 1 refuses `.env` sources and
3885
+ // destinations, so the two never meet). Files are linked through the shared
3886
+ // reconciled, exclusion-first delivery; variables stay in memory until the env
3887
+ // builder admits them. Every problem is a names-only notice: the job is never
3888
+ // failed or parked because of a credential.
3889
+ const credentialPrep = await prepareExecutorCredentialDelivery(job.repo_name, worktreePath, credentialApprovals.approvals, credentialEnvDeps, seams.credentialReferences);
3890
+ const credentialNotice = buildCredentialNoticeWorkerInstruction(credentialNoticeLines(credentialPrep));
3891
+ let credentialAdmission = null;
3572
3892
  // --- Worker log tee + watch registry + viewer tab (BAPI-535 §8) ------
3573
3893
  // BAPI-1330: ONE attempt identity — the server's job id and attempt number
3574
3894
  // plus a claim id minted here — names this attempt's log file, its registry
@@ -3779,7 +4099,14 @@ async function runPreparedSpawn(params) {
3779
4099
  }
3780
4100
  }
3781
4101
  }
3782
- let workerResources = {};
4102
+ let workerResources = {
4103
+ // BAPI-1598 — the sentinel protection follows the payload's declaration for EVERY
4104
+ // job type that spawns a worker, not only those that may provision a database.
4105
+ ...payloadWorkerDatabaseConfigOption(job.payload),
4106
+ };
4107
+ // BAPI-1598: the effective mode follows the payload for EVERY job type, so a job that never
4108
+ // prepares worker resources is not told a database it never expected is missing.
4109
+ let workerDatabaseMode = payloadWorkerDatabaseMetadata(job.payload).worker_database_mode;
3783
4110
  // BAPI-1522: why no database exists (a closed category), kept OUT of the spawn input.
3784
4111
  let databaseUnavailableCategory;
3785
4112
  let databaseUnavailableCause;
@@ -3793,17 +4120,35 @@ async function runPreparedSpawn(params) {
3793
4120
  await finalizeRegistry();
3794
4121
  return prepared.result;
3795
4122
  }
4123
+ workerDatabaseMode = prepared.workerDatabaseMode;
3796
4124
  workerResources = {
3797
4125
  ...(prepared.workerDatabase ? { workerDatabase: prepared.workerDatabase } : {}),
4126
+ ...(prepared.workerDatabaseConfig ? { workerDatabaseConfig: prepared.workerDatabaseConfig } : {}),
3798
4127
  ...(prepared.workerLauncherDirectory ? { workerLauncherDirectory: prepared.workerLauncherDirectory } : {}),
3799
4128
  };
3800
4129
  databaseUnavailableCategory = prepared.workerDatabaseUnavailableCategory;
3801
4130
  databaseUnavailableCause = prepared.workerDatabaseUnavailableCause;
3802
- // BAPI-1563: provisioning fell back to the sentinel database. Report the fact;
3803
- // the existing diagnostic line (logged at provisioning) is unchanged, and this
3804
- // is never a local carry-authority decision.
3805
- if (databaseUnavailableCategory !== undefined) {
3806
- recordVerificationObservation(job, { cause: "no_database" });
4131
+ // BAPI-1609: report the provisioning outcome on every later telemetry
4132
+ // snapshot. Only a genuinely provisioned target sets it; the sentinel
4133
+ // fallback below never does.
4134
+ if (prepared.workerDatabase !== undefined)
4135
+ observation.recordWorkerDatabaseProvisioned();
4136
+ // BAPI-1563: the worker has no database. Report the fact only when CI
4137
+ // confirms it has none either (BAPI-1598): a CI-provided database means the
4138
+ // checks are delegated, and an unknown CI capability is not confirmed absence,
4139
+ // so neither records a gap. This is never a local carry-authority decision.
4140
+ if (workerResources.workerDatabase === undefined) {
4141
+ const ciDatabase = payloadCiDatabase(job.payload);
4142
+ if (ciDatabase === "none") {
4143
+ recordVerificationObservation(job, { cause: "no_database" });
4144
+ }
4145
+ else if (ciDatabase === "provided" || workerDatabaseMode !== "absent") {
4146
+ // An unconfigured job whose CI capability is also unknown has nothing to report.
4147
+ try {
4148
+ deps.errorLog(formatWorkerDatabaseSkippedObservationLine(String(job.id), ciDatabase === "provided" ? "delegated_to_ci" : "ci_database_unknown"));
4149
+ }
4150
+ catch { /* sink */ }
4151
+ }
3807
4152
  }
3808
4153
  }
3809
4154
  const invocation = adapter.headlessInvocation;
@@ -3860,6 +4205,17 @@ async function runPreparedSpawn(params) {
3860
4205
  // job type. Absent keeps the legacy compatibility constants; a present
3861
4206
  // value, even `[]` or a malformed one, replaces them.
3862
4207
  ...payloadWorkerEnvOption(job.payload),
4208
+ // BAPI-1647 — approved sandbox credential variables, resolved above in this
4209
+ // process. Present only when there are any, so every other job's
4210
+ // environment is byte-identical.
4211
+ ...(Object.keys(credentialPrep.declaredCredentialEnv).length > 0
4212
+ ? {
4213
+ declaredCredentialEnv: credentialPrep.declaredCredentialEnv,
4214
+ onDeclaredCredentialEnv: (outcome) => {
4215
+ credentialAdmission = outcome;
4216
+ },
4217
+ }
4218
+ : {}),
3863
4219
  parentEnv: deps.env,
3864
4220
  };
3865
4221
  // The PATH the worker will receive: the launcher directory (when provisioned)
@@ -3876,6 +4232,7 @@ async function runPreparedSpawn(params) {
3876
4232
  ? job.payload.reproduce_commands : undefined;
3877
4233
  const limits = renderLocalEnvironmentLimits({
3878
4234
  databaseAvailable: workerResources.workerDatabase !== undefined,
4235
+ ...(workerDatabaseMode !== undefined ? { workerDatabaseMode } : {}),
3879
4236
  ...(databaseUnavailableCategory && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3880
4237
  ? { databaseUnavailableCategory } : {}),
3881
4238
  ...(databaseUnavailableCause && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
@@ -3890,10 +4247,35 @@ async function runPreparedSpawn(params) {
3890
4247
  // BAPI-1551: REQUIRED BEFORE PUSH sits immediately before LOCAL ENVIRONMENT
3891
4248
  // LIMITS, which stays last. With neither, the prompt is byte-identical.
3892
4249
  const required = renderRequiredBeforePush(requiredReferences);
4250
+ // BAPI-1582: an implement job's admitted gate-profile commands follow REQUIRED
4251
+ // BEFORE PUSH. Read only when the payload OWNS `pre_pr_checks`; no admitted
4252
+ // entry renders nothing, so the prompt stays byte-identical. Never the
4253
+ // ci_fix reproduction block.
4254
+ const prePrChecks = job.job_type === "implement"
4255
+ ? renderPrePrChecks(validatePrePrCheckDeclarations(payloadPrePrChecksOption(job.payload), deps.errorLog))
4256
+ : "";
4257
+ // BAPI-1647: the credential notice follows the job prompt; LOCAL
4258
+ // ENVIRONMENT LIMITS stays last. No notice renders nothing.
3893
4259
  spawnShape = invocation.value.buildSpawnShape({
3894
- prompt: [prompt, required, limits].filter((section) => section.length > 0).join("\n\n"),
4260
+ prompt: [prompt, credentialNotice, required, prePrChecks, limits].filter((section) => section.length > 0).join("\n\n"),
3895
4261
  ...shapeInput,
3896
4262
  });
4263
+ // BAPI-1647: names-only audit in the executor's local per-job log. Never
4264
+ // the job row and never the server.
4265
+ try {
4266
+ const admission = credentialAdmission;
4267
+ for (const line of formatCredentialAuditLines(job.id, credentialPrep, admission?.admitted ?? null, admission?.dropped ?? [])) {
4268
+ deps.errorLog(line);
4269
+ }
4270
+ }
4271
+ catch {
4272
+ /* audit is supplemental */
4273
+ }
4274
+ // BAPI-1546: the trusted browser target (and run id for turns), injected AFTER
4275
+ // the environment builder ran, like the job tag. `disabled` leaves the shape untouched.
4276
+ if (epicServerContext.kind !== "disabled" && spawnShape.env) {
4277
+ spawnShape = { ...spawnShape, env: withEpicServerEnv(spawnShape.env, epicServerContext) };
4278
+ }
3897
4279
  assertUsableSpawnShape(spawnShape, adapter);
3898
4280
  }
3899
4281
  catch (err) {
@@ -4251,7 +4633,7 @@ async function runPreparedSpawn(params) {
4251
4633
  await driver.abandon(driverBaseContext);
4252
4634
  await httpClient.fail(job, {
4253
4635
  error_kind: "ServerStopRequested",
4254
- error_message: "the server requested this run stop; the owned worker was terminated",
4636
+ error_message: "the server asked this job to stop (its run stopped, or its gate moved on); the owned worker was terminated",
4255
4637
  classification: "killed",
4256
4638
  ...commitResidue(finalTelemetry),
4257
4639
  telemetry: observation.snapshot(),
@@ -4506,6 +4888,11 @@ async function runPreparedSpawn(params) {
4506
4888
  genericResult = { ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status };
4507
4889
  }
4508
4890
  }
4891
+ // BAPI-1582: optional, bounded test-run telemetry for a resumed repair.
4892
+ const ciFixTestRuns = prep.ciFix
4893
+ ? await readForwardableCiFixTestRuns({ job, ciFix: prep.ciFix, worktreePath, deps, seams })
4894
+ : undefined;
4895
+ genericResult = withCiFixTestRuns(genericResult, ciFixTestRuns, RESULT_JSONB_MAX_BYTES);
4509
4896
  // BAPI-551: a worker can exit `clean_exit` yet strand its implementation if
4510
4897
  // its push never landed on origin and no PR was opened (e.g. it backgrounded
4511
4898
  // a slow push and returned early). Convert that into a fail-loud executor
@@ -4553,7 +4940,9 @@ async function runPreparedSpawn(params) {
4553
4940
  // finalization failure; it is never rewritten to look like a crash.
4554
4941
  ...observedExitCode(procResult.exitCode),
4555
4942
  ...commitResidue(git),
4556
- telemetry: withFailureTelemetry(observation.snapshot(), finalization.failure.telemetry),
4943
+ // BAPI-1582: a held or failed finalization still carries the
4944
+ // repair's test-run record, so a continuation can restore it.
4945
+ telemetry: withCiFixTestRuns(withFailureTelemetry(observation.snapshot(), finalization.failure.telemetry), ciFixTestRuns, RESULT_JSONB_MAX_BYTES),
4557
4946
  }),
4558
4947
  deps,
4559
4948
  options,
@@ -4621,9 +5010,12 @@ async function runPreparedSpawn(params) {
4621
5010
  // made; worker prose is never admissible here (R14 rule 3). It is omitted
4622
5011
  // rather than set to null when finalization had no PR to verify (a
4623
5012
  // non-implementation job), so the field's presence always means "verified".
4624
- const result = typeof finalization.prUrl === "string"
5013
+ const verifiedResult = typeof finalization.prUrl === "string"
4625
5014
  ? { ...genericResult, pr_url: finalization.prUrl }
4626
5015
  : genericResult;
5016
+ // BAPI-1582: an implement worker's current-head pre-PR record rides as bounded
5017
+ // telemetry, never gate evidence. Missing, stale, or oversized attaches nothing.
5018
+ const result = await attachPrePrChecksTelemetry(job, verifiedResult, worktreePath, git.last_commit_sha, deps);
4627
5019
  const completion = {
4628
5020
  job_type: job.job_type,
4629
5021
  exit_code: procResult.exitCode ?? 0,
@@ -5006,7 +5398,7 @@ async function runCoveredAttempt(params) {
5006
5398
  if (beat.kind === "server_stop") {
5007
5399
  // Report first, then mark the claim abandoned, exactly as the post-spawn
5008
5400
  // server-stop path does: an abandoned claim skips the terminal report.
5009
- const stopped = await notLaunched("the server requested this run stop before the worker launched");
5401
+ const stopped = await notLaunched("the server asked this job to stop (its run stopped, or its gate moved on) before the worker launched");
5010
5402
  ownership.abandoned = true;
5011
5403
  ownership.abandonReason = "server_stop";
5012
5404
  return stopped.status === "failed" ? { status: "abandoned", reason: "server_stop" } : stopped;
@@ -5332,6 +5724,9 @@ async function runCoveredAttempt(params) {
5332
5724
  },
5333
5725
  };
5334
5726
  const git = observation.git();
5727
+ // BAPI-1582: set once the worker's ci_fix test-run record is read, so a held
5728
+ // or refused covered attempt still carries it for a later continuation.
5729
+ let failTestRuns;
5335
5730
  const failWith = async (failure, envelope, extra = {}) => {
5336
5731
  await finalizeRegistry();
5337
5732
  // BAPI-1554: the primary failure text stays first; the closure-time live-work
@@ -5347,7 +5742,7 @@ async function runCoveredAttempt(params) {
5347
5742
  send: () => httpClient.fail(job, {
5348
5743
  ...failureWithWindowDiagnostic,
5349
5744
  ...commitResidue(git),
5350
- telemetry: withFailureTelemetry(observation.snapshot(), failure.telemetry),
5745
+ telemetry: withCiFixTestRuns(withFailureTelemetry(observation.snapshot(), failure.telemetry), failTestRuns, RESULT_JSONB_MAX_BYTES),
5351
5746
  completion_contract: SUPPORTED_COMPLETION_MARKER,
5352
5747
  completion_evidence: envelope,
5353
5748
  ...extra,
@@ -5418,7 +5813,7 @@ async function runCoveredAttempt(params) {
5418
5813
  // outlives the worker, so a lost claim or a server stop can arrive during
5419
5814
  // cleanup, verification or finalization, and must still win over a report
5420
5815
  // built from those phases.
5421
- const strongerOutcome = async () => {
5816
+ const strongerOutcome = async (serverStopTelemetry) => {
5422
5817
  if (ownership.abandoned) {
5423
5818
  await finalizeRegistry();
5424
5819
  return finish({ status: "abandoned", reason: ownership.abandonReason });
@@ -5427,8 +5822,9 @@ async function runCoveredAttempt(params) {
5427
5822
  if (hbNow?.kind === "server_stop") {
5428
5823
  const result = await failWith({
5429
5824
  error_kind: "ServerStopRequested",
5430
- error_message: "the server requested this run stop; the owned worker was terminated",
5825
+ error_message: "the server asked this job to stop (its run stopped, or its gate moved on); the owned worker was terminated",
5431
5826
  classification: "killed",
5827
+ ...(serverStopTelemetry ? { telemetry: serverStopTelemetry } : {}),
5432
5828
  }, { ...unverifiedEnvelope(), end_cause: "server_stop" });
5433
5829
  ownership.abandoned = true;
5434
5830
  ownership.abandonReason = "server_stop";
@@ -5460,6 +5856,40 @@ async function runCoveredAttempt(params) {
5460
5856
  errorLog: deps.errorLog,
5461
5857
  });
5462
5858
  }
5859
+ // Covered-timeout publication: a worker that timed out may still have committed
5860
+ // useful work. Publish the exact reported head, but only when every fact below
5861
+ // holds, and never let the outcome change: the timeout failure is still reported.
5862
+ let timeoutPublication;
5863
+ if (procResult.classification === "timeout" && isCoveredJobType(job.job_type)) {
5864
+ const ownershipHeld = () => !ownership.abandoned && heartbeatOutcome?.kind !== "server_stop";
5865
+ const baseline = prep.publicationBaseline ??
5866
+ (prep.publicationRemoteAbsent === true ? (prep.comparisonSha ?? prep.expectedHeadSha) : undefined);
5867
+ // One fixed deadline: a fresh allowance must not be re-derived on each read.
5868
+ const publicationDeadlineAtMs = Math.min(deps.now() + FINALIZATION_RESERVE_MS, plan.deadlineAtMs - REPORT_RESERVE_MS);
5869
+ const publicationRemainingMs = () => Math.max(0, publicationDeadlineAtMs - deps.now());
5870
+ if (!ownershipHeld())
5871
+ timeoutPublication = "ownership_abandoned";
5872
+ else if (cleanup.verdict !== "confirmed" || cleanup.survivors !== 0)
5873
+ timeoutPublication = "cleanup_not_confirmed";
5874
+ else if (finalHeadSha === null || finalHeadSha === baseline)
5875
+ timeoutPublication = "nothing_to_publish";
5876
+ else if (publicationRemainingMs() <= 0)
5877
+ timeoutPublication = "no_time_left";
5878
+ else {
5879
+ // The publisher supervises its own phase; the expired worker signal is never passed.
5880
+ const outcome = await retainedHeadPublisher({
5881
+ job, branch, worktreePath, prep, deps, ownership, observation, httpClient, options: jobOptions, control,
5882
+ remainingMs: publicationRemainingMs, candidateSha: finalHeadSha, allowCreateOnly: true,
5883
+ })();
5884
+ if (outcome.status === "refused") {
5885
+ timeoutPublication = outcome.reason !== "timeout" && publicationRemainingMs() <= 0 ? "no_time_left" : outcome.reason;
5886
+ }
5887
+ }
5888
+ // Supervision may have found a server stop or abandoned ownership meanwhile.
5889
+ const stronger = await strongerOutcome(timeoutPublication === "ownership_abandoned" ? { timeout_publication: "ownership_abandoned" } : undefined);
5890
+ if (stronger)
5891
+ return stronger;
5892
+ }
5463
5893
  const authDetection = adapter.authFailureDetection;
5464
5894
  const authFailure = authDetection?.supported === true && authDetection.value.classify(procResult.stdoutExcerpt).notAuthenticated;
5465
5895
  const capacityEvidence = authFailure
@@ -5478,6 +5908,7 @@ async function runCoveredAttempt(params) {
5478
5908
  : `worker exited (${procResult.classification}, exit_code=${procResult.exitCode})`,
5479
5909
  classification: toWireClassification(procResult.classification),
5480
5910
  ...observedExitCode(procResult.exitCode),
5911
+ ...(timeoutPublication !== undefined ? { telemetry: { timeout_publication: timeoutPublication } } : {}),
5481
5912
  }, envelope, capacityEvidence !== undefined ? { capacity_evidence: capacityEvidence } : {}));
5482
5913
  }
5483
5914
  // --- Phase 3: independent declared checks (BAPI-1302, D4c) ---------------------
@@ -5607,6 +6038,12 @@ async function runCoveredAttempt(params) {
5607
6038
  ? { ...ciResult.fields, ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status }
5608
6039
  : { ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status };
5609
6040
  }
6041
+ // BAPI-1582: the same optional test-run telemetry as the legacy completion path.
6042
+ const ciFixTestRuns = prep.ciFix
6043
+ ? await readForwardableCiFixTestRuns({ job, ciFix: prep.ciFix, worktreePath, deps, seams })
6044
+ : undefined;
6045
+ genericResult = withCiFixTestRuns(genericResult, ciFixTestRuns, RESULT_JSONB_MAX_BYTES);
6046
+ failTestRuns = ciFixTestRuns;
5610
6047
  // BAPI-1426: the server-confirmed delivery outcome, read under the same
5611
6048
  // absolute deadline as the finalization reads below.
5612
6049
  // BAPI-1563: read once, inside finalization, after the final head and the PR are
@@ -5683,8 +6120,20 @@ async function runCoveredAttempt(params) {
5683
6120
  const evidenceOutcome = finalization.ok ? finalization.deliveryOutcome?.evidenceOutcome : undefined;
5684
6121
  const publicationDependsOnCarry = evidenceOutcome !== undefined && evidenceOutcome !== "awaiting_post_pr" && evidenceOutcome !== "complete";
5685
6122
  const verificationShortfallOnly = serverPermitsPublication && publicationDependsOnCarry && envelope.cause === "required_check_failed" && unresolvedRequiredTasks(envelope).length === 0;
5686
- if (finalization.ok && (successRefusalReason(envelope) === null || verificationShortfallOnly)) {
5687
- const result = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
6123
+ // BAPI-1590: a shortfall at a pull request the executor verified at the pushed
6124
+ // head is reported as `/complete` first and the SERVER decides; its own read of
6125
+ // the open PR is authoritative, this observation is only publication evidence.
6126
+ // Implementation-style jobs qualify only through the confirmed delivery hold that
6127
+ // finalization let through (`heldAtOpenPr`), never a bare PR number; a `ci_fix`
6128
+ // qualifies through its finalization PR number plus the server-held branch.
6129
+ // Only the two causes the server may lift qualify, and any unfinished required
6130
+ // work still fails.
6131
+ const prBackedShortfallOnly = isPrBackedShortfall(finalization, job, envelope);
6132
+ const shortfallGated = verificationShortfallOnly || prBackedShortfallOnly;
6133
+ if (finalization.ok && (successRefusalReason(envelope) === null || shortfallGated)) {
6134
+ const verifiedResult = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
6135
+ // BAPI-1582: bounded pre-PR telemetry, as on the legacy completion path.
6136
+ const result = await attachPrePrChecksTelemetry(job, verifiedResult, worktreePath, git.last_commit_sha, deps);
5688
6137
  const completion = {
5689
6138
  job_type: job.job_type,
5690
6139
  exit_code: procResult.exitCode ?? 0,
@@ -5703,9 +6152,16 @@ async function runCoveredAttempt(params) {
5703
6152
  options,
5704
6153
  ownership: reportOwnership,
5705
6154
  log: deps.log,
6155
+ // BAPI-1590: only a shortfall-gated completion falls back to `/fail`.
6156
+ completionEvidenceFallback: shortfallGated && successRefusalReason(envelope) !== null,
5706
6157
  }, job, control);
5707
- await finalizeRegistry();
5708
- return finish(terminalToRunResult(terminal, "completed"));
6158
+ // BAPI-1590: on a marked refusal the server left the job running, so fall
6159
+ // through and report the SAME envelope once as `/fail` below — no second
6160
+ // finalization, evidence regeneration, worker launch, lease wait, or abandon.
6161
+ if (terminal.outcome !== "completion_evidence_refused") {
6162
+ await finalizeRegistry();
6163
+ return finish(terminalToRunResult(terminal, "completed"));
6164
+ }
5709
6165
  }
5710
6166
  // Not a success. A completion cause (required work, cleanup, verification,
5711
6167
  // permission) outranks the finalization kind; with none, finalization keeps
@@ -5747,3 +6203,43 @@ async function runCoveredAttempt(params) {
5747
6203
  ...observedExit,
5748
6204
  }, envelope));
5749
6205
  }
6206
+ /**
6207
+ * BAPI-1590 — whether a covered attempt's verification shortfall is reported as
6208
+ * `/complete` first because finalization verified a pull request at the pushed head.
6209
+ *
6210
+ * Implementation-style jobs qualify only through the confirmed delivery hold that
6211
+ * finalization let through (`heldAtOpenPr`), never a bare PR number. A `ci_fix` reads
6212
+ * no delivery outcome, so it qualifies through finalization's PR number plus the
6213
+ * server-held branch. Only the two causes the server may lift qualify
6214
+ * (`CARRY_LIFTABLE_CAUSES` in `executor_completion_contract.py`), and unfinished
6215
+ * required work never does. This is only the executor's decision to ASK: the server's
6216
+ * own provider read decides whether the success stands.
6217
+ */
6218
+ export function isPrBackedShortfall(finalization, job, envelope) {
6219
+ if (!finalization.ok)
6220
+ return false;
6221
+ const atPushedHead = finalization.heldAtOpenPr !== undefined ||
6222
+ (job.job_type === "ci_fix" &&
6223
+ typeof finalization.prNumber === "number" &&
6224
+ typeof job.expected_branch === "string" &&
6225
+ job.expected_branch.trim() !== "");
6226
+ return (atPushedHead &&
6227
+ (envelope.cause === "required_check_failed" || envelope.cause === "verification_runner_unavailable") &&
6228
+ unresolvedRequiredTasks(envelope).length === 0);
6229
+ }
6230
+ /**
6231
+ * BAPI-1582 — attach an implement worker's `pre_pr_checks_summary` when its
6232
+ * `.conductor/pre-pr-checks.json` is valid and names the final head. Telemetry
6233
+ * only: any other job type, or any read problem, returns `result` unchanged.
6234
+ */
6235
+ async function attachPrePrChecksTelemetry(job, result, worktreePath, headSha, deps) {
6236
+ if (job.job_type !== "implement")
6237
+ return result;
6238
+ return withPrePrChecksSummary(result, {
6239
+ worktreePath,
6240
+ observedHead: typeof headSha === "string" ? headSha : null,
6241
+ maxResultBytes: RESULT_JSONB_MAX_BYTES,
6242
+ deps: { readFile: deps.readFile, lstatPath: deps.lstatPath },
6243
+ errorLog: (message) => deps.errorLog(`[executor] job ${job.id}: ${message}`),
6244
+ });
6245
+ }