@bridge_gpt/mcp-server 0.2.72 → 0.2.73

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 (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -0,0 +1,315 @@
1
+ /**
2
+ * Private local state for the `/drive-epic-run` driver guard (BAPI-1642).
3
+ *
4
+ * WHAT LIVES WHERE. Two roots, both under the user's home:
5
+ *
6
+ * ~/.local/state/bapi-conductor-runs/ (BRIDGE_RUN_STATE_DIR)
7
+ * driver-sessions/<session_id>.json the session's registration
8
+ * <KEY>/driver-current.json the run's current generation
9
+ * <KEY>/tally.md the run's tally (append only)
10
+ * <KEY>/blocker-receipt-<TICKET>.json the last declare-blocked receipt
11
+ *
12
+ * ~/.local/state/bapi-conductor-guard/<session_id>/<generation>/
13
+ * cap.json release.json lapse-pending.json lapse-result.json
14
+ * lapse-output.log lapse-transcribed.json lock
15
+ *
16
+ * The second root is outside the run-state `Edit`/`Write` permission rules, so
17
+ * the driving agent is never pre-authorized to reset its own block counter or
18
+ * forge a release. The registration and `driver-current.json` stay at the paths
19
+ * the ticket fixed, under the agent-writable run-state root: editing them can
20
+ * only make the guard see a stale or unreadable registration, which allows the
21
+ * stop (fail-open), never blocks. The guard targets model mistakes, not an
22
+ * adversarial agent. This state is independent of conversation state and of any
23
+ * claim the agent makes, but it is NOT isolated from another process running as
24
+ * the same user: POSIX modes keep other users out, nothing more, and on Windows
25
+ * they are advisory.
26
+ *
27
+ * Every identifier that becomes a path segment is validated first, so a session
28
+ * id, generation, epic key, or ticket key can never form a path. Every JSON
29
+ * write is a private temp file plus rename. Every read is bounded and reports
30
+ * absent, malformed, or failed distinctly, so a corrupt counter is never read as
31
+ * a fresh zero.
32
+ */
33
+ import { randomBytes } from "node:crypto";
34
+ import { appendFile, mkdir, open, readFile, rename, stat, unlink } from "node:fs/promises";
35
+ import os from "node:os";
36
+ import path from "node:path";
37
+ import { BRIDGE_DRIVER_GUARD_STATE_DIR, BRIDGE_RUN_STATE_DIR } from "../bridge-permissions.js";
38
+ // ---------------------------------------------------------------------------
39
+ // Constants and identifier shapes
40
+ // ---------------------------------------------------------------------------
41
+ export const DRIVER_STATE_VERSION = 1;
42
+ /** A Claude Code session id: letters, digits and `-` only, so it never forms a path. */
43
+ export const DRIVER_SESSION_ID_PATTERN = /^[A-Za-z0-9-]{1,128}$/;
44
+ /** A registration generation: 32 lowercase hex characters from a CSPRNG. */
45
+ export const DRIVER_GENERATION_PATTERN = /^[0-9a-f]{32}$/;
46
+ /** An epic or ticket key, the same shape `drive-epic` accepts. */
47
+ export const DRIVER_KEY_PATTERN = /^[A-Z][A-Z0-9_]{0,19}-[0-9]+$/;
48
+ /** A run id or epic key as passed on the command line. */
49
+ export const DRIVER_RUN_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9_-]{0,127}$/;
50
+ /** No state file this module reads may be larger than this. */
51
+ export const DRIVER_STATE_MAX_BYTES = 16 * 1024;
52
+ /** A lock file older than this is a crashed holder's and may be cleared once. */
53
+ export const DRIVER_LOCK_STALE_MS = 10_000;
54
+ /** The three authorized release reasons. */
55
+ export const DRIVER_RELEASE_REASONS = ["owner", "done", "handoff"];
56
+ /** Blocks 1..3 are enforced; the next attempt allows and records a lapse. */
57
+ export const DRIVER_GUARD_BLOCK_CAP = 3;
58
+ function expandHome(dir, homeDir) {
59
+ return dir.startsWith("~/") ? path.join(homeDir, ...dir.slice(2).split("/")) : dir;
60
+ }
61
+ /** Expand both roots against `homeDir` (defaults to the OS home directory). */
62
+ export function resolveDriverStateRoots(homeDir = os.homedir()) {
63
+ return {
64
+ runRoot: expandHome(BRIDGE_RUN_STATE_DIR, homeDir),
65
+ guardRoot: expandHome(BRIDGE_DRIVER_GUARD_STATE_DIR, homeDir),
66
+ };
67
+ }
68
+ function requireSegment(value, pattern) {
69
+ if (!pattern.test(value))
70
+ throw new Error("invalid driver state identifier");
71
+ return value;
72
+ }
73
+ export function registrationPath(roots, sessionId) {
74
+ return path.join(roots.runRoot, "driver-sessions", `${requireSegment(sessionId, DRIVER_SESSION_ID_PATTERN)}.json`);
75
+ }
76
+ export function runDirPath(roots, epicKey) {
77
+ return path.join(roots.runRoot, requireSegment(epicKey, DRIVER_KEY_PATTERN));
78
+ }
79
+ export function currentPointerPath(roots, epicKey) {
80
+ return path.join(runDirPath(roots, epicKey), "driver-current.json");
81
+ }
82
+ export function tallyPath(roots, epicKey) {
83
+ return path.join(runDirPath(roots, epicKey), "tally.md");
84
+ }
85
+ export function blockerReceiptPath(roots, epicKey, ticketKey) {
86
+ return path.join(runDirPath(roots, epicKey), `blocker-receipt-${requireSegment(ticketKey, DRIVER_KEY_PATTERN)}.json`);
87
+ }
88
+ /** The guard-owned directory of one session's one generation. */
89
+ export function generationDirPath(roots, sessionId, generation) {
90
+ return path.join(roots.guardRoot, requireSegment(sessionId, DRIVER_SESSION_ID_PATTERN), requireSegment(generation, DRIVER_GENERATION_PATTERN));
91
+ }
92
+ export function generationFilePath(roots, sessionId, generation, file) {
93
+ return path.join(generationDirPath(roots, sessionId, generation), file);
94
+ }
95
+ export const LAPSE_OUTCOMES = ["escalated", "suppressed_terminal", "failed"];
96
+ /** A closed token safe for a tally line: no spaces, no punctuation beyond `_.:-`. */
97
+ export const DRIVER_CLOSED_TOKEN_PATTERN = /^[A-Za-z0-9_.:-]{1,80}$/;
98
+ /** `delivery_status` values the server can return (the `unknown:` reason is a closed token). */
99
+ export const DRIVER_DELIVERY_STATUS_PATTERN = /^(queued|handed_off|failed|not delivered: local no-op transport|not delivered: recorded locally|unknown: [a-z_]{1,64})$/;
100
+ function isRecord(value) {
101
+ return value !== null && typeof value === "object" && !Array.isArray(value);
102
+ }
103
+ function isIso(value) {
104
+ return typeof value === "string" && value.length <= 40 && !Number.isNaN(Date.parse(value));
105
+ }
106
+ function isToken(value, pattern) {
107
+ return typeof value === "string" && pattern.test(value);
108
+ }
109
+ export function parseRegistration(value) {
110
+ if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
111
+ return null;
112
+ if (!isToken(value.session_id, DRIVER_SESSION_ID_PATTERN) ||
113
+ !isToken(value.epic_run_id, DRIVER_RUN_REF_PATTERN) ||
114
+ !isToken(value.epic_key, DRIVER_KEY_PATTERN) ||
115
+ typeof value.repo_name !== "string" || value.repo_name.length === 0 || value.repo_name.length > 200 ||
116
+ !isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
117
+ typeof value.waiter_command !== "string" || value.waiter_command.length === 0 ||
118
+ value.waiter_command.length > 1000 || !isIso(value.registered_at)) {
119
+ return null;
120
+ }
121
+ return value;
122
+ }
123
+ export function parseCurrentPointer(value) {
124
+ if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
125
+ return null;
126
+ if (!isToken(value.session_id, DRIVER_SESSION_ID_PATTERN) ||
127
+ !isToken(value.generation, DRIVER_GENERATION_PATTERN) || !isIso(value.registered_at)) {
128
+ return null;
129
+ }
130
+ return value;
131
+ }
132
+ export function parseCapState(value) {
133
+ if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
134
+ return null;
135
+ if (!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
136
+ !Number.isSafeInteger(value.blocks) || value.blocks < 0 ||
137
+ value.blocks > DRIVER_GUARD_BLOCK_CAP || typeof value.lapsed !== "boolean") {
138
+ return null;
139
+ }
140
+ return value;
141
+ }
142
+ export function parseReleaseMarker(value) {
143
+ if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
144
+ return null;
145
+ if (!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
146
+ !DRIVER_RELEASE_REASONS.includes(value.reason) || !isIso(value.released_at)) {
147
+ return null;
148
+ }
149
+ return value;
150
+ }
151
+ export function parsePendingLapse(value) {
152
+ if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
153
+ return null;
154
+ if (!isToken(value.session_id, DRIVER_SESSION_ID_PATTERN) ||
155
+ !isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
156
+ !isToken(value.epic_run_id, DRIVER_RUN_REF_PATTERN) ||
157
+ !isToken(value.epic_key, DRIVER_KEY_PATTERN) || !isIso(value.created_at)) {
158
+ return null;
159
+ }
160
+ return value;
161
+ }
162
+ export function parseLapseResult(value) {
163
+ if (!isRecord(value) || value.version !== DRIVER_STATE_VERSION)
164
+ return null;
165
+ if (!isToken(value.generation, DRIVER_GENERATION_PATTERN) ||
166
+ !LAPSE_OUTCOMES.includes(value.outcome) || !isIso(value.finished_at)) {
167
+ return null;
168
+ }
169
+ if (value.ticket_key !== null && !isToken(value.ticket_key, DRIVER_KEY_PATTERN))
170
+ return null;
171
+ if (value.notification_id !== null &&
172
+ (!Number.isSafeInteger(value.notification_id) || value.notification_id <= 0))
173
+ return null;
174
+ if (value.delivery_status !== null && !isToken(value.delivery_status, DRIVER_DELIVERY_STATUS_PATTERN))
175
+ return null;
176
+ if (value.failure_reason !== null && !isToken(value.failure_reason, DRIVER_CLOSED_TOKEN_PATTERN))
177
+ return null;
178
+ return value;
179
+ }
180
+ /**
181
+ * Read one small JSON file. Absent, malformed (bad JSON or over the size cap),
182
+ * and failed (any other I/O error, including an abort) are distinct, so a
183
+ * caller can never mistake a corrupt record for a missing one.
184
+ */
185
+ export async function readDriverJson(filePath, signal) {
186
+ let raw;
187
+ try {
188
+ raw = await readFile(filePath, signal ? { signal } : {});
189
+ }
190
+ catch (error) {
191
+ const code = error?.code;
192
+ return code === "ENOENT" ? { state: "absent" } : { state: "failed" };
193
+ }
194
+ if (raw.length > DRIVER_STATE_MAX_BYTES)
195
+ return { state: "malformed" };
196
+ try {
197
+ return { state: "ok", value: JSON.parse(raw.toString("utf-8")) };
198
+ }
199
+ catch {
200
+ return { state: "malformed" };
201
+ }
202
+ }
203
+ /** Create `dir` (and parents) with mode 0700. */
204
+ export async function ensurePrivateDir(dir) {
205
+ await mkdir(dir, { recursive: true, mode: 0o700 });
206
+ }
207
+ /**
208
+ * Replace `filePath` with `value` atomically: a unique 0600 temp file in the
209
+ * same directory, then a rename. A reader sees the old file or the new one,
210
+ * never a partial write.
211
+ */
212
+ export async function writeDriverJsonAtomic(filePath, value) {
213
+ await ensurePrivateDir(path.dirname(filePath));
214
+ const temp = `${filePath}.${randomBytes(6).toString("hex")}.tmp`;
215
+ try {
216
+ const handle = await open(temp, "wx", 0o600);
217
+ try {
218
+ await handle.writeFile(`${JSON.stringify(value)}\n`, "utf-8");
219
+ }
220
+ finally {
221
+ await handle.close();
222
+ }
223
+ await rename(temp, filePath);
224
+ }
225
+ catch (error) {
226
+ await unlink(temp).catch(() => undefined);
227
+ throw error;
228
+ }
229
+ }
230
+ /**
231
+ * Create `filePath` only if it does not exist (0600). Returns false when it
232
+ * already exists. Used for once-only records such as a pending lapse.
233
+ */
234
+ export async function createDriverJsonExclusive(filePath, value) {
235
+ await ensurePrivateDir(path.dirname(filePath));
236
+ let handle;
237
+ try {
238
+ handle = await open(filePath, "wx", 0o600);
239
+ }
240
+ catch (error) {
241
+ if (error?.code === "EEXIST")
242
+ return false;
243
+ throw error;
244
+ }
245
+ try {
246
+ await handle.writeFile(`${JSON.stringify(value)}\n`, "utf-8");
247
+ }
248
+ finally {
249
+ await handle.close();
250
+ }
251
+ return true;
252
+ }
253
+ // ---------------------------------------------------------------------------
254
+ // The exclusive operation lock
255
+ // ---------------------------------------------------------------------------
256
+ /**
257
+ * Run `fn` while holding `lockPath` exclusively. Never waits: when another
258
+ * holder is live the result is `contended`, and the caller fails open. A lock
259
+ * older than {@link DRIVER_LOCK_STALE_MS} belongs to a crashed holder and is
260
+ * cleared once before one more attempt.
261
+ */
262
+ export async function withDriverLock(lockPath, fn, now = Date.now) {
263
+ await ensurePrivateDir(path.dirname(lockPath));
264
+ for (let attempt = 0; attempt < 2; attempt += 1) {
265
+ let handle;
266
+ try {
267
+ handle = await open(lockPath, "wx", 0o600);
268
+ }
269
+ catch (error) {
270
+ if (error?.code !== "EEXIST")
271
+ throw error;
272
+ if (attempt > 0)
273
+ return { state: "contended" };
274
+ const info = await stat(lockPath).catch(() => null);
275
+ if (!info || now() - info.mtimeMs < DRIVER_LOCK_STALE_MS)
276
+ return { state: "contended" };
277
+ await unlink(lockPath).catch(() => undefined);
278
+ continue;
279
+ }
280
+ await handle.close();
281
+ try {
282
+ return { state: "held", value: await fn() };
283
+ }
284
+ finally {
285
+ await unlink(lockPath).catch(() => undefined);
286
+ }
287
+ }
288
+ return { state: "contended" };
289
+ }
290
+ /**
291
+ * Format one CLI-written tally line: `- <UTC> <kind>: k=v k=v`. Every value
292
+ * must be a closed token or a safe integer; anything else is written as
293
+ * `invalid`, so no free text, message, or secret can reach the line.
294
+ */
295
+ export function formatDriverTallyLine(kind, fields, at) {
296
+ const parts = Object.entries(fields).map(([key, value]) => {
297
+ const safe = typeof value === "number"
298
+ ? (Number.isSafeInteger(value) ? String(value) : "invalid")
299
+ : (DRIVER_CLOSED_TOKEN_PATTERN.test(value) ? value : "invalid");
300
+ return `${key}=${safe}`;
301
+ });
302
+ return `- ${at.toISOString()} ${kind}: ${parts.join(" ")}\n`;
303
+ }
304
+ /**
305
+ * Append one complete line to `<KEY>/tally.md` in a single `appendFile()` call
306
+ * (0600 on create). The run directory is created private when missing.
307
+ */
308
+ export async function appendDriverTallyLine(roots, epicKey, line) {
309
+ await ensurePrivateDir(runDirPath(roots, epicKey));
310
+ await appendFile(tallyPath(roots, epicKey), line.endsWith("\n") ? line : `${line}\n`, { encoding: "utf-8", mode: 0o600 });
311
+ }
312
+ /** A short, non-identifying prefix of a generation for tally lines. */
313
+ export function generationLabel(generation) {
314
+ return generation.slice(0, 8);
315
+ }
@@ -167,14 +167,47 @@ function filterPatterns(node) {
167
167
  }
168
168
  return null;
169
169
  }
170
- function classifyBranches(node) {
170
+ /**
171
+ * BAPI-1654 — classify one pattern against ONE concrete branch name. The answer
172
+ * is `all` (it matches), `none` (it does not), or `some` when the pattern uses a
173
+ * glob form this matcher does not evaluate (`[...]` or `+`), which keeps the
174
+ * filter uncertain rather than guessed.
175
+ */
176
+ export function classifyBranchPatternForTarget(pattern, branch) {
177
+ if (pattern.includes("[") || pattern.includes("+"))
178
+ return "some";
179
+ let re = "^";
180
+ for (let i = 0; i < pattern.length; i++) {
181
+ const ch = pattern[i];
182
+ if (ch === "*" && pattern[i + 1] === "*") {
183
+ re += ".*";
184
+ i++;
185
+ }
186
+ else if (ch === "*") {
187
+ re += "[^/]*";
188
+ }
189
+ else if (ch === "?") {
190
+ re += "[^/]";
191
+ }
192
+ else {
193
+ re += ch.replace(/[\\^$.|(){}]/g, "\\$&");
194
+ }
195
+ }
196
+ return new RegExp(`${re}$`).test(branch) ? "all" : "none";
197
+ }
198
+ function classifierFor(targetBranch) {
199
+ return targetBranch === undefined
200
+ ? classifyEpicBranchPattern
201
+ : (pattern) => classifyBranchPatternForTarget(pattern, targetBranch);
202
+ }
203
+ function classifyBranches(node, classify) {
171
204
  const patterns = filterPatterns(node);
172
205
  if (patterns === null || patterns.length === 0)
173
206
  return couldNotTell("branch_filter_uncertain");
174
207
  let state = "none_in";
175
208
  for (const raw of patterns) {
176
209
  const negated = raw.startsWith("!");
177
- const match = classifyEpicBranchPattern(negated ? raw.slice(1) : raw);
210
+ const match = classify(negated ? raw.slice(1) : raw);
178
211
  if (match === "none")
179
212
  continue;
180
213
  if (!negated) {
@@ -196,21 +229,21 @@ function classifyBranches(node) {
196
229
  return EXCLUDES;
197
230
  return couldNotTell("branch_filter_uncertain");
198
231
  }
199
- function classifyBranchesIgnore(node) {
232
+ function classifyBranchesIgnore(node, classify) {
200
233
  if (node !== undefined && node.t === "seq" && node.items.length === 0)
201
234
  return COVERS;
202
235
  const patterns = filterPatterns(node);
203
236
  if (patterns === null || patterns.some((p) => p.startsWith("!"))) {
204
237
  return couldNotTell("branch_filter_uncertain");
205
238
  }
206
- const matches = patterns.map(classifyEpicBranchPattern);
239
+ const matches = patterns.map((p) => classify(p));
207
240
  if (matches.includes("all"))
208
241
  return EXCLUDES;
209
242
  if (matches.every((m) => m === "none"))
210
243
  return COVERS;
211
244
  return couldNotTell("branch_filter_uncertain");
212
245
  }
213
- function classifyPrEvent(node) {
246
+ function classifyPrEvent(node, classify) {
214
247
  if (node.t === "null")
215
248
  return COVERS;
216
249
  if (node.t !== "map")
@@ -235,9 +268,9 @@ function classifyPrEvent(node) {
235
268
  if (hasBranches && hasIgnore)
236
269
  return couldNotTell("branch_filter_uncertain");
237
270
  if (hasBranches)
238
- return classifyBranches(e.get("s:branches"));
271
+ return classifyBranches(e.get("s:branches"), classify);
239
272
  if (hasIgnore)
240
- return classifyBranchesIgnore(e.get("s:branches-ignore"));
273
+ return classifyBranchesIgnore(e.get("s:branches-ignore"), classify);
241
274
  return COVERS;
242
275
  }
243
276
  // ---------------------------------------------------------------------------
@@ -741,7 +774,7 @@ function jobsHaveUses(entries) {
741
774
  }
742
775
  return false;
743
776
  }
744
- function classifyOrThrow(text) {
777
+ function classifyOrThrow(text, classify) {
745
778
  if (typeof text !== "string" || text.trim() === "")
746
779
  return couldNotTell("unparseable");
747
780
  const root = scanRoot(text);
@@ -776,7 +809,7 @@ function classifyOrThrow(text) {
776
809
  }
777
810
  else if (node.t === "map") {
778
811
  triggerNames = [...node.entries.keys()].filter((k) => k.startsWith("s:")).map((k) => k.slice(2));
779
- prResults = PR_TRIGGER_KEYS.filter((k) => node.entries.has(`s:${k}`)).map((k) => classifyPrEvent(node.entries.get(`s:${k}`)));
812
+ prResults = PR_TRIGGER_KEYS.filter((k) => node.entries.has(`s:${k}`)).map((k) => classifyPrEvent(node.entries.get(`s:${k}`), classify));
780
813
  if (prResults.some((r) => r.coverage === "covers"))
781
814
  return COVERS;
782
815
  const uncertain = prResults.find((r) => r.coverage === "could_not_tell");
@@ -794,16 +827,91 @@ function classifyOrThrow(text) {
794
827
  }
795
828
  /**
796
829
  * Does this workflow's PR trigger run for a pull request whose base is
797
- * `epic/<EPIC>`? Never throws; see the module truth table.
830
+ * `epic/<EPIC>` (or, with `options.targetBranch`, that branch)? Never throws;
831
+ * see the module truth table.
798
832
  */
799
- export function classifyEpicPullRequestTrigger(text) {
833
+ export function classifyEpicPullRequestTrigger(text, options = {}) {
800
834
  try {
801
- return classifyOrThrow(text);
835
+ return classifyOrThrow(text, classifierFor(options.targetBranch));
802
836
  }
803
837
  catch (err) {
804
838
  return couldNotTell(err instanceof UnsupportedYaml ? "unsupported_structure" : "unparseable");
805
839
  }
806
840
  }
841
+ /**
842
+ * BAPI-1654 — the trigger's event names, as the same scanner reads them, or
843
+ * `null` when the trigger cannot be read. Used to prove an edit kept every
844
+ * existing trigger. Never returns other workflow content.
845
+ */
846
+ export function readWorkflowTriggerNames(text) {
847
+ try {
848
+ if (typeof text !== "string" || text.trim() === "")
849
+ return null;
850
+ const root = scanRoot(text);
851
+ if (root.kind !== "ok")
852
+ return null;
853
+ const trigger = findTrigger(root.entries);
854
+ if (trigger === null)
855
+ return null;
856
+ const node = parseEntryValue(trigger);
857
+ if (node.t === "str")
858
+ return [node.v];
859
+ if (node.t === "seq")
860
+ return node.items.every((i) => i.t === "str") ? node.items.map((i) => i.v) : null;
861
+ if (node.t === "map")
862
+ return [...node.entries.keys()].map((k) => (k.startsWith("s:") ? k.slice(2) : k));
863
+ return null;
864
+ }
865
+ catch {
866
+ return null;
867
+ }
868
+ }
869
+ export function readPullRequestBranchFilters(text) {
870
+ try {
871
+ if (typeof text !== "string" || text.trim() === "")
872
+ return { kind: "could_not_tell" };
873
+ const root = scanRoot(text);
874
+ if (root.kind !== "ok")
875
+ return { kind: "could_not_tell" };
876
+ const trigger = findTrigger(root.entries);
877
+ if (trigger === null)
878
+ return { kind: "could_not_tell" };
879
+ const node = parseEntryValue(trigger);
880
+ const isPr = (name) => PR_TRIGGER_KEYS.includes(name);
881
+ if (node.t === "str")
882
+ return isPr(node.v) ? { kind: "filters", branches: null } : { kind: "no_pr_trigger" };
883
+ if (node.t === "seq") {
884
+ return node.items.some((i) => i.t === "str" && isPr(i.v))
885
+ ? { kind: "filters", branches: null }
886
+ : { kind: "no_pr_trigger" };
887
+ }
888
+ if (node.t !== "map")
889
+ return { kind: "could_not_tell" };
890
+ const prKey = PR_TRIGGER_KEYS.find((k) => node.entries.has(`s:${k}`));
891
+ if (prKey === undefined)
892
+ return { kind: "no_pr_trigger" };
893
+ const event = node.entries.get(`s:${prKey}`);
894
+ if (event.t === "null")
895
+ return { kind: "filters", branches: null };
896
+ if (event.t !== "map")
897
+ return { kind: "could_not_tell" };
898
+ // A `branches-ignore` list is not "every branch": report it as unread rather than misstate it.
899
+ if (event.entries.has("s:branches-ignore"))
900
+ return { kind: "could_not_tell" };
901
+ const branches = event.entries.get("s:branches");
902
+ if (branches === undefined)
903
+ return { kind: "filters", branches: null };
904
+ if (branches.t === "str")
905
+ return { kind: "filters", branches: [branches.v] };
906
+ if (branches.t === "seq" && branches.items.every((i) => i.t === "str")) {
907
+ return { kind: "filters", branches: branches.items.map((i) => i.v) };
908
+ }
909
+ return { kind: "could_not_tell" };
910
+ }
911
+ catch {
912
+ return { kind: "could_not_tell" };
913
+ }
914
+ }
807
915
  // ---------------------------------------------------------------------------
808
916
  // Repository aggregate
809
917
  // ---------------------------------------------------------------------------
@@ -876,42 +984,55 @@ export async function inspectEpicBranchWorkflowCoverage(fs, budget = {}) {
876
984
  return { coverage: "does_not_cover", reason: "no_workflows", workflows: [] };
877
985
  const started = now();
878
986
  const workflows = [];
987
+ const targetResults = [];
988
+ const target = budget.targetBranch;
879
989
  for (const file of files) {
880
990
  const path = `${WORKFLOWS_DIR}/${file}`;
881
991
  const remaining = overall - (now() - started);
882
992
  if (remaining <= 0) {
883
993
  workflows.push({ path, coverage: "could_not_tell", reason: "read_failed" });
994
+ targetResults.push({ path, coverage: "could_not_tell", reason: "read_failed" });
884
995
  continue;
885
996
  }
886
997
  const text = await readWithTimeout(fs, path, Math.min(perRead, remaining));
887
998
  if (text === null) {
888
999
  workflows.push({ path, coverage: "could_not_tell", reason: "read_failed" });
1000
+ targetResults.push({ path, coverage: "could_not_tell", reason: "read_failed" });
889
1001
  continue;
890
1002
  }
891
1003
  workflows.push({ path, ...classifyEpicPullRequestTrigger(text) });
1004
+ if (target !== undefined)
1005
+ targetResults.push({ path, ...classifyEpicPullRequestTrigger(text, { targetBranch: target }) });
892
1006
  }
893
- if (workflows.some((w) => w.coverage === "covers")) {
894
- return { coverage: "covers", reason: "pr_trigger_covers", workflows };
895
- }
896
- if (truncated)
897
- return { coverage: "could_not_tell", reason: "file_limit_reached", workflows };
898
- if (workflows.some((w) => w.reason === "read_failed")) {
899
- return { coverage: "could_not_tell", reason: "read_failed", workflows };
900
- }
901
- const unresolved = workflows.find((w) => w.coverage === "could_not_tell");
902
- if (unresolved)
903
- return { coverage: "could_not_tell", reason: unresolved.reason, workflows };
904
- const excluded = workflows.some((w) => w.reason === "branch_filter_excludes_epic");
905
- return {
906
- coverage: "does_not_cover",
907
- reason: excluded ? "branch_filter_excludes_epic" : "no_pr_trigger",
908
- workflows,
909
- };
1007
+ const aggregate = aggregateCoverage(workflows, truncated);
1008
+ return target === undefined
1009
+ ? aggregate
1010
+ : { ...aggregate, integrationTarget: { branch: target, coverage: aggregateCoverage(targetResults, truncated).coverage } };
910
1011
  }
911
1012
  catch {
912
1013
  return { coverage: "could_not_tell", reason: "listing_failed", workflows: [] };
913
1014
  }
914
1015
  }
1016
+ /** The repository aggregate over per-workflow results; see the module documentation. */
1017
+ function aggregateCoverage(workflows, truncated) {
1018
+ if (workflows.some((w) => w.coverage === "covers")) {
1019
+ return { coverage: "covers", reason: "pr_trigger_covers", workflows };
1020
+ }
1021
+ if (truncated)
1022
+ return { coverage: "could_not_tell", reason: "file_limit_reached", workflows };
1023
+ if (workflows.some((w) => w.reason === "read_failed")) {
1024
+ return { coverage: "could_not_tell", reason: "read_failed", workflows };
1025
+ }
1026
+ const unresolved = workflows.find((w) => w.coverage === "could_not_tell");
1027
+ if (unresolved)
1028
+ return { coverage: "could_not_tell", reason: unresolved.reason, workflows };
1029
+ const excluded = workflows.some((w) => w.reason === "branch_filter_excludes_epic");
1030
+ return {
1031
+ coverage: "does_not_cover",
1032
+ reason: excluded ? "branch_filter_excludes_epic" : "no_pr_trigger",
1033
+ workflows,
1034
+ };
1035
+ }
915
1036
  /** Closed reason tokens returned by the `gh` functions. */
916
1037
  export const EPIC_BRANCH_RULES_REASONS = [
917
1038
  "invalid_input",
@@ -1097,6 +1218,78 @@ export async function readDefaultBranchClassicContextViaGh(run, ownerRepo) {
1097
1218
  return NO_DEFAULT_CONTEXT;
1098
1219
  }
1099
1220
  }
1221
+ /**
1222
+ * Read the effective required status checks on the default branch, from BOTH
1223
+ * sources GitHub enforces: repository rulesets (`rules/branches/<branch>`) and
1224
+ * classic branch protection. GET-only and bounded; it authorizes no rule change and
1225
+ * returns no response text. Any call that gives no reliable answer is `unknown`, so
1226
+ * a caller can warn on a confirmed requirement and stay silent on an uncertain one.
1227
+ * Never throws.
1228
+ */
1229
+ export async function readDefaultBranchRequiredChecksViaGh(run, ownerRepo, knownDefaultBranch) {
1230
+ try {
1231
+ if (!validOwnerRepo(ownerRepo))
1232
+ return { status: "unknown", reason: "invalid_input" };
1233
+ let defaultBranch = knownDefaultBranch;
1234
+ if (defaultBranch === undefined) {
1235
+ const repo = await ghApiJson(run, [`repos/${ownerRepo}`]);
1236
+ if (!repo.ok)
1237
+ return { status: "unknown", reason: repo.reason };
1238
+ if (!isRecord(repo.json) || typeof repo.json.default_branch !== "string") {
1239
+ return { status: "unknown", reason: "unparseable_response" };
1240
+ }
1241
+ defaultBranch = repo.json.default_branch;
1242
+ }
1243
+ if (!validBranch(defaultBranch))
1244
+ return { status: "unknown", reason: "invalid_input" };
1245
+ const rules = await readBranchRules(run, ownerRepo, defaultBranch);
1246
+ if (!rules.ok)
1247
+ return { status: "unknown", reason: rules.reason };
1248
+ const checks = new Set(rules.rules.statusChecks);
1249
+ const protection = await ghApiJson(run, [
1250
+ `repos/${ownerRepo}/branches/${encodeBranchPath(defaultBranch)}/protection`,
1251
+ ]);
1252
+ if (protection.ok) {
1253
+ if (!isRecord(protection.json))
1254
+ return { status: "unknown", reason: "unparseable_response" };
1255
+ const required = protection.json.required_status_checks;
1256
+ if (required !== undefined && required !== null) {
1257
+ if (!isRecord(required))
1258
+ return { status: "unknown", reason: "malformed_rule" };
1259
+ const contexts = required.contexts;
1260
+ if (contexts !== undefined) {
1261
+ if (!Array.isArray(contexts) || contexts.some((c) => typeof c !== "string")) {
1262
+ return { status: "unknown", reason: "malformed_rule" };
1263
+ }
1264
+ for (const c of contexts)
1265
+ checks.add(c);
1266
+ }
1267
+ const entries = required.checks;
1268
+ if (entries !== undefined) {
1269
+ if (!Array.isArray(entries) || entries.some((c) => !isRecord(c) || typeof c.context !== "string")) {
1270
+ return { status: "unknown", reason: "malformed_rule" };
1271
+ }
1272
+ for (const c of entries)
1273
+ checks.add(c.context);
1274
+ }
1275
+ }
1276
+ }
1277
+ else if (protection.reason === "not_found") {
1278
+ // A 404 can mean "no classic protection" or "cannot see it": only a branch
1279
+ // proven visible makes it the former.
1280
+ if ((await branchExists(run, ownerRepo, defaultBranch)) !== true) {
1281
+ return { status: "unknown", reason: "not_found" };
1282
+ }
1283
+ }
1284
+ else {
1285
+ return { status: "unknown", reason: protection.reason };
1286
+ }
1287
+ return { status: "known", defaultBranch, requiredChecks: [...checks].sort(byCodeUnit) };
1288
+ }
1289
+ catch {
1290
+ return { status: "unknown", reason: "gh_failed" };
1291
+ }
1292
+ }
1100
1293
  function withDefaultContext(f, c) {
1101
1294
  return {
1102
1295
  ...f,