@bridge_gpt/mcp-server 0.2.72 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (146) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +3 -0
  3. package/build/agents.generated.js +6 -6
  4. package/build/bridge-permissions.js +27 -0
  5. package/build/ci-system-detection.js +50 -0
  6. package/build/ci-trigger-adapters.js +631 -0
  7. package/build/ci-trigger-install.js +106 -0
  8. package/build/codex-launcher-pin.js +33 -2
  9. package/build/codex-skill-adapter.js +3 -1
  10. package/build/command-host.js +33 -0
  11. package/build/commands.generated.js +7 -6
  12. package/build/conductor/bridge-api-client.js +842 -35
  13. package/build/conductor/bring-up-facts.js +18 -5
  14. package/build/conductor/command-drift-production.js +42 -17
  15. package/build/conductor/command-drift.js +47 -0
  16. package/build/conductor/declare-blocked.js +554 -0
  17. package/build/conductor/doctor.js +106 -21
  18. package/build/conductor/driver-commands.js +141 -0
  19. package/build/conductor/driver-guard.js +277 -0
  20. package/build/conductor/driver-lapse.js +321 -0
  21. package/build/conductor/driver-register.js +176 -0
  22. package/build/conductor/driver-release.js +174 -0
  23. package/build/conductor/driver-session-state.js +315 -0
  24. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  25. package/build/conductor/epic-implementer-cli.js +166 -15
  26. package/build/conductor/epic-server-database.js +162 -0
  27. package/build/conductor/epic-server-guidance.js +278 -0
  28. package/build/conductor/epic-server-journal.js +239 -0
  29. package/build/conductor/epic-server-processes.js +324 -0
  30. package/build/conductor/epic-server-recipe.js +397 -0
  31. package/build/conductor/epic-server-runtime.js +1207 -0
  32. package/build/conductor/epic-server-sfcc.js +107 -0
  33. package/build/conductor/epic-server-state.js +427 -0
  34. package/build/conductor/epic-server.js +594 -0
  35. package/build/conductor/gate-discovery.js +150 -5
  36. package/build/conductor/gate-settings-review.js +224 -4
  37. package/build/conductor/launch-need-probes.js +6 -53
  38. package/build/conductor/launch-plan.js +313 -156
  39. package/build/conductor/prerequisite-inputs.js +879 -45
  40. package/build/conductor/readiness-assessment.js +16 -1
  41. package/build/conductor/readiness-cli.js +20 -9
  42. package/build/conductor/readiness-prerequisites.js +28 -9
  43. package/build/conductor/readiness-sections.js +133 -126
  44. package/build/conductor/readiness.js +1 -1
  45. package/build/conductor/recovery-cli.js +13 -2
  46. package/build/conductor/tools.js +6 -5
  47. package/build/conductor/wait-run-attention.js +2 -2
  48. package/build/conductor/wait-run-cli.js +208 -22
  49. package/build/conductor/worker-database-doctor-inspector.js +33 -2
  50. package/build/conductor/worker-setup-tally.js +27 -0
  51. package/build/credential-store.js +71 -1
  52. package/build/dependency-install-declarations.js +55 -0
  53. package/build/docs.generated.js +2 -2
  54. package/build/doctor.js +54 -3
  55. package/build/drive-epic-help.js +21 -2
  56. package/build/drive-epic.js +1811 -351
  57. package/build/engine-paths.js +20 -0
  58. package/build/epic-branch-ci-summary.js +140 -0
  59. package/build/epic-capability-statement.js +107 -0
  60. package/build/epic-ci-workflow-drift.js +30 -15
  61. package/build/epic-ci-workflow-install.js +110 -42
  62. package/build/epic-ci-workflow-v2.js +274 -0
  63. package/build/epic-ci-workflow.js +38 -12
  64. package/build/epic-implementer-bin.js +2101 -44
  65. package/build/epic-launch-context.js +607 -0
  66. package/build/epic-server-record.js +273 -0
  67. package/build/epic-shared/bridge-client.js +11 -3
  68. package/build/escalation-reachability.js +43 -0
  69. package/build/executor/ci-fix-test-runs.js +334 -0
  70. package/build/executor/completion-contract.js +8 -1
  71. package/build/executor/env.js +59 -22
  72. package/build/executor/epic-server-context.js +141 -0
  73. package/build/executor/gate-qualification-job.js +127 -26
  74. package/build/executor/http-client.js +52 -5
  75. package/build/executor/job-runner.js +423 -69
  76. package/build/executor/observation.js +8 -0
  77. package/build/executor/pre-pr-checks.js +363 -0
  78. package/build/executor/prompt-spec.js +114 -2
  79. package/build/executor/reconcile-overlap-job.js +5 -3
  80. package/build/executor/required-work-diagnostics.js +4 -2
  81. package/build/executor/required-work-ledger.js +936 -38
  82. package/build/executor/results.js +58 -0
  83. package/build/executor/terminal-mutation.js +8 -0
  84. package/build/executor/worker-command.js +72 -3
  85. package/build/executor/worker-database-config.js +281 -0
  86. package/build/executor/worker-database-target.js +16 -12
  87. package/build/executor/worker-database.js +320 -101
  88. package/build/executor/worker-finalization.js +7 -1
  89. package/build/executor/worker-resources.js +25 -3
  90. package/build/executor/worker-verification-guidance.js +18 -3
  91. package/build/executor/worktree.js +20 -1
  92. package/build/executor-launch.js +54 -2
  93. package/build/generated-assets-catalog.js +2 -2
  94. package/build/index.js +664 -335
  95. package/build/init.js +26 -11
  96. package/build/install-bridge-conductor-answers.js +465 -0
  97. package/build/install-bridge-conductor-apply.js +259 -0
  98. package/build/install-bridge-conductor-assessment.js +895 -0
  99. package/build/install-bridge-conductor-compact.js +161 -0
  100. package/build/install-bridge-conductor-contracts.js +63 -0
  101. package/build/install-bridge-conductor-gate.js +1197 -196
  102. package/build/install-bridge-conductor-setup.js +535 -79
  103. package/build/install-bridge-conductor.js +2885 -560
  104. package/build/install-bridge.js +199 -21
  105. package/build/install-maintenance.js +26 -3
  106. package/build/launcher-config-inspection.js +162 -1
  107. package/build/mcp-grant-candidates.js +767 -0
  108. package/build/mcp-grant-doctor.js +63 -0
  109. package/build/mcp-grant.js +288 -0
  110. package/build/mcp-host-targets.js +8 -0
  111. package/build/mcp-identity.js +23 -0
  112. package/build/mcp-invoke.js +126 -13
  113. package/build/mcp-presets.js +107 -0
  114. package/build/mcp-provisioning.js +134 -2
  115. package/build/mcp-registration-doctor.js +31 -2
  116. package/build/mcp-server-invocation.js +6 -1
  117. package/build/merge-workflow-install.js +234 -109
  118. package/build/pipelines.generated.js +5 -5
  119. package/build/plan-discovery.js +97 -4
  120. package/build/plan-execution-ledger.js +100 -7
  121. package/build/plan-generation-io.js +262 -0
  122. package/build/plan-generation.js +424 -0
  123. package/build/plane/build-freshness.js +6 -1
  124. package/build/plane/cli.js +75 -9
  125. package/build/plane/plane-freshness.js +17 -0
  126. package/build/plane/preflight.js +50 -10
  127. package/build/plane/shutdown.js +19 -0
  128. package/build/plane/terminal-run-cleanup.js +18 -4
  129. package/build/printed-remedy-commands.js +206 -12
  130. package/build/readiness-check.js +77 -0
  131. package/build/readiness-prerequisites.generated.js +122 -14
  132. package/build/readme.generated.js +1 -1
  133. package/build/repository-state-paths.js +38 -0
  134. package/build/run-unit-tests-launcher.js +8 -1
  135. package/build/setup-epic.js +1190 -196
  136. package/build/setup-progress.js +44 -0
  137. package/build/setup-question.js +122 -4
  138. package/build/third-party-mcp-targets.js +30 -0
  139. package/build/ticket-delivery-enrollment.js +9 -0
  140. package/build/upgrade-cli.js +85 -2
  141. package/build/v2-readiness-requirements.js +28 -1
  142. package/build/version.generated.js +3 -3
  143. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  144. package/docs/epic-implementer/getting-started.md +3 -1
  145. package/docs/epic-implementer/self-hosting.md +14 -1
  146. package/package.json +2 -2
@@ -0,0 +1,63 @@
1
+ /**
2
+ * Read-only `doctor` reporting for the worker MCP grant (BAPI-1545).
3
+ *
4
+ * Reports the grant's state (present, absent, or unusable), the granted server
5
+ * NAMES, and a warning when the grant file's mode is wider than `0600`. It reads
6
+ * the grant file and stats it — nothing else. It never writes, repairs a mode,
7
+ * creates a directory, or prints a command, an argument, an env value, a
8
+ * credential target, a parser error, or file contents.
9
+ */
10
+ import { readMcpGrant } from "./mcp-grant.js";
11
+ /** Collect the diagnostic. Never throws. */
12
+ export async function collectMcpGrantDiagnostic(deps) {
13
+ if (deps.repoName === null)
14
+ return { state: "no_repository" };
15
+ const repoName = deps.repoName;
16
+ let read;
17
+ try {
18
+ read = await readMcpGrant(repoName, deps);
19
+ }
20
+ catch {
21
+ return { state: "unusable", repoName };
22
+ }
23
+ if (read.state === "absent")
24
+ return { state: "absent", repoName };
25
+ if (read.state === "unusable")
26
+ return { state: "unusable", repoName };
27
+ let modeTooWide = null;
28
+ if (deps.platform !== "win32") {
29
+ try {
30
+ modeTooWide = ((await deps.stat(read.path)).mode & 0o077) !== 0;
31
+ }
32
+ catch {
33
+ modeTooWide = null;
34
+ }
35
+ }
36
+ return { state: "present", repoName, serverNames: read.grant.servers.map((s) => s.name).sort(), modeTooWide };
37
+ }
38
+ /** Render the section. Names and fixed text only. */
39
+ export function formatMcpGrantDiagnosticReport(diagnostic) {
40
+ const lines = ["", "Worker MCP grant (advisory)", ""];
41
+ switch (diagnostic.state) {
42
+ case "no_repository":
43
+ lines.push(" NOT CHECKED the repository name could not be resolved from this folder.");
44
+ break;
45
+ case "absent":
46
+ lines.push(` ABSENT no MCP grant for ${diagnostic.repoName}. Workers keep today's MCP servers.`, " To approve the extra MCP servers workers get, re-run: install epic-implementer");
47
+ break;
48
+ case "unusable":
49
+ lines.push(` UNUSABLE the MCP grant for ${diagnostic.repoName} cannot be used.`, " Workers get Bridge only (every extra server is withheld) and keep working.", " To replace it, re-run: install epic-implementer");
50
+ break;
51
+ case "present":
52
+ lines.push(` PRESENT MCP grant for ${diagnostic.repoName}: Bridge + ${diagnostic.serverNames.length > 0 ? diagnostic.serverNames.join(", ") : "no extra servers"}`);
53
+ if (diagnostic.modeTooWide === true) {
54
+ lines.push(" WARNING the grant file is readable or writable by other users; its mode should be 0600.");
55
+ }
56
+ else if (diagnostic.modeTooWide === null) {
57
+ lines.push(" NOTE the grant file's permissions could not be checked.");
58
+ }
59
+ break;
60
+ }
61
+ lines.push(" The grant protects against worktree edits only; same-user shell access is not sandboxed.");
62
+ return lines.join("\n");
63
+ }
@@ -0,0 +1,288 @@
1
+ /**
2
+ * The per-repository MCP grant (BAPI-1545).
3
+ *
4
+ * The repository owner approves, once, which extra MCP servers Epic Implementer
5
+ * workers get. That approval is stored here, at
6
+ * `~/.config/bridge/mcp-grants/<repo>.json`, OUTSIDE every worktree. The
7
+ * executor's provisioning and the `mcp-invoke` shim read ONLY this file on the
8
+ * grant path, so nothing a worker commits or edits inside its checkout can widen
9
+ * the servers or credentials it gets.
10
+ *
11
+ * Schema version 1:
12
+ *
13
+ * { version: 1, repo_name, granted_at, candidate_fingerprint, servers: [ … ] }
14
+ *
15
+ * Each server entry holds `name`, `source` (`preset` | `host` | `repository`),
16
+ * `transport` (`stdio`), `command`, `args`, optional non-secret `env`, optional
17
+ * `secret_bundle` (a credential-store target), and optional `secret_env_keys`.
18
+ * The file NEVER holds a secret value: imported secrets live in the credential
19
+ * store and the grant keeps only the reference and the key names.
20
+ *
21
+ * Schema rule: readers tolerate unknown TOP-LEVEL keys, so a later version can
22
+ * add fields without breaking an older reader. Recognized fields are projected
23
+ * into the returned record; unknown keys never reach a consumer. Other features
24
+ * keep their own records in their own files (the epic-server record is one).
25
+ *
26
+ * Errors are fixed strings. They never echo a command, an argument, an env
27
+ * value, or a credential target.
28
+ */
29
+ import path from "path";
30
+ import { validateMcpTarget } from "./bridge-config.js";
31
+ import { RECOGNIZED_SERVER_NAMES } from "./mcp-identity.js";
32
+ import { repositoryStateRecordPath } from "./repository-state-paths.js";
33
+ // ---------------------------------------------------------------------------
34
+ // Types
35
+ // ---------------------------------------------------------------------------
36
+ export const MCP_GRANT_VERSION = 1;
37
+ /** At most this many granted servers, matching the capability-statement bound. */
38
+ export const MCP_GRANT_MAX_SERVERS = 32;
39
+ /** At most this many characters in a granted server name. */
40
+ export const MCP_GRANT_MAX_NAME_LENGTH = 64;
41
+ const SOURCES = ["preset", "host", "repository"];
42
+ // ---------------------------------------------------------------------------
43
+ // Name rules
44
+ // ---------------------------------------------------------------------------
45
+ /**
46
+ * One prompt-safe name policy shared by the grant, the capability statement, and
47
+ * the worker prompt: a letter or digit, then letters, digits, `.`, `_`, or `-`,
48
+ * at most 64 characters. It is stricter than `validateMcpTarget()` (which it
49
+ * also passes), so a granted name can be printed in a one-line prompt with no
50
+ * quoting.
51
+ */
52
+ const GRANT_NAME_RE = /^[A-Za-z0-9][A-Za-z0-9._-]{0,63}$/;
53
+ /** Bridge's own registration names. Bridge is always provisioned and never granted. */
54
+ export const BRIDGE_RESERVED_SERVER_NAMES = ["bapi", ...RECOGNIZED_SERVER_NAMES];
55
+ /** True when `name` may be granted: prompt-safe, a valid target, and not Bridge. */
56
+ export function isGrantableServerName(name) {
57
+ if (typeof name !== "string" || !GRANT_NAME_RE.test(name))
58
+ return false;
59
+ const target = validateMcpTarget(name);
60
+ if (!target.ok || target.value !== name)
61
+ return false;
62
+ return !BRIDGE_RESERVED_SERVER_NAMES.includes(name);
63
+ }
64
+ const ENV_KEY_RE = /^[A-Za-z_][A-Za-z0-9_]*$/;
65
+ const FINGERPRINT_RE = /^[0-9a-f]{64}$/;
66
+ function hasControlChars(value) {
67
+ for (let i = 0; i < value.length; i++) {
68
+ const code = value.charCodeAt(i);
69
+ if (code <= 0x1f || code === 0x7f)
70
+ return true;
71
+ }
72
+ return false;
73
+ }
74
+ function isPlainObject(value) {
75
+ return value !== null && typeof value === "object" && !Array.isArray(value);
76
+ }
77
+ function isIsoTimestamp(value) {
78
+ return typeof value === "string" && value.length <= 64 && /^\d{4}-\d{2}-\d{2}T/.test(value) && !Number.isNaN(Date.parse(value));
79
+ }
80
+ function validateServerEntry(raw) {
81
+ if (!isPlainObject(raw))
82
+ return { ok: false };
83
+ const { name, source, transport, command, args, env, secret_bundle, secret_env_keys } = raw;
84
+ if (!isGrantableServerName(name))
85
+ return { ok: false };
86
+ if (typeof source !== "string" || !SOURCES.includes(source))
87
+ return { ok: false };
88
+ if (transport !== "stdio")
89
+ return { ok: false };
90
+ if (typeof command !== "string" || command.trim().length === 0 || hasControlChars(command))
91
+ return { ok: false };
92
+ if (!Array.isArray(args) || args.some((a) => typeof a !== "string" || hasControlChars(a)))
93
+ return { ok: false };
94
+ const entry = {
95
+ name,
96
+ source: source,
97
+ transport: "stdio",
98
+ command,
99
+ args: [...args],
100
+ };
101
+ if (env !== undefined) {
102
+ if (!isPlainObject(env))
103
+ return { ok: false };
104
+ const out = {};
105
+ for (const [key, value] of Object.entries(env)) {
106
+ if (!ENV_KEY_RE.test(key) || typeof value !== "string")
107
+ return { ok: false };
108
+ out[key] = value;
109
+ }
110
+ entry.env = out;
111
+ }
112
+ if (secret_bundle !== undefined) {
113
+ if (typeof secret_bundle !== "string" || secret_bundle.trim().length === 0 || hasControlChars(secret_bundle)) {
114
+ return { ok: false };
115
+ }
116
+ entry.secret_bundle = secret_bundle;
117
+ }
118
+ if (secret_env_keys !== undefined) {
119
+ if (!Array.isArray(secret_env_keys) || secret_env_keys.some((k) => typeof k !== "string" || !ENV_KEY_RE.test(k))) {
120
+ return { ok: false };
121
+ }
122
+ // A key named twice is a malformed list, not something to silently dedupe.
123
+ if (new Set(secret_env_keys).size !== secret_env_keys.length)
124
+ return { ok: false };
125
+ // Key names without a bundle to supply them are meaningless.
126
+ if (entry.secret_bundle === undefined && secret_env_keys.length > 0)
127
+ return { ok: false };
128
+ entry.secret_env_keys = [...secret_env_keys];
129
+ }
130
+ return { ok: true, entry };
131
+ }
132
+ /**
133
+ * Validate a parsed grant document against the expected repository. Unknown
134
+ * top-level keys are tolerated and dropped; every recognized field is checked.
135
+ */
136
+ export function validateMcpGrant(raw, expectedRepoName) {
137
+ if (!isPlainObject(raw))
138
+ return { ok: false, reason: "the grant file is not a JSON object" };
139
+ if (raw.version !== MCP_GRANT_VERSION)
140
+ return { ok: false, reason: "the grant file has an unsupported version" };
141
+ if (raw.repo_name !== expectedRepoName) {
142
+ return { ok: false, reason: "the grant file names a different repository" };
143
+ }
144
+ if (!isIsoTimestamp(raw.granted_at))
145
+ return { ok: false, reason: "the grant file has an invalid granted_at" };
146
+ if (typeof raw.candidate_fingerprint !== "string" || !FINGERPRINT_RE.test(raw.candidate_fingerprint)) {
147
+ return { ok: false, reason: "the grant file has an invalid candidate_fingerprint" };
148
+ }
149
+ if (!Array.isArray(raw.servers) || raw.servers.length > MCP_GRANT_MAX_SERVERS) {
150
+ return { ok: false, reason: "the grant file has an invalid servers list" };
151
+ }
152
+ const servers = [];
153
+ const seen = new Set();
154
+ for (const candidate of raw.servers) {
155
+ const validated = validateServerEntry(candidate);
156
+ if (!validated.ok)
157
+ return { ok: false, reason: "the grant file has an invalid server entry" };
158
+ if (seen.has(validated.entry.name))
159
+ return { ok: false, reason: "the grant file names a server twice" };
160
+ seen.add(validated.entry.name);
161
+ servers.push(validated.entry);
162
+ }
163
+ return {
164
+ ok: true,
165
+ grant: {
166
+ version: MCP_GRANT_VERSION,
167
+ repo_name: expectedRepoName,
168
+ granted_at: raw.granted_at,
169
+ candidate_fingerprint: raw.candidate_fingerprint,
170
+ servers,
171
+ },
172
+ };
173
+ }
174
+ // ---------------------------------------------------------------------------
175
+ // Reader
176
+ // ---------------------------------------------------------------------------
177
+ /** The grant file path for a repository, or null when the name is unusable. */
178
+ export function mcpGrantPath(repoName, deps) {
179
+ const resolved = repositoryStateRecordPath("mcp-grants", repoName, deps);
180
+ return resolved.ok ? resolved.path : null;
181
+ }
182
+ /**
183
+ * Read the grant for `repoName`. Only `ENOENT` is `absent`; anything else that
184
+ * stops a usable grant (unreadable, malformed, unsupported version, invalid
185
+ * identity, mismatched repository) is `unusable` with a fixed reason.
186
+ */
187
+ export async function readMcpGrant(repoName, deps) {
188
+ const resolved = repositoryStateRecordPath("mcp-grants", repoName, deps);
189
+ if (!resolved.ok)
190
+ return { state: "unusable", reason: "the repository name is not usable as a grant name" };
191
+ let text;
192
+ try {
193
+ text = await deps.readFile(resolved.path);
194
+ }
195
+ catch (err) {
196
+ const code = err && typeof err === "object" ? err.code : undefined;
197
+ if (code === "ENOENT")
198
+ return { state: "absent" };
199
+ return { state: "unusable", reason: "the grant file could not be read" };
200
+ }
201
+ let parsed;
202
+ try {
203
+ parsed = JSON.parse(text);
204
+ }
205
+ catch {
206
+ return { state: "unusable", reason: "the grant file is not valid JSON" };
207
+ }
208
+ const validated = validateMcpGrant(parsed, resolved.repoName);
209
+ if (!validated.ok)
210
+ return { state: "unusable", reason: validated.reason };
211
+ return { state: "ok", grant: validated.grant, path: resolved.path };
212
+ }
213
+ let tempCounter = 0;
214
+ function defaultTempSuffix() {
215
+ tempCounter += 1;
216
+ return `${process.pid}.${tempCounter}`;
217
+ }
218
+ /** Serialize a grant deterministically: 2-space indent and a trailing newline. */
219
+ export function formatMcpGrant(grant) {
220
+ return `${JSON.stringify(grant, null, 2)}\n`;
221
+ }
222
+ /**
223
+ * Publish a grant durably, following `durablyReplaceCredentialStoreJson()`:
224
+ * a same-directory temp file created with mode `0600`, write, fsync, close,
225
+ * chmod `0600`, atomic rename, then a best-effort directory fsync. The
226
+ * `mcp-grants` directory is created and held at mode `0700`, including when it
227
+ * already existed with wider permissions. A failure leaves any previous grant in
228
+ * place and returns a fixed error.
229
+ */
230
+ export async function writeMcpGrant(grant, deps) {
231
+ const validated = validateMcpGrant(grant, grant.repo_name);
232
+ if (!validated.ok)
233
+ return { ok: false, error: "the grant to write is not valid" };
234
+ const resolved = repositoryStateRecordPath("mcp-grants", grant.repo_name, deps);
235
+ if (!resolved.ok)
236
+ return { ok: false, error: "the repository name is not usable as a grant name" };
237
+ const isPosix = deps.platform !== "win32";
238
+ const dir = resolved.dir;
239
+ const tempPath = path.join(dir, `${path.basename(resolved.path)}.${(deps.tempSuffix ?? defaultTempSuffix)()}.tmp`);
240
+ let handle;
241
+ try {
242
+ await deps.mkdir(dir, { recursive: true });
243
+ if (isPosix)
244
+ await deps.chmod(dir, 0o700);
245
+ handle = await deps.open(tempPath, "wx", isPosix ? 0o600 : undefined);
246
+ await handle.writeFile(formatMcpGrant(validated.grant), { encoding: "utf-8" });
247
+ await handle.sync();
248
+ await handle.close();
249
+ handle = undefined;
250
+ if (isPosix)
251
+ await deps.chmod(tempPath, 0o600);
252
+ await deps.rename(tempPath, resolved.path);
253
+ }
254
+ catch {
255
+ if (handle) {
256
+ try {
257
+ await handle.close();
258
+ }
259
+ catch {
260
+ /* a close failure must not mask the write failure */
261
+ }
262
+ }
263
+ if (deps.unlink) {
264
+ try {
265
+ await deps.unlink(tempPath);
266
+ }
267
+ catch {
268
+ /* best-effort temp cleanup; the previous grant is untouched */
269
+ }
270
+ }
271
+ return { ok: false, error: "the grant file could not be written" };
272
+ }
273
+ if (isPosix) {
274
+ try {
275
+ const dirHandle = await deps.open(dir, "r");
276
+ try {
277
+ await dirHandle.sync();
278
+ }
279
+ finally {
280
+ await dirHandle.close();
281
+ }
282
+ }
283
+ catch {
284
+ /* best-effort: the file itself was fsynced and renamed */
285
+ }
286
+ }
287
+ return { ok: true, path: resolved.path };
288
+ }
@@ -20,6 +20,14 @@ import { codexHome } from "./codex-home.js";
20
20
  // Path helpers (pure)
21
21
  // ---------------------------------------------------------------------------
22
22
  /** POSIX-style join that avoids importing node:path (keeps module I/O-free). */
23
+ /**
24
+ * BAPI-1545: Cursor's USER-scope MCP file, `~/.cursor/mcp.json`. It shares the
25
+ * project target's relative path, joined to the home directory instead of the
26
+ * project root, so the grant setup item reads the same file Cursor does.
27
+ */
28
+ export function resolveCursorUserConfigPath(homedir) {
29
+ return joinPath(homedir, ".cursor/mcp.json");
30
+ }
23
31
  function joinPath(base, rel) {
24
32
  const trimmedBase = base.endsWith("/") ? base.slice(0, -1) : base;
25
33
  const trimmedRel = rel.startsWith("/") ? rel.slice(1) : rel;
@@ -25,6 +25,29 @@ export const MCP_PACKAGE_NAME = "@bridge_gpt/mcp-server";
25
25
  * JSON launcher inspection and the pure Codex TOML parser (BAPI-1445).
26
26
  */
27
27
  export const WORKTREE_SHIM_TOKEN = "mcp-invoke";
28
+ /** True for an absolute POSIX (`/…`) or Windows (`C:\…`, `C:/…`, `\\server\…`) path. */
29
+ function isAbsoluteAnyPlatform(value) {
30
+ return value.startsWith("/") || /^[A-Za-z]:[\\/]/.test(value) || value.startsWith("\\\\");
31
+ }
32
+ /**
33
+ * True for a local-build launcher (BAPI-1636): command `node` whose first
34
+ * argument is an absolute POSIX or Windows path ending in `build/index.js`, with
35
+ * no {@link WORKTREE_SHIM_TOKEN} and no {@link MCP_PACKAGE_NAME} token. Pure; it
36
+ * says nothing about which Bridge endpoint the build talks to.
37
+ */
38
+ export function isLocalBuildLauncher(command, args) {
39
+ if (command !== "node" || !Array.isArray(args) || args.length === 0)
40
+ return false;
41
+ // `args[0]` is read directly: this module's static contract pins its `const` count.
42
+ if (typeof args[0] !== "string" || !isAbsoluteAnyPlatform(args[0]))
43
+ return false;
44
+ if (!args[0].replace(/\\/g, "/").endsWith("/build/index.js"))
45
+ return false;
46
+ return !args.some((a) => typeof a !== "string" ||
47
+ a === WORKTREE_SHIM_TOKEN ||
48
+ a === MCP_PACKAGE_NAME ||
49
+ a.startsWith(`${MCP_PACKAGE_NAME}@`));
50
+ }
28
51
  /** The README resource URI served by the MCP server. */
29
52
  export const MCP_README_URI = `${MCP_SERVER_NAME}://readme`;
30
53
  /**
@@ -15,6 +15,12 @@
15
15
  * manifest entry, resolves the target's required env overlay atomically from
16
16
  * the secret store, and spawns the manifest `command`/`args`.
17
17
  *
18
+ * BAPI-1545 adds the GRANT PATH, selected by `--grant-repo <repo>`. On it the
19
+ * shim never reads `<project-root>/.bridge/config`: `--target bapi` takes its
20
+ * repository identity from the flag, and every other target is resolved from
21
+ * the owner's grant file outside the worktree (`mcp-grant.ts`). Without the
22
+ * flag, both legacy paths above are unchanged.
23
+ *
18
24
  * This file is the highest-risk surface of the worktree-credentials work: the
19
25
  * stdio passthrough plus the signal/exit-code contract is covered exhaustively
20
26
  * by its unit tests.
@@ -23,11 +29,13 @@ import { spawn, execFile } from "child_process";
23
29
  import { stat, readFile } from "fs/promises";
24
30
  import path from "path";
25
31
  import os from "os";
26
- import { resolveRepoNameForProjectRoot, readBridgeConfig, validateMcpTarget, } from "./bridge-config.js";
27
- import { resolveBapiCredentials } from "./credential-store.js";
32
+ import { resolveRepoNameForProjectRoot, readBridgeConfig, validateMcpTarget, validateRepoName, } from "./bridge-config.js";
33
+ import { resolveBapiCredentials, resolveCredentialBundle, } from "./credential-store.js";
34
+ import { readMcpGrant } from "./mcp-grant.js";
35
+ import { applyPlaywrightOriginLimit, isPlaywrightPresetEntry, PLAYWRIGHT_ORIGIN_ENV_KEYS, resolvePlaywrightAllowedOrigin, } from "./mcp-presets.js";
28
36
  import { describeBaseUrlRejection, validateHttpBaseUrl } from "./base-url.js";
29
37
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
30
- import { getThirdPartyTargetDefinition, resolveThirdPartyTargetEnv, validateThirdPartyTargetManifestEntry, } from "./third-party-mcp-targets.js";
38
+ import { getThirdPartyTargetDefinition, grantedEntryRequiredKeys, resolveThirdPartyTargetEnv, validateGrantedTargetEntry, validateThirdPartyTargetManifestEntry, } from "./third-party-mcp-targets.js";
31
39
  // ---------------------------------------------------------------------------
32
40
  // Usage / argument parsing
33
41
  // ---------------------------------------------------------------------------
@@ -54,10 +62,14 @@ export function getMcpInvokeUsage() {
54
62
  " omitted, the child inherits BAPI_BASE_URL",
55
63
  " unchanged. Must be an absolute http/https URL",
56
64
  " with no embedded username or password.",
65
+ " --grant-repo <REPO> Optional. Resolve the target from the owner's",
66
+ " MCP grant for this repository (outside the",
67
+ " worktree) and never from .bridge/config. With",
68
+ " --target bapi, use this repository name.",
57
69
  " -h, --help Show this help",
58
70
  ].join("\n");
59
71
  }
60
- const KNOWN_FLAGS = new Set(["--target", "--project-root", "--base-url"]);
72
+ const KNOWN_FLAGS = new Set(["--target", "--project-root", "--base-url", "--grant-repo"]);
61
73
  /**
62
74
  * Parse `--target`, `--project-root`, and the optional `--base-url` (split or `=`
63
75
  * form). Rejects unknown flags, positional arguments, missing values, and
@@ -73,6 +85,7 @@ export function parseMcpInvokeArgs(argv) {
73
85
  let target;
74
86
  let projectRoot;
75
87
  let baseUrl;
88
+ let grantRepo;
76
89
  for (let i = 0; i < argv.length; i++) {
77
90
  const token = argv[i];
78
91
  if (token === "-h" || token === "--help") {
@@ -115,6 +128,17 @@ export function parseMcpInvokeArgs(argv) {
115
128
  }
116
129
  baseUrl = validation.baseUrl;
117
130
  }
131
+ else if (flag === "--grant-repo") {
132
+ if (grantRepo !== undefined) {
133
+ return { status: "error", message: "Duplicate --grant-repo flag" };
134
+ }
135
+ const repo = validateRepoName(value);
136
+ // The rejected value is never echoed.
137
+ if (!repo.ok || repo.value !== value) {
138
+ return { status: "error", message: "Invalid --grant-repo: not a usable repository name" };
139
+ }
140
+ grantRepo = repo.value;
141
+ }
118
142
  else {
119
143
  if (projectRoot !== undefined) {
120
144
  return { status: "error", message: "Duplicate --project-root flag" };
@@ -141,9 +165,13 @@ export function parseMcpInvokeArgs(argv) {
141
165
  message: "--base-url is only valid with --target bapi",
142
166
  };
143
167
  }
144
- return baseUrl === undefined
145
- ? { status: "ok", target: targetValidation.value, projectRoot }
146
- : { status: "ok", target: targetValidation.value, projectRoot, baseUrl };
168
+ return {
169
+ status: "ok",
170
+ target: targetValidation.value,
171
+ projectRoot,
172
+ ...(baseUrl !== undefined ? { baseUrl } : {}),
173
+ ...(grantRepo !== undefined ? { grantRepo } : {}),
174
+ };
147
175
  }
148
176
  // ---------------------------------------------------------------------------
149
177
  // Validation, env construction, signals
@@ -374,6 +402,66 @@ export async function resolveThirdPartyInvocation(target, projectRoot, deps) {
374
402
  const env = buildChildEnv(deps.env, envResult.env);
375
403
  return { ok: true, invocation: { command, args, env } };
376
404
  }
405
+ /** One fixed line when `BRIDGE_EPIC_SERVER_URL` is set but unusable. Never the value. */
406
+ export const PLAYWRIGHT_INVALID_EPIC_SERVER_URL_MESSAGE = "Warning: BRIDGE_EPIC_SERVER_URL is not an http or https URL; the browser is limited to an origin that allows nothing.";
407
+ /**
408
+ * BAPI-1545: resolve a non-Bridge target from the owner's grant ONLY. Never
409
+ * reads `.bridge/config`. A missing entry, an unusable or absent grant, or a
410
+ * failed credential resolution is a fixed, secret-free error (the shim exits
411
+ * non-zero, the host shows the server as failed, and the job continues).
412
+ *
413
+ * The child env is the inherited env, then the entry's non-secret `env`, then
414
+ * the resolved secrets. For the Playwright preset, exactly one
415
+ * `--allowed-origins <origin>` pair is appended (deny-all when
416
+ * `BRIDGE_EPIC_SERVER_URL` is absent or invalid), and the ambient
417
+ * `PLAYWRIGHT_MCP_ALLOWED_ORIGINS` / `PLAYWRIGHT_MCP_BLOCKED_ORIGINS` are removed
418
+ * last, so nothing ambient can widen the list.
419
+ */
420
+ export async function resolveGrantedInvocation(target, grantRepo, deps) {
421
+ const read = await deps.readGrant(grantRepo);
422
+ if (read.state === "absent") {
423
+ return { ok: false, error: `no MCP grant exists for this repository; target '${target}' is not granted` };
424
+ }
425
+ if (read.state === "unusable") {
426
+ return { ok: false, error: `the MCP grant for this repository is unusable (${read.reason}); target '${target}' is withheld` };
427
+ }
428
+ const entry = read.grant.servers.find((s) => s.name === target);
429
+ if (!entry) {
430
+ return { ok: false, error: `target '${target}' is not in the MCP grant for this repository` };
431
+ }
432
+ const validation = validateGrantedTargetEntry(entry);
433
+ if (!validation.ok)
434
+ return { ok: false, error: validation.error };
435
+ const overlay = { ...(entry.env ?? {}) };
436
+ const keys = grantedEntryRequiredKeys(entry);
437
+ if (keys.length > 0) {
438
+ if (entry.secret_bundle === undefined) {
439
+ return { ok: false, error: `granted server '${target}' requires a secret_bundle` };
440
+ }
441
+ const resolved = await deps.resolveBundle(entry.secret_bundle, keys);
442
+ if (!resolved.ok) {
443
+ return { ok: false, error: `failed to resolve credentials for '${target}': ${resolved.error}` };
444
+ }
445
+ for (const key of keys) {
446
+ const value = resolved.values[key];
447
+ if (typeof value !== "string") {
448
+ return { ok: false, error: `failed to resolve credentials for '${target}': a required key is missing` };
449
+ }
450
+ overlay[key] = value;
451
+ }
452
+ }
453
+ let args = [...entry.args];
454
+ const env = buildChildEnv(deps.env, overlay);
455
+ if (isPlaywrightPresetEntry(entry)) {
456
+ const origin = resolvePlaywrightAllowedOrigin(deps.env);
457
+ if (origin.invalidSupplied)
458
+ deps.stderr(PLAYWRIGHT_INVALID_EPIC_SERVER_URL_MESSAGE);
459
+ args = applyPlaywrightOriginLimit(args, origin.origin);
460
+ for (const key of PLAYWRIGHT_ORIGIN_ENV_KEYS)
461
+ delete env[key];
462
+ }
463
+ return { ok: true, invocation: { command: entry.command, args, env } };
464
+ }
377
465
  /**
378
466
  * Run the `mcp-invoke` subcommand. Returns a process exit code (never calls
379
467
  * `process.exit`). Parses args BEFORE any validation/resolution; validates the
@@ -397,7 +485,7 @@ export async function runMcpInvokeCli(argv, overrides = {}) {
397
485
  stderr(getMcpInvokeUsage());
398
486
  return 1;
399
487
  }
400
- const { target, projectRoot, baseUrl } = parsed;
488
+ const { target, projectRoot, baseUrl, grantRepo } = parsed;
401
489
  const statFn = overrides.stat ?? ((p) => stat(p));
402
490
  const dirCheck = await validateProjectRootDirectory(projectRoot, statFn);
403
491
  if (!dirCheck.ok) {
@@ -412,12 +500,37 @@ export async function runMcpInvokeCli(argv, overrides = {}) {
412
500
  stat: (p) => stat(p),
413
501
  stderr,
414
502
  };
503
+ // BAPI-1545: on the grant path a non-Bridge target is resolved from the grant
504
+ // file only, before any worktree-config reader is even constructed.
505
+ if (grantRepo !== undefined && target !== "bapi") {
506
+ const readGrant = overrides.readMcpGrant ??
507
+ ((repo) => readMcpGrant(repo, { env, homedir: os.homedir, readFile: (p) => readFile(p, "utf-8") }));
508
+ const resolveBundle = overrides.resolveCredentialBundle ??
509
+ ((bundle, keys) => resolveCredentialBundle(bundle, keys, credentialDeps));
510
+ const resolved = await resolveGrantedInvocation(target, grantRepo, {
511
+ env,
512
+ readGrant,
513
+ resolveBundle,
514
+ stderr,
515
+ });
516
+ if (!resolved.ok) {
517
+ stderr(`Error: ${resolved.error}`);
518
+ return 1;
519
+ }
520
+ return spawnInvocation(resolved.invocation, overrides);
521
+ }
415
522
  if (target === "bapi") {
416
- const resolveRepoName = overrides.resolveRepoName ??
417
- ((pr) => resolveRepoNameForProjectRoot(pr, {
418
- readFile: (p) => readFile(p, "utf-8"),
419
- runCommand: defaultRunCommand,
420
- }));
523
+ // BAPI-1545: with `--grant-repo`, the trusted repository name is used as is
524
+ // and the worktree's `.bridge/config` is never consulted, so a worker that
525
+ // rewrites `repoName` there cannot pick another repository's credential.
526
+ // The grant itself is not read: Bridge works even when the grant is unusable.
527
+ const resolveRepoName = grantRepo !== undefined
528
+ ? async () => ({ ok: true, value: grantRepo })
529
+ : overrides.resolveRepoName ??
530
+ ((pr) => resolveRepoNameForProjectRoot(pr, {
531
+ readFile: (p) => readFile(p, "utf-8"),
532
+ runCommand: defaultRunCommand,
533
+ }));
421
534
  const resolveCredentials = overrides.resolveCredentials ??
422
535
  ((rn) => resolveBapiCredentials(rn, credentialDeps));
423
536
  // The parsed URL reaches ONLY this branch; the parser already rejected