@bridge_gpt/mcp-server 0.2.70 → 0.2.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +10 -1
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +11 -1
  5. package/build/bounded-wait.js +9 -1
  6. package/build/bridge-permissions.js +13 -5
  7. package/build/commands.generated.js +3 -3
  8. package/build/conductor/bridge-api-client.js +260 -2
  9. package/build/conductor/command-drift-production.js +7 -2
  10. package/build/conductor/doctor.js +9 -3
  11. package/build/conductor/epic-implementer-cli.js +4 -0
  12. package/build/conductor/gate-discovery.js +524 -10
  13. package/build/conductor/gate-settings-review.js +451 -0
  14. package/build/conductor/launch-need-probes.js +16 -11
  15. package/build/conductor/launch-plan.js +145 -0
  16. package/build/conductor/precheck-timings.js +14 -0
  17. package/build/conductor/preview-observations.js +10 -0
  18. package/build/conductor/readiness-sections.js +4 -1
  19. package/build/conductor/recovery-cli.js +59 -2
  20. package/build/conductor/recovery-operations.js +45 -2
  21. package/build/docs.generated.js +1 -1
  22. package/build/drive-epic.js +188 -45
  23. package/build/epic-ci-workflow-drift.js +71 -23
  24. package/build/epic-ci-workflow-install.js +83 -26
  25. package/build/epic-ci-workflow-v1.js +132 -0
  26. package/build/epic-ci-workflow.js +174 -13
  27. package/build/epic-implementer-bin.js +18 -18
  28. package/build/executor/ci-rerun-job.js +220 -14
  29. package/build/executor/env.js +207 -3
  30. package/build/executor/gate-qualification-job.js +20 -5
  31. package/build/executor/job-runner.js +112 -11
  32. package/build/executor/likely-tests.js +6 -1
  33. package/build/executor/preflight.js +5 -0
  34. package/build/executor/process-containment.js +18 -0
  35. package/build/executor/prompt-spec.js +72 -13
  36. package/build/executor/reconcile-overlap-job.js +6 -1
  37. package/build/executor/worker-command.js +136 -1
  38. package/build/executor/worker-database.js +30 -11
  39. package/build/executor/worker-resources.js +12 -1
  40. package/build/executor/worker-verification-guidance.js +29 -0
  41. package/build/index.js +221 -165
  42. package/build/install-bridge-conductor-gate.js +195 -14
  43. package/build/install-bridge-conductor-setup.js +20 -6
  44. package/build/install-bridge-conductor.js +355 -37
  45. package/build/install-bridge.js +1 -1
  46. package/build/merge-workflow-install.js +20 -0
  47. package/build/pipelines.generated.js +2 -2
  48. package/build/plan-execution-ledger.js +23 -8
  49. package/build/plane/plane-freshness.js +6 -2
  50. package/build/plane/preflight.js +19 -0
  51. package/build/printed-remedy-commands.js +8 -1
  52. package/build/readme.generated.js +1 -1
  53. package/build/repository-toolchains.js +581 -0
  54. package/build/setup-epic.js +24 -7
  55. package/build/test-command-detection.js +58 -21
  56. package/build/ticket-delivery-artifacts.js +7 -0
  57. package/build/ticket-delivery-enrollment.js +67 -4
  58. package/build/version.generated.js +3 -3
  59. package/docs/EPIC-IMPLEMENTER.md +38 -0
  60. package/docs/epic-implementer/getting-started.md +58 -2
  61. package/package.json +2 -2
@@ -22,6 +22,7 @@ import { renderWorkerVerificationGuidance, renderWorkerPrBaseGuidance, renderWor
22
22
  * read-only viewer tabs wired around every spawned worker.
23
23
  */
24
24
  import { rm, readdir, lstat, unlink, realpath, rename as fsRename, stat as fsStat } from "node:fs/promises";
25
+ import { accessSync, constants as fsConstants, realpathSync, statSync } from "node:fs";
25
26
  import { provisionWorktreeSettingsExclude } from "./permissions.js";
26
27
  import os from "node:os";
27
28
  import { runHeartbeatLoop, sendImmediateHeartbeat } from "./heartbeat.js";
@@ -40,7 +41,7 @@ import { buildNotLaunchedEnvelope, claimRequiresCleanupReport, claimRequiresComp
40
41
  import { COMPLETION_CAUSE_ERROR_KINDS, EOF_DRAIN_BOUND_MS, STDIN_CLOSE_GRACE_MS, finalizationFacts, finalizationObligations, planCompletionAllowance, readCompletionBinding, readDeclaredChecks, readOptionalWatchers, readRequiredVerification, renderApprovedVerificationGuidance, } from "./completion-supervision.js";
41
42
  import { compareFinalArtifact, createRequiredVerificationRunner, createSupervisedCommandLauncher, observeFinalArtifact, OWNERSHIP_POLL_MS, preCheckArtifactState, toCompletionCheckFact, } from "./required-verification.js";
42
43
  import { createClosureSupervisor, createRequiredWorkLedger } from "./required-work-ledger.js";
43
- import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
44
+ import { buildCleanupVerdict, CLEANUP_RESIDUALS_NOT_COVERED, createDefaultOwnershipRecordFs, createDescendantTracker, createMacProcessInspector, createOwnershipToken, hostIdentityDigest, ownershipTokenDigest, removeOwnershipRecord, runOwnedProcessSweep, withExecutorJobId, withOwnershipTag, writeOwnershipRecord, } from "./process-containment.js";
44
45
  import { resolveCompletionEvidenceCapability } from "../agent-launchers/executor-adapter.js";
45
46
  import { autoCheckpointDirtyState, PRIOR_ATTEMPT_WIP_COMMIT_MESSAGE, prepareResumeSpawn, prepareRetainedContinuationWorktree, readContinuationBinding, verifyContinuationHeadLineage, } from "./resume-pre-spawn.js";
46
47
  import { buildEpicWorkaroundWorkerInstruction, ciFixContextError, readCiFixDispatchContext, renderPromptSpecPrompt, } from "./prompt-spec.js";
@@ -53,6 +54,7 @@ import { buildGenericSuccessResult, CI_FIX_CLAIMS_STATUS_KEY, readCiFixResultArt
53
54
  import { sendTerminalMutationWithRetry } from "./terminal-mutation.js";
54
55
  import { removeStaleVerdictArtifacts } from "./stale-artifacts.js";
55
56
  import { stripWorkerEnvFiles } from "./env-file-guard.js";
57
+ import { payloadWorkerEnvOption } from "./env.js";
56
58
  import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine, } from "./worker-database.js";
57
59
  import { formatWorkerCliLauncherUnavailableLine } from "./worker-cli-launcher.js";
58
60
  import { isVerdictJobType, readVerdictArtifact } from "./verdict-artifact.js";
@@ -69,7 +71,7 @@ import { deliveryHoldOf, readFocusedPullRequest, resolveOriginBranchSha, validat
69
71
  import { DELIVERY_OUTCOME_READ_TIMEOUT_MS, fetchServerDeliveryOutcome, } from "./delivery-outcome.js";
70
72
  import { FOCUSED_REBASE_JOB_TYPE, focusedRebaseContextError, hasFocusedRebaseContext, validateFocusedRebaseContext, waitForFocusedRebase, } from "./rebase-finalization.js";
71
73
  import { ensureExecutorWorktree, finalizeRetainedExecutorWorktree, } from "./worktree.js";
72
- import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
74
+ import { CI_FIX_JOB_TYPE, renderCiFixOperatorNote, renderLocalEnvironmentLimits, resolveExecutorPrompt, resolveWorkerPermissionPosture, } from "./worker-command.js";
73
75
  import { CORRECTION_INTENT_CAPABILITY, isRemainingWork, validateCorrectionIntent, } from "./correction-dispatch.js";
74
76
  import { collectGitTelemetry, collectRemoteTrackingSha, createMcpSurfaceObserver, evaluatePreSpawnGitVerification, formatWorkerRateLimitAdvisory, normalizeMcpServerNames, } from "./observation.js";
75
77
  import { failureReasonCode, isFailureReasonCode } from "./failure-reason-codes.js";
@@ -2344,6 +2346,18 @@ export function formatPreSpawnRefusalLine(job, reason, telemetry) {
2344
2346
  return (`pre-spawn verification refused job_id=${job.id} reason=${code} ` +
2345
2347
  `dirty_paths=${JSON.stringify(paths)} dirty_paths_overflow_count=${overflow}`);
2346
2348
  }
2349
+ /**
2350
+ * In-process reporting policy, never serialized: failure objects registered here
2351
+ * leave `worker_diagnostics.final_message_excerpt` null on the outgoing `/fail`
2352
+ * copy, while executor-owned `attempt_log` metadata may still be attached. Marker
2353
+ * storage stays in this WeakSet so no field, symbol, option, or argument enters
2354
+ * the failure body or the shared HTTP client interface.
2355
+ */
2356
+ const failuresWithoutWorkerFinalMessageExcerpt = new WeakSet();
2357
+ function withoutWorkerFinalMessageExcerpt(failure) {
2358
+ failuresWithoutWorkerFinalMessageExcerpt.add(failure);
2359
+ return failure;
2360
+ }
2347
2361
  /** Reserve the branch before Worktrunk can mutate it; lock an existing tree before preparation. */
2348
2362
  async function runSpawnJob(job, httpClient, options, deps, ownership, observation, seams, control, driver) {
2349
2363
  const originalHttp = httpClient;
@@ -2352,8 +2366,18 @@ async function runSpawnJob(job, httpClient, options, deps, ownership, observatio
2352
2366
  let telemetry = { ...body.telemetry, ...observation.snapshot() };
2353
2367
  try {
2354
2368
  const diagnostics = observation.workerDiagnostics();
2355
- if (diagnostics)
2369
+ if (diagnostics && failuresWithoutWorkerFinalMessageExcerpt.has(body)) {
2370
+ // Opted-out failure: send a copy with the excerpt nulled, and drop the
2371
+ // diagnostics entirely when no attempt log is left to report. Assigned
2372
+ // after the merge above so nothing can restore the original excerpt.
2373
+ const { worker_diagnostics: _restored, ...rest } = telemetry;
2374
+ telemetry = diagnostics.attempt_log !== null
2375
+ ? { ...rest, worker_diagnostics: { ...diagnostics, final_message_excerpt: null } }
2376
+ : rest;
2377
+ }
2378
+ else if (diagnostics) {
2356
2379
  telemetry = { ...telemetry, worker_diagnostics: diagnostics };
2380
+ }
2357
2381
  }
2358
2382
  catch {
2359
2383
  if (!diagnosticWarningSent) {
@@ -2897,6 +2921,7 @@ async function prepareWorkerResources(params) {
2897
2921
  let target;
2898
2922
  let disposeLauncher;
2899
2923
  let launcherDirectory;
2924
+ let unavailableCategory;
2900
2925
  let released = false;
2901
2926
  lifecycle.releaseWorkerResources = async () => {
2902
2927
  if (released)
@@ -2941,12 +2966,19 @@ async function prepareWorkerResources(params) {
2941
2966
  shutdown.signal.addEventListener("abort", abortCombined, { once: true });
2942
2967
  const cancel = combined.signal;
2943
2968
  const provisioned = await resources
2944
- .provisionDatabase({ jobId, worktreePath: params.worktreePath, signal: cancel })
2969
+ .provisionDatabase({
2970
+ jobId,
2971
+ worktreePath: params.worktreePath,
2972
+ signal: cancel,
2973
+ // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
2974
+ ...payloadWorkerEnvOption(job.payload),
2975
+ })
2945
2976
  .catch(() => ({ kind: "unavailable", category: "create_failed" }));
2946
2977
  if (provisioned.kind === "provisioned") {
2947
2978
  target = provisioned.target;
2948
2979
  }
2949
2980
  else {
2981
+ unavailableCategory = provisioned.category;
2950
2982
  try {
2951
2983
  deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category));
2952
2984
  // A created database whose rollback failed stays for the host operator.
@@ -3014,8 +3046,33 @@ async function prepareWorkerResources(params) {
3014
3046
  kind: "ready",
3015
3047
  ...(target ? { workerDatabase: target } : {}),
3016
3048
  ...(launcherDirectory ? { workerLauncherDirectory: launcherDirectory } : {}),
3049
+ ...(!target && unavailableCategory ? { workerDatabaseUnavailableCategory: unavailableCategory } : {}),
3017
3050
  };
3018
3051
  }
3052
+ /**
3053
+ * BAPI-1522: the filesystem-backed executable check for the LOCAL ENVIRONMENT
3054
+ * LIMITS section. It never executes anything: it resolves symlinks, requires a
3055
+ * regular file with execute permission, and, when asked, requires the resolved
3056
+ * file to stay inside the worktree. Any filesystem error means "not runnable".
3057
+ */
3058
+ export const fileSystemExecutableCheck = (candidate, options) => {
3059
+ try {
3060
+ const resolved = realpathSync(candidate);
3061
+ if (options?.withinDirectory !== undefined) {
3062
+ const root = realpathSync(options.withinDirectory);
3063
+ const relative = path.relative(root, resolved);
3064
+ if (relative.startsWith("..") || path.isAbsolute(relative))
3065
+ return false;
3066
+ }
3067
+ if (!statSync(resolved).isFile())
3068
+ return false;
3069
+ accessSync(resolved, fsConstants.X_OK);
3070
+ return true;
3071
+ }
3072
+ catch {
3073
+ return false;
3074
+ }
3075
+ };
3019
3076
  function retainedHeadPublisher(params) {
3020
3077
  return async () => {
3021
3078
  const { job, branch, worktreePath, prep, deps, ownership, observation, remainingMs } = params;
@@ -3078,7 +3135,10 @@ async function runPreparedSpawn(params) {
3078
3135
  !prep.ciFix &&
3079
3136
  !prep.focusedRebase &&
3080
3137
  !isRemainingWork(job.job_type, job.payload)) {
3081
- prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key)}`;
3138
+ // BAPI-1544: a present boolean states the run's setting; an absent key (a job from
3139
+ // an older API) stays absent so the instruction keeps its conditional wording.
3140
+ const handoffEnabled = job.payload?.verification_handoff_enabled;
3141
+ prompt = `${prompt} ${buildEpicWorkaroundWorkerInstruction(job.ticket_key, typeof handoffEnabled === "boolean" ? handoffEnabled : undefined)}`;
3082
3142
  }
3083
3143
  // --- Timeout contract ------------------------------------------------
3084
3144
  const timeout = resolveJobTimeoutSeconds(job, options.defaultJobTimeoutSeconds);
@@ -3574,6 +3634,8 @@ async function runPreparedSpawn(params) {
3574
3634
  // Driver-owned jobs (their worker runs a server-rendered reconciliation) and
3575
3635
  // verdict-only jobs keep the sentinel database.
3576
3636
  let workerResources = {};
3637
+ // BAPI-1522: why no database exists (a closed category), kept OUT of the spawn input.
3638
+ let databaseUnavailableCategory;
3577
3639
  if (!driver && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)) {
3578
3640
  const prepared = await prepareWorkerResources({
3579
3641
  job, httpClient, options: jobOptions, deps, ownership, observation, control,
@@ -3588,6 +3650,7 @@ async function runPreparedSpawn(params) {
3588
3650
  ...(prepared.workerDatabase ? { workerDatabase: prepared.workerDatabase } : {}),
3589
3651
  ...(prepared.workerLauncherDirectory ? { workerLauncherDirectory: prepared.workerLauncherDirectory } : {}),
3590
3652
  };
3653
+ databaseUnavailableCategory = prepared.workerDatabaseUnavailableCategory;
3591
3654
  }
3592
3655
  const invocation = adapter.headlessInvocation;
3593
3656
  if (invocation?.supported !== true) {
@@ -3603,8 +3666,12 @@ async function runPreparedSpawn(params) {
3603
3666
  let spawnShape;
3604
3667
  try {
3605
3668
  const alias = invocation.value.resolveModelAlias(job.payload);
3606
- spawnShape = invocation.value.buildSpawnShape({
3607
- prompt,
3669
+ // BAPI-1522 — LOCAL ENVIRONMENT LIMITS is the LAST prompt section. It is built
3670
+ // here, after resources, worktree, environment, prompt expansion, and approved
3671
+ // guidance are final, from the PATH the adapter will really hand the worker.
3672
+ // The section is appended exactly once, and nothing after this point changes
3673
+ // the prompt text.
3674
+ const shapeInput = {
3608
3675
  // BAPI-1301: a covered attempt sends the prompt on a held stdin instead
3609
3676
  // of argv; every other job keeps the byte-identical legacy argv.
3610
3677
  ...(covered ? { promptTransport: "stdin-stream-json" } : {}),
@@ -3625,7 +3692,36 @@ async function runPreparedSpawn(params) {
3625
3692
  ...(driverStep ? { declaredTouchedFiles: driverStep.declaredTouchedFiles } : {}),
3626
3693
  // BAPI-1479 — explicit, executor-provisioned values; never read from `parentEnv`.
3627
3694
  ...workerResources,
3695
+ // BAPI-1521 — forwarded only when the payload OWNS the key, for every worker
3696
+ // job type. Absent keeps the legacy compatibility constants; a present
3697
+ // value, even `[]` or a malformed one, replaces them.
3698
+ ...payloadWorkerEnvOption(job.payload),
3628
3699
  parentEnv: deps.env,
3700
+ };
3701
+ // The PATH the worker will receive: the launcher directory (when provisioned)
3702
+ // first, then the inherited PATH, exactly as `env.ts` composes it. The runner
3703
+ // builds no worker environment itself (BAPI-781), so this only mirrors that
3704
+ // rule for the read-only limits check.
3705
+ const inheritedPath = deps.env.PATH;
3706
+ const workerEnvPath = workerResources.workerLauncherDirectory
3707
+ ? (typeof inheritedPath === "string" && inheritedPath.length > 0
3708
+ ? `${workerResources.workerLauncherDirectory}${path.delimiter}${inheritedPath}`
3709
+ : workerResources.workerLauncherDirectory)
3710
+ : inheritedPath;
3711
+ const reproduceCommands = job.payload && typeof job.payload === "object"
3712
+ ? job.payload.reproduce_commands : undefined;
3713
+ const limits = renderLocalEnvironmentLimits({
3714
+ databaseAvailable: workerResources.workerDatabase !== undefined,
3715
+ ...(databaseUnavailableCategory && WORKER_RESOURCE_JOB_TYPES.has(job.job_type)
3716
+ ? { databaseUnavailableCategory } : {}),
3717
+ reproduceCommands,
3718
+ ...(typeof workerEnvPath === "string" ? { workerPath: workerEnvPath } : {}),
3719
+ worktreePath,
3720
+ isExecutable: seams.executableCheck ?? fileSystemExecutableCheck,
3721
+ });
3722
+ spawnShape = invocation.value.buildSpawnShape({
3723
+ prompt: limits ? prompt + "\n\n" + limits : prompt,
3724
+ ...shapeInput,
3629
3725
  });
3630
3726
  assertUsableSpawnShape(spawnShape, adapter);
3631
3727
  }
@@ -3869,7 +3965,7 @@ async function runPreparedSpawn(params) {
3869
3965
  const legacyLineFeeder = legacyLedger ? createLedgerLineFeeder(legacyLedger) : null;
3870
3966
  let proc;
3871
3967
  try {
3872
- proc = spawnWorker({ env: spawnShape.env });
3968
+ proc = spawnWorker({ env: withExecutorJobId(spawnShape.env, job.id) });
3873
3969
  }
3874
3970
  catch (err) {
3875
3971
  await closeWorkerLog();
@@ -4175,19 +4271,22 @@ async function runPreparedSpawn(params) {
4175
4271
  // before generic success, the ci_fix artifact merge, or finalization can hide
4176
4272
  // it. Only the fixed kind and message are sent: no event text, command, path,
4177
4273
  // or output. A matching terminal task_notification leaves nothing pending.
4274
+ // The explicit opt-out below overrides the BAPI-1431 diagnostics default, so
4275
+ // no worker final-message excerpt is sent; an executor-generated relative
4276
+ // attempt-log reference may still ride along.
4178
4277
  if (legacyLedger?.observeLiveRequiredWork() === "live_required_work") {
4179
4278
  deps.errorLog(`[executor] job ${job.id}: worker exited cleanly with required background work still live`);
4180
4279
  await finalizeRegistry();
4181
4280
  const terminal = await sendTerminalMutationWithAuthReport({
4182
4281
  kind: "fail",
4183
- send: () => httpClient.fail(job, {
4282
+ send: () => httpClient.fail(job, withoutWorkerFinalMessageExcerpt({
4184
4283
  error_kind: WorkerEndedWithPendingBackgroundWork,
4185
4284
  error_message: WORKER_ENDED_WITH_PENDING_BACKGROUND_WORK_MESSAGE,
4186
4285
  classification: "crashed",
4187
4286
  ...observedExitCode(procResult.exitCode),
4188
4287
  ...commitResidue(git),
4189
4288
  telemetry: observation.snapshot(),
4190
- }),
4289
+ })),
4191
4290
  deps,
4192
4291
  options,
4193
4292
  ownership,
@@ -4642,7 +4741,9 @@ async function runCoveredAttempt(params) {
4642
4741
  const token = createOwnershipToken();
4643
4742
  const tokenDigest = ownershipTokenDigest(token);
4644
4743
  const hostDigest = hostIdentityDigest(os.hostname());
4645
- const workerEnv = withOwnershipTag(spawnShape.env, token);
4744
+ // BAPI-1544: the claimed job's ID, set last from the job row so the worker's MCP
4745
+ // server can register it on the delivery binding. Absent when the ID is unusable.
4746
+ const workerEnv = withExecutorJobId(withOwnershipTag(spawnShape.env, token), job.id);
4646
4747
  const stateDir = resolveExecutorStateDir(buildJobLogRegistryDeps(deps));
4647
4748
  const recordFs = seams.ownershipRecordFs ?? createDefaultOwnershipRecordFs();
4648
4749
  try {
@@ -153,7 +153,12 @@ function nulPaths(output) {
153
153
  const ordinal = (a, b) => a < b ? -1 : a > b ? 1 : 0;
154
154
  function testCandidate(file) {
155
155
  const base = path.posix.basename(file);
156
- return /^test_.*\.py$|^.*_test\.py$|\.(?:test|spec)\.[cm]?[jt]sx?$/.test(base);
156
+ if (/^test_.*\.py$|^.*_test\.py$|\.(?:test|spec)\.[cm]?[jt]sx?$/.test(base))
157
+ return true;
158
+ // Other stacks' conventional test files (BAPI-1519).
159
+ if (/_test\.go$|_test\.rs$|(?:Test|Tests|IT)\.java$|_spec\.rb$/.test(base))
160
+ return true;
161
+ return base.endsWith(".rs") && file.split("/").slice(0, -1).includes("tests");
157
162
  }
158
163
  /** Discover declared Python source roots without importing any project code. */
159
164
  async function pythonRoots(root, read) {
@@ -467,6 +467,11 @@ export async function collectExecutorPreflight(options, deps, seams = {}) {
467
467
  }
468
468
  // The probe gets a worker-shaped environment so a nested-session variable in
469
469
  // the executor's own process cannot change its verdict (BAPI-1386).
470
+ //
471
+ // BAPI-1521: deliberately NOT a job. This probe has no payload and therefore
472
+ // no `worker_env` declaration, and `buildHeadlessAgentEnv` passes none, so the
473
+ // legacy compatibility base constants apply on purpose. It is the one
474
+ // documented exception to the payload-presence rule.
470
475
  const verdict = await denyCapability.value.probeEnforcement({
471
476
  timeoutMs: resolveDenyProbeTimeoutMs(deps.env),
472
477
  env: buildHeadlessAgentEnv(deps.env),
@@ -107,6 +107,24 @@ export function withOwnershipTag(env, token) {
107
107
  next[OWNERSHIP_TAG_ENV] = token;
108
108
  return next;
109
109
  }
110
+ /** The environment variable carrying the claimed executor job's ID (BAPI-1544). */
111
+ export const EXECUTOR_JOB_ID_ENV = "BRIDGE_EXECUTOR_JOB_ID";
112
+ /**
113
+ * A NEW environment carrying `jobId` as the claimed executor job ID. Any ambient
114
+ * value is removed first, then the ID is set only when it is a positive safe
115
+ * integer; anything else leaves the key absent. It never throws, so a bad value
116
+ * cannot become a spawn failure, and it touches no other key (the ownership tag and
117
+ * its cleanup are unaffected). Call this AFTER the adapter/base environment is
118
+ * built, from the claimed job row, never from a payload.
119
+ */
120
+ export function withExecutorJobId(env, jobId) {
121
+ const next = { ...env };
122
+ delete next[EXECUTOR_JOB_ID_ENV];
123
+ if (typeof jobId === "number" && Number.isSafeInteger(jobId) && jobId > 0) {
124
+ next[EXECUTOR_JOB_ID_ENV] = String(jobId);
125
+ }
126
+ return next;
127
+ }
110
128
  /** Per-`ps` call bound. The whole sweep is further bounded by its deadline. */
111
129
  const PS_TIMEOUT_MS = 10_000;
112
130
  /**
@@ -37,6 +37,12 @@ import { EPIC_WORKAROUNDS_DIR, epicWorkaroundRecordPath } from "../epic-workarou
37
37
  * credentials) is recorded as a hand-off, never as a core gap, and the worker
38
38
  * continues without reporting that criterion as passed.
39
39
  *
40
+ * BAPI-1544 widens that order to unit-test steps and a fifth cause
41
+ * (`mcp_unavailable`), makes the hand-off a six-field object that adds the
42
+ * corrected invocation, binds it to the head it observed (a step that failed at one
43
+ * head can be handed off only from a new head), and states the run's actual setting
44
+ * ("this run allows" or "does not allow" hand-offs) when the job carries it.
45
+ *
40
46
  * BAPI-1492 adds the verification hand-off order for an E2E or rendered-UI step:
41
47
  * run it locally (the disposable job database when one is provided), defer to
42
48
  * `remote_ci` only when a named required workflow, job, or command runs it, and
@@ -44,13 +50,30 @@ import { EPIC_WORKAROUNDS_DIR, epicWorkaroundRecordPath } from "../epic-workarou
44
50
  * failure. Review steps always run and are recorded executed. The server alone
45
51
  * decides whether a hand-off counts, from persisted run state.
46
52
  *
53
+ * BAPI-1533 puts a test invocation rule ahead of that order: a selector that
54
+ * collects zero tests is an invocation error (never a pass, never a missing
55
+ * capability), every affected test-running step is rerun from the repository
56
+ * root with the declared runner and its command and output recorded, the
57
+ * declared build runs before a built-CLI smoke step, and an undeclared runner or
58
+ * build command is never invented. Hand-offs stay limited to the eligible
59
+ * classes, the persisted run policy, and a genuine pre-result missing
60
+ * capability. Nothing converts an ordinary escalation into a hand-off.
61
+ *
47
62
  * The worker decides from the ticket and the code alone; no supervisor scan
48
63
  * result is injected here. Kept SINGLE-LINE and free of `;`, quotes, and
49
64
  * apostrophes, like `buildPrBaseContractLaunchInstruction`, because it travels
50
65
  * in the same launch prompt.
51
66
  */
52
- export function buildEpicWorkaroundWorkerInstruction(ticketKey) {
67
+ export function buildEpicWorkaroundWorkerInstruction(ticketKey, handoffEnabled) {
53
68
  const record = (ticketKey ? epicWorkaroundRecordPath(ticketKey) : null) ?? `${EPIC_WORKAROUNDS_DIR}<TICKET>.md`;
69
+ // BAPI-1544: an explicit boolean states the run setting outright. An absent one
70
+ // (a job from an older API) keeps today's conditional wording.
71
+ const policyClause = handoffEnabled === true
72
+ ? "This run allows verification hand-offs. "
73
+ : handoffEnabled === false
74
+ ? "This run does not allow verification hand-offs, so a step that cannot run is recorded as an ordinary escalation without a handoff object. "
75
+ : "";
76
+ const allowsClause = handoffEnabled === undefined ? " and the persisted run policy allows hand-offs" : "";
54
77
  return ("Workaround contract: if a requirement of this ticket cannot be met unattended, such as a missing " +
55
78
  "credential, external setting, or access, decide whether it is minor or core. It is minor only when " +
56
79
  "the essential behavior of the ticket still works without it. For a minor gap, deliver a guarded " +
@@ -64,18 +87,35 @@ export function buildEpicWorkaroundWorkerInstruction(ticketKey) {
64
87
  "not a core gap. Record the affected acceptance criterion and the human verification step in " + record +
65
88
  " and continue. Never report an unverified acceptance criterion as passed. A dependency needed to " +
66
89
  "implement safely keeps ordinary core gap handling. " +
67
- "Verification hand-off for an e2e_tests or rendered_ui_review step: first run it locally, using the " +
68
- "disposable job database when one is provided. Record it escalated with prDependency remote_ci only " +
69
- "when a named required CI workflow, job, or command runs that check. Otherwise, if a missing live " +
70
- "server, database, toolchain, or credential stopped the check before it produced any result, record " +
71
- "the step escalated with a handoff object giving the cause, the affected criterion, an observation " +
72
- "naming the command you ran and the missing capability it hit, the head SHA it ran against, and the " +
73
- "next human action. Never put credentials or secrets in the observation. A failed assertion, an " +
90
+ "Test invocation rule for every step that runs tests: a requested test selector that collects zero " +
91
+ "tests is an invocation error whatever the exit status or runner wording, never a pass and never " +
92
+ "proof of a missing capability. Rerun every affected test-running step from the repository root with " +
93
+ "the repository declared runner and record the exact command and its output in that step evidence. " +
94
+ "Run the repository declared build command before any built CLI smoke step. If no runner or build " +
95
+ "command is declared, that is not a pass and does not let you invent a command or report success. " +
96
+ "Verification hand-off for a unit_tests, e2e_tests, or rendered_ui_review step. " + policyClause +
97
+ "First run it locally, using the disposable job database when one is provided. Record it escalated " +
98
+ "with prDependency remote_ci only when a named required CI workflow, job, or command runs that check. " +
99
+ "Otherwise, if a missing live server, database, toolchain, credential, or MCP capability stopped the " +
100
+ "check before it produced any result, both on your first invocation and on the corrected rerun" + allowsClause +
101
+ ", record the step escalated with a handoff object of exactly six fields. The cause is one of " +
102
+ "no_live_server, no_database, toolchain_unavailable, credential_unavailable, or mcp_unavailable. " +
103
+ "The criterion is the affected acceptance criterion. The observation names the command you first " +
104
+ "ran and the missing capability it hit. The corrected_invocation names the corrected rerun and the " +
105
+ "missing capability it hit. The observed_head_sha is the full head SHA both ran against, and it must " +
106
+ "equal the head you record the phase result at. The next_action is the next human step. Never put " +
107
+ "credentials or secrets in the observation or corrected_invocation. For example, a unit step whose " +
108
+ "acquire command timed out names that command and the timeout. " +
109
+ "A failed assertion, an " +
74
110
  "application error from a check that did run, and unfinished implementation or test authoring stay " +
75
- "blockers, and an unclear failure stays an ordinary escalation. Review steps (test_gap_review, " +
111
+ "blockers, and an unclear failure stays an ordinary escalation. Only those three step classes may be " +
112
+ "handed off. Neither you nor the server turns an ordinary escalation into a hand-off, and you never " +
113
+ "invent a missing capability observation. Review steps (test_gap_review, " +
76
114
  "final_plan_review, and combined_review_test) always run, acknowledge the handed-off criterion from " +
77
115
  "that escalated record and the workaround record written in the same job, and are recorded executed, " +
78
- "never handed off. A new head needs a fresh handoff observation.");
116
+ "never handed off. A hand-off counts only at the head it observed, so a new head needs a fresh " +
117
+ "observation. A step that already failed at one head can be handed off only from a new head, " +
118
+ "never at the head where it failed.");
79
119
  }
80
120
  /** Stable named-error kind used for every prompt-spec contract failure. */
81
121
  const PROMPT_CONTRACT_ERROR = "ContractError.Prompt";
@@ -158,6 +198,8 @@ const CI_FIX_PLACEHOLDERS = [
158
198
  ];
159
199
  const CI_FIX_EXCERPT_TRUNCATION_MARKER = " …[excerpt truncated]";
160
200
  const CI_FIX_HEAD_SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
201
+ const CI_FIX_STATUS_ONLY_NOTE = "provider_reports_status_only";
202
+ const CI_FIX_STATUS_ONLY_NOTE_LINE = "Note: this provider reports a status only; no log or annotations exist for it.";
161
203
  /** Build the named, bounded refusal for a focused ci_fix job. */
162
204
  export function ciFixContextError(job, reason) {
163
205
  return new ExecutorNamedError(CiFixContext, `ci_fix job ${job.id} refused before worker effects (reason=${reason})`);
@@ -346,7 +388,14 @@ function readLogExcerpts(raw, headSha, dispatched) {
346
388
  CI_FIX_EXCERPT_TRUNCATION_MARKER;
347
389
  }
348
390
  totalBytes += utf8Bytes(text);
349
- excerpts.push({ check: e.check.trim(), source: e.source.trim(), text });
391
+ // A note is optional metadata: only the exact closed token is kept, and an
392
+ // absent, malformed, or unknown one never refuses the excerpt.
393
+ excerpts.push({
394
+ check: e.check.trim(),
395
+ source: e.source.trim(),
396
+ text,
397
+ ...(e.note === CI_FIX_STATUS_ONLY_NOTE ? { note: CI_FIX_STATUS_ONLY_NOTE } : {}),
398
+ });
350
399
  }
351
400
  return { status: "supplied", excerpts };
352
401
  }
@@ -452,6 +501,16 @@ export function readCiFixDispatchContext(job) {
452
501
  function formatCheckList(names, none) {
453
502
  return names.length > 0 ? names.map((name) => `- ${sanitizeCiText(name, 200)}`).join("\n") : none;
454
503
  }
504
+ /**
505
+ * Quote any provider-controlled line that imitates the diagnostics delimiters, so
506
+ * only the renderer's own delimiter lines are structurally active.
507
+ */
508
+ function quoteDiagnosticDelimiters(value) {
509
+ return value
510
+ .split("\n")
511
+ .map((line) => (line.includes("## UNTRUSTED PROVIDER DIAGNOSTICS") ? `> ${line}` : line))
512
+ .join("\n");
513
+ }
455
514
  function formatLogExcerpts(context) {
456
515
  const evidence = context.evidence;
457
516
  const header = evidence.status === "unavailable"
@@ -473,10 +532,10 @@ function formatLogExcerpts(context) {
473
532
  "and local reproduction; do not assume what any log said.") + "\n## UNTRUSTED PROVIDER DIAGNOSTICS END ##";
474
533
  }
475
534
  const summaries = evidence.status === "available"
476
- ? evidence.required.filter((item) => item.summary).map((item) => `${sanitizeCiText(item.name, 200)} selected summary: ${item.summary}`)
535
+ ? evidence.required.filter((item) => item.summary).map((item) => quoteDiagnosticDelimiters(`${sanitizeCiText(item.name, 200)} selected summary: ${item.summary}`))
477
536
  : [];
478
537
  return header + "\n## UNTRUSTED PROVIDER DIAGNOSTICS BEGIN ##\n" +
479
- [...summaries, ...excerpts.excerpts.map((e) => `--- check: ${sanitizeCiText(e.check, 200)} (source: ${sanitizeCiText(e.source, 200)}) ---\n${sanitizeCiText(e.text)}`)].join("\n\n") +
538
+ [...summaries, ...excerpts.excerpts.map((e) => quoteDiagnosticDelimiters(`--- check: ${sanitizeCiText(e.check, 200)} (source: ${sanitizeCiText(e.source, 200)}) ---\n${sanitizeCiText(e.text)}`) + (e.note === CI_FIX_STATUS_ONLY_NOTE ? `\n${CI_FIX_STATUS_ONLY_NOTE_LINE}` : ""))].join("\n\n") +
480
539
  "\n## UNTRUSTED PROVIDER DIAGNOSTICS END ##";
481
540
  }
482
541
  /**
@@ -256,6 +256,9 @@ export function validateReconcileOverlapPayload(job) {
256
256
  conflictReportPath,
257
257
  prompt,
258
258
  reconcileGeneration: generation,
259
+ workerEnvOption: Object.prototype.hasOwnProperty.call(payload, "worker_env")
260
+ ? { workerEnv: payload.worker_env }
261
+ : {},
259
262
  },
260
263
  };
261
264
  }
@@ -361,7 +364,9 @@ export function createReconcileOverlapDriver(job, payload, seams) {
361
364
  editedReasons: new Map(),
362
365
  };
363
366
  const commands = verificationCommandUnion(payload.child, payload.peer);
364
- const workerEnv = buildExecutorBaseWorkerEnv(seams.env);
367
+ // BAPI-1521: the root payload's declaration, with presence kept (absent for an
368
+ // older payload, which keeps the compatibility constants).
369
+ const workerEnv = buildExecutorBaseWorkerEnv(seams.env, payload.workerEnvOption);
365
370
  const git = async (ctx, args, timeoutMs = GIT_TIMEOUT_MS, env) => {
366
371
  if (ctx.signal?.aborted)
367
372
  throw new ReconcileOverlapAborted("reconciliation phase aborted");
@@ -17,11 +17,12 @@
17
17
  * distinct from the argv vocabulary is what stops a future flag rename in one
18
18
  * agent's CLI from becoming an operator-visible policy break across all of them.
19
19
  */
20
- import { renderWorkerVerificationGuidance, renderWorkerPushAndCommitGuidance } from "./worker-verification-guidance.js";
20
+ import { renderWorkerVerificationGuidance, renderWorkerPushAndCommitGuidance, renderWorkerTestInvocationGuidance } from "./worker-verification-guidance.js";
21
21
  import { CiFixContext, ExecutorNamedError } from "./job-errors.js";
22
22
  import { isRemainingWork, validateCorrectionIntent } from "./correction-dispatch.js";
23
23
  import { readRequiredVerification } from "./completion-supervision.js";
24
24
  import { isValidExecutorEpicRunId } from "./claim-scope.js";
25
+ import path from "node:path";
25
26
  /**
26
27
  * BAPI-1296: `ci_fix` is the one recovery job with a FOCUSED prompt route. It
27
28
  * renders its server-authored `payload.prompt_spec` (the dispatched failing and
@@ -117,6 +118,7 @@ function resolveExecutorPromptLegacy(job, trusted) {
117
118
  : "";
118
119
  const pushing = job.job_type !== "reconcile_overlap" && kind !== "overlap_reconciliation";
119
120
  const guidance = pushing ? renderWorkerPushAndCommitGuidance(job.job_type === "rebase") +
121
+ "\n\n" + renderWorkerTestInvocationGuidance() +
120
122
  (trusted ? "\n\n" + renderWorkerVerificationGuidance(trusted.comparisonSha) : "") : "";
121
123
  const focusedHeader = `${header}${operatorContext}${prGuidance}${guidance}`;
122
124
  if (kind === "approved_spec_delta") {
@@ -234,3 +236,136 @@ export function resolveWorkerPermissionPosture(payload) {
234
236
  // than assembling a Claude-shaped command here. Re-adding a builder to this
235
237
  // module would recreate the exact coupling the extraction removed: a generic
236
238
  // job-policy module that only works for one CLI.
239
+ // ---------------------------------------------------------------------------
240
+ // LOCAL ENVIRONMENT LIMITS (BAPI-1522)
241
+ // ---------------------------------------------------------------------------
242
+ /** The heading of the final prompt section that names what cannot run locally. */
243
+ export const LOCAL_ENVIRONMENT_LIMITS_HEADING = "## LOCAL ENVIRONMENT LIMITS ##";
244
+ /**
245
+ * The closed database-unavailable categories the section may name. Mirrors
246
+ * `WorkerDatabaseUnavailableCategory`; the annotation makes the compiler reject
247
+ * a member the type does not have. Anything else is omitted from the line.
248
+ */
249
+ const RECOGNIZED_DATABASE_CATEGORIES = new Set([
250
+ "client_missing", "postgres_unavailable", "role_missing", "role_misconfigured",
251
+ "bridgeapi_reachable", "boundary_unknown", "alembic_missing", "create_failed",
252
+ "migration_failed", "timeout", "cancelled",
253
+ ]);
254
+ /**
255
+ * Mirrors the server renderer's admission rules
256
+ * (`render_reproduction_section` in `prompt_specs.py`): the first 64 entries,
257
+ * the recognized sources, and a usable (non-blank) rendered check name.
258
+ */
259
+ const REPRODUCE_MAX_ENTRIES = 64;
260
+ const REPRODUCE_MAX_CHECK_CHARS = 200;
261
+ const REPRODUCE_MAX_ARGV_ITEMS = 32;
262
+ const REPRODUCE_MAX_ARG_CHARS = 1024;
263
+ const REPRODUCE_SOURCES = new Set(["check_hint", "test_command", "none"]);
264
+ const REPRODUCE_SOURCE_NONE = "none";
265
+ /** Python `str.strip()` whitespace, which differs from JavaScript's `trim()`. */
266
+ const PYTHON_BLANK = /^[\t\n\v\f\r\x1c-\x1f \x85\xa0\u1680\u2000-\u200a\u2028\u2029\u202f\u205f\u3000]*$/;
267
+ /** Same text transforms as the server's `_reproduction_text`, for the first argv item. */
268
+ function reproductionText(value, maxChars) {
269
+ if (typeof value !== "string")
270
+ return "";
271
+ let text = Array.from(value, ch => {
272
+ const code = ch.codePointAt(0) ?? 0;
273
+ return code < 32 || code === 127 ? " " : ch;
274
+ }).slice(0, maxChars).join("").split('"""').join("' ' '");
275
+ while (text.includes("{{") || text.includes("}}")) {
276
+ text = text.split("{{").join("{ {").split("}}").join("} }");
277
+ }
278
+ return text;
279
+ }
280
+ /** The displayed first argv item of a usable argument array, or `null`. */
281
+ function displayedProgram(argv) {
282
+ if (!Array.isArray(argv) || argv.length === 0 || argv.length > REPRODUCE_MAX_ARGV_ITEMS)
283
+ return null;
284
+ for (const item of argv)
285
+ if (typeof item !== "string" || item.length === 0)
286
+ return null;
287
+ return reproductionText(argv[0], REPRODUCE_MAX_ARG_CHARS);
288
+ }
289
+ function isWithin(root, candidate) {
290
+ const relative = path.relative(root, candidate);
291
+ return relative === "" || (!relative.startsWith("..") && !path.isAbsolute(relative));
292
+ }
293
+ function programRunnable(program, o) {
294
+ try {
295
+ if (program.includes("/") || program.includes("\\")) {
296
+ const resolved = path.resolve(o.worktreePath, program);
297
+ if (!isWithin(o.worktreePath, resolved))
298
+ return false;
299
+ return o.isExecutable(resolved, { withinDirectory: o.worktreePath });
300
+ }
301
+ for (const dir of (o.workerPath ?? "").split(path.delimiter)) {
302
+ if (!dir)
303
+ continue;
304
+ if (o.isExecutable(path.resolve(o.worktreePath, dir, program)))
305
+ return true;
306
+ }
307
+ return false;
308
+ }
309
+ catch {
310
+ return false;
311
+ }
312
+ }
313
+ /**
314
+ * The 1-based positions of displayed reproduction blocks whose program is not
315
+ * runnable. A position counts every admitted block, with or without a command.
316
+ */
317
+ function unrunnableCheckPositions(o) {
318
+ const entries = Array.isArray(o.reproduceCommands) ? o.reproduceCommands.slice(0, REPRODUCE_MAX_ENTRIES) : [];
319
+ const missing = [];
320
+ let position = 0;
321
+ for (const entry of entries) {
322
+ if (!entry || typeof entry !== "object" || Array.isArray(entry))
323
+ continue;
324
+ const e = entry;
325
+ if (typeof e.source !== "string" || !REPRODUCE_SOURCES.has(e.source))
326
+ continue;
327
+ const check = reproductionText(e.check, REPRODUCE_MAX_CHECK_CHARS);
328
+ if (PYTHON_BLANK.test(check))
329
+ continue;
330
+ position += 1;
331
+ if (e.source === REPRODUCE_SOURCE_NONE)
332
+ continue;
333
+ const program = displayedProgram(e.argv);
334
+ if (program === null || program.trim().length === 0)
335
+ continue;
336
+ if (!programRunnable(program, o))
337
+ missing.push(position);
338
+ }
339
+ return missing;
340
+ }
341
+ /**
342
+ * Render the `LOCAL ENVIRONMENT LIMITS` section, or `""` when nothing is limited.
343
+ *
344
+ * Informational only: it adds no completion obligation, evidence rule, or exit.
345
+ * It names a missing program by its numbered Check position alone, never by check
346
+ * name, command text, executable name, or host path, and it never carries a
347
+ * credential, connection value, or internal diagnostic.
348
+ */
349
+ export function renderLocalEnvironmentLimits(options) {
350
+ const lines = [];
351
+ if (!options.databaseAvailable) {
352
+ const category = options.databaseUnavailableCategory;
353
+ const reason = category !== undefined && RECOGNIZED_DATABASE_CATEGORIES.has(category)
354
+ ? ` (reason: ${category})` : "";
355
+ lines.push(`- No disposable database was provisioned for this worker${reason}, so database-backed ` +
356
+ "verification cannot run locally. CI at the pushed head is the verifier.");
357
+ }
358
+ for (const position of unrunnableCheckPositions(options)) {
359
+ lines.push(`- Check ${position} in HOW TO REPRODUCE LOCALLY (counting its \`Check:\` blocks in order): ` +
360
+ "the program its command starts with is not runnable on this machine. Do not attempt that " +
361
+ "command. CI at the pushed head is the verifier.");
362
+ }
363
+ if (lines.length === 0)
364
+ return "";
365
+ return [
366
+ LOCAL_ENVIRONMENT_LIMITS_HEADING,
367
+ ...lines,
368
+ "Where the repository has no CI checks, its gate decides at merge.",
369
+ "This section is informational. It adds no completion obligation, evidence rule, or exit.",
370
+ ].join("\n");
371
+ }