@bridge_gpt/mcp-server 0.2.34 → 0.2.36
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +456 -370
- package/build/agent-capabilities/probe-context.js +8 -1
- package/build/agent-capabilities/probes.js +7 -1
- package/build/agents.generated.js +1 -1
- package/build/claude-review-workflow.js +264 -0
- package/build/cli-release.js +53 -0
- package/build/commands.generated.js +4 -4
- package/build/conductor/bridge-api-client.js +215 -0
- package/build/conductor/deny-enforcement-preflight.js +1 -0
- package/build/conductor/done-gate.js +44 -5
- package/build/conductor/epic-reconcile.js +6 -0
- package/build/conductor/install-doctor.js +462 -0
- package/build/conductor-bin.js +3 -3
- package/build/conductor-bundle-artifacts.js +30 -9
- package/build/doctor.js +234 -1
- package/build/executor/cli.js +32 -5
- package/build/executor/credentials.js +45 -11
- package/build/executor/deps.js +14 -0
- package/build/executor/env.js +23 -6
- package/build/executor/index.js +4 -0
- package/build/executor/job-runner.js +119 -9
- package/build/executor/permissions.js +12 -2
- package/build/executor/preflight.js +95 -8
- package/build/executor/prompt-spec.js +51 -0
- package/build/executor/runner.js +15 -2
- package/build/executor/service-unit.js +876 -0
- package/build/executor/test-clock.js +8 -0
- package/build/executor/types.js +0 -17
- package/build/executor/worker-command.js +62 -9
- package/build/index.js +575 -143
- package/build/init.js +153 -51
- package/build/install-bridge-conductor.js +491 -0
- package/build/install-bridge.js +628 -175
- package/build/install-reexec.js +233 -0
- package/build/mcp-host-config.js +11 -1
- package/build/mcp-install-state.js +32 -0
- package/build/mcp-provisioning.js +22 -6
- package/build/pipelines.generated.js +14 -8
- package/build/readme.generated.js +1 -1
- package/build/run-unit-tests-launcher.js +257 -0
- package/build/setup-epic.js +117 -8
- package/build/upgrade-cli.js +1 -15
- package/build/version.generated.js +1 -1
- package/docs/CONDUCTOR.md +115 -4
- package/docs/install/mcp-tool-integrations.md +29 -21
- package/package.json +8 -5
- package/pipelines/implement-ticket.json +6 -1
- package/build/conductor/supervisor-judgment-python.js +0 -141
- package/build/conductor/supervisor-judgment.js +0 -215
|
@@ -10,12 +10,12 @@ 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_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",
|
|
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 council.\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 council 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 council or a design on unratified criteria.\n\n## Stage 7 — Council Gate\n\nThe criteria are ratified. Now assess honestly whether you know **how** to meet them — and offer to convene a council when you do not.\n\n**Lean toward offering.** A council 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 council 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 council before I draft the design? (y/N)\n ```\n\n Mention that a council 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 council was offered and declined, and proceed to Stage 8 on your own analysis. Never run a council 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 council'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 council's approaches, objections, and any option you had not considered into Stage 8. If the council 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 council fails or times out, note the failure visibly and proceed with your own analysis — a missing council 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 council 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 council, 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 council** (`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, council {\"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
|
-
"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: **6**. The install manifest returns a `command_contract_version`; Stage 2\ncompares it to this number to detect a stale scaffolded copy of this command.\n\nThis command has two modes, chosen by the project's state (Stage 2 decides from the manifest's\n`configured` flag), never by the caller's role:\n\n- **Fresh configuration** (`configured == false`): the full derive → approve → apply → report flow\n below, for an admin or legacy caller. This is the original, unchanged install path.\n- **JOIN MODE** (`configured == true`): the project is already set up, so this run proposes and\n applies ZERO configuration changes for ANY caller. A new teammate — including a non-admin \"member\"\n key — gets a graceful welcome and the concise capability report instead of an error. An eligible\n b2b admin is additionally offered the teammate-invite stage (Stage 11).\n\nThis command performs a one-time \"easy install\" of Bridge API project configuration. It reads the\nserver-owned install manifest once, derives values for the **unset** bootstrap fields from the local\ncodebase, asks for human approval of the project description, applies everything in a single atomic\ncall, and then presents a **concise capability report** derived from a fresh read-after-write manifest\nread. The server owns all skip-if-set, conflict, and confirmation semantics — this command never makes\nits own skip-if-set decisions — and the server owns the complete tool catalog and the bounded concise\nprojection over it, their grouping and ordering, and every gate and dependency relationship; this\ncommand formats the server's contract and never recomputes it from prose. Indexing is never a decision\nthis command makes or asks about: it starts automatically, gated entirely by server-side readiness (see\nStage 8).\n\nThis command is portable across Claude Code, Cursor, and Copilot: it only drives the Bridge API MCP\ntools (`get_my_role`, `get_install_manifest`, `apply_install_manifest`, and — in the gated Stage 11\nonly — `invite_member`).\n\nIf any stage fails, stop immediately and report which stage failed and why.\n\n**Install-spawn context.** When the spawning instruction explicitly says this `/install-bridge` run is\nin the \"install-spawn context\" (it was launched by the `install-bridge` CLI's fresh agent session),\nStage 8, Stage 9, and Stage 10 are SKIPPED and the single closing interaction is the concise capability\nreport plus a `/learn-repository` recommendation that the spawn prompt owns. When you invoke\n`/install-bridge` directly (manual invocation), Stages 8, 9, and 10 run normally. Stage 11 is NOT part\nof that install-spawn skip set — it is independently gated (admin + b2b + interactive) and best-effort,\nso it may still run in the install-spawn context for an eligible admin.\n\n## Stage 1 — Admin preflight (defer the permission decision until the manifest is read)\n\n1. Call the `get_my_role` MCP tool (no parameters). Retain its `role`, `source`, and `customer_type`\n values — later stages branch on all three (Stage 2's mode decision uses `role`/`source`; Stage 11's\n invite gate uses `role` and `customer_type`).\n2. Classify the caller, but do NOT stop here — the member permission decision is DEFERRED until Stage 2\n has read the manifest and determined whether the project is already `configured`. A member must be\n allowed to continue at least far enough to read the manifest, because a member CAN join an\n already-configured project even though a member cannot configure a fresh one:\n - If `source` is `\"legacy\"`, or `role` is `\"admin\"`: the caller is configuration-capable (it may run\n the fresh-configuration flow when the project is unconfigured).\n - Otherwise (a non-admin `user_access` \"member\" key): the caller is join-only. It may proceed into\n JOIN MODE for a configured project, but must be refused if Stage 2 proves the project is not yet\n configured (it cannot configure a fresh repo).\n3. Preserve this exact refusal text for later use — it is emitted in Stage 2 ONLY when a non-admin\n member reaches a `configured == false` project:\n ```\n Admin role required to apply install configuration. Ask a project admin to run /install-bridge,\n or use an admin API key.\n ```\n\n## Stage 2 — Read the manifest (once, pre-apply)\n\n1. Call the `get_install_manifest` MCP tool exactly once here.\n2. Keep the returned `snapshot_token` verbatim — you must pass the SAME token to the apply call in\n Stage 5. Do not call `get_install_manifest` again before applying; a fresh read would invalidate\n the token you are about to use. (Stage 7 performs a SEPARATE, later read-after-write manifest read\n for the current capability status — that is deliberate and does not reuse this token.)\n3. The manifest contains ordered `groups` of bootstrap fields (each with `field_name`, `is_set`,\n `current_value`, `guidance`, `examples`, `validation_summary`, `requires_confirmation`), a list of\n `deferred_fields`, a `next_step`, `done_criteria`, a `command_contract_version`, and the\n `snapshot_token`. It also carries the additive capability fields (`integrations`, `configured`,\n `learned`, `indexed`, `tool_capabilities`, `concise_tool_capabilities`, `locked_tools`,\n `unlocked_tools`) — but ignore those here; the accurate capability status is the post-apply read in\n Stage 7. `tool_capabilities` is the COMPLETE catalog-backed report field (one entry per registered\n MCP tool, grouped and ordered by the server); `concise_tool_capabilities` is the ADDITIVE, bounded\n projection Stage 7 actually renders (see Stage 7); `locked_tools` / `unlocked_tools` are LEGACY\n compatibility data covering only the VCS/index policy cases and are NOT the tool inventory.\n4. Compare the manifest's `command_contract_version` to this command's contract version (6, stated at\n the top of this file). If the manifest's version is HIGHER, this scaffolded command copy is stale:\n warn the user to refresh it by running `npx -y @bridge_gpt/mcp-server --init` in the project root,\n then proceed conservatively — wherever the manifest's `guidance`, `next_step`, or `done_criteria`\n differ from these instructions, follow the manifest.\n5. **Decide the install mode from `configured`.** Read the manifest's `configured` readiness flag (use\n ONLY `configured` for this decision — not `learned` or `indexed`) and branch:\n - **`configured == true` → JOIN MODE, for EVERY caller** (admin, legacy, or member). The project is\n already set up, so this run makes ZERO configuration changes. Emit a concise welcome — for\n example: \"This Bridge project is already configured. You're joining it as a new teammate; no\n configuration changes will be proposed or applied.\" Then SKIP Stages 3, 4, and 5 entirely (no\n field derivation, no project-description approval, no `apply_install_manifest` call, no\n `config_field` writes), run Stage 6 (persist the routing credential), and render the JOIN MODE\n branch of Stage 7 (the concise capability report, drawn directly from THIS Stage-2 manifest — no\n read-after-write). Then SKIP Stages 8, 9, and 10 for every caller. A member STOPS after the Stage 7\n report; only an eligible admin continues to Stage 11.\n - **`configured == false` → apply the deferred Stage 1 role decision:**\n - `source == \"legacy\"` or `role == \"admin\"`: run the fresh-configuration flow (Stages 3 → 4 → 5 →\n 6 → 7 → 8 → 9 → 10) exactly as written, unchanged.\n - a non-admin `user_access` \"member\" key: stop immediately and display the exact refusal text\n preserved in Stage 1 (\"Admin role required to apply install configuration…\"). Do not derive,\n apply, or persist anything.\n - **`configured` absent / indeterminate (neither `true` nor `false`) → do NOT treat it as `false`.**\n `configured` comes from a best-effort capability enrichment that can silently omit the key on a\n transient server-side probe failure, so a missing value is \"unknown\", not \"unconfigured\". Re-read\n the manifest ONCE (a fresh `get_install_manifest` call) to try to resolve it, and branch on the\n refreshed value if it is now definitive. If it is STILL absent:\n - `source == \"legacy\"` or `role == \"admin\"`: proceed with the fresh-configuration flow, but NOT\n silently — first tell the user that configuration status could not be confirmed and that the run\n will attempt configuration anyway (the server owns skip-if-set, so an apply against an\n already-configured repo is a safe no-op).\n - a non-admin `user_access` \"member\" key: take the JOIN-MODE-safe path — render the welcome and the\n Stage 7 capability report (no config writes, no offers) and note that configuration status could\n not be confirmed. Do NOT emit the hard \"Admin role required\" STOP: that refusal is reserved for a\n *definitive* `configured == false`, because treating an unknown state as unconfigured would\n re-introduce the very member hard-refusal this flow removes.\n\n## Stage 3 — Derive values for UNSET bootstrap fields only\n\n**Skip this entire stage in JOIN MODE** (Stage 2 selected JOIN MODE because the manifest reported\n`configured == true`). JOIN MODE derives nothing — it proposes and applies zero configuration for every\ncaller. Run this stage only on the `configured == false` fresh-configuration path.\n\n1. Consider ONLY fields whose `is_set` is `false`. Never re-derive or overwrite a field that is\n already set — the server will also skip already-set fields, but you should not even propose them.\n2. For each unset field, derive a value from the local codebase following that field's `guidance`\n (e.g. infer `working_in` from frameworks/manifests, `version_control_system` from the git remote,\n testing stacks from test config and dependencies, directory fields from the repo layout).\n3. Omit any field you are uncertain about or that does not apply — leaving it unset is always\n acceptable. Do NOT guess.\n4. Specifically, do NOT invent a `version` when the platform has no meaningful version concept; leave\n it unset.\n5. Before deriving `version_control_system` or `base_branch`, confirm the git repository root is THIS\n project's root: `git rev-parse --show-toplevel` must resolve to the project directory itself. If\n the git root is an ancestor directory (the project is nested inside another repository), OMIT both\n fields and note why in the final report — deriving them would describe the parent repository, not\n this project.\n6. If you find real evidence for TWO OR MORE plausible values for a field (e.g. configs for multiple\n test frameworks, multiple frameworks in a monorepo), treat the value as ambiguous and omit it\n rather than picking one.\n7. Do NOT derive `selected_mcp_slugs`, even though it appears as an unset bootstrap-eligible field in\n the manifest. MCP validation manual selection is deferred to `/learn-repository`, which derives and\n confirms it with the codebase already researched. Install neither proposes nor applies this field.\n\n## Stage 4 — Human approval for confirmation-requiring fields\n\n**Skip this entire stage in JOIN MODE** — there is nothing to derive, so there is nothing to approve.\nRun it only on the `configured == false` fresh-configuration path.\n\n`project_description` is the ONLY confirmation-requiring field install proposes. It carries\n`requires_confirmation: true` in the manifest, so it is never applied on derivation alone — it needs\nexplicit human approval. (`selected_mcp_slugs` also requires confirmation, but install does not\nderive it at all; `/learn-repository` asks for it. See Stage 3 step 7.)\n\n1. If `project_description` is unset and you can draft a concise description from the codebase,\n present the proposed `project_description` text to the human and ask for explicit approval before\n including it.\n2. Include `project_description` in the apply payload ONLY as\n `{ \"value\": <approved value>, \"confirmed\": true }`, and only after the human approves it. If the\n human does not approve it, omit the field entirely.\n3. If no human response can be obtained (e.g. a non-interactive / headless session), do NOT stall and\n do NOT abandon the install: proceed to Stage 5 with `project_description` omitted, and report it\n as \"pending human input\" in the final summary. The other derived fields must still be applied — an\n unapproved description never blocks them.\n\n## Stage 5 — Apply (one call)\n\n**Skip this entire stage in JOIN MODE** — JOIN MODE makes NO `apply_install_manifest` call and writes\nzero fields for every caller. Run it only on the `configured == false` fresh-configuration path.\n\n1. Make exactly ONE call to the `apply_install_manifest` MCP tool, passing:\n - `snapshot_token`: the exact token from Stage 2.\n - `fields`: a map of the derived fields. Scalar fields may be passed directly\n (e.g. `\"base_branch\": \"main\"`); an approved `project_description` must use the\n `{ \"value\": ..., \"confirmed\": true }` object form from Stage 4. Never include\n `selected_mcp_slugs` in this payload — install does not derive or apply it (Stage 3 step 7).\n2. Do not implement any client-side skip-if-set, conflict, or confirmation logic — the server owns\n all of that and returns the outcome buckets.\n3. The apply is partial-tolerant: fields that fail server-side validation are returned in the\n `rejected` bucket while the valid fields still commit. A rejected field is therefore reported,\n not fatal — do NOT retry the whole apply just because one field was rejected.\n\n## Stage 6 — Persist the routing credential\n\n**This stage runs in BOTH modes** — JOIN MODE persists the routing credential too, so a joining\nteammate's shell-spawned CLI features (`start-tickets`) can resolve the key. Its fail-open behavior\nbelow is unchanged in either mode.\n\nThe Bash-spawned `start-tickets` CLI runs in a DIFFERENT runtime surface than this MCP server, so a\nkey that lives only in `.mcp.json` / `.cursor/mcp.json` is invisible to it and difficulty→model\nrouting silently degrades. This final stage persists the already-validated key into the user-scoped\ncredential store (`~/.config/bridge/credentials.json`) so shell-spawned CLI commands can resolve it.\n\n1. Call the `persist_routing_credential` MCP tool with `repo_name` set to the repository name for\n this install (the configured `BAPI_REPO_NAME`). Pass `repo_name` ONLY — this tool resolves the\n API key inside the MCP server process. NEVER pass or display `BAPI_API_KEY` (nor `api_key`,\n `apiKey`, `secret`, or `token`); the key value must not appear in the tool call or in any output.\n2. On success, tell the user the credential was stored, echoing the returned `target` and `path`,\n e.g. `Stored routing credential for bapi:<repo_name> at <path>`.\n3. On failure, do NOT block the install — show the rest of the install summary anyway, then tell the\n user the routing credential could not be stored. They can rerun `/install-bridge` after setting\n `BAPI_API_KEY` in the environment, or run\n `npx -y @bridge_gpt/mcp-server credentials migrate-agent-config --write-credentials` to migrate an\n existing key. Until then, `start-tickets` model routing fails open (assumes a hard ticket and\n defaults to premium/Opus when available) — this is the MOST EXPENSIVE model tier, so unexplained\n cost is the symptom of leaving this unfixed. Recommend verifying credential resolution afterwards\n with `npx -y @bridge_gpt/mcp-server doctor`.\n\n## Stage 7 — Summarize the outcome, then present the concise capability report\n\n**JOIN MODE branch (`configured == true`).** Do NOT print an applied count and do NOT fabricate apply\nbuckets — no apply happened. Instead state plainly that the project was already configured and that\nzero configuration changes were proposed or applied (the welcome from Stage 2). Then render the concise\ncapability report described in \"### Read-after-write\" below, with ONE difference: source it directly\nfrom the `concise_tool_capabilities` field of the Stage-2 manifest you already read — do NOT perform a\nread-after-write `get_install_manifest` call, because no write occurred and there is nothing to\nrefresh. Apply the same server-authority rendering rules (server order, `more_count` handling,\nmalformed/missing fallback) verbatim. After the report, a member is DONE; an eligible admin proceeds to\nStage 11. The rest of this stage (the applied-count line and six-bucket summary) applies ONLY to the\n`configured == false` fresh-configuration path.\n\n**Fresh-configuration branch (`configured == false`).**\nFirst, begin with an explicit applied count: \"Applied N of M derivable fields\" (M = the unset\nbootstrap fields you derived values for). An install that applied 0 fields must say so loudly — the\ninstall is NOT complete until the apply call reports applied fields. This applied-count line and the\nsix-bucket summary below remain the PRIMARY install result — the capability report that follows is a\nsecondary close, not a replacement for it.\n\nThen summarize the six buckets from the apply response for the user:\n- `applied` — fields written this run.\n- `skipped` — fields already set (left untouched).\n- `conflict` — fields that changed since the manifest was read (re-run /install-bridge to retry).\n- `needs_confirmation` — fields awaiting explicit confirmation (e.g. project_description).\n- `rejected` — fields that failed validation or were not bootstrap-eligible (the other fields still\n applied; fix or drop the rejected values before any retry).\n- `deferred` — fields intentionally not auto-written by install (owned by /learn-repository or set\n deliberately). `selected_mcp_slugs` belongs here: report it as deferred to `/learn-repository`,\n never as approved, declined, or pending an install-time decision.\n\n### Read-after-write: fetch the concise capability report\n\nAfter the bucket summary, call the `get_install_manifest` MCP tool ONCE MORE. This post-apply read\nreflects the configuration you just wrote (the Stage-2 read was pre-apply and is stale for this\npurpose). This read does not need the snapshot token. Use ONLY this post-write response for the\nreport below.\n\nThe response carries `concise_tool_capabilities` — an ADDITIVE, bounded projection over the complete\n`tool_capabilities` catalog (which the response still carries unchanged; this stage simply does not\nrender it). It is a server-ordered array of at most two tiers, each\n`{id, name, tools: [{tool, display_name}], more_count}`, covering only \"Regularly useful\" and\n\"Occasionally useful\", available-now tools only, with everything else in those two tiers collapsed\ninto that tier's `more_count`.\n\nServer authority: the server computed this projection's tier selection, availability filter, and\n`more_count` arithmetic. Never recompute, re-filter, re-count, or re-derive it from `tool_capabilities`,\n`docs/mcp-tool-integrations.md`, or any other documentation — render exactly what the server sent.\n\nIf the post-write response has no `concise_tool_capabilities` field at all, or it is present but\nmalformed (not the `{id, name, tools, more_count}` tier shape described above), print exactly:\n`No capability status is available yet; configuration can still continue.` and skip the section below\nentirely — never fall back to rendering the complete `tool_capabilities` catalog or a remembered/\nhallucinated capability list.\n\nOtherwise, render exactly one section, with this exact heading:\n\n**What Bridge can help with**\n\n- Render each tier from `concise_tool_capabilities` in the server's given order: \"Regularly useful\"\n first, then \"Occasionally useful\". Do not reorder, filter, re-tier, or drop a tier the server\n included, even if its `tools` array is empty.\n- Within a tier, list each tool's `display_name` only, in server order — no description,\n `availability_text`, effect, dependency explanation, or variant detail; those live on the complete\n `tool_capabilities` field, which this section does not touch.\n- Render the tier's `more_count` as plain, muted-style summary text (\"+N more\") — never as an\n expansion prompt, a link, or something requiring further action. Omit the \"+N more\" line entirely\n when `more_count` is `0`.\n- Do not locally filter, count, regroup, infer availability, or fall back to the complete\n `tool_capabilities` collection for this section under any circumstance.\n\n## Stage 8 — Offer the next step\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it); the\nspawn prompt owns the single closing concise-report-plus-learn-recommendation there. On direct manual\n`/install-bridge` invocation, run it normally:\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\n1. Offer to continue with `/learn-repository` to populate the deeper instruction-tier configuration\n (architecture, review, testing, and correctness standards), matching the manifest's `next_step`.\n Mention that it also derives and confirms the applicable MCP validation manuals\n (`selected_mcp_slugs`) — it researches the codebase first, so it can propose them with evidence\n and explain what they do, which is why install leaves that field alone.\n2. Do NOT ask about repository indexing in any form. There is no consent question, no\n `parse_repository` tool call, and no `/parse-repository` continuation here — indexing starts\n automatically once the repository reaches full parse readiness (VCS credentials, the Pinecone\n index, `working_in` / `project_description`, and SFCC prerequisites where applicable), via the\n same readiness-gated funnel the GitHub connection-confirm endpoints and the scheduled sweep already\n use. Do not claim indexing has already started — this command has no visibility into that funnel's\n outcome.\n\n## Stage 9 — Offer CI follow-up configuration (only when CI is detected)\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and learn recommendation the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\nThis stage is separate from the single apply call: it writes at most ONE field via the\n`config_field` MCP tool. `ci_followup_config` is REPLACE-NOT-AUGMENT — leaving it NULL already means\nsafe poll-only defaults, so \"skip\" is always a correct answer.\n\n1. Gate: only offer this when Stage 3 found real CI evidence (e.g. `.github/workflows/*.yml`,\n `bitbucket-pipelines.yml`). With no CI detected, skip this stage and note \"no CI detected — CI\n follow-up not offered\" in the final report.\n2. Ask ONE question, referencing the discovered CI by name, with exactly these preset profiles\n (default: skip):\n - **observe** — poll CI results only, never attempt fixes:\n `{\"strategy\": \"poll_only\", \"max_iterations\": 1, \"max_minutes\": 10, \"instructions\": \"\"}`\n - **self-heal** — bounded fix-and-iterate loop on the automation's own PRs:\n `{\"strategy\": \"fix_and_iterate\", \"max_iterations\": 3, \"max_minutes\": 45, \"instructions\": \"\"}`\n - **skip** (default) — leave `ci_followup_config` unset (NULL = baseline poll-only behavior).\n3. Do NOT offer or compose a `custom` strategy during install — free-form CI follow-up instructions\n are a deliberate later act (setup UI or a direct `config_field` update).\n4. When the human picks a profile, call the `config_field` MCP tool once (operation `\"update\"`,\n `field_name: \"ci_followup_config\"`, `value`: the profile's JSON object). If the server rejects the\n value, retry ONCE with a corrected payload; if it is rejected again, stop, show the proposed JSON\n to the human, and leave the field unset.\n5. Never select a profile in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never enable fix-and-iterate behavior.\n\n## Stage 10 — Offer the speed-vs-quality repository preference\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and learn recommendation the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\nThis stage is separate from the single apply call: it writes at most ONE field via the `config_field`\nMCP tool, `field_name: \"speed_vs_quality\"`. The column defaults to `5` (max quality) for every\nrepository, so \"skip\" always leaves a safe, valid value in place.\n\n1. Never ask this question in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never block on or silently answer this preference.\n2. Read the current value first via the `config_field` MCP tool (operation `\"get\"`,\n `field_name: \"speed_vs_quality\"`) so a reinstall can show the stored value — not always `5` — as\n the displayed default rather than silently re-asking from scratch.\n3. Ask ONE question with exactly these five numbered presets (default: the value from step 2, or `5`\n if this is the first install):\n - **1** — Max speed\n - **2** — Prefer speed\n - **3** — Balanced\n - **4** — Prefer quality\n - **5** — Max quality (default)\n4. Persist ONLY on an explicit answer — including an explicitly accepted default — by calling the\n `config_field` MCP tool once (operation `\"update\"`, `field_name: \"speed_vs_quality\"`,\n `value`: the selected integer 1-5). Do not overwrite an existing value when the human gives no\n answer at all (e.g. the session cannot obtain one) — leave the stored/default value untouched in\n that case, distinct from an explicit accepted-default selection of `5`.\n5. After a successful persist, emit one additive structured log line (mirroring the codebase's\n `logging.info(msg, extra={...})` convention for non-response-body observability signals) with\n fields: `event=\"install.speed_vs_quality\"`, `repo_name`, `field_name=\"speed_vs_quality\"`,\n `selected_preset` (the persisted integer), `outcome=\"persisted\"`. Never log this event before the\n `config_field` tool call has confirmed the write.\n6. When skipped, emit the corresponding structured event with `outcome` set to one of\n `\"skipped_non_interactive\"` (non-interactive session) or `\"skipped_no_answer\"` (interactive session,\n no explicit answer obtained) — omit `selected_preset` and any prompt text from this event.\n7. If the `config_field` call is rejected, retry ONCE with a corrected payload; if it is rejected\n again, stop, show the proposed value to the human, and leave the field at its current stored value.\n Do not log a persistence-success event for a rejected or failed write.\n\n## Stage 11 — Invite teammates (gated: b2b admins only; best-effort)\n\nThis is a best-effort final stage that lets an eligible admin mint teammate keys after configuration or\nJOIN MODE. It is **independently gated** and is NOT part of the install-spawn skip set (Stages 8–10) —\nit may run in the install-spawn context for an eligible admin. The entire stage is **fail-open**: a\nprompt failure, a declined offer, a non-interactive context, a malformed tool response, or an\n`invite_member` failure must NEVER cause this command to report the (already-completed) install as\nfailed.\n\n1. **Eligibility gate (AND).** Offer this stage ONLY when BOTH hold, using the values retained in\n Stage 1:\n - `role == \"admin\"`, AND\n - `customer_type == \"b2b\"`.\n Otherwise skip the stage silently with NO prompt: a member, a legacy-source caller whose role is not\n explicitly `\"admin\"`, and a b2c admin all skip. Reachable from BOTH the fresh-admin close (after\n Stage 10) and the JOIN MODE admin path (after the Stage 7 report), including an admin re-run against\n an already-configured b2b project.\n2. **Interactive surface required.** This stage needs a human response. If no interactive response can\n be obtained (a non-TTY / headless / spawn context that cannot prompt), skip the stage silently\n without changing the completed install result — do not stall.\n3. **Offer prompt.** Ask exactly: `Invite teammates to this project? (y/N)`. Treat a blank answer, `n`,\n `no`, an unavailable response, or any prompt failure as a non-fatal decline — skip the rest of the\n stage and report it as declined.\n4. **Collect invitees.** On an affirmative answer, collect one or more teammate email entries using\n normal **echoed** input (email is PII, not a secret — never use a muted/hidden secret prompt).\n Optionally collect a display name per entry.\n5. **Per-invite role.** Default each invitation to role `member`. Only set a specific request's role to\n `admin` after an explicit per-invite opt-up for that entry; never opt up by default.\n6. **Mint.** For each invitee, call the `invite_member` MCP tool exactly once with `{email, name?,\n role}`. Do NOT pass `repo_name` — the tool resolves the repository from the current session.\n7. **Show each key once.** After each successful call, display that response's plaintext `api_key`\n exactly once, associated with its intended recipient, followed by the exact warning:\n `Distribute securely; this key is shown once.` Do NOT repeat a minted key anywhere else — not in the\n final summary, not in retry guidance, not in diagnostics, not in a later stage.\n8. **Per-invite failure isolation.** Treat each mint failure as local to that invitee: report a\n sanitized failure for it, continue to any remaining invitees, and never change the already-completed\n install outcome. Do not surface raw error text, headers, or the caller's key.\n\n## Return\n\nThe Return contract depends on which mode Stage 2 selected.\n\n**Fresh-configuration return (`configured == false` admin/legacy path).**\nReport the admin check result, the \"Applied N of M\" count, the\napplied/skipped/conflict/needs_confirmation/rejected field names, any fields omitted for\nnested-repository or ambiguity reasons, the approval outcome for `project_description` — install's\nonly confirmation-requiring field — (approved / declined / pending human input), the fact that\n`selected_mcp_slugs` is deferred to `/learn-repository` rather than decided here, whether a\nstale-command warning was raised (manifest\n`command_contract_version` higher than this command's), whether the routing credential was persisted\n(the returned `target` and `path`, or the non-blocking failure remediation), the \"What Bridge can help\nwith\" concise capability report from the post-apply read-after-write manifest read, the CI follow-up\noutcome (profile written / skipped / no CI detected / pending / skipped in install-spawn context), the\nspeed-vs-quality preference outcome (persisted with its preset / skipped_non_interactive /\nskipped_no_answer / pending / skipped in install-spawn context), and the `/learn-repository`\nrecommendation.\n\n**JOIN MODE return (`configured == true` path).**\nReport the caller's role, the \"you're joining an already-configured project\" welcome and the explicit\nno-change status (zero configuration proposed or applied — do NOT report an applied count or apply\nbuckets), whether the routing credential was persisted (the returned `target` and `path`, or the\nnon-blocking failure remediation), and the \"What Bridge can help with\" concise capability report drawn\nfrom the Stage-2 manifest (no read-after-write). A member ends here.\n\n**Teammate-invitation outcome (Stage 11, both modes).**\nReport the Stage 11 outcome as counts/statuses only — one of offered, declined, skipped (not eligible,\nor non-interactive context), partially completed, or completed, plus how many keys were minted. Never\nrepeat teammate email addresses or minted key values in this summary.\n",
|
|
18
|
-
"learn-repository.md": "Learn and document all configuration fields for the repository by running parallel research agents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly -- the recipe determines which tools to call and with what parameters. There are exactly two narrow exceptions, both invoked directly by this command and never through the recipe: the `get_my_role` admin preflight at entry (immediately below) and the closing `get_install_manifest` capability report (step 6).\n\n## Admin preflight (UX guard — run this first)\n\nBefore the onboarding guidance below and before fetching the recipe, call the `get_my_role` MCP tool\nonce (the first of the two narrow exceptions above). Retain its `role` and `source`:\n\n- If `source` is `\"legacy\"`, or `role` is `\"admin\"`: continue to the guidance and recipe below.\n- Otherwise (any non-admin `user_access` result — e.g. a \"member\" key): stop immediately, run nothing\n else (no recipe fetch, no research, no configuration write), and display exactly one concise message:\n ```\n Admin role required to learn this repository. Learning writes shared Bridge project configuration,\n which only an admin may change. Ask a project admin to run /learn-repository, or use an admin API key.\n ```\n- If the `get_my_role` call fails or returns a malformed / unrecognized response, treat it as a\n preflight failure: stop with the same admin-required message rather than proceeding into\n configuration writes.\n\nThis preflight is a UX guard ONLY — it fails fast with one clear message instead of the cascade of\nper-field denials a non-admin would otherwise hit. It is NOT the security control: the authoritative\nenforcement is the existing server-side admin gate on the `config_field` update and\n`apply_install_manifest` routes, which already reject non-admin keys regardless of this client-side\ncheck.\n\n1. This command takes no arguments.\n\n2. **Before executing any recipe step**, tell the user what they are about to sit through and why it\n is worth it:\n\n ```\n Learning this repository. This takes a while — the research agents read the actual codebase, and\n all the unlearned fields are researched in parallel, so the wait is roughly the slowest single\n field rather than the sum of all of them. Fields that are already populated are skipped entirely.\n\n What this buys you: these fields are what ground Bridge's agents in THIS codebase. Planning,\n reviewing, and code generation all read them, so they follow your repository's actual\n architecture, testing, documentation, and correctness conventions instead of generic defaults.\n\n It runs unattended — there are no approval prompts during the run. You may be asked one batched\n question at the very end.\n ```\n\n Do not invent a specific number of minutes; the honest statement is the parallel-wait shape above.\n\n3. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"learn-repository\"`\n\n If the tool returns an error, stop and report the failure.\n\n4. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n Retain, for the closing summary: the consolidated research task's structured result (its per-field\n `status`, `character_count`, `condensed`, and `condensation_reason`), each upload step's result,\n and the final confirmation task's structured result. You will need all three — do not discard them\n as you go.\n\n5. After all steps complete, display a summary built from the results you retained:\n\n ```\n ## Learn Complete\n\n **Status**: Success / Completed with gaps / Failed at step N\n\n **Learned and applied**: <fields drafted this run and written to config>\n **Already populated (skipped)**: <fields skipped because they already had a value>\n **Condensed to fit the field limit**: <field — reason it was condensed, per field>\n **Gaps**: <fields whose research or upload failed, each named with its reason>\n **Confirmation**: <approved / applied / declined / pending human input / not applicable, per field>\n\n Review or edit any of these on the **Project Configuration** page, under **Code Writer Settings**\n for the learned instructions and **MCP Validation Manuals** for the manual selection. Bridge's\n agents read whatever is stored there, so correcting a wrong conclusion there changes their\n behavior.\n ```\n\n Rules for the summary:\n\n - A run where some fields failed but others applied is **`Completed with gaps`**, not `Failed`.\n Name every gap explicitly — an unnamed gap is worse than a failed run, because the user believes\n the field was learned.\n - Report confirmation candidates that could not be presented in a headless session with the exact\n phrase `pending human input`.\n - Every field that was condensed must appear with the reason it was condensed.\n\n6. **After** the `## Learn Complete` summary above is fully displayed, close with the same concise\n capability report `/install-bridge` renders (BAPI-658, AC-9). This is the recipe's ONE exception to\n \"do not call MCP tools directly\": call the `get_install_manifest` MCP tool EXACTLY ONCE here,\n directly, with no arguments beyond what it requires — never through the recipe, never a second time,\n and never to apply or change any configuration.\n\n The report is structurally and visually SUBORDINATE to `## Learn Complete` above it — it is a\n closing addendum, not a replacement for or a distraction from the learn summary's own status,\n fields, gaps, and confirmation outcome.\n\n If the `get_install_manifest` call errors, or its response has no `concise_tool_capabilities` field,\n or that field is present but malformed (not the server's `{id, name, tools
|
|
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 **Branch**: <selected branch>\n **PR**: <pull request URL>\n **last_commit_sha**: <latest pushed head SHA>\n **Verification**: <each bounded command run, with its observed outcome>\n **Correction commit**: <subject of the correction commit pushed after verification, or \"None\">\n **Unresolved findings**: <findings reported but not fixed, or \"None\">\n ```\n\n Rules for this summary:\n\n - **`last_commit_sha` is the latest *pushed* head**, not the commit that opened\n the PR. The pipeline opens the pull request before running its bounded\n verification, so a correction pushed afterwards moves the head — report the\n head as it stands after the final push.\n - **`Status` describes pipeline execution, not a merge verdict.** \"Success\" means\n the recipe's steps ran to completion; it does not mean CI passed, that the code\n review approved the change, or that the ticket is mergeable.\n - **Never self-declare a gate outcome.** Do not label the summary with claims such\n as \"CI passed\", \"checks green\", \"review approved\", or \"gate met\". Report the\n exact check and review states you observed instead — the `ci` and `code_review`\n gates are authoritative and the reconciler observes them independently.\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: **7**. The install manifest returns a `command_contract_version`; Stage 2\ncompares it to this number to detect a stale scaffolded copy of this command.\n\nThis command has two modes, chosen by the project's state (Stage 2 decides from the manifest's\n`configured` flag), never by the caller's role:\n\n- **Fresh configuration** (`configured == false`): the full derive → approve → apply → report flow\n below, for an admin or legacy caller. This is the original, unchanged install path.\n- **JOIN MODE** (`configured == true`): the project is already set up, so this run proposes and\n applies ZERO configuration changes for ANY caller. A new teammate — including a non-admin \"member\"\n key — gets a graceful welcome and the concise capability report instead of an error. An eligible\n b2b admin is additionally offered the teammate-invite stage (Stage 11).\n\nThis command performs a one-time \"easy install\" of Bridge API project configuration. It reads the\nserver-owned install manifest once, derives values for the **unset** bootstrap fields from the local\ncodebase, asks for human approval of the project description, applies everything in a single atomic\ncall, and then presents a **concise capability report** derived from a fresh read-after-write manifest\nread. The server owns all skip-if-set, conflict, and confirmation semantics — this command never makes\nits own skip-if-set decisions — and the server owns the complete tool catalog and the bounded concise\nprojection over it, their grouping and ordering, and every gate and dependency relationship; this\ncommand formats the server's contract and never recomputes it from prose. Indexing is never a decision\nthis command makes or asks about: it starts automatically, gated entirely by server-side readiness (see\nStage 8).\n\nThis command is portable across Claude Code, Cursor, and Copilot: it only drives the Bridge API MCP\ntools (`get_my_role`, `get_install_manifest`, `apply_install_manifest`, and — in the gated Stage 11\nonly — `invite_member`).\n\nIf any stage fails, stop immediately and report which stage failed and why.\n\n**Install-spawn context.** When the spawning instruction explicitly says this `/install-bridge` run is\nin the \"install-spawn context\" (it was launched by the `install-bridge` CLI's fresh agent session),\nStage 8, Stage 9, and Stage 10 are SKIPPED and the single closing interaction is the concise capability\nreport plus whatever conditional next step the manifest provided — the spawn prompt owns that same\n`next_step.command` rendering there, under the same non-empty rule. When you invoke\n`/install-bridge` directly (manual invocation), Stages 8, 9, and 10 run normally. Stage 11 is NOT part\nof that install-spawn skip set — it is independently gated (admin + b2b + interactive) and best-effort,\nso it may still run in the install-spawn context for an eligible admin.\n\nStage 6 is likewise NOT skipped in the install-spawn context — it still persists the routing\ncredential — but its SUCCESS output is silent there, because the `install-bridge` CLI has already told\nthe user where the credential landed and a second sentence is a duplicate. Silence covers every place\nthat success would otherwise be restated, including the Return contract, and it covers success ONLY: a\nStage 6 failure is still reported loudly and in full. JOIN MODE and manual invocation are outside this\nrule and report Stage 6 success exactly as they do today.\n\n## Stage 1 — Admin preflight (defer the permission decision until the manifest is read)\n\n1. Call the `get_my_role` MCP tool (no parameters). Retain its `role`, `source`, and `customer_type`\n values — later stages branch on all three (Stage 2's mode decision uses `role`/`source`; Stage 11's\n invite gate uses `role` and `customer_type`).\n2. Classify the caller, but do NOT stop here — the member permission decision is DEFERRED until Stage 2\n has read the manifest and determined whether the project is already `configured`. A member must be\n allowed to continue at least far enough to read the manifest, because a member CAN join an\n already-configured project even though a member cannot configure a fresh one:\n - If `source` is `\"legacy\"`, or `role` is `\"admin\"`: the caller is configuration-capable (it may run\n the fresh-configuration flow when the project is unconfigured).\n - Otherwise (a non-admin `user_access` \"member\" key): the caller is join-only. It may proceed into\n JOIN MODE for a configured project, but must be refused if Stage 2 proves the project is not yet\n configured (it cannot configure a fresh repo).\n3. Preserve this exact refusal text for later use — it is emitted in Stage 2 ONLY when a non-admin\n member reaches a `configured == false` project:\n ```\n Admin role required to apply install configuration. Ask a project admin to run /install-bridge,\n or use an admin API key.\n ```\n\n## Stage 2 — Read the manifest (once, pre-apply)\n\n1. Call the `get_install_manifest` MCP tool exactly once here.\n2. Keep the returned `snapshot_token` verbatim — you must pass the SAME token to the apply call in\n Stage 5. Do not call `get_install_manifest` again before applying; a fresh read would invalidate\n the token you are about to use. (Stage 7 performs a SEPARATE, later read-after-write manifest read\n for the current capability status — that is deliberate and does not reuse this token.)\n3. The manifest contains ordered `groups` of bootstrap fields (each with `field_name`, `is_set`,\n `current_value`, `guidance`, `examples`, `validation_summary`, `requires_confirmation`), a list of\n `deferred_fields`, a `next_step`, `done_criteria`, a `command_contract_version`, and the\n `snapshot_token`. It also carries the additive capability fields (`integrations`, `configured`,\n `learned`, `indexed`, `tool_capabilities`, `workflows`, `concise_tool_capabilities`, `locked_tools`,\n `unlocked_tools`) — but ignore those here; the accurate capability status is the post-apply read in\n Stage 7. `tool_capabilities` is the COMPLETE catalog-backed report field (one entry per registered\n MCP tool, grouped and ordered by the server); `workflows` is the separate curated collection of\n non-MCP workflows (slash commands and packaged CLI subcommands, which are not registered MCP tools\n and never appear in `tool_capabilities`); `concise_tool_capabilities` is the ADDITIVE projection over\n BOTH of those that Stage 7 actually renders — a server-ordered array of exactly two availability\n sections, each `{id, name, tools}` holding mixed capability items (see Stage 7); `locked_tools` /\n `unlocked_tools` are LEGACY compatibility data covering only the VCS/index policy cases and are NOT\n the tool inventory.\n4. Compare the manifest's `command_contract_version` to this command's contract version (7, stated at\n the top of this file). If the manifest's version is HIGHER, this scaffolded command copy is stale:\n warn the user to refresh it by running `npx -y @bridge_gpt/mcp-server --init` in the project root,\n then proceed conservatively — wherever the manifest's `guidance`, `next_step`, or `done_criteria`\n differ from these instructions, follow the manifest.\n5. **Decide the install mode from `configured`.** Read the manifest's `configured` readiness flag (use\n ONLY `configured` for this decision — not `learned` or `indexed`) and branch:\n - **`configured == true` → JOIN MODE, for EVERY caller** (admin, legacy, or member). The project is\n already set up, so this run makes ZERO configuration changes. Emit a concise welcome — for\n example: \"This Bridge project is already configured. You're joining it as a new teammate; no\n configuration changes will be proposed or applied.\" Then SKIP Stages 3, 4, and 5 entirely (no\n field derivation, no project-description approval, no `apply_install_manifest` call, no\n `config_field` writes), run Stage 6 (persist the routing credential), and render the JOIN MODE\n branch of Stage 7 (the concise capability report, drawn directly from THIS Stage-2 manifest — no\n read-after-write). Then EVALUATE Stage 8 conditionally — it renders only when THIS Stage-2\n manifest's `next_step.command` is a non-empty string, and is silent otherwise — and SKIP Stages 9\n and 10. Then continue to the independently gated Stage 11.\n The server has already encoded recommendation eligibility (learned state AND whether this caller\n can run the command) in `next_step.command`, so do NOT reproduce a role gate or a learned-state\n gate here: a joining member simply receives an empty command and sees nothing.\n - **`configured == false` → apply the deferred Stage 1 role decision:**\n - `source == \"legacy\"` or `role == \"admin\"`: run the fresh-configuration flow (Stages 3 → 4 → 5 →\n 6 → 7 → 8 → 9 → 10) exactly as written, unchanged.\n - a non-admin `user_access` \"member\" key: stop immediately and display the exact refusal text\n preserved in Stage 1 (\"Admin role required to apply install configuration…\"). Do not derive,\n apply, or persist anything.\n - **`configured` absent / indeterminate (neither `true` nor `false`) → do NOT treat it as `false`.**\n `configured` comes from a best-effort capability enrichment that can silently omit the key on a\n transient server-side probe failure, so a missing value is \"unknown\", not \"unconfigured\". Re-read\n the manifest ONCE (a fresh `get_install_manifest` call) to try to resolve it, and branch on the\n refreshed value if it is now definitive. If it is STILL absent:\n - `source == \"legacy\"` or `role == \"admin\"`: proceed with the fresh-configuration flow, but NOT\n silently — first tell the user that configuration status could not be confirmed and that the run\n will attempt configuration anyway (the server owns skip-if-set, so an apply against an\n already-configured repo is a safe no-op).\n - a non-admin `user_access` \"member\" key: take the JOIN-MODE-safe path — render the welcome and the\n Stage 7 capability report (no config writes, no Stage 9/10 offers), evaluate Stage 8 under its\n normal non-empty-command rule, and note that configuration status could not be confirmed. Do NOT\n emit the hard \"Admin role required\" STOP: that refusal is reserved for a\n *definitive* `configured == false`, because treating an unknown state as unconfigured would\n re-introduce the very member hard-refusal this flow removes.\n\n## Stage 3 — Derive values for UNSET bootstrap fields only\n\n**Skip this entire stage in JOIN MODE** (Stage 2 selected JOIN MODE because the manifest reported\n`configured == true`). JOIN MODE derives nothing — it proposes and applies zero configuration for every\ncaller. Run this stage only on the `configured == false` fresh-configuration path.\n\n1. Consider ONLY fields whose `is_set` is `false`. Never re-derive or overwrite a field that is\n already set — the server will also skip already-set fields, but you should not even propose them.\n2. For each unset field, derive a value from the local codebase following that field's `guidance`\n (e.g. infer `working_in` from frameworks/manifests, `version_control_system` from the git remote,\n testing stacks from test config and dependencies, directory fields from the repo layout).\n3. Omit any field you are uncertain about or that does not apply — leaving it unset is always\n acceptable. Do NOT guess.\n4. Specifically, do NOT invent a `version` when the platform has no meaningful version concept; leave\n it unset.\n5. Before deriving `version_control_system` or `base_branch`, confirm the git repository root is THIS\n project's root: `git rev-parse --show-toplevel` must resolve to the project directory itself. If\n the git root is an ancestor directory (the project is nested inside another repository), OMIT both\n fields and note why in the final report — deriving them would describe the parent repository, not\n this project.\n6. If you find real evidence for TWO OR MORE plausible values for a field (e.g. configs for multiple\n test frameworks, multiple frameworks in a monorepo), treat the value as ambiguous and omit it\n rather than picking one.\n7. Do NOT derive `selected_mcp_slugs`, even though it appears as an unset bootstrap-eligible field in\n the manifest. MCP validation manual selection is deferred to `/learn-repository`, which derives and\n confirms it with the codebase already researched. Install neither proposes nor applies this field.\n\n## Stage 4 — Human approval for confirmation-requiring fields\n\n**Skip this entire stage in JOIN MODE** — there is nothing to derive, so there is nothing to approve.\nRun it only on the `configured == false` fresh-configuration path.\n\n`project_description` is the ONLY confirmation-requiring field install proposes. It carries\n`requires_confirmation: true` in the manifest, so it is never applied on derivation alone — it needs\nexplicit human approval. (`selected_mcp_slugs` also requires confirmation, but install does not\nderive it at all; `/learn-repository` asks for it. See Stage 3 step 7.)\n\n1. If `project_description` is unset and you can draft a concise description from the codebase,\n present the proposed `project_description` text to the human and ask for explicit approval before\n including it.\n2. Include `project_description` in the apply payload ONLY as\n `{ \"value\": <approved value>, \"confirmed\": true }`, and only after the human approves it. If the\n human does not approve it, omit the field entirely.\n3. If no human response can be obtained (e.g. a non-interactive / headless session), do NOT stall and\n do NOT abandon the install: proceed to Stage 5 with `project_description` omitted, and report it\n as \"pending human input\" in the final summary. The other derived fields must still be applied — an\n unapproved description never blocks them.\n\n## Stage 5 — Apply (one call)\n\n**Skip this entire stage in JOIN MODE** — JOIN MODE makes NO `apply_install_manifest` call and writes\nzero fields for every caller. Run it only on the `configured == false` fresh-configuration path.\n\n1. Make exactly ONE call to the `apply_install_manifest` MCP tool, passing:\n - `snapshot_token`: the exact token from Stage 2.\n - `fields`: a map of the derived fields. Scalar fields may be passed directly\n (e.g. `\"base_branch\": \"main\"`); an approved `project_description` must use the\n `{ \"value\": ..., \"confirmed\": true }` object form from Stage 4. Never include\n `selected_mcp_slugs` in this payload — install does not derive or apply it (Stage 3 step 7).\n2. Do not implement any client-side skip-if-set, conflict, or confirmation logic — the server owns\n all of that and returns the outcome buckets.\n3. The apply is partial-tolerant: fields that fail server-side validation are returned in the\n `rejected` bucket while the valid fields still commit. A rejected field is therefore reported,\n not fatal — do NOT retry the whole apply just because one field was rejected.\n\n## Stage 6 — Persist the routing credential\n\n**This stage runs in BOTH modes** — JOIN MODE persists the routing credential too, so a joining\nteammate's shell-spawned CLI features (`start-tickets`) can resolve the key. Its fail-open behavior\nbelow is unchanged in either mode.\n\nThe Bash-spawned `start-tickets` CLI runs in a DIFFERENT runtime surface than this MCP server, so a\nkey that lives only in `.mcp.json` / `.cursor/mcp.json` is invisible to it and difficulty→model\nrouting silently degrades. This final stage persists the already-validated key into the user-scoped\ncredential store (`~/.config/bridge/credentials.json`) so shell-spawned CLI commands can resolve it.\n\n1. Call the `persist_routing_credential` MCP tool with `repo_name` set to the repository name for\n this install (the configured `BAPI_REPO_NAME`). Pass `repo_name` ONLY — this tool resolves the\n API key inside the MCP server process. NEVER pass or display `BAPI_API_KEY` (nor `api_key`,\n `apiKey`, `secret`, or `token`); the key value must not appear in the tool call or in any output.\n2. On success, tell the user the credential was stored, echoing the returned `target` and `path`,\n e.g. `Stored routing credential for bapi:<repo_name> at <path>`. EXCEPTION — in the install-spawn\n context (and outside JOIN MODE), persist silently: still call the tool, but print nothing on\n success and do not restate the `target` or `path` in any later summary or in the Return contract.\n The CLI already reported the credential destination, so this sentence would be a duplicate. This\n exception is success-only; step 3's failure reporting is unchanged in every context.\n3. On failure, do NOT block the install — show the rest of the install summary anyway, then tell the\n user the routing credential could not be stored. They can rerun `/install-bridge` after setting\n `BAPI_API_KEY` in the environment, or run\n `npx -y @bridge_gpt/mcp-server credentials migrate-agent-config --write-credentials` to migrate an\n existing key. Until then, `start-tickets` model routing fails open (assumes a hard ticket and\n defaults to premium/Opus when available) — this is the MOST EXPENSIVE model tier, so unexplained\n cost is the symptom of leaving this unfixed. Recommend verifying credential resolution afterwards\n with `npx -y @bridge_gpt/mcp-server doctor`.\n\n## Stage 7 — Summarize the outcome, then present the concise capability report\n\n**JOIN MODE branch (`configured == true`).** Do NOT print an applied count and do NOT fabricate apply\nbuckets — no apply happened. Instead state plainly that the project was already configured and that\nzero configuration changes were proposed or applied (the welcome from Stage 2). Then render the concise\ncapability report described in \"### Read-after-write\" below, with ONE difference: source it directly\nfrom the `concise_tool_capabilities` field of the Stage-2 manifest you already read — do NOT perform a\nread-after-write `get_install_manifest` call, because no write occurred and there is nothing to\nrefresh. Apply the same server-authority rendering rules (server section order, verbatim item copy,\nmalformed/missing fallback) verbatim. ALSO retain that Stage-2 manifest's `next_step` object: it is the\nauthoritative next-step source for this path, because the Stage-2 read is JOIN MODE's only manifest\nread. After the report, continue to Stage 8, which renders that `next_step` conditionally; an eligible\nadmin then proceeds to Stage 11. The rest of this stage (the applied-count line and six-bucket summary)\napplies ONLY to the `configured == false` fresh-configuration path.\n\n**Fresh-configuration branch (`configured == false`).**\nFirst, begin with an explicit applied count: \"Applied N of M derivable fields\" (M = the unset\nbootstrap fields you derived values for). An install that applied 0 fields must say so loudly — the\ninstall is NOT complete until the apply call reports applied fields. This applied-count line and the\nsix-bucket summary below remain the PRIMARY install result — the capability report that follows is a\nsecondary close, not a replacement for it.\n\nThen summarize the six buckets from the apply response for the user:\n- `applied` — fields written this run.\n- `skipped` — fields already set (left untouched).\n- `conflict` — fields that changed since the manifest was read (re-run /install-bridge to retry).\n- `needs_confirmation` — fields awaiting explicit confirmation (e.g. project_description).\n- `rejected` — fields that failed validation or were not bootstrap-eligible (the other fields still\n applied; fix or drop the rejected values before any retry).\n- `deferred` — fields intentionally not auto-written by install (owned by /learn-repository or set\n deliberately). `selected_mcp_slugs` belongs here: report it as deferred to `/learn-repository`,\n never as approved, declined, or pending an install-time decision.\n\n### Read-after-write: fetch the concise capability report\n\nAfter the bucket summary, call the `get_install_manifest` MCP tool ONCE MORE. This post-apply read\nreflects the configuration you just wrote (the Stage-2 read was pre-apply and is stale for this\npurpose). This read does not need the snapshot token. Use ONLY this post-write response for the\nreport below.\n\nRetain this post-apply response's `next_step` object as well. On the fresh-configuration path it — not\nthe pre-apply Stage-2 read — is the authoritative source for Stage 8's conditional next step. Neither\nbranch derives a command from `configured`, `learned`, or any role prose: the command is whatever the\nauthoritative manifest returned.\n\nThe response carries `concise_tool_capabilities` — an ADDITIVE projection over the complete\n`tool_capabilities` catalog and the curated `workflows` collection (the response still carries both\nunchanged; this stage simply does not render them). It is a server-ordered array of EXACTLY TWO\navailability sections, in this order:\n\n1. `{\"id\": \"available_now\", \"name\": \"Available now\", \"tools\": [...]}` — what works right now.\n2. `{\"id\": \"needs_setup\", \"name\": \"Needs setup\", \"tools\": [...]}` — what additional setup would unlock.\n\nEach entry in a section's `tools` array is a capability item:\n`{id, kind, display_name, description, how_to_use}`, where `kind` is `\"tool\"` or `\"workflow\"` and\n`how_to_use` may be `null`. Items in the `needs_setup` section carry ONE additional field,\n`availability_text` — the server's plain-language sentence naming what is missing.\n\nServer authority: the server computed this projection's section membership, availability decisions,\nretrieval-pair collapsing, and ordering. Never recompute, re-filter, re-count, re-sort, regroup, infer\navailability, pair a retrieval tool with a primary yourself, invent an item, or re-derive any of it from\n`tool_capabilities`, `workflows`, `docs/mcp-tool-integrations.md`, or any other documentation — render\nexactly what the server sent.\n\nIf the post-write response has no `concise_tool_capabilities` field at all, or it is present but\nmalformed (not the two-section `{id, name, tools}` shape described above), print exactly:\n`No capability status is available yet; configuration can still continue.` and skip the section below\nentirely — never fall back to rendering the complete `tool_capabilities` catalog, the `workflows`\ncollection, or a remembered/hallucinated capability list.\n\nOtherwise, render exactly one section, with this exact heading:\n\n**What Bridge can help with**\n\n- Render the two server sections in the order the server gave them — \"Available now\" first, then\n \"Needs setup\". Use the server's `name` as each sub-heading. Do not reorder, merge, filter, or drop a\n section, and do not add a third one.\n- Use semantic Markdown (a short bold or `###` sub-heading per section, one compact list item per\n capability) with tight vertical spacing — no table, no fixed-width columns, no ASCII box. Long\n descriptions, commands, and URLs must be free to wrap, so the report stays readable in a narrow\n terminal.\n- For each item in **Available now**, render its `display_name`, then its `description`, then its\n `how_to_use` when that value is a non-empty string (omit the invocation line entirely when it is\n `null` or empty). Render NO availability caveat, asterisk, footnote, or status note in this section —\n the server already decided these are available, including any tool that works with less codebase\n context before indexing.\n- For each item in **Needs setup**, render the same three fields, then the server's `availability_text`\n verbatim as emphasized setup guidance on its own line. Do not reword it, prefix it with a warning, or\n substitute setup advice of your own.\n- Render a `kind: \"workflow\"` item EXACTLY like a `kind: \"tool\"` item. `kind` is contract metadata for\n machine consumers, not a visual distinction: no icon, no label, no badge, no separate sub-list, no\n different indentation, and no client branching of any sort on its value.\n- Keep an empty section VISIBLE rather than dropping it. When **Available now** is empty, render the\n heading with one short neutral line such as \"Nothing is available yet.\" When **Needs setup** is empty,\n render the heading with one short line stating that every highlighted capability is ready — for\n example \"Everything highlighted here is ready to use.\"\n- Close the report with this quiet final line, after BOTH sections and regardless of whether either\n `tools` array was empty:\n See the [Bridge MCP server README](https://www.npmjs.com/package/@bridge_gpt/mcp-server) for the\n complete tool documentation.\n\n## Stage 8 — Render the server's next step (only when there is one)\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it); the\nspawn prompt owns the same conditional closing recommendation there. On direct manual\n`/install-bridge` invocation, run it normally.\n\n**This stage runs in JOIN MODE too** — it is no longer skipped wholesale for joining teammates. What\ngates it is the server's output, not the mode and not the caller's role.\n\nThis stage renders a decision the SERVER already made. The manifest's `next_step.command` encodes both\nwhether the repository still needs the deeper instruction-tier configuration AND whether this caller\ncan actually run the command; a caller who cannot gets an empty command. Never re-derive that from\n`configured`, `learned`, `role`, or `source`, and never substitute a command you happen to know.\n\n1. Read `next_step` from the AUTHORITATIVE manifest for this path (Stage 7 names it: the post-apply\n read-after-write response on the fresh-configuration path, the Stage-2 response in JOIN MODE).\n Then branch on `next_step.command` alone:\n - **`next_step.command` is a non-empty string** → render one short heading and the exact command\n the server returned, formatted as Markdown inline code — for example: ``Next step: `<command>` ``\n where `<command>` is that returned string, verbatim. Do not rename it, alias it, expand it into\n a different invocation, or replace it with a locally known command. Do not run it yourself:\n it remains the human's own explicit next invocation.\n - **`next_step.command == \"\"`** (or the key is missing/not a string) → be entirely SILENT. Emit no\n heading, no empty code span, no placeholder or fallback command, no separator or divider, no\n \"nothing to do\" notice, and no generic success or completion claim. The stage simply produces\n nothing and the run continues.\n2. Where you give supporting context for a rendered command, use the manifest's own\n `next_step.post_install_indexing` and `next_step.post_install_scheduler` text as the authoritative\n source rather than inventing a rationale for whatever command the server named. Keep that context\n subordinate to the command itself — it is explanation, not a second call to action.\n3. Do NOT ask about repository indexing in any form. There is no consent question, no\n `parse_repository` tool call, and no `/parse-repository` continuation here — indexing starts\n automatically once the repository reaches full parse readiness (VCS credentials, the Pinecone\n index, `working_in` / `project_description`, and SFCC prerequisites where applicable), via the\n same readiness-gated funnel the GitHub connection-confirm endpoints and the scheduled sweep already\n use. Do not claim indexing has already started — this command has no visibility into that funnel's\n outcome.\n\n## Stage 9 — Offer CI follow-up configuration (only when CI is detected)\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and the conditional next step the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\nThis stage is separate from the single apply call: it writes at most ONE field via the\n`config_field` MCP tool. `ci_followup_config` is REPLACE-NOT-AUGMENT — leaving it NULL already means\nsafe poll-only defaults, so \"skip\" is always a correct answer.\n\n1. Gate: only offer this when Stage 3 found real CI evidence (e.g. `.github/workflows/*.yml`,\n `bitbucket-pipelines.yml`). With no CI detected, skip this stage and note \"no CI detected — CI\n follow-up not offered\" in the final report.\n2. Ask ONE question, referencing the discovered CI by name, with exactly these preset profiles\n (default: skip):\n - **observe** — poll CI results only, never attempt fixes:\n `{\"strategy\": \"poll_only\", \"max_iterations\": 1, \"max_minutes\": 10, \"instructions\": \"\"}`\n - **self-heal** — bounded fix-and-iterate loop on the automation's own PRs:\n `{\"strategy\": \"fix_and_iterate\", \"max_iterations\": 3, \"max_minutes\": 45, \"instructions\": \"\"}`\n - **skip** (default) — leave `ci_followup_config` unset (NULL = baseline poll-only behavior).\n3. Do NOT offer or compose a `custom` strategy during install — free-form CI follow-up instructions\n are a deliberate later act (setup UI or a direct `config_field` update).\n4. When the human picks a profile, call the `config_field` MCP tool once (operation `\"update\"`,\n `field_name: \"ci_followup_config\"`, `value`: the profile's JSON object). If the server rejects the\n value, retry ONCE with a corrected payload; if it is rejected again, stop, show the proposed JSON\n to the human, and leave the field unset.\n5. Never select a profile in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never enable fix-and-iterate behavior.\n\n## Stage 10 — Offer the speed-vs-quality repository preference\n\n**Skip this entire stage in the install-spawn context** (the spawning instruction identifies it), so\nthe concise report and the conditional next step the spawn prompt owns remain the sole closing interaction. On direct\nmanual `/install-bridge` invocation, run it normally.\n\n**Also skip this stage in JOIN MODE** (`configured == true`): a joining teammate is offered no\nconfiguration follow-up; they stop after the Stage 7 capability report (an eligible admin continues to\nStage 11).\n\nThis stage is separate from the single apply call: it writes at most ONE field via the `config_field`\nMCP tool, `field_name: \"speed_vs_quality\"`. The column defaults to `5` (max quality) for every\nrepository, so \"skip\" always leaves a safe, valid value in place.\n\n1. Never ask this question in a non-interactive session — skip and list it as a pending next step. An\n unattended install must never block on or silently answer this preference.\n2. Read the current value first via the `config_field` MCP tool (operation `\"get\"`,\n `field_name: \"speed_vs_quality\"`) so a reinstall can show the stored value — not always `5` — as\n the displayed default rather than silently re-asking from scratch.\n3. Ask ONE question with exactly these five numbered presets (default: the value from step 2, or `5`\n if this is the first install):\n - **1** — Max speed\n - **2** — Prefer speed\n - **3** — Balanced\n - **4** — Prefer quality\n - **5** — Max quality (default)\n4. Persist ONLY on an explicit answer — including an explicitly accepted default — by calling the\n `config_field` MCP tool once (operation `\"update\"`, `field_name: \"speed_vs_quality\"`,\n `value`: the selected integer 1-5). Do not overwrite an existing value when the human gives no\n answer at all (e.g. the session cannot obtain one) — leave the stored/default value untouched in\n that case, distinct from an explicit accepted-default selection of `5`.\n5. After a successful persist, emit one additive structured log line (mirroring the codebase's\n `logging.info(msg, extra={...})` convention for non-response-body observability signals) with\n fields: `event=\"install.speed_vs_quality\"`, `repo_name`, `field_name=\"speed_vs_quality\"`,\n `selected_preset` (the persisted integer), `outcome=\"persisted\"`. Never log this event before the\n `config_field` tool call has confirmed the write.\n6. When skipped, emit the corresponding structured event with `outcome` set to one of\n `\"skipped_non_interactive\"` (non-interactive session) or `\"skipped_no_answer\"` (interactive session,\n no explicit answer obtained) — omit `selected_preset` and any prompt text from this event.\n7. If the `config_field` call is rejected, retry ONCE with a corrected payload; if it is rejected\n again, stop, show the proposed value to the human, and leave the field at its current stored value.\n Do not log a persistence-success event for a rejected or failed write.\n\n## Stage 11 — Invite teammates (gated: b2b admins only; best-effort)\n\nThis is a best-effort final stage that lets an eligible admin mint teammate keys after configuration or\nJOIN MODE. It is **independently gated** and is NOT part of the install-spawn skip set (Stages 8–10) —\nit may run in the install-spawn context for an eligible admin. The entire stage is **fail-open**: a\nprompt failure, a declined offer, a non-interactive context, a malformed tool response, or an\n`invite_member` failure must NEVER cause this command to report the (already-completed) install as\nfailed.\n\n1. **Eligibility gate (AND).** Offer this stage ONLY when BOTH hold, using the values retained in\n Stage 1:\n - `role == \"admin\"`, AND\n - `customer_type == \"b2b\"`.\n Otherwise skip the stage silently with NO prompt: a member, a legacy-source caller whose role is not\n explicitly `\"admin\"`, and a b2c admin all skip. Reachable from BOTH the fresh-admin close (after\n Stage 10) and the JOIN MODE admin path (after the Stage 7 report), including an admin re-run against\n an already-configured b2b project.\n2. **Interactive surface required.** This stage needs a human response. If no interactive response can\n be obtained (a non-TTY / headless / spawn context that cannot prompt), skip the stage silently\n without changing the completed install result — do not stall.\n3. **Offer prompt.** Ask exactly: `Invite teammates to this project? (y/N)`. Treat a blank answer, `n`,\n `no`, an unavailable response, or any prompt failure as a non-fatal decline — skip the rest of the\n stage and report it as declined.\n4. **Collect invitees.** On an affirmative answer, collect one or more teammate email entries using\n normal **echoed** input (email is PII, not a secret — never use a muted/hidden secret prompt).\n Optionally collect a display name per entry.\n5. **Per-invite role.** Default each invitation to role `member`. Only set a specific request's role to\n `admin` after an explicit per-invite opt-up for that entry; never opt up by default.\n6. **Mint.** For each invitee, call the `invite_member` MCP tool exactly once with `{email, name?,\n role}`. Do NOT pass `repo_name` — the tool resolves the repository from the current session.\n7. **Show each key once.** After each successful call, display that response's plaintext `api_key`\n exactly once, associated with its intended recipient, followed by the exact warning:\n `Distribute securely; this key is shown once.` Do NOT repeat a minted key anywhere else — not in the\n final summary, not in retry guidance, not in diagnostics, not in a later stage.\n8. **Per-invite failure isolation.** Treat each mint failure as local to that invitee: report a\n sanitized failure for it, continue to any remaining invitees, and never change the already-completed\n install outcome. Do not surface raw error text, headers, or the caller's key.\n\n## Return\n\nThe Return contract depends on which mode Stage 2 selected.\n\n**Fresh-configuration return (`configured == false` admin/legacy path).**\nReport the admin check result, the \"Applied N of M\" count, the\napplied/skipped/conflict/needs_confirmation/rejected field names, any fields omitted for\nnested-repository or ambiguity reasons, the approval outcome for `project_description` — install's\nonly confirmation-requiring field — (approved / declined / pending human input), the fact that\n`selected_mcp_slugs` is deferred to `/learn-repository` rather than decided here, whether a\nstale-command warning was raised (manifest\n`command_contract_version` higher than this command's), whether the routing credential was persisted\n(the returned `target` and `path`, or the non-blocking failure remediation — but in the install-spawn\ncontext report neither on success, per Stage 6's silence exception; a failure is still reported), the \"What Bridge can help\nwith\" concise capability report from the post-apply read-after-write manifest read, the CI follow-up\noutcome (profile written / skipped / no CI detected / pending / skipped in install-spawn context), the\nspeed-vs-quality preference outcome (persisted with its preset / skipped_non_interactive /\nskipped_no_answer / pending / skipped in install-spawn context), and the Stage 8 outcome — the exact\nserver-provided next-step command when the manifest returned a non-empty one, otherwise the fact that\nno next step was recommended (never a substituted command of your own).\n\n**JOIN MODE return (`configured == true` path).**\nReport the caller's role, the \"you're joining an already-configured project\" welcome and the explicit\nno-change status (zero configuration proposed or applied — do NOT report an applied count or apply\nbuckets), whether the routing credential was persisted (the returned `target` and `path`, or the\nnon-blocking failure remediation), the \"What Bridge can help with\" concise capability report drawn\nfrom the Stage-2 manifest (no read-after-write), and the Stage 8 outcome — the exact server-provided\nnext-step command when that manifest returned a non-empty one, otherwise the fact that no next step\nwas recommended.\n\n**Teammate-invitation outcome (Stage 11, both modes).**\nReport the Stage 11 outcome as counts/statuses only — one of offered, declined, skipped (not eligible,\nor non-interactive context), partially completed, or completed, plus how many keys were minted. Never\nrepeat teammate email addresses or minted key values in this summary.\n",
|
|
18
|
+
"learn-repository.md": "Learn and document all configuration fields for the repository by running parallel research agents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly -- the recipe determines which tools to call and with what parameters. There are exactly two narrow exceptions, both invoked directly by this command and never through the recipe: the `get_my_role` admin preflight at entry (immediately below) and the closing `get_install_manifest` capability report (step 6).\n\n## Admin preflight (UX guard — run this first)\n\nBefore the onboarding guidance below and before fetching the recipe, call the `get_my_role` MCP tool\nonce (the first of the two narrow exceptions above). Retain its `role` and `source`:\n\n- If `source` is `\"legacy\"`, or `role` is `\"admin\"`: continue to the guidance and recipe below.\n- Otherwise (any non-admin `user_access` result — e.g. a \"member\" key): stop immediately, run nothing\n else (no recipe fetch, no research, no configuration write), and display exactly one concise message:\n ```\n Admin role required to learn this repository. Learning writes shared Bridge project configuration,\n which only an admin may change. Ask a project admin to run /learn-repository, or use an admin API key.\n ```\n- If the `get_my_role` call fails or returns a malformed / unrecognized response, treat it as a\n preflight failure: stop with the same admin-required message rather than proceeding into\n configuration writes.\n\nThis preflight is a UX guard ONLY — it fails fast with one clear message instead of the cascade of\nper-field denials a non-admin would otherwise hit. It is NOT the security control: the authoritative\nenforcement is the existing server-side admin gate on the `config_field` update and\n`apply_install_manifest` routes, which already reject non-admin keys regardless of this client-side\ncheck.\n\n1. This command takes no arguments.\n\n2. **Before executing any recipe step**, tell the user what they are about to sit through and why it\n is worth it:\n\n ```\n Learning this repository. This takes a while — the research agents read the actual codebase, and\n all the unlearned fields are researched in parallel, so the wait is roughly the slowest single\n field rather than the sum of all of them. Fields that are already populated are skipped entirely.\n\n What this buys you: these fields are what ground Bridge's agents in THIS codebase. Planning,\n reviewing, and code generation all read them, so they follow your repository's actual\n architecture, testing, documentation, and correctness conventions instead of generic defaults.\n\n It runs unattended — there are no approval prompts during the run. You may be asked one batched\n question at the very end.\n ```\n\n Do not invent a specific number of minutes; the honest statement is the parallel-wait shape above.\n\n3. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"learn-repository\"`\n\n If the tool returns an error, stop and report the failure.\n\n4. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n Retain, for the closing summary: the consolidated research task's structured result (its per-field\n `status`, `character_count`, `condensed`, and `condensation_reason`), each upload step's result,\n and the final confirmation task's structured result. You will need all three — do not discard them\n as you go.\n\n5. After all steps complete, display a summary built from the results you retained:\n\n ```\n ## Learn Complete\n\n **Status**: Success / Completed with gaps / Failed at step N\n\n **Learned and applied**: <fields drafted this run and written to config>\n **Already populated (skipped)**: <fields skipped because they already had a value>\n **Condensed to fit the field limit**: <field — reason it was condensed, per field>\n **Gaps**: <fields whose research or upload failed, each named with its reason>\n **Confirmation**: <approved / applied / declined / pending human input / not applicable, per field>\n\n Review or edit any of these on the **Project Configuration** page, under **Code Writer Settings**\n for the learned instructions and **MCP Validation Manuals** for the manual selection. Bridge's\n agents read whatever is stored there, so correcting a wrong conclusion there changes their\n behavior.\n ```\n\n Rules for the summary:\n\n - A run where some fields failed but others applied is **`Completed with gaps`**, not `Failed`.\n Name every gap explicitly — an unnamed gap is worse than a failed run, because the user believes\n the field was learned.\n - Report confirmation candidates that could not be presented in a headless session with the exact\n phrase `pending human input`.\n - Every field that was condensed must appear with the reason it was condensed.\n\n6. **After** the `## Learn Complete` summary above is fully displayed, close with the same concise\n capability report `/install-bridge` renders (BAPI-658, AC-9). This is the recipe's ONE exception to\n \"do not call MCP tools directly\": call the `get_install_manifest` MCP tool EXACTLY ONCE here,\n directly, with no arguments beyond what it requires — never through the recipe, never a second time,\n and never to apply or change any configuration.\n\n The report is structurally and visually SUBORDINATE to `## Learn Complete` above it — it is a\n closing addendum, not a replacement for or a distraction from the learn summary's own status,\n fields, gaps, and confirmation outcome.\n\n If the `get_install_manifest` call errors, or its response has no `concise_tool_capabilities` field,\n or that field is present but malformed (not the server's two-section `{id, name, tools}` availability\n shape), print exactly this line and stop — do not attempt the report in any other form:\n\n ```\n capability report unavailable — run /install-bridge to see it\n ```\n\n Never substitute documentation, the complete `tool_capabilities` catalog, a remembered tool list, or\n an inferred capability category for a missing or malformed concise field — a hallucinated report\n during this trust-critical first run is worse than no report at all.\n\n Otherwise, render exactly one section, with this exact heading, from `concise_tool_capabilities`\n only:\n\n **What Bridge can help with**\n\n - Render the server's two availability sections in the order it gave them — \"Available now\" first,\n then \"Needs setup\" — using each section's `name` as its sub-heading. Do not reorder, merge, drop a\n section the server included even when its `tools` array is empty, or add a third one.\n - Within a section, render each item's `display_name`, then its `description`, then its `how_to_use`\n when that value is a non-empty string, in server order. Items in \"Needs setup\" additionally carry\n the server's `availability_text`, rendered verbatim as the setup guidance; items in \"Available now\"\n carry no availability caveat at all and must not be given one.\n - Render a `kind: \"workflow\"` item exactly like a `kind: \"tool\"` item. `kind` is contract metadata,\n not a visual distinction — no label, icon, separate list, or client branching on its value.\n - Keep an empty section visible with one short neutral line rather than dropping it, and close the\n report by pointing at the Bridge MCP server README for the complete tool documentation. Name the\n README in prose only — this command never hardcodes a URL.\n - Do not locally filter, count, regroup, sort, infer availability, pair a retrieval tool with a\n primary, fabricate an item, write configuration, or fall back to the complete `tool_capabilities`\n or `workflows` collections for this section under any circumstance.\n",
|
|
19
19
|
"parse-repository.md": "Queue a background job to parse and index the repository for Bridge API's AI agents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nExecute all steps in this command as a simple linear sequence of MCP tool calls.\n\n## Step 1 — Parse Arguments\n\nParse `$ARGUMENTS` for an optional `directory_path` argument (a subdirectory path to scope the parse to, e.g., `src/python`). If no argument is provided, the entire repository will be parsed. If `$ARGUMENTS` is provided but invalid (e.g., contains special characters that suggest it's not a path), report an error.\n\n## Step 2 — Queue Parse Job\n\nCall the `parse_repository` MCP tool with:\n- `directory_path`: set to the parsed `directory_path` from Step 1 if provided, otherwise omit the parameter\n\nIf the response indicates parsing is already in progress, display:\n\n```\nRepository parsing is already in progress. A previous parse job has not yet completed.\n\nRun `/check-parse-status` to monitor progress, or wait a few minutes and try again.\n```\n\nStop and do not proceed to the summary.\n\nIf the call fails or returns an error, stop immediately and display:\n\n```\nFailed to queue parse job: <error message from the tool>\n```\n\n## Summary\n\nOn successful queuing, display:\n\n```\nRepository parse job queued successfully.\n\nScope: <entire repository or directory_path if provided>\n\nProcessing typically takes several minutes for large repositories.\nRun `/check-parse-status` to monitor progress.\n```\n\nAfter the parse completes, AI-generated plans and clarifying questions will reflect the latest code changes.\n",
|
|
20
20
|
"plan-epic.md": "Plan an epic by decomposing it into sub-tasks with structured exploration documents.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nThis command is recipe-driven. Do not call MCP tools directly -- the recipe determines which tools to call and with what parameters.\n\n## Stage 0 — Setup\n\n1. **Parse arguments**: Extract the input from `$ARGUMENTS`. Trim any surrounding whitespace. If the input is empty or whitespace-only, stop immediately and display:\n ```\n Usage: /plan-epic <description of the epic or Jira key>\n ```\n\n2. **Jira key detection**: If the input matches a Jira key pattern (`[A-Z]+-\\d+`), call the `get_ticket` MCP tool with that key to fetch the epic description. Use the ticket's description as the `epic_description`, and set `epic_key` to that Jira key. If the input does not match a Jira key, use the free-form text directly as the `epic_description` and set `epic_key` to an empty string `\"\"` (there is no Jira epic to update). The recipe uses `epic_key` to decide whether to post the goals/NFRs + recommended implementation order as a comment on the epic.\n\n3. **Generate slug**: Create a kebab-case slug from the epic description — take the first 6-8 meaningful words, strip non-alphanumeric characters (except hyphens), lowercase, and truncate to 60 characters. This becomes the `epic_slug`.\n\n4. **Directory existence check**: Call the `get_docs_dir` MCP tool (no parameters) to get the docs directory path. Then run a terminal command to check if the directory `{docs_dir}/epic-plans/{epic_slug}` already exists:\n ```\n test -d {docs_dir}/epic-plans/{epic_slug} && echo \"exists\" || echo \"not_found\"\n ```\n If the directory exists, append `-{unix_timestamp}` to the `epic_slug` (e.g., `add-auth-provider-support-1710000000`).\n\n## Stage 1 — Execution\n\n5. Call the `get_pipeline_recipe` MCP tool with:\n - `pipeline`: `\"plan-epic\"`\n - `variables`: `{ \"epic_description\": \"<resolved_description>\", \"epic_slug\": \"<slug>\", \"epic_key\": \"<jira_key_or_empty_string>\" }`\n\n Note: Do NOT pass `docs_dir` in variables — it is auto-injected by the pipeline system.\n\n If the tool returns an error, stop and report the failure.\n\n6. Read and strictly obey the `agent_instructions` field in the response. Execute each step in order, announcing each as **Step N of M: <description>**.\n\n7. After all steps complete, display a summary:\n ```\n ## Pipeline Complete\n\n **Epic**: <first 80 characters of epic_description>...\n **Slug**: <epic_slug>\n **Output**: <docs_dir>/epic-plans/<epic_slug>/overview.md\n **Steps executed**: N of M\n **Status**: Success / Failed at step N\n ```\n",
|
|
21
21
|
"plan-ticket.md": "Generate an implementation plan for a Jira ticket, wait for the result, and save it locally.\n\n$ARGUMENTS\n\n---\n\n# Instructions\n\nExecute all steps in this command as a simple linear sequence of MCP tool calls.\n\n## Step 1 — Parse Arguments\n\n1. **Parse `$ARGUMENTS`**: Extract a required `ticket_key`, an optional `--second-opinion` flag, and an optional `--provider` flag.\n - Split `$ARGUMENTS` on whitespace.\n - If `--second-opinion` appears followed by a provider name (one of `openai`, `anthropic`, `gemini`), capture that provider as `second_opinion_value`.\n - If `--second-opinion` appears without a provider name following it (or is the last token), set `second_opinion_value = \"auto\"`.\n - If `--second-opinion` is absent, set `second_opinion_value = null`.\n - If `--provider` appears followed by a provider name (one of `openai`, `anthropic`, `gemini`), capture that provider as `provider_value`.\n - If `--provider` appears without a valid provider name following it (or is the last token), stop immediately and report: \"Usage error: --provider requires a provider name (openai, anthropic, or gemini).\"\n - If `--provider` is absent, set `provider_value = null`.\n - If both `--second-opinion` and `--provider` are present, `--second-opinion` takes precedence (set `provider_value = null`).\n - The remaining token (after removing flags and their arguments) is the `ticket_key`.\n - If `ticket_key` is empty or missing, stop immediately and display:\n\n ```\n Usage: /plan-ticket <ticket_key> [--second-opinion [provider]] [--provider <name>] (e.g., /plan-ticket BAPI-150)\n ```\n\n## Step 2 — Resolve Docs Directory\n\nCall the `get_docs_dir` MCP tool (no parameters). Store the returned path as `docs_dir`.\n\n## Step 3 — Generate Plan\n\nCall the `request_plan_generation` MCP tool with:\n- `ticket_number`: the parsed `ticket_key`\n- `wait_for_result`: `true`\n- `save_locally`: `true`\n- `second_opinion`: set to `second_opinion_value` if non-null; omit entirely if null\n- `provider`: set to `provider_value` if non-null; omit entirely if null\n\nThis step may take 1-5 minutes while the backend processes the plan.\n\nIf the tool returns an error, stop immediately and display:\n\n```\nPlan generation failed: <error message from the tool>\n```\n\n## Step 4 — Confirm Success\n\nDisplay a confirmation message:\n\n```\nPlan generated successfully for <ticket_key>\nSaved to: {docs_dir}/plans/<ticket_key>-plan.md\n```\n\n## Final Summary\n\nDisplay a summary block:\n\n```\n## Plan Generation Report\n\n- **Ticket**: <ticket_key>\n- **Plan Status**: Generated successfully\n- **Local File**: {docs_dir}/plans/<ticket_key>-plan.md\n```\n\nOn failure at any step, stop immediately, display which step failed and the error details, and do not proceed.\n",
|