Review Walkthrough
Trail of BitsOfficialPublished by Trail of Bits
- Skill
- Content generator
- Software development
- CC-BY-SA-4.0
- Low risk
- Has scripts
AutoGineer summary
Written by AutoGineer from the skill’s own files, not by the author
The review-walkthrough skill creates a self-contained, interactive HTML document that helps developers understand complex code changes. It captures the diff between a branch and its base, organizes the changes into logical, concept-based steps, and provides detailed explanations and review findings for each. The resulting artifact is designed for clear communication, allowing reviewers to navigate through code changes in a structured way that prioritizes comprehension over raw commit order.
What it does
- Captures a complete git diff between a branch and a specified base.
- Groups related file changes into logical steps for better readability.
- Generates HTML explanations for each step, detailing purpose and design choices.
- Identifies and documents review findings such as bugs, security issues, or performance concerns.
- Anchors findings to specific lines in the diff for precise feedback.
- Renders a final, interactive HTML walkthrough file for browser-based review.
When to use it
- When you need to present a complex set of changes to a team for review.
- When you want to provide context and design rationale alongside code diffs.
- When you need to highlight specific security or performance findings within a PR.
- When you want to improve the quality and efficiency of the code review process.
Advantages
- Improves comprehension by organizing changes by concept rather than commit order.
- Provides a structured format for documenting design decisions and trade-offs.
- Enables precise, anchored feedback on specific lines of code.
- Creates a professional, shareable artifact for team collaboration.
Usage examples
- “/review-walkthrough:review-walkthrough”
- The agent analyzes the current branch, generates a structured HTML walkthrough of the changes, and provides the path to the resulting file.
Install
Download the skill as a ZIP:
https://mp-staging.autogineer.com/agent-skills/trailofbits/review-walkthrough/downloadUnzip it into the cross-client skills folder of your project:
mkdir -p .agents/skills && unzip review-walkthrough.zip -d .agents/skills
Documentation by Trail of Bits
Review Walkthrough
Generate a self-contained HTML walkthrough of the current branch, with the final
diff split into logical steps, explanations, and critical review findings. Choose
the grouping and reading order for comprehension; commit order need not dictate
either. Invoke as /review-walkthrough:review-walkthrough in Claude Code or
$review-walkthrough in Codex.
Capture the branch diff
Respect a user-specified base. Otherwise, use the current open PR's base when PR
metadata is available. Without a PR, discover the repository's default branch
from git symbolic-ref --quiet --short refs/remotes/origin/HEAD or the configured
remote's equivalent. Do not assume it is main. If the selected base is missing
or ambiguous, ask for it rather than silently choosing another branch.
Resolve the base and HEAD to commit IDs with
git rev-parse --verify --end-of-options "${ref}^{commit}", then compute their
merge base with git merge-base. Capture the complete patch using
git diff --no-ext-diff --no-textconv --no-color --src-prefix=a/ --dst-prefix=b/ "$merge_base" "$head_sha" --.
Initialize variables and run the commands that consume them in the same shell
invocation; shell variables do not persist between tool calls. Save the patch to
a temporary file outside the checkout and retain its actual path. Stop on a Git
error or an empty patch and explain the result.
This scope includes committed changes through the captured HEAD. Mention any
uncommitted work that is excluded. Do not change branches, reset the checkout,
or alter source files to prepare the review. Keep generated data and HTML outside
the checkout unless the user requests a particular output location; generated
review artifacts never belong in the captured patch.
For a GitHub PR, collect owner, repo, pr_number, and head_sha from its
metadata. Include them only when the PR head matches the captured HEAD and the
chosen base matches the PR base. Otherwise use null and explain why comment
export is unavailable. A failed authentication or network request is not evidence
that no PR exists; report the failure and ask for the base if it cannot be
determined. GitHub access is optional when the user supplies the base or confirms
there is no PR.
Shape the review
Read the changed files and the surrounding source, tests, configuration, and dependency metadata needed to judge them. Keep the review read-only; do not run the project's tests or install its dependencies merely to build the walkthrough.
Group related files into steps covering one concept each. Put definitions before their consumers, wiring after the components it connects, and tests after or beside their subjects. Copy each complete per-file diff from the captured patch verbatim into exactly one step. Reordering files between steps is allowed; splitting, rewriting, omitting, or inventing their patches is not. Preserve rename, binary, and mode-change entries even when they have no text hunks. Binary summaries identify changed files; their payloads are outside this review.
Write one explanation per step, usually 50–150 words, covering the change's purpose, design choices, trade-offs, and connections to other steps. Refer to actual identifiers. Write one review list per step covering bugs, security, validation, API design, or performance issues supported by the code. Report findings with severity rather than suppressing minor issues. Use an empty list for a step with no findings.
Explanations and review bodies are HTML fragments. Use <p>, <strong>, <em>,
<code>, <pre>, and <ul>/<li> for structure. Write literal < and > in
prose or snippets as < and >. Backticks and Markdown fences are literal
text here. Supported inline tags also include <sup>, <sub>, <kbd>, <del>,
and <a href="https://…">. The page sanitizes fragments and converts them to
Markdown when preparing a PR comment. Only safe link targets survive; arbitrary
attributes, scripts, and images do not. Tables export as text rows with cell
separators; captions and row order are preserved. Prefer prose, lists, and code
blocks when their structure is sufficient.
Anchor findings to a file in the same step and a line in that file's displayed
diff. Use side: "RIGHT" for additions or new-file context and side: "LEFT"
for deletions or old-file context. For a range, line and end_line use that
same side within one hunk. A finding spanning multiple steps belongs with the
file it addresses, or remains unanchored. An unanchored finding is still
displayed but cannot become an inline PR comment.
Render the artifact
Use a file-writing tool to create a JSON object with the fields below. Preserve the literal patch as JSON string data, with no shell expansion.
| Field | Value |
|---|---|
title | Feature or review title |
steps | Array of objects with sha (step ID such as step-1), message (step title), files (paths in patch order), and diff (complete per-file patches) |
explanations | HTML strings, one per step |
reviews | Arrays of findings, one per step; each finding has severity (high, medium, or low), title, and HTML body |
pr_meta | Object with owner, repo, pr_number, and head_sha, or null |
An anchored finding also has file, line, and side, plus optional end_line.
The three arrays have equal lengths and corresponding entries. File paths match
the diff headers without their a/ or b/ prefix; a renamed file uses its new
path. Set side explicitly so lines that occur on both sides are unambiguous.
Run the bundled renderer with the actual paths created for this review:
uv run --no-project {baseDir}/scripts/render_walkthrough.py \
--input /tmp/data.json \
--diff /tmp/captured.patch \
--output /tmp/walkthrough.htmlThe renderer validates the data, compares every step's patches with the complete captured diff, checks anchors, and safely embeds the result in the bundled template. Fix reported input errors rather than bypassing the renderer or generating an alternative page.
Open the output with open on macOS or xdg-open on Linux when a browser is
available, and tell the user its path. In a headless run, report the file without
opening it. When PR metadata is present, the page lets the user copy a gh api
command for their selected comments. It does not execute the command or post
anything to GitHub. Comment and Request Changes require a review summary before
the command can be copied; the summary is optional for Approve.
Files
- ATTRIBUTION.mdAdded by AutoGineer948 B
- LICENSELicence file added by AutoGineer19.7 KiB
- SKILL.md6.6 KiB
- agents/openai.yaml234 B
- scripts/pyproject.toml110 B
- scripts/render_walkthrough.pyScript10.0 KiB
- template.html54.7 KiB
scripts/render_walkthrough.py
#!/usr/bin/env python3
# /// script
# requires-python = ">=3.11"
# dependencies = []
# ///
"""Validate a walkthrough against a captured Git patch and render standalone HTML."""
import argparse
import html
import json
import re
import subprocess
import tempfile
from collections import Counter
from pathlib import Path
HUNK = re.compile(r"^@@ -(\d+)(?:,\d+)? \+(\d+)(?:,\d+)? @@")
TEMPLATE = Path(__file__).resolve().parent.parent / "template.html"
def read_text(path):
# Preserve CRLF inside patch content; universal-newline conversion changes the evidence.
return path.read_bytes().decode("utf-8")
def text_field(value, key, context):
result = value.get(key)
if not isinstance(result, str) or not result.strip():
raise ValueError(f"{context}.{key} must be a nonempty string")
return result
def split_diff(patch):
if not isinstance(patch, str) or not patch.startswith("diff --git "):
raise ValueError("Expected a nonempty Git unified diff starting with 'diff --git '")
return re.split(r"(?=^diff --git )", patch, flags=re.MULTILINE)[1:]
def patch_paths(patch, count):
# --numstat parses paths using Git's own quoting rules without applying the patch.
result = subprocess.run(
["git", "apply", "--numstat", "-z", "--"],
input=patch.encode("utf-8"),
capture_output=True,
cwd=tempfile.gettempdir(),
check=False,
)
if result.returncode:
detail = result.stderr.decode("utf-8", errors="replace").strip()
raise ValueError(f"Git could not parse the captured patch: {detail}")
records = result.stdout.decode("utf-8").split("\0")
if records[-1] != "" or len(records) - 1 != count:
raise ValueError("Git did not return one path per diff block; recapture the complete patch")
paths = [record.split("\t", 2)[2] for record in records[:-1]]
if len(set(paths)) != len(paths):
raise ValueError("The captured patch contains duplicate file paths")
return paths
def diff_lines(block):
"""Return the line numbers and hunk IDs exposed in the unified diff gutter."""
lines = {"LEFT": {}, "RIGHT": {}}
old = new = 0
hunk = 0
for line in block.split("\n"):
match = HUNK.match(line)
if match:
old, new = map(int, match.groups())
hunk += 1
elif hunk and line.startswith("+"):
lines["RIGHT"][new] = hunk
new += 1
elif hunk and line.startswith("-"):
lines["LEFT"][old] = hunk
old += 1
elif hunk and line.startswith(" "):
lines["LEFT"][old] = hunk
lines["RIGHT"][new] = hunk
old += 1
new += 1
return lines
def positive_integer(value):
return type(value) is int and value > 0
def review_anchor(review, files, context):
if "file" not in review:
if any(key in review for key in ("line", "end_line", "side")):
raise ValueError(f"{context}: an anchor needs a file and line")
return {}
path = text_field(review, "file", context)
if path not in files:
raise ValueError(f"{context}: {path!r} is not a file in this step")
start = review.get("line")
end = review.get("end_line", start)
if not positive_integer(start) or not positive_integer(end) or end < start:
raise ValueError(f"{context}: line and end_line must form a positive, ordered range")
candidates = []
for side, numbers in files[path].items():
if start not in numbers or end not in numbers or numbers[start] != numbers[end]:
continue
if sum(start <= number <= end for number in numbers) == end - start + 1:
candidates.append(side)
side = review.get("side")
if side is None and len(candidates) == 1:
side = candidates[0]
if side not in candidates:
raise ValueError(
f"{context}: anchor {path}:{start}-{end} is missing or ambiguous; "
"choose LEFT for deletions or RIGHT for additions/context within one hunk"
)
result = {"file": path, "line": start, "side": side}
if end != start:
result["end_line"] = end
return result
def normalize_reviews(reviews, files, context):
if not isinstance(reviews, list):
raise ValueError(f"{context} must be an array (use [] for no findings)")
normalized = []
for index, review in enumerate(reviews):
location = f"{context}[{index}]"
if not isinstance(review, dict):
raise ValueError(f"{location} must be an object")
severity = review.get("severity")
if severity not in ("high", "medium", "low"):
raise ValueError(f"{location}.severity must be high, medium, or low")
normalized.append(
{
"severity": severity,
"title": text_field(review, "title", location),
"body": text_field(review, "body", location),
**review_anchor(review, files, location),
}
)
return normalized
def normalize_pr(meta):
if meta is None:
return None
if not isinstance(meta, dict):
raise ValueError("pr_meta must be an object or null")
for field in ("owner", "repo"):
value = text_field(meta, field, "pr_meta")
if not re.fullmatch(r"[A-Za-z0-9][A-Za-z0-9_.-]*", value):
raise ValueError(f"pr_meta.{field} must contain only a GitHub owner or repository name")
if not positive_integer(meta.get("pr_number")):
raise ValueError("pr_meta.pr_number must be a positive integer")
sha = text_field(meta, "head_sha", "pr_meta")
if not re.fullmatch(r"[0-9a-fA-F]{40}", sha):
raise ValueError("pr_meta.head_sha must be the full GitHub pull-request head SHA")
return {key: meta[key] for key in ("owner", "repo", "pr_number", "head_sha")}
def normalize_data(data, patch):
if not isinstance(data, dict):
raise ValueError("Walkthrough input must be a JSON object")
title = text_field(data, "title", "walkthrough")
steps = data.get("steps")
if not isinstance(steps, list) or not steps:
raise ValueError("steps must be a nonempty array")
for key in ("explanations", "reviews"):
if not isinstance(data.get(key), list) or len(data[key]) != len(steps):
raise ValueError(f"{key} must have exactly one entry per step")
blocks = split_diff(patch)
paths = patch_paths(patch, len(blocks))
originals = dict(zip(blocks, paths, strict=True))
if len(originals) != len(blocks):
raise ValueError("The captured patch contains duplicate diff blocks")
seen = []
normalized_steps = []
normalized_reviews = []
for index, step in enumerate(steps):
context = f"steps[{index}]"
if not isinstance(step, dict):
raise ValueError(f"{context} must be an object")
diff = text_field(step, "diff", context)
step_blocks = split_diff(diff)
if any(block not in originals for block in step_blocks):
raise ValueError(f"{context}: copy each complete file diff verbatim from the patch")
step_paths = [originals[block] for block in step_blocks]
if step.get("files") != step_paths:
raise ValueError(f"{context}.files must match the paths and order in this step's diff")
explanation = data["explanations"][index]
if not isinstance(explanation, str) or not explanation.strip():
raise ValueError(f"explanations[{index}] must be a nonempty HTML string")
normalized_steps.append(
{
"sha": f"step-{index + 1}",
"message": text_field(step, "message", context),
"files": step_paths,
"diff": diff,
}
)
files = {originals[block]: diff_lines(block) for block in step_blocks}
normalized_reviews.append(
normalize_reviews(data["reviews"][index], files, f"reviews[{index}]")
)
seen.extend(step_blocks)
if Counter(seen) != Counter(blocks):
raise ValueError(
"Missing or repeated files: each captured file diff must appear in exactly one step"
)
return {
"title": title,
"steps": normalized_steps,
"explanations": data["explanations"],
"reviews": normalized_reviews,
"pr_meta": normalize_pr(data.get("pr_meta")),
}
def render(data, patch, template=None):
data = normalize_data(data, patch)
template = read_text(TEMPLATE) if template is None else template
replacements = {"TITLE_PLACEHOLDER": html.escape(data["title"])}
for key in ("steps", "explanations", "reviews", "pr_meta"):
replacements[f"{key.upper()}_PLACEHOLDER"] = json.dumps(data[key]).replace("<", r"\u003c")
for placeholder in replacements:
expected = 2 if placeholder == "TITLE_PLACEHOLDER" else 1
if template.count(placeholder) != expected:
raise ValueError(f"Template must contain {expected} occurrence(s) of {placeholder}")
# One pass prevents placeholder-like source text from being substituted recursively.
pattern = "|".join(replacements)
return re.sub(pattern, lambda match: replacements[match[0]], template)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--input", required=True, type=Path, help="Walkthrough JSON")
parser.add_argument("--diff", required=True, type=Path, help="Complete captured Git patch")
parser.add_argument("--output", required=True, type=Path, help="Standalone HTML output")
args = parser.parse_args()
try:
if args.output.resolve() in (args.input.resolve(), args.diff.resolve(), TEMPLATE):
raise ValueError("Choose an output path different from the input, patch, and template")
data = json.loads(read_text(args.input))
page = render(data, read_text(args.diff))
args.output.write_text(page, encoding="utf-8")
except (OSError, UnicodeError, ValueError) as exc:
parser.exit(1, f"Cannot render walkthrough: {exc}\n")
print(args.output.resolve())
if __name__ == "__main__":
main()
Requirements and compatibility
Written for: Claude Code
Works with: Claude Code, Claude apps, OpenAI Codex, GitHub Copilot, Cursor, Gemini CLI, Kiro, OpenCode, Goose, Amp, Roo Code, JetBrains Junie, Factory Droid, Devin (ex-Windsurf), Mistral Vibe, OpenHands, Letta
“Works with” means the tool reads the open Agent Skills format; a skill written for one tool may use features others lack.
Needs: Claude Code frontmatter, Needs Python
Security
What our scanner noticed· Low risk
- Scripts that your agent may run
This skill includes scripts that your agent may run. Read them before you use it.
A static scan is not a guarantee. Skills are third-party content: review a skill before you let an agent use it.
Attribution and licence
- Published by
- Trail of Bits
- Publisher
- Trail of Bits (Official)
- Source
- trailofbits/skills · plugins/review-walkthrough/skills/review-walkthrough · commit e4dd0bb
- Licence
- Creative Commons Attribution-ShareAlike 4.0 International (redistribution allowed)
- LICENSE (added by AutoGineer from LICENSE)
- ATTRIBUTION.md (written by AutoGineer)
- Synced
AutoGineer is not affiliated with or endorsed by Trail of Bits.
Download ZIP
The ZIP holds the skill’s files, its licence files and an ATTRIBUTION.md. Download review-walkthrough.zip