@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.
Files changed (123) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agent-launchers/prompt.js +9 -21
  4. package/build/agents.generated.js +4 -4
  5. package/build/authored-plan.js +542 -0
  6. package/build/bridge-config.js +7 -1
  7. package/build/bridge-permissions.js +11 -0
  8. package/build/command-provisioning.js +4 -3
  9. package/build/commands.generated.js +6 -6
  10. package/build/conductor/bridge-api-client.js +692 -47
  11. package/build/conductor/command-drift.js +1 -1
  12. package/build/conductor/declared-extras.js +335 -0
  13. package/build/conductor/doctor.js +2 -0
  14. package/build/conductor/driver-pass-output.js +104 -0
  15. package/build/conductor/driver-pass.js +571 -0
  16. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  17. package/build/conductor/epic-implementer-cli.js +370 -93
  18. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  19. package/build/conductor/epic-server-sfcc.js +58 -80
  20. package/build/conductor/epic-server.js +57 -4
  21. package/build/conductor/gate-discovery.js +253 -13
  22. package/build/conductor/gate-settings-review.js +58 -25
  23. package/build/conductor/launch-plan.js +58 -12
  24. package/build/conductor/open-decision-phrases.js +50 -0
  25. package/build/conductor/prerequisite-inputs.js +181 -14
  26. package/build/connect-github-api.js +18 -0
  27. package/build/connect-github.js +35 -18
  28. package/build/credential-delivery.js +280 -0
  29. package/build/credential-launch-safety.js +142 -0
  30. package/build/credential-materialization.js +91 -16
  31. package/build/credential-references-node-deps.js +29 -0
  32. package/build/credential-references.js +1394 -0
  33. package/build/credential-references.test-fixtures.js +211 -0
  34. package/build/credential-scan-conventions.js +145 -0
  35. package/build/credential-scan.js +517 -0
  36. package/build/credential-store.js +50 -0
  37. package/build/credentials-cli.js +252 -3
  38. package/build/dependency-install-declarations.js +47 -1
  39. package/build/docs.generated.js +8 -1
  40. package/build/doctor.js +41 -0
  41. package/build/drive-epic.js +684 -49
  42. package/build/epic-branch-ci-summary.js +18 -1
  43. package/build/epic-capability-statement.js +71 -3
  44. package/build/epic-ci-workflow-drift.js +52 -13
  45. package/build/epic-ci-workflow-install.js +31 -6
  46. package/build/epic-ci-workflow-v3.js +273 -0
  47. package/build/epic-ci-workflow.js +129 -7
  48. package/build/epic-implementer-bin.js +288 -83
  49. package/build/epic-implementer-bundle-cli.js +61 -0
  50. package/build/epic-implementer-claude-hook-bin.js +1 -1
  51. package/build/epic-implementer-env.js +3 -4
  52. package/build/epic-integration-pr.js +5 -2
  53. package/build/epic-launch-context.js +102 -7
  54. package/build/epic-server-record.js +30 -15
  55. package/build/executor/completion-contract.js +24 -1
  56. package/build/executor/credential-delivery-step.js +168 -0
  57. package/build/executor/deps.js +3 -1
  58. package/build/executor/env.js +39 -1
  59. package/build/executor/epic-server-context.js +23 -7
  60. package/build/executor/gate-qualification-job.js +193 -23
  61. package/build/executor/gate-qualification-tests-ran.js +232 -0
  62. package/build/executor/guarded-fast-forward-push.js +13 -8
  63. package/build/executor/job-runner.js +167 -738
  64. package/build/executor/job-type-wrappers.js +734 -0
  65. package/build/executor/permissions.js +85 -3
  66. package/build/executor/preflight.js +6 -2
  67. package/build/executor/process-containment.js +8 -1
  68. package/build/executor/prompt-spec.js +37 -3
  69. package/build/executor/required-verification.js +28 -2
  70. package/build/executor/runner.js +4 -1
  71. package/build/executor/types.js +9 -0
  72. package/build/executor/worker-database.js +6 -1
  73. package/build/executor/worker-guard-hook.js +24 -2
  74. package/build/executor-launch.js +4 -2
  75. package/build/generated/ticket-status.js +20 -0
  76. package/build/git-exclude-lock.js +187 -0
  77. package/build/index.js +589 -326
  78. package/build/install-bridge-conductor-answers.js +112 -22
  79. package/build/install-bridge-conductor-apply.js +38 -1
  80. package/build/install-bridge-conductor-assessment.js +482 -53
  81. package/build/install-bridge-conductor-compact.js +29 -2
  82. package/build/install-bridge-conductor-contracts.js +10 -1
  83. package/build/install-bridge-conductor-gate.js +379 -89
  84. package/build/install-bridge-conductor-setup.js +46 -8
  85. package/build/install-bridge-conductor-trial-report.js +170 -0
  86. package/build/install-bridge-conductor.js +925 -141
  87. package/build/install-bridge.js +88 -11
  88. package/build/install-doctor.js +38 -8
  89. package/build/install-sfcc-detection.js +120 -0
  90. package/build/install-sfcc-setup.js +185 -0
  91. package/build/mcp-grant-candidates.js +108 -96
  92. package/build/mcp-invoke.js +168 -4
  93. package/build/mcp-provisioning.js +21 -4
  94. package/build/mcp-server-invocation.js +13 -0
  95. package/build/merge-workflow-install.js +9 -1
  96. package/build/pipelines.generated.js +8 -7
  97. package/build/plan-generation.js +17 -0
  98. package/build/plane/status.js +8 -2
  99. package/build/printed-remedy-commands.js +59 -0
  100. package/build/project-root.js +40 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-state-paths.js +5 -2
  103. package/build/repository-toolchains.js +16 -7
  104. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  105. package/build/setup-epic.js +126 -16
  106. package/build/sfcc/credentials.js +3 -2
  107. package/build/sfcc/hostname.js +98 -2
  108. package/build/sfcc/tool-wrapper.js +6 -95
  109. package/build/start-tickets.js +193 -29
  110. package/build/test-support/executor-source-files.js +200 -0
  111. package/build/testing-config-client.js +25 -2
  112. package/build/third-party-mcp-targets.js +35 -4
  113. package/build/v2-readiness-requirements.js +5 -1
  114. package/build/version.generated.js +3 -3
  115. package/build/with-credentials.js +208 -0
  116. package/build/worker-guard-hook-bin.js +2 -2
  117. package/build/worktree-credential-delivery.js +340 -0
  118. package/docs/EPIC-IMPLEMENTER.md +4 -4
  119. package/docs/install/github-app.md +79 -92
  120. package/package.json +1 -1
  121. package/build/conductor/epic-reconcile.js +0 -603
  122. package/build/conductor/epic-runtime.js +0 -2020
  123. package/build/conductor/epic-state.js +0 -774
@@ -37,7 +37,39 @@
37
37
  */
38
38
  import { randomUUID } from "node:crypto";
39
39
  import path from "node:path";
40
+ import { acquireExcludeLock } from "../git-exclude-lock.js";
40
41
  import { mergeClaudeSettingsWithAutoMemoryDisabled, mergeClaudeSettingsWithCommandHook, provisionClaudeSettingsForWorktree, DEFAULT_PRE_TOOL_USE_MATCHER, } from "../claude-settings.js";
42
+ /**
43
+ * BAPI-1647: one exact `Read(<path>)` rule per distinct restricted source path,
44
+ * in first-seen order. A path with a control character, or that is not
45
+ * absolute, is skipped (child 1 already refuses both in the record).
46
+ *
47
+ * A POSIX absolute path also gets the `Read(/<path>)` form (two leading
48
+ * slashes): Claude Code's permission grammar reads a single leading `/` as
49
+ * relative to the settings file and `//` as the filesystem root, so the second
50
+ * form is the one that is certain to match the real file. The first form is the
51
+ * one the ticket and `doctor` name, and it matches this module's existing
52
+ * `Read(/etc/shadow)` convention.
53
+ */
54
+ export function restrictedSourceDenyRules(paths) {
55
+ if (!paths || paths.length === 0)
56
+ return [];
57
+ const rules = [];
58
+ const seen = new Set();
59
+ for (const p of paths) {
60
+ if (typeof p !== "string" || p.length === 0 || /[\u0000-\u001f\u007f]/.test(p))
61
+ continue;
62
+ if (!path.posix.isAbsolute(p) && !path.win32.isAbsolute(p))
63
+ continue;
64
+ if (seen.has(p))
65
+ continue;
66
+ seen.add(p);
67
+ rules.push(`Read(${p})`);
68
+ if (path.posix.isAbsolute(p) && !p.startsWith("//"))
69
+ rules.push(`Read(/${p})`);
70
+ }
71
+ return rules;
72
+ }
41
73
  /**
42
74
  * The stable executor deny rules. Grammar mirrors the deny-enforcement probe's
43
75
  * `Bash(<cmd>:<args-glob>)` / `Read(<path-glob>)` form. Covers: reads under
@@ -115,6 +147,9 @@ export function executorDenyRules(inputs) {
115
147
  "Bash(docker:push*)",
116
148
  "Bash(git push:*mcp-server/v*)",
117
149
  "Bash(npm:publish*)",
150
+ // BAPI-1647 — restricted credential sources, appended after the stable list
151
+ // so a job with none gets exactly the list above.
152
+ ...restrictedSourceDenyRules(inputs.restrictedSourcePaths),
118
153
  ];
119
154
  }
120
155
  /**
@@ -226,16 +261,46 @@ function asObject(value) {
226
261
  * replaced.
227
262
  */
228
263
  export function mergeExecutorDenySettings(existing, inputs) {
264
+ return mergeDenyRules(existing, executorDenyRules(inputs));
265
+ }
266
+ /**
267
+ * Append `rules` to `permissions.deny`, keeping every existing setting and deny
268
+ * entry in place and adding only rules not already present (idempotent).
269
+ * Shared by the executor merge and BAPI-1647's restricted-read-only merge.
270
+ */
271
+ export function mergeDenyRules(existing, rules) {
229
272
  const permissions = { ...asObject(existing.permissions) };
230
273
  const existingDeny = Array.isArray(permissions.deny) ? permissions.deny : [];
231
274
  const merged = [...existingDeny];
232
- for (const rule of executorDenyRules(inputs)) {
275
+ for (const rule of rules) {
233
276
  if (!merged.includes(rule))
234
277
  merged.push(rule);
235
278
  }
236
279
  permissions.deny = merged;
237
280
  return { ...existing, permissions };
238
281
  }
282
+ /**
283
+ * BAPI-1647: merge ONLY the restricted-source `Read(<path>)` rules into a
284
+ * worktree's `.claude/settings.local.json`, for `start-tickets` worktrees, which
285
+ * must not receive the executor's command restrictions. Uses the same
286
+ * malformed-safe write as the executor deny layer: a malformed file is never
287
+ * clobbered, unrelated settings and MCP trust entries are kept, and every
288
+ * failure is an advisory warning, never a stop.
289
+ */
290
+ export async function provisionRestrictedReadDenyRules(worktreePath, restrictedSourcePaths, deps) {
291
+ const rules = restrictedSourceDenyRules(restrictedSourcePaths);
292
+ if (rules.length === 0)
293
+ return { ok: true };
294
+ try {
295
+ const result = await provisionClaudeSettingsForWorktree(worktreePath, (existing) => mergeDenyRules(existing, rules), deps);
296
+ if (result.ok)
297
+ return { ok: true };
298
+ return { ok: false, warning: "restricted credential read rules were not written: the worktree Claude settings could not be updated" };
299
+ }
300
+ catch {
301
+ return { ok: false, warning: "restricted credential read rules were not written: the worktree Claude settings could not be updated" };
302
+ }
303
+ }
239
304
  /**
240
305
  * The exact line appended to the worktree's `.git/info/exclude` so a worker's
241
306
  * `git add -A` cannot commit the executor-owned settings file.
@@ -447,8 +512,15 @@ export async function resolveWorktreeSettingsExclude(worktreePath, deps) {
447
512
  * the same `info/` directory and renamed into place; no lockfile is used, and
448
513
  * nothing is published when no canonical line is missing. Competing executor
449
514
  * writers add the same canonical entries, so fresh reads plus atomic publication
450
- * prevent torn files and executor-created duplicates. This does not serialize
451
- * against unrelated external editors.
515
+ * prevent torn files and executor-created duplicates. Since BAPI-1647 the whole
516
+ * read-modify-write also runs inside the cross-process exclude lock
517
+ * (`git-exclude-lock.ts`), keyed on the canonical exclude path and shared with
518
+ * every other Bridge exclude writer, so concurrent launches in two worktrees of
519
+ * one repository cannot drop each other's lines. A fresh read alone did not
520
+ * prevent that lost update. The lock is best effort here: when it cannot be had,
521
+ * the publication proceeds exactly as before, so this function's outcome never
522
+ * changes because of it. It does not serialize against unrelated external
523
+ * editors.
452
524
  *
453
525
  * Warnings are bounded to a failure category plus the affected worktree path.
454
526
  * They never carry `.git` contents, exception text, environment values, or
@@ -466,6 +538,9 @@ export async function provisionWorktreeSettingsExclude(worktreePath, deps) {
466
538
  }
467
539
  const { excludePath, infoDir } = resolved;
468
540
  let tempPath;
541
+ // Only when the caller supplies its lock boundary: the executor's injected
542
+ // filesystem is the single I/O boundary its tests fake.
543
+ const lock = deps.excludeLock ? await acquireExcludeLock(excludePath, deps.excludeLock) : null;
469
544
  try {
470
545
  await deps.mkdir(infoDir, { recursive: true });
471
546
  let existing = "";
@@ -510,6 +585,10 @@ export async function provisionWorktreeSettingsExclude(worktreePath, deps) {
510
585
  warning: excludeWarning(worktreePath, "the exclude file could not be written"),
511
586
  };
512
587
  }
588
+ finally {
589
+ if (lock?.ok)
590
+ await lock.release();
591
+ }
513
592
  }
514
593
  /**
515
594
  * Provision the executor deny layer into `<worktree>/.claude/settings.local.json`,
@@ -528,6 +607,9 @@ export async function provisionExecutorDenyLayer(worktreePath, options, deps) {
528
607
  baseBranch: options.baseBranch,
529
608
  worktreePath,
530
609
  homedir: deps.homedir(),
610
+ ...(options.restrictedSourcePaths && options.restrictedSourcePaths.length > 0
611
+ ? { restrictedSourcePaths: options.restrictedSourcePaths }
612
+ : {}),
531
613
  };
532
614
  // BAPI-1397 (F7): the deny list the worktree will actually carry — the executor
533
615
  // rules plus any operator-authored entries already in the file. Captured from
@@ -12,7 +12,7 @@ import { spawnSync } from "node:child_process";
12
12
  import { defaultResolveBinPath } from "../start-tickets-conductor.js";
13
13
  import { CORRECTION_INTENT_CAPABILITY } from "./correction-dispatch.js";
14
14
  import { resolveAllExecutorApiAccess, resolveBaseUrl, EXECUTOR_BASE_URL_REQUIRED_MESSAGE, } from "./credentials.js";
15
- import { FOCUSED_REBASE_CAPABILITY, GATE_QUALIFICATION_CAPABILITY, SCOPE_WAIT_CAPABILITY, } from "./types.js";
15
+ import { FOCUSED_REBASE_CAPABILITY, GATE_QUALIFICATION_CAPABILITY, GATE_QUALIFICATION_WORKER_DATABASE_CAPABILITY, SCOPE_WAIT_CAPABILITY, } from "./types.js";
16
16
  /**
17
17
  * Environment override for the deny probe's headless timeout (BAPI-722).
18
18
  *
@@ -674,7 +674,11 @@ export function buildClaimManifest(report, options, freeSlots) {
674
674
  // pick up repository-level qualification work it was never dedicated to.
675
675
  // Gating the token on `repoWide` keeps that work on the executor whose
676
676
  // operator chose the whole repository.
677
- ...(options.repoWide === true ? [GATE_QUALIFICATION_CAPABILITY] : []),
677
+ // BAPI-1698: the worker-database qualification capability rides the same
678
+ // repository-wide gate, beside the base token it extends.
679
+ ...(options.repoWide === true
680
+ ? [GATE_QUALIFICATION_CAPABILITY, GATE_QUALIFICATION_WORKER_DATABASE_CAPABILITY]
681
+ : []),
678
682
  ],
679
683
  // BAPI-1391: an optional job-type filter, present only when configured. An
680
684
  // older server rejects the key with a 422, so it must never appear by
@@ -6,7 +6,14 @@
6
6
  * process the job started is still running. This module produces that
7
7
  * confirmation as a closed `CompletionCleanup` verdict. The verdict is
8
8
  * SUCCESS-BLOCKING: anything other than `confirmed` with zero survivors refuses
9
- * success (`successRefusalReason` in `completion-contract.ts`).
9
+ * success (`successRefusalReason` in `completion-contract.ts`), with ONE
10
+ * exception (BAPI-1690): a `failed` verdict with a positive integer survivor
11
+ * count and exactly the single reason `survivors_detected` (`isAllStoppedCleanup`).
12
+ * That reason list is only produced when the sweep terminated every detected
13
+ * process and the confirmation sweep then found none remaining; any other
14
+ * reason (ownership_unverifiable, enumeration_failed, sweep_deadline_exhausted,
15
+ * not_run) means termination or confirmation is unproven and still blocks.
16
+ * The recorded verdict stays `failed`; the sweep logic is unchanged.
10
17
  *
11
18
  * WHAT THIS IS NOT. It is not the adapter's configuration lifecycle cleanup in
12
19
  * `agent-launchers/executor-adapter.ts` (temporary config files, isolation
@@ -24,7 +24,7 @@ import { WORKER_BACKGROUND_WORK_RULE } from "./required-work-diagnostics.js";
24
24
  import { validateEpicCapabilityStatement } from "../epic-capability-statement.js";
25
25
  import { epicServerAcquireCommandSeconds } from "./epic-server-context.js";
26
26
  import { EPIC_SERVER_DEFAULT_TIMING } from "../conductor/epic-server-recipe.js";
27
- import { buildSfccWorkerPolicyText } from "../conductor/epic-server-sfcc.js";
27
+ import { buildSfccUploadWorkerText, buildSfccWorkerPolicyText, SFCC_UPLOAD_WORKER_COMMAND_SECONDS, } from "../conductor/epic-server-sfcc.js";
28
28
  /**
29
29
  * BAPI-1546: the epic-server turn paragraph, a SEPARATE builder so the
30
30
  * workaround contract ({@link buildEpicWorkaroundWorkerInstruction}) stays
@@ -51,7 +51,8 @@ export function buildEpicServerWorkerInstruction(context, ticketKey) {
51
51
  if (context.kind === "disabled")
52
52
  return null;
53
53
  if (context.kind === "sfcc") {
54
- const sfcc = buildSfccWorkerPolicyText(context.origin);
54
+ const sfccTicket = ticketKey && /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/.test(ticketKey) ? ticketKey : "<TICKET>";
55
+ const sfcc = buildSfccWorkerPolicyText(context.origin, sfccTicket, SFCC_UPLOAD_WORKER_COMMAND_SECONDS);
55
56
  return /[;'"\r\n]/.test(sfcc) ? null : sfcc;
56
57
  }
57
58
  const ticket = ticketKey && /^[A-Z][A-Z0-9_]{0,19}-\d{1,9}$/.test(ticketKey) ? ticketKey : "<TICKET>";
@@ -83,6 +84,12 @@ export function buildEpicServerWorkerInstruction(context, ticketKey) {
83
84
  "launcher on your PATH. If it is granted, follow the turn rules. " + turnRules + " Otherwise its output is the " +
84
85
  "observation. " + handoff;
85
86
  }
87
+ if (context.sfccUpload === true) {
88
+ // The same upload sentences as the SFCC text, then the turn rules apply as above.
89
+ line =
90
+ line + " This run also approved a sandbox code version. " + buildSfccUploadWorkerText(ticket, SFCC_UPLOAD_WORKER_COMMAND_SECONDS) +
91
+ " Run the upload before you acquire the turn, and acquire the turn again for any repeated check.";
92
+ }
86
93
  return /[;'"\r\n]/.test(line) ? null : line;
87
94
  }
88
95
  /**
@@ -183,7 +190,18 @@ export function buildEpicWorkaroundWorkerInstruction(ticketKey, handoffEnabled)
183
190
  "workaround: guard exactly the deferred behavior (for example, check for a missing setting and skip " +
184
191
  "only that feature), keep the core path working, and write " + record + " naming the requirement, " +
185
192
  "the guarded substitute you delivered, and the step a human must still take. Commit that record on " +
186
- "this ticket branch with git add -f " + record + ". For a core gap, never write a workaround or a " +
193
+ "this ticket branch with git add -f " + record + ". " +
194
+ "Minor-gap disposition, for this Epic Implementer run only: when you deliver a guarded substitute " +
195
+ "for a minor gap, record that plan step as executed, not escalated. Its evidence must say that the " +
196
+ "substitute, not the original requirement, was delivered, and name the substitute, the workaround " +
197
+ "record, and the owner action still owed and when. A missing future value is a minor gap only when " +
198
+ "it is informational at this hand-off, such as a release version named in docs or a PR description " +
199
+ "that is set at publish, and a clearly marked placeholder keeps the essential behavior and every " +
200
+ "safety and correctness guarantee. A value that runtime behavior or safe operation needs is not " +
201
+ "minor just because a person supplies it later. Needing information from an outside action is not " +
202
+ "taking that action. This rule overrides the general escalation and disposition instructions only " +
203
+ "for these substitutions. Never mark unfinished core work executed to unblock delivery. " +
204
+ "For a core gap, never write a workaround or a " +
187
205
  "record: leave the required work unfinished so the run parks this ticket for a human. Planned " +
188
206
  "hand-offs: if a running app or database, a toolchain version, or live credentials are needed only " +
189
207
  "to verify an acceptance criterion and not to implement it safely, that is a planned hand-off and " +
@@ -907,3 +925,19 @@ export async function renderPromptSpecPrompt(job, context) {
907
925
  (!context.deferComparisonGuidance && job.job_type === "ci_fix"
908
926
  ? "\n\n" + renderWorkerTimeBudgetGuidance(context.timeoutSeconds) : "");
909
927
  }
928
+ /**
929
+ * BAPI-1647: one line naming the referenced credentials this worker did NOT
930
+ * receive, using child 1's closed status vocabulary (`source_missing`,
931
+ * `unreadable`, `parse_error`, `key_missing`) and the delivery outcomes. Names
932
+ * only — the caller formats each notice through `credential-delivery.ts`, which
933
+ * never carries a value, a path, or exception text. Returns "" when nothing is
934
+ * missing, so the prompt stays byte-identical.
935
+ */
936
+ export function buildCredentialNoticeWorkerInstruction(noticeLines) {
937
+ if (noticeLines.length === 0)
938
+ return "";
939
+ return ("Credential notice: some approved credentials were not provided to this worker. " +
940
+ noticeLines.join("; ") +
941
+ ". Work without them; do not search for, recreate, or ask for their values. If a step truly needs one, " +
942
+ "follow the workaround contract.");
943
+ }
@@ -111,9 +111,22 @@ export async function runRequiredVerificationCommands(input) {
111
111
  outcome = "cancelled";
112
112
  reason = input.ownershipHeld && !input.ownershipHeld() ? "ownership_lost" : "executor_cancelled";
113
113
  break;
114
- default:
114
+ case "killed_by_signal":
115
+ // BAPI-1698: the command ran and was killed by a signal nobody requested.
116
+ // A failure like any non-zero exit, so it keeps the non-zero stop rule.
117
+ outcome = "exited_nonzero";
118
+ reason = "killed_by_signal";
119
+ break;
120
+ case "launch_error":
121
+ outcome = "launch_error";
122
+ reason = "spawn_failed";
123
+ break;
124
+ default: {
125
+ const unhandled = launched.outcome;
126
+ void unhandled;
115
127
  outcome = "launch_error";
116
128
  reason = "spawn_failed";
129
+ }
117
130
  }
118
131
  facts.push({
119
132
  identity: command.identity,
@@ -276,12 +289,25 @@ export function createSupervisedCommandLauncher(input) {
276
289
  drainDeadlineMs: CHECK_DRAIN_BOUND_MS,
277
290
  });
278
291
  const output = `${result.stdoutExcerpt}\n${result.stderrExcerpt}`;
292
+ // BAPI-1698 — the order is load-bearing. Only an executor-side request
293
+ // (an abort, a timeout, a requested termination) is an interruption; a
294
+ // process that never started is a launch error; a started process killed
295
+ // by a signal nobody requested is a failure of the command.
279
296
  if (cancelled)
280
297
  return { outcome: { kind: "cancelled" }, output };
281
298
  if (result.classification === "timeout")
282
299
  return { outcome: { kind: "timed_out" }, output };
300
+ if (controller.isTerminationRequested())
301
+ return { outcome: { kind: "cancelled" }, output };
302
+ if (proc.pid === undefined && result.exitCode === null) {
303
+ // The spawn boundary reports a failed start (a missing program or
304
+ // folder) as no pid and no exit code — never inferred from exit 127.
305
+ return { outcome: { kind: "launch_error" }, output };
306
+ }
307
+ if (result.signal !== null)
308
+ return { outcome: { kind: "killed_by_signal" }, output };
283
309
  if (result.exitUnconfirmed || result.exitCode === null) {
284
- // Killed or vanished without an exit code we can trust: not an exit.
310
+ // Vanished without an exit code we can trust: not an exit.
285
311
  return { outcome: { kind: "cancelled" }, output };
286
312
  }
287
313
  return { outcome: { kind: "exited", exitCode: result.exitCode }, output };
@@ -360,7 +360,9 @@ export async function runExecutor(options, deps, httpClient, seams = {}) {
360
360
  * this requests the epic's existing draft integration pull request be
361
361
  * marked ready for review — it never creates a merge and never merges
362
362
  * anything; only a human merges an epic integration branch (see
363
- * `epic-integration-pr.ts`). Every failure here — a missing read
363
+ * `epic-integration-pr.ts`). It also never opens a pull request: `done`
364
+ * usually follows the integration PR's merge, so finding none open is the
365
+ * normal end of a run, not a gap to fill. Every failure here — a missing read
364
366
  * capability, a sanitized transport/validation failure, an invalid branch,
365
367
  * or an unexpected throw — is ADVISORY: it is logged (credential-free,
366
368
  * bounded) and never affects claiming, running jobs, or the runner's exit.
@@ -413,6 +415,7 @@ export async function runExecutor(options, deps, httpClient, seams = {}) {
413
415
  baseBranch: options.baseBranch,
414
416
  command: "executor wind-down",
415
417
  requestReady: true,
418
+ createIfAbsent: false,
416
419
  gh,
417
420
  cwd: deps.cwd,
418
421
  });
@@ -53,6 +53,15 @@ export const EXECUTOR_CLASSIFICATION_VALUES = [
53
53
  * `required_capabilities`, so only a claim declaring it can take such a job.
54
54
  */
55
55
  export const GATE_QUALIFICATION_CAPABILITY = "gate_qualification.v1";
56
+ /**
57
+ * BAPI-1698 — the capability a repository-wide executor declares when it can
58
+ * provision and drop a disposable worker database for a `gate_qualification`
59
+ * job whose sealed declaration carries `worker_database`. The server requires it
60
+ * only for such a job, so an older executor leaves the job queued for a newer
61
+ * one. Mirrors `GATE_QUALIFICATION_WORKER_DATABASE_CAPABILITY` in
62
+ * `src/python/llms/executor_completion_contract.py`.
63
+ */
64
+ export const GATE_QUALIFICATION_WORKER_DATABASE_CAPABILITY = "gate_qualification.worker_database.v1";
56
65
  /**
57
66
  * BAPI-1311 — the capability an executor declares when it can run a FOCUSED
58
67
  * merge-stage `rebase`: validate `payload.focused_rebase` before any worker
@@ -790,9 +790,13 @@ export function classifyWorkerDatabaseMigrationFailure(result) {
790
790
  function buildAlembicEnv(name, config, deps, workerEnvOption) {
791
791
  const env = buildExecutorBaseWorkerEnv({ PATH: deps.clientPath, HOME: deps.clientHome }, { workerDatabase: { name }, workerDatabaseConfig: config, legacyNotice: false, ...workerEnvOption });
792
792
  // Two worker-only switches the shared builder always sets; a migration never
793
- // needed them, and provisioning behavior is unchanged.
793
+ // needed them, and provisioning behavior is unchanged. A repository may also
794
+ // declare PYTHON_DOTENV_DISABLED in its worker_env for its workers; the
795
+ // migration runs from the operator checkout and may still read that
796
+ // checkout's `.env`, so it is dropped here too.
794
797
  delete env.BRIDGE_SKIP_PREPUSH;
795
798
  delete env.MAX_MCP_OUTPUT_TOKENS;
799
+ delete env.PYTHON_DOTENV_DISABLED;
796
800
  return env;
797
801
  }
798
802
  /**
@@ -1082,6 +1086,7 @@ function buildOfflineAlembicEnv(deps, options) {
1082
1086
  });
1083
1087
  delete env.BRIDGE_SKIP_PREPUSH;
1084
1088
  delete env.MAX_MCP_OUTPUT_TOKENS;
1089
+ delete env.PYTHON_DOTENV_DISABLED;
1085
1090
  return env;
1086
1091
  }
1087
1092
  /** Run one offline Alembic command and map interruption and failure to a row result. */
@@ -111,6 +111,12 @@ export function renderWorkerGuardReason(category, family, form) {
111
111
  "made outside the worker. Do not run regenerate-plan or call its route; record the " +
112
112
  "step escalated with its reason and continue.");
113
113
  }
114
+ if (category === "operator-verb" && (family === "reserve-council" || family === "record-decision")) {
115
+ return (`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ` +
116
+ "Convening or settling an open-decision council is the run driver's decision, " +
117
+ "made outside the worker. Do not run reserve-council or record-decision; record " +
118
+ "the open choice as an escalated step with its reason and continue.");
119
+ }
114
120
  if (category === "operator-verb" && family === "acknowledge-gaps") {
115
121
  return (`${WORKER_GUARD_REASON_PREFIX}: denied ${family} (${category}). ` +
116
122
  "Acknowledging the run's carried-gap list is the run owner's decision, made " +
@@ -1022,7 +1028,14 @@ function isClaudeWorkflowPrintLaunch(segment) {
1022
1028
  * the owner's one acknowledgement of the run's carried-gap list (route segment
1023
1029
  * `/acknowledge-gaps`), the same way.
1024
1030
  */
1025
- const OPERATOR_ONLY_VERBS = ["resolve-handoff", "regenerate-plan", "acknowledge-gaps"];
1031
+ // BAPI-1705: a worker never convenes or settles a driver council either.
1032
+ const OPERATOR_ONLY_VERBS = [
1033
+ "resolve-handoff",
1034
+ "regenerate-plan",
1035
+ "acknowledge-gaps",
1036
+ "reserve-council",
1037
+ "record-decision",
1038
+ ];
1026
1039
  /** The packaged MCP-server package token after `npx` (any version suffix). */
1027
1040
  const BRIDGE_PACKAGE_TOKEN = /^@bridge_gpt\/mcp-server(?:@\S+)?$/;
1028
1041
  /** Package runners whose package argument launches the packaged CLI. */
@@ -1070,7 +1083,16 @@ function namedOperatorOnlyRoute(token) {
1070
1083
  break;
1071
1084
  decoded = next;
1072
1085
  }
1073
- return OPERATOR_ONLY_VERBS.find((verb) => decoded.toLowerCase().includes(`/${verb}`) || token.toLowerCase().includes(`/${verb}`));
1086
+ const haystacks = [decoded.toLowerCase(), token.toLowerCase()];
1087
+ // BAPI-1705: the two council verbs share one route segment, `/driver-councils`.
1088
+ // A segment followed by a council row id is the settle (record-decision); the
1089
+ // bare collection is the reserve. Both are denied either way.
1090
+ for (const text of haystacks) {
1091
+ const council = /\/driver-councils(\/[^/?#\s"'`]+)?/.exec(text);
1092
+ if (council)
1093
+ return council[1] ? "record-decision" : "reserve-council";
1094
+ }
1095
+ return OPERATOR_ONLY_VERBS.find((verb) => haystacks.some((text) => text.includes(`/${verb}`)));
1074
1096
  }
1075
1097
  /** Node options whose next token is a value, not the script. */
1076
1098
  const NODE_VALUE_OPTIONS = new Set([
@@ -51,7 +51,7 @@ import path from "node:path";
51
51
  import { LOCAL_MERGE_CREDENTIAL_ENV_KEYS, } from "./conductor/merge-credential.js";
52
52
  import { shellQuote } from "./epic-launch-profile.js";
53
53
  import { isValidExecutorEpicRunId } from "./executor/claim-scope.js";
54
- import { ensureGitInfoExcluded } from "./git-ignore-utils.js";
54
+ import { ensureGitInfoExcludedSerialized } from "./git-exclude-lock.js";
55
55
  import { createPlaneExecFile, createPlaneProcessDeps, probeAutomationHealth, resolvePackageEntrypoint, } from "./plane/defaults.js";
56
56
  import { buildPlaneRedactor } from "./plane/supervisor.js";
57
57
  /** Directory, relative to the Git top level, holding every launcher file. */
@@ -151,7 +151,9 @@ export function createDefaultRunExecutorLaunchDeps() {
151
151
  return null;
152
152
  }
153
153
  },
154
- ensureIgnored: (repoRoot) => ensureGitInfoExcluded(repoRoot, RUN_EXECUTOR_IGNORE_ENTRY, {
154
+ ensureIgnored: (repoRoot) =>
155
+ // BAPI-1647: serialized with every other Bridge exclude writer.
156
+ ensureGitInfoExcludedSerialized(repoRoot, RUN_EXECUTOR_IGNORE_ENTRY, {
155
157
  readFile: (filePath) => readFile(filePath, "utf-8"),
156
158
  writeFile: async (filePath, data) => {
157
159
  const handle = await open(filePath, "w");
@@ -0,0 +1,20 @@
1
+ // Generated by scripts/generate_ticket_status_types.py. Do not edit.
2
+ export const EPIC_TICKET_STATUS_VALUES = [
3
+ "planned",
4
+ "ready",
5
+ "dispatched",
6
+ "running",
7
+ "blocked",
8
+ "abandoned",
9
+ "done",
10
+ "ready_for_review",
11
+ "reviewing",
12
+ "spec_review",
13
+ "implementing",
14
+ "ci",
15
+ "code_review",
16
+ "merging",
17
+ "parsing",
18
+ "smoke",
19
+ "needs_human",
20
+ ];
@@ -0,0 +1,187 @@
1
+ /**
2
+ * BAPI-1647: a bounded cross-process lock for Bridge's writes to a checkout's
3
+ * `info/exclude`.
4
+ *
5
+ * `ensureGitInfoExcluded()` (`git-ignore-utils.ts`) and the executor's
6
+ * `provisionWorktreeSettingsExclude()` (`executor/permissions.ts`) are both
7
+ * read-then-write. Linked worktrees of one repository share ONE common
8
+ * `info/exclude`, so two launches preparing two worktrees at the same moment
9
+ * could each read the file, each append their own line, and the second rename or
10
+ * write would drop the first line. Every Bridge writer therefore takes this lock
11
+ * around its whole read-modify-write and re-reads inside it.
12
+ *
13
+ * The lock is keyed on the CANONICAL exclude pathname (its directory resolved
14
+ * through `realpath`), never the worktree path: two worktrees resolve to the
15
+ * same key exactly when they share an exclude file. The lock file sits beside
16
+ * the exclude file (`exclude.bridge-lock`), created with `open(..., "wx")`, and
17
+ * only its owner removes it. A lock older than {@link STALE_LOCK_MS} is treated
18
+ * as abandoned (a crashed writer) and removed once; the critical section is a
19
+ * few milliseconds, so a live owner never gets near that age.
20
+ *
21
+ * Failure outcomes are fixed text: no path, no errno, no exception message.
22
+ */
23
+ import { mkdir as fsMkdir, open as fsOpen, realpath as fsRealpath, stat as fsStat, unlink as fsUnlink } from "fs/promises";
24
+ import path from "path";
25
+ import { ensureGitInfoExcluded } from "./git-ignore-utils.js";
26
+ /** How long a contended writer waits before giving up. */
27
+ export const EXCLUDE_LOCK_TIMEOUT_MS = 10_000;
28
+ /** Poll interval while waiting. */
29
+ export const EXCLUDE_LOCK_POLL_MS = 25;
30
+ /** A lock file older than this is an abandoned lock from a crashed writer. */
31
+ export const STALE_LOCK_MS = 60_000;
32
+ /** Lock file name beside the exclude file. */
33
+ export const EXCLUDE_LOCK_FILE_NAME = "exclude.bridge-lock";
34
+ export function defaultExcludeLockDeps() {
35
+ return {
36
+ open: (p, flags, mode) => fsOpen(p, flags, mode),
37
+ unlink: (p) => fsUnlink(p),
38
+ mkdir: (p, o) => fsMkdir(p, o),
39
+ realpath: (p) => fsRealpath(p),
40
+ mtimeMs: async (p) => (await fsStat(p)).mtimeMs,
41
+ now: () => Date.now(),
42
+ sleep: (ms) => new Promise((resolve) => setTimeout(resolve, ms)),
43
+ };
44
+ }
45
+ function errnoCode(err) {
46
+ return err && typeof err === "object" ? err.code : undefined;
47
+ }
48
+ /**
49
+ * The lock key: the exclude file's directory resolved through `realpath`, joined
50
+ * with the file name. The directory is created first so it can be resolved.
51
+ */
52
+ export async function canonicalExcludePath(excludePath, deps) {
53
+ const dir = path.dirname(excludePath);
54
+ await deps.mkdir(dir, { recursive: true });
55
+ const realDir = await deps.realpath(dir);
56
+ return path.join(realDir, path.basename(excludePath));
57
+ }
58
+ /** Acquire the lock for one resolved exclude path. */
59
+ export async function acquireExcludeLock(excludePath, deps = defaultExcludeLockDeps()) {
60
+ let lockPath;
61
+ try {
62
+ const canonical = await canonicalExcludePath(excludePath, deps);
63
+ lockPath = path.join(path.dirname(canonical), EXCLUDE_LOCK_FILE_NAME);
64
+ }
65
+ catch {
66
+ return { ok: false, reason: "lock_unavailable" };
67
+ }
68
+ let released = false;
69
+ const release = async () => {
70
+ if (released)
71
+ return;
72
+ released = true;
73
+ try {
74
+ await deps.unlink(lockPath);
75
+ }
76
+ catch {
77
+ /* a lock that is already gone never fails the caller */
78
+ }
79
+ };
80
+ const deadline = deps.now() + (deps.timeoutMs ?? EXCLUDE_LOCK_TIMEOUT_MS);
81
+ let staleChecked = false;
82
+ for (;;) {
83
+ try {
84
+ const handle = await deps.open(lockPath, "wx", 0o600);
85
+ await handle.close();
86
+ return { ok: true, release };
87
+ }
88
+ catch (err) {
89
+ if (errnoCode(err) !== "EEXIST")
90
+ return { ok: false, reason: "lock_unavailable" };
91
+ }
92
+ if (!staleChecked) {
93
+ staleChecked = true;
94
+ try {
95
+ const age = deps.now() - (await deps.mtimeMs(lockPath));
96
+ if (age > STALE_LOCK_MS) {
97
+ await deps.unlink(lockPath);
98
+ continue;
99
+ }
100
+ }
101
+ catch {
102
+ /* vanished or unreadable: retry normally */
103
+ }
104
+ }
105
+ if (deps.now() >= deadline)
106
+ return { ok: false, reason: "lock_timeout" };
107
+ await deps.sleep(EXCLUDE_LOCK_POLL_MS);
108
+ }
109
+ }
110
+ /** Run `fn` while holding the lock for `excludePath`. */
111
+ export async function withExcludeLock(excludePath, fn, deps = defaultExcludeLockDeps()) {
112
+ const lock = await acquireExcludeLock(excludePath, deps);
113
+ if (!lock.ok)
114
+ return lock;
115
+ try {
116
+ return { ok: true, value: await fn() };
117
+ }
118
+ finally {
119
+ await lock.release();
120
+ }
121
+ }
122
+ /**
123
+ * Resolve the exclude path the same way `ensureGitInfoExcluded()` does: through
124
+ * `git rev-parse --git-path info/exclude` when `runCommand` and `platform` are
125
+ * supplied (linked worktrees resolve to the common directory), else the legacy
126
+ * `<root>/.git/info/exclude` join. `git-ignore-utils.ts` keeps its resolver
127
+ * private, so this mirrors it rather than editing that file.
128
+ */
129
+ export async function resolveExcludePathForLock(worktreeRoot, deps) {
130
+ if (deps.runCommand && deps.platform) {
131
+ const api = deps.platform === "win32" ? path.win32 : path.posix;
132
+ const result = await deps.runCommand("git", ["rev-parse", "--git-path", "info/exclude"], { cwd: worktreeRoot });
133
+ if (result.exitCode !== 0 || result.stdout.trim().length === 0) {
134
+ throw new Error("Failed to resolve the worktree info/exclude path.");
135
+ }
136
+ const raw = result.stdout.trim();
137
+ return api.isAbsolute(raw) ? api.normalize(raw) : api.resolve(worktreeRoot, raw);
138
+ }
139
+ return path.join(worktreeRoot, ".git", "info", "exclude");
140
+ }
141
+ /**
142
+ * `ensureGitInfoExcluded()` inside the exclude lock, re-reading the file inside
143
+ * the critical section (the wrapped call reads first). Never throws.
144
+ */
145
+ export async function ensureGitInfoExcludedLocked(worktreeRoot, relativePath, deps, lockDeps = defaultExcludeLockDeps()) {
146
+ let excludePath;
147
+ try {
148
+ excludePath = await resolveExcludePathForLock(worktreeRoot, deps);
149
+ }
150
+ catch {
151
+ return { ok: false, reason: "exclude_failed" };
152
+ }
153
+ try {
154
+ const locked = await withExcludeLock(excludePath, () => ensureGitInfoExcluded(worktreeRoot, relativePath, deps), lockDeps);
155
+ return locked.ok ? { ok: true } : locked;
156
+ }
157
+ catch {
158
+ return { ok: false, reason: "exclude_failed" };
159
+ }
160
+ }
161
+ /**
162
+ * For the pre-existing writers whose contract predates the lock: hold the lock
163
+ * when it can be had, and otherwise fall back to the unlocked write they always
164
+ * did, so a lock problem never changes their established outcome. Errors from
165
+ * the write itself propagate exactly as before.
166
+ */
167
+ export async function ensureGitInfoExcludedSerialized(worktreeRoot, relativePath, deps, lockDeps = defaultExcludeLockDeps()) {
168
+ let excludePath;
169
+ try {
170
+ excludePath = await resolveExcludePathForLock(worktreeRoot, deps);
171
+ }
172
+ catch {
173
+ excludePath = undefined;
174
+ }
175
+ if (excludePath === undefined) {
176
+ await ensureGitInfoExcluded(worktreeRoot, relativePath, deps);
177
+ return;
178
+ }
179
+ const lock = await acquireExcludeLock(excludePath, lockDeps);
180
+ try {
181
+ await ensureGitInfoExcluded(worktreeRoot, relativePath, deps);
182
+ }
183
+ finally {
184
+ if (lock.ok)
185
+ await lock.release();
186
+ }
187
+ }