@bridge_gpt/mcp-server 0.2.73 → 0.2.75

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 (123) hide show
  1. package/README.md +14 -7
  2. package/build/agent-launchers/claude-executor-adapter.js +12 -0
  3. package/build/agent-launchers/prompt.js +9 -21
  4. package/build/agents.generated.js +4 -4
  5. package/build/authored-plan.js +542 -0
  6. package/build/bridge-config.js +7 -1
  7. package/build/bridge-permissions.js +11 -0
  8. package/build/command-provisioning.js +4 -3
  9. package/build/commands.generated.js +6 -6
  10. package/build/conductor/bridge-api-client.js +692 -47
  11. package/build/conductor/command-drift.js +1 -1
  12. package/build/conductor/declared-extras.js +335 -0
  13. package/build/conductor/doctor.js +2 -0
  14. package/build/conductor/driver-pass-output.js +104 -0
  15. package/build/conductor/driver-pass.js +571 -0
  16. package/build/conductor/epic-branch-ci-inspection.js +61 -16
  17. package/build/conductor/epic-implementer-cli.js +370 -93
  18. package/build/conductor/epic-server-sfcc-upload.js +1567 -0
  19. package/build/conductor/epic-server-sfcc.js +58 -80
  20. package/build/conductor/epic-server.js +57 -4
  21. package/build/conductor/gate-discovery.js +253 -13
  22. package/build/conductor/gate-settings-review.js +58 -25
  23. package/build/conductor/launch-plan.js +58 -12
  24. package/build/conductor/open-decision-phrases.js +50 -0
  25. package/build/conductor/prerequisite-inputs.js +181 -14
  26. package/build/connect-github-api.js +18 -0
  27. package/build/connect-github.js +35 -18
  28. package/build/credential-delivery.js +280 -0
  29. package/build/credential-launch-safety.js +142 -0
  30. package/build/credential-materialization.js +91 -16
  31. package/build/credential-references-node-deps.js +29 -0
  32. package/build/credential-references.js +1394 -0
  33. package/build/credential-references.test-fixtures.js +211 -0
  34. package/build/credential-scan-conventions.js +145 -0
  35. package/build/credential-scan.js +517 -0
  36. package/build/credential-store.js +50 -0
  37. package/build/credentials-cli.js +252 -3
  38. package/build/dependency-install-declarations.js +47 -1
  39. package/build/docs.generated.js +8 -1
  40. package/build/doctor.js +41 -0
  41. package/build/drive-epic.js +684 -49
  42. package/build/epic-branch-ci-summary.js +18 -1
  43. package/build/epic-capability-statement.js +71 -3
  44. package/build/epic-ci-workflow-drift.js +52 -13
  45. package/build/epic-ci-workflow-install.js +31 -6
  46. package/build/epic-ci-workflow-v3.js +273 -0
  47. package/build/epic-ci-workflow.js +129 -7
  48. package/build/epic-implementer-bin.js +288 -83
  49. package/build/epic-implementer-bundle-cli.js +61 -0
  50. package/build/epic-implementer-claude-hook-bin.js +1 -1
  51. package/build/epic-implementer-env.js +3 -4
  52. package/build/epic-integration-pr.js +5 -2
  53. package/build/epic-launch-context.js +102 -7
  54. package/build/epic-server-record.js +30 -15
  55. package/build/executor/completion-contract.js +24 -1
  56. package/build/executor/credential-delivery-step.js +168 -0
  57. package/build/executor/deps.js +3 -1
  58. package/build/executor/env.js +39 -1
  59. package/build/executor/epic-server-context.js +23 -7
  60. package/build/executor/gate-qualification-job.js +193 -23
  61. package/build/executor/gate-qualification-tests-ran.js +232 -0
  62. package/build/executor/guarded-fast-forward-push.js +13 -8
  63. package/build/executor/job-runner.js +167 -738
  64. package/build/executor/job-type-wrappers.js +734 -0
  65. package/build/executor/permissions.js +85 -3
  66. package/build/executor/preflight.js +6 -2
  67. package/build/executor/process-containment.js +8 -1
  68. package/build/executor/prompt-spec.js +37 -3
  69. package/build/executor/required-verification.js +28 -2
  70. package/build/executor/runner.js +4 -1
  71. package/build/executor/types.js +9 -0
  72. package/build/executor/worker-database.js +6 -1
  73. package/build/executor/worker-guard-hook.js +24 -2
  74. package/build/executor-launch.js +4 -2
  75. package/build/generated/ticket-status.js +20 -0
  76. package/build/git-exclude-lock.js +187 -0
  77. package/build/index.js +589 -326
  78. package/build/install-bridge-conductor-answers.js +112 -22
  79. package/build/install-bridge-conductor-apply.js +38 -1
  80. package/build/install-bridge-conductor-assessment.js +482 -53
  81. package/build/install-bridge-conductor-compact.js +29 -2
  82. package/build/install-bridge-conductor-contracts.js +10 -1
  83. package/build/install-bridge-conductor-gate.js +379 -89
  84. package/build/install-bridge-conductor-setup.js +46 -8
  85. package/build/install-bridge-conductor-trial-report.js +170 -0
  86. package/build/install-bridge-conductor.js +925 -141
  87. package/build/install-bridge.js +88 -11
  88. package/build/install-doctor.js +38 -8
  89. package/build/install-sfcc-detection.js +120 -0
  90. package/build/install-sfcc-setup.js +185 -0
  91. package/build/mcp-grant-candidates.js +108 -96
  92. package/build/mcp-invoke.js +168 -4
  93. package/build/mcp-provisioning.js +21 -4
  94. package/build/mcp-server-invocation.js +13 -0
  95. package/build/merge-workflow-install.js +9 -1
  96. package/build/pipelines.generated.js +8 -7
  97. package/build/plan-generation.js +17 -0
  98. package/build/plane/status.js +8 -2
  99. package/build/printed-remedy-commands.js +59 -0
  100. package/build/project-root.js +40 -0
  101. package/build/readme.generated.js +1 -1
  102. package/build/repository-state-paths.js +5 -2
  103. package/build/repository-toolchains.js +16 -7
  104. package/build/scripts/saved-commands-config-field-driver.js +65 -0
  105. package/build/setup-epic.js +126 -16
  106. package/build/sfcc/credentials.js +3 -2
  107. package/build/sfcc/hostname.js +98 -2
  108. package/build/sfcc/tool-wrapper.js +6 -95
  109. package/build/start-tickets.js +193 -29
  110. package/build/test-support/executor-source-files.js +200 -0
  111. package/build/testing-config-client.js +25 -2
  112. package/build/third-party-mcp-targets.js +35 -4
  113. package/build/v2-readiness-requirements.js +5 -1
  114. package/build/version.generated.js +3 -3
  115. package/build/with-credentials.js +208 -0
  116. package/build/worker-guard-hook-bin.js +2 -2
  117. package/build/worktree-credential-delivery.js +340 -0
  118. package/docs/EPIC-IMPLEMENTER.md +4 -4
  119. package/docs/install/github-app.md +79 -92
  120. package/package.json +1 -1
  121. package/build/conductor/epic-reconcile.js +0 -603
  122. package/build/conductor/epic-runtime.js +0 -2020
  123. package/build/conductor/epic-state.js +0 -774
@@ -66,6 +66,11 @@ import { VERSION } from "./version.generated.js";
66
66
  import { getNoticeDecision } from "./session-upgrade-notice.js";
67
67
  import { formatUpdateAdvice } from "./upgrade-advice.js";
68
68
  import { resolveBapiCredentials, getPrimaryCredentialStorePath, } from "./credential-store.js";
69
+ import { ensureGitInfoExcludedSerialized } from "./git-exclude-lock.js";
70
+ import { forWorkerLaunch, statusOnly, } from "./credential-references.js";
71
+ import { createLaunchCredentialReferenceDeps, emptyApprovalMetadata, formatNoticeLines, formatRecordUnusableNotice, hasBridgeConsumer, launchResolveOptions, legacyReferenceBackedTargets, readApprovalMetadata, } from "./credential-delivery.js";
72
+ import { createNodeWorktreeCredentialDeliveryDeps, deliverWorktreeFileCredentials, } from "./worktree-credential-delivery.js";
73
+ import { provisionRestrictedReadDenyRules } from "./executor/permissions.js";
69
74
  import { LEGACY_SERVER_NAMES, MCP_PACKAGE_NAME, MCP_SERVER_NAME } from "./mcp-identity.js";
70
75
  // BAPI-941: the shared drift diagnostic formatter. The leaf drift module imports
71
76
  // nothing from here, so this direction stays acyclic.
@@ -73,7 +78,7 @@ import { formatClaudeReviewWorkflowDriftDiagnostic } from "./claude-review-workf
73
78
  import { resolveStartTicketsRepoName as resolveSharedStartTicketsRepoName, resolveRequiredStartTicketsRepoName, } from "./start-tickets-repo.js";
74
79
  import { provisionMcpRegistrationsForCreatedWorktrees, } from "./mcp-provisioning.js";
75
80
  import { provisionCommandsForCreatedWorktrees, } from "./command-provisioning.js";
76
- import { resolveMcpShimInvocationForRuntime, buildMcpShimCommand, } from "./mcp-server-invocation.js";
81
+ import { resolveMcpShimInvocationForRuntime, buildWithCredentialsPrefix, buildMcpShimCommand, } from "./mcp-server-invocation.js";
77
82
  import { existsSync } from "node:fs";
78
83
  import { TICKET_KEY_PATTERN as SHARED_TICKET_KEY_PATTERN, TICKET_KEY_USAGE_SUMMARY, validateTicketKey, } from "./ticket-key-utils.js";
79
84
  // Per-OS prerequisite knowledge + low-level command probes live in the shared
@@ -633,7 +638,10 @@ resumeMode = false, workflow = "implement", reviewRounds,
633
638
  // command.
634
639
  baseBranch, bridgeApiBaseUrlOverride,
635
640
  // BAPI-1365: a recognized operator `--tier`, forwarded to the review prompt.
636
- manualTier, verificationScope) {
641
+ manualTier, verificationScope,
642
+ // BAPI-1647: the `with-credentials` argv prefix, present only when the
643
+ // repository approved sandbox variables.
644
+ credentialWrapper) {
637
645
  if (!isSupportedStartTicketsPlatform(deps.platform)) {
638
646
  return { ok: false, error: unsupportedPlatformMessage(deps.platform) };
639
647
  }
@@ -654,7 +662,7 @@ manualTier, verificationScope) {
654
662
  // falls back to the basename-derived repo name (the 403 root cause), and
655
663
  // (BAPI-586/BAPI-801) the run base so the spawned worker opens its PR
656
664
  // against it. The base assignment stays outermost.
657
- buildAgentShellCommand: (key, worktreePath, modelAlias, launchArgs) => prependBaseBranchEnvAssignment(prependRepoNameEnvAssignment(buildAgentShellCommand(agent, key, worktreePath, platform, autoApprove, modelAlias, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, launchArgs, bridgeApiBaseUrl, manualTier, verificationScope), repoName, platform), prBaseBranch, platform),
665
+ buildAgentShellCommand: (key, worktreePath, modelAlias, launchArgs) => prependBaseBranchEnvAssignment(prependRepoNameEnvAssignment(buildAgentShellCommand(agent, key, worktreePath, platform, autoApprove, modelAlias, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, launchArgs, bridgeApiBaseUrl, manualTier, verificationScope, credentialWrapper), repoName, platform), prBaseBranch, platform),
658
666
  spawnTerminalTab: deps.spawnTerminalTab,
659
667
  },
660
668
  };
@@ -1517,14 +1525,24 @@ export function buildAgentInvocation(agent, prompt, quote, modelAlias, launchArg
1517
1525
  }
1518
1526
  }
1519
1527
  /** POSIX agent shell command: `cd '<path>' && <agent> [--model '<alias>'] '<prompt>'`. */
1520
- export function buildPosixAgentShellCommand(agent, key, worktreePath, autoApprove = false, modelAlias, conductorEnabled = false, resumeMode = false, workflow = "implement", reviewRounds, baseBranch, launchArgs = [], bridgeApiBaseUrl, manualTier, verificationScope) {
1528
+ export function buildPosixAgentShellCommand(agent, key, worktreePath, autoApprove = false, modelAlias, conductorEnabled = false, resumeMode = false, workflow = "implement", reviewRounds, baseBranch, launchArgs = [], bridgeApiBaseUrl, manualTier, verificationScope, credentialWrapper) {
1521
1529
  const invocation = buildAgentInvocation(agent, buildAgentPrompt(key, { autoApprove, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, agentName: agent.name, manualTier, verificationScope }), (p) => `'${shSquoteInner(p)}'`, modelAlias, agent.name === "cursor-agent" && autoApprove ? worktreePath : launchArgs);
1522
- return `cd '${shSquoteInner(worktreePath)}' && ${prependBridgeApiBaseUrlEnvAssignment(invocation, bridgeApiBaseUrl, "darwin")}`;
1530
+ // BAPI-1647: when the repository approved sandbox variables, the agent runs
1531
+ // through `with-credentials`, which resolves them in its own process. Only the
1532
+ // wrapper's own argv (paths and the repository name, never a value) is added.
1533
+ const wrapped = credentialWrapper && credentialWrapper.length > 0
1534
+ ? `${credentialWrapper.map((part) => `'${shSquoteInner(part)}'`).join(" ")} ${invocation}`
1535
+ : invocation;
1536
+ return `cd '${shSquoteInner(worktreePath)}' && ${prependBridgeApiBaseUrlEnvAssignment(wrapped, bridgeApiBaseUrl, "darwin")}`;
1523
1537
  }
1524
1538
  /** PowerShell agent shell command: `Set-Location -LiteralPath '<path>'; <agent> [--model '<alias>'] '<prompt>'`. */
1525
- export function buildPowerShellAgentShellCommand(agent, key, worktreePath, autoApprove = false, modelAlias, conductorEnabled = false, resumeMode = false, workflow = "implement", reviewRounds, baseBranch, launchArgs = [], bridgeApiBaseUrl, manualTier, verificationScope) {
1539
+ export function buildPowerShellAgentShellCommand(agent, key, worktreePath, autoApprove = false, modelAlias, conductorEnabled = false, resumeMode = false, workflow = "implement", reviewRounds, baseBranch, launchArgs = [], bridgeApiBaseUrl, manualTier, verificationScope, credentialWrapper) {
1526
1540
  const invocation = buildAgentInvocation(agent, buildAgentPrompt(key, { autoApprove, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, agentName: agent.name, manualTier, verificationScope }), powershellSquote, modelAlias, agent.name === "cursor-agent" && autoApprove ? worktreePath : launchArgs);
1527
- return `Set-Location -LiteralPath ${powershellSquote(worktreePath)}; ${prependBridgeApiBaseUrlEnvAssignment(invocation, bridgeApiBaseUrl, "win32")}`;
1541
+ // BAPI-1647: the same structured wrapper, run with PowerShell's call operator.
1542
+ const wrapped = credentialWrapper && credentialWrapper.length > 0
1543
+ ? `& ${credentialWrapper.map(powershellSquote).join(" ")} ${invocation}`
1544
+ : invocation;
1545
+ return `Set-Location -LiteralPath ${powershellSquote(worktreePath)}; ${prependBridgeApiBaseUrlEnvAssignment(wrapped, bridgeApiBaseUrl, "win32")}`;
1528
1546
  }
1529
1547
  /**
1530
1548
  * Build the shell command run inside each spawned tab/session, dispatched by
@@ -1534,10 +1552,10 @@ export function buildPowerShellAgentShellCommand(agent, key, worktreePath, autoA
1534
1552
  * injected as `--model` at the spawn boundary. `conductorEnabled` appends the
1535
1553
  * BAPI-586 PR-base contract instruction to the prompt (opt-in via `--conductor`).
1536
1554
  */
1537
- export function buildAgentShellCommand(agent, key, worktreePath, platform = "darwin", autoApprove = false, modelAlias, conductorEnabled = false, resumeMode = false, workflow = "implement", reviewRounds, baseBranch, launchArgs = [], bridgeApiBaseUrl, manualTier, verificationScope) {
1555
+ export function buildAgentShellCommand(agent, key, worktreePath, platform = "darwin", autoApprove = false, modelAlias, conductorEnabled = false, resumeMode = false, workflow = "implement", reviewRounds, baseBranch, launchArgs = [], bridgeApiBaseUrl, manualTier, verificationScope, credentialWrapper) {
1538
1556
  if (platform === "win32")
1539
- return buildPowerShellAgentShellCommand(agent, key, worktreePath, autoApprove, modelAlias, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, launchArgs, bridgeApiBaseUrl, manualTier, verificationScope);
1540
- return buildPosixAgentShellCommand(agent, key, worktreePath, autoApprove, modelAlias, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, launchArgs, bridgeApiBaseUrl, manualTier, verificationScope);
1557
+ return buildPowerShellAgentShellCommand(agent, key, worktreePath, autoApprove, modelAlias, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, launchArgs, bridgeApiBaseUrl, manualTier, verificationScope, credentialWrapper);
1558
+ return buildPosixAgentShellCommand(agent, key, worktreePath, autoApprove, modelAlias, conductorEnabled, resumeMode, workflow, reviewRounds, baseBranch, launchArgs, bridgeApiBaseUrl, manualTier, verificationScope, credentialWrapper);
1541
1559
  }
1542
1560
  /**
1543
1561
  * Build the shell command run inside a spawned tab/session for an ARBITRARY
@@ -2362,25 +2380,144 @@ export function buildCommandProvisioningDeps(deps) {
2362
2380
  runCommand: deps.runCommand,
2363
2381
  platform: deps.platform,
2364
2382
  cwd: deps.cwd,
2365
- ...(!deps.readFile && !deps.writeFile && !deps.mkdir ? { recordAssets: recordProvisionedAssets } : {}),
2383
+ ...(!deps.readFile && !deps.writeFile && !deps.mkdir
2384
+ ? { recordAssets: recordProvisionedAssets, ensureExcluded: ensureGitInfoExcludedSerialized }
2385
+ : {}),
2366
2386
  };
2367
2387
  }
2388
+ /** Restricted entries' approved source paths (missing sources included). Names-only status. */
2389
+ export function restrictedSourcePathsFromStatus(status) {
2390
+ if (!status || status.state !== "ok")
2391
+ return [];
2392
+ return [...new Set(status.statuses.filter((st) => st.level === "restricted").flatMap((st) => st.source_paths ?? []))];
2393
+ }
2368
2394
  /**
2369
- * Tier-3 file-credential materialization seam.
2395
+ * Tier-3 file-credential delivery for created worktrees (BAPI-1647).
2370
2396
  *
2371
- * The committed `.bridge/config` schema does not (yet) declare file-credential
2372
- * entries — Tier-3 file materialization is a gated seam (see
2373
- * `credential-materialization.ts`, whose Windows worktree-visible copy remains
2374
- * disabled pending the open context-vs-server-only design decision). With no
2375
- * file-credential configuration there is nothing to materialize, so the default
2376
- * is a safe pass-through. The seam exists so `orchestrateStartTickets` calls it
2377
- * in the correct order — AFTER MCP registration provisioning and BEFORE tab
2378
- * spawning — once the schema and the design decision are resolved. Per-row
2379
- * failures must mark only the affected row `spawn-failed`; normal symlinks are
2380
- * never torn down on completion.
2397
+ * Runs AFTER MCP registration provisioning and BEFORE any tab opens, so no
2398
+ * worker is running while links are made. For each created row it resolves the
2399
+ * repository's approved sandbox `worktree_file` credentials with child 1's
2400
+ * `forWorkerLaunch()` and hands them to the shared reconciled, exclusion-first
2401
+ * delivery (`worktree-credential-delivery.ts`); it also merges one
2402
+ * `Read(<path>)` deny rule per restricted source into the worktree's
2403
+ * `.claude/settings.local.json`. A missing or unusable credential is a warning
2404
+ * on that row only: the row stays `created` and later rows continue. Normal
2405
+ * links are never torn down on completion; a later start's reconciliation
2406
+ * removes ones that are no longer approved. An absent or unusable record
2407
+ * approves nothing, so reconciliation still withdraws every link Bridge
2408
+ * recorded earlier; with no record and no earlier Bridge links, rows are
2409
+ * returned unchanged.
2410
+ */
2411
+ export async function materializeFileCredentialsForCreatedWorktrees(rows, deps, context) {
2412
+ if (!context || !context.repoName || !context.approvals)
2413
+ return rows;
2414
+ const repoName = context.repoName;
2415
+ const approvals = context.approvals;
2416
+ const deliveryDeps = () => context.deliveryDeps ?? createNodeWorktreeCredentialDeliveryDeps(deps.runCommand, deps.platform);
2417
+ // An absent or unusable record approves nothing, but a reused worktree may
2418
+ // still hold links Bridge recorded at an earlier start. Reconcile with an
2419
+ // empty approval set so they are withdrawn. With no Bridge state file this
2420
+ // is a no-op and the absent path returns the rows unchanged.
2421
+ const reconcileOnly = async (worktreePath, recordState) => {
2422
+ try {
2423
+ const reconciled = await deliverWorktreeFileCredentials({ worktreeRoot: worktreePath, recordState, files: [], approved: [] }, deliveryDeps());
2424
+ return reconciled.notices;
2425
+ }
2426
+ catch {
2427
+ return [];
2428
+ }
2429
+ };
2430
+ if (approvals.state === "absent") {
2431
+ let changed = false;
2432
+ const out = [];
2433
+ for (const row of rows) {
2434
+ if (row.status !== "created" || !row.path) {
2435
+ out.push(row);
2436
+ continue;
2437
+ }
2438
+ const warnings = formatNoticeLines("ok", await reconcileOnly(row.path, "absent"));
2439
+ if (warnings.length > 0) {
2440
+ changed = true;
2441
+ out.push({ ...row, warnings: [...(row.warnings ?? []), ...warnings] });
2442
+ }
2443
+ else {
2444
+ out.push(row);
2445
+ }
2446
+ }
2447
+ return changed ? out : rows;
2448
+ }
2449
+ let restrictedPaths = [];
2450
+ if (approvals.state === "ok") {
2451
+ try {
2452
+ const status = context.statusOnly
2453
+ ? await context.statusOnly(repoName)
2454
+ : await statusOnly(repoName, createLaunchCredentialReferenceDeps(deps.env));
2455
+ restrictedPaths = restrictedSourcePathsFromStatus(status);
2456
+ }
2457
+ catch {
2458
+ restrictedPaths = [];
2459
+ }
2460
+ }
2461
+ const fileEntries = new Set(approvals.metadata.files.map((f) => f.entry));
2462
+ const out = [];
2463
+ for (const row of rows) {
2464
+ if (row.status !== "created" || !row.path) {
2465
+ out.push(row);
2466
+ continue;
2467
+ }
2468
+ const worktreePath = row.path;
2469
+ const warnings = [];
2470
+ try {
2471
+ if (approvals.state === "record_unusable") {
2472
+ warnings.push(formatRecordUnusableNotice(approvals.reason));
2473
+ warnings.push(...formatNoticeLines("ok", await reconcileOnly(worktreePath, approvals.state)));
2474
+ }
2475
+ else {
2476
+ const resolution = context.resolveWorkerLaunch
2477
+ ? await context.resolveWorkerLaunch(repoName, worktreePath)
2478
+ : await forWorkerLaunch(repoName, createLaunchCredentialReferenceDeps(deps.env, worktreePath), launchResolveOptions(worktreePath));
2479
+ if (resolution.state === "record_unusable") {
2480
+ warnings.push(formatRecordUnusableNotice());
2481
+ warnings.push(...formatNoticeLines("ok", await reconcileOnly(worktreePath, resolution.state)));
2482
+ }
2483
+ else {
2484
+ const delivered = await deliverWorktreeFileCredentials({ worktreeRoot: worktreePath, recordState: resolution.state, files: resolution.files, approved: approvals.metadata.files }, deliveryDeps());
2485
+ // File-channel problems only; variable problems are reported by the
2486
+ // `with-credentials` wrapper when the agent starts.
2487
+ const notices = [
2488
+ ...resolution.unavailable.filter((u) => fileEntries.has(u.name)).map((u) => ({ name: u.name, reason: u.reason })),
2489
+ ...delivered.notices,
2490
+ ];
2491
+ warnings.push(...formatNoticeLines("ok", notices));
2492
+ }
2493
+ if (restrictedPaths.length > 0) {
2494
+ const provision = context.provisionRestrictedReads ??
2495
+ ((wt, paths) => provisionRestrictedReadDenyRules(wt, paths, {
2496
+ readFile: deps.readFile ?? ((filePath) => readFile(filePath, "utf-8")),
2497
+ writeFile: deps.writeFile ?? ((filePath, data) => writeFile(filePath, data, "utf-8")),
2498
+ mkdir: deps.mkdir ?? ((dirPath, options) => mkdir(dirPath, options)),
2499
+ }));
2500
+ const denied = await provision(worktreePath, restrictedPaths);
2501
+ if (denied.warning)
2502
+ warnings.push(denied.warning);
2503
+ }
2504
+ }
2505
+ }
2506
+ catch {
2507
+ warnings.push("referenced credentials could not be prepared for this worktree; the agent starts without them");
2508
+ }
2509
+ out.push(warnings.length > 0 ? { ...row, warnings: [...(row.warnings ?? []), ...warnings] } : row);
2510
+ }
2511
+ return out;
2512
+ }
2513
+ /**
2514
+ * BAPI-1647: read the run's credential-reference record ONCE, names only.
2515
+ * Fail-safe: any problem is `record_unusable`, which delivers nothing.
2381
2516
  */
2382
- export async function materializeFileCredentialsForCreatedWorktrees(rows, _deps) {
2383
- return rows;
2517
+ export async function readStartTicketsCredentialApprovals(repoName, deps) {
2518
+ if (!repoName)
2519
+ return null;
2520
+ return readApprovalMetadata(repoName, createLaunchCredentialReferenceDeps(deps.env));
2384
2521
  }
2385
2522
  /**
2386
2523
  * Map a diagnostic kind to its observability policy. Expected setup gaps
@@ -3934,6 +4071,21 @@ export async function orchestrateStartTickets(deps, options, overrides = {}) {
3934
4071
  ".bridge/config). Spawned worktrees may fall back to the directory name and " +
3935
4072
  "hit 403 'repository not registered' if it differs from the Bridge API project name.");
3936
4073
  }
4074
+ // BAPI-1647: one names-only read of the approved credential references for
4075
+ // the repository start-tickets resolved itself. It decides whether tabs run
4076
+ // through `with-credentials`, which bundle-less MCP entries register, whether
4077
+ // the `bapi` registration carries the trusted `--grant-repo`, and which file
4078
+ // links to prepare. No value is read here.
4079
+ let credentialApprovals = null;
4080
+ try {
4081
+ credentialApprovals = await (overrides.readCredentialApprovals ?? readStartTicketsCredentialApprovals)(resolvedRepoName, deps);
4082
+ }
4083
+ catch {
4084
+ credentialApprovals = resolvedRepoName ? { state: "record_unusable", reason: "record_unreadable", metadata: emptyApprovalMetadata() } : null;
4085
+ }
4086
+ const credentialWrapper = resolvedRepoName && credentialApprovals?.state === "ok" && Object.keys(credentialApprovals.metadata.envOwners).length > 0
4087
+ ? buildWithCredentialsPrefix(buildMcpProvisioningDeps(deps).mcpServerInvocation, resolvedRepoName)
4088
+ : undefined;
3937
4089
  const platformConfig = resolveStartTicketsPlatformConfig(deps, agent, options.autoApprove, options.conductorEnabled ?? false, resolvedRepoName,
3938
4090
  // BAPI-494: resume-mode dispatches get the full-suite remediation finalize prompt.
3939
4091
  options.resumeMode ?? false, options.workflow, options.reviewRounds,
@@ -3941,7 +4093,7 @@ export async function orchestrateStartTickets(deps, options, overrides = {}) {
3941
4093
  // epic.base_branch override applied above) so the spawned worker gets
3942
4094
  // BAPI_BASE_BRANCH — every conductor worker, and a plain worker whose base
3943
4095
  // is non-default.
3944
- options.baseBranch, bridgeApiBaseUrl, isModelTier(options.injectedTier) ? options.injectedTier : undefined, options.verificationScope);
4096
+ options.baseBranch, bridgeApiBaseUrl, isModelTier(options.injectedTier) ? options.injectedTier : undefined, options.verificationScope, credentialWrapper);
3945
4097
  if (!platformConfig.ok)
3946
4098
  return { ok: false, error: platformConfig.error };
3947
4099
  // BAPI-527: resolve the base start point new worktrees are cut from BEFORE any
@@ -3995,8 +4147,20 @@ export async function orchestrateStartTickets(deps, options, overrides = {}) {
3995
4147
  const createWorktreesFn = overrides.createWorktrees ?? createWorktrees;
3996
4148
  const provisionCommandsFn = overrides.provisionCommands ??
3997
4149
  ((rows, d) => provisionCommandsForCreatedWorktrees(rows, buildCommandProvisioningDeps(d), agent.name === "codex"));
4150
+ // BAPI-1647: names-only reference inputs to MCP provisioning. A bundle-less
4151
+ // registry entry registers only when a fingerprint-matched reference names
4152
+ // it; the `bapi` registration carries `--grant-repo <repo>` (start-tickets'
4153
+ // own resolved identity) only when the record has a `bridge` consumer.
4154
+ const credentialMetadata = credentialApprovals?.state === "ok" ? credentialApprovals.metadata : null;
4155
+ const referenceProvisioning = credentialMetadata
4156
+ ? {
4157
+ credentialReferenceTargets: (manifest) => legacyReferenceBackedTargets(credentialMetadata, manifest.mcp),
4158
+ ...(resolvedRepoName && hasBridgeConsumer(credentialMetadata) ? { bapiReferenceRepo: resolvedRepoName } : {}),
4159
+ }
4160
+ : {};
3998
4161
  const provisionFn = overrides.provisionMcpRegistrations ??
3999
- ((rows, d) => provisionMcpRegistrationsForCreatedWorktrees(rows, buildMcpProvisioningDeps(d, bridgeApiBaseUrl)));
4162
+ ((rows, d) => provisionMcpRegistrationsForCreatedWorktrees(rows, { ...buildMcpProvisioningDeps(d, bridgeApiBaseUrl), ...referenceProvisioning }));
4163
+ const credentialContext = { repoName: resolvedRepoName, approvals: credentialApprovals };
4000
4164
  const materializeFn = overrides.materializeFileCredentials ?? materializeFileCredentialsForCreatedWorktrees;
4001
4165
  const detectTerminalFn = overrides.detectTerminal ?? detectTerminal;
4002
4166
  const spawnTabsFn = overrides.spawnTabsForCreatedWorktrees ?? spawnTabsForCreatedWorktrees;
@@ -4022,10 +4186,10 @@ export async function orchestrateStartTickets(deps, options, overrides = {}) {
4022
4186
  // provisioning failures mark only that row `spawn-failed` (skipped by the
4023
4187
  // spawn step below) — they never abort the whole run.
4024
4188
  const provisioned = await provisionFn(commandProvisioned, deps);
4025
- // Materialize any Tier-3 file credentials AFTER MCP registration provisioning
4026
- // and BEFORE tab spawning (currently a pass-through seam; see
4189
+ // Deliver approved Tier-3 file credentials and restricted-read deny rules
4190
+ // AFTER MCP registration provisioning and BEFORE tab spawning (BAPI-1647; see
4027
4191
  // materializeFileCredentialsForCreatedWorktrees).
4028
- const materialized = await materializeFn(provisioned, deps);
4192
+ const materialized = await materializeFn(provisioned, deps, credentialContext);
4029
4193
  // BAPI-394: provision conductor identity (run id, per-worker id + env, Claude
4030
4194
  // hook injection) and emit the run-level `run.started` event AFTER
4031
4195
  // materialization and BEFORE model routing. The conductor stage is opted into
@@ -0,0 +1,200 @@
1
+ /**
2
+ * BAPI-1682: read the executor's spawn-path source by FILE SET, not by one file.
3
+ *
4
+ * Several static tests assert that a token never appears in the executor spawn
5
+ * path, or that a boundary appears exactly once. Written against
6
+ * `executor/job-runner.ts` alone, those checks pass vacuously the day the spawn
7
+ * code moves into another file: the token is simply no longer in the file they
8
+ * read. This helper returns the whole file set, so an absence or exact-count
9
+ * check follows the code wherever it goes.
10
+ *
11
+ * The set is `executor/job-runner.ts` plus every non-test `.ts` file under the
12
+ * declared directories below, plus any flat `executor/*.ts` file listed in
13
+ * `EXECUTOR_SPAWN_EXTRA_FILES`. Add a directory here when spawn code is split
14
+ * into it; the import guard fails until you do.
15
+ */
16
+ import { existsSync, readdirSync, readFileSync, statSync } from "node:fs";
17
+ import path from "node:path";
18
+ /** Executor subdirectories that may hold code split out of `job-runner.ts`. */
19
+ export const EXECUTOR_SPAWN_SOURCE_DIRS = ["spawn", "job-handlers"];
20
+ /**
21
+ * Flat `executor/*.ts` files (relative to `executor/`, e.g. `spawn-leak.ts`) that hold spawn
22
+ * code moved out of `job-runner.ts`. List a flat file here when spawn code is split into it.
23
+ * Empty today: no flat file holds spawn code.
24
+ */
25
+ export const EXECUTOR_SPAWN_EXTRA_FILES = [];
26
+ /**
27
+ * The flat `./name.js` imports `job-runner.ts` makes today (60 distinct, sorted). A flat import
28
+ * outside this list and outside the source set is reported. If the new file holds spawn code
29
+ * moved from `job-runner.ts`, add it to `EXECUTOR_SPAWN_EXTRA_FILES`; otherwise add its
30
+ * specifier here.
31
+ */
32
+ export const EXECUTOR_FLAT_IMPORT_BASELINE = [
33
+ "./agent-identity.js",
34
+ "./base-branch.js",
35
+ "./ci-fix-test-runs.js",
36
+ "./ci-rerun-job.js",
37
+ "./cleanup-report.js",
38
+ "./completion-contract.js",
39
+ "./completion-supervision.js",
40
+ "./correction-dispatch.js",
41
+ "./credential-delivery-step.js",
42
+ "./delivery-observations.js",
43
+ "./delivery-outcome.js",
44
+ "./dependency-refresh.js",
45
+ "./env-file-guard.js",
46
+ "./env.js",
47
+ "./epic-server-context.js",
48
+ "./failure-reason-codes.js",
49
+ "./gate-qualification-job.js",
50
+ "./guarded-fast-forward-push.js",
51
+ "./heartbeat.js",
52
+ "./index-scope.js",
53
+ "./interrupted-worktree.js",
54
+ "./job-errors.js",
55
+ "./job-log-registry.js",
56
+ "./job-type-wrappers.js",
57
+ "./job-types.js",
58
+ "./live-worker-registry.js",
59
+ "./merge-job.js",
60
+ "./observation.js",
61
+ "./packaged-recipe.js",
62
+ "./permissions.js",
63
+ "./pre-pr-checks.js",
64
+ "./preflight.js",
65
+ "./process-containment.js",
66
+ "./process.js",
67
+ "./prompt-spec.js",
68
+ "./rebase-finalization.js",
69
+ "./recently-failed-tests-file.js",
70
+ "./reconcile-overlap-job.js",
71
+ "./required-verification.js",
72
+ "./required-work-diagnostics.js",
73
+ "./required-work-ledger.js",
74
+ "./results.js",
75
+ "./resume-pre-spawn.js",
76
+ "./spawn-job-driver.js",
77
+ "./stale-artifacts.js",
78
+ "./types.js",
79
+ "./verdict-artifact.js",
80
+ "./verification-hints.js",
81
+ "./viewer-tabs.js",
82
+ "./worker-cli-launcher.js",
83
+ "./worker-command.js",
84
+ "./worker-database-config.js",
85
+ "./worker-database-target.js",
86
+ "./worker-database.js",
87
+ "./worker-finalization.js",
88
+ "./worker-log.js",
89
+ "./worker-verification-guidance.js",
90
+ "./worktree-inspection.js",
91
+ "./worktree-lock.js",
92
+ "./worktree.js",
93
+ ];
94
+ /** Strip block comments first, then line comments (the order is load-bearing). */
95
+ export function stripComments(text) {
96
+ return text.replace(/\/\*[\s\S]*?\*\//g, "").replace(/\/\/[^\n]*/g, "");
97
+ }
98
+ function normalize(text, mode) {
99
+ const lf = text.replace(/\r\n/g, "\n");
100
+ return mode === "code" ? stripComments(lf) : lf;
101
+ }
102
+ function walkSources(dir, out) {
103
+ for (const name of readdirSync(dir).sort()) {
104
+ const full = path.join(dir, name);
105
+ if (statSync(full).isDirectory())
106
+ walkSources(full, out);
107
+ else if (name.endsWith(".ts") && !name.endsWith(".test.ts") && !name.endsWith(".d.ts"))
108
+ out.push(full);
109
+ }
110
+ }
111
+ /**
112
+ * Return `job-runner.ts` and every readable, non-empty, non-test `.ts` file in
113
+ * the declared directories. Fails closed: a declared directory that exists but
114
+ * yields no source, or a missing/empty `job-runner.ts`, throws instead of
115
+ * silently returning a smaller set.
116
+ */
117
+ export function readExecutorSourceFiles(options) {
118
+ const mode = options.mode ?? "raw";
119
+ const declared = options.declaredDirs ?? EXECUTOR_SPAWN_SOURCE_DIRS;
120
+ const extras = options.extraFiles ?? EXECUTOR_SPAWN_EXTRA_FILES;
121
+ const executorDir = path.join(options.srcRoot, "executor");
122
+ const records = [];
123
+ const add = (full) => {
124
+ const content = normalize(readFileSync(full, "utf8"), mode);
125
+ if (content.trim().length === 0)
126
+ return false;
127
+ records.push({ rel: path.relative(options.srcRoot, full).split(path.sep).join("/"), content });
128
+ return true;
129
+ };
130
+ const runner = path.join(executorDir, "job-runner.ts");
131
+ if (!existsSync(runner) || !add(runner)) {
132
+ throw new Error("executor source set: executor/job-runner.ts is missing or empty");
133
+ }
134
+ for (const dir of declared) {
135
+ const full = path.join(executorDir, dir);
136
+ if (!existsSync(full) || !statSync(full).isDirectory())
137
+ continue;
138
+ const files = [];
139
+ walkSources(full, files);
140
+ let added = 0;
141
+ for (const file of files)
142
+ if (add(file))
143
+ added += 1;
144
+ if (added === 0) {
145
+ throw new Error(`executor source set: declared directory executor/${dir} has no non-test TypeScript sources`);
146
+ }
147
+ }
148
+ for (const extra of extras) {
149
+ const full = path.join(executorDir, extra);
150
+ if (!existsSync(full) || !statSync(full).isFile() || !add(full)) {
151
+ throw new Error(`executor source set: declared extra file executor/${extra} is missing or empty`);
152
+ }
153
+ }
154
+ return records;
155
+ }
156
+ /** Count matches of `pattern` across every record (a global regex is forced). */
157
+ export function countAcrossSources(records, pattern) {
158
+ const flags = pattern.flags.includes("g") ? pattern.flags : `${pattern.flags}g`;
159
+ const re = new RegExp(pattern.source, flags);
160
+ return records.reduce((sum, r) => sum + (r.content.match(re)?.length ?? 0), 0);
161
+ }
162
+ /** The records whose content contains `token`. */
163
+ export function sourcesContaining(records, token) {
164
+ return records.filter((r) => r.content.includes(token)).map((r) => r.rel);
165
+ }
166
+ /**
167
+ * Executor files `job-runner.ts` imports that the returned set does not cover: files in a
168
+ * SUBDIRECTORY, and flat `./name.js` files that are neither in the set nor in the flat-import
169
+ * baseline. Non-empty means spawn code may have moved somewhere undeclared.
170
+ */
171
+ export function findUncoveredExecutorImports(srcRoot, records, flatBaseline = EXECUTOR_FLAT_IMPORT_BASELINE) {
172
+ const runner = records.find((r) => r.rel === "executor/job-runner.ts");
173
+ if (!runner)
174
+ throw new Error("executor source set: executor/job-runner.ts is missing from the records");
175
+ const covered = new Set(records.map((r) => r.rel));
176
+ const uncovered = [];
177
+ const re = /from\s+["'](\.\/[^"'/]+\/[^"']+?)(?:\.js)?["']/g;
178
+ for (const match of runner.content.matchAll(re)) {
179
+ const rel = `executor/${match[1].slice(2)}.ts`;
180
+ if (!covered.has(rel) && existsSync(path.join(srcRoot, rel)))
181
+ uncovered.push(rel);
182
+ }
183
+ const baseline = new Set(flatBaseline);
184
+ const flat = /from\s+["'](\.\/[^"'/]+?\.js)["']/g;
185
+ for (const match of runner.content.matchAll(flat)) {
186
+ const rel = `executor/${match[1].slice(2).replace(/\.js$/, ".ts")}`;
187
+ if (!covered.has(rel) && !baseline.has(match[1]) && existsSync(path.join(srcRoot, rel)))
188
+ uncovered.push(rel);
189
+ }
190
+ return [...new Set(uncovered)].sort();
191
+ }
192
+ /** Throw a fixed, non-secret diagnostic when `job-runner.ts` imports an uncovered subdirectory. */
193
+ export function assertExecutorImportsCovered(srcRoot, records, flatBaseline = EXECUTOR_FLAT_IMPORT_BASELINE) {
194
+ const uncovered = findUncoveredExecutorImports(srcRoot, records, flatBaseline);
195
+ if (uncovered.length > 0) {
196
+ throw new Error(`executor source set: job-runner.ts imports from undeclared executor files (${uncovered.join(", ")}); ` +
197
+ "add a subdirectory to EXECUTOR_SPAWN_SOURCE_DIRS, or add the file to EXECUTOR_SPAWN_EXTRA_FILES if it holds " +
198
+ "spawn code moved from job-runner.ts; otherwise add it to EXECUTOR_FLAT_IMPORT_BASELINE");
199
+ }
200
+ }
@@ -2,7 +2,8 @@
2
2
  * Typed client for the stored test command (BAPI-1460).
3
3
  *
4
4
  * Wraps `GET` / `PUT /setup/testing-config` and the existing
5
- * `GET /jira/config-field/unit_testing_stack` reader. It reuses the shared
5
+ * `GET /jira/config-field/<field>` reader (`unit_testing_stack`, and since BAPI-1677
6
+ * the three learned instruction fields). It reuses the shared
6
7
  * {@link BridgeApiUrls} builders: `/setup/...` is a root-level mount, so it is
7
8
  * built from `buildApiUrl`, while the config-field reader sits under the
8
9
  * `/jira` mount and uses `buildGetUrl`.
@@ -17,6 +18,12 @@ import { TestCommandValidationError, validateTestCommand } from "./test-command-
17
18
  export const TESTING_CONFIG_PATH = "/setup/testing-config";
18
19
  /** The `/jira`-mounted config-field path for the learned unit-testing stack. */
19
20
  export const UNIT_TESTING_STACK_FIELD_PATH = "/config-field/unit_testing_stack";
21
+ /** BAPI-1677 — the only learned fields setup reads to work out install extras. */
22
+ export const LEARNED_INSTRUCTION_FIELDS = Object.freeze([
23
+ "architecture_instructions",
24
+ "unit_testing_instructions",
25
+ "e2e_testing_instructions",
26
+ ]);
20
27
  function failure(reason, status) {
21
28
  return { ok: false, reason, status };
22
29
  }
@@ -129,9 +136,25 @@ export async function writeStoredTestCommand(deps, testCommand) {
129
136
  }
130
137
  /** `GET /jira/config-field/unit_testing_stack`. Prose; a hint, never a command. */
131
138
  export async function readUnitTestingStack(deps) {
139
+ return readConfigField(deps, UNIT_TESTING_STACK_FIELD_PATH);
140
+ }
141
+ /** BAPI-1677 — one GET of one learned instruction field. Prose; a hint, never a command. */
142
+ export async function readLearnedInstructionField(deps, field) {
143
+ return readConfigField(deps, `/config-field/${field}`);
144
+ }
145
+ /** BAPI-1677 — exactly one GET per learned field. A failed field never fails the others. */
146
+ export async function readLearnedInstructions(deps) {
147
+ const [architecture, unit, e2e] = await Promise.all(LEARNED_INSTRUCTION_FIELDS.map((field) => readLearnedInstructionField(deps, field)));
148
+ return {
149
+ architecture_instructions: architecture,
150
+ unit_testing_instructions: unit,
151
+ e2e_testing_instructions: e2e,
152
+ };
153
+ }
154
+ async function readConfigField(deps, fieldPath) {
132
155
  let resp;
133
156
  try {
134
- resp = await deps.fetch(deps.urls.buildGetUrl(UNIT_TESTING_STACK_FIELD_PATH, { repo_name: deps.repoName }), { headers: await deps.getGetHeaders() });
157
+ resp = await deps.fetch(deps.urls.buildGetUrl(fieldPath, { repo_name: deps.repoName }), { headers: await deps.getGetHeaders() });
135
158
  }
136
159
  catch {
137
160
  return failure("transport_failure", 0);
@@ -17,6 +17,18 @@ import { resolveCredentialBundle, } from "./credential-store.js";
17
17
  // ---------------------------------------------------------------------------
18
18
  // Registry — additive; add a new entry to support a new Tier-2 target.
19
19
  // ---------------------------------------------------------------------------
20
+ /**
21
+ * `sfcc` (BAPI-1647 reconciliation): the REQUIRED keys stay `SFCC_CLIENT_ID` and
22
+ * `SFCC_CLIENT_SECRET`. `SFCC_HOSTNAME` is OPTIONAL: it is overlaid when an
23
+ * approved credential reference maps it, matching the variable names Bridge's
24
+ * own SFCC tools read (`sfcc/credentials.ts`), and its absence never refuses a
25
+ * launch.
26
+ *
27
+ * BAPI-1667: this target serves only the legacy `.bridge/config`
28
+ * `[[mcp]] target = "sfcc"` path. A granted project b2c-dx-mcp is a bundle-less
29
+ * entry under its own name, so this registry does not apply to it.
30
+ */
31
+ export const SFCC_OPTIONAL_ENV_KEYS = ["SFCC_HOSTNAME"];
20
32
  const THIRD_PARTY_TARGETS = {
21
33
  sfcc: {
22
34
  target: "sfcc",
@@ -39,14 +51,21 @@ export function getSupportedThirdPartyTargets() {
39
51
  * needed to launch it: a non-empty `command`, an `args` array, and a non-empty
40
52
  * `secret_bundle`. Errors name only the missing field, never any value.
41
53
  */
42
- export function validateThirdPartyTargetManifestEntry(entry) {
54
+ export function validateThirdPartyTargetManifestEntry(entry, reference = {}) {
43
55
  if (entry.command === undefined || entry.command.trim().length === 0) {
44
56
  return { ok: false, error: `target '${entry.target}' requires a non-empty command` };
45
57
  }
46
58
  if (entry.args === undefined) {
47
59
  return { ok: false, error: `target '${entry.target}' requires an args array` };
48
60
  }
49
- if (entry.secretBundle === undefined || entry.secretBundle.trim().length === 0) {
61
+ // BAPI-1647: a bundle-less REGISTRY entry is accepted only when the caller
62
+ // proved a fingerprint-matched approved reference covers its required keys.
63
+ // Non-registry legacy entries are still refused, as before.
64
+ const bundleMissing = entry.secretBundle === undefined || entry.secretBundle.trim().length === 0;
65
+ if (bundleMissing && reference.referenceBacked === true && getThirdPartyTargetDefinition(entry.target)) {
66
+ return { ok: true, referenceBacked: true };
67
+ }
68
+ if (bundleMissing) {
50
69
  return { ok: false, error: `target '${entry.target}' requires a non-empty secret_bundle` };
51
70
  }
52
71
  return { ok: true };
@@ -58,7 +77,7 @@ export function validateThirdPartyTargetManifestEntry(entry) {
58
77
  * granted name that matches a registry target still needs a bundle, because the
59
78
  * registry's required keys must be resolved. Errors name only the field.
60
79
  */
61
- export function validateGrantedTargetEntry(entry) {
80
+ export function validateGrantedTargetEntry(entry, reference = {}) {
62
81
  if (typeof entry.command !== "string" || entry.command.trim().length === 0) {
63
82
  return { ok: false, error: `granted server '${entry.name}' requires a non-empty command` };
64
83
  }
@@ -67,7 +86,19 @@ export function validateGrantedTargetEntry(entry) {
67
86
  }
68
87
  const registry = getThirdPartyTargetDefinition(entry.name);
69
88
  const needsBundle = (entry.secret_env_keys?.length ?? 0) > 0 || (registry?.requiredEnvKeys.length ?? 0) > 0;
70
- if (needsBundle && (entry.secret_bundle === undefined || entry.secret_bundle.trim().length === 0)) {
89
+ const bundleMissing = entry.secret_bundle === undefined || entry.secret_bundle.trim().length === 0;
90
+ // BAPI-1647: a bundle-less registry target whose required keys an applicable
91
+ // approved reference supplies launches with the reference overlay. The caller
92
+ // computes that; the validator never reads the record. Declared
93
+ // `secret_env_keys` still need a bundle: a reference does not stand in for one.
94
+ if (needsBundle &&
95
+ bundleMissing &&
96
+ reference.referenceBacked === true &&
97
+ registry !== undefined &&
98
+ (entry.secret_env_keys?.length ?? 0) === 0) {
99
+ return { ok: true, referenceBacked: true };
100
+ }
101
+ if (needsBundle && bundleMissing) {
71
102
  return { ok: false, error: `granted server '${entry.name}' requires a secret_bundle` };
72
103
  }
73
104
  return { ok: true };