@bridge_gpt/mcp-server 0.2.74 → 0.2.75

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 (62) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/prompt.js +9 -21
  3. package/build/agents.generated.js +2 -2
  4. package/build/authored-plan.js +542 -0
  5. package/build/bridge-permissions.js +8 -0
  6. package/build/commands.generated.js +5 -5
  7. package/build/conductor/bridge-api-client.js +666 -46
  8. package/build/conductor/epic-implementer-cli.js +337 -93
  9. package/build/conductor/gate-discovery.js +209 -9
  10. package/build/conductor/gate-settings-review.js +7 -11
  11. package/build/conductor/launch-plan.js +58 -12
  12. package/build/conductor/open-decision-phrases.js +50 -0
  13. package/build/conductor/prerequisite-inputs.js +181 -14
  14. package/build/connect-github-api.js +18 -0
  15. package/build/connect-github.js +35 -18
  16. package/build/docs.generated.js +2 -2
  17. package/build/drive-epic.js +387 -12
  18. package/build/epic-ci-workflow.js +3 -2
  19. package/build/epic-implementer-bin.js +152 -38
  20. package/build/epic-implementer-bundle-cli.js +61 -0
  21. package/build/epic-implementer-claude-hook-bin.js +1 -1
  22. package/build/epic-implementer-env.js +3 -4
  23. package/build/epic-integration-pr.js +5 -2
  24. package/build/executor/completion-contract.js +24 -1
  25. package/build/executor/gate-qualification-job.js +193 -23
  26. package/build/executor/gate-qualification-tests-ran.js +232 -0
  27. package/build/executor/job-runner.js +9 -722
  28. package/build/executor/job-type-wrappers.js +734 -0
  29. package/build/executor/preflight.js +6 -2
  30. package/build/executor/process-containment.js +8 -1
  31. package/build/executor/required-verification.js +28 -2
  32. package/build/executor/runner.js +4 -1
  33. package/build/executor/types.js +9 -0
  34. package/build/executor/worker-database.js +6 -1
  35. package/build/executor/worker-guard-hook.js +24 -2
  36. package/build/generated/ticket-status.js +20 -0
  37. package/build/index.js +391 -257
  38. package/build/install-bridge-conductor-answers.js +28 -1
  39. package/build/install-bridge-conductor-apply.js +11 -3
  40. package/build/install-bridge-conductor-assessment.js +114 -12
  41. package/build/install-bridge-conductor-compact.js +2 -0
  42. package/build/install-bridge-conductor-gate.js +257 -80
  43. package/build/install-bridge-conductor-setup.js +4 -4
  44. package/build/install-bridge-conductor-trial-report.js +170 -0
  45. package/build/install-bridge-conductor.js +303 -31
  46. package/build/pipelines.generated.js +7 -7
  47. package/build/plan-generation.js +17 -0
  48. package/build/printed-remedy-commands.js +54 -0
  49. package/build/readme.generated.js +1 -1
  50. package/build/repository-toolchains.js +11 -5
  51. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  52. package/build/setup-epic.js +10 -1
  53. package/build/test-support/executor-source-files.js +1 -1
  54. package/build/v2-readiness-requirements.js +5 -1
  55. package/build/version.generated.js +3 -3
  56. package/build/worker-guard-hook-bin.js +2 -2
  57. package/docs/EPIC-IMPLEMENTER.md +4 -4
  58. package/docs/install/github-app.md +79 -92
  59. package/package.json +1 -1
  60. package/build/conductor/epic-reconcile.js +0 -603
  61. package/build/conductor/epic-runtime.js +0 -2020
  62. package/build/conductor/epic-state.js +0 -774
@@ -31,6 +31,9 @@ const USAGE = [
31
31
  " write epic-plan.meta.json ({\"epic_key\": ...}) beside the DAG so",
32
32
  " drive-epic can find the plan from the epic key. Each file is a",
33
33
  " separate atomic write, not one transaction across all three.",
34
+ " Then save the finished plan to the Bridge server (BAPI-1706) so",
35
+ " anyone with repository access can run it. A failed save is a",
36
+ " warning with the exact retry command; finalize still succeeds.",
34
37
  "",
35
38
  "Options:",
36
39
  " --input <file> JSON document with epic_key, epic_slug, mappings,",
@@ -129,6 +132,7 @@ export async function runEpicImplementerBundleCli(argv, overrides = {}) {
129
132
  log: (m) => console.log(m),
130
133
  // Diagnostics go to stderr so `--json` keeps stdout a single result object.
131
134
  errorLog: (m) => console.error(m),
135
+ saveAuthoredPlan: (input) => defaultSaveAuthoredPlan(input, overrides.env ?? process.env, overrides.cwd ?? process.cwd()),
132
136
  ...overrides,
133
137
  };
134
138
  let opts;
@@ -247,6 +251,29 @@ export async function runEpicImplementerBundleCli(argv, overrides = {}) {
247
251
  return emitFailure(`Could not write meta_path ${validation.value.meta_path}. The sidecar and manifest may ` +
248
252
  "already be finalized. Re-run finalize, or check write permissions on the docs directory.");
249
253
  }
254
+ // BAPI-1706: save the finished folder to the normal Bridge server, AFTER the
255
+ // metadata exists. A failed save never fails finalize: the tickets and the
256
+ // local files already stand, so it is a warning with the exact retry command.
257
+ const saveOutcome = await saveAuthoredPlanSafely(deps, {
258
+ epicKey: validation.value.epic_key,
259
+ planDir: path.dirname(validation.value.meta_path),
260
+ });
261
+ const { renderAuthoredPlanNotSaved, renderAuthoredPlanSaved } = await import("./authored-plan.js");
262
+ const authoredPlan = saveOutcome.ok
263
+ ? {
264
+ saved: true,
265
+ created: saveOutcome.created,
266
+ authored_version: saveOutcome.result.snapshot.authored_version,
267
+ plan_hash: saveOutcome.result.snapshot.plan_hash,
268
+ saved_by: saveOutcome.result.snapshot.saved_by,
269
+ saved_at: saveOutcome.result.snapshot.saved_at,
270
+ endpoint: saveOutcome.endpoint,
271
+ }
272
+ : { saved: false, reason: saveOutcome.reason, retry_command: saveOutcome.retryCommand };
273
+ if (!saveOutcome.ok) {
274
+ for (const line of renderAuthoredPlanNotSaved(saveOutcome))
275
+ deps.errorLog(`Warning: ${line}`);
276
+ }
250
277
  const result = {
251
278
  ok: true,
252
279
  mode: "finalize",
@@ -256,15 +283,49 @@ export async function runEpicImplementerBundleCli(argv, overrides = {}) {
256
283
  manifest_path: validation.value.manifest_path,
257
284
  meta_path: validation.value.meta_path,
258
285
  ticket_keys: validation.value.mappings.map((m) => m.ticket_key),
286
+ authored_plan: authoredPlan,
259
287
  };
260
288
  if (opts.json)
261
289
  deps.log(JSON.stringify(result));
262
290
  else {
263
291
  deps.log(`Finalized ${result.sidecar_path} with ${result.ticket_keys.length} real key(s) ` +
264
292
  `and per-node touched_files. Manifest: ${result.manifest_path}`);
293
+ if (saveOutcome.ok)
294
+ deps.log(renderAuthoredPlanSaved(saveOutcome));
265
295
  }
266
296
  return 0;
267
297
  }
298
+ /** Call the saver; a thrown error becomes a fixed not-saved outcome. */
299
+ async function saveAuthoredPlanSafely(deps, input) {
300
+ try {
301
+ if (deps.saveAuthoredPlan !== undefined)
302
+ return await deps.saveAuthoredPlan(input);
303
+ return await defaultSaveAuthoredPlan(input, deps.env, deps.cwd);
304
+ }
305
+ catch {
306
+ const { renderEpicPlanSaveCommand } = await import("./authored-plan.js");
307
+ return {
308
+ ok: false,
309
+ epicKey: input.epicKey,
310
+ reason: "server_unknown",
311
+ planDir: input.planDir,
312
+ retryCommand: renderEpicPlanSaveCommand(deps.env, input),
313
+ };
314
+ }
315
+ }
316
+ /**
317
+ * The real saver: the general Bridge resolver (never a launch profile), resolved
318
+ * against this invocation's own environment and working directory.
319
+ */
320
+ async function defaultSaveAuthoredPlan(input, env, cwd) {
321
+ const { createDefaultAuthoredPlanSaveDeps, saveLocalAuthoredPlan } = await import("./authored-plan.js");
322
+ const { resolveConductorBridgeApiAccess } = await import("./conductor/bridge-api-client.js");
323
+ return saveLocalAuthoredPlan({
324
+ ...createDefaultAuthoredPlanSaveDeps(),
325
+ env,
326
+ resolveAccess: (repo) => resolveConductorBridgeApiAccess({ env, cwd, ...(repo !== undefined ? { repoName: repo } : {}) }),
327
+ }, input);
328
+ }
268
329
  /** Real filesystem seam, loaded lazily so importing this module stays cheap. */
269
330
  function createDefaultBundleFs() {
270
331
  return {
@@ -1,5 +1,5 @@
1
1
  #!/usr/bin/env node
2
2
  import{realpathSync}from"node:fs";import path from"node:path";import{fileURLToPath}from"node:url";function isBinEntrypoint(callerModuleUrl,argv1=process.argv[1]){if(argv1===void 0)return!1;let callerPath=fileURLToPath(callerModuleUrl);try{return realpathSync(argv1)===realpathSync(callerPath)}catch{return path.resolve(argv1)===callerPath}}import{spawnSync}from"node:child_process";import{readFileSync}from"node:fs";var CONDUCTOR_HOOK_EMIT_FAILED_WARNING="Warning: conductor hook emit failed.";function resolveClaudeHookEventName(payload){if(payload===null||typeof payload!="object"||Array.isArray(payload))return null;let record=payload,candidates=["hook_event_name","hookEventName","event_name","event"];for(let key of candidates){let value=record[key];if(typeof value=="string"&&value.trim().length>0)return value.trim()}return null}function mapClaudeHookEventToSemanticType(eventName){switch(eventName){case"SessionStart":return"run.started";case"SessionEnd":return"run.stopped";case"Stop":return null;case"SubagentStop":return null;case"Notification":return"agent.notification";case"PreToolUse":return"tool.intent";default:return null}}var REQUIRED_IDENTITY_ENV=["BAPI_EPIC_IMPLEMENTER_RUN_ID","BAPI_EPIC_IMPLEMENTER_WORKER_ID","BAPI_EPIC_IMPLEMENTER_TICKET_KEY","BAPI_EPIC_IMPLEMENTER_WORKTREE_PATH"];function nonEmpty(value){return typeof value=="string"&&value.trim().length>0}function buildClaudeHookConductorEvent(payload,env){let eventName=resolveClaudeHookEventName(payload),type=mapClaudeHookEventToSemanticType(eventName);if(type===null||env.BAPI_EPIC_IMPLEMENTER_ENABLED!=="1")return null;for(let key of REQUIRED_IDENTITY_ENV)if(!nonEmpty(env[key]))return null;let ticketKey=env.BAPI_EPIC_IMPLEMENTER_TICKET_KEY.trim(),worktreePath=env.BAPI_EPIC_IMPLEMENTER_WORKTREE_PATH.trim(),details={ticket_key:ticketKey,worktree_path:worktreePath};nonEmpty(env.BAPI_EPIC_IMPLEMENTER_REPO_NAME)&&(details.repo=env.BAPI_EPIC_IMPLEMENTER_REPO_NAME.trim());let raw=payload!==null&&typeof payload=="object"&&!Array.isArray(payload)?payload:{payload};return{source:"claude-code",type,subject:ticketKey,run_id:env.BAPI_EPIC_IMPLEMENTER_RUN_ID.trim(),worker_id:env.BAPI_EPIC_IMPLEMENTER_WORKER_ID.trim(),producer:"claude-code-hook",observed_via:"claude-code-hook",data:{details,raw}}}function buildConductorEmitEventArgs(event){let args=["--type",event.type,"--source",event.source];return nonEmpty(event.subject??void 0)&&args.push("--subject",event.subject),nonEmpty(event.run_id??void 0)&&args.push("--run-id",event.run_id),nonEmpty(event.worker_id??void 0)&&args.push("--worker-id",event.worker_id),nonEmpty(event.producer??void 0)&&args.push("--producer",event.producer),nonEmpty(event.observed_via??void 0)&&args.push("--observed-via",event.observed_via),args.push("--data-json-stdin","--json"),args}function resolveConductorEmitCommand(env,emitArgs){let cliFile=env.BAPI_EPIC_IMPLEMENTER_CLI_FILE;return nonEmpty(cliFile)?{command:process.execPath,args:[cliFile.trim(),"emit-event",...emitArgs]}:{command:nonEmpty(env.BAPI_EPIC_IMPLEMENTER_BIN)?env.BAPI_EPIC_IMPLEMENTER_BIN.trim():"epic-implementer",args:["emit-event",...emitArgs]}}var defaultConductorSpawn=(command,args,input)=>{let result=spawnSync(command,args,{input,encoding:"utf-8",shell:!1});return{status:result.status,error:result.error}};function emitClaudeHookEventWithConductorCli(event,deps={}){let env=deps.env??process.env,spawn=deps.spawn??defaultConductorSpawn,emitArgs=buildConductorEmitEventArgs(event),{command,args}=resolveConductorEmitCommand(env,emitArgs),stdinPayload=JSON.stringify(event.data??{});try{let result=spawn(command,args,stdinPayload);return result.error?!1:result.status===0}catch{return!1}}function runClaudeConductorHookCli(deps={}){let env=deps.env??process.env,readStdin=deps.readStdin??(()=>readStdinSync()),warn=deps.warn??(m=>process.stderr.write(`${m}
3
- `)),payload;try{let raw=readStdin();payload=JSON.parse(raw)}catch{return warn(CONDUCTOR_HOOK_EMIT_FAILED_WARNING),0}let event;try{event=buildClaudeHookConductorEvent(payload,env)}catch{return warn(CONDUCTOR_HOOK_EMIT_FAILED_WARNING),0}return event===null||emitClaudeHookEventWithConductorCli(event,{env,spawn:deps.spawn})||warn(CONDUCTOR_HOOK_EMIT_FAILED_WARNING),0}function readStdinSync(){return readFileSync(0,"utf-8")}var LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX="BAPI_CONDUCTOR_",EPIC_IMPLEMENTER_ENV_PREFIX="BAPI_EPIC_IMPLEMENTER_",LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV="CONDUCTOR_NODE_PATH",EPIC_IMPLEMENTER_NODE_PATH_ENV="EPIC_IMPLEMENTER_NODE_PATH",renamed=suffix=>[`${LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX}${suffix}`,{kind:"renamed",successor:`${EPIC_IMPLEMENTER_ENV_PREFIX}${suffix}`}],RENAMED_SUFFIXES=["ALLOW_LIVE_SOURCE_DISPATCH","BIN","BUSY_TIMEOUT_MS","CLI_FILE","DEAD_AFTER_MS","DECLARED_TOUCHED_FILES_JSON","DENY_PROBE_TIMEOUT_MS","DISPATCH_DRY_RUN","ENABLE_PRE_TOOL_USE","ENABLED","EPIC_KEY","EPIC_RUN_ID","ESCALATION_COOLDOWN_MS","GATE_NAME","GLOBAL_TIMEOUT_MS","HOOK_COMMAND","LIVE_SOURCE_PATH","LIVENESS_STALLED_AFTER_MS","MESSAGE_COOLDOWN_MS","PLAN_VERSION","QUIET_AFTER_MS","REPO_NAME","RETENTION_DAYS","RETENTION_MAX_ROWS","RUN_ID","STALL_ACTIVE_MS","STALL_BLOCKED_MS","STALL_CANDIDATE_DONE_MS","STALL_NOT_STARTED_MS","STALL_STALLED_MS","STALL_UNKNOWN_MS","STALL_VERIFYING_MS","SUPERVISOR_MODE","SUPERVISOR_POLL_LIMIT","TICKET_KEY","WAKE_INTERVAL_MS","WORKER_ID","WORKTREE_PATH"],LEGACY_EPIC_IMPLEMENTER_ENV_MAPPINGS=new Map([...RENAMED_SUFFIXES.map(renamed),[`${LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX}ALLOW_CLAUDE_MCP_SHADOWING`,{kind:"retired"}],[LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV,{kind:"renamed",successor:EPIC_IMPLEMENTER_NODE_PATH_ENV}],["CONDUCTOR_DEAD_MAN_ONLY",{kind:"renamed",successor:"EPIC_IMPLEMENTER_DEAD_MAN_ONLY"}],["CONDUCTOR_DEADMAN_CHANNEL_TYPE",{kind:"renamed",successor:"EPIC_IMPLEMENTER_DEADMAN_CHANNEL_TYPE"}],["CONDUCTOR_DEADMAN_DESTINATION_REF",{kind:"renamed",successor:"EPIC_IMPLEMENTER_DEADMAN_DESTINATION_REF"}]]);function isLegacyEpicImplementerEnvKey(key){return key.startsWith(LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX)||key===LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV||key==="CONDUCTOR_DEAD_MAN_ONLY"||key==="CONDUCTOR_DEADMAN_CHANNEL_TYPE"||key==="CONDUCTOR_DEADMAN_DESTINATION_REF"}function findLegacyEpicImplementerEnv(env){return Object.keys(env).filter(isLegacyEpicImplementerEnvKey).sort((a,b)=>a<b?-1:a>b?1:0).map(key=>({key,mapping:LEGACY_EPIC_IMPLEMENTER_ENV_MAPPINGS.get(key)??null}))}var LEGACY_EPIC_IMPLEMENTER_ENV_ERROR_HEADER="Error: legacy Conductor environment variables are set. They were renamed to the Epic Implementer names and are no longer read. Update or remove each one, then retry:";function describeFinding(finding){let{key,mapping}=finding;return mapping===null?` ${key}: unknown legacy setting. If it is still a current setting, rename the ${LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX} prefix to ${EPIC_IMPLEMENTER_ENV_PREFIX}; otherwise remove it.`:mapping.kind==="retired"?` ${key}: retired with no replacement. Remove it.`:` ${key} -> ${mapping.successor}`}function formatLegacyEpicImplementerEnvError(findings){return[LEGACY_EPIC_IMPLEMENTER_ENV_ERROR_HEADER,...findings.map(describeFinding)].join(`
3
+ `)),payload;try{let raw=readStdin();payload=JSON.parse(raw)}catch{return warn(CONDUCTOR_HOOK_EMIT_FAILED_WARNING),0}let event;try{event=buildClaudeHookConductorEvent(payload,env)}catch{return warn(CONDUCTOR_HOOK_EMIT_FAILED_WARNING),0}return event===null||emitClaudeHookEventWithConductorCli(event,{env,spawn:deps.spawn})||warn(CONDUCTOR_HOOK_EMIT_FAILED_WARNING),0}function readStdinSync(){return readFileSync(0,"utf-8")}var LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX="BAPI_CONDUCTOR_",EPIC_IMPLEMENTER_ENV_PREFIX="BAPI_EPIC_IMPLEMENTER_",LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV="CONDUCTOR_NODE_PATH",EPIC_IMPLEMENTER_NODE_PATH_ENV="EPIC_IMPLEMENTER_NODE_PATH",renamed=suffix=>[`${LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX}${suffix}`,{kind:"renamed",successor:`${EPIC_IMPLEMENTER_ENV_PREFIX}${suffix}`}],RENAMED_SUFFIXES=["ALLOW_LIVE_SOURCE_DISPATCH","BIN","BUSY_TIMEOUT_MS","CLI_FILE","DEAD_AFTER_MS","DECLARED_TOUCHED_FILES_JSON","DENY_PROBE_TIMEOUT_MS","ENABLE_PRE_TOOL_USE","ENABLED","EPIC_KEY","EPIC_RUN_ID","ESCALATION_COOLDOWN_MS","GATE_NAME","GLOBAL_TIMEOUT_MS","HOOK_COMMAND","LIVE_SOURCE_PATH","LIVENESS_STALLED_AFTER_MS","MESSAGE_COOLDOWN_MS","PLAN_VERSION","QUIET_AFTER_MS","REPO_NAME","RETENTION_DAYS","RETENTION_MAX_ROWS","RUN_ID","STALL_ACTIVE_MS","STALL_BLOCKED_MS","STALL_CANDIDATE_DONE_MS","STALL_NOT_STARTED_MS","STALL_STALLED_MS","STALL_UNKNOWN_MS","STALL_VERIFYING_MS","SUPERVISOR_MODE","SUPERVISOR_POLL_LIMIT","TICKET_KEY","WAKE_INTERVAL_MS","WORKER_ID","WORKTREE_PATH"],LEGACY_EPIC_IMPLEMENTER_ENV_MAPPINGS=new Map([...RENAMED_SUFFIXES.map(renamed),[`${LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX}ALLOW_CLAUDE_MCP_SHADOWING`,{kind:"retired"}],[LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV,{kind:"renamed",successor:EPIC_IMPLEMENTER_NODE_PATH_ENV}],["CONDUCTOR_DEAD_MAN_ONLY",{kind:"renamed",successor:"EPIC_IMPLEMENTER_DEAD_MAN_ONLY"}],["CONDUCTOR_DEADMAN_CHANNEL_TYPE",{kind:"renamed",successor:"EPIC_IMPLEMENTER_DEADMAN_CHANNEL_TYPE"}],["CONDUCTOR_DEADMAN_DESTINATION_REF",{kind:"renamed",successor:"EPIC_IMPLEMENTER_DEADMAN_DESTINATION_REF"}]]);function isLegacyEpicImplementerEnvKey(key){return key.startsWith(LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX)||key===LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV||key==="CONDUCTOR_DEAD_MAN_ONLY"||key==="CONDUCTOR_DEADMAN_CHANNEL_TYPE"||key==="CONDUCTOR_DEADMAN_DESTINATION_REF"}function findLegacyEpicImplementerEnv(env){return Object.keys(env).filter(isLegacyEpicImplementerEnvKey).sort((a,b)=>a<b?-1:a>b?1:0).map(key=>({key,mapping:LEGACY_EPIC_IMPLEMENTER_ENV_MAPPINGS.get(key)??null}))}var LEGACY_EPIC_IMPLEMENTER_ENV_ERROR_HEADER="Error: legacy Conductor environment variables are set. They were renamed to the Epic Implementer names and are no longer read. Update or remove each one, then retry:";function describeFinding(finding){let{key,mapping}=finding;return mapping===null?` ${key}: unknown legacy setting. If it is still a current setting, rename the ${LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX} prefix to ${EPIC_IMPLEMENTER_ENV_PREFIX}; otherwise remove it.`:mapping.kind==="retired"?` ${key}: retired with no replacement. Remove it.`:` ${key} -> ${mapping.successor}`}function formatLegacyEpicImplementerEnvError(findings){return[LEGACY_EPIC_IMPLEMENTER_ENV_ERROR_HEADER,...findings.map(describeFinding)].join(`
4
4
  `)+`
5
5
  `}function runLegacyEpicImplementerEnvPreflight(env,writeStderr){let findings=findLegacyEpicImplementerEnv(env);return findings.length===0?0:(writeStderr(formatLegacyEpicImplementerEnvError(findings)),1)}function runEpicImplementerClaudeHookBin(deps={}){let handler=deps.handler??runClaudeConductorHookCli,exit=deps.exit??process.exit.bind(process),writeStderr=deps.writeStderr??(chunk=>process.stderr.write(chunk));if(runLegacyEpicImplementerEnvPreflight(deps.env??process.env,writeStderr)!==0){exit(0);return}let exitCode=0;try{exitCode=handler()}catch{exitCode=0}exit(exitCode)}isBinEntrypoint(import.meta.url)&&runEpicImplementerClaudeHookBin();export{runEpicImplementerClaudeHookBin};
@@ -47,7 +47,7 @@ const renamed = (suffix) => [
47
47
  { kind: "renamed", successor: `${EPIC_IMPLEMENTER_ENV_PREFIX}${suffix}` },
48
48
  ];
49
49
  /**
50
- * The 38 live renamed `BAPI_CONDUCTOR_*` suffixes, as inventoried from non-test
50
+ * The 37 live renamed `BAPI_CONDUCTOR_*` suffixes, as inventoried from non-test
51
51
  * `mcp_server/src/**\/*.ts` at HEAD `45d854081` (re-confirmed at `315572187`).
52
52
  *
53
53
  * Deliberately absent: `PUBLISHED_IDENTITY_FIXTURE` (removed from source), the
@@ -55,7 +55,7 @@ const renamed = (suffix) => [
55
55
  * `supervisor-retired-judgment.static.test.ts`), and test-only sentinels. All of
56
56
  * those still fall through to the generic prefix pointer.
57
57
  *
58
- * These 38 prefix-derived suffixes are distinct from the three BAPI-1237
58
+ * These 37 prefix-derived suffixes are distinct from the three BAPI-1237
59
59
  * exact-name dead-man entries added directly to
60
60
  * {@link LEGACY_EPIC_IMPLEMENTER_ENV_MAPPINGS} below: the dead-man names carry no
61
61
  * `BAPI_CONDUCTOR_` prefix at all, so they cannot be expressed as a suffix here.
@@ -68,7 +68,6 @@ const RENAMED_SUFFIXES = [
68
68
  "DEAD_AFTER_MS",
69
69
  "DECLARED_TOUCHED_FILES_JSON",
70
70
  "DENY_PROBE_TIMEOUT_MS",
71
- "DISPATCH_DRY_RUN",
72
71
  "ENABLE_PRE_TOOL_USE",
73
72
  "ENABLED",
74
73
  "EPIC_KEY",
@@ -101,7 +100,7 @@ const RENAMED_SUFFIXES = [
101
100
  "WORKTREE_PATH",
102
101
  ];
103
102
  /**
104
- * Old name -> resolution. Exactly 43 keys: the 38 `BAPI_CONDUCTOR_*`
103
+ * Old name -> resolution. Exactly 42 keys: the 37 `BAPI_CONDUCTOR_*`
105
104
  * prefix-derived renamed names above, the retired shadowing override (inert
106
105
  * since BAPI-790; this supersedes that ticket's "no error" promise), the
107
106
  * exact-name node-path variable, and the three BAPI-1237 exact-name dead-man
@@ -255,7 +255,7 @@ async function maybeMakeReady(gh, prNumber, isDraft, requestReady, cwd, headBind
255
255
  }
256
256
  }
257
257
  async function ensureEpicIntegrationPullRequestInner(options) {
258
- const { epicKey, epicBranch, baseBranch, command, gh, cwd, requestReady, expectedHeadSha, repo } = options;
258
+ const { epicKey, epicBranch, baseBranch, command, gh, cwd, requestReady, expectedHeadSha, repo, createIfAbsent = true, } = options;
259
259
  const bind = (observedHeadSha) => expectedHeadSha === undefined ? undefined : { expectedHeadSha, observedHeadSha };
260
260
  const probe = await probeMatchingOpenPr(gh, epicBranch, baseBranch, cwd, repo);
261
261
  if (probe.kind === "unavailable") {
@@ -265,7 +265,10 @@ async function ensureEpicIntegrationPullRequestInner(options) {
265
265
  const readiness = await maybeMakeReady(gh, probe.number, probe.isDraft, requestReady, cwd, bind(probe.headSha), repo);
266
266
  return { kind: "already_open", reason: "already_open", prNumber: probe.number, readiness };
267
267
  }
268
- // Confirmed absent: create.
268
+ // Confirmed absent: create, unless this caller may only act on an open PR.
269
+ if (!createIfAbsent) {
270
+ return { kind: "deferred", reason: "no_open_pr" };
271
+ }
269
272
  const created = await createDraftPr(gh, epicKey, epicBranch, baseBranch, command, cwd, repo);
270
273
  if (created.kind === "no_commits") {
271
274
  return { kind: "deferred", reason: "no_commits_between_branches" };
@@ -254,6 +254,9 @@ export const CHECK_REASON_VALUES = [
254
254
  "ownership_lost",
255
255
  "executor_cancelled",
256
256
  "spawn_failed",
257
+ // BAPI-1698 — killed by a signal nobody on the executor side requested: a
258
+ // failed run (`exited_nonzero`), never an interruption or a launch error.
259
+ "killed_by_signal",
257
260
  ];
258
261
  /**
259
262
  * BAPI-1302 — what the executor saw of the final local artifact (full HEAD plus
@@ -402,6 +405,25 @@ export function verificationVerdictFromFacts(facts, declaredCount) {
402
405
  * A delivered command result (BAPI-1455) only resolves its task's execution.
403
406
  * Verification, finalization, cleanup, and denials still decide on their own.
404
407
  */
408
+ /**
409
+ * The one cleanup shape the success path admits besides confirmed-and-zero: a
410
+ * failed verdict with a positive integer survivor count and exactly the single
411
+ * reason `survivors_detected`. That shape proves the sweep stopped the detected
412
+ * processes and the confirmation sweep found none remaining. It does not change
413
+ * the recorded failed verdict. Mixed, duplicate, or empty reason lists never match.
414
+ */
415
+ export function isAllStoppedCleanup(cleanup) {
416
+ if (typeof cleanup !== "object" || cleanup === null)
417
+ return false;
418
+ const c = cleanup;
419
+ return (c.verdict === "failed" &&
420
+ typeof c.survivors === "number" &&
421
+ Number.isInteger(c.survivors) &&
422
+ c.survivors > 0 &&
423
+ Array.isArray(c.reasons) &&
424
+ c.reasons.length === 1 &&
425
+ c.reasons[0] === "survivors_detected");
426
+ }
405
427
  export function successRefusalReason(envelope) {
406
428
  if (envelope.evidence !== "sufficient")
407
429
  return "evidence_insufficient";
@@ -415,7 +437,8 @@ export function successRefusalReason(envelope) {
415
437
  if (envelope.finalization !== "ok" && envelope.finalization !== "not_required") {
416
438
  return "finalization_not_met";
417
439
  }
418
- if (envelope.cleanup.verdict !== "confirmed" || envelope.cleanup.survivors !== 0) {
440
+ if ((envelope.cleanup.verdict !== "confirmed" || envelope.cleanup.survivors !== 0) &&
441
+ !isAllStoppedCleanup(envelope.cleanup)) {
419
442
  return "cleanup_not_confirmed";
420
443
  }
421
444
  if (envelope.denials.some((d) => d.state === "blocking"))
@@ -55,17 +55,38 @@
55
55
  * result keeps exactly the pre-existing shape (no `dependency_preparation`).
56
56
  * Every message and fact stays value-free: no install output, path, argv, or
57
57
  * environment value.
58
+ *
59
+ * 7. **A declared worker database is provisioned exactly as a worker job's is
60
+ * (BAPI-1698).** When the SEALED declaration carries a disposable
61
+ * `worker_database`, the job provisions it through the executor's existing
62
+ * worker-resource seam after dependency preparation and before any command,
63
+ * runs the commands with the database environment a worker would get, and
64
+ * drops it before the checkout is removed. A completed provisioning failure
65
+ * is a COMPLETED job (`worker_database_preparation: "failed"`, every command
66
+ * `not_run`); a cancelled provisioning is an interruption. Such a job
67
+ * requires `gate_qualification.worker_database.v1`, so an older executor
68
+ * leaves it queued.
69
+ *
70
+ * 8. **Best-effort evidence that tests ran (BAPI-1698).** A command that exited
71
+ * zero is checked against a small, conservative set of plain signs that it
72
+ * executed no tests (see `gate-qualification-tests-ran.ts`). Such a command
73
+ * reports the qualification-only `no_tests_ran`, which never passes. This is
74
+ * not proof that tests ran: an unfamiliar, quiet, or ambiguous command keeps
75
+ * its pass.
58
76
  */
59
77
  import { createHash } from "node:crypto";
60
- import { mkdtemp, rm } from "node:fs/promises";
78
+ import { mkdtemp, readFile, rm } from "node:fs/promises";
61
79
  import os from "node:os";
62
80
  import path from "node:path";
63
81
  import { validateBranchName } from "../base-ref.js";
64
82
  import { parseDependencyInstallStrict, } from "../dependency-install-declarations.js";
65
83
  import { refreshDeclaredDependencies } from "./dependency-refresh.js";
84
+ import { assessTestsRanInCheckout } from "./gate-qualification-tests-ran.js";
66
85
  import { buildDependencyInstallEnv, buildExecutorBaseWorkerEnv } from "./env.js";
86
+ import { parseWorkerDatabasePayload, workerEnvNamesOf, } from "./worker-database-config.js";
87
+ import { formatWorkerDatabaseDropFailedLine, formatWorkerDatabaseUnavailableLine } from "./worker-database.js";
67
88
  import { ARTIFACT_GIT_TIMEOUT_MS, OWNERSHIP_POLL_MS, canonicalJson, createSupervisedCommandLauncher, preCheckArtifactState, runRequiredVerificationCommands, toCompletionCheckFact, } from "./required-verification.js";
68
- import { GATE_QUALIFICATION_CAPABILITY, } from "./types.js";
89
+ import { GATE_QUALIFICATION_CAPABILITY, GATE_QUALIFICATION_WORKER_DATABASE_CAPABILITY, } from "./types.js";
69
90
  // ---------------------------------------------------------------------------
70
91
  // Contract constants
71
92
  // ---------------------------------------------------------------------------
@@ -98,11 +119,18 @@ export const GATE_QUALIFICATION_DEADLINE_RESERVE_MS = 60_000;
98
119
  const HEX64_RE = /^[0-9a-f]{64}$/;
99
120
  const FULL_SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
100
121
  const SYMREF_HEAD_RE = /^ref: refs\/heads\/(\S+)\tHEAD$/m;
122
+ /**
123
+ * BAPI-1698 — a qualification-ONLY command outcome: the command exited zero, but
124
+ * the executor found plain evidence that it executed no tests. It never appears
125
+ * in a worker completion, so the shared {@link CheckOutcome} is unchanged.
126
+ */
127
+ export const GATE_QUALIFICATION_NO_TESTS_RAN = "no_tests_ran";
101
128
  /** Fixed `/fail` messages, one per inability. */
102
129
  const MESSAGES = {
103
130
  contract: "gate_qualification payload failed contract validation",
104
131
  capability: "gate_qualification job does not require the gate qualification capability",
105
132
  repo: "gate_qualification payload names a different repository than the job",
133
+ databaseCapability: "gate_qualification job with a worker database does not require the worker database capability",
106
134
  defaultBranch: "default branch could not be resolved",
107
135
  fetch: "default branch could not be fetched",
108
136
  revParse: "default branch commit could not be resolved",
@@ -235,6 +263,20 @@ export function parseGateQualificationPayload(job) {
235
263
  return refuse(MESSAGES.contract);
236
264
  dependencyInstallOption = { dependencyInstall: entries };
237
265
  }
266
+ // BAPI-1698: the worker database is read from the SIGNED body only, through the
267
+ // worker pathway's own parser. Only a valid disposable declaration is sealed;
268
+ // anything else is refused before any git or process effect.
269
+ let workerDatabaseOption = {};
270
+ if (Object.prototype.hasOwnProperty.call(envelope, "worker_database")) {
271
+ const database = parseWorkerDatabasePayload(envelope.worker_database, workerEnvNamesOf(envelope.worker_env));
272
+ if (database.classification !== "enabled")
273
+ return refuse(MESSAGES.contract);
274
+ if (Array.isArray(job.required_capabilities) &&
275
+ !job.required_capabilities.includes(GATE_QUALIFICATION_WORKER_DATABASE_CAPABILITY)) {
276
+ return refuse(MESSAGES.databaseCapability);
277
+ }
278
+ workerDatabaseOption = { workerDatabase: database.config };
279
+ }
238
280
  // The envelope digest covers the object exactly as received, minus its own
239
281
  // digest key, so any field the server signed is checked byte for byte.
240
282
  const { digest, ...signed } = envelope;
@@ -253,6 +295,7 @@ export function parseGateQualificationPayload(job) {
253
295
  ? { workerEnv: envelope.worker_env }
254
296
  : {},
255
297
  dependencyInstallOption,
298
+ workerDatabaseOption,
256
299
  },
257
300
  };
258
301
  }
@@ -319,17 +362,16 @@ async function removeCheckout(deps, dir) {
319
362
  // Best effort: a leftover temporary directory costs disk, never correctness.
320
363
  }
321
364
  }
322
- // ---------------------------------------------------------------------------
323
- // The core
324
- // ---------------------------------------------------------------------------
325
365
  function toResultFact(fact) {
326
366
  // The shared server-bound view, minus `position`: the result envelope keys
327
- // each fact by identity only.
367
+ // each fact by identity only. BAPI-1698: a zero-test pass reports the
368
+ // qualification-only `no_tests_ran`, which carries no reason.
328
369
  const bounded = toCompletionCheckFact(fact);
370
+ const noTests = fact.qualificationOutcome === GATE_QUALIFICATION_NO_TESTS_RAN;
329
371
  return {
330
372
  identity: bounded.identity,
331
- outcome: bounded.outcome,
332
- reason: bounded.reason,
373
+ outcome: noTests ? GATE_QUALIFICATION_NO_TESTS_RAN : bounded.outcome,
374
+ reason: noTests ? null : bounded.reason,
333
375
  duration_ms: bounded.duration_ms,
334
376
  };
335
377
  }
@@ -341,20 +383,27 @@ function isInterruptionFact(fact) {
341
383
  }
342
384
  /**
343
385
  * Fold what was observed into one classification, by fixed precedence:
344
- * interruption, preparation failure, any `launch_error`/`spawn_failed` fact, any
345
- * other unsuccessful or not-run fact, then passed. The server derives the same
346
- * phase from the stored result; the completion envelope carries no `phase`.
386
+ * interruption, dependency preparation failure, worker-database preparation
387
+ * failure (BAPI-1698), any `launch_error`/`spawn_failed` fact, any other
388
+ * unsuccessful or not-run fact except `no_tests_ran`, then `no_tests_ran`
389
+ * (BAPI-1698), then passed. The server derives the same phase from the stored
390
+ * result; the completion envelope carries no `phase`.
347
391
  */
348
392
  export function foldGateQualificationOutcome(input) {
349
393
  if (input.facts.some(isInterruptionFact))
350
394
  return "interrupted";
351
395
  if (input.preparationFailed === true)
352
396
  return "dependency_preparation_failed";
397
+ if (input.databasePreparationFailed === true)
398
+ return "worker_database_preparation_failed";
353
399
  if (input.facts.some((fact) => fact.outcome === "launch_error" || fact.reason === "spawn_failed")) {
354
400
  return "could_not_start";
355
401
  }
356
- if (input.facts.some((fact) => fact.outcome !== "exited_zero"))
402
+ if (input.facts.some((fact) => fact.outcome !== "exited_zero" && fact.outcome !== GATE_QUALIFICATION_NO_TESTS_RAN)) {
357
403
  return "ran_and_failed";
404
+ }
405
+ if (input.facts.some((fact) => fact.outcome === GATE_QUALIFICATION_NO_TESTS_RAN))
406
+ return "no_tests_ran";
358
407
  return "passed";
359
408
  }
360
409
  /**
@@ -363,7 +412,10 @@ export function foldGateQualificationOutcome(input) {
363
412
  * Returns the bounded result envelope, or a fixed-text inability. Never throws
364
413
  * for a git, process, or payload condition, and never returns command output.
365
414
  */
366
- export async function runGateQualificationJob(job, input, deps) {
415
+ export async function runGateQualificationJob(
416
+ // BAPI-1698: `id` names the job's worker database. Optional only so callers
417
+ // that never seal a database keep their shape; the executor always passes it.
418
+ job, input, deps) {
367
419
  const startedAt = deps.now();
368
420
  const inability = (errorKind, message) => {
369
421
  deps.errorLog(`[gate_qualification] ${message}`);
@@ -404,6 +456,12 @@ export async function runGateQualificationJob(job, input, deps) {
404
456
  catch {
405
457
  return inability(GATE_QUALIFICATION_CHECKOUT_UNAVAILABLE, MESSAGES.checkout);
406
458
  }
459
+ const jobId = job.id !== undefined ? String(job.id) : "gate-qualification";
460
+ // BAPI-1698: the provisioned worker database, set only once provisioning
461
+ // returned both a target and its role. Dropped in `finally`, before the
462
+ // checkout is removed.
463
+ let databaseTarget;
464
+ let databaseRole;
407
465
  try {
408
466
  const added = await git(deps, ["worktree", "add", "--detach", dir, sha], GATE_QUALIFICATION_WORKTREE_ADD_TIMEOUT_MS);
409
467
  if (!added.ok)
@@ -448,7 +506,9 @@ export async function runGateQualificationJob(job, input, deps) {
448
506
  }));
449
507
  const dependencyInstall = payload.dependencyInstallOption.dependencyInstall;
450
508
  const installDeclared = dependencyInstall !== undefined;
509
+ const workerDatabase = payload.workerDatabaseOption.workerDatabase;
451
510
  let preparationFailed = false;
511
+ let databasePreparationFailed = false;
452
512
  let facts = [];
453
513
  try {
454
514
  // BAPI-1637 — dependency preparation, only when the sealed declaration
@@ -480,7 +540,54 @@ export async function runGateQualificationJob(job, input, deps) {
480
540
  return inability(GATE_QUALIFICATION_INTERRUPTED, MESSAGES.interrupted);
481
541
  preparationFailed = refreshed.stale.length > 0;
482
542
  }
483
- if (preparationFailed) {
543
+ // BAPI-1698 — the sealed disposable worker database, after a successful
544
+ // dependency preparation and before any command, through the executor's
545
+ // existing worker-resource seam. A failed dependency preparation means the
546
+ // database is never attempted; it still reports as not ready.
547
+ if (workerDatabase !== undefined) {
548
+ if (preparationFailed) {
549
+ databasePreparationFailed = true;
550
+ }
551
+ else if (deps.workerResources === undefined) {
552
+ databasePreparationFailed = true;
553
+ deps.errorLog("[gate_qualification] worker database unavailable: this executor cannot provision one");
554
+ }
555
+ else {
556
+ const provisioned = await deps.workerResources
557
+ .provisionDatabase({
558
+ jobId,
559
+ worktreePath: dir,
560
+ signal: commandAbort.signal,
561
+ config: workerDatabase,
562
+ // BAPI-1521 — own-key forwarding: absence keeps the legacy migration env.
563
+ ...payload.workerEnvOption,
564
+ })
565
+ .catch(() => ({ kind: "unavailable", category: "create_failed" }));
566
+ if (provisioned.kind === "provisioned") {
567
+ databaseTarget = provisioned.target;
568
+ databaseRole = provisioned.role;
569
+ }
570
+ else if (provisioned.category === "cancelled" || commandAbort.signal.aborted) {
571
+ // A cancelled provisioning proved nothing about the gate: an inability.
572
+ return inability(GATE_QUALIFICATION_INTERRUPTED, MESSAGES.interrupted);
573
+ }
574
+ else {
575
+ databasePreparationFailed = true;
576
+ try {
577
+ const cause = "cause" in provisioned ? provisioned.cause : undefined;
578
+ deps.errorLog(formatWorkerDatabaseUnavailableLine(jobId, provisioned.category, cause));
579
+ // A created database whose rollback failed stays for the host operator.
580
+ if ("retainedName" in provisioned && provisioned.retainedName) {
581
+ deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, provisioned.retainedName));
582
+ }
583
+ }
584
+ catch {
585
+ /* sink */
586
+ }
587
+ }
588
+ }
589
+ }
590
+ if (preparationFailed || databasePreparationFailed) {
484
591
  // The install did not complete, so nothing was launched. One bounded
485
592
  // `not_run` fact per declared command, in declaration order.
486
593
  facts = commands.map((command) => ({
@@ -497,7 +604,12 @@ export async function runGateQualificationJob(job, input, deps) {
497
604
  // BAPI-1521 — the effective environment is built here, AFTER the envelope
498
605
  // was verified and BEFORE any command runs, from the sealed declaration.
499
606
  // The injected dependencies are never mutated.
500
- const commandEnv = deps.commandEnv ?? buildGateQualificationEnv(deps.baseEnv ?? {}, payload.workerEnvOption);
607
+ // BAPI-1698: a provisioned worker database reaches the commands through
608
+ // the worker environment builder's own explicit options, never ambiently.
609
+ const commandEnv = deps.commandEnv ??
610
+ buildGateQualificationEnv(deps.baseEnv ?? {}, payload.workerEnvOption, workerDatabase !== undefined && databaseTarget !== undefined
611
+ ? { workerDatabase: databaseTarget, workerDatabaseConfig: workerDatabase }
612
+ : {});
501
613
  const run = await runRequiredVerificationCommands({
502
614
  commands,
503
615
  worktreePath: dir,
@@ -517,21 +629,52 @@ export async function runGateQualificationJob(job, input, deps) {
517
629
  deps.clearTimer(watchTimer);
518
630
  input.signal.removeEventListener("abort", onOuterAbort);
519
631
  }
520
- // Names and closed tokens only: no argv, no output, no path.
632
+ // BAPI-1698 — best-effort executing-test evidence, applied AFTER the shared
633
+ // runner made every execution decision (so it never stops a later command)
634
+ // and while the detached checkout still exists. Only an exit-zero fact is
635
+ // assessed, from the output tail the runner already kept.
636
+ const readTextFile = deps.readTextFile ??
637
+ (async () => {
638
+ throw new Error("no reader");
639
+ });
640
+ const qualificationFacts = [];
521
641
  for (const fact of facts) {
522
- deps.log(`[gate_qualification] command ${fact.position} (${fact.name.slice(0, 60)}): ${fact.outcome}${fact.reason ? ` (${fact.reason})` : ""}`);
523
- if (deps.showLocalOutput && fact.outcome !== "exited_zero" && fact.output.trim().length > 0) {
524
- deps.errorLog(`[gate_qualification] output tail for ${fact.name.slice(0, 60)}:\n${fact.output}`);
642
+ let qualificationOutcome = fact.outcome;
643
+ if (fact.outcome === "exited_zero") {
644
+ const command = commands.find((candidate) => candidate.identity === fact.identity);
645
+ if (command !== undefined) {
646
+ const assessment = await assessTestsRanInCheckout({
647
+ argv: command.argv,
648
+ output: fact.output,
649
+ checkoutDir: dir,
650
+ readFile: readTextFile,
651
+ });
652
+ if (assessment === "no_tests")
653
+ qualificationOutcome = GATE_QUALIFICATION_NO_TESTS_RAN;
654
+ }
655
+ }
656
+ qualificationFacts.push({ ...fact, qualificationOutcome });
657
+ }
658
+ // Ordinals and closed tokens only: no name, argv, output, or path reaches a
659
+ // persistent log (BAPI-1698: a command name is owner-authored text).
660
+ for (const fact of qualificationFacts) {
661
+ deps.log(`[gate_qualification] command ${fact.position}: ${fact.qualificationOutcome}${fact.qualificationOutcome !== GATE_QUALIFICATION_NO_TESTS_RAN && fact.reason ? ` (${fact.reason})` : ""}`);
662
+ if (deps.showLocalOutput && fact.qualificationOutcome !== "exited_zero" && fact.output.trim().length > 0) {
663
+ deps.errorLog(`[gate_qualification] output tail for command ${fact.position}:\n${fact.output}`);
525
664
  }
526
665
  }
527
666
  // 5. An interruption proved nothing about the gate: an inability, never a
528
667
  // completed "failed" that the server would record as unqualified. A completed
529
668
  // preparation failure, by contrast, IS a result.
530
- const folded = foldGateQualificationOutcome({ facts, preparationFailed });
669
+ const folded = foldGateQualificationOutcome({
670
+ facts: qualificationFacts.map((fact) => ({ outcome: fact.qualificationOutcome, reason: fact.reason })),
671
+ preparationFailed,
672
+ databasePreparationFailed,
673
+ });
531
674
  if (folded === "interrupted") {
532
675
  return inability(GATE_QUALIFICATION_INTERRUPTED, MESSAGES.interrupted);
533
676
  }
534
- const resultFacts = facts.map(toResultFact);
677
+ const resultFacts = qualificationFacts.map(toResultFact);
535
678
  return {
536
679
  ok: true,
537
680
  result: {
@@ -543,10 +686,30 @@ export async function runGateQualificationJob(job, input, deps) {
543
686
  ...(installDeclared
544
687
  ? { dependency_preparation: preparationFailed ? "failed" : "ready" }
545
688
  : {}),
689
+ ...(workerDatabase !== undefined
690
+ ? {
691
+ worker_database_preparation: databaseTarget !== undefined && !databasePreparationFailed ? "ready" : "failed",
692
+ }
693
+ : {}),
546
694
  },
547
695
  };
548
696
  }
549
697
  finally {
698
+ // BAPI-1698: the worker database goes first, while its checkout still
699
+ // exists, and only when provisioning returned both a target and a role.
700
+ if (databaseTarget !== undefined && databaseRole !== undefined && deps.workerResources !== undefined) {
701
+ const dropped = await deps.workerResources
702
+ .dropDatabase(databaseTarget, databaseRole)
703
+ .catch(() => ({ kind: "failed" }));
704
+ if (dropped.kind !== "dropped") {
705
+ try {
706
+ deps.errorLog(formatWorkerDatabaseDropFailedLine(jobId, databaseTarget.name));
707
+ }
708
+ catch {
709
+ /* sink */
710
+ }
711
+ }
712
+ }
550
713
  await removeCheckout(deps, dir);
551
714
  }
552
715
  }
@@ -560,9 +723,11 @@ export async function runGateQualificationJob(job, input, deps) {
560
723
  * BAPI-1521: the sealed declaration's `worker_env` is passed with its presence
561
724
  * intact — absent keeps the compatibility constants, present replaces them.
562
725
  */
563
- export function buildGateQualificationEnv(parentEnv, workerEnvOption = {}) {
726
+ export function buildGateQualificationEnv(parentEnv, workerEnvOption = {}, databaseOption = {}) {
564
727
  // BAPI-1521: `CI=1` is applied last, so a declaration can never turn it off.
565
- return { ...buildExecutorBaseWorkerEnv(parentEnv, workerEnvOption), CI: "1" };
728
+ // BAPI-1698: a provisioned worker database uses the builder's existing explicit
729
+ // options, so the commands see exactly the database keys a worker would.
730
+ return { ...buildExecutorBaseWorkerEnv(parentEnv, { ...workerEnvOption, ...databaseOption }), CI: "1" };
566
731
  }
567
732
  /**
568
733
  * Production dependencies built from the executor's own boundary.
@@ -611,5 +776,10 @@ export function createProductionGateQualificationDeps(input) {
611
776
  ...(deps.runDependencyInstall ? { runDependencyInstall: deps.runDependencyInstall } : {}),
612
777
  sleep: deps.sleep,
613
778
  platform: deps.platform,
779
+ // BAPI-1698: the checkout's root `package.json`, read for test-script indirection only.
780
+ readTextFile: (filePath) => readFile(filePath, "utf8"),
781
+ // BAPI-1698: the executor's existing worker-resource seam, forwarded as is.
782
+ // Only the executor CLI supplies it; the default deps never provision.
783
+ ...(deps.workerResources ? { workerResources: deps.workerResources } : {}),
614
784
  };
615
785
  }