@bridge_gpt/mcp-server 0.2.72 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -1,10 +1,11 @@
1
1
  import { writeRecentlyFailedTestsFile } from "./recently-failed-tests-file.js";
2
+ import { CI_FIX_PRIOR_TEST_RUNS_PAYLOAD_KEY, ciFixTestRunsFsFromDeps, dispatchedLogicalJob, seedCiFixTestRunsFile, withCiFixTestRuns, } from "./ci-fix-test-runs.js";
2
3
  import { guardedFastForwardPush } from "./guarded-fast-forward-push.js";
3
4
  import { createHash, randomUUID } from "node:crypto";
4
5
  import path from "node:path";
5
6
  import { findWorktreeByBranch, parseGitWorktreePorcelain } from "./worktree-inspection.js";
6
7
  import { resolveExecutorBranch, configureExecutorBranch } from "./worktree.js";
7
- import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance, renderWorkerTimeBudgetGuidance } from "./worker-verification-guidance.js";
8
+ import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance, renderWorkerPushEachCommitGuidance, renderWorkerTimeBudgetGuidance } from "./worker-verification-guidance.js";
8
9
  /**
9
10
  * Claimed-job execution engine (BAPI-534 core, BAPI-535 job behaviors; TDD §7/§8/§9).
10
11
  *
@@ -45,21 +46,24 @@ import { COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT, requiredWorkKindTokens, } from
45
46
  import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withExecutorJobId, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
46
47
  import { resolveCompletionEvidenceCapability } from "../agent-launchers/executor-adapter.js";
47
48
  import { autoCheckpointDirtyState, PRIOR_ATTEMPT_WIP_COMMIT_MESSAGE, prepareResumeSpawn, prepareRetainedContinuationWorktree, readContinuationBinding, verifyContinuationHeadLineage, } from "./resume-pre-spawn.js";
48
- import { buildEpicWorkaroundWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
49
+ import { buildEpicWorkaroundWorkerInstruction, buildEpicCapabilityStatementWorkerInstruction, buildEpicServerWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
50
+ import { createDefaultEpicServerContextDeps, readEpicServerWorkerContext, withEpicServerEnv, } from "./epic-server-context.js";
49
51
  /** BAPI-1399: the job type whose worker implements ticket requirements from scratch. */
50
52
  const WORKAROUND_CONTRACT_JOB_TYPES = new Set(["implement"]);
51
53
  import { defaultResolveBinPath } from "../start-tickets-conductor.js";
52
54
  /** The packaged bin basename of the deterministic worker guard (BAPI-1020). */
53
55
  const WORKER_GUARD_BIN_FILENAME = "worker-guard-hook-bin.js";
54
- import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArtifact, buildSmokeResult, commitResidue, readCompletionArtifacts, resolveJobTimeoutSeconds, } from "./results.js";
56
+ import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArtifact, readCiFixTestRunsArtifact, buildSmokeResult, commitResidue, readCompletionArtifacts, RESULT_JSONB_MAX_BYTES, resolveJobTimeoutSeconds, } from "./results.js";
55
57
  import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
56
58
  import { removeStaleVerdictArtifacts } from "./stale-artifacts.js";
57
59
  import { stripWorkerEnvFiles } from "./env-file-guard.js";
58
- import { buildDependencyInstallEnv, payloadCiDatabase, payloadDependencyInstallOption, payloadWorkerEnvOption, validateDependencyInstallDeclarations, } from "./env.js";
60
+ import { buildDependencyInstallEnv, payloadCiDatabase, payloadDependencyInstallOption, payloadPrePrChecksOption, payloadWorkerEnvOption, validateDependencyInstallDeclarations, } from "./env.js";
61
+ import { validatePrePrCheckDeclarations, withPrePrChecksSummary } from "./pre-pr-checks.js";
59
62
  import { refreshDeclaredDependencies } from "./dependency-refresh.js";
60
63
  import { readVerificationHints } from "./verification-hints.js";
61
64
  import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine, } from "./worker-database.js";
62
65
  import { formatWorkerCliLauncherUnavailableLine } from "./worker-cli-launcher.js";
66
+ import { formatWorkerDatabaseMalformedLine, formatWorkerDatabaseModeLine, formatWorkerDatabaseSkippedObservationLine, payloadWorkerDatabaseConfigOption, payloadWorkerDatabaseMetadata, payloadWorkerDatabaseParse, } from "./worker-database-config.js";
63
67
  import { isVerdictJobType, readVerdictArtifact } from "./verdict-artifact.js";
64
68
  import { createWorkerLogClaimId, createWorkerLogTee, closeWorkerLogTee, distinctWorkerLogSessionIds, formatWorkerLogSessionInvariantWarning, teeAsyncIterable, } from "./worker-log.js";
65
69
  import { acquireExecutorWorktreeLock, } from "./worktree-lock.js";
@@ -74,7 +78,7 @@ import { deliveryHoldOf, readFocusedPullRequest, resolveOriginBranchSha, validat
74
78
  import { DELIVERY_OUTCOME_READ_TIMEOUT_MS, fetchServerDeliveryOutcome, } from "./delivery-outcome.js";
75
79
  import { FOCUSED_REBASE_JOB_TYPE, focusedRebaseContextError, hasFocusedRebaseContext, validateFocusedRebaseContext, waitForFocusedRebase, } from "./rebase-finalization.js";
76
80
  import { ensureExecutorWorktree, finalizeRetainedExecutorWorktree, } from "./worktree.js";
77
- import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, renderRequiredBeforePush, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
81
+ import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, renderPrePrChecks, renderRequiredBeforePush, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
78
82
  import { CORRECTION_INTENT_CAPABILITY, isRemainingWork, validateCorrectionIntent, } from "./correction-dispatch.js";
79
83
  import { collectGitTelemetry, collectRemoteTrackingSha, createMcpSurfaceObserver, evaluatePreSpawnGitVerification, formatWorkerRateLimitAdvisory, normalizeMcpServerNames, } from "./observation.js";
80
84
  import { failureReasonCode, isFailureReasonCode } from "./failure-reason-codes.js";
@@ -302,7 +306,7 @@ function buildJobLogRegistryDeps(deps) {
302
306
  * only correct value is the one the caller threads down from the validated
303
307
  * runtime configuration.
304
308
  */
305
- function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl) {
309
+ function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl, trustedRepoName) {
306
310
  return {
307
311
  readFile: deps.readFile,
308
312
  writeFile: deps.writeFile,
@@ -311,6 +315,11 @@ function buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl) {
311
315
  cwd: deps.cwd,
312
316
  mcpServerInvocation: deps.mcpServerInvocation,
313
317
  bridgeApiBaseUrl,
318
+ // BAPI-1545: the grant file lives under the operator's home. Only the one
319
+ // non-secret path variable the lookup honors is passed, never the ambient env.
320
+ env: deps.env.XDG_CONFIG_HOME !== undefined ? { XDG_CONFIG_HOME: deps.env.XDG_CONFIG_HOME } : {},
321
+ homedir: deps.homedir,
322
+ ...(trustedRepoName !== undefined ? { trustedRepoName } : {}),
314
323
  };
315
324
  }
316
325
  /**
@@ -407,10 +416,19 @@ async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, sea
407
416
  path: worktreePath,
408
417
  };
409
418
  try {
410
- const result = await provision(row, buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl));
419
+ // BAPI-1545: the claimed job's `repo_name` comes from the server's claim
420
+ // response, never from a worktree file, so it is the trusted identity the
421
+ // grant is selected by.
422
+ const result = await provision(row, buildExecutorMcpProvisioningDeps(deps, bridgeApiBaseUrl, job.repo_name));
411
423
  for (const warning of result.warnings ?? []) {
412
424
  deps.errorLog(`MCP provisioning warning: ${warning}`);
413
425
  }
426
+ if (result.mcpGrantRegistration !== undefined) {
427
+ // The grant path is never downgraded to a fail-open warning: a
428
+ // registration that could not be made authoritative is refused by the
429
+ // runner, so a stale or worker-edited file is never spawned.
430
+ return result.mcpGrantRegistration;
431
+ }
414
432
  if (result.status === "spawn-failed") {
415
433
  deps.errorLog(`MCP provisioning did not complete (${result.error ?? "unknown reason"}); continuing fail-open`);
416
434
  }
@@ -422,7 +440,30 @@ async function provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, sea
422
440
  // failure can never leak anything into the executor's own logs.
423
441
  deps.errorLog("MCP provisioning did not complete; continuing fail-open");
424
442
  }
443
+ return null;
444
+ }
445
+ /** Fixed diagnostic when no capability statement line is appended (BAPI-1545). */
446
+ export const CAPABILITY_STATEMENT_NOT_APPENDED_MESSAGE = "capability statement: none appended to the worker prompt (absent, unavailable, or unreadable)";
447
+ /**
448
+ * BAPI-1545: read and render the advisory statement. Never throws; `null` means
449
+ * append nothing.
450
+ */
451
+ async function readCapabilityStatementLine(httpClient, repoName) {
452
+ if (typeof httpClient.readEpicCapabilityStatement !== "function")
453
+ return null;
454
+ try {
455
+ const read = await httpClient.readEpicCapabilityStatement(repoName);
456
+ if (!read.ok || read.state !== "present")
457
+ return null;
458
+ return buildEpicCapabilityStatementWorkerInstruction(read.statement);
459
+ }
460
+ catch {
461
+ return null;
462
+ }
425
463
  }
464
+ /** Fixed, secret-free refusal when the grant-path registration is not authoritative. */
465
+ export const GRANT_MCP_REGISTRATION_UNVERIFIED_MESSAGE = "the MCP grant registration for this worktree could not be written and verified; " +
466
+ "refusing to spawn a worker that could load a stale or edited MCP registration";
426
467
  /**
427
468
  * Confirm the prepared worktree's own `.mcp.json` carries the Bridge shim
428
469
  * registration the worker needs, and capture the spawn contract from it
@@ -660,42 +701,96 @@ function createNoopProcess(deps, durationMs, message) {
660
701
  };
661
702
  }
662
703
  /**
663
- * Bounded newline assembly of worker stdout into whole lines for a
704
+ * Bounded newline assembly of worker stdout into logical lines for a
664
705
  * {@link RequiredWorkLedger} (BAPI-1301 covered path, BAPI-1364 legacy
665
- * observation). A line that outgrows the event bound is handed over once (the
666
- * ledger marks it `stream_oversize`) and the rest of it is discarded up to its
667
- * newline. `onLine` runs after each completed line is ingested.
706
+ * observation; one implementation serves both).
707
+ *
708
+ * A line is assembled whole until its UTF-8 size crosses {@link MAX_EVENT_BYTES}.
709
+ * From then on it is streamed to the ledger's structural reader: the buffered
710
+ * prefix (opening brace included) first, then every later segment of the same
711
+ * line through its newline, however many chunks that takes. Nothing of the tail
712
+ * is discarded, and nothing is ever reinterpreted as a new event. The reader
713
+ * decides, once, when the line ends. `onLine` runs once per completed line, never
714
+ * per chunk. A trailing fragment with no newline is finalized by `flush()` and is
715
+ * never established.
668
716
  */
669
- function createLedgerLineFeeder(ledger, onLine) {
717
+ /** Exported for the feeder's own unit tests; the runner is its only production caller. */
718
+ export function createLedgerLineFeeder(ledger, onLine) {
719
+ const WINDOW_CHARS = 64 * 1024;
670
720
  let lineBuffer = "";
671
- let discardingOversize = false;
721
+ // UTF-8 bytes of `lineBuffer`, counted incrementally; a trailing high
722
+ // surrogate is held back until its pair (or lack of one) is known.
723
+ let lineBytes = 0;
724
+ let carryHigh = false;
725
+ let streaming = false;
726
+ const resetLine = () => {
727
+ lineBuffer = "";
728
+ lineBytes = 0;
729
+ carryHigh = false;
730
+ streaming = false;
731
+ };
732
+ const streamPrefix = () => {
733
+ ledger.beginOversizeLine();
734
+ for (let i = 0; i < lineBuffer.length; i += WINDOW_CHARS) {
735
+ ledger.feedOversizeLineChunk(lineBuffer.slice(i, i + WINDOW_CHARS));
736
+ }
737
+ lineBuffer = "";
738
+ lineBytes = 0;
739
+ carryHigh = false;
740
+ streaming = true;
741
+ };
742
+ const consumeWindow = (w) => {
743
+ if (w.length === 0)
744
+ return;
745
+ if (streaming) {
746
+ ledger.feedOversizeLineChunk(w);
747
+ return;
748
+ }
749
+ const body = (carryHigh ? lineBuffer.slice(-1) : "") + w;
750
+ const endsHigh = (() => {
751
+ const c = w.charCodeAt(w.length - 1);
752
+ return c >= 0xd800 && c <= 0xdbff;
753
+ })();
754
+ lineBytes += Buffer.byteLength(endsHigh ? body.slice(0, -1) : body, "utf8");
755
+ carryHigh = endsHigh;
756
+ lineBuffer += w;
757
+ if (lineBytes + (carryHigh ? 3 : 0) > MAX_EVENT_BYTES)
758
+ streamPrefix();
759
+ };
760
+ const completeLine = () => {
761
+ if (streaming) {
762
+ ledger.endOversizeLine({ newlineTerminated: true });
763
+ }
764
+ else {
765
+ ledger.ingestLine(lineBuffer);
766
+ }
767
+ resetLine();
768
+ onLine?.();
769
+ };
672
770
  return {
673
771
  feed: (chunk) => {
674
- lineBuffer += chunk;
675
- let newline;
676
- while ((newline = lineBuffer.indexOf("\n")) >= 0) {
677
- const line = lineBuffer.slice(0, newline);
678
- lineBuffer = lineBuffer.slice(newline + 1);
679
- if (discardingOversize) {
680
- discardingOversize = false;
681
- continue;
682
- }
683
- ledger.ingestLine(line);
684
- onLine?.();
685
- }
686
- if (!discardingOversize && lineBuffer.length > MAX_EVENT_BYTES) {
687
- ledger.ingestLine(lineBuffer);
688
- lineBuffer = "";
689
- discardingOversize = true;
690
- }
691
- else if (discardingOversize) {
692
- lineBuffer = "";
772
+ let pos = 0;
773
+ while (pos < chunk.length) {
774
+ const newline = chunk.indexOf("\n", pos);
775
+ const end = newline < 0 ? chunk.length : newline;
776
+ for (let w = pos; w < end; w += WINDOW_CHARS)
777
+ consumeWindow(chunk.slice(w, Math.min(end, w + WINDOW_CHARS)));
778
+ if (newline < 0)
779
+ break;
780
+ completeLine();
781
+ pos = newline + 1;
693
782
  }
694
783
  },
695
784
  flush: () => {
696
- if (!discardingOversize && lineBuffer.length > 0)
785
+ if (streaming) {
786
+ ledger.endOversizeLine({ newlineTerminated: false });
787
+ resetLine();
788
+ onLine?.();
789
+ return;
790
+ }
791
+ if (lineBuffer.length > 0)
697
792
  ledger.ingestLine(lineBuffer);
698
- lineBuffer = "";
793
+ resetLine();
699
794
  },
700
795
  };
701
796
  }
@@ -791,6 +886,12 @@ function terminalToRunResult(terminal, successStatus) {
791
886
  // by the wrapper below, before this mapping runs) is what actually
792
887
  // notifies the runner.
793
888
  return { status: "abandoned", reason: "auth_fatal" };
889
+ case "completion_evidence_refused":
890
+ // BAPI-1590: the wrapper below hands this outcome to the caller only when
891
+ // that caller opted into the immediate `/fail` fallback, and that caller
892
+ // handles it before mapping. Reaching here means it did not, so keep the
893
+ // historical reading of a refused `/complete`: a lost claim.
894
+ return { status: "abandoned", reason: "stale_claim" };
794
895
  }
795
896
  }
796
897
  /**
@@ -801,7 +902,13 @@ function terminalToRunResult(terminal, successStatus) {
801
902
  * outcome passes through completely unchanged.
802
903
  */
803
904
  async function sendTerminalMutationWithAuthReport(params, job, control) {
804
- const terminal = await sendTerminalMutationWithRetry(params);
905
+ const { completionEvidenceFallback, ...sendParams } = params;
906
+ const terminal = await sendTerminalMutationWithRetry(sendParams);
907
+ if (terminal.outcome === "completion_evidence_refused" && completionEvidenceFallback !== true) {
908
+ params.ownership.abandoned = true;
909
+ params.ownership.abandonReason = "stale_claim";
910
+ return { outcome: "stale_claim" };
911
+ }
805
912
  if (terminal.outcome === "auth_fatal") {
806
913
  const notice = {
807
914
  jobId: job.id,
@@ -2113,6 +2220,27 @@ async function resumePriorAttemptUnderLock(params) {
2113
2220
  * `renderPromptSpecPrompt`, so untrusted check or ticket text is never
2114
2221
  * re-expanded and never reaches a worker for an unverified checkout.
2115
2222
  */
2223
+ /**
2224
+ * BAPI-1582 — read the worker's `ci_fix` test-run record after exit and return
2225
+ * it only when it is valid for this dispatch's logical job. Fail-open: a
2226
+ * missing, malformed, oversized, unsafe, or other-job record (or a reader that
2227
+ * throws) returns `undefined` and changes nothing else about the job.
2228
+ */
2229
+ async function readForwardableCiFixTestRuns(params) {
2230
+ const { job, ciFix, worktreePath, deps, seams } = params;
2231
+ try {
2232
+ const read = await (seams.readCiFixTestRunsArtifact ?? readCiFixTestRunsArtifact)(worktreePath, dispatchedLogicalJob(job.payload, ciFix), { readFile: deps.readFile, lstatPath: deps.lstatPath });
2233
+ if (read.status === "valid")
2234
+ return read.evidence;
2235
+ if (read.status === "invalid") {
2236
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record ${read.code}; not forwarded`);
2237
+ }
2238
+ }
2239
+ catch {
2240
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record unreadable; not forwarded`);
2241
+ }
2242
+ return undefined;
2243
+ }
2116
2244
  async function renderVerifiedCiFixPrompt(params) {
2117
2245
  const { job, ciFix, worktreePath, branch, baseBranch, deps, seams } = params;
2118
2246
  if (branch.trim() !== ciFix.expectedBranch) {
@@ -2393,8 +2521,11 @@ function withoutWorkerFinalMessageExcerpt(failure) {
2393
2521
  async function runSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver) {
2394
2522
  const originalHttp = httpClient;
2395
2523
  let diagnosticWarningSent = false;
2396
- const failWithTelemetry = async (failedJob, body) => {
2397
- let telemetry = { ...body.telemetry, ...observation.snapshot() };
2524
+ // Merge the sanitized worker diagnostics into one report's telemetry. Shared by
2525
+ // the failure and completion wrappers so both follow the same opt-out rule:
2526
+ // a report registered in the WeakSet never carries the final-message excerpt.
2527
+ const withWorkerDiagnostics = (body, base) => {
2528
+ let telemetry = base;
2398
2529
  try {
2399
2530
  const diagnostics = observation.workerDiagnostics();
2400
2531
  if (diagnostics && failuresWithoutWorkerFinalMessageExcerpt.has(body)) {
@@ -2419,11 +2550,26 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2419
2550
  catch { /* supplemental sink */ }
2420
2551
  }
2421
2552
  }
2553
+ return telemetry;
2554
+ };
2555
+ const failWithTelemetry = async (failedJob, body) => {
2556
+ const telemetry = withWorkerDiagnostics(body, { ...body.telemetry, ...observation.snapshot() });
2422
2557
  return originalHttp.fail(failedJob, { ...body, telemetry });
2423
2558
  };
2559
+ // BAPI-1649: a clean worker exit can still be recorded as a server-side failure
2560
+ // (for example a completion the server refuses), and the diagnostics must reach
2561
+ // that record. Only the diagnostics are added: the completion's other telemetry
2562
+ // and all of its evidence are sent exactly as built.
2563
+ const completeWithTelemetry = async (completedJob, completion) => {
2564
+ const telemetry = withWorkerDiagnostics(completion, { ...completion.telemetry });
2565
+ const hasDiagnostics = Object.prototype.hasOwnProperty.call(telemetry, "worker_diagnostics");
2566
+ return originalHttp.complete(completedJob, hasDiagnostics ? { ...completion, telemetry } : completion);
2567
+ };
2424
2568
  httpClient = new Proxy(originalHttp, { get(target, key) {
2425
2569
  if (key === "fail")
2426
2570
  return failWithTelemetry;
2571
+ if (key === "complete")
2572
+ return completeWithTelemetry;
2427
2573
  const value = Reflect.get(target, key);
2428
2574
  return typeof value === "function" ? value.bind(target) : value;
2429
2575
  } });
@@ -2872,6 +3018,22 @@ resolvedTimeoutSeconds) {
2872
3018
  classification: "crashed" });
2873
3019
  return { status: "failed", reason: "recently_failed_tests_file" };
2874
3020
  }
3021
+ // BAPI-1582: seed the ci_fix test-run record with this repair's logical job
3022
+ // and any valid prior runs the server restored. Fail-open telemetry: a
3023
+ // refused or failed seed is logged by fixed code and the spawn proceeds.
3024
+ if (prep.ciFix) {
3025
+ // Through the executor's injected I/O, never a second filesystem path.
3026
+ const seedFs = ciFixTestRunsFsFromDeps(deps);
3027
+ const seed = seedFs === undefined
3028
+ ? { status: "skipped", code: "fs_unavailable" }
3029
+ : await (seams.seedCiFixTestRunsFile ?? seedCiFixTestRunsFile)(worktreePath, {
3030
+ logicalJob: dispatchedLogicalJob(job.payload, prep.ciFix),
3031
+ prior: job.payload?.[CI_FIX_PRIOR_TEST_RUNS_PAYLOAD_KEY],
3032
+ }, seedFs).catch(() => ({ status: "skipped", code: "seed_threw" }));
3033
+ if (seed.status === "skipped") {
3034
+ deps.errorLog(`[executor] job ${job.id}: ci_fix test-run record not seeded (${seed.code})`);
3035
+ }
3036
+ }
2875
3037
  return await runPreparedSpawn({
2876
3038
  job,
2877
3039
  httpClient,
@@ -2966,7 +3128,7 @@ async function prepareDependencyRefresh(params) {
2966
3128
  entries: params.entries,
2967
3129
  worktreePath: params.worktreePath,
2968
3130
  mainCheckoutPath: deps.cwd,
2969
- env: buildDependencyInstallEnv(deps.env, job.payload),
3131
+ env: buildDependencyInstallEnv(deps.env, job.payload, payloadWorkerDatabaseConfigOption(job.payload)),
2970
3132
  remainingMs: params.remainingMs(),
2971
3133
  now: deps.now,
2972
3134
  sleep: deps.sleep,
@@ -3031,9 +3193,31 @@ async function prepareWorkerResources(params) {
3031
3193
  const { job, deps, lifecycle } = params;
3032
3194
  const jobId = String(job.id);
3033
3195
  const resources = deps.workerResources;
3196
+ // BAPI-1598 — the declaration is parsed once. Only an explicit, valid
3197
+ // `disposable_postgres` payload provisions anything; every other state keeps
3198
+ // the job stack-neutral and never falls back to a Bridge default.
3199
+ const parsed = payloadWorkerDatabaseParse(job.payload);
3200
+ const metadata = payloadWorkerDatabaseMetadata(job.payload);
3201
+ const declared = parsed.classification === "enabled" || parsed.classification === "disabled"
3202
+ ? parsed.config : undefined;
3203
+ const declaration = {
3204
+ workerDatabaseMode: metadata.worker_database_mode,
3205
+ ...(declared ? { workerDatabaseConfig: declared } : {}),
3206
+ };
3207
+ try {
3208
+ // An unconfigured job (no declaration) stays quiet; any declaration is recorded
3209
+ // by mode and live profile revision only.
3210
+ if (metadata.worker_database_mode !== "absent")
3211
+ deps.errorLog(formatWorkerDatabaseModeLine(jobId, metadata));
3212
+ if (parsed.classification === "malformed") {
3213
+ deps.errorLog(formatWorkerDatabaseMalformedLine(jobId, parsed.reason));
3214
+ }
3215
+ }
3216
+ catch { /* sink */ }
3034
3217
  if (!resources)
3035
- return { kind: "ready" };
3218
+ return { kind: "ready", ...declaration };
3036
3219
  let target;
3220
+ let targetRole;
3037
3221
  let disposeLauncher;
3038
3222
  let launcherDirectory;
3039
3223
  let unavailableCategory;
@@ -3043,8 +3227,10 @@ async function prepareWorkerResources(params) {
3043
3227
  if (released)
3044
3228
  return;
3045
3229
  released = true;
3046
- if (target) {
3047
- const dropped = await resources.dropDatabase(target).catch(() => ({ kind: "failed" }));
3230
+ if (target && targetRole !== undefined) {
3231
+ const dropped = await resources
3232
+ .dropDatabase(target, targetRole)
3233
+ .catch(() => ({ kind: "failed" }));
3048
3234
  if (dropped.kind !== "dropped") {
3049
3235
  try {
3050
3236
  deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, target.name));
@@ -3081,17 +3267,24 @@ async function prepareWorkerResources(params) {
3081
3267
  signal.addEventListener("abort", abortCombined, { once: true });
3082
3268
  shutdown.signal.addEventListener("abort", abortCombined, { once: true });
3083
3269
  const cancel = combined.signal;
3084
- const provisioned = await resources
3085
- .provisionDatabase({
3086
- jobId,
3087
- worktreePath: params.worktreePath,
3088
- signal: cancel,
3089
- // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
3090
- ...payloadWorkerEnvOption(job.payload),
3091
- })
3092
- .catch(() => ({ kind: "unavailable", category: "create_failed" }));
3093
- if (provisioned.kind === "provisioned") {
3270
+ const provisioned = parsed.classification === "enabled"
3271
+ ? await resources
3272
+ .provisionDatabase({
3273
+ jobId,
3274
+ worktreePath: params.worktreePath,
3275
+ signal: cancel,
3276
+ config: parsed.config,
3277
+ // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
3278
+ ...payloadWorkerEnvOption(job.payload),
3279
+ })
3280
+ .catch(() => ({ kind: "unavailable", category: "create_failed" }))
3281
+ : undefined;
3282
+ if (provisioned === undefined) {
3283
+ // Nothing was configured to provision: no database resource, no failure to report.
3284
+ }
3285
+ else if (provisioned.kind === "provisioned") {
3094
3286
  target = provisioned.target;
3287
+ targetRole = provisioned.role;
3095
3288
  }
3096
3289
  else {
3097
3290
  unavailableCategory = provisioned.category;
@@ -3161,6 +3354,7 @@ async function prepareWorkerResources(params) {
3161
3354
  // `kind: "error"` is an unexpected throw from the seam itself: degrade.
3162
3355
  return {
3163
3356
  kind: "ready",
3357
+ ...declaration,
3164
3358
  ...(target ? { workerDatabase: target } : {}),
3165
3359
  ...(launcherDirectory ? { workerLauncherDirectory: launcherDirectory } : {}),
3166
3360
  ...(!target && unavailableCategory ? { workerDatabaseUnavailableCategory: unavailableCategory } : {}),
@@ -3243,6 +3437,8 @@ async function runPreparedSpawn(params) {
3243
3437
  // it repairs an existing branch whose pull request already exists, and the PR
3244
3438
  // base contract's "when you open the pull request" instruction would re-add the
3245
3439
  // new-PR step the focused prompt deliberately excludes.
3440
+ // BAPI-1546: `disabled` unless the repository opted in; then injected at spawn.
3441
+ let epicServerContext = { kind: "disabled" };
3246
3442
  let prompt = isImplementationStyleJobType(job.job_type) && !prep.ciFix && !prep.focusedRebase
3247
3443
  ? `${prep.prompt} ${renderWorkerPrBaseGuidance()}`
3248
3444
  : prep.prompt;
@@ -3258,6 +3454,37 @@ async function runPreparedSpawn(params) {
3258
3454
  // an older API) stays absent so the instruction keeps its conditional wording.
3259
3455
  const handoffEnabled = job.payload?.verification_handoff_enabled;
3260
3456
  prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key, typeof handoffEnabled === "boolean" ? handoffEnabled : undefined)}`;
3457
+ // BAPI-1545: an implement job in an epic run gets the owner's advisory
3458
+ // capability statement, read once here with a short timeout. Absent,
3459
+ // unavailable, malformed, or failed reads append nothing (the prompt stays
3460
+ // byte-identical) and log one fixed line. The job proceeds either way.
3461
+ if (job.job_type === "implement" && typeof job.epic_run_id === "string" && job.epic_run_id.length > 0) {
3462
+ const capabilityLine = await readCapabilityStatementLine(httpClient, job.repo_name);
3463
+ if (capabilityLine !== null) {
3464
+ prompt = `${prompt} ${capabilityLine}`;
3465
+ }
3466
+ else {
3467
+ deps.errorLog(CAPABILITY_STATEMENT_NOT_APPENDED_MESSAGE);
3468
+ }
3469
+ }
3470
+ // BAPI-1546: the epic-server turn paragraph, beside the workaround contract,
3471
+ // only for an opted-in repository. One bounded, fail-open read; any failure
3472
+ // is "no opt-in" (or "local, unavailable"), never a failed job or a delay.
3473
+ if (typeof job.epic_run_id === "string" && job.epic_run_id.length > 0) {
3474
+ try {
3475
+ const readContext = seams.readEpicServerContext ??
3476
+ ((repo, runId) => readEpicServerWorkerContext(repo, runId, createDefaultEpicServerContextDeps(deps.env)));
3477
+ epicServerContext = await readContext(job.repo_name, job.epic_run_id);
3478
+ }
3479
+ catch {
3480
+ epicServerContext = { kind: "disabled" };
3481
+ }
3482
+ const epicServerLine = buildEpicServerWorkerInstruction(epicServerContext, job.ticket_key);
3483
+ if (epicServerLine !== null)
3484
+ prompt = `${prompt} ${epicServerLine}`;
3485
+ else
3486
+ epicServerContext = { kind: "disabled" };
3487
+ }
3261
3488
  }
3262
3489
  // --- Timeout contract ------------------------------------------------
3263
3490
  const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
@@ -3372,7 +3599,7 @@ async function runPreparedSpawn(params) {
3372
3599
  // Trusted starter context is appended AFTER packaged-command expansion, never
3373
3600
  // inserted into command arguments or scanned through untrusted server evidence.
3374
3601
  if (job.job_type === "implement" && !isRemainingWork(job.job_type, job.payload)) {
3375
- prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha);
3602
+ prompt += "\n\n" + renderWorkerVerificationGuidance(prep.comparisonSha) + "\n\n" + renderWorkerPushEachCommitGuidance();
3376
3603
  }
3377
3604
  // The locked ci_fix renderer deferred trusted guidance. All existing prompt
3378
3605
  // additions precede comparison guidance and the final total-budget block.
@@ -3529,7 +3756,7 @@ async function runPreparedSpawn(params) {
3529
3756
  // BAPI-727: the validated endpoint travels from executor bootstrap through the
3530
3757
  // runtime options to the generated registration, so the worker's MCP server
3531
3758
  // targets the same Bridge API this executor claimed the job from.
3532
- await provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, options.resolvedBaseUrl);
3759
+ const grantRegistration = await provisionMcpForPreparedSpawn(job, branch, worktreePath, deps, seams, options.resolvedBaseUrl);
3533
3760
  // --- Required Bridge MCP registration (FAIL-CLOSED) -------------------
3534
3761
  // Provisioning itself stays fail-OPEN: a skipped or malformed Tier-2 target is
3535
3762
  // a warning, and every valid worktree-provisioned server is kept. The REQUIRED
@@ -3558,10 +3785,21 @@ async function runPreparedSpawn(params) {
3558
3785
  return { status: "failed", reason: "executor_adapter_unavailable" };
3559
3786
  }
3560
3787
  const registration = await verifyRegistration(worktreePath, deps, mcpScoping.value.requiredServerName);
3561
- if (!registration.ok) {
3788
+ // BAPI-1545: on the grant path the registration must ALSO be the one
3789
+ // provisioning wrote and read back: exactly Bridge plus the granted names. The
3790
+ // expected init-event set is then that verified set, so a granted server that
3791
+ // fails to connect is still expected by name (it never fails the job), and an
3792
+ // extra server cannot appear.
3793
+ const grantMismatch = grantRegistration !== null &&
3794
+ grantRegistration !== undefined &&
3795
+ (!grantRegistration.ok ||
3796
+ (registration.ok &&
3797
+ JSON.stringify([...registration.contract.expectedServerNames].sort()) !==
3798
+ JSON.stringify([...grantRegistration.expectedServerNames].sort())));
3799
+ if (!registration.ok || grantMismatch) {
3562
3800
  await httpClient.fail(job, {
3563
3801
  error_kind: RequiredMcpRegistration,
3564
- error_message: registration.message,
3802
+ error_message: registration.ok ? GRANT_MCP_REGISTRATION_UNVERIFIED_MESSAGE : registration.message,
3565
3803
  classification: "crashed",
3566
3804
  ...commitResidue(preSpawnTelemetry),
3567
3805
  telemetry: observation.snapshot(),
@@ -3779,7 +4017,14 @@ async function runPreparedSpawn(params) {
3779
4017
  }
3780
4018
  }
3781
4019
  }
3782
- let workerResources = {};
4020
+ let workerResources = {
4021
+ // BAPI-1598 — the sentinel protection follows the payload's declaration for EVERY
4022
+ // job type that spawns a worker, not only those that may provision a database.
4023
+ ...payloadWorkerDatabaseConfigOption(job.payload),
4024
+ };
4025
+ // BAPI-1598: the effective mode follows the payload for EVERY job type, so a job that never
4026
+ // prepares worker resources is not told a database it never expected is missing.
4027
+ let workerDatabaseMode = payloadWorkerDatabaseMetadata(job.payload).worker_database_mode;
3783
4028
  // BAPI-1522: why no database exists (a closed category), kept OUT of the spawn input.
3784
4029
  let databaseUnavailableCategory;
3785
4030
  let databaseUnavailableCause;
@@ -3793,17 +4038,35 @@ async function runPreparedSpawn(params) {
3793
4038
  await finalizeRegistry();
3794
4039
  return prepared.result;
3795
4040
  }
4041
+ workerDatabaseMode = prepared.workerDatabaseMode;
3796
4042
  workerResources = {
3797
4043
  ...(prepared.workerDatabase ? { workerDatabase: prepared.workerDatabase } : {}),
4044
+ ...(prepared.workerDatabaseConfig ? { workerDatabaseConfig: prepared.workerDatabaseConfig } : {}),
3798
4045
  ...(prepared.workerLauncherDirectory ? { workerLauncherDirectory: prepared.workerLauncherDirectory } : {}),
3799
4046
  };
3800
4047
  databaseUnavailableCategory = prepared.workerDatabaseUnavailableCategory;
3801
4048
  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" });
4049
+ // BAPI-1609: report the provisioning outcome on every later telemetry
4050
+ // snapshot. Only a genuinely provisioned target sets it; the sentinel
4051
+ // fallback below never does.
4052
+ if (prepared.workerDatabase !== undefined)
4053
+ observation.recordWorkerDatabaseProvisioned();
4054
+ // BAPI-1563: the worker has no database. Report the fact only when CI
4055
+ // confirms it has none either (BAPI-1598): a CI-provided database means the
4056
+ // checks are delegated, and an unknown CI capability is not confirmed absence,
4057
+ // so neither records a gap. This is never a local carry-authority decision.
4058
+ if (workerResources.workerDatabase === undefined) {
4059
+ const ciDatabase = payloadCiDatabase(job.payload);
4060
+ if (ciDatabase === "none") {
4061
+ recordVerificationObservation(job, { cause: "no_database" });
4062
+ }
4063
+ else if (ciDatabase === "provided" || workerDatabaseMode !== "absent") {
4064
+ // An unconfigured job whose CI capability is also unknown has nothing to report.
4065
+ try {
4066
+ deps.errorLog(formatWorkerDatabaseSkippedObservationLine(String(job.id), ciDatabase === "provided" ? "delegated_to_ci" : "ci_database_unknown"));
4067
+ }
4068
+ catch { /* sink */ }
4069
+ }
3807
4070
  }
3808
4071
  }
3809
4072
  const invocation = adapter.headlessInvocation;
@@ -3876,6 +4139,7 @@ async function runPreparedSpawn(params) {
3876
4139
  ? job.payload.reproduce_commands : undefined;
3877
4140
  const limits = renderLocalEnvironmentLimits({
3878
4141
  databaseAvailable: workerResources.workerDatabase !== undefined,
4142
+ ...(workerDatabaseMode !== undefined ? { workerDatabaseMode } : {}),
3879
4143
  ...(databaseUnavailableCategory && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3880
4144
  ? { databaseUnavailableCategory } : {}),
3881
4145
  ...(databaseUnavailableCause && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
@@ -3890,10 +4154,22 @@ async function runPreparedSpawn(params) {
3890
4154
  // BAPI-1551: REQUIRED BEFORE PUSH sits immediately before LOCAL ENVIRONMENT
3891
4155
  // LIMITS, which stays last. With neither, the prompt is byte-identical.
3892
4156
  const required = renderRequiredBeforePush(requiredReferences);
4157
+ // BAPI-1582: an implement job's admitted gate-profile commands follow REQUIRED
4158
+ // BEFORE PUSH. Read only when the payload OWNS `pre_pr_checks`; no admitted
4159
+ // entry renders nothing, so the prompt stays byte-identical. Never the
4160
+ // ci_fix reproduction block.
4161
+ const prePrChecks = job.job_type === "implement"
4162
+ ? renderPrePrChecks(validatePrePrCheckDeclarations(payloadPrePrChecksOption(job.payload), deps.errorLog))
4163
+ : "";
3893
4164
  spawnShape = invocation.value.buildSpawnShape({
3894
- prompt: [prompt, required, limits].filter((section) => section.length > 0).join("\n\n"),
4165
+ prompt: [prompt, required, prePrChecks, limits].filter((section) => section.length > 0).join("\n\n"),
3895
4166
  ...shapeInput,
3896
4167
  });
4168
+ // BAPI-1546: the trusted browser target (and run id for turns), injected AFTER
4169
+ // the environment builder ran, like the job tag. `disabled` leaves the shape untouched.
4170
+ if (epicServerContext.kind !== "disabled" && spawnShape.env) {
4171
+ spawnShape = { ...spawnShape, env: withEpicServerEnv(spawnShape.env, epicServerContext) };
4172
+ }
3897
4173
  assertUsableSpawnShape(spawnShape, adapter);
3898
4174
  }
3899
4175
  catch (err) {
@@ -4506,6 +4782,11 @@ async function runPreparedSpawn(params) {
4506
4782
  genericResult = { ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status };
4507
4783
  }
4508
4784
  }
4785
+ // BAPI-1582: optional, bounded test-run telemetry for a resumed repair.
4786
+ const ciFixTestRuns = prep.ciFix
4787
+ ? await readForwardableCiFixTestRuns({ job, ciFix: prep.ciFix, worktreePath, deps, seams })
4788
+ : undefined;
4789
+ genericResult = withCiFixTestRuns(genericResult, ciFixTestRuns, RESULT_JSONB_MAX_BYTES);
4509
4790
  // BAPI-551: a worker can exit `clean_exit` yet strand its implementation if
4510
4791
  // its push never landed on origin and no PR was opened (e.g. it backgrounded
4511
4792
  // a slow push and returned early). Convert that into a fail-loud executor
@@ -4553,7 +4834,9 @@ async function runPreparedSpawn(params) {
4553
4834
  // finalization failure; it is never rewritten to look like a crash.
4554
4835
  ...observedExitCode(procResult.exitCode),
4555
4836
  ...commitResidue(git),
4556
- telemetry: withFailureTelemetry(observation.snapshot(), finalization.failure.telemetry),
4837
+ // BAPI-1582: a held or failed finalization still carries the
4838
+ // repair's test-run record, so a continuation can restore it.
4839
+ telemetry: withCiFixTestRuns(withFailureTelemetry(observation.snapshot(), finalization.failure.telemetry), ciFixTestRuns, RESULT_JSONB_MAX_BYTES),
4557
4840
  }),
4558
4841
  deps,
4559
4842
  options,
@@ -4621,9 +4904,12 @@ async function runPreparedSpawn(params) {
4621
4904
  // made; worker prose is never admissible here (R14 rule 3). It is omitted
4622
4905
  // rather than set to null when finalization had no PR to verify (a
4623
4906
  // non-implementation job), so the field's presence always means "verified".
4624
- const result = typeof finalization.prUrl === "string"
4907
+ const verifiedResult = typeof finalization.prUrl === "string"
4625
4908
  ? { ...genericResult, pr_url: finalization.prUrl }
4626
4909
  : genericResult;
4910
+ // BAPI-1582: an implement worker's current-head pre-PR record rides as bounded
4911
+ // telemetry, never gate evidence. Missing, stale, or oversized attaches nothing.
4912
+ const result = await attachPrePrChecksTelemetry(job, verifiedResult, worktreePath, git.last_commit_sha, deps);
4627
4913
  const completion = {
4628
4914
  job_type: job.job_type,
4629
4915
  exit_code: procResult.exitCode ?? 0,
@@ -5332,6 +5618,9 @@ async function runCoveredAttempt(params) {
5332
5618
  },
5333
5619
  };
5334
5620
  const git = observation.git();
5621
+ // BAPI-1582: set once the worker's ci_fix test-run record is read, so a held
5622
+ // or refused covered attempt still carries it for a later continuation.
5623
+ let failTestRuns;
5335
5624
  const failWith = async (failure, envelope, extra = {}) => {
5336
5625
  await finalizeRegistry();
5337
5626
  // BAPI-1554: the primary failure text stays first; the closure-time live-work
@@ -5347,7 +5636,7 @@ async function runCoveredAttempt(params) {
5347
5636
  send: () => httpClient.fail(job, {
5348
5637
  ...failureWithWindowDiagnostic,
5349
5638
  ...commitResidue(git),
5350
- telemetry: withFailureTelemetry(observation.snapshot(), failure.telemetry),
5639
+ telemetry: withCiFixTestRuns(withFailureTelemetry(observation.snapshot(), failure.telemetry), failTestRuns, RESULT_JSONB_MAX_BYTES),
5351
5640
  completion_contract: SUPPORTED_COMPLETION_MARKER,
5352
5641
  completion_evidence: envelope,
5353
5642
  ...extra,
@@ -5607,6 +5896,12 @@ async function runCoveredAttempt(params) {
5607
5896
  ? { ...ciResult.fields, ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status }
5608
5897
  : { ...executorResult, [CI_FIX_CLAIMS_STATUS_KEY]: ciResult.status };
5609
5898
  }
5899
+ // BAPI-1582: the same optional test-run telemetry as the legacy completion path.
5900
+ const ciFixTestRuns = prep.ciFix
5901
+ ? await readForwardableCiFixTestRuns({ job, ciFix: prep.ciFix, worktreePath, deps, seams })
5902
+ : undefined;
5903
+ genericResult = withCiFixTestRuns(genericResult, ciFixTestRuns, RESULT_JSONB_MAX_BYTES);
5904
+ failTestRuns = ciFixTestRuns;
5610
5905
  // BAPI-1426: the server-confirmed delivery outcome, read under the same
5611
5906
  // absolute deadline as the finalization reads below.
5612
5907
  // BAPI-1563: read once, inside finalization, after the final head and the PR are
@@ -5683,8 +5978,20 @@ async function runCoveredAttempt(params) {
5683
5978
  const evidenceOutcome = finalization.ok ? finalization.deliveryOutcome?.evidenceOutcome : undefined;
5684
5979
  const publicationDependsOnCarry = evidenceOutcome !== undefined && evidenceOutcome !== "awaiting_post_pr" && evidenceOutcome !== "complete";
5685
5980
  const verificationShortfallOnly = serverPermitsPublication && publicationDependsOnCarry && envelope.cause === "required_check_failed" && unresolvedRequiredTasks(envelope).length === 0;
5686
- if (finalization.ok && (successRefusalReason(envelope) === null || verificationShortfallOnly)) {
5687
- const result = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
5981
+ // BAPI-1590: a shortfall at a pull request the executor verified at the pushed
5982
+ // head is reported as `/complete` first and the SERVER decides; its own read of
5983
+ // the open PR is authoritative, this observation is only publication evidence.
5984
+ // Implementation-style jobs qualify only through the confirmed delivery hold that
5985
+ // finalization let through (`heldAtOpenPr`), never a bare PR number; a `ci_fix`
5986
+ // qualifies through its finalization PR number plus the server-held branch.
5987
+ // Only the two causes the server may lift qualify, and any unfinished required
5988
+ // work still fails.
5989
+ const prBackedShortfallOnly = isPrBackedShortfall(finalization, job, envelope);
5990
+ const shortfallGated = verificationShortfallOnly || prBackedShortfallOnly;
5991
+ if (finalization.ok && (successRefusalReason(envelope) === null || shortfallGated)) {
5992
+ const verifiedResult = typeof finalization.prUrl === "string" ? { ...genericResult, pr_url: finalization.prUrl } : genericResult;
5993
+ // BAPI-1582: bounded pre-PR telemetry, as on the legacy completion path.
5994
+ const result = await attachPrePrChecksTelemetry(job, verifiedResult, worktreePath, git.last_commit_sha, deps);
5688
5995
  const completion = {
5689
5996
  job_type: job.job_type,
5690
5997
  exit_code: procResult.exitCode ?? 0,
@@ -5703,9 +6010,16 @@ async function runCoveredAttempt(params) {
5703
6010
  options,
5704
6011
  ownership: reportOwnership,
5705
6012
  log: deps.log,
6013
+ // BAPI-1590: only a shortfall-gated completion falls back to `/fail`.
6014
+ completionEvidenceFallback: shortfallGated && successRefusalReason(envelope) !== null,
5706
6015
  }, job, control);
5707
- await finalizeRegistry();
5708
- return finish(terminalToRunResult(terminal, "completed"));
6016
+ // BAPI-1590: on a marked refusal the server left the job running, so fall
6017
+ // through and report the SAME envelope once as `/fail` below — no second
6018
+ // finalization, evidence regeneration, worker launch, lease wait, or abandon.
6019
+ if (terminal.outcome !== "completion_evidence_refused") {
6020
+ await finalizeRegistry();
6021
+ return finish(terminalToRunResult(terminal, "completed"));
6022
+ }
5709
6023
  }
5710
6024
  // Not a success. A completion cause (required work, cleanup, verification,
5711
6025
  // permission) outranks the finalization kind; with none, finalization keeps
@@ -5747,3 +6061,43 @@ async function runCoveredAttempt(params) {
5747
6061
  ...observedExit,
5748
6062
  }, envelope));
5749
6063
  }
6064
+ /**
6065
+ * BAPI-1590 — whether a covered attempt's verification shortfall is reported as
6066
+ * `/complete` first because finalization verified a pull request at the pushed head.
6067
+ *
6068
+ * Implementation-style jobs qualify only through the confirmed delivery hold that
6069
+ * finalization let through (`heldAtOpenPr`), never a bare PR number. A `ci_fix` reads
6070
+ * no delivery outcome, so it qualifies through finalization's PR number plus the
6071
+ * server-held branch. Only the two causes the server may lift qualify
6072
+ * (`CARRY_LIFTABLE_CAUSES` in `executor_completion_contract.py`), and unfinished
6073
+ * required work never does. This is only the executor's decision to ASK: the server's
6074
+ * own provider read decides whether the success stands.
6075
+ */
6076
+ export function isPrBackedShortfall(finalization, job, envelope) {
6077
+ if (!finalization.ok)
6078
+ return false;
6079
+ const atPushedHead = finalization.heldAtOpenPr !== undefined ||
6080
+ (job.job_type === "ci_fix" &&
6081
+ typeof finalization.prNumber === "number" &&
6082
+ typeof job.expected_branch === "string" &&
6083
+ job.expected_branch.trim() !== "");
6084
+ return (atPushedHead &&
6085
+ (envelope.cause === "required_check_failed" || envelope.cause === "verification_runner_unavailable") &&
6086
+ unresolvedRequiredTasks(envelope).length === 0);
6087
+ }
6088
+ /**
6089
+ * BAPI-1582 — attach an implement worker's `pre_pr_checks_summary` when its
6090
+ * `.conductor/pre-pr-checks.json` is valid and names the final head. Telemetry
6091
+ * only: any other job type, or any read problem, returns `result` unchanged.
6092
+ */
6093
+ async function attachPrePrChecksTelemetry(job, result, worktreePath, headSha, deps) {
6094
+ if (job.job_type !== "implement")
6095
+ return result;
6096
+ return withPrePrChecksSummary(result, {
6097
+ worktreePath,
6098
+ observedHead: typeof headSha === "string" ? headSha : null,
6099
+ maxResultBytes: RESULT_JSONB_MAX_BYTES,
6100
+ deps: { readFile: deps.readFile, lstatPath: deps.lstatPath },
6101
+ errorLog: (message) => deps.errorLog(`[executor] job ${job.id}: ${message}`),
6102
+ });
6103
+ }