pr-diagram: diagram a pull request
Goal: one diagram that tells a reviewer what the change does and how it flows, in 10 seconds. It is not a map of the whole codebase.
Guardrails (absolute)
- Never modify code. Don't edit, create, or delete files in the repo, and don't commit,
push, or check out branches. The
.mmdfile goes in a temp or scratchpad directory, never the repo. - Never approve, request changes, or merge. Don't run
gh pr review,gh pr merge, orgh pr close, and don't post PR comments. The only write this skill ever does isgh pr edit --body-fileon the description. - One approval step: show the full new description and ask to post it in the same message. Don't ask "want me to post?" and then show the description afterwards. That makes two approval rounds. Show the whole body, not just the added section, and end the message with the question. "Looks good", "post it", or "yes" to that message counts as approval. Silence, a question, or a requested tweak does not. After a tweak, show the full body and the question again together.
- Sign everything you add with this exact line as the last line of the added block:
- Generated by Claude Code
Arguments
/pr-diagramuses the PR for the current branch, or the local branch diff if no PR exists./pr-diagram 123or a PR URL targets that PR (works for other repos via URL).type=td|lr|sequence|state|erforces a diagram type.
Step 1: gather the diff
With a PR (all read-only):
gh pr view <N> --json number,title,body,url,baseRefName,headRefName,files,additions,deletions
gh pr diff <N> --name-only
gh pr diff <N>
No PR: find the base (gh repo view --json defaultBranchRef -q .defaultBranchRef.name), then
git diff --stat $(git merge-base origin/<base> HEAD) and git diff $(git merge-base origin/<base> HEAD).
Big diffs (>1500 changed lines or >30 files): read --stat and the PR body first, then read
only the files that carry the logic. Skip lockfiles, generated code, snapshots, and pure renames.
Step 2: identify the flow
A diff shows lines, not relationships. Read the current version of each touched file (read only) and work out:
- The flow: what triggers it (request, job, event, user action), what runs in what order, and where it ends (response, DB write, message, external call).
- The status of each step: new (added by this PR), changed (existing, modified), or unchanged (context the reviewer needs to place the change).
- The one-sentence summary a reviewer needs ("adds a retry step before the payment call").
Use the PR title and body as intent, but trust the code where they disagree. Every node and edge must trace to code you read. Never invent a step to make the picture tidier. If something is uncertain, leave it out and say so.
Removed code: if a removed step matters to reviewers, show it as a grey node labelled "(removed)" with a dotted edge. Otherwise leave it out.
Step 3: choose the diagram type
The output is always Mermaid in a .mmd file. Pick the type that matches the flow:
| The change is mainly... | Diagram |
|---|---|
| a step-by-step process or decision logic | flowchart TD (top-down) |
| components or services wiring together, or a pipeline | flowchart LR (left-right) |
| a request or message passing between 3+ participants over time | sequenceDiagram |
| a status or lifecycle change (pending → approved → …) | stateDiagram-v2 |
| tables, columns, or relations (migrations) | erDiagram |
Use one diagram. Use two only if the PR clearly changes both structure and runtime flow. If the PR is too small to need a picture (1–2 files, no new flow), say so and stop.
Step 4: build the diagram
Labels: plain English, short.
- Write what a step does, not code identifiers:
Check card is not expired, notCardValidator.validateExpiry(). When the name helps, use a short form:PaymentReconciliationServicebecomesPayment reconciler. - Shorten URLs to the path:
api.example.com/v2/orders/{id}/refundsbecomesPOST /orders/:id/refunds. - Rectangle nodes
A["..."]: max 35 characters per line. - Stadium
A(["..."])and roundedA("...")nodes: max 25 characters per line. - If a node needs more detail, split it into lines with
<br/>(each line within its limit). Use 3 lines at most. - Shape meaning: rectangle = step or component, stadium = start or end (trigger, response),
rounded = external system, diamond
A{"..."}= decision (25 characters max), cylinderA[("...")]= data store. - Max 15 nodes. Use
subgraphto group by service or area when there are more than about 8. - Label edges briefly in plain English (
sends,on failure,saves), 20 characters max. - Sequence diagrams: participant and actor names max 25 characters. Messages,
loop,alt, andoptlabels, andNotetext max 35 characters per line (split with<br/>, 3 lines at most). Don't use;or#in message text, because they break parsing.
Colors (readable in both GitHub light and dark mode). Use light fills with dark text and a strong border:
classDef new fill:#d3f9d8,stroke:#2b8a3e,stroke-width:2px,color:#0b3d17
classDef changed fill:#fff3bf,stroke:#e67700,stroke-width:2px,color:#4a2b00
classDef unchanged fill:#e9ecef,stroke:#868e96,stroke-width:1px,color:#343a40
class StepA,StepB new
class StepC changed
class StepD unchanged
Every node gets exactly one class. In stateDiagram-v2, use classDef plus class StateName new.
Sequence diagrams: classes don't apply. A rect sets only the background, and the text
color comes from GitHub's theme (light grey in dark mode). An opaque light fill makes the text
unreadable in dark mode, so always use translucent tints:
- new:
rect rgba(46,160,67,0.18) - changed:
rect rgba(210,153,34,0.22) - unchanged: no
rect
Never use opaque rect rgb(...). Add Note over for the key change.
All-new PRs (nothing changed or unchanged): keep the green tint, and also say "Everything in this diagram is new code" in the summary, since there is nothing to contrast it with.
Syntax traps (they break GitHub rendering). Check every one:
- Node IDs must be plain alphanumeric (
ChkCard). Labels must always be quoted:ChkCard["Check card"]. - Use
#quot;for a literal"inside a label.<br/>is the only HTML allowed in labels. - Never use
end(lowercase) as an ID. Always put spaces around arrows (A --> B), becauseA---oBparses as a circle edge. subgraph Id["Label"]…end. Each subgraph needs its ownend.- Sequence participants:
participant API as Orders API(the ID has no spaces). erDiagramattribute types must be single words (varchar, notvarchar(255)).- No
%%{init}%%theme blocks. TheclassDefcolors handle both modes.
Save the diagram as pr-<N>-diagram.mmd (or branch-<name>-diagram.mmd) in a temp or
scratchpad directory. Give the full path.
Step 5: self-check before presenting
- Count the characters on every label line against its limit (35 for rectangles, 25 for stadium, rounded, and diamond nodes, 20 for edge labels; in sequence diagrams, 25 for participants and 35 for messages, blocks, and notes). Fix any that are over.
- Make sure no label contains a raw code identifier (camelCase,
Foo.bar(), snake_case) where plain English works. - Check each node's color: is it really new, changed, or unchanged in the diff?
- Optional render check:
npx -y @mermaid-js/mermaid-cli -i <file>.mmd -o <file>.svg. The first run downloads Chromium (~150 MB), so ask before running it.
Step 6: present
Use this format in chat:
**<one-sentence summary of what the PR does>**
<2–3 sentences: the flow in words, where the change sits in it, anything left out or uncertain>
```mermaid
...
```
**Legend:** green = new code · yellow = changed code · grey (or no tint) = unchanged context
Saved: <full path to .mmd>
Step 7: show the full description and ask to post (same message as Step 6)
Do this before replying, so the diagram, the full new description, and the question all go out together:
-
Fetch the current body to a temp file:
gh pr view <N> --json body -q .body > <tmp>/body-old.md -
Build the new body in
<tmp>/body-new.md. Put the block between markers so reruns replace it instead of stacking:<!-- pr-diagram:start --> ## Change diagram <summary sentence> ```mermaid ...Legend: green = new · yellow = changed · grey (or no tint) = unchanged (Use words, not color emoji. Emoji render as different colors on each OS, e.g. ⬜ shows as lavender on Windows.)
- Generated by Claude Code
If the markers already exist, replace only the text between them. Otherwise append the block after a blank line. Keep every other byte of the original body unchanged. -
Check that the new body starts with the full original body. It must be preserved byte for byte.
-
End the message with the full new description in a fenced block, the PR URL, and the question: "Post this to ?" Then stop and wait (Guardrail 3).
Step 8: post (only after a yes to Step 7's message)
gh pr edit <N> --body-file <tmp>/body-new.md. Never use--bodywith inline text, because shell quoting mangles backticks and$.- Verify with
gh pr view <N> --json body -q .bodythat it matchesbody-new.md, then give the PR URL. Ignore trailing whitespace when comparing, because-qadds a newline. For example, compare.rstrip()of both in Python.
No PR yet (local branch only)? Offer the block to paste when the user opens the PR. Don't create the PR.
Don'ts
- Don't diagram every file. A diagram of everything shows nothing.
- Don't put secrets, internal hostnames, full URLs with tokens or query strings, or customer data in labels.