@bridge_gpt/mcp-server 0.2.70 → 0.2.71

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (61) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +10 -1
  3. package/build/agent-registry.js +5 -5
  4. package/build/agents.generated.js +11 -1
  5. package/build/bounded-wait.js +9 -1
  6. package/build/bridge-permissions.js +13 -5
  7. package/build/commands.generated.js +3 -3
  8. package/build/conductor/bridge-api-client.js +260 -2
  9. package/build/conductor/command-drift-production.js +7 -2
  10. package/build/conductor/doctor.js +9 -3
  11. package/build/conductor/epic-implementer-cli.js +4 -0
  12. package/build/conductor/gate-discovery.js +524 -10
  13. package/build/conductor/gate-settings-review.js +451 -0
  14. package/build/conductor/launch-need-probes.js +16 -11
  15. package/build/conductor/launch-plan.js +145 -0
  16. package/build/conductor/precheck-timings.js +14 -0
  17. package/build/conductor/preview-observations.js +10 -0
  18. package/build/conductor/readiness-sections.js +4 -1
  19. package/build/conductor/recovery-cli.js +59 -2
  20. package/build/conductor/recovery-operations.js +45 -2
  21. package/build/docs.generated.js +1 -1
  22. package/build/drive-epic.js +188 -45
  23. package/build/epic-ci-workflow-drift.js +71 -23
  24. package/build/epic-ci-workflow-install.js +83 -26
  25. package/build/epic-ci-workflow-v1.js +132 -0
  26. package/build/epic-ci-workflow.js +174 -13
  27. package/build/epic-implementer-bin.js +18 -18
  28. package/build/executor/ci-rerun-job.js +220 -14
  29. package/build/executor/env.js +207 -3
  30. package/build/executor/gate-qualification-job.js +20 -5
  31. package/build/executor/job-runner.js +112 -11
  32. package/build/executor/likely-tests.js +6 -1
  33. package/build/executor/preflight.js +5 -0
  34. package/build/executor/process-containment.js +18 -0
  35. package/build/executor/prompt-spec.js +72 -13
  36. package/build/executor/reconcile-overlap-job.js +6 -1
  37. package/build/executor/worker-command.js +136 -1
  38. package/build/executor/worker-database.js +30 -11
  39. package/build/executor/worker-resources.js +12 -1
  40. package/build/executor/worker-verification-guidance.js +29 -0
  41. package/build/index.js +221 -165
  42. package/build/install-bridge-conductor-gate.js +195 -14
  43. package/build/install-bridge-conductor-setup.js +20 -6
  44. package/build/install-bridge-conductor.js +355 -37
  45. package/build/install-bridge.js +1 -1
  46. package/build/merge-workflow-install.js +20 -0
  47. package/build/pipelines.generated.js +2 -2
  48. package/build/plan-execution-ledger.js +23 -8
  49. package/build/plane/plane-freshness.js +6 -2
  50. package/build/plane/preflight.js +19 -0
  51. package/build/printed-remedy-commands.js +8 -1
  52. package/build/readme.generated.js +1 -1
  53. package/build/repository-toolchains.js +581 -0
  54. package/build/setup-epic.js +24 -7
  55. package/build/test-command-detection.js +58 -21
  56. package/build/ticket-delivery-artifacts.js +7 -0
  57. package/build/ticket-delivery-enrollment.js +67 -4
  58. package/build/version.generated.js +3 -3
  59. package/docs/EPIC-IMPLEMENTER.md +38 -0
  60. package/docs/epic-implementer/getting-started.md +58 -2
  61. package/package.json +2 -2
@@ -31,6 +31,16 @@
31
31
  * is actuated by the executor machine's own `gh`, so no token, credential
32
32
  * bundle, or environment credential is injected, added to argv, or returned.
33
33
  *
34
+ * BAPI-1523 adds a second, check-run variant. When a no-push repair is held for an
35
+ * external CI provider, the server asks the executor to send ONE
36
+ * `POST repos/<owner>/<repo>/check-runs/<id>/rerequest` through the same ambient
37
+ * `gh`. It has no polling, no worktree, and no transition authority. It reports
38
+ * only `rerequested`, or `not_rerequestable` with a closed `forbidden` /
39
+ * `not_found` reason for a reliably identified HTTP 403 / 404. Anything else —
40
+ * 422, a timeout, a network, authentication, rate-limit, or server failure — is a
41
+ * closed job failure the server records as `rerequest_not_performed`. An absent
42
+ * `variant` is the workflow-run form above, so existing payloads stay valid.
43
+ *
34
44
  * Diagnostics go to `console.error` only. MCP stdout is a protocol channel and
35
45
  * writing child output to it corrupts the session.
36
46
  */
@@ -45,6 +55,10 @@ export const CI_RERUN_POLL_DEADLINE_MS = 3 * 60 * 1000;
45
55
  export const CI_RERUN_POLL_INTERVAL_MS = 10 * 1000;
46
56
  /** Per-`gh`-invocation timeout. */
47
57
  export const CI_RERUN_GH_TIMEOUT_MS = 60 * 1000;
58
+ /** Bounds aligned with the Python result boundary (`CI_RERUN_LANE_MAX_CHARS`). */
59
+ export const CI_RERUN_LANE_MAX_CHARS = 200;
60
+ const CI_RERUN_APP_SLUG_MAX_CHARS = 100;
61
+ const GITHUB_ACTIONS_APP_SLUG = "github-actions";
48
62
  const OWNER_REPO_RE = /^[A-Za-z0-9._-]+\/[A-Za-z0-9._-]+$/;
49
63
  const CLAUDE_REVIEW_WORKFLOW_BASENAME = CLAUDE_REVIEW_WORKFLOW_RELPATH.split("/").pop() ?? "claude-review.yml";
50
64
  /**
@@ -66,6 +80,44 @@ export function identifiesClaudeReviewWorkflow(identity) {
66
80
  normalized.includes("claude-review") ||
67
81
  normalized.includes("claude review"));
68
82
  }
83
+ function hasControlCharacter(value) {
84
+ for (let i = 0; i < value.length; i += 1) {
85
+ const code = value.charCodeAt(i);
86
+ if (code < 32 || code === 127)
87
+ return true;
88
+ }
89
+ return false;
90
+ }
91
+ function isPositiveSafeInteger(value) {
92
+ return (typeof value === "number" &&
93
+ Number.isSafeInteger(value) &&
94
+ value > 0);
95
+ }
96
+ /** A bounded, printable lane: non-empty, within the Python bound, no control characters. */
97
+ function validLane(value) {
98
+ if (typeof value !== "string")
99
+ return null;
100
+ const trimmed = value.trim();
101
+ if (!trimmed || trimmed.length > CI_RERUN_LANE_MAX_CHARS)
102
+ return null;
103
+ if (hasControlCharacter(trimmed))
104
+ return null;
105
+ return trimmed;
106
+ }
107
+ /** A normalized `owner/repo`; `.` and `..` components are never accepted. */
108
+ function validRepoFullName(value) {
109
+ if (typeof value !== "string")
110
+ return null;
111
+ const trimmed = value.trim();
112
+ if (!OWNER_REPO_RE.test(trimmed))
113
+ return null;
114
+ const parts = trimmed.split("/");
115
+ if (parts.length !== 2)
116
+ return null;
117
+ if (parts.some((part) => part === "." || part === ".."))
118
+ return null;
119
+ return trimmed.toLowerCase();
120
+ }
69
121
  /**
70
122
  * Validate a raw server payload into typed fields, SYNCHRONOUSLY and before any
71
123
  * subprocess is invoked.
@@ -73,6 +125,10 @@ export function identifiesClaudeReviewWorkflow(identity) {
73
125
  * Fails closed on every unusable shape. A job that cannot prove what it is about
74
126
  * to re-run must not run `gh` and then discover the problem — that is how a
75
127
  * malformed payload becomes a re-run of the wrong workflow.
128
+ *
129
+ * BAPI-1523 — the payload is a union selected by `variant`. An absent
130
+ * discriminator is the workflow-run form; an unknown one, or a payload carrying
131
+ * the other variant's actuator field, is refused.
76
132
  */
77
133
  export function parseCiRerunPayload(payload) {
78
134
  const refuse = (reason) => ({ ok: false, failure: { errorKind: CI_RERUN_REFUSED, reason } });
@@ -80,38 +136,92 @@ export function parseCiRerunPayload(payload) {
80
136
  return refuse("payload_not_an_object");
81
137
  }
82
138
  const raw = payload;
83
- const repoFullName = raw.repo_full_name;
84
- if (typeof repoFullName !== "string" || !OWNER_REPO_RE.test(repoFullName.trim())) {
85
- return refuse("repo_full_name_invalid");
139
+ const variantRaw = raw.variant;
140
+ if (variantRaw !== undefined &&
141
+ variantRaw !== null &&
142
+ variantRaw !== "workflow_run" &&
143
+ variantRaw !== "check_run") {
144
+ return refuse("variant_unknown");
86
145
  }
87
- const workflowRunId = raw.workflow_run_id;
88
- if (typeof workflowRunId !== "number" ||
89
- !Number.isInteger(workflowRunId) ||
90
- workflowRunId <= 0) {
91
- return refuse("workflow_run_id_invalid");
146
+ const variant = variantRaw === "check_run" ? "check_run" : "workflow_run";
147
+ // Cross-variant actuator fields are contradictory, never ignored.
148
+ if (variant === "check_run" && raw.workflow_run_id !== undefined) {
149
+ return refuse("variant_contradictory");
150
+ }
151
+ if (variant === "workflow_run" && raw.check_run_id !== undefined) {
152
+ return refuse("variant_contradictory");
153
+ }
154
+ const repoFullName = validRepoFullName(raw.repo_full_name);
155
+ if (repoFullName === null) {
156
+ return refuse("repo_full_name_invalid");
92
157
  }
93
- const lane = raw.required_check_lane;
94
- if (typeof lane !== "string" || !lane.trim()) {
95
- return refuse("required_check_lane_missing");
158
+ const lane = validLane(raw.required_check_lane);
159
+ if (lane === null) {
160
+ return refuse(typeof raw.required_check_lane === "string" && raw.required_check_lane.trim()
161
+ ? "required_check_lane_invalid"
162
+ : "required_check_lane_missing");
96
163
  }
97
164
  const attempt = raw.conductor_infra_attempt;
98
- if (typeof attempt !== "number" || !Number.isInteger(attempt) || attempt <= 0) {
165
+ if (!isPositiveSafeInteger(attempt)) {
99
166
  return refuse("conductor_infra_attempt_invalid");
100
167
  }
101
168
  const identityRaw = raw.workflow_identity;
102
169
  const workflowIdentity = typeof identityRaw === "string" && identityRaw.trim() ? identityRaw.trim() : null;
170
+ if (workflowIdentity !== null && hasControlCharacter(workflowIdentity)) {
171
+ return refuse("workflow_identity_invalid");
172
+ }
103
173
  // The review-workflow refusal, evaluated on the SERVER-SUPPLIED identity and
104
174
  // on the lane name, before any subprocess exists.
105
175
  if (identifiesClaudeReviewWorkflow(workflowIdentity) ||
106
176
  identifiesClaudeReviewWorkflow(lane)) {
107
177
  return refuse("claude_review_workflow_refused");
108
178
  }
179
+ // An `action_required` identity or conclusion is never actuated.
180
+ if (raw.conclusion === "action_required" || raw.observed_conclusion === "action_required") {
181
+ return refuse("action_required_refused");
182
+ }
183
+ if (variant === "check_run") {
184
+ const checkRunId = raw.check_run_id;
185
+ if (!isPositiveSafeInteger(checkRunId)) {
186
+ return refuse("check_run_id_invalid");
187
+ }
188
+ const appSlugRaw = raw.app_slug;
189
+ if (typeof appSlugRaw !== "string" ||
190
+ !appSlugRaw.trim() ||
191
+ appSlugRaw.trim().length > CI_RERUN_APP_SLUG_MAX_CHARS ||
192
+ hasControlCharacter(appSlugRaw)) {
193
+ return refuse("app_slug_invalid");
194
+ }
195
+ const appSlug = appSlugRaw.trim().toLowerCase();
196
+ if (appSlug === GITHUB_ACTIONS_APP_SLUG) {
197
+ return refuse("github_actions_refused");
198
+ }
199
+ if (identifiesClaudeReviewWorkflow(appSlug)) {
200
+ return refuse("claude_review_workflow_refused");
201
+ }
202
+ return {
203
+ ok: true,
204
+ fields: {
205
+ variant: "check_run",
206
+ repoFullName,
207
+ checkRunId,
208
+ requiredCheckLane: lane,
209
+ conductorInfraAttempt: attempt,
210
+ appSlug,
211
+ },
212
+ };
213
+ }
214
+ const workflowRunId = raw.workflow_run_id;
215
+ if (!isPositiveSafeInteger(workflowRunId)) {
216
+ return refuse("workflow_run_id_invalid");
217
+ }
109
218
  return {
110
219
  ok: true,
111
220
  fields: {
112
- repoFullName: repoFullName.trim().toLowerCase(),
221
+ variant: "workflow_run",
222
+ repoFullName,
113
223
  workflowRunId,
114
- requiredCheckLane: lane.trim(),
224
+ requiredCheckLane: lane,
115
225
  conductorInfraAttempt: attempt,
116
226
  workflowIdentity,
117
227
  },
@@ -156,6 +266,9 @@ export async function runCiRerunJob(payload, deps) {
156
266
  console.error(`[ci_rerun] payload refused: ${parsed.failure.reason}`);
157
267
  return parsed;
158
268
  }
269
+ if (parsed.fields.variant === "check_run") {
270
+ return runCheckRunRerequest(parsed.fields, deps);
271
+ }
159
272
  const fields = parsed.fields;
160
273
  const gh = deps.gh;
161
274
  const now = deps.now ?? (() => Date.now());
@@ -263,6 +376,99 @@ export async function runCiRerunJob(payload, deps) {
263
376
  `conclusion=${observedConclusion ?? "pending"}`);
264
377
  return { ok: true, result };
265
378
  }
379
+ /**
380
+ * The explicit HTTP status in `gh api` failure output, or `null`.
381
+ *
382
+ * Reads only the CLI's own status marker — `(HTTP 403)` or `HTTP 403:` — never
383
+ * generic prose or an exit code, so a permission failure is never inferred from
384
+ * wording. The status is the only thing taken from the text; the text itself is
385
+ * never returned or logged.
386
+ */
387
+ export function extractGhHttpStatus(stderr) {
388
+ const match = /\(HTTP (\d{3})\)|\bHTTP (\d{3}):/.exec(stderr);
389
+ if (match === null)
390
+ return null;
391
+ const status = Number(match[1] ?? match[2]);
392
+ return Number.isInteger(status) ? status : null;
393
+ }
394
+ /** GitHub also answers 403 for rate limiting; that is not a permission fact. */
395
+ function looksRateLimited(stderr) {
396
+ return /rate limit|abuse|retry-after/i.test(stderr);
397
+ }
398
+ /**
399
+ * Send ONE check-run re-request and report only the actuator fact (BAPI-1523).
400
+ *
401
+ * `gh api -X POST repos/<owner>/<repo>/check-runs/<id>/rerequest`, an argument
402
+ * array with no shell, no credential argument, no custom header, and no injected
403
+ * environment: the executor machine's ambient `gh` login is the only authority.
404
+ * It returns straight after the request — no polling, no worker, no worktree.
405
+ */
406
+ async function runCheckRunRerequest(fields, deps) {
407
+ let response;
408
+ try {
409
+ response = await deps.gh([
410
+ "api",
411
+ "-X",
412
+ "POST",
413
+ `repos/${fields.repoFullName}/check-runs/${fields.checkRunId}/rerequest`,
414
+ ], { timeoutMs: CI_RERUN_GH_TIMEOUT_MS });
415
+ }
416
+ catch {
417
+ // Contained: no exception text is returned or logged.
418
+ console.error("[ci_rerun] check-run rerequest invocation threw");
419
+ return {
420
+ ok: false,
421
+ failure: { errorKind: CI_RERUN_FAILED, reason: "rerequest_invocation_failed" },
422
+ };
423
+ }
424
+ if (response.exitCode === 0 && !response.timedOut) {
425
+ console.error(`[ci_rerun] check_run=${fields.checkRunId} rerequested`);
426
+ return {
427
+ ok: true,
428
+ result: {
429
+ check_run_id: fields.checkRunId,
430
+ lane: fields.requiredCheckLane,
431
+ outcome: "rerequested",
432
+ },
433
+ };
434
+ }
435
+ if (!response.timedOut) {
436
+ const status = extractGhHttpStatus(response.stderr);
437
+ if (status === 403 && !looksRateLimited(response.stderr)) {
438
+ console.error(`[ci_rerun] check_run=${fields.checkRunId} not rerequestable (403)`);
439
+ return {
440
+ ok: true,
441
+ result: {
442
+ check_run_id: fields.checkRunId,
443
+ lane: fields.requiredCheckLane,
444
+ outcome: "not_rerequestable",
445
+ reason: "forbidden",
446
+ },
447
+ };
448
+ }
449
+ if (status === 404) {
450
+ console.error(`[ci_rerun] check_run=${fields.checkRunId} not rerequestable (404)`);
451
+ return {
452
+ ok: true,
453
+ result: {
454
+ check_run_id: fields.checkRunId,
455
+ lane: fields.requiredCheckLane,
456
+ outcome: "not_rerequestable",
457
+ reason: "not_found",
458
+ },
459
+ };
460
+ }
461
+ }
462
+ console.error(`[ci_rerun] check_run=${fields.checkRunId} rerequest not performed ` +
463
+ `(exit=${response.exitCode ?? "null"}${response.timedOut ? ", timed out" : ""})`);
464
+ return {
465
+ ok: false,
466
+ failure: {
467
+ errorKind: CI_RERUN_FAILED,
468
+ reason: response.timedOut ? "rerequest_timed_out" : "rerequest_not_performed",
469
+ },
470
+ };
471
+ }
266
472
  /** Production dependency bundle: the existing bounded `execFile`-based runner. */
267
473
  export function createProductionCiRerunDeps() {
268
474
  return { gh: createProductionEpicIntegrationGhRunner() };
@@ -75,6 +75,68 @@ import { INDEX_SCOPE_ENV_VAR, validateOptionalIndexScope } from "../index-scope-
75
75
  import { delimiter as PLATFORM_PATH_DELIMITER } from "node:path";
76
76
  import { EPIC_IMPLEMENTER_ENV_PREFIX, EPIC_IMPLEMENTER_NODE_PATH_ENV, LEGACY_EPIC_IMPLEMENTER_ENV_PREFIX, LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV, } from "../epic-implementer-env.js";
77
77
  import { buildWorkerDatabaseEnv } from "./worker-database-target.js";
78
+ /** Entry rules for a declared worker variable (BAPI-1520), rechecked by the executor. */
79
+ const MAX_WORKER_ENV_ENTRIES = 32;
80
+ const MAX_WORKER_ENV_VALUE_BYTES = 1024;
81
+ const WORKER_ENV_NAME_PATTERN = /^[A-Z_][A-Z0-9_]{0,63}$/;
82
+ /**
83
+ * Names a declared worker variable may never use. A SORTED COPY of
84
+ * `WORKER_ENV_RESERVED_NAMES_SORTED` in `api/library/epic_implementer/gate_profile.py`
85
+ * (the authority): `tests/fixtures/executor/worker_env_reserved_names.json` is held
86
+ * to that authority by a Python test and to this export by `env.test.ts`. The
87
+ * executor owns its own copy because it may import only an allowlisted set of
88
+ * conductor modules.
89
+ */
90
+ const WORKER_ENV_RESERVED_NAMES = [
91
+ "BASH_ENV",
92
+ "BRIDGE_SKIP_PREPUSH",
93
+ "CI",
94
+ LEGACY_EPIC_IMPLEMENTER_NODE_PATH_ENV,
95
+ "DATABASE_URL",
96
+ "EPIC_IMPLEMENTER_NODE_PATH",
97
+ "GH_TOKEN",
98
+ "GITHUB_MERGE_TOKEN",
99
+ "GITHUB_TOKEN",
100
+ "HOME",
101
+ "LANG",
102
+ "LC_ALL",
103
+ "LD_PRELOAD",
104
+ "LOGNAME",
105
+ "MAX_MCP_OUTPUT_TOKENS",
106
+ "NODE_OPTIONS",
107
+ "NO_COLOR",
108
+ "OPENAI_API_KEY",
109
+ "PATH",
110
+ "PGDATABASE",
111
+ "PGHOST",
112
+ "PGPASSFILE",
113
+ "PGPASSWORD",
114
+ "PGPORT",
115
+ "PGSERVICE",
116
+ "PGUSER",
117
+ "POSTGRES_DATABASE",
118
+ "POSTGRES_DB",
119
+ "POSTGRES_HOST",
120
+ "POSTGRES_PASSWORD",
121
+ "POSTGRES_PORT",
122
+ "POSTGRES_USER",
123
+ "SHELL",
124
+ "TEMP",
125
+ "TERM",
126
+ "TMP",
127
+ "TMPDIR",
128
+ "USER",
129
+ "XDG_CONFIG_HOME",
130
+ ];
131
+ /** Reserved name prefixes; a sorted copy of `WORKER_ENV_RESERVED_PREFIXES_SORTED`. */
132
+ const WORKER_ENV_RESERVED_PREFIXES = [
133
+ "ANTHROPIC_",
134
+ "BAPI_",
135
+ "BRIDGE_",
136
+ "CLAUDE_",
137
+ "DYLD_",
138
+ "GIT_CONFIG_",
139
+ ];
78
140
  /** Non-secret operational keys forwarded to the worker when present. */
79
141
  const ALLOWED_ENV_KEYS = [
80
142
  "PATH",
@@ -143,8 +205,123 @@ export const CI_WORKER_ENV_CONSTANTS = Object.freeze({
143
205
  BGPT_INVITE_SECRET: "test-invite-secret",
144
206
  ENVIRONMENT: "LOCAL",
145
207
  });
208
+ /**
209
+ * BAPI-1521 — the ONE reserved-name policy for repository-declared worker
210
+ * variables. The exact names and prefixes are the sorted copies of
211
+ * `WORKER_ENV_RESERVED_NAMES_SORTED` / `WORKER_ENV_RESERVED_PREFIXES_SORTED` in
212
+ * `api/library/epic_implementer/gate_profile.py` (the authority; a drift test
213
+ * compares them). Every caller that applies a declaration depends on this export
214
+ * rather than keeping its own list.
215
+ *
216
+ * The executor-owned keys this builder sets or denies (`EXPLICIT_DENY_KEYS`, the
217
+ * allowlisted process names, the database keys `buildWorkerDatabaseEnv` emits)
218
+ * are all covered by those names and prefixes; {@link isWorkerEnvNameReserved}
219
+ * additionally checks `EXPLICIT_DENY_KEYS` and `ALLOWED_ENV_KEYS` so a future
220
+ * executor-owned key cannot be overwritten before the Python list catches up.
221
+ */
222
+ export const WORKER_ENV_RESERVED_POLICY = Object.freeze({
223
+ names: WORKER_ENV_RESERVED_NAMES,
224
+ prefixes: WORKER_ENV_RESERVED_PREFIXES,
225
+ });
226
+ /** True when a declared worker variable may not use `name`. */
227
+ export function isWorkerEnvNameReserved(name) {
228
+ return (WORKER_ENV_RESERVED_POLICY.names.includes(name) ||
229
+ WORKER_ENV_RESERVED_POLICY.prefixes.some((prefix) => name.startsWith(prefix)) ||
230
+ EXPLICIT_DENY_KEYS.includes(name) ||
231
+ ALLOWED_ENV_KEYS.includes(name));
232
+ }
233
+ /**
234
+ * The `{ workerEnv }` option a job payload implies: present exactly when the
235
+ * payload OWNS a `worker_env` key (whatever its value), empty otherwise. Spread it
236
+ * into an options object so absence stays absence. Never reads the value.
237
+ */
238
+ export function payloadWorkerEnvOption(payload) {
239
+ if (typeof payload !== "object" || payload === null || Array.isArray(payload))
240
+ return {};
241
+ if (!Object.prototype.hasOwnProperty.call(payload, "worker_env"))
242
+ return {};
243
+ return { workerEnv: payload.worker_env };
244
+ }
245
+ /** Printed in place of a name that is not a safely printable variable name. */
246
+ const WORKER_ENV_UNPRINTABLE_NAME_LABEL = "(unprintable name)";
247
+ const LONE_SURROGATE = /[\uD800-\uDBFF](?![\uDC00-\uDFFF])|(?<![\uD800-\uDBFF])[\uDC00-\uDFFF]/;
248
+ function logWorkerEnvSkip(name, reason) {
249
+ const label = typeof name === "string" && WORKER_ENV_NAME_PATTERN.test(name)
250
+ ? name
251
+ : WORKER_ENV_UNPRINTABLE_NAME_LABEL;
252
+ console.error(`executor: skipped declared worker variable ${label}: ${reason}`);
253
+ }
254
+ /**
255
+ * Validate a payload `worker_env` declaration against the server's entry rules
256
+ * (BAPI-1520) and return the entries safe to assign. Never throws: an invalid or
257
+ * over-bound entry is skipped with a closed reason and a sanitized name, and the
258
+ * rest of the list still applies. The first occurrence of a name wins.
259
+ *
260
+ * `taken` holds keys the executor already owns in the environment under
261
+ * construction; a declaration naming one is skipped as reserved.
262
+ */
263
+ export function validateWorkerEnvDeclarations(raw, taken = new Set()) {
264
+ if (!Array.isArray(raw)) {
265
+ // Field name only: never the received value.
266
+ console.error("executor: worker_env is present but is not a list; applying no declarations");
267
+ return [];
268
+ }
269
+ const accepted = [];
270
+ const seen = new Set();
271
+ for (let index = 0; index < raw.length; index++) {
272
+ if (index >= MAX_WORKER_ENV_ENTRIES) {
273
+ logWorkerEnvSkip(undefined, "worker_env_over_bound");
274
+ break;
275
+ }
276
+ const item = raw[index];
277
+ if (typeof item !== "object" || item === null || Array.isArray(item)) {
278
+ logWorkerEnvSkip(undefined, "worker_env_invalid_entry");
279
+ continue;
280
+ }
281
+ const entry = item;
282
+ const name = entry.name;
283
+ if (typeof name !== "string" || !WORKER_ENV_NAME_PATTERN.test(name)) {
284
+ logWorkerEnvSkip(name, "worker_env_invalid_name");
285
+ continue;
286
+ }
287
+ const value = entry.value;
288
+ if (typeof value !== "string" || LONE_SURROGATE.test(value) || /[\u0000\r\n]/.test(value)) {
289
+ logWorkerEnvSkip(name, "worker_env_invalid_value");
290
+ continue;
291
+ }
292
+ if (Buffer.byteLength(value, "utf8") > MAX_WORKER_ENV_VALUE_BYTES) {
293
+ logWorkerEnvSkip(name, "worker_env_over_bound");
294
+ continue;
295
+ }
296
+ const flag = entry.committed_literal;
297
+ if (flag !== undefined && typeof flag !== "boolean") {
298
+ logWorkerEnvSkip(name, "worker_env_invalid_entry");
299
+ continue;
300
+ }
301
+ if (isWorkerEnvNameReserved(name) || taken.has(name)) {
302
+ logWorkerEnvSkip(name, "worker_env_reserved_name");
303
+ continue;
304
+ }
305
+ if (isSecretLookingWorkerEnvName(name) && flag !== true) {
306
+ logWorkerEnvSkip(name, "worker_env_secret_name");
307
+ continue;
308
+ }
309
+ if (seen.has(name)) {
310
+ logWorkerEnvSkip(name, "worker_env_duplicate");
311
+ continue;
312
+ }
313
+ seen.add(name);
314
+ accepted.push({ name, value });
315
+ }
316
+ return accepted;
317
+ }
146
318
  /** Substrings that mark a key as secret-bearing (case-insensitive). */
147
319
  const SECRET_NAME_FRAGMENTS = ["TOKEN", "SECRET", "PASSWORD", "API_KEY"];
320
+ /** True when `name` looks secret, so a declaration of it needs `committed_literal: true`. */
321
+ function isSecretLookingWorkerEnvName(name) {
322
+ const upper = name.toUpperCase();
323
+ return SECRET_NAME_FRAGMENTS.some((fragment) => upper.includes(fragment));
324
+ }
148
325
  /**
149
326
  * Explicit deny-list of known secret / MCP / conductor keys.
150
327
  *
@@ -166,6 +343,11 @@ export const EXPLICIT_DENY_KEYS = [
166
343
  // launched the executor must never reach a worker: whoever chose the tag
167
344
  // could make an unrelated process look job-owned to the cleanup sweep.
168
345
  "BRIDGE_EXECUTOR_JOB_TAG",
346
+ // BAPI-1544: the claimed executor job's ID. Like the ownership tag it is
347
+ // injected AFTER this builder and the agent adapter have run (`job-runner.ts`,
348
+ // from the claimed job row), so an ambient value, a job payload, or an adapter
349
+ // can never choose which job a worker registers its delivery binding against.
350
+ "BRIDGE_EXECUTOR_JOB_ID",
169
351
  EPIC_IMPLEMENTER_NODE_PATH_ENV,
170
352
  // BAPI-1190: the legacy spelling stays denied so a stale ambient value from an
171
353
  // older package can never reach a worker during a version-skew window.
@@ -318,6 +500,10 @@ export function isExecutorEnvKeyAllowed(key) {
318
500
  return false;
319
501
  return true;
320
502
  }
503
+ /** True when the options object owns a `workerEnv` property (value irrelevant). */
504
+ export function hasWorkerEnvOption(options) {
505
+ return options !== undefined && Object.prototype.hasOwnProperty.call(options, "workerEnv");
506
+ }
321
507
  export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
322
508
  const env = {};
323
509
  for (const key of ALLOWED_ENV_KEYS) {
@@ -345,8 +531,17 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
345
531
  Object.assign(env, buildWorkerDatabaseEnv(options.workerDatabase));
346
532
  }
347
533
  // BAPI-1479 — CI's throwaway test values, from constants and never from
348
- // `parentEnv`, for every job type and every adapter.
349
- Object.assign(env, CI_WORKER_ENV_CONSTANTS);
534
+ // `parentEnv`, for every job type and every adapter. BAPI-1521: only when the
535
+ // payload did not carry a `worker_env` declaration at all. A present declaration
536
+ // — even an empty or malformed one — replaces the constants, so a repository
537
+ // that cleared its variables gets none, not the legacy defaults.
538
+ const workerEnvPresent = hasWorkerEnvOption(options);
539
+ if (!workerEnvPresent) {
540
+ if (options.legacyNotice !== false) {
541
+ console.error("executor: payload carries no worker_env; applying legacy compatibility constants");
542
+ }
543
+ Object.assign(env, CI_WORKER_ENV_CONSTANTS);
544
+ }
350
545
  // BAPI-1479 — the own-build launcher directory goes FIRST on PATH, from the
351
546
  // explicit option only. The inherited PATH follows it unchanged; an empty or
352
547
  // absent inherited PATH adds no empty component (an empty component means
@@ -392,6 +587,14 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
392
587
  if (Array.isArray(options.declaredTouchedFiles)) {
393
588
  env[DECLARED_TOUCHED_FILES_ENV] = JSON.stringify(normalizeDeclaredTouchedFiles(options.declaredTouchedFiles));
394
589
  }
590
+ // BAPI-1521 — repository-declared variables go in LAST among the base keys and
591
+ // can never overwrite a key the executor already owns in `env`.
592
+ if (workerEnvPresent) {
593
+ const taken = new Set(Object.keys(env));
594
+ for (const { name, value } of validateWorkerEnvDeclarations(options.workerEnv, taken)) {
595
+ env[name] = value;
596
+ }
597
+ }
395
598
  // Nothing agent-specific is added here, and deliberately nothing secret. An
396
599
  // adapter that needs to forward an operator-owned credential declares it as a
397
600
  // passthrough and copies it onto the object this function returns; see
@@ -417,5 +620,6 @@ export function buildExecutorBaseWorkerEnv(parentEnv, options = {}) {
417
620
  * capability probes are not filtered.
418
621
  */
419
622
  export function buildHeadlessAgentEnv(parentEnv) {
420
- return buildExecutorBaseWorkerEnv(parentEnv);
623
+ // BAPI-1521: not a job, so no legacy notice either; it keeps the constants silently.
624
+ return buildExecutorBaseWorkerEnv(parentEnv, { legacyNotice: false });
421
625
  }
@@ -219,7 +219,15 @@ export function parseGateQualificationPayload(job) {
219
219
  return refuse(MESSAGES.contract);
220
220
  return {
221
221
  ok: true,
222
- payload: { repoName: envelope.repo_name, revision: envelope.revision, commands, digest },
222
+ payload: {
223
+ repoName: envelope.repo_name,
224
+ revision: envelope.revision,
225
+ commands,
226
+ digest,
227
+ workerEnvOption: Object.prototype.hasOwnProperty.call(envelope, "worker_env")
228
+ ? { workerEnv: envelope.worker_env }
229
+ : {},
230
+ },
223
231
  };
224
232
  }
225
233
  // ---------------------------------------------------------------------------
@@ -386,6 +394,10 @@ export async function runGateQualificationJob(job, input, deps) {
386
394
  }, OWNERSHIP_POLL_MS);
387
395
  };
388
396
  watchOwnership();
397
+ // BAPI-1521 — the effective environment is built here, AFTER the envelope was
398
+ // verified and BEFORE any command runs, from the sealed declaration. The
399
+ // injected dependencies are never mutated.
400
+ const commandEnv = deps.commandEnv ?? buildGateQualificationEnv(deps.baseEnv ?? {}, payload.workerEnvOption);
389
401
  const commands = payload.commands.map((command) => ({
390
402
  identity: command.identity,
391
403
  position: command.position,
@@ -398,7 +410,7 @@ export async function runGateQualificationJob(job, input, deps) {
398
410
  const run = await runRequiredVerificationCommands({
399
411
  commands,
400
412
  worktreePath: dir,
401
- env: deps.commandEnv,
413
+ env: commandEnv,
402
414
  launch: deps.launch,
403
415
  now: deps.now,
404
416
  deadlineAtMs,
@@ -449,9 +461,12 @@ export async function runGateQualificationJob(job, input, deps) {
449
461
  * The explicit command environment: the executor's worker base environment
450
462
  * (allowlisted keys, parent credentials stripped, sentinel database values,
451
463
  * `BRIDGE_SKIP_PREPUSH=1`) plus `CI=1`, so test tooling runs non-interactively.
464
+ * BAPI-1521: the sealed declaration's `worker_env` is passed with its presence
465
+ * intact — absent keeps the compatibility constants, present replaces them.
452
466
  */
453
- export function buildGateQualificationEnv(parentEnv) {
454
- return { ...buildExecutorBaseWorkerEnv(parentEnv), CI: "1" };
467
+ export function buildGateQualificationEnv(parentEnv, workerEnvOption = {}) {
468
+ // BAPI-1521: `CI=1` is applied last, so a declaration can never turn it off.
469
+ return { ...buildExecutorBaseWorkerEnv(parentEnv, workerEnvOption), CI: "1" };
455
470
  }
456
471
  /**
457
472
  * Production dependencies built from the executor's own boundary.
@@ -480,7 +495,7 @@ export function createProductionGateQualificationDeps(input) {
480
495
  deps,
481
496
  ...(input.registerLive ? { registerLive: input.registerLive } : {}),
482
497
  }),
483
- commandEnv: buildGateQualificationEnv(deps.env),
498
+ baseEnv: deps.env,
484
499
  repoRoot: deps.cwd,
485
500
  fallbackBaseBranch: options.baseBranch,
486
501
  makeTempDir,