@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
@@ -23,27 +23,31 @@
23
23
  * changed) and re-runs at publication through a fresh rediscovery, so a
24
24
  * selection that went stale or unsafe is refused before anything is staged.
25
25
  *
26
- * Secrets never reach a grant. Every `env` value of an imported host or project
27
- * entry is held in a {@link CandidateSecrets} store (which refuses to
28
- * serialize), then moved into the credential store under a fresh grant-specific
29
- * target at publication. The grant keeps only that target and the key names.
30
- * The classifier may test those values for a Bridge URL and never copies one
31
- * out. An entry whose ARGUMENTS look like a credential is not offered at all,
32
- * and a non-`stdio` entry is not offered because its headers could carry
33
- * secrets.
26
+ * Secrets never reach a grant, and discovery never retains one (BAPI-1648).
27
+ * The `env` values of an imported host or project entry are inspected only
28
+ * transiently, inside the classifier, to spot a Bridge URL; a candidate keeps
29
+ * the declared key NAMES and launch metadata, nothing else. Publication does
30
+ * not copy values anywhere: a host, project, or bundle-less registry server is
31
+ * published reference-backed, with neither `secret_bundle` nor
32
+ * `secret_env_keys`, and the owner's approved credential-reference record
33
+ * (`credential-references.ts`) decides which keys a worker receives. A
34
+ * declared `.bridge/config` bundle keeps its legacy form, because that path
35
+ * already references its bundle instead of creating a copy. An entry whose
36
+ * ARGUMENTS look like a credential is not offered at all, and a non-`stdio`
37
+ * entry is not offered because its headers could carry secrets.
34
38
  *
35
- * The candidate fingerprint is a SHA-256 over the canonical inventory with every
36
- * secret value left out. It changes when a command, an argument, a source, a key
37
- * set, a non-secret value, or a declared bundle reference changes, and it does
38
- * NOT change when only a secret value rotates (rotation is a credential-store
39
- * operation). Fresh publication-specific bundle targets, package-read evidence,
40
- * destination evidence, and existing-grant findings are never part of it, so
41
- * none of them causes a repeated prompt.
39
+ * The candidate fingerprint is a SHA-256 over the canonical inventory. It
40
+ * changes when a command, an argument, a source, a declared key-name set, a
41
+ * non-secret value, or a declared bundle reference changes, and it does NOT
42
+ * change when only an imported value rotates, because no value is part of it.
43
+ * Package-read evidence, destination evidence, and existing-grant findings are
44
+ * never part of it, so none of them causes a repeated prompt.
42
45
  */
43
- import { createHash, randomBytes } from "crypto";
46
+ import { createHash } from "crypto";
44
47
  import path from "path";
45
48
  import { readBridgeConfig } from "./bridge-config.js";
46
- import { upsertCredentialBundle, } from "./credential-store.js";
49
+ import { computeLaunchFingerprint, readCredentialReferenceRecord, } from "./credential-references.js";
50
+ import { createNodeCredentialReferenceDeps } from "./credential-references-node-deps.js";
47
51
  import { resolveClaudeUserConfigPath } from "./claude-user-config-doctor.js";
48
52
  import { bridgeUrlOrigin, launcherTargetFor, parseLauncherPin, } from "./launcher-config-inspection.js";
49
53
  import { resolveCursorUserConfigPath } from "./mcp-host-targets.js";
@@ -86,31 +90,6 @@ export const CANDIDATE_EXCLUSION_TEXT = {
86
90
  other_repository_credential: "Not offered: it carries a credential for a different repository.",
87
91
  unclassifiable: "Not offered: setup cannot tell what this server connects to.",
88
92
  };
89
- /**
90
- * Literal imported env values, keyed by definition id. Kept apart from the
91
- * candidates so no candidate, grant entry, or log line can carry one. It refuses
92
- * to serialize.
93
- */
94
- export class CandidateSecrets {
95
- #values = new Map();
96
- set(definitionId, values) {
97
- this.#values.set(definitionId, { ...values });
98
- }
99
- get(definitionId) {
100
- const values = this.#values.get(definitionId);
101
- return values === undefined ? undefined : { ...values };
102
- }
103
- /**
104
- * True when any held value for `definitionId` satisfies `test`. Value-free:
105
- * only the answer leaves the holder (BAPI-1636 uses it for Bridge URLs).
106
- */
107
- anyValueMatches(definitionId, test) {
108
- return Object.values(this.#values.get(definitionId) ?? {}).some(test);
109
- }
110
- toJSON() {
111
- return "[redacted]";
112
- }
113
- }
114
93
  // ---------------------------------------------------------------------------
115
94
  // Credential-looking arguments
116
95
  // ---------------------------------------------------------------------------
@@ -166,6 +145,7 @@ export function argumentLooksLikeCredential(arg) {
166
145
  /**
167
146
  * Env values held for one entry during classification only. Value-free from
168
147
  * outside: only {@link anyValueMatches} answers, and it refuses to serialize.
148
+ * It never leaves classification: discovery projects names, not this holder.
169
149
  */
170
150
  export class EntryEnvValues {
171
151
  #values;
@@ -175,10 +155,6 @@ export class EntryEnvValues {
175
155
  anyValueMatches(test) {
176
156
  return Object.values(this.#values).some(test);
177
157
  }
178
- /** The values, for staging into {@link CandidateSecrets}. Module-internal use only. */
179
- copy() {
180
- return { ...this.#values };
181
- }
182
158
  toJSON() {
183
159
  return "[redacted]";
184
160
  }
@@ -232,7 +208,7 @@ export function classifyMcpGrantEntry(entry, context) {
232
208
  const excluded = (reason) => ({ state: "excluded", reason });
233
209
  if (!isGrantableServerName(entry.name))
234
210
  return excluded("invalid_name");
235
- if (!entry.definitionValid || entry.missingRequiredBundle === true)
211
+ if (!entry.definitionValid)
236
212
  return excluded("invalid_definition");
237
213
  if (!entry.stdio)
238
214
  return excluded("not_stdio");
@@ -348,7 +324,7 @@ function normalizeConfigEntry(name, origin, raw) {
348
324
  };
349
325
  }
350
326
  /** Normalize the `mcpServers` of one host or project config document. */
351
- function normalizeServersDocument(doc, origin, rootKey) {
327
+ export function normalizeServersDocument(doc, origin, rootKey) {
352
328
  if (!isPlainObject(doc))
353
329
  return [];
354
330
  const servers = doc[rootKey];
@@ -356,11 +332,15 @@ function normalizeServersDocument(doc, origin, rootKey) {
356
332
  return [];
357
333
  return Object.entries(servers).map(([name, raw]) => normalizeConfigEntry(name, origin, raw));
358
334
  }
359
- async function normalizeRepositoryEntries(deps) {
335
+ export async function normalizeRepositoryEntries(deps) {
360
336
  const read = await readBridgeConfig(deps.cwd, { readFile: deps.readFile });
361
337
  if (!read.ok)
362
338
  return [];
363
- return read.manifest.mcp.map((entry) => {
339
+ return normalizeBridgeConfigManifest(read.manifest);
340
+ }
341
+ /** Normalize the `[[mcp]]` entries of a parsed `.bridge/config` manifest. */
342
+ export function normalizeBridgeConfigManifest(manifest) {
343
+ return manifest.mcp.map((entry) => {
364
344
  const name = entry.target;
365
345
  const command = entry.command ?? "";
366
346
  const registry = getThirdPartyTargetDefinition(name);
@@ -383,13 +363,15 @@ async function normalizeRepositoryEntries(deps) {
383
363
  normalized.declaredBundleKeys = [...registry.requiredEnvKeys].sort();
384
364
  }
385
365
  else if (registry !== undefined && registry.requiredEnvKeys.length > 0) {
386
- normalized.missingRequiredBundle = true;
366
+ // BAPI-1648: a bundle-less registry entry is offered reference-backed. Its
367
+ // required key NAMES are declared so the server can be tied to an approval.
368
+ normalized.envKeys = [...registry.requiredEnvKeys].sort();
387
369
  }
388
370
  return normalized;
389
371
  });
390
372
  }
391
373
  /** Attach local-build package evidence, read through the injected seam. */
392
- async function withPackageEvidence(entries, readFile) {
374
+ export async function withPackageEvidence(entries, readFile) {
393
375
  const out = [];
394
376
  for (const entry of entries) {
395
377
  if (entry.definitionValid && entry.stdio && isLocalBuildLauncher(entry.command, entry.args)) {
@@ -414,20 +396,24 @@ function canonicalDefinition(def) {
414
396
  function sha256(text) {
415
397
  return createHash("sha256").update(text).digest("hex");
416
398
  }
417
- /** Turn an offered normalized entry into a raw definition. Host and project values are staged; others are plain. */
399
+ /**
400
+ * Names-only projection of an offered normalized entry: launch metadata, origin,
401
+ * declared key names, and any declared bundle metadata. It never reads an env
402
+ * value; a declared bundle supplies its own keys, so no key list is added then.
403
+ */
418
404
  function offeredDefinition(entry) {
419
- const staged = entry.secretEnv !== undefined;
405
+ const declaredNames = entry.declaredBundle === undefined ? [...entry.envKeys] : [];
406
+ const plain = { ...entry.plainEnv };
420
407
  return {
421
408
  name: entry.name,
422
409
  origin: entry.origin,
423
410
  command: entry.command,
424
411
  args: [...entry.args],
425
- env: staged ? {} : { ...entry.plainEnv },
426
- stagedEnvKeys: staged ? [...entry.envKeys] : [],
412
+ env: plain,
413
+ stagedEnvKeys: declaredNames.filter((k) => !(k in plain)),
427
414
  ...(entry.declaredBundle !== undefined
428
415
  ? { declaredBundle: entry.declaredBundle, declaredBundleKeys: [...(entry.declaredBundleKeys ?? [])] }
429
416
  : {}),
430
- ...(staged ? { secretValues: entry.secretEnv.copy() } : {}),
431
417
  };
432
418
  }
433
419
  /** Normalize one published grant entry. Its metadata is trusted for key names, never resolved. */
@@ -528,7 +514,6 @@ export async function discoverMcpGrantCandidates(deps) {
528
514
  else
529
515
  exclusionList.push({ name: entry.name, origin: entry.origin, reason: result.reason });
530
516
  }
531
- const secrets = new CandidateSecrets();
532
517
  const byName = new Map();
533
518
  for (const raw of definitions) {
534
519
  const canonical = canonicalDefinition(raw);
@@ -555,9 +540,6 @@ export async function discoverMcpGrantCandidates(deps) {
555
540
  ...(raw.declaredBundle !== undefined ? { declaredBundle: raw.declaredBundle, declaredBundleKeys: [...(raw.declaredBundleKeys ?? [])] } : {}),
556
541
  });
557
542
  }
558
- // Identical definitions share key names; the first origin's values are staged.
559
- if (raw.secretValues !== undefined && secrets.get(id) === undefined)
560
- secrets.set(id, raw.secretValues);
561
543
  }
562
544
  const candidates = [...byName.entries()]
563
545
  .sort(([a], [b]) => (a < b ? -1 : a > b ? 1 : 0))
@@ -569,11 +551,10 @@ export async function discoverMcpGrantCandidates(deps) {
569
551
  exclusions,
570
552
  presetUnavailable,
571
553
  fingerprint: computeCandidateFingerprint(candidates, exclusions, presetUnavailable),
572
- secrets,
573
554
  existingGrant: await readExistingGrant(deps, context),
574
555
  };
575
556
  }
576
- /** The canonical, secret-free fingerprint of an inventory. */
557
+ /** The canonical fingerprint of an inventory. It holds no imported value, so a rotated value never changes it. */
577
558
  export function computeCandidateFingerprint(candidates, exclusions, presetUnavailable) {
578
559
  const canonical = {
579
560
  version: 1,
@@ -697,14 +678,49 @@ export function revalidateMcpGrantSelection(fresh, selectedDefinitionIds, approv
697
678
  return { ok: false, error: `at most ${MCP_GRANT_MAX_SERVERS} servers can be approved` };
698
679
  return { ok: true, chosen };
699
680
  }
681
+ /** The fixed advisory for a credential-requiring server without an approved reference. */
682
+ export function missingReferenceAdvisory(serverName) {
683
+ return (`Advisory: ${serverName} needs credentials but has no approved credential reference. ` +
684
+ `It was published anyway; rerun /install-bridge to approve its credentials.`);
685
+ }
686
+ async function defaultReadReferences(repoName, deps) {
687
+ const base = createNodeCredentialReferenceDeps(deps.grant.env);
688
+ return readCredentialReferenceRecord(repoName, {
689
+ ...base,
690
+ homedir: deps.grant.homedir,
691
+ platform: deps.grant.platform,
692
+ });
693
+ }
700
694
  /**
701
- * Publish an approved selection: rediscover and revalidate it, then stage every
702
- * imported secret into a FRESH grant-specific credential-store target (never
703
- * one the current grant references), then write the grant durably. Any refusal
704
- * or failure stops before the grant is written, and a refusal stops before any
705
- * credential is staged, so the previous grant and the credentials it references
706
- * are left intact. Errors are fixed and name no value. The grant is written from
707
- * the revalidated fresh definitions and the fresh inventory's fingerprint.
695
+ * Servers the approved record names as `mcp_server` consumers. A consumer that
696
+ * carries a launch fingerprint approves only the definition with that exact
697
+ * launcher. Approval comes from the consumer naming the server, never from
698
+ * whether its source is currently present.
699
+ */
700
+ function approvedConsumerMatcher(read) {
701
+ if (read === null || read.state !== "ok")
702
+ return () => false;
703
+ const consumers = [];
704
+ for (const entry of read.record.credentials) {
705
+ for (const consumer of entry.consumers) {
706
+ if (consumer.kind === "mcp_server")
707
+ consumers.push(consumer);
708
+ }
709
+ }
710
+ return (name, def) => {
711
+ const fingerprint = computeLaunchFingerprint(def.command, def.args);
712
+ return consumers.some((c) => c.server === name && (c.launch_fingerprint === undefined || c.launch_fingerprint === fingerprint));
713
+ };
714
+ }
715
+ /**
716
+ * Publish an approved selection: rediscover and revalidate it, then write the
717
+ * grant durably. Host, project, and bundle-less registry servers are published
718
+ * reference-backed, with no `secret_bundle` and no `secret_env_keys`; a declared
719
+ * `.bridge/config` bundle keeps its legacy form. Nothing is copied, no
720
+ * credential-store target is created, and the reference record is never written.
721
+ * A selected credential-requiring server without an approved reference still
722
+ * publishes, with one fixed stderr advisory. Any refusal or failure stops before
723
+ * the grant is written. Errors are fixed and name no value.
708
724
  */
709
725
  export async function publishMcpGrant(repoName, inventory, selectedDefinitionIds, now, deps) {
710
726
  let fresh;
@@ -718,41 +734,37 @@ export async function publishMcpGrant(repoName, inventory, selectedDefinitionIds
718
734
  if (!revalidated.ok)
719
735
  return revalidated;
720
736
  const chosen = [...revalidated.chosen].sort((a, b) => (a.name < b.name ? -1 : 1));
721
- // Every staged key set must be available before the first credential write.
722
- for (const { name, def } of chosen) {
723
- if (def.stagedEnvKeys.length === 0)
724
- continue;
725
- const values = fresh.secrets.get(def.id);
726
- if (values === undefined || def.stagedEnvKeys.some((k) => typeof values[k] !== "string")) {
727
- return { ok: false, error: `the credentials for ${name} could not be staged` };
728
- }
729
- }
730
- const suffix = deps.bundleSuffix ?? (() => `${now.getTime().toString(36)}-${randomBytes(4).toString("hex")}`);
731
- const upsert = deps.upsertBundle ?? upsertCredentialBundle;
732
737
  const servers = [];
733
- for (const { name, def } of chosen) {
738
+ const needsApproval = [];
739
+ for (const selected of chosen) {
740
+ const { name, def } = selected;
734
741
  const entry = { name, source: def.source, transport: "stdio", command: def.command, args: [...def.args] };
735
742
  if (Object.keys(def.env).length > 0)
736
743
  entry.env = { ...def.env };
737
- if (def.stagedEnvKeys.length > 0) {
738
- const all = fresh.secrets.get(def.id);
739
- // Only the approved key names are staged.
740
- const values = {};
741
- for (const key of def.stagedEnvKeys)
742
- values[key] = all[key];
743
- const target = `mcp-grant:${repoName}:${name}:${suffix()}`;
744
- const staged = await upsert(target, values, deps.credentialStore, { createOnly: true });
745
- if (!staged.ok)
746
- return { ok: false, error: `the credentials for ${name} could not be stored` };
747
- entry.secret_bundle = target;
748
- entry.secret_env_keys = [...def.stagedEnvKeys];
749
- }
750
- else if (def.declaredBundle !== undefined) {
744
+ if (def.declaredBundle !== undefined) {
751
745
  entry.secret_bundle = def.declaredBundle;
752
746
  entry.secret_env_keys = [...(def.declaredBundleKeys ?? [])];
753
747
  }
748
+ else if (def.stagedEnvKeys.length > 0) {
749
+ needsApproval.push(selected);
750
+ }
754
751
  servers.push(entry);
755
752
  }
753
+ if (needsApproval.length > 0) {
754
+ let read = null;
755
+ try {
756
+ read = await (deps.readReferences ?? ((repo) => defaultReadReferences(repo, deps)))(repoName);
757
+ }
758
+ catch {
759
+ read = null;
760
+ }
761
+ const approved = approvedConsumerMatcher(read);
762
+ const advise = deps.advise ?? ((line) => process.stderr.write(`${line}\n`));
763
+ for (const { name, def } of needsApproval) {
764
+ if (!approved(name, def))
765
+ advise(missingReferenceAdvisory(name));
766
+ }
767
+ }
756
768
  const grant = {
757
769
  version: MCP_GRANT_VERSION,
758
770
  repo_name: repoName,
@@ -32,6 +32,9 @@ import os from "os";
32
32
  import { resolveRepoNameForProjectRoot, readBridgeConfig, validateMcpTarget, validateRepoName, } from "./bridge-config.js";
33
33
  import { resolveBapiCredentials, resolveCredentialBundle, } from "./credential-store.js";
34
34
  import { readMcpGrant } from "./mcp-grant.js";
35
+ import { forMcpServer } from "./credential-references.js";
36
+ import { createLaunchCredentialReferenceDeps, formatCredentialNotice, formatRecordUnusableNotice, launchResolveOptions, mcpReferenceEligibility, readApprovalMetadata, } from "./credential-delivery.js";
37
+ import { checkRestrictedLauncher } from "./credential-launch-safety.js";
35
38
  import { applyPlaywrightOriginLimit, isPlaywrightPresetEntry, PLAYWRIGHT_ORIGIN_ENV_KEYS, resolvePlaywrightAllowedOrigin, } from "./mcp-presets.js";
36
39
  import { describeBaseUrlRejection, validateHttpBaseUrl } from "./base-url.js";
37
40
  import { MCP_PACKAGE_NAME } from "./mcp-identity.js";
@@ -353,12 +356,95 @@ export async function resolveBapiInvocation(projectRoot, deps) {
353
356
  if (typeof deps.baseUrl === "string" && deps.baseUrl.length > 0) {
354
357
  overlay.BAPI_BASE_URL = deps.baseUrl;
355
358
  }
356
- const env = buildChildEnv(deps.env, overlay);
359
+ const env = buildChildEnv(deps.env, { ...(deps.referenceOverlay ?? {}), ...overlay });
357
360
  return {
358
361
  ok: true,
359
362
  invocation: { command: deps.execPath, args: [deps.scriptPath], env },
360
363
  };
361
364
  }
365
+ /** Production seams for one shim invocation rooted at `projectRoot`. */
366
+ export function createMcpReferenceSeams(env, projectRoot) {
367
+ const deps = createLaunchCredentialReferenceDeps(env, projectRoot);
368
+ const options = launchResolveOptions(projectRoot);
369
+ return {
370
+ readMetadata: (repoName) => readApprovalMetadata(repoName, deps),
371
+ resolve: (target, launch, repoName) => forMcpServer(target, launch, repoName, deps, options),
372
+ checkLauncher: (launch, childEnv) => checkRestrictedLauncher({ command: launch.command, args: launch.args, cwd: projectRoot, env: childEnv, worktreeRoot: projectRoot }),
373
+ };
374
+ }
375
+ /** Fixed warning prefix for every reference notice on the shim's stderr. */
376
+ function emitReferenceNotices(lines, stderr) {
377
+ for (const line of lines)
378
+ stderr(`Warning: ${line}`);
379
+ }
380
+ /**
381
+ * Resolve the overlay for one target and launch. Never throws, never returns a
382
+ * value outside the overlay, and reports problems only as fixed, names-only
383
+ * notices: a record that cannot be used gives zero values and one notice; a
384
+ * missing, unreadable, unparsable, or mismatched source omits that credential
385
+ * with a notice; restricted values are removed for a launch the worktree
386
+ * controls.
387
+ */
388
+ export async function resolveReferenceOverlay(target, launch, repoName, seams, stderr, options, metadataRead) {
389
+ try {
390
+ const read = metadataRead ?? (await seams.readMetadata(repoName));
391
+ if (read.state === "record_unusable") {
392
+ emitReferenceNotices([formatRecordUnusableNotice(read.reason)], stderr);
393
+ return {};
394
+ }
395
+ if (read.state !== "ok")
396
+ return {};
397
+ const eligibility = mcpReferenceEligibility(read.metadata, target, launch, { requireFingerprint: options.requireFingerprint });
398
+ const notices = [];
399
+ if (options.requireFingerprint) {
400
+ // Fingerprinted declarations that did not match this launch.
401
+ const declared = mcpReferenceEligibility(read.metadata, target, launch, { requireFingerprint: true, ignoreFingerprintMatch: true });
402
+ const matchedNames = new Set(eligibility.matched.map((d) => d.entry));
403
+ for (const d of declared.matched) {
404
+ if (!matchedNames.has(d.entry))
405
+ notices.push({ name: d.entry, reason: "launch_mismatch" });
406
+ }
407
+ }
408
+ if (eligibility.matched.length === 0) {
409
+ emitReferenceNotices(notices.map(formatCredentialNotice), stderr);
410
+ return {};
411
+ }
412
+ const resolution = await seams.resolve(target, launch, repoName);
413
+ if (resolution.state === "record_unusable") {
414
+ emitReferenceNotices([formatRecordUnusableNotice()], stderr);
415
+ return {};
416
+ }
417
+ const matchedNames = new Set(eligibility.matched.map((d) => d.entry));
418
+ for (const u of resolution.unavailable) {
419
+ // Unfingerprinted declarations are not this path's to report when filtered out.
420
+ if (matchedNames.has(u.name))
421
+ notices.push({ name: u.name, reason: u.reason });
422
+ }
423
+ const allowedKeys = new Set(eligibility.keys);
424
+ const overlay = {};
425
+ for (const [key, value] of Object.entries(resolution.env)) {
426
+ if (allowedKeys.has(key))
427
+ overlay[key] = value;
428
+ }
429
+ const restricted = eligibility.matched.filter((d) => d.level === "restricted");
430
+ const restrictedKeys = new Set(restricted.flatMap((d) => d.keys));
431
+ if ([...restrictedKeys].some((k) => k in overlay)) {
432
+ const verdict = await seams.checkLauncher(launch, options.childEnv);
433
+ if (verdict !== "safe") {
434
+ for (const key of restrictedKeys)
435
+ delete overlay[key];
436
+ for (const d of restricted)
437
+ notices.push({ name: d.entry, reason: "restricted_launcher" });
438
+ }
439
+ }
440
+ emitReferenceNotices([...new Set(notices.map(formatCredentialNotice))], stderr);
441
+ return overlay;
442
+ }
443
+ catch {
444
+ emitReferenceNotices([formatRecordUnusableNotice()], stderr);
445
+ return {};
446
+ }
447
+ }
362
448
  /**
363
449
  * Resolve a Tier-2 third-party invocation: read `.bridge/config`, locate the
364
450
  * requested target entry, resolve the target's required env overlay atomically
@@ -387,13 +473,43 @@ export async function resolveThirdPartyInvocation(target, projectRoot, deps) {
387
473
  error: `target '${target}' is not declared in .bridge/config`,
388
474
  };
389
475
  }
390
- const entryValidation = validateThirdPartyTargetManifestEntry(entry);
476
+ // BAPI-1647: a bundle-less registry entry is reference-BACKED when approved
477
+ // fingerprinted declarations cover its required keys. Whether the overlay is
478
+ // applied is decided separately below, against the CURRENT command and args,
479
+ // so an edited launch starts without credentials instead of being refused.
480
+ const hasBundle = entry.secretBundle !== undefined && entry.secretBundle.trim().length > 0;
481
+ let repoName;
482
+ let metadata;
483
+ let referenceBacked = false;
484
+ if (!hasBundle && deps.references && deps.resolveRepoName && entry.command !== undefined && entry.args !== undefined) {
485
+ try {
486
+ const repo = await deps.resolveRepoName(projectRoot);
487
+ if (repo.ok) {
488
+ repoName = repo.value;
489
+ metadata = await deps.references.readMetadata(repoName);
490
+ if (metadata.state === "ok") {
491
+ referenceBacked = mcpReferenceEligibility(metadata.metadata, target, { command: entry.command, args: entry.args }, {
492
+ requireFingerprint: true,
493
+ ignoreFingerprintMatch: true,
494
+ }).eligible;
495
+ }
496
+ }
497
+ }
498
+ catch {
499
+ metadata = undefined;
500
+ }
501
+ }
502
+ const entryValidation = validateThirdPartyTargetManifestEntry(entry, { referenceBacked });
391
503
  if (!entryValidation.ok) {
392
504
  return { ok: false, error: entryValidation.error };
393
505
  }
394
506
  // After validation these are guaranteed present.
395
507
  const command = entry.command;
396
508
  const args = entry.args;
509
+ if (entryValidation.referenceBacked && deps.references && repoName !== undefined) {
510
+ const overlay = await resolveReferenceOverlay(target, { command, args }, repoName, deps.references, deps.stderr ?? (() => undefined), { requireFingerprint: true, childEnv: deps.env }, metadata);
511
+ return { ok: true, invocation: { command, args, env: buildChildEnv(deps.env, overlay) } };
512
+ }
397
513
  const secretBundle = entry.secretBundle;
398
514
  const envResult = await deps.resolveTargetEnv(definition, secretBundle);
399
515
  if (!envResult.ok) {
@@ -429,11 +545,31 @@ export async function resolveGrantedInvocation(target, grantRepo, deps) {
429
545
  if (!entry) {
430
546
  return { ok: false, error: `target '${target}' is not in the MCP grant for this repository` };
431
547
  }
432
- const validation = validateGrantedTargetEntry(entry);
548
+ // BAPI-1647: an entry WITH a `secret_bundle` resolves exactly as before and
549
+ // gets no reference overlay. A bundle-less entry may be reference-backed: its
550
+ // eligibility comes from the trusted grant's own command and args (outside
551
+ // the worktree), never from the record inside the validator.
552
+ const hasBundle = entry.secret_bundle !== undefined && entry.secret_bundle.trim().length > 0;
553
+ let metadata;
554
+ let referenceBacked = false;
555
+ if (!hasBundle && deps.references) {
556
+ try {
557
+ metadata = await deps.references.readMetadata(grantRepo);
558
+ }
559
+ catch {
560
+ metadata = undefined;
561
+ }
562
+ if (metadata?.state === "ok") {
563
+ referenceBacked = mcpReferenceEligibility(metadata.metadata, target, { command: entry.command, args: entry.args }, {
564
+ requireFingerprint: false,
565
+ }).eligible;
566
+ }
567
+ }
568
+ const validation = validateGrantedTargetEntry(entry, { referenceBacked });
433
569
  if (!validation.ok)
434
570
  return { ok: false, error: validation.error };
435
571
  const overlay = { ...(entry.env ?? {}) };
436
- const keys = grantedEntryRequiredKeys(entry);
572
+ const keys = validation.referenceBacked ? [] : grantedEntryRequiredKeys(entry);
437
573
  if (keys.length > 0) {
438
574
  if (entry.secret_bundle === undefined) {
439
575
  return { ok: false, error: `granted server '${target}' requires a secret_bundle` };
@@ -450,6 +586,10 @@ export async function resolveGrantedInvocation(target, grantRepo, deps) {
450
586
  overlay[key] = value;
451
587
  }
452
588
  }
589
+ if (!hasBundle && deps.references && metadata !== undefined) {
590
+ const reference = await resolveReferenceOverlay(target, { command: entry.command, args: entry.args }, grantRepo, deps.references, deps.stderr, { requireFingerprint: false, childEnv: buildChildEnv(deps.env, overlay) }, metadata);
591
+ Object.assign(overlay, reference);
592
+ }
453
593
  let args = [...entry.args];
454
594
  const env = buildChildEnv(deps.env, overlay);
455
595
  if (isPlaywrightPresetEntry(entry)) {
@@ -492,6 +632,10 @@ export async function runMcpInvokeCli(argv, overrides = {}) {
492
632
  stderr(`Error: ${dirCheck.error}`);
493
633
  return 1;
494
634
  }
635
+ // BAPI-1647: resolved here, in the shim's own process, never by the worker.
636
+ const references = overrides.credentialReferences === null
637
+ ? undefined
638
+ : (overrides.credentialReferences ?? createMcpReferenceSeams(env, projectRoot));
495
639
  const credentialDeps = {
496
640
  env,
497
641
  homedir: os.homedir,
@@ -512,6 +656,7 @@ export async function runMcpInvokeCli(argv, overrides = {}) {
512
656
  readGrant,
513
657
  resolveBundle,
514
658
  stderr,
659
+ ...(references ? { references } : {}),
515
660
  });
516
661
  if (!resolved.ok) {
517
662
  stderr(`Error: ${resolved.error}`);
@@ -533,6 +678,13 @@ export async function runMcpInvokeCli(argv, overrides = {}) {
533
678
  }));
534
679
  const resolveCredentials = overrides.resolveCredentials ??
535
680
  ((rn) => resolveBapiCredentials(rn, credentialDeps));
681
+ // BAPI-1647: record credentials for the `bridge` consumer only under a
682
+ // TRUSTED identity (`--grant-repo`, which `start-tickets` and the executor
683
+ // write from their own resolved repository). The worktree's `.bridge/config`
684
+ // never selects them, and the grant's own state does not matter here.
685
+ const referenceOverlay = grantRepo !== undefined && references
686
+ ? await resolveReferenceOverlay("bapi", { command: process.execPath, args: [process.argv[1]] }, grantRepo, references, stderr, { requireFingerprint: false, childEnv: env })
687
+ : undefined;
536
688
  // The parsed URL reaches ONLY this branch; the parser already rejected
537
689
  // `--base-url` for every other target, so the Tier-2 path below cannot see it.
538
690
  const resolved = await resolveBapiInvocation(projectRoot, {
@@ -542,6 +694,7 @@ export async function runMcpInvokeCli(argv, overrides = {}) {
542
694
  resolveRepoName,
543
695
  resolveCredentials,
544
696
  baseUrl,
697
+ ...(referenceOverlay && Object.keys(referenceOverlay).length > 0 ? { referenceOverlay } : {}),
545
698
  });
546
699
  if (!resolved.ok) {
547
700
  stderr(`Error: ${resolved.error}`);
@@ -560,6 +713,17 @@ export async function runMcpInvokeCli(argv, overrides = {}) {
560
713
  readBridgeConfig: readConfig,
561
714
  getTargetDefinition,
562
715
  resolveTargetEnv,
716
+ ...(references
717
+ ? {
718
+ references,
719
+ stderr,
720
+ resolveRepoName: overrides.resolveRepoName ??
721
+ ((pr) => resolveRepoNameForProjectRoot(pr, {
722
+ readFile: (p) => readFile(p, "utf-8"),
723
+ runCommand: defaultRunCommand,
724
+ })),
725
+ }
726
+ : {}),
563
727
  });
564
728
  if (!resolved.ok) {
565
729
  stderr(`Error: ${resolved.error}`);
@@ -121,14 +121,14 @@ export function buildBridgeApiShimMcpServerEntry(absoluteWorktreePath, invocatio
121
121
  * or incomplete non-`bapi` targets are skipped with a secret-free warning (they
122
122
  * never appear in the returned entries).
123
123
  */
124
- export function buildMcpServerEntriesForManifest(manifest, absoluteWorktreePath, invocation, bridgeApiBaseUrl) {
124
+ export function buildMcpServerEntriesForManifest(manifest, absoluteWorktreePath, invocation, bridgeApiBaseUrl, reference = {}) {
125
125
  const entries = {};
126
126
  const warnings = [];
127
127
  for (const mcp of manifest.mcp) {
128
128
  if (mcp.target === "bapi") {
129
129
  // The optional base URL reaches ONLY this branch — Tier-2 entries below are
130
130
  // built without it and stay byte-identical to their pre-BAPI-727 shape.
131
- entries[serverNameForMcpTarget("bapi")] = buildShimMcpServerEntry("bapi", absoluteWorktreePath, invocation, bridgeApiBaseUrl);
131
+ entries[serverNameForMcpTarget("bapi")] = buildShimMcpServerEntry("bapi", absoluteWorktreePath, invocation, bridgeApiBaseUrl, reference.bapiReferenceRepo);
132
132
  continue;
133
133
  }
134
134
  const definition = getThirdPartyTargetDefinition(mcp.target);
@@ -136,7 +136,12 @@ export function buildMcpServerEntriesForManifest(manifest, absoluteWorktreePath,
136
136
  warnings.push(`MCP target '${mcp.target}' is not a supported third-party target; skipping its registration.`);
137
137
  continue;
138
138
  }
139
- const validation = validateThirdPartyTargetManifestEntry(mcp);
139
+ // BAPI-1647: a bundle-less registry entry registers only when a
140
+ // fingerprint-matched approved reference names it; otherwise the
141
+ // skip-with-warning below is unchanged.
142
+ const validation = validateThirdPartyTargetManifestEntry(mcp, {
143
+ referenceBacked: reference.referenceBackedTargets?.has(mcp.target) === true,
144
+ });
140
145
  if (!validation.ok) {
141
146
  warnings.push(`MCP target '${mcp.target}' registration skipped: ${validation.error}.`);
142
147
  continue;
@@ -489,7 +494,19 @@ export async function provisionMcpRegistrationForWorktree(row, deps) {
489
494
  if (!normalized.ok) {
490
495
  return { ...row, status: "spawn-failed", error: `MCP provisioning failed: ${normalized.error}` };
491
496
  }
492
- const built = buildMcpServerEntriesForManifest(read.manifest, normalized.path, deps.mcpServerInvocation, deps.bridgeApiBaseUrl);
497
+ // BAPI-1647: the caller's names-only eligibility, computed from its one
498
+ // explicit record read. A throwing callback means "no reference".
499
+ let referenceBackedTargets;
500
+ try {
501
+ referenceBackedTargets = deps.credentialReferenceTargets?.(read.manifest, normalized.path);
502
+ }
503
+ catch {
504
+ referenceBackedTargets = undefined;
505
+ }
506
+ const built = buildMcpServerEntriesForManifest(read.manifest, normalized.path, deps.mcpServerInvocation, deps.bridgeApiBaseUrl, {
507
+ ...(referenceBackedTargets !== undefined ? { referenceBackedTargets } : {}),
508
+ ...(deps.bapiReferenceRepo !== undefined ? { bapiReferenceRepo: deps.bapiReferenceRepo } : {}),
509
+ });
493
510
  if (Object.keys(built.entries).length === 0) {
494
511
  // Nothing supported to write (e.g. a manifest with no bapi target and no
495
512
  // supported Tier-2 targets). Surface any warnings but leave status unchanged.
@@ -171,3 +171,16 @@ export function resolveMcpShimInvocationForRuntime(deps) {
171
171
  packageSpec: deps.npmPackageSpec ?? DEFAULT_MCP_SERVER_NPM_CHANNEL_SPEC,
172
172
  };
173
173
  }
174
+ /**
175
+ * BAPI-1647: the argv prefix that runs an agent through the internal
176
+ * `with-credentials` wrapper, built from the same structured invocation the MCP
177
+ * shim uses (never by string-rewriting an MCP command). The agent argv follows
178
+ * the trailing `--`. Pure.
179
+ */
180
+ export function buildWithCredentialsPrefix(invocation, repoName) {
181
+ const tail = ["with-credentials", "--repo", repoName, "--"];
182
+ if (invocation.form === "absolute-build-path") {
183
+ return [invocation.nodeExecutable, invocation.serverEntryPath, ...tail];
184
+ }
185
+ return ["npx", "-y", invocation.packageSpec, ...tail];
186
+ }