bmod.toml
[skill] bmod = "bmod-core-tools" source = "github:bmad-code-org/BMAD-METHOD/skills"
bmad-code-org/bmad-method · GitHub
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.
프로젝트 폴더에서 아래 명령어를 실행하고, 설치할 에이전트를 선택하세요.
npx skills add bmad-code-org/bmad-method --skill bmad-review설치 명령을 직접 실행해야 적용됩니다. 지원 에이전트와 필요한 권한·라이선스는 제작자의 안내를 확인하세요.
bmod.toml[skill] bmod = "bmod-core-tools" source = "github:bmad-code-org/BMAD-METHOD/skills"
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 tickets, plans, and requirements 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."
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 behavior this change altered that could break later without any test failing. Do not hunt for bugs; report the ones you run into while tracing. A gap finding is a request to add or change one test. File it only when you can name a specific regression that test would catch. If no such test is worth writing, there is nothing to file. Gap shapes: 1. **Regression gap:** the changed code could regress where it is used, and no test would fail. 2. **Missing-adoption gap:** a site that should use the new behavior still handles the case its own way, and no test would catch that. 3. **Broken-verification gap:** a test looks like it covers the change but does not: it is skipped, flaky, not run normally, or too weak to see the regression. 4. **Stale-verification gap:** a test this change made wrong or moot. It may still pass. ## Evidence rules - Read a test before saying what it covers or misses. - Before saying no test exists, search the repo for the symbol under test and its imports. Expected file locations are not enough. - Say what you checked and how far you looked. Drop any finding you cannot ground. - Do not assign severity, confidence, priority, or ranking. ## Sequence ### Step 1: Screen Take each part of the change separately. Skip a part that changes no behavior: no change to return values, thrown errors, side effects callers can see, or observable state (including iteration order and emitted messages). Formatting, comments, renames, trivial getters and pass-throughs, and type-only changes are examples. Once a part is skipped, do not look at its callers or tests. Also skip parts that are not worth a test: static text such as prompts, skills, and documents; LLM output; and build, toolchain, dependency, and configuration changes that the build or CI run itself checks. Deterministic code that builds a prompt or request, or handles a model's response, is still eligible; the model call itself is not, and existing tests that call a model are not precedent for more. Do not skip test-only parts. A deleted or weakened test is checked in Step 4; every touched test is read in Step 5. If every part is skipped, 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. ### Step 2: Name the changed behavior For each remaining part, say what behavior differs from before: output, side effect, branch, error path, schema or event shape, default, validation rule, external contract. Handle each behavior separately. ### Step 3: Find where it is used Trace each changed behavior to the code that observes it: direct callers, registered entry points (routes, commands, DI), and contract consumers (schemas, events, APIs, database readers). Stop a path when a test there would catch a regression, when the consumer does not observe the change, or when the next hop is a guess (dynamic dispatch, reflection, code outside the repo). One to three hops is usually enough. With more than five similar consumers, check representative ones and expand only when a consumer uses the behavior differently. ### Step 4: Name the regression, then check the test For each consumer, name the smallest realistic regression it would see: the branch inverted, the default dropped, the field omitted, the old error code returned, the integration call skipped. This is the Demonstration. It describes what goes wrong for the consumer. "This line could be removed without a test failing" is not a regression. If there is no regression (the state is unreachable, the branch is defensive, the code repeats what another line already guarantees), drop the path. There is no finding and nowhere else to file it. A missing-adoption gap needs two things: evidence the change means the new behavior to replace the local one (PR intent, naming or docs, a replaced sibling site, deleted duplicate logic, a test defining the new rule), and the same observable contract at both sites. Without both, it is a refactor suggestion, not a finding. With both, missing coverage of the non-adoption is the gap. Read the relevant test. Would the Demonstration make an assertion fail? - Yes: the behavior is verified. No finding. - No test runs the path, or the test is skipped, flaky, or not run normally, or it runs the code without checking the changed result: report a regression gap or broken-verification gap. - No test asserts the site adopts the new behavior: report a missing-adoption gap. A test counts only when it runs normally and an assertion observes the changed output, branch, or contract. These do not count: assertions on source text; success, no-throw, or snapshot-only checks; mock or log-call checks; manual checks; tests that mock away the integration; end-to-end 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: a helper test covers the branch but caller values skip it; a payload or schema change is not checked at the consumer; migration tests only create new-format rows; a handled partial-failure path has no test; a deleted or weakened test leaves behavior unpinned (deleting a source-text assertion is not this). ### Step 5: Check the touched tests A test is wrong when what it asserts is not what the code should do after this change. A test or test comment is moot when it no longer exercises or describes anything. Report either as a stale-verification gap, saying what the test should assert instead, or that it should go. ### Step 6: Confirm Before writing a finding, re-open the tests or search results it relies on. Check that the Demonstration names a regression and no test you read would catch it, or that the stale assertion pins the outcome you say it does. Explain why the test misses the regression from what it sets up and checks. Do not report: cases the compiler or type checker enforces; behavior an integration, contract, or end-to-end test already verifies; low coverage or a missing test file by itself; untested code the change did not touch. Defects you ran into while tracing are reported with `gap_shape: "other"`. Do not go looking for more. ## Findings shape Emit each gap with the canonical fields plus this lens's extras: - `location` — the behavior or contract that changed, `file:line` - `trigger_condition` — the gap, in one line - `guard_snippet` — the test to add or change: the assertion or check that is absent, or how the stale assertion should read, fit to how this repo already tests - `potential_consequence` — the regression, and why the tests you read would not fail; for a missing-adoption gap, the case the site mishandles; for a stale-verification gap, what the code should do, and why the test does not say so - `gap_shape` — `"regression-gap"`, `"missing-adoption-gap"`, `"broken-verification-gap"`, `"stale-verification-gap"`, or `"other"` - `consumer` — the impacted consumer or site, named concretely with `file:line`, not "callers of this function" - `evidence` — what the relevant test asserts, with `file:line`; or the searches run and their result; for a broken-verification gap, why the apparent test does not count; for a stale-verification gap, the assertion that is wrong or moot 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_korean_counts_per_spaced_word(self):
self.assertEqual(word_count("나는 학교에 갑니다"), 3)
def test_chinese_and_japanese_count_per_character(self):
self.assertEqual(word_count("我去学校"), 4)
self.assertEqual(word_count("私は学校に行きます"), 9)
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
Chinese or Japanese character since those scripts do not space-delimit words.
Korean spaces its words, so Hangul counts per token. 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__":
if sys.platform == "win32":
# Piped output on Windows defaults to a legacy code page, not UTF-8.
sys.stdout.reconfigure(encoding="utf-8")
sys.stderr.reconfigure(encoding="utf-8")
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, ticket (initiative, epic, story, spike, bug), 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}` is the nearest folder containing `_bmad/`, starting at the project working directory and moving up through its parents.
- `{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`.
- Script not found: BMad is not set up here. Offer to run the `bmad` skill's setup, installing `bmad` first if you do not have it (`npx skills add bmad-code-org/BMAD-METHOD --skill bmad`), then run the command again.
- Any other 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 (a ticket, a plan, requirements) 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.