Files

352 lines
18 KiB
Markdown
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
---
name: code-review
description: Use when Codex needs to review an existing branch, commit range, pull request, patch, staged changes, or working-tree diff for correctness, regressions, security, authorization, API/data-contract, migration, runtime, test-coverage, and maintainability risks. Inspect repository context and surrounding code, verify findings before reporting them, prioritize issues by severity and user impact, avoid cosmetic/style nitpicks, and do not modify code unless the user explicitly asks for fixes.
---
# Code Review
Version: **2.0**.
Review code for **real engineering risk**, not stylistic preference. Ground every finding in the actual diff plus enough surrounding repository evidence to establish that the change can cause a bug, regression, security weakness, contract break, data problem, runtime failure, or material maintainability hazard.
This skill is designed to compose with `bortstack-context`. The context skill owns repository/task/decision/handoff semantics; this skill owns review methodology. Use `production-readiness-review` for a broad system-wide readiness audit rather than a bounded change review, `webapp-debug` when a reported runtime defect needs root-cause investigation, and `safe-refactor` when the goal is to change structure while preserving behavior.
## Repository workflow
In a BortStack project, use `bortstack-context` with the applicable repository `AGENTS.md` before task work. They govern scope and authorisation, branch/worktree policy, lifecycle, manual acceptance, and handoff. Find the maintained overview, current state, decisions, task and handoff records through repository instructions and layout. Use the paths and task IDs the project already uses. Follow context's canonical discussion, mission and lifecycle guidance when interpreting authority or changing task status. If a required BortStack skill is unavailable, report the dependency. If an installed skill lacks a required reference, use the reference from a verified Forge package with a matching manifest. If the required guidance is unavailable, pause the affected action.
For edits, inspect Git status and worktrees, confirm authorised scope and the source candidate, and follow the current branch policy. Use direct integration-branch work where authorised and a dedicated branch/worktree where required. Preserve unrelated work. Read-only specialist work does not require a new worktree. When acting as an authorised contributor, use `bortstack-contributor` for contributor permissions, finalisation and submission. For ordinary specialist work, use the project's normal authority.
When manual testing is relevant, discover the documented commands, configuration and hooks in the target repository. Use its supported workflow, including an existing `testtask` wrapper and its project-specific config or hook where documented. Preserve a working adapter and its supported invocation. Before use, inspect its supported arguments, candidate handling, runtime and cleanup behavior. If no adapter is required, use the established development environment. Record candidate identity, actual checks, limitations and pending human acceptance in the project's handoff. Refresh stale candidates after edits and make fixes in the authoritative source. A source snapshot, wrapper, automated check or startup alone does not establish a manual pass. Follow context and repository rules for task transitions and closure.
Outside BortStack, follow the repository's own scope, branch, test and reporting conventions and proceed with the specialist workflow. BortStack skills and records are optional there.
## Core rules
1. **Read repository instructions and context first.** Obey root/nested `AGENTS.md`, accepted task scope, durable decisions, architecture conventions, validation requirements, and review-specific repository rules.
2. **Review the actual change set.** Establish exactly what is being reviewed: working tree, staged changes, branch-vs-base, commit range, PR patch, or supplied diff. Do not review an imagined change.
3. **Inspect surrounding code before raising findings.** A suspicious diff line is not enough. Check callers, routes/components, models, migrations, auth helpers, tests, configuration, and contracts needed to prove the issue.
4. **Prioritize correctness and risk.** Focus on bugs, regressions, security/auth problems, broken data/API contracts, migration hazards, concurrency/transaction issues, runtime/deployment failures, and missing tests for meaningful behavior.
5. **Do not nitpick style.** Avoid comments about formatting, naming taste, import order, minor duplication, or subjective aesthetics unless they create a concrete maintainability or correctness risk.
6. **Do not report hypothetical findings as defects.** A finding must have a plausible execution path and repository evidence. Distinguish confirmed issue, likely issue needing verification, and non-finding.
7. **Respect accepted behavior.** Do not label deliberate behavior a bug merely because another design would be preferable. Check project decisions and existing tests first.
8. **Review across layers.** For React + Flask applications, follow changes through UI/state -> request -> route/auth/validation -> domain/model -> persistence -> response -> UI handling when relevant.
9. **Treat authentication/authorization as server-side contracts.** Verify protected actions are enforced on the backend; UI hiding alone is not authorization.
10. **Treat migrations/data changes as high-risk.** Check upgrade/downgrade safety, defaults/nullability, backfills, constraints, indexes, data compatibility, and deployment ordering where relevant.
11. **Check failure paths, not only happy paths.** Errors, retries, partial failures, missing data, invalid input, unauthenticated/unauthorized access, and stale state often expose regressions.
12. **Use tests as evidence, not proof by existence.** Inspect whether tests actually exercise the changed behavior and would fail for the identified regression.
13. **Run focused validation when practical.** Tests/lint/build/static checks can strengthen or falsify review findings. Do not claim commands were run when they were not.
14. **Do not modify code by default.** A review is read-only unless the user explicitly asks to fix findings. Do not commit, push, merge, rebase, deploy, switch branches, or alter production state.
15. **Keep findings concise and actionable.** Explain what breaks, under what conditions, why the diff causes it, and what area needs correction. Do not prescribe a large redesign unless necessary.
16. **No-padding rule.** If the change is sound, say so. Do not invent low-value findings to make the review look substantial.
## Establish review scope
Before reviewing, determine:
- repository/project identity;
- current branch and working-tree state when available;
- exact base/target or commit range;
- accepted task or feature represented by the change;
- files changed;
- relevant durable decisions and contracts;
- whether generated/vendor/lock files should be reviewed or mostly excluded;
- expected validation commands;
- whether the user requested review only or review plus fixes.
If the intended base is ambiguous and choosing the wrong one could materially change the review, resolve it from repository metadata/context where possible. Ask only when it cannot be determined safely.
Review the exact requested candidate against its documented base and acceptance criteria. For direct-branch work, use its recorded starting commit and scoped changes. Include intended untracked files when reviewing a working tree. Flag stale test evidence and unrelated changes.
## 1. Read the change set before deep-diving
Inspect the diff/patch and classify changed areas, for example:
- models/schema/migrations;
- Flask routes/services/auth;
- React components/hooks/state;
- API client/contracts;
- configuration/environment/runtime;
- tests/fixtures;
- Docker/CI/deployment;
- documentation/context only.
Identify high-risk edits first: authorization changes, destructive data operations, changed routes/status codes, token/session handling, migrations, transaction behavior, concurrency, external side effects, configuration defaults, and removed validation.
Do not infer intent solely from commit messages. Compare the diff with accepted task/context evidence and current code.
## 2. Verify behavior and contracts around each risky change
For each material edit, trace enough surrounding code to answer:
- Who calls this changed code?
- What inputs can reach it?
- Which auth/authorization checks guard it?
- What data does it read/write?
- What errors/status codes are observable?
- What state transitions or side effects occur?
- Which existing contracts depend on the old behavior?
- Do frontend and backend expectations still match?
- Are existing tests sufficient to detect regression?
Search for all important symbol/path/config references before concluding a rename/removal is safe or broken.
## 3. Review by risk category
### Correctness and regressions
Look for:
- changed conditionals that invert/skip behavior;
- missing edge-case handling;
- stale state/closure issues;
- incorrect default/null/empty handling;
- wrong ordering/filtering/pagination semantics;
- off-by-one/date/time/timezone errors;
- duplicated or omitted side effects;
- changed error/status behavior;
- caller/callee signature mismatches;
- removed compatibility behavior still used elsewhere.
A finding should identify the concrete path by which behavior breaks.
### Authentication and authorization
Check:
- unauthenticated handling;
- role/ownership/tenant checks;
- object-level authorization;
- token/session refresh/revocation behavior;
- server-side enforcement for privileged actions;
- information disclosure through errors or list/detail endpoints;
- accidental weakening caused by helper/decorator changes.
Do not treat frontend route guards or hidden controls as sufficient authorization.
### Input validation and API contracts
Check:
- required/optional fields;
- type/range/format constraints;
- unknown or extra fields if contract-sensitive;
- request/response field names;
- status/error shapes;
- pagination/filter/sort semantics;
- null/empty behavior;
- backwards compatibility with existing clients;
- serialization/deserialization changes.
### Database, migrations, and transactions
Inspect both model changes and migration files. Check:
- upgrade and downgrade coherence;
- nullable/non-null transitions;
- defaults and server defaults;
- existing-row compatibility/backfills;
- foreign keys/cascades/uniqueness;
- index additions/removals;
- enum/value compatibility;
- migration ordering/dependencies;
- transaction boundaries/rollback behavior;
- race conditions around uniqueness/availability/counters;
- data loss or irreversibility.
Do not assume an ORM model change is safe because the migration file exists.
### React/frontend behavior
Check:
- route/navigation compatibility;
- prop/context/hook contracts;
- state initialization and updates;
- async race/stale response handling;
- loading/error/empty/success states;
- form payload construction and validation;
- auth/session handling;
- accessibility regressions caused by interaction changes;
- API response assumptions;
- cleanup of timers/listeners/effects where behaviorally relevant.
Do not submit purely subjective visual-design feedback in a code review unless the accepted task includes visual requirements or the diff causes a concrete usability/accessibility defect.
### Runtime/configuration/deployment
Check:
- environment variable/key renames;
- unsafe/default configuration changes;
- startup/import paths;
- Docker build/runtime assumptions;
- nginx/SWAG/Gunicorn wiring;
- CI commands and version requirements;
- secret exposure;
- migration/deploy ordering;
- health checks/ports/volumes/network names when changed.
Treat runtime contracts as public interfaces when production depends on them.
### Security beyond auth
Look for concrete risks such as:
- injection paths;
- unsafe file/path handling;
- secret/token leakage;
- overly broad CORS or trust settings;
- CSRF/session regressions where applicable;
- insecure redirects/URL handling;
- unsafe deserialization;
- sensitive data in logs/errors;
- privilege escalation;
- missing rate/abuse controls only when the changed code creates or materially worsens the exposure.
Avoid generic security boilerplate unrelated to the diff.
## 4. Review tests as part of the change
Ask whether changed behavior has adequate regression coverage.
High-value missing-test findings include:
- new privileged endpoint without non-admin/unauthenticated tests;
- changed validation without invalid-boundary tests;
- migration with no upgrade/data-compatibility check where repository practice expects one;
- bug fix with no regression test;
- changed refresh/retry/error behavior without coverage;
- new branching logic where only happy path is tested.
Do not require a test for every trivial line. Missing tests should be reported when they leave a meaningful behavior/regression unprotected.
## 5. Validate findings where practical
Use focused commands to confirm/falsify suspected issues when the environment allows, such as:
- a relevant pytest/Vitest test file;
- a small existing reproduction test;
- lint/type/build checks;
- migration inspection/upgrade in a disposable database;
- grep/search for callers/references;
- static config validation.
Do not mutate production or introduce broad fixture/data changes solely to prove a review point.
If validation is blocked, state the limitation and keep the finding proportional to the evidence.
## 6. Severity model
Use repository-specific severity conventions if they exist. Otherwise use:
### Critical
Likely severe security compromise, irreversible/catastrophic data loss, or production-wide outage with a realistic path.
### High
Material security/authorization failure, data corruption/loss, broken core workflow, migration/deployment failure, or broad regression likely to affect users.
### Medium
Real functional defect affecting a narrower path, edge case, reliability, or important maintainability issue with credible future failure risk.
### Low
Minor but concrete defect with limited impact. Use sparingly.
Do **not** assign severity merely based on how much code is involved. Severity reflects impact and likelihood.
If the repository uses P0/P1/etc. for implementation priority, do not automatically map review severity to those task priorities unless its conventions explicitly define that mapping.
## 7. Evidence standard for a finding
Every reported finding should contain enough information to answer:
1. **Where is the problem?** File/area and changed behavior.
2. **What breaks?** Concrete consequence.
3. **When does it break?** Input/state/runtime condition.
4. **Why does this change cause it?** Repository evidence and execution path.
5. **How confident are we?** Confirmed by code/tests/runtime, or limited by environment.
Avoid speculative phrasing such as "might be insecure" without tracing a credible path.
If further evidence disproves a suspected issue, drop it from the final review.
## 8. Review-only behavior
Unless the user explicitly asks for fixes:
- do not edit application files;
- do not add tests;
- do not update context docs merely because findings exist;
- do not create tasks automatically;
- do not alter task status;
- do not commit/push/comment on external PRs.
In BortStack projects, findings can be proposed for context/task treatment, but accepted task creation remains governed by that system and user/repository conventions.
If the user asks to **review and fix**, first complete the review enough to establish the issues, then apply the appropriate implementation/debug/refactor workflow. Keep review findings and changes clearly distinguishable.
## 9. Handling an empty or clean review
A valid review can result in **no findings**.
If no material issue is found:
- say that no actionable correctness/security/regression findings were identified;
- summarize what areas were inspected;
- report validation actually run;
- state relevant limitations;
- do not manufacture style comments or speculative edge cases.
## 10. Context-system interaction
In BortStack projects:
- read project context before judging intent/accepted behavior;
- respect ADR/PDR/task constraints;
- use the project’s current-state record as evidence of known issues, but verify whether the diff affects them;
- do not turn every review finding into authorised implementation work;
- do not rewrite the project’s handoff record during a review-only task unless explicitly requested or repository rules require it;
- if a finding exposes stale context, report the mismatch and let the context workflow reconcile it appropriately.
## Completion report
Lead with findings, ordered from highest to lowest severity. For each finding include:
- severity;
- concise title;
- affected file/area;
- concrete failure/risk;
- triggering conditions;
- supporting evidence;
- validation status/limitations where relevant.
Then include a short review summary:
- change set reviewed;
- repository/context evidence inspected;
- validation run;
- areas not verified;
- whether context/tasks were changed (normally no for review-only work).
Do not bury important findings below a long narrative. Do not repeat the same root cause as multiple findings unless the consequences are genuinely independent.
## When not to use this skill
Do not use this workflow for:
- broad production-readiness auditing across the whole system — use `production-readiness-review`;
- diagnosing an already observed runtime bug whose root cause is unknown — use `webapp-debug`;
- implementing a new accepted feature — use `webapp-feature`;
- behavior-preserving restructuring — use `safe-refactor`;
- visual/browser QA of rendered application behavior — use `frontend-visual-qa`;
- deployment execution/checklists — use `deployment-check`.
## Resources
- `references/review-checklist.md` — concise cross-layer review checklist.
- `references/finding-quality.md` — evidence and severity checklist for high-signal review findings.