@bridge_gpt/mcp-server 0.2.71 → 0.2.72

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 (116) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +19 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +4 -4
  5. package/build/bridge-permissions.js +4 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/claude-review-workflow.js +1 -1
  9. package/build/cli-help.js +6 -0
  10. package/build/codex-auto-recovery.js +126 -0
  11. package/build/codex-skill-adapter.js +2 -0
  12. package/build/commands.generated.js +5 -5
  13. package/build/conductor/bridge-api-client.js +518 -23
  14. package/build/conductor/doctor.js +84 -10
  15. package/build/conductor/epic-implementer-cli.js +51 -2
  16. package/build/conductor/gate-discovery.js +136 -10
  17. package/build/conductor/gate-settings-review.js +305 -5
  18. package/build/conductor/git-hooks-uninstall.js +112 -0
  19. package/build/conductor/git-hooks.js +81 -15
  20. package/build/conductor/guided-repair.js +10 -1
  21. package/build/conductor/install-doctor.js +2 -4
  22. package/build/conductor/launch-plan.js +42 -2
  23. package/build/conductor/local-merge.js +12 -1
  24. package/build/conductor/merge-execution-contract.js +1 -1
  25. package/build/conductor/merged-child-check.js +2 -1
  26. package/build/conductor/prerequisite-inputs.js +379 -0
  27. package/build/conductor/readiness-assessment.js +78 -0
  28. package/build/conductor/readiness-cli.js +10 -0
  29. package/build/conductor/readiness-prerequisites.js +53 -0
  30. package/build/conductor/readiness-sections.js +21 -8
  31. package/build/conductor/readiness.js +20 -2
  32. package/build/conductor/recovery-cli.js +223 -13
  33. package/build/conductor/recovery-operations.js +34 -4
  34. package/build/conductor/repair-contract.js +33 -0
  35. package/build/conductor/tools.js +34 -3
  36. package/build/conductor/wait-run-attention.js +115 -0
  37. package/build/conductor/wait-run-cli.js +96 -3
  38. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  39. package/build/credential-store.js +25 -20
  40. package/build/dependency-install-declarations.js +157 -0
  41. package/build/docs.generated.js +4 -4
  42. package/build/doctor.js +37 -5
  43. package/build/drive-epic-help.js +2 -2
  44. package/build/drive-epic.js +52 -11
  45. package/build/epic-implementer-bin.js +118 -43
  46. package/build/epic-launch-profile.js +1 -1
  47. package/build/executor/cli.js +2 -0
  48. package/build/executor/completion-contract.js +16 -0
  49. package/build/executor/credentials.js +1 -1
  50. package/build/executor/delivery-observations.js +113 -0
  51. package/build/executor/delivery-outcome.js +30 -0
  52. package/build/executor/dependency-refresh-runner.js +132 -0
  53. package/build/executor/dependency-refresh.js +530 -0
  54. package/build/executor/deps.js +4 -0
  55. package/build/executor/env.js +67 -2
  56. package/build/executor/harness-coverage.js +19 -0
  57. package/build/executor/http-client.js +35 -1
  58. package/build/executor/index.js +2 -1
  59. package/build/executor/install-preflight.js +1 -1
  60. package/build/executor/job-runner.js +246 -28
  61. package/build/executor/likely-tests.js +94 -97
  62. package/build/executor/prompt-spec.js +13 -3
  63. package/build/executor/required-verification.js +28 -0
  64. package/build/executor/required-work-diagnostics.js +30 -0
  65. package/build/executor/required-work-ledger.js +19 -1
  66. package/build/executor/results.js +42 -0
  67. package/build/executor/service-discovery.js +42 -0
  68. package/build/executor/service-lifecycle.js +109 -2
  69. package/build/executor/service-uninstall.js +205 -0
  70. package/build/executor/service-unit.js +5 -3
  71. package/build/executor/test-clock.js +3 -0
  72. package/build/executor/verification-hints.js +179 -0
  73. package/build/executor/worker-command.js +54 -2
  74. package/build/executor/worker-database.js +271 -31
  75. package/build/executor/worker-finalization.js +65 -10
  76. package/build/executor/worker-guard-hook.js +10 -2
  77. package/build/executor/worker-verification-guidance.js +37 -2
  78. package/build/executor/worktree-inspection.js +42 -0
  79. package/build/github-sign-in.js +1 -1
  80. package/build/index.js +679 -278
  81. package/build/init.js +3 -3
  82. package/build/install-bridge-conductor-gate.js +236 -42
  83. package/build/install-bridge-conductor-setup.js +115 -26
  84. package/build/install-bridge-conductor.js +448 -350
  85. package/build/install-bridge.js +418 -123
  86. package/build/install-maintenance.js +104 -0
  87. package/build/install-reexec.js +1 -1
  88. package/build/local-cleanup.js +59 -0
  89. package/build/mcp-install-state.js +68 -2
  90. package/build/merge-workflow-install.js +2 -2
  91. package/build/package-script-semantics.js +10 -0
  92. package/build/pipeline-utils.js +1 -1
  93. package/build/pipelines.generated.js +5 -5
  94. package/build/plan-execution-ledger.js +148 -2
  95. package/build/plane/plane-freshness.js +6 -7
  96. package/build/plane/terminal-run-cleanup.js +5 -1
  97. package/build/plane/terminal-run-status.js +4 -0
  98. package/build/printed-remedy-commands.js +24 -4
  99. package/build/readiness-check.js +1 -78
  100. package/build/readiness-prerequisites.generated.js +199 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-toolchains.js +50 -8
  103. package/build/setup-change-policy.js +32 -0
  104. package/build/setup-epic.js +2 -2
  105. package/build/setup-question.js +62 -0
  106. package/build/start-tickets.js +4 -0
  107. package/build/test-command-detection.js +32 -88
  108. package/build/test-support/notes-fs.js +40 -0
  109. package/build/ticket-delivery-enrollment.js +21 -8
  110. package/build/ticket-delivery-run-scope.js +128 -0
  111. package/build/version.generated.js +3 -3
  112. package/build/worker-guard-hook-bin.js +2 -2
  113. package/build/worktrees.js +105 -0
  114. package/docs/EPIC-IMPLEMENTER.md +5 -0
  115. package/docs/epic-implementer/getting-started.md +40 -15
  116. package/package.json +1 -1
@@ -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);
@@ -1,4 +1,4 @@
1
- import { renderWorkerVerificationGuidance, renderWorkerTimeBudgetGuidance } from "./worker-verification-guidance.js";
1
+ import { renderPreexistingAtBaseGuidance, renderWorkerVerificationGuidance, renderWorkerTimeBudgetGuidance, } from "./worker-verification-guidance.js";
2
2
  /**
3
3
  * Executor-side structured prompt-spec renderer (BAPI-550, TDD §6/§7).
4
4
  *
@@ -20,6 +20,7 @@ import { renderWorkerVerificationGuidance, renderWorkerTimeBudgetGuidance } from
20
20
  */
21
21
  import { CiFixContext, ExecutorNamedError } from "./job-errors.js";
22
22
  import { EPIC_WORKAROUNDS_DIR, epicWorkaroundRecordPath } from "../epic-workarounds-path.js";
23
+ import { WORKER_BACKGROUND_WORK_RULE } from "./required-work-diagnostics.js";
23
24
  /**
24
25
  * BAPI-1399 — the workaround contract for a PR-producing Epic Implementer worker.
25
26
  *
@@ -59,6 +60,12 @@ import { EPIC_WORKAROUNDS_DIR, epicWorkaroundRecordPath } from "../epic-workarou
59
60
  * classes, the persisted run policy, and a genuine pre-result missing
60
61
  * capability. Nothing converts an ordinary escalation into a hand-off.
61
62
  *
63
+ * BAPI-1552 appends one exception, only when `handoffEnabled === true`: a step
64
+ * that ran and failed may use `preexisting_at_base` when the same tests also fail
65
+ * at the base commit, with the base reproduction collected at the final head (see
66
+ * `renderPreexistingAtBaseGuidance`). Without that flag the text is byte-for-byte
67
+ * the BAPI-1544 instruction.
68
+ *
62
69
  * The worker decides from the ticket and the code alone; no supervisor scan
63
70
  * result is injected here. Kept SINGLE-LINE and free of `;`, quotes, and
64
71
  * apostrophes, like `buildPrBaseContractLaunchInstruction`, because it travels
@@ -115,7 +122,8 @@ export function buildEpicWorkaroundWorkerInstruction(ticketKey, handoffEnabled)
115
122
  "that escalated record and the workaround record written in the same job, and are recorded executed, " +
116
123
  "never handed off. A hand-off counts only at the head it observed, so a new head needs a fresh " +
117
124
  "observation. A step that already failed at one head can be handed off only from a new head, " +
118
- "never at the head where it failed.");
125
+ "never at the head where it failed." +
126
+ (handoffEnabled === true ? " " + renderPreexistingAtBaseGuidance(record) : ""));
119
127
  }
120
128
  /** Stable named-error kind used for every prompt-spec contract failure. */
121
129
  const PROMPT_CONTRACT_ERROR = "ContractError.Prompt";
@@ -779,7 +787,9 @@ export async function renderPromptSpecPrompt(job, context) {
779
787
  const values = await buildPromptSpecPlaceholderValues(job, spec, context);
780
788
  const systemPrompt = buildPromptSpecSystemPrompt(spec, values);
781
789
  const userPrompt = buildPromptSpecUserPrompt(spec, values);
782
- return `${systemPrompt}\n\n${userPrompt}` +
790
+ // BAPI-1554: every worker harness, not only the Claude held-stdin one, is told
791
+ // not to report a final result while its own background work is still running.
792
+ return `${systemPrompt}\n\n${userPrompt}\n\n${WORKER_BACKGROUND_WORK_RULE}` +
783
793
  (!context.deferComparisonGuidance && ["implement", "resume", "ci_fix"].includes(job.job_type)
784
794
  ? "\n\n" + renderWorkerVerificationGuidance(context.comparisonSha) : "") +
785
795
  (!context.deferComparisonGuidance && job.job_type === "ci_fix"
@@ -151,6 +151,34 @@ export function toCompletionCheckFact(fact) {
151
151
  duration_ms: Math.min(Math.max(0, Math.floor(fact.durationMs)), 2 * 60 * 60 * 1000),
152
152
  };
153
153
  }
154
+ /**
155
+ * Supplementary observation causes derived from declared-check facts. A timed-out
156
+ * check reports `check_timed_out`; a check that could not be started or never ran
157
+ * because of an interruption reports `check_not_runnable`. A check that exited
158
+ * zero, or exited non-zero (a real failure, not a capability shortfall), reports
159
+ * nothing: this function can never turn a failed or unrun check into a pass, and
160
+ * it does not decide anything about one.
161
+ */
162
+ export function observationsFromVerificationFacts(facts) {
163
+ if (!facts)
164
+ return [];
165
+ const out = [];
166
+ for (const command of facts.commands) {
167
+ let cause = null;
168
+ if (command.outcome === "timed_out" || command.reason === "declared_timeout") {
169
+ cause = "check_timed_out";
170
+ }
171
+ else if (command.outcome === "launch_error" ||
172
+ command.reason === "spawn_failed" ||
173
+ (command.outcome === "not_run" &&
174
+ (command.reason === "reservation_exhausted" || command.reason === "stopped_after_interruption"))) {
175
+ cause = "check_not_runnable";
176
+ }
177
+ if (cause !== null)
178
+ out.push({ check_identity: command.identity, cause });
179
+ }
180
+ return out;
181
+ }
154
182
  const FULL_SHA_RE = /^[0-9a-f]{40}$/;
155
183
  /**
156
184
  * Read full HEAD and the tracked tree/index state. Untracked files are not
@@ -0,0 +1,30 @@
1
+ /**
2
+ * Exhaustive over {@link TaskKind}: a new task kind fails to compile here until
3
+ * it is given a token, so a diagnostic can never silently drop a kind.
4
+ */
5
+ export const TASK_KIND_TO_DIAGNOSTIC_TOKEN = {
6
+ delegate: "background_agent",
7
+ delegate_bg: "background_agent",
8
+ bash_bg: "background_bash",
9
+ bash_task: "background_bash",
10
+ subagent_bash: "background_bash",
11
+ monitor: "monitor",
12
+ task: "required_task",
13
+ };
14
+ /** Sorted, de-duplicated diagnostic tokens for the given task kinds. */
15
+ export function requiredWorkKindTokens(kinds) {
16
+ const tokens = new Set();
17
+ for (const kind of kinds)
18
+ tokens.add(TASK_KIND_TO_DIAGNOSTIC_TOKEN[kind]);
19
+ return [...tokens].sort();
20
+ }
21
+ /** The closed diagnostic recorded when the completion window closed over running required work. */
22
+ export const COMPLETION_WINDOW_CLOSED_ON_LIVE_AGENT = "completion_window_closed_on_live_agent";
23
+ /**
24
+ * The completion-ordering rule every worker prompt carries (BAPI-1554). It is a
25
+ * rule about WHEN to report, not a demand to cancel productive background work:
26
+ * the worker either waits for what it started or stops it, then reports. Shared
27
+ * by the generic prompt assembly and the Claude held-stdin guidance, which
28
+ * composes it at most once.
29
+ */
30
+ export const WORKER_BACKGROUND_WORK_RULE = "Do not post a final result while a sub-agent or background task you started is still running; wait for it or stop it.";
@@ -44,6 +44,7 @@
44
44
  * targets are kept only as SHA-256 digests.
45
45
  */
46
46
  import { DELIVERY_RESOLVABLE_KINDS, DELIVERY_RESOLVABLE_STATES, MAX_DENIALS, MAX_EVENT_BYTES, MAX_TASKS, boundEnvelope, boundedIdentifier, deriveCompletionCause, digestStructured, isTaskResolved, runtimeMatchesSupported, successRefusalReason, COMPLETION_CONTRACT_VERSION, COMPLETION_CONTRACT_VERSION_V2, } from "./completion-contract.js";
47
+ import { requiredWorkKindTokens } from "./required-work-diagnostics.js";
47
48
  /**
48
49
  * A background command that fails this soon after its launch acknowledgement is
49
50
  * classified `failed_to_start` and resolves execution of a required task.
@@ -1037,6 +1038,19 @@ export function createRequiredWorkLedger(init) {
1037
1038
  else if (!bashBgIds.includes(o.taskId ?? o.key))
1038
1039
  bashBgIds.push(o.taskId ?? o.key);
1039
1040
  }
1041
+ const liveRequiredKinds = [];
1042
+ for (const o of obligations.values()) {
1043
+ if (isLive(o) && o.required)
1044
+ liveRequiredKinds.push(o.kind);
1045
+ }
1046
+ for (const tid of snap.required) {
1047
+ const o = findCurrentRunByTaskId(tid);
1048
+ // A task the obligations map already holds was counted above.
1049
+ if (!o)
1050
+ liveRequiredKinds.push("task");
1051
+ else if (!obligations.has(o.key))
1052
+ liveRequiredKinds.push(o.kind);
1053
+ }
1040
1054
  return {
1041
1055
  readyToClose,
1042
1056
  liveRequired,
@@ -1052,6 +1066,7 @@ export function createRequiredWorkLedger(init) {
1052
1066
  ...snap.required,
1053
1067
  ])]
1054
1068
  : [],
1069
+ liveRequiredKinds,
1055
1070
  };
1056
1071
  };
1057
1072
  // One predicate for "a required task is still pending", shared by the envelope
@@ -1241,6 +1256,9 @@ export function createClosureSupervisor(opts) {
1241
1256
  const close = (reason) => {
1242
1257
  if (closed || disposed)
1243
1258
  return;
1259
+ // BAPI-1554: capture what was running BEFORE anything below can change the
1260
+ // ledger, and freeze it so the later log and failure text cannot drift.
1261
+ const windowLiveKinds = Object.freeze(reason === "window" ? requiredWorkKindTokens(ledger.closureState().liveRequiredKinds) : []);
1244
1262
  closed = true;
1245
1263
  closedReason = reason;
1246
1264
  clearDebounce();
@@ -1260,7 +1278,7 @@ export function createClosureSupervisor(opts) {
1260
1278
  });
1261
1279
  if (reason === "window") {
1262
1280
  try {
1263
- opts.onWindowExpiry?.();
1281
+ opts.onWindowExpiry?.(windowLiveKinds);
1264
1282
  }
1265
1283
  catch {
1266
1284
  /* the caller's termination scheduling must never break closure */
@@ -162,6 +162,44 @@ export const CI_FIX_CHECK_CLAIMS_KEY = "check_fix_claims";
162
162
  export const CI_FIX_ATTRIBUTION_KEY = "ci_failure_attribution";
163
163
  export const CI_FIX_ATTRIBUTION_REASON_KEY = "ci_failure_attribution_reason";
164
164
  export const CI_FIX_ATTRIBUTION_EXTERNAL = "external";
165
+ export const CI_FIX_NO_PUSH_REASON_KEY = "no_push_reason";
166
+ export const CI_FIX_NO_PUSH_REASON_MAX_BYTES = 300;
167
+ /** Optional diagnostics are tolerant; unrelated artifact fields remain strict. */
168
+ export function normalizeCiFixNoPushReason(value) {
169
+ if (value === undefined || value === null)
170
+ return undefined;
171
+ const data = isPlainRecord(value) ? value : {};
172
+ const codes = ["not_reproducible", "external_failure", "already_fixed", "no_safe_change", "other"];
173
+ const reason = {
174
+ code: typeof data.code === "string" && codes.includes(data.code)
175
+ ? data.code : "other",
176
+ };
177
+ if (typeof data.text === "string") {
178
+ // Buffer replaces malformed surrogates; iterate code points when bounding.
179
+ let text = Buffer.from(data.text, "utf8").toString("utf8")
180
+ .replace(/[\s\u0085\u0000-\u001f\u007f-\u009f]+/gu, " ").trim();
181
+ text = text
182
+ .replace(/\b(authorization|cookie|set-cookie|x-api-key|x-bgpt-api-key|x-forge-oauth-system|x-forge-oauth-user)\b[ \t]*[:=][^\r\n]*/gi, "$1: [REDACTED]")
183
+ .replace(/\bBearer\s+\S+/gi, "Bearer [REDACTED]")
184
+ .replace(/\bBasic\s+\S+/gi, "Basic [REDACTED]")
185
+ .replace(/([\w.\-]*(?:token|api[-_]?key|secret|password|passwd|pwd)[\w.\-]*)\s*[:=]\s*\S+/gi, "$1=[REDACTED]")
186
+ .replace(/\b([a-z][a-z0-9+.\-]*:\/\/)[^\s:/@]+:[^\s/@]+@/gi, "$1[REDACTED]@")
187
+ .replace(/\b(?:sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, "[REDACTED]")
188
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{16,}/g, "[REDACTED]");
189
+ const originalBytes = byteLength(text);
190
+ const marker = originalBytes > CI_FIX_NO_PUSH_REASON_MAX_BYTES ? `…[truncated, was ${originalBytes} bytes]` : "";
191
+ const budget = CI_FIX_NO_PUSH_REASON_MAX_BYTES - byteLength(marker);
192
+ let bounded = "";
193
+ for (const point of text) {
194
+ if (byteLength(bounded + point) > budget)
195
+ break;
196
+ bounded += point;
197
+ }
198
+ if (bounded.trim() || marker)
199
+ reason.text = bounded.trimEnd() + marker;
200
+ }
201
+ return reason;
202
+ }
165
203
  /**
166
204
  * Executor-owned status of the artifact, carried at `result.check_fix_claims_status`
167
205
  * so an operator can tell "the worker wrote nothing" from "the worker wrote
@@ -170,6 +208,7 @@ export const CI_FIX_ATTRIBUTION_EXTERNAL = "external";
170
208
  */
171
209
  export const CI_FIX_CLAIMS_STATUS_KEY = "check_fix_claims_status";
172
210
  const CI_FIX_RESULT_ALLOWED_KEYS = new Set([
211
+ CI_FIX_NO_PUSH_REASON_KEY,
173
212
  CI_FIX_CHECK_CLAIMS_KEY,
174
213
  CI_FIX_ATTRIBUTION_KEY,
175
214
  CI_FIX_ATTRIBUTION_REASON_KEY,
@@ -254,6 +293,9 @@ export async function readCiFixResultArtifact(worktreePath, requiredChecks, deps
254
293
  validatedClaims[name] = value;
255
294
  }
256
295
  const fields = { [CI_FIX_CHECK_CLAIMS_KEY]: validatedClaims };
296
+ const noPushReason = normalizeCiFixNoPushReason(parsed[CI_FIX_NO_PUSH_REASON_KEY]);
297
+ if (noPushReason !== undefined)
298
+ fields[CI_FIX_NO_PUSH_REASON_KEY] = noPushReason;
257
299
  const hasAttribution = Object.prototype.hasOwnProperty.call(parsed, CI_FIX_ATTRIBUTION_KEY);
258
300
  const hasReason = Object.prototype.hasOwnProperty.call(parsed, CI_FIX_ATTRIBUTION_REASON_KEY);
259
301
  if (hasAttribution || hasReason) {
@@ -0,0 +1,42 @@
1
+ /**
2
+ * Filesystem-only discovery for locally installed executor service units.
3
+ *
4
+ * This deliberately neither consults install state nor runs a service manager:
5
+ * an uninstall must be able to show stale on-disk units without credentials or
6
+ * an active executor runtime.
7
+ */
8
+ import { readdir } from "node:fs/promises";
9
+ import { executorIdFromLaunchdFilename, executorIdFromSystemdFilename, executorLaunchdDirForHome, executorLaunchdPlistPathForId, executorSystemdDirForHome, executorSystemdUnitPathForId, validateExecutorId, } from "./service-unit.js";
10
+ const defaultDeps = { readdir };
11
+ /** Enumerate only convention-matching filenames in the fixed per-user directory. */
12
+ export async function discoverExecutorServiceUnits(platform, homeDir, deps = defaultDeps) {
13
+ if (platform !== "darwin" && platform !== "linux")
14
+ return { ok: false, reason: "unsupported-platform" };
15
+ const directory = platform === "darwin" ? executorLaunchdDirForHome(homeDir) : executorSystemdDirForHome(homeDir);
16
+ let names;
17
+ try {
18
+ names = await deps.readdir(directory);
19
+ }
20
+ catch (error) {
21
+ if (error.code === "ENOENT")
22
+ return { ok: true, units: [] };
23
+ return { ok: false, reason: "directory-unavailable" };
24
+ }
25
+ const parser = platform === "darwin" ? executorIdFromLaunchdFilename : executorIdFromSystemdFilename;
26
+ const pathFor = platform === "darwin" ? executorLaunchdPlistPathForId : executorSystemdUnitPathForId;
27
+ return {
28
+ ok: true,
29
+ units: names.flatMap((name) => {
30
+ const executorId = parser(name);
31
+ if (executorId) {
32
+ try {
33
+ validateExecutorId(executorId, platform);
34
+ }
35
+ catch {
36
+ return [];
37
+ }
38
+ }
39
+ return executorId ? [{ executorId, path: pathFor(executorId, homeDir), platform }] : [];
40
+ }).sort((a, b) => a.executorId.localeCompare(b.executorId)),
41
+ };
42
+ }