customize.toml
# DO NOT EDIT -- overwritten on every update.
#
# Workflow customization surface for bmad-review.
#
# Override files (not edited here):
# {project-root}/_bmad/custom/bmad-review.toml (team)
# {project-root}/_bmad/custom/bmad-review.user.toml (personal)
[workflow]
# --- Configurable below. Overrides merge per BMad structural rules: ---
# scalars: override wins
# arrays (persistent_facts, activation_steps_*, review_guidance): append
# arrays of tables keyed by `code`: matching key replaces, new keys append
# Steps executed on activation: prepend runs before the skill's own
# activation flow, append runs after the lens plan is settled and before the
# lenses run. Each entry is a literal instruction.
activation_steps_prepend = []
activation_steps_append = []
# Standing context held for every review, code and document alike. Entries
# prefixed `file:` are paths or globs whose contents load as facts; all others
# are literal facts. The shipped entry is a project-wide glob — set it to []
# if you don't want every review scanning for it.
persistent_facts = []
# Standing review directives applied on every run alongside each lens's own
# method. Each entry is a literal sentence or a `file:`-prefixed path/glob
# whose contents load as directives.
#
# Examples:
# "Flag passive voice in headings."
# "Second-person imperative is the house voice; never suggest changing it."
# "file:{project-root}/docs/terminology.md"
review_guidance = []
# Executed after the findings are delivered. Freeform directive; empty = the
# review ends with the findings.
#
# Example:
# on_complete = "Append a one-line review summary to {project-root}/docs/review-log.md"
on_complete = ""
# How findings are presented when the caller doesn't say: "json" (the raw
# findings array only), "markdown" (the human report only), or "both". A lens
# that declares its own rendering keeps it for its own findings.
output_format = "both"
# Where to write the review report. Empty = present in chat only. Accepts
# {project-root}-prefixed paths.
report_path = ""
# How findings are presented — shaping, not destination. Freeform directive;
# empty = each lens's default ordering and rollup.
#
# Example:
# output_preferences = "Cap output at the 20 highest-impact findings."
output_preferences = ""
# --- Editorial lens settings (used by the structure and prose lenses) ---
# Default reader the editorial lenses calibrate for when the request doesn't
# say:
# "humans" clarity, flow, comprehension aids preserved
# "llm" precision, consistent terminology, no hedging
# A reader type stated in the request wins for that run.
reader_type = "humans"
# The baseline style guide for every editorial review: the name of a guide the
# model knows well, a `file:`-prefixed path to a style guide document, or the
# rules inline as text. A style guide stated in the request wins for that run.
# Where the guide in effect conflicts with the lens's generic principles, the
# guide wins — except content is sacrosanct.
#
# Examples (set in team/user override TOML):
# style_guide = "file:{project-root}/_bmad/style-guides/company-voice.md"
# style_guide = "Sentence-case headings. No Oxford comma. Address the reader as 'you'."
style_guide = "Microsoft Writing Style Guide"
# ---------------------------------------------------------------------------
# Review lenses. Each lens is a pass over the content with its own method and
# stance. `instruction` is the lens's whole execution recipe — the shipped
# lenses load a reference file from the skill root, but an override may inline
# any prompt.
#
# `applies_to` is the content this lens can review: "code", "docs", or "any".
# It is the first filter — a lens never joins a default review for content it
# does not apply to. `when` (optional) refines that judgement in prose. An
# explicitly requested lens always runs, whatever both say.
#
# `after` (optional) names a lens this one builds on: it runs once that lens
# has completed and receives its findings, instead of running independently.
#
# Empty `instruction` disables a lens. Keyed by `code`: an override with a
# matching code replaces the shipped lens, a new code appends.
#
# Example (add an org-specific lens in team/user override TOML):
# [[workflow.lenses]]
# code = "accessibility"
# name = "Accessibility"
# applies_to = "any"
# when = "UI code or user-facing documents."
# instruction = "Review against WCAG 2.2 AA. Emit findings in the canonical fields."
# ---------------------------------------------------------------------------
[[workflow.lenses]]
code = "adversarial"
name = "Adversarial"
applies_to = "any"
when = "always"
instruction = "Load `references/lens-adversarial.md` from the skill root and follow it."
[[workflow.lenses]]
code = "edge-case-hunter"
name = "Edge-Case Hunter"
applies_to = "any"
when = "Content with behavior to trace: code, diffs, and the specs, requirements, plans, and stories that define behavior. Skip for prose documents with no behavioral surface."
instruction = "Load `references/lens-edge-case-hunter.md` from the skill root and follow it."
[[workflow.lenses]]
code = "verification-gap"
name = "Verification Gap"
applies_to = "code"
when = "Reviewed inside a repo where tests can be searched and read."
instruction = "Load `references/lens-verification-gap.md` from the skill root and follow it."
[[workflow.lenses]]
code = "structure"
name = "Editorial Structure"
applies_to = "docs"
when = "Documents whose shape is the author's to change."
instruction = "Load `references/lens-structure.md` from the skill root and follow it."
[[workflow.lenses]]
code = "prose"
name = "Editorial Prose"
applies_to = "docs"
after = "structure"
when = "Documents being copy-edited."
instruction = "Load `references/lens-prose.md` from the skill root and follow it."
module-manifest.toml
module = "toolbox"
version = "6.13.0-next"
update_source = "github:bmad-code-org/BMAD-METHOD/skills"
knowledge = "`references/help.md` in the `bmad` skill"
references/editorial-common.md
# Editorial Lenses — Common Ground
Shared by the `structure` and `prose` lenses. Load this once; when both lenses run, the setup below is done once and serves both.
## Stance
Review a document as a clinical editor and return suggested fixes the author can accept or reject row by row. Two passes: **structure** (cuts, merges, moves, condensing — does the document's shape serve its purpose?) then **prose** (copy-edit for communication issues that impede comprehension). Which of the two run, and in what order, is decided by lens selection — see the skill's Execution section.
**Content is sacrosanct.** Never challenge ideas — only how they're organized and expressed. Propose, don't execute: the author decides what to accept.
The baseline style guide is `{workflow.style_guide}`; a style guide stated in the request wins over the configured one for that run. Where the style guide in effect conflicts with a generic principle here — including the reader calibration — the style guide wins. Nothing overrides content being sacrosanct.
## Setup
1. Gather inputs: the content (required — a path or pasted text), plus whatever the request states: purpose, target audience, length target, reader type, style guide. If no reviewable content was provided, say so and stop. Request-level values win; `{workflow.reader_type}` and `{workflow.style_guide}` fill what the request leaves unstated. Treat `{workflow.review_guidance}` entries as standing review directives.
2. When the content is a file, get exact word counts — document total and per heading section — via `uv run {skill-root}/scripts/word_metrics.py <path>` (`--help` documents the output), and ground every word-impact estimate and the reduction summary in those numbers. If the content was pasted or the script cannot run, estimate and mark the numbers as estimates.
3. Infer purpose and audience from the content and standing context when not provided, and open the output with your one-sentence read — "this document exists to help [audience] accomplish [goal]" — so the author can correct a wrong premise before acting on the findings.
## Reader calibration
Calibrate every finding to the reader type — stated in the request, else `{workflow.reader_type}`.
**humans** (default) — optimize for clarity, flow, and natural progression. These elements serve comprehension and engagement; preserve them unless clearly wasteful, and flag any recommendation that would cut one:
- Visual aids: diagrams, images, and flowcharts anchor understanding
- Expectation-setting: "What You'll Learn" helps readers confirm they're in the right place
- Reader's journey: organize content as a linear progression, not a database
- Mental models: overview before details prevents cognitive overload
- Warmth: encouraging tone reduces anxiety for new users
- Whitespace: admonitions and callouts provide visual breathing room
- Summaries: recaps help retention; they're reinforcement, not redundancy
- Examples: concrete illustrations make abstract concepts accessible
- Engagement: flow techniques (transitions, variety) are functional, not fluff — they maintain attention
**llm** — optimize for precision and unambiguity. An LLM-targeted document may run longer where explicitness pays and shorter where warmth was cut:
- Dependency-first: define concepts before usage to minimize hallucination risk
- Cut emotional language, encouragement, and orientation sections
- Reference well-known standards ("conventional commits", "REST APIs") instead of re-teaching them; be explicit where a concept is not well-known — and either way, ground the expectation with an example
- Consistent terminology: same word for same concept throughout
- No hedging ("might", "could", "generally") — direct statements
- Prefer structured formats (tables, lists, YAML) over prose
- Unambiguous references: no unclear antecedents ("it", "this", "the above")
## Findings shape
The editorial lenses render as a findings table rather than the canonical JSON fields. One findings table serves both passes:
| Pass | Original Text | Revised Text | Changes |
| --------- | ----------------------------------------------------- | --------------------------------------------- | -------------------------------------------------------------------- |
| structure | §Setup — full section (~180 words) | MERGE into §Installation | Duplicates the install steps; one source of truth (saves ~150 words) |
| prose | The system will processes data and it handles errors. | The system processes data and handles errors. | Fixed subject-verb agreement; removed redundant "it" |
Structure rows name the section or passage in **Original Text** and carry the tagged disposition (with move target or condensed rewrite) in **Revised Text**; prose rows quote the exact text and its revision. Order rows by comprehension impact; when a long document would produce more rows than an author can realistically act on, present the highest-impact rows and roll the rest into one closing line — "N further minor fixes; ask to expand." Above the table, give the purpose/audience read plus — when the structure pass ran — the chosen structure model. When the structure pass ran, close with a summary: total recommendations, estimated reduction (words and % of original, computed from the word-metrics counts) if all are accepted, whether a provided length target is met, and any comprehension trade-offs (cuts that sacrifice reader engagement for brevity). A pass that finds nothing is a valid result; say so.
Shape the table per `{workflow.output_preferences}`.
references/lens-adversarial.md
# Adversarial Lens
Conduct a review of the provided content.
Look for what's missing, not only what's wrong.
Find at least ten issues to fix or improve.
If `also_consider` areas were provided, weigh them alongside the normal analysis.
If the content is empty, stop and say so.
If you have zero findings, re-check and keep thinking; do not stop with an empty list.
## Findings shape
Emit each finding with the canonical fields:
- `location` — where in the content (file:line for code, section or heading for documents, "general" when it spans the whole artifact)
- `trigger_condition` — the problem, in one line
- `guard_snippet` — the concrete fix or improvement
- `potential_consequence` — what goes wrong if it ships unaddressed
No severity, priority, or ranking.
references/lens-edge-case-hunter.md
# Edge-Case Lens
You are a pure path tracer. Never comment on whether the content is good or bad; only list missing handling. Your method is exhaustive path enumeration — mechanically walk every branch, not hunt by intuition. Report ONLY paths and conditions that lack handling — discard handled ones silently. Do not editorialize or add filler.
**MANDATORY: Execute the steps below IN EXACT ORDER. DO NOT skip steps or change the sequence. Each action within a step is a REQUIRED action to complete that step.**
**Scope rules:**
- When the content is a diff, scan only the diff hunks and list boundaries that are directly reachable from the changed lines and lack an explicit guard in the diff.
- When it is not a diff (full file, function, or document), the entire provided content is the scope.
- Ignore the rest of the codebase unless the provided content explicitly references external functions.
- When the launch message names a claims file, do NOT read it before Step 4: the path tracing in Steps 1–2 must finish before the narrative is seen.
## Step 1: Exhaustive path analysis
Walk every branching path and boundary condition within scope — report only unhandled ones.
- If `also_consider` areas were provided, incorporate them into the analysis
- Walk all branching paths: control flow (conditionals, loops, error handlers, early returns) and domain boundaries (where values, states, or conditions transition). Derive the relevant edge classes from the content itself — don't rely on a fixed checklist. Examples: missing else/default, unguarded inputs, off-by-one loops, arithmetic overflow, implicit type coercion, race conditions, timeout gaps
- Consider implicit branches: the diff special-cases or changes the handling of one or more members of a fixed set of values — enums, status codes, sentinels, type tags, flags, value ranges. The rest of the set is implicit branches (e.g. the diff changes the `RED` and `YELLOW` cases of a `RED`/`YELLOW`/`GREEN` enum; `GREEN` is the implicit branch)
- Consider handle lifetime: when the changed code re-checks, re-fetches, or re-validates something it already held — a handle, index, id, pointer — the re-check exists because an intervening call can invalidate it. Identify that call, what it does to the thing held, and what the changed code silently skips when the re-check fails
- For each call site the diff adds or changes — in test files as well as production code — read the callee's declaration and check the call against it: argument count, order, types, and defaults. Report any mismatch
- For each path: determine whether the content handles it
- Collect only the unhandled paths as findings — discard handled ones silently
## Step 2: Validate completeness
- Revisit every edge class from Step 1 — e.g., missing else/default, null/empty inputs, off-by-one loops, arithmetic overflow, implicit type coercion, race conditions, timeout gaps
- Add any newly found unhandled paths to findings; discard confirmed-handled ones
## Step 3: Deletion check
Runs only when the diff removed or replaced meaningful code (ignore pure renames and whitespace). Subordinate to the edge-case pass; findings are usually few or none.
For each chunk of removed or replaced code, ask: did it carry behavior or a contract that the change neither re-established nor intentionally retired? Add a finding for any resulting regression, orphaned reference, or newly-dead code. Skip anything already covered by your edge-case findings. Add nothing if nothing qualifies.
Deletion findings go in the same array with the four standard fields plus:
- `kind`: `"deletion"`
- `confidence`: `"high"`, `"medium"`, or `"low"` — these are inferences; rate them
For a deletion finding the standard fields read as: `location` = the removed item; `trigger_condition` = the behavior or contract it enforced; `guard_snippet` = where or how to re-establish it; `potential_consequence` = the regression or orphan.
## Step 4: Claims check
Runs only when the message that launched you named a claims file. Read that file now, for the first time; the path tracing is finished and the claims cannot steer it retroactively.
The file holds the change's own narrative — commit messages and any stated description. The narrative is the author's testimony, not evidence: a claim repeated in a code comment is still the same claim, not confirmation. Extract each checkable claim — what the change does, what it preserves, ordering, arithmetic, and parity with existing code ("exactly as X does") — then try to falsify each one against the code you have already traced. Where your trace is not enough to decide, read the code that decides it: the compared-to function, the actual callee, the state the claim assumes.
Claim findings go in the same array with the four standard fields plus:
- `kind`: `"claim"`
- `confidence`: `"high"`, `"medium"`, or `"low"`
For a claim finding the standard fields read as: `location` = where the code contradicts the claim; `trigger_condition` = the claim, quoted or tightly paraphrased; `guard_snippet` = what the code actually does; `potential_consequence` = what goes wrong for someone who believed the claim.
Verified claims produce nothing. Add nothing if nothing is falsified.
## Findings shape
Each edge-case finding contains exactly these four fields:
```json
[{
"location": "file:start-end (or file:line when single line, or file:hunk when exact line unavailable)",
"trigger_condition": "one-line description (max 15 words)",
"guard_snippet": "minimal code sketch that closes the gap (single-line escaped string, no raw newlines or unescaped quotes)",
"potential_consequence": "what could actually go wrong (max 15 words)"
}]
```
An empty array is valid when nothing is found. Do not assign severity labels, rankings, or priority levels.
references/lens-prose.md
# Prose Lens
Load `references/editorial-common.md` from the skill root first and follow it — stance, setup, reader calibration, and findings shape are shared with the structure lens. When the structure lens ran ahead of this one, its findings are supplied to you; when this lens runs alone, there are none and the clauses below that depend on them do not apply.
You are a clinical copy-editor: precise, professional, neither warm nor cynical. First analyze the style, tone, and voice of the text and note intentional stylistic choices to preserve (informal tone, technical jargon, rhetorical patterns). Then copy-edit for communication issues that impede comprehension — never rewrite for preference, and apply the smallest fix that achieves clarity. Fix prose within the existing structure (shape problems belong to the structure pass). Skip code blocks, frontmatter, and structural markup. Preserve the author's voice and the stylistic choices you noted. When the structure pass ran, skip passages it tagged CUT, and attach fixes inside MERGE'd passages to the surviving location. Deduplicate: the same issue in several places is one row listing all locations, and merge overlapping fixes into single entries so no suggestions conflict. Phrase uncertain fixes as "Consider: …?" rather than definitive changes.
Emit rows with `Pass` = `prose`.
references/lens-structure.md
# Structure Lens
Load `references/editorial-common.md` from the skill root first and follow it — stance, setup, reader calibration, and findings shape are shared with the prose lens.
You are a structural editor focused on high-value density. Brevity is clarity: concise writing respects limited attention spans and enables effective scanning. Every section must justify its existence — cut anything that delays understanding. True redundancy is failure — but comprehension sets the floor: optimize for the minimum words that maintain understanding. Front-load value: critical information comes first; nice-to-know comes last (or goes).
Load `references/structure-models.md`, pick the model matching the document's purpose, and evaluate the document against it. Hunt for: sections that don't serve the stated purpose, true redundancy (identical information with no reinforcement value), scope violations (content that belongs in a different document), buried critical information, premature detail, missing scaffolding, and the classic anti-patterns — FAQs that should be inline, appendices that should be cut, overviews that repeat the body verbatim. For human readers, also assess pacing: is there enough whitespace and visual variety to maintain attention? Tag each finding CUT, MERGE, MOVE, CONDENSE, QUESTION, or PRESERVE (explicitly keep something that looks cuttable but serves comprehension), and state its word impact from the word-metrics counts. If a length target was provided, assess whether the recommendations meet it.
Emit rows with `Pass` = `structure`.
references/lens-verification-gap.md
# Verification-Gap Lens
**Goal:** Find changed behavior that could break without reliable verification catching it. Ask one question — "if the behavior this change is supposed to produce broke where it's actually used, would verification fail?" Do not hunt for correctness bugs, but report genuine problems you notice while tracing verification.
The main verification gap shapes are:
1. **Regression gap:** the changed code regresses where it's used, and no test covering that use would fail.
2. **Missing-adoption gap:** a place that should now use the new behavior doesn't; it handles the same case its own way, or not at all, and no test would flag the omission.
3. **Broken-verification gap:** a test appears to cover the changed behavior, but would not actually protect it because it is skipped, flaky, not run in the normal verification path, or too weak to observe the regression.
## Evidence rules
- Read a test before claiming what it covers, runs, asserts, or misses.
- Before claiming no test exists, search the whole repo by the symbol under test and by import references; expected file locations are not enough.
- Never assert what you did not verify. If a finding cannot be grounded, drop it.
- In a finding, say what you actually checked — "none of the tests I read cover this" — and show how far you looked. Say a test doesn't exist anywhere only when the symbol/import-reference search actually shows that.
- Do not assign severity, confidence, priority, or ranking.
## Review sequence
### Step 1: Screen for behavioral change
Before applying the non-behavioral stop to a test-only change, check whether it removes or weakens verification of deterministic behavior. If so, continue to Step 2; it is eligible for a broken-verification gap even though production behavior is unchanged.
If the change is non-behavioral, stop here and return zero findings (`[]`); when the output format includes a markdown report, note there that the change is non-behavioral (a caller's exact zero-findings output contract wins over this note). Call it non-behavioral only when the changed code does not alter return values, thrown errors, caller-visible side effects, or observable state (including iteration order and emitted messages). After the changed code meets that test, stop; do not inspect callers or tests for extra confirmation.
Common non-behavioral examples: formatting, comments, whitespace; pure renames; trivial getters/setters and pass-throughs; type-only or compiler-enforced changes with no runtime effect; etc.
### Step 2: Find the behavior that changed
Identify what behavior changed compared to the previous version: output, side effect, branch, error path, schema/event shape, config default, validation/authorization rule, external contract, etc. If the change affects more than one behavior, handle each separately.
Treat broad-impact changes as behavioral even when no single changed line looks important: dependency, toolchain, build/config, data-file, etc.
Seek verification of behavior, not the literal text of implementation or documentation artifacts. Tests may assert exact content or structure when they execute deterministic construction or transformation and inspect its output, including generated prompts and request payloads. Do not seek phrase-existence assertions over hand-authored prompts, skills, documents, or source files.
For LLM-backed behavior, stop at the inference boundary: do not require invoking a model or judging its semantic response. Deterministic request construction and response handling remain eligible without live inference; existing inference tests are not precedent for more.
### Step 3: Trace where that behavior is used
Trace the changed behavior to the places that observe it. Start with direct callers and registered entry points (routes, commands, DI), contract consumers (schemas, events, APIs, database readers), and reverse-dependency info if already available.
Follow a path only while the changed behavior is reachable and unverified. Stop when a test at that boundary would fail, the consumer does not observe the changed behavior, or the next hop is guesswork (dynamic dispatch, reflection, outside-repo consumers, etc.). Prefer the nearest observable boundary, often one to three hops away, especially across contract, integration, or service edges. If there are more than five similar consumers, group obvious repeats and check representative paths; expand only when a consumer observes the behavior differently.
### Step 4: Qualify the consumer, then check its test
For each consumer, name the smallest realistic regression this consumer would observe: invert the branch, drop the default, omit the field, return the old error code, skip the integration call, etc. This is the Demonstration. If no such regression exists, drop the path; untested downstream code is not a finding.
A `Missing-adoption gap` qualifies not by the adoption failure alone but by a supersession signal: the change gives clear evidence the new behavior is meant to replace the local one — PR intent, naming or docs, a replaced sibling site, deleted duplicate logic, or a test defining the new rule — and the local site shares the same observable contract. Without a supersession signal and a shared observable contract, it is a refactor suggestion, not a verification-gap finding. Once both hold, check whether any test for that site would flag the non-adoption; missing coverage of the non-adoption is the gap itself, not a disqualifier.
Find and read the relevant test. Ask whether the Demonstration would make an assertion fail.
- If yes, the behavior is verified. No finding.
- For a regression-style Demonstration: if no test runs the path, the test is skipped/flaky/not run normally, or the test runs the code without checking the changed result, report a `Regression gap` or `Broken-verification gap`.
- For a qualifying Missing-adoption case: if none of the site tests you found assert it adopts the new behavior, report a `Missing-adoption gap`.
A test counts only if it runs normally and an assertion observes the changed output, branch, or contract. These do not count: no execution; success/no-throw/snapshot-only checks; mock/log-call checks; human-only checks; tests that mock away the integration; e2e tests that pass through without checking the changed output; stale assertions or fixtures.
For example, `expect(x ?? DEFAULT).toBe(DEFAULT)` passes when `x` is missing.
Common patterns:
- **Caller-path gap** — helper test covers the branch, but caller values skip it.
- **Contract drift** — payload/schema/event changes must be verified at the consumer.
- **Migration compatibility** — tests only create new-format rows or fresh schemas.
- **Phantom exception** — handled partial-failure path has no test.
- **Missing-adoption gap** — sibling site should use the new rule/helper and does not.
- **Removed verification** — deleted test or weakened assertion leaves behavior unpinned.
### Step 5: Confirm each finding is real
Before writing a finding, re-open the specific tests or search results the finding relies on. Verify the Demonstration would not make any test you checked fail, or that the absence claim is backed by the symbol/import-reference search. Do not claim more than you verified; drop any finding you cannot ground.
Explain why the test misses the bug using what the test sets up and checks.
Do not report: compiler/type-checker-enforced cases; behavior already verified by an integration, contract, or e2e test; implementation-detail or mock-only tests; low coverage or a missing test file by itself; legacy untested code the change did not affect.
Report genuine problems you noticed while tracing verification, even if they are not verification gaps — emit them as findings with `gap_shape: "other"`. This permits reporting what you already reached, not extra hunting.
## Findings shape
Emit each gap with the canonical fields plus this lens's extras:
- `location` — the changed surface: the exact behavior or contract that changed, `file:line`
- `trigger_condition` — the gap, in one line
- `guard_snippet` — the missing verification: the precise assertion or check that's absent, optionally with the test shape that would close it, fit to the repo's own way of verifying — don't impose a generic test pyramid
- `potential_consequence` — the concrete thing that ships wrong: the regression the checked evidence would not catch, or the site that should use the new behavior and doesn't, with why the tests you checked would not fail
- `gap_shape` — `"regression-gap"`, `"missing-adoption-gap"`, `"broken-verification-gap"`, or `"other"`
- `consumer` — the impacted consumer or site, named concretely with `file:line` (e.g. "the `createInvoice` mutation used by the billing dashboard at `billing/dashboard.ts:88`", not "callers of this function")
- `evidence` — what you actually checked: what the relevant test asserts with `file:line`; or, if none, the symbol/import-reference searches run and their result; for a broken-verification gap, the apparent test and why it does not count
For `gap_shape: "other"` findings the four canonical fields suffice (description only); `consumer` and `evidence` are optional. An empty array is valid when the change is non-behavioral or every changed behavior is verified. When this lens comes up clean and a markdown report is presented, its clean statement for this lens is exactly: `No verification gaps found.`
references/structure-models.md
# Structure Models
Reference shapes for the structure pass. Pick the one matching the document's purpose and evaluate the document against its rules; a document that fits none cleanly is judged against the closest model, with the mismatch itself noted as a finding when the shape fights the purpose.
## Tutorial/Guide (Linear)
**Applicability:** Tutorials, detailed guides, how-to articles, walkthroughs
- Prerequisites: setup/context MUST precede action
- Sequence: steps follow strict chronological or logical dependency order
- Goal-oriented: clear "Definition of Done" at the end
## Reference/Database
**Applicability:** API docs, glossaries, configuration references, cheat sheets
- Random access: no narrative flow required; the reader jumps to a specific item
- MECE: topics are Mutually Exclusive and Collectively Exhaustive
- Consistent schema: every item follows an identical structure (e.g., Signature → Params → Returns)
## Explanation (Conceptual)
**Applicability:** Deep dives, architecture overviews, conceptual guides, whitepapers, project context
- Abstract to concrete: Definition → Context → Implementation/Example
- Scaffolding: complex ideas built on established foundations
## Prompt/Task Definition (Functional)
**Applicability:** BMad skills and workflows, prompts, system instructions, agent definitions
- Meta-first: inputs, usage constraints, and context defined before instructions
- Separation of concerns: instructions (logic) separate from data (content)
- Explicit flow: execution order is stated, never implied
## Strategic/Context (Pyramid)
**Applicability:** PRDs, research reports, proposals, decision records
- Top-down: conclusion/status/recommendation starts the document
- Grouping: supporting context grouped logically below the headline
- Ordering: most critical information first
- MECE: arguments/groups are Mutually Exclusive and Collectively Exhaustive
- Evidence: data supports arguments, never leads
scripts/tests/test_word_metrics.py
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# ///
"""Tests for word_metrics.py."""
import sys
import unittest
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
from word_metrics import section_metrics, word_count
DOC = """Intro line before any heading.
# Title
Two words here indeed.
## Section A
Alpha beta gamma.
```
# not a heading
fenced words ignored as headings
```
## Section B
Delta epsilon.
"""
class WordMetricsTest(unittest.TestCase):
def test_word_count(self):
self.assertEqual(word_count("one two three\nfour"), 4)
self.assertEqual(word_count(""), 0)
def test_sections_split_on_headings(self):
sections = section_metrics(DOC)
headings = [s["heading"] for s in sections]
self.assertEqual(headings, ["(preamble)", "Title", "Section A", "Section B"])
def test_fenced_heading_not_a_section(self):
sections = section_metrics(DOC)
self.assertNotIn("not a heading", [s["heading"] for s in sections])
def test_section_words_counted(self):
sections = {s["heading"]: s["words"] for s in section_metrics(DOC)}
self.assertEqual(sections["Section B"], 2)
# Section A body includes the fenced block's tokens
self.assertGreater(sections["Section A"], 3)
def test_empty_preamble_dropped(self):
sections = section_metrics("# Only\n\nwords here\n")
self.assertEqual([s["heading"] for s in sections], ["Only"])
if __name__ == "__main__":
unittest.main()
scripts/word_metrics.py
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# ///
"""Exact word counts for a document, as JSON.
Emits the document's total word count and a per-heading-section breakdown so
an editorial review can ground word-impact estimates and reduction
percentages in real numbers instead of guessing. Sections are delimited by
markdown headings (# through ######); heading markers inside fenced code
blocks are ignored (fences pair CommonMark-style: a fence closes only on a
run of the same character at least as long, so ```` fences may embed ```
examples). A word is any whitespace-separated token, plus one word per CJK
character since those scripts do not space-delimit words. For non-markdown
input the result is a single section holding the full text.
"""
import argparse
import json
import re
import sys
from pathlib import Path
HEADING = re.compile(r"^(#{1,6})\s+(\S.*)$")
FENCE = re.compile(r"^ {0,3}(`{3,}|~{3,})")
CJK = re.compile(r"[-ヿ㐀-䶿一-鿿豈-가-ヲ-゚]")
def word_count(text: str) -> int:
cjk = len(CJK.findall(text))
return cjk + len(CJK.sub(" ", text).split())
def section_metrics(text: str) -> list[dict]:
sections = []
current = {"heading": "(preamble)", "level": 0, "body": []}
open_fence = None # (char, length) while inside a fenced block
for line in text.splitlines():
fence = FENCE.match(line)
if fence:
marker = fence.group(1)
if open_fence is None:
open_fence = (marker[0], len(marker))
elif marker[0] == open_fence[0] and len(marker) >= open_fence[1] and line.strip() == marker:
open_fence = None
current["body"].append(line)
continue
match = None if open_fence else HEADING.match(line)
if match:
sections.append(current)
current = {
"heading": match.group(2).strip(),
"level": len(match.group(1)),
"body": [],
}
else:
current["body"].append(line)
sections.append(current)
out = []
for section in sections:
words = word_count("\n".join(section["body"]))
if section["heading"] == "(preamble)" and words == 0:
continue
out.append({"heading": section["heading"], "level": section["level"], "words": words})
return out
def metrics(path: Path) -> dict:
text = path.read_text(encoding="utf-8", errors="replace")
return {
"file": str(path),
"total_words": word_count(text),
"sections": section_metrics(text),
}
def main() -> int:
if hasattr(sys.stdout, "reconfigure"):
sys.stdout.reconfigure(encoding="utf-8") # JSON is UTF-8 regardless of locale code page
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
parser.add_argument("path", help="document to measure")
parser.add_argument("-o", "--output", help="write JSON here (default: stdout)")
args = parser.parse_args()
path = Path(args.path)
if not path.is_file():
print(f"error: not a readable file: {path}", file=sys.stderr)
return 2
result = json.dumps(metrics(path), indent=2, ensure_ascii=False)
if args.output:
Path(args.output).write_text(result + "\n", encoding="utf-8")
else:
print(result)
return 0
if __name__ == "__main__":
sys.exit(main())
SKILL.md
---
name: bmad-review
description: 'Runs one or more installed review lenses — adversarial critique, edge cases, verification gaps, structure, prose — and reports triaged findings. Use when, and only when, the user asks you to review a diff, a pull request, or an artifact — code or documents, one or many — and actually says "review"; an explicit skill:bmad-review directive from another skill counts as that ask. A request to act on feedback from an earlier review is a change, not a review. Never invoke this uninvited, including on edits you just made.'
---
# BMad Review
Review content through lenses — each a distinct method and stance — and report findings in one canonical shape. Report what is real — never pad to look thorough. Each lens sets its own stance toward the content and toward zero findings: for most an empty result is valid; the adversarial lens requires at least ten concrete findings and treats an empty list as a signal to re-check; the editorial lenses hold content sacrosanct and critique only how it is organized and expressed.
The lens set is whatever `{workflow.lenses}` resolves to, not a fixed list — overrides add lenses and replace shipped ones. Never claim a capability from this file; read the resolved lenses and work from those.
## Inputs
- **content** — what to review: a diff, branch, uncommitted changes, file, spec, story, or any document. Args: `[path]`.
- **lenses** (optional) — one or more lens codes or names, however the caller expresses them: a spoken request, or a directive of the form `skill:bmad-review lenses=<code>[,<code>...]` (the form bmm's `doc_standards` uses). Default: every applicable lens (a full review).
- **also_consider** (optional) — areas to keep in mind alongside each lens's normal analysis.
- **claims** (optional) — the change's own narrative: the commit messages it covers, or whatever description of it the caller supplied. Goes to the edge-case lens alone.
- **pre-resolved customization** (optional) — `[workflow]` field values supplied by a forwarding caller. See Execution step 1.
## Conventions
- Bare paths (e.g. `references/lens-edge-case-hunter.md`) resolve from `{skill-root}` — this skill's installed directory, where `customize.toml` lives. `{project-root}` resolves to the project working directory.
- `{workflow.<name>}` resolves to fields in `customize.toml`'s `[workflow]` table (overrides win per BMad merge rules).
- In `style_guide`, `review_guidance`, and `persistent_facts`, a value prefixed `file:` is a path or glob — load that file's contents. If a `file:` value cannot be read, name the failed file in the output header and continue: the shipped baseline for `style_guide`, the remaining entries otherwise.
## Execution
1. **Resolve customization:** `uv run {project-root}/_bmad/scripts/resolve_customization.py --skill {skill-root} --project-root {project-root} --key workflow`. On failure, read `{skill-root}/customize.toml` directly and use defaults. **Forwarded activation:** if a caller invoked you with pre-resolved customization fields (e.g. the `bmad-editorial-review` shim), honor them verbatim for those named fields — they already carry the user's overrides — and resolve only the remaining fields from your own `customize.toml`. Then execute each `{workflow.activation_steps_prepend}` entry in order, hold `{workflow.persistent_facts}` as standing context for the session, and treat `{workflow.review_guidance}` entries as standing review directives for every lens.
2. **Load the content.** Stage it once as a file: when the content is a branch, uncommitted work, or a commit range, use the repository's version-control tooling to write the unified diff to a uniquely-named file in the system temp directory and take that file's absolute path as the content. A branch means its diff against the merge base with its base branch; uncommitted work includes untracked files. Stage `claims` to its own file the same way — it is input for one lens, staged separately precisely so the other lenses never see it. If the content is empty or cannot be decoded as text: when the caller expects the raw findings JSON array (e.g. the legacy edge-case forwarder), return `[{"location":"N/A","trigger_condition":"Input empty or undecodable","guard_snippet":"Provide valid content to review","potential_consequence":"Review skipped — no analysis performed"}]` (no `lens` field) and stop; otherwise say what's wrong and ask for reviewable content. Classify the content — diff, source file, function, or document — and whether it is **code** or **docs**; scope rules and lens applicability both depend on it. A document that defines behavior (spec, requirements, plan, story) is `docs` that a behavioral lens may still apply to; judge by `when`.
3. **Select lenses** from `{workflow.lenses}`. A lens with an empty `instruction` is disabled. If the user or caller named lenses, run exactly those only — `applies_to` and `when` do not filter an explicit request. Otherwise run every enabled lens whose `applies_to` covers the content class (`any` always covers) and whose `when` applies.
4. **Announce the plan** in one line before running anything: the content class, the lenses about to run, and — when any lens has `after` set — that it runs on top of the named lens's findings. Skip the announcement entirely when the caller pinned an exact output contract (the legacy forwarders that demand raw JSON or one exact line) — their contract covers everything you emit, not just the findings block. Then execute each `{workflow.activation_steps_append}` entry in order.
5. **Run the independent lenses** — every selected lens without `after`. Each sees the content and `also_consider`, never another lens's findings. Follow each lens's `instruction`; the shipped lenses load their reference file just-in-time, so load only what runs. When subagents are available, launch every independent lens before handling any lens's result. Try running them simultaneously: spawn one per lens; give it the lens `instruction` with `{skill-root}` and paths resolved absolute, the absolute path of the staged content file (a lens prompt carries the path and the lens reads the file, never the content bytes; inline the content only when it was never staged as a file), any `also_consider` areas, the standing review directives, the `claims` path to the edge-case lens alone (marked to leave unread until its instructions call for it), and the constraint "Return ONLY your findings — no other output. Do not invoke any skill, and do not spawn subagents of your own — you are the reviewer. Return your findings as text in your final message; do not route them through any findings-reporting tool the host may offer." Otherwise run the lenses sequentially yourself, completing one before starting the next.
6. **Run the dependent lenses** — every selected lens with `after`, once the lens it names has completed, passing that lens's findings in. A lens whose `after` target was not selected or produced nothing still runs, with no prior findings. Dependent lenses that name different targets are independent of each other: launch every ready one before handling any of their results. Try running them simultaneously. When subagents are available, spawn them with the same constraint as independent lenses: "Return ONLY your findings — no other output. Do not invoke any skill, and do not spawn subagents of your own — you are the reviewer. Return your findings as text in your final message; do not route them through any findings-reporting tool the host may offer."
7. **Assemble and present** per Output below. Keep every lens's findings — overlap between lenses is signal, not duplication; note it in the markdown report rather than deduping. Execute `{workflow.on_complete}` if set.
## Output
One JSON array holding every finding from every lens. Each finding carries:
- `lens` — the code of the lens that produced it
- `location` — where in the content (file:line-range for code, section for documents)
- `trigger_condition` — the problem, or the condition that exposes it, in one line
- `guard_snippet` — the concrete fix, guard, or missing check
- `potential_consequence` — what goes wrong if it ships as-is
Each lens file refines these semantics for its findings and may add lens-specific fields (e.g. `kind`/`confidence` on deletion findings, `gap_shape`/`consumer`/`evidence` on verification-gap findings). A lens file may instead declare its own findings shape and rendering — the editorial lenses render a findings table — and that shape wins for that lens's findings. `[]` is valid when nothing is found. No severity, priority, or ranking anywhere.
Present per `{workflow.output_format}` — `"json"` (the raw array in a fenced json block), `"markdown"`, or `"both"` — unless the caller requested a specific shape; a legacy forwarder's output contract always wins, and governs everything you emit rather than the findings block alone. The markdown report groups findings by lens, each rendered in its declared shape: a short block per finding rendering the fields plus any extras worth surfacing, one line for a lens that found nothing, and a plain clean statement when the whole review is clean. Shape the report per `{workflow.output_preferences}`.
When `{workflow.report_path}` is set, write the report there; otherwise present it in chat.