@bridge_gpt/mcp-server 0.2.69 → 0.2.71

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 (164) hide show
  1. package/README.md +140 -292
  2. package/build/agent-launchers/claude-executor-adapter.js +27 -5
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +15 -5
  5. package/build/artifact-diff.js +110 -0
  6. package/build/bin-entrypoint.js +36 -0
  7. package/build/bounded-wait.js +9 -1
  8. package/build/bridge-permissions.js +36 -9
  9. package/build/claude-review-workflow-drift.js +3 -3
  10. package/build/codex-bridge-profile.js +1 -1
  11. package/build/commands.generated.js +6 -6
  12. package/build/conductor/bridge-api-client.js +858 -21
  13. package/build/conductor/bring-up-facts.js +9 -9
  14. package/build/conductor/command-drift-production.js +7 -2
  15. package/build/conductor/doctor.js +472 -18
  16. package/build/conductor/epic-child-continuation.js +54 -3
  17. package/build/conductor/epic-implementer-cli.js +136 -34
  18. package/build/conductor/epic-runtime.js +2 -2
  19. package/build/conductor/epic-state.js +1 -1
  20. package/build/conductor/gate-discovery.js +524 -10
  21. package/build/conductor/gate-settings-review.js +451 -0
  22. package/build/conductor/hook-runtime-qualification.js +1 -1
  23. package/build/conductor/install-doctor.js +4 -2
  24. package/build/conductor/launch-need-probes.js +342 -0
  25. package/build/conductor/launch-plan.js +145 -0
  26. package/build/conductor/local-merge.js +241 -56
  27. package/build/conductor/merge-credential.js +172 -0
  28. package/build/conductor/merge-execution-eligibility.js +1 -1
  29. package/build/conductor/merged-child-check.js +95 -0
  30. package/build/conductor/plan-trim.js +30 -0
  31. package/build/conductor/pr-ci-producer.js +1 -1
  32. package/build/conductor/precheck-timings.js +14 -0
  33. package/build/conductor/preview-observations.js +10 -0
  34. package/build/conductor/readiness-cli.js +11 -6
  35. package/build/conductor/readiness-prerequisites.js +41 -0
  36. package/build/conductor/readiness-sections.js +348 -55
  37. package/build/conductor/readiness.js +99 -87
  38. package/build/conductor/recovery-cli.js +665 -23
  39. package/build/conductor/recovery-operations.js +350 -8
  40. package/build/conductor/repair-contract.js +47 -2
  41. package/build/conductor/repository-workflow-remedy.js +8 -6
  42. package/build/conductor/stored-merge-credential.js +76 -0
  43. package/build/conductor/stored-merge-token-probe.js +28 -0
  44. package/build/conductor/temporary-plan.js +50 -0
  45. package/build/conductor/wait-run-cli.js +759 -0
  46. package/build/conductor/worker-database-doctor-inspector.js +49 -0
  47. package/build/conductor-bin.js +2 -2
  48. package/build/conductor-claude-hook-bin.js +2 -2
  49. package/build/conductor-claude-hook-removed-stub-bin.js +2 -5
  50. package/build/conductor-removed-stub-bin.js +2 -5
  51. package/build/credential-store.js +356 -13
  52. package/build/docs.generated.js +26 -13
  53. package/build/doctor.js +94 -32
  54. package/build/drive-epic-help.js +212 -0
  55. package/build/drive-epic.js +1989 -379
  56. package/build/epic-ci-workflow-drift.js +125 -0
  57. package/build/epic-ci-workflow-install.js +240 -0
  58. package/build/epic-ci-workflow-v1.js +132 -0
  59. package/build/epic-ci-workflow.js +318 -0
  60. package/build/epic-contract-context.js +326 -0
  61. package/build/epic-implementer-bin.js +58 -42
  62. package/build/epic-implementer-claude-hook-bin.js +2 -2
  63. package/build/escalation-reachability.js +134 -0
  64. package/build/executor/ci-rerun-job.js +220 -14
  65. package/build/executor/cleanup-report.js +99 -0
  66. package/build/executor/cli.js +12 -1
  67. package/build/executor/completion-contract.js +66 -11
  68. package/build/executor/completion-supervision.js +99 -0
  69. package/build/executor/delivery-outcome.js +179 -0
  70. package/build/executor/deps.js +3 -0
  71. package/build/executor/env.js +276 -1
  72. package/build/executor/failure-reason-codes.js +126 -0
  73. package/build/executor/gate-qualification-job.js +20 -5
  74. package/build/executor/heartbeat.js +38 -0
  75. package/build/executor/http-client.js +72 -0
  76. package/build/executor/integration-job.js +298 -5
  77. package/build/executor/job-errors.js +36 -6
  78. package/build/executor/job-runner.js +830 -45
  79. package/build/executor/likely-tests.js +42 -3
  80. package/build/executor/merge-job.js +145 -2
  81. package/build/executor/observation.js +73 -4
  82. package/build/executor/permissions.js +193 -97
  83. package/build/executor/preflight.js +19 -3
  84. package/build/executor/process-containment.js +46 -2
  85. package/build/executor/prompt-spec.js +113 -9
  86. package/build/executor/rebase-finalization.js +38 -3
  87. package/build/executor/reconcile-overlap-job.js +41 -8
  88. package/build/executor/required-work-ledger.js +236 -81
  89. package/build/executor/resume-pre-spawn.js +38 -1
  90. package/build/executor/runner.js +91 -3
  91. package/build/executor/test-clock.js +8 -0
  92. package/build/executor/types.js +37 -2
  93. package/build/executor/worker-cli-launcher.js +259 -0
  94. package/build/executor/worker-command.js +177 -5
  95. package/build/executor/worker-database-target.js +91 -0
  96. package/build/executor/worker-database.js +927 -0
  97. package/build/executor/worker-finalization.js +106 -0
  98. package/build/executor/worker-guard-hook.js +203 -0
  99. package/build/executor/worker-resources.js +58 -0
  100. package/build/executor/worker-verification-guidance.js +44 -2
  101. package/build/executor/worktree.js +303 -15
  102. package/build/executor-launch.js +11 -1
  103. package/build/generated-assets-doctor.js +9 -1
  104. package/build/generated-assets-health.js +13 -4
  105. package/build/generated-assets-legacy.js +39 -0
  106. package/build/generated-assets-paths.js +12 -1
  107. package/build/generated-assets-repair.js +4 -1
  108. package/build/generated-assets-test-support.js +12 -0
  109. package/build/github-remote.js +33 -0
  110. package/build/github-sign-in.js +62 -0
  111. package/build/index.js +1133 -546
  112. package/build/init.js +39 -1
  113. package/build/install-bridge-conductor-gate.js +270 -11
  114. package/build/install-bridge-conductor-setup.js +427 -0
  115. package/build/install-bridge-conductor.js +1545 -268
  116. package/build/install-bridge.js +376 -60
  117. package/build/mcp-install-state.js +8 -2
  118. package/build/merge-pull-request.js +6 -0
  119. package/build/merge-workflow-install.js +782 -344
  120. package/build/phase-result-artifacts.js +75 -20
  121. package/build/pipeline-orchestrator.js +247 -4
  122. package/build/pipelines.generated.js +35 -35
  123. package/build/plan-discovery.js +15 -2
  124. package/build/plan-execution-ledger.js +321 -17
  125. package/build/plan-phase-routing.js +48 -13
  126. package/build/plane/cli.js +105 -51
  127. package/build/plane/defaults.js +3 -0
  128. package/build/plane/plane-freshness.js +298 -0
  129. package/build/plane/preflight.js +19 -0
  130. package/build/plane/schema-compatibility.js +137 -0
  131. package/build/plane/shutdown-deps.js +38 -0
  132. package/build/plane/shutdown.js +83 -8
  133. package/build/plane/terminal-run-cleanup.js +303 -0
  134. package/build/printed-remedy-commands.js +33 -4
  135. package/build/readiness-check.js +6 -2
  136. package/build/readiness-prerequisites.generated.js +532 -0
  137. package/build/readme.generated.js +1 -1
  138. package/build/repository-toolchains.js +581 -0
  139. package/build/setup-epic.js +421 -34
  140. package/build/shared-resources.generated.js +5 -0
  141. package/build/start-tickets.js +28 -15
  142. package/build/test-command-detection.js +284 -0
  143. package/build/test-command-validation.js +73 -0
  144. package/build/testing-config-client.js +150 -0
  145. package/build/ticket-delivery-artifacts.js +265 -0
  146. package/build/ticket-delivery-enrollment.js +369 -0
  147. package/build/ticket-delivery.js +205 -0
  148. package/build/ticket-review-summary.js +14 -0
  149. package/build/upgrade-cli.js +13 -0
  150. package/build/v2-readiness-requirements.js +552 -0
  151. package/build/version.generated.js +3 -3
  152. package/build/worker-guard-hook-bin.js +2 -2
  153. package/build/worktree-core.js +22 -7
  154. package/docs/BRIDGE-DIRECTORY-README.md +48 -0
  155. package/docs/EPIC-IMPLEMENTER-INSTALL.md +12 -867
  156. package/docs/EPIC-IMPLEMENTER.md +142 -63
  157. package/docs/epic-implementer/getting-started.md +187 -0
  158. package/docs/epic-implementer/self-hosting.md +133 -0
  159. package/package.json +4 -4
  160. package/pipelines/idea-to-ticket.json +1 -1
  161. package/pipelines/implement-ticket.json +8 -8
  162. package/pipelines/review-ticket.json +2 -2
  163. package/design-assets/favicon/favicon-32x32.png +0 -0
  164. package/design-assets/just-logo-rough-draft.png +0 -0
@@ -4,7 +4,7 @@ import { createHash, randomUUID } from "node:crypto";
4
4
  import path from "node:path";
5
5
  import { findWorktreeByBranch, parseGitWorktreePorcelain } from "./worktree-inspection.js";
6
6
  import { resolveExecutorBranch, configureExecutorBranch } from "./worktree.js";
7
- import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance } from "./worker-verification-guidance.js";
7
+ import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance, renderWorkerTimeBudgetGuidance } from "./worker-verification-guidance.js";
8
8
  /**
9
9
  * Claimed-job execution engine (BAPI-534 core, BAPI-535 job behaviors; TDD §7/§8/§9).
10
10
  *
@@ -21,11 +21,14 @@ import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance } from "./
21
21
  * `spec_review`, plus per-job worker-log tee, watch registry, and optional
22
22
  * read-only viewer tabs wired around every spawned worker.
23
23
  */
24
- import { rm, readdir, lstat, unlink, realpath } from "node:fs/promises";
24
+ import { rm, readdir, lstat, unlink, realpath, rename as fsRename, stat as fsStat } from "node:fs/promises";
25
+ import { accessSync, constants as fsConstants, realpathSync, statSync } from "node:fs";
26
+ import { provisionWorktreeSettingsExclude } from "./permissions.js";
25
27
  import os from "node:os";
26
- import { runHeartbeatLoop } from "./heartbeat.js";
27
- import { isExecutorNamedError, toExecutorFailure, RebaseNotVerified, secretFreeErrorMessage, MissingVerdictArtifact, PackagedRecipeUndeliverable, PreSpawnVerification, RequiredMcpRegistration, McpSurfaceMismatch, WorkerStartupFatal, WORKER_STARTUP_FATAL_MESSAGE, WorkerEndedWithPendingBackgroundWork, WORKER_ENDED_WITH_PENDING_BACKGROUND_WORK_MESSAGE, formatMcpSurfaceMismatch, ClaudeNotAuthenticated, CLAUDE_NOT_AUTHENTICATED_MESSAGE, ExecutorAdapterUnavailable, ExecutorNamedError, WorktreeBusy, StaleArtifactCleanupFailed, CiFixContext, WORKTREE_BUSY_MESSAGE, WorkerEnvFilePresent, WORKER_ENV_FILE_PRESENT_MESSAGE, } from "./job-errors.js";
28
- import { buildConductorMergeAccessForExecutorJob, buildDefaultMergeLocalDeps, runExecutorMergeJob, MERGE_RETRYABLE, MERGE_FAILED, } from "./merge-job.js";
28
+ import { runHeartbeatLoop, sendImmediateHeartbeat } from "./heartbeat.js";
29
+ import { cleanupReportPermitsRecordRemoval, retryWakeCleanupReport, submitCleanupReport, } from "./cleanup-report.js";
30
+ import { isExecutorNamedError, toExecutorFailure, RebaseNotVerified, secretFreeErrorMessage, secretFreeWorktreeMessage, WorktreeSetupRefused, MissingVerdictArtifact, PackagedRecipeUndeliverable, PreSpawnVerification, RequiredMcpRegistration, McpSurfaceMismatch, WorkerStartupFatal, WORKER_STARTUP_FATAL_MESSAGE, WorkerEndedWithPendingBackgroundWork, WORKER_ENDED_WITH_PENDING_BACKGROUND_WORK_MESSAGE, formatMcpSurfaceMismatch, ClaudeNotAuthenticated, CLAUDE_NOT_AUTHENTICATED_MESSAGE, ExecutorAdapterUnavailable, ExecutorNamedError, WorktreeBusy, StaleArtifactCleanupFailed, CiFixContext, WORKTREE_BUSY_MESSAGE, WorkerEnvFilePresent, WORKER_ENV_FILE_PRESENT_MESSAGE, } from "./job-errors.js";
31
+ import { buildConductorMergeAccessForExecutorJob, buildMergeLocalDepsForJob, runExecutorMergeJob, MERGE_RETRYABLE, MERGE_FAILED, MERGE_ACCESS_UNAVAILABLE, MERGE_FLOW_ERROR, MERGE_FLOW_TIMEOUT, MERGE_NO_OUTCOME, } from "./merge-job.js";
29
32
  import { createProductionCiRerunDeps, runCiRerunJob, } from "./ci-rerun-job.js";
30
33
  import { createProductionGateQualificationDeps, runGateQualificationJob, GATE_QUALIFICATION_FAILED, GATE_QUALIFICATION_INTERRUPTED, } from "./gate-qualification-job.js";
31
34
  import { createObservationState } from "./observation.js";
@@ -34,11 +37,11 @@ import { resolveExecutorAgentAdapter } from "../agent-launchers/executor-adapter
34
37
  import { redactAdapterDiagnostic } from "../agent-launchers/executor-adapter.js";
35
38
  import { resolveExecutorAgentId } from "./agent-identity.js";
36
39
  import { closeStdinBounded, createProcessTerminationController, runProcessWithTimeout, writeStdinBounded, } from "./process.js";
37
- import { buildNotLaunchedEnvelope, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, verificationVerdictFromFacts, } from "./completion-contract.js";
38
- import { COMPLETION_CAUSE_ERROR_KINDS, EOF_DRAIN_BOUND_MS, STDIN_CLOSE_GRACE_MS, finalizationFacts, finalizationObligations, planCompletionAllowance, readCompletionBinding, readDeclaredChecks, readOptionalWatchers, readRequiredVerification, } from "./completion-supervision.js";
40
+ import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, 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";
39
42
  import { compareFinalArtifact, createRequiredVerificationRunner, createSupervisedCommandLauncher, observeFinalArtifact, OWNERSHIP_POLL_MS, preCheckArtifactState, toCompletionCheckFact, } from "./required-verification.js";
40
43
  import { createClosureSupervisor, createRequiredWorkLedger } from "./required-work-ledger.js";
41
- import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
44
+ import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withExecutorJobId, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
42
45
  import { resolveCompletionEvidenceCapability } from "../agent-launchers/executor-adapter.js";
43
46
  import { autoCheckpointDirtyState, PRIOR_ATTEMPT_WIP_COMMIT_MESSAGE, prepareResumeSpawn, prepareRetainedContinuationWorktree, readContinuationBinding, verifyContinuationHeadLineage, } from "./resume-pre-spawn.js";
44
47
  import { buildEpicWorkaroundWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
@@ -51,6 +54,9 @@ import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArt
51
54
  import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
52
55
  import { removeStaleVerdictArtifacts } from "./stale-artifacts.js";
53
56
  import { stripWorkerEnvFiles } from "./env-file-guard.js";
57
+ import { payloadWorkerEnvOption } from "./env.js";
58
+ import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine, } from "./worker-database.js";
59
+ import { formatWorkerCliLauncherUnavailableLine } from "./worker-cli-launcher.js";
54
60
  import { isVerdictJobType, readVerdictArtifact } from "./verdict-artifact.js";
55
61
  import { createWorkerLogClaimId, createWorkerLogTee, closeWorkerLogTee, distinctWorkerLogSessionIds, formatWorkerLogSessionInvariantWarning, teeAsyncIterable, } from "./worker-log.js";
56
62
  import { acquireExecutorWorktreeLock, } from "./worktree-lock.js";
@@ -61,12 +67,14 @@ import { cleanupInterruptedWorktree } from "./interrupted-worktree.js";
61
67
  import { lazyProviderCheckPoller, runReconcileOverlapJob, } from "./reconcile-overlap-job.js";
62
68
  import { resolveExecutorJobBaseBranch } from "./base-branch.js";
63
69
  import { resolveExecutorJobIndexScope } from "./index-scope.js";
64
- import { readFocusedPullRequest, validateWorkerFinalization } from "./worker-finalization.js";
70
+ import { deliveryHoldOf, readFocusedPullRequest, resolveOriginBranchSha, validateWorkerFinalization, } from "./worker-finalization.js";
71
+ import { DELIVERY_OUTCOME_READ_TIMEOUT_MS, fetchServerDeliveryOutcome, } from "./delivery-outcome.js";
65
72
  import { FOCUSED_REBASE_JOB_TYPE, focusedRebaseContextError, hasFocusedRebaseContext, validateFocusedRebaseContext, waitForFocusedRebase, } from "./rebase-finalization.js";
66
73
  import { ensureExecutorWorktree, finalizeRetainedExecutorWorktree, } from "./worktree.js";
67
- import { CI_FIX_JOB_TYPE, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
74
+ import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
68
75
  import { CORRECTION_INTENT_CAPABILITY, isRemainingWork, validateCorrectionIntent, } from "./correction-dispatch.js";
69
76
  import { collectGitTelemetry, collectRemoteTrackingSha, createMcpSurfaceObserver, evaluatePreSpawnGitVerification, formatWorkerRateLimitAdvisory, normalizeMcpServerNames, } from "./observation.js";
77
+ import { failureReasonCode, isFailureReasonCode } from "./failure-reason-codes.js";
70
78
  import { readCustomizedCommands, TERMINAL_CAPACITY_PROTOCOL_VERSIONS, TERMINAL_CAPACITY_RUNTIME_CONTRACTS, TERMINAL_CAPACITY_RUNTIMES, } from "./types.js";
71
79
  import { resolvePackagedRecipes } from "./packaged-recipe.js";
72
80
  import { probeInstalledCorrectionHook } from "./preflight.js";
@@ -90,6 +98,71 @@ const ENV_FILE_TRACKED_LOOKUP_TIMEOUT_MS = 5_000;
90
98
  const ENV_FILE_TRACKED_LOOKUP_FAILED_MESSAGE = "[executor] tracked env-file lookup unavailable; exempting nothing";
91
99
  /** Default runtime for the no-op smoke process (ms). */
92
100
  const DEFAULT_SMOKE_DURATION_MS = 100;
101
+ /**
102
+ * BAPI-1426: implementation-style job types that never read a delivery outcome.
103
+ * `reconcile_overlap`'s push is the wrapper's own, not a ticket delivery attempt.
104
+ * BAPI-1516: `ci_fix` is excluded too. A repair is judged by its own completion
105
+ * contract (a provider-observed push plus dispatched-check claims), not by ticket
106
+ * delivery readiness. An older server still guards `ci_fix`; the executor then
107
+ * reports success and that server's refusal parks the ticket as before, which the
108
+ * reconciler's green-head lane recovers once the PR head is green.
109
+ */
110
+ const DELIVERY_OUTCOME_EXCLUDED_JOB_TYPES = new Set([
111
+ "reconcile_overlap",
112
+ "ci_fix",
113
+ ]);
114
+ /** BAPI-1426: the outcome used when the read could not run or failed. */
115
+ const DELIVERY_OUTCOME_UNAVAILABLE = { bound: "unknown", unavailable: true };
116
+ /**
117
+ * BAPI-1426: read the server-confirmed delivery outcome for a finalizing
118
+ * implementation-style job. Returns undefined (no read at all) for a job with no
119
+ * ticket or branch, and for the excluded job types above. Bounded by
120
+ * `remainingMs`; never throws.
121
+ */
122
+ async function readDeliveryOutcomeForFinalization(params) {
123
+ const { job, branch, deps, seams } = params;
124
+ const env = params.resolvedBaseUrl !== undefined && params.resolvedBaseUrl.trim() !== ""
125
+ ? { ...deps.env, BAPI_BASE_URL: params.resolvedBaseUrl }
126
+ : deps.env;
127
+ if (!isImplementationStyleJobType(job.job_type) || DELIVERY_OUTCOME_EXCLUDED_JOB_TYPES.has(job.job_type)) {
128
+ return undefined;
129
+ }
130
+ const trimmedBranch = typeof branch === "string" ? branch.trim() : "";
131
+ if (!trimmedBranch || !job.ticket_key)
132
+ return undefined;
133
+ const budgetMs = Math.min(DELIVERY_OUTCOME_READ_TIMEOUT_MS, params.remainingMs());
134
+ if (budgetMs <= 0)
135
+ return DELIVERY_OUTCOME_UNAVAILABLE;
136
+ try {
137
+ if (seams.fetchDeliveryOutcome)
138
+ return await seams.fetchDeliveryOutcome(job, trimmedBranch);
139
+ return await fetchServerDeliveryOutcome(job, trimmedBranch, {
140
+ fetch: deps.fetch,
141
+ accessDeps: {
142
+ env,
143
+ cwd: deps.cwd,
144
+ homedir: deps.homedir,
145
+ platform: deps.platform,
146
+ readFile: deps.readFile,
147
+ stat: deps.stat,
148
+ },
149
+ timeoutMs: budgetMs,
150
+ setTimer: deps.setTimer,
151
+ clearTimer: deps.clearTimer,
152
+ });
153
+ }
154
+ catch {
155
+ return DELIVERY_OUTCOME_UNAVAILABLE;
156
+ }
157
+ }
158
+ /**
159
+ * BAPI-1426: a finalization failure may carry its own telemetry (the delivery
160
+ * hold marker). It is merged over the observation snapshot instead of being
161
+ * replaced by it; a failure without telemetry keeps the snapshot unchanged.
162
+ */
163
+ function withFailureTelemetry(snapshot, failureTelemetry) {
164
+ return failureTelemetry ? { ...snapshot, ...failureTelemetry } : snapshot;
165
+ }
93
166
  /** ProcessClassification maps 1:1 onto the wire ExecutorClassification. */
94
167
  function toWireClassification(c) {
95
168
  return c;
@@ -507,6 +580,7 @@ export async function defaultRunMergeForClaimed(job, deps, options, controls) {
507
580
  error_kind: MERGE_RETRYABLE,
508
581
  error_message: accessResult.error,
509
582
  classification: "crashed",
583
+ telemetry: { failure_reason_code: MERGE_ACCESS_UNAVAILABLE },
510
584
  },
511
585
  };
512
586
  }
@@ -514,12 +588,19 @@ export async function defaultRunMergeForClaimed(job, deps, options, controls) {
514
588
  access: accessResult.access,
515
589
  // Thread the overall-timeout abort signal into local merge deps WITHOUT
516
590
  // changing the local `gh` credential model (the signal is not a credential).
517
- localMergeDeps: buildDefaultMergeLocalDeps(deps, controls?.signal),
591
+ // BAPI-1453: the same signal bounds the post-`gh_pr_view_failed` permission
592
+ // probe, so it can never outlive the merge flow's own timeout.
593
+ // BAPI-1461: resolved when the job runs, with the stored-entry fallback for
594
+ // an executor started in the person's own session. A durable-host service
595
+ // executor declared itself with --scrub-inherited-github-credentials and
596
+ // never reads a stored GitHub credential.
597
+ localMergeDeps: await buildMergeLocalDepsForJob(job, deps, { allowStoredEntry: options.scrubInheritedGithubCredentials !== true }, controls?.signal),
518
598
  // BAPI-951: the executor's own configured base — resolveExecutorJobBaseBranch
519
599
  // (called inside runExecutorMergeJob) resolves the CHILD PR's base from the
520
600
  // job's persisted run base, falling back to this value for a legacy job.
521
601
  repositoryBaseBranch: options.baseBranch,
522
602
  epicIntegrationAdvisoryLog: deps.errorLog,
603
+ diagnosticLog: deps.errorLog,
523
604
  cwd: deps.cwd,
524
605
  });
525
606
  }
@@ -1205,7 +1286,7 @@ async function runMergeJob(job, httpClient, options, deps, ownership, observatio
1205
1286
  error_kind: MERGE_RETRYABLE,
1206
1287
  error_message: `merge flow timed out after ${timeoutSeconds} seconds`,
1207
1288
  classification: "timeout",
1208
- telemetry: observation.snapshot(),
1289
+ telemetry: { failure_reason_code: MERGE_FLOW_TIMEOUT, ...observation.snapshot() },
1209
1290
  }),
1210
1291
  deps,
1211
1292
  options,
@@ -1223,7 +1304,7 @@ async function runMergeJob(job, httpClient, options, deps, ownership, observatio
1223
1304
  error_kind: MERGE_FAILED,
1224
1305
  error_message: secretFreeErrorMessage(flowError),
1225
1306
  classification: "crashed",
1226
- telemetry: observation.snapshot(),
1307
+ telemetry: { failure_reason_code: MERGE_FLOW_ERROR, ...observation.snapshot() },
1227
1308
  }),
1228
1309
  deps,
1229
1310
  options,
@@ -1242,7 +1323,7 @@ async function runMergeJob(job, httpClient, options, deps, ownership, observatio
1242
1323
  error_kind: MERGE_FAILED,
1243
1324
  error_message: "merge flow completed without an outcome",
1244
1325
  classification: "crashed",
1245
- telemetry: observation.snapshot(),
1326
+ telemetry: { failure_reason_code: MERGE_NO_OUTCOME, ...observation.snapshot() },
1246
1327
  }),
1247
1328
  deps,
1248
1329
  options,
@@ -1271,7 +1352,13 @@ async function runMergeJob(job, httpClient, options, deps, ownership, observatio
1271
1352
  }
1272
1353
  const terminal = await sendTerminalMutationWithAuthReport({
1273
1354
  kind: "fail",
1274
- send: () => httpClient.fail(job, { ...outcome.failure, telemetry: observation.snapshot() }),
1355
+ // BAPI-1453: MERGE the builder's telemetry with the snapshot rather than
1356
+ // replacing it, so `failure_reason_code` survives. Observation state never
1357
+ // carries a code, so the snapshot cannot overwrite it.
1358
+ send: () => httpClient.fail(job, {
1359
+ ...outcome.failure,
1360
+ telemetry: { ...outcome.failure.telemetry, ...observation.snapshot() },
1361
+ }),
1275
1362
  deps,
1276
1363
  options,
1277
1364
  ownership,
@@ -1519,13 +1606,68 @@ function resolveStaleBranchClassification(payload) {
1519
1606
  return "unknown";
1520
1607
  return raw.trim() === PR_NOT_ATTACHED_REASON_CODE ? "succeeded_pr_not_attached" : "unknown";
1521
1608
  }
1522
- /** The `/fail` payload for a failed worktree preparation. */
1609
+ /**
1610
+ * BAPI-1530: structured worktree outcomes the executor reports as the named,
1611
+ * deterministic `WorktreeSetupRefused`. A fetch, ref-resolution, or unclassified
1612
+ * failure (`unavailable` or no kind at all) keeps `WorktreeError` so the server's
1613
+ * legacy crash and transient handling is unchanged.
1614
+ */
1615
+ const SETUP_REFUSAL_KINDS = new Set([
1616
+ "stale_branch",
1617
+ "lineage_refused",
1618
+ "setup_refused",
1619
+ ]);
1620
+ /**
1621
+ * Display-only reason codes. They are set from structured outcomes only and read
1622
+ * by no disposition decision; a deliberate refusal with no accurate display
1623
+ * category (lock, authority, occupied destination) carries none.
1624
+ */
1625
+ function worktreeDisplayReasonCode(kind) {
1626
+ switch (kind) {
1627
+ case "stale_branch":
1628
+ return failureReasonCode("worktree_stale_branch");
1629
+ case "lineage_refused":
1630
+ return failureReasonCode("worktree_lineage_refused");
1631
+ case "unavailable":
1632
+ return failureReasonCode("worktree_fetch_failed");
1633
+ default:
1634
+ return undefined;
1635
+ }
1636
+ }
1637
+ /**
1638
+ * The `/fail` payload for a failed worktree preparation. The message is redacted
1639
+ * and bounded here, before it reaches the server or a log line, so raw Worktrunk
1640
+ * stderr never crosses the boundary. A named failure that already carries its own
1641
+ * secret-free message is returned as it is.
1642
+ */
1523
1643
  function jobWorktreeFailure(wt) {
1524
- return (wt.failure ?? {
1525
- error_kind: "WorktreeError",
1526
- error_message: wt.error,
1644
+ if (wt.failure)
1645
+ return wt.failure;
1646
+ const refused = wt.failureKind !== undefined && SETUP_REFUSAL_KINDS.has(wt.failureKind);
1647
+ const displayCode = worktreeDisplayReasonCode(wt.failureKind);
1648
+ return {
1649
+ error_kind: refused ? WorktreeSetupRefused : "WorktreeError",
1650
+ error_message: secretFreeWorktreeMessage(wt.error),
1527
1651
  classification: "crashed",
1528
- });
1652
+ ...(displayCode ? { telemetry: { failure_reason_code: displayCode } } : {}),
1653
+ };
1654
+ }
1655
+ /** The payload key the reconciler stamps with a fenced child's resume head (BAPI-1530). */
1656
+ const FENCED_RESUME_HEAD_KEY = "fenced_implement_resume_head_sha";
1657
+ /**
1658
+ * BAPI-1530: the SERVER-AUTHORED resume head from the job payload, or `null`.
1659
+ * Absent, malformed, or non-SHA values degrade to the ordinary guarded
1660
+ * fresh-dispatch path: absence proves nothing about the server's version and
1661
+ * triggers no renaming.
1662
+ */
1663
+ function readFencedResumeHead(payload) {
1664
+ if (!payload || typeof payload !== "object")
1665
+ return null;
1666
+ const raw = payload[FENCED_RESUME_HEAD_KEY];
1667
+ if (typeof raw !== "string")
1668
+ return null;
1669
+ const head = raw.trim().toLowerCase();
1670
+ return /^[0-9a-f]{40}$/.test(head) ? head : null;
1529
1671
  }
1530
1672
  /**
1531
1673
  * Prepare a job's worktree. A job the server dispatched as a parked-child
@@ -1775,6 +1917,9 @@ async function prepareSpawn(job, httpClient, options, deps, seams, preparation)
1775
1917
  // `implement` retry acts on it; `ensureExecutorWorktree` re-checks that.
1776
1918
  // Spread only when present so an ordinary job keeps its exact legacy policy.
1777
1919
  ...(job.prior_attempt_head_sha ? { priorAttemptHeadSha: job.prior_attempt_head_sha } : {}),
1920
+ // BAPI-1530: forwarded separately from the claim's prior-attempt head so
1921
+ // same-row retry preservation keeps its own semantics.
1922
+ ...(readFencedResumeHead(job.payload) ? { fencedImplementResumeHeadSha: readFencedResumeHead(job.payload) } : {}),
1778
1923
  });
1779
1924
  if (!wt.ok) {
1780
1925
  await httpClient.fail(job, jobWorktreeFailure(wt));
@@ -1971,9 +2116,11 @@ async function renderVerifiedCiFixPrompt(params) {
1971
2116
  workBranch: branch,
1972
2117
  baseBranch,
1973
2118
  runCommand: deps.runCommand,
1974
- comparisonSha: ciFix.headSha,
2119
+ comparisonSha: ciFix.failingHeadSha ?? ciFix.headSha,
2120
+ timeoutSeconds: params.timeoutSeconds,
2121
+ deferComparisonGuidance: true,
1975
2122
  });
1976
- return { ok: true, prompt };
2123
+ return { ok: true, prompt: prompt + ciFixProvenanceGuidance(ciFix) + renderCiFixOperatorNote(job.payload) };
1977
2124
  }
1978
2125
  catch (err) {
1979
2126
  return {
@@ -1982,8 +2129,57 @@ async function renderVerifiedCiFixPrompt(params) {
1982
2129
  };
1983
2130
  }
1984
2131
  }
2132
+ /**
2133
+ * BAPI-1514: the provenance line for a focused ci_fix prompt. It separates the
2134
+ * ORIGINAL failing head (`failingHeadSha`) from the head the supplied evidence
2135
+ * describes (`evidenceHeadSha` on a refreshed payload, else the legacy anchor),
2136
+ * and never calls the evidence stale when it describes the start head itself.
2137
+ */
2138
+ function ciFixProvenanceGuidance(ciFix) {
2139
+ const original = ciFix.failingHeadSha;
2140
+ if (ciFix.evidenceHeadSha) {
2141
+ const evidence = ciFix.evidenceHeadSha;
2142
+ if (!original || original === evidence) {
2143
+ return "\n\nSupplied CI logs and snapshots describe the evidence head " + evidence +
2144
+ ", the head this repair was dispatched against. Re-verify the affected behavior at the execution head.";
2145
+ }
2146
+ return "\n\nOriginal failing head " + original + "; evidence head " + evidence +
2147
+ "; the supplied CI logs and snapshots describe the evidence head, the head this repair was dispatched against." +
2148
+ " Inspect the diff from the original failing head for context and re-verify the affected behavior at the execution head.";
2149
+ }
2150
+ if (!original)
2151
+ return "";
2152
+ if (original === ciFix.headSha) {
2153
+ return "\n\nSupplied CI logs and snapshots describe the failing head " + original +
2154
+ ", the head this repair was dispatched against. Re-verify the affected behavior at the execution head.";
2155
+ }
2156
+ return "\n\nSupplied CI logs and snapshots describe the failing head " + original +
2157
+ " and may predate this pushed checkout. Inspect the diff from that anchor and re-verify the affected behavior at the execution head.";
2158
+ }
1985
2159
  /** BAPI-1311: cap on any one focused finalization read, before the deadline clamp. */
1986
2160
  const FOCUSED_FINALIZATION_READ_MAX_MS = 120_000;
2161
+ /** BAPI-1473: bound on the pre-launch origin-tip read for a focused rebase. */
2162
+ const FOCUSED_REBASE_START_TIP_READ_MAX_MS = 30_000;
2163
+ /**
2164
+ * BAPI-1473: the work branch's authoritative origin tip just before a focused
2165
+ * rebase worker launches, as a full lower-case SHA, or null when it cannot be
2166
+ * established. Never throws; null keeps the existing post-push wait.
2167
+ */
2168
+ async function readFocusedRebaseStartTip(deps, worktreePath, branch, remainingMs) {
2169
+ const timeoutMs = Math.min(FOCUSED_REBASE_START_TIP_READ_MAX_MS, remainingMs());
2170
+ if (timeoutMs <= 0)
2171
+ return null;
2172
+ try {
2173
+ const lookup = await resolveOriginBranchSha(deps.runCommand, worktreePath, branch, { timeoutMs });
2174
+ if (lookup.state !== "found")
2175
+ return null;
2176
+ const sha = lookup.sha.trim().toLowerCase();
2177
+ return /^[0-9a-f]{40}$/.test(sha) ? sha : null;
2178
+ }
2179
+ catch {
2180
+ return null;
2181
+ }
2182
+ }
1987
2183
  /**
1988
2184
  * BAPI-1311 — run the focused rebase's post-push wait and, unless it is `ready`,
1989
2185
  * report the job's ONE terminal outcome.
@@ -2057,6 +2253,7 @@ async function superviseFocusedRebaseWait(params) {
2057
2253
  expectedBaseBranch: params.expectedBaseBranch,
2058
2254
  readPullRequest: (timeoutMs) => readFocusedPullRequest(deps.runCommand, params.worktreePath, params.context.prNumber, { timeoutMs }),
2059
2255
  pollChecks,
2256
+ ...(params.readDelivery ? { readDelivery: params.readDelivery } : {}),
2060
2257
  now: deps.now,
2061
2258
  sleep: deps.sleep,
2062
2259
  signal,
@@ -2135,6 +2332,32 @@ async function superviseFocusedRebaseWait(params) {
2135
2332
  * returns BEFORE either the deny layer or MCP provisioning runs — neither ever
2136
2333
  * touches a worktree that will not become a runnable worker.
2137
2334
  */
2335
+ /**
2336
+ * BAPI-1453 — the single executor log line for a pre-spawn refusal: the job id,
2337
+ * the closed reason, and the bounded dirty-path evidence from the observation
2338
+ * snapshot. Paths are already repository-relative, length-bounded,
2339
+ * control-escaped, and redaction-checked by `parseDirtyPathEvidence`, and are
2340
+ * JSON-quoted here so the line stays one line.
2341
+ */
2342
+ export function formatPreSpawnRefusalLine(job, reason, telemetry) {
2343
+ const code = isFailureReasonCode(reason) ? reason : "unknown";
2344
+ const paths = Array.isArray(telemetry.dirty_paths) ? telemetry.dirty_paths : [];
2345
+ const overflow = typeof telemetry.dirty_paths_overflow_count === "number" ? telemetry.dirty_paths_overflow_count : 0;
2346
+ return (`pre-spawn verification refused job_id=${job.id} reason=${code} ` +
2347
+ `dirty_paths=${JSON.stringify(paths)} dirty_paths_overflow_count=${overflow}`);
2348
+ }
2349
+ /**
2350
+ * In-process reporting policy, never serialized: failure objects registered here
2351
+ * leave `worker_diagnostics.final_message_excerpt` null on the outgoing `/fail`
2352
+ * copy, while executor-owned `attempt_log` metadata may still be attached. Marker
2353
+ * storage stays in this WeakSet so no field, symbol, option, or argument enters
2354
+ * the failure body or the shared HTTP client interface.
2355
+ */
2356
+ const failuresWithoutWorkerFinalMessageExcerpt = new WeakSet();
2357
+ function withoutWorkerFinalMessageExcerpt(failure) {
2358
+ failuresWithoutWorkerFinalMessageExcerpt.add(failure);
2359
+ return failure;
2360
+ }
2138
2361
  /** Reserve the branch before Worktrunk can mutate it; lock an existing tree before preparation. */
2139
2362
  async function runSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver) {
2140
2363
  const originalHttp = httpClient;
@@ -2143,8 +2366,18 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2143
2366
  let telemetry = { ...body.telemetry, ...observation.snapshot() };
2144
2367
  try {
2145
2368
  const diagnostics = observation.workerDiagnostics();
2146
- if (diagnostics)
2369
+ if (diagnostics && failuresWithoutWorkerFinalMessageExcerpt.has(body)) {
2370
+ // Opted-out failure: send a copy with the excerpt nulled, and drop the
2371
+ // diagnostics entirely when no attempt log is left to report. Assigned
2372
+ // after the merge above so nothing can restore the original excerpt.
2373
+ const { worker_diagnostics: _restored, ...rest } = telemetry;
2374
+ telemetry = diagnostics.attempt_log !== null
2375
+ ? { ...rest, worker_diagnostics: { ...diagnostics, final_message_excerpt: null } }
2376
+ : rest;
2377
+ }
2378
+ else if (diagnostics) {
2147
2379
  telemetry = { ...telemetry, worker_diagnostics: diagnostics };
2380
+ }
2148
2381
  }
2149
2382
  catch {
2150
2383
  if (!diagnosticWarningSent) {
@@ -2221,20 +2454,37 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2221
2454
  }
2222
2455
  };
2223
2456
  try {
2224
- return await runReservedSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver, undefined, undefined, reserve);
2457
+ return await runReservedSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver, undefined, undefined, reserve, timeout.timeoutSeconds);
2225
2458
  }
2226
2459
  finally {
2227
2460
  await retainedLock?.release();
2228
2461
  await reservation?.release();
2229
2462
  }
2230
2463
  }
2464
+ /**
2465
+ * The filesystem boundary for exclude provisioning, built from the runner's
2466
+ * injected deps. A deps builder that omits the optional `rename`/`removeFile`
2467
+ * seams gets the real operation, matching the worktree-lock fallback direction.
2468
+ */
2469
+ function excludeProvisioningDeps(deps) {
2470
+ return {
2471
+ readFile: deps.readFile,
2472
+ writeFile: deps.writeFile,
2473
+ mkdir: deps.mkdir,
2474
+ stat: deps.stat ?? ((filePath) => fsStat(filePath)),
2475
+ rename: deps.rename ?? ((from, to) => fsRename(from, to)),
2476
+ removeFile: deps.removeFile ?? ((filePath) => rm(filePath, { force: true })),
2477
+ };
2478
+ }
2231
2479
  async function runReservedSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control,
2232
2480
  /**
2233
2481
  * BAPI-1152: an optional spawn-job driver (`reconcile_overlap`). It runs inside
2234
2482
  * the SAME lock and the SAME prepared-spawn path as every other spawn job, so it
2235
2483
  * adds no second worktree entry and no second worker launcher.
2236
2484
  */
2237
- driver, retainedLock, preparation, reserve) {
2485
+ driver, retainedLock, preparation, reserve,
2486
+ /** Successful total budget resolved before preparation, never remaining time. */
2487
+ resolvedTimeoutSeconds) {
2238
2488
  // A server-owned read precedes every worktree reset/cut and worker launch.
2239
2489
  // Only this boundary can authorize a no-charge pre-work wait; a later plan
2240
2490
  // retrieval failure is ordinary bounded worker failure.
@@ -2290,9 +2540,7 @@ driver, retainedLock, preparation, reserve) {
2290
2540
  claude: {
2291
2541
  readFile: deps.readFile,
2292
2542
  denyProvisioningDeps: {
2293
- readFile: deps.readFile,
2294
- writeFile: deps.writeFile,
2295
- mkdir: deps.mkdir,
2543
+ ...excludeProvisioningDeps(deps),
2296
2544
  homedir: deps.homedir,
2297
2545
  },
2298
2546
  },
@@ -2377,6 +2625,18 @@ driver, retainedLock, preparation, reserve) {
2377
2625
  return { status: "failed", reason: "focused_rebase_context" };
2378
2626
  }
2379
2627
  }
2628
+ // BAPI-1451: provision the shared git exclude BEFORE any lock acquisition. The
2629
+ // retained-worktree lock (inside `reserve()`) and the fresh-worktree lock both
2630
+ // write `.conductor/` artifacts, and so do the recently-failed file and
2631
+ // pre-spawn verification. The executor clone's common `info/exclude` covers
2632
+ // both retained and newly prepared linked worktrees. A warning is logged and
2633
+ // the job continues unchanged: no failure reason, alert, cleanup, or early
2634
+ // return — dirty-worktree refusal stays with pre-spawn verification.
2635
+ {
2636
+ const provisioned = await (seams.provisionWorktreeSettingsExclude ?? provisionWorktreeSettingsExclude)(deps.cwd, excludeProvisioningDeps(deps));
2637
+ if (provisioned.warning)
2638
+ deps.errorLog(provisioned.warning);
2639
+ }
2380
2640
  // Acquire ownership only after read-only admission and contract validation.
2381
2641
  if (reserve) {
2382
2642
  const held = await reserve();
@@ -2505,6 +2765,7 @@ driver, retainedLock, preparation, reserve) {
2505
2765
  const rendered = await renderVerifiedCiFixPrompt({
2506
2766
  job,
2507
2767
  ciFix: prep.ciFix,
2768
+ timeoutSeconds: resolvedTimeoutSeconds,
2508
2769
  publication: prep.publication, preparation,
2509
2770
  worktreePath,
2510
2771
  branch,
@@ -2521,7 +2782,7 @@ driver, retainedLock, preparation, reserve) {
2521
2782
  readyPrep = { ...prep, prompt: rendered.prompt };
2522
2783
  }
2523
2784
  if (["implement", "resume", "remediate", "rebase", "ci_fix"].includes(job.job_type)) {
2524
- readyPrep = { ...readyPrep, comparisonSha: prep.ciFix?.headSha ??
2785
+ readyPrep = { ...readyPrep, comparisonSha: prep.ciFix?.failingHeadSha ?? prep.ciFix?.headSha ??
2525
2786
  await captureComparisonSha(worktreePath, deps) };
2526
2787
  if (!prep.ciFix && isRemainingWork(job.job_type, job.payload)) {
2527
2788
  if (job.job_type === "resume" || prep.priorWork) {
@@ -2568,6 +2829,9 @@ driver, retainedLock, preparation, reserve) {
2568
2829
  });
2569
2830
  return { status: "failed", reason: "stale_artifact_cleanup" };
2570
2831
  }
2832
+ // `.conductor/` is excluded through the executor-provisioned common
2833
+ // `info/exclude` (see the spawn-entry provisioning above), independently of
2834
+ // any repository `.gitignore`.
2571
2835
  try {
2572
2836
  await (seams.writeRecentlyFailedTestsFile ?? writeRecentlyFailedTestsFile)(worktreePath, job.payload?.recently_failed_tests);
2573
2837
  }
@@ -2615,10 +2879,200 @@ driver, retainedLock, preparation, reserve) {
2615
2879
  // touching it, and the two steps above are what establish that it cannot.
2616
2880
  spawnLifecycle.deregisterLiveWorker?.();
2617
2881
  spawnLifecycle.deregisterLiveWorker = undefined;
2882
+ // BAPI-1479 — the job database and launcher go AFTER the worker is
2883
+ // contained (supervision has settled by now) and BEFORE the worktree lock is
2884
+ // released. A drop failure is one bounded, non-fatal line on the executor's
2885
+ // stderr; it never changes the job's result.
2886
+ await spawnLifecycle.releaseWorkerResources?.().catch(() => undefined);
2618
2887
  await spawnLifecycle.closeWorkerLog?.();
2619
2888
  await worktreeLock.release();
2620
2889
  }
2621
2890
  }
2891
+ /**
2892
+ * BAPI-1479: the job types whose worker gets a disposable database and the
2893
+ * own-build launcher — the PR-producing worker jobs, which are the ones that run
2894
+ * the repository's tests. Verdict-only and driver-owned jobs keep the sentinel.
2895
+ */
2896
+ const WORKER_RESOURCE_JOB_TYPES = new Set([
2897
+ "implement", "resume", "remediate", "ci_fix", "rebase",
2898
+ ]);
2899
+ /**
2900
+ * BAPI-1479 — provision the job's disposable database and own-build launcher
2901
+ * before the worker's spawn shape is built.
2902
+ *
2903
+ * Runs under the SAME heartbeat, server-stop, and timeout supervision as a
2904
+ * driver phase, and an executor shutdown aborts it through the live-worker
2905
+ * registry (which is sticky, so a shutdown that already started still reaches
2906
+ * it). It never stops a job for a missing prerequisite: an unavailable database
2907
+ * or launcher logs ONE bounded non-fatal line and the worker spawns with the
2908
+ * sentinel database and the inherited `PATH`, exactly as before. Only the
2909
+ * existing interruptions end the job here — lease loss, a server stop, or the job
2910
+ * timeout — and they report through the existing outcomes, never a new code.
2911
+ *
2912
+ * Whatever was created is registered on `lifecycle.releaseWorkerResources` the
2913
+ * moment it exists, so `runSpawnJob`'s `finally` drops it on every exit path.
2914
+ */
2915
+ async function prepareWorkerResources(params) {
2916
+ const { job, deps, lifecycle } = params;
2917
+ const jobId = String(job.id);
2918
+ const resources = deps.workerResources;
2919
+ if (!resources)
2920
+ return { kind: "ready" };
2921
+ let target;
2922
+ let disposeLauncher;
2923
+ let launcherDirectory;
2924
+ let unavailableCategory;
2925
+ let released = false;
2926
+ lifecycle.releaseWorkerResources = async () => {
2927
+ if (released)
2928
+ return;
2929
+ released = true;
2930
+ if (target) {
2931
+ const dropped = await resources.dropDatabase(target).catch(() => ({ kind: "failed" }));
2932
+ if (dropped.kind !== "dropped") {
2933
+ try {
2934
+ deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, target.name));
2935
+ }
2936
+ catch { /* sink */ }
2937
+ }
2938
+ }
2939
+ if (disposeLauncher)
2940
+ await disposeLauncher().catch(() => undefined);
2941
+ };
2942
+ // An executor shutdown aborts provisioning the same way it terminates a worker.
2943
+ const shutdown = new AbortController();
2944
+ const deregister = params.control?.liveWorkers.register({
2945
+ requestTermination: () => shutdown.abort(),
2946
+ });
2947
+ let phase;
2948
+ try {
2949
+ phase = await superviseDriverPhase({
2950
+ job,
2951
+ httpClient: params.httpClient,
2952
+ options: params.options,
2953
+ deps,
2954
+ ownership: params.ownership,
2955
+ observation: params.observation,
2956
+ control: params.control,
2957
+ timeoutSeconds: Math.max(1, Math.ceil(params.remainingMs() / 1000)),
2958
+ collectTelemetry: params.collectTelemetry,
2959
+ run: async (signal) => {
2960
+ // Combined by hand: `AbortSignal.any` is not available on Node 18.
2961
+ const combined = new AbortController();
2962
+ const abortCombined = () => combined.abort();
2963
+ if (signal.aborted || shutdown.signal.aborted)
2964
+ combined.abort();
2965
+ signal.addEventListener("abort", abortCombined, { once: true });
2966
+ shutdown.signal.addEventListener("abort", abortCombined, { once: true });
2967
+ 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") {
2978
+ target = provisioned.target;
2979
+ }
2980
+ else {
2981
+ unavailableCategory = provisioned.category;
2982
+ try {
2983
+ deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category));
2984
+ // A created database whose rollback failed stays for the host operator.
2985
+ if ("retainedName" in provisioned && provisioned.retainedName) {
2986
+ deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, provisioned.retainedName));
2987
+ }
2988
+ }
2989
+ catch { /* sink */ }
2990
+ }
2991
+ if (cancel.aborted)
2992
+ return;
2993
+ const launcher = await resources
2994
+ .createLauncher({ jobId })
2995
+ .catch(() => ({ kind: "unavailable", reason: "wrapper_unverified" }));
2996
+ if (launcher.kind === "available") {
2997
+ disposeLauncher = launcher.dispose;
2998
+ if (!released)
2999
+ launcherDirectory = launcher.directory;
3000
+ else
3001
+ await launcher.dispose().catch(() => undefined);
3002
+ }
3003
+ else {
3004
+ try {
3005
+ deps.errorLog(formatWorkerCliLauncherUnavailableLine(jobId, launcher.reason));
3006
+ }
3007
+ catch { /* sink */ }
3008
+ }
3009
+ },
3010
+ });
3011
+ }
3012
+ finally {
3013
+ deregister?.();
3014
+ }
3015
+ if (phase.kind === "abandoned") {
3016
+ return { kind: "interrupted", result: { status: "abandoned", reason: params.ownership.abandonReason } };
3017
+ }
3018
+ if (phase.kind === "server_stop") {
3019
+ await params.httpClient.fail(job, {
3020
+ error_kind: "ServerStopRequested",
3021
+ error_message: "the server requested this run stop before the worker started",
3022
+ classification: "killed",
3023
+ telemetry: params.observation.snapshot(),
3024
+ });
3025
+ params.ownership.abandoned = true;
3026
+ params.ownership.abandonReason = "server_stop";
3027
+ return { kind: "interrupted", result: { status: "abandoned", reason: "server_stop" } };
3028
+ }
3029
+ if (phase.kind === "timeout") {
3030
+ await params.httpClient.fail(job, {
3031
+ error_kind: "Timeout",
3032
+ error_message: `${job.job_type} exceeded the job timeout before the worker started`,
3033
+ classification: "timeout",
3034
+ telemetry: params.observation.snapshot(),
3035
+ });
3036
+ return { kind: "interrupted", result: { status: "failed", reason: "timeout" } };
3037
+ }
3038
+ // An executor shutdown during provisioning: spawn nothing new with a
3039
+ // half-prepared target. The sticky registry terminates the worker on
3040
+ // registration anyway, so continuing with the sentinel keeps the existing
3041
+ // shutdown semantics while the database (if any) is dropped by the `finally`.
3042
+ if (shutdown.signal.aborted)
3043
+ return { kind: "ready" };
3044
+ // `kind: "error"` is an unexpected throw from the seam itself: degrade.
3045
+ return {
3046
+ kind: "ready",
3047
+ ...(target ? { workerDatabase: target } : {}),
3048
+ ...(launcherDirectory ? { workerLauncherDirectory: launcherDirectory } : {}),
3049
+ ...(!target && unavailableCategory ? { workerDatabaseUnavailableCategory: unavailableCategory } : {}),
3050
+ };
3051
+ }
3052
+ /**
3053
+ * BAPI-1522: the filesystem-backed executable check for the LOCAL ENVIRONMENT
3054
+ * LIMITS section. It never executes anything: it resolves symlinks, requires a
3055
+ * regular file with execute permission, and, when asked, requires the resolved
3056
+ * file to stay inside the worktree. Any filesystem error means "not runnable".
3057
+ */
3058
+ export const fileSystemExecutableCheck = (candidate, options) => {
3059
+ try {
3060
+ const resolved = realpathSync(candidate);
3061
+ if (options?.withinDirectory !== undefined) {
3062
+ const root = realpathSync(options.withinDirectory);
3063
+ const relative = path.relative(root, resolved);
3064
+ if (relative.startsWith("..") || path.isAbsolute(relative))
3065
+ return false;
3066
+ }
3067
+ if (!statSync(resolved).isFile())
3068
+ return false;
3069
+ accessSync(resolved, fsConstants.X_OK);
3070
+ return true;
3071
+ }
3072
+ catch {
3073
+ return false;
3074
+ }
3075
+ };
2622
3076
  function retainedHeadPublisher(params) {
2623
3077
  return async () => {
2624
3078
  const { job, branch, worktreePath, prep, deps, ownership, observation, remainingMs } = params;
@@ -2681,7 +3135,10 @@ async function runPreparedSpawn(params) {
2681
3135
  !prep.ciFix &&
2682
3136
  !prep.focusedRebase &&
2683
3137
  !isRemainingWork(job.job_type, job.payload)) {
2684
- prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key)}`;
3138
+ // BAPI-1544: a present boolean states the run's setting; an absent key (a job from
3139
+ // an older API) stays absent so the instruction keeps its conditional wording.
3140
+ const handoffEnabled = job.payload?.verification_handoff_enabled;
3141
+ prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key, typeof handoffEnabled === "boolean" ? handoffEnabled : undefined)}`;
2685
3142
  }
2686
3143
  // --- Timeout contract ------------------------------------------------
2687
3144
  const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
@@ -2700,7 +3157,8 @@ async function runPreparedSpawn(params) {
2700
3157
  // an envelope, rather than run under the legacy contract that the server
2701
3158
  // would then refuse to accept.
2702
3159
  const covered = claimIsCovered(job);
2703
- if (covered && (!isCoveredJobType(job.job_type) || driver)) {
3160
+ const policyRebase = job.job_type === "rebase" && job.required_capabilities?.includes("required_verification.ci_deferral.v2");
3161
+ if (covered && ((!isCoveredJobType(job.job_type) && !policyRebase) || driver)) {
2704
3162
  return await refuseCoveredClaimBeforeLaunch({
2705
3163
  job, httpClient, options, deps, ownership, observation, control,
2706
3164
  runtime: unrecognizedRuntime(adapter),
@@ -2797,6 +3255,15 @@ async function runPreparedSpawn(params) {
2797
3255
  if (job.job_type === "implement" && !isRemainingWork(job.job_type, job.payload)) {
2798
3256
  prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha);
2799
3257
  }
3258
+ // The locked ci_fix renderer deferred trusted guidance. All existing prompt
3259
+ // additions precede comparison guidance and the final total-budget block.
3260
+ if (prep.ciFix) {
3261
+ prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha) +
3262
+ "\n\n" + renderWorkerTimeBudgetGuidance(timeout.timeoutSeconds);
3263
+ }
3264
+ const approvedVerificationGuidance = renderApprovedVerificationGuidance(job.payload);
3265
+ if (approvedVerificationGuidance)
3266
+ prompt += "\n\n" + approvedVerificationGuidance;
2800
3267
  // --- Pre-spawn git verification (FAIL-CLOSED, BAPI-731 WS-E) ---------
2801
3268
  // FIRST of the pre-spawn contracts, and deliberately BEFORE every
2802
3269
  // executor-owned write to the worktree (deny layer, MCP provisioning, worker
@@ -2809,7 +3276,9 @@ async function runPreparedSpawn(params) {
2809
3276
  // failing check. It does NOT replace or weaken the existing hard-reset /
2810
3277
  // untracked-clean / head-verify behavior in `worktree-core.ts`; it is an
2811
3278
  // additional independent check on top of them.
2812
- const preSpawnTelemetry = await collectGitTelemetry({ runCommand: deps.runCommand, now: deps.now }, worktreePath, effectiveBaseBranch);
3279
+ const preSpawnTelemetry = await collectGitTelemetry({ runCommand: deps.runCommand, now: deps.now }, worktreePath, effectiveBaseBranch,
3280
+ // BAPI-1453: a refusal must name the files it found.
3281
+ { includeDirtyPaths: true });
2813
3282
  // BAPI-1152: a driver proves its own pre-spawn state (a reconciliation worker
2814
3283
  // may start inside an in-progress merge, which the generic "clean at the
2815
3284
  // prepared commit" check would refuse by design).
@@ -2827,12 +3296,28 @@ async function runPreparedSpawn(params) {
2827
3296
  observation.setAttemptEndSha(verification.observedSha);
2828
3297
  }
2829
3298
  observation.setGitTelemetry(preSpawnTelemetry);
3299
+ // BAPI-1453: one executor log line naming the job, the reason, and the
3300
+ // bounded dirty-path evidence. The paths come from the SAME observation
3301
+ // snapshot the `/fail` body carries, never from a second copy, and never
3302
+ // reach `error_message` (fixed strings and validated SHAs only).
3303
+ const refusalTelemetry = observation.snapshot();
3304
+ try {
3305
+ deps.errorLog(formatPreSpawnRefusalLine(job, verification.reason, refusalTelemetry));
3306
+ }
3307
+ catch {
3308
+ /* supplemental logging cannot change the refusal */
3309
+ }
2830
3310
  await httpClient.fail(job, {
2831
3311
  error_kind: PreSpawnVerification,
2832
3312
  error_message: verification.message,
2833
3313
  classification: "crashed",
2834
3314
  ...commitResidue(preSpawnTelemetry),
2835
- telemetry: observation.snapshot(),
3315
+ // Builder-owned code first; the spawn-path wrapper then layers the
3316
+ // snapshot over it, so both survive.
3317
+ telemetry: {
3318
+ ...(isFailureReasonCode(verification.reason) ? { failure_reason_code: verification.reason } : {}),
3319
+ ...refusalTelemetry,
3320
+ },
2836
3321
  });
2837
3322
  return { status: "failed", reason: "pre_spawn_verification" };
2838
3323
  }
@@ -3141,6 +3626,32 @@ async function runPreparedSpawn(params) {
3141
3626
  // is denied at the env builder and cannot reach `spawnShape.env`. It stays out
3142
3627
  // of `argv` entirely: it is a routing declaration, not a command-line input,
3143
3628
  // and argv is world-readable via `ps`.
3629
+ // --- Worker resources (BAPI-1479) --------------------------------------
3630
+ // The job's disposable database and own-build launcher, prepared ONCE for this
3631
+ // prepared job, before the one spawn shape both the covered and legacy launches
3632
+ // use. A retry of the job is a fresh claim with a fresh execution, so it gets
3633
+ // fresh resources; nothing is recovered from an earlier execution's state.
3634
+ // Driver-owned jobs (their worker runs a server-rendered reconciliation) and
3635
+ // verdict-only jobs keep the sentinel database.
3636
+ let workerResources = {};
3637
+ // BAPI-1522: why no database exists (a closed category), kept OUT of the spawn input.
3638
+ let databaseUnavailableCategory;
3639
+ if (!driver && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)) {
3640
+ const prepared = await prepareWorkerResources({
3641
+ job, httpClient, options: jobOptions, deps, ownership, observation, control,
3642
+ worktreePath, remainingMs, lifecycle, collectTelemetry: driverTelemetry,
3643
+ });
3644
+ if (prepared.kind === "interrupted") {
3645
+ await closeWorkerLog();
3646
+ await finalizeRegistry();
3647
+ return prepared.result;
3648
+ }
3649
+ workerResources = {
3650
+ ...(prepared.workerDatabase ? { workerDatabase: prepared.workerDatabase } : {}),
3651
+ ...(prepared.workerLauncherDirectory ? { workerLauncherDirectory: prepared.workerLauncherDirectory } : {}),
3652
+ };
3653
+ databaseUnavailableCategory = prepared.workerDatabaseUnavailableCategory;
3654
+ }
3144
3655
  const invocation = adapter.headlessInvocation;
3145
3656
  if (invocation?.supported !== true) {
3146
3657
  await closeWorkerLog();
@@ -3155,8 +3666,12 @@ async function runPreparedSpawn(params) {
3155
3666
  let spawnShape;
3156
3667
  try {
3157
3668
  const alias = invocation.value.resolveModelAlias(job.payload);
3158
- spawnShape = invocation.value.buildSpawnShape({
3159
- prompt,
3669
+ // BAPI-1522 — LOCAL ENVIRONMENT LIMITS is the LAST prompt section. It is built
3670
+ // here, after resources, worktree, environment, prompt expansion, and approved
3671
+ // guidance are final, from the PATH the adapter will really hand the worker.
3672
+ // The section is appended exactly once, and nothing after this point changes
3673
+ // the prompt text.
3674
+ const shapeInput = {
3160
3675
  // BAPI-1301: a covered attempt sends the prompt on a held stdin instead
3161
3676
  // of argv; every other job keeps the byte-identical legacy argv.
3162
3677
  ...(covered ? { promptTransport: "stdin-stream-json" } : {}),
@@ -3175,7 +3690,38 @@ async function runPreparedSpawn(params) {
3175
3690
  ...(driver?.omitWorkerBranch ? {} : { workerBranch: branch }),
3176
3691
  ...(correctionWork ? { correctionIntentVersion: 1 } : {}),
3177
3692
  ...(driverStep ? { declaredTouchedFiles: driverStep.declaredTouchedFiles } : {}),
3693
+ // BAPI-1479 — explicit, executor-provisioned values; never read from `parentEnv`.
3694
+ ...workerResources,
3695
+ // BAPI-1521 — forwarded only when the payload OWNS the key, for every worker
3696
+ // job type. Absent keeps the legacy compatibility constants; a present
3697
+ // value, even `[]` or a malformed one, replaces them.
3698
+ ...payloadWorkerEnvOption(job.payload),
3178
3699
  parentEnv: deps.env,
3700
+ };
3701
+ // The PATH the worker will receive: the launcher directory (when provisioned)
3702
+ // first, then the inherited PATH, exactly as `env.ts` composes it. The runner
3703
+ // builds no worker environment itself (BAPI-781), so this only mirrors that
3704
+ // rule for the read-only limits check.
3705
+ const inheritedPath = deps.env.PATH;
3706
+ const workerEnvPath = workerResources.workerLauncherDirectory
3707
+ ? (typeof inheritedPath === "string" && inheritedPath.length > 0
3708
+ ? `${workerResources.workerLauncherDirectory}${path.delimiter}${inheritedPath}`
3709
+ : workerResources.workerLauncherDirectory)
3710
+ : inheritedPath;
3711
+ const reproduceCommands = job.payload && typeof job.payload === "object"
3712
+ ? job.payload.reproduce_commands : undefined;
3713
+ const limits = renderLocalEnvironmentLimits({
3714
+ databaseAvailable: workerResources.workerDatabase !== undefined,
3715
+ ...(databaseUnavailableCategory && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3716
+ ? { databaseUnavailableCategory } : {}),
3717
+ reproduceCommands,
3718
+ ...(typeof workerEnvPath === "string" ? { workerPath: workerEnvPath } : {}),
3719
+ worktreePath,
3720
+ isExecutable: seams.executableCheck ?? fileSystemExecutableCheck,
3721
+ });
3722
+ spawnShape = invocation.value.buildSpawnShape({
3723
+ prompt: limits ? prompt + "\n\n" + limits : prompt,
3724
+ ...shapeInput,
3179
3725
  });
3180
3726
  assertUsableSpawnShape(spawnShape, adapter);
3181
3727
  }
@@ -3309,6 +3855,15 @@ async function runPreparedSpawn(params) {
3309
3855
  // the covered attempt launch through it, so there is still exactly one place a
3310
3856
  // worker can be started, always from the verified spawn shape. Only a covered
3311
3857
  // attempt asks for a held stdin; the legacy options stay byte-identical.
3858
+ // BAPI-1473: a focused rebase records the work branch's ORIGIN tip immediately
3859
+ // before its worker launches. When finalization later proves the origin tip is
3860
+ // still exactly this SHA, the worker pushed nothing (it only renewed evidence),
3861
+ // so there is no post-push evidence to wait for. Read with the same
3862
+ // authoritative `git ls-remote` finalization uses, never a local tracking ref
3863
+ // and never `job.expected_head_sha`. Unknown (null) keeps the existing wait.
3864
+ const focusedRebaseStartTip = prep.focusedRebase
3865
+ ? await readFocusedRebaseStartTip(deps, worktreePath, branch, remainingMs)
3866
+ : null;
3312
3867
  const spawnWorker = (spawnOptions) => deps.spawnProcess(spawnShape.executable, spawnShape.argv, {
3313
3868
  cwd: worktreePath,
3314
3869
  env: spawnOptions.env,
@@ -3342,11 +3897,29 @@ async function runPreparedSpawn(params) {
3342
3897
  if (!spawnShape.stdinMessages?.initial) {
3343
3898
  return await refuse("unsupported_runtime", "the executor adapter produced no held-stdin prompt message for a covered job");
3344
3899
  }
3900
+ // BAPI-1504 — a job stamped with `cleanup_report.v1` is only safe to run on a
3901
+ // client that can deliver the report; refusing here, before any worker exists,
3902
+ // names the missing capability in the envelope instead of launching a job whose
3903
+ // interruption could never be proven clean.
3904
+ if (claimRequiresCleanupReport(job.required_capabilities) && typeof httpClient.reportCleanup !== "function") {
3905
+ await closeWorkerLog();
3906
+ await finalizeRegistry();
3907
+ return await refuseCoveredClaimBeforeLaunch({
3908
+ job, httpClient, options, deps, ownership, observation, control,
3909
+ runtime, dispatchHeadSha, reason: "unsupported_runtime",
3910
+ message: "this executor cannot deliver cleanup reports (cleanup_report.v1); update the executor",
3911
+ missingCapabilities: ["cleanup_report"],
3912
+ });
3913
+ }
3345
3914
  // BAPI-1302 (D4c) — the server-stamped declaration is validated WHOLE,
3346
3915
  // before any allowance is reserved or a worker exists. A truncated,
3347
3916
  // malformed, unsupported or server-refused declaration never launches work
3348
3917
  // against a partial set of checks.
3349
3918
  const verificationRead = readRequiredVerification(job.payload);
3919
+ if (verificationRead.kind === "ok" && verificationRead.declaration.policyVersion === 2 &&
3920
+ !job.required_capabilities?.includes("required_verification.ci_deferral.v2")) {
3921
+ return await refuse("declaration_refused", "CI-deferral capability was not negotiated; refusing to launch");
3922
+ }
3350
3923
  if (verificationRead.kind === "refused") {
3351
3924
  deps.errorLog(`[executor] job ${job.id}: required-verification declaration refused (${verificationRead.reason})`);
3352
3925
  return await refuse("declaration_refused", "the job's required-verification declaration is unusable; refusing to launch");
@@ -3392,7 +3965,7 @@ async function runPreparedSpawn(params) {
3392
3965
  const legacyLineFeeder = legacyLedger ? createLedgerLineFeeder(legacyLedger) : null;
3393
3966
  let proc;
3394
3967
  try {
3395
- proc = spawnWorker({ env: spawnShape.env });
3968
+ proc = spawnWorker({ env: withExecutorJobId(spawnShape.env, job.id) });
3396
3969
  }
3397
3970
  catch (err) {
3398
3971
  await closeWorkerLog();
@@ -3698,19 +4271,22 @@ async function runPreparedSpawn(params) {
3698
4271
  // before generic success, the ci_fix artifact merge, or finalization can hide
3699
4272
  // it. Only the fixed kind and message are sent: no event text, command, path,
3700
4273
  // or output. A matching terminal task_notification leaves nothing pending.
4274
+ // The explicit opt-out below overrides the BAPI-1431 diagnostics default, so
4275
+ // no worker final-message excerpt is sent; an executor-generated relative
4276
+ // attempt-log reference may still ride along.
3701
4277
  if (legacyLedger?.observeLiveRequiredWork() === "live_required_work") {
3702
4278
  deps.errorLog(`[executor] job ${job.id}: worker exited cleanly with required background work still live`);
3703
4279
  await finalizeRegistry();
3704
4280
  const terminal = await sendTerminalMutationWithAuthReport({
3705
4281
  kind: "fail",
3706
- send: () => httpClient.fail(job, {
4282
+ send: () => httpClient.fail(job, withoutWorkerFinalMessageExcerpt({
3707
4283
  error_kind: WorkerEndedWithPendingBackgroundWork,
3708
4284
  error_message: WORKER_ENDED_WITH_PENDING_BACKGROUND_WORK_MESSAGE,
3709
4285
  classification: "crashed",
3710
4286
  ...observedExitCode(procResult.exitCode),
3711
4287
  ...commitResidue(git),
3712
4288
  telemetry: observation.snapshot(),
3713
- }),
4289
+ })),
3714
4290
  deps,
3715
4291
  options,
3716
4292
  ownership,
@@ -3761,11 +4337,24 @@ async function runPreparedSpawn(params) {
3761
4337
  // its push never landed on origin and no PR was opened (e.g. it backgrounded
3762
4338
  // a slow push and returned early). Convert that into a fail-loud executor
3763
4339
  // failure rather than silently reporting success.
4340
+ //
4341
+ // BAPI-1426: a managed ticket's server-confirmed delivery outcome is read
4342
+ // first, so an intentional held checkpoint finalizes as a `/fail` with its
4343
+ // 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
+ });
3764
4352
  const finalization = await validateWorkerFinalization({
3765
4353
  job,
3766
4354
  branch,
3767
4355
  worktreePath,
3768
4356
  result: genericResult,
4357
+ ...(deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
3769
4358
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, remainingMs, httpClient, options: jobOptions, control }),
3770
4359
  runCommand: deps.runCommand,
3771
4360
  headSha: git.last_commit_sha,
@@ -3791,7 +4380,7 @@ async function runPreparedSpawn(params) {
3791
4380
  // finalization failure; it is never rewritten to look like a crash.
3792
4381
  ...observedExitCode(procResult.exitCode),
3793
4382
  ...commitResidue(git),
3794
- telemetry: observation.snapshot(),
4383
+ telemetry: withFailureTelemetry(observation.snapshot(), finalization.failure.telemetry),
3795
4384
  }),
3796
4385
  deps,
3797
4386
  options,
@@ -3808,11 +4397,38 @@ async function runPreparedSpawn(params) {
3808
4397
  // supervision a worker gets, bounded by the job's ORIGINAL absolute deadline.
3809
4398
  // It launches no worker, enqueues nothing, and resets nothing: a pending check
3810
4399
  // is waited on, never repaired again. Only `ready` reaches `/complete`, once.
3811
- if (prep.focusedRebase) {
4400
+ //
4401
+ // BAPI-1473: two narrower successful ends, both still submitting `/complete`
4402
+ // exactly once below and leaving the server's completion contract and
4403
+ // delivery guard as the authority:
4404
+ // - NO PUSH: the verified origin tip equals the tip recorded before launch,
4405
+ // so the worker only renewed evidence. Skip the post-push wait.
4406
+ // - DEFERRED CI: the wait itself ends `ready` while required checks are still
4407
+ // pending when the server's readiness at the pushed head shows renewed
4408
+ // evidence with only `remote_ci` deferrals (`readDelivery` below).
4409
+ // Neither is merge behavior: the merge guard keeps the child in `merging`
4410
+ // until readiness is `complete`, which needs green checks at the head.
4411
+ const focusedRebasePushedNothing = prep.focusedRebase !== undefined &&
4412
+ focusedRebaseStartTip !== null &&
4413
+ typeof finalization.pushedHeadSha === "string" &&
4414
+ finalization.pushedHeadSha.trim().toLowerCase() === focusedRebaseStartTip;
4415
+ if (focusedRebasePushedNothing) {
4416
+ deps.errorLog(`[executor] job ${job.id}: focused rebase pushed nothing (origin tip unchanged); ` +
4417
+ "skipping the post-push wait and submitting completion once for the server to decide");
4418
+ }
4419
+ if (prep.focusedRebase && !focusedRebasePushedNothing) {
3812
4420
  const focusedTerminal = await superviseFocusedRebaseWait({
3813
4421
  job, httpClient, options, jobOptions, deps, ownership, observation, seams, control,
3814
4422
  context: prep.focusedRebase,
3815
4423
  pushedHeadSha: finalization.pushedHeadSha ?? null,
4424
+ readDelivery: () => readDeliveryOutcomeForFinalization({
4425
+ job,
4426
+ branch,
4427
+ deps,
4428
+ seams,
4429
+ remainingMs,
4430
+ resolvedBaseUrl: options.resolvedBaseUrl,
4431
+ }),
3816
4432
  expectedBaseBranch: effectiveBaseBranch,
3817
4433
  worktreePath,
3818
4434
  jobDeadlineMs,
@@ -4015,6 +4631,7 @@ export function unlaunchedVerification(read) {
4015
4631
  const facts = {
4016
4632
  provenance,
4017
4633
  declaration_digest: digest,
4634
+ ...(read.kind === "ok" && read.declaration.policyVersion === 2 ? { deferred_obligation_identities: read.declaration.deferredIdentities ?? [] } : {}),
4018
4635
  tested_head_sha: null,
4019
4636
  artifact: "not_observed",
4020
4637
  commands: [],
@@ -4073,7 +4690,7 @@ async function refuseCoveredClaimBeforeLaunch(input) {
4073
4690
  finalization: "unknown",
4074
4691
  verification: unlaunched.verification,
4075
4692
  cleanup: buildCleanupVerdict("confirmed", 0, []),
4076
- missingCapabilities: [],
4693
+ missingCapabilities: input.missingCapabilities ?? [],
4077
4694
  ...(unlaunched.facts ? { verificationFacts: unlaunched.facts } : {}),
4078
4695
  });
4079
4696
  const cause = envelope.cause ?? "required_work_incomplete";
@@ -4124,7 +4741,9 @@ async function runCoveredAttempt(params) {
4124
4741
  const token = createOwnershipToken();
4125
4742
  const tokenDigest = ownershipTokenDigest(token);
4126
4743
  const hostDigest = hostIdentityDigest(os.hostname());
4127
- const workerEnv = withOwnershipTag(spawnShape.env, token);
4744
+ // BAPI-1544: the claimed job's ID, set last from the job row so the worker's MCP
4745
+ // server can register it on the delivery binding. Absent when the ID is unusable.
4746
+ const workerEnv = withExecutorJobId(withOwnershipTag(spawnShape.env, token), job.id);
4128
4747
  const stateDir = resolveExecutorStateDir(buildJobLogRegistryDeps(deps));
4129
4748
  const recordFs = seams.ownershipRecordFs ?? createDefaultOwnershipRecordFs();
4130
4749
  try {
@@ -4159,6 +4778,90 @@ async function runCoveredAttempt(params) {
4159
4778
  optionalWatchers: readOptionalWatchers(job.payload),
4160
4779
  obligations,
4161
4780
  });
4781
+ // --- Ownership persisted BEFORE the spawn (BAPI-1504) ---------------------------
4782
+ // A job stamped with `cleanup_report.v1` stores `NULL` ownership only if no worker
4783
+ // was ever spawned, which lets the server read a null as proof of that. So the
4784
+ // server must hold this attempt's ownership (token digest, `worker: null`) before
4785
+ // the worker exists. The local record above was written first.
4786
+ const requiresCleanupReport = claimRequiresCleanupReport(job.required_capabilities);
4787
+ if (requiresCleanupReport) {
4788
+ const abandonBeforeLaunch = async (result) => {
4789
+ await closeWorkerLog();
4790
+ await finalizeRegistry();
4791
+ await removeOwnershipRecord(stateDir, job.id, recordFs).catch(() => undefined);
4792
+ return result;
4793
+ };
4794
+ const notLaunched = async (message) => {
4795
+ await closeWorkerLog();
4796
+ await finalizeRegistry();
4797
+ await removeOwnershipRecord(stateDir, job.id, recordFs).catch(() => undefined);
4798
+ return await refuseCoveredClaimBeforeLaunch({
4799
+ job, httpClient, options, deps, ownership, observation, control,
4800
+ runtime: params.runtime, dispatchHeadSha: params.dispatchHeadSha,
4801
+ reason: "not_launched", message,
4802
+ });
4803
+ };
4804
+ const preSpawnContext = {
4805
+ version: 1,
4806
+ token_digest: tokenDigest,
4807
+ host_digest: hostDigest,
4808
+ worker: null,
4809
+ };
4810
+ // Transient failures retry only inside the existing dead-man window; the window
4811
+ // is measured from the last successful beat and is never extended by a retry.
4812
+ for (;;) {
4813
+ let beat;
4814
+ try {
4815
+ beat = await sendImmediateHeartbeat({
4816
+ job,
4817
+ httpClient,
4818
+ deps,
4819
+ ownership,
4820
+ observation,
4821
+ collectTelemetry: () => collectGitTelemetry({ runCommand: deps.runCommand, now: deps.now }, worktreePath, effectiveBaseBranch),
4822
+ ownershipContext: preSpawnContext,
4823
+ });
4824
+ }
4825
+ catch {
4826
+ beat = { kind: "transient" };
4827
+ }
4828
+ if (beat.kind === "accepted")
4829
+ break;
4830
+ if (beat.kind === "stale_claim") {
4831
+ return await abandonBeforeLaunch({ status: "abandoned", reason: "stale_claim" });
4832
+ }
4833
+ if (beat.kind === "server_stop") {
4834
+ // Report first, then mark the claim abandoned, exactly as the post-spawn
4835
+ // server-stop path does: an abandoned claim skips the terminal report.
4836
+ const stopped = await notLaunched("the server requested this run stop before the worker launched");
4837
+ ownership.abandoned = true;
4838
+ ownership.abandonReason = "server_stop";
4839
+ return stopped.status === "failed" ? { status: "abandoned", reason: "server_stop" } : stopped;
4840
+ }
4841
+ if (beat.kind === "auth_fatal") {
4842
+ control?.reportAuthFatal?.({
4843
+ jobId: job.id,
4844
+ repoName: job.repo_name,
4845
+ category: "heartbeat",
4846
+ httpStatus: beat.httpStatus,
4847
+ });
4848
+ return await abandonBeforeLaunch({ status: "abandoned", reason: "auth_fatal" });
4849
+ }
4850
+ // transient
4851
+ if (deps.now() - ownership.lastSuccessfulHeartbeatAt >= options.deadmanMs) {
4852
+ return await notLaunched("ownership could not be recorded with the server before launch; not launching the worker");
4853
+ }
4854
+ await deps.sleep(Math.min(jobOptions.heartbeatIntervalMs, 5_000));
4855
+ }
4856
+ // The claim, the run, and the executor can all change while the beat was in
4857
+ // flight; check once more immediately before the spawn.
4858
+ if (ownership.abandoned) {
4859
+ return await abandonBeforeLaunch({ status: "abandoned", reason: ownership.abandonReason });
4860
+ }
4861
+ if (control?.liveWorkers.isShutdownRequested() === true) {
4862
+ return await notLaunched("the executor is shutting down; not launching the worker");
4863
+ }
4864
+ }
4162
4865
  // --- Spawn (held stdin) ---------------------------------------------------
4163
4866
  let proc;
4164
4867
  try {
@@ -4451,7 +5154,7 @@ async function runCoveredAttempt(params) {
4451
5154
  send: () => httpClient.fail(job, {
4452
5155
  ...failure,
4453
5156
  ...commitResidue(git),
4454
- telemetry: observation.snapshot(),
5157
+ telemetry: withFailureTelemetry(observation.snapshot(), failure.telemetry),
4455
5158
  completion_contract: SUPPORTED_COMPLETION_MARKER,
4456
5159
  completion_evidence: envelope,
4457
5160
  ...extra,
@@ -4467,6 +5170,53 @@ async function runCoveredAttempt(params) {
4467
5170
  // The terminal report is acknowledged (or ownership is gone): only now does
4468
5171
  // the job-level heartbeat end, and only now is the restart record retired.
4469
5172
  await endHeartbeat();
5173
+ // BAPI-1504 — a lost claim after a CONFIRMED sweep: deliver the cleanup fact
5174
+ // before the record can be removed. The first attempt is awaited (bounded by
5175
+ // the HTTP client); a retained outcome continues in the background and the
5176
+ // record stays until a terminal server answer.
5177
+ if (requiresCleanupReport &&
5178
+ claimIsCovered(job) &&
5179
+ result.status === "abandoned" &&
5180
+ (result.reason === "stale_claim" || result.reason === "deadman") &&
5181
+ cleanup.verdict === "confirmed" &&
5182
+ cleanup.survivors === 0) {
5183
+ const first = await submitCleanupReport({
5184
+ httpClient, jobId: job.id, repoName: job.repo_name, ownershipToken: token, path: "wake",
5185
+ });
5186
+ if (cleanupReportPermitsRecordRemoval(first)) {
5187
+ await removeOwnershipRecord(stateDir, job.id, recordFs).catch(() => undefined);
5188
+ }
5189
+ else if (first.kind === "retained" && first.retryable) {
5190
+ const retry = retryWakeCleanupReport({
5191
+ httpClient,
5192
+ jobId: job.id,
5193
+ repoName: job.repo_name,
5194
+ ownershipToken: token,
5195
+ firstResult: first,
5196
+ intervalMs: jobOptions.heartbeatIntervalMs,
5197
+ shouldStop: () => control?.liveWorkers.isShutdownRequested() === true,
5198
+ deps: {
5199
+ now: deps.now,
5200
+ sleep: deps.sleep,
5201
+ diagnostic: (d) => deps.errorLog(`[executor] ${d.event} job=${d.jobId}`),
5202
+ },
5203
+ onTerminal: () => removeOwnershipRecord(stateDir, job.id, recordFs).catch(() => undefined),
5204
+ });
5205
+ if (control?.trackBackground)
5206
+ control.trackBackground(retry);
5207
+ else
5208
+ void retry;
5209
+ }
5210
+ // Any other retained outcome keeps the record for the next start.
5211
+ return result;
5212
+ }
5213
+ // BAPI-1504 — an abandoned covered attempt whose sweep did NOT confirm keeps
5214
+ // its record, so the next start can sweep again and report only then.
5215
+ if (requiresCleanupReport &&
5216
+ result.status === "abandoned" &&
5217
+ (result.reason === "stale_claim" || result.reason === "deadman")) {
5218
+ return result;
5219
+ }
4470
5220
  await removeOwnershipRecord(stateDir, job.id, recordFs).catch(() => undefined);
4471
5221
  return result;
4472
5222
  };
@@ -4552,6 +5302,7 @@ async function runCoveredAttempt(params) {
4552
5302
  verificationFacts = {
4553
5303
  provenance: declaration.provenance,
4554
5304
  declaration_digest: declaration.digest,
5305
+ ...(declaration.policyVersion === 2 ? { deferred_obligation_identities: declaration.deferredIdentities ?? [] } : {}),
4555
5306
  tested_head_sha: null,
4556
5307
  artifact: "not_observed",
4557
5308
  commands: [],
@@ -4631,6 +5382,7 @@ async function runCoveredAttempt(params) {
4631
5382
  verificationFacts = {
4632
5383
  provenance: "declared",
4633
5384
  declaration_digest: declaration.digest,
5385
+ ...(declaration.policyVersion === 2 ? { deferred_obligation_identities: declaration.deferredIdentities ?? [] } : {}),
4634
5386
  tested_head_sha: before.head,
4635
5387
  artifact,
4636
5388
  commands: declaredOrderFacts(checks, runFacts).map(toCompletionCheckFact),
@@ -4657,11 +5409,22 @@ async function runCoveredAttempt(params) {
4657
5409
  ? { ...ciResult.fields, ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status }
4658
5410
  : { ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status };
4659
5411
  }
5412
+ // BAPI-1426: the server-confirmed delivery outcome, read under the same
5413
+ // 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
+ });
4660
5422
  const finalization = await validateWorkerFinalization({
4661
5423
  job,
4662
5424
  branch,
4663
5425
  worktreePath,
4664
5426
  result: genericResult,
5427
+ ...(deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
4665
5428
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, httpClient, options: jobOptions, control,
4666
5429
  remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()) }),
4667
5430
  callTimeoutMs: () => Math.min(120_000, Math.max(0, plan.deadlineAtMs - deps.now())),
@@ -4672,8 +5435,17 @@ async function runCoveredAttempt(params) {
4672
5435
  // the existence-only legacy fallback is refused here.
4673
5436
  coveredAttempt: true,
4674
5437
  });
4675
- const facts = finalizationFacts(finalization.ok ? { ok: true } : { ok: false, errorKind: finalization.failure.error_kind });
4676
- const envelope = envelopeWith({
5438
+ // BAPI-1426: a server-confirmed delivery hold proved the push (origin equals
5439
+ // the worker HEAD and the server's preserved head) and deliberately left the
5440
+ // pull request unmet. Its completion cause is set on the envelope so the
5441
+ // envelope, `successRefusalReason` and the `/fail` error kind all agree. A
5442
+ // stronger cause the envelope already derived (cleanup, a locally failed
5443
+ // check, unfinished tasks) is kept.
5444
+ const deliveryHold = finalization.ok ? null : deliveryHoldOf(finalization.failure);
5445
+ const facts = deliveryHold
5446
+ ? { verdict: "unmet", pushSatisfied: true, prSatisfied: false }
5447
+ : finalizationFacts(finalization.ok ? { ok: true } : { ok: false, errorKind: finalization.failure.error_kind });
5448
+ const derivedEnvelope = envelopeWith({
4677
5449
  finalization: facts.verdict,
4678
5450
  verification,
4679
5451
  missing: [],
@@ -4681,6 +5453,14 @@ async function runCoveredAttempt(params) {
4681
5453
  prSatisfied: facts.prSatisfied,
4682
5454
  ...(verificationFacts ? { verificationFacts } : {}),
4683
5455
  });
5456
+ const deliveryHoldCause = deliveryHold
5457
+ ? deliveryHold.outcome === "verification_failed"
5458
+ ? "required_check_failed"
5459
+ : "required_work_incomplete"
5460
+ : null;
5461
+ const envelope = deliveryHoldCause !== null && derivedEnvelope.cause === null
5462
+ ? { ...derivedEnvelope, cause: deliveryHoldCause }
5463
+ : derivedEnvelope;
4684
5464
  // --- Phase 5: terminal report -----------------------------------------------------
4685
5465
  const lateStronger = await strongerOutcome();
4686
5466
  if (lateStronger)
@@ -4723,6 +5503,11 @@ async function runCoveredAttempt(params) {
4723
5503
  ...observedExitCode(procResult.exitCode),
4724
5504
  };
4725
5505
  const cause = envelope.cause;
5506
+ if (cause && !finalization.ok && deliveryHold && cause === deliveryHoldCause) {
5507
+ // BAPI-1426: the intentional delivery hold keeps its own bounded message and
5508
+ // hold marker; its error kind already equals the envelope's cause.
5509
+ return finish(await failWith({ ...finalization.failure, error_kind: COMPLETION_CAUSE_ERROR_KINDS[cause], ...observedExit }, envelope));
5510
+ }
4726
5511
  if (cause) {
4727
5512
  return finish(await failWith({
4728
5513
  error_kind: COMPLETION_CAUSE_ERROR_KINDS[cause],