@bridge_gpt/mcp-server 0.2.25 → 0.2.27

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (73) hide show
  1. package/README.md +59 -9
  2. package/build/agents.generated.js +1 -1
  3. package/build/bridge-api-urls.js +31 -0
  4. package/build/commands.generated.js +4 -4
  5. package/build/conductor-bin.js +68 -9267
  6. package/build/conductor-bundle-artifacts.js +802 -0
  7. package/build/conductor-bundle-cli.js +256 -0
  8. package/build/conductor-claude-hook-bin.js +2 -172
  9. package/build/decision-page-template.js +2 -31
  10. package/build/docs.generated.js +2 -1
  11. package/build/doctor.js +148 -1
  12. package/build/env-flags.js +31 -0
  13. package/build/index.js +4659 -34836
  14. package/build/init.js +87 -59
  15. package/build/install-bridge.js +380 -22
  16. package/build/mcp-host-config.js +521 -0
  17. package/build/mcp-host-targets.js +194 -0
  18. package/build/mcp-install-state.js +175 -0
  19. package/build/pipelines.generated.js +5 -4
  20. package/build/readme.generated.js +1 -1
  21. package/build/start-tickets.js +118 -5
  22. package/build/tool-surface-gating.js +396 -0
  23. package/build/version.generated.js +1 -1
  24. package/docs/install/mcp-tool-integrations.md +2 -2
  25. package/package.json +5 -7
  26. package/design-assets/favicon/android-chrome-192x192.png +0 -0
  27. package/design-assets/favicon/android-chrome-512x512.png +0 -0
  28. package/design-assets/favicon/apple-touch-icon.png +0 -0
  29. package/design-assets/favicon/favicon-16x16.png +0 -0
  30. package/design-assets/favicon/favicon.ico +0 -0
  31. package/design-assets/favicon/site.webmanifest +0 -1
  32. package/public/css/main.min.css +0 -4971
  33. package/public/css/main.min.css.map +0 -1
  34. package/public/fonts/OFL.txt +0 -93
  35. package/public/fonts/SourceSansPro-Black.ttf +0 -0
  36. package/public/fonts/SourceSansPro-BlackItalic.ttf +0 -0
  37. package/public/fonts/SourceSansPro-Bold.ttf +0 -0
  38. package/public/fonts/SourceSansPro-BoldItalic.ttf +0 -0
  39. package/public/fonts/SourceSansPro-ExtraLight.ttf +0 -0
  40. package/public/fonts/SourceSansPro-ExtraLightItalic.ttf +0 -0
  41. package/public/fonts/SourceSansPro-Italic.ttf +0 -0
  42. package/public/fonts/SourceSansPro-Light.ttf +0 -0
  43. package/public/fonts/SourceSansPro-LightItalic.ttf +0 -0
  44. package/public/fonts/SourceSansPro-Regular.ttf +0 -0
  45. package/public/fonts/SourceSansPro-SemiBold.ttf +0 -0
  46. package/public/fonts/SourceSansPro-SemiBoldItalic.ttf +0 -0
  47. package/public/img/bridge-logo-160x51.webp +0 -0
  48. package/public/img/bridge-logo-300x92.webp +0 -0
  49. package/public/img/favicon/android-chrome-192x192.png +0 -0
  50. package/public/img/favicon/android-chrome-512x512.png +0 -0
  51. package/public/img/favicon/apple-touch-icon.png +0 -0
  52. package/public/img/favicon/favicon-16x16.png +0 -0
  53. package/public/img/favicon/favicon-32x32.png +0 -0
  54. package/public/img/favicon/favicon.ico +0 -0
  55. package/public/img/favicon/site.webmanifest +0 -1
  56. package/public/img/installation/bitbucket/app-password-1.png +0 -0
  57. package/public/img/installation/bitbucket/app-password-2.png +0 -0
  58. package/public/img/installation/bitbucket/create-token-1.png +0 -0
  59. package/public/img/installation/bitbucket/create-token-2.png +0 -0
  60. package/public/img/installation/bitbucket/webhook-1.png +0 -0
  61. package/public/img/installation/github/github-review-webhook.png +0 -0
  62. package/public/img/installation/jira/credentials/api-key.png +0 -0
  63. package/public/img/installation/jira/webhook/create-rule.png +0 -0
  64. package/public/img/installation/jira/webhook/project-settings.png +0 -0
  65. package/public/img/installation/jira/webhook/rule-create-1.png +0 -0
  66. package/public/img/installation/jira/webhook/rule-create-2.png +0 -0
  67. package/public/img/installation/jira/webhook/rule-create-3.png +0 -0
  68. package/public/img/installation/pinecone/pinecone-api-key.png +0 -0
  69. package/public/img/installation/pinecone/pinecone-index.png +0 -0
  70. package/public/js/main.min.js +0 -10427
  71. package/public/js/main.min.js.map +0 -1
  72. package/smoke-test/SMOKE-TEST.md +0 -560
  73. package/smoke-test/smoke-test-mcp.md +0 -23
@@ -10,19 +10,19 @@ export const COMMANDS = {
10
10
  "create-pr.md": "# Create PR: $ARGUMENTS\n\n$ARGUMENTS\n\nThis command takes a Jira ticket key (e.g., `BAPI-150`), fetches the ticket summary, determines the base branch, and creates a pull request on the configured VCS provider. It is designed to run after `/commit-ticket` completes.\n\nIf any critical stage fails (Stage 0), stop immediately and report which stage failed and why. Non-critical stages (Stage 1 and Stage 2) should log a warning but not stop the pipeline.\n\n---\n\n# Instructions\n\nYou are executing a 3-stage pipeline to create a pull request for a Jira ticket. Execute all stages in sequence.\n\n## Stage 0 — Setup and Argument Parsing\n\n1. **Parse `$ARGUMENTS`**: Extract a single required `ticket_key` argument. The expected format is a Jira ticket key such as `BAPI-150` or `PROJ-123` — one or more uppercase letters, a hyphen, and one or more digits (regex: `[A-Z]+-\\d+`). If `$ARGUMENTS` is empty or the value does not match the expected format, stop immediately and display:\n\n ```\n Invalid ticket key format: '<value>'. Expected format: PROJ-123 (uppercase letters, hyphen, digits).\n Usage: /create-pr <ticket_key> (e.g., /create-pr BAPI-150)\n ```\n\n2. **Connectivity check**: Call the `ping` MCP tool (no parameters). If the ping fails or does not return `\"status\": \"ok\"`, stop immediately and display:\n\n ```\n Connectivity check failed. Please verify:\n - Check that the Bridge API MCP server is configured in your editor's MCP settings\n - Check that BAPI_BASE_URL is set and the server is reachable\n - Check that BAPI_API_KEY is valid\n - Check that BAPI_REPO_NAME matches a configured repository\n ```\n\n3. **Get current branch**: Run `git branch --show-current` in the terminal. Store the result as `head_branch`. Verify that `head_branch` contains the `ticket_key` (case-insensitive comparison). If the branch does not contain the ticket key, stop immediately and display:\n\n ```\n Current branch '<head_branch>' does not contain ticket key <ticket_key>.\n Please switch to the correct feature branch before running /create-pr.\n ```\n\n4. **Resolve base branch**: Call the `config_field` MCP tool with `operation` set to `\"get\"` and `field_name` set to `base_branch`. If the tool returns null, or an HTTP 400 Validation Error / Invalid field name, treat it as not set and fallback to `main`. Store the resolved value as `base_branch`.\n\n5. **Fetch ticket summary**: Call the `get_ticket` MCP tool with `ticket_number` set to the parsed `ticket_key`. Extract the ticket summary from the response. If the tool returns an error, log a warning and use a generic summary based on the ticket key.\n\n6. **Resolve docs directory**: Call the `get_docs_dir` MCP tool (no parameters). Store the returned path as `docs_dir`.\n\nThis stage is **critical** — stop immediately on failure. Do not proceed to Stage 1.\n\n## Stage 1 — Create Pull Request\n\n1. **Compose PR title**: Format the title as `<ticket_key>: <ticket_summary>`. Truncate to 72 characters if needed.\n\n2. **Compose PR body**: Build a PR body that includes:\n - A brief description derived from the ticket summary\n - A plain text reference to the local implementation plan: `Implementation Plan available locally at {docs_dir}/plans/{ticket_key}-plan.md` (do not use markdown hyperlink syntax — the local path is sufficient for team members pulling the branch)\n\n3. **Create the pull request**: Call the `create_pull_request` MCP tool with:\n - `head_branch`: the current branch from Stage 0\n - `base_branch`: the resolved base branch from Stage 0\n - `title`: the composed PR title\n - `body`: the composed PR body\n\n4. **Handle the response with graceful degradation**:\n - If the response contains `available: false`: Report the reason to the user and skip to Stage 2. Do not halt the pipeline.\n - If the response contains `created: false`: Log \"PR already exists\" and store the returned PR URL. Continue to Stage 2.\n - If the response contains `created: true`: Store the PR URL. Continue to Stage 2.\n - If an HTTP error occurs: Warn the user with the error details and continue to Stage 2. Do not halt the pipeline.\n\nThis stage is **non-critical** — warn on failure, continue to Stage 2 regardless.\n\n## Stage 2 — Summary Report\n\nDisplay a structured report after all stages complete:\n\n```\n## Pull Request Report\n\n**Ticket**: <ticket_key>\n**Branch**: <head_branch>\n**Base Branch**: <base_branch>\n**PR URL**: <pr_url or \"N/A — see warnings\">\n\n**Warnings**:\n<If any non-critical stages had warnings (Stage 1: PR creation failed or unavailable),\nlist them here. If no warnings, omit this section.>\n```\n\nThis stage is **non-critical** — display the report regardless.\n\n## Final Report\n\nOn success, display the structured report from Stage 2 confirming that the pull request was created (or already existed), including the branch name, base branch, PR URL, and any warnings from earlier stages.\n\nOn failure at any critical stage (Stage 0), display which stage failed and the error details.\n",
11
11
  "critique-ticket.md": "Generate a ticket quality critique and save it locally.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command triggers an AI-powered critique of a Jira ticket and saves the result locally. **No human confirmation gates** — the command runs end-to-end without pausing. `$ARGUMENTS` should contain a single Jira ticket key in `PROJECT-NUMBER` format (e.g., `BAPI-123`).\n\nIf any step fails, stop immediately and report which step failed and why.\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\n2. **Validate the ticket key format**: Validate that `ticket_key` matches the regex pattern `^[A-Za-z][A-Za-z0-9]+-\\d+$`. If validation fails, stop immediately and report: \"The argument does not match the expected `PROJECT-NUMBER` format. Example: `BAPI-123`.\"\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 Critique\n\nCall the `request_ticket_critique` MCP tool with:\n- `ticket_number`: the validated `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\nIf the tool returns an error, stop immediately and report: \"Critique generation failed.\" Include the error details.\n\n## Final Report\n\n**On success**, display a summary including:\n\n- Path to the saved critique document: `{docs_dir}/ticket-critiques/{ticket_key}-ticket-quality-critique.md`\n\nNote: The critique was NOT pushed to Jira. To incorporate the critique findings into the Jira ticket description, run: `/update-ticket {ticket_key}`\n\n**On failure at any step**, stop immediately and display the step that failed and the error details.\n",
12
12
  "estimate-epic.md": "Estimate an entire Jira Epic or an explicit ticket-key group via the shared epic estimation orchestrator.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\n`$ARGUMENTS` is either a Jira Epic key (e.g. `BAPI-518`) or an explicit `--tickets` key list — never both. This command calls the `estimate_epic` MCP tool, which delegates to the Bridge API epic estimation orchestrator, and renders the structured result.\n\nIf any step fails, stop immediately and report which step failed and why, preserving the user's originally entered epic key or ticket list in the report.\n\n## Step 1 — Parse Arguments\n\n1. **Parse `$ARGUMENTS`**: Extract exactly one key-source input, plus an optional `--allow-partial` flag.\n - Split `$ARGUMENTS` on whitespace.\n - If `--tickets` appears, every token after it (up to the next flag or end of input) is the explicit ticket-key list — this is the `ticket_keys` mode.\n - Otherwise, the first token matching the Jira key pattern (`[A-Z][A-Z0-9]+-\\d+`) is the `epic_key` — this is the epic mode.\n - `--allow-partial` may appear anywhere; if present, set `allow_partial_value = true`. If absent, omit `allow_partial` entirely (do not pass `false`).\n - Never resolve both an `epic_key` and a `ticket_keys` list from the same invocation — usage is one mode or the other.\n\n2. **Validate input**:\n - Usage forms: `/estimate-epic EPIC-KEY` or `/estimate-epic --tickets KEY-1 KEY-2 ...`, plus optional `--allow-partial`.\n - If neither an `epic_key` nor a `--tickets` list can be resolved, stop immediately and report:\n ```\n Usage: /estimate-epic EPIC-KEY [--allow-partial]\n /estimate-epic --tickets KEY-1 KEY-2 ... [--allow-partial]\n ```\n - If `--tickets` is present but followed by zero keys, stop immediately and report: \"`--tickets` requires at least one ticket key.\"\n - Do not invent or pass a `mode` parameter — there isn't one; the tool infers the source from whichever of `epic_key`/`ticket_keys` is supplied.\n\n## Step 2 — Call the Tool\n\nCall the `estimate_epic` MCP tool with:\n- `epic_key`: the resolved epic key — **only** when in epic mode. Omit entirely in ticket-key mode.\n- `ticket_keys`: the resolved ticket-key list — **only** when in ticket-key mode. Omit entirely in epic mode.\n- `allow_partial`: `allow_partial_value` if `--allow-partial` was passed; omit entirely otherwise (never pass `null`, an empty string, or an empty array for any absent field).\n\nNever pass both `epic_key` and `ticket_keys` in the same call.\n\nIf the tool returns an error envelope (a JSON object with an `error` field), stop and report the error message, preserving the epic key or ticket list the user originally entered.\n\n## Step 3 — Render the Result\n\nRender the successful result as a structured report — do not dump raw JSON by default:\n\n1. **Top**: the final estimate and its scale label (`estimate_label`) as the primary heading — this is the strongest element of the report.\n2. **Immediately after the summary**: `math_source`.\n3. **Next**: resolved child ticket keys (`child_ticket_keys`) and the per-child breakdown, presented compactly.\n4. **Only if non-empty**: a compact warning section listing `failed_child_keys` and `skipped_child_keys`.\n\nKeep the happy-path report concise and scannable. Use backticks for Jira keys and technical identifiers (e.g. `BAPI-518`).\n\n> Note: this tool does not accept a `recreate` parameter — the underlying epic estimation orchestrator (BAPI-522) always reuses cached child estimates and has no recreate knob to forward to.\n\n## Final Report\n\nOn successful completion, display a structured summary per Step 3 above. On failure, display the error message returned by the tool (or the usage error from Step 1), preserving the user's originally entered epic key or ticket list.\n",
13
- "explore-ticket.md": "Explore the codebase for a task, settle its acceptance criteria with the user, then propose a design that meets them.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\n`$ARGUMENTS` is a free-form prompt describing a task you want to accomplish and your goals for it. This is **not** a Jira ticket key — it is plain text describing the work.\n\nExecute all exploration and analysis directly in the main conversation. The user should see exploration progress as it happens.\n\nThis command runs strictly outside-in, and the order is the point:\n\n1. **Requirements first.** Establish what the system must do, how it must behave, and what standards it must meet — then get the user to ratify that on an interactive decision page. The page settles **requirements only**. It never asks the user to pick an implementation.\n2. **Then how.** Only once the criteria are ratified do you consider how to meet them, optionally with a brainstorm.\n3. **Then the design.** You describe the final proposed design yourself, in the exploration doc. There is no second decision page.\n4. **Then ticket(s).**\n\nNever invert this. A design proposed against unratified criteria is a guess, and an implementation choice presented before the criteria are settled asks the user to commit to a solution for a problem they have not yet agreed on.\n\nIf any critical stage fails, stop immediately and report which stage failed and why.\n\n## Stage 0 — Setup\n\n1. **Parse prompt**: Extract the prompt text from `$ARGUMENTS`. Trim any surrounding whitespace. If the prompt is empty or whitespace-only, stop immediately and display: `Usage: /explore-ticket <prompt describing your task and goals>`\n\n2. **Resolve docs directory**: Call the `get_docs_dir` MCP tool (no parameters). Store the returned path as `docs_dir`.\n\n3. **Generate output slug**: Create a kebab-case slug from the prompt — take the first 6-8 meaningful words, strip non-alphanumeric characters, lowercase, and truncate to 60 characters. The slug **must start with a letter** so it is a valid decision-page `ticket_key` in Stage 5 (`/^[A-Za-z][A-Za-z0-9_-]*$/`); if it would start with a digit or hyphen, prefix it with `exploration-`. If `{docs_dir}/explorations/{slug}.md` already exists, append a short timestamp suffix (e.g., `-1710000000`) — and fold that suffix **into the `slug` variable itself**, not just the filename, so that Stage 4 (the doc), Stage 5 (`ticket_key`, `output_filename`), and Stage 8 (the doc rewrite) all reference the same slug. The output file path is `{docs_dir}/explorations/{slug}.md`.\n\n4. **Initialize tracking**: Prepare to track `key_files_examined` (list of files read during exploration), `web_searches` (list of topics searched), and `research_queries` (list of deep research queries).\n\nIf this stage fails, stop immediately and report the error. Do not proceed to Stage 1.\n\n## Stage 1 — Codebase Exploration\n\nThis is the core discovery stage. Take your time — thorough exploration is more valuable than speed.\n\n1. **Analyze the prompt** to identify which areas of the codebase are relevant: route files, agent flows, database models, library utilities, LLM integration, MCP server, unit and E2E suites, etc.\n\n2. **Search for files** matching patterns related to the task (e.g., `api/routes/**/*.py`, `src/python/llms/agents/**/*.py`, `db/models/*.py`).\n\n3. **Search for content** — relevant function names, class names, patterns, and keywords across the codebase.\n\n4. **Read the most relevant files** in detail — understand existing implementations, conventions, and patterns that relate to the task.\n\n5. **Build a mental model** of:\n - What exists today that relates to the task\n - What patterns and conventions are used in similar features\n - What dependencies, data flows, and integration points are involved\n - What gaps or unknowns remain that need external research\n - Whether there is an established precedent for this kind of work, or none at all — Stage 7 depends on this judgement\n\nExplore to understand the problem and its constraints. Resist designing a solution while you read — you do not yet know what the system is required to do, and Stage 8 is where the design gets written.\n\n6. **Track all significant files** examined in `key_files_examined`.\n\nDo not rush this stage. When in doubt, read more code rather than less. Continue exploring until you have a solid understanding of the relevant code.\n\nThis stage is non-blocking — always proceed to Stage 2 regardless of what you find, since the exploration informs what research is needed.\n\n## Stage 2 — Research Unknowns\n\nBased on gaps identified in Stage 1, decide what research is needed. Apply these decision rules:\n\n- **No research needed**: The codebase exploration answered all questions. Skip directly to Stage 3.\n- **Web search**: For quick factual lookups — library API signatures, configuration syntax, small \"how to\" questions. Examples: \"FastAPI dependency injection with custom headers\", \"Alembic batch migration syntax\". Do web searches inline and capture relevant findings.\n- **Deep research** (via `request_deep_research` MCP tool): For large, multi-faceted unknowns that require synthesizing information from multiple sources. Examples: \"Best practices for implementing WebSocket connection pooling in Python asyncio\", \"Tradeoffs between different approaches to real-time notification delivery in FastAPI applications\". Only use deep research when the question genuinely needs a multi-source investigation.\n\n**If deep research is needed:**\n\n1. Call `request_deep_research` with `wait_for_result` set to `true`, `save_locally` set to `true`, a descriptive `query`, and `context` describing the Bridge API tech stack and the specific task.\n2. If deep research fails, note the failure and fall back to web searches for the same topic. Do NOT halt the pipeline.\n\nTrack all research performed in `research_queries` and `web_searches`.\n\nThis stage is non-blocking — failures degrade the quality of analysis but do not stop the command. Log a warning for any failed research and continue.\n\n## Stage 3 — Frame Acceptance Criteria\n\nEstablish what \"done and correct\" means. Everything in this stage is about the system's obligations, not its implementation. Do not name a technical approach here — that is Stage 8's job, and it does not happen until the user has ratified this framing.\n\n1. **State the frame plainly (required).**\n - **Business goal** — the value this work delivers and why it matters.\n - **Desired end-state** — the concrete state the system should reach once this work is done.\n - **System behavior** — how the system must behave to complete its task (the quality attributes in prose, not a feature list).\n\n2. **Derive the acceptance criteria — what the system must do (required).** Write 3-8 criteria. Each one gets:\n - An `id` (`AC-1`, `AC-2`, …).\n - A `criterion` — a single obligation stated concretely enough to be checked. Write it as observable behavior (\"an operator who revokes a key sees the next request rejected\"), not as a task (\"add a revocation endpoint\").\n - A `verification` — how we would confirm it holds. Name the observable signal: a response code on a specific route, a row state, a log line, a rendered element, a user-visible outcome. **A criterion nobody can check is not yet a criterion** — sharpen it or drop it.\n - A `status`, using the rubric in step 4.\n\n Cover the failure and edge behavior, not just the happy path. If the work changes something that already exists, at least one criterion should pin down what must **not** regress.\n\n3. **Identify the non-functional requirements — the standards the system must meet (required).** Consider every one of these canonical NFR categories and include the ones that genuinely apply (omit the rest): security/privacy, performance/latency, reliability/failure-modes, observability/auditability, accessibility/UX, data-integrity/migration, compatibility, operability/config, compliance/SOC2, rollout/reversibility. For each NFR you include, write its `requirement` and its `implication` (what it changes about the implementation) — an NFR with no concrete implication is boilerplate; drop it.\n\n4. **Classify every acceptance criterion and every NFR** with this rubric: `confirmed` only if explicitly stated or observable in code; `assumed` only if a low-risk, reversible default; `open` if it touches architecture, the data model, security, user-visible behavior, migration, or irreversible creation and is not settled. When a criterion or an NFR is genuinely unclear, prefer marking it `open` and asking. Clear criteria make everything downstream more accurate, so surfacing an unclear one is a success, not a delay.\n\n5. **Frame the open requirement questions.** Where a requirement is unsettled **and** has discrete candidate answers, express it as a question the user can answer by clicking (e.g. \"Must revocation take effect immediately, or is eventual acceptable?\"). These become cards in Stage 5. They are questions about *what the system must do* — never about how to build it. If a question has no discrete answers, leave it as prose in the doc instead.\n\n6. **Sanity-check the frame against itself.** Do any two criteria conflict? Does a criterion conflict with an NFR (e.g. an auditability requirement against a latency budget)? Note every tension you find — Stage 7 treats these as a brainstorm trigger, and Stage 8 must resolve them explicitly rather than quietly favouring one side.\n\nThis stage is inline analysis — no tool calls required. This stage is non-blocking — always proceed to Stage 4.\n\n## Stage 4 — Write Requirements Draft\n\nWrite what you know so far to disk, so the user has something to read alongside the decision page. The design is deliberately absent — it does not exist yet.\n\n1. Create the `explorations/` directory under `docs_dir` if it does not exist.\n\n2. Write the exploration document to the slug-based path determined in Stage 0 (`{docs_dir}/explorations/{slug}.md`) with this structure:\n\n```markdown\n# Exploration: {concise summary of the prompt}\n\n**Date**: {current date}\n**Prompt**: {original prompt text}\n**Status**: Requirements drafted — awaiting ratification\n\n## Context\n\n{Brief description of the task and what areas of the codebase are relevant.}\n\n## Acceptance Criteria\n\n{The criteria from Stage 3 — what the system must do. One entry per criterion: its id, the criterion itself, how it is verified, and its status (confirmed / assumed / open).}\n\n## Goals & NFRs\n\n{The business goal, desired end-state, and required system behavior from Stage 3. Then the non-functional requirements — the standards the system must meet: each with its category, requirement, implication, and status (confirmed / assumed / open). Note any tension between criteria or between a criterion and an NFR.}\n\n## Open Questions\n\n{Requirement questions that are still unsettled. Mark which ones are going onto the decision page as cards and which are open-ended prose.}\n\n## Codebase Findings\n\n{Key discoveries from Stage 1. What exists today, what patterns are used, what the relevant code paths look like. Reference specific files and functions with file_path:line_number format.}\n\n## Research Findings\n\n{Findings from web searches and deep research, if any. If no research was performed, state \"No external research was needed.\"}\n\n## Key Files\n\n{Bulleted list of the most important files examined, with one-line descriptions of their relevance.}\n```\n\nDo not add a design, an implementation plan, or a recommendation to this draft. Stage 8 adds those once the criteria are settled.\n\nIf the file cannot be written, stop immediately and report the failure.\n\n## Stage 5 — Generate Requirements Decision Page\n\nTurn the Stage 3 framing into an interactive HTML decision page so the user can ratify the requirements by clicking. **This page settles requirements only.** It must not contain a single implementation option — the user is agreeing on what the system must do, not choosing how to build it.\n\n1. **Map the acceptance criteria to `acceptance_criteria`.** Each entry has `id`, `criterion`, `verification`, and `status`. Ids must be unique — a duplicate id is rejected, because the id is the key the page reports the user's stance under. Every criterion renders with an Agreed / Ask about this / Disagree control, so pass all of them, not only the open ones. Pass the NFRs the same way under `nfrs`.\n\n2. **Map each open requirement question from Stage 3 step 5 to an actionable item.** Each entry has:\n - `id`: a short stable id, e.g. `R-1`, `R-2`.\n - `question`: the requirement question.\n - `options`: the 2-4 candidate answers (string array). Do **not** include \"None of these\" or \"Ask about this\" — the renderer auto-appends both.\n - `option_consequences`: what each answer would mean for the criteria, **parallel to and the same length as** `options`.\n - `why_it_matters`: the concrete impact line.\n - `recommendation_explanation`: why the recommended answer is best.\n - `recommendation_index`: the 0-based index of the recommended answer (must be within `options`).\n - `codebase_evidence` (optional): the Assessment paragraph plus `file:line` citations, shown collapsed.\n\n **These cards are requirement questions, never implementation choices.** \"Must revocation be immediate or is eventual acceptable?\" is a valid card. \"Should we use a short-TTL cache or pub/sub invalidation?\" is not — it is a solution, it belongs to Stage 8, and putting it here defeats the purpose of the page. If you cannot phrase a card without naming a mechanism, it is not a requirement question. When there are no such questions, pass an empty array — a criteria-only page is expected and renders correctly.\n\n3. **Call `generate_decision_page`** with routing fields at the root and all heavy arrays nested under `content`:\n - `artifact_type`: `pre_ticket_planning` (renders the acceptance-criteria and goals panel above any cards).\n - `ticket_key`: the Stage 0 `slug` (a non-Jira slug is fine — it must start with a letter and contain only letters, digits, hyphens, or underscores).\n - `output_subdir`: `explorations` (so the page lands beside the markdown doc).\n - `output_filename`: `{slug}-requirements.html`.\n - `labels`: requirements-flavored overrides, e.g. `title` = \"Requirements\", `section_heading` = \"Open Requirement Questions\", and an `intro` that frames the page as agreeing on what the system must do before any design work begins.\n - `content`: an object containing `system_goals` and `actionable_items`. **`system_goals` MUST ALWAYS be passed** inside `content` so the backend always writes a page. Never omit it, even if every criterion and NFR is confirmed. `acceptance_criteria` and `nfrs` both live inside `system_goals`. (Do not pass `implementation_order` inside `content` — that is for epic surfaces, not a single explored task.)\n\n ```typescript\n interface ExploreTicketContent {\n system_goals?: {\n business_goal: string;\n desired_end_state: string;\n system_behavior: string;\n acceptance_criteria?: Array<{\n id: string; // e.g. \"AC-1\"; must be unique\n criterion: string; // what the system must do\n verification: string; // how we would confirm it holds\n status: \"confirmed\" | \"assumed\" | \"open\";\n }>;\n nfrs?: Array<{\n category: string;\n requirement: string;\n implication: string;\n status: \"confirmed\" | \"assumed\" | \"open\";\n }>;\n };\n actionable_items?: Array<{\n id: string; // e.g. \"R-1\"; a REQUIREMENT question, not a design choice\n question: string;\n why_it_matters: string;\n recommendation_explanation: string;\n options: string[]; // 2-4 candidate answers (no \"None of these\" or \"Ask about this\")\n option_consequences: string[]; // same length as options\n recommendation_index: number; // 0-based within options\n codebase_evidence?: string; // optional: assessment + file:line citations\n original_question?: string; // optional: only when item maps to a verbatim question\n }>;\n // clear_improvements: not used by this command — it captures requirements, not findings\n // implementation_order: for epic surfaces only — do NOT include for single task explorations\n // depends_on: hard prerequisites (titles/keys that must land first)\n // recommended_after: soft sequencing preferences, not hard blockers\n }\n ```\n\n Example call:\n ```json\n {\n \"ticket_key\": \"revoke-api-keys\",\n \"artifact_type\": \"pre_ticket_planning\",\n \"output_subdir\": \"explorations\",\n \"output_filename\": \"revoke-api-keys-requirements.html\",\n \"labels\": { \"title\": \"Requirements\", \"section_heading\": \"Open Requirement Questions\" },\n \"content\": {\n \"system_goals\": {\n \"business_goal\": \"Operators can cut off a leaked key immediately.\",\n \"desired_end_state\": \"Revocation is self-serve and takes effect at once.\",\n \"system_behavior\": \"Rejects revoked credentials without a restart.\",\n \"acceptance_criteria\": [\n { \"id\": \"AC-1\", \"criterion\": \"An operator who revokes a key sees the next request with it rejected.\", \"verification\": \"The following call to the protected route returns 401.\", \"status\": \"confirmed\" },\n { \"id\": \"AC-2\", \"criterion\": \"Revocation is recorded with actor and timestamp.\", \"verification\": \"An audit row names the operator and the revoked key id.\", \"status\": \"open\" }\n ],\n \"nfrs\": [\n { \"category\": \"security/privacy\", \"requirement\": \"The raw key is never logged on the revoke path.\", \"implication\": \"Log the key id, never the secret.\", \"status\": \"open\" }\n ]\n },\n \"actionable_items\": [\n {\n \"id\": \"R-1\",\n \"question\": \"Must revocation take effect immediately, or is eventual acceptable?\",\n \"why_it_matters\": \"Sets the hard bound AC-1 has to meet.\",\n \"recommendation_explanation\": \"A leaked key is an active incident; eventual leaves a usable window.\",\n \"options\": [\"Immediately (under 5s)\", \"Eventually (under 60s is acceptable)\"],\n \"option_consequences\": [\"AC-1 gains a 5s bound.\", \"AC-1 gains a 60s bound.\"],\n \"recommendation_index\": 0\n }\n ]\n }\n }\n ```\n\n4. **Handle the response `status`:**\n - `no_decisions_needed`: no page was written. This should not occur when `system_goals` is always passed. Skip Stage 6 entirely, tell the user there were no open requirements, and proceed to Stage 7 treating the Stage 3 framing as the settled criteria.\n - `decision_page_generated`: surface the returned `file_path` and proceed to Stage 6. **Always proceed to Stage 6 when `decision_page_generated` is returned**, regardless of `actionable_items_count`. A criteria-only page with zero cards still has stance controls that must be submitted.\n\nThis stage is non-blocking: if `generate_decision_page` fails, do not halt. **You MUST output a highly visible warning** (e.g. **⚠ WARNING: The requirements page could not be generated** in bold) explaining that generation failed and that the user should review the criteria in the markdown doc written in Stage 4 instead. Do not silently continue — the failure must be diagnosable from your output. Then ask the user to confirm the criteria in chat before proceeding to Stage 7.\n\n## Stage 6 — Ratify Requirements\n\nCapture the user's stances, settle the criteria, and fold the result into the doc. Nothing downstream may start until the criteria are agreed — this is the gate the whole command is built around.\n\n1. **Direct the user to the page.** Provide the `file_path` from Stage 5 and tell them to open it in their browser. Explain that they are agreeing on what the system must do — not how it will be built — that they can accept, question, or reject each criterion, and that they can ask questions in chat before submitting.\n\n2. **Q&A loop and commit signal.** Engage with each user message as either a commit or a discussion turn:\n - **Commit:** trim the full message and attempt to parse the entire trimmed message as JSON. Treat it as a commit only when the parsed value is an object with all three top-level fields: `ticket_key` (string), `decisions` (object), and `general_comment` (string). The first valid commit-shaped paste commits — do not over-validate the per-card fields. The page also submits `acceptance_criteria_feedback` and `nfr_feedback` objects, each keyed by criterion id or NFR category with a `stance` of `agreed`, `ask`, or `disagree` plus a `comment`.\n - **Discussion:** anything that is not commit-shaped JSON. Answer from the doc written in Stage 4 and from codebase lookups. If a JSON-shaped paste is missing one of the three required fields, say which field is missing rather than treating it as a freeform question.\n - **In-flight overrides:** when the user clearly changes an answer in chat (\"AC-2 is wrong\", \"go with eventual for R-1\") or gives new overarching guidance, record it as a working-memory override. On commit, the submitted JSON is the baseline and recorded overrides take precedence; post a one-line acknowledgement naming each overridden item before you rewrite the doc.\n\n3. **Resolve every \"ask\" (hard rule).** After accepting a commit, scan all three: any item in `decisions` where `choice === \"ask\"`, any entry in `acceptance_criteria_feedback` where `stance === \"ask\"`, and any entry in `nfr_feedback` where `stance === \"ask\"`. For each, present the relevant evidence and continue the discussion until the user gives an explicit answer, which you record as an override. Do not proceed while any `ask` remains unresolved — do not honor \"just skip those\".\n\n4. **Resolve every \"disagree\".** A disagree means the criterion is wrong as written. Work out with the user what it should say, restate it back, and get explicit agreement on the corrected wording. A rejected criterion is either rewritten or dropped — never carried forward as-is.\n\n5. **Settle the criteria and update the doc.** Rewrite the Acceptance Criteria, Goals & NFRs, and Open Questions sections of `{docs_dir}/explorations/{slug}.md` to the agreed set: fold in every correction, resolve each answered requirement question into the criterion it affects, promote settled criteria out of `open`, and weave `general_comment` in as overarching guidance. Set the doc's Status line to \"Requirements ratified\". Preserve all unaffected sections unchanged. **The settled criteria are now the contract** — every later stage is judged against them.\n\nThis stage is non-blocking: if the user never commits, leave the doc as written in Stage 4, tell them the requirements are unratified, and stop without forcing a decision. Do not proceed to a brainstorm or a design on unratified criteria.\n\n## Stage 7 — Brainstorm Gate\n\nThe criteria are ratified. Now assess honestly whether you know **how** to meet them — and offer to brainstorm when you do not.\n\n**Lean toward offering.** A brainstorm is cheap relative to committing the user to the wrong design, and this command prioritizes discovery over premature commitment. Do not wait for the user to ask for one.\n\n1. **Check the triggers.** Offer a brainstorm when **any** of these hold:\n - More than one materially different approach could satisfy a criterion, and the codebase evidence you gathered cannot separate them.\n - A criterion has no obvious implementation path in the existing code.\n - Meeting one criterion appears to trade off against another criterion or against an NFR (any tension noted in Stage 3 step 6, or created by a correction in Stage 6).\n - The work touches an area with no established pattern — Stage 1 found no precedent to follow.\n - Ratification materially changed the problem — the user tightened a bound, rejected a criterion, or added an obligation you had not framed.\n - Stage 2 research surfaced competing approaches with no clear winner.\n\n Do **not** offer when every ratified criterion maps cleanly onto a well-trodden pattern already used in this codebase and you can point to the precedent.\n\n2. **Ask for approval.** When a trigger fires, first summarize the uncertainty in 1-3 bullets — name the specific criteria at issue and what you cannot currently decide. Then ask exactly:\n\n ```\n Significant uncertainty about how to meet {AC ids}. Run a brainstorm before I draft the design? (y/N)\n ```\n\n Mention that a brainstorm polls for up to ~15 minutes before you ask, so the user is choosing with the cost in view.\n\n Treat an empty response, any negative response (`n`, `no`, or similar), or any ambiguous/unrecognized response as **decline** — do not guess intent. On decline, note in one line that the brainstorm was offered and declined, and proceed to Stage 8 on your own analysis. Never run a brainstorm without an explicit affirmative (`y` or `yes`).\n\n3. **Run it on approval.** Call `request_brainstorm` with:\n - `task_description`: the task, the **ratified** acceptance criteria and NFRs from Stage 6, and the specific uncertainty you summarized. Sent verbatim — this tool does not read from a file. State plainly that the criteria are settled and the brainstorm's job is to find how to meet them, not to revisit what they are.\n - `mode`: `technical`.\n - `wait_for_result`: `true`. `save_locally`: `true`.\n\n While it runs, tell the user it is polling and roughly how long it may take.\n\n4. **Fold the result into your analysis.** Carry the brainstorm's approaches, objections, and any option you had not considered into Stage 8. If the brainstorm argues a ratified criterion is unmeetable, do not silently drop it — raise it with the user in Stage 8 as an explicit conflict.\n\nIf the brainstorm fails or times out, note the failure visibly and proceed with your own analysis — a missing brainstorm degrades the design but does not invalidate it. This stage is non-blocking — always proceed to Stage 8.\n\n## Stage 8 — Propose Final Design\n\nNow describe how you would build it. **Do not generate a decision page for this stage.** The requirements page was the user's decision surface; the design is your proposal, written into the doc and discussed in chat. Generating a second page here would ask the user to ratify a solution, which is not what this command does.\n\n1. **Work out the design against the ratified criteria.** Consider the approaches you know plus anything the brainstorm surfaced. For each candidate, establish which criteria it satisfies and at what cost. An approach that cannot meet a ratified criterion is not a candidate — discard it and say why.\n\n2. **Resolve any tension explicitly.** Where meeting one criterion costs another, or costs an NFR, state which obligation your design privileges and what that costs the other. Do not let a tension pass silently.\n\n3. **Commit to a single proposed design.** You are recommending, not offering a menu. Name the approach, describe how it works, list the files to create or modify, and map each ratified criterion to the part of the design that satisfies it. Where you seriously considered an alternative, record it and why you rejected it — as history, not as an open choice.\n\n4. **Rewrite `{docs_dir}/explorations/{slug}.md`** so it reads as a finished proposal, not a mechanical append. Set the Status line to \"Design proposed\". Keep the ratified Acceptance Criteria and Goals & NFRs sections intact — they are the contract and must not drift — and add:\n\n```markdown\n## Approaches Considered\n\n{Each candidate, what it would mean, and why it was or was not chosen. Note which came from the brainstorm, if one ran. If no alternatives were seriously considered, state that and why the path was obvious.}\n\n## Proposed Design\n\n{The recommended approach in enough detail to implement: how it works, the files to create or modify, the sequence of work, and the risks. Reference specific files with file_path:line_number format.}\n\n## Criteria Coverage\n\n{Each ratified criterion mapped to the part of the design that satisfies it, and how it will be verified. Any criterion the design only partially meets must say so plainly.}\n```\n\n5. **Present the design in chat and invite pushback.** Summarize the proposal and state clearly that it is a proposal. If the user objects, revise the design — but if their objection actually changes what the system must do rather than how it is built, say so: that is a criteria change, and it means reopening the criteria rather than quietly bending the design around it.\n\nThis stage is non-blocking — always proceed to Stage 9 once the design is written, even if the user has not responded to it.\n\n## Stage 9 — Ticket Handoff\n\n1. **Assess readiness.** The work is ready to become a ticket when the criteria are ratified, the design is proposed, and no criterion is left unresolved or only partially covered. If something is still open, say what it is and recommend the follow-up that would close it rather than creating a ticket on a soft foundation:\n - A **wider brainstorm** (`request_brainstorm`) when the design would benefit from a broad review before implementation. If Stage 7 already ran one, only suggest another when something material changed since.\n - A **second opinion** (`second_opinion`) when a few specific contested points need an independent check.\n - **Web or deep research** (`request_deep_research`) when the design still rests on technical unknowns that need grounding.\n\n2. **Offer to create the ticket(s).** When the work is ready, ask exactly:\n\n ```\n Requirements ratified and design proposed. Create the ticket(s) now? (y/N)\n ```\n\n Treat an empty response, any negative response, or any ambiguous/unrecognized response as **decline** — do not guess intent. On decline, report that the exploration doc is the artifact and point at `/write-ticket` for later. Never create a ticket without an explicit affirmative (`y` or `yes`) — creation is irreversible.\n\n3. **Create on approval.** Use `create_ticket` (or `/write-ticket` for a larger draft), building the ticket from the doc: the ratified acceptance criteria become the ticket's acceptance criteria verbatim, and the proposed design becomes its implementation notes. Do not restate or reinterpret the criteria — they were ratified in that wording. Split into multiple tickets when the design has independently shippable slices; say why you split before you do.\n\nThis stage is non-blocking: if the user never answers, leave the doc as written in Stage 8 and stop without forcing a decision.\n\n## Final Report\n\nOn successful completion of all stages, display:\n\n> **Exploration Complete**\n>\n> **Prompt**: {first 80 characters of prompt}...\n> **Output**: {full path to the exploration doc}\n> **Requirements Page**: {full path to the generated requirements.html, or \"not generated\" when generation failed}\n> **Acceptance Criteria**: {count} ratified ({count} corrected by the user, {count} still open)\n> **Files Examined**: {count of key_files_examined}\n> **Research**: {count of web_searches} web searches, {count of research_queries} deep research queries, brainstorm {\"run\" | \"offered and declined\" | \"not needed\"}\n>\n> **Requirements**: {\"Ratified\" | \"Unratified — page not submitted\"}\n> **Design**: {\"Proposed\" | \"Not reached\"}\n> **Ticket(s)**: {\"Created: KEY-1, KEY-2\" | \"Declined — doc is the artifact\" | \"Not offered — work not ready\"}\n\nOn failure at any stage, stop immediately and report:\n- Which stage failed (by number and name)\n- The error details\n- Any partial results that were produced before the failure\n",
13
+ "explore-ticket.md": "Explore the codebase for a task, settle its acceptance criteria with the user, then propose a design that meets them.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\n`$ARGUMENTS` is a free-form prompt describing a task you want to accomplish and your goals for it. This is **not** a Jira ticket key — it is plain text describing the work.\n\nExecute all exploration and analysis directly in the main conversation. The user should see exploration progress as it happens.\n\nThis command runs strictly outside-in, and the order is the point:\n\n1. **Requirements first.** Establish what the system must do, how it must behave, and what standards it must meet — then get the user to ratify that on an interactive decision page. The page settles **requirements only**. It never asks the user to pick an implementation.\n2. **Then how.** Only once the criteria are ratified do you consider how to meet them, optionally with a brainstorm.\n3. **Then the design.** You describe the final proposed design yourself, in the exploration doc. There is no second decision page.\n4. **Then ticket(s).**\n\nNever invert this. A design proposed against unratified criteria is a guess, and an implementation choice presented before the criteria are settled asks the user to commit to a solution for a problem they have not yet agreed on.\n\nIf any critical stage fails, stop immediately and report which stage failed and why.\n\n## Stage 0 — Setup\n\n1. **Parse prompt**: Extract the prompt text from `$ARGUMENTS`. Trim any surrounding whitespace. If the prompt is empty or whitespace-only, stop immediately and display: `Usage: /explore-ticket <prompt describing your task and goals>`\n\n2. **Resolve docs directory**: Call the `get_docs_dir` MCP tool (no parameters). Store the returned path as `docs_dir`.\n\n3. **Generate output slug**: Create a kebab-case slug from the prompt — take the first 6-8 meaningful words, strip non-alphanumeric characters, lowercase, and truncate to 60 characters. The slug **must start with a letter** so it is a valid decision-page `ticket_key` in Stage 5 (`/^[A-Za-z][A-Za-z0-9_-]*$/`); if it would start with a digit or hyphen, prefix it with `exploration-`. If `{docs_dir}/explorations/{slug}.md` already exists, append a short timestamp suffix (e.g., `-1710000000`) — and fold that suffix **into the `slug` variable itself**, not just the filename, so that Stage 4 (the doc), Stage 5 (`ticket_key`, `output_filename`), and Stage 8 (the doc rewrite) all reference the same slug. The output file path is `{docs_dir}/explorations/{slug}.md`.\n\n4. **Initialize tracking**: Prepare to track `key_files_examined` (list of files read during exploration), `web_searches` (list of topics searched), and `research_queries` (list of deep research queries).\n\nIf this stage fails, stop immediately and report the error. Do not proceed to Stage 1.\n\n## Stage 1 — Codebase Exploration\n\nThis is the core discovery stage. Take your time — thorough exploration is more valuable than speed.\n\n1. **Analyze the prompt** to identify which areas of the codebase are relevant: route files, agent flows, database models, library utilities, LLM integration, MCP server, unit and E2E suites, etc.\n\n2. **Search for files** matching patterns related to the task (e.g., `api/routes/**/*.py`, `src/python/llms/agents/**/*.py`, `db/models/*.py`).\n\n3. **Search for content** — relevant function names, class names, patterns, and keywords across the codebase.\n\n4. **Read the most relevant files** in detail — understand existing implementations, conventions, and patterns that relate to the task.\n\n5. **Build a mental model** of:\n - What exists today that relates to the task\n - What patterns and conventions are used in similar features\n - What dependencies, data flows, and integration points are involved\n - What gaps or unknowns remain that need external research\n - Whether there is an established precedent for this kind of work, or none at all — Stage 7 depends on this judgement\n\nExplore to understand the problem and its constraints. Resist designing a solution while you read — you do not yet know what the system is required to do, and Stage 8 is where the design gets written.\n\n6. **Track all significant files** examined in `key_files_examined`.\n\nDo not rush this stage. When in doubt, read more code rather than less. Continue exploring until you have a solid understanding of the relevant code.\n\nThis stage is non-blocking — always proceed to Stage 2 regardless of what you find, since the exploration informs what research is needed.\n\n## Stage 2 — Research Unknowns\n\nBased on gaps identified in Stage 1, decide what research is needed. Apply these decision rules:\n\n- **No research needed**: The codebase exploration answered all questions. Skip directly to Stage 3.\n- **Web search**: For quick factual lookups — library API signatures, configuration syntax, small \"how to\" questions. Examples: \"FastAPI dependency injection with custom headers\", \"Alembic batch migration syntax\". Do web searches inline and capture relevant findings.\n- **Deep research** (via `request_deep_research` MCP tool): For large, multi-faceted unknowns that require synthesizing information from multiple sources. Examples: \"Best practices for implementing WebSocket connection pooling in Python asyncio\", \"Tradeoffs between different approaches to real-time notification delivery in FastAPI applications\". Only use deep research when the question genuinely needs a multi-source investigation.\n\n**If deep research is needed:**\n\n1. Call `request_deep_research` with `wait_for_result` set to `true`, `save_locally` set to `true`, a descriptive `query`, and `context` describing the Bridge API tech stack and the specific task.\n2. If deep research fails, note the failure and fall back to web searches for the same topic. Do NOT halt the pipeline.\n\nTrack all research performed in `research_queries` and `web_searches`.\n\nThis stage is non-blocking — failures degrade the quality of analysis but do not stop the command. Log a warning for any failed research and continue.\n\n## Stage 3 — Frame Acceptance Criteria\n\nEstablish what \"done and correct\" means. Everything in this stage is about the system's obligations, not its implementation. Do not name a technical approach here — that is Stage 8's job, and it does not happen until the user has ratified this framing.\n\n1. **State the frame plainly (required).**\n - **Business goal** — the value this work delivers and why it matters.\n - **Desired end-state** — the concrete state the system should reach once this work is done.\n - **System behavior** — how the system must behave to complete its task (the quality attributes in prose, not a feature list).\n\n2. **Derive the acceptance criteria — what the system must do (required).** Write 3-8 criteria. Each one gets:\n - An `id` (`AC-1`, `AC-2`, …).\n - A `criterion` — a single obligation stated concretely enough to be checked. Write it as observable behavior (\"an operator who revokes a key sees the next request rejected\"), not as a task (\"add a revocation endpoint\").\n - A `verification` — how we would confirm it holds. Name the observable signal: a response code on a specific route, a row state, a log line, a rendered element, a user-visible outcome. **A criterion nobody can check is not yet a criterion** — sharpen it or drop it.\n - A `status`, using the rubric in step 4.\n\n Cover the failure and edge behavior, not just the happy path. If the work changes something that already exists, at least one criterion should pin down what must **not** regress.\n\n3. **Identify the non-functional requirements — the standards the system must meet (required).** Consider every one of these canonical NFR categories and include the ones that genuinely apply (omit the rest): security/privacy, performance/latency, reliability/failure-modes, observability/auditability, accessibility/UX, data-integrity/migration, compatibility, operability/config, compliance/SOC2, rollout/reversibility. For each NFR you include, write its `requirement` and its `implication` (what it changes about the implementation) — an NFR with no concrete implication is boilerplate; drop it.\n\n4. **Classify every acceptance criterion and every NFR** with this rubric: `confirmed` only if explicitly stated or observable in code; `assumed` only if a low-risk, reversible default; `open` if it touches architecture, the data model, security, user-visible behavior, migration, or irreversible creation and is not settled. When a criterion or an NFR is genuinely unclear, prefer marking it `open` and asking. Clear criteria make everything downstream more accurate, so surfacing an unclear one is a success, not a delay.\n\n5. **Frame the open requirement questions.** Where a requirement is unsettled **and** has discrete candidate answers, express it as a question the user can answer by clicking (e.g. \"Must revocation take effect immediately, or is eventual acceptable?\"). These become cards in Stage 5. They are questions about *what the system must do* — never about how to build it. If a question has no discrete answers, leave it as prose in the doc instead.\n\n6. **Sanity-check the frame against itself.** Do any two criteria conflict? Does a criterion conflict with an NFR (e.g. an auditability requirement against a latency budget)? Note every tension you find — Stage 7 treats these as a brainstorm trigger, and Stage 8 must resolve them explicitly rather than quietly favouring one side.\n\nThis stage is inline analysis — no tool calls required. This stage is non-blocking — always proceed to Stage 4.\n\n## Stage 4 — Write Requirements Draft\n\nWrite what you know so far to disk, so the user has something to read alongside the decision page. The design is deliberately absent — it does not exist yet.\n\n1. Create the `explorations/` directory under `docs_dir` if it does not exist.\n\n2. Write the exploration document to the slug-based path determined in Stage 0 (`{docs_dir}/explorations/{slug}.md`) with this structure:\n\n```markdown\n# Exploration: {concise summary of the prompt}\n\n**Date**: {current date}\n**Prompt**: {original prompt text}\n**Status**: Requirements drafted — awaiting ratification\n\n## Context\n\n{Brief description of the task and what areas of the codebase are relevant.}\n\n## Acceptance Criteria\n\n{The criteria from Stage 3 — what the system must do. One entry per criterion: its id, the criterion itself, how it is verified, and its status (confirmed / assumed / open).}\n\n## Goals & NFRs\n\n{The business goal, desired end-state, and required system behavior from Stage 3. Then the non-functional requirements — the standards the system must meet: each with its category, requirement, implication, and status (confirmed / assumed / open). Note any tension between criteria or between a criterion and an NFR.}\n\n## Open Questions\n\n{Requirement questions that are still unsettled. Mark which ones are going onto the decision page as cards and which are open-ended prose.}\n\n## Codebase Findings\n\n{Key discoveries from Stage 1. What exists today, what patterns are used, what the relevant code paths look like. Reference specific files and functions with file_path:line_number format.}\n\n## Research Findings\n\n{Findings from web searches and deep research, if any. If no research was performed, state \"No external research was needed.\"}\n\n## Key Files\n\n{Bulleted list of the most important files examined, with one-line descriptions of their relevance.}\n```\n\nDo not add a design, an implementation plan, or a recommendation to this draft. Stage 8 adds those once the criteria are settled.\n\nIf the file cannot be written, stop immediately and report the failure.\n\n## Stage 5 — Generate Requirements Decision Page\n\nTurn the Stage 3 framing into an interactive HTML decision page so the user can ratify the requirements by clicking. **This page settles requirements only.** It must not contain a single implementation option — the user is agreeing on what the system must do, not choosing how to build it.\n\n1. **Map the acceptance criteria to `acceptance_criteria`.** Each entry has `id`, `criterion`, `verification`, and `status`. Ids must be unique — a duplicate id is rejected, because the id is the key the page reports the user's stance under. Every criterion renders with an Agreed / Ask about this / Disagree control, so pass all of them, not only the open ones. Pass the NFRs the same way under `nfrs`.\n\n2. **Map each open requirement question from Stage 3 step 5 to an actionable item.** Each entry has:\n - `id`: a short stable id, e.g. `R-1`, `R-2`.\n - `question`: the requirement question.\n - `options`: the 2-4 candidate answers (string array). Do **not** include \"None of these\" or \"Ask about this\" — the renderer auto-appends both.\n - `option_consequences`: what each answer would mean for the criteria, **parallel to and the same length as** `options`.\n - `why_it_matters`: the concrete impact line.\n - `recommendation_explanation`: why the recommended answer is best.\n - `recommendation_index`: the 0-based index of the recommended answer (must be within `options`).\n - `codebase_evidence` (optional): the Assessment paragraph plus `file:line` citations, shown collapsed.\n\n **These cards are requirement questions, never implementation choices.** \"Must revocation be immediate or is eventual acceptable?\" is a valid card. \"Should we use a short-TTL cache or pub/sub invalidation?\" is not — it is a solution, it belongs to Stage 8, and putting it here defeats the purpose of the page. If you cannot phrase a card without naming a mechanism, it is not a requirement question. When there are no such questions, pass an empty array — a criteria-only page is expected and renders correctly.\n\n3. **Call `generate_decision_page`** with routing fields at the root and all heavy arrays nested under `content`:\n - `artifact_type`: `pre_ticket_planning` (renders the acceptance-criteria and goals panel above any cards).\n - `ticket_key`: the Stage 0 `slug` (a non-Jira slug is fine — it must start with a letter and contain only letters, digits, hyphens, or underscores).\n - `output_subdir`: `explorations` (so the page lands beside the markdown doc).\n - `output_filename`: `{slug}-requirements.html`.\n - `labels`: requirements-flavored overrides, e.g. `title` = \"Requirements\", `section_heading` = \"Open Requirement Questions\", and an `intro` that frames the page as agreeing on what the system must do before any design work begins.\n - `content`: an object containing `system_goals` and `actionable_items`. **`system_goals` MUST ALWAYS be passed** inside `content` so the backend always writes a page. Never omit it, even if every criterion and NFR is confirmed. `acceptance_criteria` and `nfrs` both live inside `system_goals`. (Do not pass `implementation_order` inside `content` — that is for epic surfaces, not a single explored task.)\n\n ```typescript\n interface ExploreTicketContent {\n system_goals?: {\n business_goal: string;\n desired_end_state: string;\n system_behavior: string;\n acceptance_criteria?: Array<{\n id: string; // e.g. \"AC-1\"; must be unique\n criterion: string; // what the system must do\n verification: string; // how we would confirm it holds\n status: \"confirmed\" | \"assumed\" | \"open\";\n }>;\n nfrs?: Array<{\n category: string;\n requirement: string;\n implication: string;\n status: \"confirmed\" | \"assumed\" | \"open\";\n }>;\n };\n actionable_items?: Array<{\n id: string; // e.g. \"R-1\"; a REQUIREMENT question, not a design choice\n question: string;\n why_it_matters: string;\n recommendation_explanation: string;\n options: string[]; // 2-4 candidate answers (no \"None of these\" or \"Ask about this\")\n option_consequences: string[]; // same length as options\n recommendation_index: number; // 0-based within options\n codebase_evidence?: string; // optional: assessment + file:line citations\n original_question?: string; // optional: only when item maps to a verbatim question\n }>;\n // clear_improvements: not used by this command — it captures requirements, not findings\n // implementation_order: for epic surfaces only — do NOT include for single task explorations\n // depends_on: hard prerequisites (titles/keys that must land first)\n // recommended_after: soft sequencing preferences, not hard blockers\n }\n ```\n\n Example call:\n ```json\n {\n \"ticket_key\": \"revoke-api-keys\",\n \"artifact_type\": \"pre_ticket_planning\",\n \"output_subdir\": \"explorations\",\n \"output_filename\": \"revoke-api-keys-requirements.html\",\n \"labels\": { \"title\": \"Requirements\", \"section_heading\": \"Open Requirement Questions\" },\n \"content\": {\n \"system_goals\": {\n \"business_goal\": \"Operators can cut off a leaked key immediately.\",\n \"desired_end_state\": \"Revocation is self-serve and takes effect at once.\",\n \"system_behavior\": \"Rejects revoked credentials without a restart.\",\n \"acceptance_criteria\": [\n { \"id\": \"AC-1\", \"criterion\": \"An operator who revokes a key sees the next request with it rejected.\", \"verification\": \"The following call to the protected route returns 401.\", \"status\": \"confirmed\" },\n { \"id\": \"AC-2\", \"criterion\": \"Revocation is recorded with actor and timestamp.\", \"verification\": \"An audit row names the operator and the revoked key id.\", \"status\": \"open\" }\n ],\n \"nfrs\": [\n { \"category\": \"security/privacy\", \"requirement\": \"The raw key is never logged on the revoke path.\", \"implication\": \"Log the key id, never the secret.\", \"status\": \"open\" }\n ]\n },\n \"actionable_items\": [\n {\n \"id\": \"R-1\",\n \"question\": \"Must revocation take effect immediately, or is eventual acceptable?\",\n \"why_it_matters\": \"Sets the hard bound AC-1 has to meet.\",\n \"recommendation_explanation\": \"A leaked key is an active incident; eventual leaves a usable window.\",\n \"options\": [\"Immediately (under 5s)\", \"Eventually (under 60s is acceptable)\"],\n \"option_consequences\": [\"AC-1 gains a 5s bound.\", \"AC-1 gains a 60s bound.\"],\n \"recommendation_index\": 0\n }\n ]\n }\n }\n ```\n\n4. **Handle the response `status`:**\n - `no_decisions_needed`: no page was written. This should not occur when `system_goals` is always passed. Skip Stage 6 entirely, tell the user there were no open requirements, and proceed to Stage 7 treating the Stage 3 framing as the settled criteria.\n - `decision_page_generated`: surface the returned `file_path` and proceed to Stage 6. **Always proceed to Stage 6 when `decision_page_generated` is returned**, regardless of `actionable_items_count`. A criteria-only page with zero cards still has stance controls that must be submitted.\n\nThis stage is non-blocking: if `generate_decision_page` fails, do not halt. **You MUST output a highly visible warning** (e.g. **⚠ WARNING: The requirements page could not be generated** in bold) explaining that generation failed and that the user should review the criteria in the markdown doc written in Stage 4 instead. Do not silently continue — the failure must be diagnosable from your output. Then ask the user to confirm the criteria in chat before proceeding to Stage 7.\n\n## Stage 6 — Ratify Requirements\n\nCapture the user's stances, settle the criteria, and fold the result into the doc. Nothing downstream may start until the criteria are agreed — this is the gate the whole command is built around.\n\n1. **Direct the user to the page.** Provide the `file_path` from Stage 5 and tell them to open it in their browser. Explain that they are agreeing on what the system must do — not how it will be built — that they can accept, question, or reject each criterion, and that they can ask questions in chat before submitting.\n\n2. **Q&A loop and commit signal.** Engage with each user message as either a commit or a discussion turn:\n - **Commit:** trim the full message and attempt to parse the entire trimmed message as JSON. Treat it as a commit only when the parsed value is an object with all three top-level fields: `ticket_key` (string), `decisions` (object), and `general_comment` (string). The first valid commit-shaped paste commits — do not over-validate the per-card fields. The page also submits `acceptance_criteria_feedback` and `nfr_feedback` objects, each keyed by criterion id or NFR category with a `stance` of `agreed`, `ask`, or `disagree` plus a `comment`.\n - **Discussion:** anything that is not commit-shaped JSON. Answer from the doc written in Stage 4 and from codebase lookups. If a JSON-shaped paste is missing one of the three required fields, say which field is missing rather than treating it as a freeform question.\n - **In-flight overrides:** when the user clearly changes an answer in chat (\"AC-2 is wrong\", \"go with eventual for R-1\") or gives new overarching guidance, record it as a working-memory override. On commit, the submitted JSON is the baseline and recorded overrides take precedence; post a one-line acknowledgement naming each overridden item before you rewrite the doc.\n\n3. **Resolve every \"ask\" (hard rule).** After accepting a commit, scan all three: any item in `decisions` where `choice === \"ask\"`, any entry in `acceptance_criteria_feedback` where `stance === \"ask\"`, and any entry in `nfr_feedback` where `stance === \"ask\"`. For each, present the relevant evidence and continue the discussion until the user gives an explicit answer, which you record as an override. Do not proceed while any `ask` remains unresolved — do not honor \"just skip those\".\n\n4. **Resolve every \"disagree\".** A disagree means the criterion is wrong as written. Work out with the user what it should say, restate it back, and get explicit agreement on the corrected wording. A rejected criterion is either rewritten or dropped — never carried forward as-is.\n\n5. **Settle the criteria and update the doc.** Rewrite the Acceptance Criteria, Goals & NFRs, and Open Questions sections of `{docs_dir}/explorations/{slug}.md` to the agreed set: fold in every correction, resolve each answered requirement question into the criterion it affects, promote settled criteria out of `open`, and weave `general_comment` in as overarching guidance. Set the doc's Status line to \"Requirements ratified\". Preserve all unaffected sections unchanged. **The settled criteria are now the contract** — every later stage is judged against them.\n\nThis stage is non-blocking: if the user never commits, leave the doc as written in Stage 4, tell them the requirements are unratified, and stop without forcing a decision. Do not proceed to a brainstorm or a design on unratified criteria.\n\n## Stage 7 — Brainstorm Gate\n\nThe criteria are ratified. Now assess honestly whether you know **how** to meet them — and offer to brainstorm when you do not.\n\n**Lean toward offering.** A brainstorm is cheap relative to committing the user to the wrong design, and this command prioritizes discovery over premature commitment. Do not wait for the user to ask for one.\n\n1. **Check the triggers.** Offer a brainstorm when **any** of these hold:\n - More than one materially different approach could satisfy a criterion, and the codebase evidence you gathered cannot separate them.\n - A criterion has no obvious implementation path in the existing code.\n - Meeting one criterion appears to trade off against another criterion or against an NFR (any tension noted in Stage 3 step 6, or created by a correction in Stage 6).\n - The work touches an area with no established pattern — Stage 1 found no precedent to follow.\n - Ratification materially changed the problem — the user tightened a bound, rejected a criterion, or added an obligation you had not framed.\n - Stage 2 research surfaced competing approaches with no clear winner.\n\n Do **not** offer when every ratified criterion maps cleanly onto a well-trodden pattern already used in this codebase and you can point to the precedent.\n\n2. **Ask for approval.** When a trigger fires, first summarize the uncertainty in 1-3 bullets — name the specific criteria at issue and what you cannot currently decide. Then ask exactly:\n\n ```\n Significant uncertainty about how to meet {AC ids}. Run a brainstorm before I draft the design? (y/N)\n ```\n\n Mention that a brainstorm polls for up to ~15 minutes before you ask, so the user is choosing with the cost in view.\n\n Treat an empty response, any negative response (`n`, `no`, or similar), or any ambiguous/unrecognized response as **decline** — do not guess intent. On decline, note in one line that the brainstorm was offered and declined, and proceed to Stage 8 on your own analysis. Never run a brainstorm without an explicit affirmative (`y` or `yes`).\n\n3. **Run it on approval.** Call `request_council` with:\n - `task_description`: the task, the **ratified** acceptance criteria and NFRs from Stage 6, and the specific uncertainty you summarized. Sent verbatim — this tool does not read from a file. State plainly that the criteria are settled and the brainstorm's job is to find how to meet them, not to revisit what they are.\n - `mode`: `technical`.\n - `wait_for_result`: `true`. `save_locally`: `true`.\n\n While it runs, tell the user it is polling and roughly how long it may take.\n\n4. **Fold the result into your analysis.** Carry the brainstorm's approaches, objections, and any option you had not considered into Stage 8. If the brainstorm argues a ratified criterion is unmeetable, do not silently drop it — raise it with the user in Stage 8 as an explicit conflict.\n\nIf the brainstorm fails or times out, note the failure visibly and proceed with your own analysis — a missing brainstorm degrades the design but does not invalidate it. This stage is non-blocking — always proceed to Stage 8.\n\n## Stage 8 — Propose Final Design\n\nNow describe how you would build it. **Do not generate a decision page for this stage.** The requirements page was the user's decision surface; the design is your proposal, written into the doc and discussed in chat. Generating a second page here would ask the user to ratify a solution, which is not what this command does.\n\n1. **Work out the design against the ratified criteria.** Consider the approaches you know plus anything the brainstorm surfaced. For each candidate, establish which criteria it satisfies and at what cost. An approach that cannot meet a ratified criterion is not a candidate — discard it and say why.\n\n2. **Resolve any tension explicitly.** Where meeting one criterion costs another, or costs an NFR, state which obligation your design privileges and what that costs the other. Do not let a tension pass silently.\n\n3. **Commit to a single proposed design.** You are recommending, not offering a menu. Name the approach, describe how it works, list the files to create or modify, and map each ratified criterion to the part of the design that satisfies it. Where you seriously considered an alternative, record it and why you rejected it — as history, not as an open choice.\n\n4. **Rewrite `{docs_dir}/explorations/{slug}.md`** so it reads as a finished proposal, not a mechanical append. Set the Status line to \"Design proposed\". Keep the ratified Acceptance Criteria and Goals & NFRs sections intact — they are the contract and must not drift — and add:\n\n```markdown\n## Approaches Considered\n\n{Each candidate, what it would mean, and why it was or was not chosen. Note which came from the brainstorm, if one ran. If no alternatives were seriously considered, state that and why the path was obvious.}\n\n## Proposed Design\n\n{The recommended approach in enough detail to implement: how it works, the files to create or modify, the sequence of work, and the risks. Reference specific files with file_path:line_number format.}\n\n## Criteria Coverage\n\n{Each ratified criterion mapped to the part of the design that satisfies it, and how it will be verified. Any criterion the design only partially meets must say so plainly.}\n```\n\n5. **Present the design in chat and invite pushback.** Summarize the proposal and state clearly that it is a proposal. If the user objects, revise the design — but if their objection actually changes what the system must do rather than how it is built, say so: that is a criteria change, and it means reopening the criteria rather than quietly bending the design around it.\n\nThis stage is non-blocking — always proceed to Stage 9 once the design is written, even if the user has not responded to it.\n\n## Stage 9 — Ticket Handoff\n\n1. **Assess readiness.** The work is ready to become a ticket when the criteria are ratified, the design is proposed, and no criterion is left unresolved or only partially covered. If something is still open, say what it is and recommend the follow-up that would close it rather than creating a ticket on a soft foundation:\n - A **wider brainstorm** (`request_council`) when the design would benefit from a broad review before implementation. If Stage 7 already ran one, only suggest another when something material changed since.\n - A **second opinion** (`second_opinion`) when a few specific contested points need an independent check.\n - **Web or deep research** (`request_deep_research`) when the design still rests on technical unknowns that need grounding.\n\n2. **Offer to create the ticket(s).** When the work is ready, ask exactly:\n\n ```\n Requirements ratified and design proposed. Create the ticket(s) now? (y/N)\n ```\n\n Treat an empty response, any negative response, or any ambiguous/unrecognized response as **decline** — do not guess intent. On decline, report that the exploration doc is the artifact and point at `/write-ticket` for later. Never create a ticket without an explicit affirmative (`y` or `yes`) — creation is irreversible.\n\n3. **Create on approval.** Use `create_ticket` (or `/write-ticket` for a larger draft), building the ticket from the doc: the ratified acceptance criteria become the ticket's acceptance criteria verbatim, and the proposed design becomes its implementation notes. Do not restate or reinterpret the criteria — they were ratified in that wording. Split into multiple tickets when the design has independently shippable slices; say why you split before you do.\n\nThis stage is non-blocking: if the user never answers, leave the doc as written in Stage 8 and stop without forcing a decision.\n\n## Final Report\n\nOn successful completion of all stages, display:\n\n> **Exploration Complete**\n>\n> **Prompt**: {first 80 characters of prompt}...\n> **Output**: {full path to the exploration doc}\n> **Requirements Page**: {full path to the generated requirements.html, or \"not generated\" when generation failed}\n> **Acceptance Criteria**: {count} ratified ({count} corrected by the user, {count} still open)\n> **Files Examined**: {count of key_files_examined}\n> **Research**: {count of web_searches} web searches, {count of research_queries} deep research queries, brainstorm {\"run\" | \"offered and declined\" | \"not needed\"}\n>\n> **Requirements**: {\"Ratified\" | \"Unratified — page not submitted\"}\n> **Design**: {\"Proposed\" | \"Not reached\"}\n> **Ticket(s)**: {\"Created: KEY-1, KEY-2\" | \"Declined — doc is the artifact\" | \"Not offered — work not ready\"}\n\nOn failure at any stage, stop immediately and report:\n- Which stage failed (by number and name)\n- The error details\n- Any partial results that were produced before the failure\n",
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: **2**. 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 **capability report** derived from a fresh read-after-write manifest read.\nThe server owns all skip-if-set, conflict, and confirmation semantics — this command never makes its\nown skip-if-set decisions — and the server owns all tool locked/unlocked membership; this command\nformats the server's contract and never recomputes it from prose.\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 and Stage 9 are SKIPPED and the single closing interaction is the index-consent question the\nspawn prompt owns. When you invoke `/install-bridge` directly (manual invocation), Stages 8 and 9\nrun 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`, `locked_tools`, `unlocked_tools`) — but ignore those here; the accurate\n capability status is the post-apply read in Stage 7.\n4. Compare the manifest's `command_contract_version` to this command's contract version (2, 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 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.\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 current capability status\n\nAfter the bucket summary, call the `get_install_manifest` MCP tool ONCE MORE. This post-apply read\nreflects the configuration you just wrote, so its capability fields are current (the Stage-2 read was\npre-apply and is stale for this purpose). This read does not need the snapshot token. Use ONLY this\npost-write response for the capability report below.\n\nThe response carries: the `integrations` checklist (each item `label`, `is_configured`,\n`required_for`, `configure_in`), the separate `configured` / `learned` / `indexed` readiness values,\nand the server-computed `locked_tools` / `unlocked_tools` arrays. Each tool entry is exactly\n`{tool, effect, missing, semantics}`: `effect` is `BLOCK` (unavailable) or `DEGRADE` (usable now,\nbut without codebase context); `missing` lists the server-computed dependency identifiers (integration\nids such as `github_app` / `vcs_access_token`, and `code_index`); `semantics` is `all_of` or `any_of`\nand you MUST preserve it verbatim — never recompute membership yourself, and cite\n`docs/mcp-tool-integrations.md` only for the human explanation of a gate, never to recalculate it.\n\nIf the post-write response has no capability fields at all (no `integrations` / `locked_tools` /\n`unlocked_tools` keys, e.g. the additive enrichment was omitted), print exactly:\n`No capability status is available yet; configuration can still continue.` and skip the five sections.\n\nOtherwise render exactly these five sections, in this order, with these exact headings:\n\n**Connected ✓**\n\n- List each configured integration's `label` from the post-write `integrations` checklist, with a\n restrained `✓` marker. (Do not let the `✓` markers dominate the report.)\n\n**Not yet connected ✗**\n\n- List each unconfigured integration: its `label`, its `required_for` items, and the exact\n `configure_in` pointer. Do NOT include `setup_instructions` content — the pointer is the only\n configuration direction you emit. The pointer is per-integration and is NOT always the setup UI:\n `github_app` points at the terminal command `npx -y @bridge_gpt/mcp-server@latest connect-github\n --repo <repo_name>`, while Jira, `vcs_access_token`, `vcs_webhook`, and SFCC point at the setup UI.\n Emit whatever the server sent, verbatim — never rewrite a command pointer into \"the setup UI\".\n STRICT INVARIANT: you DIRECT the human to that pointer; you never ask for, accept, echo, or\n transport an integration credential (API token, access token, webhook secret) in any form. This is\n unchanged for GitHub: the connect-github command authenticates the human to GitHub in their own\n browser, and no GitHub credential ever reaches Bridge or an agent.\n\n**Tools you can use now**\n\n- Render each `unlocked_tools` entry with an explicit `BLOCK` or `DEGRADE` text label (do not rely on\n color). Describe a `DEGRADE` tool as \"available with reduced/no codebase context\" — never as failed\n or unavailable. Entries here with a non-empty `missing` list are still usable; state the caveat.\n\n**Tools you'll unlock**\n\n- Group `locked_tools` by each missing gating integration so the human can scan by \"what would I\n configure to unlock these\". Preserve the server's `all_of` / `any_of` semantics in plain text, e.g.\n \"requires VCS and a successful code index\" (`all_of` with `code_index`) or \"requires GitHub App or\n VCS access token\" (`any_of`). A tool with multiple missing integrations may appear under more than\n one group, but keep its complete server-provided relationship intact. Cite\n `docs/mcp-tool-integrations.md` briefly for each gate's human \"why\" — but do not recompute membership\n from it.\n\n**Recommended next step + why**\n\n- Make this section visually strongest through ordering and concise wording. Choose the single most\n valuable next action using this deterministic priority based only on the server output:\n 1. If any `locked_tools` entry is missing a VCS integration (`github_app` / `vcs_access_token`),\n recommend connecting VCS first, using that integration's own `configure_in` pointer verbatim\n (for `github_app` that is the `connect-github` terminal command, not the setup UI).\n 2. Else if any `locked_tools` entry is missing `code_index`, recommend running repository indexing\n (`/parse-repository`) next.\n 3. Else if `learned` is false, recommend running `/learn-repository` to populate the deeper\n instruction-tier configuration.\n- If `indexed` is `null` (unknown), include this exact warning:\n `Index status could not be confirmed—check again before relying on codebase-grounded tools.`\n\n## Stage 8 — Offer the next steps\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it); the\nspawn prompt owns the single closing index-consent question there. On direct manual `/install-bridge`\ninvocation, 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. After `/learn-repository` completes (or if the human declines it), offer to start **repository\n indexing**: ask ONE consent question (\"Start repository indexing now? It runs as a background job\n and makes the codebase searchable for Bridge API's agents.\"). On yes, call the `parse_repository`\n MCP tool once. Report that the job was QUEUED and that progress can be checked with\n `get_parse_status` (or `/check-parse-status`) — do NOT poll it to completion in this session.\n Indexing is deliberately last so the applied `exclude_directories` / `custom_directories` values\n scope it correctly. If no human response can be obtained (non-interactive session), skip indexing\n and list it as a pending next step in the final report — never start it without consent.\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 index-consent question the spawn prompt owns remains 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## 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 five-section\ncapability report (Connected ✓ / Not yet connected ✗ / Tools you can use now / Tools you'll unlock /\nRecommended next step + why) 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), and\nthe recommended next step.\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: **4**. 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 **capability report** derived from a fresh read-after-write manifest read.\nThe server owns all skip-if-set, conflict, and confirmation semantics — this command never makes its\nown skip-if-set decisions — and the server owns the complete tool catalog, its grouping and ordering,\nand every gate and dependency relationship; this command formats the server's contract and never\nrecomputes it from prose.\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 index-consent\nquestion the spawn prompt owns. When you invoke `/install-bridge` directly (manual invocation),\nStages 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`, `locked_tools`, `unlocked_tools`) — but ignore those\n here; the accurate capability status is the post-apply read in Stage 7. `tool_capabilities` is the\n COMPLETE catalog-backed report field (one entry per registered MCP tool, grouped and ordered by the\n server); `locked_tools` / `unlocked_tools` are LEGACY compatibility data covering only the VCS/index\n policy cases and are NOT the tool inventory.\n4. Compare the manifest's `command_contract_version` to this command's contract version (4, 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 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.\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 current capability status\n\nAfter the bucket summary, call the `get_install_manifest` MCP tool ONCE MORE. This post-apply read\nreflects the configuration you just wrote, so its capability fields are current (the Stage-2 read was\npre-apply and is stale for this purpose). This read does not need the snapshot token. Use ONLY this\npost-write response for the capability report below.\n\nThe response carries:\n\n- the `integrations` checklist — each item has `label`, `is_configured`, `required_for`,\n `configure_in`, and MAY have `optional_components` (a list of optional, non-gating add-ons nested\n under that integration, each with `id`, `label`, `is_configured`, `required_for`, `configure_in`,\n and `gating: false`);\n- the separate `configured` / `learned` / `indexed` readiness values;\n- `tool_capabilities` — the COMPLETE catalog-backed collection. It is an ordered array of groups, each\n `{id, name, description, tools}`. Each tool is `{tool, display_name, description, group, profile,\n availability, availability_text, effect, missing, semantics, variants}`, one entry per registered MCP\n tool, keyed by physical tool id;\n- `locked_tools` / `unlocked_tools` — LEGACY compatibility arrays covering only the VCS/index policy\n cases, keyed by policy-case id. They are NOT the tool inventory and you do not render them.\n\nServer authority: the server owns catalog membership, grouping, ordering, gates, and dependency\nrelationships. Never recompute any of them, and never derive them from `docs/mcp-tool-integrations.md`\nor any other documentation — cite that file only for a human explanation of a gate's \"why\".\n\nIf the post-write response has no capability fields at all (no `integrations` / `tool_capabilities`\nkeys, e.g. the additive enrichment was omitted), print exactly:\n`No capability status is available yet; configuration can still continue.` and skip the five sections.\n\nOtherwise, open with a short plain-language framing before the first section: explain that Bridge\nconnects the user's systems (their tracker, their code host, their platform) to their local code\neditor, and that connecting more of those systems unlocks richer capabilities. Then render exactly\nthese five sections, in this order, with these exact headings:\n\n**Connected ✓**\n\n- List each configured integration's `label` from the post-write `integrations` checklist, with a\n restrained `✓` marker. (Do not let the `✓` markers dominate the report.)\n- If a listed integration has `optional_components`, list each component beneath its parent as a\n sub-item, and describe it as optional and not required for the parent to work. A component with\n `gating: false` NEVER blocks anything: it is not a separate integration, it does not belong in the\n top-level list, and its state must not change how you describe its parent.\n\n**Not yet connected ✗**\n\n- List each unconfigured integration: its `label`, its `required_for` items, and the exact\n `configure_in` pointer. Do NOT include `setup_instructions` content — the pointer is the only\n configuration direction you emit. Apply the same `optional_components` rule as above.\n- The pointer is per-integration and is NOT always the setup UI. Emit whatever the server sent,\n VERBATIM: `github_app` points at the terminal command `npx -y @bridge_gpt/mcp-server@latest\n connect-github --repo <repo_name>`; `sfcc` points at the guide `docs/install/sfcc-integration.md`;\n Jira and `vcs_access_token` point at the setup UI. Never rewrite a command pointer into \"the setup\n UI\", and never replace GitHub's command with a guide.\n- STRICT INVARIANT: you DIRECT the human to that pointer; you never ask for, accept, echo, or\n transport an integration credential (Jira, GitHub, VCS, webhook, or SFCC — API token, access token,\n access key, webhook secret) in any form. This is unchanged for GitHub: the connect-github command\n authenticates the human to GitHub in their own browser, and no GitHub credential ever reaches Bridge\n or an agent. The SFCC pointer is a guide the human follows themselves — it is never an invitation to\n hand you credentials.\n\n**Tools you can use now**\n\n- Render from `tool_capabilities`, using the server's group order and, within each group, the server's\n tool order. Show each group's `name`, then each tool's `display_name`, its one-sentence\n `description`, and its `availability_text` exactly as provided.\n- Include here every tool whose `availability` is `available_now`, `available_with_less_context`,\n `profile_required`, or `varies_by_variant`.\n- Describe an `available_with_less_context` tool as available now with less codebase context — never\n as failed or unavailable.\n- For a `profile_required` tool, emit the server's neutral profile wording as given. Do NOT claim the\n profile is or is not registered locally: the server cannot observe that, so neither can you.\n- A `varies_by_variant` tool belongs here because at least one of its options is usable now. Render\n its variants beneath it and rely on each variant's own `availability_text` for accuracy — do NOT\n describe the whole tool as blocked, and do NOT describe it as fully available. (This is a common\n state, not a corner case: `create_doc` reports it whenever VCS is connected but the repository is\n not yet indexed, since `tdd` needs the index while `fsd`/`prd` do not.)\n- If a tool has a non-empty `variants` array, render the variants as sub-items BENEATH that one tool,\n each with its `label` and its own `availability_text`. Variants are options of a single tool\n (`create_doc`'s tdd/fsd/prd, `request_council`'s modes) — never present them as separately\n registered tools, and never invent an id like `create_doc:tdd`.\n- NEVER emit `BLOCK` or `DEGRADE`. The `effect` field is internal metadata that remains in the\n payload for compatibility; it is not for display. `availability_text` is what a human reads.\n\n**Tools you'll unlock**\n\n- Render every tool whose `availability` is `available_after_dependencies`, in the same server-provided\n grouping and order, each with its `display_name`, `description`, and `availability_text`. Where a\n tool's `variants` differ, show the variants beneath it so the user can see which options are already\n usable.\n- The `availability_text` already names the connection needed in plain language, including \"or\"\n relationships (an unknown VCS provider yields \"the GitHub App or a VCS access token\") and the\n separately-required repository index. Emit it as given rather than re-deriving it from `missing` or\n `semantics`.\n- Cite `docs/mcp-tool-integrations.md` briefly for a gate's human \"why\" — but never recompute\n membership from it.\n\n**Recommended next step + why**\n\n- Make this section visually strongest through ordering and concise wording. Choose the single most\n valuable next action using this deterministic priority based only on the server output. Jira or SFCC\n never displaces this order unless the server itself reports it as a dependency:\n 1. If any tool's `missing` includes a VCS integration (`github_app` / `vcs_access_token`), recommend\n connecting VCS first, using that integration's own `configure_in` pointer verbatim (for\n `github_app` that is the `connect-github` terminal command, not the setup UI).\n 2. Else if any tool's `missing` includes `code_index`, recommend running repository indexing\n (`/parse-repository`) next.\n 3. Else if `learned` is false, recommend running `/learn-repository` to populate the deeper\n instruction-tier configuration.\n- If `indexed` is `null` (unknown), include this exact warning:\n `Index status could not be confirmed—check again before relying on codebase-grounded tools.`\n\n## Stage 8 — Offer the next steps\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it); the\nspawn prompt owns the single closing index-consent question there. On direct manual `/install-bridge`\ninvocation, 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. After `/learn-repository` completes (or if the human declines it), offer to start **repository\n indexing**: ask ONE consent question (\"Start repository indexing now? It runs as a background job\n and makes the codebase searchable for Bridge API's agents.\"). On yes, call the `parse_repository`\n MCP tool once. Report that the job was QUEUED and that progress can be checked with\n `get_parse_status` (or `/check-parse-status`) — do NOT poll it to completion in this session.\n Indexing is deliberately last so the applied `exclude_directories` / `custom_directories` values\n scope it correctly. If no human response can be obtained (non-interactive session), skip indexing\n and list it as a pending next step in the final report — never start it without consent.\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 index-consent question the spawn prompt owns remains 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 index-consent question the spawn prompt owns remains 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 five-section\ncapability report (Connected ✓ / Not yet connected ✗ / Tools you can use now / Tools you'll unlock /\nRecommended next step + why) 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 recommended next step.\n",
18
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",
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",
22
22
  "regression-check.md": "Run the deterministic regression-reviewer (lightweight mode) against a proposed code change and report its blast radius — which real call-sites, tests, mocks, or config the change does and doesn't account for.\n\n$ARGUMENTS\n\n---\n\n<!-- Platform coverage: this command reaches Cursor + Claude Code (the commands\n bundle is scaffolded to .claude/commands/ and .cursor/commands/ by --init).\n The companion `regression-reviewer` agent (agents/src/regression-reviewer.md)\n reaches Claude Code + GitHub Copilot. Union: Cursor, Copilot, and Claude\n Code all get this review, either via the command or the agent. -->\n\n# Instructions\n\nThis is the standalone diff/PR (or ticket-description) review entry point for the regression-reviewer (BAPI-460). It mirrors the `regression-reviewer` agent's orchestration exactly — same subcommand, same parsing, same report — so the same logical review behaves identically whether invoked as a Cursor command or a Claude Code agent.\n\n## Step 1 — Determine the Input Shape\n\nParse `$ARGUMENTS`:\n\n- If it looks like a git diff range, a ref, a PR number, or is empty (defaulting to the working tree vs. `HEAD`), treat this as a **diff/PR invocation**. Resolve a `--diff <range>` value when one is given (e.g. `main...HEAD`, a commit SHA range); omit `--diff` to use the default working-tree-vs-HEAD diff.\n- If it names specific function/class/symbol names (e.g. `--symbols resolve_db_params,SomeClass`, or prose describing a not-yet-diffed planned change), treat this as a **ticket-description invocation**. Extract the symbol names and pass them via `--symbols a,b,c`.\n\nIf neither a diff nor any extractable symbol names are available, stop and ask the user to provide one.\n\n## Step 2 — Run the Deterministic Core\n\nExecute exactly:\n\n```bash\nnpx -y @bridge_gpt/mcp-server regression-check --mode lightweight --json [--diff <range> | --symbols a,b,c]\n```\n\nDo NOT hand-roll your own `ast-grep`/`ripgrep` invocations or re-discover call-sites yourself — the subcommand owns that structural analysis.\n\n## Step 3 — Parse the Findings (Fail-Open)\n\nParse the JSON: `summary.symbols_analyzed`, `summary.truncated`, `summary.tools_used`, `summary.degraded_flags`, and the `findings` array (`symbol`, `file`, `definition_location`, `call_sites` (`count`, `by_file`), `broad_mentions`).\n\nIf `summary.degraded_flags` is non-empty (e.g. `ast-grep` or `ripgrep` was unavailable), do NOT treat the run as a failure. Proceed with whatever data IS present and call out each degraded section explicitly — never silently drop a gap. If `summary.truncated` is `true`, state that the symbol set was capped.\n\n**Ripgrep degradation formatting**: if any entry in `summary.degraded_flags` mentions ripgrep, render it with an action-first visual hierarchy of three scannable segments rather than as a plain sentence:\n1. **Status/Problem** — a warning header with a semantic warning indicator (e.g. ⚠️).\n2. **Root Cause** — a brief note that `rg` must be a real binary on `PATH`; a shell function/alias is invisible to the spawned subcommand.\n3. **Remediation** — a standalone, copy-pasteable install command (e.g. `brew install ripgrep`) on its own line.\n\nApply monospace typography (backticks) to every reference to a system command, CLI tool (`rg`), environment term (`PATH`), or installation package, in this warning and throughout the report.\n\n## Step 4 — Synthesize Risk\n\nFor each symbol, compare `call_sites.count` against `broad_mentions.length`:\n- **Accounted for**: every real call-site and broad mention is either already touched by the change or clearly unaffected (e.g. a doc/comment mention).\n- **Not accounted for**: a real call-site, or an uninspected broad mention, sits in a file the proposed change does not touch. Name the specific file.\n\nRank \"not accounted for\" items by how directly they call the changed symbol (a real call-site outranks a textual mention).\n\n## Step 5 — Propose De-Risking (Diagnostic Synthesis, Not a Patch)\n\nFor each \"not accounted for\" item, name ONE of:\n- **Update the affected caller**: point to the exact `file:line` and describe what needs to change there.\n- **Add a compatibility/guard seam**: when updating every caller isn't right (e.g. a public API, a config key read elsewhere), describe the seam needed — not its full implementation.\n\nDo NOT implement the fix. State what needs to happen and where.\n\n## Final Output\n\nPrint this report to chat (no file write required):\n\n```markdown\n# Regression Review: [Symbol(s) / Change Description]\n\n**Mode**: lightweight\n**Input**: [--diff <range> | --symbols a,b,c]\n**Tools used**: [summary.tools_used, joined]\n**Degraded**: [list summary.degraded_flags, or \"none\"]\n**Symbols analyzed**: [summary.symbols_analyzed.length][ — TRUNCATED, capped at N if summary.truncated]\n\n## Summary\n\n[2-3 sentences: overall risk level, how many symbols are fully accounted for vs. not, and any degraded-tool caveats.]\n\n## Systems Accounted For / Not Accounted For\n\nRender as a `.data-table`-style markdown table (bold header row; left-aligned `Symbol` / `File` columns; tight ✅/⚠️ status indicators):\n\n| Symbol | File | Real Call-Sites | Broad Mentions | Status |\n|---|---|---|---|---|\n| `helper` | `src/foo.py` | 3 | 4 | ⚠️ Not accounted for |\n| `caller` | `src/foo.py` | 1 | 1 | ✅ Accounted for |\n\nIf `definition_location` is `null` for a symbol, degrade gracefully — do not leave the `File` column blank. Render a muted `—` placeholder there instead.\n\n## De-Risking Guidance\n\n### 1. [Symbol / File]\n- **Issue**: [what's not accounted for, with file:line]\n- **Recommendation**: Update the affected caller at `file:line` | Add a compatibility/guard seam — [describe]\n\n[Continue for each not-accounted-for item]\n\n---\n\n*Generated by regression-check (lightweight mode). Structural findings via ast-grep + ripgrep; Pinecone semantic search not available.*\n```\n",
23
23
  "reimplement-ticket.md": "# Reimplement Ticket: $ARGUMENTS\n\n$ARGUMENTS\n\nThis command retrieves the reimplement context for a previously-implemented Jira ticket via MCP, then implements follow-up changes inline. Use this for small follow-up requests on tickets that have already been through the plan+implement cycle.\n\nIf any critical stage fails (Stage 0 or Stage 1), stop immediately and report which stage failed and why.\n\n---\n\n# Instructions\n\nYou are executing a 4-stage pipeline to implement follow-up changes on a Jira ticket using assembled reimplement context. Execute all stages in sequence.\n\n## Stage 0 — Setup and Argument Parsing\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 does not match the expected format (one or more uppercase letters, a hyphen, and one or more digits), stop immediately and display:\n\n ```\n Invalid ticket key format: '<value>'. Expected format: PROJ-123 (uppercase letters, hyphen, digits).\n Usage: /reimplement-ticket <ticket_key> [--second-opinion [provider]] [--provider <name>] (e.g., /reimplement-ticket BAPI-150)\n ```\n\nThis stage is **critical** — stop immediately on failure. Do not proceed to Stage 1.\n\n## Stage 1 — Request and Retrieve Reimplement Context\n\nCall the `request_reimplement_context` MCP tool with:\n- `ticket_number`: the parsed `ticket_key` from Stage 0\n- `wait_for_result`: `true`\n- `save_locally`: `true`\n- `second_opinion`: set to `second_opinion_value` if it is non-null; omit the parameter entirely if `second_opinion_value` is null\n- `provider`: set to `provider_value` if it is non-null; omit the parameter entirely if `provider_value` is null\n\nIf the tool returns an error or 404 persists after polling, stop immediately and display:\n\n```\nFailed to retrieve reimplement context for <ticket_key>.\nThis may mean:\n- The ticket has not been previously processed by Bridge API\n- Background processing failed — check server logs\n- The ticket does not exist in Jira\n\nTry running /plan-ticket <ticket_key> first if this is a new ticket.\n```\n\nOn success, read and internalize the returned context markdown. This document contains:\n- A summary of changes (if applicable)\n- New/changed information since last processing (comments, description changes, attachments)\n- The original ticket description\n- The existing implementation plan (at the bottom, for reference only)\n\nThis stage is **critical** — stop immediately on failure. Do not proceed to Stage 2.\n\n## Stage 2 — Implement Follow-Up Changes\n\nExecute changes inline in this conversation. Work directly so the user can see all progress and approve tool calls.\n\nFollow these rules:\n\n1. **Focus on the new information.** The context document identifies what has changed since the last implementation. Focus your changes on addressing the new/changed requirements.\n2. **Reference the existing plan as supplementary guidance only.** The plan at the bottom of the context describes the original implementation, not the follow-up. Use it to understand the existing code structure, not as a step-by-step guide.\n3. **Make code changes** as directed by the new information.\n4. **Run tests and checks** to verify your changes don't break existing functionality.\n5. **Do NOT run `git commit` or `git push`.** Leave all changes uncommitted for developer review.\n6. **Scope guard**: If the follow-up changes are too large in scope (e.g., fundamentally restructuring the original implementation, touching more than 5-6 files, or requiring new infrastructure), stop and ask the user for guidance rather than attempting everything. Follow-up reimplementations should be small and targeted.\n7. **If a change is ambiguous or blocked**, note the issue clearly and continue with the next change rather than halting entirely.\n\nThis stage is **critical** — if a blocking error prevents further progress, stop and report the failure.\n\n## Stage 3 — Final Summary Report\n\nDisplay a structured report after all stages complete:\n\n```\n## Reimplement Complete\n\n**Ticket**: <ticket_key>\n\n**Changes Made**:\n- <brief summary of each change>\n\n**Developer Action Items**:\n- All changes are uncommitted. Review the changes with `git diff` before committing.\n- Run the project's test suite to verify nothing is broken before committing.\n\n**Warnings**:\n<If any issues arose during implementation (scope concerns, ambiguous requirements,\nfiles that couldn't be modified), list them here. If no warnings, omit this section.>\n```\n\n## Final Report\n\nOn success, display the structured report from Stage 3 confirming that the follow-up changes are complete.\n\nOn failure at any critical stage (Stage 0 or Stage 1), display which stage failed and the error details.\n",
24
- "review-and-implement.md": "---\nschedulable: true\ninteractive: true\narguments: {\"positionals\":[{\"name\":\"ticketKey\",\"type\":\"string\",\"required\":true}],\"flags\":[{\"name\":\"auto\",\"flag\":\"--auto\",\"type\":\"boolean\"},{\"name\":\"rounds\",\"flag\":\"--rounds\",\"type\":\"string\"},{\"name\":\"baseBranch\",\"flag\":\"--base-branch\",\"type\":\"string\"}]}\n---\n\n# Review and Implement: $ARGUMENTS\n\n$ARGUMENTS\n\nThis command runs inside a single already-created worktree (typically spawned by `/start-tickets --workflow review-and-implement`, or its front door `/review-and-start`): it reviews the ticket via `/review-ticket`, pauses at a per-ticket human proceed/halt gate, and only then implements it via `/implement-ticket`. It creates no worktrees, refreshes no base branch, and does not monitor sibling sessions — those responsibilities stay in the launcher (`start-tickets`) and the parent front-door command.\n\n---\n\n# Instructions\n\n## Argument Parsing\n\nParse `$ARGUMENTS`:\n\n1. **Ticket key**: exactly one required token matching the Jira key pattern (`[A-Z][A-Z0-9]+-\\d+`). If zero tokens match, or more than one token matches, stop immediately and display:\n ```\n Invalid ticket key. Expected exactly one key, e.g. PROJ-123.\n Usage: /review-and-implement <ticket_key> [--auto] [--rounds=1|2] [--base-branch=BRANCH]\n ```\n2. **`--auto`**: an optional position-independent flag. When present, sets chain-level `auto_approve` to `true`. This single flag applies to BOTH the review phase and the implementation phase below — there is no separate review-auto or implementation-auto state.\n3. **`--rounds`**: an optional position-independent `--rounds <n>` / `--rounds=<n>` argument, `1` or `2`. Normalize either form to `--rounds=<n>`. Reject any other value:\n ```\n Invalid --rounds value. Expected: --rounds=1 or --rounds=2.\n Usage: /review-and-implement <ticket_key> [--auto] [--rounds=1|2] [--base-branch=BRANCH]\n ```\n When omitted, forward no `--rounds` to `/review-ticket` (the backend's difficulty-adaptive review policy decides the shape).\n4. **`--base-branch`**: an optional position-independent `--base-branch <branch>` / `--base-branch=<branch>` argument. Validate it using the same rules `/start-tickets` Stage 0 uses: after trimming, non-empty, at most 255 characters, must not start with `-`, and must not contain ASCII control characters (`0x00`–`0x1F` or `0x7F`). Reject a malformed value:\n ```\n Invalid --base-branch value: <reason>\n Usage: /review-and-implement <ticket_key> [--auto] [--rounds=1|2] [--base-branch=BRANCH]\n ```\n\n## Phase 1 — Review (inline)\n\nInvoke `/review-ticket <ticket_key>` **inline, in this same session**, forwarding:\n- `--auto` when chain-level `auto_approve` is `true`.\n- The normalized `--rounds=<n>` when `--rounds` was supplied.\n- `--base-branch=<branch>` when it was supplied.\n\n`/review-ticket` grounds its codebase evaluation against a **fresh `git archive` of `origin/<base>`**, materialized into an isolated temp directory via `materialize_fresh_base` (see `docs/BAPI-474-ground-review-against-fresh-base.md`) — NOT against this worktree's own working tree. Review therefore behaves identically whether run standalone or, as here, inside a worktree that `start-tickets` already created; the worktree's isolation exists for the implementation phase below, not for review's codebase grounding.\n\nIf the review pipeline itself fails (any step reports `Status: Failed at step N`), halt this ticket immediately — in **both** auto and non-auto mode — before Phase 2 or Phase 3 run. Report:\n```\nReview failed for <ticket_key> at step N. Implementation was not started.\n```\nDo not attempt any cleanup; the worktree/branch remains available for manual inspection or cleanup.\n\n## Phase 2 — Halt Gate\n\n`/review-ticket` produces **decisions that rewrite the ticket** — it does NOT emit a binary approve/decline verdict token. Do not parse, infer, or synthesize an approve/decline signal from its output; no such token exists to parse.\n\n- **When chain-level `auto_approve` is `true`** and Phase 1 completed successfully: skip this gate entirely and proceed straight to Phase 3.\n- **Otherwise** (non-auto, and Phase 1 completed successfully): after the ticket has been rewritten, ask the user exactly:\n ```\n Proceed to implementation for <ticket_key>? (y/N)\n ```\n Treat an empty response, any negative response (`n`, `no`, or similar), or any ambiguous/unrecognized response as **halt** — do not guess intent. On halt, report:\n ```\n Halted before implementation for <ticket_key> (declined). The worktree/branch remains available for manual cleanup.\n ```\n and stop. Do not perform Phase 3 or any cleanup.\n- On an explicit affirmative response (`y` or `yes`), proceed to Phase 3.\n\n## Phase 3 — Implement (inline)\n\nInvoke `/implement-ticket <ticket_key>` **inline, in this same session**, appending `--auto` when chain-level `auto_approve` is `true` (and omitting it on the manual-confirmation path). This is the same single chain-level `--auto` from Phase 1 — there is no separate implementation-only auto flag.\n\n## Scope\n\nThis command composes `/review-ticket` and `/implement-ticket`; it owns none of their internals and must not:\n- create, re-cut, or switch a Worktrunk worktree,\n- refresh or fetch the launcher's base branch,\n- monitor or coordinate with sibling `/review-and-implement` sessions spawned for other tickets,\n- orchestrate the parent `start-tickets` / `/review-and-start` session.\n\nA halt (review failure or a declined gate) affects **this ticket only** — sibling worktrees spawned for other keys are unaffected. Review and implementation share the single difficulty-derived model tier selected when this session was spawned by `start-tickets`; this command does not re-resolve or override model routing.\n",
25
- "review-and-start.md": "---\nschedulable: true\narguments: {\"positionals\":[{\"name\":\"ticketKeys\",\"type\":\"string\",\"required\":true,\"variadic\":true}],\"flags\":[{\"name\":\"auto\",\"flag\":\"--auto\",\"type\":\"boolean\"},{\"name\":\"rounds\",\"flag\":\"--rounds\",\"type\":\"string\"},{\"name\":\"agent\",\"flag\":\"--agent\",\"type\":\"string\"},{\"name\":\"baseBranch\",\"flag\":\"--base-branch\",\"type\":\"string\"},{\"name\":\"maxParallel\",\"flag\":\"--max-parallel\",\"type\":\"string\"},{\"name\":\"dryRun\",\"flag\":\"--dry-run\",\"type\":\"boolean\"}]}\n---\n\n# Review and Start: $ARGUMENTS\n\n$ARGUMENTS\n\nThis command takes one or more Jira ticket keys (e.g., `BAPI-248` or `BAPI-248 BAPI-250` — both flow through the identical ordered `keys: string[]` path) and spawns one refreshed, self-contained Worktrunk worktree per ticket, each running `/review-and-implement <KEY>` — review, then a per-ticket human proceed/halt gate, then implementation. It is the **recommended front door** for chaining \"review these tickets, then implement the ones that pass\" starting from *existing ticket keys* (the entry point `/full-automation` lacks, since its server orchestrator only accepts an idea).\n\nIt is a thin shim over the packaged `start-tickets` CLI, invoked with `--workflow review-and-implement`: this command performs the same connectivity check and branch enrichment as `/start-tickets`, then hands off to the identical worktree/base-refresh/model-routing/credential/cross-platform-spawn/`doctor` engine — reused verbatim. The review→implement halt-gate decision logic lives entirely in the spawned `/review-and-implement` session, never here or in the CLI. Using `start-tickets --workflow review-and-implement` directly (documented in `commands/src/start-tickets.md`) remains available as the lower-level launcher seam this command drives.\n\n---\n\n# Instructions\n\nYou are executing a 4-stage pipeline that resolves connectivity and per-ticket branch names, then spawns N parallel Worktrunk worktrees via the packaged CLI's `--workflow review-and-implement` seam. Execute all stages in sequence directly in the main thread.\n\n## Stage 0 — Argument Parsing and Connectivity Check\n\n1. **Parse `$ARGUMENTS`** into ticket keys and pass-through flags:\n - **Ticket keys**: every whitespace-separated token matching `[A-Z]+-[0-9]+` (e.g., `BAPI-248`). A single key and multiple keys flow through the identical ordered `keys: string[]` path — there is no separate single-ticket code path. If zero keys are found, stop immediately and display:\n ```\n No ticket keys found in arguments. Expected one or more keys like BAPI-248.\n Usage: /review-and-start [flags] <KEY> [KEY ...] (e.g., /review-and-start BAPI-248 BAPI-250)\n ```\n - **`--auto`**: a single chain-level flag. When present, it is forwarded to `start-tickets --auto`, which threads it into BOTH the review and implementation phases of every spawned `/review-and-implement <KEY>` session.\n - **`--rounds`**: normalize `--rounds 1`/`--rounds=1` and `--rounds 2`/`--rounds=2` to `--rounds=<n>`; reject any other value. This value is forwarded to the review phase of every spawned session.\n - **Selected agent**: validate `--agent <name>` / `--agent=<name>` against `claude`/`cursor-agent` using the same rule as `/start-tickets`; default `claude`.\n - **User-supplied base branch**: validate `--base-branch <branch>` / `--base-branch=<branch>` using the same non-empty/≤255-character/no-leading-dash/no-control-character rules as `/start-tickets` Stage 0. A user-supplied value takes precedence over Stage 2a's `config_field` resolution below.\n - **`--max-parallel N`**: a positive integer; the CLI's own default (3) applies when omitted.\n - **`--dry-run`**: a boolean toggle.\n - Reject malformed input before proceeding: an unsupported flag, a ticket key not matching `[A-Z]+-[0-9]+`, an unsupported `--agent`/`--rounds`/`--base-branch` value — stop and report the malformed argument.\n\n2. **Connectivity check**: Call the `ping` MCP tool (no parameters). If the ping fails or does not return `\"status\": \"ok\"`, stop immediately and display:\n ```\n Connectivity check failed. Please verify:\n - Check that the Bridge API MCP server is configured in your editor's MCP settings\n - Check that BAPI_BASE_URL is set and the server is reachable\n - Check that BAPI_API_KEY is valid\n - Check that BAPI_REPO_NAME matches a configured repository\n ```\n\nThis stage is **critical** — stop immediately on failure. Do not proceed to Stage 1.\n\n## Stage 1 — Acknowledge CLI Pre-flight\n\nThe packaged `start-tickets` CLI (driven with `--workflow review-and-implement` in Stage 3) owns all platform pre-flight checks, refreshed worktree creation, secret-free credential provisioning, difficulty→model-tier routing, and cross-platform terminal spawning — identical to `/start-tickets`. This command does not duplicate or re-verify any of that; see `commands/src/start-tickets.md` Stage 1 for the full prerequisite/provisioning description it drives. This command does not expose `--conductor`, `--terminal`, or `--no-refresh-main`/`--no-refresh-base` — it stays scoped to the front-door flags listed above. Proceed to Stage 2.\n\n## Stage 2 — Resolve Base Branch + Enrich Branch Names (best-effort)\n\n### Stage 2a — Resolve Base Branch\n\nIdentical to `/start-tickets` Stage 2a: if the user supplied `--base-branch`, use it and skip the `config_field` lookup entirely. Otherwise call `config_field` (`operation: \"get\"`, `field_name: \"base_branch\"`) and treat a non-empty string `value` as the configured base branch; treat `null`, an empty/whitespace-only string, an HTTP `400` response, or any other lookup failure as \"unset\" and omit `--base-branch` from Stage 3 (the CLI then defaults to `main`). When forwarding a resolved value into the Stage 3 Bash invocation, apply the same mandatory single-quote escaping rule as `/start-tickets` (`'` → `'\\''`, then wrap the whole value in single quotes) before interpolating it into the command string — never expand it unquoted.\n\n### Stage 2b — Enrich Branch Names\n\nIdentical to `/start-tickets` Stage 2b: for each ticket key without a user-provided `--branch` override, call `get_ticket` (`ticket_number` set to the key, `save_locally: false`), slugify its `summary` (lowercase, collapse runs of `[^a-z0-9]+` to a single `-`, trim leading/trailing dashes, truncate to at most 40 characters preferring a dash boundary), and build `feature/<KEY>-<slug>`. On any per-key failure (404, network error, empty slug), emit a warning and let the CLI apply its default `feature/<KEY>` for that key only; never stop the pipeline. Credentials never reach the Bash-spawned CLI — this enrichment stays in the command, exactly as in `/start-tickets`.\n\nThis stage is **non-critical** — warnings are acceptable; the pipeline continues with the fallback branch for any key that fails enrichment.\n\n## Stage 3 — Invoke the Packaged CLI\n\nUse the **Bash tool** to invoke exactly **one** CLI invocation covering every requested key — never a per-key loop:\n\n```\nnpx -y @bridge_gpt/mcp-server start-tickets --workflow review-and-implement <pass-through-flags> <base-branch-flag> <branch-overrides> <ticket-keys>\n```\n\nWhere:\n- `<pass-through-flags>` forwards `--auto` (only if supplied), the normalized `--rounds=<n>` (only if supplied), `--agent <name>` (only if supplied), `--max-parallel N` (only if supplied), and `--dry-run` (only if supplied) verbatim.\n- `<base-branch-flag>` is `--base-branch '<escaped-value>'` only when a value was resolved in Stage 2a; otherwise omitted entirely.\n- `<branch-overrides>` is the list of `--branch KEY=BRANCH` flags assembled in Stage 2b.\n- `<ticket-keys>` is the original ordered list of keys parsed in Stage 0.\n\nCredentials are never placed in this shell command — the same secret-free provisioning path `/start-tickets` uses applies here unchanged.\n\nExample, single key, hands-off:\n\n```\nnpx -y @bridge_gpt/mcp-server start-tickets --workflow review-and-implement --auto --rounds=1 --branch BAPI-248=feature/BAPI-248-add-pr-rating-pre-evaluation-step BAPI-248\n```\n\nExample, multiple keys, manual per-ticket gate (no `--auto`):\n\n```\nnpx -y @bridge_gpt/mcp-server start-tickets --workflow review-and-implement --branch BAPI-248=feature/BAPI-248-add-pr-rating-pre-evaluation-step --branch BAPI-250=feature/BAPI-250-deep-research-durability BAPI-248 BAPI-250\n```\n\nPass through the CLI's stdout and stderr to the user verbatim. If the CLI exits non-zero, treat that as a critical failure: report the exit code and the CLI's error output, and stop.\n\nThis stage is **critical** — propagate any non-zero exit from the packaged CLI.\n\n## Stage 4 — Final Report\n\nOnce the CLI exits 0, parse its `Summary` section (one stable line per ticket: `KEY branch=BRANCH status=STATUS`, optional trailing `path=PATH`) and reformat it as a markdown table, identical in shape to `/start-tickets` Stage 4 (`Ticket | Branch | Status`; statuses `dry-run`, `spawned`, `create-failed`, `spawn-failed`).\n\nThis report describes **worktree/spawn status only**. State explicitly in the report:\n- Each successfully spawned session independently continues through `/review-ticket`, its own per-ticket halt gate, and `/implement-ticket` — this parent session does not observe or report that later outcome. Never claim or imply that review or implementation has completed.\n- When `--dry-run` was passed, state explicitly that no worktrees were created and no tabs/sessions were opened.\n- As a fixed trade-off of this design: the difficulty-derived model tier selected at spawn time serves the **entire** chained review-and-implement session (both phases share one model), and a non-auto (including a non-auto scheduled) run pauses at each ticket's own gate rather than proceeding hands-off.\n\nIf the CLI reported any `create-failed`/`spawn-failed` statuses, or Stage 2b emitted enrichment warnings, list them under a `Warnings:` heading. If there were none, omit that section.\n\nSee `docs/claude/parallel-worktrees.md` for the underlying runbook this command builds on, and `commands/src/review-and-implement.md` for the per-ticket review→gate→implement composition each spawned session runs.\n",
24
+ "review-and-implement.md": "---\nschedulable: true\ninteractive: true\narguments: {\"positionals\":[{\"name\":\"ticketKey\",\"type\":\"string\",\"required\":true}],\"flags\":[{\"name\":\"auto\",\"flag\":\"--auto\",\"type\":\"boolean\"},{\"name\":\"rounds\",\"flag\":\"--rounds\",\"type\":\"string\"},{\"name\":\"baseBranch\",\"flag\":\"--base-branch\",\"type\":\"string\"}]}\n---\n\n# Review and Implement: $ARGUMENTS\n\n$ARGUMENTS\n\nThis command runs inside a single already-created worktree (typically spawned by `/start-tickets --workflow review-and-implement`, or its front door `/review-and-start`). It reviews the ticket via `/review-ticket` **in this same session**, pauses at a per-ticket human proceed/halt gate, and — only on approval — hands the ticket off to a **freshly spawned implementation session** (`start-tickets --workflow implement`) that reuses this same worktree. Review and implementation therefore run in **two separate agent sessions/contexts**: the review session ends the moment the fresh implementation session is spawned, and the fresh session reads all reviewed ticket state back from the server rather than inheriting this session's transcript. It creates no *new* worktrees, refreshes no base branch, and does not monitor sibling sessions — those responsibilities stay in the launcher (`start-tickets`) and the parent front-door command.\n\n---\n\n# Instructions\n\n## Argument Parsing\n\nParse `$ARGUMENTS`:\n\n1. **Ticket key**: exactly one required token matching the Jira key pattern (`[A-Z][A-Z0-9]+-\\d+`). If zero tokens match, or more than one token matches, stop immediately and display:\n ```\n Invalid ticket key. Expected exactly one key, e.g. PROJ-123.\n Usage: /review-and-implement <ticket_key> [--auto] [--rounds=1|2] [--base-branch=BRANCH]\n ```\n2. **`--auto`**: an optional position-independent flag. When present, sets chain-level `auto_approve` to `true`. This single flag applies to BOTH the review phase and the implementation phase below — there is no separate review-auto or implementation-auto state.\n3. **`--rounds`**: an optional position-independent `--rounds <n>` / `--rounds=<n>` argument, `1` or `2`. Normalize either form to `--rounds=<n>`. Reject any other value:\n ```\n Invalid --rounds value. Expected: --rounds=1 or --rounds=2.\n Usage: /review-and-implement <ticket_key> [--auto] [--rounds=1|2] [--base-branch=BRANCH]\n ```\n When omitted, forward no `--rounds` to `/review-ticket` (the backend's difficulty-adaptive review policy decides the shape).\n4. **`--base-branch`**: an optional position-independent `--base-branch <branch>` / `--base-branch=<branch>` argument. Validate it using the same rules `/start-tickets` Stage 0 uses: after trimming, non-empty, at most 255 characters, must not start with `-`, and must not contain ASCII control characters (`0x00`–`0x1F` or `0x7F`). Reject a malformed value:\n ```\n Invalid --base-branch value: <reason>\n Usage: /review-and-implement <ticket_key> [--auto] [--rounds=1|2] [--base-branch=BRANCH]\n ```\n\n## Phase 0 — Capture Worktree Identity (before review)\n\nBefore any review work runs, perform the **capture step of the Cleanup Helper** (below): record this ticket worktree's absolute top-level path and current branch, and resolve the main checkout. These captured values are the ONLY inputs the later cleanup and handoff steps use — capturing them up front means a mid-run branch switch cannot redirect a later `git worktree remove`/`git branch -D` at the wrong target.\n\n## Cleanup Helper\n\nA single named procedure invoked by **both** halt paths — review failure (Phase 1) and a declined gate (Phase 2). It never runs on the success path (a successful handoff intentionally keeps the worktree). Perform its steps exactly; it is local to this command's workflow and adds **no** new cleanup CLI flag, launcher subcommand, or MCP surface.\n\n**Capture (run in Phase 0, before `/review-ticket`):**\n\n1. Capture the ticket worktree's **absolute top-level path** with `git rev-parse --show-toplevel` and its **current branch** with `git rev-parse --abbrev-ref HEAD`, both run from inside this worktree. Call these `<capturedPath>` and `<capturedBranch>`.\n2. Resolve the **main checkout** from `git worktree list --porcelain`: parse the `worktree <path>` records exactly, retaining each path verbatim **without splitting on whitespace** (a path may contain spaces), and select the main (non-linked, bare-repo-backed) checkout. **Refuse to treat `<capturedPath>` (the current ticket worktree) as the main checkout** — if the resolution is ambiguous or would resolve to the ticket worktree itself, abort cleanup and report retention instead. Call the result `<mainCheckout>`.\n\n**Remove (run only when a halt path fires):**\n\n3. Confirm `<capturedPath>` is still **registered against `<capturedBranch>`** in `git worktree list --porcelain` before deleting anything. If the path is unregistered, detached, or bound to a different branch than captured, **do not remove** — report retention.\n4. Confirm the ticket worktree is **clean** with `git status --porcelain` (run against `<capturedPath>`). If the output is non-empty (uncommitted or untracked changes), **report and retain** it — never force-remove unexpected local work.\n5. From `<mainCheckout>` (never from inside the ticket worktree), run `git worktree remove <capturedPath>` using shell-safe single-quoting of `<capturedPath>` and **no `--force`**.\n6. Only **after** the worktree removal succeeds, and again from `<mainCheckout>`, run `git branch -D -- <capturedBranch>` (shell-safe quoting). Preserve this remove-then-delete ordering; never delete the branch first.\n7. Report the exact branch and worktree removed (e.g. `Cleaned up worktree <capturedPath> and branch <capturedBranch>`), or, on any failure, a **bounded** cleanup-failure message that names what could not be removed and contains no credential or raw secret material.\n\n## Phase 1 — Review (inline)\n\n### Pre-review tier snapshot\n\nBefore invoking `/review-ticket`, call the `get_ticket_model_tier` MCP tool (`ticket_number` set to `<ticket_key>`) and record a **tier snapshot**. Retain the value **only** when it is one of the recognized tiers `cheap`, `basic`, or `premium`; treat any tool error, missing/`null` payload, or unrecognized value as an **unresolved** snapshot. A tier-snapshot failure is **non-critical**: do NOT abort — continue into review, and let the later implementation launcher perform its ordinary difficulty-based routing when the snapshot is unresolved. The snapshot exists only to let the fresh implementation session reuse the review-time tier decision (via `--tier`) instead of recomputing it; it is a coarse `cheap|basic|premium` label, never a raw model alias.\n\n### Run review\n\nInvoke `/review-ticket <ticket_key>` **inline, in this same session**, forwarding:\n- `--auto` when chain-level `auto_approve` is `true`.\n- The normalized `--rounds=<n>` when `--rounds` was supplied.\n- `--base-branch=<branch>` when it was supplied.\n\n`/review-ticket` grounds its codebase evaluation against a **fresh `git archive` of `origin/<base>`**, materialized into an isolated temp directory via `materialize_fresh_base` (see `docs/BAPI-474-ground-review-against-fresh-base.md`) — **not against this worktree's own working tree** (i.e. fresh-base grounding is not worktree-local). Review therefore behaves identically whether run standalone or, as here, inside a worktree that `start-tickets` already created; the worktree's isolation exists for the implementation phase below, not for review's codebase grounding.\n\nIf the review pipeline itself fails (any step reports `Status: Failed at step N`), halt this ticket immediately — in **both** auto and non-auto mode — before Phase 2 or Phase 3 run. Invoke the **Cleanup Helper** to remove this ticket's worktree and branch, then report:\n```\nReview failed for <ticket_key> at step N. Implementation was not started.\n```\nand stop. No implementation session is spawned.\n\n## Phase 2 — Halt Gate\n\n`/review-ticket` produces **decisions that rewrite the ticket** — it does NOT emit a binary approve/decline verdict token. Do not parse, infer, or synthesize an approve/decline signal from its output; no such token exists to parse.\n\n- **When chain-level `auto_approve` is `true`** and Phase 1 completed successfully: skip this gate entirely and proceed straight to Phase 3.\n- **Otherwise** (non-auto, and Phase 1 completed successfully): after the ticket has been rewritten, ask the user exactly:\n ```\n Proceed to implementation for <ticket_key>? (y/N)\n ```\n Treat an empty response, any negative response (`n`, `no`, or similar), or any ambiguous/unrecognized response as **decline** — do not guess intent. On decline, invoke the **Cleanup Helper** to remove this ticket's worktree and branch, then report:\n ```\n Declined implementation for <ticket_key>. The worktree and branch were cleaned up.\n ```\n and stop. Do not spawn an implementation session.\n- On an explicit affirmative response (`y` or `yes`), proceed to Phase 3.\n\n## Phase 3 — Implement (fresh session handoff)\n\n**Never invoke `/implement-ticket` inline in this session.** Instead, spawn a fresh implementation session that reuses this worktree, then end this review session.\n\n1. **Resolve the launcher directory.** Run the handoff from the `<mainCheckout>` resolved in Phase 0 — `start-tickets` manages worktrees and must run from the main checkout, never from inside the ticket worktree.\n2. **Construct exactly one launcher command** for this single ticket key:\n ```\n npx -y @bridge_gpt/mcp-server start-tickets --workflow implement <handoff-flags> <ticket_key>\n ```\n Assemble `<handoff-flags>` conditionally:\n - `--tier=<snapshot>` **only** when the Phase 1 tier snapshot resolved to a valid `cheap|basic|premium` value. When the snapshot is unresolved, **omit `--tier` entirely** so the fresh launcher follows its normal fail-open difficulty routing.\n - `--branch <ticket_key>=<capturedBranch>` **only** when `<capturedBranch>` differs from the launcher default `feature/<ticket_key>` (i.e. an enriched branch such as `feature/<KEY>-<slug>`). This reuses the existing worktree/branch via the launcher's `switch` path instead of cutting a new one; when the branch is already the bare `feature/<ticket_key>`, no override is needed.\n - `--auto` **only** when chain-level `auto_approve` is active.\n3. **Credential invariant.** `BAPI_API_KEY` and every other credential MUST be absent from this launcher command and its environment assignment — the spawned CLI resolves credentials on its own through `resolveBapiCredentials` / the user-scoped credential store. Never inline a key, authorization header, or credential-store payload into the command string.\n4. **Starter prompt boundary.** The fresh session's starter prompt is only `/implement-ticket <ticket_key>` (plus `--auto` when auto is active) — the launcher builds it. The review transcript, the tier snapshot, the branch metadata, and any review decisions are **excluded** from that prompt; the fresh session reads all reviewed ticket state back from the server.\n5. **On success** (launcher exits `0` and reports the ticket spawned): **end this review session immediately.** Do not monitor, parse, or wait for any output from the fresh implementation session — that session owns the implementation lifecycle from here.\n6. **On a non-zero launcher exit**: treat it as a **handoff failure**. Report the exit code and the launcher's error output, and **retain** the existing clean worktree for a manual retry — do **not** invoke the Cleanup Helper (a failed handoff is not a decline). \n\n## Scope\n\nThis command composes `/review-ticket` (inline) and a fresh `start-tickets --workflow implement` handoff; it owns none of their internals and must not:\n- create, re-cut, or switch a *new* Worktrunk worktree itself (the fresh launcher reuses the existing one),\n- refresh or fetch the launcher's base branch,\n- monitor or coordinate with sibling `/review-and-implement` sessions spawned for other tickets,\n- orchestrate the parent `start-tickets` / `/review-and-start` session,\n- carry the review transcript, tier snapshot, or branch metadata into the fresh implementation session's starter prompt.\n\nA halt (review failure or a declined gate) affects **this ticket only** — it cleans up this ticket's own worktree/branch and never touches sibling worktrees spawned for other keys, which continue independently. The fresh implementation session receives only `/implement-ticket <ticket_key> [--auto]` as its starter prompt and reads all reviewed ticket state back from the server.\n",
25
+ "review-and-start.md": "---\nschedulable: true\narguments: {\"positionals\":[{\"name\":\"ticketKeys\",\"type\":\"string\",\"required\":true,\"variadic\":true}],\"flags\":[{\"name\":\"auto\",\"flag\":\"--auto\",\"type\":\"boolean\"},{\"name\":\"rounds\",\"flag\":\"--rounds\",\"type\":\"string\"},{\"name\":\"agent\",\"flag\":\"--agent\",\"type\":\"string\"},{\"name\":\"baseBranch\",\"flag\":\"--base-branch\",\"type\":\"string\"},{\"name\":\"maxParallel\",\"flag\":\"--max-parallel\",\"type\":\"string\"},{\"name\":\"dryRun\",\"flag\":\"--dry-run\",\"type\":\"boolean\"}]}\n---\n\n# Review and Start: $ARGUMENTS\n\n$ARGUMENTS\n\nThis command takes one or more Jira ticket keys (e.g., `BAPI-248` or `BAPI-248 BAPI-250` — both flow through the identical ordered `keys: string[]` path) and spawns one refreshed, self-contained Worktrunk worktree per ticket, each running `/review-and-implement <KEY>`: review runs in that spawned session, then a per-ticket human proceed/halt gate, and — only on approval — that session hands the ticket off to a **fresh implementation session** that reuses the same worktree. Review and implementation thus run in two separate agent sessions per ticket, not one shared context. It is the **recommended front door** for chaining \"review these tickets, then implement the ones that pass\" starting from *existing ticket keys* (the entry point `/full-automation` lacks, since its server orchestrator only accepts an idea).\n\nIt is a thin shim over the packaged `start-tickets` CLI, invoked with `--workflow review-and-implement`: this command performs the same connectivity check and branch enrichment as `/start-tickets`, then hands off to the identical worktree/base-refresh/model-routing/credential/cross-platform-spawn/`doctor` engine — reused verbatim. The review→implement halt-gate decision logic lives entirely in the spawned `/review-and-implement` session, never here or in the CLI. Using `start-tickets --workflow review-and-implement` directly (documented in `commands/src/start-tickets.md`) remains available as the lower-level launcher seam this command drives.\n\n---\n\n# Instructions\n\nYou are executing a 4-stage pipeline that resolves connectivity and per-ticket branch names, then spawns N parallel Worktrunk worktrees via the packaged CLI's `--workflow review-and-implement` seam. Execute all stages in sequence directly in the main thread.\n\n## Stage 0 — Argument Parsing and Connectivity Check\n\n1. **Parse `$ARGUMENTS`** into ticket keys and pass-through flags:\n - **Ticket keys**: every whitespace-separated token matching `[A-Z]+-[0-9]+` (e.g., `BAPI-248`). A single key and multiple keys flow through the identical ordered `keys: string[]` path — there is no separate single-ticket code path. If zero keys are found, stop immediately and display:\n ```\n No ticket keys found in arguments. Expected one or more keys like BAPI-248.\n Usage: /review-and-start [flags] <KEY> [KEY ...] (e.g., /review-and-start BAPI-248 BAPI-250)\n ```\n - **`--auto`**: a single chain-level flag. When present, it is forwarded to `start-tickets --auto`, which threads it into BOTH the review and implementation phases of every spawned `/review-and-implement <KEY>` session.\n - **`--rounds`**: normalize `--rounds 1`/`--rounds=1` and `--rounds 2`/`--rounds=2` to `--rounds=<n>`; reject any other value. This value is forwarded to the review phase of every spawned session.\n - **Selected agent**: validate `--agent <name>` / `--agent=<name>` against `claude`/`cursor-agent` using the same rule as `/start-tickets`; default `claude`.\n - **User-supplied base branch**: validate `--base-branch <branch>` / `--base-branch=<branch>` using the same non-empty/≤255-character/no-leading-dash/no-control-character rules as `/start-tickets` Stage 0. A user-supplied value takes precedence over Stage 2a's `config_field` resolution below.\n - **`--max-parallel N`**: a positive integer; the CLI's own default (3) applies when omitted.\n - **`--dry-run`**: a boolean toggle.\n - Reject malformed input before proceeding: an unsupported flag, a ticket key not matching `[A-Z]+-[0-9]+`, an unsupported `--agent`/`--rounds`/`--base-branch` value — stop and report the malformed argument.\n\n2. **Connectivity check**: Call the `ping` MCP tool (no parameters). If the ping fails or does not return `\"status\": \"ok\"`, stop immediately and display:\n ```\n Connectivity check failed. Please verify:\n - Check that the Bridge API MCP server is configured in your editor's MCP settings\n - Check that BAPI_BASE_URL is set and the server is reachable\n - Check that BAPI_API_KEY is valid\n - Check that BAPI_REPO_NAME matches a configured repository\n ```\n\nThis stage is **critical** — stop immediately on failure. Do not proceed to Stage 1.\n\n## Stage 1 — Acknowledge CLI Pre-flight\n\nThe packaged `start-tickets` CLI (driven with `--workflow review-and-implement` in Stage 3) owns all platform pre-flight checks, refreshed worktree creation, secret-free credential provisioning, difficulty→model-tier routing, and cross-platform terminal spawning — identical to `/start-tickets`. This command does not duplicate or re-verify any of that; see `commands/src/start-tickets.md` Stage 1 for the full prerequisite/provisioning description it drives. This command does not expose `--conductor`, `--terminal`, or `--no-refresh-main`/`--no-refresh-base` — it stays scoped to the front-door flags listed above. Proceed to Stage 2.\n\n## Stage 2 — Resolve Base Branch + Enrich Branch Names (best-effort)\n\n### Stage 2a — Resolve Base Branch\n\nIdentical to `/start-tickets` Stage 2a: if the user supplied `--base-branch`, use it and skip the `config_field` lookup entirely. Otherwise call `config_field` (`operation: \"get\"`, `field_name: \"base_branch\"`) and treat a non-empty string `value` as the configured base branch; treat `null`, an empty/whitespace-only string, an HTTP `400` response, or any other lookup failure as \"unset\" and omit `--base-branch` from Stage 3 (the CLI then defaults to `main`). When forwarding a resolved value into the Stage 3 Bash invocation, apply the same mandatory single-quote escaping rule as `/start-tickets` (`'` → `'\\''`, then wrap the whole value in single quotes) before interpolating it into the command string — never expand it unquoted.\n\n### Stage 2b — Enrich Branch Names\n\nIdentical to `/start-tickets` Stage 2b: for each ticket key without a user-provided `--branch` override, call `get_ticket` (`ticket_number` set to the key, `save_locally: false`), slugify its `summary` (lowercase, collapse runs of `[^a-z0-9]+` to a single `-`, trim leading/trailing dashes, truncate to at most 40 characters preferring a dash boundary), and build `feature/<KEY>-<slug>`. On any per-key failure (404, network error, empty slug), emit a warning and let the CLI apply its default `feature/<KEY>` for that key only; never stop the pipeline. Credentials never reach the Bash-spawned CLI — this enrichment stays in the command, exactly as in `/start-tickets`.\n\nThis stage is **non-critical** — warnings are acceptable; the pipeline continues with the fallback branch for any key that fails enrichment.\n\n## Stage 3 — Invoke the Packaged CLI\n\nUse the **Bash tool** to invoke exactly **one** CLI invocation covering every requested key — never a per-key loop:\n\n```\nnpx -y @bridge_gpt/mcp-server start-tickets --workflow review-and-implement <pass-through-flags> <base-branch-flag> <branch-overrides> <ticket-keys>\n```\n\nWhere:\n- `<pass-through-flags>` forwards `--auto` (only if supplied), the normalized `--rounds=<n>` (only if supplied), `--agent <name>` (only if supplied), `--max-parallel N` (only if supplied), and `--dry-run` (only if supplied) verbatim.\n- `<base-branch-flag>` is `--base-branch '<escaped-value>'` only when a value was resolved in Stage 2a; otherwise omitted entirely.\n- `<branch-overrides>` is the list of `--branch KEY=BRANCH` flags assembled in Stage 2b.\n- `<ticket-keys>` is the original ordered list of keys parsed in Stage 0.\n\nCredentials are never placed in this shell command — the same secret-free provisioning path `/start-tickets` uses applies here unchanged.\n\nExample, single key, hands-off:\n\n```\nnpx -y @bridge_gpt/mcp-server start-tickets --workflow review-and-implement --auto --rounds=1 --branch BAPI-248=feature/BAPI-248-add-pr-rating-pre-evaluation-step BAPI-248\n```\n\nExample, multiple keys, manual per-ticket gate (no `--auto`):\n\n```\nnpx -y @bridge_gpt/mcp-server start-tickets --workflow review-and-implement --branch BAPI-248=feature/BAPI-248-add-pr-rating-pre-evaluation-step --branch BAPI-250=feature/BAPI-250-deep-research-durability BAPI-248 BAPI-250\n```\n\nPass through the CLI's stdout and stderr to the user verbatim. If the CLI exits non-zero, treat that as a critical failure: report the exit code and the CLI's error output, and stop.\n\nThis stage is **critical** — propagate any non-zero exit from the packaged CLI.\n\n## Stage 4 — Final Report\n\nOnce the CLI exits 0, parse its `Summary` section (one stable line per ticket: `KEY branch=BRANCH status=STATUS`, optional trailing `path=PATH`) and reformat it as a markdown table, identical in shape to `/start-tickets` Stage 4 (`Ticket | Branch | Status`; statuses `dry-run`, `spawned`, `create-failed`, `spawn-failed`).\n\nThis report describes **worktree/spawn status only**. State explicitly in the report:\n- Each successfully spawned session first runs `/review-ticket` and its own per-ticket halt gate; on successful review and approval (or `--auto`), it then opens a **fresh implementation session** (`/implement-ticket`) that reuses the same worktree. Review and implementation run in two separate agent sessions, not one shared context. This parent session does not observe or report either the review outcome or the later implementation outcome. Never claim or imply that review or implementation has completed.\n- When `--dry-run` was passed, state explicitly that no worktrees were created and no tabs/sessions were opened.\n- As a fixed trade-off of this design: the review session's difficulty-derived model tier is snapshotted and reused (via `--tier`) by the fresh implementation session, so both phases run on the same tier; and a non-auto (including a non-auto scheduled) run pauses at each ticket's own gate rather than proceeding hands-off. For an `--auto` run, each ticket's eventual implementation completion is observed in its own fresh implementation tab, not here.\n\nIf the CLI reported any `create-failed`/`spawn-failed` statuses, or Stage 2b emitted enrichment warnings, list them under a `Warnings:` heading. If there were none, omit that section.\n\nSee `docs/claude/parallel-worktrees.md` for the underlying runbook this command builds on, and `commands/src/review-and-implement.md` for the per-ticket review→gate→implement composition each spawned session runs.\n",
26
26
  "review-ticket.md": "---\nschedulable: true\ninteractive: true\narguments: {\"positionals\":[{\"name\":\"ticketKey\",\"type\":\"string\",\"required\":true}],\"flags\":[{\"name\":\"auto\",\"flag\":\"--auto\",\"type\":\"boolean\"},{\"name\":\"rounds\",\"flag\":\"--rounds\",\"type\":\"string\"},{\"name\":\"noRefreshBase\",\"flag\":\"--no-refresh-base\",\"type\":\"boolean\"},{\"name\":\"baseBranch\",\"flag\":\"--base-branch\",\"type\":\"string\"},{\"name\":\"baseSha\",\"flag\":\"--base-sha\",\"type\":\"string\"}]}\n---\n\n# Review 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\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 - An optional position-independent `--rounds=<n>` argument, where `<n>` is `1` or `2`.\n - An optional position-independent `--no-refresh-base` flag.\n - An optional position-independent `--base-branch=<branch>` argument.\n - An optional position-independent `--base-sha=<sha>` argument.\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`. A token matching `--rounds=1` sets `rounds` to `1`; a token matching `--rounds=2` sets `rounds` to `2`. If no `--rounds` token is present, leave `rounds` unset (omitted) so the backend's difficulty-adaptive review policy can decide the review shape when enabled for this repo; when adaptive routing is disabled, unavailable, or the ticket's difficulty cannot be resolved, the backend falls back to a full premium second-opinion review. The presence of a `--no-refresh-base` token sets `no_refresh_base` to `true`. A token matching `--base-branch=<branch>` sets `base_branch` to `<branch>`. A token matching `--base-sha=<sha>` sets `base_sha` to `<sha>`.\n\n `--auto`, `--rounds`, `--no-refresh-base`, `--base-branch`, and `--base-sha` are all independent and may be supplied in any combination.\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] [--rounds=1|2] [--no-refresh-base] [--base-branch=BRANCH] [--base-sha=SHA]\n Usage: /review-ticket <ticket_key> [--auto] [--rounds=1|2] [--no-refresh-base] [--base-branch=BRANCH] [--base-sha=SHA]\n ```\n\n If a `--rounds` token is present but its value is not `1` or `2`, stop and display:\n ```\n Invalid --rounds value. Expected: --rounds=1 or --rounds=2 (omit to let the backend decide adaptively; default falls back to a full review)\n Usage: /review-ticket <ticket_key> [--auto] [--rounds=1|2] [--no-refresh-base] [--base-branch=BRANCH] [--base-sha=SHA]\n ```\n\n2. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"review-ticket\"`\n - `variables`: `{ \"ticket_key\": \"<ticket_key>\", \"base_branch\": \"<base_branch or \"\">\", \"base_sha\": \"<base_sha or \"\">\", \"no_refresh_base\": \"<\"true\" if --no-refresh-base was passed, else \"\">\" }`\n - `auto_approve`: `true` — only when `--auto` was passed; otherwise omit this field entirely.\n - `rounds`: `1` — only when `--rounds=1` was explicitly passed on the command; `2` — only when `--rounds=2` was explicitly passed. When `--rounds` was NOT supplied, omit `rounds` entirely (do not pass `rounds: null`) so the backend's difficulty-adaptive review policy can choose the review shape when enabled for this repo. An explicit `rounds` value is forwarded to the backend and forces the review shape: `--rounds=1` requests a single-pass review, and `--rounds=2` forces the full second-opinion review even when adaptive routing is enabled. Do NOT translate `rounds` into `skip_steps` — the backend executor now owns all round orchestration (including any second-opinion rounds), so the recipe carries a single `request_ticket_review` step and you never pass `skip_steps` for round control.\n\n Example combined-mode payload (`--rounds=1 --auto --base-branch=develop`):\n ```json\n {\n \"pipeline\": \"review-ticket\",\n \"variables\": { \"ticket_key\": \"PROJ-123\", \"base_branch\": \"develop\", \"base_sha\": \"\", \"no_refresh_base\": \"\" },\n \"auto_approve\": true,\n \"rounds\": 1\n }\n ```\n\n Example explicit full-review payload (`--rounds=2`), which forces the full second-opinion review even if adaptive routing is enabled for this repo:\n ```json\n {\n \"pipeline\": \"review-ticket\",\n \"variables\": { \"ticket_key\": \"PROJ-123\", \"base_branch\": \"\", \"base_sha\": \"\", \"no_refresh_base\": \"\" },\n \"rounds\": 2\n }\n ```\n\n Example adaptive payload (no `--rounds`), which lets the backend policy executor decide the review shape (falling back to a full premium review when adaptive routing is disabled or the ticket's difficulty cannot be resolved):\n ```json\n {\n \"pipeline\": \"review-ticket\",\n \"variables\": { \"ticket_key\": \"PROJ-123\", \"base_branch\": \"\", \"base_sha\": \"\", \"no_refresh_base\": \"\" }\n }\n ```\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",
27
27
  "review-tickets.md": "---\nschedulable: true\ninteractive: true\narguments: {\"positionals\":[{\"name\":\"ticketKeys\",\"type\":\"string\",\"required\":true,\"variadic\":true}],\"flags\":[{\"name\":\"auto\",\"flag\":\"--auto\",\"type\":\"boolean\"},{\"name\":\"rounds\",\"flag\":\"--rounds\",\"type\":\"string\"},{\"name\":\"review\",\"flag\":\"--review\",\"type\":\"string\",\"repeatable\":true},{\"name\":\"agent\",\"flag\":\"--agent\",\"type\":\"string\"},{\"name\":\"model\",\"flag\":\"--model\",\"type\":\"string\"},{\"name\":\"maxParallel\",\"flag\":\"--max-parallel\",\"type\":\"string\"},{\"name\":\"dryRun\",\"flag\":\"--dry-run\",\"type\":\"boolean\"},{\"name\":\"noRefreshBase\",\"flag\":\"--no-refresh-base\",\"type\":\"boolean\"},{\"name\":\"baseBranch\",\"flag\":\"--base-branch\",\"type\":\"string\"}]}\n---\n\n# Review Tickets: $ARGUMENTS\n\n$ARGUMENTS\n\nThis command takes one or more Jira ticket keys and invokes the packaged `@bridge_gpt/mcp-server` CLI subcommand `review-tickets`, which opens one terminal tab per ticket running the selected agent with `/review-ticket <KEY> [--auto] [--rounds=<1|2>]`. By default `--rounds` is omitted so the backend routes each review by difficulty (difficulty-adaptive review); pass an explicit `--rounds=1|2` (globally or per ticket) to force the review shape. Unlike `/start-tickets`, it creates no Worktrunk worktrees — but it now requires `git` on PATH: the parent process fetches `origin/<base_branch>` once and pins a single `base_sha` for the whole batch before spawning tabs (BAPI-474), so every spawned review grounds its codebase evaluation against the same freshly-fetched base tree. Pass `--no-refresh-base` to skip this and restore the prior git-free, in-place-grounded behavior.\n\n---\n\n# Instructions\n\n## Stage 0 — Parse Arguments and Connectivity Check\n\n1. **Parse `$ARGUMENTS`** to extract ticket keys, review modes, and pass-through flags:\n\n - **Ticket keys**: every whitespace-separated token matching `[A-Z]+-[0-9]+` (e.g., `BAPI-1`). If zero keys are found, stop immediately and display:\n ```\n No ticket keys found. Expected one or more keys like BAPI-1.\n Usage: /review-tickets [flags] KEY [KEY ...]\n ```\n\n - **Review mode interpretation** (per ticket or global):\n - `auto` or `--auto` → per-ticket or global auto-approve flag.\n - `single-pass`, `one-pass`, `rounds=1`, or `--rounds=1` → `rounds=1` (single-pass review).\n - `full`, `two-pass`, `rounds=2`, or `--rounds=2` → `rounds=2` (full second-opinion review).\n - **omitted rounds → `adaptive`**: when no rounds mode is given for a ticket, do NOT choose a round count — leave it adaptive so the backend's difficulty-adaptive review policy decides the shape. `adaptive` is a distinct mode from `1` and `2`.\n - `--auto` and `--rounds` are independent: both may apply to the same ticket.\n\n The backend executor now owns all review round orchestration (including any second-opinion rounds) server-side — there is no client-side step to skip, so this command never sends `skip_steps` and never translates `--rounds=1` into skipping a second-opinion step. An explicit `--rounds` value forwarded to each spawned `/review-ticket` forces the review shape (`1` = single pass, `2` = full second-opinion review). A spawned `/review-ticket` invoked without any `--rounds` (the default) lets the backend's difficulty-adaptive review policy decide the shape (falling back to a full premium second-opinion review when adaptive routing is disabled, unavailable, or the ticket's difficulty cannot be resolved). This batch command therefore forwards **no** `--rounds` by default; it only forwards `--rounds` when the caller explicitly supplies a rounds mode (globally via `--rounds`, or per ticket via `--review`).\n\n - **Homogeneous modes**: when all tickets share the same auto and rounds mode, translate into global `--auto` (if all auto) and, only when all tickets share the same *explicit* rounds value, global `--rounds=1|2`. When all tickets are adaptive (no rounds given), omit `--rounds` entirely — do not synthesize a default.\n\n - **Heterogeneous modes**: when tickets differ in auto or rounds mode, translate into repeatable `--review KEY=auto,rounds=N` overrides. Only emit a `rounds=N` subtoken for tickets given an explicit `1`/`2`; adaptive tickets carry no `rounds` subtoken (a bare `--review KEY=auto` if they are auto, or no override at all). Do NOT set global `--auto` when only some tickets are auto-approved, and do NOT set global `--rounds` when only some tickets have an explicit rounds value.\n\n - **Pass-through flags**: collect `--dry-run`, `--max-parallel N`, `--agent claude|cursor-agent`, `--model VALUE`, `--no-refresh-base`, and `--base-branch VALUE` if supplied, and forward verbatim to the CLI.\n\n2. **Connectivity check**: Call the `ping` MCP tool. If it fails or does not return `\"status\": \"ok\"`, stop immediately and display:\n ```\n Connectivity check failed. Please verify:\n - Check that the Bridge API MCP server is configured in your editor's MCP settings\n - Check that BAPI_BASE_URL is set and the server is reachable\n - Check that BAPI_API_KEY is valid\n - Check that BAPI_REPO_NAME matches a configured repository\n ```\n\n## Stage 1 — Invoke the Packaged CLI\n\nUse the **Bash tool** to invoke exactly one CLI invocation:\n\n```\nnpx -y @bridge_gpt/mcp-server review-tickets [--auto] [--rounds=1|2] [--review KEY=auto,rounds=N ...] [--agent <name>] [--model <alias>] [--max-parallel N] [--dry-run] [--no-refresh-base] [--base-branch BRANCH] KEY [KEY ...]\n```\n\n- `review-tickets` runs all tabs from the current repository cwd — it creates no worktrees.\n- The command never runs `wt` or `git-wt` — but it now requires `git` on PATH (BAPI-474): before spawning any tabs, the parent process fetches `origin/<base_branch>` once and pins a single `base_sha` for the whole batch, so a mid-batch `origin` advance can never mix bases within one run. Pass `--no-refresh-base` to skip the fetch and restore the prior git-free, in-place-grounded behavior.\n- Prerequisites: macOS `osascript` + `git`, Windows `wt.exe` or PowerShell + `git`, Linux `tmux` + `git` (git is not required when `--no-refresh-base` is passed).\n\nPass through the CLI's stdout and stderr verbatim. If the CLI exits non-zero, treat it as a critical failure and report the exit code and error output.\n\n## Stage 2 — Final Report\n\nOnce the CLI exits 0, parse its `Summary:` lines (each shaped like `KEY auto=<true|false> rounds=<1|2|adaptive> agent=<agent> model=<alias|default> status=<status>`) and render as a markdown table (`rounds=adaptive` means the backend chose the shape by difficulty):\n\n```\n| Ticket | Auto | Rounds | Agent | Model | Status |\n|----------|-------|----------|--------|---------|---------|\n| BAPI-1 | false | adaptive | claude | default | spawned |\n| BAPI-2 | true | 1 | claude | default | spawned |\n```\n\nRender any CLI `Warnings:` lines below the table. If there were none, omit the warnings section.\n",
28
28
  "run-tests.md": "Run the project's full test suite (unit and E2E) using the project-configured test stacks, triage failures, fix test-code issues, and produce a structured health-check report.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command discovers how to run tests by reading per-project configuration from the Bridge API, not from hardcoded paths. Stages run only when the project has the corresponding stack configured.\n\n## Stage 0 — Argument Parsing and Setup\n\n1. **Parse `$ARGUMENTS`** for optional flags. Supported flags:\n - `--skip-e2e` — skip the E2E test stage even if an E2E stack is configured (e.g., when no local server is running)\n - `--unit-only` — shorthand that implies `--skip-e2e`\n\n Resolve flags to boolean variables:\n - Start with: `run_unit = true`, `run_e2e = true`\n - If `--unit-only` is present: set `run_e2e = false`\n - If `--skip-e2e` is present: set `run_e2e = false`\n - Unknown flags: note them in the final report as \"Unrecognized flag ignored\" but do not fail\n\n2. **Generate a run timestamp** using the current date and time in `YYYY-MM-DD-HH-MM` format (e.g., `2026-03-10-14-35`). Store this as `run_timestamp`. Both output documents will use this value.\n\nThis stage has no failure conditions — proceed to Stage 1.\n\n## Stage 1 — Resolve Project Config via MCP\n\nRead the per-project test setup from the Bridge database. Every subsequent stage is driven by what these calls return.\n\n1. **Resolve docs directory**: Call the `get_docs_dir` MCP tool (no parameters). Store the returned path as `docs_dir`.\n\n2. **Read unit-test stack**: Call the `config_field` MCP tool with `operation` set to `\"get\"` and `field_name` set to `unit_testing_stack`. Store the returned value as `unit_stack` (may be null/empty).\n\n3. **Read unit-test instructions**: Call the `config_field` MCP tool with `operation` set to `\"get\"` and `field_name` set to `unit_testing_instructions`. Store the returned value as `unit_instructions` (may be null/empty).\n\n4. **Read E2E stack**: Call the `config_field` MCP tool with `operation` set to `\"get\"` and `field_name` set to `e2e_testing_stack`. Store as `e2e_stack`.\n\n5. **Read E2E instructions**: Call the `config_field` MCP tool with `operation` set to `\"get\"` and `field_name` set to `e2e_testing_instructions`. Store as `e2e_instructions`.\n\n6. **Compute configuration booleans**:\n - `unit_configured` = `true` if either `unit_stack` or `unit_instructions` is a non-empty string; otherwise `false`\n - `e2e_configured` = `true` if either `e2e_stack` or `e2e_instructions` is a non-empty string; otherwise `false`\n\n7. **Create the output directory**:\n ```\n mkdir -p {docs_dir}/testing/\n ```\n If this fails, stop immediately and report: `Cannot create output directory {docs_dir}/testing/ — check permissions.`\n\nIf any MCP call fails (e.g., the API is unreachable or returns 4xx/5xx), stop immediately and report which call failed. Do not fall back to hardcoded commands — the whole point of this command is that test setup lives in config.\n\n## Stage 2 — Unit / Standard Tests\n\nIf `run_unit` is `false`, skip this stage and record: `Unit tests: SKIPPED — run_unit was set to false (this should not happen in normal use; report as a bug).`\n\nIf `unit_configured` is `false`, skip and record:\n```\nUnit tests: SKIPPED — no unit_testing_stack or unit_testing_instructions configured for this repo. Configure via /learn-unit-testing or the project setup UI before running /run-tests.\n```\n\nOtherwise:\n\n1. Read `unit_instructions` carefully. It is the source of truth for **how to run unit tests in this repo** — runner binary, paths, environment activation, sub-suites (if the project distinguishes \"unit\" from \"integration\", both belong in this stage), and any flags. Pair it with `unit_stack` (a short label, e.g., `Pytest`, `Jest + React Testing Library`) for context.\n\n2. **Derive the test command(s)**: Extract the literal shell commands the instructions describe. If the instructions describe multiple sub-suites (e.g., a fast unit batch and a slower integration batch), plan to run each as a **separate batch** in the order described. Do not invent runners or paths that the instructions do not mention.\n\n3. **If the instructions do not specify any runnable command**, skip and record:\n ```\n Unit tests: SKIPPED — unit_testing_instructions does not describe how to invoke tests; please update via /learn-unit-testing.\n ```\n\n4. **Run each batch sequentially** in the terminal. **Continue to the next batch even if the current one has failures.** Capture the full output of each batch, including the runner's summary line (e.g., `47 passed, 3 failed in 12.4s` or `Tests: 5 failed, 22 passed`).\n\n5. For each failing test, apply the **Triage Logic** (below), then record the result.\n\n## Stage 3 — E2E Tests\n\nIf `run_e2e` is `false`, skip this stage and record: `E2E tests: SKIPPED — --skip-e2e or --unit-only flag was set.`\n\nIf `e2e_configured` is `false`, skip and record:\n```\nE2E tests: SKIPPED — no e2e_testing_stack or e2e_testing_instructions configured (the project may not have an E2E suite).\n```\n\nOtherwise:\n\n1. Read `e2e_instructions`. It is the source of truth for the E2E runner, spec paths, browser config, and any prerequisites. Pair with `e2e_stack` for context.\n\n2. **Detect server prerequisites**: If `e2e_instructions` indicates that a local server must be running (look for explicit cues such as \"server\", \"running\", \"localhost\", \"started\", \"dev server\", a URL, or a port number) and describes a readiness check, perform that check exactly as described. If the instructions describe a server prerequisite but do not describe a check, attempt the check the instructions imply (e.g., curl the URL the instructions mention) and skip the stage if it fails:\n ```\n E2E tests: SKIPPED — e2e_testing_instructions describe a server prerequisite that wasn't met. Start the server per the instructions and re-run.\n ```\n\n3. **Derive the test command(s)** from the instructions, including any spec-directory batching the instructions specify.\n\n4. **If the instructions do not specify any runnable command**, skip and record:\n ```\n E2E tests: SKIPPED — e2e_testing_instructions does not describe how to invoke tests; please update via /learn-e2e-testing.\n ```\n\n5. **Run each batch sequentially** in the terminal. **Continue to the next batch even if the current one has failures.** Capture the full output and summary line of each batch.\n\n6. For each failing test, apply the **Triage Logic** (below), then record the result.\n\n## Triage Logic\n\nFor every failing test, examine the test file and the code it tests. Classify as ONE of the following:\n\n### TEST-CODE ISSUE — fix it directly\n\nClassify as a test-code issue if ANY of the following applies:\n- The test asserts against a hardcoded value that no longer matches current behavior (outdated mock data)\n- The test imports or calls a function that was renamed, moved, or removed\n- The test asserts on a response field that was restructured\n- The test expects a specific error message string that has since changed\n- A fixture references a removed table column, model field, or schema member\n\n**Action**: Apply a minimal, targeted fix to the test file only. Then re-run just that failing test, using the runner described in the relevant instructions field (`unit_instructions` for unit-test failures, `e2e_instructions` for E2E failures). Adapt the runner invocation that the instructions provide to target a single test, following whatever convention the instructions or stack idiomatically use.\n\nIf the re-run **still fails** after your fix, do not make further edits — escalate to implementation-code issue instead and revert your change.\n\n### IMPLEMENTATION-CODE ISSUE (or UNCERTAIN) — document, do not fix\n\nClassify as an implementation issue if ANY of the following applies:\n- The production function raises an unexpected exception\n- A handler returns the wrong status code or response shape for a documented behavior\n- Business logic produces incorrect output that the test correctly asserts against\n- You are not confident the test is wrong\n\n**Action**: Do NOT modify any file outside the test directories described in `unit_testing_instructions` / `e2e_testing_instructions`. When in doubt about whether a path is test-only, treat it as production code and escalate. Record the failure in the implementation-issues document for the user to triage.\n\n## Stage 4 — Write Output Documents\n\n### Document 1: Test Run Report (always write this)\n\nWrite to: `{docs_dir}/testing/test-run-{run_timestamp}.md`\n\n```markdown\n# Test Run: {run_timestamp}\n\n## Configuration\n- Unit stack: {unit_stack or \"not configured\"}\n- E2E stack: {e2e_stack or \"not configured\"}\n- Unit tests: RUN | SKIPPED — (reason)\n- E2E tests: RUN | SKIPPED — (reason)\n\n## Unit Tests\n**Stack**: {unit_stack or \"not configured\"}\n**Result**: X passed, Y failed (sum across batches)\n\n### Batch 1: `<command>`\n**Result**: X passed, Y failed\n**Fixes applied**:\n- `path/to/test_file`: brief description of what was fixed\n- (or \"none\" if no fixes were needed)\n\n### Batch 2: `<command>`\n...\n\n**Failures escalated as implementation issues**: N\n\n## E2E Tests\n**Stack**: {e2e_stack or \"not configured\"}\n**Result**: X passed, Y failed (sum across batches)\n\n### Batch 1: `<command>`\n**Result**: X passed, Y failed\n**Fixes applied**: ...\n\n### Batch 2: `<command>`\n...\n\n**Failures escalated as implementation issues**: N\n\n## Overall Summary\n- Total test fixes applied: N\n- Suspected implementation issues found: N\n- Implementation issues document: {docs_dir}/testing/implementation-issues-{run_timestamp}.md\n (or \"not created — no issues found\")\n```\n\n### Document 2: Implementation Issues (only write if issues were found)\n\nIf at least one failure was escalated as an implementation-code issue, write to:\n`{docs_dir}/testing/implementation-issues-{run_timestamp}.md`\n\n```markdown\n# Suspected Implementation Issues: {run_timestamp}\n\nThese test failures were NOT fixed. They may indicate bugs in production code.\nA developer should investigate each item before merging.\n\n## Issue 1\n- **Test**: `path/to/test_file::test_function_name`\n- **Tier**: unit | e2e\n- **Failure message**: (paste the key assertion or exception line)\n- **Why not fixed**: (brief reasoning, e.g., \"production function raises KeyError on valid input\")\n\n## Issue 2\n...\n```\n\nIf no implementation issues were found, do NOT create this file.\n\n## Final Output\n\nAfter writing all documents, print this summary:\n\n```\nTest run complete: {run_timestamp}\nReport saved to: {docs_dir}/testing/test-run-{run_timestamp}.md\nImplementation issues: {docs_dir}/testing/implementation-issues-{run_timestamp}.md (if applicable)\nNo suspected implementation issues found. (if none)\n```\n",