@bridge_gpt/mcp-server 0.2.75 → 0.2.77

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 (94) hide show
  1. package/README.md +8 -6
  2. package/build/agents.generated.js +5 -5
  3. package/build/cli-dispatch.js +333 -0
  4. package/build/codex-auto-recovery.js +25 -7
  5. package/build/commands.generated.js +8 -8
  6. package/build/conductor/bridge-api-client.js +193 -13
  7. package/build/conductor/declare-blocked.js +146 -7
  8. package/build/conductor/driver-pass.js +8 -0
  9. package/build/conductor/driver-register.js +8 -2
  10. package/build/conductor/epic-implementer-cli.js +15 -10
  11. package/build/conductor/epic-server-journal.js +52 -22
  12. package/build/conductor/epic-server-recipe.js +15 -5
  13. package/build/conductor/epic-server-runtime.js +163 -45
  14. package/build/conductor/epic-server.js +13 -6
  15. package/build/conductor/install-doctor.js +30 -2
  16. package/build/conductor/launch-plan.js +28 -7
  17. package/build/conductor/local-merge.js +55 -13
  18. package/build/conductor/pr-ci-producer.js +12 -3
  19. package/build/conductor/readiness-prerequisites.js +89 -2
  20. package/build/conductor/readiness-sections.js +46 -13
  21. package/build/conductor/readiness.js +3 -40
  22. package/build/conductor/recovery-cli.js +14 -12
  23. package/build/conductor/repository-workflow-remedy.js +147 -7
  24. package/build/conductor/ui-readiness.js +224 -0
  25. package/build/conductor/wait-run-attention.js +9 -4
  26. package/build/conductor/wait-run-cli.js +9 -2
  27. package/build/docs.generated.js +67 -4
  28. package/build/doctor.js +97 -1
  29. package/build/drive-epic.js +625 -33
  30. package/build/engine-paths.js +10 -0
  31. package/build/epic-coherence-input-cli.js +105 -10
  32. package/build/epic-coherence-input.js +877 -4
  33. package/build/epic-coherence-input.test-fixtures.js +117 -0
  34. package/build/epic-implementer-bin.js +947 -120
  35. package/build/epic-implementer-env.js +2 -2
  36. package/build/epic-launch-context.js +8 -1
  37. package/build/epic-shared/cut-protocol.js +55 -3
  38. package/build/executor/completion-contract.js +14 -1
  39. package/build/executor/failure-reason-codes.js +2 -0
  40. package/build/executor/guarded-fast-forward-push.js +25 -2
  41. package/build/executor/integration-job.js +56 -2
  42. package/build/executor/job-runner.js +87 -28
  43. package/build/executor/likely-tests.js +78 -6
  44. package/build/executor/merge-job.js +45 -1
  45. package/build/executor/permissions.js +187 -2
  46. package/build/executor/provider-checks.js +101 -5
  47. package/build/executor/rebase-finalization.js +29 -27
  48. package/build/executor/reconcile-overlap-job.js +70 -17
  49. package/build/executor/rename-aside.js +265 -0
  50. package/build/executor/required-work-ledger.js +89 -6
  51. package/build/executor/resume-pre-spawn.js +32 -8
  52. package/build/executor/runner.js +26 -4
  53. package/build/executor/types.js +121 -0
  54. package/build/executor/worktree.js +39 -2
  55. package/build/index.js +2500 -495
  56. package/build/init.js +16 -0
  57. package/build/install-bridge-conductor-answers.js +4 -0
  58. package/build/install-bridge-conductor-apply.js +10 -0
  59. package/build/install-bridge-conductor-assessment.js +84 -0
  60. package/build/install-bridge-conductor-contracts.js +9 -1
  61. package/build/install-bridge-conductor-setup.js +103 -3
  62. package/build/install-bridge-conductor.js +440 -812
  63. package/build/install-bridge.js +4 -11
  64. package/build/language-catalog.generated.js +2649 -0
  65. package/build/mcp-host-config.js +54 -37
  66. package/build/phase-context-git-probe.js +16 -0
  67. package/build/pipelines.generated.js +47 -19
  68. package/build/plan-execution-ledger.js +35 -0
  69. package/build/plan-generation.js +34 -0
  70. package/build/plane/build-freshness.js +6 -0
  71. package/build/plane/cli.js +12 -5
  72. package/build/plane/plane-freshness.js +43 -26
  73. package/build/printed-remedy-commands.js +17 -0
  74. package/build/readiness-prerequisites.generated.js +28 -0
  75. package/build/readme.generated.js +1 -1
  76. package/build/run-unit-tests-launcher.js +3 -1
  77. package/build/secret-redaction.js +3 -0
  78. package/build/server.js +7946 -0
  79. package/build/setup-epic.js +41 -8
  80. package/build/start-tickets-prereqs.js +3 -6
  81. package/build/test-support/console-guard.js +30 -0
  82. package/build/test-support/create-preview-world.js +232 -0
  83. package/build/test-support/module-imports.js +155 -0
  84. package/build/test-support/server-client.js +96 -0
  85. package/build/test-support/stdio-server.js +146 -0
  86. package/build/ticket-delivery.js +65 -0
  87. package/build/v2-readiness-requirements.js +39 -5
  88. package/build/version.generated.js +3 -3
  89. package/build/worktree-core.js +51 -7
  90. package/docs/EPIC-IMPLEMENTER.md +150 -2
  91. package/docs/epic-implementer/getting-started.md +5 -1
  92. package/package.json +3 -3
  93. package/pipelines/implement-ticket.json +2 -2
  94. package/pipelines/learn-repository.json +19 -1
@@ -0,0 +1,146 @@
1
+ /**
2
+ * Run the real MCP server bin over stdio against a local HTTP backend.
3
+ *
4
+ * For rules that live in `startServer()` (index scope, the project-root line,
5
+ * `roots/list` after connect, stdout reserved for the protocol), a test needs
6
+ * the whole entry point, not an imported module. This spawns `build/index.js`
7
+ * with `BAPI_BASE_URL` pointed at an in-process HTTP server that records every
8
+ * request, then speaks newline-delimited JSON-RPC on the child's stdio.
9
+ */
10
+ import { spawn } from "node:child_process";
11
+ import { createServer } from "node:http";
12
+ import path from "node:path";
13
+ const BIN = path.join(import.meta.dirname, "..", "index.js");
14
+ async function startBackend(record, respond) {
15
+ const server = createServer((req, res) => {
16
+ const chunks = [];
17
+ req.on("data", (chunk) => chunks.push(chunk));
18
+ req.on("end", () => {
19
+ const raw = Buffer.concat(chunks).toString("utf8");
20
+ let body = raw;
21
+ try {
22
+ body = raw ? JSON.parse(raw) : undefined;
23
+ }
24
+ catch {
25
+ body = raw;
26
+ }
27
+ const url = new URL(req.url ?? "/", "http://backend.test");
28
+ const request = {
29
+ method: req.method ?? "GET",
30
+ path: url.pathname,
31
+ query: url.searchParams,
32
+ headers: req.headers,
33
+ body,
34
+ };
35
+ record.push(request);
36
+ const answer = respond(request) ?? {};
37
+ res.writeHead(answer.status ?? 200, { "content-type": "application/json" });
38
+ res.end(JSON.stringify(answer.body ?? {}));
39
+ });
40
+ });
41
+ await new Promise((resolve) => server.listen(0, "127.0.0.1", resolve));
42
+ return server;
43
+ }
44
+ export async function startStdioServer(options = {}) {
45
+ const backend = [];
46
+ const http = await startBackend(backend, options.respond ?? (() => undefined));
47
+ const port = http.address().port;
48
+ const child = spawn(process.execPath, [BIN], {
49
+ env: {
50
+ ...process.env,
51
+ BAPI_BASE_URL: `http://127.0.0.1:${port}`,
52
+ BAPI_REPO_NAME: "stdio-server-repo",
53
+ BAPI_API_KEY: "stdio-server-sentinel-key",
54
+ BAPI_MCP_UPDATE_CHECK_ENABLED: "false",
55
+ BAPI_MCP_TOOL_SURFACE_GATING_ENABLED: "false",
56
+ ...options.env,
57
+ },
58
+ stdio: ["pipe", "pipe", "pipe"],
59
+ });
60
+ let stdout = "";
61
+ let stderr = "";
62
+ const lines = [];
63
+ const pending = new Map();
64
+ const clientRequests = [];
65
+ let nextId = 1;
66
+ const send = (message) => child.stdin.write(JSON.stringify(message) + "\n");
67
+ child.stdout.on("data", (chunk) => {
68
+ stdout += chunk.toString("utf8");
69
+ let newline;
70
+ while ((newline = stdout.indexOf("\n")) >= 0) {
71
+ const line = stdout.slice(0, newline);
72
+ stdout = stdout.slice(newline + 1);
73
+ if (!line)
74
+ continue;
75
+ lines.push(line);
76
+ let message;
77
+ try {
78
+ message = JSON.parse(line);
79
+ }
80
+ catch {
81
+ continue;
82
+ }
83
+ if (message.method && message.id !== undefined) {
84
+ // A request from the server to this client.
85
+ clientRequests.push(message.method);
86
+ if (message.method === "roots/list") {
87
+ send({ jsonrpc: "2.0", id: message.id, result: { roots: options.roots ?? [] } });
88
+ }
89
+ else {
90
+ send({ jsonrpc: "2.0", id: message.id, result: {} });
91
+ }
92
+ }
93
+ else if (message.id !== undefined && pending.has(message.id)) {
94
+ const waiter = pending.get(message.id);
95
+ pending.delete(message.id);
96
+ if (message.error)
97
+ waiter.reject(new Error(JSON.stringify(message.error)));
98
+ else
99
+ waiter.resolve(message.result);
100
+ }
101
+ }
102
+ });
103
+ child.stderr.on("data", (chunk) => {
104
+ stderr += chunk.toString("utf8");
105
+ });
106
+ child.on("exit", () => {
107
+ for (const waiter of pending.values())
108
+ waiter.reject(new Error(`server exited: ${stderr}`));
109
+ pending.clear();
110
+ });
111
+ const handle = {
112
+ backend,
113
+ clientRequests,
114
+ request(method, params) {
115
+ const id = nextId++;
116
+ return new Promise((resolve, reject) => {
117
+ pending.set(id, { resolve, reject });
118
+ send({ jsonrpc: "2.0", id, method, params });
119
+ setTimeout(() => {
120
+ if (pending.delete(id))
121
+ reject(new Error(`timed out waiting for ${method}; stderr: ${stderr}`));
122
+ }, 20_000).unref();
123
+ });
124
+ },
125
+ notify(method, params) {
126
+ send({ jsonrpc: "2.0", method, params });
127
+ },
128
+ stdoutLines: () => [...lines],
129
+ stderr: () => stderr,
130
+ async close() {
131
+ child.kill();
132
+ await new Promise((resolve) => http.close(() => resolve()));
133
+ },
134
+ };
135
+ return handle;
136
+ }
137
+ /** `initialize` + `notifications/initialized`, with roots support declared. */
138
+ export async function initialize(server, clientName = "stdio-server-test") {
139
+ const result = await server.request("initialize", {
140
+ protocolVersion: "2025-06-18",
141
+ capabilities: { roots: { listChanged: false } },
142
+ clientInfo: { name: clientName, version: "0.0.0" },
143
+ });
144
+ server.notify("notifications/initialized");
145
+ return result;
146
+ }
@@ -13,6 +13,71 @@
13
13
  */
14
14
  import { redactSecrets } from "./secret-redaction.js";
15
15
  export const READINESS_BOUNDARIES = ["publish", "merge", "complete"];
16
+ // ---------------------------------------------------------------------------
17
+ // Presentation: a draft opened because verification gaps are recorded (BAPI-1712)
18
+ // ---------------------------------------------------------------------------
19
+ /** The server's publication reason for a draft opened over admitted gaps. */
20
+ export const PUBLICATION_REASON_VERIFICATION_GAPS = "verification_gaps_recorded";
21
+ const GAP_DRAFT_MESSAGE = "A draft pull request is the successful publication for this run. It is not a hold " +
22
+ "and not proof that verification passed: the recorded gaps stay unverified and are " +
23
+ "disclosed in the PR body's managed Unverified gaps section. Continue the recipe.";
24
+ function isPlainRecord(value) {
25
+ return value !== null && typeof value === "object" && !Array.isArray(value);
26
+ }
27
+ /**
28
+ * The gap-draft note for a readiness view, or `undefined` for any other outcome.
29
+ *
30
+ * Presentation only: it reads the server's publication decision and never decides
31
+ * anything. It applies when the action is `draft_pr` and either the reason is
32
+ * `verification_gaps_recorded` or readiness lists recorded gaps (an explicit draft
33
+ * request can change the reason the server reports).
34
+ */
35
+ export function gapDraftPublicationNote(readiness) {
36
+ if (!isPlainRecord(readiness))
37
+ return undefined;
38
+ const publication = readiness.publication;
39
+ if (!isPlainRecord(publication) || publication.action !== "draft_pr")
40
+ return undefined;
41
+ const gaps = Array.isArray(readiness.recorded_gaps)
42
+ ? readiness.recorded_gaps
43
+ : undefined;
44
+ const reason = typeof publication.reason === "string" ? publication.reason : "";
45
+ if (reason !== PUBLICATION_REASON_VERIFICATION_GAPS && !(gaps && gaps.length > 0)) {
46
+ return undefined;
47
+ }
48
+ const disclosure = readiness.disclosure;
49
+ const markdown = isPlainRecord(disclosure) && typeof disclosure.markdown === "string" ? disclosure.markdown : undefined;
50
+ return {
51
+ outcome: "draft_published_with_verification_gaps",
52
+ published: true,
53
+ held: false,
54
+ verification_complete: false,
55
+ reason,
56
+ message: GAP_DRAFT_MESSAGE,
57
+ ...(gaps ? { recorded_gaps: gaps } : {}),
58
+ ...(markdown !== undefined ? { disclosure_markdown: markdown } : {}),
59
+ };
60
+ }
61
+ /**
62
+ * Annotate a successful `create_pull_request` reply (`detail.delivery` is the
63
+ * readiness view) with the gap-draft note. Any other reply, or text that is not
64
+ * a JSON object, is returned byte for byte.
65
+ */
66
+ export function annotateGapDraftPublication(text) {
67
+ let parsed;
68
+ try {
69
+ parsed = JSON.parse(text);
70
+ }
71
+ catch {
72
+ return text;
73
+ }
74
+ if (!isPlainRecord(parsed) || !isPlainRecord(parsed.detail))
75
+ return text;
76
+ const note = gapDraftPublicationNote(parsed.detail.delivery);
77
+ if (!note)
78
+ return text;
79
+ return JSON.stringify({ ...parsed, publication_outcome: note }, null, 2);
80
+ }
16
81
  const STATUS_CODES = {
17
82
  400: "BAD_REQUEST",
18
83
  401: "UNAUTHORIZED",
@@ -1,4 +1,4 @@
1
- import { mergeReadinessPrerequisites, formatReadinessPrerequisites } from "./conductor/readiness-prerequisites.js";
1
+ import { overlayReadinessPrerequisites, formatReadinessPrerequisites } from "./conductor/readiness-prerequisites.js";
2
2
  import { READINESS_PREREQUISITE_BY_ID, READINESS_LEGACY_IDS } from "./readiness-prerequisites.generated.js";
3
3
  import { indexedWorkflowsDisplayRemedy } from "./printed-remedy-commands.js";
4
4
  /**
@@ -25,7 +25,7 @@ import { indexedWorkflowsDisplayRemedy } from "./printed-remedy-commands.js";
25
25
  * names (from the dependency-free `conductor/merge-credential.ts`), nothing else.
26
26
  */
27
27
  import { gateProfileWaivesCiWorkflow, isProviderRepositoryIdentity, } from "./conductor/bridge-api-client.js";
28
- import { repositoryWorkflowRemedy } from "./conductor/repository-workflow-remedy.js";
28
+ import { repositoryReadinessVerdict, repositoryWorkflowRemedy, } from "./conductor/repository-workflow-remedy.js";
29
29
  import { LOCAL_MERGE_CREDENTIAL_ENV_KEYS } from "./conductor/merge-credential.js";
30
30
  import { createReadinessCheckSafely } from "./readiness-check.js";
31
31
  /**
@@ -138,7 +138,13 @@ const LEGACY_V2_READINESS_REQUIREMENTS = [
138
138
  // profile is never told to add a file it does not need. Gate-profile WARNINGS
139
139
  // (epic-branch rows) are not requirements and are never read here.
140
140
  remedyFor: (r) => repositoryWorkflowRemedy(gateProfileWaivesCiWorkflow(r) ? { ...r, conductor_ci_workflow: null } : r),
141
- satisfied: (r) => r.unattended?.repository_readiness_confirmed === true,
141
+ // BAPI-1714: only a PROVEN deficiency refuses. The verdict is `denied` when
142
+ // the server's aggregate flag is false AND its `repository_readiness`
143
+ // admission record says denied; an unverifiable read is `unknown` and passes
144
+ // here (first approval re-checks it). This replaces the client-side override
145
+ // that used to bypass this predicate whenever the server sent prerequisites,
146
+ // which is why preview was green while create refused.
147
+ satisfied: (r) => repositoryReadinessVerdict(r) !== "denied",
142
148
  },
143
149
  // BAPI-1135 — merge-execution eligibility is deliberately NOT a requirement here.
144
150
  //
@@ -168,6 +174,11 @@ const LEGACY_V2_READINESS_REQUIREMENTS = [
168
174
  const LAUNCH_ONLY_BLOCKING_IDS = [
169
175
  { id: 'server.escalation-webhook-reachable', unattendedOnly: true },
170
176
  { id: 'server.provider-default-branch-readable', unattendedOnly: false },
177
+ // BAPI-1747 — the server's merge-authority finding. Only a row the server projects
178
+ // `not_met` + `blocking` (the proven universal merge denial) refuses; a warning,
179
+ // unknown, or absent row (an older server) never does. The four warning-only
180
+ // run-path IDs deliberately have no requirement here.
181
+ { id: 'server.resolved-merge-mode', unattendedOnly: false },
171
182
  ];
172
183
  const NEW_IDS = ['server.indexed-workflows', 'server.unattended-notify-default'];
173
184
  export const V2_READINESS_REQUIREMENTS = [
@@ -176,7 +187,6 @@ export const V2_READINESS_REQUIREMENTS = [
176
187
  const descriptor = READINESS_PREREQUISITE_BY_ID.get(id);
177
188
  return { ...req, id, describe: descriptor?.label ?? req.describe,
178
189
  governedRowIds: req.governedRowIds.map(row => READINESS_LEGACY_IDS[row] ?? row),
179
- ...(req.id === 'repository_readiness' ? { satisfied: (r) => r.prerequisites !== undefined ? true : req.satisfied(r) } : {}),
180
190
  ...(req.id === 'unattended_notify_default' ? {
181
191
  satisfied: (r) => !r.prerequisites?.some(p => p.id === id && p.check_status === 'not_met' && p.impact === 'blocking'),
182
192
  remedyFor: (r) => r.prerequisites?.find(p => p.id === id)?.fix ?? 'Retry readiness.',
@@ -472,6 +482,12 @@ export function unattendedPostureCheck(readiness) {
472
482
  /** The resolved merge mode, as a supporting fact. Absent or null is a warning, never a default. */
473
483
  export function resolvedMergeModeCheck(readiness) {
474
484
  const base = { id: RESOLVED_MERGE_MODE_ROW_ID, source: "server", label: "Resolved merge mode" };
485
+ // BAPI-1747 — a server that reports its own merge-authority row is authoritative,
486
+ // as `mergeReadinessPrerequisites` already treats server rows. With no such row
487
+ // (an older server) the client-built row below is unchanged.
488
+ const serverRow = readiness.prerequisites?.find((p) => p.id === RESOLVED_MERGE_MODE_ROW_ID);
489
+ if (serverRow !== undefined)
490
+ return resolvedMergeModeFromServerRow(base, serverRow, readiness.resolved_merge_execution_mode);
475
491
  const mode = readiness.resolved_merge_execution_mode;
476
492
  if (mode === undefined) {
477
493
  return createReadinessCheckSafely({
@@ -491,6 +507,24 @@ export function resolvedMergeModeCheck(readiness) {
491
507
  }
492
508
  return createReadinessCheckSafely({ ...base, status: "pass", detail: `a new run merges in ${mode} mode` });
493
509
  }
510
+ function resolvedMergeModeFromServerRow(base, row, mode) {
511
+ const names = (row.findings ?? []).map((f) => f.reason).join(", ");
512
+ const suffix = names ? ` (${names})` : "";
513
+ if (row.check_status === "met") {
514
+ return createReadinessCheckSafely({ ...base, status: "pass", detail: typeof mode === "string" ? `a new run merges in ${mode} mode` : "the server confirmed merge authority" });
515
+ }
516
+ if (row.check_status === "not_applicable") {
517
+ return createReadinessCheckSafely({ ...base, status: "skip", detail: "merge authority does not apply to this launch" });
518
+ }
519
+ const remediation = row.fix ? { remediation: row.fix } : {};
520
+ if (row.check_status === "not_met" && row.impact === "blocking") {
521
+ return createReadinessCheckSafely({ ...base, status: "fail", detail: `the server would refuse every merge for this launch${suffix}`, ...remediation });
522
+ }
523
+ if (row.check_status === "not_met") {
524
+ return createReadinessCheckSafely({ ...base, status: "warn", detail: `the server reported a merge-authority gap${suffix}`, ...remediation });
525
+ }
526
+ return createReadinessCheckSafely({ ...base, status: "warn", detail: `Capability not verified: the server could not check merge authority${suffix}`, ...remediation });
527
+ }
494
528
  /** The provider repository, as a supporting fact. */
495
529
  export function providerRepositoryCheck(readiness) {
496
530
  const base = { id: PROVIDER_REPOSITORY_ROW_ID, source: "server", label: "Provider repository" };
@@ -579,5 +613,5 @@ export function readinessApplicabilityLabel(check) {
579
613
  }
580
614
  /** Render the compact launch summary drive-epic prints before creating a run. */
581
615
  export function formatLaunchReadinessSummary(checks, options = {}) {
582
- return formatReadinessPrerequisites(mergeReadinessPrerequisites(checks, options.prerequisites), options);
616
+ return formatReadinessPrerequisites(overlayReadinessPrerequisites(checks, options.prerequisites, options.toolVisibility), options);
583
617
  }
@@ -1,4 +1,4 @@
1
1
  // AUTO-GENERATED — do not edit manually. Regenerate with: npm run build
2
- export const VERSION = "0.2.75";
3
- export const BUILD_COMMIT = "e66184422c92";
4
- export const LAUNCHER_ARGS = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.75", "serve"];
2
+ export const VERSION = "0.2.77";
3
+ export const BUILD_COMMIT = "dae84fcf944a";
4
+ export const LAUNCHER_ARGS = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.77", "serve"];
@@ -285,14 +285,58 @@ export async function isExistingBranchSafeToReuse(deps, branch, baseStartPoint,
285
285
  * success or a bounded, secret-free `create-failed` error string on failure.
286
286
  * Shared by the recovery freshen path and the BAPI-586 fresh-dispatch alignment.
287
287
  */
288
- async function hardResetWorktree(deps, worktreePath, ref) {
288
+ async function hardResetWorktree(deps, worktreePath, ref, lockRetryRemainingMs) {
289
289
  const resetArgs = ["reset", "--hard", ref];
290
- const reset = await deps.runCommand("git", resetArgs, { cwd: worktreePath });
291
- if (!commandSucceeded(reset)) {
290
+ const clock = deps.now ?? (() => performance.now());
291
+ const pause = deps.sleep ?? ((ms) => new Promise((resolve) => setTimeout(resolve, ms)));
292
+ const preparationAllowance = () => lockRetryRemainingMs ? lockRetryRemainingMs() - RESET_PREPARATION_MARGIN_MS : RESET_LOCK_RETRY_CAP_MS;
293
+ const initialBudget = Math.max(0, Math.min(RESET_LOCK_RETRY_CAP_MS, preparationAllowance()));
294
+ const startedAt = clock();
295
+ const remaining = () => Math.max(0, Math.min(initialBudget - (clock() - startedAt), preparationAllowance()));
296
+ let nextPauseMs = RESET_LOCK_INITIAL_PAUSE_MS;
297
+ let previousFailure = "";
298
+ for (let attempt = 1;; attempt += 1) {
299
+ const allowance = remaining();
300
+ // The first attempt always runs, even with no allowance left.
301
+ if (attempt > 1 && allowance <= 0)
302
+ return previousFailure;
303
+ const reset = await deps.runCommand("git", resetArgs, {
304
+ cwd: worktreePath,
305
+ timeoutMs: Math.max(1, allowance),
306
+ });
307
+ if (commandSucceeded(reset))
308
+ return null;
292
309
  const reason = (reset.stderr || reset.stdout || "").trim();
293
- return `git ${resetArgs.join(" ")} failed${reason ? `: ${reason}` : ""}`;
310
+ previousFailure = `git ${resetArgs.join(" ")} failed${reason ? `: ${reason}` : ""}`;
311
+ // Classify the raw output, before any diagnostic formatting. Only the final
312
+ // failure is returned; earlier output is never accumulated.
313
+ if (!isRetryableLockFailure(`${reset.stderr ?? ""}\n${reset.stdout ?? ""}`))
314
+ return previousFailure;
315
+ const pauseFor = Math.min(nextPauseMs, remaining());
316
+ if (pauseFor <= 0)
317
+ return previousFailure;
318
+ await pause(pauseFor);
319
+ nextPauseMs = Math.min(nextPauseMs * 2, RESET_LOCK_MAX_PAUSE_MS);
294
320
  }
295
- return null;
321
+ }
322
+ /** BAPI-1742: reset lock retry limits. Implementation details, not user configuration. */
323
+ const RESET_LOCK_RETRY_CAP_MS = 60_000;
324
+ const RESET_PREPARATION_MARGIN_MS = 5_000;
325
+ const RESET_LOCK_INITIAL_PAUSE_MS = 250;
326
+ const RESET_LOCK_MAX_PAUSE_MS = 5_000;
327
+ /**
328
+ * BAPI-1742: true only for Git's English lock-contention message: a path token that
329
+ * ends exactly in `.lock` AND the text `File exists`. Localized lock messages,
330
+ * permission errors, corrupt objects, unknown refs and every other failure keep the
331
+ * single-attempt behavior. The process locale is not changed to widen this match,
332
+ * and the retry never inspects, deletes, or renames a lock file.
333
+ */
334
+ function isRetryableLockFailure(rawOutput) {
335
+ if (!rawOutput.includes("File exists"))
336
+ return false;
337
+ return rawOutput
338
+ .split(/[\s'"`:]+/)
339
+ .some((token) => token.length > ".lock".length && token.endsWith(".lock"));
296
340
  }
297
341
  /** The one fixed, sanitized diagnostic emitted for ANY cleanup failure. */
298
342
  const CLEANUP_FAILURE_DIAGNOSTIC = "untracked-file cleanup did not complete; continuing with the reset worktree";
@@ -456,7 +500,7 @@ export async function createWorktreeForTicket(deps, key, branchOverrides, worktr
456
500
  const selected = await resetTarget(behavior.freshenFromOrigin);
457
501
  if (!selected.ok)
458
502
  return { key, branch, status: "create-failed", error: selected.error };
459
- const resetError = await hardResetWorktree(deps, worktreePath, selected.target);
503
+ const resetError = await hardResetWorktree(deps, worktreePath, selected.target, behavior.lockRetryRemainingMs);
460
504
  if (resetError) {
461
505
  return { key, branch, status: "create-failed", error: resetError };
462
506
  }
@@ -475,7 +519,7 @@ export async function createWorktreeForTicket(deps, key, branchOverrides, worktr
475
519
  const selected = await resetTarget(behavior.alignExistingBranchTo);
476
520
  if (!selected.ok)
477
521
  return { key, branch, status: "create-failed", error: selected.error };
478
- const resetError = await hardResetWorktree(deps, worktreePath, selected.target);
522
+ const resetError = await hardResetWorktree(deps, worktreePath, selected.target, behavior.lockRetryRemainingMs);
479
523
  if (resetError) {
480
524
  return { key, branch, status: "create-failed", error: resetError };
481
525
  }
@@ -110,6 +110,73 @@ is created, and `drive-epic --dry-run` lists them:
110
110
  | An escalation channel | A `--policy-file` that declares `notify.webhook_url`, **or** an email address on the account. `notify.local_sink` does not count. |
111
111
  | Repository readiness | `.github/workflows/epic-implementer-ci.yml` confirmed on the default branch, plus `.github/workflows/claude-review.yml` when the run uses AI review (`verdict_protocol`). A first-approval feature-branch run with no policy set needs no review workflow. The refusal names what is missing. |
112
112
 
113
+ **What blocks, and what only warns.** Only a *proven* gap in the review or CI
114
+ workflow blocks a new unattended run. If Bridge cannot read the workflows, the
115
+ preview prints a warning and continues:
116
+
117
+ ```text
118
+ Repository workflows could not be verified. Preview continues; first approval will re-check them and may refuse if they remain unverifiable.
119
+ ```
120
+
121
+ First approval has the final say, so a run created after that warning can still be
122
+ refused there. A missing `run-id:` or `Reviewed-SHA:` marker is named once, with
123
+ three ways out. Switch the review default:
124
+
125
+ ```bash
126
+ npx -y @bridge_gpt/mcp-server install epic-implementer --review-policy repository_policy
127
+ ```
128
+
129
+ Or add the markers to `.github/workflows/claude-review.yml`, or pass `--attended`.
130
+ To see exactly what is missing, run:
131
+
132
+ ```bash
133
+ npx -y @bridge_gpt/mcp-server epic-implementer readiness
134
+ ```
135
+
136
+ **Resuming setup.** If a run is still `planning` and the server holds the epic's
137
+ plan, `drive-epic` finishes setup for that run instead of attaching to it. A run
138
+ that is already approved or later is attached to as before, and is not re-checked
139
+ against the repository workflows.
140
+
141
+ **Fresh installs.** `install epic-implementer` stores `verdict_protocol` as the
142
+ review default only when Bridge read `.github/workflows/claude-review.yml`, the file
143
+ exists, and it emits both markers. Otherwise it stores `repository_policy`. Pass
144
+ `--review-policy verdict_protocol` to opt in anyway; setup then offers to write the
145
+ workflow. A default you already stored is never changed.
146
+
147
+ **Upgrading.** A launch snapshot written before this change can hold a stale
148
+ "workflow missing" answer. It expires after ten minutes, so at most one launch that
149
+ spans the upgrade is affected; run it again. Deploy the server before publishing the
150
+ MCP package.
151
+
152
+ **Required checks, refused before create.** When the launch report for
153
+ the policy you are about to create says first approval would refuse its required
154
+ checks (for example, a stored local gate that is not qualified for its current
155
+ revision), `drive-epic --dry-run` refuses with `server.admission-required-checks`,
156
+ names the server's reason code, and prints the remedy, such as qualifying the gate
157
+ with `npx -y @bridge_gpt/mcp-server install epic-implementer --qualify-gate`. A real
158
+ create refuses the same way with `setup-epic REFUSED (required_checks_admission_denied)`
159
+ and ends with `No run was created.` Only a proven denial from the stored gate profile
160
+ refuses (an unqualified local command, a provider check that never reported, or a missing
161
+ migration guard). An unreadable
162
+ report, or a record the server could not verify, continues, and first approval stays
163
+ the authority. A policy that approval exempts (`--attended`, auto-merge off, an
164
+ operator `no_ci_gate` on a provider gate) is never refused. Re-attaching to a live
165
+ run is never refused.
166
+
167
+ **The auto-merge forecast.** The preview's `Auto-merge:` line also says
168
+ what first approval's CI-gate stamp will do, when that differs from what the run
169
+ asks for. For example:
170
+
171
+ ```text
172
+ Auto-merge into epic/PROJ-1: on (the server confirms at approval); first approval will require merge approval (local_gate_verification_disabled)
173
+ ```
174
+
175
+ It may instead end with `; kept at first approval (<reason ids>)`. When the server
176
+ cannot tell, or nothing changes, the line is unchanged. The `--json` document carries
177
+ the same facts in `summary.auto_merge.forecast`. The forecast is advisory: it never
178
+ changes the decision.
179
+
113
180
  **Merge-execution eligibility.** If the repository cannot perform a merge without
114
181
  a standing write credential, `setup-epic` refuses with
115
182
  `merge_execution_ineligible`, names the remedy
@@ -184,6 +251,64 @@ npx -y @bridge_gpt/mcp-server executor --repo <name> --epic-run-id <id>
184
251
 
185
252
  Owners who run their own Bridge server have extra steps. Run `npx -y @bridge_gpt/mcp-server drive-epic --help-advanced` to read them.
186
253
 
254
+ ## Test pruning and checked-once evidence
255
+
256
+ Workers now remove edit-confirmation tests that their own change made pointless,
257
+ and they leave a record of what they removed and what they checked once.
258
+
259
+ **Touched-code-only pruning.** A worker looks only at tests for code the ticket
260
+ changed. It finds candidates by source file name and imports first, then by
261
+ targeted searches in those test paths. It never scans the whole repository.
262
+
263
+ **Assertion-level safeguards.** Each assertion is judged on its own. A search match
264
+ is only a candidate. The worker removes an assertion only when it is an
265
+ edit-confirmation pin: a check that text, source, a count, or a copy's bytes match
266
+ what an edit wrote, with no runtime code, parser, protocol, or invariant using that
267
+ value. These are never treated as pins: parsed headers, JSON keys and tool names;
268
+ protocol and CLI envelopes; security and architecture guards; migration and registry
269
+ invariants; counts that are data; API shape, status codes, data and state. A test
270
+ file that a plan step names for writing or updating is never deleted whole.
271
+
272
+ **Behavioral protection.** If a pin is the only behavioral protection, the worker
273
+ first adds a replacement behavioral test that passes. If it cannot, it keeps the
274
+ pin and updates it. A worker never changes a valid expectation to accept broken
275
+ behavior.
276
+
277
+ **Opt-out and customer requests.** Each test step in a plan ends with a deletion
278
+ line. If your repository's unit-testing instructions say `never delete tests`, the
279
+ line reads `Test deletion: not allowed (repository instruction)` and nothing is
280
+ deleted. A missing, conflicting, or unreadable line also means no deletion. If you
281
+ ask for a specific assertion, it is protected even when general deletion is
282
+ allowed.
283
+
284
+ ### Two pull request sections
285
+
286
+ Every pull request description carries two sections, rebuilt from durable records
287
+ (the branch diff, commit bodies, and the phase-result ledger), never from memory:
288
+
289
+ - `## Tests removed` lists each file, test or assertion, action (`deleted` or
290
+ `updated`), and reason. It reads `None` when there are no entries.
291
+ - `## Checked once` lists each run-once check with its command, the full commit SHA
292
+ it checked, and the outcome. It reads `None` when there are no entries. A failed
293
+ check is shown as failed. An unavailable one is shown as a named gap. An earlier
294
+ pass is marked as historical, so it never looks like it covers a later commit.
295
+
296
+ ### Run-once checks and honest failures
297
+
298
+ Some plan steps are one-time facts the diff cannot show, such as rendering the
299
+ migration SQL offline. The worker runs the targeted command once and commits no test
300
+ for it. If the environment is unavailable, the step is disclosed through the
301
+ existing hand-off. If the command runs and fails, that is a failure, not a gap.
302
+ Renewal happens only in a safe, disposable environment, and a state-changing
303
+ command is never blindly repeated.
304
+
305
+ ### Where actions are reported
306
+
307
+ Automated `ci_fix` repair reports its updated and deleted tests in its result file
308
+ and in its fix commit body. It does not edit the pull request description.
309
+ Interactive and post-PR corrections list them in the correction commit body and
310
+ refresh the two pull request sections.
311
+
187
312
  ## The CI gate
188
313
 
189
314
  Each ticket's `ci` gate reads `policy_json.required_checks` and waits for those
@@ -263,6 +388,17 @@ policy is a no-op. A different one is refused with a redacted diff unless you ad
263
388
  branches other than same-repository `feature/BAPI-*` and `epic/**` get an
264
389
  immediate green. That is cost control, not proof the suites ran.
265
390
 
391
+ ### Failing assertions: stale pin or real defect
392
+
393
+ Before a `ci_fix` job repairs a failing assertion, it reads the ticket's existing
394
+ plan once (`get_plan`; this is a read, not a new plan) and sorts the failure. A stale
395
+ pin is a text, source, count, or copy-byte expectation the ticket deliberately
396
+ changed. It may be deleted only with clear deletion permission, and otherwise is
397
+ updated. A failure in a protected contract category, including API shape, status
398
+ codes, data and state, is a production defect or a contract, so the worker repairs
399
+ production code instead. The repair stays bounded as before: the same rounds, the
400
+ same result format, and no new stop.
401
+
266
402
  ## Plan metadata: `touched_files`
267
403
 
268
404
  **Plan-time file-overlap serialization is on by default**
@@ -376,6 +512,18 @@ Epic Implementer. It runs a read-only doctor first, then asks for consent before
376
512
  each write: the supervisor project defaults, an optional `claude-review` workflow,
377
513
  adding `epic_implementer` to your MCP config, and the local git hooks.
378
514
 
515
+ **Qualifying the local gate.** A stored `local` or `mixed` gate must
516
+ pass once under the executor before an unattended run is admitted. When the server
517
+ reports the stored gate unqualified (or stale after an edit), setup offers to run it
518
+ now: "Run the local gate once now to qualify it? [y/N]" (the `qualify_gate` choice
519
+ with `--answers`). Approving runs the gate's commands once, for the stored revision.
520
+ Declining runs nothing; setup then ends `Not ready`, and the `Repository test gate`
521
+ item names the fix (re-run setup and approve, or pass `--qualify-gate`).
522
+ `--qualify-gate` still qualifies with no question. Setup never reports `Ready` from
523
+ its own run alone: the closing verdict comes from the server's refreshed report. A
524
+ signed-out `gh` does not undo writes you approved separately, and setup withholds
525
+ `Ready` while `gh` is signed out.
526
+
379
527
  `npx -y @bridge_gpt/mcp-server install conductor --merge-workflow --codeowner <@org/team|@user>`
380
528
  generates the merge workflow and its CODEOWNERS fragment, pushes a branch with your own git, and
381
529
  opens a PR with your own `gh`. It never merges that PR. Replace
@@ -599,8 +747,8 @@ atomically over the target. A hook edited in the meantime is left alone
599
747
 
600
748
  **Repairing old cache-backed hooks.** Hooks installed from `npx` before durable
601
749
  hook installation point into the npx cache. Install persistently (`npm i -g @bridge_gpt/mcp-server`),
602
- then re-run `epic-implementer install-git-hooks` (or `install conductor` and
603
- accept the local-observability consent). The managed block is replaced in place.
750
+ then re-run `epic-implementer install-git-hooks`. Setup does not install hooks;
751
+ it only recommends this command. The managed block is replaced in place.
604
752
 
605
753
  **Upgrades and rollback.** `npm i -g @bridge_gpt/mcp-server@<version>` replaces
606
754
  the package in place, so hooks keep working without a rewrite. To roll back,
@@ -30,6 +30,9 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
30
30
  - **Repository workflow readiness** (`server.repository-workflow-readiness`) — The CI and review workflows are confirmed on the default branch. Fix: Run setup, merge the setup pull request, then run setup again.
31
31
  - **Workflows at indexed commit** (`server.indexed-workflows`) — The repository index includes the workflow files on the default branch. Fix: Merge the setup pull request, then run setup again. It starts the re-index and reports this item as pending until the index reaches that commit.
32
32
  - **Integration branch configured** (`server.integration-branch-unset`) — The repository has an integration branch set. This is a note only and never blocks a launch. Fix: Nothing is needed. Set the repository's base branch to clear the note.
33
+ - **CI status readable by the run** (`server.ci-poll-readable`) — The run can poll CI: the CI check configuration is stored, so the MCP server shows the `poll_ci_checks` and `wait_for_ci_checks` tools, and Bridge can read CI for the default-branch head. A warning only; it never blocks a launch. Fix: Run the `resolve_ci_checks` MCP tool for this repository.
34
+ - **Watched checks run on epic branches** (`server.epic-branch-check-triggers`) — Every required or watched check (for example `claude-review`) runs for pull requests into `epic/**` branches. It names each check whose workflow does not, and each check it could not map to one workflow. A warning only. Fix: Add `epic/**` to the `pull_request` branches of each named check's workflow and merge that change.
35
+ - **Worker environment declarations** (`server.worker-environment`) — Workers will start with the database and environment variables they need: a worker database is declared when CI provides one, and a profile with local test commands declares its worker variables (without them, workers start with none of the default variables). Names and counts only, never values. A warning only. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer` and declare the worker database and worker variables for the test gate.
33
36
  - **Service availability** (`server.service-availability`) — Bridge could read this repository's readiness from the server. Fix: Retry in a few minutes. If it keeps failing, email info@bridgegpt.ai.
34
37
  - **Claude login** (`install.claude-login`) — Claude Code is signed in on this computer. Fix: Run `claude` and sign in, then run setup again.
35
38
  - **Repository identity** (`install.identity`) — Bridge knows which repository this folder is. Fix: Run setup from the repository root, or pass `--repo <name>`.
@@ -39,6 +42,7 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
39
42
  - **Integration credentials** (`install.integrations`) — The integration credentials this repository uses, such as Jira or GitHub, are stored. Fix: Run `npx -y @bridge_gpt/mcp-server install`.
40
43
  - **GitHub connection** (`install.github`) — Bridge's GitHub App is connected to this repository. Fix: Run `npx -y @bridge_gpt/mcp-server connect-github`.
41
44
  - **Repository indexing** (`install.indexing`) — The repository has been indexed by Bridge. Fix: Run `/parse-repository`, or let setup queue the index.
45
+ - **Run tools visible in MCP sessions** (`install.run-tools-visible`) — The MCP session this computer starts loads the Epic Implementer run tools (the `full` or `epic_implementer` group). Checked on this computer only; the server reports it as unknown. A warning only; it never blocks a launch. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`, accept the tool-visibility fix, then restart your MCP client.
42
46
  - **Conductor event ledger** (`conductor.ledger`) — The local Epic Implementer event ledger can be read. Fix: Run `npx -y @bridge_gpt/mcp-server epic-implementer doctor` and follow what it prints.
43
47
  - **Conductor git hooks** (`conductor.git-hooks`) — Optional: the git hooks that feed the local event ledger are installed. Fix: Run `npx -y @bridge_gpt/mcp-server epic-implementer install-git-hooks`.
44
48
  - **Epic Implementer MCP profile** (`conductor.mcp-profile`) — The `epic_implementer` tool profile is on in your MCP host. Fix: Let setup add it (it asks first), then restart your MCP client.
@@ -56,7 +60,7 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
56
60
  - **Supervisor review-policy alignment** (`conductor.install-section-supervisor-review-alignment`) — The review policy and the review workflow agree. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
57
61
  - **GitHub App actions permission** (`conductor.install-section-github-actions-permission`) — The GitHub App may start workflow runs. Only needed when merges go through GitHub Actions. Fix: Accept the updated permission on the GitHub App's installation page.
58
62
  - **Merge execution eligibility** (`conductor.install-section-merge-execution-eligibility`) — This repository can use GitHub Actions merges. Only needed for that merge mode. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer --merge-workflow --codeowner <@org/team|@user>` and merge its pull request.
59
- - **Epic Implementer MCP profile token** (`conductor.install-section-epic-implementer-profile-token`) — The Bridge key used by the Epic Implementer tool profile is stored. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; it fixes what it can and prints the one step it cannot.
63
+ - **Epic Implementer MCP profile token** (`conductor.install-section-epic-implementer-profile-token`) — The Bridge entries in your project's supported MCP configuration files (`.mcp.json`, `.vscode/mcp.json`, `.cursor/mcp.json`) load the `epic_implementer` group, so your editor can see the Epic Implementer tools. Fix: Run `npx -y @bridge_gpt/mcp-server install epic-implementer`; setup adds the group to your existing Bridge entry after you approve it (it keeps your other groups and creates no file), then restart your MCP client.
60
64
  - **Conductor hook targets** (`conductor.install-section-conductor-hook-targets`) — The git hook targets are in place for this clone. Fix: Run `npx -y @bridge_gpt/mcp-server epic-implementer install-git-hooks`.
61
65
  - **GitHub Actions merge: local observation prerequisites** (`conductor.install-section-gh-actions-merge-auth`) — This computer can observe GitHub Actions merges. Only needed for that merge mode. Fix: Sign in with `gh auth login` and rerun setup.
62
66
  - **GitHub Actions merge: capability observability** (`conductor.install-section-gh-actions-merge-observable`) — Bridge can observe the outcome of GitHub Actions merges. Only needed for that merge mode. Fix: Rerun setup and follow the step it prints.