@bridge_gpt/mcp-server 0.2.71 → 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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -8,7 +8,7 @@
8
8
  * logged and never included in any error string.
9
9
  */
10
10
  import { RECONCILER_LIVENESS_VALUES } from "./types.js";
11
- import { EXECUTOR_REPORTABLE_END_CAUSE_VALUES, } from "./completion-contract.js";
11
+ import { EXECUTOR_REPORTABLE_END_CAUSE_VALUES, MAX_VERIFICATION_OBSERVATIONS, } from "./completion-contract.js";
12
12
  import { readEpicRunCompletionState, } from "../conductor/bridge-api-client.js";
13
13
  /** BAPI-1258 — the server's stable `error_code` for refused capacity evidence. */
14
14
  export const UNSUPPORTED_TERMINAL_CAPACITY_ERROR_CODE = "UNSUPPORTED_TERMINAL_CAPACITY";
@@ -128,6 +128,33 @@ export function envelopeForClaim(job, envelope) {
128
128
  const { end_cause: _omitted, ...rest } = envelope;
129
129
  return rest;
130
130
  }
131
+ /**
132
+ * BAPI-1563 — normalize a claim's `delivery_observations_capability`. Only the
133
+ * exact `{protocol_version: 1}` is admitted; absent, null, or anything else (an
134
+ * older server, a future protocol) reads as no capability.
135
+ */
136
+ export function normalizeDeliveryObservationsCapability(value) {
137
+ if (value === null || typeof value !== "object" || Array.isArray(value))
138
+ return null;
139
+ return value.protocol_version === 1 ? { protocol_version: 1 } : null;
140
+ }
141
+ /**
142
+ * BAPI-1563 — the observation fields of a terminal report, present ONLY when the
143
+ * claim advertised the capability. Without it both are omitted, so an older
144
+ * server's strict schema never sees an unknown key. This governs serialization
145
+ * and nothing else: no permission or success decision is derived from it, and a
146
+ * rejection is never parsed or resent.
147
+ */
148
+ function deliveryObservationFields(job, report) {
149
+ if (normalizeDeliveryObservationsCapability(job.delivery_observations_capability) === null)
150
+ return {};
151
+ return {
152
+ ...(report.observed_pr !== undefined ? { observed_pr: report.observed_pr } : {}),
153
+ ...(report.verification_observations !== undefined && report.verification_observations.length > 0
154
+ ? { verification_observations: report.verification_observations.slice(0, MAX_VERIFICATION_OBSERVATIONS) }
155
+ : {}),
156
+ };
157
+ }
131
158
  /** Bound a server-provided diagnostic snippet included in error strings. */
132
159
  function boundedDetail(text) {
133
160
  const trimmed = (text ?? "").trim();
@@ -347,6 +374,11 @@ export function createExecutorHttpClient(config) {
347
374
  // BAPI-1421 (F4): only recognized executor-reportable end causes are
348
375
  // kept; an older server's absent key becomes an empty list.
349
376
  job.end_cause_capability = normalizeEndCauseCapability(job.end_cause_capability);
377
+ // BAPI-1563: the observation capability is normalized in place only when
378
+ // the server sent the key, so an older server's claim keeps its shape.
379
+ if ("delivery_observations_capability" in job) {
380
+ job.delivery_observations_capability = normalizeDeliveryObservationsCapability(job.delivery_observations_capability);
381
+ }
350
382
  job.prior_attempt_head_sha = normalizePriorAttemptHeadSha(job.prior_attempt_head_sha, () => (config.warn ?? ((message) => console.error(message)))(`executor: ignoring malformed prior attempt head in the claim for job ${String(job.id)}; ` +
351
383
  `treating it as a first dispatch.`));
352
384
  return { kind: "claimed", job, reconcilerLiveness };
@@ -504,6 +536,7 @@ export function createExecutorHttpClient(config) {
504
536
  last_commit_sha: completion.last_commit_sha,
505
537
  telemetry: completion.telemetry,
506
538
  ...completionContractFields(job, completion),
539
+ ...deliveryObservationFields(job, completion),
507
540
  };
508
541
  return mutate(`/${job.id}/complete`, body, true, job.repo_name);
509
542
  },
@@ -521,6 +554,7 @@ export function createExecutorHttpClient(config) {
521
554
  last_commit_sha: failure.last_commit_sha,
522
555
  telemetry: failure.telemetry,
523
556
  ...completionContractFields(job, failure),
557
+ ...deliveryObservationFields(job, failure),
524
558
  };
525
559
  if (failure.capacity_evidence === undefined) {
526
560
  return mutate(`/${job.id}/fail`, body, false, job.repo_name);
@@ -17,7 +17,7 @@ export { runExecutor } from "./runner.js";
17
17
  // imports the generator still cannot start a persistent daemon.
18
18
  export { runExecutorInstallServiceCli, getExecutorInstallServiceUsage, buildExecutorServiceArtifact, writeExecutorServiceArtifact, inspectExecutorServiceArtifact, executorLaunchdDirForHome, executorSystemdDirForHome, executorIdFromLaunchdFilename, executorIdFromSystemdFilename,
19
19
  // Programmatic, lifecycle-free plan/write seam (BAPI-779) — how
20
- // `install conductor` reaches the generator without shelling out to the CLI.
20
+ // `install epic-implementer` reaches the generator without shelling out to the CLI.
21
21
  planExecutorServiceInstall, writeExecutorServicePlan, resolvePackagedExecutorInvocation,
22
22
  // Durable-host credential declaration contract (BAPI-1137, R-4). doctor needs
23
23
  // the shared inspector and the postcondition helper so its diagnostic and the
@@ -25,6 +25,7 @@ planExecutorServiceInstall, writeExecutorServicePlan, resolvePackagedExecutorInv
25
25
  // and the argument-contract predicate keeps the contract locally auditable
26
26
  // rather than discoverable only by reading the renderer.
27
27
  inspectExecutorServiceCredentialDeclaration, assertExecutorServiceCredentialPostcondition, checkExecutorServiceArgumentContract, isAllowedExecutorServiceUnitEnvKey, executorLaunchdLogPathsForId, EXECUTOR_SERVICE_BASE_URL_ENV, EXECUTOR_SERVICE_PATH_ENV, EXECUTOR_SERVICE_UNIT_ENV_ALLOWLIST, EXECUTOR_SERVICE_UNIT_FILE_MODE, } from "./service-unit.js";
28
+ export { discoverExecutorServiceUnits } from "./service-discovery.js";
28
29
  // Consented lifecycle (BAPI-779, R-1). Deliberately a SEPARATE module from the
29
30
  // generator above: importing the writer never grants the ability to start a
30
31
  // persistent daemon.
@@ -1,5 +1,5 @@
1
1
  /**
2
- * Executor installation preflight for `install conductor` (BAPI-779).
2
+ * Executor installation preflight for `install epic-implementer` (BAPI-779).
3
3
  *
4
4
  * This is the gate that runs BEFORE the installer writes a service unit or
5
5
  * starts anything: it answers "can this host actually run a conductor executor?"
@@ -37,10 +37,11 @@ import { resolveExecutorAgentAdapter } from "../agent-launchers/executor-adapter
37
37
  import { redactAdapterDiagnostic } from "../agent-launchers/executor-adapter.js";
38
38
  import { resolveExecutorAgentId } from "./agent-identity.js";
39
39
  import { closeStdinBounded, createProcessTerminationController, runProcessWithTimeout, writeStdinBounded, } from "./process.js";
40
- import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, verificationVerdictFromFacts, } from "./completion-contract.js";
40
+ import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresCompletionEvidence, COMPLETION_CONTRACT_MARKER_VALUES, isCoveredJobType, MAX_EVENT_BYTES, runtimeMatchesSupported, successRefusalReason, unresolvedRequiredTasks, verificationVerdictFromFacts, } from "./completion-contract.js";
41
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";
42
42
  import { compareFinalArtifact, createRequiredVerificationRunner, createSupervisedCommandLauncher, observeFinalArtifact, OWNERSHIP_POLL_MS, preCheckArtifactState, toCompletionCheckFact, } from "./required-verification.js";
43
43
  import { createClosureSupervisor, createRequiredWorkLedger } from "./required-work-ledger.js";
44
+ import { COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT, requiredWorkKindTokens, } from "./required-work-diagnostics.js";
44
45
  import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withExecutorJobId, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
45
46
  import { resolveCompletionEvidenceCapability } from "../agent-launchers/executor-adapter.js";
46
47
  import { autoCheckpointDirtyState, PRIOR_ATTEMPT_WIP_COMMIT_MESSAGE, prepareResumeSpawn, prepareRetainedContinuationWorktree, readContinuationBinding, verifyContinuationHeadLineage, } from "./resume-pre-spawn.js";
@@ -54,7 +55,9 @@ import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArt
54
55
  import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
55
56
  import { removeStaleVerdictArtifacts } from "./stale-artifacts.js";
56
57
  import { stripWorkerEnvFiles } from "./env-file-guard.js";
57
- import { payloadWorkerEnvOption } from "./env.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";
58
61
  import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine, } from "./worker-database.js";
59
62
  import { formatWorkerCliLauncherUnavailableLine } from "./worker-cli-launcher.js";
60
63
  import { isVerdictJobType, readVerdictArtifact } from "./verdict-artifact.js";
@@ -71,12 +74,13 @@ import { deliveryHoldOf, readFocusedPullRequest, resolveOriginBranchSha, validat
71
74
  import { DELIVERY_OUTCOME_READ_TIMEOUT_MS, fetchServerDeliveryOutcome, } from "./delivery-outcome.js";
72
75
  import { FOCUSED_REBASE_JOB_TYPE, focusedRebaseContextError, hasFocusedRebaseContext, validateFocusedRebaseContext, waitForFocusedRebase, } from "./rebase-finalization.js";
73
76
  import { ensureExecutorWorktree, finalizeRetainedExecutorWorktree, } from "./worktree.js";
74
- import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
77
+ import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, renderRequiredBeforePush, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
75
78
  import { CORRECTION_INTENT_CAPABILITY, isRemainingWork, validateCorrectionIntent, } from "./correction-dispatch.js";
76
79
  import { collectGitTelemetry, collectRemoteTrackingSha, createMcpSurfaceObserver, evaluatePreSpawnGitVerification, formatWorkerRateLimitAdvisory, normalizeMcpServerNames, } from "./observation.js";
77
80
  import { failureReasonCode, isFailureReasonCode } from "./failure-reason-codes.js";
78
81
  import { readCustomizedCommands, TERMINAL_CAPACITY_PROTOCOL_VERSIONS, TERMINAL_CAPACITY_RUNTIME_CONTRACTS, TERMINAL_CAPACITY_RUNTIMES, } from "./types.js";
79
82
  import { resolvePackagedRecipes } from "./packaged-recipe.js";
83
+ import { recordObservedPr, recordVerificationFacts, recordVerificationObservation, withDeliveryObservations, } from "./delivery-observations.js";
80
84
  import { probeInstalledCorrectionHook } from "./preflight.js";
81
85
  import { isRecognizedServerName, MCP_SERVER_NAME } from "../mcp-identity.js";
82
86
  /**
@@ -111,6 +115,17 @@ const DELIVERY_OUTCOME_EXCLUDED_JOB_TYPES = new Set([
111
115
  "reconcile_overlap",
112
116
  "ci_fix",
113
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
+ }
114
129
  /** BAPI-1426: the outcome used when the read could not run or failed. */
115
130
  const DELIVERY_OUTCOME_UNAVAILABLE = { bound: "unknown", unavailable: true };
116
131
  /**
@@ -164,6 +179,16 @@ function withFailureTelemetry(snapshot, failureTelemetry) {
164
179
  return failureTelemetry ? { ...snapshot, ...failureTelemetry } : snapshot;
165
180
  }
166
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
+ }
167
192
  function toWireClassification(c) {
168
193
  return c;
169
194
  }
@@ -858,6 +883,12 @@ export async function runClaimedJob(job, httpClient, options, deps, _report, sea
858
883
  */
859
884
  control) {
860
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);
861
892
  // BAPI-1301: a covered claim must carry an envelope on EVERY terminal report,
862
893
  // including the many refusals that happen before a worker exists (worktree
863
894
  // preparation, pre-spawn verification, MCP registration, …). Without one the
@@ -2896,6 +2927,90 @@ resolvedTimeoutSeconds) {
2896
2927
  const WORKER_RESOURCE_JOB_TYPES = new Set([
2897
2928
  "implement", "resume", "remediate", "ci_fix", "rebase",
2898
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
+ }
2899
3014
  /**
2900
3015
  * BAPI-1479 — provision the job's disposable database and own-build launcher
2901
3016
  * before the worker's spawn shape is built.
@@ -2922,6 +3037,7 @@ async function prepareWorkerResources(params) {
2922
3037
  let disposeLauncher;
2923
3038
  let launcherDirectory;
2924
3039
  let unavailableCategory;
3040
+ let unavailableCause;
2925
3041
  let released = false;
2926
3042
  lifecycle.releaseWorkerResources = async () => {
2927
3043
  if (released)
@@ -2979,8 +3095,9 @@ async function prepareWorkerResources(params) {
2979
3095
  }
2980
3096
  else {
2981
3097
  unavailableCategory = provisioned.category;
3098
+ unavailableCause = "cause" in provisioned ? provisioned.cause : undefined;
2982
3099
  try {
2983
- deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category));
3100
+ deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category, unavailableCause));
2984
3101
  // A created database whose rollback failed stays for the host operator.
2985
3102
  if ("retainedName" in provisioned && provisioned.retainedName) {
2986
3103
  deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, provisioned.retainedName));
@@ -3047,6 +3164,8 @@ async function prepareWorkerResources(params) {
3047
3164
  ...(target ? { workerDatabase: target } : {}),
3048
3165
  ...(launcherDirectory ? { workerLauncherDirectory: launcherDirectory } : {}),
3049
3166
  ...(!target && unavailableCategory ? { workerDatabaseUnavailableCategory: unavailableCategory } : {}),
3167
+ ...(!target && unavailableCategory && unavailableCause
3168
+ ? { workerDatabaseUnavailableCause: unavailableCause } : {}),
3050
3169
  };
3051
3170
  }
3052
3171
  /**
@@ -3633,9 +3752,37 @@ async function runPreparedSpawn(params) {
3633
3752
  // fresh resources; nothing is recovered from an earlier execution's state.
3634
3753
  // Driver-owned jobs (their worker runs a server-rendered reconciliation) and
3635
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
+ }
3636
3782
  let workerResources = {};
3637
3783
  // BAPI-1522: why no database exists (a closed category), kept OUT of the spawn input.
3638
3784
  let databaseUnavailableCategory;
3785
+ let databaseUnavailableCause;
3639
3786
  if (!driver && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)) {
3640
3787
  const prepared = await prepareWorkerResources({
3641
3788
  job, httpClient, options: jobOptions, deps, ownership, observation, control,
@@ -3651,6 +3798,13 @@ async function runPreparedSpawn(params) {
3651
3798
  ...(prepared.workerLauncherDirectory ? { workerLauncherDirectory: prepared.workerLauncherDirectory } : {}),
3652
3799
  };
3653
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
+ }
3654
3808
  }
3655
3809
  const invocation = adapter.headlessInvocation;
3656
3810
  if (invocation?.supported !== true) {
@@ -3663,6 +3817,16 @@ async function runPreparedSpawn(params) {
3663
3817
  });
3664
3818
  return { status: "failed", reason: "executor_adapter_unavailable" };
3665
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
+ }
3666
3830
  let spawnShape;
3667
3831
  try {
3668
3832
  const alias = invocation.value.resolveModelAlias(job.payload);
@@ -3714,13 +3878,20 @@ async function runPreparedSpawn(params) {
3714
3878
  databaseAvailable: workerResources.workerDatabase !== undefined,
3715
3879
  ...(databaseUnavailableCategory && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3716
3880
  ? { databaseUnavailableCategory } : {}),
3881
+ ...(databaseUnavailableCause && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3882
+ ? { databaseUnavailableCause } : {}),
3717
3883
  reproduceCommands,
3718
3884
  ...(typeof workerEnvPath === "string" ? { workerPath: workerEnvPath } : {}),
3719
3885
  worktreePath,
3720
3886
  isExecutable: seams.executableCheck ?? fileSystemExecutableCheck,
3887
+ ...(workerResourceJob ? { ciDatabase: payloadCiDatabase(job.payload) } : {}),
3888
+ ...(staleDependencies.length > 0 ? { staleDependencyCwds: staleDependencies } : {}),
3721
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);
3722
3893
  spawnShape = invocation.value.buildSpawnShape({
3723
- prompt: limits ? prompt + "\n\n" + limits : prompt,
3894
+ prompt: [prompt, required, limits].filter((section) => section.length > 0).join("\n\n"),
3724
3895
  ...shapeInput,
3725
3896
  });
3726
3897
  assertUsableSpawnShape(spawnShape, adapter);
@@ -4321,6 +4492,8 @@ async function runPreparedSpawn(params) {
4321
4492
  lstatPath: deps.lstatPath,
4322
4493
  });
4323
4494
  if ("fields" in ciResult) {
4495
+ // Includes a present normalized no_push_reason; the reader omits absent
4496
+ // diagnostics. Executor-observed identities retain precedence.
4324
4497
  genericResult = {
4325
4498
  ...ciResult.fields,
4326
4499
  ...executorResult,
@@ -4341,20 +4514,20 @@ async function runPreparedSpawn(params) {
4341
4514
  // BAPI-1426: a managed ticket's server-confirmed delivery outcome is read
4342
4515
  // first, so an intentional held checkpoint finalizes as a `/fail` with its
4343
4516
  // 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
- });
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.
4352
4521
  const finalization = await validateWorkerFinalization({
4353
4522
  job,
4354
4523
  branch,
4355
4524
  worktreePath,
4356
4525
  result: genericResult,
4357
- ...(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),
4358
4531
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, remainingMs, httpClient, options: jobOptions, control }),
4359
4532
  runCommand: deps.runCommand,
4360
4533
  headSha: git.last_commit_sha,
@@ -4982,11 +5155,23 @@ async function runCoveredAttempt(params) {
4982
5155
  // BAPI-1395: a worker that ignores the stdin EOF the completion window sent is
4983
5156
  // ended through the existing termination controller, not a second kill path.
4984
5157
  let postWindowExitTimer;
5158
+ let windowLiveKinds = [];
4985
5159
  const supervisor = createClosureSupervisor({
4986
5160
  ledger,
4987
5161
  deps: stdinDeps,
4988
5162
  ...(params.windowNudge ? { buildWindowNudge: params.windowNudge } : {}),
4989
- 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
+ }
4990
5175
  const graceMs = Math.max(0, Math.min(POST_WINDOW_EXIT_GRACE_MS, plan.workerDeadlineAtMs - deps.now()));
4991
5176
  postWindowExitTimer = deps.setTimer(() => {
4992
5177
  postWindowExitTimer = undefined;
@@ -5149,10 +5334,18 @@ async function runCoveredAttempt(params) {
5149
5334
  const git = observation.git();
5150
5335
  const failWith = async (failure, envelope, extra = {}) => {
5151
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;
5152
5345
  const terminal = await sendTerminalMutationWithAuthReport({
5153
5346
  kind: "fail",
5154
5347
  send: () => httpClient.fail(job, {
5155
- ...failure,
5348
+ ...failureWithWindowDiagnostic,
5156
5349
  ...commitResidue(git),
5157
5350
  telemetry: withFailureTelemetry(observation.snapshot(), failure.telemetry),
5158
5351
  completion_contract: SUPPORTED_COMPLETION_MARKER,
@@ -5389,6 +5582,10 @@ async function runCoveredAttempt(params) {
5389
5582
  };
5390
5583
  verification = verificationVerdictFromFacts(verificationFacts, checks.length);
5391
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);
5392
5589
  // --- Phase 4: finalization (unchanged executor facts) ----------------------------
5393
5590
  const artifacts = await readCompletionArtifacts(worktreePath, deps);
5394
5591
  const executorResult = buildGenericSuccessResult({
@@ -5404,6 +5601,7 @@ async function runCoveredAttempt(params) {
5404
5601
  readFile: deps.readFile,
5405
5602
  lstatPath: deps.lstatPath,
5406
5603
  });
5604
+ // Forward the same validated optional diagnostic on this completion path.
5407
5605
  genericResult =
5408
5606
  "fields" in ciResult
5409
5607
  ? { ...ciResult.fields, ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status }
@@ -5411,20 +5609,23 @@ async function runCoveredAttempt(params) {
5411
5609
  }
5412
5610
  // BAPI-1426: the server-confirmed delivery outcome, read under the same
5413
5611
  // 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
- });
5612
+ // BAPI-1563: read once, inside finalization, after the final head and the PR are
5613
+ // known (`refreshDeliveryOutcome` below), never from an earlier verdict.
5422
5614
  const finalization = await validateWorkerFinalization({
5423
5615
  job,
5424
5616
  branch,
5425
5617
  worktreePath,
5426
5618
  result: genericResult,
5427
- ...(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),
5428
5629
  publishRetainedHead: retainedHeadPublisher({ job, branch, worktreePath, prep, deps, ownership, observation, httpClient, options: jobOptions, control,
5429
5630
  remainingMs: () => Math.max(0, plan.deadlineAtMs - deps.now()) }),
5430
5631
  callTimeoutMs: () => Math.min(120_000, Math.max(0, plan.deadlineAtMs - deps.now())),
@@ -5465,7 +5666,24 @@ async function runCoveredAttempt(params) {
5465
5666
  const lateStronger = await strongerOutcome();
5466
5667
  if (lateStronger)
5467
5668
  return lateStronger;
5468
- 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)) {
5469
5687
  const result = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
5470
5688
  const completion = {
5471
5689
  job_type: job.job_type,
@@ -5511,7 +5729,7 @@ async function runCoveredAttempt(params) {
5511
5729
  if (cause) {
5512
5730
  return finish(await failWith({
5513
5731
  error_kind: COMPLETION_CAUSE_ERROR_KINDS[cause],
5514
- 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)})`,
5515
5733
  ...observedExit,
5516
5734
  }, envelope));
5517
5735
  }
@@ -5525,7 +5743,7 @@ async function runCoveredAttempt(params) {
5525
5743
  }
5526
5744
  return finish(await failWith({
5527
5745
  error_kind: COMPLETION_CAUSE_ERROR_KINDS.required_work_incomplete,
5528
- 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)})`,
5529
5747
  ...observedExit,
5530
5748
  }, envelope));
5531
5749
  }