@bridge_gpt/mcp-server 0.2.72 → 0.2.74

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 (181) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +15 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +30 -0
  6. package/build/ci-system-detection.js +50 -0
  7. package/build/ci-trigger-adapters.js +631 -0
  8. package/build/ci-trigger-install.js +106 -0
  9. package/build/codex-launcher-pin.js +33 -2
  10. package/build/codex-skill-adapter.js +3 -1
  11. package/build/command-host.js +33 -0
  12. package/build/command-provisioning.js +4 -3
  13. package/build/commands.generated.js +7 -6
  14. package/build/conductor/bridge-api-client.js +867 -35
  15. package/build/conductor/bring-up-facts.js +18 -5
  16. package/build/conductor/command-drift-production.js +42 -17
  17. package/build/conductor/command-drift.js +48 -1
  18. package/build/conductor/declare-blocked.js +554 -0
  19. package/build/conductor/declared-extras.js +335 -0
  20. package/build/conductor/doctor.js +108 -21
  21. package/build/conductor/driver-commands.js +141 -0
  22. package/build/conductor/driver-guard.js +277 -0
  23. package/build/conductor/driver-lapse.js +321 -0
  24. package/build/conductor/driver-pass-output.js +104 -0
  25. package/build/conductor/driver-pass.js +571 -0
  26. package/build/conductor/driver-register.js +176 -0
  27. package/build/conductor/driver-release.js +174 -0
  28. package/build/conductor/driver-session-state.js +315 -0
  29. package/build/conductor/epic-branch-ci-inspection.js +281 -43
  30. package/build/conductor/epic-implementer-cli.js +199 -15
  31. package/build/conductor/epic-server-database.js +162 -0
  32. package/build/conductor/epic-server-guidance.js +278 -0
  33. package/build/conductor/epic-server-journal.js +239 -0
  34. package/build/conductor/epic-server-processes.js +324 -0
  35. package/build/conductor/epic-server-recipe.js +397 -0
  36. package/build/conductor/epic-server-runtime.js +1207 -0
  37. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  38. package/build/conductor/epic-server-sfcc.js +85 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +647 -0
  41. package/build/conductor/gate-discovery.js +196 -11
  42. package/build/conductor/gate-settings-review.js +261 -4
  43. package/build/conductor/launch-need-probes.js +6 -53
  44. package/build/conductor/launch-plan.js +313 -156
  45. package/build/conductor/prerequisite-inputs.js +879 -45
  46. package/build/conductor/readiness-assessment.js +16 -1
  47. package/build/conductor/readiness-cli.js +20 -9
  48. package/build/conductor/readiness-prerequisites.js +28 -9
  49. package/build/conductor/readiness-sections.js +133 -126
  50. package/build/conductor/readiness.js +1 -1
  51. package/build/conductor/recovery-cli.js +13 -2
  52. package/build/conductor/tools.js +6 -5
  53. package/build/conductor/wait-run-attention.js +2 -2
  54. package/build/conductor/wait-run-cli.js +208 -22
  55. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  56. package/build/conductor/worker-setup-tally.js +27 -0
  57. package/build/credential-delivery.js +280 -0
  58. package/build/credential-launch-safety.js +142 -0
  59. package/build/credential-materialization.js +91 -16
  60. package/build/credential-references-node-deps.js +29 -0
  61. package/build/credential-references.js +1394 -0
  62. package/build/credential-references.test-fixtures.js +211 -0
  63. package/build/credential-scan-conventions.js +145 -0
  64. package/build/credential-scan.js +517 -0
  65. package/build/credential-store.js +121 -1
  66. package/build/credentials-cli.js +252 -3
  67. package/build/dependency-install-declarations.js +102 -1
  68. package/build/docs.generated.js +10 -3
  69. package/build/doctor.js +95 -3
  70. package/build/drive-epic-help.js +21 -2
  71. package/build/drive-epic.js +2095 -375
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +157 -0
  74. package/build/epic-capability-statement.js +175 -0
  75. package/build/epic-ci-workflow-drift.js +77 -23
  76. package/build/epic-ci-workflow-install.js +137 -44
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow-v3.js +273 -0
  79. package/build/epic-ci-workflow.js +165 -18
  80. package/build/epic-implementer-bin.js +2204 -56
  81. package/build/epic-launch-context.js +702 -0
  82. package/build/epic-server-record.js +288 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/completion-contract.js +8 -1
  87. package/build/executor/credential-delivery-step.js +168 -0
  88. package/build/executor/deps.js +3 -1
  89. package/build/executor/env.js +98 -23
  90. package/build/executor/epic-server-context.js +157 -0
  91. package/build/executor/gate-qualification-job.js +127 -26
  92. package/build/executor/guarded-fast-forward-push.js +13 -8
  93. package/build/executor/http-client.js +52 -5
  94. package/build/executor/job-runner.js +577 -81
  95. package/build/executor/observation.js +8 -0
  96. package/build/executor/permissions.js +85 -3
  97. package/build/executor/pre-pr-checks.js +363 -0
  98. package/build/executor/prompt-spec.js +149 -3
  99. package/build/executor/reconcile-overlap-job.js +5 -3
  100. package/build/executor/required-work-diagnostics.js +4 -2
  101. package/build/executor/required-work-ledger.js +936 -38
  102. package/build/executor/results.js +58 -0
  103. package/build/executor/terminal-mutation.js +8 -0
  104. package/build/executor/worker-command.js +72 -3
  105. package/build/executor/worker-database-config.js +281 -0
  106. package/build/executor/worker-database-target.js +16 -12
  107. package/build/executor/worker-database.js +320 -101
  108. package/build/executor/worker-finalization.js +7 -1
  109. package/build/executor/worker-resources.js +25 -3
  110. package/build/executor/worker-verification-guidance.js +18 -3
  111. package/build/executor/worktree.js +20 -1
  112. package/build/executor-launch.js +58 -4
  113. package/build/generated-assets-catalog.js +2 -2
  114. package/build/git-exclude-lock.js +187 -0
  115. package/build/index.js +824 -366
  116. package/build/init.js +26 -11
  117. package/build/install-bridge-conductor-answers.js +528 -0
  118. package/build/install-bridge-conductor-apply.js +288 -0
  119. package/build/install-bridge-conductor-assessment.js +1222 -0
  120. package/build/install-bridge-conductor-compact.js +186 -0
  121. package/build/install-bridge-conductor-contracts.js +72 -0
  122. package/build/install-bridge-conductor-gate.js +1312 -198
  123. package/build/install-bridge-conductor-setup.js +577 -83
  124. package/build/install-bridge-conductor.js +3381 -544
  125. package/build/install-bridge.js +280 -25
  126. package/build/install-doctor.js +38 -8
  127. package/build/install-maintenance.js +26 -3
  128. package/build/install-sfcc-detection.js +120 -0
  129. package/build/install-sfcc-setup.js +185 -0
  130. package/build/launcher-config-inspection.js +162 -1
  131. package/build/mcp-grant-candidates.js +779 -0
  132. package/build/mcp-grant-doctor.js +63 -0
  133. package/build/mcp-grant.js +288 -0
  134. package/build/mcp-host-targets.js +8 -0
  135. package/build/mcp-identity.js +23 -0
  136. package/build/mcp-invoke.js +292 -15
  137. package/build/mcp-presets.js +107 -0
  138. package/build/mcp-provisioning.js +155 -6
  139. package/build/mcp-registration-doctor.js +31 -2
  140. package/build/mcp-server-invocation.js +19 -1
  141. package/build/merge-workflow-install.js +243 -110
  142. package/build/pipelines.generated.js +7 -6
  143. package/build/plan-discovery.js +97 -4
  144. package/build/plan-execution-ledger.js +100 -7
  145. package/build/plan-generation-io.js +262 -0
  146. package/build/plan-generation.js +424 -0
  147. package/build/plane/build-freshness.js +6 -1
  148. package/build/plane/cli.js +75 -9
  149. package/build/plane/plane-freshness.js +17 -0
  150. package/build/plane/preflight.js +50 -10
  151. package/build/plane/shutdown.js +19 -0
  152. package/build/plane/status.js +8 -2
  153. package/build/plane/terminal-run-cleanup.js +18 -4
  154. package/build/printed-remedy-commands.js +211 -12
  155. package/build/project-root.js +40 -0
  156. package/build/readiness-check.js +77 -0
  157. package/build/readiness-prerequisites.generated.js +122 -14
  158. package/build/readme.generated.js +1 -1
  159. package/build/repository-state-paths.js +41 -0
  160. package/build/repository-toolchains.js +6 -3
  161. package/build/run-unit-tests-launcher.js +8 -1
  162. package/build/setup-epic.js +1305 -210
  163. package/build/setup-progress.js +44 -0
  164. package/build/setup-question.js +122 -4
  165. package/build/sfcc/credentials.js +3 -2
  166. package/build/sfcc/hostname.js +98 -2
  167. package/build/sfcc/tool-wrapper.js +6 -95
  168. package/build/start-tickets.js +193 -29
  169. package/build/test-support/executor-source-files.js +200 -0
  170. package/build/testing-config-client.js +25 -2
  171. package/build/third-party-mcp-targets.js +63 -2
  172. package/build/ticket-delivery-enrollment.js +9 -0
  173. package/build/upgrade-cli.js +85 -2
  174. package/build/v2-readiness-requirements.js +28 -1
  175. package/build/version.generated.js +3 -3
  176. package/build/with-credentials.js +208 -0
  177. package/build/worktree-credential-delivery.js +340 -0
  178. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  179. package/docs/epic-implementer/getting-started.md +3 -1
  180. package/docs/epic-implementer/self-hosting.md +14 -1
  181. package/package.json +2 -2
@@ -0,0 +1,334 @@
1
+ /**
2
+ * BAPI-1582 — bounded, resume-safe `ci_fix` test-run evidence (executor side).
3
+ *
4
+ * Mirrors `src/python/epic_implementer/ci_fix_test_runs.py`: the same logical
5
+ * identity, closed vocabulary, and bounds. Keep the two in step.
6
+ *
7
+ * The worker records its runs in `<worktree>/.conductor/ci-fix-test-runs.json`.
8
+ * Before spawn the executor seeds that file with the dispatched logical job and
9
+ * any valid prior runs the server restored (`ci_fix_prior_test_runs`). After
10
+ * exit it reads the file back and forwards a valid record as the optional
11
+ * `ci_fix_test_runs` result field. Everything here is telemetry and fail-open:
12
+ * a missing, malformed, oversized, unsafe, or other-job record means "no prior
13
+ * runs", never a failed job.
14
+ */
15
+ import path from "node:path";
16
+ import { constants } from "node:fs";
17
+ import { lstat, mkdir, open, readFile, rename, unlink } from "node:fs/promises";
18
+ import { randomUUID } from "node:crypto";
19
+ export const CI_FIX_TEST_RUNS_PATH = ".conductor/ci-fix-test-runs.json";
20
+ export const CI_FIX_TEST_RUNS_RESULT_KEY = "ci_fix_test_runs";
21
+ export const CI_FIX_PRIOR_TEST_RUNS_PAYLOAD_KEY = "ci_fix_prior_test_runs";
22
+ export const CI_FIX_LOGICAL_JOB_PAYLOAD_KEY = "ci_fix_logical_job";
23
+ export const CI_FIX_TEST_RUNS_VERSION = 1;
24
+ export const CI_FIX_TEST_RUNS_MAX_RUNS = 128;
25
+ export const CI_FIX_TEST_RUNS_MAX_SUITES = 64;
26
+ export const CI_FIX_TEST_RUNS_SUITE_MAX_CHARS = 500;
27
+ export const CI_FIX_LOGICAL_JOB_MAX_CHECKS = 32;
28
+ export const CI_FIX_LOGICAL_JOB_CHECK_MAX_BYTES = 200;
29
+ /** Serialized sub-budget, well below `RESULT_JSONB_MAX_BYTES` (64 000). */
30
+ export const CI_FIX_TEST_RUNS_MAX_BYTES = 24_000;
31
+ const SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
32
+ // C0/C1 controls and U+FEFF, rejected BEFORE trimming: JavaScript's `trim` and
33
+ // Python's `strip` disagree on exactly these, so neither side may strip them.
34
+ // eslint-disable-next-line no-control-regex
35
+ const CONTROL_RE = /[\x00-\x1f\x7f-\x9f\ufeff]/;
36
+ const KINDS = new Set(["targeted", "broad"]);
37
+ const OUTCOMES = new Set(["passed", "failed", "timed_out"]);
38
+ function isRecord(value) {
39
+ return value !== null && typeof value === "object" && !Array.isArray(value);
40
+ }
41
+ function isSha(value) {
42
+ return typeof value === "string" && SHA_RE.test(value);
43
+ }
44
+ /** Code-point order, matching Python's `sorted` over `str`. */
45
+ function compareCodePoints(a, b) {
46
+ const left = Array.from(a);
47
+ const right = Array.from(b);
48
+ for (let i = 0; i < Math.min(left.length, right.length); i++) {
49
+ const diff = left[i].codePointAt(0) - right[i].codePointAt(0);
50
+ if (diff !== 0)
51
+ return diff;
52
+ }
53
+ return left.length - right.length;
54
+ }
55
+ /** Distinct check names, stripped and sorted (the server's `_canonical_checks` rule). */
56
+ export function canonicalCheckSet(checks) {
57
+ const names = new Set();
58
+ for (const check of checks) {
59
+ if (typeof check === "string" && check.trim())
60
+ names.add(check.trim());
61
+ }
62
+ return [...names].sort(compareCodePoints);
63
+ }
64
+ /** The canonical logical job, or `undefined` when it cannot be established. */
65
+ export function ciFixLogicalJob(failingHeadSha, checks) {
66
+ if (!isSha(failingHeadSha) || !Array.isArray(checks))
67
+ return undefined;
68
+ if (checks.some((check) => typeof check !== "string" || CONTROL_RE.test(check)))
69
+ return undefined;
70
+ const canonical = canonicalCheckSet(checks);
71
+ if (canonical.length === 0 || canonical.length > CI_FIX_LOGICAL_JOB_MAX_CHECKS)
72
+ return undefined;
73
+ for (const name of canonical) {
74
+ if (Buffer.byteLength(name, "utf8") > CI_FIX_LOGICAL_JOB_CHECK_MAX_BYTES)
75
+ return undefined;
76
+ }
77
+ return { failing_head_sha: failingHeadSha, checks: canonical };
78
+ }
79
+ export function sameLogicalJob(a, b) {
80
+ return (a.failing_head_sha === b.failing_head_sha &&
81
+ a.checks.length === b.checks.length &&
82
+ a.checks.every((name, index) => name === b.checks[index]));
83
+ }
84
+ /**
85
+ * The logical job this `ci_fix` dispatch repairs. A continuation carries the
86
+ * server's `ci_fix_logical_job` (the original anchor and ORIGINAL check set);
87
+ * it is used when it names the same anchor. Otherwise the job is the anchor
88
+ * (`failing_head_sha`, else the bound head) plus the dispatched set.
89
+ */
90
+ export function dispatchedLogicalJob(payload, ciFix) {
91
+ const anchor = ciFix.failingHeadSha ?? ciFix.headSha;
92
+ if (isRecord(payload) && Object.prototype.hasOwnProperty.call(payload, CI_FIX_LOGICAL_JOB_PAYLOAD_KEY)) {
93
+ const stamped = payload[CI_FIX_LOGICAL_JOB_PAYLOAD_KEY];
94
+ if (isRecord(stamped) && stamped.failing_head_sha === anchor) {
95
+ const job = ciFixLogicalJob(anchor, stamped.checks);
96
+ if (job)
97
+ return job;
98
+ }
99
+ }
100
+ return ciFixLogicalJob(anchor, ciFix.requiredClaimChecks);
101
+ }
102
+ function parseRun(value) {
103
+ if (!isRecord(value))
104
+ return undefined;
105
+ const { suite, kind, head_sha: headSha, outcome } = value;
106
+ if (typeof suite !== "string" ||
107
+ CONTROL_RE.test(suite) ||
108
+ !suite.trim()) {
109
+ return undefined;
110
+ }
111
+ if (typeof kind !== "string" || !KINDS.has(kind))
112
+ return undefined;
113
+ if (typeof outcome !== "string" || !OUTCOMES.has(outcome))
114
+ return undefined;
115
+ if (!isSha(headSha))
116
+ return undefined;
117
+ return { suite, kind: kind, head_sha: headSha, outcome: outcome };
118
+ }
119
+ export function serializedSize(value) {
120
+ return Buffer.byteLength(JSON.stringify(value), "utf8");
121
+ }
122
+ /** Python measures `len(suite)` in code points; mirror that, not UTF-16 units. */
123
+ function withinSuiteBound(runs) {
124
+ return runs.every((run) => Array.from(run.suite).length <= CI_FIX_TEST_RUNS_SUITE_MAX_CHARS);
125
+ }
126
+ function bounded(evidence) {
127
+ return (evidence.runs.length <= CI_FIX_TEST_RUNS_MAX_RUNS &&
128
+ new Set(evidence.runs.map((run) => run.suite)).size <= CI_FIX_TEST_RUNS_MAX_SUITES &&
129
+ serializedSize(evidence) <= CI_FIX_TEST_RUNS_MAX_BYTES);
130
+ }
131
+ /**
132
+ * Normalize one version-1 record, or return `undefined`. Never throws. Only
133
+ * declared fields are kept; any invalid part makes the whole record absent.
134
+ */
135
+ export function parseCiFixTestRuns(value, expected) {
136
+ try {
137
+ if (!isRecord(value))
138
+ return undefined;
139
+ if (value.version !== CI_FIX_TEST_RUNS_VERSION)
140
+ return undefined;
141
+ const logical = value.logical_job;
142
+ if (!isRecord(logical))
143
+ return undefined;
144
+ const job = ciFixLogicalJob(logical.failing_head_sha, logical.checks);
145
+ if (!job || (expected && !sameLogicalJob(job, expected)))
146
+ return undefined;
147
+ const runsValue = value.runs;
148
+ if (!Array.isArray(runsValue) || runsValue.length > CI_FIX_TEST_RUNS_MAX_RUNS)
149
+ return undefined;
150
+ const runs = [];
151
+ for (const item of runsValue) {
152
+ const run = parseRun(item);
153
+ if (!run)
154
+ return undefined;
155
+ runs.push(run);
156
+ }
157
+ if (!withinSuiteBound(runs))
158
+ return undefined;
159
+ const evidence = { version: 1, logical_job: job, runs };
160
+ return bounded(evidence) ? evidence : undefined;
161
+ }
162
+ catch {
163
+ return undefined;
164
+ }
165
+ }
166
+ function runKey(run) {
167
+ return JSON.stringify([run.suite, run.kind, run.head_sha, run.outcome]);
168
+ }
169
+ /**
170
+ * Merge two records of the SAME logical job conservatively. Exact duplicate
171
+ * observations collapse; distinct ones are kept in order (`server` first). A
172
+ * `passed` observation that conflicts with a failed or timed-out one for the
173
+ * same suite, kind, and head is dropped, so a merge never manufactures a
174
+ * reusable pass. When the merge exceeds the bounds, the oldest runs go first.
175
+ */
176
+ export function mergeCiFixTestRuns(server, local) {
177
+ const seen = new Set();
178
+ const combined = [];
179
+ for (const run of [...server.runs, ...local.runs]) {
180
+ const key = runKey(run);
181
+ if (seen.has(key))
182
+ continue;
183
+ seen.add(key);
184
+ combined.push(run);
185
+ }
186
+ const notPassed = new Set(combined
187
+ .filter((run) => run.outcome !== "passed")
188
+ .map((run) => JSON.stringify([run.suite, run.kind, run.head_sha])));
189
+ let runs = combined.filter((run) => run.outcome !== "passed" || !notPassed.has(JSON.stringify([run.suite, run.kind, run.head_sha])));
190
+ let merged = { version: 1, logical_job: server.logical_job, runs };
191
+ while (runs.length > 0 && !bounded(merged)) {
192
+ runs = runs.slice(1);
193
+ merged = { version: 1, logical_job: server.logical_job, runs };
194
+ }
195
+ return merged;
196
+ }
197
+ export const realCiFixTestRunsFs = {
198
+ lstat: async (p) => {
199
+ try {
200
+ const stat = await lstat(p);
201
+ return { isDirectory: stat.isDirectory(), isSymbolicLink: stat.isSymbolicLink() };
202
+ }
203
+ catch (error) {
204
+ if (errorCode(error) === "ENOENT")
205
+ return null;
206
+ throw error;
207
+ }
208
+ },
209
+ mkdir: (p) => mkdir(p, { recursive: true }),
210
+ readFile: (p) => readFile(p, "utf8"),
211
+ writeExclusive: async (p, data) => {
212
+ const handle = await open(p, constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | constants.O_NOFOLLOW, 0o600);
213
+ try {
214
+ await handle.writeFile(data, "utf8");
215
+ await handle.sync();
216
+ }
217
+ finally {
218
+ await handle.close();
219
+ }
220
+ },
221
+ rename: (from, to) => rename(from, to),
222
+ unlink: (p) => unlink(p),
223
+ };
224
+ /** The seams from executor deps, or `undefined` when a required one is missing. */
225
+ export function ciFixTestRunsFsFromDeps(deps) {
226
+ const { lstatPath, writeFileExclusive, rename: move, removeFile } = deps;
227
+ if (!lstatPath || !writeFileExclusive || !move || !removeFile)
228
+ return undefined;
229
+ return {
230
+ lstat: lstatPath,
231
+ mkdir: (p) => deps.mkdir(p, { recursive: true }),
232
+ readFile: (p) => deps.readFile(p),
233
+ writeExclusive: writeFileExclusive,
234
+ rename: move,
235
+ unlink: removeFile,
236
+ };
237
+ }
238
+ function errorCode(error) {
239
+ return error && typeof error === "object" ? error.code : undefined;
240
+ }
241
+ /** A safe `.conductor` directory: a real directory, never a link. */
242
+ async function safeDirectory(fs, directory) {
243
+ const meta = await fs.lstat(directory);
244
+ return meta !== null && meta.isDirectory && !meta.isSymbolicLink;
245
+ }
246
+ /**
247
+ * Seed `<worktree>/.conductor/ci-fix-test-runs.json` before a `ci_fix` spawn.
248
+ *
249
+ * The written record is the valid server record merged with a valid same-job
250
+ * local one, else whichever of the two is valid, else a fresh record with no
251
+ * runs. A malformed or other-job local file is replaced. A symlinked or
252
+ * non-regular `.conductor` directory or leaf is refused, and the record is
253
+ * published through an exclusive temporary file and a rename. Never throws:
254
+ * every failure is a `skipped` result with a fixed, secret-free code.
255
+ */
256
+ export async function seedCiFixTestRunsFile(worktreePath, input, fs = realCiFixTestRunsFs) {
257
+ const job = input.logicalJob;
258
+ if (!job)
259
+ return { status: "skipped", code: "logical_job_unavailable" };
260
+ let temporary;
261
+ try {
262
+ const directory = path.join(worktreePath, ".conductor");
263
+ const existing = await fs.lstat(directory);
264
+ if (existing === null)
265
+ await fs.mkdir(directory);
266
+ if (!(await safeDirectory(fs, directory)))
267
+ return { status: "skipped", code: "directory_unsafe" };
268
+ const destination = path.join(worktreePath, CI_FIX_TEST_RUNS_PATH);
269
+ const leaf = await fs.lstat(destination);
270
+ if (leaf !== null && (leaf.isDirectory || leaf.isSymbolicLink)) {
271
+ return { status: "skipped", code: "destination_unsafe" };
272
+ }
273
+ let local;
274
+ if (leaf !== null) {
275
+ try {
276
+ const raw = await fs.readFile(destination);
277
+ local = Buffer.byteLength(raw, "utf8") <= CI_FIX_TEST_RUNS_MAX_BYTES * 4
278
+ ? parseCiFixTestRuns(JSON.parse(raw), job)
279
+ : undefined;
280
+ }
281
+ catch {
282
+ local = undefined;
283
+ }
284
+ }
285
+ const server = parseCiFixTestRuns(input.prior, job);
286
+ let record;
287
+ let source;
288
+ if (server && local) {
289
+ record = mergeCiFixTestRuns(server, local);
290
+ source = "merged";
291
+ }
292
+ else if (server) {
293
+ record = server;
294
+ source = "server";
295
+ }
296
+ else if (local) {
297
+ record = local;
298
+ source = "local";
299
+ }
300
+ else {
301
+ record = { version: 1, logical_job: job, runs: [] };
302
+ source = "fresh";
303
+ }
304
+ temporary = path.join(directory, `.ci-fix-test-runs-${randomUUID()}.tmp`);
305
+ await fs.writeExclusive(temporary, JSON.stringify(record) + "\n");
306
+ // Re-check right before publishing: the directory and leaf may have moved.
307
+ if (!(await safeDirectory(fs, directory)))
308
+ return { status: "skipped", code: "directory_changed" };
309
+ const current = await fs.lstat(destination);
310
+ if (current !== null && (current.isDirectory || current.isSymbolicLink)) {
311
+ return { status: "skipped", code: "destination_unsafe" };
312
+ }
313
+ await fs.rename(temporary, destination);
314
+ temporary = undefined;
315
+ return { status: "written", source };
316
+ }
317
+ catch {
318
+ return { status: "skipped", code: "write_failed" };
319
+ }
320
+ finally {
321
+ if (temporary !== undefined)
322
+ await fs.unlink(temporary).catch(() => undefined);
323
+ }
324
+ }
325
+ /**
326
+ * Add a valid record to a result envelope, or return the envelope unchanged
327
+ * when the record is absent or the augmented envelope would exceed `maxBytes`.
328
+ */
329
+ export function withCiFixTestRuns(result, evidence, maxBytes) {
330
+ if (!evidence)
331
+ return result;
332
+ const augmented = { ...result, [CI_FIX_TEST_RUNS_RESULT_KEY]: evidence };
333
+ return serializedSize(augmented) <= maxBytes ? augmented : result;
334
+ }
@@ -305,8 +305,15 @@ export const MAX_TASKS = 64;
305
305
  export const MAX_DENIALS = 32;
306
306
  export const MAX_IDENTIFIER_CHARS = 128;
307
307
  export const MAX_SERIALIZED_BYTES = 32 * 1024;
308
- /** One stream-json event larger than this is `stream_oversize`, never parsed. */
308
+ /**
309
+ * One stream-json event larger than this is never retained or parsed as a whole
310
+ * event. It is read structurally instead: a bounded, incremental parser keeps
311
+ * only lifecycle metadata, and the event is `stream_oversize` unless that
312
+ * projection fully establishes its meaning.
313
+ */
309
314
  export const MAX_EVENT_BYTES = 1024 * 1024;
315
+ /** Hard per-line ceiling (UTF-8 bytes, newline excluded) for structural reading. */
316
+ export const MAX_STRUCTURAL_EVENT_BYTES = 32 * 1024 * 1024;
310
317
  const IDENTIFIER_RE = /^[A-Za-z0-9][A-Za-z0-9_.:-]*$/;
311
318
  export function sha256Hex(value) {
312
319
  return createHash("sha256").update(value, "utf8").digest("hex");
@@ -0,0 +1,168 @@
1
+ /**
2
+ * BAPI-1647: referenced-credential delivery for one executor worker start.
3
+ *
4
+ * Every reference operation is keyed on the claimed job's `repo_name` — the
5
+ * identity from the server's claim response, the same one
6
+ * `provisionMcpForPreparedSpawn` selects the MCP grant by — and runs in the
7
+ * executor's own process. Nothing is read from the worktree's checkout to decide
8
+ * what a worker receives.
9
+ *
10
+ * Two phases, in spawn-path order:
11
+ *
12
+ * 1. {@link readExecutorCredentialApprovals} — before the deny layer: one
13
+ * names-only record read plus child 1's `statusOnly()`, which yields every
14
+ * restricted entry's source path (missing ones included) for the
15
+ * `Read(<path>)` deny rules, and the reference inputs MCP provisioning uses.
16
+ * 2. {@link prepareExecutorCredentialDelivery} — after MCP provisioning and
17
+ * before the final `.env*` strip: child 1's `forWorkerLaunch()`, the shared
18
+ * reconciled, exclusion-first file delivery, and the sandbox variables for
19
+ * the env builder. Values live only in the returned in-memory map.
20
+ *
21
+ * Nothing here fails or parks a job: every problem becomes a names-only notice
22
+ * for the worker prompt and the executor's local per-job log.
23
+ */
24
+ import { forWorkerLaunch, statusOnly, } from "../credential-references.js";
25
+ import { createLaunchCredentialReferenceDeps, emptyApprovalMetadata, formatNoticeLines, launchResolveOptions, readApprovalMetadata, } from "../credential-delivery.js";
26
+ import { createNodeWorktreeCredentialDeliveryDeps, deliverWorktreeFileCredentials, } from "../worktree-credential-delivery.js";
27
+ import { isWorkerEnvNameReserved } from "./env.js";
28
+ function referenceDeps(deps, worktreePath) {
29
+ return createLaunchCredentialReferenceDeps(deps.env, worktreePath, { homedir: deps.homedir });
30
+ }
31
+ function recordReadDeps(deps) {
32
+ const base = referenceDeps(deps);
33
+ const read = deps.readFile;
34
+ if (!read)
35
+ return base;
36
+ return { ...base, readFile: read, readBytes: async (p) => Buffer.from(await read(p), "utf-8") };
37
+ }
38
+ /** Phase 1: names-only record read and restricted source paths. Never throws. */
39
+ export async function readExecutorCredentialApprovals(repoName, deps, seams = {}) {
40
+ let approvals;
41
+ try {
42
+ approvals = seams.readApprovals
43
+ ? await seams.readApprovals(repoName)
44
+ : await readApprovalMetadata(repoName, recordReadDeps(deps));
45
+ }
46
+ catch {
47
+ approvals = { state: "record_unusable", reason: "record_unreadable", metadata: emptyApprovalMetadata() };
48
+ }
49
+ let restrictedSourcePaths = [];
50
+ if (approvals.state === "ok") {
51
+ try {
52
+ const status = seams.statusOnly
53
+ ? await seams.statusOnly(repoName)
54
+ : await statusOnly(repoName, referenceDeps(deps));
55
+ if (status.state === "ok") {
56
+ restrictedSourcePaths = [
57
+ ...new Set(status.statuses.filter((st) => st.level === "restricted").flatMap((st) => st.source_paths ?? [])),
58
+ ];
59
+ }
60
+ }
61
+ catch {
62
+ restrictedSourcePaths = [];
63
+ }
64
+ }
65
+ return { approvals, restrictedSourcePaths };
66
+ }
67
+ /**
68
+ * Node-backed delivery deps for the no-approval reconcile. The Bridge state
69
+ * file is read through the executor's injected reader, so a worktree with no
70
+ * earlier Bridge links does no filesystem work outside the runner's boundary.
71
+ */
72
+ function reconcileDeliveryDeps(deps) {
73
+ const base = createNodeWorktreeCredentialDeliveryDeps(deps.runCommand, deps.platform);
74
+ return deps.readFile ? { ...base, readFile: deps.readFile } : base;
75
+ }
76
+ /** Phase 2: resolve and deliver for one worker start. Never throws. */
77
+ export async function prepareExecutorCredentialDelivery(repoName, worktreePath, approvals, deps, seams = {}) {
78
+ const prep = {
79
+ recordState: approvals.state,
80
+ ...(approvals.reason ? { recordReason: approvals.reason } : {}),
81
+ declaredCredentialEnv: {},
82
+ selected: [],
83
+ deliveredFiles: [],
84
+ offeredEnv: [],
85
+ eligibleMcp: [...new Set(approvals.metadata.mcp.map((d) => d.entry))],
86
+ notices: [],
87
+ };
88
+ // An absent or unusable record approves nothing. Reconciliation still runs
89
+ // so a link Bridge recorded at an earlier start (a retained or reused
90
+ // worktree) is withdrawn instead of surviving revocation. With no Bridge
91
+ // state file this is a no-op, so prompt, env, and argv stay unchanged.
92
+ const reconcileOnly = async (recordState) => {
93
+ try {
94
+ const reconciled = await deliverWorktreeFileCredentials({ worktreeRoot: worktreePath, recordState, files: [], approved: [] }, seams.deliveryDeps ?? reconcileDeliveryDeps(deps));
95
+ prep.notices.push(...reconciled.notices);
96
+ }
97
+ catch {
98
+ // Delivery never throws; contained anyway so this step never fails a job.
99
+ }
100
+ };
101
+ if (approvals.state !== "ok") {
102
+ await reconcileOnly(approvals.state);
103
+ return prep;
104
+ }
105
+ // Selected from the names-only approvals BEFORE resolving, so a resolver
106
+ // failure can still name every credential the worker did not receive.
107
+ const envEntries = new Set(Object.values(approvals.metadata.envOwners));
108
+ const fileEntries = new Set(approvals.metadata.files.map((f) => f.entry));
109
+ prep.selected = [...new Set([...fileEntries, ...envEntries])];
110
+ try {
111
+ const resolution = seams.resolveWorkerLaunch
112
+ ? await seams.resolveWorkerLaunch(repoName, worktreePath)
113
+ : await forWorkerLaunch(repoName, referenceDeps(deps, worktreePath), launchResolveOptions(worktreePath));
114
+ prep.recordState = resolution.state;
115
+ if (resolution.state !== "ok") {
116
+ await reconcileOnly(resolution.state);
117
+ return prep;
118
+ }
119
+ for (const u of resolution.unavailable)
120
+ prep.notices.push({ name: u.name, reason: u.reason });
121
+ const delivered = await deliverWorktreeFileCredentials({ worktreeRoot: worktreePath, recordState: resolution.state, files: resolution.files, approved: approvals.metadata.files }, seams.deliveryDeps ?? createNodeWorktreeCredentialDeliveryDeps(deps.runCommand, deps.platform));
122
+ prep.deliveredFiles = [...new Set(delivered.delivered.map((d) => d.name))];
123
+ prep.notices.push(...delivered.notices);
124
+ for (const [name, value] of Object.entries(resolution.env)) {
125
+ // Rechecked here so the worker notice can name it; the env builder
126
+ // rechecks again and also drops a collision with an executor-owned key.
127
+ if (isWorkerEnvNameReserved(name)) {
128
+ prep.notices.push({ name, reason: "reserved_name" });
129
+ continue;
130
+ }
131
+ prep.declaredCredentialEnv[name] = value;
132
+ prep.offeredEnv.push(name);
133
+ }
134
+ }
135
+ catch {
136
+ prep.declaredCredentialEnv = {};
137
+ prep.offeredEnv = [];
138
+ prep.notices.push(...prep.selected.map((name) => ({ name, reason: "unreadable" })));
139
+ }
140
+ return prep;
141
+ }
142
+ /** Notice lines for the worker prompt (one record-level line when unusable). */
143
+ export function credentialNoticeLines(prep) {
144
+ return formatNoticeLines(prep.recordState, prep.notices, prep.recordReason);
145
+ }
146
+ /**
147
+ * Names-only audit lines for the executor's local per-job log. MCP entries are
148
+ * reported as `eligible` only: the executor never sees an MCP server launch, so
149
+ * it never claims one received its credentials.
150
+ */
151
+ export function formatCredentialAuditLines(jobId, prep, admittedEnv, droppedEnv = []) {
152
+ if (prep.recordState === "absent")
153
+ return [];
154
+ const list = (names) => (names.length > 0 ? [...names].sort().join(",") : "-");
155
+ const lines = [`[executor] job ${jobId}: credentials record=${prep.recordState}`];
156
+ if (prep.recordState !== "ok")
157
+ return lines;
158
+ const deliveredEnv = admittedEnv ?? [];
159
+ lines.push(`[executor] job ${jobId}: credentials selected=${list(prep.selected)}`);
160
+ lines.push(`[executor] job ${jobId}: credentials delivered files=${list(prep.deliveredFiles)} variables=${list(deliveredEnv)}`);
161
+ const unavailable = [
162
+ ...prep.notices.map((n) => `${n.name}(${n.reason})`),
163
+ ...droppedEnv.map((d) => `${d.name}(${d.reason})`),
164
+ ];
165
+ lines.push(`[executor] job ${jobId}: credentials unavailable=${list([...new Set(unavailable)])}`);
166
+ lines.push(`[executor] job ${jobId}: credentials mcp eligible=${list(prep.eligibleMcp)}`);
167
+ return lines;
168
+ }
@@ -10,7 +10,7 @@ import { recordProvisionedAssets } from "../generated-assets-inventory.js";
10
10
  */
11
11
  import { execFile, spawn } from "node:child_process";
12
12
  import { existsSync } from "node:fs";
13
- import { open, readFile, writeFile, appendFile, mkdir, mkdtemp, chmod, rm, rename, readdir, lstat, stat, statfs, } from "node:fs/promises";
13
+ import { open, readFile, writeFile, appendFile, mkdir, mkdtemp, chmod, rm, rename, readdir, lstat, stat, statfs, realpath, } from "node:fs/promises";
14
14
  import os from "node:os";
15
15
  import { promisify } from "node:util";
16
16
  import { resolveMcpShimInvocationForRuntime } from "../mcp-server-invocation.js";
@@ -162,6 +162,8 @@ export function createDefaultExecutorDeps() {
162
162
  }
163
163
  },
164
164
  removeFile: (filePath) => rm(filePath, { force: true }),
165
+ // BAPI-1647: canonical paths for the cross-process exclude lock's key.
166
+ realpath: (filePath) => realpath(filePath),
165
167
  // BAPI-1021 (AC-6): worker-log archival's rename seam. Real `fs.promises.rename`
166
168
  // rejects with `code: "EXDEV"` across filesystems/devices, which worker-log.ts
167
169
  // treats as an ordinary best-effort archive failure like any other.