@bridge_gpt/mcp-server 0.2.75 → 0.2.76

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 (64) hide show
  1. package/README.md +5 -5
  2. package/build/agents.generated.js +4 -4
  3. package/build/codex-auto-recovery.js +25 -7
  4. package/build/commands.generated.js +6 -6
  5. package/build/conductor/bridge-api-client.js +141 -6
  6. package/build/conductor/declare-blocked.js +4 -0
  7. package/build/conductor/driver-pass.js +8 -0
  8. package/build/conductor/epic-implementer-cli.js +4 -3
  9. package/build/conductor/epic-server-journal.js +13 -0
  10. package/build/conductor/epic-server-recipe.js +15 -5
  11. package/build/conductor/epic-server-runtime.js +163 -45
  12. package/build/conductor/epic-server.js +13 -6
  13. package/build/conductor/install-doctor.js +30 -2
  14. package/build/conductor/local-merge.js +54 -12
  15. package/build/conductor/pr-ci-producer.js +12 -3
  16. package/build/conductor/readiness-sections.js +46 -13
  17. package/build/conductor/readiness.js +3 -40
  18. package/build/conductor/recovery-cli.js +12 -12
  19. package/build/conductor/repository-workflow-remedy.js +147 -7
  20. package/build/conductor/ui-readiness.js +224 -0
  21. package/build/conductor/wait-run-attention.js +9 -4
  22. package/build/conductor/wait-run-cli.js +9 -2
  23. package/build/docs.generated.js +2 -2
  24. package/build/drive-epic.js +402 -27
  25. package/build/epic-implementer-bin.js +62 -42
  26. package/build/epic-launch-context.js +8 -1
  27. package/build/epic-shared/cut-protocol.js +55 -3
  28. package/build/executor/failure-reason-codes.js +2 -0
  29. package/build/executor/integration-job.js +56 -2
  30. package/build/executor/job-runner.js +4 -1
  31. package/build/executor/merge-job.js +45 -1
  32. package/build/executor/permissions.js +187 -2
  33. package/build/executor/provider-checks.js +28 -5
  34. package/build/executor/reconcile-overlap-job.js +70 -17
  35. package/build/executor/required-work-ledger.js +7 -2
  36. package/build/executor/resume-pre-spawn.js +32 -8
  37. package/build/executor/runner.js +26 -4
  38. package/build/executor/worktree.js +12 -1
  39. package/build/index.js +376 -434
  40. package/build/init.js +16 -0
  41. package/build/install-bridge-conductor-answers.js +4 -0
  42. package/build/install-bridge-conductor-apply.js +10 -0
  43. package/build/install-bridge-conductor-assessment.js +71 -0
  44. package/build/install-bridge-conductor-contracts.js +9 -1
  45. package/build/install-bridge-conductor-setup.js +103 -3
  46. package/build/install-bridge-conductor.js +437 -93
  47. package/build/mcp-host-config.js +54 -37
  48. package/build/phase-context-git-probe.js +16 -0
  49. package/build/pipelines.generated.js +9 -9
  50. package/build/plan-execution-ledger.js +27 -0
  51. package/build/plane/plane-freshness.js +43 -26
  52. package/build/printed-remedy-commands.js +8 -0
  53. package/build/readme.generated.js +1 -1
  54. package/build/secret-redaction.js +3 -0
  55. package/build/setup-epic.js +41 -8
  56. package/build/test-support/create-preview-world.js +232 -0
  57. package/build/ticket-delivery.js +65 -0
  58. package/build/v2-readiness-requirements.js +8 -3
  59. package/build/version.generated.js +3 -3
  60. package/build/worktree-core.js +51 -7
  61. package/docs/EPIC-IMPLEMENTER.md +79 -0
  62. package/docs/epic-implementer/getting-started.md +1 -1
  63. package/package.json +1 -1
  64. package/pipelines/implement-ticket.json +2 -2
@@ -15,6 +15,7 @@ const SECRET_PATTERNS = [
15
15
  // Well-known provider key shapes.
16
16
  [/\b(sk|pk|rk)-[A-Za-z0-9_-]{16,}/g, REDACTED],
17
17
  [/\bgh[pousr]_[A-Za-z0-9]{16,}/g, REDACTED],
18
+ [/\bgithub_pat_[A-Za-z0-9_]{16,}/g, REDACTED],
18
19
  // key/secret/password/token assignments in prose, env, JSON, or CLI form.
19
20
  [
20
21
  /\b([A-Za-z0-9_-]*(?:api[_-]?key|secret|password|passwd|token|credential)[A-Za-z0-9_-]*)\s*[:=]\s*("[^"]*"|'[^']*'|\S+)/gi,
@@ -22,6 +23,8 @@ const SECRET_PATTERNS = [
22
23
  ],
23
24
  // Credentials embedded in a URL.
24
25
  [/\b([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+:[^/\s@]+@/gi, `$1${REDACTED}@`],
26
+ // A bare token as the whole userinfo of an http(s) URL (`https://<token>@host`).
27
+ [/\b(https?:\/\/)[^/\s:@]+@/gi, `$1${REDACTED}@`],
25
28
  ];
26
29
  /** Redact secret-bearing substrings while leaving safe technical text intact. */
27
30
  export function redactSecrets(value) {
@@ -95,7 +95,8 @@ import { formatEpicLaunchChannelIdentity, getPinnedEpicLaunchPolicy, readEpicLau
95
95
  import { mapLegacyMergeExecutionModeToPolicyMode, resolveMergeExecutionMode, } from "./merge-pull-request.js";
96
96
  import { MERGE_EXECUTION_INELIGIBLE, MERGE_EXECUTION_MODE_GITHUB_ACTIONS, MERGE_WORKFLOW_CODEOWNER_INSTRUCTION, MERGE_WORKFLOW_REMEDY_COMMAND, } from "./conductor/merge-execution-contract.js";
97
97
  import { classifyMergeExecutionEligibility } from "./conductor/merge-execution-eligibility.js";
98
- import { repositoryWorkflowRemedy } from "./conductor/repository-workflow-remedy.js";
98
+ import { repositoryReadinessVerdict, requiredChecksAdmissionRemedy, requiredChecksAdmissionVerdict, } from "./conductor/repository-workflow-remedy.js";
99
+ import { gateProfileAwareRepositoryWorkflowRemedy } from "./conductor/readiness.js";
99
100
  import { resolveTrackedPaths } from "./git-reachability.js";
100
101
  import { validateBranchName } from "./base-ref.js";
101
102
  import { TICKET_KEY_PATTERN } from "./ticket-key-utils.js";
@@ -1827,6 +1828,10 @@ function uncertainty(reason) {
1827
1828
  export function isSetupEpicPrerequisiteWarning(value) {
1828
1829
  return typeof value === "object" && value !== null && value.warning === true;
1829
1830
  }
1831
+ /** BAPI-1714 — confirmed -> true, denied -> false, unknown -> null. */
1832
+ function verdictToFact(verdict) {
1833
+ return verdict === "confirmed" ? true : verdict === "denied" ? false : null;
1834
+ }
1830
1835
  /** The unattended facts of either input, each `null` when the input does not establish it. */
1831
1836
  function unattendedFactsOf(input) {
1832
1837
  if (input === null)
@@ -1849,7 +1854,10 @@ function unattendedFactsOf(input) {
1849
1854
  return {
1850
1855
  conductorAllowed: bool(unattended.conductor_allowed),
1851
1856
  webhookDefaultDeclared: bool(unattended.notify_webhook_default_declared),
1852
- repositoryReadinessConfirmed: bool(unattended.repository_readiness_confirmed),
1857
+ // BAPI-1714 — the shared verdict: `false` only for a PROVEN deficiency (the
1858
+ // server flag is false AND its admission record says denied). An unverifiable
1859
+ // read is `null`, which continues as uncertainty and never refuses.
1860
+ repositoryReadinessConfirmed: verdictToFact(repositoryReadinessVerdict(input)),
1853
1861
  emailAvailable: bool(unattended.escalation_email_available),
1854
1862
  emailTransport: transport !== undefined &&
1855
1863
  transport.severity !== null &&
@@ -1859,6 +1867,9 @@ function unattendedFactsOf(input) {
1859
1867
  : "unknown",
1860
1868
  };
1861
1869
  }
1870
+ /** BAPI-1714 — the snapshot-false refusal: a snapshot holds no workflow detail to name. */
1871
+ const SNAPSHOT_REPOSITORY_READINESS_REMEDY = "The repository's review or CI workflow is missing something an auto-merging run needs. " +
1872
+ `Run \`npx -y ${MCP_PACKAGE_NAME} epic-implementer readiness\` to see what; fix it, or pass \`--attended\`.`;
1862
1873
  export function evaluateSetupEpicUnattendedPrerequisites(readiness, requestedPolicy) {
1863
1874
  const facts = unattendedFactsOf(readiness);
1864
1875
  // A missing `unattended` block proves nothing (an older server, or an unreadable
@@ -1919,13 +1930,20 @@ export function evaluateSetupEpicUnattendedPrerequisites(readiness, requestedPol
1919
1930
  }
1920
1931
  if (facts.repositoryReadinessConfirmed === false) {
1921
1932
  // BAPI-1359: the shared formatter names the specific missing item; the reason
1922
- // code and the trailing sentence are unchanged. A snapshot carries no workflow
1923
- // detail, so it gets the formatter's own generic fallback.
1933
+ // code and the trailing sentence are unchanged.
1934
+ //
1935
+ // BAPI-1714: a full report gets the gate-aware remedy, which names only the
1936
+ // failing workflow section (no fixed opening that could name a workflow that
1937
+ // is fine). A snapshot carries no workflow detail, so it gets one fixed,
1938
+ // truthful message that points at the read-only readiness command. Neither
1939
+ // says "could not verify" or "Retry readiness": this refusal is a PROVEN
1940
+ // deficiency, never an unknown.
1941
+ const remedy = readiness !== null && !isReadinessSnapshot(readiness)
1942
+ ? gateProfileAwareRepositoryWorkflowRemedy(readiness)
1943
+ : SNAPSHOT_REPOSITORY_READINESS_REMEDY;
1924
1944
  return {
1925
1945
  reason: "repository_readiness_unconfirmed",
1926
- message: "the unattended default authorizes automatic merge, which requires the review and " +
1927
- "epic-implementer-ci workflows to be CONFIRMED on the default branch, and they are not. " +
1928
- `${repositoryWorkflowRemedy(readiness !== null && !isReadinessSnapshot(readiness) ? readiness : null)} No run was created.`,
1946
+ message: `${remedy} No run was created.`,
1929
1947
  };
1930
1948
  }
1931
1949
  if (facts.repositoryReadinessConfirmed === null)
@@ -4011,8 +4029,12 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
4011
4029
  if (classified.status === "behind_target") {
4012
4030
  // One plain push (no force, no leading '+'). Whatever it returns, the remote
4013
4031
  // is re-read once; only an exact match with the cut lets setup continue.
4032
+ // `--no-verify`, as in the exact cut (epic-shared/cut-protocol.ts): this push
4033
+ // sends no new code, only moves the branch forward to the canonical indexed
4034
+ // commit. A repository's pre-push hook (tests, Husky, pre-commit) would
4035
+ // otherwise run here with an inherited environment and can block the launch.
4014
4036
  try {
4015
- await runGit(gitDeps, ["push", "origin", `${cutCommitSha}:refs/heads/${branch}`]);
4037
+ await runGit(gitDeps, ["push", "--no-verify", "origin", `${cutCommitSha}:refs/heads/${branch}`]);
4016
4038
  }
4017
4039
  catch { /* judged by the re-read below */ }
4018
4040
  let reread;
@@ -4233,6 +4255,17 @@ async function executeSetupEpic(argv, overrides, runIdSink, handoff) {
4233
4255
  deps.errorLog(`setup-epic REFUSED (${unattended.reason}): ${unattended.message}`);
4234
4256
  return 1;
4235
4257
  }
4258
+ // BAPI-1526 — first approval would refuse this create's required checks.
4259
+ // `launchReadiness` is the policy-aware report for this same
4260
+ // `composedForCreate`, so the server already exempted any policy approval
4261
+ // would exempt. Only a proven denial refuses, and only before a run exists:
4262
+ // a `null` report (the POST failed) or any other record continues, and
4263
+ // approval stays the authority. A drive-epic create delegates here, so both
4264
+ // entry points refuse before the run row exists.
4265
+ if (existingRunId === null && requiredChecksAdmissionVerdict(launchReadiness) === "denied") {
4266
+ deps.errorLog(`setup-epic REFUSED (required_checks_admission_denied): ${requiredChecksAdmissionRemedy(launchReadiness)} No run was created.`);
4267
+ return 1;
4268
+ }
4236
4269
  }
4237
4270
  }
4238
4271
  try {
@@ -0,0 +1,232 @@
1
+ /**
2
+ * A small, hermetic `drive-epic` CREATE-preview world for tests outside `drive-epic.test.ts`.
3
+ *
4
+ * It is the same recipe the drive-epic suite uses: every boundary is an in-memory fake, every
5
+ * plane or launch seam throws when reached, and the plan comes from a supplied `--plan-file`
6
+ * whose DAG is served from memory. A preview built here reaches the decision `create`, so the
7
+ * launch-plan facts, and with them the BAPI-1718 UI readiness advisory, are collected.
8
+ *
9
+ * `runDriveEpicCli` merges its overrides over the production defaults. Every seam a create
10
+ * preview could reach is therefore named here, so a test never touches the network, `gh`, `git`,
11
+ * the owner's home, or a real credential.
12
+ */
13
+ import { resolve as nativePath } from "node:path";
14
+ import { runDriveEpicCli } from "../drive-epic.js";
15
+ import { buildEpicLaunchContext } from "../epic-launch-context.js";
16
+ import { inspectHostSleep } from "../plane/plane-freshness.js";
17
+ export const PREVIEW_WORLD_SENTINEL_KEY = "preview-world-secret-do-not-print";
18
+ export const PREVIEW_WORLD_EPIC = "BAPI-1275";
19
+ export const PREVIEW_WORLD_PLAN_PATH = nativePath("/supplied/plan.json");
20
+ export const PREVIEW_WORLD_ACCESS = {
21
+ repoName: "bapi",
22
+ apiKey: PREVIEW_WORLD_SENTINEL_KEY,
23
+ baseUrl: "https://example.invalid",
24
+ };
25
+ /** A fully green readiness report: the preview reaches `create`. */
26
+ export function greenPreviewReadiness(repoName = "bapi") {
27
+ return {
28
+ repo_name: repoName,
29
+ merge_execution: {
30
+ branch_scope: "default_branch",
31
+ branch_protection_probe_succeeded: true,
32
+ branch_protection_actions_bot_admitted: true,
33
+ merge_workflow_probe_succeeded: true,
34
+ merge_workflow_present: true,
35
+ merge_workflow_enabled: true,
36
+ merge_workflow_version: 1,
37
+ merge_workflow_token_write_authority: true,
38
+ },
39
+ bring_up: {
40
+ migration_readable: true,
41
+ database_migration_current: true,
42
+ heartbeat_readable: true,
43
+ worker_present: true,
44
+ fresh_reconciler_count: 1,
45
+ single_transition_authority: true,
46
+ },
47
+ supervisor: {
48
+ setup_present: true,
49
+ setup_source: "project_default",
50
+ setup_created_at: null,
51
+ setup_updated_at: null,
52
+ config_present: true,
53
+ config_source: "project_default",
54
+ config_created_at: null,
55
+ config_updated_at: null,
56
+ required_checks_count: 2,
57
+ required_checks_empty: false,
58
+ auto_merge_enabled: true,
59
+ merge_approval_required_set: true,
60
+ review_policy_alignment: null,
61
+ review_policy_present: true,
62
+ },
63
+ github: {
64
+ credentials_readable: true,
65
+ owner_resolved: true,
66
+ repo_id_resolved: true,
67
+ installation_id_resolved: true,
68
+ credentials_complete: true,
69
+ actions_probe_succeeded: true,
70
+ actions_permission_present: true,
71
+ actions_permission_level: "read",
72
+ actions_write: false,
73
+ },
74
+ reconciler: {
75
+ liveness_readable: true,
76
+ last_tick_at: "2026-08-21T00:00:00Z",
77
+ last_tick_age_seconds: 5,
78
+ stale: false,
79
+ active_run_count: 0,
80
+ expired_lease_count: 0,
81
+ },
82
+ executor: {
83
+ liveness_readable: true,
84
+ last_seen_at: "2026-08-21T00:00:00Z",
85
+ last_seen_age_seconds: 5,
86
+ ready: true,
87
+ },
88
+ thresholds: { reconciler_stale_after_seconds: 120, executor_stale_after_seconds: 120 },
89
+ review_workflow: null,
90
+ conductor_ci_workflow: null,
91
+ unattended: {
92
+ conductor_allowed: true,
93
+ notify_webhook_default_declared: true,
94
+ notify_webhook_default_verified: true,
95
+ repository_readiness_confirmed: true,
96
+ },
97
+ };
98
+ }
99
+ function refuse(name) {
100
+ throw new Error(`${name} must not be reached by a create preview`);
101
+ }
102
+ export function createPreviewWorld(o) {
103
+ const out = [];
104
+ const err = [];
105
+ const mutations = [];
106
+ const repoName = o.repoName ?? PREVIEW_WORLD_ACCESS.repoName;
107
+ const access = { ...PREVIEW_WORLD_ACCESS, repoName };
108
+ const readiness = greenPreviewReadiness(repoName);
109
+ const dag = JSON.stringify({
110
+ plan_version: 1,
111
+ nodes: o.keys.map((ticket_key, i) => ({
112
+ ticket_key,
113
+ status: "planned",
114
+ depends_on: i === 0 ? [] : [o.keys[i - 1]],
115
+ automations: [],
116
+ ...(o.touchedFiles?.[ticket_key] !== undefined ? { touched_files: o.touchedFiles[ticket_key] } : {}),
117
+ })),
118
+ edges: o.keys.slice(1).map((key, i) => ({ from: o.keys[i], to: key })),
119
+ });
120
+ const deps = {
121
+ inspectRepositoryIdentity: async () => ({ repoRoot: nativePath("/repo"), isBridge: true }),
122
+ resolveAccess: async () => ({ ok: true, access }),
123
+ adoptLaunchTarget: () => undefined,
124
+ readReadiness: async () => readiness,
125
+ // A launch reads no readiness; the preview's stored snapshot is never read back here.
126
+ readScopeBaseBranch: async () => "main",
127
+ readLaunchContext: async (binding) => ({
128
+ kind: "usable",
129
+ value: {
130
+ sourceVersion: 2,
131
+ context: buildEpicLaunchContext({
132
+ epicKey: binding.epicKey,
133
+ baseBranch: binding.baseBranch,
134
+ targetBaseUrl: binding.targetBaseUrl,
135
+ writtenAt: binding.now,
136
+ readiness: { kind: "ready", readiness, attempts: 1 },
137
+ repoName: binding.repository?.repoName ?? null,
138
+ isBridge: binding.repository?.isBridge ?? null,
139
+ serverPlanDigest: "digest-0123456789",
140
+ }),
141
+ },
142
+ }),
143
+ writeLaunchContext: async () => ({ ok: true, path: "(not written in tests)" }),
144
+ writeLaunchOutcome: async () => ({ ok: true, path: "(not written in tests)" }),
145
+ reportLaunch: () => undefined,
146
+ resolveDocsDir: async () => ({ ok: true, docsDir: nativePath("/repo/docs/tmp") }),
147
+ discoveryFs: {
148
+ readdir: async () => { throw Object.assign(new Error("ENOENT"), { code: "ENOENT" }); },
149
+ readFile: async () => { throw new Error("ENOENT"); },
150
+ },
151
+ readPlanDag: async () => dag,
152
+ readPolicyFile: async () => { throw new Error("ENOENT: no fixture policy"); },
153
+ readLiveEpicRun: async () => ({ kind: "none" }),
154
+ readEligibilityArtifact: async () => { throw new Error("ENOENT: no fixture artifact"); },
155
+ previewSetupEpic: async () => ({
156
+ exitCode: 0,
157
+ stdout: [JSON.stringify({
158
+ dry_run: true,
159
+ epic_key: PREVIEW_WORLD_EPIC,
160
+ repo_name: repoName,
161
+ plan_version: 1,
162
+ local_plan_hash: "sha256:abc",
163
+ existing_run_id: null,
164
+ feature_branch: `epic/${PREVIEW_WORLD_EPIC}`,
165
+ server_validated: true,
166
+ policy_applied: "absent",
167
+ warnings: [],
168
+ create_policy: {
169
+ posture: "unattended",
170
+ v2_auto_merge_enabled: true,
171
+ merge_execution_mode: "machine_token",
172
+ integration_preparation: { enabled: true },
173
+ },
174
+ })],
175
+ stderr: [],
176
+ }),
177
+ inspectRunExecutorPrecondition: async () => ({ ok: true }),
178
+ // Nothing that creates, prepares, or starts a run may run.
179
+ runSetupEpic: async () => { mutations.push("runSetupEpic"); return refuse("runSetupEpic"); },
180
+ prepareRunExecutor: async () => { mutations.push("prepareRunExecutor"); return refuse("prepareRunExecutor"); },
181
+ ensureRunExecutor: async () => { mutations.push("ensureRunExecutor"); return refuse("ensureRunExecutor"); },
182
+ runPlane: async () => { mutations.push("runPlane"); return refuse("runPlane"); },
183
+ launchControlPlane: async () => { mutations.push("launchControlPlane"); return refuse("launchControlPlane"); },
184
+ requestScopedLanes: async () => { mutations.push("requestScopedLanes"); return refuse("requestScopedLanes"); },
185
+ runPlanePreflight: async () => refuse("runPlanePreflight"),
186
+ probePlanePort: async () => refuse("probePlanePort"),
187
+ readRunState: async () => refuse("readRunState"),
188
+ readPlaneReconcilerState: async () => refuse("readPlaneReconcilerState"),
189
+ readPlaneManifest: async () => refuse("readPlaneManifest"),
190
+ cleanupTerminalRunPlane: async () => refuse("cleanupTerminalRunPlane"),
191
+ listLiveRunIds: async () => refuse("listLiveRunIds"),
192
+ resolvePlaneEndpoint: () => ({
193
+ ok: true,
194
+ endpoint: { host: "127.0.0.1", port: 8000, baseUrl: "http://127.0.0.1:8000" },
195
+ }),
196
+ cwd: () => nativePath("/repo"),
197
+ // Hermetic launch-need probes: each answers "could not tell".
198
+ inspectRequiredRunners: async () => ({ state: "unverifiable", reason: "probe_failed" }),
199
+ inspectHostSleep: (root) => inspectHostSleep(root, { execFile: async () => refuse("pmset"), platform: "linux" }),
200
+ execEngineStatus: undefined,
201
+ runCommand: async () => ({ exitCode: 0, stdout: "", stderr: "" }),
202
+ launchSleep: async () => undefined,
203
+ attemptPlanGeneration: undefined,
204
+ publishGeneratedPlan: undefined,
205
+ lookupAuthoredPlan: undefined,
206
+ uploadAuthoredPlan: undefined,
207
+ materializeAuthoredPlan: undefined,
208
+ readPrerequisiteCache: async () => ({ kind: "unavailable" }),
209
+ // The advisory UI readiness reads are the test's to install; absent means unavailable.
210
+ readUiTicketDescription: undefined,
211
+ listUiTrackedFiles: undefined,
212
+ readUiMcpGrant: undefined,
213
+ readUiEpicServerRecord: undefined,
214
+ log: (line) => out.push(line),
215
+ errorLog: (line) => err.push(line),
216
+ ...o.seams,
217
+ };
218
+ return {
219
+ deps,
220
+ out,
221
+ err,
222
+ mutations,
223
+ preview: async (extraArgv = [], options = {}) => {
224
+ out.length = 0;
225
+ err.length = 0;
226
+ const json = options.json !== false;
227
+ const code = await runDriveEpicCli([PREVIEW_WORLD_EPIC, "--plan-file", PREVIEW_WORLD_PLAN_PATH, "--dry-run", ...(json ? ["--json"] : []), ...extraArgv], deps);
228
+ const doc = (json ? JSON.parse(out[0] ?? "null") : null);
229
+ return { code, doc, text: [...out, ...err].join("\n") };
230
+ },
231
+ };
232
+ }
@@ -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",
@@ -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
  //
@@ -176,7 +182,6 @@ export const V2_READINESS_REQUIREMENTS = [
176
182
  const descriptor = READINESS_PREREQUISITE_BY_ID.get(id);
177
183
  return { ...req, id, describe: descriptor?.label ?? req.describe,
178
184
  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
185
  ...(req.id === 'unattended_notify_default' ? {
181
186
  satisfied: (r) => !r.prerequisites?.some(p => p.id === id && p.check_status === 'not_met' && p.impact === 'blocking'),
182
187
  remedyFor: (r) => r.prerequisites?.find(p => p.id === id)?.fix ?? 'Retry readiness.',
@@ -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.76";
3
+ export const BUILD_COMMIT = "693d8ca6350a";
4
+ export const LAUNCHER_ARGS = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.76", "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
@@ -376,6 +443,18 @@ Epic Implementer. It runs a read-only doctor first, then asks for consent before
376
443
  each write: the supervisor project defaults, an optional `claude-review` workflow,
377
444
  adding `epic_implementer` to your MCP config, and the local git hooks.
378
445
 
446
+ **Qualifying the local gate.** A stored `local` or `mixed` gate must
447
+ pass once under the executor before an unattended run is admitted. When the server
448
+ reports the stored gate unqualified (or stale after an edit), setup offers to run it
449
+ now: "Run the local gate once now to qualify it? [y/N]" (the `qualify_gate` choice
450
+ with `--answers`). Approving runs the gate's commands once, for the stored revision.
451
+ Declining runs nothing; setup then ends `Not ready`, and the `Repository test gate`
452
+ item names the fix (re-run setup and approve, or pass `--qualify-gate`).
453
+ `--qualify-gate` still qualifies with no question. Setup never reports `Ready` from
454
+ its own run alone: the closing verdict comes from the server's refreshed report. A
455
+ signed-out `gh` does not undo writes you approved separately, and setup withholds
456
+ `Ready` while `gh` is signed out.
457
+
379
458
  `npx -y @bridge_gpt/mcp-server install conductor --merge-workflow --codeowner <@org/team|@user>`
380
459
  generates the merge workflow and its CODEOWNERS fragment, pushes a branch with your own git, and
381
460
  opens a PR with your own `gh`. It never merges that PR. Replace
@@ -56,7 +56,7 @@ Setup checks every item below for you, fixes what it can, and prints the one ste
56
56
  - **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
57
  - **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
58
  - **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.
59
+ - **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
60
  - **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
61
  - **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
62
  - **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.