@bridge_gpt/mcp-server 0.2.37 → 0.2.39
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 +193 -16
- package/build/agent-capabilities/probe-context.js +2 -1
- package/build/agent-launchers/claude-executor-adapter.js +392 -0
- package/build/agent-launchers/executor-adapter-inspection.js +163 -0
- package/build/agent-launchers/executor-adapter-registry.js +90 -0
- package/build/agent-launchers/executor-adapter.js +136 -0
- package/build/agent-registry.js +28 -0
- package/build/agents.generated.js +1 -1
- package/build/claude-login.js +85 -0
- package/build/claude-user-config-doctor.js +59 -33
- package/build/commands.generated.js +12 -11
- package/build/conduct-epic/bridge-client.js +345 -0
- package/build/conduct-epic/checkpoint-store.js +423 -0
- package/build/conduct-epic/cli.js +1732 -0
- package/build/conduct-epic/lock.js +302 -0
- package/build/conduct-epic/pr-state.js +197 -0
- package/build/conduct-epic/spawn.js +101 -0
- package/build/conductor/bridge-api-client.js +37 -2
- package/build/conductor/doctor.js +11 -1
- package/build/conductor/install-doctor.js +184 -10
- package/build/conductor-bin.js +7 -7
- package/build/credential-store.js +10 -4
- package/build/credentials-cli.js +34 -19
- package/build/docs.generated.js +1 -1
- package/build/doctor.js +579 -88
- package/build/executor/agent-identity.js +32 -0
- package/build/executor/cli.js +50 -39
- package/build/executor/deps.js +15 -1
- package/build/executor/env.js +56 -45
- package/build/executor/index.js +9 -1
- package/build/executor/install-preflight.js +138 -0
- package/build/executor/job-errors.js +200 -0
- package/build/executor/job-runner.js +619 -268
- package/build/executor/observation.js +165 -0
- package/build/executor/permissions.js +163 -36
- package/build/executor/platform.js +54 -0
- package/build/executor/preflight.js +175 -67
- package/build/executor/process.js +39 -7
- package/build/executor/runner.js +19 -0
- package/build/executor/service-lifecycle.js +269 -0
- package/build/executor/service-unit.js +121 -12
- package/build/executor/stale-artifacts.js +70 -0
- package/build/executor/test-clock.js +188 -24
- package/build/executor/worker-command.js +22 -58
- package/build/executor/worker-log.js +82 -0
- package/build/executor/worktree-lock.js +264 -0
- package/build/index.js +527 -357
- package/build/install-bridge-conductor.js +376 -38
- package/build/install-bridge.js +414 -114
- package/build/install-doctor.js +13 -0
- package/build/install-reexec.js +5 -3
- package/build/mcp-install-state.js +130 -0
- package/build/mcp-profile.js +11 -2
- package/build/mcp-provisioning.js +15 -0
- package/build/merge-pull-request.js +562 -0
- package/build/phase-result-artifacts.js +450 -0
- package/build/pipeline-orchestrator.js +4 -0
- package/build/pipeline-utils.js +16 -0
- package/build/pipelines.generated.js +7 -7
- package/build/plane/preflight.js +18 -14
- package/build/plane/supervisor.js +8 -1
- package/build/project-root.js +34 -0
- package/build/readme.generated.js +1 -1
- package/build/run-unit-tests-launcher.js +36 -9
- package/build/setup-epic.js +57 -4
- package/build/sfcc/ocapi-shape.js +23 -4
- package/build/sfcc/permissions.js +25 -6
- package/build/sfcc/read-body.js +92 -0
- package/build/sfcc/read-projection.js +6 -2
- package/build/sfcc/reads-custom-object-def.js +33 -21
- package/build/sfcc/reads-site-preference.js +20 -7
- package/build/sfcc/reads-system-object.js +11 -5
- package/build/sfcc/register.js +61 -23
- package/build/sfcc/registration-inventory.js +89 -0
- package/build/sfcc/setup-status.js +18 -34
- package/build/sfcc/tool-wrapper.js +294 -17
- package/build/sfcc/write-grants.js +33 -1
- package/build/sfcc/write-guard.js +41 -12
- package/build/sfcc/write-result.js +16 -7
- package/build/sfcc/writes-custom-object-def.js +12 -4
- package/build/sfcc/writes-site-preference.js +6 -1
- package/build/sfcc/writes-system-object.js +11 -2
- package/build/sfcc/writes.js +13 -8
- package/build/start-tickets-prereqs.js +25 -15
- package/build/start-tickets.js +123 -21
- package/build/version.generated.js +1 -1
- package/build/worktree-core.js +9 -3
- package/docs/install/mcp-tool-integrations.md +54 -9
- package/docs/install/sfcc-integration.md +71 -24
- package/package.json +3 -3
- package/build/executor/worker-config-isolation.js +0 -287
|
@@ -690,12 +690,12 @@ export const CHAIN_RECIPES = {
|
|
|
690
690
|
};
|
|
691
691
|
export const INSTRUCTIONS = {
|
|
692
692
|
"assess-epic-research-needs.md": "Analyze the epic description and build a structured research plan.\n\n## Epic Description\n\n{epic_description}\n\n## Instructions\n\n1. Create the directory structure for this epic's artifacts:\n ```\n mkdir -p {docs_dir}/epic-plans/{epic_slug}\n ```\n\n2. Analyze the epic description above. Determine what external knowledge is required to plan this epic effectively. Consider:\n - Unfamiliar technologies, libraries, or frameworks mentioned\n - API documentation or integration specs that need to be consulted\n - Best practices or architectural patterns that require research\n - Domain-specific knowledge gaps\n\n3. Decide on a **Research Mode**:\n - **deep**: Use when the epic involves large, multi-faceted unknowns requiring synthesis from multiple sources (e.g., \"best practices for implementing WebSocket connection pooling in Python asyncio\").\n - **web**: Use for quick factual lookups — library API signatures, configuration syntax, small \"how to\" questions.\n - **none**: Use when the codebase exploration alone will provide sufficient context and no external knowledge is needed.\n\n4. Write a structured research plan to `{docs_dir}/epic-plans/{epic_slug}/research-plan.md` with these sections:\n\n```markdown\n# Research Plan\n\n## Research Mode\n{deep | web | none}\n\n## Deep Research Query\n{If mode is \"deep\": a single, well-crafted query for the deep research tool. Otherwise: \"N/A\"}\n\n## Web Search Topics\n{If mode is \"web\" or as fallback topics for \"deep\": a numbered list of specific search topics. Otherwise: \"N/A\"}\n\n## Rationale\n{Brief explanation of why this research mode was chosen and what knowledge gaps it addresses.}\n```\n\n## Return\n\nConfirm the research plan was written to `{docs_dir}/epic-plans/{epic_slug}/research-plan.md` and report the chosen Research Mode (`deep`, `web`, or `none`) along with a one-line rationale.\n",
|
|
693
|
-
"capture-review-decisions.md": "Capture user decisions on review findings for {ticket_key} using the HTML decision page, then interpretively rewrite the clarifying questions and critique docs and upload both to Jira.\n\n## Step 1: Read source documents\n\nRead the combined review-and-resolution file:\n- `{docs_dir}/review/{ticket_key}-review-and-resolution.md`\n\nIf the file does not exist or is unreadable, stop and report: \"Combined review-and-resolution file not found or unreadable. Run the earlier pipeline steps first.\"\n\nThe combined file existing but containing no actionable items (empty `Needs Scrutiny` and `Open Questions` sections) is **not** a failure condition — Step 4 handles the no-decisions-needed flow gracefully when `generate_decision_page` is called with empty `actionable_items`.\n\n## Step 2: Map evaluation items to decision page input\n\nTransform the combined review-and-resolution document into `generate_decision_page` JSON input using these mapping rules:\n\n| Evaluation Section | JSON Field | Mapping Rule |\n|---|---|---|\n| Open Questions | `actionable_items` | E-item title → `question`, `**Source**` → `source`, `**Original question**` → `original_question`, `**Why it matters**` → `why_it_matters`, decision tree branch labels → `options` (string array, labels only), `**Option consequences**` (parallel to branches) → `option_consequences`, `**Recommendation explanation**` → `recommendation_explanation`, combined `**Assessment**` paragraph and `**Codebase Evidence**` bullet list → `codebase_evidence`, `**Recommendation Index**` → `recommendation_index` |\n| Needs Scrutiny | `actionable_items` | E-item title → `question`, `**Source**` → `source`, `**Original question**` → `original_question`, `**Why it matters**` → `why_it_matters`, decision tree branch labels → `options` (string array, labels only), `**Option consequences**` (parallel to branches) → `option_consequences`, `**Recommendation explanation**` → `recommendation_explanation`, combined `**Assessment**` paragraph and `**Codebase Evidence**` bullet list → `codebase_evidence`, `**Recommendation Index**` → `recommendation_index` |\n| Confirmed Improvements | `clear_improvements` | E-item title → `title`, confidence tag → `confidence`, recommended action → `action`, `**Source**` from the combined file → `source` |\n\n**Important**: The `original_question`, `why_it_matters`, `option_consequences`, `recommendation_explanation`, and the collapsed `codebase_evidence` block together replace the old single `context` blob. Each clarity field guides a different facet of the user's decision: `original_question` reminds the reviewer what was asked, `why_it_matters` frames the impact, `option_consequences` describe the behavioral outcome of each branch, `recommendation_explanation` motivates the recommended branch, and the closed-by-default `codebase_evidence` block surfaces the Assessment + file:line citations on demand without overwhelming the card.\n\nFor each actionable item, the `options` array is a list of plain label strings extracted from the combined file's decision tree branches. The tool auto-generates value keys (`opt-0`, `opt-1`, etc.) and auto-appends a \"None of these\" option. Do not generate value keys yourself.\n\n## Step 2.5: Auto-approve fast path\n\nFor this run, `auto_approve` = `{auto_approve}`.\n\nIf `auto_approve` is `true` and Step 2 produced at least one actionable item, skip Steps 3–6 entirely and synthesize the commit JSON directly:\n\n- `ticket_key`: `{ticket_key}`\n- `general_comment`: `\"\"`\n- `decisions`: an object keyed by each `actionable_items[*].id` from Step 2's mapped input. For each item:\n - If `recommendation_index` is a non-negative integer within range of `options`: `choice = \"opt-\" + recommendation_index`, `chosen_label = options[recommendation_index]`, `comment = \"\"`, `source` copied from the item.\n - Otherwise (missing, null, or out of range): `choice = \"opt-0\"`, `chosen_label = options[0]`, `comment = \"\"`, `source` copied. Never emit `\"none\"` and never emit `\"ask\"`.\n\nPost a single chat acknowledgement listing each auto-approved item ID and chosen label, then proceed directly to Step 7 with the synthesized JSON. Step 7's \"Hard rule\" about resolving `ask` items does not apply because no item carries `choice === \"ask\"`.\n\nIf Step 2 produced zero actionable items, fall through to Step 3 — Step 4's existing `no_decisions_needed` branch handles the empty case correctly.\n\nOtherwise (any value of `auto_approve` other than the literal `true` — including empty, `false`, or missing), proceed to Step 3.\n\n## Step 3: Call the MCP tool\n\nCall `generate_decision_page` with `ticket_key` at the root and the review arrays nested under `content`:\n\n**Always pass `content`, even when both arrays are empty.** Send `\"content\": { \"actionable_items\": [], \"clear_improvements\": [] }` rather than omitting the key — that is what reaches the `no_decisions_needed` branch Step 2 relies on. Omitting `content` entirely is rejected with a `VALIDATION_ERROR`, because root-level arrays are silently dropped by the tool's lean input schema and a missing wrapper is far more often a mistake than a deliberate empty call.\n\n```typescript\ninterface ReviewDecisionsContent {\n actionable_items?: Array<{\n id: string;\n question: string;\n why_it_matters: string; // required — concrete one-sentence impact\n recommendation_explanation: string; // required — why the recommended branch is best\n options: string[]; // 2-4 option labels\n option_consequences: string[]; // same length as options\n recommendation_index: number; // 0-based index into options\n original_question?: string; // optional display field\n codebase_evidence?: string; // optional display field — assessment + file:line\n source?: string; // optional source reference\n }>;\n clear_improvements?: Array<{\n id: string;\n title: string;\n action: string;\n confidence: string;\n source: string; // required for clear_improvements\n }>;\n}\n```\n\nExample call:\n```json\n{\n \"ticket_key\": \"{ticket_key}\",\n \"content\": {\n \"actionable_items\": [\n {\n \"id\": \"E-1\",\n \"question\": \"Should we add a configurable timeout?\",\n \"why_it_matters\": \"Timeout behavior affects retry paths and user-visible latency.\",\n \"recommendation_explanation\": \"Configurable matches existing latency-branching code.\",\n \"options\": [\"Keep existing\", \"Add configurable timeout\"],\n \"option_consequences\": [\"No new work.\", \"Implementers add config + tests.\"],\n \"recommendation_index\": 1,\n \"original_question\": \"Does the ticket specify timeout behavior?\",\n \"source\": \"Clarifying Q1\"\n }\n ],\n \"clear_improvements\": [\n { \"id\": \"ci-1\", \"title\": \"Tidy logging\", \"action\": \"Use the logger.\", \"confidence\": \"high\", \"source\": \"Eval 1\" }\n ]\n }\n}\n```\n\n## Step 4: Check tool response\n\nThe tool returns a JSON response with a `status` field:\n- If `status` is `\"no_decisions_needed\"`: skip Steps 5, 6, 7, and 8 entirely. Output a success message: \"No actionable review decisions needed — skipping doc rewrite and upload.\" This covers both the case where every item was confirmed as a Confirmed Improvement and the case where no items were emitted (e.g., both upstream source documents were absent).\n- If `status` is `\"decision_page_generated\"`: continue to Step 5. The response includes `file_path`.\n\n## Step 5: Direct user to the decision page\n\nTell the user to open the generated HTML file in their browser. Provide the `file_path` from the tool response. Then say to the user, verbatim: `Open the page. For any item you're unsure about, choose \"Ask about this\" — when you submit, I'll talk through those before we proceed. You can also ask me questions in chat before submitting if you prefer.`\n\nThis step only directs the user to the page and explains the two allowed next actions (submit selections, or ask questions first). Do not describe Step 7's rewrite semantics here; that belongs to the rewrite step.\n\n## Step 6: Q&A loop and commit signal\n\nEnter an open-ended Q&A loop. There is no turn cap — the user may ask any number of questions in any number of turns. Do not stop and wait silently; engage with each user message as either a commit signal or a discussion turn.\n\n### Proceed signal (commit)\n\nTrim the full user message and attempt to parse the entire trimmed message as JSON. The message is a commit only when the parsed value is an object with all three of these top-level fields:\n\n- `ticket_key` — must be a string\n- `decisions` — must be an object\n- `general_comment` — must be a string\n\nThe first valid commit-shaped JSON paste commits immediately. Proceed to Step 7 without prompting for additional confirmation. Any combination of `decisions` keys is accepted (the page may submit a partial set if the user only resolved some items conversationally). Do not over-validate the per-card fields beyond the top-level commit-shape check — the page guarantees the per-card schema, and over-validating risks rejecting valid pastes if the page schema evolves.\n\n### Discussion signal (Q&A turn)\n\nAnything that is not commit-shaped JSON is a discussion turn. This includes:\n\n- Freeform questions (with or without other text).\n- Questions pasted alongside other text or alongside JSON.\n- Malformed JSON (parse failure).\n- Well-formed JSON missing one or more of the required top-level keys (`ticket_key`, `decisions`, `general_comment`).\n\nFor JSON-shaped input that is missing required top-level fields, call this out in the reply — explain which fields are missing and ask whether the user intended to submit or share partial state — rather than silently treating it as a freeform question.\n\nAnswer discussion turns using these sources, in priority order:\n\n1. The combined `{ticket_key}-review-and-resolution.md` file already read in Step 1.\n2. The original `{ticket_key}-clarifying-questions.md` and `{ticket_key}-ticket-quality-critique.md` documents.\n3. Codebase lookups when the question requires verifying current code state.\n\nFallback: if running on a pre-PR1 branch where the combined review-and-resolution document does not exist, use the pre-PR1 `{ticket_key}-review-evaluation.md` and `{ticket_key}-resolution-guide.md` pair in its place.\n\nFor plain freeform questions, infer the item from chat context when possible.\n\n### In-flight decision state\n\nDuring the Q&A loop, maintain in-flight JSON state — agent-owned working memory representing the user's current intent for `decisions` and `general_comment`. This in-flight JSON state lives only in the agent's working memory for the duration of the loop; do not persist it server-side.\n\n- When the user clearly changes their mind about an item, chooses an option conversationally with reasonably explicit decision language (\"choose option B for E-3\", \"go with the configurable timeout\", \"change E-7 to None of these\"), or gives new overarching guidance, record that as an in-flight override.\n- Ambiguous preference language (\"I'm leaning toward...\", \"maybe option B is fine\") should be discussed but not recorded as an override unless the user gives reasonably explicit decision language.\n- `general_comment` may be updated in the in-flight state when the user gives overarching guidance during Q&A.\n- The page's general-comment textarea is preserved unchanged. Do not modify the page DOM during Q&A; the user can still fill the textarea before submitting if they prefer.\n\nOn the eventual JSON commit, the user-submitted JSON is the baseline and the recorded in-flight overrides take precedence over it. Before proceeding to Step 7, post a brief one-line acknowledgement in chat naming each overridden item ID and/or `general_comment`. The acknowledgement is mandatory (not optional) — it is the user's last chance to object before Step 7's document rewrite. The user does not need to re-open, edit, or re-submit the decision page after changing their mind in chat; they can submit the page as-is to provide the commit signal, and the in-flight state remains the source of truth for overrides.\n\n### Ask-about-this resolution\n\nAfter accepting a commit, scan `decisions` for any item where `choice === \"ask\"`. The user has signaled that they need more information before deciding on those items. For each such item:\n\n- If `comment` is non-empty, treat it as the user's specific question or stated uncertainty and answer that directly.\n- If `comment` is empty, proactively present the most relevant missing context — the item's `codebase_evidence`, related code lookups, prior-round answers — and lay out the trade-offs the user appears to need help weighing.\n- Continue the Q&A turn-by-turn until the user gives an explicit decision in chat for that item (\"go with option B\", \"none of these, because …\"). Record that decision as an in-flight override using the same override mechanism described above.\n\n**Hard rule.** Step 7 must not run while any `decisions[*].choice === \"ask\"` remains unresolved by an in-flight override. Do not honor \"just proceed\", \"skip those\", or any other instruction to defer resolution — every `ask` item must end with a recorded `opt-N` or `none` override before the rewrite step. The pre-Step-7 acknowledgement line lists every overridden item, including the ones resolved out of `ask`.\n\n## Step 7: Interpretively rewrite source documents\n\nThe pasted JSON contains a `decisions` object keyed by item ID. Each decision includes `source`, `choice`, `chosen_label`, and `comment`. Use these fields to locate and rewrite the corresponding sections in:\n- `{docs_dir}/clarifying-questions/{ticket_key}-clarifying-questions.md`\n- `{docs_dir}/ticket-critiques/{ticket_key}-ticket-quality-critique.md`\n\nAfter a second-opinion run, each document has this shape:\n\n- A top-level H1 (`# Ticket Analysis` or `# Ticket Quality Critique`) followed by an italic provider-attribution line `_This analysis was generated by GPT|Claude|Gemini._` naming the first-round LLM family. **Preserve this attribution line verbatim** — do not move, edit, or remove it during the rewrite step.\n- The first-round questions / critique items, exactly as written by the first-round model.\n- **Inline second-opinion blockquotes** (`> **Second opinion (<provider>) - concurrence|refinement|disagreement.** ... > *Citations: ...*`) nested directly under each prior item the second round addressed. The `(<provider>)` parenthetical is the second-round LLM family (`GPT|Claude|Gemini`). Items the second round did not comment on have no blockquote — that is the \"weak concurrence\" signal.\n- A **`## New in Second Opinion`** tail block listing items the second round added on top of the first round. Immediately under the H2 there is a second italic attribution line `_These additional points were raised by GPT|Claude|Gemini._` naming the second-round family — **also preserve this verbatim**. Then agent-specific sub-headings:\n - Clarifier docs: `### New Requirements Questions` / `### New Technical Questions` (numbering continues from the prior section).\n - Critique docs: `### New Requested Changes` / `### New Points to Consider` (numbering continues from the prior section).\n- A final **`## Second Opinion Summary`** footer (1-3 sentences). **This footer must be preserved verbatim** — it is the canonical record of the second round's overall position and should not be edited.\n\nThe `source` field on each decision tells you where the item lives:\n\n- `Clarifying Q3 (prior round, weak concurrence)` → the prior section, no inline blockquote. Rewrite the prior item's answer.\n- `Clarifying Q9 (prior round, concurrence inline)` → the prior section, prior item carries an explicit `concurrence` blockquote. Rewrite the prior answer; the blockquote can be removed once the answer absorbs the resolution.\n- `Clarifying Q3 (prior round, refinement inline)` / `(prior round, disagreement inline)` → the prior section, prior item carries an explicit `refinement` or `disagreement` blockquote. Rewrite the prior answer to reconcile the dispute, then handle the blockquote per the rule below.\n- `Clarifying Q11 (new in second opinion → New Requirements Questions)` → the `## New in Second Opinion > ### New Requirements Questions` sub-section. Rewrite the item in place inside that sub-section, not at the top of the prior analysis.\n- Equivalent forms for critique items: `Critique: Requested Change 2 (prior round, refinement inline)`, `Critique: Points to Consider N+1 (new in second opinion → New Points to Consider)`, etc.\n\n**Legacy fallback shape**: if the document instead ends with `\\n\\n---\\n\\n` followed by a `## Second Opinion` section (because the JSON pipeline fell back), apply decisions to the equivalent location: `### Response to Prior Items` for inline-style responses, `### Additional Points > New X` for tail-style new items. Preserve the `\\n\\n---\\n\\n` separator and the `## Second Opinion` heading verbatim.\n\nApply the decision to the item in its home location. Then apply the decision:\n\n### Actionable item decisions\n\n- **Selected option** (`choice` is `opt-N`): Add `**Review Decision**: Accepted. <chosen_label>.` to the corresponding section. Integrate the selected direction into the section text so it reads as a final recommendation or resolved answer.\n- **None of these** (`choice` is `none`): Add `**Review Decision**: Rejected — none of the proposed options accepted.` Include the user's `comment` explaining why. Rewrite the section to reflect this decision.\n\nFor actionable items sourced from clarifying questions, rewrite the question's best-guess answer so it reads as the final resolved direction chosen by the reviewer. Do not leave the item framed as an unresolved accept/reject/modify prompt.\n\nFor items sourced from `(prior round, refinement inline)` or `(prior round, disagreement inline)` — disputes of a prior-round item carried in an inline blockquote — the prior-round item is the canonical home: rewrite its answer to absorb the resolution. Then handle the blockquote in one of two ways: (a) remove the blockquote outright if the rewritten answer fully absorbs the second-opinion content, or (b) shorten the blockquote to a single sentence noting the resolution while preserving the `(<provider>)` attribution (e.g. `> **Second opinion (Claude) - refinement.** Resolved by reviewer decision E-N.`). Citations from the original blockquote may be promoted into the rewritten prior-item answer if useful — keep the strongest 1-2 grounding refs.\n\nFor items sourced from `(new in second opinion → ...)` — gap-captured items that received a decision — rewrite the item in place inside its tail-block sub-section (`## New in Second Opinion > ### New X`), not at the top of the prior analysis. Preserve the sub-section heading and continued numbering.\n\n### General comment handling\n\nTreat `general_comment` as overarching guidance that informs the tone and direction of both document rewrites. If it contains specific actionable feedback, weave it into the relevant sections. If it is broad or general, use it as context for how the rewrites should read. Do not create a separate \"General Comment\" or \"Reviewer Notes\" section — the goal is \"final draft\" form.\n\n### Rewrite principles\n\nThe goal is a **final draft** — the documents should read as if they were written with the decisions already made. Do not mechanically append decisions. Instead, lightly rewrite affected sections so they reflect the decisions naturally. Preserve all non-affected sections unchanged. The prior-round content should still read as coherent standalone analysis after integration. Preserve the `## New in Second Opinion` tail block intact for any items that weren't decided. **Always preserve the `## Second Opinion Summary` footer verbatim** — it is the canonical record of the second round's overall position and should not be edited even when individual items it references have been resolved.\n\n## Step 8: Upload to Jira\n\nUpload both updated documents to Jira using `attachment` (operation: `\"upload\"`):\n\n1. Upload clarifying questions:\n - `ticket_number`: `{ticket_key}`\n - `file_path`: `{docs_dir}/clarifying-questions/{ticket_key}-clarifying-questions.md`\n - `link_type`: `clarifying-questions.md`\n\n2. Upload ticket quality critique:\n - `ticket_number`: `{ticket_key}`\n - `file_path`: `{docs_dir}/ticket-critiques/{ticket_key}-ticket-quality-critique.md`\n - `link_type`: `ticket-quality-critique.md`\n\n## Step 9: Complete\n\nConfirm: \"Review decisions captured and uploaded to {ticket_key}.\"\n\n## Return\n\nConfirm \"Review decisions captured and uploaded to {ticket_key}.\" and list the two attachments uploaded (`{ticket_key}-clarifying-questions.md` and `{ticket_key}-ticket-quality-critique.md`). Note any decisions that could not be applied.\n",
|
|
694
|
-
"checkpoint-work.md": "Checkpoint the work produced for ticket {ticket_key}.\n\nThis is the **durability boundary**. The production phase has just authored its\nartifacts and they exist only in the worktree. The pre-PR verification phase that\nruns next executes the plan's review steps, its test commands, and — for a\nfrontend ticket — a remediation loop of up to three cycles. That is the long part of\nthe run, and it is exactly where a session runs out of budget.\n\nSo the work is pushed to origin *first*. After this step, a worker that dies mid\nverification has still left its implementation recoverable on a remote ref.\n\nThis step is deliberately narrow. It makes **no branch decision**, opens **no pull\nrequest**, and asks for **no approval**. Branch selection and the pull request belong\nto `commit-and-push.md` and `create-pr.md`, which run later on the same branch. Doing\nany of that here would put a decision — and a possible pause — in front of the very\ndurability guarantee this step exists to provide.\n\n---\n\n## Step 1 — Assess the Worktree\n\nRun and note the results:\n\n- `git rev-parse --abbrev-ref HEAD` — the current branch.\n- `git status --porcelain` — everything modified, added, or untracked.\n\n**Use the branch you are on.** Do not create, rename, switch, or select a branch.\n\nStop immediately, reporting the reason, if any of these hold:\n\n- HEAD is detached (`git rev-parse --abbrev-ref HEAD` reports `HEAD`).\n- A merge, rebase, or cherry-pick is in progress.\n\nNeither is a state to commit into, and both need a human.\n\n## Step 2 — Clean Tree\n\nAn empty `git status --porcelain` means there is nothing new to checkpoint. It does\n**not** automatically mean everything is safe: the point of this step is that the work\nis on origin, so prove it rather than assume it.\n\n1. Run `git rev-parse HEAD`.\n2. Run `git ls-remote --heads origin <branch>` and compare the remote tip to HEAD.\n3. If the remote already contains HEAD, the checkpoint is satisfied. Report it and\n return.\n4. If HEAD is not on origin, there are local commits that were never pushed. Push them\n now with `git push origin <branch>` and re-verify.\n\nDo **not** create an empty commit to represent a checkpoint. An empty commit records\nnothing and proves nothing.\n\n## Step 3 — Commit and Push\n\nWhen there are changes to checkpoint:\n\n1. Stage the produced ticket work explicitly with `git add <file1> <file2> ...`. Do not use `git add -A` or `git add .` — a blanket stage sweeps in unrelated\n local files, and this step runs without an approval gate to catch that.\n2. Commit with:\n\n ```\n {ticket_key}: checkpoint produced work before verification\n ```\n\n3. Push the current branch immediately: `git push origin <branch>`. Add `-u` only if\n the branch has no upstream yet.\n\nUse the plain push command — do **not** add `--no-verify`. A Conductor worker already\nreceives `BRIDGE_SKIP_PREPUSH=1` from the executor, so bypassing hooks here is never\nnecessary.\n\n## Step 4 — Prove Durability\n\n1. Run `git rev-parse HEAD` and record the SHA.\n2. Run `git ls-remote --heads origin <branch>` and confirm the remote tip equals that\n SHA.\n\n**Stop the pipeline** and report the failure if the commit fails, the push fails or is\nrejected, or the remote tip does not match HEAD. The phase that follows is the long\none; entering it without durable work is precisely the failure this step prevents.\n\n## Return\n\nReturn a machine-readable result as a fenced block tagged `bapi-checkpoint`, followed\nby a one-line human summary:\n\n```bapi-checkpoint\n{\"version\":1,\"branch\":\"<current branch>\",\"sha\":\"<checkpoint HEAD sha>\",\"pushed\":true,\"remoteMatchesHead\":true}\n```\n\nIf nothing needed committing because HEAD was already on origin, report the same shape\nwith the existing SHA and note that no new commit was required.\n",
|
|
695
|
-
"clarify-open-nfrs.md": "Proactively clarify any open non-functional requirements with the user via an interactive decision page before decomposing the epic. Clear goals and a clear desired end-state make the functional decomposition far more accurate, so resolve the unclear NFRs first.\n\n## Inputs\n\n- The framing written by the previous step: `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md`.\n\n##
|
|
693
|
+
"capture-review-decisions.md": "Capture user decisions on review findings for {ticket_key} using the HTML decision page, then interpretively rewrite the clarifying questions and critique docs and upload both to Jira.\n\n## Step 1: Read source documents\n\nRead the combined review-and-resolution file:\n- `{docs_dir}/review/{ticket_key}-review-and-resolution.md`\n\nIf the file does not exist or is unreadable, stop and report: \"Combined review-and-resolution file not found or unreadable. Run the earlier pipeline steps first.\"\n\nThe combined file existing but containing no actionable items (empty `Needs Scrutiny` and `Open Questions` sections) is **not** a failure condition — Step 4 handles the no-decisions-needed flow gracefully when `generate_decision_page` is called with empty `actionable_items`.\n\n## Step 2: Map evaluation items to decision page input\n\nTransform the combined review-and-resolution document into `generate_decision_page` JSON input using these mapping rules:\n\n| Evaluation Section | JSON Field | Mapping Rule |\n|---|---|---|\n| Open Questions | `actionable_items` | E-item title → `question`, `**Source**` → `source`, `**Original question**` → `original_question`, `**Why it matters**` → `why_it_matters`, decision tree branch labels → `options` (string array, labels only), `**Option consequences**` (parallel to branches) → `option_consequences`, `**Recommendation explanation**` → `recommendation_explanation`, combined `**Assessment**` paragraph and `**Codebase Evidence**` bullet list → `codebase_evidence`, `**Recommendation Index**` → `recommendation_index` |\n| Needs Scrutiny | `actionable_items` | E-item title → `question`, `**Source**` → `source`, `**Original question**` → `original_question`, `**Why it matters**` → `why_it_matters`, decision tree branch labels → `options` (string array, labels only), `**Option consequences**` (parallel to branches) → `option_consequences`, `**Recommendation explanation**` → `recommendation_explanation`, combined `**Assessment**` paragraph and `**Codebase Evidence**` bullet list → `codebase_evidence`, `**Recommendation Index**` → `recommendation_index` |\n| Confirmed Improvements | `clear_improvements` | E-item title → `title`, confidence tag → `confidence`, recommended action → `action`, `**Source**` from the combined file → `source` |\n\n**Important**: The `original_question`, `why_it_matters`, `option_consequences`, `recommendation_explanation`, and the collapsed `codebase_evidence` block together replace the old single `context` blob. Each clarity field guides a different facet of the user's decision: `original_question` reminds the reviewer what was asked, `why_it_matters` frames the impact, `option_consequences` describe the behavioral outcome of each branch, `recommendation_explanation` motivates the recommended branch, and the closed-by-default `codebase_evidence` block surfaces the Assessment + file:line citations on demand without overwhelming the card.\n\nFor each actionable item, the `options` array is a list of plain label strings extracted from the combined file's decision tree branches. The tool auto-generates value keys (`opt-0`, `opt-1`, etc.) and auto-appends a \"None of these\" option. Do not generate value keys yourself.\n\n## Step 2.5: Auto-approve fast path\n\nFor this run, `auto_approve` = `{auto_approve}`.\n\nIf `auto_approve` is `true` and Step 2 produced at least one actionable item, skip Steps 3–6 entirely and synthesize the commit JSON directly:\n\n- `ticket_key`: `{ticket_key}`\n- `general_comment`: `\"\"`\n- `decisions`: an object keyed by each `actionable_items[*].id` from Step 2's mapped input. For each item:\n - If `recommendation_index` is a non-negative integer within range of `options`: `choice = \"opt-\" + recommendation_index`, `chosen_label = options[recommendation_index]`, `comment = \"\"`, `source` copied from the item.\n - Otherwise (missing, null, or out of range): `choice = \"opt-0\"`, `chosen_label = options[0]`, `comment = \"\"`, `source` copied. Never emit `\"none\"` and never emit `\"ask\"`.\n\nPost a single chat acknowledgement listing each auto-approved item ID and chosen label, then proceed directly to Step 7 with the synthesized JSON. Step 7's \"Hard rule\" about resolving `ask` items does not apply because no item carries `choice === \"ask\"`.\n\nThe synthesized settled decisions still receive the implications review described under Step 6's \"Implications review and proceed gate\" before Step 7 runs — literal `auto_approve = true` only skips the human proceed gate, not the review itself. \"Skip Steps 3–6\" above means skipping their interactive portions (rendering the page, waiting on chat, the Q&A loop); it does not exempt this fast path from the review obligation.\n\nIf Step 2 produced zero actionable items, fall through to Step 3 — Step 4's existing `no_decisions_needed` branch handles the empty case correctly.\n\nOtherwise (any value of `auto_approve` other than the literal `true` — including empty, `false`, or missing), proceed to Step 3.\n\n## Step 3: Call the MCP tool\n\nCall `generate_decision_page` with `ticket_key` at the root and the review arrays nested under `content`:\n\n**Always pass `content`, even when both arrays are empty.** Send `\"content\": { \"actionable_items\": [], \"clear_improvements\": [] }` rather than omitting the key — that is what reaches the `no_decisions_needed` branch Step 2 relies on. Omitting `content` entirely is rejected with a `VALIDATION_ERROR`, because root-level arrays are silently dropped by the tool's lean input schema and a missing wrapper is far more often a mistake than a deliberate empty call.\n\n```typescript\ninterface ReviewDecisionsContent {\n actionable_items?: Array<{\n id: string;\n question: string;\n why_it_matters: string; // required — concrete one-sentence impact\n recommendation_explanation: string; // required — why the recommended branch is best\n options: string[]; // 2-4 option labels\n option_consequences: string[]; // same length as options\n recommendation_index: number; // 0-based index into options\n original_question?: string; // optional display field\n codebase_evidence?: string; // optional display field — assessment + file:line\n source?: string; // optional source reference\n }>;\n clear_improvements?: Array<{\n id: string;\n title: string;\n action: string;\n confidence: string;\n source: string; // required for clear_improvements\n }>;\n}\n```\n\nExample call:\n```json\n{\n \"ticket_key\": \"{ticket_key}\",\n \"content\": {\n \"actionable_items\": [\n {\n \"id\": \"E-1\",\n \"question\": \"Should we add a configurable timeout?\",\n \"why_it_matters\": \"Timeout behavior affects retry paths and user-visible latency.\",\n \"recommendation_explanation\": \"Configurable matches existing latency-branching code.\",\n \"options\": [\"Keep existing\", \"Add configurable timeout\"],\n \"option_consequences\": [\"No new work.\", \"Implementers add config + tests.\"],\n \"recommendation_index\": 1,\n \"original_question\": \"Does the ticket specify timeout behavior?\",\n \"source\": \"Clarifying Q1\"\n }\n ],\n \"clear_improvements\": [\n { \"id\": \"ci-1\", \"title\": \"Tidy logging\", \"action\": \"Use the logger.\", \"confidence\": \"high\", \"source\": \"Eval 1\" }\n ]\n }\n}\n```\n\n## Step 4: Check tool response\n\nThe tool returns a JSON response with a `status` field:\n- If `status` is `\"no_decisions_needed\"`: skip Steps 5, 6, 7, and 8 entirely. Output a success message: \"No actionable review decisions needed — skipping doc rewrite and upload.\" This covers both the case where every item was confirmed as a Confirmed Improvement and the case where no items were emitted (e.g., both upstream source documents were absent).\n- If `status` is `\"decision_page_generated\"`: continue to Step 5. The response includes `file_path`.\n\n## Step 5: Direct user to the decision page\n\nTell the user to open the generated HTML file in their browser. Provide the `file_path` from the tool response. Then say to the user, verbatim: `Open the page. For any item you're unsure about, choose \"Ask about this\" — when you submit, I'll talk through those before we proceed. You can also ask me questions in chat before submitting if you prefer.`\n\nThis step only directs the user to the page and explains the two allowed next actions (submit selections, or ask questions first). Do not describe Step 7's rewrite semantics here; that belongs to the rewrite step.\n\n## Step 6: Q&A loop and commit signal\n\nEnter an open-ended Q&A loop. There is no turn cap — the user may ask any number of questions in any number of turns. Do not stop and wait silently; engage with each user message as either a commit signal or a discussion turn.\n\n### Proceed signal (commit)\n\nTrim the full user message and attempt to parse the entire trimmed message as JSON. The message is a commit only when the parsed value is an object with all three of these top-level fields:\n\n- `ticket_key` — must be a string\n- `decisions` — must be an object\n- `general_comment` — must be a string\n\nThe first valid commit-shaped JSON paste commits immediately. Proceed to Step 7 without prompting for additional confirmation. Any combination of `decisions` keys is accepted (the page may submit a partial set if the user only resolved some items conversationally). Do not over-validate the per-card fields beyond the top-level commit-shape check — the page guarantees the per-card schema, and over-validating risks rejecting valid pastes if the page schema evolves.\n\n### Discussion signal (Q&A turn)\n\nAnything that is not commit-shaped JSON is a discussion turn. This includes:\n\n- Freeform questions (with or without other text).\n- Questions pasted alongside other text or alongside JSON.\n- Malformed JSON (parse failure).\n- Well-formed JSON missing one or more of the required top-level keys (`ticket_key`, `decisions`, `general_comment`).\n\nFor JSON-shaped input that is missing required top-level fields, call this out in the reply — explain which fields are missing and ask whether the user intended to submit or share partial state — rather than silently treating it as a freeform question.\n\nAnswer discussion turns using these sources, in priority order:\n\n1. The combined `{ticket_key}-review-and-resolution.md` file already read in Step 1.\n2. The original `{ticket_key}-clarifying-questions.md` and `{ticket_key}-ticket-quality-critique.md` documents.\n3. Codebase lookups when the question requires verifying current code state.\n\nFallback: if running on a pre-PR1 branch where the combined review-and-resolution document does not exist, use the pre-PR1 `{ticket_key}-review-evaluation.md` and `{ticket_key}-resolution-guide.md` pair in its place.\n\nFor plain freeform questions, infer the item from chat context when possible.\n\n### In-flight decision state\n\nDuring the Q&A loop, maintain in-flight JSON state — agent-owned working memory representing the user's current intent for `decisions` and `general_comment`. This in-flight JSON state lives only in the agent's working memory for the duration of the loop; do not persist it server-side.\n\n- When the user clearly changes their mind about an item, chooses an option conversationally with reasonably explicit decision language (\"choose option B for E-3\", \"go with the configurable timeout\", \"change E-7 to None of these\"), or gives new overarching guidance, record that as an in-flight override.\n- Ambiguous preference language (\"I'm leaning toward...\", \"maybe option B is fine\") should be discussed but not recorded as an override unless the user gives reasonably explicit decision language.\n- `general_comment` may be updated in the in-flight state when the user gives overarching guidance during Q&A.\n- The page's general-comment textarea is preserved unchanged. Do not modify the page DOM during Q&A; the user can still fill the textarea before submitting if they prefer.\n\nOn the eventual JSON commit, the user-submitted JSON is the baseline and the recorded in-flight overrides take precedence over it. Before proceeding to Step 7, post a brief one-line acknowledgement in chat naming each overridden item ID and/or `general_comment`. The acknowledgement is mandatory (not optional) — it is the user's last chance to object before Step 7's document rewrite. The user does not need to re-open, edit, or re-submit the decision page after changing their mind in chat; they can submit the page as-is to provide the commit signal, and the in-flight state remains the source of truth for overrides.\n\n### Ask-about-this resolution\n\nAfter accepting a commit, scan `decisions` for any item where `choice === \"ask\"`. The user has signaled that they need more information before deciding on those items. For each such item:\n\n- If `comment` is non-empty, treat it as the user's specific question or stated uncertainty and answer that directly.\n- If `comment` is empty, proactively present the most relevant missing context — the item's `codebase_evidence`, related code lookups, prior-round answers — and lay out the trade-offs the user appears to need help weighing.\n- Continue the Q&A turn-by-turn until the user gives an explicit decision in chat for that item (\"go with option B\", \"none of these, because …\"). Record that decision as an in-flight override using the same override mechanism described above.\n\n**Hard rule.** Step 7 must not run while any `decisions[*].choice === \"ask\"` remains unresolved by an in-flight override. Do not honor \"just proceed\", \"skip those\", or any other instruction to defer resolution — every `ask` item must end with a recorded `opt-N` or `none` override before the rewrite step. The pre-Step-7 acknowledgement line lists every overridden item, including the ones resolved out of `ask`.\n\n### Implications review and proceed gate\n\n**Review the wider implications, then gate on a decision.** Build the review from the complete settled set: the submitted `decisions`, any in-flight overrides recorded during the conversation (these take precedence over the submission), every `\"none\"` answer together with the reason given for it, `general_comment`, and — where this surface tracks acceptance-criterion or NFR stances — those stances too. Do not start the review until every `ask` has an explicit recorded resolution and every in-flight override has been applied.\n\nConsider three fixed categories, regardless of whether a decision was framed as technical, user-facing, or business-oriented:\n- **Program / application** — architecture, code paths, operability, maintenance burden, and requirements imposed on other parts of the software.\n- **User** — end users, new users performing setup, operators, and developers, including prerequisites, setup friction, and additional steps.\n- **Business** — cost, adoption, support load, compliance, and reversibility.\n\nEmit only the categories with material second-order implications. For each included category, write at most four one-line bullets of about 25 words, each naming who or what is affected and how — never a restatement of the selected decision. Close with a line naming every considered category that was omitted, e.g. `Considered, nothing material: business.` — omit this closing line only when all three categories have material implications.\n\nIf the review cannot be produced, report that in one line and continue without stalling the workflow or presenting the gate below.\n\nThis review stays in chat and must not be written into the clarifying-questions or ticket-critique documents rewritten in Step 7.\n\nThen present the gate, verbatim: `Implications reviewed. Proceed, or name a decision to revisit.` Accept only a normalized `proceed`, `yes`, `y`, or `go` as a continuation token. Any other response names a decision to reopen: re-settle it in chat, record the new override, rerun the entire implications review against the changed settled set, and present the gate again.\n\nLiteral `auto_approve = true` emits the review but skips this gate entirely; a missing or non-true `auto_approve` value follows the human-in-the-loop path above.\n\nA decision named at this gate is re-settled in chat and recorded as an in-flight override using the same override mechanism as the rest of this step; the rerun review picks it up, and the pre-Step-7 acknowledgement line above also names it. Step 7 must not begin until every submitted `ask` is resolved (per the hard rule above) **and** this gate has accepted a proceed token — except when the review fails open or `auto_approve` is literal `true`.\n\n## Step 7: Interpretively rewrite source documents\n\nThe pasted JSON contains a `decisions` object keyed by item ID. Each decision includes `source`, `choice`, `chosen_label`, and `comment`. Use these fields to locate and rewrite the corresponding sections in:\n- `{docs_dir}/clarifying-questions/{ticket_key}-clarifying-questions.md`\n- `{docs_dir}/ticket-critiques/{ticket_key}-ticket-quality-critique.md`\n\nAfter a second-opinion run, each document has this shape:\n\n- A top-level H1 (`# Ticket Analysis` or `# Ticket Quality Critique`) followed by an italic provider-attribution line `_This analysis was generated by GPT|Claude|Gemini._` naming the first-round LLM family. **Preserve this attribution line verbatim** — do not move, edit, or remove it during the rewrite step.\n- The first-round questions / critique items, exactly as written by the first-round model.\n- **Inline second-opinion blockquotes** (`> **Second opinion (<provider>) - concurrence|refinement|disagreement.** ... > *Citations: ...*`) nested directly under each prior item the second round addressed. The `(<provider>)` parenthetical is the second-round LLM family (`GPT|Claude|Gemini`). Items the second round did not comment on have no blockquote — that is the \"weak concurrence\" signal.\n- A **`## New in Second Opinion`** tail block listing items the second round added on top of the first round. Immediately under the H2 there is a second italic attribution line `_These additional points were raised by GPT|Claude|Gemini._` naming the second-round family — **also preserve this verbatim**. Then agent-specific sub-headings:\n - Clarifier docs: `### New Requirements Questions` / `### New Technical Questions` (numbering continues from the prior section).\n - Critique docs: `### New Requested Changes` / `### New Points to Consider` (numbering continues from the prior section).\n- A final **`## Second Opinion Summary`** footer (1-3 sentences). **This footer must be preserved verbatim** — it is the canonical record of the second round's overall position and should not be edited.\n\nThe `source` field on each decision tells you where the item lives:\n\n- `Clarifying Q3 (prior round, weak concurrence)` → the prior section, no inline blockquote. Rewrite the prior item's answer.\n- `Clarifying Q9 (prior round, concurrence inline)` → the prior section, prior item carries an explicit `concurrence` blockquote. Rewrite the prior answer; the blockquote can be removed once the answer absorbs the resolution.\n- `Clarifying Q3 (prior round, refinement inline)` / `(prior round, disagreement inline)` → the prior section, prior item carries an explicit `refinement` or `disagreement` blockquote. Rewrite the prior answer to reconcile the dispute, then handle the blockquote per the rule below.\n- `Clarifying Q11 (new in second opinion → New Requirements Questions)` → the `## New in Second Opinion > ### New Requirements Questions` sub-section. Rewrite the item in place inside that sub-section, not at the top of the prior analysis.\n- Equivalent forms for critique items: `Critique: Requested Change 2 (prior round, refinement inline)`, `Critique: Points to Consider N+1 (new in second opinion → New Points to Consider)`, etc.\n\n**Legacy fallback shape**: if the document instead ends with `\\n\\n---\\n\\n` followed by a `## Second Opinion` section (because the JSON pipeline fell back), apply decisions to the equivalent location: `### Response to Prior Items` for inline-style responses, `### Additional Points > New X` for tail-style new items. Preserve the `\\n\\n---\\n\\n` separator and the `## Second Opinion` heading verbatim.\n\nApply the decision to the item in its home location. Then apply the decision:\n\n### Actionable item decisions\n\n- **Selected option** (`choice` is `opt-N`): Add `**Review Decision**: Accepted. <chosen_label>.` to the corresponding section. Integrate the selected direction into the section text so it reads as a final recommendation or resolved answer.\n- **None of these** (`choice` is `none`): Add `**Review Decision**: Rejected — none of the proposed options accepted.` Include the user's `comment` explaining why. Rewrite the section to reflect this decision.\n\nFor actionable items sourced from clarifying questions, rewrite the question's best-guess answer so it reads as the final resolved direction chosen by the reviewer. Do not leave the item framed as an unresolved accept/reject/modify prompt.\n\nFor items sourced from `(prior round, refinement inline)` or `(prior round, disagreement inline)` — disputes of a prior-round item carried in an inline blockquote — the prior-round item is the canonical home: rewrite its answer to absorb the resolution. Then handle the blockquote in one of two ways: (a) remove the blockquote outright if the rewritten answer fully absorbs the second-opinion content, or (b) shorten the blockquote to a single sentence noting the resolution while preserving the `(<provider>)` attribution (e.g. `> **Second opinion (Claude) - refinement.** Resolved by reviewer decision E-N.`). Citations from the original blockquote may be promoted into the rewritten prior-item answer if useful — keep the strongest 1-2 grounding refs.\n\nFor items sourced from `(new in second opinion → ...)` — gap-captured items that received a decision — rewrite the item in place inside its tail-block sub-section (`## New in Second Opinion > ### New X`), not at the top of the prior analysis. Preserve the sub-section heading and continued numbering.\n\n### General comment handling\n\nTreat `general_comment` as overarching guidance that informs the tone and direction of both document rewrites. If it contains specific actionable feedback, weave it into the relevant sections. If it is broad or general, use it as context for how the rewrites should read. Do not create a separate \"General Comment\" or \"Reviewer Notes\" section — the goal is \"final draft\" form.\n\n### Rewrite principles\n\nThe goal is a **final draft** — the documents should read as if they were written with the decisions already made. Do not mechanically append decisions. Instead, lightly rewrite affected sections so they reflect the decisions naturally. Preserve all non-affected sections unchanged. The prior-round content should still read as coherent standalone analysis after integration. Preserve the `## New in Second Opinion` tail block intact for any items that weren't decided. **Always preserve the `## Second Opinion Summary` footer verbatim** — it is the canonical record of the second round's overall position and should not be edited even when individual items it references have been resolved.\n\n## Step 8: Upload to Jira\n\nUpload both updated documents to Jira using `attachment` (operation: `\"upload\"`):\n\n1. Upload clarifying questions:\n - `ticket_number`: `{ticket_key}`\n - `file_path`: `{docs_dir}/clarifying-questions/{ticket_key}-clarifying-questions.md`\n - `link_type`: `clarifying-questions.md`\n\n2. Upload ticket quality critique:\n - `ticket_number`: `{ticket_key}`\n - `file_path`: `{docs_dir}/ticket-critiques/{ticket_key}-ticket-quality-critique.md`\n - `link_type`: `ticket-quality-critique.md`\n\n## Step 9: Complete\n\nConfirm: \"Review decisions captured and uploaded to {ticket_key}.\"\n\n## Return\n\nConfirm \"Review decisions captured and uploaded to {ticket_key}.\" and list the two attachments uploaded (`{ticket_key}-clarifying-questions.md` and `{ticket_key}-ticket-quality-critique.md`). Note any decisions that could not be applied.\n",
|
|
694
|
+
"checkpoint-work.md": "Checkpoint the work produced for ticket {ticket_key}.\n\nThis is the **durability boundary**. The production phase has just authored its\nartifacts and they exist only in the worktree. The pre-PR verification phase that\nruns next executes the plan's review steps, its test commands, and — for a\nfrontend ticket — a remediation loop of up to three cycles. That is the long part of\nthe run, and it is exactly where a session runs out of budget.\n\nSo the work is pushed to origin *first*. After this step, a worker that dies mid\nverification has still left its implementation recoverable on a remote ref.\n\nThis step is deliberately narrow. It makes **no branch decision**, opens **no pull\nrequest**, and asks for **no approval**. Branch selection and the pull request belong\nto `commit-and-push.md` and `create-pr.md`, which run later on the same branch. Doing\nany of that here would put a decision — and a possible pause — in front of the very\ndurability guarantee this step exists to provide.\n\n**Execution mode for this run: `{execution_mode}`.** Under `orchestrated`\n(`run_pipeline` / `resume_pipeline`) the checkpoint is returned as a fenced text block\nthat orchestration parses. Under `inline` (`get_pipeline_recipe`) there is no\norchestrator, so the checkpoint is recorded with a tool call instead. Follow the\nbranch that matches wherever the two are named.\n\n---\n\n## Step 1 — Assess the Worktree\n\nRun and note the results:\n\n- `git rev-parse --abbrev-ref HEAD` — the current branch.\n- `git status --porcelain` — everything modified, added, or untracked.\n\n**Use the branch you are on.** Do not create, rename, switch, or select a branch.\n\nStop immediately, reporting the reason, if any of these hold:\n\n- HEAD is detached (`git rev-parse --abbrev-ref HEAD` reports `HEAD`).\n- A merge, rebase, or cherry-pick is in progress.\n\nNeither is a state to commit into, and both need a human.\n\n## Step 2 — Clean Tree\n\nAn empty `git status --porcelain` means there is nothing new to checkpoint. It does\n**not** automatically mean everything is safe: the point of this step is that the work\nis on origin, so prove it rather than assume it.\n\n1. Run `git rev-parse HEAD`.\n2. Run `git ls-remote --heads origin <branch>` and compare the remote tip to HEAD.\n3. If the remote already contains HEAD, the checkpoint is satisfied. Report it and\n return.\n4. If HEAD is not on origin, there are local commits that were never pushed. Push them\n now with `git push origin <branch>` and re-verify.\n\nDo **not** create an empty commit to represent a checkpoint. An empty commit records\nnothing and proves nothing.\n\n## Step 3 — Commit and Push\n\nWhen there are changes to checkpoint:\n\n1. Stage the produced ticket work explicitly with `git add <file1> <file2> ...`. Do not use `git add -A` or `git add .` — a blanket stage sweeps in unrelated\n local files, and this step runs without an approval gate to catch that.\n2. Commit with:\n\n ```\n {ticket_key}: checkpoint produced work before verification\n ```\n\n3. Push the current branch immediately: `git push origin <branch>`. Add `-u` only if\n the branch has no upstream yet.\n\nUse the plain push command — do **not** add `--no-verify`. A Conductor worker already\nreceives `BRIDGE_SKIP_PREPUSH=1` from the executor, so bypassing hooks here is never\nnecessary.\n\n## Step 4 — Prove Durability\n\n1. Run `git rev-parse HEAD` and record the SHA.\n2. Run `git ls-remote --heads origin <branch>` and confirm the remote tip equals that\n SHA.\n\n**Stop the pipeline** and report the failure if the commit fails, the push fails or is\nrejected, or the remote tip does not match HEAD. The phase that follows is the long\none; entering it without durable work is precisely the failure this step prevents.\n\n## Return\n\nRecord the checkpoint the way this run's executor can actually read.\n\n### orchestrated\n\nReturn a machine-readable result as a fenced block tagged `bapi-checkpoint`, followed\nby a one-line human summary:\n\n```bapi-checkpoint\n{\"version\":1,\"branch\":\"<current branch>\",\"sha\":\"<checkpoint HEAD sha>\",\"pushed\":true,\"remoteMatchesHead\":true}\n```\n\nIf nothing needed committing because HEAD was already on origin, report the same shape\nwith the existing SHA and note that no new commit was required.\n\n### inline\n\nCall the `record_checkpoint` tool with `ticket_key` `{ticket_key}`, the `branch` and\n`sha` you verified in Step 4, and `pushed` / `remote_matches_head` set from what you\nactually observed. The tool refuses anything that does not report the work durable on\norigin, which is the point: a checkpoint that is not on the remote is not a checkpoint.\nReport the one-line human summary as well, but **do not emit a fenced `bapi-checkpoint`\nblock** — nothing parses one on this path.\n\nThe same applies when HEAD was already on origin and no new commit was needed: record\nthat existing SHA. The checkpoint is a claim about durability, not about having made a\ncommit.\n\nThe tool call is this step's final action, **not the end of your turn.** When it\nreturns successfully, continue immediately to the next recipe step —\n`execute-plan-verification.md`, the long pre-PR verification phase this checkpoint\nexists to protect.\n",
|
|
695
|
+
"clarify-open-nfrs.md": "Proactively clarify any open non-functional requirements with the user via an interactive decision page before decomposing the epic. Clear goals and a clear desired end-state make the functional decomposition far more accurate, so resolve the unclear NFRs first.\n\n## Inputs\n\n- The framing written by the previous step: `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md`.\n\n## Step 1: Read the framing\n\nRead `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md`. Collect the NFRs marked `open` and note the business goal, desired end-state, and system behavior.\n\n## Step 2: Skip if nothing is open\n\n**If there are no `open` NFRs**, skip the decision page entirely. Note that no clarification was needed and proceed (return). Do not generate a page just to fill it.\n\n## Step 3: Build the decision-page inputs\n\n**If there is at least one `open` NFR**, build the inputs for an interactive planning decision page:\n - `system_goals` (read-only): `business_goal`, `desired_end_state`, `system_behavior`, and `nfrs` — the full classified NFR list, each with `category`, `requirement`, `implication`, and `status`.\n - `actionable_items`: one card per `open` NFR. Each card has:\n - `id`: a short stable id, e.g. `NFR-1`, `NFR-2`.\n - `question`: the decision the open NFR poses (e.g. \"What latency budget must the harvester meet?\").\n - `options`: 2–4 concrete option labels. Do **not** include \"None of these\" or \"Ask about this\" — the renderer auto-appends both. If there is one obvious answer, still provide the strongest alternative as a second option.\n - `option_consequences`: one consequence line per option, parallel to and the same length as `options`.\n - `why_it_matters`: the concrete impact of the decision.\n - `recommendation_explanation`: why the recommended option is best.\n - `recommendation_index`: the 0-based index of the recommended option.\n\n## Step 4: Call generate_decision_page\n\n**Call `generate_decision_page`** with `ticket_key`, `artifact_type`, routing fields, and `labels` at the root, and `system_goals` + `actionable_items` nested under `content`:\n - `artifact_type`: `pre_ticket_planning`.\n - `ticket_key`: `{epic_slug}`.\n - `output_subdir`: `epic-plans/{epic_slug}`.\n - `output_filename`: `{epic_slug}-nfr-decisions.html`.\n - `labels`: planning-flavored overrides, e.g. `title` = \"Epic Planning Decisions\", `section_heading` = \"Open Non-Functional Requirements\", and an `intro` that frames the page as settling the goals and NFRs before decomposition.\n - `content`: an object containing `system_goals` and `actionable_items` from step 3. (Omit `implementation_order` — the order is produced after decomposition.)\n\n ```typescript\n interface NfrPlanningContent {\n system_goals?: {\n business_goal: string;\n desired_end_state: string;\n system_behavior: string;\n nfrs?: Array<{\n category: string; // e.g. \"security/privacy\", \"performance/latency\"\n requirement: string;\n implication: string; // required — what this changes about the implementation\n status: \"confirmed\" | \"assumed\" | \"open\";\n }>;\n };\n actionable_items?: Array<{\n id: string; // e.g. \"NFR-1\", \"NFR-2\"\n question: string;\n why_it_matters: string;\n recommendation_explanation: string;\n options: string[]; // 2-4 option labels\n option_consequences: string[]; // same length as options\n recommendation_index: number;\n }>;\n }\n ```\n\n Example call:\n ```json\n {\n \"ticket_key\": \"{epic_slug}\",\n \"artifact_type\": \"pre_ticket_planning\",\n \"output_subdir\": \"epic-plans/{epic_slug}\",\n \"output_filename\": \"{epic_slug}-nfr-decisions.html\",\n \"labels\": { \"title\": \"Epic Planning Decisions\", \"section_heading\": \"Open Non-Functional Requirements\" },\n \"content\": {\n \"system_goals\": {\n \"business_goal\": \"Reduce MCP token tax to improve agent context efficiency.\",\n \"desired_end_state\": \"Core profile uses fewer than 15k tokens per session.\",\n \"system_behavior\": \"On-demand contract delivery with no schema round-trips.\",\n \"nfrs\": [\n { \"category\": \"performance/latency\", \"requirement\": \"No latency regression\", \"implication\": \"Validate in handler, not at boundary\", \"status\": \"confirmed\" },\n { \"category\": \"security/privacy\", \"requirement\": \"Errors never leak into HTML\", \"implication\": \"Use JSON envelope only\", \"status\": \"confirmed\" }\n ]\n },\n \"actionable_items\": [\n {\n \"id\": \"NFR-1\",\n \"question\": \"What latency budget must the harvester meet?\",\n \"why_it_matters\": \"Sets the retry window for downstream consumers.\",\n \"recommendation_explanation\": \"Under 30s matches existing SLA.\",\n \"options\": [\"Under 30s\", \"Under 60s\"],\n \"option_consequences\": [\"Tight but achievable.\", \"Relaxed, may delay alerts.\"],\n \"recommendation_index\": 0\n }\n ]\n }\n }\n ```\n\n## Step 5: Capture the user's choices (stop and wait)\n\nDirect the user to the returned `file_path`, tell them to open it and submit. Treat a paste as a commit only when it is a JSON object with all three top-level fields: `ticket_key` (string), `decisions` (object), and `general_comment` (string). The submitted JSON is the baseline; record any explicit conversational change to a decision as an in-flight override, which takes precedence over the submission when constructing the settled set used in Step 6. A `\"none\"` selection carries any reason supplied in the card comment or chat — retain it. For any item where `choice === \"ask\"`, discuss until the user gives an explicit decision — record it the same way as any other override — before continuing; every `\"ask\"` must be replaced by an explicit recorded decision before Step 6 begins. You MUST stop and wait for the user to respond — do NOT assume answers and do NOT proceed until the open NFRs are resolved or the user explicitly declines.\n\n## Step 6: Review implications and gate\n\nThis surface's tracked stances are the NFR stances captured in Step 5. **Review the wider implications, then gate on a decision.** Build the review from the complete settled set: the submitted `decisions`, any in-flight overrides recorded during the conversation (these take precedence over the submission), every `\"none\"` answer together with the reason given for it, `general_comment`, and — where this surface tracks acceptance-criterion or NFR stances — those stances too. Do not start the review until every `ask` has an explicit recorded resolution and every in-flight override has been applied.\n\nConsider three fixed categories, regardless of whether a decision was framed as technical, user-facing, or business-oriented:\n- **Program / application** — architecture, code paths, operability, maintenance burden, and requirements imposed on other parts of the software.\n- **User** — end users, new users performing setup, operators, and developers, including prerequisites, setup friction, and additional steps.\n- **Business** — cost, adoption, support load, compliance, and reversibility.\n\nEmit only the categories with material second-order implications. For each included category, write at most four one-line bullets of about 25 words, each naming who or what is affected and how — never a restatement of the selected decision. Close with a line naming every considered category that was omitted, e.g. `Considered, nothing material: business.` — omit this closing line only when all three categories have material implications.\n\nIf the review cannot be produced, report that in one line and continue without stalling the workflow or presenting the gate below.\n\nThe latest review will be written under `## Implications` in `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md` once the gate below allows continuation.\n\nThen present the gate, verbatim: `Implications reviewed. Proceed, or name a decision to revisit.` Accept only a normalized `proceed`, `yes`, `y`, or `go` as a continuation token. Any other response names a decision to reopen: re-settle it in chat, record the new override, rerun the entire implications review against the changed settled set, and present the gate again.\n\nLiteral `auto_approve = true` emits the review but skips this gate entirely; a missing or non-true `auto_approve` value follows the human-in-the-loop path above.\n\n## Step 7: Fold the answers back into the framing\n\nRewrite `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md` so each resolved NFR's `status` moves from `open` to `confirmed` (or `assumed` when the user chose a provisional default), recording the chosen resolution in the `requirement`/`implication`. Weave `general_comment` in as overarching guidance. Add or update the `## Implications` section with the latest review from Step 6 — the final one after any reopen/review loop — or its one-line fail-open notice if generation was unavailable. Leave settled sections unchanged. Run this rewrite only after Step 6's implications-review loop has completed or followed its non-blocking fail-open path.\n\nThis step is non-blocking only insofar as the user may explicitly decline; if `generate_decision_page` fails, log a warning, direct the user to the markdown framing instead, and continue.\n\n## Return\n\nReport whether a planning decision page was generated (and its path) or skipped because there were no open NFRs, and how many open NFRs were resolved into `confirmed`/`assumed`.\n",
|
|
696
696
|
"commit-and-push.md": "Stage, commit, and push implementation changes for ticket {ticket_key}.\n\nBefore executing, assess the git state and present a clear plan for user approval.\n\n## Step 1 — Assess Git State\n\nRun these commands and note the results:\n- `git branch --show-current` — record the current branch name\n- `git status --porcelain` — identify all modified, added, and untracked files\n\n### If the working tree is clean (nothing to commit)\n\nAn empty `git status --porcelain` is not one situation — it is two, and they must\nbe told apart before anything else happens. Check the published state of the\nbranch this ticket's work would live on (the current branch if it references\n`{ticket_key}`, otherwise `feature/{ticket_key}`):\n\n- `git ls-remote --heads origin <branch>` — non-empty output means the branch is\n already pushed.\n- `gh pr list --head <branch> --state all` — reports any pull request already\n opened from that branch.\n\nThen apply the matching rule:\n\n1. **Clean tree, and no pushed branch or pull request exists for this ticket** —\n the implementation phase produced nothing. **Stop the pipeline here** and\n report the failure. Proceeding would open an empty pull request; an empty\n implementation must halt.\n2. **Clean tree, but the branch is already pushed and/or a pull request already\n exists** — this is a legitimate **re-entry**, not an empty implementation.\n Recovery runs (`ci_fix`, `remediate`, `rebase`) re-enter this pipeline on a\n branch whose commits were pushed by an earlier session, so there is often\n nothing new to commit. **Do not halt.** There is nothing to stage, so skip\n Steps 2–5 entirely: run `git rev-parse HEAD`, record the result as\n `last_commit_sha`, and return successfully so the pipeline continues to the\n downstream steps (pull request handling, verification, CI monitoring) the\n re-entry was dispatched to run. Before returning, compare `git rev-parse HEAD`\n against the remote tip from `git ls-remote` — if local commits exist that were\n never pushed, push them (`git push origin <branch>`) first, preserving the\n finalization boundary.\n\nEither signal — a pushed branch or an existing pull request — selects the\nre-entry case. Only when both are absent does the clean tree mean an empty\nimplementation.\n\n## Step 2 — Determine Branch\n\nDecide the branching strategy and be prepared to state it explicitly. Cover:\n\n- Whether you will commit on the current branch, or create a new branch.\n- If creating a new branch: the exact new branch name, and which branch it will be created from (current branch vs. `main`).\n- If branching from `main`: whether `main` needs to be pulled/updated first, and the command you will run.\n- Whether the target branch already exists remotely (and if so, whether you will push to the existing remote branch).\n\nDefault rules:\n\n- If the current branch already contains `{ticket_key}` (case-insensitive), plan to commit on the current branch.\n- Otherwise, plan to create a new branch named `feature/{ticket_key}` from the current branch.\n\n## Step 3 — Prepare Commit Details\n\n- Separate implementation files from unrelated changes. Only stage files related to the ticket.\n- Compose a commit message: `{ticket_key}: <brief description of what was implemented>`\n\n## Step 4 — Present Plan for Approval (commit, push, and PR)\n\nFor this run, `auto_approve` = `{auto_approve}`.\n\n**Auto-approve mode.** If `auto_approve` is `true`, do NOT present the approval plan and do NOT wait for user input. Apply the default branching rule from Step 2 (commit on the current branch if it contains `{ticket_key}` case-insensitively; otherwise create `feature/{ticket_key}` from the current branch). Stage all files reported by `git status --porcelain` that you assess as related to the ticket per Step 3's \"Only stage files related to the ticket\" rule (when uncertain, prefer including over excluding — auto-approve trades caution for momentum, and the user has explicitly opted in). Use the commit-message format from Step 3. Skip directly to Step 5 and execute.\n\nOtherwise (any value of `auto_approve` other than the literal `true` — including empty, `false`, or missing), proceed with the existing approval flow below.\n\nPresent a single approval plan covering the commit, push, and pull request creation before proceeding:\n\n```\nCommit Plan for {ticket_key}\n─────────────────────────────\nCurrent branch: <current branch name>\nBranching: - <\"Commit on current branch\" | \"Create new branch `<name>` from `<source branch>`\">\n - <if branching from main: \"Pull latest main first via `git checkout main && git pull`\" | omit if N/A>\n - <\"Remote branch already exists — will push to existing\" | \"New remote branch — will push with -u\" | omit if N/A>\nFiles to stage: <count> files\n - path/to/file1.py\n - path/to/file2.py\nExcluded: <any unrelated changed files, or \"None\">\nCommit message: {ticket_key}: <description>\nPush to: origin/<target branch>\nPR title: <commit subject — derived automatically after commit>\nPR base: main\n```\n\nWait for the user to approve, request changes, or reject. The user may adjust the branch name, file inclusion, commit message, PR title, PR base, or give other instructions. The PR title defaults to the commit subject after the commit is made, and the PR base defaults to `main`.\n\nDo not proceed until the user explicitly approves.\n\n## Step 5 — Execute\n\nThis step is the **finalization boundary**: the commit and the push must both\ncomplete, synchronously and successfully, before this instruction returns. Nothing\ndownstream — pull request creation, verification, CI monitoring — may begin while\nthe implementation exists only in the local worktree.\n\n1. If creating a new branch, run `git checkout -b <branch name>`.\n2. Stage approved files with `git add <file1> <file2> ...` — do not use `git add -A` or `git add .`.\n3. Commit with the approved message.\n4. Push with `git push -u origin <branch>`. Use the plain push command — do **not**\n add `--no-verify`. Normal git hook behavior is preserved here; a Conductor\n worker already receives `BRIDGE_SKIP_PREPUSH=1` from the executor, so the\n instruction never needs to bypass hooks itself.\n5. If the commit fails, or the push fails or is rejected, **stop the pipeline\n here** and report the failure. Do not continue toward pull request creation or\n verification with work that exists only locally. One exception: a commit that\n fails only because there is genuinely nothing to commit means Step 1's\n clean-tree rule applies — resolve it there (halt when nothing was ever\n published; proceed when the branch/PR already exists) instead of treating the\n empty commit itself as the terminal failure.\n6. After the push succeeds, run `git rev-parse HEAD` and record the resulting SHA\n as `last_commit_sha` — the durable head that was actually published to the\n remote.\n\n## Return\n\nReport that the commit was made and pushed: the selected branch name, the pushed\nremote (e.g. `origin/feature/{ticket_key}`), the commit subject line, and the\npost-push `git rev-parse HEAD` value labeled `last_commit_sha`. Note any files that\nwere intentionally excluded from the commit. If commit or push failed, report the\nfailure instead — the pipeline stops rather than proceeding.\n\nIn the clean-tree re-entry case (Step 1, rule 2), report that no new commit was\nneeded: the branch name, the existing pushed remote, and the current\n`git rev-parse HEAD` value labeled `last_commit_sha` — and state that the pipeline\nis continuing to the downstream steps.\n",
|
|
697
697
|
"comp-analysis.md": "Perceive any attached/referenced design comp with your OWN vision and map it to the existing codebase BEFORE the `jira-ticket-writer` drafts. This is the pre-writer perception step: the orchestrating recipe agent (already a frontier vision model) opens the comp, classifies it against the shared fidelity taxonomy, researches the code, and writes a structured comp→codebase map the writer consumes. The writer stays text-only and never opens images — it only reads the map you produce here.\n\nThis step is gated and backend-safe. It runs the perception with the ORCHESTRATING agent's own vision — a local image via the Read tool, or an already-attached Jira comp fetched as raw bytes via the BAPI-562 binary-safe `attachment` download (operation `download`) into a worktree `file_path`. It does NOT call `describe_image()`, does NOT depend on `src/python/llms/vision.py`, and does NOT require the `CHEAP_MODEL` vision path or any vision-model upgrade or procurement. The heavy visual reasoning is done for free by the agent that already runs the recipe.\n\n## Inputs\n\n- Run manifest: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/run-manifest.json` (source of truth for `idea`, `scope`, `readiness`). Read whichever prior artifacts exist under `{docs_dir}/idea-to-ticket/{slug}-{run_id}/` (research pack, resolved uncertainties, goals-and-nfrs, standards checklist) and proceed without the ones that do not.\n- Output artifact (this step writes it): `{docs_dir}/idea-to-ticket/{slug}-{run_id}/comp-analysis.json` — the structured comp→codebase map the drafting step reads.\n\n## Instructions\n\n1. **Gate first — evaluate only text/material metadata, never open an image yet.** Proceed to any image work ONLY when BOTH conditions hold:\n - a design comp is **referenced or attached** (a local image path in the idea/materials, or an already-attached Jira comp with an `attachment_id`), AND\n - the requested work is **design/UI work** (a frontend/fullstack change with a visual surface).\n\n This gate is deliberately conservative. A **backend-only** request, a **no-comp** request, or a **non-design** request fails the gate.\n\n2. **Not-applicable branch (gate fails) — short-circuit immediately.** When either gate condition is not met, write `comp-analysis.json` with `applicable: false`, a short `reason`, and the `gate` evidence fields, then **return immediately** — do NOT open any image, do NOT download any attachment, do NOT inject any fidelity/comp/visual language, and add no measurable latency. A backend-only or no-comp authoring input must be byte-for-byte unaffected downstream. Concretely, the not-applicable artifact is:\n\n ```json\n { \"applicable\": false, \"reason\": \"backend-only work; no design comp referenced\", \"gate\": { \"comp_referenced\": false, \"design_ui_work\": false }, \"warnings\": [] }\n ```\n\n3. **Applicable branch — obtain and OPEN the comp with your own vision.** When the gate passes:\n - **Local image path** → open it directly with the Read tool.\n - **Already-attached Jira comp** → fetch it as raw bytes using the BAPI-562 binary-safe `attachment` capability with operation `download`, passing the comp's `attachment_id` and a worktree `file_path`; the download saves the PNG/JPEG bytes to that `file_path` inside the project root, then open the saved file with the Read tool.\n - You are the orchestrating vision model — reason over the actual pixels yourself. Do NOT call `describe_image()`, do NOT use `src/python/llms/vision.py` / `CHEAP_MODEL`, and do NOT delegate perception to the text-only `jira-ticket-writer` subagent.\n\n4. **Degraded paths are skip-clean and warn-not-halt.** If the comp is missing, unreadable, an unsupported format, external-only (an `http(s)` URL you cannot fetch into a worktree `file_path`), or turns out not to be a usable design comp, write a valid `comp-analysis.json` with `applicable: false`, a `reason`, and a populated `warnings` array describing what failed, then return. A missing, unreadable, or non-comp image NEVER blocks downstream drafting and NEVER requires further image work after the failure.\n\n5. **Classify the opened comp using the shared fidelity taxonomy (do not fork it).** Using your own vision, classify the comp as exactly one of these four classes — the same labels the downstream final plan reviewer uses (`src/python/llms/agents/planner_agent/final_plan_review_agent.py`, `_get_runtime_verification_instructions`), so authoring, planning, and implementation all agree:\n - `full comp`\n - `wireframe`\n - `annotated-screenshot-of-existing-UI`\n - `unknown`\n\n Record `fidelity_classification` with a `class` (one of the four), a `confidence` value, and a short `reasoning` string.\n\n6. **Apply class-appropriate mapping depth — no over-specification.** Match the per-class rules exactly:\n - **full comp** (confident) → map exact existing components, Jinja2 templates, SCSS/CSS tokens, and routes; strict/exact component + token depth is used ONLY here.\n - **wireframe** → map layout and structure only (regions, order, rough proportions, responsive behavior); defer color, type, spacing, and component polish to the repo design system, NOT to the wireframe.\n - **annotated-screenshot-of-existing-UI** → map ONLY the delta against the current UI; preserve everything outside the annotated region and do not reproduce the screenshot wholesale.\n - **unknown / low confidence** → fall back to the design-system floor rather than mapping pixels.\n\n **Hard rule:** strict/exact mapping depth is enabled ONLY for a confidently-classified full comp. Fail toward the design system, never toward reproducing an ambiguous image.\n\n7. **Research the codebase and map each region/element to concrete existing code.** Inspect the working tree (search, grep, file reads) for the existing UI implementation surfaces: reusable components, Jinja2 templates, plain CSS/SCSS tokens and design-system styles, routes, and reusable frontend patterns. Only cite files you actually inspected — do not invent file paths, component names, tokens, or routes. For each region/element of the comp, produce a `mappings[]` entry containing:\n - `region` — the comp region or element name.\n - `visual_description` — a short description of what it looks like.\n - `components` — mapped existing component file(s).\n - `templates` — mapped existing Jinja2 template(s).\n - `tokens` — style/token references (SCSS/CSS tokens or design-system styles).\n - `routes` — route reference(s) where the element lives or should wire.\n - `confidence` — confidence for this mapping.\n - `implementation_guidance` — concrete guidance (e.g. \"reuse component X\", \"extend template Y\", \"use token Z\", \"wire route R\").\n\n8. **Write the structured map to a stable schema.** Write `comp-analysis.json` at `{docs_dir}/idea-to-ticket/{slug}-{run_id}/comp-analysis.json` with these fields:\n - `applicable` — boolean; `true` only after a comp was both detected AND successfully opened.\n - `reason` — short string explaining the applicability decision.\n - `gate` — the two-condition gate evidence (`comp_referenced`, `design_ui_work`).\n - `comp` — provenance of the opened comp (source kind, path or `attachment_id`, filename, MIME type when known).\n - `fidelity_classification` — `{ class, confidence, reasoning }`, present only when `applicable` is true.\n - `mappings` — array of the per-region entries defined in step 7 (present only when `applicable` is true).\n - `design_system_floor` — the design-system fallback guidance to use for wireframe/unknown/low-confidence regions.\n - `warnings` — array of degraded-path notes (may be empty).\n - `writer_guidance` — instructions for the downstream drafting step: when `applicable` is `true`, Requirements must cite the mapped components/templates/tokens/routes as concrete implementation guidance; when `applicable` is `false` or the map is missing, the writer must ignore this artifact and mention no comp analysis, design comp, or visual-fidelity language unless the original request independently requires it.\n\n9. **Never over-write.** Write the artifact exactly once at the path above. Downstream steps (`draft-and-critique.md`) read it; do not move it.\n\n## Return\n\nConfirm the path written (`{docs_dir}/idea-to-ticket/{slug}-{run_id}/comp-analysis.json`), whether the analysis was `applicable`, the fidelity `class` when applicable, and any `warnings`.\n",
|
|
698
|
-
"create-pr.md": "# Create a pull request for the just-pushed branch\n\nThe implementation has been committed and pushed. Open a PR against `main`
|
|
698
|
+
"create-pr.md": "# Create a pull request for the just-pushed branch\n\nThe implementation has been committed and pushed. Open a PR for the current branch against the PR base resolved in Step 3 — which is `main` only when nothing higher in that order of precedence supplies a base — with a descriptive title derived from the commit you just made.\n\n## Step 1 — Read the commit subject line\n\nRun `git log -1 --pretty=%s` to get the most recent commit subject. The implement-ticket pipeline asks the commit step to use the form `{ticket_key}: <description>`, so this line is normally already a good PR title.\n\n## Step 2 — Determine the head branch\n\nUse `git branch --show-current`. This is the head branch.\n\n## Step 2.5 — Run the file-scope guard (warn-only, before opening the PR)\n\nBefore opening or updating the PR, run the conductor file-scope guard so an\nout-of-scope diff is surfaced in the PR-creation context:\n\n```bash\nnode \"$BAPI_CONDUCTOR_CLI_FILE\" file-scope-guard\n```\n\n(or `conductor file-scope-guard` if the packaged binary is on PATH).\n\nThis guard is **warn-only and fail-open** — it **always exits 0 and never blocks\nPR creation** in v1. Behavior:\n\n- If `BAPI_CONDUCTOR_DECLARED_TOUCHED_FILES_JSON` is **absent, empty, or invalid**,\n the guard is a **no-op** — it prints nothing and you **continue** to Step 3\n normally. Do not treat a missing declaration as an error.\n- If the guard prints a warning that your branch diff touched files **outside** the\n ticket's declared touched-file set, **surface that warning in the PR-creation\n context** (include it in your summary to the user / PR notes) but **do not block**\n — proceed to open the PR. The warning is advisory: it flags a possible\n sibling-scope over-reach for human review, it does not stop the workflow.\n\n## Step 3 — Resolve the base, compose the body, and call create_pull_request\n\n### Resolve the PR base\n\nResolve `base_branch` through this ordered precedence, taking the first tier that yields a usable value:\n\n1. **`BAPI_BASE_BRANCH` from the environment, when set and non-empty.** Read it explicitly with Bash — never infer the base from branch ancestry or from the repository default branch:\n\n ```bash\n echo \"${BAPI_BASE_BRANCH:-}\"\n ```\n\n The non-failing `:-` form returns an empty line when the variable is unset, so the read never errors. `start-tickets` exports this variable into the worker's shell whenever the run has a non-default base (an epic branch, for example), which makes it the run's own answer and the highest-priority tier.\n2. **A PR base the user supplied at the commit step.** The commit step advertises PR base as an adjustable field, so an override given there carries forward into this call rather than being silently replaced by a lower tier.\n3. **The repository's configured base branch.** Call `config_field` with `operation: \"get\"` and `field_name: \"base_branch\"`.\n4. **`main`** — the normal fallback default when no tier above supplied a base.\n\nTreat a null, empty, or whitespace-only configured value, an HTTP `400`, or any lookup error as **unset** and continue quietly to the `main` fallback. Missing configuration is an ordinary outcome here, not a failure of this step.\n\n### Compose the PR body\n\nBuild `body` in this reading order:\n\n1. A concise summary line for the ticket — what this pull request changes.\n2. A plainly labeled reference to the local implementation plan, as plain text rather than a markdown hyperlink (the path is local to whoever pulls the branch): `Implementation plan available locally at <docs_dir>/plans/{ticket_key}-plan.md`. Use the plan location this recipe already knows when it has one; otherwise resolve `<docs_dir>` with the `get_docs_dir` MCP tool.\n3. The checklist text of `.github/PULL_REQUEST_TEMPLATE.md`, read from the current worktree when that file exists, appended after the plan reference without rewriting its markdown structure. Omit this part when the file is absent.\n\nGitHub's REST API does not automatically apply the repository pull request template — that template is a web-UI affordance only. A pull request opened through this tool therefore carries an empty description unless the recipe inlines the checklist into `body` itself, which is exactly why the checklist is read from the worktree and appended here.\n\n### Call the tool and report the PR URL\n\nCall the `create_pull_request` MCP tool directly with:\n\n- `head_branch`: value from `git branch --show-current`\n- `base_branch`: the base resolved above\n- `title`: the commit subject from Step 1 (the derived PR title) — unless the user supplied a different PR title at the commit step, in which case use that value instead.\n- `body`: the body composed above\n\nHonor any PR title / PR base overrides the user gave at the commit step's plan; the commit step advertises those fields as adjustable, so any override the user gave there must carry forward into this tool call rather than being silently replaced by a lower-precedence value.\n\n`create_pull_request` is the only mechanism this recipe uses to open a pull request. Do not shell out to a VCS command-line client to create it.\n\nReport the returned `pr_url` to the user.\n\n### The PR URL is a hard prerequisite for everything downstream\n\nThis step completes the durable artifact that the rest of the pipeline — and, under\nthe Conductor, the reconciler — binds to. It therefore has a strict success\ncondition: the call must yield a **non-empty PR URL**, either for a pull request it\nnewly opened or for an already-open pull request on this head branch that the\nresponse identifies.\n\nIf the tool is unavailable, errors, or returns neither a usable new PR URL nor an\nexisting one, **stop here and report the failure**. Do not advance to the\npost-finalization verification phase, which exists only to add work on top of an\nopen pull request.\n\nThen run `git rev-parse HEAD` and record the current pushed head SHA, so the\ndownstream phases report the same durable head this pull request points at.\n\n## Return\n\nReturn the head branch, the base branch that was used, the pull request URL, and\nthe current pushed HEAD SHA. If no usable pull request URL was obtained, return\nthat failure instead — the pipeline stops rather than proceeding to verification.\n",
|
|
699
699
|
"decompose-epic-candidate.md": "Decompose an Epic parent draft into ordered child tickets with idempotency and per-child duplicate checks.\n\n## Inputs\n\n- Epic parent draft: `{docs_dir}/tickets/EPIC-{slug}.md`.\n- Research pack: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-pack.md` / `.json`.\n- Standards checklist: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/standards-checklist.json`.\n- Resolved uncertainties: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/resolved-uncertainties.md`.\n- Goals & NFR framing: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/goals-and-nfrs.md` (its System Goals/NFRs and any provisional Recommended Implementation Order should inform the child breakdown and ordering).\n- Hard cap variable `{max_children}` (string integer; default `\"10\"` when not set by the caller). The default `\"10\"` is a **hard ceiling / upper bound, not a target** child count — it caps how many children are allowed, and is **not a goal to fill**. The normal target child count is smaller (fewer, larger M/L slices); see the sizing heuristics in step 2.\n\n## Instructions\n\n1. Read the Epic parent draft, research pack, standards checklist, and resolved uncertainties. Use only this context plus optional narrow web search; do not call deep research from this step.\n\n2. Propose ordered child tickets that, together, fully implement the Epic.\n\n **Sizing heuristics (maintainer-owned defaults).** Size each proposed child by its expected **file-touch breadth and depth plus rough lines of code (LOC) changed**, using these exact thresholds:\n - `S = 1–2 files / <~80 LOC`\n - `M = ~3–8 files / ~80–400 LOC (ideal target)`\n - `L = ~8–15 files / ~400–900 LOC (acceptable)`\n - `XL = >15 files / >~900 LOC → split further; never emit an XL child`\n\n Target size priority: `M (ideal) → L (acceptable) → S (only if unavoidable); never XL`.\n\n Bias the decomposition toward **fewer, larger, independently implementable vertical slices** rather than many tiny one-feature children. The Bridge implementation tooling works better on M–L vertical slices, and a swarm of tiny S children magnifies sibling merge risk under parallel execution. Each child should be an independently implementable vertical slice; if a proposed child would be XL, split it further until each piece is M or L.\n\n Each proposed child must include:\n - `summary` — Jira title.\n - `issue_type` — typically `Task`; use `Spike` only for primarily discovery children.\n - `rationale` — short explanation of why this child exists and what it produces. Include a brief size estimate inside this existing field (do **not** add a new `size` field), e.g. `Estimated size: M (~4 files / ~150 LOC)`.\n - `labels` — must include `ai-generated`, `idea-to-ticket`, `idea-to-ticket-child`, and the unique child idempotency label `bapi-idea-to-ticket-{run_id}-child-<N>` where `<N>` is the 1-based child index in the final ordered list.\n - `idempotency_label` — the same `bapi-idea-to-ticket-{run_id}-child-<N>` string.\n - `draft_path` — `{docs_dir}/tickets/TICKET-{slug}-child-<N>.md` (drafts written by `jira-ticket-writer` later).\n - `depends_on` — array of the 1-based child indexes that are **hard prerequisites** (must land first), or empty. Keep this list minimal and real.\n - `recommended_after` — array of child indexes that are **soft sequencing** preferences (nicer to do after, but not blockers), or empty.\n - `order_rationale` — one line explaining why this child sits at this point in the order.\n\n Keep hard prerequisites (`depends_on`) strictly separate from soft sequencing (`recommended_after`). These fields drive the recommended implementation order posted to the epic later; they do **not** create Jira dependency links.\n\n3. Hard cap enforcement. First attempt a normal, smaller M/L-biased decomposition per the step 2 sizing heuristics. Then count proposed children: `{max_children}` is a hard ceiling that **halts on exceed**, not a target to fill. If the count exceeds `{max_children}` (parsed as an integer), halt locally with a clear \"split first\" message: ask the user to split the idea into multiple smaller Epics or to raise `--max-children` deliberately. Do not silently truncate.\n\n4. Per-child duplicate lookup. For each proposed child (in order), call `get_tickets` once with a title/keyword search built from the child's summary. If a clear duplicate exists, drop that child from the plan and record the drop reason; never halt the whole run because a child has a duplicate. Re-number `<N>` only after all drops are finalized so child indexes are contiguous.\n\n5. Per-child research is restricted to the parent research pack plus optional narrow web search. Do not call deep research per child.\n\n6. Write `{docs_dir}/idea-to-ticket/{slug}-{run_id}/decomposition-plan.json` with at minimum:\n - `parent_summary` — copy from the parent draft.\n - `max_children` — the resolved integer value used for the cap.\n - `children` — ordered array of surviving children with all fields from step 2 (including `depends_on`, `recommended_after`, and `order_rationale`). After re-numbering in step 4, fix up the `depends_on`/`recommended_after` indexes so they still point at the correct surviving children.\n - `dropped_children` — array of `{proposed_summary, reason}` for children removed by duplicate lookup.\n\n## Return\n\nConfirm `decomposition-plan.json` was written, report the final child count and the number of children dropped for duplicate reasons.\n",
|
|
700
700
|
"decompose-epic.md": "Decompose the epic into manageable sub-tasks and get user approval.\n\n## Epic Description\n\n{epic_description}\n\n## Instructions\n\n1. Read the following artifacts to establish full context. If a file does not exist or is empty, proceed without it:\n - `{docs_dir}/epic-plans/{epic_slug}/research-findings.md`\n - `{docs_dir}/epic-plans/{epic_slug}/codebase-exploration.md`\n\n2. Reason about the epic and produce a decomposition. Consider:\n - Logical groupings of work that can be implemented and tested independently\n - Dependencies between sub-tasks (what must be built first)\n - A reasonable scope for each sub-task (each should be achievable in a single implementation session)\n\n3. Write the decomposition to `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md` with this format:\n\n```markdown\n# Epic Decomposition\n\n## Sub-tasks\n\n### 1. {Sub-task title}\n- **Scope**: {What this sub-task covers}\n- **Key files/areas**: {Files and code areas involved}\n- **Dependencies**: {Other sub-task numbers this depends on, or \"None\"}\n\n### 2. {Sub-task title}\n...\n```\n\n In addition, you MUST also write a structured JSON sidecar at\n `{docs_dir}/epic-plans/{epic_slug}/epic-plan.dag.json`.\n This file is the machine-readable intermediate consumed by the `plan-epic`\n pipeline to store and approve the plan in the backend — it must be written\n from your structured decomposition data, NEVER by re-parsing the markdown.\n\n The sidecar format is:\n\n```json\n{\n \"plan_version\": 1,\n \"nodes\": [\n {\n \"ticket_key\": \"BAPI-XXX\",\n \"status\": \"planned\",\n \"depends_on\": [],\n \"touched_files\": [\"api/routes/example.py\", \"src/python/llms/ai_client.py\"],\n \"automations\": [\n { \"kind\": \"start-tickets\" }\n ]\n }\n ],\n \"edges\": [\n { \"from\": \"BAPI-XXX\", \"to\": \"BAPI-YYY\" }\n ]\n}\n```\n\n Rules for the sidecar:\n - `plan_version` must be 1 for a new plan (an integer, never a float).\n - Each node `ticket_key` must match the Jira key of the created sub-task\n (populated after Jira ticket creation in a later pipeline step; use the\n planned Jira key if known, or a placeholder like \"TBD-1\" if not yet created).\n - `ticket_key` values must be unique and non-empty after trimming.\n - `depends_on` lists the `ticket_key` values this node depends on (mirrors\n the markdown Dependencies field). `depends_on` is the **canonical**\n dependency declaration.\n - `status` must be `\"planned\"` for newly-created sub-tasks.\n - `touched_files` is **required on every node** — the sorted, deduplicated,\n repository-relative POSIX paths this sub-task is predicted to change.\n Populate it from your current code research and the sub-task's ownership,\n the same analysis that tells you which sub-tasks collide.\n - No leading `./`, no absolute paths, no `..` traversal segments, no\n temporary-worktree paths, and no prose. Declare **concrete files**: the\n backend intersects these paths as exact strings, so a directory or glob\n entry matches nothing and protects nothing.\n - `[]` is permitted **only** when the decomposition explicitly establishes\n that the sub-task changes no repository files. Unknown file ownership is\n **blocking** — resolve it or flag it; never represent it as an empty\n array, which silently disables file-overlap protection.\n - `automations` lists automation kinds to run on the ticket — valid values\n are `\"start-tickets\"` and `\"review-tickets\"`. Use an empty array if none.\n - `edges` is an explicit list of directed dependency edges (from → to, where\n `from` is the predecessor). It may be empty if all dependencies are captured\n in `depends_on`, but any edge you do write must encode the same graph as\n `depends_on` — a contradictory graph blocks readiness.\n - Do **not** set `base_lineage` on any node. It affects the plan hash but has\n no consumer in either conductor, so setting it invalidates the approved hash\n for no behavioral gain.\n - The DAG must be acyclic (no circular dependencies).\n - The deterministic Jira-dependency-link DAG builder is the documented\n fallback/recovery path if this sidecar is lost or corrupted (not built here).\n\n **Placeholders are finalized later, not here.** `TBD-N` remains the correct\n node identity for the window before the epic's Jira tickets exist. The\n standalone `emit-conductor-bundle.md` task replaces every placeholder with the\n real ticket key and finalizes `touched_files` after the tickets are created and\n before the plan is stored or approved. Write your best `touched_files`\n prediction here anyway — that task reconciles it against the whole epic.\n\n4. **Soft limit check**: If the decomposition results in more than 8 sub-tasks, you must verbally warn the user: \"This decomposition has N sub-tasks, which exceeds the recommended limit of 8. Consider splitting this feature into multiple epics.\" Then proceed with the approval flow.\n\n5. Present the decomposition to the user and ask for their feedback. Explain the reasoning behind the breakdown and the dependency ordering.\n\n6. You MUST stop and wait for the user to respond. Do NOT assume approval. Do NOT proceed to the next step.\n\n7. If the user provides feedback or rejects the decomposition:\n - Incorporate their feedback\n - Rewrite `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md` with the revised version\n - Present the revised decomposition and ask for approval again\n - Repeat until the user explicitly approves\n\n8. Only after explicit user approval, confirm: \"Decomposition approved. Proceeding to sub-task exploration.\"\n\n## Return\n\nConfirm \"Decomposition approved.\" and report the final sub-task count plus the path to `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md`. Flag if the count exceeded the recommended limit of 8.\n",
|
|
701
701
|
"draft-and-critique.md": "Draft the ticket(s) for this idea, run a BAPI-320 hygiene pass, and emit structured draft metadata.\n\n## Inputs\n\n- Run manifest: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/run-manifest.json`.\n- Research pack: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-pack.md` / `.json`.\n- Duplicate assessment: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/duplicate-assessment.json`.\n- Standards checklist: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/standards-checklist.json`.\n- Resolved uncertainties: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/resolved-uncertainties.md`.\n- Goals & NFR framing: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/goals-and-nfrs.md`.\n- Comp→codebase map (optional): `{docs_dir}/idea-to-ticket/{slug}-{run_id}/comp-analysis.json`. Produced upstream by the gated `comp-analysis.md` perception step. A missing, unreadable, or `applicable: false` map is treated exactly like `applicable: false` — a no-op: it never halts drafting and this step injects no visual-fidelity/comp language on its own.\n\n## Instructions\n\n1. **Resolve the regression-completeness gate once, before drafting.** Call the `config_field` MCP tool with `operation` set to `\"get\"` and `field_name` set to `enable_regression_checks`. Normalize the response: only the exact value `true` (a JSON boolean `true`, or the case-insensitive string `\"true\"`) counts as enabled. Treat a missing tool, a tool error, `null`, `false`, or any other/malformed value as disabled — this lookup is fail-open and defaults OFF. Store the normalized boolean as `enable_regression_checks` and reuse the same stored value for every `jira-ticket-writer` invocation this flow makes (including any later critique/revision call) — do not re-resolve it per call. The `jira-ticket-writer` sub-agent must not call `config_field` itself.\n\n2. Read the six required input artifacts in full before drafting, plus the comp-analysis map when it is present. The manifest's `scope` (`task`, `spike`, or `epic_candidate`) determines the drafting path.\n\n The goals-and-nfrs.md framing must shape every draft. Lead each draft with the **business goal** and **desired end-state**, and include an explicit **Non-Functional Requirements** section (and, where it clarifies behavior, the required **system behavior**). For the **epic_candidate** parent, these belong in the Epic description itself (the parent's `slim_description` should at least name the business goal + end-state, and the attached full draft must carry the Goals / Desired End-State / Non-Functional Requirements sections). Any NFR still marked `open` in the framing must be written into the draft as an explicit assumption plus an open-risk note — never silently dropped. This flow is documentary: do not generate a decision page and do not pause for clarification here.\n\n3. Drafting path by scope:\n - **task** or **spike**:\n - Call the `jira-ticket-writer` sub-agent with an explicit output path of `{docs_dir}/tickets/TICKET-{slug}.md`. The sub-agent must write the full markdown draft to that exact file. Pass the comp-analysis map path (`{docs_dir}/idea-to-ticket/{slug}-{run_id}/comp-analysis.json`) into the sub-agent prompt alongside the six existing input artifacts (run manifest, research pack, duplicate assessment, standards checklist, resolved uncertainties, goals-and-nfrs) and the stored `enable_regression_checks` value from step 1.\n - **epic_candidate**:\n - Call `jira-ticket-writer` to draft only the Epic parent. Use the explicit output path `{docs_dir}/tickets/EPIC-{slug}.md`. Pass the same comp-analysis map path into the sub-agent prompt alongside the six existing input artifacts and the stored `enable_regression_checks` value from step 1. Child tickets are produced later by `decompose-epic-candidate.md`; do not draft them here.\n\n Comp-analysis map consumption (both paths): when `comp-analysis.json` has `applicable: true`, tell the writer its Requirements MUST use the mapped components/templates/tokens/routes as concrete implementation guidance (e.g. \"reuse component X\", \"use token Z\", \"extend template Y\", \"wire route R\"). When the map has `applicable: false` or is missing/unreadable, tell the writer to ignore the artifact entirely and avoid mentioning comp analysis, design comps, or visual fidelity unless the original request independently requires those materials. This step only feeds the text JSON map to the writer — it never opens images, calls `describe_image()`, or performs vision analysis itself.\n\n Regression-gate consumption (both paths): state `enable_regression_checks: {stored value from step 1}` explicitly in the sub-agent prompt, and tell the writer this value was already resolved by the caller and must not be looked up again. The writer only runs its Regression Completeness Pass when this value is exactly `true`.\n\n4. Issue type policy:\n - Default ambiguous ideas to `Task`.\n - Choose `Spike` only when the work is primarily discovery/research/learning with no clear acceptance criteria yet.\n - The Epic parent uses Jira issue type `Epic`.\n\n5. Hygiene pass (BAPI-320 forbidden tokens). After the sub-agent writes the draft, read it back and ensure none of these tokens are present:\n - markdown tables (any `|`-separated header row).\n - escaped pipe-table patterns (e.g. `\\|`).\n - task-list checkboxes such as `- [ ]` or `- [x]`.\n - angle-bracket placeholder tokens (any `<placeholder>` form, even inside backticks).\n - raw HTML blocks (`<div>`, `<br>`, `<table>`, etc.).\n When a forbidden token is found, rewrite the surrounding paragraph in plain prose or bullet form and save the cleaned draft over the same path.\n\n6. Write `{docs_dir}/idea-to-ticket/{slug}-{run_id}/draft-metadata.json` describing what Jira should later create.\n\n For **task** / **spike** scope, the metadata shape is:\n - `summary` — Jira ticket title.\n - `issue_type` — `Task` or `Spike`.\n - `labels` — array of Jira labels. Must include `ai-generated`, `idea-to-ticket`, the per-run label `bapi-idea-to-ticket-{run_id}`, and the stable idea-hash label `bapi-idea-hash-{idea_hash}` (so a future run of the same idea is caught by label).\n - `idempotency_label` — `bapi-idea-to-ticket-{run_id}` (matches the label used by the duplicate-and-context-scan step).\n - `slim_description` — short Jira-safe description (no forbidden tokens). The full draft is uploaded as an attachment. It must include a CONCISE, high-level summary of the draft's `## Materials & Access` inventory (Planning Assets, Downloadable Assets, Planning & Downloadable Assets vs. unphased record-only material), noting that the exhaustive list lives in the attached full draft. This keeps the missing-materials record visible to human reviewers and to description-reading review/critique flows.\n - `attachment_path` — `{docs_dir}/tickets/TICKET-{slug}.md` (or the equivalent path used above).\n\n For **epic_candidate** scope, the metadata shape is:\n - `parent.summary` — Epic title.\n - `parent.issue_type` — `Epic`.\n - `parent.labels` — must include `ai-generated`, `idea-to-ticket`, `bapi-idea-to-ticket-{run_id}-parent`, and the stable idea-hash label `bapi-idea-hash-{idea_hash}`.\n - `parent.idempotency_label` — `bapi-idea-to-ticket-{run_id}-parent`.\n - `parent.slim_description` — short Epic description. It must include a CONCISE, high-level summary of the Epic draft's `## Materials & Access` inventory (Planning Assets, Downloadable Assets, Planning & Downloadable Assets vs. unphased record-only material), noting that the exhaustive list lives in the attached full draft.\n - `parent.attachment_path` — `{docs_dir}/tickets/EPIC-{slug}.md`.\n - `children` — placeholder array. Populated later by `decompose-epic-candidate.md`; leave as an empty array here.\n\n7. Save the metadata exactly once. Downstream steps read this file; do not move it.\n\n## Return\n\nConfirm the draft path, the metadata path, and the chosen scope (`task`, `spike`, or `epic_candidate`).\n",
|
|
@@ -703,8 +703,8 @@ export const INSTRUCTIONS = {
|
|
|
703
703
|
"emit-conductor-bundle.md": "Harmonize an epic's sibling tickets against each other and emit the artifacts the conductor needs, after the tickets exist and before the plan is approved.\n\nEach sibling ticket was drafted by a separate writer session that could not see\nits siblings. Each independently re-researched the codebase and re-derived\ninterfaces, names, and file ownership, so siblings routinely disagree exactly at\nthe seams where they must agree — the dependency edges. The decomposition itself\nwas coherent (one agent, one context, wrote `epic-plan.md` and every exploration\ndocument); that coherence is discarded at the handoff. This task reads every\nsibling in one context and restores it.\n\nThe window is forced. Real ticket keys exist only after creation, and description\nrewrites are free before approval but trip `spec_stale` after it.\n\n**This is a standalone task, deliberately not a step in `plan-epic.json`.**\n`plan-epic` creates no tickets, so wiring this in there would guarantee it runs\nbefore any sibling exists. The local agent invokes it directly, immediately after\ncreating the epic's tickets, passing the ordered node→key mapping it already\nholds.\n\n## Inputs\n\n- `epic_key` — the Jira key of the epic (e.g. `BAPI-634`). **Required.**\n `setup-epic --dry-run` needs it, it cannot be derived safely from the slug, and\n it cannot be recovered from Jira: `get_tickets` filters only by free-text\n `search` and `labels`, with no `parent_key` filter.\n- `epic_slug` — the sanitized slug naming the epic-plan directory.\n- An **ordered array of mapping entries**, one per sidecar node, each with:\n - `plan_node_id` — the node's identity in `epic-plan.dag.json` (a `TBD-N`\n placeholder on the initial run, or the real key on a rerun).\n - `ticket_key` — the real Jira key created for that node.\n - `exploration_path` — that sub-task's exploration document, relative to the\n epic-plan directory.\n - `draft_path` — that sub-task's draft, relative to the epic-plan directory.\n\n**Node identity comes only from `plan_node_id`.** Never infer which node a ticket\nbelongs to from mapping order, ticket titles, description text, or a Jira search.\nA key list plus `epic_slug` cannot determine which real key replaces which\n`TBD-N`, and guessing attaches one ticket's dependencies to another.\n\n## Instructions\n\nResolve `docs_dir` by calling the `get_docs_dir` MCP tool (no parameters). The\nsole workspace for this task is `{docs_dir}/epic-plans/{epic_slug}`. Never read or\nwrite outside it.\n\nExecute the following phases **in this order**. The ordering is the safety\nproperty: every external write is gated behind local validation, so a failure\nleaves Jira untouched rather than half-mutated. Pipeline ordering cannot protect a\nmanual or recovery run, so this task owns it.\n\n### Phase 1 — Non-mutating run-state precheck\n\nBefore reading artifacts, confirm the epic is still in the pre-approval window:\n\n```bash\nnpx -y -p @bridge_gpt/mcp-server conductor epic-status --epic-key <epic_key> --json\n```\n\nThis is read-only. Interpret the result:\n\n- `{\"status\": \"unknown\", \"state\": null}` — no run exists yet. **Proceed**; the\n dry-run and a later `store-and-approve-epic-plan` will create it.\n- `epic_run.status` is `planning` **and** its plan version is not yet stored —\n a single unapproved planning run. **Proceed**; it may be reused.\n- `epic_run.status` is `active`, `blocked`, `done`, or `abandoned` — **halt.**\n- `epic_run.approved_plan_hash` is non-null (the plan is approved) — **halt.**\n- The sidecar's `plan_version` is already stored — **halt.** Plan blobs are\n immutable and post-approval description rewrites are forbidden; this needs an\n explicit re-plan.\n- Multiple runs, or any ambiguous/unreadable state — **halt.** Never guess.\n\nHalting here means reporting the state and stopping. Do not attempt a repair.\n\n### Phase 2 — Validate inputs and source artifacts\n\nAssemble the mapping into a JSON input document:\n\n```json\n{\n \"epic_key\": \"<epic_key>\",\n \"epic_slug\": \"<epic_slug>\",\n \"decomposition_fingerprint\": \"<stable fingerprint of this decomposition>\",\n \"mappings\": [\n {\n \"plan_node_id\": \"TBD-1\",\n \"ticket_key\": \"BAPI-635\",\n \"exploration_path\": \"explorations/01-<subtask-slug>.md\",\n \"draft_path\": \"drafts/01-<subtask-slug>.md\"\n }\n ]\n}\n```\n\nThen run the deterministic entry validation **before reading any mapped file,\nfetching any ticket, or writing any artifact**:\n\n```bash\nnpx -y @bridge_gpt/mcp-server emit-conductor-bundle validate \\\n --input <path to the input document> \\\n --json\n```\n\nThis writes nothing. A non-zero exit halts the task; relay its error verbatim.\nThese are entry-point checks, not agent judgment. It enforces:\n\n- `epic_key` and every `ticket_key` match the project's Jira key pattern, are\n non-empty and unique, and no child key equals `epic_key`.\n- `epic_slug` matches the sanitized slug grammar.\n- The mapping is **complete and one-to-one**: every sidecar node has exactly one\n entry, and every entry matches exactly one node — by `plan_node_id` on the\n initial run, or by its already-mapped `ticket_key` on a rerun.\n- An existing `sibling-ticket-manifest.json` agrees with the supplied mapping on\n epic identity, slug, plan version, decomposition fingerprint, and every\n node→key pair. **On disagreement, halt** — never silently prefer either source.\n- Every mapped path resolves beneath `{docs_dir}/epic-plans/{epic_slug}`.\n Absolute paths, `..` traversal, paths into another epic's directory, unknown\n mapping paths, and symlink escapes are all rejected before their content is read.\n\nThen load these **authoritative artifacts** into one working context:\n\n- `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md`\n- `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md`\n- `{docs_dir}/epic-plans/{epic_slug}/epic-plan.dag.json`\n- every mapped exploration document\n- every mapped draft\n\n**Halt** if any of them is missing, malformed, or unmatched. These are\nauthoritative inputs; proceeding without one voids the reconciliation guarantee.\n\nRe-fetch every mapped child ticket by its supplied key (`get_ticket`) and keep\nthe complete sibling set in one context. Reading them one at a time defeats the\nentire purpose of this task.\n\nDelimit every dynamically inserted Jira, plan, draft, or exploration excerpt with\ntriple quotes before analyzing it, and strip secret-like content before it can\nreach a prompt, a rendered description, decision material, a report, or an\nattachment.\n\n### Phase 3 — Harmonize the whole epic (in memory)\n\n**Authority order when sources conflict:**\n\n1. Exploration documents and current code research — primary evidence.\n2. Intended scope in `epic-plan.md` — what the decomposition meant to build.\n3. Current ticket descriptions — **outputs to be corrected, never authoritative\n inputs.**\n\nReview the complete sibling set once against this taxonomy, rather than a vague\n\"look for problems\" pass:\n\n- **interface drift** — the same function, endpoint, table, or field described\n differently across siblings.\n- **ownership collision** — two tickets both claiming to create the same file,\n symbol, or migration.\n- **orphan consumer** — a ticket consuming a seam no sibling produces.\n- **order violation** — a ticket assuming work a later sibling does.\n- **scope overlap** — two tickets covering the same work.\n- **vocabulary drift** — the same concept named inconsistently.\n- **NFR conflict** — a ticket contradicting `goals-and-nfrs.md`.\n\nEvery dependency edge must end up with an explicit producer, an explicit\nconsumer, an owned seam, an exact interface or artifact name, and a required\nordering.\n\n#### Canonical contract blocks\n\nRender each shared seam **once**, and insert byte-identical text into both the\nproducer's and the consumer's description. This is what makes \"described\nidentically at the edge\" checkable rather than a matter of opinion.\n\nUse stable delimiters and a stable seam identifier:\n\n```\n<!-- BEGIN CONTRACT: {seam_id} -->\n**Contract: {seam_id}**\n\n- **Producer**: {producer_ticket_key}\n- **Consumer(s)**: {consumer_ticket_keys}\n- **Interface**: {exact name and signature/shape}\n- **Ordering**: {what must exist before what}\n<!-- END CONTRACT: {seam_id} -->\n```\n\n`{seam_id}` is derived deterministically from the seam's identity (the interface\nor artifact name), so the same seam keeps the same id across runs. Everything\noutside a contract block stays ticket-specific: each ticket keeps its own\nsummary, scope, requirements, acceptance criteria, constraints, and risks.\n\n#### Fold in the exploration document\n\nThe description is the **only** channel a conductor worker can see. The\nreconciler resolves the spec and ships it in the job payload; the worker reads the\nticket, not the repo. `docs/tmp/epic-plans/` is gitignored and worker worktrees\nare cut from a pinned `origin/<base>` SHA, so exploration documents are never on\ndisk for the implementing agent.\n\nFold each sub-task's exploration document into its ticket under a deterministic\ndelimited section:\n\n```\n<!-- BEGIN EXPLORATION: {ticket_key} -->\n...\n<!-- END EXPLORATION: {ticket_key} -->\n```\n\nPreserve every implementation-relevant file, symbol, interface, constraint,\ndecision, and open risk. Resolve every mapped `TBD-N` token to its real key in\nticket prose, exploration content, drafts, and contract blocks — not only in the\nsidecar. Drafts authored before the tickets existed refer to siblings as `TBD-N`;\na worker receiving that text has no actionable dependency reference.\n\n#### The spec length bound — fail loud\n\nValidate every complete rendered description against the bound. The conductor's\npayload bound is **64,000 characters** (the reconciler no longer truncates\nsilently — overflow beyond its own bound is visibly marked). For Jira-backed\ntickets the **practical** limit binds far earlier: Jira caps a description at\n**32,767 characters**, so treat that as the real-world ceiling there.\n\nCount **Unicode code points**, not UTF-16 code units — the server's bound is a\nPython `len()`, so an astral character (an emoji, say) counts once there but\ntwice under a naive JavaScript `.length`, which would reject a description that\nactually fits.\n\n- Compact repetition and non-actionable prose **first**, without dropping\n actionable content.\n- If the required content still will not fit, **fail loud and escalate** as a\n decomposition/scope finding.\n- An attachment is **not** a workaround — the worker cannot see it.\n- Raising the server-side bound is out of scope.\n\n#### Auto-resolve vs escalate\n\n**Auto-resolve only** when the authoritative artifacts make the intended contract\nunambiguous: normalizing vocabulary, or copying a producer's already-defined\ninterface name to its consumer.\n\n**Escalate** any proposed change to scope, decomposition, ownership boundaries,\ndependencies, public contracts, migrations, NFRs, or acceptance criteria. A\ncontradiction implying a scope or decomposition change is not a wording fix;\nauto-resolving one silently is worse than the contradiction, because it launders a\nreal decision into prose nobody reviewed.\n\n#### Build `touched_files`\n\nThe file-ownership map you built to detect **ownership collision** *is*\n`touched_files`. This step is the only place with a whole-epic view, and nothing\nelse emits the field today.\n\n- Sorted, deduplicated, repository-relative POSIX paths — no leading `./`, no\n absolute paths, no `..` traversal, no temporary-worktree paths, no prose. The\n `finalize` step rejects anything else rather than dropping it. Concrete files\n only: the backend intersects these as exact strings, so a directory or glob\n entry protects nothing.\n- Every node carries the field. `[]` is valid **only** where the ticket genuinely\n touches no repository files and that is explicit.\n- **Unknown ownership is escalated, never encoded as `[]`** — an empty array\n silently disables overlap protection.\n- When two tickets legitimately touch the same file, **both** keep it. If one\n consumes an interface the other produces, add the semantic dependency\n explicitly rather than relying on overlap serialization for ordering.\n\n### Phase 4 — Escalate and halt, if there are escalations\n\nAssign this invocation a local `harmonization_run_id`, and give each finding a\nstable id derived deterministically from its normalized class, its sorted\naffected ticket keys, and its seam or file identity — so the same contradiction\nkeeps the same id across runs and a resumed decision still applies.\n\nIf any finding is escalated, build **one consolidated decision page** using the\ninteraction established in `clarify-open-nfrs.md` — call `generate_decision_page`\nwith `artifact_type: \"pre_ticket_planning\"`, `ticket_key: {epic_slug}`,\n`output_subdir: \"epic-plans/{epic_slug}\"`, and\n`output_filename: \"{epic_slug}-harmonization-decisions.html\"`. Give each item its\ntaxonomy class, affected tickets, bounded conflicting evidence, options, and a\nrecommended resolution.\n\nBefore halting, atomically persist the validated manifest, the provisional report,\nand the decision-page reference. Then **halt without changing the sidecar or\nJira**. Stop and wait for the user; do not assume a resolution.\n\n**On resume**: read the manifest, re-fetch all tickets, re-evaluate the complete\nsibling set, apply the recorded decision, and continue from this phase. Do not\nrestart `plan-epic` — that risks recreating tickets or losing the key mapping. Do\nnot post a duplicate decision page or order comments.\n\n### Phase 5 — Stage the local bundle\n\nAdd the whole-epic ownership map to the input document as\n`touched_files_by_key` (real Jira key → its predicted files), then finalize:\n\n```bash\nnpx -y @bridge_gpt/mcp-server emit-conductor-bundle finalize \\\n --input <path to the input document> \\\n --json\n```\n\nThis atomically writes, in one deterministic step:\n\n1. The finalized `{docs_dir}/epic-plans/{epic_slug}/epic-plan.dag.json` — the\n validated node→key map applied across `nodes[].ticket_key`,\n `nodes[].depends_on`, and `edges[].from`/`to`, with each node's normalized\n `touched_files` attached and nothing else mutated. It rejects residual `TBD-`,\n duplicate keys, unknown references, self-dependencies, cycles, and ordinary\n edges that contradict the canonical `depends_on` graph.\n2. `{docs_dir}/epic-plans/{epic_slug}/sibling-ticket-manifest.json` — versioned\n schema, epic identity, sidecar plan version, decomposition fingerprint, the\n ordered mapping, run phase, decisions, and completed-mutation markers. It\n records both the validated source-sidecar identity and the finalized-sidecar\n identity, so a rerun can tell a legitimate finalized sidecar from a different\n decomposition, and it excludes descriptions, credentials, exploration bodies,\n and raw Jira responses.\n\nEvery write is a temp file in the destination directory followed by a rename, so\nan interrupted run cannot leave a partial recovery source. A non-zero exit halts\nthe task; relay its error verbatim.\n\nThen write the report artifacts:\n\n3. `{docs_dir}/epic-plans/{epic_slug}/harmonization-report.json` — versioned\n schema, run metadata, and bounded findings.\n4. A run-scoped archive beside it\n (`harmonization-report.{harmonization_run_id}.json`), **without replacing\n earlier archives**. The fixed path holds only the latest run, so without the\n archive one idempotent rerun would erase the only measurement of what this gate\n ever caught.\n\n- **Preserve `plan_version`.** Do not bump it: these changes finalize version 1\n *before* it is stored.\n- **Never set `base_lineage`.** It affects the plan hash but has no consumer in\n either conductor, so setting it invalidates the approved hash for no gain.\n\n### Phase 6 — The dry-run gate\n\n```bash\nnpx -y @bridge_gpt/mcp-server setup-epic \\\n --epic-key <epic_key> \\\n --plan-file <docs_dir>/epic-plans/<epic_slug>/epic-plan.dag.json \\\n --dry-run \\\n --json\n```\n\n`validateEpicPlanSidecar()` is a pure local function over the parsed sidecar —\nplan version, key uniqueness, `touched_files`, acyclicity — with no Jira\ndependency. Running it first costs nothing and removes the partial-mutation\nfailure mode entirely.\n\n- **Any non-zero exit halts.** Relay the command's failure text verbatim; it is\n already actionable.\n- **Any `touched_files` warning halts**, even on a successful exit. That warning\n means a node's ownership is undeclared, which is the exact gap this task exists\n to close: an undeclared node is never pre-serialized against an overlapping\n sibling, so it relies entirely on reactive conflict detection at the merge gate.\n Go back and declare it before proceeding.\n\n This halt is **this task's own planning-quality bar, not a server rejection.**\n Plan storage *accepts* an omitted `touched_files` as an explicit opt-out\n (BAPI-722), so nothing downstream will stop you — which is precisely why the\n standard has to be held here. (A *malformed* `touched_files` is different: the\n server does reject that outright with `VALIDATION`.)\n- **Never fall back** to POSTing `/jira/epic-runs/runs` directly, storing the\n plan, or approving it. A duplicate active run wedges the epic permanently.\n\nIf staging or the dry-run fails, leave Jira descriptions and attachments\nuntouched.\n\n### Phase 7 — Apply the external mutations\n\nOnly on a passing dry-run. Repeat the **Phase 1 run-state precheck immediately\nbefore the first Jira write**, and halt if it now shows approval, activation,\nblocking, plan storage, multiple runs, or an ambiguous state. On a resume,\nre-fetch all sibling tickets and re-evaluate the complete set before applying any\nrecorded decision.\n\n**Descriptions.** Compare each complete proposed description against the ticket's\ncurrent Jira description using the same normalization as\n`normalize_ticket_spec()`: collapse every run of whitespace to a single space and\ntrim, so cosmetic diffs never trigger a rewrite. A pure reflow or indentation\nedit is deliberately **not** a material change — the server treats it the same\nway, and diverging here would false-freeze tickets via `spec_stale`. Call\n`update_ticket_description` **only when the normalized descriptions differ\nmaterially**, and pass the **complete rendered description** — this is a full\nrewrite, not an append. Record each successful description mutation in the\nmanifest before moving to the next one, so a retry converges without duplicating\nwork.\n\n**Drafts and attachments.** Refresh the local draft with the reconciled complete\ndocument, then upload it with the `attachment` tool\n(`operation: \"upload\"`, `replace_existing: true`), which replaces any existing\nattachment of the same filename. Note it is delete-then-create rather than an\natomic revision, so the attachment id changes. If replacement is unavailable,\nmark the superseded local draft prominently and upload one deterministically named\nreconciled document instead. Skip the upload when an equivalent revision is\nalready present. **Do not add a Jira comment solely to refresh or supersede an\nattachment.** Record each draft/attachment mutation in the manifest so a retry\nskips completed equivalent work.\n\n**Finalize the reports.** After the required mutations converge, atomically\nrewrite the fixed and run-scoped reports with the actual mutation outcomes.\n\n### Clean reruns\n\nA rerun over an already-harmonized epic is a **clean no-op**. It must not call\n`update_ticket_description`, upload a duplicate attachment, add a comment, alter\nplan semantics, bump `plan_version`, approve anything, or create status rows. It\nstill runs the final dry-run validation, still emits the fixed report (with an\nempty `findings` array), and still preserves every prior archive. It may rewrite\nidentical local JSON whose bytes differ only by normalization.\n\n### Never do these\n\n- Never create or seed `epic_ticket_status` rows, and never add a fallback\n seeding path. Seeding is owned by `approve_epic_plan`, which seeds one\n `planned` row per plan node idempotently before flipping the run to `active`.\n- Never approve a plan, activate a run, or POST to `/jira/epic-runs/runs`.\n- Never set `base_lineage`.\n- Never rewrite a description after the run reaches `active` — that trips\n `spec_stale`.\n\n## Return\n\nReport:\n\n- The manifest path.\n- The fixed report path and the run-scoped archive path.\n- The ticket keys whose descriptions **changed**, and those left **unchanged**.\n- Attachment outcomes per ticket.\n- The dry-run result.\n- Exactly one status: **`ready_for_approval`** or **`decision_required`**.\n\nState explicitly that **approval remains a separate subsequent action** — this\ntask never approves the plan. On `ready_for_approval`, the operator runs\n`store-and-approve-epic-plan` next.\n",
|
|
704
704
|
"evaluate-and-recommend.md": "Evaluate the clarifying questions and ticket critiques generated for {ticket_key} against the actual codebase, then decorate every actionable item with the resolution guidance the reviewer will need on the decision page. The result is a single combined review-and-resolution document.\n\n## Phase 0 — Grounding & Audit Setup\n\nBefore gathering any source documents, extract the codebase-grounding context produced by the preceding `materialize_fresh_base` pipeline step:\n\n- Read the `materialize_fresh_base` tool result from earlier in this session. It returns JSON `{ base_sha, base_branch, fresh_base_root }` — or, when `no_refresh_base` was set, `{ base_sha: \"local-stale\", fresh_base_root: <original repo root> }`.\n- Retain `fresh_base_root` and `base_sha` for the rest of this procedure. Every codebase read in Phase 1 / Phase 2 below is grounded against `fresh_base_root`. `fresh_base_root` is also the exact value you must pass to the pipeline's later `cleanup_fresh_base` step — it is a *runtime* value returned by the tool call, not a static recipe variable, so pass the real path string you captured here, not any placeholder text shown in the step's params.\n- If the `materialize_fresh_base` step's result contains an `error` field and `no_refresh_base` was NOT set, this is the fail-loud condition the recipe's `on_error: \"halt\"` exists for: stop here, do not fall back to grounding against your own working directory, and report the failure (name the attempted base branch and the remediation — retry, or rerun with `--no-refresh-base`).\n\n**Metadata Audit Header** — the very first content of the generated review-and-resolution document, before any other section, must be:\n\n```\n**Base SHA**: <base_sha>\n**Base Branch**: <base_branch, or \"(local, in-place)\" when base_sha is \"local-stale\">\n**Grounding Status**: <Freshly Materialized | Stale/In-Place Fallback>\n```\n\n- `Grounding Status` is **Freshly Materialized** whenever `base_sha` is a real commit SHA (the normal path).\n- `Grounding Status` is **Stale/In-Place Fallback** whenever `base_sha` is exactly `local-stale` (the `--no-refresh-base` opt-out path). In this case, immediately follow the header with a prominent, bold, high-contrast warning block, for example:\n\n > **⚠ STALE GROUNDING — `--no-refresh-base` was used.** This review evaluated the codebase as checked out locally, NOT a freshly-fetched `origin/<base>`. `file:line` citations may reflect uncommitted or unmerged local state.\n\n**Codebase grounding rule**: Ground ALL file reads and codebase searches exclusively against the `fresh_base_root` directory extracted above. Do NOT read codebase files from your default working directory or session cwd — `fresh_base_root` is the only trustworthy source of truth for `file:line` citations in this procedure.\n\n**Original-repo rule**: Ticket docs, `{docs_dir}` inputs, and ALL output paths stay in the ORIGINAL repository, never the `fresh_base_root` temp dir. This includes the ticket-fetch call below, the clarifying-questions / critique source documents, and the saved review-and-resolution output file (see the Save rule at the bottom). Do NOT redirect any of these into `fresh_base_root`.\n\n**Path hygiene rule**: Every `file:line` citation and Codebase Evidence entry in the output document MUST be repo-relative — strip the `fresh_base_root` absolute-path prefix before writing it down. A citation must never contain a temp-dir / `/tmp/...`-style absolute path (write `src/foo.ts:10`, never `/tmp/bridge-review-.../src/foo.ts:10`).\n\n1. Fetch the current ticket description using the `get_ticket` tool with ticket_number `{ticket_key}` exactly once at the top of this procedure.\n\n2. Gather the clarifying questions and critique documents from the preceding pipeline steps. The local files at `{docs_dir}/clarifying-questions/{ticket_key}-clarifying-questions.md` and `{docs_dir}/ticket-critiques/{ticket_key}-ticket-quality-critique.md` are the canonical source. After a second-opinion run, each document has this shape:\n\n - A top-level H1 (`# Ticket Analysis` for clarifier docs, `# Ticket Quality Critique` for critique docs) followed by an italic provider-attribution line of the form `_This analysis was generated by GPT|Claude|Gemini._`. The attribution names the LLM family that produced the **first round**.\n - The first-round questions / critique items, exactly as written by the first-round model.\n - **Inline second-opinion blockquotes** nested directly under each prior item the second round addressed. Each blockquote starts with `> **Second opinion (<provider>) - <stance>.**` where `<provider>` is `GPT|Claude|Gemini` and `<stance>` is `concurrence|refinement|disagreement`. The blockquote is followed by `> *Citations: <comma-separated grounding refs>*`. Items the second round did **not** comment on have no blockquote — that is the \"weak concurrence\" signal. Use the provider name in the blockquote header to attribute the comment to the second-round LLM family in your evaluation prose where helpful.\n - A **`## New in Second Opinion`** tail block listing items the second round added on top of the first round. Immediately under the H2 you will find a second italic attribution line of the form `_These additional points were raised by GPT|Claude|Gemini._` — this names the second-round LLM family. Sub-headings are agent-specific:\n - Clarifier docs: `### New Requirements Questions` and `### New Technical Questions` — numbering continues from the prior section.\n - Critique docs: `### New Requested Changes` and `### New Points to Consider` — numbering continues from the prior section.\n Each new item has its own `*Citations: ...*` line.\n - A final **`## Second Opinion Summary`** footer (1-3 sentences) capturing the second round's overall position. This always renders, even when the second round had no inline comments and no new items.\n\n **Legacy fallback shape**: in rare cases (model lacks JSON-schema support, the JSON call failed, or the response could not be parsed), the document may instead end with `\\n\\n---\\n\\n` followed by a `## Second Opinion` section containing `### Response to Prior Items` and `### Additional Points` subsections. If you detect this fallback shape, treat it equivalently: subsection responses tagged `concurrence` map to weak/strong concurrence (use the body length to disambiguate — bare one-line concurrences are weak), `refinement`/`disagreement` map to the disagree buckets, and items under `### Additional Points` map to the gap-captured bucket below.\n\n **Partial-source-doc tolerance**: if the clarifying-questions doc OR the ticket-critique doc is missing or unreadable, skip that document silently and produce items only for the surviving doc. Do not fail. If **both** documents are absent, still write the combined output file at `{docs_dir}/review/{ticket_key}-review-and-resolution.md` with the standard top-level sections (`Confirmed Improvements`, `Needs Scrutiny`, `Open Questions`, `Round Agreement Summary`) present but no emitted E-items in any section. This preserves downstream file-existence expectations for the capture-review-decisions step.\n\n3. Determine **Round Agreement** for every clarifying question and critique point using these rules:\n\n - **Both rounds agree (weak concurrence)** — the prior item has NO inline blockquote AND is not in `## New in Second Opinion`. The second round did not object to the point and did not consider it important enough to comment on. Briefly validate the answer's groundedness against the codebase. If validation surfaces concerns, demote this item to **rounds disagree** (single round only depth) and treat as Needs Scrutiny.\n - **Both rounds agree (strong concurrence)** — the prior item carries an inline `> **Second opinion (<provider>) - concurrence.** ...` blockquote. The second round explicitly reinforced the prior point. Reuse the blockquote's `*Citations:*` as starting evidence; verify briefly.\n - **Rounds disagree (refinement)** — the prior item carries an inline `> **Second opinion (<provider>) - refinement.** ...` blockquote. The second round modified or added detail. Apply full disagreement-depth analysis; reuse blockquote citations.\n - **Rounds disagree (disagreement)** — the prior item carries an inline `> **Second opinion (<provider>) - disagreement.** ...` blockquote. The second round contradicts the prior. Apply full disagreement-depth analysis; categorize the outcome based on which position the codebase supports.\n - **Gap captured** — the item lives under `## New in Second Opinion > ### New <category>` (one of: New Requirements Questions, New Technical Questions, New Requested Changes, New Points to Consider). Apply the two-axis check below. Reuse the new item's `*Citations:*` as starting evidence.\n - **Single round only** — the document has none of the above markers (no inline blockquotes, no `## New in Second Opinion` block, no `## Second Opinion Summary` footer). The pipeline ran only one round. Treat every item as a disagreement: cite 2+ codebase locations and give full analytical depth.\n\n Apply these depth and categorization rules:\n\n - **Both rounds agree (weak concurrence)**: 1 codebase citation, 1-2 sentence assessment confirming grounding. Categorize as Confirmed Improvement if grounded; demote to Needs Scrutiny if validation finds problems.\n - **Both rounds agree (strong concurrence)**: 1 codebase citation (may reuse a blockquote citation), 1-2 sentence assessment. Categorize as Confirmed Improvement.\n - **Rounds disagree (refinement or disagreement)**: 2+ codebase citations, 3-4 sentence assessment that explicitly weighs the prior-round position against the second-opinion position. Categorize based on which position the evidence supports. Always include both positions in the Assessment.\n - **Gap captured — two-axis check** (for items in `## New in Second Opinion`):\n - If both the question is grounded in the codebase/standards AND the best-guess answer is sensible → **Confirmed Improvement** with a 1-2 sentence assessment and 1 citation.\n - If the question is genuine but the best-guess answer is flawed → **Needs Scrutiny**. Cite 2+ files. Use disagreement-depth.\n - If the question itself does not hold up → **Needs Scrutiny** with evidence of what the code actually does. Disagreement-depth.\n - If neither codebase nor standards can settle the question → **Open Questions**. Disagreement-depth.\n - **Single round only**: Treat as a disagreement — cite 2+ codebase locations and give full analytical depth.\n\n For critique points (Requested Changes and Points to Consider), apply the same Round Agreement rules. The signal locations are inline `> **Second opinion (<provider>) - ...**` blockquotes nested under items in `### Requested Changes` / `### Points to Consider`, and gap-captured items under `## New in Second Opinion > ### New Requested Changes` / `### New Points to Consider`.\n\n **Depth calibration**:\n - When Round Agreement is `both rounds agree (weak concurrence)`, `both rounds agree (strong concurrence)`, or `gap captured` (passes both axes), keep Assessment to 1-2 sentences and Codebase Evidence to 1 citation — the validation step or the consensus does the heavy lifting.\n - When Round Agreement is `rounds disagree (refinement)`, `rounds disagree (disagreement)`, or `single round only`, Assessment should be 3-4 sentences and Codebase Evidence should cite 2+ files explaining the discrepancy.\n - A `gap captured` item that FAILS the two-axis check uses the disagreement depth, not the gap-captured depth.\n - A `weak concurrence` item that FAILS your validation gets demoted: change Round Agreement to `rounds disagree (single round only)`, expand Assessment to 3-4 sentences, and add a 2nd citation.\n\n **Source field conventions** — the `**Source**` string disambiguates where in the source doc the item lives so the downstream `capture-review-decisions` step can route the rewrite correctly. Use these forms:\n\n - **Weak concurrence (silent prior item)**: `Clarifying Q3 (prior round, weak concurrence)` or `Critique: Requested Change 2 (prior round, weak concurrence)`.\n - **Strong concurrence (explicit blockquote)**: `Clarifying Q9 (prior round, concurrence inline)` or `Critique: Points to Consider 1 (prior round, concurrence inline)`.\n - **Refinement (inline blockquote)**: `Clarifying Q3 (prior round, refinement inline)`.\n - **Disagreement (inline blockquote)**: `Clarifying Q5 (prior round, disagreement inline)`.\n - **Gap captured (tail-block item)**: `Clarifying Q11 (new in second opinion → New Requirements Questions)` or `Critique: Requested Change N+1 (new in second opinion → New Requested Changes)`. Always spell out the sub-section name after the arrow — capture-review-decisions uses it to find the rewrite target.\n - **Single round only**: `Clarifying Q3 (single round)`.\n\n## Phase 1 — Evaluate and classify every item\n\nNumber every item sequentially across all sections (E-1, E-2, E-3, …). When the same underlying issue is raised in BOTH the clarifying-questions doc and the critique doc, consolidate it into a SINGLE E-item rather than emitting one per source, and cite both origins in its `**Source**` field (e.g. `Clarifying Q3 + Critique: Requested Change 2`); keep the numbering sequential with no gaps. Classify every clarifying question and every critique point into exactly one of three buckets using the Round Agreement rules, codebase groundedness checks, and the `gap captured` two-axis check before producing any recommendation decoration:\n\n- **Confirmed Improvements**: Suggestions that are grounded and would genuinely improve the ticket by closing significant gaps or correcting design issues. Includes weak-concurrence items that passed validation, strong-concurrence items, and `gap captured` items that passed both axes.\n- **Needs Scrutiny**: Suggestions based on inaccurate codebase assumptions, with evidence of the actual code behavior. Includes `gap captured` items that failed either axis, weak-concurrence items demoted by validation, and the loser of any rounds-disagree pair.\n- **Open Questions**: Legitimate ambiguities that require human input to resolve.\n\nPhase 1 must complete before Phase 2 begins — do not start decorating an item with a decision tree, recommendation index, or clarity fields until classification is final.\n\n## Phase 2 — Decorate actionable items with resolution guidance\n\nPhase 2 applies **only** to items in the `Needs Scrutiny` and `Open Questions` buckets. Confirmed Improvements remain compact and undecorated (see \"Confirmed Improvements output\" below).\n\nFor every actionable (Needs Scrutiny / Open Questions) item, produce the following template using these stable labels:\n\n```\n### E-<sequential number>: <concise title>\n\n**Source**: <where this item lives in the source doc — see Source field conventions above>\n\n**Round Agreement**: <one of the six values> — <1 sentence on what the second round contributed>\n\n**Confidence**: <High|Medium|Low>\n\n**Resolution path**: <\"resolve at your desk\" or \"needs a conversation\">\n\n**Decision tree**:\n- If <condition 1>, then <action 1>. See `file:line`. <1-2 sentence rationale.>\n- If <condition 2>, then <action 2>. See `file:line`. <1-2 sentence rationale.>\n- If <condition 3>, then <action 3>. See `file:line`. <1-2 sentence rationale.>\n\n**Recommendation Index**: <0-based index of the recommended branch in the decision tree above>\n\n**Recommendation**: <which branch the evidence best supports and why, 1-2 sentences>\n\n**Original question**: <the clarifying-question or critique point as it was originally raised, sourced verbatim or near-verbatim from the original clarifying-questions / critique docs. Light rephrasing is allowed; do NOT introduce new technical content. Soft cap ~30 words.>\n\n**Option consequences**:\n- <consequence for branch 1 — describe the behavioral consequence of choosing this option, not its rationale. ~25 words.>\n- <consequence for branch 2 — same shape. ~25 words.>\n- <consequence for branch 3 — same shape. ~25 words.>\n\n**Why it matters**: <one concrete sentence on the impact this decision has on the ticket, the users, or the affected code paths. Soft cap ~40 words.>\n\n**Recommendation explanation**: <explain why the recommended branch is the best choice, tied to the codebase evidence and the consequences of each option. Soft cap ~60 words.>\n\n**Assessment**: <three-point structure>\n1. **State the original suggestion**: What did the clarifying question or critique point propose?\n2. **State the codebase evidence**: What does the actual code show about this suggestion?\n3. **State the implication**: Does the evidence confirm the suggestion, contradict it, or leave it unresolved?\n\n**Codebase Evidence**:\n- `path/to/file.ts:42` — <what this line/block demonstrates>\n- `path/to/other.ts:110-125` — <what this range demonstrates>\n\n<If no direct codebase evidence exists, state: \"No direct codebase evidence found.\">\n```\n\n**Writing quality**: Write each Assessment as if explaining to a colleague who has NOT read the original clarifying questions or critique documents. Each assessment should be self-contained and understandable without cross-referencing the source material. The three-point Assessment structure ensures every assessment tells a complete story rather than assuming the reader already knows what was suggested and why.\n\n**Decision tree rules**:\n- Each decision tree must have **2–4 branches**. Do not exceed 4 and do not produce only 1.\n- **Strict lower bound — reclassify on single-branch items**: If you can think of only one branch for a `Needs Scrutiny` or `Open Questions` item — that is, the resolution is effectively forced — you must reclassify the item as a **Confirmed Improvement** instead of emitting a single-branch decision tree. The 2-branch lower bound is a hard rule; do not work around it by stretching to a contrived second branch. If a single answer is genuinely the only path, the item belongs in Confirmed Improvements.\n- Each branch must end with a concrete, actionable step (not \"investigate further\").\n- Cite relevant code in `file:line` format where possible. If no code reference exists, omit the citation rather than fabricating one.\n- Cap each branch at 2-3 sentences total (including the action and rationale).\n- `**Recommendation Index**` must be the 0-based index of the recommended branch in the decision tree above. The first branch is index 0, the second is index 1, etc.\n- **Option consequences** must be a list parallel to the decision-tree branches: one entry per branch, in the same order. Describe the behavioral consequence of choosing that option, not its rationale.\n- **\"resolve at your desk\"**: The item can be resolved through technical investigation — reading code, running tests, or checking configuration. No stakeholder input needed.\n- **\"needs a conversation\"**: The item involves a product decision, scope question, or cross-team dependency that cannot be resolved from the codebase alone.\n\n**Confidence Tags** — assign confidence based on codebase evidence strength:\n- **High**: Cite specific `file:line` references that directly support the assessment.\n- **Medium**: Reference related code patterns or architectural conventions, but not the exact code in question.\n- **Low**: No direct codebase evidence. Assessment is based on general reasoning or domain knowledge.\n\n### Confirmed Improvements output\n\nRender each Confirmed Improvement as a single bullet in a compact list. No headings per item, no decision trees, no clarity-field decoration:\n\n- **E-<number>: <title>** — Source: <source string>; Round Agreement: <one of the six values>; Confidence: <High|Medium|Low>. <recommended action, 1 sentence.>\n\nThe compact bullet still includes `Source`, `Round Agreement`, `Confidence`, and the one-sentence recommended action so `capture-review-decisions.md` can map these items to its `clear_improvements` array.\n\n## Round Agreement Summary\n\nAfter all items are processed, produce a summary section that groups items by round agreement status:\n\n### Points of Disagreement\nFor items where the evaluation marked `rounds disagree (refinement)`, `rounds disagree (disagreement)`, or `single round only` — including `gap captured` items that failed the two-axis check and landed in Needs Scrutiny — list as bullets with the E-number, the nature of the disagreement, and a 1-sentence explanation of why this disagreement matters for the ticket (e.g., it indicates an architectural ambiguity, a scope question, or a standards gap).\n\nIf no items were marked as disagreements, write: \"All reviewed points had round consensus. No disagreement-driven risks identified.\"\n\n### Points of Agreement\nSplit this section into two sub-bullets to surface the difference between the second round explicitly reinforcing a point versus tacitly accepting it:\n\n**Strong agreement** — items where the evaluation marked `both rounds agree (strong concurrence)`. The second round took the trouble to write an explicit `concurrence` blockquote; this is a soft signal that the point is important enough that the second round wanted to underline it. List as bullets with the E-number and a half-sentence noting the shared conclusion.\n\n**Weak agreement** — items where the evaluation marked `both rounds agree (weak concurrence)`. The second round did not object and did not consider the item important enough to comment on; the local agent's brief validation found no concerns. List as bullets with the E-number and a half-sentence noting the conclusion. Lower priority for human review than strong-agreement items.\n\nIf a sub-bullet has no items, omit it (rather than writing a \"no items\" note for each — keep the section tidy).\n\n### Gaps Captured by Second Round\nFor items where the evaluation marked `gap captured` (sound second-opinion Additional Points confirmed as Confirmed Improvements): list as bullets with the E-number and a half-sentence noting the gap the second round surfaced. These items did not require a decision — they are already in Confirmed Improvements — but are surfaced here so the reviewer sees what the second-round analysis added on top of the first round.\n\nIf no gaps were captured, write: \"The second round did not surface any net-new confirmed improvements.\"\n\n## Edge Cases\n\n- If the evaluation contains zero items in Needs Scrutiny, write: \"No items flagged for scrutiny. All reviewed suggestions were either confirmed or remain open questions.\"\n- If the evaluation contains zero items in Open Questions, write: \"No open questions identified. All ambiguities were resolved through codebase analysis.\"\n- If both Needs Scrutiny and Open Questions are empty, include only the Confirmed Improvements section and add a summary: \"All suggestions from the review were confirmed as grounded improvements. No decision trees are needed.\"\n- If both source documents are absent, still write the combined file with the standard top-level sections present but no emitted E-items rather than failing.\n\n## Example of a Well-Written E-Item (Weak Concurrence — Confirmed Improvement)\n\n### E-2: Caching of analysis-type lookups\n\n**Source**: Clarifying Q4 (prior round, weak concurrence)\n\n**Round Agreement**: both rounds agree (weak concurrence) — the second round did not comment on this item; brief validation confirms the answer is grounded.\n\n**Assessment**: The prior round suggested caching `ANALYSIS_TYPES` lookups in a module-level variable to avoid repeated DB round trips. The codebase already does this at `src/python/learn_repository/__init__.py:14`, so the suggestion is grounded and the second round's silence is consistent with tacit agreement.\n\n**Codebase Evidence**:\n- `src/python/learn_repository/__init__.py:14` — module-level constant pattern is the established convention\n\n(Confirmed Improvements compact bullet form: **E-2: Caching of analysis-type lookups** — Source: Clarifying Q4 (prior round, weak concurrence); Round Agreement: both rounds agree (weak concurrence); Confidence: High. Confirm the existing module-level cache and add a short comment naming the pattern.)\n\n## Example of a Well-Written E-Item (Strong Concurrence — Confirmed Improvement)\n\n### E-4: Sequential per-type review_repository fan-out\n\n**Source**: Clarifying Technical Q2 (prior round, concurrence inline)\n\n**Round Agreement**: both rounds agree (strong concurrence) — the second round explicitly reinforced the prior recommendation, citing per-type lock release simplicity as the deciding factor.\n\n**Assessment**: The prior round recommended sequential per-type execution; the second-opinion blockquote reinforced this, noting that the per-type lock release contract becomes trivial under sequential execution. `review_repository` already uses internal `asyncio.gather` for chunk-level concurrency, so wrapping it in another concurrency layer would not buy throughput and would complicate the abort/finally cleanup contract.\n\n**Codebase Evidence**:\n- `src/python/learn_repository/review_repository.py:369-387` — review_repository internally gathers chunks with return_exceptions=True\n\n## Example of a Well-Written E-Item (Rounds Disagree — Needs Scrutiny with full clarity fields)\n\n### E-5: Authentication middleware placement for new endpoint\n\n**Source**: Clarifying Q2 (prior round, disagreement inline)\n\n**Round Agreement**: rounds disagree (disagreement) — the prior round recommended adding auth at the router level; the second-opinion blockquote argued the existing middleware stack already covers it.\n\n**Confidence**: High\n\n**Resolution path**: resolve at your desk\n\n**Decision tree**:\n- If the global middleware stack already enforces auth on `/api/*` routes, then drop the explicit `Depends(require_api_key)` from the new endpoint. See `main.py:45-52`.\n- If routers each opt in to auth via dependencies, then add `Depends(require_api_key)` to the new endpoint. See `api/routes/__init__.py:18-30`.\n- If only certain `/api/*` sub-paths need auth, then carve out a sub-router with its own dependency. See `api/routes/__init__.py:18-30`.\n\n**Recommendation Index**: 1\n\n**Recommendation**: The existing routers each opt in to auth, so the new endpoint must do the same. Adding `Depends(require_api_key)` is the smallest correct change.\n\n**Original question**: Should the new `/api/exports` endpoint declare an explicit auth dependency, or is it covered by the global middleware?\n\n**Option consequences**:\n- Endpoint becomes publicly reachable; protected data leaks via the new path.\n- Endpoint requires a valid API key, matching every other `/api/*` route.\n- Adds a parallel router; doubles the auth surface that has to be kept consistent.\n\n**Why it matters**: Authentication on `/api/exports` directly determines whether protected data leaks; the wrong default is a security regression, not a stylistic choice.\n\n**Recommendation explanation**: The codebase pattern in `api/routes/__init__.py:18-30` shows each router declaring its own `Depends(require_api_key)`. Following that convention adds two lines, keeps auth uniform across endpoints, and avoids a parallel sub-router that future maintainers would have to keep in sync.\n\n**Assessment**: The prior round suggested that the new `/api/exports` endpoint needs an explicit `Depends(require_api_key)` guard because it is not covered by the global middleware. The second opinion disagreed, claiming the middleware stack in `main.py` handles authentication for all `/api/*` routes. Codebase analysis shows that `main.py:45-52` applies rate limiting globally but authentication is applied per-router in `api/routes/__init__.py:18-30` — each router must opt in via `Depends(require_api_key)`. This supports the prior round's position: the new endpoint needs an explicit auth dependency.\n\n**Codebase Evidence**:\n- `main.py:45-52` — global middleware applies rate limiting and CORS, but not authentication\n- `api/routes/__init__.py:18-30` — each router includes its own auth dependency; there is no catch-all auth middleware\n\n## Example of a Well-Written E-Item (Gap Captured — Confirmed Improvement)\n\n### E-7: Missing Alembic migration for new role-scope column\n\n**Source**: Critique: Requested Change N+1 (new in second opinion → New Requested Changes)\n\n**Round Agreement**: gap captured — the second opinion surfaced a missing migration that the prior round did not raise, and recommended adding an Alembic revision.\n\n**Assessment**: The ticket introduces a new `role_scope` column on the `users` table but does not mention a migration. The second opinion flagged this gap and recommended adding an Alembic revision; both the gap and the recommendation are grounded, since `db/alembic/versions/` is the established location for schema changes per the project's database guide.\n\n**Codebase Evidence**:\n- `db/alembic/versions/` — all schema changes land here as autogenerated revisions\n\n## Save rule\n\nSave the combined review-and-resolution document to `{docs_dir}/review/{ticket_key}-review-and-resolution.md`. Output only the combined review-and-resolution document — no meta-commentary.\n\n## Return\n\nConfirm \"Review-and-resolution document written to `{docs_dir}/review/{ticket_key}-review-and-resolution.md`.\" and report the total count of E-items captured.\n",
|
|
705
705
|
"execute-epic-research.md": "Execute the research plan and write findings.\n\n## Instructions\n\n1. Read the research plan from `{docs_dir}/epic-plans/{epic_slug}/research-plan.md`.\n\n2. Execute the plan based on the Research Mode:\n\n **If mode is `deep`**:\n - Call the `request_deep_research` MCP tool with:\n - `query`: the Deep Research Query from the plan\n - `context`: \"Bridge API is a Python/FastAPI application with PostgreSQL, LiteLLM, and Pinecone. This research supports epic planning for: {epic_description}\"\n - `wait_for_result`: true\n - `save_locally`: true\n - If deep research fails, log a warning and fall back to web searches using the Web Search Topics from the plan. Do NOT halt.\n\n **If mode is `web`**:\n - Perform web searches for each topic listed in the plan.\n - Capture relevant findings from each search.\n\n **If mode is `none`**:\n - Write a brief note: \"No external research needed. Proceeding with codebase exploration.\"\n\n3. Write all findings to `{docs_dir}/epic-plans/{epic_slug}/research-findings.md` with this structure:\n\n```markdown\n# Research Findings\n\n## Mode\n{deep | web | none}\n\n## Findings\n{Synthesized research results organized by topic. Include source references where applicable.}\n\n## Key Takeaways\n{Bullet points summarizing the most important findings that will inform the codebase exploration and epic decomposition.}\n```\n\n## Return\n\nConfirm research findings were written to `{docs_dir}/epic-plans/{epic_slug}/research-findings.md` and report the mode used (`deep`, `web`, or `none`) plus a one-line summary of the key takeaways.\n",
|
|
706
|
-
"execute-plan-verification.md": "Execute the remaining plan steps for ticket {ticket_key} — faithfully — before the pull request opens.\n\nThe production phase authored the artifacts and the checkpoint pushed them to origin.\nThis phase runs everything else the plan asked for: its review steps, its\ntest-execution steps, and — when the plan authored one — its rendered-UI remediation\nloop.\n\n**This phase runs the plan as written.** It has no fixed depth and no cost-based\nnarrowing rule. If the plan says to grep for every call site of a changed signature,\ngrep for every call site. If it supplies a test command, run that command. A step is\nnot narrowed, substituted, or dropped because it is expensive or slow — that judgment\nis what removed a whole class of plan steps from execution in the first place.\n\nRunning before the pull request is deliberate. The remediation loop *changes code*.\nRunning it after the PR opened would guarantee the PR's first head carried the\nun-iterated first draft, and would pay `claude-review` plus `conductor-ci` on every\none of up to three cycles. The work is durable on origin throughout; it is simply not\nexternally visible until the PR opens a moment later.\n\n---\n\n## Step 1 — Confirm the Checkpoint Is Durable\n\nBefore starting any long-running work:\n\n1. Run `git rev-parse --abbrev-ref HEAD` and `git rev-parse HEAD`.\n2. Confirm the checkpoint SHA
|
|
707
|
-
"execute-plan.md": "Execute the production obligations of the AI-generated implementation plan for ticket {ticket_key}.\n\nThis is the **production phase**. It authors artifacts. It is followed immediately by\na deterministic checkpoint (`checkpoint-work.md`) that commits and pushes everything\nproduced here, and then by the pre-PR verification phase\n(`execute-plan-verification.md`) that runs the plan's remaining steps.\n\nThe phase boundary is about *what kind of work* each phase does, not about postponing\ninconvenient work. This phase writes code, tests, migrations, fixtures, and\nconfiguration. It does not run the plan's review steps, its test-execution steps, or\nits rendered-UI remediation loop — those belong to the pre-PR verification phase,\nwhich owns them explicitly and will execute them. They are routed, not deferred:\nevery step in the plan is assigned to a phase, and the phase that owns a step is\nrequired to settle it.\n\n---\n\n## Step 1 — Retrieve the Plan and Your Routing\n\n1. Call the `get_plan` tool for `{ticket_key}` with `include_metadata` set to `true`\n to retrieve the plan body and its provenance metadata.\n2. Derive the total number of steps from the returned plan.\n3. Read the **Routed phase context** block appended to this instruction by\n orchestration. It carries `ownedSteps` — the exact step IDs this phase must\n settle — and `ledger`, the durable record of work already completed. Determine\n your owned set from that block.\n4. Announce: **\"Plan contains N steps. This phase owns M of them.\"**\n\nIf the routed context is absent or reports `plan_metadata_status` other than `ok`,\nsay so plainly and treat every step as production-relevant. Do **not** infer ownership\nby keyword-matching the plan prose; guessing ownership from prose is what let an\nentire class of steps go unexecuted.\n\nThe local file at `{docs_dir}/plans/{ticket_key}-plan.md` is a saved copy of the same\nplan and may be used as a reference.\n\n## Step 2 — Re-entry Check\n\nA retry after a checkpoint re-enters this phase against a worktree that may already\ncontain the produced work. Before executing anything:\n\n1. Run `git status --porcelain` and `git rev-parse HEAD`.\n2. If the durable ledger already records a step as `executed` or `adapted`, that work\n is done. Do not redo it and do not apply it a second time.\n3. If the ledger is empty but the worktree or the current HEAD already contains the\n artifacts a step calls for, verify the existing artifact is equivalent to what the\n step asks for and record the step as `executed`, noting that it was already\n present. Creating it again risks duplicating or clobbering it.\n\nRe-entry is normal — recovery runs (`ci_fix`, `remediate`, `rebase`) re-enter this\nrecipe from step 1 and reuse the existing plan. Treat an already-satisfied step as\nsatisfied, not as a reason to start over.\n\n## Step 3 — Execute Each Owned Production Step in Order\n\nFor each step in the plan, in strict plan order:\n\n1. **Announce** before starting: **\"Step X of N: <step title from plan>\"**\n2. **Execute** its production work, making the code changes it directs.\n3. **Confirm** after completing: **\"Step X complete — <brief summary>.\"**\n\n### Rules\n\n- **Produce every implementation artifact the plan asks for.** Production code,\n test code, database migrations, generated-source inputs, fixtures, and\n configuration files are all authored in this phase. A step that creates a test file is production\n work and must be completed here — only the *execution* of that test belongs to the\n next phase.\n- **Leave verification actions inside later ranges alone.** Steps you do not own are\n executed by the phase that owns them, which runs before the pull request opens. Do\n not run them here, and do not treat them as skipped.\n- Preserve strict plan order and sequential order within a step. Do not reorder or\n combine steps.\n- **This phase has no commit or push authority of its own.** `checkpoint-work.md` runs\n immediately after it and owns `git commit` and `git push` for the work produced\n here. Do not commit or push ad hoc — a deterministic step owns that boundary\n precisely so the durability guarantee does not depend on prose.\n- Lightweight commands needed to *perform* a change are fine — listing or reading\n files, searching the codebase, inspecting git state, running a code generator whose\n output a later edit consumes.\n- Do not create the pull request. `create-pr.md` owns that.\n\n### When a step's premise is false\n\nA plan step sometimes cites something that is not there. Generated plans routinely\nreference `docs/tmp/` files that are absent from a worktree, because those paths are\ngitignored. That is a **discovery case**, not a failure: locate the equivalent\nmaterial, or proceed without it, and record a locator adaptation.\n\nYou may adapt **mechanically**, and only in these three ways:\n\n- **locator-correction** — the step names a path, file, symbol, or selector that has\n moved or does not exist, and you use the correct one.\n- **repository-command-correction** — the step names a command that is not this\n repository's actual command, and you use the real one.\n- **equivalent-implementation-recognized** — the change the step asks for already\n exists in an equivalent form.\n\nAnything touching **design, schema, public API, dependencies, or security escalates.**\nThose are not corrections to how a step is addressed; they are changes to what it\nasks for, and that decision is not yours to make silently.\n\nRecord every adaptation with the original premise, the correction made, and a one-line\nrationale. **Never silently skip a step.** A step you cannot execute is `escalated`\nwith a reason — a step that vanishes without a record is the exact defect this\nprotocol exists to remove.\n\nIf a requirement is ambiguous because the plan lacks ticket detail, call the\n`get_ticket` tool with `ticket_number` set to `{ticket_key}`, use only the fields\nrelevant to the unresolved requirement, and continue. Do not call `get_ticket`\nunconditionally — `get_plan` in Step 1 remains the sole unconditional context\nretrieval.\n\n## Step 4 — Final Audit\n\n1. Re-enumerate every step you own from the routed context.\n2. Confirm each one has a terminal disposition: `executed`, `adapted`, `escalated`, or\n `unrun-advisory` (the last only when the plan itself declares that range advisory).\n3. Announce: **\"Audit complete — M of M owned steps settled.\"**\n\n## Return\n\nReport production coverage: which owned steps were executed, which were mechanically\nadapted and how, and which were escalated and why.\n\nThen end your result with the machine-readable phase-result envelope, in a fenced\nblock tagged `bapi-phase-result`. Orchestration parses this block, validates it\nagainst the steps you own, and persists it as durable state that survives an approval\npause and a resumed session. A step you owned but did not report will be rejected.\n\n```bapi-phase-result\n{\"version\":1,\"phase\":\"produce\",\"records\":[{\"stepId\":1,\"provenanceClass\":\"implementation\",\"disposition\":\"executed\",\"evidence\":\"created src/foo.py and its migration\"}]}\n```\n",
|
|
706
|
+
"execute-plan-verification.md": "Execute the remaining plan steps for ticket {ticket_key} — faithfully — before the pull request opens.\n\nThe production phase authored the artifacts and the checkpoint pushed them to origin.\nThis phase runs everything else the plan asked for: its review steps, its\ntest-execution steps, and — when the plan authored one — its rendered-UI remediation\nloop.\n\n**This phase runs the plan as written.** It has no fixed depth and no cost-based\nnarrowing rule. If the plan says to grep for every call site of a changed signature,\ngrep for every call site. If it supplies a test command, run that command. A step is\nnot narrowed, substituted, or dropped because it is expensive or slow — that judgment\nis what removed a whole class of plan steps from execution in the first place.\n\nRunning before the pull request is deliberate. The remediation loop *changes code*.\nRunning it after the PR opened would guarantee the PR's first head carried the\nun-iterated first draft, and would pay `claude-review` plus `conductor-ci` on every\none of up to three cycles. The work is durable on origin throughout; it is simply not\nexternally visible until the PR opens a moment later.\n\n**Tool and scope boundary.** Use only the tools this recipe names, the repo's own tooling, and MCP\ncapabilities provisioned for this repository. Keep all work confined to this worktree unless\nexplicitly told to do otherwise.\n\n**Execution mode for this run: `{execution_mode}`.** Under `orchestrated`\n(`run_pipeline` / `resume_pipeline`) orchestration appends the routed phase context and\nparses the fenced result envelope you return. Under `inline` (`get_pipeline_recipe`)\nthere is no orchestrator: you obtain routing and the prior ledger with a tool call, and\nyou record your result with one. Follow the branch that matches wherever the two are\nnamed.\n\n---\n\n## Step 1 — Confirm the Checkpoint Is Durable\n\nBefore starting any long-running work:\n\n1. Run `git rev-parse --abbrev-ref HEAD` and `git rev-parse HEAD`.\n2. Confirm the checkpoint SHA recorded by `checkpoint-work.md` is present on origin —\n `git ls-remote --heads origin <branch>`. The recorded checkpoint comes from the\n routed context's `checkpoint` block when **orchestrated**, and from the `checkpoint`\n field `get_phase_context` returns in Step 2 when **inline**.\n\nIf the branch is not on origin, or HEAD and the recorded checkpoint disagree, **stop and report it**. This phase is long; entering it without recoverable work reintroduces\nthe failure the checkpoint exists to prevent.\n\n## Step 2 — Determine What You Own\n\n1. Call `get_plan` for `{ticket_key}` to retrieve the plan body.\n2. Obtain your routing and the prior ledger, by mode:\n - **orchestrated** — read the **Routed phase context** block appended to this\n instruction. `ownedSteps` lists the exact step IDs this phase must settle;\n `ledger` carries what earlier phases already recorded.\n - **inline** — call `get_phase_context` with `ticket_key` `{ticket_key}` and\n `phase` `pre_pr_verification`. It returns `ownedSteps`, the merged `ledger`,\n `terminalStepIds`, and the durable `checkpoint` Step 1 needs.\n3. Do not re-run a step the ledger already records as `executed` or `adapted` unless a\n correction since then invalidated its evidence. Settle such a step in your phase\n result anyway, with evidence naming the prior record — every owned step must be\n reported, and one you correctly skipped is settled, not missing.\n4. Name the routing source you used when you report, either the routed phase context\n or the `routingSource` value the tool returned.\n\nIf `get_phase_context` reports an error, or the routed context is absent or its\nmetadata status is not `ok`, say so plainly and execute every remaining review,\ntest-execution, and rendered-UI step in the plan. When routing is unavailable here the\nsafe failure is to run more, not less — this phase only verifies, so over-running costs\ntime, while under-running ships unverified work.\n\n## Step 3 — Execute in Plan Order\n\nWork through your owned steps in their original plan order — review steps,\nplan-authored test commands, static searches, architecture-conformance checks, runtime checks,\nand rendered-UI remediation.\n\nRun each command the plan supplies, as the plan supplies it.\n\n### Mechanical adaptation, and its boundary\n\nYou may correct a step **mechanically**, in exactly three ways:\n\n- **locator-correction** — a cited path, file, symbol, or selector has moved or is\n absent (a `docs/tmp/` citation missing from the worktree is the common case, since\n those paths are gitignored). Use the correct locator, or proceed without the\n material, and record it.\n- **repository-command-correction** — the step names a command that is not this\n repository's actual command. Use the real one.\n- **equivalent-implementation-recognized** — what the step asks for already exists in\n equivalent form.\n\n**Escalate** anything involving design, schema, public API, dependencies, or security.\nThose change what the step asks for rather than how it is addressed.\n\nA capability the environment genuinely cannot provide, and a check that genuinely\nrequires an open pull request, are handed forward to the post-PR gap-closing phase as\n`escalated` with that reason recorded. Everything else is executed here.\n\n**Never silently skip a step.** Every owned step ends as `executed`, `adapted`,\n`escalated`, or `unrun-advisory` — the last only when the plan itself declared that range advisory.\n\n## Step 4 — Rendered-UI Remediation\n\nWhen the plan authored a rendered-UI loop, run it as written:\n\n1. Render the actual implementation.\n2. Score every dimension of the plan's fixed rubric, recording the completed table —\n dimension, score, one-sentence reason, and fix attempted — for that cycle.\n3. Apply the accepted fixes.\n4. Stop as soon as the plan's threshold is met; otherwise repeat, to the plan's\n three-cycle cap.\n5. If the cap is reached with dimensions still below threshold, record the final\n scores and the unresolved defects as an **escalation**. Do not claim acceptance.\n\nThe rubric table and the accepted fixes are the evidence that the loop ran. Carry them\nin this step's record.\n\n## Step 5 — Publish Every Material Change Immediately\n\nAfter each material code change:\n\n1. Stage the specific files, commit, and **push immediately**. The commit and its push\n are one consecutive sequence, never separated by another check. An unpushed\n correction is invisible to the pull request, to CI, and to the reconciler.\n2. Run `git rev-parse HEAD` and record the new pushed SHA.\n\nThen continue with the next verification action. Do not batch several cycles of\nchanges behind a single push — the point of pushing immediately is that the next\nlong-running action cannot strand them.\n\n## Step 6 — Report Honestly\n\nRecord the exact command run, its observed result, and on failure the relevant detail:\nfailing test names, error output, diagnostic lines. Report all of it, including\nfailures you did not fix.\n\n**Do not issue a gate verdict.** Do not write that CI passed, that the gate is met, or\nthat the review is approved. Those states are decided by the `ci` and `code_review`\ngates and observed by the reconciler, never asserted by this phase. Worker\nself-verification has reported green while the full suite was red; that is why the\ngates decide and this phase only observes.\n\n## Return\n\nReport the branch, the latest pushed SHA, every command run with its observed outcome,\nevery correction commit pushed, and every unresolved finding.\n\nThen record the machine-readable phase result, by mode.\n\n### orchestrated\n\nEnd your result with the envelope in a fenced block tagged `bapi-phase-result`.\nOrchestration validates it against the steps you own and persists it as durable state;\nan owned step you do not report will be rejected.\n\n```bapi-phase-result\n{\"version\":1,\"phase\":\"pre_pr_verification\",\"lastCommitSha\":\"<sha>\",\"records\":[{\"stepId\":12,\"provenanceClass\":\"final_plan_review\",\"disposition\":\"executed\",\"evidence\":\"grepped all call sites of changed signature; 4 found, all updated\"}]}\n```\n\n### inline\n\nCall the `record_phase_result` tool with `ticket_key` `{ticket_key}` and\n`phase_result` set to that same envelope object. The tool validates it against the\nsteps you own and persists it to the durable ledger; an owned step you do not report\nis rejected there. **Do not also emit a fenced `bapi-phase-result` block** — nothing\nparses one on this path.\n\nThe tool call is this phase's final action, **not the end of your turn.** When it\nreturns successfully, continue immediately with the next recipe step —\n`commit-and-push.md`, then the pull request. Stopping here leaves verified work with no\npull request, which is how an earlier run stranded four pushed correction commits.\n\nIf the call fails, fix what it reports and call it again.\n",
|
|
707
|
+
"execute-plan.md": "Execute the production obligations of the AI-generated implementation plan for ticket {ticket_key}.\n\nThis is the **production phase**. It authors artifacts. It is followed immediately by\na deterministic checkpoint (`checkpoint-work.md`) that commits and pushes everything\nproduced here, and then by the pre-PR verification phase\n(`execute-plan-verification.md`) that runs the plan's remaining steps.\n\nThe phase boundary is about *what kind of work* each phase does, not about postponing\ninconvenient work. This phase writes code, tests, migrations, fixtures, and\nconfiguration. It does not run the plan's review steps, its test-execution steps, or\nits rendered-UI remediation loop — those belong to the pre-PR verification phase,\nwhich owns them explicitly and will execute them. They are routed, not deferred:\nevery step in the plan is assigned to a phase, and the phase that owns a step is\nrequired to settle it.\n\n**Tool and scope boundary.** Use only the tools this recipe names, the repo's own tooling, and MCP\ncapabilities provisioned for this repository. Keep all work confined to this worktree unless\nexplicitly told to do otherwise.\n\n**Execution mode for this run: `{execution_mode}`.** Two executors run this file and\nthey differ in exactly one respect — who keeps the durable record:\n\n- `orchestrated` — `run_pipeline` / `resume_pipeline` drive the recipe. Orchestration\n appends the routed phase context below, and it parses, validates, and persists the\n fenced result envelope you return.\n- `inline` — `get_pipeline_recipe` returned the recipe and you are executing every\n step yourself. **No orchestrator is watching.** Nothing appends routed context and\n nothing reads a returned envelope. You derive your own routing and record your own\n result, both through tool calls, and then you keep going to the next recipe step.\n\nFollow the branch that matches the mode above wherever the two are named.\n\n---\n\n## Step 1 — Retrieve the Plan and Your Routing\n\n1. Call the `get_plan` tool for `{ticket_key}` to retrieve the plan body.\n2. Derive the total number of steps from the returned plan.\n3. Determine your owned set, by mode:\n - **orchestrated** — read the **Routed phase context** block appended to this\n instruction. It carries `ownedSteps` — the exact step IDs this phase must\n settle — and `ledger`, the durable record of work already completed.\n - **inline** — call the `get_phase_context` tool with `ticket_key`\n `{ticket_key}` and `phase` `produce`. It returns the same `ownedSteps`,\n `ownedRanges`, and `ledger`, derived server-side from the plan's provenance\n metadata by the same code the orchestrator uses.\n4. Announce: **\"Plan contains N steps. This phase owns M of them.\"** — and name the\n routing source you used, either the routed phase context or the `routingSource`\n value `get_phase_context` returned. Silence about the source is what made an\n earlier run's ownership claim unauditable.\n\nIf `get_phase_context` reports an error, or the routed context is absent or reports\n`plan_metadata_status` other than `ok`, **stop before making any production change**\nand report the reason. Do **not** infer ownership by keyword-matching the plan prose;\nguessing ownership from prose is what let an entire class of steps go unexecuted, and\nproducing artifacts against a routing you cannot verify is worse than producing none.\n\nThe local file at `{docs_dir}/plans/{ticket_key}-plan.md` is a saved copy of the same\nplan and may be used as a reference.\n\n## Step 2 — Re-entry Check\n\nA retry after a checkpoint re-enters this phase against a worktree that may already\ncontain the produced work. Before executing anything:\n\n1. Run `git status --porcelain` and `git rev-parse HEAD`.\n2. If the durable ledger already records a step as `executed` or `adapted`, that work\n is done. Do not redo it and do not apply it a second time. Inline, that ledger is\n the `ledger` / `terminalStepIds` `get_phase_context` returned; orchestrated, it is\n the `ledger` in the routed context. Report such a step as `executed` again in your\n phase result, with evidence naming the prior record — the phase result must settle\n every owned step, and a step you skipped because it was already done is settled,\n not missing.\n3. If the ledger is empty but the worktree or the current HEAD already contains the\n artifacts a step calls for, verify the existing artifact is equivalent to what the\n step asks for and record the step as `executed`, noting that it was already\n present. Creating it again risks duplicating or clobbering it.\n\nRe-entry is normal — recovery runs (`ci_fix`, `remediate`, `rebase`) re-enter this\nrecipe from step 1 and reuse the existing plan. Treat an already-satisfied step as\nsatisfied, not as a reason to start over.\n\n## Step 3 — Execute Each Owned Production Step in Order\n\nFor each step in the plan, in strict plan order:\n\n1. **Announce** before starting: **\"Step X of N: <step title from plan>\"**\n2. **Execute** its production work, making the code changes it directs.\n3. **Confirm** after completing: **\"Step X complete — <brief summary>.\"**\n\n### Rules\n\n- **Produce every implementation artifact the plan asks for.** Production code,\n test code, database migrations, generated-source inputs, fixtures, and\n configuration files are all authored in this phase. A step that creates a test file is production\n work and must be completed here — only the *execution* of that test belongs to the\n next phase.\n- **Leave verification actions inside later ranges alone.** Steps you do not own are\n executed by the phase that owns them, which runs before the pull request opens. Do\n not run them here, and do not treat them as skipped.\n- Preserve strict plan order and sequential order within a step. Do not reorder or\n combine steps.\n- **This phase has no commit or push authority of its own.** `checkpoint-work.md` runs\n immediately after it and owns `git commit` and `git push` for the work produced\n here. Do not commit or push ad hoc — a deterministic step owns that boundary\n precisely so the durability guarantee does not depend on prose.\n- Lightweight commands needed to *perform* a change are fine — listing or reading\n files, searching the codebase, inspecting git state, running a code generator whose\n output a later edit consumes.\n- Do not create the pull request. `create-pr.md` owns that.\n\n### When a step's premise is false\n\nA plan step sometimes cites something that is not there. Generated plans routinely\nreference `docs/tmp/` files that are absent from a worktree, because those paths are\ngitignored. That is a **discovery case**, not a failure: locate the equivalent\nmaterial, or proceed without it, and record a locator adaptation.\n\nYou may adapt **mechanically**, and only in these three ways:\n\n- **locator-correction** — the step names a path, file, symbol, or selector that has\n moved or does not exist, and you use the correct one.\n- **repository-command-correction** — the step names a command that is not this\n repository's actual command, and you use the real one.\n- **equivalent-implementation-recognized** — the change the step asks for already\n exists in an equivalent form.\n\nAnything touching **design, schema, public API, dependencies, or security escalates.**\nThose are not corrections to how a step is addressed; they are changes to what it\nasks for, and that decision is not yours to make silently.\n\nRecord every adaptation with the original premise, the correction made, and a one-line\nrationale. **Never silently skip a step.** A step you cannot execute is `escalated`\nwith a reason — a step that vanishes without a record is the exact defect this\nprotocol exists to remove.\n\nIf a requirement is ambiguous because the plan lacks ticket detail, call the\n`get_ticket` tool with `ticket_number` set to `{ticket_key}`, use only the fields\nrelevant to the unresolved requirement, and continue. Do not call `get_ticket`\nunconditionally — `get_plan` in Step 1 remains the sole unconditional context\nretrieval.\n\n## Step 4 — Final Audit\n\n1. Re-enumerate every step you own from the routed context.\n2. Confirm each one has a terminal disposition: `executed`, `adapted`, `escalated`, or\n `unrun-advisory` (the last only when the plan itself declares that range advisory).\n3. Announce: **\"Audit complete — M of M owned steps settled.\"**\n\n## Return\n\nReport production coverage: which owned steps were executed, which were mechanically\nadapted and how, and which were escalated and why.\n\nThen record the machine-readable phase result. **How you record it depends on the\nmode**, and the difference is not cosmetic — it is the difference between a durable\nrecord and a message to nobody.\n\n### orchestrated\n\nEnd your result with the envelope in a fenced block tagged `bapi-phase-result`.\nOrchestration parses this block, validates it against the steps you own, and persists\nit as durable state that survives an approval pause and a resumed session. A step you\nowned but did not report will be rejected.\n\n```bapi-phase-result\n{\"version\":1,\"phase\":\"produce\",\"records\":[{\"stepId\":1,\"provenanceClass\":\"implementation\",\"disposition\":\"executed\",\"evidence\":\"created src/foo.py and its migration\"}]}\n```\n\n### inline\n\nCall the `record_phase_result` tool with `ticket_key` `{ticket_key}` and\n`phase_result` set to that same envelope object. The tool validates it against the\nsteps you own and persists it to the durable ledger; a step you owned but did not\nreport is rejected there, and an owned step left unsettled fails the call rather than\ndisappearing. **Do not also emit a fenced `bapi-phase-result` block** — inline there is\nno orchestration to parse one, and a text envelope addressed to nobody is exactly what\nused to end the turn here.\n\nThe tool call is this phase's final action. **It is not the end of your turn.** When it\nreturns successfully the produce phase is complete and the *next recipe step* —\n`checkpoint-work.md`, which pushes everything you just produced — begins immediately.\nContinue to it in the same turn. Stopping here strands the work you just authored in an\nuncommitted worktree, which is the single most damaging way this pipeline has failed.\n\nIf the call fails, fix what it reports and call it again. Do not proceed past a failed\nrecording: an unrecorded phase result means the next phase reads an empty ledger and\nredoes work you already did.\n",
|
|
708
708
|
"execute-research.md": "Execute the research plan and produce a consolidated research pack.\n\n## Inputs\n\n- Research plan: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-plan.json`.\n- Run manifest: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/run-manifest.json`.\n\n## Instructions\n\n1. Read `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-plan.json`. Execute only the tools listed in `selected_tools`. Do not invoke any tool that is not in that list.\n\n2. For each selected tool:\n - **codebase_search**: search the local working tree using the listed `codebase_search_topics`. Capture file paths, function names, and short excerpts as evidence.\n - **web_search**: run narrow, targeted searches for each item in `web_search_topics`. Capture the source URL and a short summary for each result.\n - **deep_research**: run the deep research query exactly once with the planned `deep_research_query`. Capture the consolidated answer plus the cited URLs.\n\n3. Tool failures must be recorded, not silently dropped:\n - If a tool returns an error, missing-credential message, or empty result, record the failure under `per_tool_failures` in the research pack and continue with the remaining tools.\n - A partial research pack is preferable to no research pack. Do not halt the pipeline because one tool failed.\n\n4. Write two artifacts to the run directory:\n - `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-pack.md` — a human-readable consolidated brief. It must include these sections:\n - **Evidence table** — a structured list of evidence rows: claim, source (file path / URL), and tool that produced it. Render as a bulleted list, not a markdown table (BAPI-320 hygiene).\n - **Codebase references** — file paths and function names worth citing in the ticket.\n - **External references** — only present when web/deep search ran; URL + short summary per item.\n - **Unresolved unknowns** — questions the research could not answer.\n - **Per-tool failures** — any tool that failed, with the failure reason.\n - `{docs_dir}/idea-to-ticket/{slug}-{run_id}/research-pack.json` — machine-readable counterpart with the same evidence rows, references, unresolved unknowns, and per-tool failures arrays.\n\n5. Mark research failures as warnings in `research-pack.json` so downstream steps can branch on them: include `partial: true` when any selected tool failed.\n\n## Return\n\nConfirm `research-pack.md` and `research-pack.json` were written, and list any tools that failed.\n",
|
|
709
709
|
"explore-epic-codebase.md": "Perform a holistic, epic-level codebase exploration.\n\n## Epic Description\n\n{epic_description}\n\n## Instructions\n\n1. Read the research findings from `{docs_dir}/epic-plans/{epic_slug}/research-findings.md` to establish context. If the file does not exist or is empty, proceed without it.\n\n2. Explore the codebase with a focus on breadth rather than depth. The goal is to build a \"lay of the land\" understanding for the entire epic, not to deeply analyze any single sub-task. Search by filename pattern, search file contents by text pattern, and read relevant files to find:\n - Files, modules, and directories relevant to the epic\n - Architectural patterns used in similar features\n - Integration points and dependencies between modules\n - Existing conventions for the type of work this epic involves\n - Database models, API routes, agent flows, and utilities that may be affected\n\n3. Build a mental model of:\n - What exists today that relates to the epic\n - What patterns and conventions are used in similar features\n - What dependencies, data flows, and integration points are involved\n - What areas of the codebase will likely need changes\n\n4. Write the exploration findings to `{docs_dir}/epic-plans/{epic_slug}/codebase-exploration.md` with this structure:\n\n```markdown\n# Codebase Exploration\n\n## Architecture Overview\n{High-level description of how the relevant parts of the codebase are structured.}\n\n## Relevant Code Areas\n{List of key files, modules, and directories with brief descriptions of their relevance to the epic.}\n\n## Existing Patterns\n{Patterns and conventions discovered that should be followed when implementing the epic.}\n\n## Integration Points\n{Dependencies, data flows, and integration points that the epic will need to account for.}\n\n## Potential Challenges\n{Any architectural constraints, technical debt, or complexity that could affect implementation.}\n```\n\n## Return\n\nConfirm the codebase exploration was written to `{docs_dir}/epic-plans/{epic_slug}/codebase-exploration.md` and return a concise summary of the discovered codebase areas, naming the key files and patterns relevant to the epic.\n",
|
|
710
710
|
"explore-epic-subtasks.md": "Perform focused code explorations for each approved sub-task.\n\n## Instructions\n\n1. Read the approved decomposition from `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md`.\n\n2. Create the explorations directory:\n ```\n mkdir -p {docs_dir}/epic-plans/{epic_slug}/explorations/\n ```\n\n3. For each sub-task in the decomposition, perform a focused exploration:\n - Search for specific files and patterns relevant to the sub-task\n - Identify implementation options and tradeoffs\n - Reference the holistic codebase exploration (`{docs_dir}/epic-plans/{epic_slug}/codebase-exploration.md`) and research findings (`{docs_dir}/epic-plans/{epic_slug}/research-findings.md`) for context\n - Default to lightweight exploration — only go deeper when the holistic exploration left significant gaps for a specific sub-task\n\n4. Write an exploration document for each sub-task to `{docs_dir}/epic-plans/{epic_slug}/explorations/NN-{subtask-slug}.md` (using zero-padded numbering, e.g., `01-add-pipeline-json.md`, `02-create-instruction-files.md`).\n\n5. Each exploration document MUST include these exactly named sections:\n\n```markdown\n# {Sub-task title}\n\n## Context\n{Brief description of the sub-task scope and its role within the epic.}\n\n## Relevant Code\n{Specific files, functions, and patterns relevant to this sub-task. Reference with file_path:line_number format.}\n\n## Implementation Options\n{Viable approaches for implementing the sub-task. For each option: description, pros, cons.}\n\n## Recommendation\n{Which option to pursue and why. Include any caveats or risks.}\n```\n\n6. **Word count guidance**: Target 300-500 words per document. Keep the exploration lightweight. Only exceed this limit if the holistic codebase exploration left significant gaps for a specific sub-task.\n\n## Return\n\nConfirm one exploration document was written per sub-task under `{docs_dir}/epic-plans/{epic_slug}/explorations/` and return a concise summary of the discovered code areas and recommended approaches across the sub-tasks.\n",
|
|
@@ -732,6 +732,6 @@ export const INSTRUCTIONS = {
|
|
|
732
732
|
"update-ticket-rewrite.md": "Rewrite the Jira ticket description for {ticket_key} using the generated clarifying questions and critique documents.\n\n1. Fetch the current ticket description using the `get_ticket` tool with ticket_number `{ticket_key}`.\n2. Read the clarifying questions from the local file saved by the previous step (check `{docs_dir}/clarifying-questions/` for `{ticket_key}-clarifying-questions.md`). For each best-guess answer, verify it against the codebase using file search and code grep. Accept verified answers, correct inaccurate ones with evidence, and let ambiguous ones stand.\n3. Read the critique from the local file saved by the previous step (check `{docs_dir}/ticket-critiques/` for `{ticket_key}-ticket-quality-critique.md`). Address all Requested Changes. Apply Points to Consider selectively — accept genuine improvements, skip stylistic preferences.\n4. Write the rewritten ticket in standard markdown format (not Jira wiki markup). Preserve the Summary, Requirements, and Acceptance Criteria structure.\n5. Save the output to `{docs_dir}/tickets/{ticket_key}.md`. Output only the clean rewritten ticket — no meta-commentary.\n\n## Return\n\nConfirm the rewritten ticket was saved to `{docs_dir}/tickets/{ticket_key}.md` and briefly note which clarifying-question answers were corrected against the codebase and which critique Requested Changes were addressed.\n",
|
|
733
733
|
"upload-and-track.md": "Step-10 umbrella upload instruction. Idempotently create the Jira ticket(s) for this run, attach the full draft(s), and call `track_ticket`.\n\n## Inputs\n\n- Run manifest: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/run-manifest.json`.\n- Draft metadata: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/draft-metadata.json`.\n- For epic runs, this instruction is also responsible for producing or refreshing `{docs_dir}/idea-to-ticket/{slug}-{run_id}/decomposition-plan.json` before any Jira mutation, by following `decompose-epic-candidate.md` (hard cap `{max_children}`).\n- Pipeline variable `auto_approve_external` controls whether the external-mutation pause is skipped (for this run, `auto_approve_external` = `{auto_approve_external}`). Treat the literal string `\"true\"` as skip; any other value (including `\"false\"`, missing, or empty) means pause and ask.\n\n## Instructions\n\n> **Orchestrator-directed step.** This agent task is part of the full-automation chain and is authorized to call `get_tickets`, `create_ticket`, `attachment` (operations: `upload`, `list`), `update_ticket_description`, `track_ticket`, and `add_comment`, and to execute the shared `gather-and-attach-materials.md` instruction, as directed below — performing orchestrator-directed tool calls is not \"re-orchestrating\".\n\n1. Read `run-manifest.json` and `draft-metadata.json`. Branch internally based on the manifest's `scope`:\n - `task` or `spike` → follow the **Single-ticket path** below.\n - `epic_candidate` → follow the **Epic path** below.\n The orchestrator does not support conditional steps; this branching lives in agent logic.\n\n2. External approval gate, applied before any mutating MCP tool call:\n - If `auto_approve_external` is `\"false\"` (or any non-`\"true\"` value), summarize the exact planned Jira mutations — list every `create_ticket`, `attachment` (operation: `\"upload\"`), and `track_ticket` call with its key arguments — and ask the user for explicit confirmation in this agent task before proceeding.\n - If `auto_approve_external` is `\"true\"`, proceed without the confirmation pause.\n\n3. **Single-ticket path** (`scope` is `task` or `spike`):\n 1. Idempotency lookup. Call `get_tickets` with its `labels` parameter set to both the per-run label `<idempotency_label>` and the stable `bapi-idea-hash-{idea_hash}` label from `draft-metadata.json` (comma-separated). If a match is found by either label, reuse that ticket key and skip `create_ticket`.\n 2. If no match was found, call `create_ticket` with `summary`, `slim_description` as the description, `issue_type`, and `labels` exactly as written in the metadata. Capture the returned `ticket_key`.\n 3. Upload the full markdown draft via `attachment` (operation: `\"upload\"`) using `attachment_path`.\n 4. **Gather and attach referenced materials.** Execute the shared `gather-and-attach-materials.md` instruction as an `agent_task`, passing `ticket_number` = the resolved ticket key, `draft_file_path` = `attachment_path`, and `auto_approve_external` = the inherited `{auto_approve_external}` value. It attaches phase-eligible local materials (Planning Assets, Downloadable Assets, and Planning & Downloadable Assets) and records external/auth-gated and binary/image materials per its own warn-not-halt rules. Any attach failure it reports is recorded (via `update_ticket_description`) as `partial_success` and never halts this step.\n 5. Call `track_ticket` with the resolved ticket key so Bridge API picks the new ticket up.\n 6. Write `{docs_dir}/idea-to-ticket/{slug}-{run_id}/upload-state.json` describing the final state.\n\n4. **Epic path** (`scope` is `epic_candidate`):\n 1. If `decomposition-plan.json` does not yet exist for this run, follow `decompose-epic-candidate.md` first to produce it (hard cap `{max_children}`).\n 2. Draft any surviving children that lack a draft on disk by calling `jira-ticket-writer` per child with the `draft_path` from the decomposition plan. After drafting, extend `draft-metadata.json` so `children[]` mirrors the final list from the decomposition plan.\n 3. Parent first. Look up the Epic parent by `bapi-idea-to-ticket-{run_id}-parent` via `get_tickets`. If found, reuse that key; otherwise call `create_ticket` with the parent's summary, slim description, issue type `Epic`, and parent labels. Attach the Epic draft via `attachment` (operation: `\"upload\"`) using `parent.attachment_path`. Then **gather and attach the Epic parent's referenced materials** by executing the shared `gather-and-attach-materials.md` instruction as an `agent_task`, passing `ticket_number` = the Epic key, `draft_file_path` = `parent.attachment_path`, and `auto_approve_external` = the inherited `{auto_approve_external}` value. Then call `track_ticket` for the Epic key.\n 4. Children next. For each child in order:\n - Look up by the child's `idempotency_label`. If found, reuse that key.\n - Otherwise call `create_ticket(parent_key=<epic_key>)` with the child's `summary`, `slim_description`, `issue_type`, and `labels`. The `parent_key` is required so Jira's modern parent linkage is set.\n - Upload the child draft via `attachment` (operation: `\"upload\"`) using `draft_path`.\n - **Gather and attach this child's referenced materials** by executing the shared `gather-and-attach-materials.md` instruction as an `agent_task`, passing `ticket_number` = the child key, `draft_file_path` = `draft_path`, and `auto_approve_external` = the inherited `{auto_approve_external}` value.\n - Call `track_ticket` for the child key.\n 5. After every parent or child mutation, write partial progress to `{docs_dir}/idea-to-ticket/{slug}-{run_id}/upload-state.json` so a later resume can pick up exactly where the run stopped.\n 6. **Recommended implementation order comment.** Once the Epic parent and all surviving children exist (real keys known), post a single comment on the Epic via `add_comment` with `ticket_number` set to the Epic key. The comment carries (a) a short System Goals / Non-Functional Requirements summary from `goals-and-nfrs.md`, and (b) the **Recommended Implementation Order** — the children in order, each referenced by its real Jira key, derived from the `depends_on` / `recommended_after` / `order_rationale` fields in `decomposition-plan.json`. State that this is recommended sequencing only — do **not** create Jira dependency links and do **not** attach a separate markdown doc. Skip this only if the run reused a pre-existing comment for the same run (idempotency); do not post duplicate order comments on resume.\n\n5. Required child label set whenever any child is created: `ai-generated`, `idea-to-ticket`, `idea-to-ticket-child`, and `bapi-idea-to-ticket-{run_id}-child-<N>` (1-based index from the decomposition plan).\n\n6. Partial-failure recovery rules:\n - If `create_ticket` succeeds but `attachment` (operation: `\"upload\"`) fails, record the outcome as `partial_success` in `upload-state.json` and continue with the next planned mutation; do not retry inside this step.\n - If the Epic parent is created successfully but one or more children fail, preserve the parent key and any completed child keys in `upload-state.json` before raising the failure.\n - On resume of any prior run, search by every relevant idempotency label first (`bapi-idea-to-ticket-{run_id}` for single tickets, `bapi-idea-to-ticket-{run_id}-parent`, and each `bapi-idea-to-ticket-{run_id}-child-<N>`) before considering any `create_ticket` call. Idempotency labels are how this pipeline avoids creating duplicate tickets across retries.\n\n## Return\n\nConfirm the run's final upload outcome: attachment results, `track_ticket` outcome, and any `partial_success` rows recorded in `upload-state.json`.\n\nThen, as the FINAL content of your reply, emit a fenced ```json block holding the authoritative payload for this run — and nothing else. The chain reads ONLY this final fenced JSON block to pick its review / start-tickets targets, so it must contain exactly the keys from `upload-state.json` and never any key you merely looked up during duplicate detection. Duplicate-detection / looked-up keys must not appear in this authoritative payload unless they are the final created/reused ticket for this run.\n\nThere are exactly two authoritative final payload shapes:\n\n- **Single-ticket path** (`scope` is `task` or `spike`): emit strictly `created_ticket_keys` containing **exactly one** implementable ticket key. `created_ticket_keys` is only for the single-ticket `task`/`spike` path and must contain exactly one implementable ticket key:\n\n ```json\n {\"created_ticket_keys\": [\"BAPI-331\"]}\n ```\n\n- **Epic path** (`scope` is `epic_candidate`): emit the Epic parent key separately as `epic_parent_key`, and the implementable children as `child_ticket_keys`:\n\n ```json\n {\"epic_parent_key\": \"BAPI-400\", \"child_ticket_keys\": [\"BAPI-401\", \"BAPI-402\"]}\n ```\n\n `child_ticket_keys` contains **only** implementable child Task/Spike ticket keys, listed in final decomposition order. `child_ticket_keys` must **never** include the Epic parent key.\n",
|
|
734
734
|
"upload-epic-hierarchy.md": "Standalone Epic upload protocol. Use as the detailed reference for the Epic path triggered from `upload-and-track.md`.\n\n## Inputs\n\n- Run manifest: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/run-manifest.json` with `scope == \"epic_candidate\"`.\n- Draft metadata: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/draft-metadata.json` with a populated `parent` and `children`.\n- Decomposition plan: `{docs_dir}/idea-to-ticket/{slug}-{run_id}/decomposition-plan.json`.\n- Pipeline variable `auto_approve_external` governs the external-mutation pause as in `upload-and-track.md` (for this run, `auto_approve_external` = `{auto_approve_external}`).\n\n## Instructions\n\n1. Parent idempotency lookup. Search Jira via `get_tickets` for issues carrying the label `bapi-idea-to-ticket-{run_id}-parent`. If a match exists, reuse that ticket key as the Epic parent and skip `create_ticket` for the parent. Otherwise call `create_ticket` with the parent's summary, slim description, `issue_type = \"Epic\"`, and labels including `ai-generated`, `idea-to-ticket`, and `bapi-idea-to-ticket-{run_id}-parent`. After creation or reuse, upload the Epic draft via `attachment` (operation: `\"upload\"`) and call `track_ticket`.\n\n2. Capture the resolved Epic key into a local variable `epic_key`. Every subsequent child mutation must reference this exact key.\n\n3. Per-child idempotency lookup. For each child in `decomposition-plan.json` (in order), search Jira by the child's `idempotency_label` (`bapi-idea-to-ticket-{run_id}-child-<N>`). If a match exists, reuse that key and skip `create_ticket` for that child. Otherwise call `create_ticket(parent_key=<epic_key>)` with:\n - `summary` — child summary.\n - `slim_description` — child slim description.\n - `issue_type` — typically `Task` (or `Spike` when the child is primarily discovery).\n - `labels` — `ai-generated`, `idea-to-ticket`, `idea-to-ticket-child`, and the child's own `bapi-idea-to-ticket-{run_id}-child-<N>` label.\n The `parent_key` argument is REQUIRED for every child `create_ticket` call so Jira sets the modern parent relationship; never omit it.\n\n4. After each child is created or reused, upload its draft via `attachment` (operation: `\"upload\"`) using the child's `draft_path`, then call `track_ticket` for that child key, then append the child outcome to `upload-state.json` in the run directory.\n\n5. On partial failure (e.g., parent succeeded, third child failed), preserve `epic_key` plus every completed child key in `upload-state.json`. The next run of this protocol must rediscover those keys via the idempotency-label lookups in steps 1 and 3 before considering any new `create_ticket` call.\n\n## Return\n\nConfirm the Epic key, the number of children created vs reused vs failed, and the path of the updated `upload-state.json`.\n",
|
|
735
|
-
"verify-plan.md": "Close the remaining plan gaps for ticket {ticket_key}, now that the pull request is open.\n\nThe plan's work has already been executed. The production phase authored the\nartifacts, the checkpoint pushed them, and the pre-PR verification phase ran the\nplan's review steps, test commands, and rendered-UI remediation — publishing each\nmaterial correction as it went. The pull request was then opened on top of all of it.\n\nThis phase exists for the narrow remainder: the plan obligations that genuinely could\n**not** be reached before a pull request existed, plus corrections attributable to this\nticket.\n\nTwo consequences follow, and both are deliberate:\n\n- **This phase does not re-run completed work.** A step the durable ledger records as\n `executed` or `adapted` stays settled unless a later correction invalidated its\n evidence. Re-running it duplicates work the pre-PR phase already did and burns the\n budget this protocol was reordered to protect.\n- **This phase never issues a verdict.** You report what you observed. The\n authoritative pass/fail belongs to the pipeline's `ci` and `code_review` gates,\n which the reconciler observes independently. Worker self-verification has\n demonstrably reported green while the full suite was red; that is exactly why the\n gates, not this phase, decide.\n\n---\n\n## Step 1 — Establish that the durable artifact exists\n\nBefore running any check:\n\n1. Run `git branch --show-current` and `git rev-parse HEAD`, then verify the branch\n has been pushed and the local head is present on the remote (for example via\n `git status -sb` showing no unpushed ahead-count, or `git ls-remote origin <branch>`).\n2. Verify that a usable pull request URL was obtained by the preceding PR step —\n either a newly opened pull request or an already-open one on this head branch.\n\nIf the branch is not pushed, or no usable pull request URL exists, then\n**stop this phase** and report the missing prerequisite. This phase exists only to\nadd work on top of an open pull request.\n\n## Step 2 — Recover what remains from durable state\n\n1. Call the `get_plan` tool for `{ticket_key}
|
|
735
|
+
"verify-plan.md": "Close the remaining plan gaps for ticket {ticket_key}, now that the pull request is open.\n\nThe plan's work has already been executed. The production phase authored the\nartifacts, the checkpoint pushed them, and the pre-PR verification phase ran the\nplan's review steps, test commands, and rendered-UI remediation — publishing each\nmaterial correction as it went. The pull request was then opened on top of all of it.\n\nThis phase exists for the narrow remainder: the plan obligations that genuinely could\n**not** be reached before a pull request existed, plus corrections attributable to this\nticket.\n\nTwo consequences follow, and both are deliberate:\n\n- **This phase does not re-run completed work.** A step the durable ledger records as\n `executed` or `adapted` stays settled unless a later correction invalidated its\n evidence. Re-running it duplicates work the pre-PR phase already did and burns the\n budget this protocol was reordered to protect.\n- **This phase never issues a verdict.** You report what you observed. The\n authoritative pass/fail belongs to the pipeline's `ci` and `code_review` gates,\n which the reconciler observes independently. Worker self-verification has\n demonstrably reported green while the full suite was red; that is exactly why the\n gates, not this phase, decide.\n\n**Tool and scope boundary.** Use only the tools this recipe names, the repo's own tooling, and MCP\ncapabilities provisioned for this repository. Keep all work confined to this worktree unless\nexplicitly told to do otherwise.\n\n**Execution mode for this run: `{execution_mode}`.** Under `orchestrated`\n(`run_pipeline` / `resume_pipeline`) orchestration appends the routed phase context and\nparses the fenced result envelope you return. Under `inline` (`get_pipeline_recipe`)\nthere is no orchestrator: the ledger is read with a tool call and written with one.\nFollow the branch that matches wherever the two are named.\n\n---\n\n## Step 1 — Establish that the durable artifact exists\n\nBefore running any check:\n\n1. Run `git branch --show-current` and `git rev-parse HEAD`, then verify the branch\n has been pushed and the local head is present on the remote (for example via\n `git status -sb` showing no unpushed ahead-count, or `git ls-remote origin <branch>`).\n2. Verify that a usable pull request URL was obtained by the preceding PR step —\n either a newly opened pull request or an already-open one on this head branch.\n\nIf the branch is not pushed, or no usable pull request URL exists, then\n**stop this phase** and report the missing prerequisite. This phase exists only to\nadd work on top of an open pull request.\n\n## Step 2 — Recover what remains from durable state\n\n1. Call the `get_plan` tool for `{ticket_key}`. The local copy at\n `{docs_dir}/plans/{ticket_key}-plan.md` may be used as a reference.\n2. Recover the durable ledger, by mode:\n - **orchestrated** — read the **Routed phase context** block appended to this\n instruction: `ledger` carries every disposition earlier phases recorded, and\n `ownedSteps` carries anything routed directly to this phase.\n - **inline** — call `get_phase_context` with `ticket_key` `{ticket_key}` and\n `phase` `post_pr_gap_close`. It returns the same `ownedSteps` plus the `ledger`\n merged from every earlier phase's artifact, `terminalStepIds` for what is\n already settled, and `unresolved` for the escalations that are this phase's\n actual subject.\n\nRecover the remaining work from that durable record, not from conversation. A\ncompaction or a resumed session loses the conversation; the ledger survives both,\nwhich is why it replaced the conversational hand-off.\n\n## Step 3 — Select only genuine gaps\n\nRun only:\n\n- Steps the ledger records as `escalated` **because a capability was unavailable\n before the pull request existed**, or **because the check genuinely requires an open pull request** — and\n which are now satisfiable.\n- Corrections clearly attributable to this ticket's change.\n\nReport — do not attempt to fix — failures that are unrelated to this ticket, flaky,\nenvironmental, pre-existing on the base branch, or outside the declared file scope.\nSpeculative edits made under budget pressure are how a correction round turns into a\nregression.\n\nApply the same adaptation boundary the earlier phases use: **locator-correction**,\n**repository-command-correction**, and **equivalent-implementation-recognized** are\nmechanical and may be applied; anything touching design, schema, public API,\ndependencies, or security escalates instead.\n\nBefore beginning any correction, apply the **low-budget guard**: only start if enough\nsession budget clearly remains to make the edit, commit it, *and* push it. Starting a\nfix you cannot finish and publish is strictly worse than reporting the finding and\nletting the CI and review gates handle it — an unpushed correction is invisible to\nthose gates.\n\n## Step 4 — Report what you observed, honestly\n\nFor every check you run, record the exact command, its observed result, and — on\nfailure — the relevant failure detail (the failing test names, the error output, the\ndiagnostic lines).\n\nReport all of it, including failures you did not fix. Never soften or omit a failing\nresult.\n\nDescribe only what you observed. Do not write that CI passed, that the gate is met,\nthat the review is approved, or any equivalent claim about the pipeline's verdict —\nthose states are decided by the `ci` and `code_review` gates and observed by the\nreconciler, never asserted by this phase.\n\n## Step 5 — Correct only what is clearly yours, and push it immediately\n\nFor each accepted correction:\n\n1. Make the edit.\n2. Stage the specific files, commit, and **push immediately** — the commit and its\n push are one consecutive sequence, never separated by another check. A local\n commit that is never pushed is not visible to the pull request, to CI, or to the\n reconciler.\n3. Run `git rev-parse HEAD` again and record the new pushed head as\n `last_commit_sha`.\n\n## Step 6 — Final git-state audit\n\nBefore returning, run `git status --porcelain` and resolve the working tree:\n\n- Legitimate corrections still uncommitted → commit and push them (Step 5's\n commit-then-push-immediately rule applies).\n- Accidental diagnostic edits — debug prints, scratch files, temporary config\n tweaks made while investigating a failure → revert them when it is safe to do so.\n- Anything you cannot safely resolve → leave it and **report it explicitly**,\n naming each remaining dirty path.\n\nNever return leaving unpushed commits unreported.\n\n## Step 7 — Hand unresolved findings forward\n\nAn unresolved local finding is normally **not** a reason to stop the pipeline. The\npull request is open and the authoritative gates will evaluate it. Report the\nfinding and let CI monitoring and code review take it from there.\n\nStop only when continuing would be unsafe or impossible — for example the durable\nartifact from Step 1 turned out to be missing, or the working tree is in a state you\ncannot resolve without risking the pushed branch.\n\n## Return\n\nReturn a summary containing:\n\n- the branch and the pull request URL,\n- the latest pushed `last_commit_sha`,\n- every gap-closing command run, with its observed outcome,\n- the correction commit, if one was made and pushed,\n- every unresolved finding and every unresolved dirty path.\n\nState these as worker observations. Do not include a pass/fail verdict for the `ci`\nor `code_review` gates.\n\nThen record the machine-readable phase result, by mode, so the durable ledger records\nhow the remaining gaps closed.\n\n### orchestrated\n\nEnd your result with the envelope in a fenced block tagged `bapi-phase-result`, which\norchestration parses, validates, and persists:\n\n```bapi-phase-result\n{\"version\":1,\"phase\":\"post_pr_gap_close\",\"lastCommitSha\":\"<sha>\",\"records\":[]}\n```\n\n### inline\n\nCall the `record_phase_result` tool with `ticket_key` `{ticket_key}` and\n`phase_result` set to that same envelope object; the tool validates and persists it.\n**Do not also emit a fenced `bapi-phase-result` block** — nothing parses one on this\npath.\n\nThe tool call is this phase's final action, **not the end of your turn.** When it\nreturns successfully, continue immediately with the next recipe step — the ticket\nstatus transition, the CI follow-up config, and CI monitoring. The pull request is\nopen and its gates are still pending; stopping here abandons the run before anything\nobserves them.\n\nIf the call fails, fix what it reports and call it again.\n",
|
|
736
736
|
"write-epic-summary.md": "Synthesize all sub-task explorations into a final overview document.\n\n## Instructions\n\n1. First, use a terminal command or glob pattern to list all files in `{docs_dir}/epic-plans/{epic_slug}/explorations/`. Then read each file. Do not guess filenames — discover them dynamically.\n\n2. Also read:\n - `{docs_dir}/epic-plans/{epic_slug}/research-findings.md`\n - `{docs_dir}/epic-plans/{epic_slug}/epic-plan.md`\n - `{docs_dir}/epic-plans/{epic_slug}/goals-and-nfrs.md` (the goals/NFR framing; carry its System Goals, NFRs, and any Recommended Implementation Order through to the overview).\n\n3. Synthesize the information into an overview and write it to `{docs_dir}/epic-plans/{epic_slug}/overview.md` with the following required sections:\n\n```markdown\n# Epic Overview: {epic title derived from description}\n\n## Epic Description and Goals\n{Summary of the epic's purpose, scope, and desired outcomes. Lead with the business goal and desired end-state from goals-and-nfrs.md.}\n\n## Non-Functional Requirements\n{The classified NFRs from goals-and-nfrs.md — each with its category, requirement, implication, and final status (confirmed/assumed). Any NFRs the user clarified should now read as confirmed/assumed, not open.}\n\n## Research Summary\n{Key external findings that informed the decomposition. If no research was performed, state \"No external research was needed.\"}\n\n## Sub-task List\n{Numbered list of all sub-tasks with relative markdown links to their exploration docs.}\n1. [Sub-task title](explorations/01-subtask-slug.md) — one-line summary\n2. [Sub-task title](explorations/02-subtask-slug.md) — one-line summary\n...\n\n## Dependency Graph\n{Textual list showing execution ordering and dependencies between sub-tasks.}\n- Sub-task 1: No dependencies (start here)\n- Sub-task 2: Depends on Sub-task 1\n- Sub-task 3: Depends on Sub-task 1\n- Sub-task 4: Depends on Sub-tasks 2, 3\n...\n\n## Recommended Implementation Order\n{The recommended order in which to implement the sub-tasks, reconciling the provisional order from goals-and-nfrs.md with the approved decomposition. For each sub-task give the position, its hard prerequisites (depends on), any soft sequencing preferences (recommended after), and a one-line rationale. This is recommended sequencing only — no Jira dependency links are created.}\n\n## Next Steps\n{One-line summaries for each sub-task, specifically formatted so they can be copy-pasted directly into the `/write-ticket` command. Each line should be a self-contained ticket description.}\n```\n\n4. After writing the overview, display the file path to the user and summarize the epic plan.\n\n5. **Push the goals/NFRs + recommended order into the Jira epic (only when `{epic_key}` is non-empty).** The `epic_key` is empty when this run was started from free-form text rather than an existing Epic; in that case skip this step. When `{epic_key}` is a real Jira key, post the System Goals, the final NFRs, and the Recommended Implementation Order as a **comment** on that epic by calling the `add_comment` MCP tool with `ticket_number` set to `{epic_key}` and a concise comment containing those three parts. Do not create Jira dependency links and do not attach a separate markdown doc — the comment is the delivery. Display: `\"Posted epic goals/NFRs and recommended implementation order to {epic_key}\"`.\n\n## Return\n\nConfirm the overview was written to `{docs_dir}/epic-plans/{epic_slug}/overview.md` and report the total sub-task count along with a one-line summary of the epic plan. State whether the goals/NFRs + recommended order were posted as a comment on `{epic_key}` or skipped because no epic key was provided.\n"
|
|
737
737
|
};
|