@bridge_gpt/mcp-server 0.2.71 → 0.2.73

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (198) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +22 -3
  3. package/build/agent-notes.js +171 -95
  4. package/build/agents.generated.js +7 -7
  5. package/build/bridge-permissions.js +31 -0
  6. package/build/bridge-worktree-inspection.js +237 -0
  7. package/build/check-evidence.js +6 -0
  8. package/build/ci-system-detection.js +50 -0
  9. package/build/ci-trigger-adapters.js +631 -0
  10. package/build/ci-trigger-install.js +106 -0
  11. package/build/claude-review-workflow.js +1 -1
  12. package/build/cli-help.js +6 -0
  13. package/build/codex-auto-recovery.js +126 -0
  14. package/build/codex-launcher-pin.js +33 -2
  15. package/build/codex-skill-adapter.js +5 -1
  16. package/build/command-host.js +33 -0
  17. package/build/commands.generated.js +7 -6
  18. package/build/conductor/bridge-api-client.js +1352 -50
  19. package/build/conductor/bring-up-facts.js +18 -5
  20. package/build/conductor/command-drift-production.js +42 -17
  21. package/build/conductor/command-drift.js +47 -0
  22. package/build/conductor/declare-blocked.js +554 -0
  23. package/build/conductor/doctor.js +187 -28
  24. package/build/conductor/driver-commands.js +141 -0
  25. package/build/conductor/driver-guard.js +277 -0
  26. package/build/conductor/driver-lapse.js +321 -0
  27. package/build/conductor/driver-register.js +176 -0
  28. package/build/conductor/driver-release.js +174 -0
  29. package/build/conductor/driver-session-state.js +315 -0
  30. package/build/conductor/epic-branch-ci-inspection.js +222 -29
  31. package/build/conductor/epic-implementer-cli.js +213 -13
  32. package/build/conductor/epic-server-database.js +162 -0
  33. package/build/conductor/epic-server-guidance.js +278 -0
  34. package/build/conductor/epic-server-journal.js +239 -0
  35. package/build/conductor/epic-server-processes.js +324 -0
  36. package/build/conductor/epic-server-recipe.js +397 -0
  37. package/build/conductor/epic-server-runtime.js +1207 -0
  38. package/build/conductor/epic-server-sfcc.js +107 -0
  39. package/build/conductor/epic-server-state.js +427 -0
  40. package/build/conductor/epic-server.js +594 -0
  41. package/build/conductor/gate-discovery.js +281 -10
  42. package/build/conductor/gate-settings-review.js +525 -5
  43. package/build/conductor/git-hooks-uninstall.js +112 -0
  44. package/build/conductor/git-hooks.js +81 -15
  45. package/build/conductor/guided-repair.js +10 -1
  46. package/build/conductor/install-doctor.js +2 -4
  47. package/build/conductor/launch-need-probes.js +6 -53
  48. package/build/conductor/launch-plan.js +318 -121
  49. package/build/conductor/local-merge.js +12 -1
  50. package/build/conductor/merge-execution-contract.js +1 -1
  51. package/build/conductor/merged-child-check.js +2 -1
  52. package/build/conductor/prerequisite-inputs.js +1213 -0
  53. package/build/conductor/readiness-assessment.js +93 -0
  54. package/build/conductor/readiness-cli.js +30 -9
  55. package/build/conductor/readiness-prerequisites.js +77 -5
  56. package/build/conductor/readiness-sections.js +146 -126
  57. package/build/conductor/readiness.js +21 -3
  58. package/build/conductor/recovery-cli.js +236 -15
  59. package/build/conductor/recovery-operations.js +34 -4
  60. package/build/conductor/repair-contract.js +33 -0
  61. package/build/conductor/tools.js +36 -4
  62. package/build/conductor/wait-run-attention.js +115 -0
  63. package/build/conductor/wait-run-cli.js +300 -21
  64. package/build/conductor/worker-database-doctor-inspector.js +34 -2
  65. package/build/conductor/worker-setup-tally.js +27 -0
  66. package/build/credential-store.js +96 -21
  67. package/build/dependency-install-declarations.js +212 -0
  68. package/build/docs.generated.js +4 -4
  69. package/build/doctor.js +91 -8
  70. package/build/drive-epic-help.js +23 -4
  71. package/build/drive-epic.js +1841 -340
  72. package/build/engine-paths.js +20 -0
  73. package/build/epic-branch-ci-summary.js +140 -0
  74. package/build/epic-capability-statement.js +107 -0
  75. package/build/epic-ci-workflow-drift.js +30 -15
  76. package/build/epic-ci-workflow-install.js +110 -42
  77. package/build/epic-ci-workflow-v2.js +274 -0
  78. package/build/epic-ci-workflow.js +38 -12
  79. package/build/epic-implementer-bin.js +2184 -52
  80. package/build/epic-launch-context.js +607 -0
  81. package/build/epic-launch-profile.js +1 -1
  82. package/build/epic-server-record.js +273 -0
  83. package/build/epic-shared/bridge-client.js +11 -3
  84. package/build/escalation-reachability.js +43 -0
  85. package/build/executor/ci-fix-test-runs.js +334 -0
  86. package/build/executor/cli.js +2 -0
  87. package/build/executor/completion-contract.js +24 -1
  88. package/build/executor/credentials.js +1 -1
  89. package/build/executor/delivery-observations.js +113 -0
  90. package/build/executor/delivery-outcome.js +30 -0
  91. package/build/executor/dependency-refresh-runner.js +132 -0
  92. package/build/executor/dependency-refresh.js +530 -0
  93. package/build/executor/deps.js +4 -0
  94. package/build/executor/env.js +119 -17
  95. package/build/executor/epic-server-context.js +141 -0
  96. package/build/executor/gate-qualification-job.js +127 -26
  97. package/build/executor/harness-coverage.js +19 -0
  98. package/build/executor/http-client.js +87 -6
  99. package/build/executor/index.js +2 -1
  100. package/build/executor/install-preflight.js +1 -1
  101. package/build/executor/job-runner.js +659 -87
  102. package/build/executor/likely-tests.js +94 -97
  103. package/build/executor/observation.js +8 -0
  104. package/build/executor/pre-pr-checks.js +363 -0
  105. package/build/executor/prompt-spec.js +127 -5
  106. package/build/executor/reconcile-overlap-job.js +5 -3
  107. package/build/executor/required-verification.js +28 -0
  108. package/build/executor/required-work-diagnostics.js +32 -0
  109. package/build/executor/required-work-ledger.js +955 -39
  110. package/build/executor/results.js +100 -0
  111. package/build/executor/service-discovery.js +42 -0
  112. package/build/executor/service-lifecycle.js +109 -2
  113. package/build/executor/service-uninstall.js +205 -0
  114. package/build/executor/service-unit.js +5 -3
  115. package/build/executor/terminal-mutation.js +8 -0
  116. package/build/executor/test-clock.js +3 -0
  117. package/build/executor/verification-hints.js +179 -0
  118. package/build/executor/worker-command.js +126 -5
  119. package/build/executor/worker-database-config.js +281 -0
  120. package/build/executor/worker-database-target.js +16 -12
  121. package/build/executor/worker-database.js +575 -116
  122. package/build/executor/worker-finalization.js +71 -10
  123. package/build/executor/worker-guard-hook.js +10 -2
  124. package/build/executor/worker-resources.js +25 -3
  125. package/build/executor/worker-verification-guidance.js +55 -5
  126. package/build/executor/worktree-inspection.js +42 -0
  127. package/build/executor/worktree.js +20 -1
  128. package/build/executor-launch.js +54 -2
  129. package/build/generated-assets-catalog.js +2 -2
  130. package/build/github-sign-in.js +1 -1
  131. package/build/index.js +1111 -381
  132. package/build/init.js +29 -14
  133. package/build/install-bridge-conductor-answers.js +465 -0
  134. package/build/install-bridge-conductor-apply.js +259 -0
  135. package/build/install-bridge-conductor-assessment.js +895 -0
  136. package/build/install-bridge-conductor-compact.js +161 -0
  137. package/build/install-bridge-conductor-contracts.js +63 -0
  138. package/build/install-bridge-conductor-gate.js +1383 -188
  139. package/build/install-bridge-conductor-setup.js +637 -92
  140. package/build/install-bridge-conductor.js +3163 -740
  141. package/build/install-bridge.js +601 -128
  142. package/build/install-maintenance.js +127 -0
  143. package/build/install-reexec.js +1 -1
  144. package/build/launcher-config-inspection.js +162 -1
  145. package/build/local-cleanup.js +59 -0
  146. package/build/mcp-grant-candidates.js +767 -0
  147. package/build/mcp-grant-doctor.js +63 -0
  148. package/build/mcp-grant.js +288 -0
  149. package/build/mcp-host-targets.js +8 -0
  150. package/build/mcp-identity.js +23 -0
  151. package/build/mcp-install-state.js +68 -2
  152. package/build/mcp-invoke.js +126 -13
  153. package/build/mcp-presets.js +107 -0
  154. package/build/mcp-provisioning.js +134 -2
  155. package/build/mcp-registration-doctor.js +31 -2
  156. package/build/mcp-server-invocation.js +6 -1
  157. package/build/merge-workflow-install.js +236 -111
  158. package/build/package-script-semantics.js +10 -0
  159. package/build/pipeline-utils.js +1 -1
  160. package/build/pipelines.generated.js +6 -6
  161. package/build/plan-discovery.js +97 -4
  162. package/build/plan-execution-ledger.js +248 -9
  163. package/build/plan-generation-io.js +262 -0
  164. package/build/plan-generation.js +424 -0
  165. package/build/plane/build-freshness.js +6 -1
  166. package/build/plane/cli.js +75 -9
  167. package/build/plane/plane-freshness.js +23 -7
  168. package/build/plane/preflight.js +50 -10
  169. package/build/plane/shutdown.js +19 -0
  170. package/build/plane/terminal-run-cleanup.js +23 -5
  171. package/build/plane/terminal-run-status.js +4 -0
  172. package/build/printed-remedy-commands.js +229 -15
  173. package/build/readiness-check.js +1 -1
  174. package/build/readiness-prerequisites.generated.js +311 -4
  175. package/build/readme.generated.js +1 -1
  176. package/build/repository-state-paths.js +38 -0
  177. package/build/repository-toolchains.js +50 -8
  178. package/build/run-unit-tests-launcher.js +8 -1
  179. package/build/setup-change-policy.js +32 -0
  180. package/build/setup-epic.js +1192 -198
  181. package/build/setup-progress.js +44 -0
  182. package/build/setup-question.js +180 -0
  183. package/build/start-tickets.js +4 -0
  184. package/build/test-command-detection.js +32 -88
  185. package/build/test-support/notes-fs.js +40 -0
  186. package/build/third-party-mcp-targets.js +30 -0
  187. package/build/ticket-delivery-enrollment.js +30 -8
  188. package/build/ticket-delivery-run-scope.js +128 -0
  189. package/build/upgrade-cli.js +85 -2
  190. package/build/v2-readiness-requirements.js +28 -1
  191. package/build/version.generated.js +3 -3
  192. package/build/worker-guard-hook-bin.js +2 -2
  193. package/build/worktrees.js +105 -0
  194. package/docs/EPIC-IMPLEMENTER-INSTALL.md +9 -1
  195. package/docs/EPIC-IMPLEMENTER.md +5 -0
  196. package/docs/epic-implementer/getting-started.md +42 -15
  197. package/docs/epic-implementer/self-hosting.md +14 -1
  198. package/package.json +2 -2
@@ -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
  /**
@@ -17,6 +17,8 @@
17
17
  * unit-testable with in-memory fakes.
18
18
  */
19
19
  import { validPackagedAssetInventory } from "./generated-assets-context.js";
20
+ import { lstat, readFile, open, rename, unlink } from "node:fs/promises";
21
+ import { randomUUID } from "node:crypto";
20
22
  import { currentDestinationForLegacyDoc } from "./generated-assets-legacy.js";
21
23
  import { executorIdFromLaunchdFilename, executorIdFromSystemdFilename, } from "./executor/service-unit.js";
22
24
  import { HOST_PLATFORM_ORDER, isHostPlatformId, } from "./mcp-host-targets.js";
@@ -24,8 +26,72 @@ import { HOST_PLATFORM_ORDER, isHostPlatformId, } from "./mcp-host-targets.js";
24
26
  export const MCP_INSTALL_STATE_VERSION = 1;
25
27
  /** The relative path of the state file within a project. */
26
28
  export const MCP_INSTALL_STATE_RELPATH = ".bridge/install-state.json";
29
+ /** Narrow inverse: preserve the complete document and remove only this locator. */
30
+ export async function forgetInstalledExecutorServiceUnit(cwd, unitPath, homeDir, deps = { lstat, readFile, open, rename, unlink }) {
31
+ const locator = canonicalExecutorServiceUnitLocator(unitPath, homeDir);
32
+ if (!locator)
33
+ return { ok: false, reason: "invalid-target" };
34
+ const target = installStatePath(cwd);
35
+ let snapshot, raw;
36
+ try {
37
+ const parent = await deps.lstat(joinCwd(cwd, ".bridge"));
38
+ if (parent.isSymbolicLink() || !parent.isDirectory())
39
+ return { ok: false, reason: "unsafe-state" };
40
+ snapshot = await deps.lstat(target);
41
+ if (!snapshot.isFile() || snapshot.isSymbolicLink())
42
+ return { ok: false, reason: "unsafe-state" };
43
+ raw = await deps.readFile(target);
44
+ }
45
+ catch (error) {
46
+ return error.code === "ENOENT" ? { ok: true, outcome: "missing-state" } : { ok: false, reason: "unsafe-state" };
47
+ }
48
+ let doc;
49
+ try {
50
+ doc = JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(raw));
51
+ const supported = new Set(["version", "selectedPlatforms", "projectConfigPaths", "executorServiceUnitPaths", "capabilities", "packagedAssets"]);
52
+ if (!doc || Array.isArray(doc) || doc.version !== MCP_INSTALL_STATE_VERSION || Object.keys(doc).some(key => !supported.has(key)) ||
53
+ !Array.isArray(doc.selectedPlatforms) || !doc.selectedPlatforms.every(isHostPlatformId) ||
54
+ (doc.projectConfigPaths !== undefined && (!Array.isArray(doc.projectConfigPaths) || !doc.projectConfigPaths.every(isRecordableProjectPath))) ||
55
+ (doc.capabilities !== undefined && (!Array.isArray(doc.capabilities) || !doc.capabilities.every(isMcpInstallCapabilityId))) ||
56
+ (doc.packagedAssets !== undefined && !validPackagedAssetInventory(doc.packagedAssets)) ||
57
+ (doc.executorServiceUnitPaths !== undefined && (!Array.isArray(doc.executorServiceUnitPaths) || !doc.executorServiceUnitPaths.every(v => typeof v === "string" && isGeneratedExecutorUnitLocator(v))))) {
58
+ return { ok: false, reason: "unsafe-state" };
59
+ }
60
+ }
61
+ catch {
62
+ return { ok: false, reason: "unsafe-state" };
63
+ }
64
+ if (!Array.isArray(doc.executorServiceUnitPaths) || !doc.executorServiceUnitPaths.includes(locator))
65
+ return { ok: true, outcome: "unrecorded" };
66
+ doc.executorServiceUnitPaths = doc.executorServiceUnitPaths.filter(v => v !== locator);
67
+ const temp = `${target}.${randomUUID()}.tmp`;
68
+ let owned = false;
69
+ try {
70
+ const handle = await deps.open(temp, "wx", snapshot.mode & 0o777);
71
+ owned = true;
72
+ try {
73
+ await handle.writeFile(JSON.stringify(doc, null, 2) + "\n", "utf8");
74
+ }
75
+ finally {
76
+ await handle.close();
77
+ }
78
+ const now = await deps.lstat(target);
79
+ if (!now.isFile() || now.isSymbolicLink() || now.dev !== snapshot.dev || now.ino !== snapshot.ino || now.mode !== snapshot.mode || !(await deps.readFile(target)).equals(raw))
80
+ return { ok: false, reason: "concurrent-change" };
81
+ await deps.rename(temp, target);
82
+ owned = false;
83
+ return { ok: true, outcome: "forgotten" };
84
+ }
85
+ catch {
86
+ return { ok: false, reason: "publication-failed" };
87
+ }
88
+ finally {
89
+ if (owned)
90
+ await deps.unlink(temp).catch(() => { });
91
+ }
92
+ }
27
93
  /**
28
- * The conductor capabilities `install conductor` may record (BAPI-775).
94
+ * The conductor capabilities `install epic-implementer` may record (BAPI-775).
29
95
  *
30
96
  * A CLOSED vocabulary, validated on read and on write: install state is a
31
97
  * diagnostic inventory of what this tool provisioned, so an arbitrary
@@ -460,7 +526,7 @@ export async function recordInstalledExecutorServiceUnit(cwd, unitPath, homeDir,
460
526
  * {@link MCP_INSTALL_CAPABILITY_IDS} vocabulary BEFORE any read or write, so an
461
527
  * unrecognized identifier is refused with an advisory result and touches
462
528
  * nothing — never silently dropped after a rewrite. Repeating a capability is a
463
- * set-style no-op, so re-running `install conductor` cannot duplicate an entry.
529
+ * set-style no-op, so re-running `install epic-implementer` cannot duplicate an entry.
464
530
  */
465
531
  export async function recordInstalledConductorCapability(cwd, capability, deps) {
466
532
  if (!isMcpInstallCapabilityId(capability)) {