@bridge_gpt/mcp-server 0.2.71 → 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 (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -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/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -1,15 +1,22 @@
1
1
  /**
2
2
  * Local, read-only discovery. Optional .bridge/verification-hints.json is
3
- * {version:1,pins:[{paths:["exact/file", "directory/"],tests:["reference"]}]}.
3
+ * {version:1,pins?:[{paths:["exact/file", "directory/"],tests:["reference"]}],
4
+ * always?:["test/file.py", "test/directory/"]} (see `verification-hints.ts`).
4
5
  * Exact paths match exactly; directory prefixes match at directory boundaries.
6
+ * Admitted `always` entries (BAPI-1551) are the repository's always-run guards:
7
+ * they are returned FIRST, also as `required`, and are read before any other
8
+ * source so a git failure or the output cap cannot drop them.
5
9
  * Optional .conductor/recently-failed-tests.json is
6
10
  * {version:1,tests:["most-recent-first reference"],truncated:false}.
7
11
  * Child 3 writes recent failures under the worker worktree before each spawn.
8
12
  * Optional declared touched files (raw JSON, supplied by the caller) admit the
9
13
  * declared files that are tests and exist in the worktree.
10
- * References are data only, never commands. Priority: recent failures, sorted
11
- * declared tests, ordered pins, sorted inferred tracked tests; exact
12
- * deduplication precedes the limit.
14
+ * References are data only, never commands. Priority: always-run guards, recent
15
+ * failures, sorted declared tests, ordered pins, inferred tracked tests; exact
16
+ * deduplication precedes the limit. Inferred tests are scanned in deterministic
17
+ * proximity order (a: basename matches a changed file's stem, b: same top-level
18
+ * directory or a mirrored test directory, c: everything else, then ordinal) BEFORE
19
+ * either scan cap, so nearby tests survive truncation. Admission still needs a literal.
13
20
  * Missing/malformed/unreadable/truncated sources degrade advisory coverage.
14
21
  * Changed files come from the committed `<base>..HEAD` diff only; workers commit
15
22
  * before discovery. BAPI-1479 confirmed this was not why workers saw no output
@@ -17,18 +24,17 @@
17
24
  * stay out of scope.
18
25
  */
19
26
  import path from "node:path";
20
- import { constants } from "node:fs";
21
- import { lstat, open } from "node:fs/promises";
22
27
  import { execFile } from "node:child_process";
23
28
  import { normalizeDeclaredTouchedFiles } from "../conductor/file-scope-guard.js";
29
+ import { containedKind, containedText, object, readVerificationHints, validReference, validRepoPath, MAX_OPTIONAL_JSON_BYTES, } from "./verification-hints.js";
30
+ export { validTestReference } from "./verification-hints.js";
24
31
  export const RECENTLY_FAILED_TESTS_PATH = ".conductor/recently-failed-tests.json";
25
32
  export const RECENTLY_FAILED_TESTS_MAX_COUNT = 20;
26
- export const TEST_REFERENCE_MAX_LENGTH = 512;
33
+ export { TEST_REFERENCE_MAX_LENGTH, MAX_OPTIONAL_JSON_BYTES } from "./verification-hints.js";
27
34
  export const MAX_OUTPUT_REFERENCES = 100;
28
35
  export const MAX_SCAN_FILE_BYTES = 256 * 1024;
29
36
  export const MAX_SCAN_TOTAL_BYTES = 16 * 1024 * 1024;
30
37
  export const MAX_CANDIDATE_FILES = 10_000;
31
- export const MAX_OPTIONAL_JSON_BYTES = 256 * 1024;
32
38
  export const GIT_TIMEOUT_MS = 10_000;
33
39
  export const GIT_MAX_STDOUT_BYTES = 4 * 1024 * 1024;
34
40
  export const DISCOVERY_NOTES = {
@@ -42,26 +48,6 @@ export const DISCOVERY_NOTES = {
42
48
  empty: "No likely tests discovered; retain targeted verification.",
43
49
  };
44
50
  export function isFullCommitSha(value) { return /^[a-fA-F0-9]{40}$/.test(value); }
45
- function object(value) {
46
- return value !== null && typeof value === "object" && !Array.isArray(value)
47
- ? value : undefined;
48
- }
49
- export function validTestReference(value) {
50
- return typeof value === "string" && value.trim().length > 0 &&
51
- value.length <= TEST_REFERENCE_MAX_LENGTH && !/[\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(value);
52
- }
53
- function validRepoPath(value, directory = false) {
54
- const candidate = directory && value.endsWith("/") ? value.slice(0, -1) : value;
55
- return !!candidate && !path.isAbsolute(candidate) && !/[:\\\x00-\x1f\x7f-\x9f\u2028\u2029]/.test(candidate) &&
56
- candidate.split("/").every(p => p !== "" && p !== "." && p !== "..");
57
- }
58
- function validReference(value) {
59
- if (!validTestReference(value))
60
- return false;
61
- const file = value.split("::")[0];
62
- const fileShaped = value.includes("/") || /\.(?:py|[cm]?[jt]sx?)(?:::|$)/.test(value) || value.includes("::");
63
- return !fileShaped || validRepoPath(file);
64
- }
65
51
  export function parseRecentlyFailedTests(value) {
66
52
  const doc = object(value);
67
53
  if (!doc || doc.version !== 1 || !Array.isArray(doc.tests) || typeof doc.truncated !== "boolean")
@@ -79,61 +65,6 @@ export function parseRecentlyFailedTests(value) {
79
65
  return { available: true, value: { version: 1, tests,
80
66
  truncated: doc.truncated || doc.tests.length > RECENTLY_FAILED_TESTS_MAX_COUNT }, skipped };
81
67
  }
82
- function parseHints(value) {
83
- const doc = object(value);
84
- if (!doc || doc.version !== 1 || !Array.isArray(doc.pins))
85
- return undefined;
86
- const pins = [];
87
- let skipped = false;
88
- for (const entry of doc.pins) {
89
- const pin = object(entry);
90
- if (!pin || !Array.isArray(pin.paths) || !Array.isArray(pin.tests)) {
91
- skipped = true;
92
- continue;
93
- }
94
- const paths = pin.paths.filter((p) => typeof p === "string" && validRepoPath(p, true));
95
- const tests = pin.tests.filter(validReference);
96
- if (paths.length !== pin.paths.length || tests.length !== pin.tests.length)
97
- skipped = true;
98
- if (paths.length && tests.length)
99
- pins.push({ paths, tests });
100
- else
101
- skipped = true;
102
- }
103
- return { pins, skipped };
104
- }
105
- /** No-follow and fstat protect the final component; lstat every ancestor first.
106
- * Reads at most limit+1 bytes even if a file grows between stat and read.
107
- */
108
- async function containedText(root, relative, limit) {
109
- if (!validRepoPath(relative))
110
- throw new Error("invalid_path");
111
- let current = root;
112
- for (const part of relative.split("/")) {
113
- current = path.join(current, part);
114
- const info = await lstat(current);
115
- if (info.isSymbolicLink())
116
- throw new Error("symlink");
117
- if (current !== path.join(root, relative) && !info.isDirectory())
118
- throw new Error("ancestor");
119
- }
120
- const handle = await open(current, constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0));
121
- try {
122
- const info = await handle.stat();
123
- if (!info.isFile())
124
- throw new Error("not_regular");
125
- if (info.size > limit)
126
- throw new Error("bound");
127
- const buffer = Buffer.alloc(limit + 1);
128
- const { bytesRead } = await handle.read(buffer, 0, buffer.length, 0);
129
- if (bytesRead > limit)
130
- throw new Error("bound");
131
- return buffer.subarray(0, bytesRead).toString("utf8");
132
- }
133
- finally {
134
- await handle.close();
135
- }
136
- }
137
68
  async function boundedGit(cwd, argv) {
138
69
  return new Promise((resolve, reject) => {
139
70
  execFile("git", argv, { cwd, shell: false, timeout: GIT_TIMEOUT_MS,
@@ -160,6 +91,58 @@ function testCandidate(file) {
160
91
  return true;
161
92
  return base.endsWith(".rs") && file.split("/").slice(0, -1).includes("tests");
162
93
  }
94
+ /** Proximity tiers for an inferred test candidate; lower is scanned first. */
95
+ const TIER_NEARBY_NAME = 0;
96
+ const TIER_NEARBY_DIRECTORY = 1;
97
+ const TIER_OTHER = 2;
98
+ /** The file name without only its final extension (`widget.service.ts` -> `widget.service`). */
99
+ function basenameStem(file) {
100
+ const base = path.posix.basename(file);
101
+ const dot = base.lastIndexOf(".");
102
+ return dot > 0 ? base.slice(0, dot) : base;
103
+ }
104
+ function nameMatchesStem(candidateBase, stem) {
105
+ if (!stem)
106
+ return false;
107
+ return (candidateBase.startsWith(`test_${stem}`) && candidateBase.endsWith(".py")) ||
108
+ candidateBase === `${stem}_test.py` ||
109
+ candidateBase.startsWith(`${stem}.test.`) || candidateBase.startsWith(`${stem}.spec.`);
110
+ }
111
+ /** True when `needle` appears as a contiguous run of whole segments inside `haystack`. */
112
+ function containsSegments(haystack, needle) {
113
+ if (needle.length === 0)
114
+ return false;
115
+ for (let i = 0; i + needle.length <= haystack.length; i++) {
116
+ if (needle.every((segment, j) => haystack[i + j] === segment))
117
+ return true;
118
+ }
119
+ return false;
120
+ }
121
+ function directoryNearby(candidate, changedFile) {
122
+ const candidateDirs = candidate.split("/").slice(0, -1);
123
+ const changedDirs = changedFile.split("/").slice(0, -1);
124
+ if (changedDirs.length === 0)
125
+ return false;
126
+ if (candidateDirs[0] === changedDirs[0])
127
+ return true;
128
+ if (candidateDirs[0] !== "tests")
129
+ return false;
130
+ const suite = candidateDirs.slice(1);
131
+ // The mirrored parent path, with or without its top-level directory; never empty.
132
+ return containsSegments(suite, changedDirs) || containsSegments(suite, changedDirs.slice(1));
133
+ }
134
+ /** The best tier a candidate earns across every changed file. */
135
+ function proximityTier(candidate, changed) {
136
+ const base = path.posix.basename(candidate);
137
+ let best = TIER_OTHER;
138
+ for (const file of changed) {
139
+ if (nameMatchesStem(base, basenameStem(file)))
140
+ return TIER_NEARBY_NAME;
141
+ if (best > TIER_NEARBY_DIRECTORY && directoryNearby(candidate, file))
142
+ best = TIER_NEARBY_DIRECTORY;
143
+ }
144
+ return best;
145
+ }
163
146
  /** Discover declared Python source roots without importing any project code. */
164
147
  async function pythonRoots(root, read) {
165
148
  const roots = [""];
@@ -181,6 +164,7 @@ async function pythonRoots(root, read) {
181
164
  export async function resolveLikelyTests(options) {
182
165
  const references = [];
183
166
  const diagnostics = new Set();
167
+ let required = [];
184
168
  const add = (items) => {
185
169
  for (const item of items)
186
170
  if (!references.includes(item))
@@ -191,7 +175,8 @@ export async function resolveLikelyTests(options) {
191
175
  diagnostics.add("truncated");
192
176
  if (!references.length)
193
177
  diagnostics.add("empty");
194
- return { references: references.slice(0, MAX_OUTPUT_REFERENCES), diagnostics: [...diagnostics] };
178
+ // The required guards come first and number at most 32, so the cap never cuts them.
179
+ return { references: references.slice(0, MAX_OUTPUT_REFERENCES), diagnostics: [...diagnostics], required };
195
180
  };
196
181
  if (!isFullCommitSha(options.comparisonSha)) {
197
182
  diagnostics.add("invalid_arguments");
@@ -199,6 +184,21 @@ export async function resolveLikelyTests(options) {
199
184
  }
200
185
  const git = options.git ?? boundedGit;
201
186
  const read = options.readText ?? containedText;
187
+ // BAPI-1551 — the hints file is read FIRST, before recent failures, declared
188
+ // files, and every git-dependent step, so its always-run guards survive a git
189
+ // failure and the output cap. Without a git root it is read from `cwd`.
190
+ const readHints = async (base) => {
191
+ const result = await readVerificationHints(base, { readText: read, kindOf: options.kindOf ?? containedKind });
192
+ if (result.status === "ok") {
193
+ required = [...result.required];
194
+ add(required);
195
+ if (result.skipped)
196
+ diagnostics.add("skipped_entries");
197
+ }
198
+ else
199
+ diagnostics.add(result.status === "missing" ? "hints_missing" : "data_unavailable");
200
+ return result;
201
+ };
202
202
  let root;
203
203
  try {
204
204
  root = (await git(options.cwd, ["rev-parse", "--show-toplevel"])).trim();
@@ -206,9 +206,13 @@ export async function resolveLikelyTests(options) {
206
206
  throw new Error("root");
207
207
  }
208
208
  catch {
209
+ if (path.isAbsolute(options.cwd))
210
+ await readHints(options.cwd);
209
211
  diagnostics.add("git_unavailable");
210
212
  return finish();
211
213
  }
214
+ const hints = await readHints(root);
215
+ const pins = hints.status === "ok" ? hints.pins : [];
212
216
  try {
213
217
  const raw = await read(root, RECENTLY_FAILED_TESTS_PATH, MAX_OPTIONAL_JSON_BYTES);
214
218
  const recent = parseRecentlyFailedTests(JSON.parse(raw));
@@ -252,17 +256,6 @@ export async function resolveLikelyTests(options) {
252
256
  add(admitted);
253
257
  }
254
258
  }
255
- let hints;
256
- try {
257
- hints = parseHints(JSON.parse(await read(root, ".bridge/verification-hints.json", MAX_OPTIONAL_JSON_BYTES)));
258
- if (!hints)
259
- diagnostics.add("data_unavailable");
260
- else if (hints.skipped)
261
- diagnostics.add("skipped_entries");
262
- }
263
- catch (error) {
264
- diagnostics.add(error.code === "ENOENT" ? "hints_missing" : "data_unavailable");
265
- }
266
259
  let changed;
267
260
  try {
268
261
  const verified = (await git(root, ["rev-parse", "--verify", `${options.comparisonSha}^{commit}`])).trim();
@@ -277,7 +270,7 @@ export async function resolveLikelyTests(options) {
277
270
  diagnostics.add("git_unavailable");
278
271
  return finish();
279
272
  }
280
- for (const pin of hints?.pins ?? []) {
273
+ for (const pin of pins) {
281
274
  if (pin.paths.some(p => changed.some(c => p.endsWith("/") ? c.startsWith(p) : c === p)))
282
275
  add(pin.tests);
283
276
  }
@@ -292,7 +285,11 @@ export async function resolveLikelyTests(options) {
292
285
  diagnostics.add("git_unavailable");
293
286
  return finish();
294
287
  }
295
- const candidates = tracked.filter(testCandidate).sort(ordinal);
288
+ // Deterministic (tier, ordinal) order BEFORE either scan cap; Array.sort is stable.
289
+ const candidates = tracked.filter(testCandidate).sort(ordinal)
290
+ .map(file => ({ file, tier: proximityTier(file, changed) }))
291
+ .sort((a, b) => a.tier - b.tier)
292
+ .map(entry => entry.file);
296
293
  if (candidates.length > MAX_CANDIDATE_FILES)
297
294
  diagnostics.add("truncated");
298
295
  const roots = await pythonRoots(root, read);
@@ -681,6 +681,7 @@ export function createObservationState(deps, options) {
681
681
  let exitCode;
682
682
  let attemptStartSha;
683
683
  let attemptEndSha;
684
+ let workerDatabaseProvisioned = false;
684
685
  /**
685
686
  * BAPI-828/BAPI-898: the MOST SEVERE qualifying advisory observed so far wins,
686
687
  * ranked by {@link rateLimitSeverity}. An advisory at equal or lower severity —
@@ -847,6 +848,9 @@ export function createObservationState(deps, options) {
847
848
  }
848
849
  publication = { ...publication, to_sha: fact.to_sha };
849
850
  },
851
+ recordWorkerDatabaseProvisioned() {
852
+ workerDatabaseProvisioned = true;
853
+ },
850
854
  snapshot() {
851
855
  const residue = { ...git };
852
856
  if (publication) {
@@ -870,6 +874,10 @@ export function createObservationState(deps, options) {
870
874
  residue.attempt_start_sha = attemptStartSha;
871
875
  if (attemptEndSha !== undefined)
872
876
  residue.attempt_end_sha = attemptEndSha;
877
+ // BAPI-1609: absent until a database was really provisioned, so a job
878
+ // without one serializes exactly as before.
879
+ if (workerDatabaseProvisioned)
880
+ residue.worker_resources = { database: "provisioned" };
873
881
  return residue;
874
882
  },
875
883
  terminalCapacity() {
@@ -0,0 +1,363 @@
1
+ /**
2
+ * BAPI-1582 — pre-PR checks for an `implement` worker.
3
+ *
4
+ * Two contracts live here:
5
+ *
6
+ * 1. **Declarations.** The server stamps `pre_pr_checks` on an implement payload:
7
+ * every owner-confirmed gate-profile reproduction hint as
8
+ * `{check, argv, timeout_seconds}`, sorted by check name. The executor
9
+ * re-validates each entry before rendering it into the worker prompt. An
10
+ * invalid entry is skipped with a closed reason and its position; an argv item
11
+ * is never logged or rendered from a rejected entry.
12
+ *
13
+ * 2. **Evidence.** The worker writes `<worktree>/.conductor/pre-pr-checks.json`
14
+ * before it calls `create_pull_request`. After exit the executor reads it with
15
+ * a bounded, no-follow read, trusts it only when its `tested_head` equals the
16
+ * observed final head, and attaches a bounded summary to the completion result
17
+ * as telemetry. It is never gate evidence, never a ledger record, and a
18
+ * missing, stale, or malformed record attaches nothing and fails nothing.
19
+ */
20
+ import path from "node:path";
21
+ /** The shared budget, in seconds, for the whole pre-PR step of one implement attempt. */
22
+ export const PRE_PR_BUDGET_SECONDS = 600;
23
+ /** Declaration bounds (mirror the gate profile's reproduction-hint rules). */
24
+ export const PRE_PR_MAX_DECLARATIONS = 32;
25
+ export const PRE_PR_CHECK_NAME_MAX_CHARS = 200;
26
+ export const PRE_PR_ARGV_MAX_ITEMS = 32;
27
+ export const PRE_PR_ARG_MAX_CHARS = 1024;
28
+ export const PRE_PR_TIMEOUT_MIN_SECONDS = 1;
29
+ export const PRE_PR_TIMEOUT_MAX_SECONDS = 1800;
30
+ /** The evidence record's location under the worktree. */
31
+ export const PRE_PR_EVIDENCE_RELATIVE_PATH = path.join(".conductor", "pre-pr-checks.json");
32
+ /** Largest evidence file the executor reads. */
33
+ export const PRE_PR_EVIDENCE_MAX_BYTES = 64_000;
34
+ /** The completion-result key the bounded summary rides on. */
35
+ export const PRE_PR_SUMMARY_KEY = "pre_pr_checks_summary";
36
+ const CONTROL_CHAR_RE = /[\x00-\x1f\x7f]/;
37
+ const DECLARATION_KEYS = new Set(["check", "argv", "timeout_seconds"]);
38
+ function isPlainRecord(value) {
39
+ return value !== null && typeof value === "object" && !Array.isArray(value);
40
+ }
41
+ function rejectDeclaration(raw) {
42
+ if (!isPlainRecord(raw))
43
+ return "not_an_object";
44
+ for (const key of Object.keys(raw))
45
+ if (!DECLARATION_KEYS.has(key))
46
+ return "unexpected_key";
47
+ const check = raw.check;
48
+ if (typeof check !== "string")
49
+ return "check_invalid";
50
+ const name = check.trim();
51
+ if (!name || name.length > PRE_PR_CHECK_NAME_MAX_CHARS || CONTROL_CHAR_RE.test(name))
52
+ return "check_invalid";
53
+ const argv = raw.argv;
54
+ if (!Array.isArray(argv))
55
+ return "argv_not_a_list";
56
+ if (argv.length < 1 || argv.length > PRE_PR_ARGV_MAX_ITEMS)
57
+ return "argv_count_invalid";
58
+ for (const item of argv) {
59
+ if (typeof item !== "string" || !item.trim() || item.length > PRE_PR_ARG_MAX_CHARS || item.includes("\x00")) {
60
+ return "argv_item_invalid";
61
+ }
62
+ }
63
+ const timeout = raw.timeout_seconds;
64
+ if (typeof timeout !== "number" || !Number.isInteger(timeout) ||
65
+ timeout < PRE_PR_TIMEOUT_MIN_SECONDS || timeout > PRE_PR_TIMEOUT_MAX_SECONDS) {
66
+ return "timeout_invalid";
67
+ }
68
+ return { check: name, argv: [...argv], timeoutSeconds: timeout };
69
+ }
70
+ /**
71
+ * Validate a payload `pre_pr_checks` value. Never throws. Entries keep their
72
+ * supplied (server-sorted) order; a duplicate check name or an entry past
73
+ * {@link PRE_PR_MAX_DECLARATIONS} is skipped, never silently merged.
74
+ */
75
+ export function admitPrePrChecks(raw) {
76
+ if (!Array.isArray(raw))
77
+ return { entries: [], skipped: [], notAList: true };
78
+ const entries = [];
79
+ const skipped = [];
80
+ const seen = new Set();
81
+ raw.forEach((item, position) => {
82
+ if (position >= PRE_PR_MAX_DECLARATIONS) {
83
+ skipped.push({ position, reason: "too_many_declarations" });
84
+ return;
85
+ }
86
+ const verdict = rejectDeclaration(item);
87
+ if (typeof verdict === "string") {
88
+ skipped.push({ position, reason: verdict });
89
+ return;
90
+ }
91
+ if (seen.has(verdict.check)) {
92
+ skipped.push({ position, reason: "duplicate_check" });
93
+ return;
94
+ }
95
+ seen.add(verdict.check);
96
+ entries.push(verdict);
97
+ });
98
+ return { entries, skipped, notAList: false };
99
+ }
100
+ /**
101
+ * The admitted entries for a payload option, logging each skip by position and
102
+ * closed reason only. Absent (`undefined`) admits nothing and logs nothing.
103
+ */
104
+ export function validatePrePrCheckDeclarations(option, errorLog = (message) => console.error(message)) {
105
+ if (!Object.prototype.hasOwnProperty.call(option, "prePrChecks"))
106
+ return [];
107
+ const log = (message) => { try {
108
+ errorLog(message);
109
+ }
110
+ catch { /* sink */ } };
111
+ let admitted;
112
+ try {
113
+ admitted = admitPrePrChecks(option.prePrChecks);
114
+ }
115
+ catch {
116
+ admitted = { entries: [], skipped: [], notAList: true };
117
+ }
118
+ if (admitted.notAList) {
119
+ log("executor: pre_pr_checks is present but is not a list; rendering no pre-PR checks");
120
+ return [];
121
+ }
122
+ for (const skip of admitted.skipped) {
123
+ log(`executor: skipped pre_pr_checks entry ${skip.position}: ${skip.reason}`);
124
+ }
125
+ return admitted.entries;
126
+ }
127
+ // ---------------------------------------------------------------------------
128
+ // Evidence record
129
+ // ---------------------------------------------------------------------------
130
+ export const PRE_PR_SOURCES = ["required", "likely_tests", "gate_profile"];
131
+ export const PRE_PR_RUN_OUTCOMES = ["passed", "failed", "timed_out"];
132
+ export const PRE_PR_SKIP_REASONS = ["budget", "unmappable", "not_executable", "unavailable"];
133
+ /** Evidence bounds. */
134
+ export const PRE_PR_EVIDENCE_MAX_SELECTED = 256;
135
+ export const PRE_PR_EVIDENCE_MAX_RUNS = 512;
136
+ export const PRE_PR_EVIDENCE_MAX_SKIPPED = 256;
137
+ export const PRE_PR_EVIDENCE_NAME_MAX_CHARS = 500;
138
+ /** Largest duration accepted for one run or the whole step (a day; anything more is malformed). */
139
+ const PRE_PR_MAX_SECONDS = 86_400;
140
+ /** Names listed in the summary's not-passed and unverified lists. */
141
+ export const PRE_PR_SUMMARY_MAX_NAMES = 16;
142
+ const SHA_RE = /^(?:[0-9a-f]{40}|[0-9a-f]{64})$/;
143
+ function validName(value) {
144
+ return typeof value === "string" && value.trim().length > 0 &&
145
+ value.length <= PRE_PR_EVIDENCE_NAME_MAX_CHARS && !CONTROL_CHAR_RE.test(value);
146
+ }
147
+ function validSeconds(value) {
148
+ return typeof value === "number" && Number.isFinite(value) && value >= 0 && value <= PRE_PR_MAX_SECONDS;
149
+ }
150
+ function validSha(value) {
151
+ return typeof value === "string" && SHA_RE.test(value);
152
+ }
153
+ function oneOf(values, value) {
154
+ return typeof value === "string" && values.includes(value);
155
+ }
156
+ function exactKeys(value, keys) {
157
+ const present = Object.keys(value);
158
+ return present.length === keys.length && keys.every((key) => Object.prototype.hasOwnProperty.call(value, key));
159
+ }
160
+ /**
161
+ * Validate a parsed evidence record. Returns the record (with only its declared
162
+ * fields) or `null`. Never throws. Unknown keys, unknown vocabulary, an invalid
163
+ * SHA, a negative or non-finite duration, or an array over its bound all reject
164
+ * the whole record — nothing from it is trusted partially.
165
+ */
166
+ export function validatePrePrEvidence(raw) {
167
+ if (!isPlainRecord(raw))
168
+ return null;
169
+ if (!exactKeys(raw, ["version", "tested_head", "budget_seconds", "elapsed_seconds", "selected", "run", "skipped"])) {
170
+ return null;
171
+ }
172
+ if (raw.version !== 1 || !validSha(raw.tested_head))
173
+ return null;
174
+ if (raw.budget_seconds !== PRE_PR_BUDGET_SECONDS || !validSeconds(raw.elapsed_seconds))
175
+ return null;
176
+ const { selected, run, skipped } = raw;
177
+ if (!Array.isArray(selected) || selected.length > PRE_PR_EVIDENCE_MAX_SELECTED)
178
+ return null;
179
+ if (!Array.isArray(run) || run.length > PRE_PR_EVIDENCE_MAX_RUNS)
180
+ return null;
181
+ if (!Array.isArray(skipped) || skipped.length > PRE_PR_EVIDENCE_MAX_SKIPPED)
182
+ return null;
183
+ const out = {
184
+ version: 1,
185
+ tested_head: raw.tested_head,
186
+ budget_seconds: PRE_PR_BUDGET_SECONDS,
187
+ elapsed_seconds: raw.elapsed_seconds,
188
+ selected: [],
189
+ run: [],
190
+ skipped: [],
191
+ };
192
+ for (const entry of selected) {
193
+ if (!isPlainRecord(entry) || !exactKeys(entry, ["name", "source"]))
194
+ return null;
195
+ if (!validName(entry.name) || !oneOf(PRE_PR_SOURCES, entry.source))
196
+ return null;
197
+ out.selected.push({ name: entry.name, source: entry.source });
198
+ }
199
+ for (const entry of run) {
200
+ if (!isPlainRecord(entry) || !exactKeys(entry, ["name", "source", "head_sha", "outcome", "seconds"]))
201
+ return null;
202
+ if (!validName(entry.name) || !oneOf(PRE_PR_SOURCES, entry.source) || !validSha(entry.head_sha) ||
203
+ !oneOf(PRE_PR_RUN_OUTCOMES, entry.outcome) || !validSeconds(entry.seconds)) {
204
+ return null;
205
+ }
206
+ out.run.push({
207
+ name: entry.name, source: entry.source, head_sha: entry.head_sha,
208
+ outcome: entry.outcome, seconds: entry.seconds,
209
+ });
210
+ }
211
+ for (const entry of skipped) {
212
+ if (!isPlainRecord(entry) || !exactKeys(entry, ["name", "source", "reason"]))
213
+ return null;
214
+ if (!validName(entry.name) || !oneOf(PRE_PR_SOURCES, entry.source) || !oneOf(PRE_PR_SKIP_REASONS, entry.reason)) {
215
+ return null;
216
+ }
217
+ out.skipped.push({ name: entry.name, source: entry.source, reason: entry.reason });
218
+ }
219
+ return out;
220
+ }
221
+ /**
222
+ * Summarize a validated record observed at `observedHead`. Returns `null` for a
223
+ * stale record (its `tested_head` is not the observed head).
224
+ */
225
+ export function summarizePrePrEvidence(evidence, observedHead) {
226
+ if (evidence.tested_head !== observedHead.trim().toLowerCase())
227
+ return null;
228
+ const atHead = { passed: 0, failed: 0, timed_out: 0 };
229
+ const latestAtHead = new Map();
230
+ let historical = 0;
231
+ for (const run of evidence.run) {
232
+ if (run.head_sha === evidence.tested_head) {
233
+ atHead[run.outcome] += 1;
234
+ latestAtHead.set(run.name, run.outcome);
235
+ }
236
+ else {
237
+ historical += 1;
238
+ }
239
+ }
240
+ const skipped = { budget: 0, unmappable: 0, not_executable: 0, unavailable: 0 };
241
+ const skippedNames = new Set();
242
+ for (const skip of evidence.skipped) {
243
+ skipped[skip.reason] += 1;
244
+ skippedNames.add(skip.name);
245
+ }
246
+ const notPassed = [];
247
+ const unverified = [];
248
+ const seen = new Set();
249
+ for (const { name } of evidence.selected) {
250
+ if (seen.has(name))
251
+ continue;
252
+ seen.add(name);
253
+ const outcome = latestAtHead.get(name);
254
+ if (outcome === undefined) {
255
+ if (!skippedNames.has(name))
256
+ unverified.push(name);
257
+ }
258
+ else if (outcome !== "passed") {
259
+ notPassed.push(name);
260
+ }
261
+ }
262
+ return {
263
+ version: 1,
264
+ tested_head: evidence.tested_head,
265
+ budget_seconds: evidence.budget_seconds,
266
+ elapsed_seconds: evidence.elapsed_seconds,
267
+ selected_count: evidence.selected.length,
268
+ at_tested_head: atHead,
269
+ historical_run_count: historical,
270
+ skipped,
271
+ not_passed_at_tested_head: notPassed.slice(0, PRE_PR_SUMMARY_MAX_NAMES),
272
+ unverified_at_tested_head: unverified.slice(0, PRE_PR_SUMMARY_MAX_NAMES),
273
+ unverified_at_tested_head_count: unverified.length,
274
+ };
275
+ }
276
+ /**
277
+ * Read `<worktree>/.conductor/pre-pr-checks.json` with a bounded, no-follow read.
278
+ * Never throws; `code` is a fixed, secret-free token.
279
+ */
280
+ export async function readPrePrEvidenceArtifact(worktreePath, deps) {
281
+ const conductorDir = path.join(worktreePath, ".conductor");
282
+ const artifactPath = path.join(worktreePath, PRE_PR_EVIDENCE_RELATIVE_PATH);
283
+ if (deps.lstatPath) {
284
+ try {
285
+ const dirMeta = await deps.lstatPath(conductorDir);
286
+ if (dirMeta === null)
287
+ return { status: "missing", code: "artifact_absent" };
288
+ if (dirMeta.isSymbolicLink || !dirMeta.isDirectory)
289
+ return { status: "invalid", code: "artifact_dir_unsafe" };
290
+ const meta = await deps.lstatPath(artifactPath);
291
+ if (meta === null)
292
+ return { status: "missing", code: "artifact_absent" };
293
+ if (meta.isDirectory || meta.isSymbolicLink)
294
+ return { status: "invalid", code: "artifact_not_regular_file" };
295
+ }
296
+ catch {
297
+ return { status: "invalid", code: "artifact_unreadable" };
298
+ }
299
+ }
300
+ let raw;
301
+ try {
302
+ raw = await deps.readFile(artifactPath);
303
+ }
304
+ catch (err) {
305
+ const code = err && typeof err === "object" ? err.code : undefined;
306
+ return code === "ENOENT"
307
+ ? { status: "missing", code: "artifact_absent" }
308
+ : { status: "invalid", code: "artifact_unreadable" };
309
+ }
310
+ if (typeof raw !== "string")
311
+ return { status: "invalid", code: "artifact_unreadable" };
312
+ if (Buffer.byteLength(raw, "utf8") > PRE_PR_EVIDENCE_MAX_BYTES)
313
+ return { status: "invalid", code: "artifact_oversized" };
314
+ let parsed;
315
+ try {
316
+ parsed = JSON.parse(raw);
317
+ }
318
+ catch {
319
+ return { status: "invalid", code: "artifact_not_json" };
320
+ }
321
+ const evidence = validatePrePrEvidence(parsed);
322
+ return evidence === null ? { status: "invalid", code: "artifact_invalid" } : { status: "ok", evidence };
323
+ }
324
+ const CONTENT_FAILURE_CODES = new Set(["artifact_oversized", "artifact_not_json", "artifact_invalid"]);
325
+ /**
326
+ * Attach the bounded summary to `result` when a valid, current-head record
327
+ * exists and the augmented result still fits `maxResultBytes`. Otherwise
328
+ * `result` is returned unchanged. Never throws.
329
+ */
330
+ export async function withPrePrChecksSummary(result, options) {
331
+ const log = (message) => { try {
332
+ options.errorLog?.(message);
333
+ }
334
+ catch { /* sink */ } };
335
+ try {
336
+ if (typeof options.observedHead !== "string" || !SHA_RE.test(options.observedHead.trim().toLowerCase())) {
337
+ return result;
338
+ }
339
+ const read = await readPrePrEvidenceArtifact(options.worktreePath, options.deps);
340
+ if (read.status !== "ok") {
341
+ // An absent or unreadable record is ordinary (no pre-PR step, full scope,
342
+ // or a filesystem shape the worker never wrote): stay quiet. Only a record
343
+ // the worker wrote with bad content is worth a line.
344
+ if (CONTENT_FAILURE_CODES.has(read.code))
345
+ log(`executor: pre-PR checks record invalid (${read.code}); no summary attached`);
346
+ return result;
347
+ }
348
+ const summary = summarizePrePrEvidence(read.evidence, options.observedHead);
349
+ if (summary === null) {
350
+ log("executor: pre-PR checks record is stale (tested_head is not the final head); no summary attached");
351
+ return result;
352
+ }
353
+ const augmented = { ...result, [PRE_PR_SUMMARY_KEY]: summary };
354
+ if (Buffer.byteLength(JSON.stringify(augmented), "utf8") > options.maxResultBytes) {
355
+ log("executor: pre-PR checks summary would exceed the result budget; not attached");
356
+ return result;
357
+ }
358
+ return augmented;
359
+ }
360
+ catch {
361
+ return result;
362
+ }
363
+ }