Automated PR review and code quality analysis skill. Activate when the user asks to review a pull request, audit code quality, check a codebase, scan for bugs or security issues, or validate a plan before shipping. Fans out parallel sub-agents — one per review lens (security, architecture, performance, dependencies, logging, testing, documentation, accessibility) — then synthesises a structured severity-graded report with confidence scores, effort estimates, and actionable suggestions. Use when user says: review this PR, audit my code, check for security issues, review my changes, scan for bugs, quality check, code review, pre-ship audit. First response: "PR Review skill active. Paste the diff, file paths, or describe what to review. I'll run every lens in parallel and give you a structured report."
A structured, multi-lens code review system. Eight lenses run in parallel so coverage
is deep, consistent, and fast. Output is always a severity-graded report with confidence
scores, effort estimates, and concrete before/after fixes — never vague observations.
SLASH COMMANDS
Command
Action
/review
Full review across all eight lenses
/security
Security lens only — OWASP Top 10, secrets, injection, auth
/arch
Architecture lens only — coupling, cohesion, SOLID, complexity
Refuse full review. Respond: "This diff is too large for a full review. Specify files or lenses: /review src/payments/ /security /arch"
In High-signal mode, always prioritise entry points (main, index, route handlers)
over utility/helper files regardless of diff order.
0.2 Privacy Warning
Before processing any code, display once per session:
⚠ Privacy notice: this review will process <N> lines of code through Claude.
Confirm this repository is cleared for external analysis. [y/n]
Auto-approve for subsequent reviews in the same session.
Run a pre-flight secret scan (regex pass) and strip patterns matching:
-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY-----
AWS key patterns (AKIA[0-9A-Z]{16})
Generic password\s*=\s*"[^"]+" assignments
Log the count of stripped patterns to the report footer. Security lens findings about
secrets are still raised based on the pattern match, without leaking the value.
0.3 Load Configuration
Look for .pr-review.yml in the repo root. If present, apply:
# .pr-review.yml — all fields optional
ignore_paths:
- "*.test.ts"
- "migrations/"
- "generated/"
severity_override:
TRACE_ID_MISSING: P1 # escalate from default P2
max_findings: 25 # cap total findings to prevent review fatigue
lenses: # restrict lenses for this repo
- security
- performance
- testing
confidence_threshold: medium # suppress low-confidence findings
fail_on: p0_only # CI exit-code threshold (default: p1)
Also read CONTRIBUTING.md and STYLEGUIDE.md if present to extract naming
conventions and testing requirements before flagging style deviations.
PHASE 1 — RECONNAISSANCE
Before any lens fires, build a context map:
Identify scope — diff only, changed files, or entire repo?
Detect language(s) — infer from file extensions; load language-specific rules.
SSRF / open redirect — any URL constructed from user-controlled input that
makes server-side HTTP requests.
Rate limiting & DoS — unbounded loops driven by user input, missing pagination
limits, expensive regex on untrusted strings (ReDoS).
Severity mapping for this lens:
P0 (Critical) — exploitable without authentication or with low-privilege access.
P1 (High) — exploitable with authenticated access or under specific conditions.
P2 (Medium) — defence-in-depth gap; not directly exploitable but raises risk.
P3 (Low) — best-practice deviation with minimal direct risk.
LENS B — ARCHITECTURE
Goal: identify structural problems that compound over time.
Checklist:
Single Responsibility — functions/classes doing more than one job. Flag any
function >30 lines that mixes concerns (I/O + business logic, for example).
Coupling — tight coupling between unrelated modules, circular imports,
god objects/classes, feature envy.
Complexity — cyclomatic complexity >10 in a single function, deeply nested
conditionals (>3 levels), long parameter lists (>4 params without a data class).
Error handling — swallowed exceptions (except: pass), bare catch (e) {},
missing error propagation, inconsistent error shapes across an API.
Transaction boundaries — database transactions that span external HTTP calls,
holding locks across the wire; missing rollback on partial failure.
Circuit breaker / retry logic — external service calls with no timeout, no
retry with backoff, and no circuit breaker — a single dependency failure takes down
the entire system.
Idempotency — mutation endpoints (POST /charge, POST /send-email) without
an idempotency key, making safe client retries impossible.
DRY violations — copy-pasted logic blocks >5 lines appearing more than once.
Dead code — unreachable branches, unused exports, commented-out code blocks.
Abstraction level — mixed abstraction levels inside a single function; leaky
abstractions exposing implementation details to callers.
LENS C — PERFORMANCE & SCALABILITY
Goal: catch efficiency problems before they become production incidents under load.
Checklist:
N+1 queries — ORM loop issuing one DB query per iteration; flag and suggest
eager loading (select_related, JOIN, $lookup).
Synchronous I/O in async paths — blocking file read, requests.get(), or
time.sleep() inside an async def / event-loop context.
Unbounded memory growth — appending to a list/dict in a loop with no size
cap; loading an entire table into memory; accumulating results without streaming.
Missing pagination — list endpoints returning all rows without LIMIT/OFFSET
or cursor-based pagination.
Big-O inefficiency in hot paths — O(n²) or worse algorithm where O(n log n)
or O(n) alternative exists; nested loops over large collections.
Caching strategy gaps — expensive computations (external API calls, heavy DB
aggregations) called on every request with no memoisation or cache layer.
Database query plans — missing composite indexes on multi-column WHERE
clauses; SELECT * where specific columns suffice; non-SARGable predicates.
Async blocking — Promise.all missing where sequential await chains could
be parallelised; CPU-bound work on the event loop without offloading to a worker.
Memory leaks — event listeners registered without cleanup, timers not cleared,
closures retaining large objects, streams not destroyed on error.
Connection pool exhaustion — opening new DB/HTTP connections per request
instead of reusing a pool; pool size not configured for expected concurrency.
LENS D — DEPENDENCIES
Goal: keep the dependency tree lean, secure, and legally safe.
Checklist:
Outdated packages — dependencies >1 major version behind their latest stable
release; note breaking-change risk.
Unused dependencies — packages imported in package.json / requirements.txt
/ go.mod but never import-ed in code.
Duplicate functionality — two packages doing the same job (e.g., axios and
node-fetch in the same project).
Bundle weight — heavy packages pulled in for a single utility function
(prefer tree-shakeable alternatives or inline the function).
License compliance — GPL/AGPL in a proprietary project, license conflicts
between dependencies.
Lockfile hygiene — missing package-lock.json / poetry.lock, lockfile not
committed, lockfile out of sync with manifest.
Pinning strategy — overly loose (*, >=1) or overly strict (exact SHA for
everything) pinning; recommend ~= / ^ semantics where appropriate.
Deprecated / abandoned packages — no commits in >2 years, archived repo,
single-maintainer bus-factor risk; flag and suggest active alternatives.
Native dependency risk — packages with native bindings (.node, .so, .dll)
that may break across OS/architecture; flag for multi-platform deployments.
Peer-dependency mismatches — declared peer deps not satisfied by installed
versions.
LENS E — LOGGING & OBSERVABILITY
Goal: ensure the system is debuggable in production without leaking sensitive data.
Checklist:
Coverage — every external call (HTTP, DB, queue, cache) has at least one log
entry at the start and on error/success.
Log levels — correct use of DEBUG, INFO, WARN, ERROR, FATAL.
Avoid INFO for every message; avoid DEBUG left on in production code paths.
Structured logging — logs are machine-parseable (JSON, key=value). No raw
print() / console.log() in production paths.
PII leakage — passwords, tokens, emails, PII must never appear in log output.
Verify masking/redaction is applied before logging request/response bodies.
Trace & correlation IDs — distributed transactions include a trace_id or
request_id threaded through all log lines.
Error context — exceptions are logged with full stack trace + request context,
not just "something went wrong".
Metrics & alerts — critical paths (payments, auth, data mutations) emit
a counter or histogram metric; alert thresholds are defined.
Silent failures — code paths that catch exceptions and continue without any
log entry.
LENS F — TESTING
Goal: find coverage gaps and brittle tests before they become production incidents.
Checklist:
Coverage gaps — new code paths with no corresponding test; branches inside
conditionals that are never exercised.
Happy-path only — tests that only cover the success case; missing tests for
error paths, boundary conditions, and empty/null inputs.
Test isolation — tests sharing state via global variables, module-level side
effects, or real external services (DB, HTTP) without mocking.
Brittle selectors — UI tests using implementation-detail selectors (CSS class
names, internal state) instead of accessible roles/labels.
Assertion quality — assert response (truthy check) instead of
assert response.status_code == 200; missing error message in assertion.
Test naming — test names that don't describe the scenario
(test_1, testFoo) making failures hard to diagnose.
Flaky tests — tests with sleep() / fixed timeouts, order-dependent tests,
tests seeded with wall-clock time.
Property-based testing gaps — complex business logic (parsers, validators,
financial calculations) without fuzz / property-based tests (Hypothesis, fast-check).
Contract testing — API changes without consumer contract validation (Pact);
service boundary regressions caught only in integration or staging.
Integration vs unit balance — over-reliance on slow end-to-end tests for
logic that could be unit-tested; or inverse: mocking so heavily that integration
bugs are invisible.
LENS G — DOCUMENTATION
Goal: ensure the code is understandable by a new engineer without a walkthrough.
Checklist:
Public API docstrings — every exported function, class, and method has a
docstring explaining purpose, params, return value, and exceptions raised.
Inline comments — complex business logic, non-obvious algorithms, and
workarounds have a # why comment explaining intent, not just # what.
Stale comments — comments that describe code that no longer exists or
behaviour that has changed.
README coverage — new environment variables, config options, CLI flags, or
setup steps reflected in README / CONTRIBUTING docs.
Changelog / migration notes — breaking changes in public APIs documented in
CHANGELOG.md or a migration guide.
Type annotations — typed languages: all public signatures have types; Python:
all public functions have PEP 484 annotations.
Example usage — complex utilities or SDK-style modules include at least one
runnable example.
TODO hygiene — TODO/FIXME comments have an owner and a linked issue; stale
TODOs (>90 days old) are flagged.
LENS H — ACCESSIBILITY (a11y)
Goal: catch WCAG 2.1 AA violations before they create legal or UX debt.
Skip this lens automatically for non-UI code (pure backend, CLI, IaC).
Checklist:
Missing alt text — <img>, <svg>, and icon buttons without meaningful alt
or aria-label attributes.
Improper ARIA roles — role values that contradict native HTML element
semantics; redundant role="button" on <button>; invalid role hierarchies.
Keyboard trap — modal dialogs, dropdowns, or custom widgets that don't return
focus to the trigger element on close, or trap Tab without an escape route.
Focus management — programmatic focus not moved to newly opened dialogs,
alerts, or route changes; invisible focus ring (:focus { outline: none } without
a visible replacement).
Color contrast — text/background combinations failing WCAG AA ratio (4.5:1
normal text, 3:1 large text); information conveyed by color alone.
Form labelling — inputs without associated <label>, aria-label, or
aria-labelledby; required fields not marked with aria-required.
Interactive element sizing — touch targets smaller than 44×44 px (WCAG 2.5.5).
Motion & animation — animations not respecting prefers-reduced-motion;
auto-playing video/audio without a pause control.
Language declaration — missing lang attribute on <html>; mixed-language
sections without a lang override on the containing element.
Semantic structure — skipped heading levels (<h1> → <h3>); landmark
regions (<main>, <nav>, <aside>) missing or misused.
PHASE 3 — SYNTHESIS RULES
When merging findings from all lenses:
Deduplicate — if two lenses flag the same function, emit one finding with both
lens tags.
Promote severity — a finding tagged by two or more lenses is promoted one
severity level (e.g., P2 → P1).
Group by file — sort findings by file path, then by line number.
Count totals — report P0 / P1 / P2 / P3 counts in the header.
Confidence scoring — assign confidence: high | medium | low to each finding:
high — definitive code evidence (e.g., f-string SQL query with user input).
medium — likely issue but context-dependent (e.g., missing auth check that may
be covered by middleware not visible in the diff).
low — pattern match with high false-positive rate; surface as "Consider
checking…" not as a hard assertion.
Apply configuration — honour ignore_paths, severity_override, and
max_findings from .pr-review.yml if loaded in Phase 0.
Trim noise — suppress P3 findings if total finding count >30 (or max_findings
config value). Always append (N P3 findings suppressed — run /full to see all) to
the report footer when any P3s are trimmed.
Respect suppression comments — if a flagged line carries a # pr-review-ignore: REASON
comment, omit the finding from the report and record the suppression in the footer:
Suppressed: <ID> — <REASON>.
┌─ [<ID>] <SEVERITY> · <LENS>
│ File : path/to/file.ext (line <N>–<M>)
│ Issue : <one-sentence description of the problem>
│ Impact : <what goes wrong if this is not fixed>
│ Confidence : <high | medium | low>
│ Effort : <trivial | small | medium | large>
│ Owner : <@handle from CODEOWNERS — omit if no CODEOWNERS file>
│ Fix : <concrete, actionable suggestion — include code snippet when helpful>
│ Refs : <OWASP link / CWE / RFC / relevant doc — only when directly applicable>
└──────────────────────────────────────────────────────────
Severity Legend
Severity
Emoji
Meaning
Expected action
P0 Critical
🔴
Exploitable, data-loss, or outage risk
Block merge immediately
P1 High
🟠
Significant bug or security gap
Fix before merge
P2 Medium
🟡
Quality or maintainability debt
Fix in follow-up PR
P3 Low
🔵
Style, minor inconsistency, nice-to-have
Backlog or skip
Report Footer
───────────────────────────────────────────────────────────
RECOMMENDED ACTIONS
1. Address all P0s before merge.
2. <specific top recommendation based on findings>
3. <second specific recommendation>
Run `/fix <ID>` for a ready-to-apply patch on any finding.
Run `/explain <ID>` for an educational deep-dive on any finding.
Run `/issues` to open GitHub issues for P0 + P1 findings.
Run `/pr-comment` to post findings as inline review comments.
<Trend line if prior reports exist in session>
<Suppression notes: Suppressed: <ID> — <REASON>>
<Pre-flight secret strips: N patterns redacted before analysis>
<P3 suppression note if applicable>
───────────────────────────────────────────────────────────
GITHUB INTEGRATION
When the user runs /issues after a report:
Authenticate — use the available GitHub tool or confirm the user's gh CLI is
authenticated (gh auth status).
One issue per finding (P0 and P1 only by default; ask before opening P2).
Issue title format: [pr-review][<SEVERITY>] <one-sentence description>
Issue body template:
## Finding
**ID**: <report-ID>
**Severity**: <P0/P1>
**Lens**: <lens name>
**File**: `path/to/file.ext` (line N–M)
## Problem
<Issue description from report>
## Impact
<Impact description from report>
## Suggested Fix
<Fix description from report — include code snippet>
## References
<Refs from report>
---
*Opened automatically by the `pr-review` skill.*
Label issues using this mapping:
P0 → bug
P1 Security lens → security
P1 other lenses → enhancement
P2/P3 → tech-debt
Report back with a list of created issue URLs.
/pr-comment — Inline Review Comments
Post findings as inline review comments directly on the PR diff:
Create a pending review via the GitHub API
(POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews).
For each finding with a line number, add a comment at that exact diff line.
For findings without a precise line (e.g., architectural patterns), add a top-level
review comment.
Submit the review with body: PR Review skill — <summary line from report>.
P0 findings → submit as REQUEST_CHANGES; P1/P2 → COMMENT; P3 → omit from
inline comments (include only in the submitted review body).
FALSE POSITIVE MANAGEMENT
Developers will abandon automated review tools if they can't suppress noise.
In-code Suppression
Place a comment on the flagged line to suppress a specific finding:
# pr-review-ignore: intentional MD5 — used for cache key only, not security
cache_key = hashlib.md5(url.encode()).hexdigest()
Rules:
The comment must include a REASON after the colon.
The finding is omitted from the report and recorded in the footer.
Suppressions without a reason are rejected and reported as a new P3 finding.
Confidence-Based Behaviour
Confidence
Report behaviour
high
Full finding block with all fields
medium
Full finding block; prefix Issue with "Likely:"
low
Compact one-liner only, grouped in a CONSIDER CHECKING section at the bottom
Low-confidence findings are never mixed with high/medium findings. The CONSIDER CHECKING section is collapsible and does not contribute to the P0/P1/P2/P3 totals
in the header.
Pattern Learning
When the user responds "not an issue" or dismisses a finding during the session,
record the suppression in session state:
Apply suppression to the same pattern in subsequent /review calls within the session.
CI/CD INTEGRATION
Exit Codes (for scripted / pipeline use)
Condition
Exit code
Behaviour
P0 finding(s) present
1
Always blocks CI
P1 finding(s) present
1 (default) / 0 (if fail_on: p0_only in config)
Configurable
P2/P3 only
0
CI passes
Review error / timeout
2
Infrastructure failure — do not block merge
SARIF Output
Run /review --sarif to emit findings in SARIF 2.1.0 format, compatible with
GitHub Advanced Security, GitLab SAST, and the VS Code SARIF Viewer extension:
any overuse, missing null checks, async without await, prototype pollution
Java / Kotlin
Checked exceptions swallowed, thread-safety of shared state, equals/hashCode contract
Go
Error return ignored (_), goroutine leak, unbuffered channel in hot path
SQL
Implicit type coercions, missing WHERE on UPDATE/DELETE, non-SARGable predicates
Terraform / IaC
Public S3 buckets, wildcard IAM policies, unencrypted storage, missing state locking
DIFF MODE
When the user runs /diff, compare the current review against the main branch baseline
and any prior review in the session:
Require baseline — if no prior report exists, respond:
"No previous report found. Run /review first, make your changes, then run /diff."
Main branch comparison — compare findings against the pre-existing state of main:
Pre-existing debt on main that the PR did not introduce → label [PRE-EXISTING],
surface as P3 only (do not block merge for inherited debt).
New issues introduced by this PR → label [NEW].
Identify resolved findings — findings in a prior session report absent from the
current report. Mark with [FIXED].
Regression detection — automatically escalate severity by one level if:
A test file was deleted or a test function was removed in the diff.
An authentication/authorisation check was deleted in the diff.
A rate-limit or input-validation call was removed in the diff.
Identify unchanged findings — present in both reports. Compact one-liner only:
[UNCHANGED] <ID> · <severity> · <one-line description>
Output format — standard finding block for [NEW]; compact one-liner for
[UNCHANGED]; strikethrough summary line for [FIXED]; italic note for
[PRE-EXISTING].
Summary line: Delta: +N new −M resolved = K unchanged (P pre-existing)
BEHAVIOUR RULES
Never be vague. Every finding must name the exact file, line range, and fix.
Show code. When suggesting a fix, always include a before/after snippet.
No false praise. Do not comment on things that are fine; silence means approval.
Stay in scope. Only flag what is in the diff or the explicitly specified files
unless a cross-file dependency is directly relevant to a finding.
Respect intent. Read the PR description and linked issue before flagging style
deviations — the author may have had a reason.
Be fast. Use parallel sub-agents for all eight lenses. Do not serialise lens
execution unless there is a dependency.
One finding, one fix. Do not bundle multiple problems into a single finding block.
Respect suppression. Never re-raise a finding suppressed with # pr-review-ignore.
Record suppressions in the footer for transparency.
Confidence transparency. Never assert a low-confidence finding as fact. Use
"Consider checking…" phrasing for low-confidence items.
Skip inapplicable lenses. Do not run the a11y lens on pure backend code; do not
run the performance lens on a README-only change. Log skipped lenses in the header.
EXAMPLES
Example: invoking a full review
User: "Review this PR — here's the diff: [paste diff]"
Claude fans out eight parallel lens sub-agents, then synthesises:
═══════════════════════════════════════════════════════════
PR REVIEW REPORT
Scope : 4 files changed, +312 −47 lines
Mode : full
Lenses : Security · Architecture · Performance · Deps · Logging · Testing · Docs · a11y
Summary : 1 critical 3 high 5 medium 8 low
═══════════════════════════════════════════════════════════
┌─ [SEC-001] 🔴 P0 Critical · Security
│ File : src/api/users.py (line 42–44)
│ Issue : Raw SQL query constructed with f-string from user input — SQL injection.
│ Impact : Attacker can dump or delete the entire users table.
│ Confidence : high
│ Effort : trivial
│ Fix : Replace with parameterised query:
│ # Before
│ db.execute(f"SELECT * FROM users WHERE id = {user_id}")
│ # After
│ db.execute("SELECT * FROM users WHERE id = %s", (user_id,))
│ Refs : OWASP A03:2021 — Injection · CWE-89
└──────────────────────────────────────────────────────────
...
───────────────────────────────────────────────────────────
RECOMMENDED ACTIONS
1. Address all P0s before merge.
2. Replace MD5 password hashing with bcrypt (SEC-002).
3. Add structured logging; remove plaintext password from log line (LOG-001).
Run /fix <ID> for a ready-to-apply patch on any finding.
Run /explain <ID> for an educational deep-dive on any finding.
Run /issues to open GitHub issues for P0 + P1 findings.
Run /pr-comment to post findings as inline review comments.
Trend: this PR introduces 4 P1s. Session average: 1.2 P1s per review.
───────────────────────────────────────────────────────────
Example: targeted security scan only
User: "/security src/payments/"
Claude runs only the Security lens against all files under src/payments/.
Example: generating a fix
User: "/fix SEC-001"
Claude produces a complete, ready-to-apply patch in unified diff format.
Example: educational mode
User: "/explain SEC-001"
Claude explains SQL injection from first principles — what it is, why parameterised
queries prevent it, real-world breach examples, and links to OWASP and CWE.
PROGRESS TRACKING AND ITERATION LOOP
Session Progress Header
Every /review, /fix, /iterate, and /progress output begins with:
SESSION PROGRESS
Fixed this session: [N] findings | Still open: [P0: X · P1: Y · P2: Z]
Next priority: [issue-id] — [one-line description]
/iterate <issue-id> Protocol
Show the before-state (the exact code that was flagged).
Ask the user to apply the fix (or apply it directly if the diff is accessible).
Re-scan only the affected file and line range — not the full diff.
Report the result: [FIXED] or [STILL PRESENT] or [NEW ISSUE INTRODUCED].
Immediately show the next highest-priority finding.
ITERATE: SEC-001
Before : db.execute(f"SELECT * FROM users WHERE id = {user_id}")
Fix : db.execute("SELECT * FROM users WHERE id = %s", (user_id,))
Status : [FIXED] — SQL injection vector removed
SESSION PROGRESS: 1/4 P0s fixed
→ Next: /iterate SEC-002 (hardcoded API key in config.py line 18)
/focus <issue-id> Protocol
When the user needs to deeply understand a finding before fixing it:
Full context: what does this code do, why is this specific pattern dangerous?
Exploitation scenario: concretely, how would an attacker use this?
Step-by-step fix: each change needed, in order, with code snippets.
Verification: how to confirm the fix worked (test case or observable check).
Related issues: any other findings in this report that relate to the same root cause.
Do not move to the next finding until the user confirms this one is resolved.
Example: CI pipeline integration
# .github/workflows/pr-review.yml
- name: PR Review
run: claude --skill pr-review --review ${{ github.event.pull_request.diff_url }}
# Exits 1 on P0/P1 findings (configurable via fail_on), 0 on P2/P3 only
- name: PR Review (SARIF upload)
run: claude --skill pr-review --review --sarif > results.sarif
- uses: github/codeql-action/upload-sarif@v3
with:
sarif_file: results.sarif
1---2name: pr-review3description: >4 Automated PR review and code quality analysis skill. Activate when the user asks to5 review a pull request, audit code quality, check a codebase, scan for bugs or security6 issues, or validate a plan before shipping. Fans out parallel sub-agents — one per7 review lens (security, architecture, performance, dependencies, logging, testing,8 documentation, accessibility) — then synthesises a structured severity-graded report9 with confidence scores, effort estimates, and actionable suggestions.10 Use when user says: review this PR, audit my code, check for security issues, review11 my changes, scan for bugs, quality check, code review, pre-ship audit.12 First response: "PR Review skill active. Paste the diff, file paths, or describe what13 to review. I'll run every lens in parallel and give you a structured report."14license: Apache 2.015metadata:16 source: https://skillmd.com/skills/sandeeprdy1729/pr-review17---1819# Automated PR Review & Code Quality2021A structured, multi-lens code review system. Eight lenses run in parallel so coverage22is deep, consistent, and fast. Output is always a severity-graded report with confidence23scores, effort estimates, and concrete before/after fixes — never vague observations.2425---2627## SLASH COMMANDS2829| Command | Action |30| --- | --- |31| `/review` | Full review across all eight lenses |32| `/security` | Security lens only — OWASP Top 10, secrets, injection, auth |33| `/arch` | Architecture lens only — coupling, cohesion, SOLID, complexity |34| `/perf` | Performance lens only — N+1, memory leaks, Big-O, caching, async blocking |35| `/a11y` | Accessibility lens only — WCAG 2.1 AA, ARIA, keyboard, color contrast |36| `/deps` | Dependency lens only — outdated packages, license risk, supply chain |37| `/logging` | Logging & observability lens only — missing logs, PII leakage, trace IDs |38| `/testing` | Testing lens only — coverage gaps, brittle tests, missing edge cases |39| `/docs` | Documentation lens only — missing docstrings, stale comments, unclear APIs |40| `/fix <issue-id>` | Generate a ready-to-apply patch for a specific issue from the report |41| `/explain <issue-id>` | Educational deep-dive: why this is dangerous, not just how to fix it |42| `/issues` | Open GitHub issues for every P0 and P1 finding in the last report |43| `/pr-comment` | Post findings as inline GitHub PR review comments on specific lines |44| `/summary` | One-paragraph executive summary of the last report |45| `/tldr` | One-sentence summary for Slack/Discord notifications |46| `/diff` | New/resolved findings vs the previous review — compares against main branch baseline |47| `/iterate <issue-id>` | Fix an issue, then re-check just that code area — show what changed and confirm the fix |48| `/focus <issue-id>` | Deep dive on one finding: full context, step-by-step fix guide, before/after example |49| `/progress` | Show: findings fixed this session / findings still open / next priority |5051---5253## HIGH-LEVEL WORKFLOW5455```56Input (diff / file paths / plan / repo)57 │58 ├─ Phase 0: Guardrails ── size check, privacy warning, load config59 │60 ├─ Phase 1: Reconnaissance ── read files, understand intent, build context map61 │62 ├─ Phase 2: Fan-out ── launch all eight lenses in parallel (sub-agents)63 │ ├─ Lens A: Security64 │ ├─ Lens B: Architecture65 │ ├─ Lens C: Performance & Scalability66 │ ├─ Lens D: Dependencies67 │ ├─ Lens E: Logging & Observability68 │ ├─ Lens F: Testing69 │ ├─ Lens G: Documentation70 │ └─ Lens H: Accessibility (a11y)71 │72 ├─ Phase 3: Synthesis ── merge, deduplicate, confidence score, assign severities73 │74 ├─ Phase 4: Prioritization ── effort estimates, CODEOWNERS tagging, team baseline75 │76 └─ Phase 5: Output ── structured report + optional CI/GitHub actions77```7879---8081## PHASE 0 — GUARDRAILS8283Run before any other phase. Perform three checks and halt or warn as described.8485### 0.1 Size Check8687| Diff size | Behaviour |88| --- | --- |89| ≤20 files and ≤2 000 lines | Full review — all lenses, all severities |90| 21–100 files or 2 001–5 000 lines | High-signal mode — Security + Architecture + Performance only; P3 suppressed entirely |91| >100 files or >5 000 lines | Refuse full review. Respond: "This diff is too large for a full review. Specify files or lenses: `/review src/payments/ /security /arch`" |9293In High-signal mode, always prioritise entry points (`main`, `index`, route handlers)94over utility/helper files regardless of diff order.9596### 0.2 Privacy Warning9798Before processing any code, display once per session:99100```101⚠ Privacy notice: this review will process <N> lines of code through Claude.102 Confirm this repository is cleared for external analysis. [y/n]103```104105Auto-approve for subsequent reviews in the same session.106107Run a pre-flight secret scan (regex pass) and strip patterns matching:108- `-----BEGIN (RSA|EC|OPENSSH) PRIVATE KEY-----`109- AWS key patterns (`AKIA[0-9A-Z]{16}`)110- Generic `password\s*=\s*"[^"]+"` assignments111112Log the count of stripped patterns to the report footer. Security lens findings about113secrets are still raised based on the pattern match, without leaking the value.114115### 0.3 Load Configuration116117Look for `.pr-review.yml` in the repo root. If present, apply:118119```yaml120# .pr-review.yml — all fields optional121ignore_paths:122 - "*.test.ts"123 - "migrations/"124 - "generated/"125severity_override:126 TRACE_ID_MISSING: P1 # escalate from default P2127max_findings: 25 # cap total findings to prevent review fatigue128lenses: # restrict lenses for this repo129 - security130 - performance131 - testing132confidence_threshold: medium # suppress low-confidence findings133fail_on: p0_only # CI exit-code threshold (default: p1)134```135136Also read `CONTRIBUTING.md` and `STYLEGUIDE.md` if present to extract naming137conventions and testing requirements before flagging style deviations.138139---140141## PHASE 1 — RECONNAISSANCE142143Before any lens fires, build a context map:1441451. **Identify scope** — diff only, changed files, or entire repo?1462. **Detect language(s)** — infer from file extensions; load language-specific rules.1473. **Detect framework(s)** — React, Django, Spring, etc.; apply framework-specific checks.1484. **Read entry points** — `main`, `index`, `app`, route registrations.1495. **Understand intent** — read PR description, commit messages, linked issue titles.1506. **Check CODEOWNERS** — map changed files to owners for finding attribution.1517. **Flag obvious blockers** — syntax errors, merge conflicts, broken imports — report152 these immediately before continuing.153154---155156## PHASE 2 — REVIEW LENSES157158### LENS A — SECURITY159160> Goal: find every exploitable vulnerability before it ships.161162**Checklist:**163164- [ ] **Injection** — SQL, command, LDAP, XPath, template injection. Verify all user165 input is parameterised or sanitised before use.166- [ ] **Authentication & authorisation** — broken auth flows, missing `@login_required`167 / auth middleware, insecure direct object references (IDOR), JWT algorithm confusion.168- [ ] **Secrets & credentials** — hardcoded API keys, passwords, tokens in source or169 config files. Check `.env` handling; verify secrets are never logged.170- [ ] **Cryptography** — weak algorithms (MD5, SHA-1, DES, ECB mode), insufficient key171 lengths, predictable IVs, insecure random number generation.172- [ ] **Data exposure** — PII in logs, stack traces returned to clients, verbose error173 messages, over-permissive CORS, missing HTTPS enforcement.174- [ ] **CORS misconfiguration** — overly permissive `Access-Control-Allow-Origin: *` in175 production, credentials allowed with wildcard origin, missing `Vary: Origin`.176- [ ] **Deserialization of untrusted data** — `pickle.loads`, `yaml.load` (vs `safe_load`),177 Java `ObjectInputStream`, PHP `unserialize` on user-controlled input.178- [ ] **XXE (XML External Entity)** — XML parsers with external entity resolution enabled179 when processing user-supplied XML.180- [ ] **Path traversal in file operations** — user-controlled path components in `open()`,181 `fs.readFile()`, `File()` calls without normalisation and boundary checks.182- [ ] **Input validation** — missing length/type/range checks at system boundaries,183 unvalidated redirects.184- [ ] **Dependency vulnerabilities** — known CVEs in direct and transitive dependencies185 (cross-reference with dependency lens).186- [ ] **Supply chain** — typosquatted packages, unpinned versions, absent lockfile187 integrity checks.188- [ ] **SSRF / open redirect** — any URL constructed from user-controlled input that189 makes server-side HTTP requests.190- [ ] **Rate limiting & DoS** — unbounded loops driven by user input, missing pagination191 limits, expensive regex on untrusted strings (ReDoS).192193**Severity mapping for this lens:**194- `P0 (Critical)` — exploitable without authentication or with low-privilege access.195- `P1 (High)` — exploitable with authenticated access or under specific conditions.196- `P2 (Medium)` — defence-in-depth gap; not directly exploitable but raises risk.197- `P3 (Low)` — best-practice deviation with minimal direct risk.198199---200201### LENS B — ARCHITECTURE202203> Goal: identify structural problems that compound over time.204205**Checklist:**206207- [ ] **Single Responsibility** — functions/classes doing more than one job. Flag any208 function >30 lines that mixes concerns (I/O + business logic, for example).209- [ ] **Coupling** — tight coupling between unrelated modules, circular imports,210 god objects/classes, feature envy.211- [ ] **Cohesion** — modules with unrelated responsibilities, poor layer separation212 (e.g., database queries inside UI components).213- [ ] **Complexity** — cyclomatic complexity >10 in a single function, deeply nested214 conditionals (>3 levels), long parameter lists (>4 params without a data class).215- [ ] **Naming** — misleading names, abbreviations, Hungarian notation, generic names216 (`data`, `info`, `temp`, `manager`, `utils` with >15 methods).217- [ ] **Error handling** — swallowed exceptions (`except: pass`), bare `catch (e) {}`,218 missing error propagation, inconsistent error shapes across an API.219- [ ] **Transaction boundaries** — database transactions that span external HTTP calls,220 holding locks across the wire; missing rollback on partial failure.221- [ ] **Circuit breaker / retry logic** — external service calls with no timeout, no222 retry with backoff, and no circuit breaker — a single dependency failure takes down223 the entire system.224- [ ] **Idempotency** — mutation endpoints (`POST /charge`, `POST /send-email`) without225 an idempotency key, making safe client retries impossible.226- [ ] **DRY violations** — copy-pasted logic blocks >5 lines appearing more than once.227- [ ] **Dead code** — unreachable branches, unused exports, commented-out code blocks.228- [ ] **Abstraction level** — mixed abstraction levels inside a single function; leaky229 abstractions exposing implementation details to callers.230231---232233### LENS C — PERFORMANCE & SCALABILITY234235> Goal: catch efficiency problems before they become production incidents under load.236237**Checklist:**238239- [ ] **N+1 queries** — ORM loop issuing one DB query per iteration; flag and suggest240 eager loading (`select_related`, `JOIN`, `$lookup`).241- [ ] **Synchronous I/O in async paths** — blocking file read, `requests.get()`, or242 `time.sleep()` inside an `async def` / event-loop context.243- [ ] **Unbounded memory growth** — appending to a list/dict in a loop with no size244 cap; loading an entire table into memory; accumulating results without streaming.245- [ ] **Missing pagination** — list endpoints returning all rows without `LIMIT`/`OFFSET`246 or cursor-based pagination.247- [ ] **Big-O inefficiency in hot paths** — O(n²) or worse algorithm where O(n log n)248 or O(n) alternative exists; nested loops over large collections.249- [ ] **Caching strategy gaps** — expensive computations (external API calls, heavy DB250 aggregations) called on every request with no memoisation or cache layer.251- [ ] **Database query plans** — missing composite indexes on multi-column `WHERE`252 clauses; `SELECT *` where specific columns suffice; non-SARGable predicates.253- [ ] **Async blocking** — `Promise.all` missing where sequential `await` chains could254 be parallelised; CPU-bound work on the event loop without offloading to a worker.255- [ ] **Memory leaks** — event listeners registered without cleanup, timers not cleared,256 closures retaining large objects, streams not destroyed on error.257- [ ] **Connection pool exhaustion** — opening new DB/HTTP connections per request258 instead of reusing a pool; pool size not configured for expected concurrency.259260---261262### LENS D — DEPENDENCIES263264> Goal: keep the dependency tree lean, secure, and legally safe.265266**Checklist:**267268- [ ] **Outdated packages** — dependencies >1 major version behind their latest stable269 release; note breaking-change risk.270- [ ] **Unused dependencies** — packages imported in `package.json` / `requirements.txt`271 / `go.mod` but never `import`-ed in code.272- [ ] **Duplicate functionality** — two packages doing the same job (e.g., `axios` and273 `node-fetch` in the same project).274- [ ] **Bundle weight** — heavy packages pulled in for a single utility function275 (prefer tree-shakeable alternatives or inline the function).276- [ ] **License compliance** — GPL/AGPL in a proprietary project, license conflicts277 between dependencies.278- [ ] **Lockfile hygiene** — missing `package-lock.json` / `poetry.lock`, lockfile not279 committed, lockfile out of sync with manifest.280- [ ] **Pinning strategy** — overly loose (`*`, `>=1`) or overly strict (exact SHA for281 everything) pinning; recommend `~=` / `^` semantics where appropriate.282- [ ] **Deprecated / abandoned packages** — no commits in >2 years, archived repo,283 single-maintainer bus-factor risk; flag and suggest active alternatives.284- [ ] **Native dependency risk** — packages with native bindings (`.node`, `.so`, `.dll`)285 that may break across OS/architecture; flag for multi-platform deployments.286- [ ] **Peer-dependency mismatches** — declared peer deps not satisfied by installed287 versions.288289---290291### LENS E — LOGGING & OBSERVABILITY292293> Goal: ensure the system is debuggable in production without leaking sensitive data.294295**Checklist:**296297- [ ] **Coverage** — every external call (HTTP, DB, queue, cache) has at least one log298 entry at the start and on error/success.299- [ ] **Log levels** — correct use of `DEBUG`, `INFO`, `WARN`, `ERROR`, `FATAL`.300 Avoid `INFO` for every message; avoid `DEBUG` left on in production code paths.301- [ ] **Structured logging** — logs are machine-parseable (JSON, key=value). No raw302 `print()` / `console.log()` in production paths.303- [ ] **PII leakage** — passwords, tokens, emails, PII must never appear in log output.304 Verify masking/redaction is applied before logging request/response bodies.305- [ ] **Trace & correlation IDs** — distributed transactions include a `trace_id` or306 `request_id` threaded through all log lines.307- [ ] **Error context** — exceptions are logged with full stack trace + request context,308 not just `"something went wrong"`.309- [ ] **Metrics & alerts** — critical paths (payments, auth, data mutations) emit310 a counter or histogram metric; alert thresholds are defined.311- [ ] **Silent failures** — code paths that catch exceptions and continue without any312 log entry.313314---315316### LENS F — TESTING317318> Goal: find coverage gaps and brittle tests before they become production incidents.319320**Checklist:**321322- [ ] **Coverage gaps** — new code paths with no corresponding test; branches inside323 conditionals that are never exercised.324- [ ] **Happy-path only** — tests that only cover the success case; missing tests for325 error paths, boundary conditions, and empty/null inputs.326- [ ] **Edge cases** — off-by-one errors, empty collections, `null`/`undefined`,327 maximum-length inputs, concurrent access, timezone edge cases.328- [ ] **Test isolation** — tests sharing state via global variables, module-level side329 effects, or real external services (DB, HTTP) without mocking.330- [ ] **Brittle selectors** — UI tests using implementation-detail selectors (CSS class331 names, internal state) instead of accessible roles/labels.332- [ ] **Assertion quality** — `assert response` (truthy check) instead of333 `assert response.status_code == 200`; missing error message in assertion.334- [ ] **Test naming** — test names that don't describe the scenario335 (`test_1`, `testFoo`) making failures hard to diagnose.336- [ ] **Flaky tests** — tests with `sleep()` / fixed timeouts, order-dependent tests,337 tests seeded with wall-clock time.338- [ ] **Property-based testing gaps** — complex business logic (parsers, validators,339 financial calculations) without fuzz / property-based tests (Hypothesis, fast-check).340- [ ] **Contract testing** — API changes without consumer contract validation (Pact);341 service boundary regressions caught only in integration or staging.342- [ ] **Integration vs unit balance** — over-reliance on slow end-to-end tests for343 logic that could be unit-tested; or inverse: mocking so heavily that integration344 bugs are invisible.345346---347348### LENS G — DOCUMENTATION349350> Goal: ensure the code is understandable by a new engineer without a walkthrough.351352**Checklist:**353354- [ ] **Public API docstrings** — every exported function, class, and method has a355 docstring explaining purpose, params, return value, and exceptions raised.356- [ ] **Inline comments** — complex business logic, non-obvious algorithms, and357 workarounds have a `# why` comment explaining intent, not just `# what`.358- [ ] **Stale comments** — comments that describe code that no longer exists or359 behaviour that has changed.360- [ ] **README coverage** — new environment variables, config options, CLI flags, or361 setup steps reflected in README / CONTRIBUTING docs.362- [ ] **Changelog / migration notes** — breaking changes in public APIs documented in363 CHANGELOG.md or a migration guide.364- [ ] **Type annotations** — typed languages: all public signatures have types; Python:365 all public functions have PEP 484 annotations.366- [ ] **Example usage** — complex utilities or SDK-style modules include at least one367 runnable example.368- [ ] **TODO hygiene** — `TODO`/`FIXME` comments have an owner and a linked issue; stale369 TODOs (>90 days old) are flagged.370371---372373### LENS H — ACCESSIBILITY (a11y)374375> Goal: catch WCAG 2.1 AA violations before they create legal or UX debt.376> Skip this lens automatically for non-UI code (pure backend, CLI, IaC).377378**Checklist:**379380- [ ] **Missing alt text** — `<img>`, `<svg>`, and icon buttons without meaningful `alt`381 or `aria-label` attributes.382- [ ] **Improper ARIA roles** — `role` values that contradict native HTML element383 semantics; redundant `role="button"` on `<button>`; invalid role hierarchies.384- [ ] **Keyboard trap** — modal dialogs, dropdowns, or custom widgets that don't return385 focus to the trigger element on close, or trap Tab without an escape route.386- [ ] **Focus management** — programmatic focus not moved to newly opened dialogs,387 alerts, or route changes; invisible focus ring (`:focus { outline: none }` without388 a visible replacement).389- [ ] **Color contrast** — text/background combinations failing WCAG AA ratio (4.5:1390 normal text, 3:1 large text); information conveyed by color alone.391- [ ] **Form labelling** — inputs without associated `<label>`, `aria-label`, or392 `aria-labelledby`; required fields not marked with `aria-required`.393- [ ] **Interactive element sizing** — touch targets smaller than 44×44 px (WCAG 2.5.5).394- [ ] **Motion & animation** — animations not respecting `prefers-reduced-motion`;395 auto-playing video/audio without a pause control.396- [ ] **Language declaration** — missing `lang` attribute on `<html>`; mixed-language397 sections without a `lang` override on the containing element.398- [ ] **Semantic structure** — skipped heading levels (`<h1>` → `<h3>`); landmark399 regions (`<main>`, `<nav>`, `<aside>`) missing or misused.400401---402403## PHASE 3 — SYNTHESIS RULES404405When merging findings from all lenses:4064071. **Deduplicate** — if two lenses flag the same function, emit one finding with both408 lens tags.4092. **Promote severity** — a finding tagged by two or more lenses is promoted one410 severity level (e.g., P2 → P1).4113. **Group by file** — sort findings by file path, then by line number.4124. **Count totals** — report `P0 / P1 / P2 / P3` counts in the header.4135. **Confidence scoring** — assign `confidence: high | medium | low` to each finding:414 - `high` — definitive code evidence (e.g., f-string SQL query with user input).415 - `medium` — likely issue but context-dependent (e.g., missing auth check that may416 be covered by middleware not visible in the diff).417 - `low` — pattern match with high false-positive rate; surface as "Consider418 checking…" not as a hard assertion.4196. **Apply configuration** — honour `ignore_paths`, `severity_override`, and420 `max_findings` from `.pr-review.yml` if loaded in Phase 0.4217. **Trim noise** — suppress P3 findings if total finding count >30 (or `max_findings`422 config value). Always append `(N P3 findings suppressed — run /full to see all)` to423 the report footer when any P3s are trimmed.4248. **Respect suppression comments** — if a flagged line carries a `# pr-review-ignore: REASON`425 comment, omit the finding from the report and record the suppression in the footer:426 `Suppressed: <ID> — <REASON>`.427428---429430## PHASE 4 — PRIORITIZATION431432After synthesis, annotate each finding with:433434### Effort Estimate435436| Tag | Meaning |437| --- | --- |438| `effort: trivial` | <5 min — rename, add a comment, single-line fix |439| `effort: small` | <30 min — replace one function, add one test case |440| `effort: medium` | Hours — refactor a module, add a feature flag |441| `effort: large` | Refactor — multi-file change, requires design discussion |442443### CODEOWNERS Attribution444445If a `CODEOWNERS` file exists in the repo root or `.github/`, append the responsible446owner handle to each finding:447448```449│ Owner : @payments-team450```451452### Team Baseline453454If previous review reports exist in the conversation, compute and append to the455report footer:456457```458Trend: this PR introduces N P1s. Session average: M P1s per review.459```460461---462463## PHASE 5 — OUTPUT FORMAT464465### Report Header466467```468═══════════════════════════════════════════════════════════469 PR REVIEW REPORT470 Scope : <files reviewed / diff size>471 Mode : <full | high-signal>472 Lenses : <active lenses> [<skipped lenses> skipped]473 Summary : <P0_count> critical <P1_count> high <P2_count> medium <P3_count> low474═══════════════════════════════════════════════════════════475```476477### Finding Block (one per issue)478479```480┌─ [<ID>] <SEVERITY> · <LENS>481│ File : path/to/file.ext (line <N>–<M>)482│ Issue : <one-sentence description of the problem>483│ Impact : <what goes wrong if this is not fixed>484│ Confidence : <high | medium | low>485│ Effort : <trivial | small | medium | large>486│ Owner : <@handle from CODEOWNERS — omit if no CODEOWNERS file>487│ Fix : <concrete, actionable suggestion — include code snippet when helpful>488│ Refs : <OWASP link / CWE / RFC / relevant doc — only when directly applicable>489└──────────────────────────────────────────────────────────490```491492### Severity Legend493494| Severity | Emoji | Meaning | Expected action |495|---|---|---|---|496| `P0 Critical` | 🔴 | Exploitable, data-loss, or outage risk | Block merge immediately |497| `P1 High` | 🟠 | Significant bug or security gap | Fix before merge |498| `P2 Medium` | 🟡 | Quality or maintainability debt | Fix in follow-up PR |499| `P3 Low` | 🔵 | Style, minor inconsistency, nice-to-have | Backlog or skip |500501### Report Footer502503```504───────────────────────────────────────────────────────────505 RECOMMENDED ACTIONS506 1. Address all P0s before merge.507 2. <specific top recommendation based on findings>508 3. <second specific recommendation>509 Run `/fix <ID>` for a ready-to-apply patch on any finding.510 Run `/explain <ID>` for an educational deep-dive on any finding.511 Run `/issues` to open GitHub issues for P0 + P1 findings.512 Run `/pr-comment` to post findings as inline review comments.513 <Trend line if prior reports exist in session>514 <Suppression notes: Suppressed: <ID> — <REASON>>515 <Pre-flight secret strips: N patterns redacted before analysis>516 <P3 suppression note if applicable>517───────────────────────────────────────────────────────────518```519520---521522## GITHUB INTEGRATION523524When the user runs `/issues` after a report:5255261. **Authenticate** — use the available GitHub tool or confirm the user's `gh` CLI is527 authenticated (`gh auth status`).5282. **One issue per finding** (P0 and P1 only by default; ask before opening P2).5293. **Issue title format**: `[pr-review][<SEVERITY>] <one-sentence description>`5304. **Issue body template**:531532```markdown533## Finding534535**ID**: <report-ID>536**Severity**: <P0/P1>537**Lens**: <lens name>538**File**: `path/to/file.ext` (line N–M)539540## Problem541542<Issue description from report>543544## Impact545546<Impact description from report>547548## Suggested Fix549550<Fix description from report — include code snippet>551552## References553554<Refs from report>555556---557*Opened automatically by the `pr-review` skill.*558```5595605. **Label issues** using this mapping:561 - P0 → `bug`562 - P1 Security lens → `security`563 - P1 other lenses → `enhancement`564 - P2/P3 → `tech-debt`5656. **Report back** with a list of created issue URLs.566567### `/pr-comment` — Inline Review Comments568569Post findings as inline review comments directly on the PR diff:5705711. Create a pending review via the GitHub API572 (`POST /repos/{owner}/{repo}/pulls/{pull_number}/reviews`).5732. For each finding with a line number, add a comment at that exact diff line.5743. For findings without a precise line (e.g., architectural patterns), add a top-level575 review comment.5764. Submit the review with body: `PR Review skill — <summary line from report>`.5775. P0 findings → submit as `REQUEST_CHANGES`; P1/P2 → `COMMENT`; P3 → omit from578 inline comments (include only in the submitted review body).579580---581582## FALSE POSITIVE MANAGEMENT583584Developers will abandon automated review tools if they can't suppress noise.585586### In-code Suppression587588Place a comment on the flagged line to suppress a specific finding:589590```python591# pr-review-ignore: intentional MD5 — used for cache key only, not security592cache_key = hashlib.md5(url.encode()).hexdigest()593```594595Rules:596- The comment must include a `REASON` after the colon.597- The finding is omitted from the report and recorded in the footer.598- Suppressions without a reason are rejected and reported as a new `P3` finding.599600### Confidence-Based Behaviour601602| Confidence | Report behaviour |603| --- | --- |604| `high` | Full finding block with all fields |605| `medium` | Full finding block; prefix Issue with "Likely:" |606| `low` | Compact one-liner only, grouped in a `CONSIDER CHECKING` section at the bottom |607608Low-confidence findings are never mixed with high/medium findings. The `CONSIDER609CHECKING` section is collapsible and does not contribute to the P0/P1/P2/P3 totals610in the header.611612### Pattern Learning613614When the user responds "not an issue" or dismisses a finding during the session,615record the suppression in session state:616617```618Dismissed: <lens> · <file-pattern> · <code-pattern>619```620621Apply suppression to the same pattern in subsequent `/review` calls within the session.622623---624625## CI/CD INTEGRATION626627### Exit Codes (for scripted / pipeline use)628629| Condition | Exit code | Behaviour |630| --- | --- | --- |631| P0 finding(s) present | `1` | Always blocks CI |632| P1 finding(s) present | `1` (default) / `0` (if `fail_on: p0_only` in config) | Configurable |633| P2/P3 only | `0` | CI passes |634| Review error / timeout | `2` | Infrastructure failure — do not block merge |635636### SARIF Output637638Run `/review --sarif` to emit findings in SARIF 2.1.0 format, compatible with639GitHub Advanced Security, GitLab SAST, and the VS Code SARIF Viewer extension:640641```json642{643 "version": "2.1.0",644 "$schema": "https://json.schemastore.org/sarif-2.1.0.json",645 "runs": [{646 "tool": { "driver": { "name": "pr-review", "version": "2.0.0" } },647 "results": [{648 "ruleId": "SEC-001",649 "level": "error",650 "message": { "text": "<issue description>" },651 "locations": [{652 "physicalLocation": {653 "artifactLocation": { "uri": "src/api/users.py" },654 "region": { "startLine": 42, "endLine": 44 }655 }656 }]657 }]658 }]659}660```661662Upload to GitHub Advanced Security:663664```yaml665# .github/workflows/pr-review.yml666- name: PR Review667 run: claude --skill pr-review --review --sarif > results.sarif668- name: Upload SARIF669 uses: github/codeql-action/upload-sarif@v3670 with:671 sarif_file: results.sarif672```673674---675676## LANGUAGE-SPECIFIC RULE EXTENSIONS677678Load additional rule sets based on detected language:679680| Language | Extra checks to apply |681|---|---|682| **Python** | Type annotations (PEP 484), `__all__` exports, mutable default args, `except Exception` breadth |683| **TypeScript / JS** | `any` overuse, missing `null` checks, `async` without `await`, prototype pollution |684| **Java / Kotlin** | Checked exceptions swallowed, thread-safety of shared state, `equals`/`hashCode` contract |685| **Go** | Error return ignored (`_`), goroutine leak, unbuffered channel in hot path |686| **SQL** | Implicit type coercions, missing `WHERE` on `UPDATE`/`DELETE`, non-SARGable predicates |687| **Terraform / IaC** | Public S3 buckets, wildcard IAM policies, unencrypted storage, missing state locking |688689---690691## DIFF MODE692693When the user runs `/diff`, compare the current review against the main branch baseline694and any prior review in the session:6956961. **Require baseline** — if no prior report exists, respond:697 `"No previous report found. Run /review first, make your changes, then run /diff."`6982. **Main branch comparison** — compare findings against the pre-existing state of `main`:699 - Pre-existing debt on `main` that the PR did not introduce → label `[PRE-EXISTING]`,700 surface as `P3` only (do not block merge for inherited debt).701 - New issues introduced by this PR → label `[NEW]`.7023. **Identify resolved findings** — findings in a prior session report absent from the703 current report. Mark with `[FIXED]`.7044. **Regression detection** — automatically escalate severity by one level if:705 - A test file was deleted or a test function was removed in the diff.706 - An authentication/authorisation check was deleted in the diff.707 - A rate-limit or input-validation call was removed in the diff.7085. **Identify unchanged findings** — present in both reports. Compact one-liner only:709 `[UNCHANGED] <ID> · <severity> · <one-line description>`7106. **Output format** — standard finding block for `[NEW]`; compact one-liner for711 `[UNCHANGED]`; ~~strikethrough~~ summary line for `[FIXED]`; italic note for712 `[PRE-EXISTING]`.7137. **Summary line**: `Delta: +N new −M resolved = K unchanged (P pre-existing)`714715---716717## BEHAVIOUR RULES718719- **Never be vague.** Every finding must name the exact file, line range, and fix.720- **Show code.** When suggesting a fix, always include a before/after snippet.721- **No false praise.** Do not comment on things that are fine; silence means approval.722- **Stay in scope.** Only flag what is in the diff or the explicitly specified files723 unless a cross-file dependency is directly relevant to a finding.724- **Respect intent.** Read the PR description and linked issue before flagging style725 deviations — the author may have had a reason.726- **Be fast.** Use parallel sub-agents for all eight lenses. Do not serialise lens727 execution unless there is a dependency.728- **One finding, one fix.** Do not bundle multiple problems into a single finding block.729- **Respect suppression.** Never re-raise a finding suppressed with `# pr-review-ignore`.730 Record suppressions in the footer for transparency.731- **Confidence transparency.** Never assert a low-confidence finding as fact. Use732 "Consider checking…" phrasing for low-confidence items.733- **Skip inapplicable lenses.** Do not run the a11y lens on pure backend code; do not734 run the performance lens on a README-only change. Log skipped lenses in the header.735736---737738## EXAMPLES739740### Example: invoking a full review741742> User: "Review this PR — here's the diff: [paste diff]"743744Claude fans out eight parallel lens sub-agents, then synthesises:745746```747═══════════════════════════════════════════════════════════748 PR REVIEW REPORT749 Scope : 4 files changed, +312 −47 lines750 Mode : full751 Lenses : Security · Architecture · Performance · Deps · Logging · Testing · Docs · a11y752 Summary : 1 critical 3 high 5 medium 8 low753═══════════════════════════════════════════════════════════754755┌─ [SEC-001] 🔴 P0 Critical · Security756│ File : src/api/users.py (line 42–44)757│ Issue : Raw SQL query constructed with f-string from user input — SQL injection.758│ Impact : Attacker can dump or delete the entire users table.759│ Confidence : high760│ Effort : trivial761│ Fix : Replace with parameterised query:762│ # Before763│ db.execute(f"SELECT * FROM users WHERE id = {user_id}")764│ # After765│ db.execute("SELECT * FROM users WHERE id = %s", (user_id,))766│ Refs : OWASP A03:2021 — Injection · CWE-89767└──────────────────────────────────────────────────────────768769...770771───────────────────────────────────────────────────────────772 RECOMMENDED ACTIONS773 1. Address all P0s before merge.774 2. Replace MD5 password hashing with bcrypt (SEC-002).775 3. Add structured logging; remove plaintext password from log line (LOG-001).776 Run /fix <ID> for a ready-to-apply patch on any finding.777 Run /explain <ID> for an educational deep-dive on any finding.778 Run /issues to open GitHub issues for P0 + P1 findings.779 Run /pr-comment to post findings as inline review comments.780 Trend: this PR introduces 4 P1s. Session average: 1.2 P1s per review.781───────────────────────────────────────────────────────────782```783784### Example: targeted security scan only785786> User: "/security src/payments/"787788Claude runs only the Security lens against all files under `src/payments/`.789790### Example: generating a fix791792> User: "/fix SEC-001"793794Claude produces a complete, ready-to-apply patch in unified diff format.795796### Example: educational mode797798> User: "/explain SEC-001"799800Claude explains SQL injection from first principles — what it is, why parameterised801queries prevent it, real-world breach examples, and links to OWASP and CWE.802803---804805## PROGRESS TRACKING AND ITERATION LOOP806807### Session Progress Header808809Every `/review`, `/fix`, `/iterate`, and `/progress` output begins with:810811```812SESSION PROGRESS813 Fixed this session: [N] findings | Still open: [P0: X · P1: Y · P2: Z]814 Next priority: [issue-id] — [one-line description]815```816817### `/iterate <issue-id>` Protocol8188191. Show the before-state (the exact code that was flagged).8202. Ask the user to apply the fix (or apply it directly if the diff is accessible).8213. Re-scan only the affected file and line range — not the full diff.8224. Report the result: `[FIXED]` or `[STILL PRESENT]` or `[NEW ISSUE INTRODUCED]`.8235. Immediately show the next highest-priority finding.824825```826ITERATE: SEC-001827 Before : db.execute(f"SELECT * FROM users WHERE id = {user_id}")828 Fix : db.execute("SELECT * FROM users WHERE id = %s", (user_id,))829 Status : [FIXED] — SQL injection vector removed830831 SESSION PROGRESS: 1/4 P0s fixed832 → Next: /iterate SEC-002 (hardcoded API key in config.py line 18)833```834835### `/focus <issue-id>` Protocol836837When the user needs to deeply understand a finding before fixing it:8388391. Full context: what does this code do, why is this specific pattern dangerous?8402. Exploitation scenario: concretely, how would an attacker use this?8413. Step-by-step fix: each change needed, in order, with code snippets.8424. Verification: how to confirm the fix worked (test case or observable check).8435. Related issues: any other findings in this report that relate to the same root cause.844845Do not move to the next finding until the user confirms this one is resolved.846847### Example: CI pipeline integration848849```yaml850# .github/workflows/pr-review.yml851- name: PR Review852 run: claude --skill pr-review --review ${{ github.event.pull_request.diff_url }}853 # Exits 1 on P0/P1 findings (configurable via fail_on), 0 on P2/P3 only854855- name: PR Review (SARIF upload)856 run: claude --skill pr-review --review --sarif > results.sarif857- uses: github/codeql-action/upload-sarif@v3858 with:859 sarif_file: results.sarif860```
Run npx get-skill add sandeeprdy1729/pr-review in your terminal (requires Node.js), paste this page's agent-chat prompt into Claude, Cursor, or any MCP-connected agent, or download the SKILL.md file and copy it into your agent's skills directory.
Automated PR review and code quality analysis skill. Activate when the user asks to review a pull request, audit code quality, check a codebase, scan for bugs or security issues, or validate a plan before shipping. Fans out parallel sub-agents — one per review lens (security, architecture, performance, dependencies, logging, testing, documentation, accessibility) — then synthesises a structured severity-graded report with confidence scores, effort estimates, and actionable suggestions. Use when user says: review this PR, audit my code, check for security issues, review my changes, scan for bugs, quality check, code review, pre-ship audit. First response: "PR Review skill active. Paste the diff, file paths, or describe what to review. I'll run every lens in parallel and give you a structured report." It is listed under Web & Frontend on SkillMD.
This skill has not completed SkillMD's automated safety review yet. Capability flags: makes network calls, reads secrets. SkillMD never runs a skill's scripts for you; review the SKILL.md before installing.
This skill is tagged as working with Claude Code, Claude.ai, OpenAI Codex. SKILL.md is an open format, so most agents that read a skills directory can load it too.
Yes. Installing skills from SkillMD is free. This skill is licensed under Apache 2.
Sandeeprdy1729 (@sandeeprdy1729) published this skill. Their other Agent Skills are listed on their SkillMD profile.