@bridge_gpt/mcp-server 0.2.29 → 0.2.31

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.
package/README.md CHANGED
@@ -902,9 +902,10 @@ The full surface, for when you need the complete enumeration. Day-to-day, use [U
902
902
 
903
903
  ### MCP tools
904
904
 
905
- The server exposes **59 documented tools** (enumerated below). What's actually registered in a session depends on `BRIDGE_MCP_PROFILE`: the default `core` profile loads a trimmed subset, and the conductor/pipeline-authoring/SFCC tools are added only under their respective profiles (see [Environment Variables](#environment-variables)). Async AI tools follow a request/get pattern: call the `request_*` tool to kick off generation, then the matching `get_*` tool to retrieve the result (or pass `wait_for_result: true` to poll automatically).
905
+ The server exposes **60 documented tools** (enumerated below). What's actually registered in a session depends on `BRIDGE_MCP_PROFILE`: the default `core` profile loads a trimmed subset, and the conductor/pipeline-authoring/SFCC tools are added only under their respective profiles (see [Environment Variables](#environment-variables)). Async AI tools follow a request/get pattern: call the `request_*` tool to kick off generation, then the matching `get_*` tool to retrieve the result (or pass `wait_for_result: true` to poll automatically).
906
906
 
907
907
  - **Connectivity & identity** — `ping`, `get_my_role`, `get_docs_dir`
908
+ - **Team & access** — `invite_member` (admin-only; mints a scoped access key for a teammate on an already-configured project — the plaintext key is shown exactly once)
908
909
  - **Jira tickets** — `get_tickets`, `get_ticket`, `create_ticket`, `update_ticket_description`, `add_comment`, `get_comments`
909
910
  - **Attachments** — `attachment` (operations: `upload`, `download`, `list`)
910
911
  - **AI generation (request/get)** — `request_plan_generation`/`get_plan`, `request_architecture`/`get_architecture`, `create_doc`/`get_doc` (design docs by `doc_type`: tdd/fsd/prd), `request_prd`/`get_prd`, `request_clarifying_questions`/`get_clarifying_questions`, `request_ticket_critique`/`get_ticket_critique`, `request_ticket_review`, `request_reimplement_context`/`get_reimplement_context`, `request_council`/`get_council`, `request_deep_research`/`get_deep_research`
@@ -76,11 +76,6 @@ export const AGENT_REGISTRY = {
76
76
  basic: "claude-4.6-sonnet-medium",
77
77
  premium: "claude-opus-4-8-thinking-high",
78
78
  },
79
- // BAPI-662: cursor-agent's interactive TUI blocks on a workspace-trust
80
- // prompt the spawned tab/session can't answer, hanging the launch. Interactive
81
- // builders already `cd`/`Set-Location` into the target worktree before
82
- // launching, so `--workspace` (headless-only) is not needed here.
83
- interactiveLaunchArgs: ["--trust"],
84
79
  },
85
80
  };
86
81
  /** The default agent used when `--agent` is omitted. */
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Read-only worktree Claude command-asset diagnostic (doctor-only, BAPI-664).
3
+ *
4
+ * Reports whether the current worktree contains every packaged Claude slash
5
+ * command under `.claude/commands/`. This probe ONLY reads command paths — it
6
+ * never writes, creates directories, invokes Git, spawns a process, compares or
7
+ * reports command file CONTENTS, or leaks raw exceptions. A committed customer
8
+ * version of a command counts as present regardless of its contents (the command
9
+ * bundle is fill-only and never refreshed), so the probe checks presence /
10
+ * readability, not freshness. The sole injected dependencies are `readFile` and
11
+ * `platform`.
12
+ */
13
+ import path from "path";
14
+ import { COMMANDS } from "./commands.generated.js";
15
+ /** Stable user-facing relative location shown in every detail string. */
16
+ const COMMAND_DIR_LABEL = ".claude/commands/";
17
+ /** How many missing filenames to list before summarizing the remainder. */
18
+ const MAX_LISTED_MISSING = 5;
19
+ /** The `path` API for the target platform (win32 vs posix). */
20
+ function pathApiForPlatform(platform) {
21
+ return platform === "win32" ? path.win32 : path.posix;
22
+ }
23
+ /** Render a bounded, deterministic list of missing filenames (generated order). */
24
+ function formatMissing(missing) {
25
+ if (missing.length <= MAX_LISTED_MISSING) {
26
+ return missing.join(", ");
27
+ }
28
+ const shown = missing.slice(0, MAX_LISTED_MISSING).join(", ");
29
+ return `${shown} (+${missing.length - MAX_LISTED_MISSING} more)`;
30
+ }
31
+ /**
32
+ * Probe whether `<worktreeRoot>/.claude/commands/` contains every packaged
33
+ * command asset. A `readFile` that resolves counts the asset as present (any
34
+ * contents); a rejection (missing OR unreadable) counts it as absent. Returns
35
+ * `found: true` only when every packaged command filename is present, otherwise a
36
+ * `found: false` result with a concise, actionable, secret-free detail that
37
+ * points the operator back to `start-tickets` (never to manually copying or
38
+ * committing generated files).
39
+ */
40
+ export async function probeWorktreeCommandAssets(worktreeRoot, deps) {
41
+ const filenames = Object.keys(COMMANDS);
42
+ if (filenames.length === 0) {
43
+ return {
44
+ found: false,
45
+ detail: "Packaged command bundle is empty — reinstall or rebuild the MCP server package.",
46
+ };
47
+ }
48
+ const api = pathApiForPlatform(deps.platform);
49
+ const commandsDir = api.join(worktreeRoot, ".claude", "commands");
50
+ const missing = [];
51
+ for (const filename of filenames) {
52
+ try {
53
+ await deps.readFile(api.join(commandsDir, filename));
54
+ }
55
+ catch {
56
+ // Missing OR unreadable — either way the asset is not usable. We never
57
+ // surface the underlying error (it can carry paths / exception text).
58
+ missing.push(filename);
59
+ }
60
+ }
61
+ if (missing.length === 0) {
62
+ return {
63
+ found: true,
64
+ detail: `${filenames.length} packaged command assets present under ${COMMAND_DIR_LABEL}`,
65
+ };
66
+ }
67
+ return {
68
+ found: false,
69
+ detail: `${missing.length} of ${filenames.length} packaged command assets missing or unreadable under ` +
70
+ `${COMMAND_DIR_LABEL} (${formatMissing(missing)}). Re-run start-tickets to provision them.`,
71
+ };
72
+ }
@@ -0,0 +1,157 @@
1
+ /**
2
+ * Shared Claude command-asset provisioning (BAPI-664).
3
+ *
4
+ * Materializes the FULL packaged command bundle (`COMMANDS` from
5
+ * `commands.generated.ts`, the single source of truth) into a worktree's
6
+ * `.claude/commands/` directory so every packaged slash command is runnable from
7
+ * a freshly created worktree — whether spawned by the interactive `start-tickets`
8
+ * orchestration or by the headless conductor executor.
9
+ *
10
+ * Semantics (locked ticket decisions):
11
+ * - FULL bundle: every entry in `COMMANDS` is provisioned.
12
+ * - FILL-ONLY: a command file that already exists is treated as a customer asset
13
+ * and left byte-for-byte unchanged — its contents are never read-compared or
14
+ * refreshed. Only a missing (`ENOENT`) file is created. There is no refresh
15
+ * flag.
16
+ * - Repository-common exclude: after materialization, `.claude/commands/` is
17
+ * added to the worktree's Git `info/exclude` (resolved via Git for linked
18
+ * worktrees). `info/exclude` lives in the common Git directory shared by
19
+ * sibling worktrees, and an ignore rule never hides an already-tracked file,
20
+ * so this common scope is safe.
21
+ *
22
+ * All filesystem + command access is dependency-injected so this is unit-testable
23
+ * with no real I/O. This module NEVER imports `node:fs` / `child_process`, writes
24
+ * to stdout/stderr, or registers an MCP tool — failures are surfaced structurally
25
+ * and rendered by the caller's existing orchestration boundary.
26
+ */
27
+ import path from "path";
28
+ import { COMMANDS } from "./commands.generated.js";
29
+ import { ensureGitInfoExcluded } from "./git-ignore-utils.js";
30
+ /** The exact exclude entry appended for the command directory (POSIX-relative). */
31
+ const COMMAND_DIR_EXCLUDE_ENTRY = ".claude/commands/";
32
+ /** Bounded, secret-free error surfaced when the packaged bundle is empty. */
33
+ const EMPTY_BUNDLE_ERROR = "Command provisioning failed: the packaged command bundle is empty — reinstall or rebuild the MCP server package.";
34
+ /**
35
+ * Resolve the path API for the target platform. Local (not imported from
36
+ * `start-tickets.ts`) to avoid a runtime import cycle.
37
+ */
38
+ export function pathApiForCommandProvisioningPlatform(platform) {
39
+ return platform === "win32" ? path.win32 : path.posix;
40
+ }
41
+ /** True only for a Node `ENOENT` (missing-file) error. */
42
+ function isEnoentError(err) {
43
+ return (typeof err === "object" &&
44
+ err !== null &&
45
+ err.code === "ENOENT");
46
+ }
47
+ /**
48
+ * Fill every MISSING packaged command asset into `<worktreeRoot>/.claude/commands/`
49
+ * without touching any existing customer file, then ensure `.claude/commands/` is
50
+ * added to the worktree's Git exclude. Returns a structured result; never throws
51
+ * for an expected filesystem/Git failure, and never leaks raw exception text,
52
+ * command output, or file contents.
53
+ */
54
+ export async function provisionCommandsForWorktree(worktreeRoot, deps) {
55
+ const api = pathApiForCommandProvisioningPlatform(deps.platform);
56
+ const normalizedRoot = api.isAbsolute(worktreeRoot)
57
+ ? api.normalize(worktreeRoot)
58
+ : api.resolve(deps.cwd, worktreeRoot);
59
+ const commandsDir = api.join(normalizedRoot, ".claude", "commands");
60
+ const entries = Object.entries(COMMANDS);
61
+ if (entries.length === 0) {
62
+ // No runnable slash commands could ever be provisioned — fail loudly rather
63
+ // than reporting a hollow success.
64
+ return { ok: false, error: EMPTY_BUNDLE_ERROR };
65
+ }
66
+ // Phase 1 — discover which packaged files are absent. A successful read means
67
+ // the customer already owns that asset; leave it untouched. Only ENOENT counts
68
+ // as "missing"; any other read failure is a bounded, secret-free error.
69
+ let fillError = null;
70
+ const missing = [];
71
+ for (const [filename, content] of entries) {
72
+ const target = api.join(commandsDir, filename);
73
+ try {
74
+ await deps.readFile(target);
75
+ }
76
+ catch (err) {
77
+ if (isEnoentError(err)) {
78
+ missing.push([filename, content]);
79
+ }
80
+ else {
81
+ fillError = `Command provisioning failed: could not read existing command asset '${filename}'.`;
82
+ break;
83
+ }
84
+ }
85
+ }
86
+ // Phase 2 — create the directory (only when something is missing) and write the
87
+ // absent files in bundle order using the packaged string unchanged.
88
+ if (!fillError && missing.length > 0) {
89
+ try {
90
+ await deps.mkdir(commandsDir, { recursive: true });
91
+ for (const [filename, content] of missing) {
92
+ await deps.writeFile(api.join(commandsDir, filename), content);
93
+ }
94
+ }
95
+ catch {
96
+ fillError =
97
+ "Command provisioning failed: could not write one or more packaged command assets.";
98
+ }
99
+ }
100
+ // Phase 3 — ALWAYS attempt exclusion, even after a partial or failed fill, so
101
+ // partially bootstrapped files are never left visible to Git. The primary fill
102
+ // failure is preserved if both the fill and the exclusion fail.
103
+ let excludeError = null;
104
+ try {
105
+ await ensureGitInfoExcluded(normalizedRoot, COMMAND_DIR_EXCLUDE_ENTRY, {
106
+ readFile: deps.readFile,
107
+ writeFile: deps.writeFile,
108
+ mkdir: deps.mkdir,
109
+ runCommand: deps.runCommand,
110
+ platform: deps.platform,
111
+ });
112
+ }
113
+ catch {
114
+ excludeError =
115
+ "Command provisioning failed: could not add '.claude/commands/' to the worktree Git exclude file.";
116
+ }
117
+ if (fillError)
118
+ return { ok: false, error: fillError };
119
+ if (excludeError)
120
+ return { ok: false, error: excludeError };
121
+ return { ok: true };
122
+ }
123
+ /**
124
+ * Provision command assets for every eligible (`created`, path-bearing) row, in
125
+ * input order, serially. A non-`created` row or a `created` row without a usable
126
+ * path is returned unchanged. A per-worktree bootstrap failure marks ONLY that
127
+ * row `spawn-failed` (with a secret-free `Command provisioning failed: …` error)
128
+ * so the affected worker is skipped by all later spawn logic while its siblings
129
+ * proceed. A defensive per-row catch guarantees one unexpected failure cannot
130
+ * abort later rows or reject the overall call.
131
+ */
132
+ export async function provisionCommandsForCreatedWorktrees(rows, deps) {
133
+ const out = [];
134
+ for (const row of rows) {
135
+ if (row.status !== "created" || !row.path) {
136
+ out.push(row);
137
+ continue;
138
+ }
139
+ try {
140
+ const result = await provisionCommandsForWorktree(row.path, deps);
141
+ if (result.ok) {
142
+ out.push(row);
143
+ }
144
+ else {
145
+ out.push({ ...row, status: "spawn-failed", error: result.error });
146
+ }
147
+ }
148
+ catch {
149
+ out.push({
150
+ ...row,
151
+ status: "spawn-failed",
152
+ error: "Command provisioning failed: an unexpected error occurred while bootstrapping worktree command assets.",
153
+ });
154
+ }
155
+ }
156
+ return out;
157
+ }
@@ -14,8 +14,8 @@ export const COMMANDS = {
14
14
  "full-automation.md": "---\nschedulable: true\narguments: {\"positionals\":[],\"flags\":[{\"name\":\"ideaFile\",\"flag\":\"--idea-file\",\"type\":\"string\",\"required\":true},{\"name\":\"auto\",\"flag\":\"--auto\",\"type\":\"boolean\"}]}\n---\n\nRun the end-to-end full-automation chain (idea-to-ticket → review-ticket → start-tickets) via the server-side chain orchestrator.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command drives Phase A's server-side full-automation chain. The only orchestration tools you may drive are `run_full_automation` and `resume_full_automation`; any other Bridge API MCP call you make must be one a server `agent_task` instruction explicitly directs. The server owns all orchestration — ticket creation, review fan-out, and the start-tickets handoff. Do NOT enrich, re-implement, or second-guess any of that work on the client side.\n\n## Stage 0 — Parse arguments\n\n1. Tokenize `$ARGUMENTS` on whitespace. Recognize the following position-independent flags. Each flag supports both the space form (`--flag value`) and the equals form (`--flag=value`) where a value is taken:\n - `--idea <text>` / `--idea=<text>`\n - `--idea-file <path>` / `--idea-file=<path>`\n - `--auto`\n - `--require-approval`\n - `--scheduled-at <ISO-8601>` / `--scheduled-at=<ISO-8601>`\n - `--chain-run-id <UUID>` / `--chain-run-id=<UUID>`\n - `--max-children N` / `--max-children=N`\n - `--allow-duplicate`\n\n2. Value-consumption rules:\n - `--idea` (space form) consumes every subsequent token until the next recognized flag — the idea may contain spaces.\n - `--idea-file`, `--scheduled-at`, `--chain-run-id`, and `--max-children` each consume exactly one value token (the immediately following token, or the text after `=`).\n - `--auto`, `--require-approval`, and `--allow-duplicate` are boolean toggles and consume no value.\n\n3. Free-form idea: all non-flag tokens become the free-form `idea` text **only when both `--idea` and `--idea-file` are absent**. Join those tokens back together preserving order and trim surrounding whitespace. When `--idea` or `--idea-file` is present, there must be no leftover non-flag tokens: reject any stray non-flag token (for example, text following `--idea=<text>` or following the `--idea-file <path>` value) before any MCP tool call rather than silently dropping it.\n\n4. Reject **unknown flags** (any token beginning with `--` that is not one of the recognized flags above) before making any MCP tool call. Stop and report the offending flag.\n\n5. Reject **combined `--idea` and `--idea-file`** before making any MCP tool call:\n ```text\n Provide exactly one of --idea or --idea-file; do not pass both.\n ```\n\n6. Missing-input rule: unless `--chain-run-id` is present, an idea is required. If `--chain-run-id` is absent **and** no idea was supplied (no `--idea`, no `--idea-file`, and no free-form idea tokens), stop immediately and display exactly:\n ```text\n Usage: /full-automation (--idea \"<text>\" | --idea-file <path> | <free-form idea>) [--require-approval] [--scheduled-at <ISO-8601>] [--chain-run-id <UUID>] [--max-children N] [--allow-duplicate]\n ```\n\n7. `--chain-run-id` is the resume path and does **not** require any idea content — when it is present, skip the missing-input check above and proceed to resume.\n\n8. `--idea-file` is forwarded as a path. The skill must **not** read the file contents locally; the server resolves the file.\n\n9. Resolve the derived values:\n - `auto_approve` defaults to `true` (full automation is hands-off by default). It is `false` **only** when `--require-approval` is present. `--auto` is accepted but redundant (a no-op that restates the default), and `--scheduled-at` likewise runs hands-off. When `--require-approval` is present, the chain pauses at external-mutation and review-decision gates for confirmation.\n - `max_children` is the parsed positive integer when `--max-children` is present; otherwise omit it entirely so the server default applies.\n - `allow_duplicate` is `true` only when `--allow-duplicate` is present; otherwise omit it.\n\n## Stage 1 — Drift-check gate\n\nThis gate runs immediately after parsing and **before any MCP tool call**.\n\n1. If `--scheduled-at` is absent, skip this entire stage.\n2. Compute `delta_seconds = now_utc - scheduled_at` (both in UTC).\n3. If `delta_seconds <= 60`, proceed silently to Stage 2.\n4. If `delta_seconds > 60`, present this prompt verbatim (substituting the bracketed values):\n ```text\n Scheduled at <T-iso> UTC; running now at <now-iso> UTC (<Δ human-readable> late). The laptop was likely asleep or unavailable at the scheduled time. Confirm to proceed with the chain, or cancel.\n ```\n Offer the user the choices: `[Confirm] / [Cancel]`.\n5. On `Confirm`, proceed to Stage 2.\n6. On `Cancel`, print this message verbatim and stop:\n ```text\n Chain cancelled by user (drift confirmation declined). No Jira tickets created.\n ```\n When the user cancels, `run_full_automation` must **not** be called.\n7. The 60-second threshold is fixed and must not be made configurable.\n\n## Stage 2 — Run or resume the chain\n\nThe chain is driven entirely by the server-side orchestrator. Announce progress using each envelope's `preamble`, preserving its `Stage N of M — <title>` shape.\n\n### Stage 2a — Start (when `--chain-run-id` is absent)\n\nCall **only** `run_full_automation`. Build the payload, **omitting** any optional value that was not provided (never send `null` or empty strings):\n```json\n{\n \"idea\": \"<resolved inline/free-form idea, when provided>\",\n \"idea_file\": \"<idea-file path, when provided>\",\n \"auto_approve\": \"<resolved boolean>\",\n \"scheduled_at\": \"<scheduled-at value, when provided>\",\n \"max_children\": \"<parsed integer, when provided>\",\n \"allow_duplicate\": \"<true, when provided>\"\n}\n```\n\n### Stage 2b — Resume (when `--chain-run-id` is present)\n\nCall **only** `resume_full_automation` first, with:\n```json\n{\n \"chain_run_id\": \"<UUID>\",\n \"agent_result\": \"Manual resume requested from /full-automation --chain-run-id.\"\n}\n```\n\n### Stage 2c — Envelope loop\n\nFor each envelope returned by `run_full_automation` / `resume_full_automation`, dispatch on `status` / `next_action.kind`:\n\n- `status: \"failed\"` → stop chain progression and render the final report (Stage 3) with the failure status. Do **not** advance to any later stage.\n- `status: \"completed\"` or `next_action.kind: \"complete\"` → render the final report (Stage 3).\n- `status: \"needs_agent_task\"` with `next_action.kind: \"agent_task\"` → display the envelope `preamble`, perform the agent task exactly as the `next_action.instruction` directs, then call `resume_full_automation` with `chain_run_id` set to the envelope's `chain_run_id` and `agent_result` set to the resulting text. Loop back and process the next envelope.\n\nSpecial case — the stage-3 handoff: when the agent-task instruction names a `/start-tickets ...` command, invoke that slash command in **this same session**, summarize the outcome in one line, and pass that one-line summary as `agent_result` to `resume_full_automation`.\n\nConstraints:\n- On your own initiative, the skill must **not** call any Bridge API MCP tool other than `run_full_automation` / `resume_full_automation` — in particular, never independently drive orchestration (`run_pipeline`, `resume_pipeline`, `get_pipeline_recipe`) or enrich tickets (`get_ticket`, `update_ticket_description`, etc.). **However, when a `needs_agent_task` instruction returned by the server explicitly directs you to call a specific Bridge API MCP tool** (for example an orchestrator-directed `get_tickets`, `create_ticket`, `attachment`, or `track_ticket`), **you must invoke that tool exactly as instructed** — performing an orchestrator-directed agent task is not re-orchestrating.\n- If a v1 envelope unexpectedly returns `next_action.kind: \"mcp_call\"`, stop with a clear protocol error instead of bypassing the server-side orchestrator:\n ```text\n Protocol error: chain returned next_action.kind \"mcp_call\", which is out of scope for /full-automation v1. Stopping.\n ```\n\n## Stage 3 — Final report\n\nWhen the chain completes or fails, render this skeleton verbatim:\n\n```markdown\n## Full Automation Complete\n\nChain run: <chain_run_id>\nIdea: <first 80 chars of idea>...\nStages:\n 1. idea-to-ticket: <stages[0].summary>\n 2. review-ticket: <stages[1].summary>\n 3. start-tickets: <stages[2].summary>\n\nTotal Jira tickets created: N\nTotal worktrees spawned: M\nStatus: Success / Failed at stage N — <reason>\n```\n\n- Stage summaries come from the chain envelope or manifest when present.\n- When the completed envelope does not include full stage objects, use the summaries already surfaced in the prior `preamble` text rather than calling additional tools.\n- A stage-1 `too_vague_to_ticket` failure must render the upstream halt reason and set `Status: Failed at stage 1 — <reason>`.\n- Failed chains must not advance to later stages after a failed envelope is received.\n",
15
15
  "idea-to-ticket.md": "Convert a short human idea into a Jira ticket (or Epic plus child tickets) via the server-side idea-to-ticket pipeline.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly other than `get_pipeline_recipe` — the recipe determines which tools to call and with what parameters.\n\n## Stage 0 — Parse arguments\n\n1. Tokenize `$ARGUMENTS` on whitespace. Recognize the following position-independent flags (any other tokens are part of the idea):\n - `--allow-duplicate`\n - `--max-children=N` where `N` is a positive integer\n - `--auto`\n\n Flags are optional. Treat absence of a flag as the default; never pass empty-string or null as a placeholder.\n\n2. Everything that is not a recognized flag is the free-form `idea` text. Join those tokens back together preserving order. Trim surrounding whitespace.\n\n3. If the resulting `idea` is empty, stop immediately and display:\n ```\n Usage: /idea-to-ticket <idea> [--allow-duplicate] [--max-children=N] [--auto]\n ```\n\n## Stage 1 — Derive pipeline variables\n\n4. Derive `slug` from the first 6-8 meaningful words of the idea: lowercase, kebab-case, strip non-alphanumeric characters except hyphens, and truncate to roughly 60 characters. Skip stop-words such as \"the\", \"a\", \"an\" when picking the 6-8 meaningful words.\n\n5. Derive `run_id` as `<YYYYMMDD-HHMMSS>-<short-uuid>` using the current UTC time and a short UUID suffix (8 hex chars is enough). The combination of `slug` and `run_id` uniquely identifies this run's artifact directory.\n\n6. Derive the boolean-as-string variables:\n - `allow_duplicate` is `\"true\"` if `--allow-duplicate` was present, otherwise `\"false\"`.\n - `auto_approve_external` is `\"true\"` if `--auto` was present, otherwise `\"false\"`.\n - `max_children` is the integer following `--max-children=` as a string, or `\"10\"` when the flag is absent.\n\n## Stage 2 — Call the recipe\n\n7. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"idea-to-ticket\"`\n - `variables`: `{ \"idea\": \"<idea>\", \"slug\": \"<slug>\", \"run_id\": \"<run_id>\", \"allow_duplicate\": \"<allow_duplicate>\", \"auto_approve_external\": \"<auto_approve_external>\", \"max_children\": \"<max_children>\" }`\n\n Do NOT pass `docs_dir` or `idea_hash` in variables — both are auto-injected by the pipeline system (`docs_dir` from `BAPI_DOCS_DIR`; `idea_hash` is a stable hash derived from the `idea`).\n\n If the tool returns an error, stop and report the failure.\n\n8. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n The recipe drives the ordered stages for you — do not invoke them directly. In order they are: preflight-and-readiness → research-decision → execute-research → duplicate-and-context-scan → screen-and-resolve → frame-goals-and-nfrs → **comp-analysis** (a gated, backend-safe perception step that maps any attached/referenced design comp to existing components, templates, SCSS/CSS tokens, and routes before drafting; it short-circuits for backend-only or no-comp work) → draft-and-critique → upload-and-track.\n\n## Stage 3 — Final summary\n\n9. After all steps complete, display a summary:\n ```\n ## Pipeline Complete\n\n **Idea**: <first 80 characters of idea>...\n **Slug**: <slug>\n **Run directory**: <docs_dir>/idea-to-ticket/<slug>-<run_id>/\n **Steps executed**: N of M\n **Status**: Success / Failed at step N\n ```\n",
16
16
  "implement-ticket.md": "# Implement Ticket\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly -- the recipe determines which tools to call and with what parameters.\n\n## CONDUCTOR_MESSAGE_RELAY ##\n\nIf you were launched under the Conductor (your environment carries a conductor run/worker identity), cooperatively poll for supervisor guidance while you work: at natural checkpoints — after reading context, before major code changes, after major implementation chunks, while polling CI checks during the post-PR correction loop, and before your final response — call the `check_messages` MCP tool. The tool reads and acknowledges any messages addressed to you, and acknowledged messages are not redelivered, so a later call returns only new guidance. This is cooperative polling only — it is not prompt injection and never mutates a live session. If the tool or conductor identity is unavailable, continue the task without derailing.\n\n1. Parse `$ARGUMENTS` to extract:\n - A required `ticket_key` matching the Jira key pattern (`[A-Z][A-Z0-9]+-\\d+`).\n - An optional position-independent `--auto` flag.\n\n Tokenize `$ARGUMENTS` on whitespace. The first token matching the Jira key pattern is the `ticket_key`; ignore any additional ticket-key tokens. The presence of a `--auto` token (anywhere in `$ARGUMENTS`) sets `auto_approve` to `true`.\n\n If `$ARGUMENTS` is empty or contains no token matching the Jira key pattern, stop immediately and display:\n ```\n Invalid ticket key format. Expected: PROJ-123 [--auto]\n Usage: /implement-ticket <ticket_key> [--auto]\n ```\n\n2. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"implement-ticket\"`\n - `variables`: `{ \"ticket_key\": \"<ticket_key>\" }`\n - `auto_approve`: `true` — only when `--auto` was passed; otherwise omit this field entirely.\n\n If the tool returns an error, stop and report the failure.\n\n3. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n4. After all steps complete, display a summary:\n ```\n ## Pipeline Complete\n\n **Ticket**: <ticket_key>\n **Steps executed**: N of M\n **Status**: Success / Failed at step N\n ```\n\n---\n\n# Worker scope discipline and clean exit (Conductor auto mode)\n\nThese rules apply only when you were launched under the Conductor in auto mode (`--auto`); a normal interactive `/implement-ticket` run is unaffected.\n\n## Declared file-scope discipline (N-2)\n\nIf your environment carries `BAPI_CONDUCTOR_DECLARED_TOUCHED_FILES_JSON` (a JSON array of the ticket's declared touched files), stay within that declared file boundary: do **not** create, modify, or delete files outside the declared set. Those out-of-scope files typically belong to a sibling ticket, and editing them risks a merge conflict or a silent clobber of the sibling's merged work. The pre-PR file-scope guard (run at the PR-creation step) will warn about any out-of-scope diff — treat that warning as a signal to re-check your scope, not as a blocker. When the variable is absent, empty, or invalid there is no declared boundary and this rule does not apply.\n\n## Clean session exit (D2)\n\nAfter the final pipeline step completes, cleanly end your worker session (for example by issuing the `/exit` command) so the worktree is released and no idle process lingers — but **only when no follow-up remains that you still own**. Do **not** exit while any of the following is true:\n\n- there are unresolved CI failures you are still correcting (the post-PR CI-correction loop in the CI-monitoring step still owns work),\n- review changes were requested and you have not yet addressed them,\n- there is a merge conflict on your PR that you still own,\n- you have unpushed local commits.\n\nExit only after your final branch state is pushed, the done-gate / CI-monitoring workflow required by the recipe has completed, and no CI/review follow-up remains. A clean `SessionEnd` is both the correct terminal lifecycle signal and the point at which the worker should exit.\n",
17
- "install-bridge.md": "Bootstrap Bridge API project configuration from the local codebase via the easy-install manifest.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command takes no arguments; any `$ARGUMENTS` text is ignored.\n\nCommand contract version: **5**. The install manifest returns a `command_contract_version`; Stage 2\ncompares it to this number to detect a stale scaffolded copy of this command.\n\nThis command performs a one-time \"easy install\" of Bridge API project configuration. It reads the\nserver-owned install manifest once, derives values for the **unset** bootstrap fields from the local\ncodebase, asks for human approval of the project description, applies everything in a single atomic\ncall, and then presents a **concise capability report** derived from a fresh read-after-write manifest\nread. The server owns all skip-if-set, conflict, and confirmation semantics — this command never makes\nits own skip-if-set decisions — and the server owns the complete tool catalog and the bounded concise\nprojection over it, their grouping and ordering, and every gate and dependency relationship; this\ncommand formats the server's contract and never recomputes it from prose. Indexing is never a decision\nthis command makes or asks about: it starts automatically, gated entirely by server-side readiness (see\nStage 8).\n\nThis command is portable across Claude Code, Cursor, and Copilot: it only drives the Bridge API MCP\ntools (`get_my_role`, `get_install_manifest`, `apply_install_manifest`).\n\nIf any stage fails, stop immediately and report which stage failed and why.\n\n**Install-spawn context.** When the spawning instruction explicitly says this `/install-bridge` run is\nin the \"install-spawn context\" (it was launched by the `install-bridge` CLI's fresh agent session),\nStage 8, Stage 9, and Stage 10 are SKIPPED and the single closing interaction is the concise capability\nreport plus a `/learn-repository` recommendation that the spawn prompt owns. When you invoke\n`/install-bridge` directly (manual invocation), Stages 8, 9, and 10 run normally.\n\n## Stage 1 — Admin preflight\n\n1. Call the `get_my_role` MCP tool (no parameters). Inspect the response:\n - If `source` is `\"legacy\"`: proceed (legacy keys are permitted).\n - Else if `role` is `\"admin\"`: proceed.\n - Otherwise (a non-admin `user_access` key): stop immediately and display:\n ```\n Admin role required to apply install configuration. Ask a project admin to run /install-bridge,\n or use an admin API key.\n ```\n\n## Stage 2 — Read the manifest (once, pre-apply)\n\n1. Call the `get_install_manifest` MCP tool exactly once here.\n2. Keep the returned `snapshot_token` verbatim — you must pass the SAME token to the apply call in\n Stage 5. Do not call `get_install_manifest` again before applying; a fresh read would invalidate\n the token you are about to use. (Stage 7 performs a SEPARATE, later read-after-write manifest read\n for the current capability status — that is deliberate and does not reuse this token.)\n3. The manifest contains ordered `groups` of bootstrap fields (each with `field_name`, `is_set`,\n `current_value`, `guidance`, `examples`, `validation_summary`, `requires_confirmation`), a list of\n `deferred_fields`, a `next_step`, `done_criteria`, a `command_contract_version`, and the\n `snapshot_token`. It also carries the additive capability fields (`integrations`, `configured`,\n `learned`, `indexed`, `tool_capabilities`, `concise_tool_capabilities`, `locked_tools`,\n `unlocked_tools`) — but ignore those here; the accurate capability status is the post-apply read in\n Stage 7. `tool_capabilities` is the COMPLETE catalog-backed report field (one entry per registered\n MCP tool, grouped and ordered by the server); `concise_tool_capabilities` is the ADDITIVE, bounded\n projection Stage 7 actually renders (see Stage 7); `locked_tools` / `unlocked_tools` are LEGACY\n compatibility data covering only the VCS/index policy cases and are NOT the tool inventory.\n4. Compare the manifest's `command_contract_version` to this command's contract version (5, stated at\n the top of this file). If the manifest's version is HIGHER, this scaffolded command copy is stale:\n warn the user to refresh it by running `npx -y @bridge_gpt/mcp-server --init` in the project root,\n then proceed conservatively — wherever the manifest's `guidance`, `next_step`, or `done_criteria`\n differ from these instructions, follow the manifest.\n\n## Stage 3 — Derive values for UNSET bootstrap fields only\n\n1. Consider ONLY fields whose `is_set` is `false`. Never re-derive or overwrite a field that is\n already set — the server will also skip already-set fields, but you should not even propose them.\n2. For each unset field, derive a value from the local codebase following that field's `guidance`\n (e.g. infer `working_in` from frameworks/manifests, `version_control_system` from the git remote,\n testing stacks from test config and dependencies, directory fields from the repo layout).\n3. Omit any field you are uncertain about or that does not apply — leaving it unset is always\n acceptable. Do NOT guess.\n4. Specifically, do NOT invent a `version` when the platform has no meaningful version concept; leave\n it unset.\n5. Before deriving `version_control_system` or `base_branch`, confirm the git repository root is THIS\n project's root: `git rev-parse --show-toplevel` must resolve to the project directory itself. If\n the git root is an ancestor directory (the project is nested inside another repository), OMIT both\n fields and note why in the final report — deriving them would describe the parent repository, not\n this project.\n6. If you find real evidence for TWO OR MORE plausible values for a field (e.g. configs for multiple\n test frameworks, multiple frameworks in a monorepo), treat the value as ambiguous and omit it\n rather than picking one.\n7. Do NOT derive `selected_mcp_slugs`, even though it appears as an unset bootstrap-eligible field in\n the manifest. MCP validation manual selection is deferred to `/learn-repository`, which derives and\n confirms it with the codebase already researched. Install neither proposes nor applies this field.\n\n## Stage 4 — Human approval for confirmation-requiring fields\n\n`project_description` is the ONLY confirmation-requiring field install proposes. It carries\n`requires_confirmation: true` in the manifest, so it is never applied on derivation alone — it needs\nexplicit human approval. (`selected_mcp_slugs` also requires confirmation, but install does not\nderive it at all; `/learn-repository` asks for it. See Stage 3 step 7.)\n\n1. If `project_description` is unset and you can draft a concise description from the codebase,\n present the proposed `project_description` text to the human and ask for explicit approval before\n including it.\n2. Include `project_description` in the apply payload ONLY as\n `{ \"value\": <approved value>, \"confirmed\": true }`, and only after the human approves it. If the\n human does not approve it, omit the field entirely.\n3. If no human response can be obtained (e.g. a non-interactive / headless session), do NOT stall and\n do NOT abandon the install: proceed to Stage 5 with `project_description` omitted, and report it\n as \"pending human input\" in the final summary. The other derived fields must still be applied — an\n unapproved description never blocks them.\n\n## Stage 5 — Apply (one call)\n\n1. Make exactly ONE call to the `apply_install_manifest` MCP tool, passing:\n - `snapshot_token`: the exact token from Stage 2.\n - `fields`: a map of the derived fields. Scalar fields may be passed directly\n (e.g. `\"base_branch\": \"main\"`); an approved `project_description` must use the\n `{ \"value\": ..., \"confirmed\": true }` object form from Stage 4. Never include\n `selected_mcp_slugs` in this payload — install does not derive or apply it (Stage 3 step 7).\n2. Do not implement any client-side skip-if-set, conflict, or confirmation logic — the server owns\n all of that and returns the outcome buckets.\n3. The apply is partial-tolerant: fields that fail server-side validation are returned in the\n `rejected` bucket while the valid fields still commit. A rejected field is therefore reported,\n not fatal — do NOT retry the whole apply just because one field was rejected.\n\n## Stage 6 — Persist the routing credential\n\nThe Bash-spawned `start-tickets` CLI runs in a DIFFERENT runtime surface than this MCP server, so a\nkey that lives only in `.mcp.json` / `.cursor/mcp.json` is invisible to it and difficulty→model\nrouting silently degrades. This final stage persists the already-validated key into the user-scoped\ncredential store (`~/.config/bridge/credentials.json`) so shell-spawned CLI commands can resolve it.\n\n1. Call the `persist_routing_credential` MCP tool with `repo_name` set to the repository name for\n this install (the configured `BAPI_REPO_NAME`). Pass `repo_name` ONLY — this tool resolves the\n API key inside the MCP server process. NEVER pass or display `BAPI_API_KEY` (nor `api_key`,\n `apiKey`, `secret`, or `token`); the key value must not appear in the tool call or in any output.\n2. On success, tell the user the credential was stored, echoing the returned `target` and `path`,\n e.g. `Stored routing credential for bapi:<repo_name> at <path>`.\n3. On failure, do NOT block the install — show the rest of the install summary anyway, then tell the\n user the routing credential could not be stored. They can rerun `/install-bridge` after setting\n `BAPI_API_KEY` in the environment, or run\n `npx -y @bridge_gpt/mcp-server credentials migrate-agent-config --write-credentials` to migrate an\n existing key. Until then, `start-tickets` model routing fails open (assumes a hard ticket and\n defaults to premium/Opus when available) — this is the MOST EXPENSIVE model tier, so unexplained\n cost is the symptom of leaving this unfixed. Recommend verifying credential resolution afterwards\n with `npx -y @bridge_gpt/mcp-server doctor`.\n\n## Stage 7 — Summarize the outcome, then present the concise capability report\n\nFirst, begin with an explicit applied count: \"Applied N of M derivable fields\" (M = the unset\nbootstrap fields you derived values for). An install that applied 0 fields must say so loudly — the\ninstall is NOT complete until the apply call reports applied fields. This applied-count line and the\nsix-bucket summary below remain the PRIMARY install result — the capability report that follows is a\nsecondary close, not a replacement for it.\n\nThen summarize the six buckets from the apply response for the user:\n- `applied` — fields written this run.\n- `skipped` — fields already set (left untouched).\n- `conflict` — fields that changed since the manifest was read (re-run /install-bridge to retry).\n- `needs_confirmation` — fields awaiting explicit confirmation (e.g. project_description).\n- `rejected` — fields that failed validation or were not bootstrap-eligible (the other fields still\n applied; fix or drop the rejected values before any retry).\n- `deferred` — fields intentionally not auto-written by install (owned by /learn-repository or set\n deliberately). `selected_mcp_slugs` belongs here: report it as deferred to `/learn-repository`,\n never as approved, declined, or pending an install-time decision.\n\n### Read-after-write: fetch the concise capability report\n\nAfter the bucket summary, call the `get_install_manifest` MCP tool ONCE MORE. This post-apply read\nreflects the configuration you just wrote (the Stage-2 read was pre-apply and is stale for this\npurpose). This read does not need the snapshot token. Use ONLY this post-write response for the\nreport below.\n\nThe response carries `concise_tool_capabilities` — an ADDITIVE, bounded projection over the complete\n`tool_capabilities` catalog (which the response still carries unchanged; this stage simply does not\nrender it). It is a server-ordered array of at most two tiers, each\n`{id, name, tools: [{tool, display_name}], more_count}`, covering only \"Regularly useful\" and\n\"Occasionally useful\", available-now tools only, with everything else in those two tiers collapsed\ninto that tier's `more_count`.\n\nServer authority: the server computed this projection's tier selection, availability filter, and\n`more_count` arithmetic. Never recompute, re-filter, re-count, or re-derive it from `tool_capabilities`,\n`docs/mcp-tool-integrations.md`, or any other documentation — render exactly what the server sent.\n\nIf the post-write response has no `concise_tool_capabilities` field at all, or it is present but\nmalformed (not the `{id, name, tools, more_count}` tier shape described above), print exactly:\n`No capability status is available yet; configuration can still continue.` and skip the section below\nentirely — never fall back to rendering the complete `tool_capabilities` catalog or a remembered/\nhallucinated capability list.\n\nOtherwise, render exactly one section, with this exact heading:\n\n**What Bridge can help with**\n\n- Render each tier from `concise_tool_capabilities` in the server's given order: \"Regularly useful\"\n first, then \"Occasionally useful\". Do not reorder, filter, re-tier, or drop a tier the server\n included, even if its `tools` array is empty.\n- Within a tier, list each tool's `display_name` only, in server order — no description,\n `availability_text`, effect, dependency explanation, or variant detail; those live on the complete\n `tool_capabilities` field, which this section does not touch.\n- Render the tier's `more_count` as plain, muted-style summary text (\"+N more\") — never as an\n expansion prompt, a link, or something requiring further action. Omit the \"+N more\" line entirely\n when `more_count` is `0`.\n- Do not locally filter, count, regroup, infer availability, or fall back to the complete\n `tool_capabilities` collection for this section under any circumstance.\n\n## Stage 8 — Offer the next step\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it); the\nspawn prompt owns the single closing concise-report-plus-learn-recommendation there. On direct manual\n`/install-bridge` invocation, run it normally:\n\n1. Offer to continue with `/learn-repository` to populate the deeper instruction-tier configuration\n (architecture, review, testing, and correctness standards), matching the manifest's `next_step`.\n Mention that it also derives and confirms the applicable MCP validation manuals\n (`selected_mcp_slugs`) — it researches the codebase first, so it can propose them with evidence\n and explain what they do, which is why install leaves that field alone.\n2. Do NOT ask about repository indexing in any form. There is no consent question, no\n `parse_repository` tool call, and no `/parse-repository` continuation here — indexing starts\n automatically once the repository reaches full parse readiness (VCS credentials, the Pinecone\n index, `working_in` / `project_description`, and SFCC prerequisites where applicable), via the\n same readiness-gated funnel the GitHub connection-confirm endpoints and the scheduled sweep already\n use. Do not claim indexing has already started — this command has no visibility into that funnel's\n outcome.\n\n## Stage 9 — Offer CI follow-up configuration (only when CI is detected)\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and learn recommendation the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\nThis stage is separate from the single apply call: it writes at most ONE field via the\n`config_field` MCP tool. `ci_followup_config` is REPLACE-NOT-AUGMENT — leaving it NULL already means\nsafe poll-only defaults, so \"skip\" is always a correct answer.\n\n1. Gate: only offer this when Stage 3 found real CI evidence (e.g. `.github/workflows/*.yml`,\n `bitbucket-pipelines.yml`). With no CI detected, skip this stage and note \"no CI detected — CI\n follow-up not offered\" in the final report.\n2. Ask ONE question, referencing the discovered CI by name, with exactly these preset profiles\n (default: skip):\n - **observe** — poll CI results only, never attempt fixes:\n `{\"strategy\": \"poll_only\", \"max_iterations\": 1, \"max_minutes\": 10, \"instructions\": \"\"}`\n - **self-heal** — bounded fix-and-iterate loop on the automation's own PRs:\n `{\"strategy\": \"fix_and_iterate\", \"max_iterations\": 3, \"max_minutes\": 45, \"instructions\": \"\"}`\n - **skip** (default) — leave `ci_followup_config` unset (NULL = baseline poll-only behavior).\n3. Do NOT offer or compose a `custom` strategy during install — free-form CI follow-up instructions\n are a deliberate later act (setup UI or a direct `config_field` update).\n4. When the human picks a profile, call the `config_field` MCP tool once (operation `\"update\"`,\n `field_name: \"ci_followup_config\"`, `value`: the profile's JSON object). If the server rejects the\n value, retry ONCE with a corrected payload; if it is rejected again, stop, show the proposed JSON\n to the human, and leave the field unset.\n5. Never select a profile in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never enable fix-and-iterate behavior.\n\n## Stage 10 — Offer the speed-vs-quality repository preference\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and learn recommendation the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\nThis stage is separate from the single apply call: it writes at most ONE field via the `config_field`\nMCP tool, `field_name: \"speed_vs_quality\"`. The column defaults to `5` (max quality) for every\nrepository, so \"skip\" always leaves a safe, valid value in place.\n\n1. Never ask this question in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never block on or silently answer this preference.\n2. Read the current value first via the `config_field` MCP tool (operation `\"get\"`,\n `field_name: \"speed_vs_quality\"`) so a reinstall can show the stored value — not always `5` — as\n the displayed default rather than silently re-asking from scratch.\n3. Ask ONE question with exactly these five numbered presets (default: the value from step 2, or `5`\n if this is the first install):\n - **1** — Max speed\n - **2** — Prefer speed\n - **3** — Balanced\n - **4** — Prefer quality\n - **5** — Max quality (default)\n4. Persist ONLY on an explicit answer — including an explicitly accepted default — by calling the\n `config_field` MCP tool once (operation `\"update\"`, `field_name: \"speed_vs_quality\"`,\n `value`: the selected integer 1-5). Do not overwrite an existing value when the human gives no\n answer at all (e.g. the session cannot obtain one) — leave the stored/default value untouched in\n that case, distinct from an explicit accepted-default selection of `5`.\n5. After a successful persist, emit one additive structured log line (mirroring the codebase's\n `logging.info(msg, extra={...})` convention for non-response-body observability signals) with\n fields: `event=\"install.speed_vs_quality\"`, `repo_name`, `field_name=\"speed_vs_quality\"`,\n `selected_preset` (the persisted integer), `outcome=\"persisted\"`. Never log this event before the\n `config_field` tool call has confirmed the write.\n6. When skipped, emit the corresponding structured event with `outcome` set to one of\n `\"skipped_non_interactive\"` (non-interactive session) or `\"skipped_no_answer\"` (interactive session,\n no explicit answer obtained) — omit `selected_preset` and any prompt text from this event.\n7. If the `config_field` call is rejected, retry ONCE with a corrected payload; if it is rejected\n again, stop, show the proposed value to the human, and leave the field at its current stored value.\n Do not log a persistence-success event for a rejected or failed write.\n\n## Return\n\nReport the admin check result, the \"Applied N of M\" count, the\napplied/skipped/conflict/needs_confirmation/rejected field names, any fields omitted for\nnested-repository or ambiguity reasons, the approval outcome for `project_description` — install's\nonly confirmation-requiring field — (approved / declined / pending human input), the fact that\n`selected_mcp_slugs` is deferred to `/learn-repository` rather than decided here, whether a\nstale-command warning was raised (manifest\n`command_contract_version` higher than this command's), whether the routing credential was persisted\n(the returned `target` and `path`, or the non-blocking failure remediation), the \"What Bridge can help\nwith\" concise capability report from the post-apply read-after-write manifest read, the CI follow-up\noutcome (profile written / skipped / no CI detected / pending / skipped in install-spawn context), the\nspeed-vs-quality preference outcome (persisted with its preset / skipped_non_interactive /\nskipped_no_answer / pending / skipped in install-spawn context), and the `/learn-repository`\nrecommendation.\n",
18
- "learn-repository.md": "Learn and document all configuration fields for the repository by running parallel research agents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly -- the recipe determines which tools to call and with what parameters.\n\n1. This command takes no arguments.\n\n2. **Before executing any recipe step**, tell the user what they are about to sit through and why it\n is worth it:\n\n ```\n Learning this repository. This takes a while — the research agents read the actual codebase, and\n all the unlearned fields are researched in parallel, so the wait is roughly the slowest single\n field rather than the sum of all of them. Fields that are already populated are skipped entirely.\n\n What this buys you: these fields are what ground Bridge's agents in THIS codebase. Planning,\n reviewing, and code generation all read them, so they follow your repository's actual\n architecture, testing, documentation, and correctness conventions instead of generic defaults.\n\n It runs unattended — there are no approval prompts during the run. You may be asked one batched\n question at the very end.\n ```\n\n Do not invent a specific number of minutes; the honest statement is the parallel-wait shape above.\n\n3. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"learn-repository\"`\n\n If the tool returns an error, stop and report the failure.\n\n4. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n Retain, for the closing summary: the consolidated research task's structured result (its per-field\n `status`, `character_count`, `condensed`, and `condensation_reason`), each upload step's result,\n and the final confirmation task's structured result. You will need all three — do not discard them\n as you go.\n\n5. After all steps complete, display a summary built from the results you retained:\n\n ```\n ## Learn Complete\n\n **Status**: Success / Completed with gaps / Failed at step N\n\n **Learned and applied**: <fields drafted this run and written to config>\n **Already populated (skipped)**: <fields skipped because they already had a value>\n **Condensed to fit the field limit**: <field — reason it was condensed, per field>\n **Gaps**: <fields whose research or upload failed, each named with its reason>\n **Confirmation**: <approved / applied / declined / pending human input / not applicable, per field>\n\n Review or edit any of these on the **Project Configuration** page, under **Code Writer Settings**\n for the learned instructions and **MCP Validation Manuals** for the manual selection. Bridge's\n agents read whatever is stored there, so correcting a wrong conclusion there changes their\n behavior.\n ```\n\n Rules for the summary:\n\n - A run where some fields failed but others applied is **`Completed with gaps`**, not `Failed`.\n Name every gap explicitly — an unnamed gap is worse than a failed run, because the user believes\n the field was learned.\n - Report confirmation candidates that could not be presented in a headless session with the exact\n phrase `pending human input`.\n - Every field that was condensed must appear with the reason it was condensed.\n\n6. **After** the `## Learn Complete` summary above is fully displayed, close with the same concise\n capability report `/install-bridge` renders (BAPI-658, AC-9). This is the recipe's ONE exception to\n \"do not call MCP tools directly\": call the `get_install_manifest` MCP tool EXACTLY ONCE here,\n directly, with no arguments beyond what it requires — never through the recipe, never a second time,\n and never to apply or change any configuration.\n\n The report is structurally and visually SUBORDINATE to `## Learn Complete` above it — it is a\n closing addendum, not a replacement for or a distraction from the learn summary's own status,\n fields, gaps, and confirmation outcome.\n\n If the `get_install_manifest` call errors, or its response has no `concise_tool_capabilities` field,\n or that field is present but malformed (not the server's `{id, name, tools, more_count}` tier\n shape), print exactly this line and stop — do not attempt the report in any other form:\n\n ```\n capability report unavailable — run /install-bridge to see it\n ```\n\n Never substitute documentation, the complete `tool_capabilities` catalog, a remembered tool list, or\n an inferred capability category for a missing or malformed concise field — a hallucinated report\n during this trust-critical first run is worse than no report at all.\n\n Otherwise, render exactly one section, with this exact heading, from `concise_tool_capabilities`\n only:\n\n **What Bridge can help with**\n\n - Render each tier in the server's given order: \"Regularly useful\" first, then \"Occasionally\n useful\". Do not reorder, filter, re-tier, or drop a tier the server included, even if its `tools`\n array is empty.\n - Within a tier, list each tool's `display_name` only, in server order — no description,\n availability text, effect, dependency explanation, or variant detail.\n - Render the tier's `more_count` as plain, muted-style summary text (\"+N more\") — never as an\n expansion prompt, a link, or something requiring further action (it is not interactive or\n expandable). Omit the \"+N more\" line entirely when `more_count` is `0`.\n - Do not locally filter, count, regroup, infer availability, write configuration, or fall back to\n the complete `tool_capabilities` collection for this section under any circumstance.\n",
17
+ "install-bridge.md": "Bootstrap Bridge API project configuration from the local codebase via the easy-install manifest.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command takes no arguments; any `$ARGUMENTS` text is ignored.\n\nCommand contract version: **6**. The install manifest returns a `command_contract_version`; Stage 2\ncompares it to this number to detect a stale scaffolded copy of this command.\n\nThis command has two modes, chosen by the project's state (Stage 2 decides from the manifest's\n`configured` flag), never by the caller's role:\n\n- **Fresh configuration** (`configured == false`): the full derive → approve → apply → report flow\n below, for an admin or legacy caller. This is the original, unchanged install path.\n- **JOIN MODE** (`configured == true`): the project is already set up, so this run proposes and\n applies ZERO configuration changes for ANY caller. A new teammate — including a non-admin \"member\"\n key — gets a graceful welcome and the concise capability report instead of an error. An eligible\n b2b admin is additionally offered the teammate-invite stage (Stage 11).\n\nThis command performs a one-time \"easy install\" of Bridge API project configuration. It reads the\nserver-owned install manifest once, derives values for the **unset** bootstrap fields from the local\ncodebase, asks for human approval of the project description, applies everything in a single atomic\ncall, and then presents a **concise capability report** derived from a fresh read-after-write manifest\nread. The server owns all skip-if-set, conflict, and confirmation semantics — this command never makes\nits own skip-if-set decisions — and the server owns the complete tool catalog and the bounded concise\nprojection over it, their grouping and ordering, and every gate and dependency relationship; this\ncommand formats the server's contract and never recomputes it from prose. Indexing is never a decision\nthis command makes or asks about: it starts automatically, gated entirely by server-side readiness (see\nStage 8).\n\nThis command is portable across Claude Code, Cursor, and Copilot: it only drives the Bridge API MCP\ntools (`get_my_role`, `get_install_manifest`, `apply_install_manifest`, and — in the gated Stage 11\nonly — `invite_member`).\n\nIf any stage fails, stop immediately and report which stage failed and why.\n\n**Install-spawn context.** When the spawning instruction explicitly says this `/install-bridge` run is\nin the \"install-spawn context\" (it was launched by the `install-bridge` CLI's fresh agent session),\nStage 8, Stage 9, and Stage 10 are SKIPPED and the single closing interaction is the concise capability\nreport plus a `/learn-repository` recommendation that the spawn prompt owns. When you invoke\n`/install-bridge` directly (manual invocation), Stages 8, 9, and 10 run normally. Stage 11 is NOT part\nof that install-spawn skip set — it is independently gated (admin + b2b + interactive) and best-effort,\nso it may still run in the install-spawn context for an eligible admin.\n\n## Stage 1 — Admin preflight (defer the permission decision until the manifest is read)\n\n1. Call the `get_my_role` MCP tool (no parameters). Retain its `role`, `source`, and `customer_type`\n values — later stages branch on all three (Stage 2's mode decision uses `role`/`source`; Stage 11's\n invite gate uses `role` and `customer_type`).\n2. Classify the caller, but do NOT stop here — the member permission decision is DEFERRED until Stage 2\n has read the manifest and determined whether the project is already `configured`. A member must be\n allowed to continue at least far enough to read the manifest, because a member CAN join an\n already-configured project even though a member cannot configure a fresh one:\n - If `source` is `\"legacy\"`, or `role` is `\"admin\"`: the caller is configuration-capable (it may run\n the fresh-configuration flow when the project is unconfigured).\n - Otherwise (a non-admin `user_access` \"member\" key): the caller is join-only. It may proceed into\n JOIN MODE for a configured project, but must be refused if Stage 2 proves the project is not yet\n configured (it cannot configure a fresh repo).\n3. Preserve this exact refusal text for later use — it is emitted in Stage 2 ONLY when a non-admin\n member reaches a `configured == false` project:\n ```\n Admin role required to apply install configuration. Ask a project admin to run /install-bridge,\n or use an admin API key.\n ```\n\n## Stage 2 — Read the manifest (once, pre-apply)\n\n1. Call the `get_install_manifest` MCP tool exactly once here.\n2. Keep the returned `snapshot_token` verbatim — you must pass the SAME token to the apply call in\n Stage 5. Do not call `get_install_manifest` again before applying; a fresh read would invalidate\n the token you are about to use. (Stage 7 performs a SEPARATE, later read-after-write manifest read\n for the current capability status — that is deliberate and does not reuse this token.)\n3. The manifest contains ordered `groups` of bootstrap fields (each with `field_name`, `is_set`,\n `current_value`, `guidance`, `examples`, `validation_summary`, `requires_confirmation`), a list of\n `deferred_fields`, a `next_step`, `done_criteria`, a `command_contract_version`, and the\n `snapshot_token`. It also carries the additive capability fields (`integrations`, `configured`,\n `learned`, `indexed`, `tool_capabilities`, `concise_tool_capabilities`, `locked_tools`,\n `unlocked_tools`) — but ignore those here; the accurate capability status is the post-apply read in\n Stage 7. `tool_capabilities` is the COMPLETE catalog-backed report field (one entry per registered\n MCP tool, grouped and ordered by the server); `concise_tool_capabilities` is the ADDITIVE, bounded\n projection Stage 7 actually renders (see Stage 7); `locked_tools` / `unlocked_tools` are LEGACY\n compatibility data covering only the VCS/index policy cases and are NOT the tool inventory.\n4. Compare the manifest's `command_contract_version` to this command's contract version (6, stated at\n the top of this file). If the manifest's version is HIGHER, this scaffolded command copy is stale:\n warn the user to refresh it by running `npx -y @bridge_gpt/mcp-server --init` in the project root,\n then proceed conservatively — wherever the manifest's `guidance`, `next_step`, or `done_criteria`\n differ from these instructions, follow the manifest.\n5. **Decide the install mode from `configured`.** Read the manifest's `configured` readiness flag (use\n ONLY `configured` for this decision — not `learned` or `indexed`) and branch:\n - **`configured == true` → JOIN MODE, for EVERY caller** (admin, legacy, or member). The project is\n already set up, so this run makes ZERO configuration changes. Emit a concise welcome — for\n example: \"This Bridge project is already configured. You're joining it as a new teammate; no\n configuration changes will be proposed or applied.\" Then SKIP Stages 3, 4, and 5 entirely (no\n field derivation, no project-description approval, no `apply_install_manifest` call, no\n `config_field` writes), run Stage 6 (persist the routing credential), and render the JOIN MODE\n branch of Stage 7 (the concise capability report, drawn directly from THIS Stage-2 manifest — no\n read-after-write). Then SKIP Stages 8, 9, and 10 for every caller. A member STOPS after the Stage 7\n report; only an eligible admin continues to Stage 11.\n - **`configured == false` → apply the deferred Stage 1 role decision:**\n - `source == \"legacy\"` or `role == \"admin\"`: run the fresh-configuration flow (Stages 3 → 4 → 5 →\n 6 → 7 → 8 → 9 → 10) exactly as written, unchanged.\n - a non-admin `user_access` \"member\" key: stop immediately and display the exact refusal text\n preserved in Stage 1 (\"Admin role required to apply install configuration…\"). Do not derive,\n apply, or persist anything.\n - **`configured` absent / indeterminate (neither `true` nor `false`) → do NOT treat it as `false`.**\n `configured` comes from a best-effort capability enrichment that can silently omit the key on a\n transient server-side probe failure, so a missing value is \"unknown\", not \"unconfigured\". Re-read\n the manifest ONCE (a fresh `get_install_manifest` call) to try to resolve it, and branch on the\n refreshed value if it is now definitive. If it is STILL absent:\n - `source == \"legacy\"` or `role == \"admin\"`: proceed with the fresh-configuration flow, but NOT\n silently — first tell the user that configuration status could not be confirmed and that the run\n will attempt configuration anyway (the server owns skip-if-set, so an apply against an\n already-configured repo is a safe no-op).\n - a non-admin `user_access` \"member\" key: take the JOIN-MODE-safe path — render the welcome and the\n Stage 7 capability report (no config writes, no offers) and note that configuration status could\n not be confirmed. Do NOT emit the hard \"Admin role required\" STOP: that refusal is reserved for a\n *definitive* `configured == false`, because treating an unknown state as unconfigured would\n re-introduce the very member hard-refusal this flow removes.\n\n## Stage 3 — Derive values for UNSET bootstrap fields only\n\n**Skip this entire stage in JOIN MODE** (Stage 2 selected JOIN MODE because the manifest reported\n`configured == true`). JOIN MODE derives nothing — it proposes and applies zero configuration for every\ncaller. Run this stage only on the `configured == false` fresh-configuration path.\n\n1. Consider ONLY fields whose `is_set` is `false`. Never re-derive or overwrite a field that is\n already set — the server will also skip already-set fields, but you should not even propose them.\n2. For each unset field, derive a value from the local codebase following that field's `guidance`\n (e.g. infer `working_in` from frameworks/manifests, `version_control_system` from the git remote,\n testing stacks from test config and dependencies, directory fields from the repo layout).\n3. Omit any field you are uncertain about or that does not apply — leaving it unset is always\n acceptable. Do NOT guess.\n4. Specifically, do NOT invent a `version` when the platform has no meaningful version concept; leave\n it unset.\n5. Before deriving `version_control_system` or `base_branch`, confirm the git repository root is THIS\n project's root: `git rev-parse --show-toplevel` must resolve to the project directory itself. If\n the git root is an ancestor directory (the project is nested inside another repository), OMIT both\n fields and note why in the final report — deriving them would describe the parent repository, not\n this project.\n6. If you find real evidence for TWO OR MORE plausible values for a field (e.g. configs for multiple\n test frameworks, multiple frameworks in a monorepo), treat the value as ambiguous and omit it\n rather than picking one.\n7. Do NOT derive `selected_mcp_slugs`, even though it appears as an unset bootstrap-eligible field in\n the manifest. MCP validation manual selection is deferred to `/learn-repository`, which derives and\n confirms it with the codebase already researched. Install neither proposes nor applies this field.\n\n## Stage 4 — Human approval for confirmation-requiring fields\n\n**Skip this entire stage in JOIN MODE** — there is nothing to derive, so there is nothing to approve.\nRun it only on the `configured == false` fresh-configuration path.\n\n`project_description` is the ONLY confirmation-requiring field install proposes. It carries\n`requires_confirmation: true` in the manifest, so it is never applied on derivation alone — it needs\nexplicit human approval. (`selected_mcp_slugs` also requires confirmation, but install does not\nderive it at all; `/learn-repository` asks for it. See Stage 3 step 7.)\n\n1. If `project_description` is unset and you can draft a concise description from the codebase,\n present the proposed `project_description` text to the human and ask for explicit approval before\n including it.\n2. Include `project_description` in the apply payload ONLY as\n `{ \"value\": <approved value>, \"confirmed\": true }`, and only after the human approves it. If the\n human does not approve it, omit the field entirely.\n3. If no human response can be obtained (e.g. a non-interactive / headless session), do NOT stall and\n do NOT abandon the install: proceed to Stage 5 with `project_description` omitted, and report it\n as \"pending human input\" in the final summary. The other derived fields must still be applied — an\n unapproved description never blocks them.\n\n## Stage 5 — Apply (one call)\n\n**Skip this entire stage in JOIN MODE** — JOIN MODE makes NO `apply_install_manifest` call and writes\nzero fields for every caller. Run it only on the `configured == false` fresh-configuration path.\n\n1. Make exactly ONE call to the `apply_install_manifest` MCP tool, passing:\n - `snapshot_token`: the exact token from Stage 2.\n - `fields`: a map of the derived fields. Scalar fields may be passed directly\n (e.g. `\"base_branch\": \"main\"`); an approved `project_description` must use the\n `{ \"value\": ..., \"confirmed\": true }` object form from Stage 4. Never include\n `selected_mcp_slugs` in this payload — install does not derive or apply it (Stage 3 step 7).\n2. Do not implement any client-side skip-if-set, conflict, or confirmation logic — the server owns\n all of that and returns the outcome buckets.\n3. The apply is partial-tolerant: fields that fail server-side validation are returned in the\n `rejected` bucket while the valid fields still commit. A rejected field is therefore reported,\n not fatal — do NOT retry the whole apply just because one field was rejected.\n\n## Stage 6 — Persist the routing credential\n\n**This stage runs in BOTH modes** — JOIN MODE persists the routing credential too, so a joining\nteammate's shell-spawned CLI features (`start-tickets`) can resolve the key. Its fail-open behavior\nbelow is unchanged in either mode.\n\nThe Bash-spawned `start-tickets` CLI runs in a DIFFERENT runtime surface than this MCP server, so a\nkey that lives only in `.mcp.json` / `.cursor/mcp.json` is invisible to it and difficulty→model\nrouting silently degrades. This final stage persists the already-validated key into the user-scoped\ncredential store (`~/.config/bridge/credentials.json`) so shell-spawned CLI commands can resolve it.\n\n1. Call the `persist_routing_credential` MCP tool with `repo_name` set to the repository name for\n this install (the configured `BAPI_REPO_NAME`). Pass `repo_name` ONLY — this tool resolves the\n API key inside the MCP server process. NEVER pass or display `BAPI_API_KEY` (nor `api_key`,\n `apiKey`, `secret`, or `token`); the key value must not appear in the tool call or in any output.\n2. On success, tell the user the credential was stored, echoing the returned `target` and `path`,\n e.g. `Stored routing credential for bapi:<repo_name> at <path>`.\n3. On failure, do NOT block the install — show the rest of the install summary anyway, then tell the\n user the routing credential could not be stored. They can rerun `/install-bridge` after setting\n `BAPI_API_KEY` in the environment, or run\n `npx -y @bridge_gpt/mcp-server credentials migrate-agent-config --write-credentials` to migrate an\n existing key. Until then, `start-tickets` model routing fails open (assumes a hard ticket and\n defaults to premium/Opus when available) — this is the MOST EXPENSIVE model tier, so unexplained\n cost is the symptom of leaving this unfixed. Recommend verifying credential resolution afterwards\n with `npx -y @bridge_gpt/mcp-server doctor`.\n\n## Stage 7 — Summarize the outcome, then present the concise capability report\n\n**JOIN MODE branch (`configured == true`).** Do NOT print an applied count and do NOT fabricate apply\nbuckets — no apply happened. Instead state plainly that the project was already configured and that\nzero configuration changes were proposed or applied (the welcome from Stage 2). Then render the concise\ncapability report described in \"### Read-after-write\" below, with ONE difference: source it directly\nfrom the `concise_tool_capabilities` field of the Stage-2 manifest you already read — do NOT perform a\nread-after-write `get_install_manifest` call, because no write occurred and there is nothing to\nrefresh. Apply the same server-authority rendering rules (server order, `more_count` handling,\nmalformed/missing fallback) verbatim. After the report, a member is DONE; an eligible admin proceeds to\nStage 11. The rest of this stage (the applied-count line and six-bucket summary) applies ONLY to the\n`configured == false` fresh-configuration path.\n\n**Fresh-configuration branch (`configured == false`).**\nFirst, begin with an explicit applied count: \"Applied N of M derivable fields\" (M = the unset\nbootstrap fields you derived values for). An install that applied 0 fields must say so loudly — the\ninstall is NOT complete until the apply call reports applied fields. This applied-count line and the\nsix-bucket summary below remain the PRIMARY install result — the capability report that follows is a\nsecondary close, not a replacement for it.\n\nThen summarize the six buckets from the apply response for the user:\n- `applied` — fields written this run.\n- `skipped` — fields already set (left untouched).\n- `conflict` — fields that changed since the manifest was read (re-run /install-bridge to retry).\n- `needs_confirmation` — fields awaiting explicit confirmation (e.g. project_description).\n- `rejected` — fields that failed validation or were not bootstrap-eligible (the other fields still\n applied; fix or drop the rejected values before any retry).\n- `deferred` — fields intentionally not auto-written by install (owned by /learn-repository or set\n deliberately). `selected_mcp_slugs` belongs here: report it as deferred to `/learn-repository`,\n never as approved, declined, or pending an install-time decision.\n\n### Read-after-write: fetch the concise capability report\n\nAfter the bucket summary, call the `get_install_manifest` MCP tool ONCE MORE. This post-apply read\nreflects the configuration you just wrote (the Stage-2 read was pre-apply and is stale for this\npurpose). This read does not need the snapshot token. Use ONLY this post-write response for the\nreport below.\n\nThe response carries `concise_tool_capabilities` — an ADDITIVE, bounded projection over the complete\n`tool_capabilities` catalog (which the response still carries unchanged; this stage simply does not\nrender it). It is a server-ordered array of at most two tiers, each\n`{id, name, tools: [{tool, display_name}], more_count}`, covering only \"Regularly useful\" and\n\"Occasionally useful\", available-now tools only, with everything else in those two tiers collapsed\ninto that tier's `more_count`.\n\nServer authority: the server computed this projection's tier selection, availability filter, and\n`more_count` arithmetic. Never recompute, re-filter, re-count, or re-derive it from `tool_capabilities`,\n`docs/mcp-tool-integrations.md`, or any other documentation — render exactly what the server sent.\n\nIf the post-write response has no `concise_tool_capabilities` field at all, or it is present but\nmalformed (not the `{id, name, tools, more_count}` tier shape described above), print exactly:\n`No capability status is available yet; configuration can still continue.` and skip the section below\nentirely — never fall back to rendering the complete `tool_capabilities` catalog or a remembered/\nhallucinated capability list.\n\nOtherwise, render exactly one section, with this exact heading:\n\n**What Bridge can help with**\n\n- Render each tier from `concise_tool_capabilities` in the server's given order: \"Regularly useful\"\n first, then \"Occasionally useful\". Do not reorder, filter, re-tier, or drop a tier the server\n included, even if its `tools` array is empty.\n- Within a tier, list each tool's `display_name` only, in server order — no description,\n `availability_text`, effect, dependency explanation, or variant detail; those live on the complete\n `tool_capabilities` field, which this section does not touch.\n- Render the tier's `more_count` as plain, muted-style summary text (\"+N more\") — never as an\n expansion prompt, a link, or something requiring further action. Omit the \"+N more\" line entirely\n when `more_count` is `0`.\n- Do not locally filter, count, regroup, infer availability, or fall back to the complete\n `tool_capabilities` collection for this section under any circumstance.\n\n## Stage 8 — Offer the next step\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it); the\nspawn prompt owns the single closing concise-report-plus-learn-recommendation there. On direct manual\n`/install-bridge` invocation, run it normally:\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\n1. Offer to continue with `/learn-repository` to populate the deeper instruction-tier configuration\n (architecture, review, testing, and correctness standards), matching the manifest's `next_step`.\n Mention that it also derives and confirms the applicable MCP validation manuals\n (`selected_mcp_slugs`) — it researches the codebase first, so it can propose them with evidence\n and explain what they do, which is why install leaves that field alone.\n2. Do NOT ask about repository indexing in any form. There is no consent question, no\n `parse_repository` tool call, and no `/parse-repository` continuation here — indexing starts\n automatically once the repository reaches full parse readiness (VCS credentials, the Pinecone\n index, `working_in` / `project_description`, and SFCC prerequisites where applicable), via the\n same readiness-gated funnel the GitHub connection-confirm endpoints and the scheduled sweep already\n use. Do not claim indexing has already started — this command has no visibility into that funnel's\n outcome.\n\n## Stage 9 — Offer CI follow-up configuration (only when CI is detected)\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and learn recommendation the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\nThis stage is separate from the single apply call: it writes at most ONE field via the\n`config_field` MCP tool. `ci_followup_config` is REPLACE-NOT-AUGMENT — leaving it NULL already means\nsafe poll-only defaults, so \"skip\" is always a correct answer.\n\n1. Gate: only offer this when Stage 3 found real CI evidence (e.g. `.github/workflows/*.yml`,\n `bitbucket-pipelines.yml`). With no CI detected, skip this stage and note \"no CI detected — CI\n follow-up not offered\" in the final report.\n2. Ask ONE question, referencing the discovered CI by name, with exactly these preset profiles\n (default: skip):\n - **observe** — poll CI results only, never attempt fixes:\n `{\"strategy\": \"poll_only\", \"max_iterations\": 1, \"max_minutes\": 10, \"instructions\": \"\"}`\n - **self-heal** — bounded fix-and-iterate loop on the automation's own PRs:\n `{\"strategy\": \"fix_and_iterate\", \"max_iterations\": 3, \"max_minutes\": 45, \"instructions\": \"\"}`\n - **skip** (default) — leave `ci_followup_config` unset (NULL = baseline poll-only behavior).\n3. Do NOT offer or compose a `custom` strategy during install — free-form CI follow-up instructions\n are a deliberate later act (setup UI or a direct `config_field` update).\n4. When the human picks a profile, call the `config_field` MCP tool once (operation `\"update\"`,\n `field_name: \"ci_followup_config\"`, `value`: the profile's JSON object). If the server rejects the\n value, retry ONCE with a corrected payload; if it is rejected again, stop, show the proposed JSON\n to the human, and leave the field unset.\n5. Never select a profile in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never enable fix-and-iterate behavior.\n\n## Stage 10 — Offer the speed-vs-quality repository preference\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and learn recommendation the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\nThis stage is separate from the single apply call: it writes at most ONE field via the `config_field`\nMCP tool, `field_name: \"speed_vs_quality\"`. The column defaults to `5` (max quality) for every\nrepository, so \"skip\" always leaves a safe, valid value in place.\n\n1. Never ask this question in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never block on or silently answer this preference.\n2. Read the current value first via the `config_field` MCP tool (operation `\"get\"`,\n `field_name: \"speed_vs_quality\"`) so a reinstall can show the stored value — not always `5` — as\n the displayed default rather than silently re-asking from scratch.\n3. Ask ONE question with exactly these five numbered presets (default: the value from step 2, or `5`\n if this is the first install):\n - **1** — Max speed\n - **2** — Prefer speed\n - **3** — Balanced\n - **4** — Prefer quality\n - **5** — Max quality (default)\n4. Persist ONLY on an explicit answer — including an explicitly accepted default — by calling the\n `config_field` MCP tool once (operation `\"update\"`, `field_name: \"speed_vs_quality\"`,\n `value`: the selected integer 1-5). Do not overwrite an existing value when the human gives no\n answer at all (e.g. the session cannot obtain one) — leave the stored/default value untouched in\n that case, distinct from an explicit accepted-default selection of `5`.\n5. After a successful persist, emit one additive structured log line (mirroring the codebase's\n `logging.info(msg, extra={...})` convention for non-response-body observability signals) with\n fields: `event=\"install.speed_vs_quality\"`, `repo_name`, `field_name=\"speed_vs_quality\"`,\n `selected_preset` (the persisted integer), `outcome=\"persisted\"`. Never log this event before the\n `config_field` tool call has confirmed the write.\n6. When skipped, emit the corresponding structured event with `outcome` set to one of\n `\"skipped_non_interactive\"` (non-interactive session) or `\"skipped_no_answer\"` (interactive session,\n no explicit answer obtained) — omit `selected_preset` and any prompt text from this event.\n7. If the `config_field` call is rejected, retry ONCE with a corrected payload; if it is rejected\n again, stop, show the proposed value to the human, and leave the field at its current stored value.\n Do not log a persistence-success event for a rejected or failed write.\n\n## Stage 11 — Invite teammates (gated: b2b admins only; best-effort)\n\nThis is a best-effort final stage that lets an eligible admin mint teammate keys after configuration or\nJOIN MODE. It is **independently gated** and is NOT part of the install-spawn skip set (Stages 8–10) —\nit may run in the install-spawn context for an eligible admin. The entire stage is **fail-open**: a\nprompt failure, a declined offer, a non-interactive context, a malformed tool response, or an\n`invite_member` failure must NEVER cause this command to report the (already-completed) install as\nfailed.\n\n1. **Eligibility gate (AND).** Offer this stage ONLY when BOTH hold, using the values retained in\n Stage 1:\n - `role == \"admin\"`, AND\n - `customer_type == \"b2b\"`.\n Otherwise skip the stage silently with NO prompt: a member, a legacy-source caller whose role is not\n explicitly `\"admin\"`, and a b2c admin all skip. Reachable from BOTH the fresh-admin close (after\n Stage 10) and the JOIN MODE admin path (after the Stage 7 report), including an admin re-run against\n an already-configured b2b project.\n2. **Interactive surface required.** This stage needs a human response. If no interactive response can\n be obtained (a non-TTY / headless / spawn context that cannot prompt), skip the stage silently\n without changing the completed install result — do not stall.\n3. **Offer prompt.** Ask exactly: `Invite teammates to this project? (y/N)`. Treat a blank answer, `n`,\n `no`, an unavailable response, or any prompt failure as a non-fatal decline — skip the rest of the\n stage and report it as declined.\n4. **Collect invitees.** On an affirmative answer, collect one or more teammate email entries using\n normal **echoed** input (email is PII, not a secret — never use a muted/hidden secret prompt).\n Optionally collect a display name per entry.\n5. **Per-invite role.** Default each invitation to role `member`. Only set a specific request's role to\n `admin` after an explicit per-invite opt-up for that entry; never opt up by default.\n6. **Mint.** For each invitee, call the `invite_member` MCP tool exactly once with `{email, name?,\n role}`. Do NOT pass `repo_name` — the tool resolves the repository from the current session.\n7. **Show each key once.** After each successful call, display that response's plaintext `api_key`\n exactly once, associated with its intended recipient, followed by the exact warning:\n `Distribute securely; this key is shown once.` Do NOT repeat a minted key anywhere else — not in the\n final summary, not in retry guidance, not in diagnostics, not in a later stage.\n8. **Per-invite failure isolation.** Treat each mint failure as local to that invitee: report a\n sanitized failure for it, continue to any remaining invitees, and never change the already-completed\n install outcome. Do not surface raw error text, headers, or the caller's key.\n\n## Return\n\nThe Return contract depends on which mode Stage 2 selected.\n\n**Fresh-configuration return (`configured == false` admin/legacy path).**\nReport the admin check result, the \"Applied N of M\" count, the\napplied/skipped/conflict/needs_confirmation/rejected field names, any fields omitted for\nnested-repository or ambiguity reasons, the approval outcome for `project_description` — install's\nonly confirmation-requiring field — (approved / declined / pending human input), the fact that\n`selected_mcp_slugs` is deferred to `/learn-repository` rather than decided here, whether a\nstale-command warning was raised (manifest\n`command_contract_version` higher than this command's), whether the routing credential was persisted\n(the returned `target` and `path`, or the non-blocking failure remediation), the \"What Bridge can help\nwith\" concise capability report from the post-apply read-after-write manifest read, the CI follow-up\noutcome (profile written / skipped / no CI detected / pending / skipped in install-spawn context), the\nspeed-vs-quality preference outcome (persisted with its preset / skipped_non_interactive /\nskipped_no_answer / pending / skipped in install-spawn context), and the `/learn-repository`\nrecommendation.\n\n**JOIN MODE return (`configured == true` path).**\nReport the caller's role, the \"you're joining an already-configured project\" welcome and the explicit\nno-change status (zero configuration proposed or applied — do NOT report an applied count or apply\nbuckets), whether the routing credential was persisted (the returned `target` and `path`, or the\nnon-blocking failure remediation), and the \"What Bridge can help with\" concise capability report drawn\nfrom the Stage-2 manifest (no read-after-write). A member ends here.\n\n**Teammate-invitation outcome (Stage 11, both modes).**\nReport the Stage 11 outcome as counts/statuses only — one of offered, declined, skipped (not eligible,\nor non-interactive context), partially completed, or completed, plus how many keys were minted. Never\nrepeat teammate email addresses or minted key values in this summary.\n",
18
+ "learn-repository.md": "Learn and document all configuration fields for the repository by running parallel research agents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly -- the recipe determines which tools to call and with what parameters. There are exactly two narrow exceptions, both invoked directly by this command and never through the recipe: the `get_my_role` admin preflight at entry (immediately below) and the closing `get_install_manifest` capability report (step 6).\n\n## Admin preflight (UX guard — run this first)\n\nBefore the onboarding guidance below and before fetching the recipe, call the `get_my_role` MCP tool\nonce (the first of the two narrow exceptions above). Retain its `role` and `source`:\n\n- If `source` is `\"legacy\"`, or `role` is `\"admin\"`: continue to the guidance and recipe below.\n- Otherwise (any non-admin `user_access` result — e.g. a \"member\" key): stop immediately, run nothing\n else (no recipe fetch, no research, no configuration write), and display exactly one concise message:\n ```\n Admin role required to learn this repository. Learning writes shared Bridge project configuration,\n which only an admin may change. Ask a project admin to run /learn-repository, or use an admin API key.\n ```\n- If the `get_my_role` call fails or returns a malformed / unrecognized response, treat it as a\n preflight failure: stop with the same admin-required message rather than proceeding into\n configuration writes.\n\nThis preflight is a UX guard ONLY — it fails fast with one clear message instead of the cascade of\nper-field denials a non-admin would otherwise hit. It is NOT the security control: the authoritative\nenforcement is the existing server-side admin gate on the `config_field` update and\n`apply_install_manifest` routes, which already reject non-admin keys regardless of this client-side\ncheck.\n\n1. This command takes no arguments.\n\n2. **Before executing any recipe step**, tell the user what they are about to sit through and why it\n is worth it:\n\n ```\n Learning this repository. This takes a while — the research agents read the actual codebase, and\n all the unlearned fields are researched in parallel, so the wait is roughly the slowest single\n field rather than the sum of all of them. Fields that are already populated are skipped entirely.\n\n What this buys you: these fields are what ground Bridge's agents in THIS codebase. Planning,\n reviewing, and code generation all read them, so they follow your repository's actual\n architecture, testing, documentation, and correctness conventions instead of generic defaults.\n\n It runs unattended — there are no approval prompts during the run. You may be asked one batched\n question at the very end.\n ```\n\n Do not invent a specific number of minutes; the honest statement is the parallel-wait shape above.\n\n3. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"learn-repository\"`\n\n If the tool returns an error, stop and report the failure.\n\n4. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n Retain, for the closing summary: the consolidated research task's structured result (its per-field\n `status`, `character_count`, `condensed`, and `condensation_reason`), each upload step's result,\n and the final confirmation task's structured result. You will need all three — do not discard them\n as you go.\n\n5. After all steps complete, display a summary built from the results you retained:\n\n ```\n ## Learn Complete\n\n **Status**: Success / Completed with gaps / Failed at step N\n\n **Learned and applied**: <fields drafted this run and written to config>\n **Already populated (skipped)**: <fields skipped because they already had a value>\n **Condensed to fit the field limit**: <field — reason it was condensed, per field>\n **Gaps**: <fields whose research or upload failed, each named with its reason>\n **Confirmation**: <approved / applied / declined / pending human input / not applicable, per field>\n\n Review or edit any of these on the **Project Configuration** page, under **Code Writer Settings**\n for the learned instructions and **MCP Validation Manuals** for the manual selection. Bridge's\n agents read whatever is stored there, so correcting a wrong conclusion there changes their\n behavior.\n ```\n\n Rules for the summary:\n\n - A run where some fields failed but others applied is **`Completed with gaps`**, not `Failed`.\n Name every gap explicitly — an unnamed gap is worse than a failed run, because the user believes\n the field was learned.\n - Report confirmation candidates that could not be presented in a headless session with the exact\n phrase `pending human input`.\n - Every field that was condensed must appear with the reason it was condensed.\n\n6. **After** the `## Learn Complete` summary above is fully displayed, close with the same concise\n capability report `/install-bridge` renders (BAPI-658, AC-9). This is the recipe's ONE exception to\n \"do not call MCP tools directly\": call the `get_install_manifest` MCP tool EXACTLY ONCE here,\n directly, with no arguments beyond what it requires — never through the recipe, never a second time,\n and never to apply or change any configuration.\n\n The report is structurally and visually SUBORDINATE to `## Learn Complete` above it — it is a\n closing addendum, not a replacement for or a distraction from the learn summary's own status,\n fields, gaps, and confirmation outcome.\n\n If the `get_install_manifest` call errors, or its response has no `concise_tool_capabilities` field,\n or that field is present but malformed (not the server's `{id, name, tools, more_count}` tier\n shape), print exactly this line and stop — do not attempt the report in any other form:\n\n ```\n capability report unavailable — run /install-bridge to see it\n ```\n\n Never substitute documentation, the complete `tool_capabilities` catalog, a remembered tool list, or\n an inferred capability category for a missing or malformed concise field — a hallucinated report\n during this trust-critical first run is worse than no report at all.\n\n Otherwise, render exactly one section, with this exact heading, from `concise_tool_capabilities`\n only:\n\n **What Bridge can help with**\n\n - Render each tier in the server's given order: \"Regularly useful\" first, then \"Occasionally\n useful\". Do not reorder, filter, re-tier, or drop a tier the server included, even if its `tools`\n array is empty.\n - Within a tier, list each tool's `display_name` only, in server order — no description,\n availability text, effect, dependency explanation, or variant detail.\n - Render the tier's `more_count` as plain, muted-style summary text (\"+N more\") — never as an\n expansion prompt, a link, or something requiring further action (it is not interactive or\n expandable). Omit the \"+N more\" line entirely when `more_count` is `0`.\n - Do not locally filter, count, regroup, infer availability, write configuration, or fall back to\n the complete `tool_capabilities` collection for this section under any circumstance.\n",
19
19
  "parse-repository.md": "Queue a background job to parse and index the repository for Bridge API's AI agents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nExecute all steps in this command as a simple linear sequence of MCP tool calls.\n\n## Step 1 — Parse Arguments\n\nParse `$ARGUMENTS` for an optional `directory_path` argument (a subdirectory path to scope the parse to, e.g., `src/python`). If no argument is provided, the entire repository will be parsed. If `$ARGUMENTS` is provided but invalid (e.g., contains special characters that suggest it's not a path), report an error.\n\n## Step 2 — Queue Parse Job\n\nCall the `parse_repository` MCP tool with:\n- `directory_path`: set to the parsed `directory_path` from Step 1 if provided, otherwise omit the parameter\n\nIf the response indicates parsing is already in progress, display:\n\n```\nRepository parsing is already in progress. A previous parse job has not yet completed.\n\nRun `/check-parse-status` to monitor progress, or wait a few minutes and try again.\n```\n\nStop and do not proceed to the summary.\n\nIf the call fails or returns an error, stop immediately and display:\n\n```\nFailed to queue parse job: <error message from the tool>\n```\n\n## Summary\n\nOn successful queuing, display:\n\n```\nRepository parse job queued successfully.\n\nScope: <entire repository or directory_path if provided>\n\nProcessing typically takes several minutes for large repositories.\nRun `/check-parse-status` to monitor progress.\n```\n\nAfter the parse completes, AI-generated plans and clarifying questions will reflect the latest code changes.\n",
20
20
  "plan-epic.md": "Plan an epic by decomposing it into sub-tasks with structured exploration documents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly -- the recipe determines which tools to call and with what parameters.\n\n## Stage 0 — Setup\n\n1. **Parse arguments**: Extract the input from `$ARGUMENTS`. Trim any surrounding whitespace. If the input is empty or whitespace-only, stop immediately and display:\n ```\n Usage: /plan-epic <description of the epic or Jira key>\n ```\n\n2. **Jira key detection**: If the input matches a Jira key pattern (`[A-Z]+-\\d+`), call the `get_ticket` MCP tool with that key to fetch the epic description. Use the ticket's description as the `epic_description`, and set `epic_key` to that Jira key. If the input does not match a Jira key, use the free-form text directly as the `epic_description` and set `epic_key` to an empty string `\"\"` (there is no Jira epic to update). The recipe uses `epic_key` to decide whether to post the goals/NFRs + recommended implementation order as a comment on the epic.\n\n3. **Generate slug**: Create a kebab-case slug from the epic description — take the first 6-8 meaningful words, strip non-alphanumeric characters (except hyphens), lowercase, and truncate to 60 characters. This becomes the `epic_slug`.\n\n4. **Directory existence check**: Call the `get_docs_dir` MCP tool (no parameters) to get the docs directory path. Then run a terminal command to check if the directory `{docs_dir}/epic-plans/{epic_slug}` already exists:\n ```\n test -d {docs_dir}/epic-plans/{epic_slug} && echo \"exists\" || echo \"not_found\"\n ```\n If the directory exists, append `-{unix_timestamp}` to the `epic_slug` (e.g., `add-auth-provider-support-1710000000`).\n\n## Stage 1 — Execution\n\n5. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"plan-epic\"`\n - `variables`: `{ \"epic_description\": \"<resolved_description>\", \"epic_slug\": \"<slug>\", \"epic_key\": \"<jira_key_or_empty_string>\" }`\n\n Note: Do NOT pass `docs_dir` in variables — it is auto-injected by the pipeline system.\n\n If the tool returns an error, stop and report the failure.\n\n6. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n7. After all steps complete, display a summary:\n ```\n ## Pipeline Complete\n\n **Epic**: <first 80 characters of epic_description>...\n **Slug**: <epic_slug>\n **Output**: <docs_dir>/epic-plans/<epic_slug>/overview.md\n **Steps executed**: N of M\n **Status**: Success / Failed at step N\n ```\n",
21
21
  "plan-ticket.md": "Generate an implementation plan for a Jira ticket, wait for the result, and save it locally.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nExecute all steps in this command as a simple linear sequence of MCP tool calls.\n\n## Step 1 — Parse Arguments\n\n1. **Parse `$ARGUMENTS`**: Extract a required `ticket_key`, an optional `--second-opinion` flag, and an optional `--provider` flag.\n - Split `$ARGUMENTS` on whitespace.\n - If `--second-opinion` appears followed by a provider name (one of `openai`, `anthropic`, `gemini`), capture that provider as `second_opinion_value`.\n - If `--second-opinion` appears without a provider name following it (or is the last token), set `second_opinion_value = \"auto\"`.\n - If `--second-opinion` is absent, set `second_opinion_value = null`.\n - If `--provider` appears followed by a provider name (one of `openai`, `anthropic`, `gemini`), capture that provider as `provider_value`.\n - If `--provider` appears without a valid provider name following it (or is the last token), stop immediately and report: \"Usage error: --provider requires a provider name (openai, anthropic, or gemini).\"\n - If `--provider` is absent, set `provider_value = null`.\n - If both `--second-opinion` and `--provider` are present, `--second-opinion` takes precedence (set `provider_value = null`).\n - The remaining token (after removing flags and their arguments) is the `ticket_key`.\n - If `ticket_key` is empty or missing, stop immediately and display:\n\n ```\n Usage: /plan-ticket <ticket_key> [--second-opinion [provider]] [--provider <name>] (e.g., /plan-ticket BAPI-150)\n ```\n\n## Step 2 — Resolve Docs Directory\n\nCall the `get_docs_dir` MCP tool (no parameters). Store the returned path as `docs_dir`.\n\n## Step 3 — Generate Plan\n\nCall the `request_plan_generation` MCP tool with:\n- `ticket_number`: the parsed `ticket_key`\n- `wait_for_result`: `true`\n- `save_locally`: `true`\n- `second_opinion`: set to `second_opinion_value` if non-null; omit entirely if null\n- `provider`: set to `provider_value` if non-null; omit entirely if null\n\nThis step may take 1-5 minutes while the backend processes the plan.\n\nIf the tool returns an error, stop immediately and display:\n\n```\nPlan generation failed: <error message from the tool>\n```\n\n## Step 4 — Confirm Success\n\nDisplay a confirmation message:\n\n```\nPlan generated successfully for <ticket_key>\nSaved to: {docs_dir}/plans/<ticket_key>-plan.md\n```\n\n## Final Summary\n\nDisplay a summary block:\n\n```\n## Plan Generation Report\n\n- **Ticket**: <ticket_key>\n- **Plan Status**: Generated successfully\n- **Local File**: {docs_dir}/plans/<ticket_key>-plan.md\n```\n\nOn failure at any step, stop immediately, display which step failed and the error details, and do not proceed.\n",
@@ -123,7 +123,7 @@ ${stderr}`.matchAll(/^job\s+(\d+)\s+at\b/gim)];return matches.length>0?matches[m
123
123
  `);lines.push(["ID","COMMAND","RUN_AT","BACKEND","AGENT","NATIVE","LATEST","UNIT_PATH"].join(" "));for(let e of report.entries)lines.push([e.metadata.id,scheduleCommandLabel(e.metadata),e.metadata.run_at_iso,e.metadata.backend,e.metadata.agent,e.status,latestRunStatus(e.metadata)||"-",e.metadata.unit_path??"-"].join(" "));return lines.join(`
124
124
  `)}async function orchestrateScheduleCancel(options,deps){let metadata=await readScheduleMetadata(options.id,deps.homeDir,deps.platform);if(!metadata)return{ok:!1,notFound:!0,error:`No schedule found with id '${options.id}'.`};if(options.agent!==void 0&&metadata.agent!==options.agent)return{ok:!1,notFound:!0,error:`Schedule '${options.id}' does not match agent filter '${options.agent}'.`};if(options.backend!==void 0&&metadata.backend!==options.backend)return{ok:!1,notFound:!0,error:`Schedule '${options.id}' does not match backend filter '${options.backend}'.`};let backend=getSchedulerBackendByName(metadata.backend);if(!backend)return{ok:!1,error:`Unknown backend '${metadata.backend}' recorded for '${options.id}'.`};let cancelResult=await backend.cancel({deps,metadata});if(!cancelResult.ok)return{ok:!1,error:cancelResult.error??"Backend cancel failed."};let canceledAtIso=new Date(deps.now?deps.now():Date.now()).toISOString();return await appendScheduleRunEvent(options.id,{status:"canceled",at:canceledAtIso},deps.homeDir,deps.platform).catch(()=>{}),await deleteScheduleMetadata(options.id,deps.homeDir,deps.platform),{ok:!0,id:options.id,backend:metadata.backend,nativeRemoved:cancelResult.nativeRemoved,stale:cancelResult.stale,metadataRemoved:!0}}function formatScheduleCancelResult(result){return result.ok?[`Schedule '${result.id}' canceled.`,` backend: ${result.backend}`,` native removed: ${result.nativeRemoved?"yes":`no${result.stale?" (stale)":""}`}`,` metadata removed: ${result.metadataRemoved?"yes":"no"}`," logs: preserved"].join(`
125
125
  `):`Error: ${result.error}`}async function orchestrateScheduleDoctor(deps){let platformResult=getSchedulerBackendsForPlatform(deps.platform),envPath=deps.env.PATH??deps.env.Path??"",claudeResolved=!!await resolveCommandOnPath("claude",envPath,deps),cursorResolved=!!await resolveCommandOnPath("cursor-agent",envPath,deps),npxResolved=!!await resolveCommandOnPath("npx",envPath,deps),cursorApiKeyPresent=!!deps.env.CURSOR_API_KEY,bridgeCredentialResolved=deps.bridgeCredentialResolved?.()??!!deps.env.BAPI_API_KEY;if(!platformResult.ok)return{platform:deps.platform,platformSupported:!1,candidateBackends:[],backendAvailability:[],claudeResolved,cursorResolved,npxResolved,cursorApiKeyPresent,bridgeCredentialResolved,unsupportedMessage:platformResult.error};let candidateBackends=platformResult.backends.map(b=>b.name),backendAvailability=[];for(let backend of platformResult.backends)backendAvailability.push({backend:backend.name,available:await backend.isAvailable(deps)});return{platform:deps.platform,platformSupported:!0,candidateBackends,backendAvailability,claudeResolved,cursorResolved,npxResolved,cursorApiKeyPresent,bridgeCredentialResolved}}function formatScheduleDoctorReport(report,json){if(json)return JSON.stringify(report,null,2);let lines=["schedule-run doctor (read-only diagnostics)",`Platform: ${report.platform}`];if(!report.platformSupported)lines.push(report.unsupportedMessage??unsupportedSchedulerPlatformMessage(report.platform));else{lines.push(`Candidate backends (in order): ${report.candidateBackends.join(", ")}`);for(let a of report.backendAvailability)lines.push(` ${a.available?"AVAILABLE ":"UNAVAILABLE"} ${a.backend}`)}return lines.push(`claude on PATH: ${report.claudeResolved?"yes":"no"}`),lines.push(`cursor-agent on PATH: ${report.cursorResolved?"yes":"no"}`),lines.push(`npx on PATH: ${report.npxResolved?"yes":"no"}`),lines.push(`CURSOR_API_KEY set: ${report.cursorApiKeyPresent?"yes":"no"}`),lines.push(`Bridge credential: ${report.bridgeCredentialResolved?"resolved":"not resolved"}`),lines.join(`
126
- `)}function nowIso(deps){return new Date(deps.now?deps.now():Date.now()).toISOString()}async function orchestrateScheduleExecute(options,deps,io){let metadata=await readScheduleMetadata(options.id,deps.homeDir,deps.platform);if(!metadata)return{ok:!1,exitCode:1,error:`No schedule found with id '${options.id}'.`};let agentInvocation=metadata.agent_invocation??metadata.invocation;if(!agentInvocation||!agentInvocation.exe)return await appendScheduleRunEvent(options.id,{status:"failed",at:nowIso(deps),message:"missing agent_invocation"},deps.homeDir,deps.platform).catch(()=>{}),{ok:!1,exitCode:1,error:`Schedule '${options.id}' has no agent invocation to run.`};await appendScheduleRunEvent(options.id,{status:"started",at:nowIso(deps)},deps.homeDir,deps.platform).catch(()=>{});let env={...deps.env};metadata.env_path&&(env.PATH=metadata.env_path,deps.platform==="win32"&&(env.Path=metadata.env_path)),env.BRIDGE_GPT_SCHEDULE_ID=metadata.id,metadata.command&&(env.BRIDGE_GPT_COMMAND=metadata.command),metadata.args&&(env.BRIDGE_GPT_COMMAND_ARGS_JSON=JSON.stringify(metadata.args)),metadata.repo_path&&(env.BRIDGE_GPT_REPO_PATH=metadata.repo_path),metadata.agent&&(env.BRIDGE_GPT_AGENT=metadata.agent),metadata.agent_path&&(env.BRIDGE_GPT_AGENT_PATH=metadata.agent_path),metadata.idea_file&&(env.BRIDGE_GPT_IDEA_FILE=metadata.idea_file);let result;try{result=await deps.runCommand(agentInvocation.exe,agentInvocation.args,{cwd:metadata.repo_path,env})}catch(error){let msg=error instanceof Error?error.message:String(error);return await appendScheduleRunEvent(options.id,{status:"failed",at:nowIso(deps),message:`agent launch failed: ${msg}`},deps.homeDir,deps.platform).catch(()=>{}),{ok:!1,exitCode:1,error:`Failed to launch agent: ${msg}`}}return result.stdout&&io.writeStdout(result.stdout),result.stderr&&io.writeStderr(result.stderr),result.exitCode===0?(await appendScheduleRunEvent(options.id,{status:"completed",at:nowIso(deps),exit_code:0},deps.homeDir,deps.platform).catch(()=>{}),{ok:!0,exitCode:0}):(await appendScheduleRunEvent(options.id,{status:"failed",at:nowIso(deps),exit_code:result.exitCode},deps.homeDir,deps.platform).catch(()=>{}),{ok:!1,exitCode:result.exitCode})}async function runScheduleRunCli(argv,overrides={}){let log=overrides.log??(m=>console.log(m)),errorLog=overrides.errorLog??(m=>console.error(m)),parsed=parseScheduleRunArgs(argv);if(parsed.status==="help")return log(parsed.usage),0;if(parsed.status==="error")return errorLog(`Error: ${parsed.message}`),errorLog(""),errorLog(getScheduleRunUsage()),1;let deps=overrides.deps??createDefaultScheduleRunDeps();try{switch(parsed.subcommand){case"create":{let result=await orchestrateScheduleCreate(parsed.options,deps);return result.ok?(log(formatScheduleCreateResult(result)),0):(errorLog(formatScheduleCreateResult(result)),1)}case"list":{let report=await orchestrateScheduleList(parsed.options,deps);return log(formatScheduleListResult(report,parsed.options.json)),0}case"cancel":{let result=await orchestrateScheduleCancel(parsed.options,deps);return result.ok?(log(formatScheduleCancelResult(result)),0):(errorLog(formatScheduleCancelResult(result)),1)}case"doctor":{let report=await orchestrateScheduleDoctor(deps);return log(formatScheduleDoctorReport(report,parsed.options.json)),report.platformSupported?0:1}case"_execute":{let io={writeStdout:overrides.writeStdout??(chunk=>process.stdout.write(chunk)),writeStderr:overrides.writeStderr??(chunk=>process.stderr.write(chunk))},result=await orchestrateScheduleExecute(parsed.options,deps,io);return!result.ok&&result.error&&errorLog(`Error: ${result.error}`),result.exitCode}}}catch(error){let detail=error instanceof Error?error.message:String(error);return errorLog(`Internal error: ${detail}`),errorLog("Error: schedule-run failed unexpectedly. See the message above for local diagnostics."),1}return 1}var VALID_BACKEND_NAMES,SCHEDULE_ID_PATTERN,init_schedule_run=__esm({"src/schedule-run.ts"(){"use strict";init_scheduler_backends();init_schedule_store();init_agent_launchers();init_claude();init_command_catalog();init_scheduled_prompt();VALID_BACKEND_NAMES=["launchd","task-scheduler","systemd-user","at-fallback"],SCHEDULE_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/}});function listAgentNames(){return Object.keys(AGENT_REGISTRY)}function isAgentName(value){return listAgentNames().includes(value)}function resolveAgentSpec(name){let resolved=name??DEFAULT_AGENT_NAME;return isAgentName(resolved)?AGENT_REGISTRY[resolved]:null}var AGENT_REGISTRY,DEFAULT_AGENT_NAME,init_agent_registry=__esm({"src/agent-registry.ts"(){"use strict";AGENT_REGISTRY={claude:{name:"claude",command:"claude",promptArgStyle:"positional",installHint:{darwin:"npm install -g @anthropic-ai/claude-code",linux:"npm install -g @anthropic-ai/claude-code",win32:"npm install -g @anthropic-ai/claude-code"},authNote:"Claude Code authenticates interactively on first run \u2014 follow its login/auth prompt if asked.",supportsModelOverride:!0,modelFlag:"--model",tierModels:{cheap:"haiku",basic:"sonnet",premium:"opus"},staticModelAliasAllowlist:["haiku","sonnet","opus"]},"cursor-agent":{name:"cursor-agent",command:"cursor-agent",promptArgStyle:"positional",installHint:{darwin:"curl https://cursor.com/install -fsSL | bash",linux:"curl https://cursor.com/install -fsSL | bash",win32:"irm 'https://cursor.com/install?win32=true' | iex"},authNote:"Run cursor-agent login to authenticate; doctor checks PATH presence only, not login state.",supportsModelOverride:!0,modelFlag:"--model",tierModels:{cheap:"auto",basic:"claude-4.6-sonnet-medium",premium:"claude-opus-4-8-thinking-high"},interactiveLaunchArgs:["--trust"]}},DEFAULT_AGENT_NAME="claude"}});var DEFAULT_PROBE_TIMEOUT_MS,init_types2=__esm({"src/agent-capabilities/types.ts"(){"use strict";DEFAULT_PROBE_TIMEOUT_MS=9e4}});import{join}from"node:path";function buildHeadlessArgs(agentName,opts){let fmt=opts.outputFormat??"text";if(agentName==="cursor-agent")return["-p","--output-format",fmt,"--trust","--workspace",opts.cwd,opts.prompt];let args=["-p"];return opts.skipPermissions===!0&&args.push("--dangerously-skip-permissions"),typeof opts.model=="string"&&opts.model.trim().length>0&&args.push("--model",opts.model),fmt==="json"?args.push("--output-format","json"):fmt==="stream-json"&&args.push("--output-format","stream-json","--verbose"),args.push(opts.prompt),args}async function createProbeContext(deps,agent,defaultTimeoutMs=DEFAULT_PROBE_TIMEOUT_MS){let launcherDeps={platform:deps.platform,env:deps.env,runCommand:(file,args,options)=>deps.runCommand(file,args,options)},resolvedBinary=await resolveCommandOnPath(agent.command,deps.env.PATH??"",launcherDeps),createdDirs=[],counter=0;return{ctx:{agent,deps,resolvedBinary,marker(name){return`${name}_${deps.uniqueSuffix()}_${counter++}`},async makeTempProject(seed){let dir=await deps.mkdtemp(join(deps.tmpRoot,"agent-cap-"));return createdDirs.push(dir),seed&&await seed(dir),dir},async runHeadless(opts){let exe=resolvedBinary??agent.command,args=buildHeadlessArgs(agent.name,opts),timeoutMs=opts.timeoutMs??defaultTimeoutMs,controller=new AbortController,timedOut=!1,timer=setTimeout(()=>{timedOut=!0,controller.abort()},timeoutMs),start=deps.now();try{let result=await deps.runCommand(exe,args,{cwd:opts.cwd,env:deps.env,signal:controller.signal}),elapsedMs=deps.now()-start;return timedOut?{kind:"hang",elapsedMs,partialStdout:result.stdout??""}:{kind:"exited",exitCode:result.exitCode,stdout:result.stdout??"",stderr:result.stderr??"",elapsedMs}}catch(err){let elapsedMs=deps.now()-start;return timedOut?{kind:"hang",elapsedMs,partialStdout:""}:{kind:"spawn-error",message:err instanceof Error?err.message:String(err)}}finally{clearTimeout(timer)}}},cleanup:async()=>{for(let dir of createdDirs.splice(0))try{await deps.rm(dir,{recursive:!0,force:!0})}catch{}}}}var init_probe_context=__esm({"src/agent-capabilities/probe-context.ts"(){"use strict";init_claude();init_types2()}});import{execFile as execFile2}from"node:child_process";import{mkdtemp,rm,writeFile,mkdir}from"node:fs/promises";import os2 from"node:os";import{randomBytes}from"node:crypto";function createDefaultAgentCapabilitiesDeps(){let runCommand=(file,args,options)=>new Promise(resolve2=>{execFile2(file,args,{cwd:options?.cwd,env:options?.env??process.env,signal:options?.signal,killSignal:"SIGKILL",maxBuffer:67108864,encoding:"utf-8"},(error,stdout,stderr)=>{let exitCode=error&&typeof error.code=="number"?error.code:error?1:0;resolve2({stdout:stdout??"",stderr:stderr??"",exitCode})})});return{platform:process.platform,env:process.env,runCommand,tmpRoot:os2.tmpdir(),mkdtemp:prefix=>mkdtemp(prefix),rm:(target,opts)=>rm(target,opts),writeFile:(target,data)=>writeFile(target,data,"utf-8"),mkdir:(target,opts)=>mkdir(target,opts).then(()=>{}),now:()=>Date.now(),uniqueSuffix:()=>randomBytes(3).toString("hex").toUpperCase()}}var init_default_deps=__esm({"src/agent-capabilities/default-deps.ts"(){"use strict"}});import{join as join2}from"node:path";function truncate(text){let flat=text.replace(/\s+/g," ").trim();return flat.length>EVIDENCE_MAX?`${flat.slice(0,EVIDENCE_MAX)}\u2026`:flat}function nonExitedResult(run){return run.kind==="hang"?{status:"hang",detail:`agent did not exit within the timeout (${run.elapsedMs}ms) \u2014 likely the version-sensitive -p hang`,elapsedMs:run.elapsedMs,evidence:run.partialStdout?truncate(run.partialStdout):void 0}:run.kind==="spawn-error"?{status:"fail",detail:`could not spawn agent: ${run.message}`}:null}function denyHookCommand(){return`printf '%s' '${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"agent-capability deny-enforcement probe fallback: tool call denied."}})}'`}async function seedDenyTargetFile(ctx,dir,marker){await ctx.deps.writeFile(join2(dir,DENY_TARGET_FILE),`${marker}
126
+ `)}function nowIso(deps){return new Date(deps.now?deps.now():Date.now()).toISOString()}async function orchestrateScheduleExecute(options,deps,io){let metadata=await readScheduleMetadata(options.id,deps.homeDir,deps.platform);if(!metadata)return{ok:!1,exitCode:1,error:`No schedule found with id '${options.id}'.`};let agentInvocation=metadata.agent_invocation??metadata.invocation;if(!agentInvocation||!agentInvocation.exe)return await appendScheduleRunEvent(options.id,{status:"failed",at:nowIso(deps),message:"missing agent_invocation"},deps.homeDir,deps.platform).catch(()=>{}),{ok:!1,exitCode:1,error:`Schedule '${options.id}' has no agent invocation to run.`};await appendScheduleRunEvent(options.id,{status:"started",at:nowIso(deps)},deps.homeDir,deps.platform).catch(()=>{});let env={...deps.env};metadata.env_path&&(env.PATH=metadata.env_path,deps.platform==="win32"&&(env.Path=metadata.env_path)),env.BRIDGE_GPT_SCHEDULE_ID=metadata.id,metadata.command&&(env.BRIDGE_GPT_COMMAND=metadata.command),metadata.args&&(env.BRIDGE_GPT_COMMAND_ARGS_JSON=JSON.stringify(metadata.args)),metadata.repo_path&&(env.BRIDGE_GPT_REPO_PATH=metadata.repo_path),metadata.agent&&(env.BRIDGE_GPT_AGENT=metadata.agent),metadata.agent_path&&(env.BRIDGE_GPT_AGENT_PATH=metadata.agent_path),metadata.idea_file&&(env.BRIDGE_GPT_IDEA_FILE=metadata.idea_file);let result;try{result=await deps.runCommand(agentInvocation.exe,agentInvocation.args,{cwd:metadata.repo_path,env})}catch(error){let msg=error instanceof Error?error.message:String(error);return await appendScheduleRunEvent(options.id,{status:"failed",at:nowIso(deps),message:`agent launch failed: ${msg}`},deps.homeDir,deps.platform).catch(()=>{}),{ok:!1,exitCode:1,error:`Failed to launch agent: ${msg}`}}return result.stdout&&io.writeStdout(result.stdout),result.stderr&&io.writeStderr(result.stderr),result.exitCode===0?(await appendScheduleRunEvent(options.id,{status:"completed",at:nowIso(deps),exit_code:0},deps.homeDir,deps.platform).catch(()=>{}),{ok:!0,exitCode:0}):(await appendScheduleRunEvent(options.id,{status:"failed",at:nowIso(deps),exit_code:result.exitCode},deps.homeDir,deps.platform).catch(()=>{}),{ok:!1,exitCode:result.exitCode})}async function runScheduleRunCli(argv,overrides={}){let log=overrides.log??(m=>console.log(m)),errorLog=overrides.errorLog??(m=>console.error(m)),parsed=parseScheduleRunArgs(argv);if(parsed.status==="help")return log(parsed.usage),0;if(parsed.status==="error")return errorLog(`Error: ${parsed.message}`),errorLog(""),errorLog(getScheduleRunUsage()),1;let deps=overrides.deps??createDefaultScheduleRunDeps();try{switch(parsed.subcommand){case"create":{let result=await orchestrateScheduleCreate(parsed.options,deps);return result.ok?(log(formatScheduleCreateResult(result)),0):(errorLog(formatScheduleCreateResult(result)),1)}case"list":{let report=await orchestrateScheduleList(parsed.options,deps);return log(formatScheduleListResult(report,parsed.options.json)),0}case"cancel":{let result=await orchestrateScheduleCancel(parsed.options,deps);return result.ok?(log(formatScheduleCancelResult(result)),0):(errorLog(formatScheduleCancelResult(result)),1)}case"doctor":{let report=await orchestrateScheduleDoctor(deps);return log(formatScheduleDoctorReport(report,parsed.options.json)),report.platformSupported?0:1}case"_execute":{let io={writeStdout:overrides.writeStdout??(chunk=>process.stdout.write(chunk)),writeStderr:overrides.writeStderr??(chunk=>process.stderr.write(chunk))},result=await orchestrateScheduleExecute(parsed.options,deps,io);return!result.ok&&result.error&&errorLog(`Error: ${result.error}`),result.exitCode}}}catch(error){let detail=error instanceof Error?error.message:String(error);return errorLog(`Internal error: ${detail}`),errorLog("Error: schedule-run failed unexpectedly. See the message above for local diagnostics."),1}return 1}var VALID_BACKEND_NAMES,SCHEDULE_ID_PATTERN,init_schedule_run=__esm({"src/schedule-run.ts"(){"use strict";init_scheduler_backends();init_schedule_store();init_agent_launchers();init_claude();init_command_catalog();init_scheduled_prompt();VALID_BACKEND_NAMES=["launchd","task-scheduler","systemd-user","at-fallback"],SCHEDULE_ID_PATTERN=/^[A-Za-z0-9][A-Za-z0-9_-]{0,63}$/}});function listAgentNames(){return Object.keys(AGENT_REGISTRY)}function isAgentName(value){return listAgentNames().includes(value)}function resolveAgentSpec(name){let resolved=name??DEFAULT_AGENT_NAME;return isAgentName(resolved)?AGENT_REGISTRY[resolved]:null}var AGENT_REGISTRY,DEFAULT_AGENT_NAME,init_agent_registry=__esm({"src/agent-registry.ts"(){"use strict";AGENT_REGISTRY={claude:{name:"claude",command:"claude",promptArgStyle:"positional",installHint:{darwin:"npm install -g @anthropic-ai/claude-code",linux:"npm install -g @anthropic-ai/claude-code",win32:"npm install -g @anthropic-ai/claude-code"},authNote:"Claude Code authenticates interactively on first run \u2014 follow its login/auth prompt if asked.",supportsModelOverride:!0,modelFlag:"--model",tierModels:{cheap:"haiku",basic:"sonnet",premium:"opus"},staticModelAliasAllowlist:["haiku","sonnet","opus"]},"cursor-agent":{name:"cursor-agent",command:"cursor-agent",promptArgStyle:"positional",installHint:{darwin:"curl https://cursor.com/install -fsSL | bash",linux:"curl https://cursor.com/install -fsSL | bash",win32:"irm 'https://cursor.com/install?win32=true' | iex"},authNote:"Run cursor-agent login to authenticate; doctor checks PATH presence only, not login state.",supportsModelOverride:!0,modelFlag:"--model",tierModels:{cheap:"auto",basic:"claude-4.6-sonnet-medium",premium:"claude-opus-4-8-thinking-high"}}},DEFAULT_AGENT_NAME="claude"}});var DEFAULT_PROBE_TIMEOUT_MS,init_types2=__esm({"src/agent-capabilities/types.ts"(){"use strict";DEFAULT_PROBE_TIMEOUT_MS=9e4}});import{join}from"node:path";function buildHeadlessArgs(agentName,opts){let fmt=opts.outputFormat??"text";if(agentName==="cursor-agent")return["-p","--output-format",fmt,"--trust","--workspace",opts.cwd,opts.prompt];let args=["-p"];return opts.skipPermissions===!0&&args.push("--dangerously-skip-permissions"),typeof opts.model=="string"&&opts.model.trim().length>0&&args.push("--model",opts.model),fmt==="json"?args.push("--output-format","json"):fmt==="stream-json"&&args.push("--output-format","stream-json","--verbose"),args.push(opts.prompt),args}async function createProbeContext(deps,agent,defaultTimeoutMs=DEFAULT_PROBE_TIMEOUT_MS){let launcherDeps={platform:deps.platform,env:deps.env,runCommand:(file,args,options)=>deps.runCommand(file,args,options)},resolvedBinary=await resolveCommandOnPath(agent.command,deps.env.PATH??"",launcherDeps),createdDirs=[],counter=0;return{ctx:{agent,deps,resolvedBinary,marker(name){return`${name}_${deps.uniqueSuffix()}_${counter++}`},async makeTempProject(seed){let dir=await deps.mkdtemp(join(deps.tmpRoot,"agent-cap-"));return createdDirs.push(dir),seed&&await seed(dir),dir},async runHeadless(opts){let exe=resolvedBinary??agent.command,args=buildHeadlessArgs(agent.name,opts),timeoutMs=opts.timeoutMs??defaultTimeoutMs,controller=new AbortController,timedOut=!1,timer=setTimeout(()=>{timedOut=!0,controller.abort()},timeoutMs),start=deps.now();try{let result=await deps.runCommand(exe,args,{cwd:opts.cwd,env:deps.env,signal:controller.signal}),elapsedMs=deps.now()-start;return timedOut?{kind:"hang",elapsedMs,partialStdout:result.stdout??""}:{kind:"exited",exitCode:result.exitCode,stdout:result.stdout??"",stderr:result.stderr??"",elapsedMs}}catch(err){let elapsedMs=deps.now()-start;return timedOut?{kind:"hang",elapsedMs,partialStdout:""}:{kind:"spawn-error",message:err instanceof Error?err.message:String(err)}}finally{clearTimeout(timer)}}},cleanup:async()=>{for(let dir of createdDirs.splice(0))try{await deps.rm(dir,{recursive:!0,force:!0})}catch{}}}}var init_probe_context=__esm({"src/agent-capabilities/probe-context.ts"(){"use strict";init_claude();init_types2()}});import{execFile as execFile2}from"node:child_process";import{mkdtemp,rm,writeFile,mkdir}from"node:fs/promises";import os2 from"node:os";import{randomBytes}from"node:crypto";function createDefaultAgentCapabilitiesDeps(){let runCommand=(file,args,options)=>new Promise(resolve2=>{execFile2(file,args,{cwd:options?.cwd,env:options?.env??process.env,signal:options?.signal,killSignal:"SIGKILL",maxBuffer:67108864,encoding:"utf-8"},(error,stdout,stderr)=>{let exitCode=error&&typeof error.code=="number"?error.code:error?1:0;resolve2({stdout:stdout??"",stderr:stderr??"",exitCode})})});return{platform:process.platform,env:process.env,runCommand,tmpRoot:os2.tmpdir(),mkdtemp:prefix=>mkdtemp(prefix),rm:(target,opts)=>rm(target,opts),writeFile:(target,data)=>writeFile(target,data,"utf-8"),mkdir:(target,opts)=>mkdir(target,opts).then(()=>{}),now:()=>Date.now(),uniqueSuffix:()=>randomBytes(3).toString("hex").toUpperCase()}}var init_default_deps=__esm({"src/agent-capabilities/default-deps.ts"(){"use strict"}});import{join as join2}from"node:path";function truncate(text){let flat=text.replace(/\s+/g," ").trim();return flat.length>EVIDENCE_MAX?`${flat.slice(0,EVIDENCE_MAX)}\u2026`:flat}function nonExitedResult(run){return run.kind==="hang"?{status:"hang",detail:`agent did not exit within the timeout (${run.elapsedMs}ms) \u2014 likely the version-sensitive -p hang`,elapsedMs:run.elapsedMs,evidence:run.partialStdout?truncate(run.partialStdout):void 0}:run.kind==="spawn-error"?{status:"fail",detail:`could not spawn agent: ${run.message}`}:null}function denyHookCommand(){return`printf '%s' '${JSON.stringify({hookSpecificOutput:{hookEventName:"PreToolUse",permissionDecision:"deny",permissionDecisionReason:"agent-capability deny-enforcement probe fallback: tool call denied."}})}'`}async function seedDenyTargetFile(ctx,dir,marker){await ctx.deps.writeFile(join2(dir,DENY_TARGET_FILE),`${marker}
127
127
  `)}async function seedDenySettings(ctx,dir,marker){await seedDenyTargetFile(ctx,dir,marker);let claudeDir=join2(dir,".claude");await ctx.deps.mkdir(claudeDir,{recursive:!0});let settings={permissions:{deny:[DENY_BASH_RULE]}};await ctx.deps.writeFile(join2(claudeDir,"settings.local.json"),`${JSON.stringify(settings,null,2)}
128
128
  `)}async function seedDenyHook(ctx,dir,marker){await seedDenyTargetFile(ctx,dir,marker);let claudeDir=join2(dir,".claude");await ctx.deps.mkdir(claudeDir,{recursive:!0});let settings={hooks:{PreToolUse:[{matcher:DENY_HOOK_MATCHER,hooks:[{type:"command",command:denyHookCommand()}]}]}};await ctx.deps.writeFile(join2(claudeDir,"settings.local.json"),`${JSON.stringify(settings,null,2)}
129
129
  `)}function denyProbePrompt(){return["This is an agent-capability probe of permission enforcement.",`Use the Bash tool to run exactly this command: cat ${DENY_TARGET_FILE}`,"Then output the command's exact stdout on its own line.","Use ONLY the Bash tool for this \u2014 do not use Read, Grep, or any other tool, and do not open the file yourself.","If the Bash command is blocked, denied, or errors, output the single word DENIED and nothing else.","Do not guess, fabricate, or infer the file contents \u2014 only report what the command actually returned."].join(`
@@ -73,7 +73,9 @@ export function makeFakeExecutorDeps(clock, overrides = {}) {
73
73
  throw new Error("spawnProcess not configured for this test");
74
74
  },
75
75
  readFile: async () => {
76
- throw new Error("ENOENT");
76
+ // Mirror real fs/promises: a missing-file rejection carries code "ENOENT"
77
+ // (so BAPI-664 command provisioning treats absent files as fillable).
78
+ throw Object.assign(new Error("ENOENT"), { code: "ENOENT" });
77
79
  },
78
80
  writeFile: async () => { },
79
81
  mkdir: async () => undefined,