@bridge_gpt/mcp-server 0.2.70 → 0.2.72

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 (134) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +29 -4
  3. package/build/agent-notes.js +171 -95
  4. package/build/agent-registry.js +5 -5
  5. package/build/agents.generated.js +12 -2
  6. package/build/bounded-wait.js +9 -1
  7. package/build/bridge-permissions.js +17 -5
  8. package/build/bridge-worktree-inspection.js +237 -0
  9. package/build/check-evidence.js +6 -0
  10. package/build/claude-review-workflow.js +1 -1
  11. package/build/cli-help.js +6 -0
  12. package/build/codex-auto-recovery.js +126 -0
  13. package/build/codex-skill-adapter.js +2 -0
  14. package/build/commands.generated.js +5 -5
  15. package/build/conductor/bridge-api-client.js +776 -23
  16. package/build/conductor/command-drift-production.js +7 -2
  17. package/build/conductor/doctor.js +93 -13
  18. package/build/conductor/epic-implementer-cli.js +55 -2
  19. package/build/conductor/gate-discovery.js +659 -19
  20. package/build/conductor/gate-settings-review.js +751 -0
  21. package/build/conductor/git-hooks-uninstall.js +112 -0
  22. package/build/conductor/git-hooks.js +81 -15
  23. package/build/conductor/guided-repair.js +10 -1
  24. package/build/conductor/install-doctor.js +2 -4
  25. package/build/conductor/launch-need-probes.js +16 -11
  26. package/build/conductor/launch-plan.js +185 -0
  27. package/build/conductor/local-merge.js +12 -1
  28. package/build/conductor/merge-execution-contract.js +1 -1
  29. package/build/conductor/merged-child-check.js +2 -1
  30. package/build/conductor/precheck-timings.js +14 -0
  31. package/build/conductor/prerequisite-inputs.js +379 -0
  32. package/build/conductor/preview-observations.js +10 -0
  33. package/build/conductor/readiness-assessment.js +78 -0
  34. package/build/conductor/readiness-cli.js +10 -0
  35. package/build/conductor/readiness-prerequisites.js +53 -0
  36. package/build/conductor/readiness-sections.js +25 -9
  37. package/build/conductor/readiness.js +20 -2
  38. package/build/conductor/recovery-cli.js +281 -14
  39. package/build/conductor/recovery-operations.js +78 -5
  40. package/build/conductor/repair-contract.js +33 -0
  41. package/build/conductor/tools.js +34 -3
  42. package/build/conductor/wait-run-attention.js +115 -0
  43. package/build/conductor/wait-run-cli.js +96 -3
  44. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  45. package/build/credential-store.js +25 -20
  46. package/build/dependency-install-declarations.js +157 -0
  47. package/build/docs.generated.js +4 -4
  48. package/build/doctor.js +37 -5
  49. package/build/drive-epic-help.js +2 -2
  50. package/build/drive-epic.js +240 -56
  51. package/build/epic-ci-workflow-drift.js +71 -23
  52. package/build/epic-ci-workflow-install.js +83 -26
  53. package/build/epic-ci-workflow-v1.js +132 -0
  54. package/build/epic-ci-workflow.js +174 -13
  55. package/build/epic-implementer-bin.js +119 -44
  56. package/build/epic-launch-profile.js +1 -1
  57. package/build/executor/ci-rerun-job.js +220 -14
  58. package/build/executor/cli.js +2 -0
  59. package/build/executor/completion-contract.js +16 -0
  60. package/build/executor/credentials.js +1 -1
  61. package/build/executor/delivery-observations.js +113 -0
  62. package/build/executor/delivery-outcome.js +30 -0
  63. package/build/executor/dependency-refresh-runner.js +132 -0
  64. package/build/executor/dependency-refresh.js +530 -0
  65. package/build/executor/deps.js +4 -0
  66. package/build/executor/env.js +274 -5
  67. package/build/executor/gate-qualification-job.js +20 -5
  68. package/build/executor/harness-coverage.js +19 -0
  69. package/build/executor/http-client.js +35 -1
  70. package/build/executor/index.js +2 -1
  71. package/build/executor/install-preflight.js +1 -1
  72. package/build/executor/job-runner.js +355 -36
  73. package/build/executor/likely-tests.js +100 -98
  74. package/build/executor/preflight.js +5 -0
  75. package/build/executor/process-containment.js +18 -0
  76. package/build/executor/prompt-spec.js +84 -15
  77. package/build/executor/reconcile-overlap-job.js +6 -1
  78. package/build/executor/required-verification.js +28 -0
  79. package/build/executor/required-work-diagnostics.js +30 -0
  80. package/build/executor/required-work-ledger.js +19 -1
  81. package/build/executor/results.js +42 -0
  82. package/build/executor/service-discovery.js +42 -0
  83. package/build/executor/service-lifecycle.js +109 -2
  84. package/build/executor/service-uninstall.js +205 -0
  85. package/build/executor/service-unit.js +5 -3
  86. package/build/executor/test-clock.js +3 -0
  87. package/build/executor/verification-hints.js +179 -0
  88. package/build/executor/worker-command.js +188 -1
  89. package/build/executor/worker-database.js +299 -40
  90. package/build/executor/worker-finalization.js +65 -10
  91. package/build/executor/worker-guard-hook.js +10 -2
  92. package/build/executor/worker-resources.js +12 -1
  93. package/build/executor/worker-verification-guidance.js +64 -0
  94. package/build/executor/worktree-inspection.js +42 -0
  95. package/build/github-sign-in.js +1 -1
  96. package/build/index.js +767 -310
  97. package/build/init.js +3 -3
  98. package/build/install-bridge-conductor-gate.js +416 -41
  99. package/build/install-bridge-conductor-setup.js +135 -32
  100. package/build/install-bridge-conductor.js +769 -353
  101. package/build/install-bridge.js +419 -124
  102. package/build/install-maintenance.js +104 -0
  103. package/build/install-reexec.js +1 -1
  104. package/build/local-cleanup.js +59 -0
  105. package/build/mcp-install-state.js +68 -2
  106. package/build/merge-workflow-install.js +22 -2
  107. package/build/package-script-semantics.js +10 -0
  108. package/build/pipeline-utils.js +1 -1
  109. package/build/pipelines.generated.js +6 -6
  110. package/build/plan-execution-ledger.js +171 -10
  111. package/build/plane/plane-freshness.js +12 -9
  112. package/build/plane/preflight.js +19 -0
  113. package/build/plane/terminal-run-cleanup.js +5 -1
  114. package/build/plane/terminal-run-status.js +4 -0
  115. package/build/printed-remedy-commands.js +31 -4
  116. package/build/readiness-check.js +1 -78
  117. package/build/readiness-prerequisites.generated.js +199 -0
  118. package/build/readme.generated.js +1 -1
  119. package/build/repository-toolchains.js +623 -0
  120. package/build/setup-change-policy.js +32 -0
  121. package/build/setup-epic.js +26 -9
  122. package/build/setup-question.js +62 -0
  123. package/build/start-tickets.js +4 -0
  124. package/build/test-command-detection.js +61 -80
  125. package/build/test-support/notes-fs.js +40 -0
  126. package/build/ticket-delivery-artifacts.js +7 -0
  127. package/build/ticket-delivery-enrollment.js +80 -4
  128. package/build/ticket-delivery-run-scope.js +128 -0
  129. package/build/version.generated.js +3 -3
  130. package/build/worker-guard-hook-bin.js +2 -2
  131. package/build/worktrees.js +105 -0
  132. package/docs/EPIC-IMPLEMENTER.md +43 -0
  133. package/docs/epic-implementer/getting-started.md +95 -14
  134. package/package.json +2 -2
@@ -22,6 +22,7 @@ import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance, renderWor
22
22
  * read-only viewer tabs wired around every spawned worker.
23
23
  */
24
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";
25
26
  import { provisionWorktreeSettingsExclude } from "./permissions.js";
26
27
  import os from "node:os";
27
28
  import { runHeartbeatLoop, sendImmediateHeartbeat } from "./heartbeat.js";
@@ -36,11 +37,12 @@ import { resolveExecutorAgentAdapter } from "../agent-launchers/executor-adapter
36
37
  import { redactAdapterDiagnostic } from "../agent-launchers/executor-adapter.js";
37
38
  import { resolveExecutorAgentId } from "./agent-identity.js";
38
39
  import { closeStdinBounded, createProcessTerminationController, runProcessWithTimeout, writeStdinBounded, } from "./process.js";
39
- import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, verificationVerdictFromFacts, } from "./completion-contract.js";
40
+ import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, unresolvedRequiredTasks, verificationVerdictFromFacts, } from "./completion-contract.js";
40
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";
41
42
  import { compareFinalArtifact, createRequiredVerificationRunner, createSupervisedCommandLauncher, observeFinalArtifact, OWNERSHIP_POLL_MS, preCheckArtifactState, toCompletionCheckFact, } from "./required-verification.js";
42
43
  import { createClosureSupervisor, createRequiredWorkLedger } from "./required-work-ledger.js";
43
- import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
44
+ import { COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT, requiredWorkKindTokens, } from "./required-work-diagnostics.js";
45
+ import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withExecutorJobId, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
44
46
  import { resolveCompletionEvidenceCapability } from "../agent-launchers/executor-adapter.js";
45
47
  import { autoCheckpointDirtyState, PRIOR_ATTEMPT_WIP_COMMIT_MESSAGE, prepareResumeSpawn, prepareRetainedContinuationWorktree, readContinuationBinding, verifyContinuationHeadLineage, } from "./resume-pre-spawn.js";
46
48
  import { buildEpicWorkaroundWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
@@ -53,6 +55,9 @@ import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArt
53
55
  import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
54
56
  import { removeStaleVerdictArtifacts } from "./stale-artifacts.js";
55
57
  import { stripWorkerEnvFiles } from "./env-file-guard.js";
58
+ import { buildDependencyInstallEnv, payloadCiDatabase, payloadDependencyInstallOption, payloadWorkerEnvOption, validateDependencyInstallDeclarations, } from "./env.js";
59
+ import { refreshDeclaredDependencies } from "./dependency-refresh.js";
60
+ import { readVerificationHints } from "./verification-hints.js";
56
61
  import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine, } from "./worker-database.js";
57
62
  import { formatWorkerCliLauncherUnavailableLine } from "./worker-cli-launcher.js";
58
63
  import { isVerdictJobType, readVerdictArtifact } from "./verdict-artifact.js";
@@ -69,12 +74,13 @@ import { deliveryHoldOf, readFocusedPullRequest, resolveOriginBranchSha, validat
69
74
  import { DELIVERY_OUTCOME_READ_TIMEOUT_MS, fetchServerDeliveryOutcome, } from "./delivery-outcome.js";
70
75
  import { FOCUSED_REBASE_JOB_TYPE, focusedRebaseContextError, hasFocusedRebaseContext, validateFocusedRebaseContext, waitForFocusedRebase, } from "./rebase-finalization.js";
71
76
  import { ensureExecutorWorktree, finalizeRetainedExecutorWorktree, } from "./worktree.js";
72
- import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
77
+ import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, renderRequiredBeforePush, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
73
78
  import { CORRECTION_INTENT_CAPABILITY, isRemainingWork, validateCorrectionIntent, } from "./correction-dispatch.js";
74
79
  import { collectGitTelemetry, collectRemoteTrackingSha, createMcpSurfaceObserver, evaluatePreSpawnGitVerification, formatWorkerRateLimitAdvisory, normalizeMcpServerNames, } from "./observation.js";
75
80
  import { failureReasonCode, isFailureReasonCode } from "./failure-reason-codes.js";
76
81
  import { readCustomizedCommands, TERMINAL_CAPACITY_PROTOCOL_VERSIONS, TERMINAL_CAPACITY_RUNTIME_CONTRACTS, TERMINAL_CAPACITY_RUNTIMES, } from "./types.js";
77
82
  import { resolvePackagedRecipes } from "./packaged-recipe.js";
83
+ import { recordObservedPr, recordVerificationFacts, recordVerificationObservation, withDeliveryObservations, } from "./delivery-observations.js";
78
84
  import { probeInstalledCorrectionHook } from "./preflight.js";
79
85
  import { isRecognizedServerName, MCP_SERVER_NAME } from "../mcp-identity.js";
80
86
  /**
@@ -109,6 +115,17 @@ const DELIVERY_OUTCOME_EXCLUDED_JOB_TYPES = new Set([
109
115
  "reconcile_overlap",
110
116
  "ci_fix",
111
117
  ]);
118
+ /**
119
+ * BAPI-1563: whether a server assessment permits an implementation job to report
120
+ * success: bound, available, and the boundary outcome is `awaiting_post_pr` or
121
+ * `complete`. Permission, not proof of verification.
122
+ */
123
+ function serverOutcomePermitsSuccess(outcome) {
124
+ return (outcome !== undefined &&
125
+ outcome.bound === true &&
126
+ outcome.unavailable !== true &&
127
+ (outcome.outcome === "awaiting_post_pr" || outcome.outcome === "complete"));
128
+ }
112
129
  /** BAPI-1426: the outcome used when the read could not run or failed. */
113
130
  const DELIVERY_OUTCOME_UNAVAILABLE = { bound: "unknown", unavailable: true };
114
131
  /**
@@ -162,6 +179,16 @@ function withFailureTelemetry(snapshot, failureTelemetry) {
162
179
  return failureTelemetry ? { ...snapshot, ...failureTelemetry } : snapshot;
163
180
  }
164
181
  /** ProcessClassification maps 1:1 onto the wire ExecutorClassification. */
182
+ /**
183
+ * BAPI-1554 — `; unresolved: <sorted tokens>` for the required work an envelope
184
+ * still lists as unresolved, or the empty string when there is none (so today's
185
+ * message stays byte-for-byte). Closed tokens only: never a task id, command,
186
+ * prompt, or output.
187
+ */
188
+ function unresolvedKindsSuffix(envelope) {
189
+ const tokens = requiredWorkKindTokens(unresolvedRequiredTasks(envelope).map((task) => task.kind));
190
+ return tokens.length > 0 ? `; unresolved: ${tokens.join(", ")}` : "";
191
+ }
165
192
  function toWireClassification(c) {
166
193
  return c;
167
194
  }
@@ -856,6 +883,12 @@ export async function runClaimedJob(job, httpClient, options, deps, _report, sea
856
883
  */
857
884
  control) {
858
885
  const { ownership, observation } = createJobRunState(options, deps);
886
+ // BAPI-1563: every terminal report of this job carries the pull request the
887
+ // executor discovered and the supplementary observations it accumulated, including
888
+ // failures emitted before finalization, from a catch block, a supervision stop or
889
+ // cleanup. Wrapped ONCE so it is structural, not a per-site duty. Serialization is
890
+ // gated on the claim's capability by the HTTP client; nothing here grants anything.
891
+ httpClient = withDeliveryObservations(httpClient);
859
892
  // BAPI-1301: a covered claim must carry an envelope on EVERY terminal report,
860
893
  // including the many refusals that happen before a worker exists (worktree
861
894
  // preparation, pre-spawn verification, MCP registration, …). Without one the
@@ -2344,6 +2377,18 @@ export function formatPreSpawnRefusalLine(job, reason, telemetry) {
2344
2377
  return (`pre-spawn verification refused job_id=${job.id} reason=${code} ` +
2345
2378
  `dirty_paths=${JSON.stringify(paths)} dirty_paths_overflow_count=${overflow}`);
2346
2379
  }
2380
+ /**
2381
+ * In-process reporting policy, never serialized: failure objects registered here
2382
+ * leave `worker_diagnostics.final_message_excerpt` null on the outgoing `/fail`
2383
+ * copy, while executor-owned `attempt_log` metadata may still be attached. Marker
2384
+ * storage stays in this WeakSet so no field, symbol, option, or argument enters
2385
+ * the failure body or the shared HTTP client interface.
2386
+ */
2387
+ const failuresWithoutWorkerFinalMessageExcerpt = new WeakSet();
2388
+ function withoutWorkerFinalMessageExcerpt(failure) {
2389
+ failuresWithoutWorkerFinalMessageExcerpt.add(failure);
2390
+ return failure;
2391
+ }
2347
2392
  /** Reserve the branch before Worktrunk can mutate it; lock an existing tree before preparation. */
2348
2393
  async function runSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver) {
2349
2394
  const originalHttp = httpClient;
@@ -2352,8 +2397,18 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2352
2397
  let telemetry = { ...body.telemetry, ...observation.snapshot() };
2353
2398
  try {
2354
2399
  const diagnostics = observation.workerDiagnostics();
2355
- if (diagnostics)
2400
+ if (diagnostics && failuresWithoutWorkerFinalMessageExcerpt.has(body)) {
2401
+ // Opted-out failure: send a copy with the excerpt nulled, and drop the
2402
+ // diagnostics entirely when no attempt log is left to report. Assigned
2403
+ // after the merge above so nothing can restore the original excerpt.
2404
+ const { worker_diagnostics: _restored, ...rest } = telemetry;
2405
+ telemetry = diagnostics.attempt_log !== null
2406
+ ? { ...rest, worker_diagnostics: { ...diagnostics, final_message_excerpt: null } }
2407
+ : rest;
2408
+ }
2409
+ else if (diagnostics) {
2356
2410
  telemetry = { ...telemetry, worker_diagnostics: diagnostics };
2411
+ }
2357
2412
  }
2358
2413
  catch {
2359
2414
  if (!diagnosticWarningSent) {
@@ -2872,6 +2927,90 @@ resolvedTimeoutSeconds) {
2872
2927
  const WORKER_RESOURCE_JOB_TYPES = new Set([
2873
2928
  "implement", "resume", "remediate", "ci_fix", "rebase",
2874
2929
  ]);
2930
+ /**
2931
+ * BAPI-1551: the pre-spawn dependency refresh, supervised exactly like
2932
+ * {@link prepareWorkerResources}: the job's lease, the server stop signal, and the
2933
+ * job timeout keep their existing outcomes, and an executor shutdown aborts the
2934
+ * install through the live-worker registry. Every refresh failure is fail-open:
2935
+ * the result carries stale records for LOCAL ENVIRONMENT LIMITS and the worker
2936
+ * still spawns. An unexpected throw from the seam degrades to "no stale records".
2937
+ */
2938
+ async function prepareDependencyRefresh(params) {
2939
+ const { job, deps } = params;
2940
+ const shutdown = new AbortController();
2941
+ const deregister = params.control?.liveWorkers.register({
2942
+ requestTermination: () => shutdown.abort(),
2943
+ });
2944
+ let phase;
2945
+ try {
2946
+ phase = await superviseDriverPhase({
2947
+ job,
2948
+ httpClient: params.httpClient,
2949
+ options: params.options,
2950
+ deps,
2951
+ ownership: params.ownership,
2952
+ observation: params.observation,
2953
+ control: params.control,
2954
+ timeoutSeconds: Math.max(1, Math.ceil(params.remainingMs() / 1000)),
2955
+ collectTelemetry: params.collectTelemetry,
2956
+ run: async (signal) => {
2957
+ // Combined by hand: `AbortSignal.any` is not available on Node 18.
2958
+ const combined = new AbortController();
2959
+ const abortCombined = () => combined.abort();
2960
+ if (signal.aborted || shutdown.signal.aborted)
2961
+ combined.abort();
2962
+ signal.addEventListener("abort", abortCombined, { once: true });
2963
+ shutdown.signal.addEventListener("abort", abortCombined, { once: true });
2964
+ const result = await params.refresh({
2965
+ jobId: String(job.id),
2966
+ entries: params.entries,
2967
+ worktreePath: params.worktreePath,
2968
+ mainCheckoutPath: deps.cwd,
2969
+ env: buildDependencyInstallEnv(deps.env, job.payload),
2970
+ remainingMs: params.remainingMs(),
2971
+ now: deps.now,
2972
+ sleep: deps.sleep,
2973
+ signal: combined.signal,
2974
+ log: (message) => deps.errorLog(message),
2975
+ platform: deps.platform,
2976
+ ...(deps.runDependencyInstall ? { runInstall: deps.runDependencyInstall } : {}),
2977
+ });
2978
+ return result.stale;
2979
+ },
2980
+ });
2981
+ }
2982
+ finally {
2983
+ deregister?.();
2984
+ }
2985
+ if (phase.kind === "abandoned") {
2986
+ return { kind: "interrupted", result: { status: "abandoned", reason: params.ownership.abandonReason } };
2987
+ }
2988
+ if (phase.kind === "server_stop") {
2989
+ await params.httpClient.fail(job, {
2990
+ error_kind: "ServerStopRequested",
2991
+ error_message: "the server requested this run stop before the worker started",
2992
+ classification: "killed",
2993
+ telemetry: params.observation.snapshot(),
2994
+ });
2995
+ params.ownership.abandoned = true;
2996
+ params.ownership.abandonReason = "server_stop";
2997
+ return { kind: "interrupted", result: { status: "abandoned", reason: "server_stop" } };
2998
+ }
2999
+ if (phase.kind === "timeout") {
3000
+ await params.httpClient.fail(job, {
3001
+ error_kind: "Timeout",
3002
+ error_message: `${job.job_type} exceeded the job timeout before the worker started`,
3003
+ classification: "timeout",
3004
+ telemetry: params.observation.snapshot(),
3005
+ });
3006
+ return { kind: "interrupted", result: { status: "failed", reason: "timeout" } };
3007
+ }
3008
+ // A shutdown during the refresh keeps the existing shutdown semantics: the
3009
+ // sticky registry terminates the worker on registration anyway.
3010
+ if (phase.kind === "error")
3011
+ return { kind: "ready", stale: [] };
3012
+ return { kind: "ready", stale: phase.value };
3013
+ }
2875
3014
  /**
2876
3015
  * BAPI-1479 — provision the job's disposable database and own-build launcher
2877
3016
  * before the worker's spawn shape is built.
@@ -2897,6 +3036,8 @@ async function prepareWorkerResources(params) {
2897
3036
  let target;
2898
3037
  let disposeLauncher;
2899
3038
  let launcherDirectory;
3039
+ let unavailableCategory;
3040
+ let unavailableCause;
2900
3041
  let released = false;
2901
3042
  lifecycle.releaseWorkerResources = async () => {
2902
3043
  if (released)
@@ -2941,14 +3082,22 @@ async function prepareWorkerResources(params) {
2941
3082
  shutdown.signal.addEventListener("abort", abortCombined, { once: true });
2942
3083
  const cancel = combined.signal;
2943
3084
  const provisioned = await resources
2944
- .provisionDatabase({ jobId, worktreePath: params.worktreePath, signal: cancel })
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
+ })
2945
3092
  .catch(() => ({ kind: "unavailable", category: "create_failed" }));
2946
3093
  if (provisioned.kind === "provisioned") {
2947
3094
  target = provisioned.target;
2948
3095
  }
2949
3096
  else {
3097
+ unavailableCategory = provisioned.category;
3098
+ unavailableCause = "cause" in provisioned ? provisioned.cause : undefined;
2950
3099
  try {
2951
- deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category));
3100
+ deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category, unavailableCause));
2952
3101
  // A created database whose rollback failed stays for the host operator.
2953
3102
  if ("retainedName" in provisioned && provisioned.retainedName) {
2954
3103
  deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, provisioned.retainedName));
@@ -3014,8 +3163,35 @@ async function prepareWorkerResources(params) {
3014
3163
  kind: "ready",
3015
3164
  ...(target ? { workerDatabase: target } : {}),
3016
3165
  ...(launcherDirectory ? { workerLauncherDirectory: launcherDirectory } : {}),
3166
+ ...(!target && unavailableCategory ? { workerDatabaseUnavailableCategory: unavailableCategory } : {}),
3167
+ ...(!target && unavailableCategory && unavailableCause
3168
+ ? { workerDatabaseUnavailableCause: unavailableCause } : {}),
3017
3169
  };
3018
3170
  }
3171
+ /**
3172
+ * BAPI-1522: the filesystem-backed executable check for the LOCAL ENVIRONMENT
3173
+ * LIMITS section. It never executes anything: it resolves symlinks, requires a
3174
+ * regular file with execute permission, and, when asked, requires the resolved
3175
+ * file to stay inside the worktree. Any filesystem error means "not runnable".
3176
+ */
3177
+ export const fileSystemExecutableCheck = (candidate, options) => {
3178
+ try {
3179
+ const resolved = realpathSync(candidate);
3180
+ if (options?.withinDirectory !== undefined) {
3181
+ const root = realpathSync(options.withinDirectory);
3182
+ const relative = path.relative(root, resolved);
3183
+ if (relative.startsWith("..") || path.isAbsolute(relative))
3184
+ return false;
3185
+ }
3186
+ if (!statSync(resolved).isFile())
3187
+ return false;
3188
+ accessSync(resolved, fsConstants.X_OK);
3189
+ return true;
3190
+ }
3191
+ catch {
3192
+ return false;
3193
+ }
3194
+ };
3019
3195
  function retainedHeadPublisher(params) {
3020
3196
  return async () => {
3021
3197
  const { job, branch, worktreePath, prep, deps, ownership, observation, remainingMs } = params;
@@ -3078,7 +3254,10 @@ async function runPreparedSpawn(params) {
3078
3254
  !prep.ciFix &&
3079
3255
  !prep.focusedRebase &&
3080
3256
  !isRemainingWork(job.job_type, job.payload)) {
3081
- prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key)}`;
3257
+ // BAPI-1544: a present boolean states the run's setting; an absent key (a job from
3258
+ // an older API) stays absent so the instruction keeps its conditional wording.
3259
+ const handoffEnabled = job.payload?.verification_handoff_enabled;
3260
+ prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key, typeof handoffEnabled === "boolean" ? handoffEnabled : undefined)}`;
3082
3261
  }
3083
3262
  // --- Timeout contract ------------------------------------------------
3084
3263
  const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
@@ -3573,7 +3752,37 @@ async function runPreparedSpawn(params) {
3573
3752
  // fresh resources; nothing is recovered from an earlier execution's state.
3574
3753
  // Driver-owned jobs (their worker runs a server-rendered reconciliation) and
3575
3754
  // verdict-only jobs keep the sentinel database.
3755
+ // --- Dependency refresh (BAPI-1551) -----------------------------------
3756
+ // Runs only for a non-driver worker job whose payload OWNS `dependency_install`
3757
+ // with at least one admitted entry, after the worktree is ensured and locked
3758
+ // and BEFORE worker resources: database provisioning runs the repository's own
3759
+ // migration code, which must see the refreshed dependencies. A repository with
3760
+ // no declaration performs no new filesystem or process operation here.
3761
+ let staleDependencies = [];
3762
+ const workerResourceJob = !driver && WORKER_RESOURCE_JOB_TYPES.has(job.job_type);
3763
+ if (workerResourceJob) {
3764
+ const declared = payloadDependencyInstallOption(job.payload);
3765
+ if (Object.prototype.hasOwnProperty.call(declared, "dependencyInstall")) {
3766
+ const entries = validateDependencyInstallDeclarations(declared.dependencyInstall, (m) => deps.errorLog(m));
3767
+ if (entries.length > 0) {
3768
+ const refreshed = await prepareDependencyRefresh({
3769
+ job, httpClient, options: jobOptions, deps, ownership, observation, control,
3770
+ worktreePath, remainingMs, collectTelemetry: driverTelemetry, entries,
3771
+ refresh: seams.refreshDependencies ?? refreshDeclaredDependencies,
3772
+ });
3773
+ if (refreshed.kind === "interrupted") {
3774
+ await closeWorkerLog();
3775
+ await finalizeRegistry();
3776
+ return refreshed.result;
3777
+ }
3778
+ staleDependencies = refreshed.stale;
3779
+ }
3780
+ }
3781
+ }
3576
3782
  let workerResources = {};
3783
+ // BAPI-1522: why no database exists (a closed category), kept OUT of the spawn input.
3784
+ let databaseUnavailableCategory;
3785
+ let databaseUnavailableCause;
3577
3786
  if (!driver && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)) {
3578
3787
  const prepared = await prepareWorkerResources({
3579
3788
  job, httpClient, options: jobOptions, deps, ownership, observation, control,
@@ -3588,6 +3797,14 @@ async function runPreparedSpawn(params) {
3588
3797
  ...(prepared.workerDatabase ? { workerDatabase: prepared.workerDatabase } : {}),
3589
3798
  ...(prepared.workerLauncherDirectory ? { workerLauncherDirectory: prepared.workerLauncherDirectory } : {}),
3590
3799
  };
3800
+ databaseUnavailableCategory = prepared.workerDatabaseUnavailableCategory;
3801
+ 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" });
3807
+ }
3591
3808
  }
3592
3809
  const invocation = adapter.headlessInvocation;
3593
3810
  if (invocation?.supported !== true) {
@@ -3600,11 +3817,25 @@ async function runPreparedSpawn(params) {
3600
3817
  });
3601
3818
  return { status: "failed", reason: "executor_adapter_unavailable" };
3602
3819
  }
3820
+ // BAPI-1551: the repository's always-run guards, read through the same parser
3821
+ // likely-tests uses. Read-only, never throws, and an absent or malformed file
3822
+ // or an empty `always` list renders nothing.
3823
+ let requiredReferences = [];
3824
+ if (workerResourceJob) {
3825
+ const hints = await (seams.readVerificationHints ?? deps.readVerificationHints ?? readVerificationHints)(worktreePath)
3826
+ .catch(() => ({ status: "malformed" }));
3827
+ if (hints.status === "ok")
3828
+ requiredReferences = hints.required;
3829
+ }
3603
3830
  let spawnShape;
3604
3831
  try {
3605
3832
  const alias = invocation.value.resolveModelAlias(job.payload);
3606
- spawnShape = invocation.value.buildSpawnShape({
3607
- prompt,
3833
+ // BAPI-1522 — LOCAL ENVIRONMENT LIMITS is the LAST prompt section. It is built
3834
+ // here, after resources, worktree, environment, prompt expansion, and approved
3835
+ // guidance are final, from the PATH the adapter will really hand the worker.
3836
+ // The section is appended exactly once, and nothing after this point changes
3837
+ // the prompt text.
3838
+ const shapeInput = {
3608
3839
  // BAPI-1301: a covered attempt sends the prompt on a held stdin instead
3609
3840
  // of argv; every other job keeps the byte-identical legacy argv.
3610
3841
  ...(covered ? { promptTransport: "stdin-stream-json" } : {}),
@@ -3625,7 +3856,43 @@ async function runPreparedSpawn(params) {
3625
3856
  ...(driverStep ? { declaredTouchedFiles: driverStep.declaredTouchedFiles } : {}),
3626
3857
  // BAPI-1479 — explicit, executor-provisioned values; never read from `parentEnv`.
3627
3858
  ...workerResources,
3859
+ // BAPI-1521 — forwarded only when the payload OWNS the key, for every worker
3860
+ // job type. Absent keeps the legacy compatibility constants; a present
3861
+ // value, even `[]` or a malformed one, replaces them.
3862
+ ...payloadWorkerEnvOption(job.payload),
3628
3863
  parentEnv: deps.env,
3864
+ };
3865
+ // The PATH the worker will receive: the launcher directory (when provisioned)
3866
+ // first, then the inherited PATH, exactly as `env.ts` composes it. The runner
3867
+ // builds no worker environment itself (BAPI-781), so this only mirrors that
3868
+ // rule for the read-only limits check.
3869
+ const inheritedPath = deps.env.PATH;
3870
+ const workerEnvPath = workerResources.workerLauncherDirectory
3871
+ ? (typeof inheritedPath === "string" && inheritedPath.length > 0
3872
+ ? `${workerResources.workerLauncherDirectory}${path.delimiter}${inheritedPath}`
3873
+ : workerResources.workerLauncherDirectory)
3874
+ : inheritedPath;
3875
+ const reproduceCommands = job.payload && typeof job.payload === "object"
3876
+ ? job.payload.reproduce_commands : undefined;
3877
+ const limits = renderLocalEnvironmentLimits({
3878
+ databaseAvailable: workerResources.workerDatabase !== undefined,
3879
+ ...(databaseUnavailableCategory && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3880
+ ? { databaseUnavailableCategory } : {}),
3881
+ ...(databaseUnavailableCause && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3882
+ ? { databaseUnavailableCause } : {}),
3883
+ reproduceCommands,
3884
+ ...(typeof workerEnvPath === "string" ? { workerPath: workerEnvPath } : {}),
3885
+ worktreePath,
3886
+ isExecutable: seams.executableCheck ?? fileSystemExecutableCheck,
3887
+ ...(workerResourceJob ? { ciDatabase: payloadCiDatabase(job.payload) } : {}),
3888
+ ...(staleDependencies.length > 0 ? { staleDependencyCwds: staleDependencies } : {}),
3889
+ });
3890
+ // BAPI-1551: REQUIRED BEFORE PUSH sits immediately before LOCAL ENVIRONMENT
3891
+ // LIMITS, which stays last. With neither, the prompt is byte-identical.
3892
+ const required = renderRequiredBeforePush(requiredReferences);
3893
+ spawnShape = invocation.value.buildSpawnShape({
3894
+ prompt: [prompt, required, limits].filter((section) => section.length > 0).join("\n\n"),
3895
+ ...shapeInput,
3629
3896
  });
3630
3897
  assertUsableSpawnShape(spawnShape, adapter);
3631
3898
  }
@@ -3869,7 +4136,7 @@ async function runPreparedSpawn(params) {
3869
4136
  const legacyLineFeeder = legacyLedger ? createLedgerLineFeeder(legacyLedger) : null;
3870
4137
  let proc;
3871
4138
  try {
3872
- proc = spawnWorker({ env: spawnShape.env });
4139
+ proc = spawnWorker({ env: withExecutorJobId(spawnShape.env, job.id) });
3873
4140
  }
3874
4141
  catch (err) {
3875
4142
  await closeWorkerLog();
@@ -4175,19 +4442,22 @@ async function runPreparedSpawn(params) {
4175
4442
  // before generic success, the ci_fix artifact merge, or finalization can hide
4176
4443
  // it. Only the fixed kind and message are sent: no event text, command, path,
4177
4444
  // or output. A matching terminal task_notification leaves nothing pending.
4445
+ // The explicit opt-out below overrides the BAPI-1431 diagnostics default, so
4446
+ // no worker final-message excerpt is sent; an executor-generated relative
4447
+ // attempt-log reference may still ride along.
4178
4448
  if (legacyLedger?.observeLiveRequiredWork() === "live_required_work") {
4179
4449
  deps.errorLog(`[executor] job ${job.id}: worker exited cleanly with required background work still live`);
4180
4450
  await finalizeRegistry();
4181
4451
  const terminal = await sendTerminalMutationWithAuthReport({
4182
4452
  kind: "fail",
4183
- send: () => httpClient.fail(job, {
4453
+ send: () => httpClient.fail(job, withoutWorkerFinalMessageExcerpt({
4184
4454
  error_kind: WorkerEndedWithPendingBackgroundWork,
4185
4455
  error_message: WORKER_ENDED_WITH_PENDING_BACKGROUND_WORK_MESSAGE,
4186
4456
  classification: "crashed",
4187
4457
  ...observedExitCode(procResult.exitCode),
4188
4458
  ...commitResidue(git),
4189
4459
  telemetry: observation.snapshot(),
4190
- }),
4460
+ })),
4191
4461
  deps,
4192
4462
  options,
4193
4463
  ownership,
@@ -4222,6 +4492,8 @@ async function runPreparedSpawn(params) {
4222
4492
  lstatPath: deps.lstatPath,
4223
4493
  });
4224
4494
  if ("fields" in ciResult) {
4495
+ // Includes a present normalized no_push_reason; the reader omits absent
4496
+ // diagnostics. Executor-observed identities retain precedence.
4225
4497
  genericResult = {
4226
4498
  ...ciResult.fields,
4227
4499
  ...executorResult,
@@ -4242,20 +4514,20 @@ async function runPreparedSpawn(params) {
4242
4514
  // BAPI-1426: a managed ticket's server-confirmed delivery outcome is read
4243
4515
  // first, so an intentional held checkpoint finalizes as a `/fail` with its
4244
4516
  // completion cause instead of a missing-PR failure or a success.
4245
- const deliveryOutcome = await readDeliveryOutcomeForFinalization({
4246
- job,
4247
- branch,
4248
- deps,
4249
- seams,
4250
- remainingMs,
4251
- resolvedBaseUrl: options.resolvedBaseUrl,
4252
- });
4517
+ //
4518
+ // BAPI-1563: the assessment is read ONCE, inside finalization, after the final
4519
+ // head is proven on origin and the PR is discovered (`refreshDeliveryOutcome`),
4520
+ // never from an earlier verdict taken before the PR existed.
4253
4521
  const finalization = await validateWorkerFinalization({
4254
4522
  job,
4255
4523
  branch,
4256
4524
  worktreePath,
4257
4525
  result: genericResult,
4258
- ...(deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
4526
+ // BAPI-1563: a fresh assessment after the final head and PR are known.
4527
+ refreshDeliveryOutcome: () => readDeliveryOutcomeForFinalization({
4528
+ job, branch, deps, seams, remainingMs, resolvedBaseUrl: options.resolvedBaseUrl,
4529
+ }),
4530
+ onObservedPr: (pr) => recordObservedPr(job, pr),
4259
4531
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, remainingMs, httpClient, options: jobOptions, control }),
4260
4532
  runCommand: deps.runCommand,
4261
4533
  headSha: git.last_commit_sha,
@@ -4642,7 +4914,9 @@ async function runCoveredAttempt(params) {
4642
4914
  const token = createOwnershipToken();
4643
4915
  const tokenDigest = ownershipTokenDigest(token);
4644
4916
  const hostDigest = hostIdentityDigest(os.hostname());
4645
- const workerEnv = withOwnershipTag(spawnShape.env, token);
4917
+ // BAPI-1544: the claimed job's ID, set last from the job row so the worker's MCP
4918
+ // server can register it on the delivery binding. Absent when the ID is unusable.
4919
+ const workerEnv = withExecutorJobId(withOwnershipTag(spawnShape.env, token), job.id);
4646
4920
  const stateDir = resolveExecutorStateDir(buildJobLogRegistryDeps(deps));
4647
4921
  const recordFs = seams.ownershipRecordFs ?? createDefaultOwnershipRecordFs();
4648
4922
  try {
@@ -4881,11 +5155,23 @@ async function runCoveredAttempt(params) {
4881
5155
  // BAPI-1395: a worker that ignores the stdin EOF the completion window sent is
4882
5156
  // ended through the existing termination controller, not a second kill path.
4883
5157
  let postWindowExitTimer;
5158
+ let windowLiveKinds = [];
4884
5159
  const supervisor = createClosureSupervisor({
4885
5160
  ledger,
4886
5161
  deps: stdinDeps,
4887
5162
  ...(params.windowNudge ? { buildWindowNudge: params.windowNudge } : {}),
4888
- onWindowExpiry: () => {
5163
+ onWindowExpiry: (liveKinds) => {
5164
+ // BAPI-1554: keep the closure-time snapshot of running required work for
5165
+ // the executor log and for the failure text of an already-failing attempt.
5166
+ windowLiveKinds = liveKinds;
5167
+ if (liveKinds.length > 0) {
5168
+ try {
5169
+ deps.log(`${COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT}: ${liveKinds.join(", ")}`);
5170
+ }
5171
+ catch {
5172
+ /* a log failure must never break the termination scheduling below */
5173
+ }
5174
+ }
4889
5175
  const graceMs = Math.max(0, Math.min(POST_WINDOW_EXIT_GRACE_MS, plan.workerDeadlineAtMs - deps.now()));
4890
5176
  postWindowExitTimer = deps.setTimer(() => {
4891
5177
  postWindowExitTimer = undefined;
@@ -5048,10 +5334,18 @@ async function runCoveredAttempt(params) {
5048
5334
  const git = observation.git();
5049
5335
  const failWith = async (failure, envelope, extra = {}) => {
5050
5336
  await finalizeRegistry();
5337
+ // BAPI-1554: the primary failure text stays first; the closure-time live-work
5338
+ // snapshot is appended only to an attempt that is failing anyway.
5339
+ const failureWithWindowDiagnostic = windowLiveKinds.length > 0
5340
+ ? {
5341
+ ...failure,
5342
+ error_message: `${failure.error_message} (${COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT}: ${windowLiveKinds.join(", ")})`,
5343
+ }
5344
+ : failure;
5051
5345
  const terminal = await sendTerminalMutationWithAuthReport({
5052
5346
  kind: "fail",
5053
5347
  send: () => httpClient.fail(job, {
5054
- ...failure,
5348
+ ...failureWithWindowDiagnostic,
5055
5349
  ...commitResidue(git),
5056
5350
  telemetry: withFailureTelemetry(observation.snapshot(), failure.telemetry),
5057
5351
  completion_contract: SUPPORTED_COMPLETION_MARKER,
@@ -5288,6 +5582,10 @@ async function runCoveredAttempt(params) {
5288
5582
  };
5289
5583
  verification = verificationVerdictFromFacts(verificationFacts, checks.length);
5290
5584
  }
5585
+ // BAPI-1563: supplementary observation causes derived from the declared-check
5586
+ // facts (timed out, could not run). Facts only: a failed or unrun check is never
5587
+ // turned into a pass here, and the server alone decides what an observation means.
5588
+ recordVerificationFacts(job, verificationFacts);
5291
5589
  // --- Phase 4: finalization (unchanged executor facts) ----------------------------
5292
5590
  const artifacts = await readCompletionArtifacts(worktreePath, deps);
5293
5591
  const executorResult = buildGenericSuccessResult({
@@ -5303,6 +5601,7 @@ async function runCoveredAttempt(params) {
5303
5601
  readFile: deps.readFile,
5304
5602
  lstatPath: deps.lstatPath,
5305
5603
  });
5604
+ // Forward the same validated optional diagnostic on this completion path.
5306
5605
  genericResult =
5307
5606
  "fields" in ciResult
5308
5607
  ? { ...ciResult.fields, ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status }
@@ -5310,20 +5609,23 @@ async function runCoveredAttempt(params) {
5310
5609
  }
5311
5610
  // BAPI-1426: the server-confirmed delivery outcome, read under the same
5312
5611
  // absolute deadline as the finalization reads below.
5313
- const deliveryOutcome = await readDeliveryOutcomeForFinalization({
5314
- job,
5315
- branch,
5316
- deps,
5317
- seams,
5318
- remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()),
5319
- resolvedBaseUrl: options.resolvedBaseUrl,
5320
- });
5612
+ // BAPI-1563: read once, inside finalization, after the final head and the PR are
5613
+ // known (`refreshDeliveryOutcome` below), never from an earlier verdict.
5321
5614
  const finalization = await validateWorkerFinalization({
5322
5615
  job,
5323
5616
  branch,
5324
5617
  worktreePath,
5325
5618
  result: genericResult,
5326
- ...(deliveryOutcome !== undefined ? { deliveryOutcome } : {}),
5619
+ // BAPI-1563: a fresh assessment after the final head and PR are known.
5620
+ refreshDeliveryOutcome: () => readDeliveryOutcomeForFinalization({
5621
+ job,
5622
+ branch,
5623
+ deps,
5624
+ seams,
5625
+ remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()),
5626
+ resolvedBaseUrl: options.resolvedBaseUrl,
5627
+ }),
5628
+ onObservedPr: (pr) => recordObservedPr(job, pr),
5327
5629
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, httpClient, options: jobOptions, control,
5328
5630
  remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()) }),
5329
5631
  callTimeoutMs: () => Math.min(120_000, Math.max(0, plan.deadlineAtMs - deps.now())),
@@ -5364,7 +5666,24 @@ async function runCoveredAttempt(params) {
5364
5666
  const lateStronger = await strongerOutcome();
5365
5667
  if (lateStronger)
5366
5668
  return lateStronger;
5367
- if (finalization.ok && successRefusalReason(envelope) === null) {
5669
+ // BAPI-1563: the executor reports facts and follows the server. When the fresh
5670
+ // server assessment PERMITS publication at this head (`awaiting_post_pr` or
5671
+ // `complete`), a local verification shortfall alone (a failed, unavailable or
5672
+ // unrun declared check) does not turn the report into RequiredCheckFailed: the
5673
+ // job reports success with the discovered PR and the truthful envelope, and the
5674
+ // server decides. The envelope is not rewritten, so the shortfall is never read
5675
+ // as a pass. Any other cause (unfinished work, cleanup, permission) still fails.
5676
+ const serverPermitsPublication = finalization.ok && serverOutcomePermitsSuccess(finalization.deliveryOutcome);
5677
+ // The server accepts this shortfall success only when publication depends on the
5678
+ // carry (`api/routes/executor_jobs.py`, `publication_depends_on_carry`): the
5679
+ // boundary outcome permits publication while the evidence-only outcome does
5680
+ // not. Mirror that rule from the parsed `evidenceOutcome`. When it is absent or
5681
+ // itself permits publication (attended run, switch off, hand-off), the server
5682
+ // would refuse with 409, so keep the existing RequiredCheckFailed report.
5683
+ const evidenceOutcome = finalization.ok ? finalization.deliveryOutcome?.evidenceOutcome : undefined;
5684
+ const publicationDependsOnCarry = evidenceOutcome !== undefined && evidenceOutcome !== "awaiting_post_pr" && evidenceOutcome !== "complete";
5685
+ const verificationShortfallOnly = serverPermitsPublication && publicationDependsOnCarry && envelope.cause === "required_check_failed" && unresolvedRequiredTasks(envelope).length === 0;
5686
+ if (finalization.ok && (successRefusalReason(envelope) === null || verificationShortfallOnly)) {
5368
5687
  const result = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
5369
5688
  const completion = {
5370
5689
  job_type: job.job_type,
@@ -5410,7 +5729,7 @@ async function runCoveredAttempt(params) {
5410
5729
  if (cause) {
5411
5730
  return finish(await failWith({
5412
5731
  error_kind: COMPLETION_CAUSE_ERROR_KINDS[cause],
5413
- error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? cause})`,
5732
+ error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? cause}${unresolvedKindsSuffix(envelope)})`,
5414
5733
  ...observedExit,
5415
5734
  }, envelope));
5416
5735
  }
@@ -5424,7 +5743,7 @@ async function runCoveredAttempt(params) {
5424
5743
  }
5425
5744
  return finish(await failWith({
5426
5745
  error_kind: COMPLETION_CAUSE_ERROR_KINDS.required_work_incomplete,
5427
- error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? "unknown"})`,
5746
+ error_message: `covered attempt did not prove completion (${successRefusalReason(envelope) ?? "unknown"}${unresolvedKindsSuffix(envelope)})`,
5428
5747
  ...observedExit,
5429
5748
  }, envelope));
5430
5749
  }