@bridge_gpt/mcp-server 0.2.73 → 0.2.74

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 (90) hide show
  1. package/README.md +5 -5
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agents.generated.js +3 -3
  4. package/build/bridge-config.js +7 -1
  5. package/build/bridge-permissions.js +3 -0
  6. package/build/command-provisioning.js +4 -3
  7. package/build/commands.generated.js +5 -5
  8. package/build/conductor/bridge-api-client.js +26 -1
  9. package/build/conductor/command-drift.js +1 -1
  10. package/build/conductor/declared-extras.js +335 -0
  11. package/build/conductor/doctor.js +2 -0
  12. package/build/conductor/driver-pass-output.js +104 -0
  13. package/build/conductor/driver-pass.js +571 -0
  14. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  15. package/build/conductor/epic-implementer-cli.js +33 -0
  16. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  17. package/build/conductor/epic-server-sfcc.js +58 -80
  18. package/build/conductor/epic-server.js +57 -4
  19. package/build/conductor/gate-discovery.js +46 -6
  20. package/build/conductor/gate-settings-review.js +51 -14
  21. package/build/credential-delivery.js +280 -0
  22. package/build/credential-launch-safety.js +142 -0
  23. package/build/credential-materialization.js +91 -16
  24. package/build/credential-references-node-deps.js +29 -0
  25. package/build/credential-references.js +1394 -0
  26. package/build/credential-references.test-fixtures.js +211 -0
  27. package/build/credential-scan-conventions.js +145 -0
  28. package/build/credential-scan.js +517 -0
  29. package/build/credential-store.js +50 -0
  30. package/build/credentials-cli.js +252 -3
  31. package/build/dependency-install-declarations.js +47 -1
  32. package/build/docs.generated.js +8 -1
  33. package/build/doctor.js +41 -0
  34. package/build/drive-epic.js +297 -37
  35. package/build/epic-branch-ci-summary.js +18 -1
  36. package/build/epic-capability-statement.js +71 -3
  37. package/build/epic-ci-workflow-drift.js +52 -13
  38. package/build/epic-ci-workflow-install.js +31 -6
  39. package/build/epic-ci-workflow-v3.js +273 -0
  40. package/build/epic-ci-workflow.js +128 -7
  41. package/build/epic-implementer-bin.js +161 -70
  42. package/build/epic-launch-context.js +102 -7
  43. package/build/epic-server-record.js +30 -15
  44. package/build/executor/credential-delivery-step.js +168 -0
  45. package/build/executor/deps.js +3 -1
  46. package/build/executor/env.js +39 -1
  47. package/build/executor/epic-server-context.js +23 -7
  48. package/build/executor/guarded-fast-forward-push.js +13 -8
  49. package/build/executor/job-runner.js +159 -17
  50. package/build/executor/permissions.js +85 -3
  51. package/build/executor/prompt-spec.js +37 -3
  52. package/build/executor-launch.js +4 -2
  53. package/build/git-exclude-lock.js +187 -0
  54. package/build/index.js +398 -269
  55. package/build/install-bridge-conductor-answers.js +84 -21
  56. package/build/install-bridge-conductor-apply.js +30 -1
  57. package/build/install-bridge-conductor-assessment.js +375 -48
  58. package/build/install-bridge-conductor-compact.js +27 -2
  59. package/build/install-bridge-conductor-contracts.js +10 -1
  60. package/build/install-bridge-conductor-gate.js +124 -11
  61. package/build/install-bridge-conductor-setup.js +46 -8
  62. package/build/install-bridge-conductor.js +625 -113
  63. package/build/install-bridge.js +88 -11
  64. package/build/install-doctor.js +38 -8
  65. package/build/install-sfcc-detection.js +120 -0
  66. package/build/install-sfcc-setup.js +185 -0
  67. package/build/mcp-grant-candidates.js +108 -96
  68. package/build/mcp-invoke.js +168 -4
  69. package/build/mcp-provisioning.js +21 -4
  70. package/build/mcp-server-invocation.js +13 -0
  71. package/build/merge-workflow-install.js +9 -1
  72. package/build/pipelines.generated.js +2 -1
  73. package/build/plane/status.js +8 -2
  74. package/build/printed-remedy-commands.js +5 -0
  75. package/build/project-root.js +40 -0
  76. package/build/readme.generated.js +1 -1
  77. package/build/repository-state-paths.js +5 -2
  78. package/build/repository-toolchains.js +6 -3
  79. package/build/setup-epic.js +116 -15
  80. package/build/sfcc/credentials.js +3 -2
  81. package/build/sfcc/hostname.js +98 -2
  82. package/build/sfcc/tool-wrapper.js +6 -95
  83. package/build/start-tickets.js +193 -29
  84. package/build/test-support/executor-source-files.js +200 -0
  85. package/build/testing-config-client.js +25 -2
  86. package/build/third-party-mcp-targets.js +35 -4
  87. package/build/version.generated.js +3 -3
  88. package/build/with-credentials.js +208 -0
  89. package/build/worktree-credential-delivery.js +340 -0
  90. package/package.json +1 -1
@@ -0,0 +1,208 @@
1
+ /**
2
+ * BAPI-1647: `with-credentials --repo <repo> -- <agent argv>` — an internal
3
+ * subcommand that `start-tickets` puts in front of the agent in each tab.
4
+ *
5
+ * It resolves the repository's approved SANDBOX shell variables through child
6
+ * 1's `forWorkerLaunch()` in its OWN process, at the moment the agent starts,
7
+ * and then runs the agent with those variables in its environment. So a value
8
+ * never appears in the tab command, in any argv, in a prompt file, or in a
9
+ * `start-tickets` summary, and a rotated value is picked up at the next start
10
+ * with no Bridge step.
11
+ *
12
+ * - The repository identity comes from `--repo`, which `start-tickets` writes
13
+ * from the repository it resolved itself — never from the worktree.
14
+ * - Only the variable channel is applied here. File credentials were already
15
+ * linked into the worktree before the tab opened; MCP credentials are
16
+ * resolved by the `mcp-invoke` shim.
17
+ * - Missing credentials are a notice on stderr, never a failure: the agent
18
+ * starts either way and its exit status is returned unchanged. stdout belongs
19
+ * to the agent alone.
20
+ * - A reserved worker-environment name (child 1 already refuses it in the
21
+ * record) is rechecked and dropped with a notice naming only the variable.
22
+ */
23
+ import { spawn } from "child_process";
24
+ import { existsSync } from "fs";
25
+ import path from "path";
26
+ import { validateRepoName } from "./bridge-config.js";
27
+ import { forWorkerLaunch } from "./credential-references.js";
28
+ import { createLaunchCredentialReferenceDeps, formatNoticeLines, launchResolveOptions, } from "./credential-delivery.js";
29
+ import { isWorkerEnvNameReserved } from "./executor/env.js";
30
+ import { spawnMcpCommand } from "./mcp-invoke.js";
31
+ export const WITH_CREDENTIALS_SUBCOMMAND = "with-credentials";
32
+ // ---------------------------------------------------------------------------
33
+ // Windows `.cmd` / `.bat` agents
34
+ // ---------------------------------------------------------------------------
35
+ /**
36
+ * Node cannot spawn a `.cmd`/`.bat` shim (how npm installs `claude` on
37
+ * Windows) without a shell. Rather than `shell: true`, which joins argv
38
+ * unquoted, the shim is run through `cmd.exe /d /s /c "<line>"` with every part
39
+ * escaped for both the C runtime and cmd's metacharacters (the scheme
40
+ * `cross-spawn` uses), and `windowsVerbatimArguments` so Node adds nothing.
41
+ */
42
+ const CMD_META = /([()\][%!^"`<>&|;, *?])/g;
43
+ function escapeWindowsArgument(arg) {
44
+ let escaped = arg.replace(/(\\*)"/g, '$1$1\\"').replace(/(\\*)$/, "$1$1");
45
+ escaped = `"${escaped}"`;
46
+ // Twice: once for cmd parsing the line, once for the .cmd shim re-parsing `%*`.
47
+ return escaped.replace(CMD_META, "^$1").replace(CMD_META, "^$1");
48
+ }
49
+ function escapeWindowsCommand(command) {
50
+ return command.replace(CMD_META, "^$1");
51
+ }
52
+ /**
53
+ * Resolve the agent on Windows through `PATH`/`PATHEXT`. A `.cmd`/`.bat`
54
+ * resolves to a `cmd.exe` invocation; anything else is spawned directly.
55
+ */
56
+ export function resolveWindowsAgentInvocation(command, args, env, fileExists) {
57
+ const exts = (env.PATHEXT ?? ".COM;.EXE;.BAT;.CMD").split(";").filter((e) => e.length > 0);
58
+ const hasSep = /[\\/]/.test(command);
59
+ const dirs = hasSep ? [""] : (env.PATH ?? env.Path ?? "").split(";").filter((d) => d.length > 0);
60
+ let resolved = null;
61
+ for (const dir of dirs) {
62
+ const base = dir.length === 0 ? command : path.win32.join(dir, command);
63
+ const hasExt = exts.some((e) => base.toLowerCase().endsWith(e.toLowerCase()));
64
+ for (const candidate of hasExt ? [base] : exts.map((e) => `${base}${e}`)) {
65
+ if (fileExists(candidate)) {
66
+ resolved = candidate;
67
+ break;
68
+ }
69
+ }
70
+ if (resolved)
71
+ break;
72
+ }
73
+ if (resolved && /\.(cmd|bat)$/i.test(resolved)) {
74
+ const line = [escapeWindowsCommand(path.win32.normalize(resolved)), ...args.map(escapeWindowsArgument)].join(" ");
75
+ return { command: env.ComSpec ?? env.COMSPEC ?? "cmd.exe", args: ["/d", "/s", "/c", `"${line}"`], verbatim: true };
76
+ }
77
+ return { command: resolved ?? command, args: [...args], verbatim: false };
78
+ }
79
+ export function getWithCredentialsUsage() {
80
+ return [
81
+ "Usage: with-credentials --repo <repo> -- <agent> [args...]",
82
+ "",
83
+ "Internal: run an agent with the repository's approved sandbox credential",
84
+ "variables in its environment. Used by start-tickets tabs.",
85
+ ].join("\n");
86
+ }
87
+ /** Parse argv (after the subcommand). Never echoes an agent argument. */
88
+ export function parseWithCredentialsArgs(argv) {
89
+ const separator = argv.indexOf("--");
90
+ const head = separator === -1 ? [...argv] : argv.slice(0, separator);
91
+ if (head.includes("--help") || head.includes("-h"))
92
+ return { status: "help" };
93
+ if (separator === -1)
94
+ return { status: "error", message: "missing '--' before the agent command" };
95
+ let repo;
96
+ for (let i = 0; i < head.length; i++) {
97
+ if (head[i] === "--repo") {
98
+ if (repo !== undefined)
99
+ return { status: "error", message: "--repo was given more than once" };
100
+ const value = head[i + 1];
101
+ if (value === undefined)
102
+ return { status: "error", message: "--repo needs a value" };
103
+ repo = value;
104
+ i++;
105
+ continue;
106
+ }
107
+ return { status: "error", message: "unknown option before '--'" };
108
+ }
109
+ if (repo === undefined)
110
+ return { status: "error", message: "--repo is required" };
111
+ const validated = validateRepoName(repo);
112
+ if (!validated.ok)
113
+ return { status: "error", message: `invalid --repo: ${validated.error}` };
114
+ const agent = argv.slice(separator + 1);
115
+ if (agent.length === 0 || agent[0].length === 0) {
116
+ return { status: "error", message: "the agent command after '--' is empty" };
117
+ }
118
+ return { status: "ok", repo: validated.value, command: agent[0], args: agent.slice(1) };
119
+ }
120
+ /**
121
+ * Build the agent environment: the inherited environment plus admitted
122
+ * variables. A reserved name is dropped. Returns names-only notices.
123
+ */
124
+ export function buildAgentEnv(parentEnv, values) {
125
+ const env = { ...parentEnv };
126
+ const notices = [];
127
+ const admitted = [];
128
+ for (const [name, value] of Object.entries(values)) {
129
+ if (isWorkerEnvNameReserved(name)) {
130
+ notices.push({ name, reason: "reserved_name" });
131
+ continue;
132
+ }
133
+ // Same rule as the executor's admitDeclaredCredentialEnv: an approved
134
+ // credential never overrides a variable the agent's environment already
135
+ // sets. The collision is named (never its value) and the inherited value wins.
136
+ if (env[name] !== undefined) {
137
+ notices.push({ name, reason: "name_collision" });
138
+ continue;
139
+ }
140
+ env[name] = value;
141
+ admitted.push(name);
142
+ }
143
+ return { env, notices, admitted };
144
+ }
145
+ /** Run the subcommand. Returns the agent's exit status (never calls `process.exit`). */
146
+ export async function runWithCredentialsCli(argv, overrides = {}) {
147
+ const stderr = overrides.stderr ?? ((m) => process.stderr.write(`${m}\n`));
148
+ const env = overrides.env ?? process.env;
149
+ const cwd = overrides.cwd ?? process.cwd();
150
+ const parsed = parseWithCredentialsArgs(argv);
151
+ if (parsed.status === "help") {
152
+ // Usage goes to stderr so stdout stays the agent's.
153
+ stderr(getWithCredentialsUsage());
154
+ return 0;
155
+ }
156
+ if (parsed.status === "error") {
157
+ stderr(`Error: ${parsed.message}`);
158
+ stderr(getWithCredentialsUsage());
159
+ return 2;
160
+ }
161
+ let resolution;
162
+ try {
163
+ resolution = overrides.resolve
164
+ ? await overrides.resolve(parsed.repo, cwd)
165
+ : await forWorkerLaunch(parsed.repo, createLaunchCredentialReferenceDeps(env, cwd), launchResolveOptions(cwd));
166
+ }
167
+ catch {
168
+ resolution = { state: "record_unusable", files: [], env: {}, unavailable: [] };
169
+ }
170
+ // Only the variable channel applies here; file specs were linked before the tab opened.
171
+ const values = resolution.state === "ok" ? resolution.env : {};
172
+ const built = buildAgentEnv(env, values);
173
+ const notices = [
174
+ ...resolution.unavailable.map((u) => ({ name: u.name, reason: u.reason })),
175
+ ...built.notices,
176
+ ];
177
+ for (const line of formatNoticeLines(resolution.state, notices))
178
+ stderr(`Warning: ${line}`);
179
+ const invocation = { command: parsed.command, args: parsed.args, env: built.env };
180
+ try {
181
+ if (overrides.spawnAgent)
182
+ return await overrides.spawnAgent(invocation);
183
+ const platform = overrides.platform ?? process.platform;
184
+ const win = platform === "win32"
185
+ ? resolveWindowsAgentInvocation(invocation.command, invocation.args, invocation.env, existsSync)
186
+ : null;
187
+ const spawnFn = win?.verbatim
188
+ ? ((command, args, options) => spawn(command, args, { ...options, windowsVerbatimArguments: true }))
189
+ : spawn;
190
+ return await spawnMcpCommand({
191
+ spawn: spawnFn,
192
+ command: win ? win.command : invocation.command,
193
+ args: win ? win.args : invocation.args,
194
+ env: invocation.env,
195
+ onSignal: (s, h) => {
196
+ process.on(s, h);
197
+ },
198
+ offSignal: (s, h) => {
199
+ process.off(s, h);
200
+ },
201
+ });
202
+ }
203
+ catch {
204
+ // Fixed text: never the command, its arguments, or the error.
205
+ stderr("Error: the agent could not be started");
206
+ return 127;
207
+ }
208
+ }
@@ -0,0 +1,340 @@
1
+ /**
2
+ * BAPI-1647: the one file-delivery lifecycle shared by the EI executor and
3
+ * `start-tickets` worktrees.
4
+ *
5
+ * For each approved sandbox `worktree_file` destination, at every worker start:
6
+ *
7
+ * 1. RECONCILE. Bridge keeps a small, names-and-paths-only state file under
8
+ * the worktree's OWN git directory (`git rev-parse --git-dir`, so each
9
+ * linked worktree has its own). A link Bridge recorded that is no longer
10
+ * approved, or whose approved source changed, is removed — but only after
11
+ * `lstat` + `readlink` show it is still exactly the link Bridge made. A
12
+ * regular file, a foreign link, or a target Bridge cannot identify is left
13
+ * in place. An absent or unusable record approves nothing, so it removes
14
+ * every identifiable Bridge link.
15
+ * 2. EXCLUDE FIRST. Every approved destination — retained, new, or one whose
16
+ * source is missing right now — is added to the checkout's local
17
+ * `info/exclude` under the cross-process exclude lock. A link is created
18
+ * (or kept) only after its exclusion succeeded, so a reused worktree never
19
+ * fails the pre-spawn clean check because of an unexcluded link.
20
+ * 3. LINK. Ownership is recorded BEFORE the link is exposed, and rolled back
21
+ * when the hardened materializer refuses. An unrecorded symlink that
22
+ * already points at the approved source is used but never adopted.
23
+ *
24
+ * WHY A SYMLINK IS SAFE TO LEAVE IN A CHECKOUT: git stores a symlink as the
25
+ * link's TARGET PATHNAME, never the bytes of the file it points to. Even a
26
+ * link that was somehow committed would carry only a path such as
27
+ * `/Users/owner/.config/tool/dw.json`, not the secret. The local exclusion is
28
+ * still required so the link (and its path) stays out of commits and out of
29
+ * `git status`.
30
+ *
31
+ * Every failure omits only the affected credential with a named notice. Nothing
32
+ * here fails a job or a `start-tickets` row, and nothing reads or copies a
33
+ * credential file's contents.
34
+ */
35
+ import { lstat, mkdir, readFile, readlink, realpath, rename, symlink, unlink, writeFile } from "fs/promises";
36
+ import path from "path";
37
+ import { materializeFileCredentialForWorktree, } from "./credential-materialization.js";
38
+ import { defaultExcludeLockDeps, ensureGitInfoExcludedLocked, } from "./git-exclude-lock.js";
39
+ export const CREDENTIAL_LINK_STATE_VERSION = 1;
40
+ /** Relative to the worktree's own git directory. */
41
+ export const CREDENTIAL_LINK_STATE_RELPATH = path.join("bridge", "credential-links.json");
42
+ function errnoCode(err) {
43
+ return err && typeof err === "object" ? err.code : undefined;
44
+ }
45
+ function isWithin(child, root) {
46
+ const rel = path.relative(root, child);
47
+ return rel === "" || (!rel.startsWith("..") && !path.isAbsolute(rel));
48
+ }
49
+ function outcomeFor(reason) {
50
+ switch (reason) {
51
+ case "dest_occupied":
52
+ return "dest_occupied";
53
+ case "dest_unsafe":
54
+ case "invalid_dest":
55
+ return "dest_unsafe";
56
+ default:
57
+ return "dest_unavailable";
58
+ }
59
+ }
60
+ function parseState(raw) {
61
+ let parsed;
62
+ try {
63
+ parsed = JSON.parse(raw);
64
+ }
65
+ catch {
66
+ return null;
67
+ }
68
+ if (!parsed || typeof parsed !== "object")
69
+ return null;
70
+ const obj = parsed;
71
+ if (obj.version !== CREDENTIAL_LINK_STATE_VERSION || !Array.isArray(obj.links))
72
+ return null;
73
+ const links = [];
74
+ for (const item of obj.links) {
75
+ if (!item || typeof item !== "object")
76
+ return null;
77
+ const { name, dest, source } = item;
78
+ if (typeof name !== "string" || typeof dest !== "string" || typeof source !== "string")
79
+ return null;
80
+ if (path.isAbsolute(dest) || dest.split(/[\\/]+/).includes("..") || !path.isAbsolute(source))
81
+ return null;
82
+ links.push({ name, dest, source });
83
+ }
84
+ return { version: CREDENTIAL_LINK_STATE_VERSION, links };
85
+ }
86
+ async function resolveGitDir(worktreeRoot, deps) {
87
+ try {
88
+ const result = await deps.runCommand("git", ["rev-parse", "--git-dir"], { cwd: worktreeRoot });
89
+ const raw = result.stdout.trim();
90
+ if (result.exitCode !== 0 || raw.length === 0)
91
+ return null;
92
+ return path.isAbsolute(raw) ? path.normalize(raw) : path.resolve(worktreeRoot, raw);
93
+ }
94
+ catch {
95
+ return null;
96
+ }
97
+ }
98
+ /**
99
+ * Remove one Bridge-recorded link, only when it is still provably Bridge's:
100
+ * its parent canonicalizes inside the worktree, it is a symlink, and it points
101
+ * at the recorded source. Returns "removed", "left" (not identifiable — left in
102
+ * place), or "failed" (identifiable but could not be removed).
103
+ */
104
+ async function removeOwnedLink(worktreeRoot, realRoot, entry, deps) {
105
+ const linkPath = path.join(worktreeRoot, entry.dest);
106
+ try {
107
+ const parent = await deps.realpath(path.dirname(linkPath));
108
+ if (!isWithin(parent, realRoot))
109
+ return "unsafe";
110
+ }
111
+ catch (err) {
112
+ return errnoCode(err) === "ENOENT" ? "removed" : "left";
113
+ }
114
+ let stat;
115
+ try {
116
+ stat = await deps.lstat(linkPath);
117
+ }
118
+ catch (err) {
119
+ return errnoCode(err) === "ENOENT" ? "removed" : "left";
120
+ }
121
+ if (!stat.isSymbolicLink())
122
+ return "left";
123
+ try {
124
+ if ((await deps.readlink(linkPath)) !== entry.source)
125
+ return "left";
126
+ }
127
+ catch {
128
+ return "left";
129
+ }
130
+ try {
131
+ await deps.unlink(linkPath);
132
+ return "removed";
133
+ }
134
+ catch (err) {
135
+ return errnoCode(err) === "ENOENT" ? "removed" : "failed";
136
+ }
137
+ }
138
+ /** Deliver approved file credentials into one worktree. Never throws. */
139
+ export async function deliverWorktreeFileCredentials(input, deps) {
140
+ const result = { delivered: [], notices: [], removed: [] };
141
+ try {
142
+ return await deliver(input, deps, result);
143
+ }
144
+ catch {
145
+ // Contain anything unexpected: omit every credential not yet delivered.
146
+ const delivered = new Set(result.delivered.map((d) => d.name));
147
+ for (const spec of input.files) {
148
+ if (!delivered.has(spec.name))
149
+ result.notices.push({ name: spec.name, reason: "dest_unavailable" });
150
+ }
151
+ return result;
152
+ }
153
+ }
154
+ async function deliver(input, deps, result) {
155
+ const { worktreeRoot } = input;
156
+ if (deps.platform === "win32") {
157
+ // The file channel stays gated on Windows; variables and MCP overlays still apply.
158
+ for (const spec of input.files)
159
+ result.notices.push({ name: spec.name, reason: "windows_gated" });
160
+ return result;
161
+ }
162
+ const approved = input.recordState === "ok" ? input.approved : [];
163
+ const gitDir = await resolveGitDir(worktreeRoot, deps);
164
+ if (gitDir === null) {
165
+ for (const spec of input.files)
166
+ result.notices.push({ name: spec.name, reason: "state_write_failed" });
167
+ return result;
168
+ }
169
+ const statePath = path.join(gitDir, CREDENTIAL_LINK_STATE_RELPATH);
170
+ let state;
171
+ try {
172
+ state = parseState(await deps.readFile(statePath));
173
+ }
174
+ catch (err) {
175
+ state = errnoCode(err) === "ENOENT" ? { version: CREDENTIAL_LINK_STATE_VERSION, links: [] } : null;
176
+ }
177
+ if (state === null) {
178
+ // Ownership bookkeeping is unreadable: never guess what Bridge owns.
179
+ for (const spec of input.files)
180
+ result.notices.push({ name: spec.name, reason: "state_write_failed" });
181
+ return result;
182
+ }
183
+ // Nothing recorded, approved, or offered (for example an absent record in a
184
+ // worktree Bridge never linked into): no further filesystem work.
185
+ if (state.links.length === 0 && approved.length === 0 && input.files.length === 0)
186
+ return result;
187
+ let realRoot;
188
+ try {
189
+ realRoot = await deps.realpath(worktreeRoot);
190
+ }
191
+ catch {
192
+ for (const spec of input.files)
193
+ result.notices.push({ name: spec.name, reason: "state_write_failed" });
194
+ return result;
195
+ }
196
+ const publish = async (links) => {
197
+ try {
198
+ await deps.mkdir(path.dirname(statePath), { recursive: true });
199
+ const temp = `${statePath}.${deps.tempSuffix ? deps.tempSuffix() : `${process.pid}.${Date.now()}`}.tmp`;
200
+ const body = { version: CREDENTIAL_LINK_STATE_VERSION, links };
201
+ await deps.writeFile(temp, `${JSON.stringify(body, null, 2)}\n`);
202
+ await deps.rename(temp, statePath);
203
+ return true;
204
+ }
205
+ catch {
206
+ return false;
207
+ }
208
+ };
209
+ const specByDest = new Map(input.files.map((spec) => [spec.dest, spec]));
210
+ const approvedByDest = new Map(approved.map((a) => [a.dest, a.entry]));
211
+ // 1. Reconcile recorded links.
212
+ const kept = [];
213
+ let stateChanged = false;
214
+ for (const entry of state.links) {
215
+ const stillApproved = approvedByDest.get(entry.dest) === entry.name;
216
+ const spec = specByDest.get(entry.dest);
217
+ const sameSource = spec === undefined || spec.source === entry.source;
218
+ if (stillApproved && sameSource) {
219
+ kept.push(entry);
220
+ continue;
221
+ }
222
+ const outcome = await removeOwnedLink(worktreeRoot, realRoot, entry, deps);
223
+ if (outcome === "failed") {
224
+ kept.push(entry);
225
+ result.notices.push({ name: entry.name, reason: "reconcile_failed" });
226
+ continue;
227
+ }
228
+ // A parent that now resolves outside the worktree: never delete through
229
+ // it; name the omission and stop tracking a link Bridge cannot reach.
230
+ if (outcome === "unsafe")
231
+ result.notices.push({ name: entry.name, reason: "reconcile_failed" });
232
+ if (outcome === "removed")
233
+ result.removed.push(entry.dest);
234
+ stateChanged = true;
235
+ }
236
+ let links = kept;
237
+ if (stateChanged && !(await publish(links))) {
238
+ for (const spec of input.files)
239
+ result.notices.push({ name: spec.name, reason: "state_write_failed" });
240
+ return result;
241
+ }
242
+ // 2. Exclude every approved destination first.
243
+ const gitDeps = {
244
+ readFile: deps.readFile,
245
+ writeFile: deps.writeFile,
246
+ mkdir: deps.mkdir,
247
+ runCommand: deps.runCommand,
248
+ platform: deps.platform,
249
+ };
250
+ const ensureExcluded = deps.ensureExcluded ??
251
+ ((root, rel, d) => ensureGitInfoExcludedLocked(root, rel, d, deps.excludeLock ?? defaultExcludeLockDeps()));
252
+ const excluded = new Set();
253
+ for (const { dest } of approved) {
254
+ if (excluded.has(dest))
255
+ continue;
256
+ const outcome = await ensureExcluded(worktreeRoot, dest, gitDeps);
257
+ if (outcome.ok)
258
+ excluded.add(dest);
259
+ }
260
+ // A retained Bridge link whose exclusion failed is withdrawn.
261
+ const retained = [];
262
+ for (const entry of links) {
263
+ if (excluded.has(entry.dest)) {
264
+ retained.push(entry);
265
+ continue;
266
+ }
267
+ const outcome = await removeOwnedLink(worktreeRoot, realRoot, entry, deps);
268
+ if (outcome === "failed") {
269
+ retained.push(entry);
270
+ result.notices.push({ name: entry.name, reason: "reconcile_failed" });
271
+ }
272
+ else if (outcome === "unsafe") {
273
+ result.notices.push({ name: entry.name, reason: "reconcile_failed" });
274
+ }
275
+ else if (outcome === "removed") {
276
+ result.removed.push(entry.dest);
277
+ }
278
+ }
279
+ if (retained.length !== links.length) {
280
+ links = retained;
281
+ if (!(await publish(links))) {
282
+ for (const spec of input.files)
283
+ result.notices.push({ name: spec.name, reason: "state_write_failed" });
284
+ return result;
285
+ }
286
+ }
287
+ // 3. Link each resolvable credential whose exclusion succeeded.
288
+ for (const spec of input.files) {
289
+ if (!excluded.has(spec.dest)) {
290
+ result.notices.push({ name: spec.name, reason: "exclude_failed" });
291
+ continue;
292
+ }
293
+ const recorded = links.some((l) => l.dest === spec.dest && l.source === spec.source);
294
+ let willCreate = false;
295
+ if (!recorded) {
296
+ try {
297
+ await deps.lstat(path.join(worktreeRoot, spec.dest));
298
+ }
299
+ catch (err) {
300
+ willCreate = errnoCode(err) === "ENOENT";
301
+ }
302
+ }
303
+ if (willCreate) {
304
+ const next = [...links.filter((l) => l.dest !== spec.dest), { name: spec.name, dest: spec.dest, source: spec.source }];
305
+ if (!(await publish(next))) {
306
+ result.notices.push({ name: spec.name, reason: "state_write_failed" });
307
+ continue;
308
+ }
309
+ links = next;
310
+ }
311
+ const materialized = await materializeFileCredentialForWorktree({ canonicalSourcePath: spec.source, worktreeRelativeDestPath: spec.dest }, worktreeRoot, deps);
312
+ if (materialized.ok) {
313
+ result.delivered.push({ name: spec.name, dest: spec.dest });
314
+ continue;
315
+ }
316
+ result.notices.push({ name: spec.name, reason: outcomeFor(materialized.reason) });
317
+ if (willCreate) {
318
+ const rolledBack = links.filter((l) => l.dest !== spec.dest);
319
+ if (await publish(rolledBack))
320
+ links = rolledBack;
321
+ }
322
+ }
323
+ return result;
324
+ }
325
+ /** Node-backed deps for the production executor and `start-tickets` callers. */
326
+ export function createNodeWorktreeCredentialDeliveryDeps(runCommand, platform) {
327
+ return {
328
+ platform,
329
+ runCommand,
330
+ readFile: (p) => readFile(p, "utf-8"),
331
+ writeFile: (p, data) => writeFile(p, data, { encoding: "utf-8", mode: 0o600 }),
332
+ mkdir: (p, o) => mkdir(p, o),
333
+ rename: (a, b) => rename(a, b),
334
+ unlink: (p) => unlink(p),
335
+ symlink: (target, linkPath) => symlink(target, linkPath),
336
+ lstat: (p) => lstat(p),
337
+ readlink: (p) => readlink(p),
338
+ realpath: (p) => realpath(p),
339
+ };
340
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@bridge_gpt/mcp-server",
3
- "version": "0.2.73",
3
+ "version": "0.2.74",
4
4
  "description": "Bridge API MCP server — exposes Jira endpoints as MCP tools for Claude Code agents",
5
5
  "license": "MIT",
6
6
  "type": "module",