@bridge_gpt/mcp-server 0.2.62 → 0.2.66

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 (113) hide show
  1. package/README.md +66 -15
  2. package/build/agent-launchers/claude-executor-adapter.js +145 -20
  3. package/build/agent-launchers/executor-adapter.js +81 -2
  4. package/build/agents.generated.js +10 -1
  5. package/build/bounded-wait.js +32 -1
  6. package/build/bridge-config.js +104 -0
  7. package/build/codex-bridge-profile.js +10 -1
  8. package/build/commands.generated.js +7 -6
  9. package/build/conductor/bridge-api-client.js +565 -32
  10. package/build/conductor/bring-up-facts.js +3 -1
  11. package/build/conductor/doctor.js +23 -14
  12. package/build/conductor/epic-child-continuation.js +351 -0
  13. package/build/conductor/epic-implementer-cli.js +154 -17
  14. package/build/conductor/git-hooks.js +529 -118
  15. package/build/conductor/guided-repair.js +323 -0
  16. package/build/conductor/hook-runtime-qualification.js +340 -0
  17. package/build/conductor/readiness-cli.js +30 -9
  18. package/build/conductor/readiness-sections.js +5 -4
  19. package/build/conductor/readiness.js +45 -12
  20. package/build/conductor/recovery-cli.js +859 -27
  21. package/build/conductor/recovery-operations.js +574 -5
  22. package/build/conductor/repair-contract.js +69 -3
  23. package/build/conductor-bundle-artifacts.js +1 -0
  24. package/build/credential-store.js +52 -13
  25. package/build/diagnostic-text.js +36 -0
  26. package/build/docs.generated.js +3 -2
  27. package/build/doctor.js +147 -21
  28. package/build/drive-epic-key.js +12 -0
  29. package/build/drive-epic.js +1537 -125
  30. package/build/epic-coherence-input-cli.js +137 -0
  31. package/build/epic-coherence-input.js +920 -0
  32. package/build/epic-coherence-input.test-fixtures.js +175 -0
  33. package/build/epic-implementer-bin.js +41 -33
  34. package/build/epic-implementer-bundle-cli.js +14 -1
  35. package/build/epic-launch-diagnostic.js +31 -0
  36. package/build/epic-launch-profile.js +58 -19
  37. package/build/epic-run-status.js +5 -0
  38. package/build/epic-shared/bridge-client.js +46 -4
  39. package/build/executor/cli.js +39 -0
  40. package/build/executor/completion-contract.js +423 -0
  41. package/build/executor/completion-supervision.js +291 -0
  42. package/build/executor/correction-dispatch.js +60 -0
  43. package/build/executor/credentials.js +3 -1
  44. package/build/executor/deps.js +65 -1
  45. package/build/executor/env.js +12 -0
  46. package/build/executor/heartbeat.js +13 -3
  47. package/build/executor/http-client.js +91 -4
  48. package/build/executor/integration-job.js +6 -1
  49. package/build/executor/job-errors.js +61 -4
  50. package/build/executor/job-log-registry.js +340 -73
  51. package/build/executor/job-runner.js +1550 -55
  52. package/build/executor/job-types.js +9 -6
  53. package/build/executor/preflight.js +189 -1
  54. package/build/executor/process-containment.js +756 -0
  55. package/build/executor/process.js +235 -5
  56. package/build/executor/prompt-spec.js +366 -1
  57. package/build/executor/provider-checks.js +69 -0
  58. package/build/executor/rebase-finalization.js +351 -0
  59. package/build/executor/reconcile-overlap-job.js +77 -84
  60. package/build/executor/required-verification.js +313 -0
  61. package/build/executor/required-work-ledger.js +1121 -0
  62. package/build/executor/results.js +142 -0
  63. package/build/executor/resume-pre-spawn.js +87 -4
  64. package/build/executor/runner.js +168 -0
  65. package/build/executor/stale-artifacts.js +5 -4
  66. package/build/executor/test-declaration.js +20 -0
  67. package/build/executor/types.js +13 -0
  68. package/build/executor/watch-cli.js +35 -8
  69. package/build/executor/worker-command.js +70 -34
  70. package/build/executor/worker-finalization.js +168 -26
  71. package/build/executor/worker-guard-hook.js +75 -14
  72. package/build/executor/worker-log.js +137 -70
  73. package/build/executor/worktree-gc.js +30 -6
  74. package/build/executor/worktree.js +13 -0
  75. package/build/executor-launch.js +658 -0
  76. package/build/index.js +594 -1152
  77. package/build/init.js +107 -4
  78. package/build/install-bridge-conductor.js +231 -41
  79. package/build/install-bridge.js +284 -20
  80. package/build/install-doctor.js +172 -30
  81. package/build/install-reexec.js +69 -7
  82. package/build/macos-terminal-permission-guidance.js +16 -0
  83. package/build/merge-pull-request.js +1 -1
  84. package/build/model-thresholds-tool.js +185 -0
  85. package/build/pipelines.generated.js +9 -8
  86. package/build/plan-discovery.js +137 -0
  87. package/build/plan-epic-implementer-eligibility.js +2 -2
  88. package/build/plane/cli.js +37 -3
  89. package/build/plane/member-logs.js +3 -0
  90. package/build/plane/member-roster.js +7 -1
  91. package/build/plane/shutdown.js +59 -1
  92. package/build/plane/status.js +4 -0
  93. package/build/plane/supervisor.js +146 -0
  94. package/build/plane/worker-exit-code.js +2 -0
  95. package/build/project-root.js +99 -0
  96. package/build/readme.generated.js +1 -1
  97. package/build/review-tickets.js +156 -13
  98. package/build/scripts/executor-protocol-contract-driver.js +13 -3
  99. package/build/setup-epic.js +208 -125
  100. package/build/sfcc/setup-status.js +2 -0
  101. package/build/sfcc/tool-wrapper.js +2 -0
  102. package/build/sfcc/tools-configured.js +96 -0
  103. package/build/start-tickets.js +163 -58
  104. package/build/upgrade-cli.js +109 -24
  105. package/build/version.generated.js +3 -3
  106. package/build/windows-npm-entry.js +103 -0
  107. package/build/worker-guard-hook-bin.js +5 -4
  108. package/build/worktree-core.js +6 -5
  109. package/docs/CONDUCTOR.md +116 -2
  110. package/docs/install/mcp-tool-integrations.md +1 -0
  111. package/docs/install/sfcc-integration.md +12 -7
  112. package/package.json +2 -1
  113. package/pipelines/implement-ticket.json +1 -1
@@ -0,0 +1,291 @@
1
+ import { sha256Hex } from "./completion-contract.js";
2
+ import { canonicalJson } from "./required-verification.js";
3
+ /** Reserved for the owned-process sweep after the worker exits. */
4
+ export const CLEANUP_RESERVE_MS = 20_000;
5
+ /** Reserved for `validateWorkerFinalization` (git + gh reads). */
6
+ export const FINALIZATION_RESERVE_MS = 60_000;
7
+ /** Reserved for preparing and delivering the terminal report, with retries. */
8
+ export const REPORT_RESERVE_MS = 30_000;
9
+ /** Reserved for cleanup after declared checks, when any are declared. */
10
+ export const CHECK_CLEANUP_RESERVE_MS = 10_000;
11
+ /**
12
+ * Between closing stdin at the hold deadline and the process timer's SIGTERM.
13
+ * The measured CLI stops its own tasks within ~0.4 s of stdin EOF; the rest is
14
+ * margin for EOF draining.
15
+ */
16
+ export const STDIN_CLOSE_GRACE_MS = 10_000;
17
+ /** A worker window shorter than this cannot do useful work: refuse instead. */
18
+ export const MIN_WORKER_WINDOW_MS = 60_000;
19
+ /** Bound on the post-exit wait for stdout/stderr EOF. */
20
+ export const EOF_DRAIN_BOUND_MS = 5_000;
21
+ /**
22
+ * Plan the covered attempt's phases from its remaining authorized allowance.
23
+ *
24
+ * `remainingMs` is what is left of the job's own timeout at this moment (the
25
+ * caller has already spent some of it preparing the worktree), minus any
26
+ * allowance the ORIGINATING attempt already spent when this job is a
27
+ * continuation. The plan never returns a window larger than that.
28
+ */
29
+ export function planCompletionAllowance(input) {
30
+ const verificationMs = input.declaredCheckTimeoutsMs.reduce((sum, ms) => sum + Math.max(0, ms), 0);
31
+ const reservations = {
32
+ cleanupMs: CLEANUP_RESERVE_MS,
33
+ verificationMs,
34
+ checkCleanupMs: verificationMs > 0 ? CHECK_CLEANUP_RESERVE_MS : 0,
35
+ finalizationMs: FINALIZATION_RESERVE_MS,
36
+ reportMs: REPORT_RESERVE_MS,
37
+ };
38
+ const reserved = reservations.cleanupMs +
39
+ reservations.verificationMs +
40
+ reservations.checkCleanupMs +
41
+ reservations.finalizationMs +
42
+ reservations.reportMs;
43
+ const available = Math.max(0, input.remainingMs - Math.max(0, input.spentAllowanceMs ?? 0));
44
+ const workerWindowMs = available - reserved;
45
+ if (workerWindowMs < MIN_WORKER_WINDOW_MS)
46
+ return { ok: false, reason: "allowance_exhausted" };
47
+ const deadlineAtMs = input.nowMs + available;
48
+ const workerDeadlineAtMs = input.nowMs + workerWindowMs;
49
+ return {
50
+ ok: true,
51
+ deadlineAtMs,
52
+ workerDeadlineAtMs,
53
+ holdDeadlineAtMs: workerDeadlineAtMs - STDIN_CLOSE_GRACE_MS,
54
+ workerWindowMs,
55
+ reservations,
56
+ };
57
+ }
58
+ /** The payload key the server stamps the declaration under. */
59
+ export const REQUIRED_VERIFICATION_PAYLOAD_KEY = "required_verification";
60
+ export const REQUIRED_VERIFICATION_SCHEMA_VERSION = 1;
61
+ /** Bounds, identical to the server's `ReconcileVerificationCommand` / overlap contract. */
62
+ export const DECLARATION_MAX_COMMANDS = 16;
63
+ export const DECLARATION_MAX_NAME_CHARS = 120;
64
+ export const DECLARATION_MAX_ARGV = 32;
65
+ export const DECLARATION_MAX_ARG_CHARS = 1024;
66
+ export const DECLARATION_MIN_TIMEOUT_SECONDS = 1;
67
+ export const DECLARATION_MAX_TIMEOUT_SECONDS = 30 * 60;
68
+ const DIGEST_RE = /^[0-9a-f]{64}$/;
69
+ const COMMAND_KEYS = ["argv", "identity", "name", "position", "timeout_seconds"];
70
+ const DECLARATION_KEYS = new Set([
71
+ "schema_version",
72
+ "provenance",
73
+ "plan_version",
74
+ "plan_hash",
75
+ "commands",
76
+ "digest",
77
+ "refusal_reason",
78
+ ]);
79
+ /** `cmd-<position>-<16 hex>` over the canonical typed value — the server's `command_identity`. */
80
+ export function declaredCommandIdentity(position, value) {
81
+ const typed = { name: value.name, argv: [...value.argv], timeout_seconds: value.timeout_seconds };
82
+ return `cmd-${String(position).padStart(2, "0")}-${sha256Hex(canonicalJson(typed)).slice(0, 16)}`;
83
+ }
84
+ /** SHA-256 over every declaration field except `digest` — the server's `declaration_digest`. */
85
+ export function computeDeclarationDigest(declaration) {
86
+ const body = {};
87
+ for (const [k, v] of Object.entries(declaration))
88
+ if (k !== "digest")
89
+ body[k] = v;
90
+ return sha256Hex(canonicalJson(body));
91
+ }
92
+ function isInt(value) {
93
+ return typeof value === "number" && Number.isInteger(value);
94
+ }
95
+ function validCommand(raw, index) {
96
+ if (!raw || typeof raw !== "object" || Array.isArray(raw))
97
+ return "malformed_command";
98
+ const e = raw;
99
+ const keys = Object.keys(e).sort();
100
+ if (keys.length !== COMMAND_KEYS.length || keys.some((k, i) => k !== COMMAND_KEYS[i]))
101
+ return "malformed_command";
102
+ const { identity, position, name, argv, timeout_seconds: timeout } = e;
103
+ if (typeof name !== "string" || name.trim().length === 0 || name.length > DECLARATION_MAX_NAME_CHARS) {
104
+ return "malformed_command";
105
+ }
106
+ if (!Array.isArray(argv) || argv.length === 0 || argv.length > DECLARATION_MAX_ARGV)
107
+ return "malformed_command";
108
+ for (const arg of argv) {
109
+ if (typeof arg !== "string" || arg.trim().length === 0 || arg.length > DECLARATION_MAX_ARG_CHARS || arg.includes("\0")) {
110
+ return "malformed_command";
111
+ }
112
+ }
113
+ if (!isInt(timeout) || timeout < DECLARATION_MIN_TIMEOUT_SECONDS || timeout > DECLARATION_MAX_TIMEOUT_SECONDS) {
114
+ return "malformed_command";
115
+ }
116
+ if (!isInt(position) || position !== index)
117
+ return "position_mismatch";
118
+ if (typeof identity !== "string" || identity !== declaredCommandIdentity(index, { name, argv: argv, timeout_seconds: timeout })) {
119
+ return "identity_mismatch";
120
+ }
121
+ return { identity, position, name, argv: [...argv], timeoutSeconds: timeout };
122
+ }
123
+ /**
124
+ * Read and validate a claimed job's `required_verification` declaration,
125
+ * all-or-nothing. See {@link RequiredVerificationRead}.
126
+ */
127
+ export function readRequiredVerification(payload) {
128
+ if (!payload || !Object.prototype.hasOwnProperty.call(payload, REQUIRED_VERIFICATION_PAYLOAD_KEY)) {
129
+ return { kind: "none" };
130
+ }
131
+ const raw = payload[REQUIRED_VERIFICATION_PAYLOAD_KEY];
132
+ if (!raw || typeof raw !== "object" || Array.isArray(raw)) {
133
+ return { kind: "refused", reason: "not_an_object", provenance: null, digest: null };
134
+ }
135
+ const d = raw;
136
+ const digest = typeof d.digest === "string" && DIGEST_RE.test(d.digest) ? d.digest : null;
137
+ const provenance = d.provenance === "declared" || d.provenance === "declared_empty" || d.provenance === "absent" || d.provenance === "refused"
138
+ ? d.provenance
139
+ : null;
140
+ const refuse = (reason) => ({
141
+ kind: "refused",
142
+ reason,
143
+ provenance,
144
+ digest,
145
+ });
146
+ if (d.schema_version !== REQUIRED_VERIFICATION_SCHEMA_VERSION)
147
+ return refuse("unsupported_schema_version");
148
+ if (Object.keys(d).some((k) => !DECLARATION_KEYS.has(k)))
149
+ return refuse("unsupported_schema_version");
150
+ if (provenance === null)
151
+ return refuse("unknown_provenance");
152
+ if (digest === null)
153
+ return refuse("malformed_digest");
154
+ if (provenance === "refused")
155
+ return refuse("server_refused");
156
+ if (Object.prototype.hasOwnProperty.call(d, "refusal_reason"))
157
+ return refuse("unknown_provenance");
158
+ const planVersion = d.plan_version;
159
+ const planHash = d.plan_hash;
160
+ if (!(planVersion === null || (isInt(planVersion) && planVersion >= 0)))
161
+ return refuse("malformed_plan_identity");
162
+ if (!(planHash === null || (typeof planHash === "string" && planHash.length > 0))) {
163
+ return refuse("malformed_plan_identity");
164
+ }
165
+ if (!Array.isArray(d.commands) || d.commands.length > DECLARATION_MAX_COMMANDS)
166
+ return refuse("cardinality_mismatch");
167
+ const commands = d.commands;
168
+ if ((provenance === "declared") !== commands.length > 0)
169
+ return refuse("cardinality_mismatch");
170
+ const checks = [];
171
+ const seen = new Set();
172
+ for (let i = 0; i < commands.length; i++) {
173
+ const parsed = validCommand(commands[i], i);
174
+ if (typeof parsed === "string")
175
+ return refuse(parsed);
176
+ if (seen.has(parsed.identity))
177
+ return refuse("duplicate_identity");
178
+ seen.add(parsed.identity);
179
+ checks.push(parsed);
180
+ }
181
+ if (computeDeclarationDigest(d) !== digest)
182
+ return refuse("digest_mismatch");
183
+ return {
184
+ kind: "ok",
185
+ declaration: {
186
+ provenance,
187
+ digest,
188
+ planVersion: planVersion,
189
+ planHash: planHash,
190
+ checks,
191
+ },
192
+ };
193
+ }
194
+ /**
195
+ * The declared checks of a VALIDATED declaration, or `[]`. Never a partial
196
+ * list: a declaration that fails validation has no runnable checks at all, and
197
+ * the covered lane refuses it before launch (see {@link readRequiredVerification}).
198
+ */
199
+ export function readDeclaredChecks(payload) {
200
+ const read = readRequiredVerification(payload);
201
+ return read.kind === "ok" ? read.declaration.checks : [];
202
+ }
203
+ export function finalizationObligations(branch, baseBranch) {
204
+ return {
205
+ push: { remote: "origin", ref: `refs/heads/${branch}` },
206
+ prCreate: { head: branch, base: baseBranch },
207
+ };
208
+ }
209
+ /**
210
+ * Map a finalization outcome onto the contract verdict plus which of the two
211
+ * obligations were independently satisfied. The mapping reads the executor's
212
+ * own finalization error kinds; it never trusts worker text.
213
+ */
214
+ export function finalizationFacts(outcome) {
215
+ if (outcome === null)
216
+ return { verdict: "unknown", pushSatisfied: false, prSatisfied: false };
217
+ if (outcome.ok)
218
+ return { verdict: "ok", pushSatisfied: true, prSatisfied: true };
219
+ switch (outcome.errorKind) {
220
+ case "WorkerFinalizationPrNotAttached":
221
+ case "WorkerFinalizationPrBaseMismatch":
222
+ return { verdict: "unmet", pushSatisfied: true, prSatisfied: false };
223
+ case "WorkerFinalizationMissingRemoteBranchAndPr":
224
+ case "WorkerFinalizationSavedButUnfinalized":
225
+ return { verdict: "unmet", pushSatisfied: false, prSatisfied: false };
226
+ // BAPI-1330: the worker's full HEAD, or the PR's head, could not be
227
+ // established. Nothing was observed MISSING, so the verdict is `unknown`
228
+ // and neither push nor PR is inferred satisfied.
229
+ case "WorkerFinalizationPublicationUnverified":
230
+ return { verdict: "unknown", pushSatisfied: false, prSatisfied: false };
231
+ default:
232
+ return { verdict: "unknown", pushSatisfied: false, prSatisfied: false };
233
+ }
234
+ }
235
+ /**
236
+ * Read the server-stamped completion binding for a claimed job.
237
+ *
238
+ * The job id, run, child and attempt come from the CLAIM (the server minted
239
+ * them); the park generation and originating job come from the payload's
240
+ * `completion_binding`, which only the reconciler writes. Nothing here is taken
241
+ * from worker output.
242
+ */
243
+ export function readCompletionBinding(job, dispatchHeadSha) {
244
+ const raw = job.payload?.["completion_binding"];
245
+ const b = raw && typeof raw === "object" ? raw : {};
246
+ const intOrNull = (v) => typeof v === "number" && Number.isInteger(v) && v >= 0 ? v : null;
247
+ const spentSeconds = intOrNull(b["spent_allowance_seconds"]) ?? 0;
248
+ return {
249
+ binding: {
250
+ job_id: job.id,
251
+ epic_run_id: job.epic_run_id ?? null,
252
+ ticket_key: job.ticket_key ?? null,
253
+ attempt: job.attempt_count,
254
+ park_generation: intOrNull(b["park_generation"]),
255
+ originating_job_id: intOrNull(b["originating_job_id"]),
256
+ dispatch_head_sha: dispatchHeadSha,
257
+ final_head_sha: null,
258
+ },
259
+ spentAllowanceMs: spentSeconds * 1000,
260
+ };
261
+ }
262
+ /**
263
+ * Read the server-owned optional-watcher declaration. Only an exact kind +
264
+ * input digest match makes a watcher optional; worker prose or a label the
265
+ * worker assigns can never do it.
266
+ */
267
+ export function readOptionalWatchers(payload) {
268
+ const policy = payload?.["completion_policy"];
269
+ const raw = policy && typeof policy === "object" ? policy["optional_watchers"] : undefined;
270
+ if (!Array.isArray(raw))
271
+ return [];
272
+ const out = [];
273
+ for (const entry of raw.slice(0, 16)) {
274
+ if (!entry || typeof entry !== "object")
275
+ continue;
276
+ const e = entry;
277
+ if ((e["kind"] === "monitor" || e["kind"] === "bash_bg") && typeof e["input_digest"] === "string" && /^[0-9a-f]{64}$/.test(e["input_digest"])) {
278
+ out.push({ kind: e["kind"], input_digest: e["input_digest"] });
279
+ }
280
+ }
281
+ return out;
282
+ }
283
+ /** Terminal `error_kind` for each completion cause. Executor-owned vocabulary. */
284
+ export const COMPLETION_CAUSE_ERROR_KINDS = {
285
+ required_work_incomplete: "ContractError.RequiredWorkIncomplete",
286
+ required_check_failed: "ContractError.RequiredCheckFailed",
287
+ permission_stop: "ContractError.PermissionStop",
288
+ unsupported_completion_evidence: "ContractError.CompletionEvidenceUnsupported",
289
+ cleanup_unconfirmed: "ContractError.CleanupUnconfirmed",
290
+ verification_runner_unavailable: "ContractError.VerificationRunnerUnavailable",
291
+ };
@@ -0,0 +1,60 @@
1
+ /** BAPI-1328: persisted remaining-work authority, independent of prompt text. */
2
+ export const CORRECTION_INTENT_CAPABILITY = "correction_intent.v1";
3
+ export const CORRECTION_INTENT_VERSION = 1;
4
+ export const CORRECTION_KINDS = [
5
+ "review_fix", "operator_remediation", "ci_fix", "focused_rebase",
6
+ "overlap_reconciliation", "approved_spec_delta", "continuation",
7
+ "required_checks", "finalization", "integration_correction",
8
+ ];
9
+ function nonblank(value) {
10
+ return typeof value === "string" && value.trim().length > 0 && value.length <= 4096;
11
+ }
12
+ function reference(value) {
13
+ return value !== null && typeof value === "object" && !Array.isArray(value) &&
14
+ Object.keys(value).length > 0 && Object.entries(value).every(([key, item]) => nonblank(key) && ((typeof item === "string" && nonblank(item)) ||
15
+ (typeof item === "number" && Number.isInteger(item))));
16
+ }
17
+ /** A prompt or job type never grants correction authority. */
18
+ export function validateCorrectionIntent(value, row) {
19
+ const refuse = (code, detail) => ({ ok: false, code, detail });
20
+ if (!value || typeof value !== "object" || Array.isArray(value))
21
+ return refuse("correction_context_missing", "correction intent is absent");
22
+ const intent = value;
23
+ if (intent.version !== CORRECTION_INTENT_VERSION)
24
+ return refuse("correction_contract_version_unsupported", "unsupported correction intent version");
25
+ if (!CORRECTION_KINDS.includes(intent.kind))
26
+ return refuse("correction_contract_invalid", "unknown correction kind");
27
+ for (const key of ["repo_name", "epic_run_id", "ticket_key"]) {
28
+ if (!nonblank(row[key]) || intent[key] !== row[key])
29
+ return refuse("correction_contract_invalid", `${key} differs from row`);
30
+ }
31
+ if (!nonblank(intent.branch) || (row.expected_branch && intent.branch !== row.expected_branch))
32
+ return refuse("correction_context_missing", "retained branch is unavailable or changed");
33
+ if (!nonblank(intent.head_sha) || (row.expected_head_sha && intent.head_sha !== row.expected_head_sha))
34
+ return refuse("correction_context_missing", "retained head is unavailable or changed");
35
+ if (!nonblank(intent.obligation) || !reference(intent.context_ref))
36
+ return refuse("correction_context_missing", "remaining obligation or context reference is absent");
37
+ if (intent.resume !== undefined && intent.resume !== null && intent.resume !== false)
38
+ return refuse("correction_contract_invalid", "unsupported resume metadata");
39
+ if (intent.kind === "approved_spec_delta") {
40
+ const delta = intent.approved_delta;
41
+ if (!delta || typeof delta !== "object" || Array.isArray(delta))
42
+ return refuse("renewed_scope_approval_required", "approved same-ticket delta is absent");
43
+ const d = delta;
44
+ if (!["old_identity", "new_identity", "obligation"].every(key => nonblank(d[key])) ||
45
+ !["file_boundary", "dependency_boundary"].every(key => Array.isArray(d[key]) && (key !== "file_boundary" || d[key].length > 0) &&
46
+ d[key].every(nonblank)))
47
+ return refuse("renewed_scope_approval_required", "approved delta identity or boundary is absent");
48
+ }
49
+ return { ok: true, intent };
50
+ }
51
+ export function isRemainingWork(jobType, payload) {
52
+ if (["remediate", "rebase", "ci_fix", "reconcile_overlap", "resume"].includes(jobType))
53
+ return true;
54
+ if (!payload || typeof payload !== "object" || Array.isArray(payload))
55
+ return false;
56
+ const p = payload;
57
+ return p.correction_intent !== undefined || p.continuation !== undefined ||
58
+ p.continuation_of_job_id !== undefined || p.finalization !== undefined ||
59
+ p.remaining_checks !== undefined || p.required_checks_remaining !== undefined;
60
+ }
@@ -83,7 +83,9 @@ export async function resolveExecutorApiAccess(repoName, deps, explicitBaseUrl)
83
83
  // sent to another. A restarted executor re-reads the binding here, so a unit
84
84
  // whose --base-url drifted from the approved target refuses before its first
85
85
  // authenticated request. An unbound (legacy) entry keeps today's behavior —
86
- // the explicit-target requirement above still applies to it.
86
+ // the explicit-target requirement above still applies to it. This agrees
87
+ // with the production epic launch (BAPI-1272), which also accepts an unbound
88
+ // stored key at production and refuses one bound to another endpoint.
87
89
  if (result.credentials.source === "file") {
88
90
  const bound = await readStoredBinding(`bapi:${trimmed}`, storeDeps);
89
91
  if (bound !== null && bound !== url.baseUrl) {
@@ -25,6 +25,43 @@ const MAX_COMMAND_BUFFER = 10 * 1024 * 1024;
25
25
  * evaluation instead of stalling.
26
26
  */
27
27
  const EXECUTOR_HTTP_TIMEOUT_MS = 30_000;
28
+ /**
29
+ * Wrap a real child stdin as the fakeable {@link OwnedStdin} (BAPI-1301, D4a).
30
+ *
31
+ * The permanent no-op `error` listener is the load-bearing line. A child that
32
+ * exits while its stdin is held open turns the next write (or the final `end()`)
33
+ * into an `EPIPE` emitted as an `error` event, and an `error` event with no
34
+ * listener is an uncaught exception that would crash the executor and every job
35
+ * it is supervising. With the listener attached the failure is still observable
36
+ * — `writeStdinBounded` / `closeStdinBounded` register their own one-shot
37
+ * `error` listener and report `write_error` — but it can never escape.
38
+ */
39
+ function wrapChildStdin(stream) {
40
+ if (!stream)
41
+ return null;
42
+ stream.setDefaultEncoding("utf8");
43
+ stream.on("error", () => {
44
+ /* observed by the bounded write/close helpers; never uncaught */
45
+ });
46
+ return {
47
+ write: (data) => stream.write(data),
48
+ once: (event, listener) => {
49
+ stream.once(event, listener);
50
+ },
51
+ off: (event, listener) => {
52
+ stream.off(event, listener);
53
+ },
54
+ end: () => {
55
+ stream.end();
56
+ },
57
+ get writableEnded() {
58
+ return stream.writableEnded;
59
+ },
60
+ get destroyed() {
61
+ return stream.destroyed;
62
+ },
63
+ };
64
+ }
28
65
  export function createDefaultExecutorDeps() {
29
66
  return {
30
67
  async runCommand(file, args, options) {
@@ -46,24 +83,50 @@ export function createDefaultExecutorDeps() {
46
83
  }
47
84
  },
48
85
  spawnProcess(file, args, options) {
86
+ // BAPI-1301 (D4a): stdin is piped ONLY when the caller selected it. Every
87
+ // legacy spawn keeps `"ignore"`, byte-for-byte the pre-BAPI-1301 stdio.
88
+ const pipeStdin = options.stdin === "pipe";
49
89
  const child = spawn(file, args, {
50
90
  cwd: options.cwd,
51
91
  env: options.env,
52
- stdio: ["ignore", "pipe", "pipe"],
92
+ stdio: [pipeStdin ? "pipe" : "ignore", "pipe", "pipe"],
53
93
  shell: false,
54
94
  });
55
95
  child.stdout?.setEncoding("utf8");
56
96
  child.stderr?.setEncoding("utf8");
97
+ const stdin = pipeStdin ? wrapChildStdin(child.stdin) : null;
98
+ // Recorded on the first `exit`, so `exited()` resolves even when it is
99
+ // asked after the event already fired.
100
+ let exitInfo = null;
101
+ const exitWaiters = [];
102
+ const settleExit = (info) => {
103
+ if (exitInfo !== null)
104
+ return;
105
+ exitInfo = info;
106
+ for (const waiter of exitWaiters.splice(0))
107
+ waiter(info);
108
+ };
109
+ child.on("exit", (code, signal) => settleExit({ exitCode: code, signal }));
110
+ child.on("error", () => settleExit({ exitCode: null, signal: null }));
57
111
  return {
58
112
  pid: child.pid,
59
113
  stdout: child.stdout ?? null,
60
114
  stderr: child.stderr ?? null,
115
+ ...(pipeStdin ? { stdin } : {}),
61
116
  wait() {
62
117
  return new Promise((resolve) => {
63
118
  child.on("close", (code, signal) => resolve({ exitCode: code, signal }));
64
119
  child.on("error", () => resolve({ exitCode: null, signal: null }));
65
120
  });
66
121
  },
122
+ exited() {
123
+ return new Promise((resolve) => {
124
+ if (exitInfo !== null)
125
+ resolve(exitInfo);
126
+ else
127
+ exitWaiters.push(resolve);
128
+ });
129
+ },
67
130
  kill(signal) {
68
131
  try {
69
132
  child.kill(signal);
@@ -128,6 +191,7 @@ export function createDefaultExecutorDeps() {
128
191
  env: process.env,
129
192
  cwd: process.cwd(),
130
193
  platform: process.platform,
194
+ arch: process.arch,
131
195
  homedir: os.homedir,
132
196
  async fetch(url, init) {
133
197
  const g = globalThis;
@@ -118,7 +118,14 @@ const SECRET_NAME_FRAGMENTS = ["TOKEN", "SECRET", "PASSWORD", "API_KEY"];
118
118
  * without anything in the executor choosing that.
119
119
  */
120
120
  export const EXPLICIT_DENY_KEYS = [
121
+ "BAPI_CORRECTION_INTENT_VERSION",
121
122
  "BRIDGE_MCP_PROFILE",
123
+ // BAPI-1301: the per-job ownership tag. The executor injects a fresh,
124
+ // unpredictable value AFTER this builder and the adapter have run
125
+ // (`process-containment.ts`), so an ambient value from the shell that
126
+ // launched the executor must never reach a worker: whoever chose the tag
127
+ // could make an unrelated process look job-owned to the cleanup sweep.
128
+ "BRIDGE_EXECUTOR_JOB_TAG",
122
129
  EPIC_IMPLEMENTER_NODE_PATH_ENV,
123
130
  // BAPI-1190: the legacy spelling stays denied so a stale ambient value from an
124
131
  // older package can never reach a worker during a version-skew window.
@@ -281,6 +288,11 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
281
288
  env.POSTGRES_DATABASE = WORKER_SENTINEL_DATABASE_NAME;
282
289
  env.POSTGRES_DB = WORKER_SENTINEL_DATABASE_NAME;
283
290
  env.PGDATABASE = WORKER_SENTINEL_DATABASE_NAME;
291
+ if (options.correctionIntentVersion !== undefined) {
292
+ if (options.correctionIntentVersion !== 1)
293
+ throw new Error("unsupported correction intent version");
294
+ env.BAPI_CORRECTION_INTENT_VERSION = "1";
295
+ }
284
296
  if (typeof options.effectiveBaseBranch === "string" &&
285
297
  options.effectiveBaseBranch.length > 0) {
286
298
  env[PR_BASE_BRANCH_ENV_VAR] = options.effectiveBaseBranch;
@@ -49,6 +49,14 @@ export const PUSH_DETECT_INTERVAL_MS = 5_000;
49
49
  */
50
50
  export async function runHeartbeatLoop(params) {
51
51
  const { job, httpClient, options, deps, ownership, proc, observation } = params;
52
+ // BAPI-1301: every signal this loop sends goes through here, so a job-level
53
+ // phase host can withhold it once no owned child is live.
54
+ const signalTarget = () => params.currentChild ? params.currentChild() : proc;
55
+ const killCurrent = (reason) => {
56
+ const target = signalTarget();
57
+ if (target)
58
+ killOwnedProcess(target, reason);
59
+ };
52
60
  const pushDetectIntervalMs = params.pushDetectIntervalMs ?? PUSH_DETECT_INTERVAL_MS;
53
61
  // Baseline for push detection. `undefined` means "not yet sampled": the FIRST
54
62
  // successful sample only establishes the baseline and never itself triggers a
@@ -65,6 +73,7 @@ export async function runHeartbeatLoop(params) {
65
73
  const git = await params.collectTelemetry();
66
74
  observation.setGitTelemetry(git);
67
75
  const residue = observation.snapshot();
76
+ const ownershipContext = params.ownershipContext?.();
68
77
  const result = normalizeHeartbeatResult(await httpClient.heartbeat(job, {
69
78
  // Unconditionally the LOCAL head — never the remote marker. This is what
70
79
  // preserves the BAPI-704 semantic that a zero-commit job reports the base
@@ -72,11 +81,12 @@ export async function runHeartbeatLoop(params) {
72
81
  local_commit_count: git.local_commit_count,
73
82
  last_commit_sha: git.last_commit_sha,
74
83
  telemetry: residue,
84
+ ...(ownershipContext !== undefined ? { ownership_context: ownershipContext } : {}),
75
85
  }));
76
86
  // Checked BEFORE the outcome switch: a stop request is authoritative even
77
87
  // when it rides along with a non-`updated` outcome.
78
88
  if (result.stop_requested === true) {
79
- killOwnedProcess(proc, "server_stop");
89
+ killCurrent("server_stop");
80
90
  return { kind: "server_stop" };
81
91
  }
82
92
  if (result.outcome === "auth_fatal") {
@@ -94,7 +104,7 @@ export async function runHeartbeatLoop(params) {
94
104
  }
95
105
  if (result.outcome === "stale_claim") {
96
106
  // Definitive dead claim: kill the worker and stop touching the worktree.
97
- killOwnedProcess(proc, "stale_claim");
107
+ killCurrent("stale_claim");
98
108
  ownership.abandoned = true;
99
109
  ownership.abandonReason = "stale_claim";
100
110
  return { kind: "abandoned" };
@@ -102,7 +112,7 @@ export async function runHeartbeatLoop(params) {
102
112
  // retry_later / fatal_http_error: keep the worker alive within the dead-man
103
113
  // window; SIGKILL + abandon once 2 minutes pass without a successful beat.
104
114
  if (deps.now() - ownership.lastSuccessfulHeartbeatAt >= options.deadmanMs) {
105
- killOwnedProcess(proc, "deadman");
115
+ killCurrent("deadman");
106
116
  ownership.abandoned = true;
107
117
  ownership.abandonReason = "deadman";
108
118
  return { kind: "abandoned" };