@bridge_gpt/mcp-server 0.2.73 → 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.
- package/README.md +14 -7
- package/build/agent-launchers/claude-executor-adapter.js +12 -0
- package/build/agent-launchers/prompt.js +9 -21
- package/build/agents.generated.js +4 -4
- package/build/authored-plan.js +542 -0
- package/build/bridge-config.js +7 -1
- package/build/bridge-permissions.js +11 -0
- package/build/command-provisioning.js +4 -3
- package/build/commands.generated.js +6 -6
- package/build/conductor/bridge-api-client.js +692 -47
- package/build/conductor/command-drift.js +1 -1
- package/build/conductor/declared-extras.js +335 -0
- package/build/conductor/doctor.js +2 -0
- package/build/conductor/driver-pass-output.js +104 -0
- package/build/conductor/driver-pass.js +571 -0
- package/build/conductor/epic-branch-ci-inspection.js +61 -16
- package/build/conductor/epic-implementer-cli.js +370 -93
- package/build/conductor/epic-server-sfcc-upload.js +1567 -0
- package/build/conductor/epic-server-sfcc.js +58 -80
- package/build/conductor/epic-server.js +57 -4
- package/build/conductor/gate-discovery.js +253 -13
- package/build/conductor/gate-settings-review.js +58 -25
- package/build/conductor/launch-plan.js +58 -12
- package/build/conductor/open-decision-phrases.js +50 -0
- package/build/conductor/prerequisite-inputs.js +181 -14
- package/build/connect-github-api.js +18 -0
- package/build/connect-github.js +35 -18
- package/build/credential-delivery.js +280 -0
- package/build/credential-launch-safety.js +142 -0
- package/build/credential-materialization.js +91 -16
- package/build/credential-references-node-deps.js +29 -0
- package/build/credential-references.js +1394 -0
- package/build/credential-references.test-fixtures.js +211 -0
- package/build/credential-scan-conventions.js +145 -0
- package/build/credential-scan.js +517 -0
- package/build/credential-store.js +50 -0
- package/build/credentials-cli.js +252 -3
- package/build/dependency-install-declarations.js +47 -1
- package/build/docs.generated.js +8 -1
- package/build/doctor.js +41 -0
- package/build/drive-epic.js +684 -49
- package/build/epic-branch-ci-summary.js +18 -1
- package/build/epic-capability-statement.js +71 -3
- package/build/epic-ci-workflow-drift.js +52 -13
- package/build/epic-ci-workflow-install.js +31 -6
- package/build/epic-ci-workflow-v3.js +273 -0
- package/build/epic-ci-workflow.js +129 -7
- package/build/epic-implementer-bin.js +288 -83
- package/build/epic-implementer-bundle-cli.js +61 -0
- package/build/epic-implementer-claude-hook-bin.js +1 -1
- package/build/epic-implementer-env.js +3 -4
- package/build/epic-integration-pr.js +5 -2
- package/build/epic-launch-context.js +102 -7
- package/build/epic-server-record.js +30 -15
- package/build/executor/completion-contract.js +24 -1
- package/build/executor/credential-delivery-step.js +168 -0
- package/build/executor/deps.js +3 -1
- package/build/executor/env.js +39 -1
- package/build/executor/epic-server-context.js +23 -7
- package/build/executor/gate-qualification-job.js +193 -23
- package/build/executor/gate-qualification-tests-ran.js +232 -0
- package/build/executor/guarded-fast-forward-push.js +13 -8
- package/build/executor/job-runner.js +167 -738
- package/build/executor/job-type-wrappers.js +734 -0
- package/build/executor/permissions.js +85 -3
- package/build/executor/preflight.js +6 -2
- package/build/executor/process-containment.js +8 -1
- package/build/executor/prompt-spec.js +37 -3
- package/build/executor/required-verification.js +28 -2
- package/build/executor/runner.js +4 -1
- package/build/executor/types.js +9 -0
- package/build/executor/worker-database.js +6 -1
- package/build/executor/worker-guard-hook.js +24 -2
- package/build/executor-launch.js +4 -2
- package/build/generated/ticket-status.js +20 -0
- package/build/git-exclude-lock.js +187 -0
- package/build/index.js +589 -326
- package/build/install-bridge-conductor-answers.js +112 -22
- package/build/install-bridge-conductor-apply.js +38 -1
- package/build/install-bridge-conductor-assessment.js +482 -53
- package/build/install-bridge-conductor-compact.js +29 -2
- package/build/install-bridge-conductor-contracts.js +10 -1
- package/build/install-bridge-conductor-gate.js +379 -89
- package/build/install-bridge-conductor-setup.js +46 -8
- package/build/install-bridge-conductor-trial-report.js +170 -0
- package/build/install-bridge-conductor.js +925 -141
- package/build/install-bridge.js +88 -11
- package/build/install-doctor.js +38 -8
- package/build/install-sfcc-detection.js +120 -0
- package/build/install-sfcc-setup.js +185 -0
- package/build/mcp-grant-candidates.js +108 -96
- package/build/mcp-invoke.js +168 -4
- package/build/mcp-provisioning.js +21 -4
- package/build/mcp-server-invocation.js +13 -0
- package/build/merge-workflow-install.js +9 -1
- package/build/pipelines.generated.js +8 -7
- package/build/plan-generation.js +17 -0
- package/build/plane/status.js +8 -2
- package/build/printed-remedy-commands.js +59 -0
- package/build/project-root.js +40 -0
- package/build/readme.generated.js +1 -1
- package/build/repository-state-paths.js +5 -2
- package/build/repository-toolchains.js +16 -7
- package/build/scripts/saved-commands-config-field-driver.js +65 -0
- package/build/setup-epic.js +126 -16
- package/build/sfcc/credentials.js +3 -2
- package/build/sfcc/hostname.js +98 -2
- package/build/sfcc/tool-wrapper.js +6 -95
- package/build/start-tickets.js +193 -29
- package/build/test-support/executor-source-files.js +200 -0
- package/build/testing-config-client.js +25 -2
- package/build/third-party-mcp-targets.js +35 -4
- package/build/v2-readiness-requirements.js +5 -1
- package/build/version.generated.js +3 -3
- package/build/with-credentials.js +208 -0
- package/build/worker-guard-hook-bin.js +2 -2
- package/build/worktree-credential-delivery.js +340 -0
- package/docs/EPIC-IMPLEMENTER.md +4 -4
- package/docs/install/github-app.md +79 -92
- package/package.json +1 -1
- package/build/conductor/epic-reconcile.js +0 -603
- package/build/conductor/epic-runtime.js +0 -2020
- 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","
|
|
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
|
|
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
|
|
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
|
|
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" };
|
|
@@ -275,16 +275,22 @@ async function removeIfRegularFile(fs, target) {
|
|
|
275
275
|
// Best effort.
|
|
276
276
|
}
|
|
277
277
|
}
|
|
278
|
-
/**
|
|
279
|
-
|
|
280
|
-
|
|
278
|
+
/**
|
|
279
|
+
* Write one allowlisted JSON document beside the other per-epic run-state files.
|
|
280
|
+
* Never throws and never persists exception text: the failure is a closed code.
|
|
281
|
+
* Shared by the launch-context and launch-outcome writers so both keep the same
|
|
282
|
+
* 0700 directory, 0600 file, exclusive temporary file, symlink refusal, atomic
|
|
283
|
+
* rename, and best-effort cleanup.
|
|
284
|
+
*/
|
|
285
|
+
async function writeRunStateDocument(epicKey, fileName, document, options) {
|
|
286
|
+
if (!EPIC_KEY_RE.test(epicKey))
|
|
281
287
|
return { ok: false, reason: "invalid_epic_key" };
|
|
282
288
|
const fs = options.fs ?? NODE_LAUNCH_CONTEXT_FS;
|
|
283
289
|
const root = options.stateDir ?? defaultRunStateDir();
|
|
284
|
-
const dir = path.join(root,
|
|
285
|
-
const destination = path.join(dir,
|
|
290
|
+
const dir = path.join(root, epicKey);
|
|
291
|
+
const destination = path.join(dir, fileName);
|
|
286
292
|
const suffix = (options.randomSuffix ?? (() => `${process.pid}-${Date.now()}-${Math.random().toString(16).slice(2)}`))();
|
|
287
|
-
const temporary = path.join(dir, `.${
|
|
293
|
+
const temporary = path.join(dir, `.${fileName}.${suffix}.tmp`);
|
|
288
294
|
// The directory: created 0700, or an existing real directory tightened to 0700.
|
|
289
295
|
try {
|
|
290
296
|
await fs.mkdir(dir, { recursive: true, mode: 0o700 });
|
|
@@ -312,7 +318,7 @@ export async function writeEpicLaunchContext(context, options = {}) {
|
|
|
312
318
|
let handle = null;
|
|
313
319
|
try {
|
|
314
320
|
handle = await fs.open(temporary, fsConstants.O_WRONLY | fsConstants.O_CREAT | fsConstants.O_EXCL | (fsConstants.O_NOFOLLOW ?? 0), 0o600);
|
|
315
|
-
await handle.writeFile(`${JSON.stringify(
|
|
321
|
+
await handle.writeFile(`${JSON.stringify(document, null, 2)}\n`);
|
|
316
322
|
await handle.close();
|
|
317
323
|
handle = null;
|
|
318
324
|
await fs.chmod(temporary, 0o600);
|
|
@@ -328,6 +334,95 @@ export async function writeEpicLaunchContext(context, options = {}) {
|
|
|
328
334
|
return { ok: false, reason: "write_failed" };
|
|
329
335
|
}
|
|
330
336
|
}
|
|
337
|
+
/** Write the launch-context file. Never throws. */
|
|
338
|
+
export async function writeEpicLaunchContext(context, options = {}) {
|
|
339
|
+
return writeRunStateDocument(context.epic_key, LAUNCH_CONTEXT_FILE_NAME, context, options);
|
|
340
|
+
}
|
|
341
|
+
// ---------------------------------------------------------------------------
|
|
342
|
+
// BAPI-1686 — the launch-outcome record
|
|
343
|
+
// ---------------------------------------------------------------------------
|
|
344
|
+
//
|
|
345
|
+
// `launch-outcome.json` sits beside `launch-context.json` and says how ONE
|
|
346
|
+
// `drive-epic` invocation ended: what it proved about the run, whether it refused
|
|
347
|
+
// before any create request, any epic branch it moved, and what happened to a
|
|
348
|
+
// plane it started. It is an explicit allowlisted projection; no setup result,
|
|
349
|
+
// server response, or observation object is ever spread into it. It carries no
|
|
350
|
+
// credential, email address, command, raw server text, or free-form diagnostic
|
|
351
|
+
// message, and a failed write returns a closed code, never exception text.
|
|
352
|
+
// Writing is best-effort and never a stop.
|
|
353
|
+
/** The schema of the launch-outcome record. */
|
|
354
|
+
export const LAUNCH_OUTCOME_SCHEMA_VERSION = 1;
|
|
355
|
+
/** The file name under the epic's run-state directory. */
|
|
356
|
+
export const LAUNCH_OUTCOME_FILE_NAME = "launch-outcome.json";
|
|
357
|
+
/** The closed values of {@link LaunchOutcomeWindDown}. */
|
|
358
|
+
export const LAUNCH_OUTCOME_WIND_DOWN_VALUES = [
|
|
359
|
+
"not_applicable", "pending", "completed", "failed",
|
|
360
|
+
];
|
|
361
|
+
/** The launch outcomes drive-epic and setup-epic already share (not a second vocabulary). */
|
|
362
|
+
const LAUNCH_OUTCOME_VALUES = [
|
|
363
|
+
"active", "pending_activation", "not_confirmed", "refused", "terminal",
|
|
364
|
+
];
|
|
365
|
+
const OBSERVATION_CODE_RE = /^[a-z][a-z0-9_]{0,63}$/;
|
|
366
|
+
const RUN_ID_RE = /^[A-Za-z0-9_-]{1,100}$/;
|
|
367
|
+
const RUN_STATUS_RE = /^[a-z_]{1,40}$/;
|
|
368
|
+
const GIT_SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
|
|
369
|
+
const MAX_OUTCOME_OBSERVATIONS = 32;
|
|
370
|
+
const isoOrNull = (value) => typeof value === "string" && !Number.isNaN(Date.parse(value)) && value.length <= 40 ? value : null;
|
|
371
|
+
/**
|
|
372
|
+
* Project untrusted launch facts into the allowlisted document, or `null` when a
|
|
373
|
+
* required field is invalid. Optional fields that fail validation become `null`
|
|
374
|
+
* (or the safe default) rather than being copied.
|
|
375
|
+
*/
|
|
376
|
+
export function projectLaunchOutcome(input) {
|
|
377
|
+
if (!EPIC_KEY_RE.test(input.epicKey))
|
|
378
|
+
return null;
|
|
379
|
+
const invokedAt = isoOrNull(input.invokedAt);
|
|
380
|
+
const writtenAt = isoOrNull(input.writtenAt);
|
|
381
|
+
if (invokedAt === null || writtenAt === null)
|
|
382
|
+
return null;
|
|
383
|
+
if (!LAUNCH_OUTCOME_VALUES.includes(input.launchOutcome))
|
|
384
|
+
return null;
|
|
385
|
+
const move = input.branchMove;
|
|
386
|
+
const branchMove = move != null && BRANCH_RE.test(move.branch) && GIT_SHA_RE.test(move.from) && GIT_SHA_RE.test(move.to)
|
|
387
|
+
? { branch: move.branch, from: move.from, to: move.to }
|
|
388
|
+
: null;
|
|
389
|
+
const codes = [];
|
|
390
|
+
for (const entry of input.observations ?? []) {
|
|
391
|
+
const code = entry?.code;
|
|
392
|
+
if (typeof code === "string" && OBSERVATION_CODE_RE.test(code) && !codes.includes(code))
|
|
393
|
+
codes.push(code);
|
|
394
|
+
if (codes.length >= MAX_OUTCOME_OBSERVATIONS)
|
|
395
|
+
break;
|
|
396
|
+
}
|
|
397
|
+
return {
|
|
398
|
+
schema_version: LAUNCH_OUTCOME_SCHEMA_VERSION,
|
|
399
|
+
epic_key: input.epicKey,
|
|
400
|
+
invoked_at: invokedAt,
|
|
401
|
+
written_at: writtenAt,
|
|
402
|
+
launch_outcome: input.launchOutcome,
|
|
403
|
+
epic_run_id: typeof input.epicRunId === "string" && RUN_ID_RE.test(input.epicRunId) ? input.epicRunId : null,
|
|
404
|
+
run_status: typeof input.runStatus === "string" && RUN_STATUS_RE.test(input.runStatus) ? input.runStatus : null,
|
|
405
|
+
refused_before_create: input.refusedBeforeCreate === true,
|
|
406
|
+
branch_move: branchMove,
|
|
407
|
+
wind_down: input.windDown !== undefined && LAUNCH_OUTCOME_WIND_DOWN_VALUES.includes(input.windDown)
|
|
408
|
+
? input.windDown
|
|
409
|
+
: "not_applicable",
|
|
410
|
+
observations: codes,
|
|
411
|
+
};
|
|
412
|
+
}
|
|
413
|
+
/** Write `launch-outcome.json`. Never throws; the result is a closed code on failure. */
|
|
414
|
+
export async function writeEpicLaunchOutcome(input, options = {}) {
|
|
415
|
+
try {
|
|
416
|
+
const document = projectLaunchOutcome(input);
|
|
417
|
+
if (document === null) {
|
|
418
|
+
return { ok: false, reason: EPIC_KEY_RE.test(input.epicKey) ? "write_failed" : "invalid_epic_key" };
|
|
419
|
+
}
|
|
420
|
+
return await writeRunStateDocument(document.epic_key, LAUNCH_OUTCOME_FILE_NAME, document, options);
|
|
421
|
+
}
|
|
422
|
+
catch {
|
|
423
|
+
return { ok: false, reason: "write_failed" };
|
|
424
|
+
}
|
|
425
|
+
}
|
|
331
426
|
const UNKNOWN_REASONS = new Set([
|
|
332
427
|
"readiness_unknown",
|
|
333
428
|
"not_reported",
|
|
@@ -8,14 +8,25 @@
|
|
|
8
8
|
* required version: 1
|
|
9
9
|
* required mode: "none" | "local" | "sfcc_shared_active"
|
|
10
10
|
* optional recipe: "present" | "absent"
|
|
11
|
-
* sfcc_shared_active
|
|
11
|
+
* sfcc_shared_active, required:
|
|
12
12
|
* sfcc: { sandbox_id, credential_ref, storefront_origin }
|
|
13
|
+
* local / none, optional (BAPI-1669):
|
|
14
|
+
* sfcc: { sandbox_id, credential_ref, storefront_origin? }
|
|
13
15
|
*
|
|
14
|
-
*
|
|
15
|
-
*
|
|
16
|
-
*
|
|
17
|
-
*
|
|
18
|
-
*
|
|
16
|
+
* An approved sandbox is allowed beside every mode: the upload verb needs only
|
|
17
|
+
* the approved sandbox, and the mode only picks where browser checks run. The
|
|
18
|
+
* version stays 1. An older reader rejects `sfcc` on a local or none record, so
|
|
19
|
+
* it reads one as `unusable` (fail-safe: no server). Reader and writer ship
|
|
20
|
+
* together.
|
|
21
|
+
*
|
|
22
|
+
* `sandbox_id` is a non-secret instance identifier. `credential_ref` is the name
|
|
23
|
+
* of an entry in this repository's worker credential record (BAPI-1667), the one
|
|
24
|
+
* for the sandbox account; a legacy credential-store target such as `sfcc:<id>`
|
|
25
|
+
* still validates and reads as before. Nothing resolves it yet, so it is
|
|
26
|
+
* informational. The record NEVER holds a secret value. `storefront_origin` is the approved http(s) origin
|
|
27
|
+
* the browser is limited to; it is required for `sfcc_shared_active` and optional
|
|
28
|
+
* otherwise, but must normalize when present. A `local` record with `sfcc` is
|
|
29
|
+
* still local to the local-helper verbs.
|
|
19
30
|
*
|
|
20
31
|
* Unknown top-level keys are tolerated, matching the grant's schema rule. This
|
|
21
32
|
* module is the ONLY reader and writer of the record: the setup item, the
|
|
@@ -89,17 +100,25 @@ export function normalizeStorefrontOrigin(value) {
|
|
|
89
100
|
function isPlainObject(value) {
|
|
90
101
|
return value !== null && typeof value === "object" && !Array.isArray(value);
|
|
91
102
|
}
|
|
92
|
-
function validateSfccTarget(raw) {
|
|
103
|
+
function validateSfccTarget(raw, originRequired) {
|
|
93
104
|
if (!isPlainObject(raw))
|
|
94
105
|
return null;
|
|
95
106
|
if (!isValidSfccSandboxId(raw.sandbox_id))
|
|
96
107
|
return null;
|
|
97
108
|
if (!isValidCredentialReference(raw.credential_ref))
|
|
98
109
|
return null;
|
|
110
|
+
const target = { sandbox_id: raw.sandbox_id, credential_ref: raw.credential_ref };
|
|
111
|
+
if (raw.storefront_origin === undefined) {
|
|
112
|
+
if (originRequired)
|
|
113
|
+
return null;
|
|
114
|
+
return target;
|
|
115
|
+
}
|
|
116
|
+
// A supplied origin must normalize in every mode; it is never treated as omitted.
|
|
99
117
|
const origin = normalizeStorefrontOrigin(raw.storefront_origin);
|
|
100
118
|
if (origin === null)
|
|
101
119
|
return null;
|
|
102
|
-
|
|
120
|
+
target.storefront_origin = origin;
|
|
121
|
+
return target;
|
|
103
122
|
}
|
|
104
123
|
/** Validate a parsed record. Unknown top-level keys are dropped. */
|
|
105
124
|
export function validateEpicServerRecord(raw) {
|
|
@@ -116,16 +135,12 @@ export function validateEpicServerRecord(raw) {
|
|
|
116
135
|
return null;
|
|
117
136
|
record.recipe = doc.recipe;
|
|
118
137
|
}
|
|
119
|
-
if (record.mode === "sfcc_shared_active") {
|
|
120
|
-
const sfcc = validateSfccTarget(doc.sfcc);
|
|
138
|
+
if (record.mode === "sfcc_shared_active" || doc.sfcc !== undefined) {
|
|
139
|
+
const sfcc = validateSfccTarget(doc.sfcc, record.mode === "sfcc_shared_active");
|
|
121
140
|
if (sfcc === null)
|
|
122
141
|
return null;
|
|
123
142
|
record.sfcc = sfcc;
|
|
124
143
|
}
|
|
125
|
-
else if (doc.sfcc !== undefined) {
|
|
126
|
-
// SFCC-only fields on a local or none record are a malformed record.
|
|
127
|
-
return null;
|
|
128
|
-
}
|
|
129
144
|
return record;
|
|
130
145
|
}
|
|
131
146
|
// ---------------------------------------------------------------------------
|
|
@@ -181,7 +196,7 @@ export function formatEpicServerRecord(record) {
|
|
|
181
196
|
out.sfcc = {
|
|
182
197
|
sandbox_id: record.sfcc.sandbox_id,
|
|
183
198
|
credential_ref: record.sfcc.credential_ref,
|
|
184
|
-
storefront_origin: record.sfcc.storefront_origin,
|
|
199
|
+
...(record.sfcc.storefront_origin !== undefined ? { storefront_origin: record.sfcc.storefront_origin } : {}),
|
|
185
200
|
};
|
|
186
201
|
}
|
|
187
202
|
return `${JSON.stringify(out, null, 2)}\n`;
|
|
@@ -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"))
|
|
@@ -0,0 +1,168 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* BAPI-1647: referenced-credential delivery for one executor worker start.
|
|
3
|
+
*
|
|
4
|
+
* Every reference operation is keyed on the claimed job's `repo_name` — the
|
|
5
|
+
* identity from the server's claim response, the same one
|
|
6
|
+
* `provisionMcpForPreparedSpawn` selects the MCP grant by — and runs in the
|
|
7
|
+
* executor's own process. Nothing is read from the worktree's checkout to decide
|
|
8
|
+
* what a worker receives.
|
|
9
|
+
*
|
|
10
|
+
* Two phases, in spawn-path order:
|
|
11
|
+
*
|
|
12
|
+
* 1. {@link readExecutorCredentialApprovals} — before the deny layer: one
|
|
13
|
+
* names-only record read plus child 1's `statusOnly()`, which yields every
|
|
14
|
+
* restricted entry's source path (missing ones included) for the
|
|
15
|
+
* `Read(<path>)` deny rules, and the reference inputs MCP provisioning uses.
|
|
16
|
+
* 2. {@link prepareExecutorCredentialDelivery} — after MCP provisioning and
|
|
17
|
+
* before the final `.env*` strip: child 1's `forWorkerLaunch()`, the shared
|
|
18
|
+
* reconciled, exclusion-first file delivery, and the sandbox variables for
|
|
19
|
+
* the env builder. Values live only in the returned in-memory map.
|
|
20
|
+
*
|
|
21
|
+
* Nothing here fails or parks a job: every problem becomes a names-only notice
|
|
22
|
+
* for the worker prompt and the executor's local per-job log.
|
|
23
|
+
*/
|
|
24
|
+
import { forWorkerLaunch, statusOnly, } from "../credential-references.js";
|
|
25
|
+
import { createLaunchCredentialReferenceDeps, emptyApprovalMetadata, formatNoticeLines, launchResolveOptions, readApprovalMetadata, } from "../credential-delivery.js";
|
|
26
|
+
import { createNodeWorktreeCredentialDeliveryDeps, deliverWorktreeFileCredentials, } from "../worktree-credential-delivery.js";
|
|
27
|
+
import { isWorkerEnvNameReserved } from "./env.js";
|
|
28
|
+
function referenceDeps(deps, worktreePath) {
|
|
29
|
+
return createLaunchCredentialReferenceDeps(deps.env, worktreePath, { homedir: deps.homedir });
|
|
30
|
+
}
|
|
31
|
+
function recordReadDeps(deps) {
|
|
32
|
+
const base = referenceDeps(deps);
|
|
33
|
+
const read = deps.readFile;
|
|
34
|
+
if (!read)
|
|
35
|
+
return base;
|
|
36
|
+
return { ...base, readFile: read, readBytes: async (p) => Buffer.from(await read(p), "utf-8") };
|
|
37
|
+
}
|
|
38
|
+
/** Phase 1: names-only record read and restricted source paths. Never throws. */
|
|
39
|
+
export async function readExecutorCredentialApprovals(repoName, deps, seams = {}) {
|
|
40
|
+
let approvals;
|
|
41
|
+
try {
|
|
42
|
+
approvals = seams.readApprovals
|
|
43
|
+
? await seams.readApprovals(repoName)
|
|
44
|
+
: await readApprovalMetadata(repoName, recordReadDeps(deps));
|
|
45
|
+
}
|
|
46
|
+
catch {
|
|
47
|
+
approvals = { state: "record_unusable", reason: "record_unreadable", metadata: emptyApprovalMetadata() };
|
|
48
|
+
}
|
|
49
|
+
let restrictedSourcePaths = [];
|
|
50
|
+
if (approvals.state === "ok") {
|
|
51
|
+
try {
|
|
52
|
+
const status = seams.statusOnly
|
|
53
|
+
? await seams.statusOnly(repoName)
|
|
54
|
+
: await statusOnly(repoName, referenceDeps(deps));
|
|
55
|
+
if (status.state === "ok") {
|
|
56
|
+
restrictedSourcePaths = [
|
|
57
|
+
...new Set(status.statuses.filter((st) => st.level === "restricted").flatMap((st) => st.source_paths ?? [])),
|
|
58
|
+
];
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
catch {
|
|
62
|
+
restrictedSourcePaths = [];
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
return { approvals, restrictedSourcePaths };
|
|
66
|
+
}
|
|
67
|
+
/**
|
|
68
|
+
* Node-backed delivery deps for the no-approval reconcile. The Bridge state
|
|
69
|
+
* file is read through the executor's injected reader, so a worktree with no
|
|
70
|
+
* earlier Bridge links does no filesystem work outside the runner's boundary.
|
|
71
|
+
*/
|
|
72
|
+
function reconcileDeliveryDeps(deps) {
|
|
73
|
+
const base = createNodeWorktreeCredentialDeliveryDeps(deps.runCommand, deps.platform);
|
|
74
|
+
return deps.readFile ? { ...base, readFile: deps.readFile } : base;
|
|
75
|
+
}
|
|
76
|
+
/** Phase 2: resolve and deliver for one worker start. Never throws. */
|
|
77
|
+
export async function prepareExecutorCredentialDelivery(repoName, worktreePath, approvals, deps, seams = {}) {
|
|
78
|
+
const prep = {
|
|
79
|
+
recordState: approvals.state,
|
|
80
|
+
...(approvals.reason ? { recordReason: approvals.reason } : {}),
|
|
81
|
+
declaredCredentialEnv: {},
|
|
82
|
+
selected: [],
|
|
83
|
+
deliveredFiles: [],
|
|
84
|
+
offeredEnv: [],
|
|
85
|
+
eligibleMcp: [...new Set(approvals.metadata.mcp.map((d) => d.entry))],
|
|
86
|
+
notices: [],
|
|
87
|
+
};
|
|
88
|
+
// An absent or unusable record approves nothing. Reconciliation still runs
|
|
89
|
+
// so a link Bridge recorded at an earlier start (a retained or reused
|
|
90
|
+
// worktree) is withdrawn instead of surviving revocation. With no Bridge
|
|
91
|
+
// state file this is a no-op, so prompt, env, and argv stay unchanged.
|
|
92
|
+
const reconcileOnly = async (recordState) => {
|
|
93
|
+
try {
|
|
94
|
+
const reconciled = await deliverWorktreeFileCredentials({ worktreeRoot: worktreePath, recordState, files: [], approved: [] }, seams.deliveryDeps ?? reconcileDeliveryDeps(deps));
|
|
95
|
+
prep.notices.push(...reconciled.notices);
|
|
96
|
+
}
|
|
97
|
+
catch {
|
|
98
|
+
// Delivery never throws; contained anyway so this step never fails a job.
|
|
99
|
+
}
|
|
100
|
+
};
|
|
101
|
+
if (approvals.state !== "ok") {
|
|
102
|
+
await reconcileOnly(approvals.state);
|
|
103
|
+
return prep;
|
|
104
|
+
}
|
|
105
|
+
// Selected from the names-only approvals BEFORE resolving, so a resolver
|
|
106
|
+
// failure can still name every credential the worker did not receive.
|
|
107
|
+
const envEntries = new Set(Object.values(approvals.metadata.envOwners));
|
|
108
|
+
const fileEntries = new Set(approvals.metadata.files.map((f) => f.entry));
|
|
109
|
+
prep.selected = [...new Set([...fileEntries, ...envEntries])];
|
|
110
|
+
try {
|
|
111
|
+
const resolution = seams.resolveWorkerLaunch
|
|
112
|
+
? await seams.resolveWorkerLaunch(repoName, worktreePath)
|
|
113
|
+
: await forWorkerLaunch(repoName, referenceDeps(deps, worktreePath), launchResolveOptions(worktreePath));
|
|
114
|
+
prep.recordState = resolution.state;
|
|
115
|
+
if (resolution.state !== "ok") {
|
|
116
|
+
await reconcileOnly(resolution.state);
|
|
117
|
+
return prep;
|
|
118
|
+
}
|
|
119
|
+
for (const u of resolution.unavailable)
|
|
120
|
+
prep.notices.push({ name: u.name, reason: u.reason });
|
|
121
|
+
const delivered = await deliverWorktreeFileCredentials({ worktreeRoot: worktreePath, recordState: resolution.state, files: resolution.files, approved: approvals.metadata.files }, seams.deliveryDeps ?? createNodeWorktreeCredentialDeliveryDeps(deps.runCommand, deps.platform));
|
|
122
|
+
prep.deliveredFiles = [...new Set(delivered.delivered.map((d) => d.name))];
|
|
123
|
+
prep.notices.push(...delivered.notices);
|
|
124
|
+
for (const [name, value] of Object.entries(resolution.env)) {
|
|
125
|
+
// Rechecked here so the worker notice can name it; the env builder
|
|
126
|
+
// rechecks again and also drops a collision with an executor-owned key.
|
|
127
|
+
if (isWorkerEnvNameReserved(name)) {
|
|
128
|
+
prep.notices.push({ name, reason: "reserved_name" });
|
|
129
|
+
continue;
|
|
130
|
+
}
|
|
131
|
+
prep.declaredCredentialEnv[name] = value;
|
|
132
|
+
prep.offeredEnv.push(name);
|
|
133
|
+
}
|
|
134
|
+
}
|
|
135
|
+
catch {
|
|
136
|
+
prep.declaredCredentialEnv = {};
|
|
137
|
+
prep.offeredEnv = [];
|
|
138
|
+
prep.notices.push(...prep.selected.map((name) => ({ name, reason: "unreadable" })));
|
|
139
|
+
}
|
|
140
|
+
return prep;
|
|
141
|
+
}
|
|
142
|
+
/** Notice lines for the worker prompt (one record-level line when unusable). */
|
|
143
|
+
export function credentialNoticeLines(prep) {
|
|
144
|
+
return formatNoticeLines(prep.recordState, prep.notices, prep.recordReason);
|
|
145
|
+
}
|
|
146
|
+
/**
|
|
147
|
+
* Names-only audit lines for the executor's local per-job log. MCP entries are
|
|
148
|
+
* reported as `eligible` only: the executor never sees an MCP server launch, so
|
|
149
|
+
* it never claims one received its credentials.
|
|
150
|
+
*/
|
|
151
|
+
export function formatCredentialAuditLines(jobId, prep, admittedEnv, droppedEnv = []) {
|
|
152
|
+
if (prep.recordState === "absent")
|
|
153
|
+
return [];
|
|
154
|
+
const list = (names) => (names.length > 0 ? [...names].sort().join(",") : "-");
|
|
155
|
+
const lines = [`[executor] job ${jobId}: credentials record=${prep.recordState}`];
|
|
156
|
+
if (prep.recordState !== "ok")
|
|
157
|
+
return lines;
|
|
158
|
+
const deliveredEnv = admittedEnv ?? [];
|
|
159
|
+
lines.push(`[executor] job ${jobId}: credentials selected=${list(prep.selected)}`);
|
|
160
|
+
lines.push(`[executor] job ${jobId}: credentials delivered files=${list(prep.deliveredFiles)} variables=${list(deliveredEnv)}`);
|
|
161
|
+
const unavailable = [
|
|
162
|
+
...prep.notices.map((n) => `${n.name}(${n.reason})`),
|
|
163
|
+
...droppedEnv.map((d) => `${d.name}(${d.reason})`),
|
|
164
|
+
];
|
|
165
|
+
lines.push(`[executor] job ${jobId}: credentials unavailable=${list([...new Set(unavailable)])}`);
|
|
166
|
+
lines.push(`[executor] job ${jobId}: credentials mcp eligible=${list(prep.eligibleMcp)}`);
|
|
167
|
+
return lines;
|
|
168
|
+
}
|
package/build/executor/deps.js
CHANGED
|
@@ -10,7 +10,7 @@ import { recordProvisionedAssets } from "../generated-assets-inventory.js";
|
|
|
10
10
|
*/
|
|
11
11
|
import { execFile, spawn } from "node:child_process";
|
|
12
12
|
import { existsSync } from "node:fs";
|
|
13
|
-
import { open, readFile, writeFile, appendFile, mkdir, mkdtemp, chmod, rm, rename, readdir, lstat, stat, statfs, } from "node:fs/promises";
|
|
13
|
+
import { open, readFile, writeFile, appendFile, mkdir, mkdtemp, chmod, rm, rename, readdir, lstat, stat, statfs, realpath, } from "node:fs/promises";
|
|
14
14
|
import os from "node:os";
|
|
15
15
|
import { promisify } from "node:util";
|
|
16
16
|
import { resolveMcpShimInvocationForRuntime } from "../mcp-server-invocation.js";
|
|
@@ -162,6 +162,8 @@ export function createDefaultExecutorDeps() {
|
|
|
162
162
|
}
|
|
163
163
|
},
|
|
164
164
|
removeFile: (filePath) => rm(filePath, { force: true }),
|
|
165
|
+
// BAPI-1647: canonical paths for the cross-process exclude lock's key.
|
|
166
|
+
realpath: (filePath) => realpath(filePath),
|
|
165
167
|
// BAPI-1021 (AC-6): worker-log archival's rename seam. Real `fs.promises.rename`
|
|
166
168
|
// rejects with `code: "EXDEV"` across filesystems/devices, which worker-log.ts
|
|
167
169
|
// treats as an ordinary best-effort archive failure like any other.
|