@bridge_gpt/mcp-server 0.2.70 → 0.2.72

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 (134) hide show
  1. package/README.md +55 -17
  2. package/build/agent-launchers/claude-executor-adapter.js +29 -4
  3. package/build/agent-notes.js +171 -95
  4. package/build/agent-registry.js +5 -5
  5. package/build/agents.generated.js +12 -2
  6. package/build/bounded-wait.js +9 -1
  7. package/build/bridge-permissions.js +17 -5
  8. package/build/bridge-worktree-inspection.js +237 -0
  9. package/build/check-evidence.js +6 -0
  10. package/build/claude-review-workflow.js +1 -1
  11. package/build/cli-help.js +6 -0
  12. package/build/codex-auto-recovery.js +126 -0
  13. package/build/codex-skill-adapter.js +2 -0
  14. package/build/commands.generated.js +5 -5
  15. package/build/conductor/bridge-api-client.js +776 -23
  16. package/build/conductor/command-drift-production.js +7 -2
  17. package/build/conductor/doctor.js +93 -13
  18. package/build/conductor/epic-implementer-cli.js +55 -2
  19. package/build/conductor/gate-discovery.js +659 -19
  20. package/build/conductor/gate-settings-review.js +751 -0
  21. package/build/conductor/git-hooks-uninstall.js +112 -0
  22. package/build/conductor/git-hooks.js +81 -15
  23. package/build/conductor/guided-repair.js +10 -1
  24. package/build/conductor/install-doctor.js +2 -4
  25. package/build/conductor/launch-need-probes.js +16 -11
  26. package/build/conductor/launch-plan.js +185 -0
  27. package/build/conductor/local-merge.js +12 -1
  28. package/build/conductor/merge-execution-contract.js +1 -1
  29. package/build/conductor/merged-child-check.js +2 -1
  30. package/build/conductor/precheck-timings.js +14 -0
  31. package/build/conductor/prerequisite-inputs.js +379 -0
  32. package/build/conductor/preview-observations.js +10 -0
  33. package/build/conductor/readiness-assessment.js +78 -0
  34. package/build/conductor/readiness-cli.js +10 -0
  35. package/build/conductor/readiness-prerequisites.js +53 -0
  36. package/build/conductor/readiness-sections.js +25 -9
  37. package/build/conductor/readiness.js +20 -2
  38. package/build/conductor/recovery-cli.js +281 -14
  39. package/build/conductor/recovery-operations.js +78 -5
  40. package/build/conductor/repair-contract.js +33 -0
  41. package/build/conductor/tools.js +34 -3
  42. package/build/conductor/wait-run-attention.js +115 -0
  43. package/build/conductor/wait-run-cli.js +96 -3
  44. package/build/conductor/worker-database-doctor-inspector.js +1 -0
  45. package/build/credential-store.js +25 -20
  46. package/build/dependency-install-declarations.js +157 -0
  47. package/build/docs.generated.js +4 -4
  48. package/build/doctor.js +37 -5
  49. package/build/drive-epic-help.js +2 -2
  50. package/build/drive-epic.js +240 -56
  51. package/build/epic-ci-workflow-drift.js +71 -23
  52. package/build/epic-ci-workflow-install.js +83 -26
  53. package/build/epic-ci-workflow-v1.js +132 -0
  54. package/build/epic-ci-workflow.js +174 -13
  55. package/build/epic-implementer-bin.js +119 -44
  56. package/build/epic-launch-profile.js +1 -1
  57. package/build/executor/ci-rerun-job.js +220 -14
  58. package/build/executor/cli.js +2 -0
  59. package/build/executor/completion-contract.js +16 -0
  60. package/build/executor/credentials.js +1 -1
  61. package/build/executor/delivery-observations.js +113 -0
  62. package/build/executor/delivery-outcome.js +30 -0
  63. package/build/executor/dependency-refresh-runner.js +132 -0
  64. package/build/executor/dependency-refresh.js +530 -0
  65. package/build/executor/deps.js +4 -0
  66. package/build/executor/env.js +274 -5
  67. package/build/executor/gate-qualification-job.js +20 -5
  68. package/build/executor/harness-coverage.js +19 -0
  69. package/build/executor/http-client.js +35 -1
  70. package/build/executor/index.js +2 -1
  71. package/build/executor/install-preflight.js +1 -1
  72. package/build/executor/job-runner.js +355 -36
  73. package/build/executor/likely-tests.js +100 -98
  74. package/build/executor/preflight.js +5 -0
  75. package/build/executor/process-containment.js +18 -0
  76. package/build/executor/prompt-spec.js +84 -15
  77. package/build/executor/reconcile-overlap-job.js +6 -1
  78. package/build/executor/required-verification.js +28 -0
  79. package/build/executor/required-work-diagnostics.js +30 -0
  80. package/build/executor/required-work-ledger.js +19 -1
  81. package/build/executor/results.js +42 -0
  82. package/build/executor/service-discovery.js +42 -0
  83. package/build/executor/service-lifecycle.js +109 -2
  84. package/build/executor/service-uninstall.js +205 -0
  85. package/build/executor/service-unit.js +5 -3
  86. package/build/executor/test-clock.js +3 -0
  87. package/build/executor/verification-hints.js +179 -0
  88. package/build/executor/worker-command.js +188 -1
  89. package/build/executor/worker-database.js +299 -40
  90. package/build/executor/worker-finalization.js +65 -10
  91. package/build/executor/worker-guard-hook.js +10 -2
  92. package/build/executor/worker-resources.js +12 -1
  93. package/build/executor/worker-verification-guidance.js +64 -0
  94. package/build/executor/worktree-inspection.js +42 -0
  95. package/build/github-sign-in.js +1 -1
  96. package/build/index.js +767 -310
  97. package/build/init.js +3 -3
  98. package/build/install-bridge-conductor-gate.js +416 -41
  99. package/build/install-bridge-conductor-setup.js +135 -32
  100. package/build/install-bridge-conductor.js +769 -353
  101. package/build/install-bridge.js +419 -124
  102. package/build/install-maintenance.js +104 -0
  103. package/build/install-reexec.js +1 -1
  104. package/build/local-cleanup.js +59 -0
  105. package/build/mcp-install-state.js +68 -2
  106. package/build/merge-workflow-install.js +22 -2
  107. package/build/package-script-semantics.js +10 -0
  108. package/build/pipeline-utils.js +1 -1
  109. package/build/pipelines.generated.js +6 -6
  110. package/build/plan-execution-ledger.js +171 -10
  111. package/build/plane/plane-freshness.js +12 -9
  112. package/build/plane/preflight.js +19 -0
  113. package/build/plane/terminal-run-cleanup.js +5 -1
  114. package/build/plane/terminal-run-status.js +4 -0
  115. package/build/printed-remedy-commands.js +31 -4
  116. package/build/readiness-check.js +1 -78
  117. package/build/readiness-prerequisites.generated.js +199 -0
  118. package/build/readme.generated.js +1 -1
  119. package/build/repository-toolchains.js +623 -0
  120. package/build/setup-change-policy.js +32 -0
  121. package/build/setup-epic.js +26 -9
  122. package/build/setup-question.js +62 -0
  123. package/build/start-tickets.js +4 -0
  124. package/build/test-command-detection.js +61 -80
  125. package/build/test-support/notes-fs.js +40 -0
  126. package/build/ticket-delivery-artifacts.js +7 -0
  127. package/build/ticket-delivery-enrollment.js +80 -4
  128. package/build/ticket-delivery-run-scope.js +128 -0
  129. package/build/version.generated.js +3 -3
  130. package/build/worker-guard-hook-bin.js +2 -2
  131. package/build/worktrees.js +105 -0
  132. package/docs/EPIC-IMPLEMENTER.md +43 -0
  133. package/docs/epic-implementer/getting-started.md +95 -14
  134. package/package.json +2 -2
package/README.md CHANGED
@@ -199,10 +199,11 @@ committing anything that can hold a credential.
199
199
  cannot be used as one; and the consent prompt before the final agent session. With
200
200
  more than one launchable tool selected, the first one is used and the installer
201
201
  says so; pass `--agent` to choose another.
202
- - *Overwrite confirmations, each default **No** and each skippable with `--force`:*
203
- a saved key for this project already exists; a host config already contains a
204
- `BAPI_API_KEY`; a **git-tracked** config would receive your real key; a saved but
205
- expired self-serve signup would be discarded.
202
+ - *Changes that require consent:* replacing a different installed credential,
203
+ authorizing a credential for another endpoint, and writing a real key into a
204
+ **git-tracked** config. Generic `--force` does not authorize credential
205
+ replacement or endpoint transfer. A saved but expired self-serve signup also
206
+ requires confirmation before it is discarded.
206
207
 
207
208
  **A fresh agent session opens at the end — if your selection can launch one.** See
208
209
  step 6 above for the three conditions. Use `--agent cursor-agent` if you want
@@ -215,9 +216,10 @@ file is global too.
215
216
 
216
217
  **Your key is stored for the tools that read the store.** The MCP server and the
217
218
  shell-spawned tooling (`start-tickets` and its model routing) resolve it from
218
- `~/.config/bridge/credentials.json` on their own. The **installer** does not: a
219
- repeat `install` prompts for the credential again unless you pass `--api-key` or
220
- set `BAPI_API_KEY` in the environment.
219
+ `~/.config/bridge/credentials.json` on their own. The **installer** also reads the
220
+ saved key when the installed project is known. Repeat installation can refresh
221
+ that project without another token prompt. A different candidate requires
222
+ validation and explicit replacement consent.
221
223
 
222
224
  **A next step, when the project needs one.** The session closes with whatever
223
225
  command the server says comes next, and stays quiet when there is nothing to
@@ -410,7 +412,7 @@ later boot.
410
412
  "mcpServers": {
411
413
  "bridge": {
412
414
  "command": "npx",
413
- "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.70", "serve"],
415
+ "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.72", "serve"],
414
416
  "env": {
415
417
  "BAPI_BASE_URL": "https://bridgegpt-api.com",
416
418
  "BAPI_REPO_NAME": "your-repo",
@@ -432,7 +434,7 @@ later boot.
432
434
  "bridge": {
433
435
  "type": "stdio",
434
436
  "command": "npx",
435
- "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.70", "serve"],
437
+ "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.72", "serve"],
436
438
  "env": {
437
439
  "BAPI_BASE_URL": "https://bridgegpt-api.com",
438
440
  "BAPI_REPO_NAME": "your-repo",
@@ -454,7 +456,7 @@ later boot.
454
456
  "bridge": {
455
457
  "type": "stdio",
456
458
  "command": "npx",
457
- "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.70", "serve"],
459
+ "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.72", "serve"],
458
460
  "env": {
459
461
  "BAPI_BASE_URL": "https://bridgegpt-api.com",
460
462
  "BAPI_REPO_NAME": "your-repo",
@@ -477,7 +479,7 @@ Windsurf only supports global MCP configuration.
477
479
  "mcpServers": {
478
480
  "bridge": {
479
481
  "command": "npx",
480
- "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.70", "serve"],
482
+ "args": ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.72", "serve"],
481
483
  "env": {
482
484
  "BAPI_BASE_URL": "https://bridgegpt-api.com",
483
485
  "BAPI_REPO_NAME": "your-repo",
@@ -496,7 +498,7 @@ Windsurf only supports global MCP configuration.
496
498
  ```toml
497
499
  [mcp_servers.bridge]
498
500
  command = "npx"
499
- args = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.70", "serve"]
501
+ args = ["-y", "--prefer-offline", "@bridge_gpt/mcp-server@0.2.72", "serve"]
500
502
 
501
503
  [mcp_servers.bridge.env]
502
504
  BAPI_BASE_URL = "https://bridgegpt-api.com"
@@ -1104,7 +1106,7 @@ The Epic Implementer drives a whole epic, several related tickets, from an appro
1104
1106
  This is the one starting point. The same four steps work with Bridge's own ticket storage and with Jira:
1105
1107
 
1106
1108
  1. **Install.** `npx -y @bridge_gpt/mcp-server install` (skip it when Bridge is already installed).
1107
- 2. **Set up.** `npx -y @bridge_gpt/mcp-server install conductor` checks everything, fixes what is missing, checks again, and ends with one verdict: "Ready for your first epic" or "Not ready: N steps left".
1109
+ 2. **Set up.** `npx -y @bridge_gpt/mcp-server install epic-implementer` checks everything, fixes what is missing, checks again, and ends with one verdict: "Ready for your first epic" or "Not ready: N steps left".
1108
1110
  3. **Define the epic.** `/define-tickets` writes real child ticket keys, `epic-plan.dag.json`, and `epic-plan.meta.json`.
1109
1111
  4. **Launch.** `/drive-epic-run <EPIC> [<plan path>]` previews, asks you once, creates the run through `drive-epic`, and drives it. From a shell, run `npx -y @bridge_gpt/mcp-server drive-epic <EPIC>`.
1110
1112
 
@@ -1278,7 +1280,7 @@ It has two parts:
1278
1280
 
1279
1281
  What each command is for:
1280
1282
 
1281
- - **`install conductor`** sets up the repository, once. It checks, fixes what is missing, checks again, and ends with one verdict. It is also spelled `install-bridge conductor`, and `install conductor --help` lists every option.
1283
+ - **`install epic-implementer`** sets up the repository, once. It checks, fixes what is missing, checks again, and ends with one verdict. It is also spelled `install conductor`, and `install epic-implementer --help` lists every option.
1282
1284
  - **`/define-tickets`** writes the child tickets and the plan files. **`/plan-epic`** is the advanced planner; it needs `emit-epic-implementer-bundle finalize` and never creates a run.
1283
1285
  - **`/drive-epic-run <EPIC> [<plan path>]`** previews the launch, asks you once, creates the run through [`drive-epic`](#drive-epic), then watches and recovers it. In Claude Code it first checks whether Bridge's auto-mode sandbox description is in `~/.claude/settings.json`. Only when it is missing, it asks you once, in the session, and writes it only after an explicit yes. You can add it yourself with `npx -y @bridge_gpt/mcp-server bridge-permissions` (run from the project root; it asks first), inspect it with `bridge-permissions --check --json`, and remove it with `install --remove-bridge-permissions`. `install` itself never touches that file.
1284
1286
  - **Monitor** with the MCP tools `get_epic_snapshot` and `explain_run` (they need the `epic_implementer` profile; see [Environment Variables](#environment-variables)), `notifications <EPIC|run-id> [--follow]`, `epic-implementer epic-status`, and `executor watch <job>`.
@@ -1414,14 +1416,14 @@ Two retired names remain as failing pointers: the old event-ledger CLI name and
1414
1416
  > The v1 `epic-implementer epic-tick` command is **frozen** — it throws on every invocation. There is nothing to schedule locally, and `epic-implementer doctor` flags any epic-tick schedule left over from an earlier release so you can cancel it.
1415
1417
 
1416
1418
  <!-- BEGIN GENERATED: merge-workflow-install (managed by mcp_server/scripts/sync-readme-merge-workflow.js — DO NOT EDIT BY HAND) -->
1417
- ### `install conductor --merge-workflow`
1419
+ ### `install epic-implementer --merge-workflow`
1418
1420
 
1419
1421
  Generates the Epic Implementer **merge workflow** plus its CODEOWNERS fragment
1420
1422
  and repository-rule guidance, commits them on a managed branch, pushes with
1421
1423
  **your own git identity**, and opens a pull request with **your own `gh`**.
1422
1424
 
1423
1425
  ```
1424
- npx -y @bridge_gpt/mcp-server install conductor --merge-workflow --codeowner <@org/team|@user>
1426
+ npx -y @bridge_gpt/mcp-server install epic-implementer --merge-workflow --codeowner <@org/team|@user>
1425
1427
  ```
1426
1428
 
1427
1429
  `--codeowner` is **required** and takes exactly one `@user` or `@org/team`. Bridge
@@ -1606,7 +1608,7 @@ If a custom pipeline has the same key as a built-in pipeline, the custom version
1606
1608
  | `BAPI_PLANE_PYTHON` | No | `python` | Executable used for the Python members of `plane up` (Bridge API source checkout only). Point it at a venv interpreter when `python` on `PATH` is not the one you want |
1607
1609
  | `BAPI_PLANE_UVICORN` | No | `uvicorn` | Executable used for the server member of `plane up` |
1608
1610
  | `BAPI_PLANE_PORT` | No | `8000` | Port for the local plane server (`127.0.0.1`). Only for `plane up` and a local `drive-epic` target, from a Bridge API source checkout |
1609
- | `BAPI_EPIC_LAUNCH_PROFILE` | No | _(none)_ | Selects a host-local launch profile (saved by `install conductor --launch-profile`) for `drive-epic`. `--launch-profile` takes precedence. See `drive-epic --help-advanced` |
1611
+ | `BAPI_EPIC_LAUNCH_PROFILE` | No | _(none)_ | Selects a host-local launch profile (saved by `install epic-implementer --launch-profile`) for `drive-epic`. `--launch-profile` takes precedence. See `drive-epic --help-advanced` |
1610
1612
  | `BAPI_DOCS_DIR` | No | `docs/tmp` | Local directory for saving plans, critiques, and research reports |
1611
1613
  | `BAPI_PIPELINES_DIR` | No | `.bridge/pipelines` | Directory for user-defined custom pipeline JSON files |
1612
1614
  | `BAPI_WORKTRUNK_BIN` | No | `wt` (`git-wt` on Windows) | Override the Worktrunk executable name/path used by `start-tickets` for nonstandard installs |
@@ -2022,3 +2024,39 @@ there is no guarantee that old pending bytes survive every failure.
2022
2024
  ### Out of scope
2023
2025
 
2024
2026
  The CLI cannot diagnose non-delivery, a sender mismatch, or incompatible server behavior. It preserves saved attempts, uses the existing neutral guidance and server-enforced resend limits, and still permits the existing teammate-invite route; unresolved cases go to info@bridgegpt.ai, which does not promise a support-issued invite or a verification bypass.
2027
+
2028
+
2029
+ ## Repeat installation and identity preservation
2030
+
2031
+ Run `npx -y @bridge_gpt/mcp-server install` to refresh an existing installation.
2032
+ The installer reads project and host identity before onboarding. A saved credential
2033
+ can resume the installed project without another token prompt. Equal credentials
2034
+ are a no-op. A different candidate is validated before an explained replacement
2035
+ question; refusal, EOF, and noninteractive input preserve the installed identity.
2036
+ Generic `--force` is not credential replacement or endpoint transfer permission.
2037
+
2038
+ Production is the default destination and is displayed without another URL
2039
+ confirmation. Explicit development destinations require credentials authorized for
2040
+ that endpoint. Credential-store read and parse failures require repair; they do
2041
+ not select signup. To stop a declined environment candidate from recurring, unset
2042
+ `BAPI_API_KEY` in future shells. Secret values never belong in diagnostic output.
2043
+ Dry-run previews defer credential validation and authorization and do not read
2044
+ credentials, write notes, or persist preferences.
2045
+
2046
+ Repeat installation preserves valid tool selections and optimization posture.
2047
+ Independent completed maintenance is retained when an optional replacement or
2048
+ launch is declined. Operational failures and blocked requested capabilities return
2049
+ status 1; completed maintenance with a usable retained identity returns status 0.
2050
+
2051
+ Epic Implementer setup uses `npx -y @bridge_gpt/mcp-server install epic-implementer`.
2052
+ It requires a supported github.com repository, GitHub CLI sign-in, and Claude Code
2053
+ sign-in before dependent mutations. Fix the prerequisite and rerun setup; general
2054
+ Bridge maintenance remains available. Local token removal does not require a new
2055
+ network sign-in.
2056
+
2057
+ Agent notes are planned by canonical physical target. Shared AGENTS.md/CLAUDE.md
2058
+ files receive full guidance once. Valid marker lines and unowned bytes survive;
2059
+ broken links, outside-root targets, malformed regions, and stale observations are
2060
+ refused. Existing files are updated in place to preserve links. A separate Claude
2061
+ pointer waits for canonical guidance. These checks cover ordinary concurrent
2062
+ changes and do not claim a transactional or adversarial filesystem guarantee.
@@ -2,8 +2,9 @@ import { evaluateClaudeMcpShadowingPolicy, inspectClaudeUserConfigForMcpShadowin
2
2
  import { createDefaultAgentCapabilitiesDeps } from "../agent-capabilities/default-deps.js";
3
3
  import { runDenyEnforcementPreflight, } from "../conductor/deny-enforcement-preflight.js";
4
4
  import { CLAUDE_DISABLE_AUTO_MEMORY_ENV } from "../claude-settings.js";
5
- import { buildExecutorBaseWorkerEnv } from "../executor/env.js";
5
+ import { buildExecutorBaseWorkerEnv, hasWorkerEnvOption } from "../executor/env.js";
6
6
  import { ExecutorNamedError } from "../executor/job-errors.js";
7
+ import { WORKER_BACKGROUND_WORK_RULE } from "../executor/required-work-diagnostics.js";
7
8
  import { provisionExecutorDenyLayer } from "../executor/permissions.js";
8
9
  import { WORKER_GUARD_ROOT_FLAG } from "../executor/worker-guard-hook.js";
9
10
  import { SUPPORTED_EXECUTOR_PLATFORMS, evaluateExecutorPlatform } from "../executor/platform.js";
@@ -17,8 +18,23 @@ export const CLAUDE_ADAPTER_ID = "claude-reference";
17
18
  export const CLAUDE_ADAPTER_STRATEGY_ID = "claude-strict-mcp-v1";
18
19
  /** Contract revision this implementation targets. */
19
20
  export const CLAUDE_ADAPTER_VERSION = "1.0.0";
20
- /** Preventive guidance for every held-stdin Claude worker (BAPI-1508). */
21
- export const CLAUDE_HELD_STDIN_WORKER_GUIDANCE = "Do not use SendMessage to contact a background agent that has already finished. Start a fresh Agent instead.";
21
+ /** Preventive guidance for a held-stdin Claude worker that may not message a finished agent (BAPI-1508). */
22
+ const CLAUDE_FINISHED_AGENT_GUIDANCE = "Do not use SendMessage to contact a background agent that has already finished. Start a fresh Agent instead.";
23
+ /**
24
+ * Preventive guidance for every held-stdin Claude worker: the BAPI-1508 sentence
25
+ * followed by the BAPI-1554 completion-ordering rule.
26
+ */
27
+ export const CLAUDE_HELD_STDIN_WORKER_GUIDANCE = `${CLAUDE_FINISHED_AGENT_GUIDANCE} ${WORKER_BACKGROUND_WORK_RULE}`;
28
+ /**
29
+ * The guidance to append to a held-stdin prompt. The generic prompt assembly
30
+ * already carries the completion-ordering rule, so a prompt that has it gets only
31
+ * the Claude-specific sentence: the final prompt names the rule exactly once.
32
+ */
33
+ export function claudeHeldStdinGuidanceFor(prompt) {
34
+ return prompt.includes(WORKER_BACKGROUND_WORK_RULE)
35
+ ? CLAUDE_FINISHED_AGENT_GUIDANCE
36
+ : CLAUDE_HELD_STDIN_WORKER_GUIDANCE;
37
+ }
22
38
  /** The one operator-owned credential name this adapter forwards. */
23
39
  export const CLAUDE_OAUTH_TOKEN_ENV = "CLAUDE_CODE_OAUTH_TOKEN";
24
40
  /**
@@ -391,6 +407,10 @@ function claudePermissionArgs(posture) {
391
407
  * BAPI-1479's `workerDatabase` and `workerLauncherDirectory` are forwarded the
392
408
  * same way: explicit job-runner values the generic builder owns, never
393
409
  * reconstructed here from `parentEnv`.
410
+ *
411
+ * BAPI-1521's `workerEnv` is forwarded with its PRESENCE intact: the property is
412
+ * passed on only when the caller's options own it, so the generic builder alone
413
+ * decides between the compatibility constants and the declaration.
394
414
  */
395
415
  export function buildClaudeWorkerEnv(parentEnv, options = {}) {
396
416
  const env = buildExecutorBaseWorkerEnv(parentEnv, options);
@@ -492,6 +512,11 @@ export function createClaudeExecutorAdapter(spec, deps = {}) {
492
512
  if (input.workerLauncherDirectory !== undefined) {
493
513
  envOptions.workerLauncherDirectory = input.workerLauncherDirectory;
494
514
  }
515
+ // BAPI-1521: presence, not value — an own-key check keeps `[]`, `null` and a
516
+ // malformed value distinct from an absent declaration.
517
+ if (hasWorkerEnvOption(input)) {
518
+ envOptions.workerEnv = input.workerEnv;
519
+ }
495
520
  // BAPI-1301 (D4a): the held-stdin transport is opted into per spawn. The
496
521
  // argv form returns exactly the pre-BAPI-1301 three-key shape.
497
522
  if (input.promptTransport === "stdin-stream-json") {
@@ -501,7 +526,7 @@ export function createClaudeExecutorAdapter(spec, deps = {}) {
501
526
  promptTransport: "stdin-stream-json",
502
527
  }),
503
528
  env: buildClaudeWorkerEnv(input.parentEnv, envOptions),
504
- stdinMessages: { initial: buildClaudeStdinUserMessage(`${input.prompt}\n\n${CLAUDE_HELD_STDIN_WORKER_GUIDANCE}`) },
529
+ stdinMessages: { initial: buildClaudeStdinUserMessage(`${input.prompt}\n\n${claudeHeldStdinGuidanceFor(input.prompt)}`) },
505
530
  };
506
531
  }
507
532
  // BAPI-1364: the legacy `-p <prompt>` worker has no held stdin and no
@@ -15,9 +15,66 @@
15
15
  * bookkeeping of its own — those stay the caller's responsibility.
16
16
  */
17
17
  import path from "path";
18
+ import { constants } from "node:fs";
18
19
  /** The runtime marker pair this module owns inside a target notes file. */
19
20
  export const BRIDGE_MCP_GUIDANCE_BEGIN_MARKER = "<!-- BEGIN BRIDGE MCP GUIDANCE -->";
20
21
  export const BRIDGE_MCP_GUIDANCE_END_MARKER = "<!-- END BRIDGE MCP GUIDANCE -->";
22
+ function contains(root, target) {
23
+ const relative = path.relative(root, target);
24
+ return relative !== "" && !relative.startsWith(`..${path.sep}`) && relative !== ".." && !path.isAbsolute(relative);
25
+ }
26
+ function sameIdentity(a, b) {
27
+ return a.dev === b.dev && a.ino === b.ino && a.isSymbolicLink() === b.isSymbolicLink() && a.isFile() === b.isFile();
28
+ }
29
+ async function planPhysicalTargets(options, targets) {
30
+ const fs = options.fs;
31
+ if (!fs)
32
+ return { plans: [], failures: targets.map(target => ({ target, status: "failed", reason: "safe filesystem operations unavailable" })) };
33
+ let root;
34
+ try {
35
+ root = await fs.realpath(options.cwd);
36
+ }
37
+ catch {
38
+ return { plans: [], failures: targets.map(target => ({ target, status: "failed", reason: "project root unavailable" })) };
39
+ }
40
+ const plans = [];
41
+ const failures = [];
42
+ for (const target of targets) {
43
+ const logicalPath = path.join(root, target);
44
+ try {
45
+ let link;
46
+ try {
47
+ link = await fs.lstat(logicalPath);
48
+ }
49
+ catch (error) {
50
+ if (!isEnoent(error))
51
+ throw error;
52
+ plans.push({ root, logical: [target], path: logicalPath, original: Buffer.alloc(0), links: new Map(), absent: true });
53
+ continue;
54
+ }
55
+ const resolved = await fs.realpath(logicalPath);
56
+ if (!contains(root, resolved))
57
+ throw new Error("outside root");
58
+ const identity = await fs.lstat(resolved);
59
+ if (!identity.isFile() || identity.isSymbolicLink())
60
+ throw new Error("not regular");
61
+ const original = await fs.readBytes(resolved);
62
+ const group = plans.find(p => !p.absent && (p.path === resolved ||
63
+ (identity.dev !== undefined && identity.ino !== undefined && identity.ino !== 0 && p.identity?.dev === identity.dev && p.identity?.ino === identity.ino)));
64
+ if (group) {
65
+ group.logical.push(target);
66
+ group.links.set(target, { path: resolved, stat: link });
67
+ }
68
+ else
69
+ plans.push({ root, logical: [target], path: resolved, original, identity,
70
+ links: new Map([[target, { path: resolved, stat: link }]]), absent: false });
71
+ }
72
+ catch {
73
+ failures.push({ target, status: "failed", reason: "unsafe or unreadable target (broken link, outside root, or non-regular file)" });
74
+ }
75
+ }
76
+ return { plans, failures };
77
+ }
21
78
  /** Platforms whose shared notes file is AGENTS.md. Claude Code also gets CLAUDE.md. */
22
79
  const AGENTS_MD_PLATFORMS = new Set([
23
80
  "cursor",
@@ -26,7 +83,7 @@ const AGENTS_MD_PLATFORMS = new Set([
26
83
  "claude-code",
27
84
  ]);
28
85
  /**
29
- * Pure projection from a selected-platform set to the physical notes files
86
+ * Pure projection from a selected-platform set to logical notes filenames
30
87
  * that selection implies. Never touches the filesystem or re-detects
31
88
  * platforms — the caller supplies the already-selected set.
32
89
  */
@@ -65,61 +122,42 @@ const CLAUDE_NOTES_POINTER_NOTE = "Bridge MCP usage guidance is maintained in AG
65
122
  function buildClaudeOwnedBody() {
66
123
  return `@AGENTS.md\n\n${CLAUDE_NOTES_POINTER_NOTE}`;
67
124
  }
68
- function countOccurrences(text, marker) {
69
- return text.split(marker).length - 1;
70
- }
71
- /**
72
- * Locate the existing owned region in *text*, or classify why it cannot be
73
- * located safely. A malformed topology (a missing half, a duplicate, reversed
74
- * order, or a marker not on its own line) is reported rather than repaired —
75
- * this module never appends a second region next to one it cannot parse.
76
- */
77
125
  function scanMarkers(text) {
78
- const beginCount = countOccurrences(text, BRIDGE_MCP_GUIDANCE_BEGIN_MARKER);
79
- const endCount = countOccurrences(text, BRIDGE_MCP_GUIDANCE_END_MARKER);
80
- if (beginCount === 0 && endCount === 0)
126
+ const begin = BRIDGE_MCP_GUIDANCE_BEGIN_MARKER;
127
+ const end = BRIDGE_MCP_GUIDANCE_END_MARKER;
128
+ const begins = text.split(begin).length - 1;
129
+ const ends = text.split(end).length - 1;
130
+ if (!begins && !ends)
81
131
  return { kind: "absent" };
82
- if (beginCount === 0 || endCount === 0) {
83
- return { kind: "malformed", reason: "missing half of the marker pair" };
84
- }
85
- if (beginCount > 1)
86
- return { kind: "malformed", reason: "duplicate BEGIN marker" };
87
- if (endCount > 1)
88
- return { kind: "malformed", reason: "duplicate END marker" };
89
- const beginIndex = text.indexOf(BRIDGE_MCP_GUIDANCE_BEGIN_MARKER);
90
- const endIndex = text.indexOf(BRIDGE_MCP_GUIDANCE_END_MARKER);
91
- if (endIndex < beginIndex)
92
- return { kind: "malformed", reason: "markers are reversed" };
93
- const afterBegin = beginIndex + BRIDGE_MCP_GUIDANCE_BEGIN_MARKER.length;
94
- if (text[afterBegin] !== "\n") {
95
- return { kind: "malformed", reason: "BEGIN marker is not on its own line" };
132
+ if (begins !== 1 || ends !== 1)
133
+ return { kind: "malformed", reason: "expected exactly one marker pair" };
134
+ const b = text.indexOf(begin), e = text.indexOf(end);
135
+ const after = b + begin.length;
136
+ const endLineStart = text.lastIndexOf("\n", e - 1) + 1;
137
+ if (e < b || (text[after] !== "\n" && text.slice(after, after + 2) !== "\r\n")
138
+ || text.slice(endLineStart, e).trim().length > 0) {
139
+ return { kind: "malformed", reason: "reversed or invalid marker line" };
96
140
  }
97
- const contentStart = afterBegin + 1;
98
- const lineStart = text.lastIndexOf("\n", endIndex - 1) + 1;
99
- if (text.slice(lineStart, endIndex).trim().length > 0) {
100
- return { kind: "malformed", reason: "END marker is not on its own line" };
101
- }
102
- return { kind: "present", contentStart, contentEnd: endIndex };
103
- }
104
- /** Replace only the bytes between valid existing markers; preserve everything else. */
105
- function replaceRegion(text, contentStart, contentEnd, ownedBody) {
106
- const normalized = ownedBody.trim() + "\n";
107
- return text.slice(0, contentStart) + normalized + text.slice(contentEnd);
141
+ // Historical notes allowed a prefix before BEGIN and indentation before END.
142
+ // Keep those bytes outside the replaceable body, including END indentation.
143
+ return { kind: "present", contentStart: after + (text.slice(after, after + 2) === "\r\n" ? 2 : 1), contentEnd: endLineStart };
108
144
  }
109
- /**
110
- * Append one fresh owned region at EOF, using the minimal separator needed
111
- * for a clean markdown boundary. The existing prefix is never normalized —
112
- * only the amount of new whitespace inserted before the region varies.
113
- */
114
- function appendRegion(existingText, ownedBody) {
115
- const region = `${BRIDGE_MCP_GUIDANCE_BEGIN_MARKER}\n${ownedBody.trim()}\n${BRIDGE_MCP_GUIDANCE_END_MARKER}\n`;
116
- if (existingText.length === 0)
117
- return region;
118
- if (existingText.endsWith("\n\n"))
119
- return existingText + region;
120
- if (existingText.endsWith("\n"))
121
- return existingText + "\n" + region;
122
- return existingText + "\n\n" + region;
145
+ function newlineFor(text) { return text.includes("\r\n") ? "\r\n" : "\n"; }
146
+ /** Latin-1 is used only to locate ASCII boundaries: all unowned bytes are sliced unchanged. */
147
+ function mergeBytes(original, ownedBody) {
148
+ const text = original.toString("latin1");
149
+ const scan = scanMarkers(text);
150
+ if (scan.kind === "malformed")
151
+ return null;
152
+ const newline = scan.kind === "present"
153
+ ? (text.slice(scan.contentStart - 2, scan.contentStart) === "\r\n" ? "\r\n" : "\n")
154
+ : newlineFor(text);
155
+ const body = Buffer.from(ownedBody.trim().replace(/\r?\n/g, newline) + newline, "utf8");
156
+ if (scan.kind === "present")
157
+ return Buffer.concat([original.subarray(0, scan.contentStart), body, original.subarray(scan.contentEnd)]);
158
+ const separator = text.length === 0 || text.endsWith(newline + newline) ? "" : text.endsWith(newline) ? newline : newline + newline;
159
+ return Buffer.concat([original, Buffer.from(separator + BRIDGE_MCP_GUIDANCE_BEGIN_MARKER + newline), body,
160
+ Buffer.from(BRIDGE_MCP_GUIDANCE_END_MARKER + newline)]);
123
161
  }
124
162
  function isEnoent(err) {
125
163
  return (typeof err === "object" &&
@@ -127,58 +165,96 @@ function isEnoent(err) {
127
165
  "code" in err &&
128
166
  err.code === "ENOENT");
129
167
  }
130
- async function writeOneTarget(target, options) {
131
- const filePath = path.join(options.cwd, target);
132
- let existing;
168
+ async function applyPhysicalTarget(plan, options, merged) {
169
+ const results = (status, reason) => plan.logical.map((target, i) => ({ target, status: status === "written" && i > 0 ? "skipped" : status,
170
+ reason: status === "written" && i > 0 ? "shared physical target updated once" : reason }));
171
+ const fs = options.fs;
172
+ let handle;
173
+ let createdIdentity;
133
174
  try {
134
- existing = await options.readFile(filePath);
135
- }
136
- catch (err) {
137
- if (isEnoent(err)) {
138
- existing = "";
175
+ const root = await fs.realpath(options.cwd);
176
+ if (root !== plan.root || !contains(root, plan.path))
177
+ return results("failed", "target changed since planning");
178
+ if (!plan.absent) {
179
+ for (const [logical, link] of plan.links) {
180
+ const logicalPath = path.join(root, logical);
181
+ if (await fs.realpath(logicalPath) !== link.path || !sameIdentity(await fs.lstat(logicalPath), link.stat))
182
+ return results("failed", "target changed since planning");
183
+ }
184
+ if (!sameIdentity(await fs.lstat(plan.path), plan.identity) || !(await fs.readBytes(plan.path)).equals(plan.original))
185
+ return results("failed", "content or identity changed since planning");
139
186
  }
140
- else {
141
- return { target, status: "failed", reason: "could not read the existing file" };
187
+ if (!plan.absent && merged.equals(plan.original))
188
+ return results("skipped", "content already up to date");
189
+ if (plan.absent)
190
+ await options.mkdir(path.dirname(plan.path), { recursive: true });
191
+ const noFollow = constants.O_NOFOLLOW ?? 0;
192
+ handle = await fs.open(plan.path, plan.absent ? constants.O_WRONLY | constants.O_CREAT | constants.O_EXCL | noFollow : constants.O_RDWR | noFollow, 0o644);
193
+ const identity = await handle.stat();
194
+ if (plan.absent)
195
+ createdIdentity = identity;
196
+ if (!identity.isFile() || (!plan.absent && (!sameIdentity(identity, plan.identity) || !(await handle.readFile()).equals(plan.original))))
197
+ return results("failed", "opened target changed since planning");
198
+ if (await fs.realpath(options.cwd) !== plan.root)
199
+ return results("failed", "project root changed since planning");
200
+ for (const [logical, link] of plan.links) {
201
+ if (await fs.realpath(path.join(plan.root, logical)) !== link.path || !sameIdentity(await fs.lstat(path.join(plan.root, logical)), link.stat))
202
+ return results("failed", "target changed since planning");
142
203
  }
143
- }
144
- const ownedBody = target === "AGENTS.md" ? options.guidance : buildClaudeOwnedBody();
145
- const scan = scanMarkers(existing);
146
- let merged;
147
- if (scan.kind === "malformed") {
148
- return {
149
- target,
150
- status: "failed",
151
- reason: `existing marker region is malformed (${scan.reason})`,
152
- };
153
- }
154
- else if (scan.kind === "present") {
155
- merged = replaceRegion(existing, scan.contentStart, scan.contentEnd, ownedBody);
156
- }
157
- else {
158
- merged = appendRegion(existing, ownedBody);
159
- }
160
- if (merged === existing) {
161
- return { target, status: "skipped", reason: "content already up to date" };
162
- }
163
- try {
164
- await options.mkdir(path.dirname(filePath), { recursive: true });
165
- await options.writeFile(filePath, merged, { encoding: "utf-8" });
204
+ // Positioned writes avoid the read handle's offset. Never rename over linked files.
205
+ let offset = 0;
206
+ while (offset < merged.length) {
207
+ const { bytesWritten } = await handle.write(merged, offset, merged.length - offset, offset);
208
+ if (bytesWritten <= 0)
209
+ throw new Error("short write");
210
+ offset += bytesWritten;
211
+ }
212
+ await handle.truncate(merged.length);
213
+ await handle.sync();
214
+ return results("written");
166
215
  }
167
216
  catch {
168
- return { target, status: "failed", reason: "could not write the file" };
217
+ // Only remove our still-empty exclusively created file. Never remove a replacement or an uncertain partial write.
218
+ if (plan.absent && createdIdentity && fs.unlink) {
219
+ try {
220
+ if (sameIdentity(await fs.lstat(plan.path), createdIdentity) && (await fs.readBytes(plan.path)).length === 0)
221
+ await fs.unlink(plan.path);
222
+ }
223
+ catch { /* an uncertain or replaced target is retained */ }
224
+ }
225
+ return results("failed", "could not safely update target (changed target or filesystem failure)");
226
+ }
227
+ finally {
228
+ if (handle) {
229
+ try {
230
+ await handle.close();
231
+ }
232
+ catch { /* preserve the primary result */ }
233
+ }
169
234
  }
170
- return { target, status: "written" };
171
235
  }
172
- /**
173
- * Create or refresh the Bridge-owned notes region in every target the
174
- * selected platforms resolve to. Each target is handled independently — a
175
- * failure on one never rolls back or blocks a write already made to another.
176
- */
236
+ /** Plan all logical targets before writing; independent successes are retained. */
177
237
  export async function writeAgentNotes(options) {
178
238
  const { targets, unsupportedPlatforms } = resolveAgentNotesTargets(options.selectedPlatforms);
179
- const files = [];
180
- for (const target of targets) {
181
- files.push(await writeOneTarget(target, options));
239
+ const { plans, failures } = await planPhysicalTargets(options, targets);
240
+ const files = [...failures];
241
+ let canonicalCurrent = false;
242
+ for (const plan of plans) {
243
+ const canonical = plan.logical.includes("AGENTS.md");
244
+ if (!canonical && !canonicalCurrent) {
245
+ files.push(...plan.logical.map(target => ({ target, status: "skipped", reason: "Claude pointer deferred: canonical AGENTS.md guidance is unavailable" })));
246
+ continue;
247
+ }
248
+ const merged = mergeBytes(plan.original, canonical ? options.guidance : buildClaudeOwnedBody());
249
+ if (!merged) {
250
+ files.push(...plan.logical.map(target => ({ target, status: "failed", reason: "existing marker region is malformed" })));
251
+ continue;
252
+ }
253
+ const applied = await applyPhysicalTarget(plan, options, merged);
254
+ files.push(...applied);
255
+ if (canonical)
256
+ canonicalCurrent = applied.every(result => result.status !== "failed");
182
257
  }
258
+ files.sort((a, b) => targets.indexOf(a.target) - targets.indexOf(b.target));
183
259
  return { files, unsupportedPlatforms };
184
260
  }
@@ -59,11 +59,11 @@ export const AGENT_REGISTRY = {
59
59
  supportsModelOverride: true,
60
60
  modelFlag: "--model",
61
61
  // Claude family aliases float to the latest release and never drift, so they
62
- // can be validated against a static allowlist. The `cheap` tier deliberately
63
- // maps to `sonnet` (not `haiku`): even the lowest-difficulty tickets route to
64
- // sonnet. `haiku` stays in the allowlist so a per-repo
65
- // `difficulty_model_tier_overrides` may still opt back into it.
66
- tierModels: { cheap: "sonnet", basic: "sonnet", premium: "opus" },
62
+ // can be validated against a static allowlist. The `cheap` tier maps to
63
+ // `haiku` (Haiku 5.5 onward). It previously mapped to `sonnet` because
64
+ // Haiku 4.5 was too weak for autonomous implementation. A per-repo
65
+ // `difficulty_model_tier_overrides` of `{ "cheap": "sonnet" }` restores that.
66
+ tierModels: { cheap: "haiku", basic: "sonnet", premium: "opus" },
67
67
  staticModelAliasAllowlist: ["haiku", "sonnet", "opus"],
68
68
  // BAPI-781: the reference executor adapter. `managedCarriers` is EMPTY and
69
69
  // `passthroughs` names only the operator's own OAuth variable — Bridge