| name | ui-review |
| description | [Code Quality] Use when reviewing UI/frontend changes for long-content overflow, responsive multi-screen layout (flex-wrap / row-to-column on small devices), flex-vs-fixed sizing, z-index discipline, SCSS/BEM styling quality, and async UI states & feedback (loading indicator, error surface, empty state). |
Codex compatibility note:
- Invoke repository skills with
$skill-name in Codex; this mirrored copy rewrites legacy Claude /skill-name references.
- Task tracker mandate: BEFORE executing any workflow or skill step, create/update task tracking for all steps and keep it synchronized as progress changes.
- User-question prompts mean to ask the user directly in Codex.
- Ignore Claude-specific mode-switch instructions when they appear.
- Strict execution contract: when a user explicitly invokes a skill, execute that skill protocol as written.
- Subagent authorization: when a skill is user-invoked or AI-detected and its protocol requires subagents, that skill activation authorizes use of the required
spawn_agent subagent(s) for that task.
- Do not skip, reorder, or merge protocol steps unless the user explicitly approves the deviation first.
- For workflow skills, execute each listed child-skill step explicitly and report step-by-step evidence.
- If a required step/tool cannot run in this environment, stop and ask the user before adapting.
Codex Project-Reference Loading (No Hooks)
Codex uses static project-reference loading instead of runtime-injected project docs.
When coding, planning, debugging, testing, or reviewing, open project docs explicitly using this routing.
Always read:
docs/project-config.json (project-specific paths, commands, modules, and workflow/test settings)
docs/project-reference/docs-index-reference.md (routes to the full docs/project-reference/* catalog)
docs/project-reference/lessons.md (always-on guardrails and anti-patterns)
Missing/stale context route: If docs/project-config.json, the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any task-required reference doc is missing or stale, auto-run $project-init or the narrow setup route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) before ordinary project-specific work. If Codex mirrors or AGENTS.md are missing/stale, ask the user to run $sync-codex; do not auto-run it.
Situation-based docs:
- Project structure/architecture/tech-stack/deployment/setup (any layer โ backend, frontend, or infra):
project-structure-reference.md
- Backend/CQRS/API/domain/entity changes:
backend-patterns-reference.md, domain-entities-reference.md
- Frontend/UI/styling/design-system:
frontend-patterns-reference.md, scss-styling-guide.md, design-system/README.md
- Spec authoring,
docs/specs/ pathing, or TC format: feature-spec-reference.md, spec-system-reference.md, spec-principles.md
- Behavior/public-contract changes or spec-test-code sync:
workflow-spec-test-code-cycle-reference.md plus the spec docs above
- Derived spec indexes/ERDs/reimplementation guides:
spec-system-reference.md and source Feature Specs under docs/specs/
- Integration test implementation/review:
integration-test-reference.md
- E2E test implementation/review:
e2e-test-reference.md
- Code review/audit work:
code-review-rules.md plus domain docs above based on changed files
Do not read all docs blindly. Start from docs-index-reference.md, then open only relevant files for the task.
[BLOCKING] Execute skill steps in declared order. NEVER skip, reorder, or merge steps without explicit user approval.
[BLOCKING] Before each step or sub-skill call, update task tracking: set in_progress when step starts, set completed when step ends.
[BLOCKING] Every completed/skipped step MUST include brief evidence or explicit skip reason.
[BLOCKING] If Task tools are unavailable, create and maintain an equivalent step-by-step plan tracker with the same status transitions.
Quick Summary
Goal: Validate UI/frontend changes for the six visual-quality dimensions that break in production but slip past correctness review โ long-content overflow & truncation, responsive multi-screen layout (flex-wrap / row-to-column so it stays usable on small devices), flex-grow vs fixed sizing, z-index scale discipline, SCSS/CSS/BEM styling quality, and async UI states & feedback (loading indicator, user-visible error surface, empty state, in-flight disable) โ so frontend/UI changes survive real content, responsive layouts, layering, styling conventions, and the loading/error/empty branches before handoff.
Default scope: All uncommitted frontend changes (staged + unstaged) matching the frontend path and file-extension patterns declared by the project configuration/docs index. Override: specify files, directories, components, or full frontend codebase.
CONDITIONAL โ SKIP when no frontend files in scope. In workflow context this skill is SKIPPED when the diff has no files matching the project frontend path/extension patterns. If invoked standalone with no frontend changes โ announce "No frontend changes detected โ ui-review skipped" and report clean.
ROUTING BOUNDARY (read before starting):
ui-review (this skill) โ the project UI review gate. Purpose: find issues, assign severity, give project-specific fix guidance citing real reuse targets (sourced from the project reference docs). It complements architecture-review. In workflow-review-changes it runs in TWO places by design (keep both): (a) INTERNALLY as changes-review's UI dimension (step 1), AND (b) as a DEDICATED conditional parallel-batch member (step 9, ui-ux-designer sub-agent). Both fire only when frontend files are in scope.
web-design-guidelines โ a generic, standalone accessibility / UX checklist. Cross-read it for a11y depth (WCAG, focus order, ARIA, contrast); do NOT duplicate its content here.
ui-ux-designer โ specialized UI/UX, accessibility, responsive layout, and design-token review/authoring sub-agent when the local agent catalog provides it.
MANDATORY MUST ATTENTION Plan tasks to READ UI rules BEFORE reviewing:
- Project styling rules doc โ BEM convention, mixins, variables, responsive patterns (READ FIRST โ primary styling rules source; resolve via project config/docs index)
- Project design-system/token doc โ design tokens, especially the Z-Index & Layering section
- Project frontend architecture/patterns doc โ base component classes, state/store, API service, lifecycle teardown rules shared with
architecture-review
- Project code-review rules doc โ anti-patterns and conventions
Not found โ search: "scss styling", "design tokens", "frontend patterns". Rules come from docs โ NOT general knowledge.
Workflow:
- Phase 0: Load UI Rules โ Resolve and read the four project UI/styling rule docs above
- Phase 1: Determine Scope โ Changed frontend files (default) or user-specified scope
- Phase 2: Blast Radius โ Run graph trace if graph.db exists
- Phase 3: UI Category Review โ Check each file against all 6 applicable categories
- Phase 4: Finalize โ Generate compliance report with PASS/BLOCKED/WARN verdicts
- Fix Loop: Validate โ Fix โ Full UI Re-Review โ validate findings first; after validated fixes, rerun the full UI review using the local sub-agent selection guide only when that protocol calls for agents
Key Rules:
- Write findings to
plans/reports/ui-review-{date}-{slug}.md
- BLOCKED = must fix before merge | WARN = review and decide | PASS = compliant
- Every violation needs
file:line proof + grep 3+ counterexamples before flagging
- Review is read-only until
$why-review --validate-findings confirms findings; fixes may happen only in the validated fix loop or downstream plan/feature-implement, and every fix restarts a full UI review from Phase 0 with brand-new tasks.
Your Mission
$ARGUMENTS
First Principle โ Easy to Change
The success metric of every coding decision is future change cost.
DRY, SRP, abstraction, design patterns, naming, layering, tests โ every
technique exists to serve one goal: making the next change cheaper.
When evaluating styling, a layout, a token, or a component, ask:
does this make the next change cheaper or more expensive?
- Reject "best practices" that raise change cost (hardcoded values forcing
per-file edits, hand-rolled overflow handling, raw breakpoints,
copy-pasted truncation CSS).
- Name the real enemies in findings: magic values, duplicated styling
knowledge, fixed sizing that fights the viewport, cross-system token
mixing, z-index escalation wars.
- A simpler layout that survives 320px and a 200-char value beats a
pixel-perfect fixed layout that breaks on either.
Apply this lens before invoking any specific rule, pattern, or checklist
below โ if a downstream rule would raise change cost, this principle wins.
Review Mindset (NON-NEGOTIABLE)
Skeptical. Every claim needs traced proof, confidence >80%.
- NEVER flag a styling violation without reading the actual SCSS/template + tracing the rendered element
- Every finding MUST include
file:line evidence
- Before flagging a pattern violation: grep 3+ existing examples โ codebase convention wins
- Question: "Is this actually a violation, or an established exception (icon dimensions, fixed brand assets, genuinely fixed UI)?"
Phase 0: Load UI Rules (MANDATORY FIRST) (MUST ATTENTION)
MUST ATTENTION: Read project UI docs BEFORE reviewing. Rules come from docs, not general knowledge.
- read the project styling rules doc โ extract BEM convention, mixin names, variable names, responsive breakpoint mixins, nesting limits
- read the project design-system/token doc โ extract design tokens and the Z-Index & Layering section
- read the project frontend architecture/patterns doc โ extract base component classes, store/effect patterns, API service base, lifecycle teardown pattern
- read the project code-review rules doc โ extract frontend anti-patterns and review rules directly
CROSS-SYSTEM WARNING (carry through every category): Do NOT mix token systems with incompatible root-size, namespace, or layer assumptions in one file. When flagging a fix, recommend whichever token system the file already imports/uses; never introduce another system unless the project docs explicitly require migration.
Phase 1: Determine Scope
Default (no override): Review all uncommitted frontend changes.
git status
git diff
git diff --cached
- Collect file list to review
- Filter to files matching the project frontend path/extension patterns resolved from project config/docs
- If ZERO frontend files match โ announce
"No frontend changes detected โ ui-review skipped" and report clean (honor the CONDITIONAL skip)
Phase 2: Blast Radius (if graph.db exists)
- If
.code-graph/graph.db exists: run graph trace on key changed component files
- Record: impacted file count, shared-component fan-out (a changed shared-library component affects every consumer app), risk level
- Prioritize review by highest-impact files first (shared library components > app-local components)
- Graph unavailable: note "Graph not available โ skipping blast radius" and proceed
For each changed component/style file with downstream impact:
python .claude/scripts/code_graph trace <changed-file> --direction both --json
Use --node-mode file first (10-30x less noise), then --node-mode function for detail. Flag shared-component consumers impacted by a styling or layout change.
Phase 3: UI Category Review
Create report: plans/reports/ui-review-{date}-{slug}.md
For EACH file in scope, evaluate against ALL applicable categories. Skip categories not applicable to the file type (e.g., a pure .ts store file skips overflow/sizing/z-index but still hits Category 5's architecture checks and Category 6's loading/error/empty-state wiring).
Apply the Think: reasoning prompt before each category โ derive violations, do NOT recite checklists.
Category 1: Long-Content Overflow & Truncation โ Severity: WARN (HIGH when a flex child truncates with no min-width: 0)
Think: Does every text container survive a 200-char value? Single-line or multi-line? Can the user still read the full value when it is truncated?
Detection signals:
- Hand-rolled
text-overflow: ellipsis (with white-space: nowrap / overflow: hidden re-declared by hand) instead of the project mixin/directive
- A flex child that truncates but has NO
min-width: 0 โ the flex-overflow trap: a flex item's default min-width: auto refuses to shrink below content width, so ellipsis never triggers
- Truncated text with NO tooltip /
title to reveal the full value
DECISION RULE the reviewer enforces:
- Single-line labels / table cells / chips โ ellipsis + tooltip-on-overflow
- Multi-line prose / descriptions โ wrap or
-webkit-line-clamp
Project fix guidance (cite real reuse targets from the resolved styling rules doc):
- Prefer the project's documented overflow/ellipsis directive, component, or utility. It must expose the full value only when the element actually overflows and must handle the flex
min-width trap.
- OR the project's documented truncate/text-ellipsis mixins or utility classes from the styling rules doc.
- Multi-line: use the project-documented clamp pattern.
GOOD vs BAD: a utility/token-driven truncation that exposes the full value on overflow (tooltip/title) is correct; a hand-rolled substring / width-math truncation, or truncated text with no tooltip, is the anti-pattern. Cite the styling rules doc for the project's reuse targets.
Category 2: Responsive Multi-Screen via Flex โ Severity: WARN (BLOCKED only when content is broken on a small screen โ clipped, cut off, or unreachable)
Think: Is this usable at 320 / 768 / 1024 / 1440? Does the layout flex, wrap, and reflow from row to column on small screens? If it genuinely cannot reflow, does it at least stay usable via a fixed min-width/min-height + overflow: auto scroll โ or does content get clipped, cut off, or pushed out of reach?
Small-screen usability โ the minimum bar (canonical):
- Preferred: reflow โ
flex-wrap: wrap, a flex-direction: row โ column switch at the breakpoint, or a responsive grid that collapses to a single column.
- Acceptable fallback: when a layout genuinely can't reflow (dense tables, canvases, diagrams, wide data grids), a fixed
min-width/min-height with overflow: auto is fine โ scrolling is OK, not a defect. Do NOT flag a component BLOCKED merely because it scrolls.
- Hard minimum (BLOCKED if violated): on a small screen the UI is usable and nothing is broken โ no clipped, cut-off, or unreachable content/controls (e.g. a submit button pushed off-screen with no scroll path, text overlapping, a fixed row that overflows AND hides content instead of scrolling).
- Escalation: if making a surface small-screen-usable would need a refactor too large for the current change, STOP and confirm scope with the user before proceeding โ note it as a finding, do not silently rewrite the layout.
Detection signals:
- Raw
@media (max-width: NNNpx) / (min-width: NNNpx) in component SCSS that bypasses the breakpoint mixins
- A multi-child flex
row with NO flex-wrap, NO flex-direction: column override, AND no overflow: auto escape โ content is trapped and clips on a phone (BLOCKED); the same row WITH a scroll escape is at most WARN (prefer reflow)
- Multi-column CSS grid with fixed column counts / fixed track widths and no single-column collapse and no scroll container at small breakpoints
- Non-flex fixed layouts (absolute positioning, fixed px widths on containers) that cannot reflow AND cannot scroll โ content lost off-screen
- Content clipped, overlapping, or a control pushed out of reach below ~360px with no scroll path (BLOCKED). Horizontal scroll by itself, with all content still reachable, is the acceptable fallback โ not a finding.
Project fix guidance:
- Preferred: the project documented responsive-flex mixins/utilities; add
flex-wrap: wrap and/or the documented row โ column breakpoint switch so the layout stacks vertically on small screens
- Fallback (when reflow isn't feasible): give the container a sensible
min-width/min-height and overflow: auto so everything stays reachable by scroll
- Breakpoints from the project breakpoint tokens โ NEVER inline pixel breakpoints
- Large layout refactor required โ surface it as a finding and confirm with the user; don't bundle a big responsive rewrite into an unrelated change
Anti-patterns: raw @media pixel breakpoints that bypass the project's breakpoint mixins; a flex-direction: row with no wrap, no column fallback, AND no scroll escape so content clips; and non-flex fixed grids that neither reflow nor scroll. Cite the styling rules doc for documented offenders; grep the changeset for the same patterns.
Category 3: Flex-Grow vs Fixed Width/Height (prefer min/max) โ Severity: WARN
Think: Must this size be fixed, or can it grow/shrink with content + viewport?
Detection signals:
- Fixed
width: / height: in px (โฅ ~3 digits) on containers / cards / forms / dialogs
Project fix guidance:
- Prefer
flex: 1 / flex-grow + max-width / min-width caps, and min-width: 0 on truncating flex children
- The project flex-container mixin/utility documented in the styling rules doc
- Reserve fixed px for icons / borders / genuinely fixed UI
Anti-patterns: large fixed width: / height: in px on containers / cards / forms / dialogs (e.g. width: 964px, height: 772px) that should flex with content + viewport. Cite the styling rules doc for documented offenders.
Category 4: Z-Index Scale Discipline โ Severity: BLOCKED (HARD GATE)
Think: Which layer does this surface belong to (base / raised / dropdown / sticky / modal / toast)?
Detection signals:
- Raw numeric
z-index (literal value instead of a token)
- ANY
z-index with !important โ BLOCKED (an escalation war that the next dev will only beat with a bigger literal)
Project fix guidance โ use tokens:
- The project documented z-index layer tokens
- Existing legacy/framework token systems only when the current file already uses that system
- The semantic layer variables declared canonical by the project design-system doc
Cross-reference the project design-system Z-Index & Layering map. The chosen token MUST match the surface's semantic layer.
GOOD vs BAD: a z-index set from a semantic token / layer scale is correct; a raw literal (e.g. z-index: 99999, z-index: 10000) or z-index: N !important is the anti-pattern. Cite the design-system and styling docs for the project's token scale and documented offenders.
Category 5: SCSS/CSS Best Practices & BEM โ Severity: WARN (BLOCKED on !important, chained BEM modifiers)
Think: Does this stylesheet read cleanly, follow BEM, and use tokens โ or does it hardcode, over-nest, and chain modifiers?
SCSS/BEM rules (canonical): BEM classes on ALL template elements (block__element--modifier). No magic numbers โ use variables / design tokens. Max 3 nesting levels.
Detection signals:
- Nesting > 3 levels
- Hardcoded hex colors (should use CSS vars / design tokens)
px where rem is expected
- Chained BEM modifiers (
.block__element.--modifier) โ .--mod MUST be a separate class, NEVER chained โ BLOCKED
- Template elements missing BEM classes
!important โ BLOCKED
Apply fixes per the resolved project styling rules doc.
Frontend architecture checks (OWNED JOINTLY WITH architecture-review Category 8 โ reference, do not drift):
These checks are lifted from architecture-review Category 8 so the two skills stay synchronized. They are owned jointly; when one changes, update both. They apply to the .ts files in scope:
- Components MUST extend the project-documented base component/form/store component classes (BLOCKED)
- State MUST use the project-documented store/effect pattern โ NEVER ad hoc local state when the project provides a canonical store pattern (BLOCKED)
- API services MUST extend the project-documented API service base โ NEVER raw HTTP clients when the project provides a service abstraction (BLOCKED)
- All subscriptions MUST use the project's auto-teardown operator โ NEVER manual unsubscribe (BLOCKED)
- All template elements MUST have BEM classes (WARN)
- Logic in lowest layer: Model > Service > Component (WARN)
Category 6: Async UI States & Feedback โ Loading / Error / Empty / Disabled โ Severity: BLOCKED (HARD GATE when an async fetch or mutation renders NO loading indicator OR NO user-visible error surface)
This is the fundamental UI-resilience gate. A screen whose happy path renders perfectly but shows a frozen blank while loading, fails silently on error, or shows nothing when empty is a broken user experience. Every async or interactive surface MUST answer three questions for the user: what do I see while it's working, when it fails, and when there's nothing?
Think: For EACH async operation the file performs (data fetch, form submit, mutation, navigation-triggered load, subscription), trace what the user actually sees in the in-flight, failure, and zero-result branches โ not just the success branch. If any of those three branches renders a blank/frozen screen or nothing at all, that is the finding.
The essential states every async/interactive surface MUST handle (canonical vocabulary โ shared verbatim with design-spec "Component States Checklist": Default / Loading / Disabled / Error / Empty / Success):
- Loading โ every in-flight async request MUST render a loading indicator (spinner / skeleton / progress bar), NEVER a frozen or blank screen. Lists/tables โ skeleton rows; buttons โ in-button spinner + disabled.
- Error โ every operation that can fail (network, validation, server error) MUST surface a human-readable error to the user WITH a recovery/retry path where sensible. NEVER a silent failure, a swallowed
catch, or a raw stack trace / raw error object rendered to the user.
- Empty โ every collection / list / table view MUST render a meaningful empty state (message + optional CTA) when it has zero items, NOT a blank area.
- Disabled / in-flight guard โ submit/action controls MUST disable (or show busy) while their request is in-flight, to prevent double-submission.
- Success โ a completed mutation SHOULD give confirmation feedback (toast / inline / visibly updated data).
Detection signals:
- An async call (fetch / HTTP /
subscribe / awaited mutation) whose template binds NO loading flag (isLoading / pending / loading$ / skeleton) โ BLOCKED
- A
.catch / try-catch / error callback that logs or swallows the error but renders NO user-visible error surface โ BLOCKED
- A raw error shown to the user (stack trace, raw JSON, unmapped exception) โ WARN
- A list/table rendered from a collection with NO empty-state branch (
@empty, *ngIf="!items.length", items.length === 0 ? โฆ) โ WARN (BLOCKED when the collection is the screen's primary content)
- A submit handler that does NOT disable its trigger while in-flight (double-submit risk) โ WARN (BLOCKED for payment / create / irreversible actions)
Check for centralized handling BEFORE flagging BLOCKED (avoid false positives): many apps satisfy loading/error at the app level โ a route-level progress bar, an HTTP interceptor that shows a global spinner/toast, an error boundary, or a base component that renders loading/error for all its children. If such a mechanism demonstrably covers this surface, the local component is compliant โ grep for the shared mechanism (per this skill's "grep 3+ counterexamples / established exception" rule) and downgrade or drop the finding. Flag BLOCKED only when NO layer โ local or global โ gives the user a loading indicator / error surface.
Project fix guidance (cite real reuse targets from the resolved frontend/patterns + design-system docs):
- Prefer the project's documented loading component / skeleton / spinner and the documented error-banner / empty-state components or patterns โ NEVER hand-roll one-off state UI when a canonical one exists.
- Bind loading / error / empty off the store / view-model / API-service state per the project's documented state pattern โ state belongs in the lowest layer (Model > Service > Component), not improvised in the template.
GOOD vs BAD: a fetch bound to isLoading โ skeleton, error โ inline retry banner, and empty โ placeholder is correct; a fetch that renders ONLY the populated happy path (blank while loading, nothing on error, blank when empty) is the anti-pattern. Cite the frontend-patterns and design-system docs for the project's reuse targets.
Note vs Category 5's Bug-Detection "Error Handling": the shared Bug Detection protocol checks that catch scope is correct and exceptions are not swallowed at the code level; Category 6 checks that the failure/loading/empty branch produces a user-visible state at the UI level. Both must pass โ a correctly-caught error that renders nothing still fails Category 6.
Phase 4: Finalize โ UI Compliance Report
Update report with final sections:
Verdict Scoring
| Verdict | Condition |
|---|
| BLOCKED | 1+ BLOCKED findings โ must fix before merge |
| WARN | 0 BLOCKED, 1+ WARN findings โ review and decide |
| PASS | 0 BLOCKED, 0 WARN โ UI compliant |
Severity vocabulary (single source of truth). Category headers and this verdict table use BLOCKED / WARN / PASS. The fresh sub-agent (Phase 5 and Round 2) emits Critical / High / Medium / Low + PASS / FAIL from the shared review-protocol template. Reconcile the two with this mapping โ do NOT treat them as separate scales:
| This skill | Sub-agent (Round 2) | Merge gate |
|---|
| BLOCKED | Critical / High โ FAIL | Must fix before merge |
| WARN | Medium / Low โ WARN/INFO | Review and decide |
| PASS | (no findings) โ PASS | Merge-clear |
A category's "(HIGH when โฆ)" note is NOT a separate tier โ it means that WARN escalates to BLOCKED when the stated condition holds (i.e., the finding is a real rendered bug, not a latent risk).
Report Structure
# UI Review Report โ {date}
## Scope
- Files reviewed: {count}
- Components / apps affected: {list}
- Blast radius: {summary from Phase 2}
## Verdict: {PASS | WARN | BLOCKED}
## BLOCKED Findings (Must Fix)
### {Category}: {description}
- **File:** {path}:{line}
- **Rule:** {rule from project UI doc}
- **Evidence:** {what was found}
- **Fix:** {reuse target to use โ directive / mixin / token}
## WARN Findings (Review)
### {Category}: {description}
- **File:** {path}:{line}
- **Rule:** {rule from project UI doc}
- **Evidence:** {what was found}
- **Recommendation:** {suggested action}
## PASS Categories
- {list of categories that passed with no findings}
## UI Health Summary
- Long-content Overflow & Truncation: {PASS/WARN/BLOCKED}
- Responsive Multi-Screen (flex-wrap / rowโcolumn, usable on small devices): {PASS/WARN/BLOCKED}
- Flex-Grow vs Fixed Sizing: {PASS/WARN/BLOCKED}
- Z-Index Scale Discipline: {PASS/WARN/BLOCKED}
- SCSS/CSS Best Practices & BEM: {PASS/WARN/BLOCKED}
- Async UI States & Feedback (loading / error / empty / disabled): {PASS/WARN/BLOCKED}
- Frontend Architecture (joint w/ architecture-review): {PASS/WARN/BLOCKED/N/A}
Systematic Review Protocol (10+ changed frontend files)
- Categorize โ Group files by app / shared-library / component concern
- Parallel Sub-Agents โ Launch one UI/UX-specialized sub-agent per group with the UI-category checklist
- Synchronize โ Collect findings, cross-reference shared-component consumers and cross-system token mixing
- Consolidate โ Single holistic report with per-category verdicts
Phase 5: Why-Review Findings Validation Gate (MANDATORY when findings exist)
Purpose: Adversarial validation of own findings BEFORE handoff. Catches over-flagged Highs, false positives, and severity inflation at the source rather than letting them propagate downstream.
Trigger: Any finding produced (Critical, High, Medium, OR Low). Skip ONLY when the report's verdict is unconditional PASS with literally zero findings.
Protocol:
- Read own finalized report from
plans/reports/ui-review-{date}-{slug}.md (the exact path written in Phase 3 โ NOT {skill}-โฆ)
- Invoke
$why-review --validate-findings plans/reports/ui-review-{date}-{slug}.md
- Read the validation verdict path returned by why-review, expected as
plans/reports/why-review-validate-{date}.md
- If why-review demotes/removes any finding: UPDATE own finalized report with revised severities, remove false positives, and add a
## Why-Review Validation Notes section citing what changed and why
- If why-review confirms all findings: Append
## Why-Review Validation line to own report stating "All N findings re-validated against actual code; no severity changes."
- If the report changed after validation: re-run this validation gate, maximum 2 validation passes, until the report's remaining findings are validated or zero findings remain.
Skip conditions (record explicit reason if skipping):
- Verdict is unconditional PASS with zero findings โ log "Skipped โ no findings to validate"
- Why-review skill itself is the active context (avoid recursion)
Why this exists: AI sub-agent reports inherit confirmation bias โ the orchestrator absorbs severity claims as ground truth. The 2026-05-09 review incident produced 5 Highs; adversarial validation demoted 3 of them. Codify this as standard practice.
Phase 6: Validated Fix + Full UI Re-Review Loop (MANDATORY when validated findings remain)
Trigger: Phase 5 returns CLEAN/validated and the UI review report still has one or more findings that must be fixed.
Protocol:
- Create a fresh fix-cycle task list before editing. Do not reuse the review tasks.
- Fix only findings that survived
$why-review --validate-findings; route broader or cross-cutting fixes through the parent $plan + $feature-implement flow when this skill is running inside a workflow.
- Run targeted verification for the fixed UI files and any affected consumers.
- Re-invoke
$ui-review from Phase 0 over the full current UI scope, not only the fixed files.
- The re-run MUST create brand-new review tasks, reload the UI docs, determine scope again, rerun blast radius where applicable, and review every changed UI file from the start.
- Repeat validate โ fix โ full UI re-review until a complete pass has zero findings.
- If the same validated blocker repeats across 3 full invocations with no progress, stop and ask the user for a decision.
Non-negotiable rules:
- Never fix a finding before
$why-review --validate-findings validates it.
- Never mark UI review clean after a targeted fix check only; the clean verdict must come from a full Phase 0 restart.
- Never review only fixed files during the recursive pass; analyze all UI files in scope again.
- Never reuse old todo/task items for the recursive review pass.
Workflow Recommendation
MANDATORY โ NO EXCEPTIONS: If NOT already in a workflow, MUST use ask the user directly to ask user. Do NOT judge task complexity or decide "simple enough to skip" โ user decides, not you:
- Activate
workflow-review-changes workflow (Recommended) โ run the canonical workflow from .claude/workflows.json; it runs UI review in TWO places by design (keep both) โ internally as $changes-review's UI dimension AND as a dedicated conditional parallel-batch reviewer (step 9) โ alongside findings validation, the other parallel reviewers, code-simplifier self-review, fix-plan cycle, full re-review restart, docs, and handoff.
- Execute
$ui-review directly โ run this skill standalone
Next Steps
MANDATORY โ NO EXCEPTIONS: After completing, use ask the user directly to present:
- "$code-simplifier" (Recommended) โ Simplify and refine the styling/component code
- "$web-design-guidelines" โ Generic accessibility / UX checklist for a11y depth
- "Skip, continue manually" โ user decides
AI Agent Integrity Gate (NON-NEGOTIABLE)
Before reporting ANY work done:
- Grep every removed name. Extraction/rename/delete โ grep confirms 0 dangling refs across ALL file types (SCSS
@use, template class refs, TS imports)
- Ask WHY before changing. Existing values intentional until proven otherwise โ a fixed
width may be a genuinely fixed UI element; no "fix" without traced rationale
- Verify ALL outputs. One compiled stylesheet โ all consumers โ a shared-component style change affects every consuming app
- Evaluate pattern fit. Copying a nearby mixin/token? Verify the file imports/uses the SAME token system and does not mix incompatible project token systems
- New artifact = wired artifact. Created a class/mixin? Prove it is imported, referenced in the template, and reachable
[IMPORTANT] Use task tracking to break ALL work into small tasks BEFORE starting. Simple tasks: ask user whether to skip.
Fresh Context Re-Review โ Eliminate orchestrator confirmation bias after fixes by restarting the full review with isolated sub-agents where applicable.
Why: The main agent knows what it (or $feature-implement) just fixed and rationalizes findings accordingly. A fresh sub-agent has ZERO memory, re-reads from scratch, and catches what the main agent dismissed. Sub-agent bias is mitigated by (1) fresh context, (2) verbatim protocol injection, (3) main agent not filtering the report.
When: ONLY after a validated-finding fix cycle, or when the user/workflow explicitly requests an independent high-risk UI synthesis pass. A review pass that finds issues triggers validation first; it does NOT trigger a fresh-context pass over the same findings before validation/fix.
How:
- Start a NEW full review invocation/task breakdown; when that protocol calls for agents, spawn a NEW
spawn_agent tool call โ use the UI/UX-specialized agent_type from the local sub-agent selection guide
- Inject ALL required review protocols VERBATIM into the prompt โ see
SYNC:review-protocol-injection for the full list and template. Never reference protocols by file path; AI compliance drops behind file-read indirection (see SYNC:shared-protocol-duplication-policy)
- Sub-agent re-reads ALL target files from scratch via its own tool calls โ never pass file contents inline in the prompt
- Sub-agent writes structured report to
plans/reports/{review-type}-round{N}-{date}.md
- Main agent reads the report, integrates findings into its own report, DOES NOT override or filter
Rules:
- NEVER reuse a sub-agent across rounds โ every iteration that uses sub-agents spawns a NEW
spawn_agent call
- NEVER fix unvalidated findings; validate first using the caller's validation gate
- NEVER skip the full review restart after a validated fix cycle โ every fix invalidates the prior verdict
- Continue until a complete full review pass has zero findings; if the same blocker repeats across 3 full invocations with no progress, escalate by asking the user directly
- Track iteration count in conversation context (session-scoped, no persistent files)
Sub-Agent Type Override
MANDATORY: UI reviews spawn the UI/UX-specialized sub-agent defined by the local sub-agent selection guide.
Keep agent_type: "ui-ux-designer" in the canonical template below when that agent type exists in the local catalog.
Rationale: The shared sub-agent selection guide routes frontend UI/UX, accessibility, responsive layout, and design-token work to the UI/UX specialization. Do not fall back to a generic code-reviewer catch-all unless the local catalog lacks a UI/UX reviewer.
Review Protocol Injection โ Every fresh sub-agent review prompt MUST embed 11 protocol blocks VERBATIM. The template below has ALL 11 bodies already expanded inline. Copy the template wholesale into the Agent call's prompt field at runtime, replacing only the {placeholders} in Task / Round / Reference Docs / Target Files / Output sections with context-specific values. Do NOT touch the embedded protocol sections.
Why inline expansion: Placeholder markers would force file-read indirection at runtime. AI compliance drops significantly behind indirection (see SYNC:shared-protocol-duplication-policy). Therefore the template carries all 11 protocol bodies pre-embedded.
Subagent Type Selection
ui-ux-designer โ default for UI reviews when the local agent catalog provides it
code-reviewer โ fallback only when the local catalog lacks a UI/UX-specialized reviewer
Canonical Agent Call Template (Copy Verbatim)
spawn_agent({
description: "Fresh Round {N} UI review",
agent_type: "ui-ux-designer",
prompt: `
## Task
{review-specific task โ e.g., "Review all uncommitted frontend changes for UI quality: long-content overflow, responsive layout (flex-wrap / rowโcolumn, usable on small devices), flex-vs-fixed sizing, z-index discipline, SCSS/BEM, and async UI states & feedback (loading indicator, user-visible error surface, empty state, in-flight disable)" | "Review SCSS/template files under {path}"}
## Round
Round {N}. You have ZERO memory of prior rounds. Re-read all target files from scratch via your own tool calls. Do NOT trust anything from the main agent beyond this prompt.
## Protocols (follow VERBATIM โ these are non-negotiable)
### Spec โ Tests โ Code Triangulation
DO THIS FIRST โ before any per-protocol check below. The review target is the WHOLE PACKAGE, not the diff alone: load the behavior's spec (ยง3 ACs / ยง4 BRs / ยง8 TCs), its tests, and the changed code TOGETHER, and reason about their mutual consistency BEFORE judging any one in isolation.
1. Locate all three faces: the Feature Spec section(s) governing the changed behavior, the tests that guard it, and the production code that implements it. A missing face is itself a finding (SPEC-GAP / TEST-GAP / DEAD-SPEC).
2. Triangulate pairwise โ every disagreement is a finding; classify which face is wrong:
- code vs spec: behavior the code does that no ยง3/ยง4/ยง8 rule describes โ CODE-EXTRA or SPEC-STALE; a [HARD] ยง4 rule or ยง5 invariant with no enforcing code path โ CODE-WRONG.
- tests vs spec: a ยง8 TC with no test, or a test asserting behavior no TC/rule names โ TEST-GAP or SPEC-SILENT.
- tests vs code: a changed code path with no covering test โ TEST-GAP; a test that still passes against a deliberately broken invariant โ WEAK-TEST (apply the mutation thinking in Bug Detection).
3. Hidden-rule capture: any invariant the code enforces but the spec never states (SPEC-SILENT) MUST be surfaced as a finding to add into ยง3/ยง4/ยง8 AND guarded with a test โ the enrichment loop, never a silent pass.
4. Only after the three faces agree โ or every disagreement is logged as a finding โ proceed to the per-protocol checks below; when enrichment adds spec/test content, re-review the package against the enriched spec.
NEVER mark review PASS while any spec/test/code face disagrees without a logged finding. The diff is the entry point; the package is the unit of judgment.
### Evidence-Based Reasoning
Speculation is FORBIDDEN. Every claim needs proof.
1. Cite file:line, grep results, or framework docs for EVERY claim
2. Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
3. Cross-service validation required for architectural changes
4. "I don't have enough evidence" is valid and expected output
BLOCKED until: Evidence file path (file:line) provided; Grep search performed; 3+ similar patterns found; Confidence level stated.
Forbidden without proof: "obviously", "I think", "should be", "probably", "this is because".
If incomplete โ output: "Insufficient evidence. Verified: [...]. Not verified: [...]."
### Bug Detection
MUST check categories 1-4 for EVERY review. Never skip.
1. Null Safety: Can params/returns be null? Are they guarded? Optional chaining gaps? .find() returns checked?
2. Boundary Conditions: Off-by-one (< vs <=)? Empty collections handled? Zero/negative values? Max limits?
3. Error Handling: Try-catch scope correct? Silent swallowed exceptions? Error types specific? Cleanup in finally?
4. Resource Management: Connections/streams closed? Subscriptions unsubscribed on destroy? Timers cleared? Memory bounded?
5. Concurrency (if async): Missing await? Race conditions on shared state? Stale closures? Retry storms?
6. Stack-Specific: Check the configured language/runtime pitfalls and framework-specific failure modes discovered from local code.
Classify: CRITICAL (crash/corrupt) โ FAIL | HIGH (incorrect behavior) โ FAIL | MEDIUM (edge case) โ WARN | LOW (defensive) โ INFO.
### Design Patterns Quality
Priority checks for every code change:
1. DRY via OOP: Same-suffix classes (*Entity, *Dto, *Service) MUST share base class. 3+ similar patterns โ extract to shared abstraction.
2. Right Responsibility: Logic in LOWEST layer (Entity > Domain Service > Application Service > Controller). Never business logic in controllers.
3. SOLID: Single responsibility (one reason to change). Open-closed (extend, don't modify). Liskov (subtypes substitutable). Interface segregation (small interfaces). Dependency inversion (depend on abstractions).
4. After extraction/move/rename: Grep ENTIRE scope for dangling references. Zero tolerance.
5. YAGNI gate: NEVER recommend patterns unless 3+ occurrences exist. Don't extract for hypothetical future use.
Anti-patterns to flag: God Object, Copy-Paste inheritance, Circular Dependency, Leaky Abstraction.
### Logic & Intention Review
Verify WHAT code does matches WHY it was changed.
1. Change Intention Check: Every changed file MUST serve the stated purpose. Flag unrelated changes as scope creep.
2. Happy Path Trace: Walk through one complete success scenario through changed code.
3. Error Path Trace: Walk through one failure/edge case scenario through changed code.
4. Acceptance Mapping: If plan context available, map every acceptance criterion to a code change.
5. Tests Verify Intent: For test/spec changes, verify tests name the protected business rule or invariant and would fail if that intent breaks.
6. Migration Test Exclusion: Do not write tests for migration code. Schema/data migrations are one-time execution paths, not core application logic.
NEVER mark review PASS without completing both traces (happy + error path).
### Test Spec Verification
Map changed code to test specifications.
1. Identify the project's test/spec format from existing docs, test-case files, BDD feature files, or spec folders.
2. Every changed code path MUST map to a corresponding test case/spec (or flag as "needs test case").
3. New functions/endpoints/handlers โ flag for test spec creation.
4. Migration files are excluded from test/spec creation; schema/data migrations are one-time execution paths, not core application logic.
5. If spec evidence fields exist, verify they point to actual code (file:line, not stale references).
6. Verify each meaningful test case names the business intent/invariant; flag behavior-only cases that only mirror implementation details.
7. Auth/data changes โ verify corresponding authorization and data-state test cases exist.
8. If no specs exist for a changed path โ log the gap and recommend the project's test-spec workflow.
NEVER skip test mapping. Untested code paths are the #1 source of production bugs.
### Behavioral Delta Matrix
MANDATORY for any bugfix review. Produce input-state ร pre-fix ร post-fix ร delta table BEFORE writing verdict.
- Minimum 3 rows; include at least one row OUTSIDE the original bug report.
- Any "REGRESSION" delta โ review returns FAIL until a preservation test is added.
- Narrative descriptions do NOT substitute for the matrix.
Example rows (external-record sync fix):
| Input | Pre-fix | Post-fix | Delta |
| --------------------- | ------- | ------------------------- | ---------- |
| Record exists (valid) | Reused | Always recreated โ orphan | REGRESSION |
| Record missing (404) | Error | Recreated | Fixed |
### Fix-Layer Accountability
NEVER fix at the crash site. Trace the full flow, fix at the owning layer. The crash site is a SYMPTOM, not the cause.
MANDATORY before ANY fix:
1. Trace full data flow โ Map the complete path from data origin to crash site across ALL layers (storage โ backend โ API โ frontend โ UI). Identify where bad state ENTERS, not where it CRASHES.
2. Identify the invariant owner โ Which layer's contract guarantees this value is valid? Fix at the LOWEST layer that owns the invariant, not the highest layer that consumes it.
3. One fix, maximum protection โ If fix requires touching 3+ files with defensive checks, you are at the wrong layer โ go lower.
4. Verify no bypass paths โ Confirm all data flows through the fix point. Check for direct construction skipping factories, clone/spread without re-validation, raw data not wrapped in domain models, mutations outside the model layer.
BLOCKED until: Full data flow traced (origin โ crash); Invariant owner identified with file:line evidence; All access sites audited (grep count); Fix layer justified (lowest layer that protects most consumers).
Anti-patterns (REJECT): "Fix it where it crashes" (crash site โ cause site, trace upstream); "Add defensive checks at every consumer" (scattered defense = wrong layer); "Both fix is safer" (pick ONE authoritative layer).
### Rationalization Prevention
AI skips steps via these evasions. Recognize and reject:
- "Too simple for a plan" โ Simple + wrong assumptions = wasted time. Plan anyway.
- "I'll test after" โ RED before GREEN. Write/verify test first.
- "Already searched" โ Show grep evidence with file:line. No proof = no search.
- "Just do it" โ Still need task tracking. Skip depth, never skip tracking.
- "Just a small fix" โ Small fix in wrong location cascades. Verify file:line first.
- "Code is self-explanatory" โ Future readers need evidence trail. Document anyway.
- "Combine steps to save time" โ Combined steps dilute focus. Each step has distinct purpose.
### Graph-Assisted Investigation
MANDATORY when .code-graph/graph.db exists.
HARD-GATE: MUST run at least ONE graph command on key files before concluding any investigation.
Pattern: Grep finds files โ trace --direction both reveals full system flow โ Grep verifies details.
- Investigation/Scout: trace --direction both on 2-3 entry files
- Fix/Debug: callers_of on buggy function + tests_for
- Feature/Enhancement: connections on files to be modified
- Code Review: tests_for on changed functions
- Blast Radius: trace --direction downstream
CLI: python .claude/scripts/code_graph {command} --json. Use --node-mode file first (10-30x less noise), then --node-mode function for detail.
### Understand Code First
HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
1. Search 3+ similar patterns (grep/glob) โ cite file:line evidence.
2. Read existing files in target area โ understand structure, base classes, conventions.
3. Run python .claude/scripts/code_graph trace <file> --direction both --json when .code-graph/graph.db exists.
4. Map dependencies via connections or callers_of โ know what depends on your target.
5. Write investigation to .ai/workspace/analysis/ for non-trivial tasks (3+ files).
6. Re-read analysis file before implementing โ never work from memory alone.
7. NEVER invent new patterns when existing ones work โ match exactly or document deviation.
BLOCKED until: Read target files; Grep 3+ patterns; Graph trace (if graph.db exists); Assumptions verified with evidence.
## Reference Docs (READ before reviewing)
- {resolved project styling rules doc}
- {resolved project design-system/token doc, especially Z-Index & Layering}
- {resolved project frontend architecture/patterns doc}
- {resolved project code-review rules doc}
## Target Files
{explicit file list OR "run git diff and filter by the project frontend path/extension patterns"}
## Output
Write a structured report to plans/reports/ui-review-round{N}-{date}.md with sections:
- Status: PASS | FAIL
- Issue Count: {number}
- Critical Issues (with file:line evidence)
- High Priority Issues (with file:line evidence)
- Medium / Low Issues
- Cross-cutting findings (cross-system token mixing, shared-component fan-out)
Return the report path and status to the main agent.
Every finding MUST have file:line evidence. Speculation is forbidden.
`
})
Rules
- DO copy the template wholesale โ including all 11 embedded protocol sections
- DO replace only the
{placeholders} in Task / Round / Reference Docs / Target Files / Output sections with context-specific content
- DO keep the UI/UX-specialized
agent_type for UI reviews when the local catalog provides it (see Sub-Agent Type Override above)
- DO NOT paraphrase, summarize, or skip any protocol section
- DO NOT pass file contents inline โ the sub-agent reads via its own tool calls so it has a fresh context
- DO NOT reference protocols by file path or tag name โ the bodies are already embedded above
- DO NOT introduce placeholder markers for the protocols โ they must stay literally expanded
Critical Purpose: UI quality โ no content overflow without escape, no broken responsive layouts (rows that never wrap or stack on small devices), no fixed sizing fighting the viewport, no z-index escalation wars, no styling/BEM drift, and no async surface that leaves the user staring at a frozen blank while loading, a silent failure on error, or a blank area when empty.
External Memory: Complex/lengthy work โ write findings to plans/reports/. Prevents context loss, serves as deliverable.
Evidence Gate: MANDATORY โ every finding requires file:line proof + confidence percentage (>80% act, <80% verify first).
fresh-context-review is intentionally OVERRIDE-only in this skill โ see the OVERRIDE:fresh-context-review block above (it uses the UI/UX-specialized ui-ux-designer agent_type, NOT the generic code-reviewer). The generic SYNC:fresh-context-review copy is deliberately omitted here so the two cannot drift into a code-reviewer vs ui-ux-designer contradiction. This mirrors how OVERRIDE:review-protocol-injection is handled (override-only, no generic SYNC copy). Do NOT re-add the generic SYNC:fresh-context-review block โ the sync-inline-versions.md propagation only updates existing SYNC: markers, so omission is stable.
Complexity Prevention (UI-scoped) โ measure code by cost of change: one UI change should map to one code change. The full backend-OOP treatise (anemic models, primitive obsession, value objects, repo leakage) does not apply to UI review and is intentionally not carried here. UI-relevant essence: (1) extract repeated component lifecycle โ 3+ forms/list views reimplementing loading/dirty/submit/pagination โ base component / hook / composable / mixin; (2) keep derivations, formatting, and validation off the template โ move them onto the model / store / view-model / API service, not inline in the component. For deeper OOP/DRY structural review of any backend the UI calls, defer to $changes-review / $architecture-review.
Graph-Assisted Investigation โ MANDATORY when .code-graph/graph.db exists.
HARD-GATE: MUST ATTENTION run at least ONE graph command on key files before concluding any investigation.
Pattern: Grep finds files โ trace --direction both reveals full system flow โ Grep verifies details
| Task | Minimum Graph Action |
|---|
| Investigation/Scout | trace --direction both on 2-3 entry files |
| Fix/Debug | callers_of on buggy function + tests_for |
| Feature/Enhancement | connections on files to be modified |
| Code Review | tests_for on changed functions |
| Blast Radius | trace --direction downstream |
CLI: python .claude/scripts/code_graph {command} --json. Use --node-mode file first (10-30x less noise), then --node-mode function for detail.
Nested Task Expansion Contract โ For workflow-step invocation, the [Workflow] ... row is only a parent container; the child skill still creates visible phase tasks.
- Call the current task list first. If a matching active parent workflow row exists, set
nested=true and record parentTaskId; otherwise run standalone.
- Create one task per declared phase before phase work. When nested, prefix subjects
[N.M] $skill-name โ phase.
- When nested, link the parent with
TaskUpdate(parentTaskId, addBlockedBy: [childIds]).
- Orchestrators must pre-expand a child skill's phase list and link the workflow row before invoking that child skill or sub-agent.
- Mark exactly one child
in_progress before work and completed immediately after evidence is written.
- Complete the parent only after all child tasks are completed or explicitly cancelled with reason.
Blocked until: the current task list done, child phases created, parent linked when nested, first child marked in_progress.
Project Reference Docs Gate โ Run after task-tracking bootstrap and before target/source file reads, grep, edits, or analysis. Project docs override generic framework assumptions.
- Identify scope: file types, domain area, and operation.
- Read
docs/project-config.json first โ the project's machine-readable map. It is the single source of truth for THIS repo (modules/paths, framework + search keywords, test/E2E/integration run-commands, design system, architecture rules, workflow patterns); ground exact paths, run-commands, and conventions on it before investigating, planning, or coding โ never assume framework defaults (CLAUDE.md + reference docs are derived from it). If it โ or the docs index, lessons.md, CLAUDE.md, AGENTS.md, or any required reference doc โ is missing or stale, auto-run $project-init or the narrow route ($project-config, $docs-init, $scan-all, $scan --target=<key>, $claude-md-init) first; if Codex mirrors or AGENTS.md are stale, ask the user to run $sync-codex (never auto-run it).
- Required docs by trigger: always
docs/project-reference/lessons.md; doc lookup docs-index-reference.md; review code-review-rules.md; backend/CQRS/API backend-patterns-reference.md; domain/entity domain-entities-reference.md; frontend/UI frontend-patterns-reference.md; styles/design scss-styling-guide.md + design-system/design-system-canonical.md; integration tests integration-test-reference.md; E2E e2e-test-reference.md; feature docs/specs feature-spec-reference.md + spec-system-reference.md + spec-principles.md; behavior/public-contract/spec-test-code sync workflow-spec-test-code-cycle-reference.md; derived spec index/ERD/reimplementation guides spec-system-reference.md + source Feature Specs under docs/specs/; architecture/new area project-structure-reference.md.
- Read every required doc, then before target work state:
Reference docs read: ... | Not applicable: ....
Ready when: scope evaluated, docs/project-config.json consulted, required docs checked/read or setup route completed, lessons.md confirmed, citation emitted.
Task Tracking & External Report Persistence โ Bootstrap this before execution; then run project-reference doc prefetch before target/source work.
- Create a small task breakdown before target file reads, grep, edits, or analysis. On context loss, inspect the current task list first.
- Mark one task
in_progress before work and completed immediately after evidence; never batch transitions.
- For plan/review work, create
plans/reports/{skill}-{YYMMDD}-{HHmm}-{slug}.md before first finding.
- Append findings after each file/section/decision and synthesize from the report file at the end.
- Final output cites
Full report: plans/reports/{filename}.
Blocked until: task breakdown exists, report path declared for plan/review work, first finding persisted before the next finding.
Sub-Agent Return Contract โ When this skill spawns a sub-agent, the sub-agent MUST return ONLY this structure. Main agent reads only this summary โ NEVER requests full sub-agent output inline.
## Sub-Agent Result: [skill-name]
Status: โ
PASS | โ ๏ธ PARTIAL | โ FAIL
Confidence: [0-100]%
### Findings (Critical/High only โ max 10 bullets)
- [severity] [file:line] [finding]
### Actions Taken
- [file changed] [what changed]
### Blockers (if any)
- [blocker description]
Full report: plans/reports/[skill-name]-[date]-[slug].md
Main agent reads Full report file ONLY when: (a) resolving a specific blocker, or (b) building a fix plan.
Sub-agent writes full report incrementally (per SYNC:incremental-persistence) โ not held in memory.
Context budget โ the return payload is a SUMMARY, not a transcript: โค10 finding bullets, no raw file contents / full diffs / verbatim logs inline, no re-pasted source. Everything beyond the summary lives in the Full report on disk. A sub-agent that would exceed the summary shape MUST write the detail to its report and return only the pointer โ the orchestrator's context is the scarce resource the whole map-reduce protects.
Critical Thinking Mindset โ Apply critical thinking, sequential thinking. Every claim needs traced proof, confidence >80% to act.
Anti-hallucination: Never present guess as fact โ cite sources for every claim, admit uncertainty freely, self-check output for errors, cross-reference independently, stay skeptical of own confidence โ certainty without evidence root of all hallucination.
Sequential Thinking Protocol โ Structured multi-step reasoning for complex/ambiguous work. Use when planning, reviewing, debugging, or refining ideas where one-shot reasoning is unsafe.
Trigger when: complex problem decomposition ยท adaptive plans needing revision ยท analysis with course correction ยท unclear/emerging scope ยท multi-step solutions ยท hypothesis-driven debugging ยท cross-cutting trade-off evaluation.
Format (explicit mode โ visible thought trail):
Thought N/M: [aspect] โ one aspect per thought, state assumptions/uncertainty
Thought N/M [REVISION of Thought K]: ... โ when prior reasoning invalidated; state Original / Why revised / Impact
Thought N/M [BRANCH A from Thought K]: ... โ explore alternative; converge with decision rationale
Thought N/M [HYPOTHESIS]: ... then [VERIFICATION]: ... โ test before acting
Thought N/N [FINAL] โ only when verified, all critical aspects addressed, confidence >80%
Mandatory closers: Confidence % stated ยท Assumptions listed ยท Open questions surfaced ยท Next action concrete.
Stop conditions: confidence <80% on any critical decision โ escalate by asking the user directly ยท โฅ3 revisions on same thought โ re-frame the problem ยท branch count >3 โ split into sub-task.
Implicit mode: apply methodology internally without visible markers when adding markers would clutter the response (routine work where reasoning aids accuracy).
Deep-dive: see $sequential-thinking skill (.claude/skills/sequential-thinking/SKILL.md) for worked examples (API design, debugging, architecture), advanced techniques (spiral refinement, hypothesis testing, convergence), and meta-strategies (uncertainty handling, revision cascades).
Evidence-Based Reasoning โ Speculation is FORBIDDEN. Every claim needs proof.
- Cite
file:line, grep results, or framework docs for EVERY claim
- Declare confidence: >80% act freely, 60-80% verify first, <60% DO NOT recommend
- Cross-service validation required for architectural changes
- "I don't have enough evidence" is valid and expected output
BLOCKED until: - [ ] Evidence file path (file:line) - [ ] Grep search performed - [ ] 3+ similar patterns found - [ ] Confidence level stated
Forbidden without proof: "obviously", "I think", "should be", "probably", "this is because"
If incomplete โ output: "Insufficient evidence. Verified: [...]. Not verified: [...]."
Design Patterns Quality โ Priority checks for every code change:
- DRY via OOP: Identify classes/modules with the same purpose, naming pattern, or lifecycle. Apply your knowledge of the project's language/framework to determine the idiomatic abstraction (base class, mixin, trait, protocol, decorator). 3+ similar patterns โ extract to shared abstraction.
- Right Responsibility: Logic in LOWEST layer (Entity > Domain Service > Application Service > Controller). Never business logic in controllers.
- SOLID: Single responsibility (one reason to change). Open-closed (extend, don't modify). Liskov (subtypes substitutable). Interface segregation (small interfaces). Dependency inversion (depend on abstractions).
- After extraction/move/rename: Grep ENTIRE scope for dangling references. Zero tolerance.
- YAGNI gate: NEVER recommend patterns unless 3+ occurrences exist. Don't extract for hypothetical future use.
Anti-patterns to flag: God Object, Copy-Paste inheritance, Circular Dependency, Leaky Abstraction.
Serial Attention for Design Quality โ Scan one quality dimension at a time (serial passes), not all concerns at once. โ why: split attention misses violations that single-focus passes catch.
- Identify applicable dimensions โ Based on the code's language, domain, and patterns, determine which quality dimensions apply: DRY, SOLID principles (SRP/OCP/LSP/ISP/DIP), OOP idioms, cohesion/coupling, GRASP, Law of Demeter, CQRS invariants, etc. Your list is NOT fixed โ derive from what the code actually does.
- One focused pass per dimension โ Dedicate single-focus attention to EACH dimension in sequence. Do NOT mix concerns across passes.
- Threshold: 3+ similar patterns = MANDATORY extraction โ Not optional suggestion. Flag as mandatory structural fix requiring action.
- 2+ violations of same kind = structural finding โ Report as "pattern problem" needing architectural resolution, not a list of individual instances.
Validated-Finding Fix + Full Re-Review Loop โ Re-review is triggered by a validated finding fix cycle, not by a round number. Review purpose: review โ validate findings โ fix validated findings โ full re-review until a complete review pass finds no issues. A clean review ENDS the loop โ no further rounds required.
aka Self-Review Convergence Loop. The name is historical โ there is NO 2-round cap; "double-round-trip" only means a validated-finding fix cycle forces at least one fresh re-review. It runs until a clean pass, bounded by the 5-round ceiling below.
Round cap โ 5 rounds MAX (a ceiling, NEVER a target). A clean pass ENDS the loop immediately at ANY round โ round 1 included; the cap never obliges you to keep spinning. Hitting round 5 with validated findings still open โ STOP and escalate by asking the user directly with the still-open findings listed; NEVER emit a silent "good enough" PASS on cap exhaustion, and NEVER let the cap substitute for the clean-review requirement. The 3-repeated-no-progress blocker rule stays an EARLIER exit โ escalate at whichever trips first.
Universal scope (any new output/judgment): any newly produced output or judgment gets โฅ1 self-review; any new judgment gets โฅ1 $why-review --validate-findings pass; anything flagged to re-check is re-checked โฅ1 time โ before that output is treated as final. This loop is the default convergence contract for ANY work-producing skill, not review skills only.
Routing invariant (author-facing): a skill that validates findings MUST route them through $why-review --validate-findings (the terminal validator) โ NEVER fork an inline finding-validation. Routing through why-review is what makes the finding-survival bar and this loop apply; the verify-review-validate-coverage sensor enforces this exact route mechanically.
Round 1: Main-session review. Read target files, build understanding, note issues. Output findings + verdict (PASS / FAIL).
Decision after Round 1:
- No issues found (PASS, zero findings) โ review ENDS. Do NOT spawn a fresh sub-agent for confirmation.
- Issues found (FAIL, or any non-zero findings) โ run the active review skill's findings-validation gate first; for review skills the default gate is
$why-review --validate-findings <report-path>. Fix only validated findings, then restart the full review protocol from the beginning with a fresh task breakdown.
Fresh full re-review after every fix cycle: Re-run the whole review protocol over the current full target. When sub-agents are part of that protocol, spawn NEW spawn_agent calls โ never reuse prior agents. Reviewers re-read ALL files from scratch with ZERO memory of prior rounds. See SYNC:fresh-context-review for the spawn mechanism and SYNC:review-protocol-injection for the canonical Agent prompt template. Each fresh full review must catch:
- Cross-cutting concerns missed in the prior round
- Interaction bugs between changed files
- Convention drift (new code vs existing patterns)
- Missing pieces that should exist but don't
- Subtle edge cases the prior round rationalized away
- Regressions introduced by the fixes themselves
Loop termination: After each full re-review, repeat the same decision: clean โ END; issues โ validate findings โ fix โ restart from the first review phase. Continue until a complete review pass finds zero issues, capped at 5 rounds. Escalate by asking the user directly at whichever comes first: the same validated finding repeats for 3 full invocations with no progress ยท a fix requires product/owner input ยท round 5 completes with validated findings still open. NEVER loop past 5 rounds, and NEVER convert cap exhaustion into a PASS.
Rules:
- A clean Round 1 ENDS the review โ no mandatory Round 2
- NEVER fix unvalidated findings; validate first using the caller's validation gate
- Every surviving finding must additionally clear the finding-survival bar defined in why-review's Findings Validation Routine (a deliberately higher bar than the generic act-gate โ "keep this finding?" is a stricter question than "act on this evidence?"); a finding below the bar is demoted or dropped, not kept
- NEVER skip the full re-review after a fix cycle (every fix invalidates the prior verdict)
- NEVER reuse a sub-agent across rounds โ every iteration that uses sub-agents spawns NEW Agent calls
- Main agent READS sub-agent reports but MUST NOT filter, reinterpret, or override findings
- The 5-round cap NEVER replaces the clean-review requirement โ it bounds runaway looping, it does not authorize shipping an un-clean review; a clean pass ends the loop early at any round, and cap exhaustion escalates rather than passes
- Enforce the round cap of 5 alongside the 3 repeated-no-progress blocker rule; both are escalation triggers, neither is a completion criterion
- Track recursive invocation count and repeated blockers in conversation context (session-scoped)
- Final verdict must incorporate ALL rounds executed
Report must include ## Round N Findings (Fresh Sub-Agent) for every round Nโฅ2 that was executed.
Source/test drift check. For coding, fix, debug, investigation, test, or review work: when source behavior changes, inspect affected unit/integration/E2E tests and decide from evidence whether tests should change to match intended behavior or the source change is an unintended bug to fix. Do not write tests for migration code; schema/data migrations are one-time execution paths, not core application logic.
Understand Code First โ HARD-GATE: Do NOT write, plan, or fix until you READ existing code.
- Search 3+ similar patterns (
grep/glob) โ cite file:line evidence
- Read existing files in target area โ understand structure, base classes, conventions
- Run
python .claude/scripts/code_graph trace <file> --direction both --json when .code-graph/graph.db exists
- Map dependencies via
connections or callers_of โ know what depends on your target
- Write investigation to
.ai/workspace/analysis/ for non-trivial tasks (3+ files)
- Re-read analysis file before implementing โ never work from memory alone. โ why: long context drifts from the file; the file is ground truth
- NEVER invent new patterns when existing ones work โ match exactly or document deviation. โ why: divergent patterns fragment the codebase and slow every future reader
BLOCKED until: - [ ] Read target files - [ ] Grep 3+ patterns - [ ] Graph trace (if graph.db exists) - [ ] Assumptions verified with evidence
AI Mistake Prevention โ Failure modes to avoid on every task:
Re-read files after context changes. Context compaction, resume, or long-running work can make memory stale; verify current files before acting.
Verify generated content against source evidence. AI hallucinates APIs, names, claims, and document facts. Check the relevant source before documenting or referencing.
Check downstream references before deleting or renaming. Removing an artifact can stale docs, generated mirrors, configs, and callers; map references first.
Trace the full impact chain after edits. Changing a definition can miss derived outputs and consumers. Follow the affected chain before declaring done.
Verify ALL affected outputs, not just the first. One green check is not all green checks; validate every output surface the change can affect.
Assume existing values are intentional โ ask WHY before changing. Before changing a constant, limit, flag, wording, or pattern, read nearby context and history.
Surface ambiguity before acting โ don't pick silently. Multiple valid interpretations require an explicit question or stated assumption with risk.
Keep shared guidance role-relevant. Universal guidance must help every receiving skill or agent; code-specific obligations belong only in code-specific protocols.
Systematic Review Batching (map-reduce) โ When a changeset is large, do NOT review files one-by-one. Partition into size-capped batches, fire one specialized sub-agent per batch in parallel, then reduce. This bounds EVERY context โ each batch agent AND the orchestrator โ so coverage stays complete as file count grows.
Trigger ladder (one ordered escalation โ not competing thresholds):
- < 10 changed files โ sequential per-file review (default; no batching).
- โฅ 10 changed files โ switch to systematic parallel mode. Announce:
"Detected {N} changed files. Switching to systematic parallel review protocol." Then: categorize โ size-capped batches โ flat consolidation.
- categories > 6 OR files > 40 โ additionally insert the hierarchical synthesis tier (below). Everything from rung 2 still applies.
Step 1 โ Categorize. Group changed files into logical categories derived from the project's actual structure (not forced). Category is the concern axis; orient with these examples, derive what fits the repository:
| Category Type | Example Groupings |
|---|
| Agent/Tooling | AI scripts, hooks, skill definitions, workflow configs, linting rules |
| Root config/docs | Root README, project config, CI/CD pipeline configs |
| Reference docs | Architecture docs, patterns references, setup guides |
| Feature/domain docs | Business feature documentation, spec files, ADRs |
| Backend logic | Service/handler/controller source (infer from project structure) |
| Frontend logic | UI component/state/API source (infer from project structure) |
| Data/Schema | Migrations, schema files, seed data |
| Tests | Unit, integration, E2E test files |
| Infrastructure | Docker, k8s, CI/CD, cloud manifests |
Step 2 โ Size-capped batches. One sub-agent per batch of โค8 files OR โค2000 diff-lines, whichever hits first. Category stays the concern axis, but any category exceeding a cap splits into multiple size-capped batches (30 backend files โ 4 batches). Size caps โ not category caps โ make "many files" safe: a category cap alone lets one giant category blow a single agent's context.
Step 2a โ Sub-agent type per batch (match the batch's dominant concern):
- Code logic (any stack) โ
code-reviewer
- Security-sensitive changes โ
security-auditor
- Performance-critical paths โ
performance-optimizer
- Docs, plans, specs, configs, infra โ
general-purpose
Each batch sub-agent receives: its full file list; SYNC:category-review-thinking as its primary thinking model โ derive each category's concerns from first principles, NOT a fixed checklist (if the consuming skill does not carry that block, apply category-first thinking directly); project reference docs relevant to its concern (discover via *patterns*, *conventions*, *style-guide*); cross-reference verification instructions (counts, tables, links). All batch agents run in parallel and write findings to plans/reports/ (per SYNC:task-tracking-external-report); reducers read from disk, never from memory.
Step 3 โ Reduce.
- Flat reduction (rung 2, โค6 categories AND โค40 files): the orchestrator collects each batch report, cross-references counts/tables/contracts ACROSS batches, detects gaps visible only across categories (feature in code but missing from docs; new API endpoint with no client call), and consolidates into one categorized holistic report.
- Hierarchical reduction (rung 3, > 6 categories OR > 40 files): insert a mid-tier โ each concern gets ONE synthesizer agent that reads only its own batch reports and emits a single concern-synthesis. The orchestrator reads the concern-syntheses (~5), never the raw batch reports โ keeping the reducer's context O(#concerns), not O(#files).
- Cross-concern interaction pass (mandatory at rung 3 โ closes the synthesis-tier blind spot): concern-siloed synthesis can drop an interaction spanning two concerns AND two batches (tainted source in data-layer/batch 7 โ sink in api/batch 3). So: (a) each concern-synthesizer MUST emit an explicit "cross-concern interaction candidates" list โ entities/symbols/contracts it touched that plausibly bind to another concern (shared DTOs, event names, table/collection names, exported symbols); (b) the orchestrator MUST run the Step-3 cross-reference/gap step over those candidate lists across all concern-syntheses, not only within a batch, before concluding. Without this pass the tier trades completeness for context-bounding on exactly the large diffs it targets.
Step 4 โ Holistic assessment. With all findings combined, judge: overall coherence as a unified intent; cross-category sync (docs match code? contracts match callers?); risk areas where categories interact; missing doc/spec updates for changed artifacts.
No silent truncation. If any cap forces sampling or a batch is dropped for budget, ANNOUNCE the dropped/sampled scope explicitly โ bounded coverage must never read as complete coverage.
Severity Rubric โ Classify every finding by consequence, not by how easy it is to fix. One scale across all reviews so a "High" means the same thing everywhere.
| Severity | Action | Definition |
|---|
| CRITICAL | Block merge | Silent runtime failure, data corruption, validation bypass, security hole |
| HIGH | Must fix | Incorrect behavior, invariant gap, architectural violation |
| MEDIUM | Should fix | Design debt, maintainability, likely future bug |
| LOW | Nice to fix | Convention, documentation, minor clarity |
Score-based skills map their numeric scale onto these tiers โ do not invent a parallel vocabulary:
- 0-2 criterion scoring (e.g. production-readiness-review):
0 = CRITICAL/HIGH (criterion unmet, blocks production readiness), 1 = MEDIUM (partial, should fix), 2 = pass (no finding).
- Two-axis scoring (e.g. performance-review, impact ร likelihood): map the resulting cell to the nearest tier โ high-impact + high-likelihood โ CRITICAL/HIGH; low-impact OR low-likelihood โ MEDIUM/LOW.
A finding's tier drives the gate: CRITICAL/HIGH must be resolved or explicitly accepted by the owner before PASS; MEDIUM/LOW may ship with a tracked follow-up.
Category Review Thinking โ A thinking framework for reviewing any category of changed files. NOT a fixed checklist โ derive concerns from domain knowledge; the examples are starting points only. Your knowledge of the category exceeds any list here โ trust it.
Step 1 โ Understand the category's role. What is this category responsible for in the overall system? What invariants must it uphold? What are its consumer contracts (who depends on it, what do they expect)?
Step 2 โ Read project conventions for this category. Search for reference docs, style guides, ADRs, or READMEs specific to this area. Grep 3+ existing similar files โ extract naming conventions, structural patterns, shared base classes. If no docs exist, derive conventions empirically from existing code.
Step 3 โ Derive concerns from first principles. Apply all that are relevant; expand beyond this list based on the actual category: