diff --git a/README.md b/README.md index dc60aa3..c081ce5 100644 --- a/README.md +++ b/README.md @@ -78,6 +78,7 @@ Every skill features an explicit **"Your call"** checkpoint where the agent paus | **[`inspect-flake-update`](skills/inspect-flake-update/SKILL.md)** | `/inspect-flake-update` | Inspects updated flake.lock inputs, reviews upstream revisions, runs nix flake check, and drafts commit messages. | 46 lines | | **[`nix-devshell`](skills/nix-devshell/SKILL.md)** | `/nix-devshell` | Authors, extends, validates, and troubleshoots project Nix development shells from repository evidence. | 75 lines | | **[`verify-slice`](skills/verify-slice/SKILL.md)** | `/verify-slice` | Runs risk-proportional verification and PR review across behavioral, state, security, ergonomic, and regression perspectives using falsifiable assertions. | 37 lines | +| **[`code-review`](skills/code-review/SKILL.md)** | `/code-review` | Inspects diffs across four isolated axes: Spec & Scope, Standards & Smells, Seam & Test Integrity, and Defensive Invariants. | 42 lines | ### Vault Extensions (`extensions/`) diff --git a/install.sh b/install.sh index b7ca725..f59cf26 100755 --- a/install.sh +++ b/install.sh @@ -33,7 +33,7 @@ while [[ $# -gt 0 ]]; do done # Active skills to install -ACTIVE_PORTABLE_SKILLS=(build-skill diagnose document git-commit inspect-flake-update journal-builder nix-devshell practice reconcile-docs verify-slice) +ACTIVE_PORTABLE_SKILLS=(build-skill code-review diagnose document git-commit inspect-flake-update journal-builder nix-devshell practice reconcile-docs verify-slice) ACTIVE_EXTENSION_SKILLS=(draft-curation commit-logger) # Legacy / deprecated skills to clean up or back up if found in target diff --git a/skills/code-review/SKILL.md b/skills/code-review/SKILL.md new file mode 100644 index 0000000..a42e70c --- /dev/null +++ b/skills/code-review/SKILL.md @@ -0,0 +1,42 @@ +--- +name: code-review +description: >- + Inspects git diffs, pull requests, and commit ranges across four independent + axes: Spec & Scope, Standards & Smells, Seam & Test Integrity, and Defensive + Invariants. Use when reviewing code changes before merge or verifying diff + quality. Not for live runtime QA: use verify-slice. +--- + +# Code Review + +## Use when +- Reviewing a branch, pull request, work-in-progress diff, or commit range before merge. +- Evaluating code structure, defensive invariants, and test seam integrity. +- Not for live runtime browser or deployment testing: use `verify-slice`. +- Not for debugging an unknown symptom: use `diagnose`. + +## Steps +1. **Pin the fixed point and scope.** Resolve the base ref and record its commit SHA via `git rev-parse `. Inspect working-tree state (`git status --short`, unstaged `git diff`, staged `git diff --cached`) alongside committed history (`git diff ...HEAD` and `git log ..HEAD --oneline`). Report findings distinguished across committed, staged, and unstaged changes. +2. **Select execution tier.** Match the change to the risk tiers from [axes](references/axes.md) (`Lightweight`, `Standard`, or `High-Assurance`). Single-agent sequential pass for Lightweight; independent review passes for Standard; isolated subagents per axis for High-Assurance. +3. **Inspect the four axes.** Evaluate the diff against each axis independently using [axes](references/axes.md): + - **Spec & Scope**: originating requirements satisfied, minimal shared-file footprint, zero scope creep. + - **Standards & Smells**: repository rules and Fowler smell diagnostics from [smell-heuristics](references/smell-heuristics.md) (evaluated as confirmed violations, potential smells, or contextual trade-offs). + - **Seam & Test Integrity**: tests verify public interface seams, assertions are non-tautological, negative/boundary paths covered, vertical slices prioritized over bulk imagined tests. + - **Defensive Invariants**: system properties from [defensive-invariants](references/defensive-invariants.md) (trust boundaries, authority, consistency, failure semantics, resource limits). +4. **Record structured findings.** Record every finding using the schema in [finding-schema](references/finding-schema.md) (`ID`, `Axis`, `Severity`, `Evidence`, `Invariant`, `Impact`, `Disposition`). A strong pass on one axis never compensates for a failure on another. +5. **Aggregate without silent resolution.** When multiple reviewers or passes disagree, keep the disagreement visible under `Unresolved` until evidence settles it. +6. **Recommend runtime verification scenarios.** Identify stateful or high-risk paths that static inspection cannot prove and list them as suggested scenarios for `verify-slice`. +7. **Present the review summary.** Group findings by axis and apply the decision matrix from [axes](references/axes.md): `Needs Rework` (confirmed defects require changes), `Blocked` (unresolved Critical/High risks or unestablished scope), or `Ready` (no blocking defects; documented trade-offs accepted by owner). Never authorize release: the human owner decides release. + +## Your call +- **Handling findings**: decide whether confirmed findings block merge, trigger a rework loop, or become tracked follow-up issues. +- **Adjudicating unresolved disagreements**: resolve conflicting reviewer perspectives or accepted architectural trade-offs. +- **Authorizing release**: verification and review evidence inform decisions, but the human owner remains the sole release authority. + +## Done when +- All four axes have been inspected across working-tree and committed changes, every finding is recorded with evidence and disposition, candidate runtime scenarios are passed to `verify-slice` if needed, and the human owner has reviewed the findings. + +## Hands off to +- `diagnose`: when a finding exposes a root cause that requires deeper troubleshooting. +- `verify-slice`: to execute behavioral and runtime verification scenarios. +- `git-commit`: when committing review fixes or test adjustments. diff --git a/skills/code-review/references/axes.md b/skills/code-review/references/axes.md new file mode 100644 index 0000000..5fd4370 --- /dev/null +++ b/skills/code-review/references/axes.md @@ -0,0 +1,53 @@ +# Review Axes and Risk Tiers + +Reference for `code-review`. Inspects git diffs across four distinct evaluation dimensions without allowing strength on one axis to compensate for defects on another. + +Derived and adapted from Matt Pocock's skills repository (github.com/mattpocock/skills), combining the multi-axis review discipline with empirical safety and verification invariants. + +## 1. The Four Review Axes + +| Axis | Primary Question | Failure Mode Caught | Core Inspection Questions | +| :--- | :--- | :--- | :--- | +| **Spec & Scope** | Did we build what was requested, and only that? | Scope creep, missing requirements, leaky abstractions | 1. Does the diff satisfy the originating issue or specification contract?
2. Is there unrequested functionality or premature generalization?
3. Are changes to shared entrypoints (e.g., routers, base config) minimal and additive? | +| **Standards & Smells** | Is the implementation maintainable and consistent? | Structural debt, friction with conventions | 1. Does the code adhere to repo standards (`CODING_STANDARDS.md`, linter configs)?
2. Are code smells present that warrant refactoring? (See [smell-heuristics](smell-heuristics.md)).
3. Is naming clear and aligned with domain vocabulary? | +| **Seam & Test Integrity** | Do tests prove actual contracts at public interfaces? | Tautological tests, implementation coupling | 1. Are tests verifying public interfaces (seams) rather than mocking private internals?
2. Are assertions non-tautological (do not mirror code logic or pass by construction)?
3. Prefer tests establishing observable behavior through meaningful vertical slices. Batch independent cases when doing so preserves clear contracts and does not substitute test quantity for behavioral evidence. | +| **Defensive Invariants** | Does the code preserve critical system properties under stress? | Injection, state desync, unhandled crashes | 1. Are untrusted inputs sanitized before reaching sinks? (See [defensive-invariants](defensive-invariants.md)).
2. Does state reconcile against authoritative sources rather than local heuristic drift?
3. Are failure semantics, timeouts, and resource limits explicit? | + +### Non-Compensation Invariant +A strong pass on one axis never excuses a failure on another: +- Clean abstractions and zero code smells cannot excuse an unescaped HTML sink or an unhandled conflict. +- 100% test coverage cannot excuse unrequested feature drift or broken domain invariants. +- Strict spec compliance cannot excuse fragile code structure that breaks repository conventions. + +## 2. Review Recommendations Matrix + +The distinction between recommendations is clear: `Needs Rework` means an established defect requires implementation or test changes; `Blocked` means the review cannot establish sufficient confidence or scope to proceed safely. + +| Condition Observed | Final Recommendation | Action Required | +| :--- | :--- | :--- | +| **Confirmed Critical or High** | `Needs Rework` | Fix confirmed defects before release review. | +| **Confirmed Medium or Low requiring changes** | `Needs Rework` | Apply requested refactoring or test coverage fixes. | +| **Unresolved Critical or High** | `Blocked` | Resolve missing evidence or escalate to human owner before proceeding. | +| **Unresolved Medium or Low** | `Ready` (Conditional) | Human owner may adjudicate and accept trade-offs without blocking. | +| **Scope Inability or Missing Base Ref** | `Blocked` | Establish base commit and diff boundaries before reviewing. | +| **No Blocking Findings** | `Ready` | Implementation is structurally sound; proceed to `verify-slice` or release. | + +### Documented Trade-Off Acceptance +When a human owner accepts a documented trade-off for a Medium or Low finding, record the finding disposition as `Accepted Trade-off` (distinct from `Rejected`). This preserves audit traceability without misclassifying an intentional compromise as a disproven defect. + +## 3. Risk-Scaled Execution Tiers + +To keep review overhead proportional to risk, execution mode reuses the tiers established in `verify-slice`: + +| Review Risk Tier | Typical Change | Review Execution Strategy | +| :--- | :--- | :--- | +| **Lightweight** | Copy updates, styling adjustments, isolated bugfixes with no new state or untrusted data. | Single-agent sequential pass inspecting all 4 axes in order. | +| **Standard** | New UI components, regular API endpoints, database queries, or schema additions. | Independent review passes over the diff. Subagents may be used when helpful to prevent bias. | +| **High-Assurance** | Auth, permissions, payments, concurrent state reconciliation, destructive actions, or core shared libraries. | Fully isolated reviewers for separate axes (e.g., Subagent 1 on Spec, Invariants, and Tests; Subagent 2 on Standards and Smells), followed by independent aggregation. | + +## 4. Aggregation and Anti-Silence Rules + +When multiple passes or subagents inspect a change: +1. **Never silently resolve disagreements**: If Reviewer A flags a pattern as a defect and Reviewer B considers it acceptable, record the finding under `Unresolved` with both perspectives cited. The human owner adjudicates. +2. **Preserve exact evidence**: Every finding must include exact file paths, line numbers, and code snippets demonstrating the condition. +3. **Recommend runtime verification**: Where static analysis cannot verify dynamic timing, rendering, or network failure modes, formulate concrete candidate assertions and pass them to `verify-slice`. diff --git a/skills/code-review/references/defensive-invariants.md b/skills/code-review/references/defensive-invariants.md new file mode 100644 index 0000000..9b9e1bb --- /dev/null +++ b/skills/code-review/references/defensive-invariants.md @@ -0,0 +1,43 @@ +# Defensive Invariants + +Reference for `code-review`. Defines system properties that must hold true across backend APIs, frontend clients, CLI tools, and system infrastructure. + +## 1. Core System Properties + +Every change that handles external data, mutable state, or distributed operations must satisfy five defensive properties: + +### A. Trust Boundaries +Untrusted data enters the system from HTTP parameters, headers, route variables, environment files, user input forms, external webhook bodies, or database text fields. +- **Verification Rule**: Trace every untrusted value from source to sink. Verify safe APIs, parameterization, or contextual encoding (e.g. escaping HTML for DOM text, quoting attribute values, validating URL protocols). +- **Anti-pattern**: Relying on HTML sanitization to protect URL targets (`href="javascript:..."`), or interpolating raw strings into SQL, HTML, or shell commands. + +### B. Authority +Every piece of mutable state must have a single authoritative owner (usually a database, an authoritative server endpoint, or a dedicated state actor). +- **Verification Rule**: Components, views, and CLI tools must never invent duplicate truth or assume their local copy is permanently accurate after out-of-band mutations can occur. +- **Anti-pattern**: Mutating local UI counters or status badges via optimistic arithmetic without reconciling against authoritative responses. + +### C. Consistency and Conflict Handling +Operations that touch shared or concurrent state must handle collisions and out-of-band updates predictably. +- **Verification Rule**: When a mutation encounters a conflict (such as HTTP 409, unique constraint violation, or file lock contention), the system must fetch authoritative state or signal conflict to the operator. +- **Anti-pattern**: Swallowing conflicts, or applying a naive local patch (like `counter + 1`) that desynchronizes whenever multiple records or operators mutate state simultaneously. + +### D. Failure Semantics +When external calls, network sockets, or sub-processes fail, the system must behave deterministically. +- **Verification Rule**: Failure paths must release locks, clean up temporary files, surface understandable error messages, and avoid partial half-committed state. Retries must be idempotent. +- **Anti-pattern**: Empty `catch` or `except` blocks, unhandled promise rejections, silent fallback to empty arrays on network failures, or retrying non-idempotent mutations. + +### E. Resource Boundaries +Input sizes, execution duration, concurrency, and memory consumption must have explicit boundaries. +- **Verification Rule**: Incoming payloads must have size limits; pagination must be enforced; timeouts must guard external calls; file streams and database connections must be closed deterministically. +- **Anti-pattern**: Unbounded `SELECT *` queries, unbounded regex evaluations vulnerable to catastrophic backtracking, or reading unbounded streams entirely into memory. + +## 2. Multi-Stack Reference Examples + +| Stack / Context | Property | Concrete Risk | Defect Pattern | Correct Invariant Pattern | +| :--- | :--- | :--- | :--- | :--- | +| **Frontend / Web** | Trust Boundaries | XSS / DOM Injection | `el.innerHTML = '' + user.name + ''` | Use `textContent`, safe DOM builders, or context-aware `escapeHtml(user.name)`. | +| **Frontend / Web** | Consistency | Stale Counters on Conflict | Local counter increment on 409 duplicate check-in. | On 409 conflict, fetch authoritative session/record state from the server. | +| **Python / FastAPI** | Resource Boundaries | Memory exhaustion | Reading entire uploaded file via `await file.read()`. | Enforce payload size limits and stream chunks using configured buffer limits. | +| **Python / FastAPI** | Consistency | Race conditions | Non-atomic read-then-write on database balance or status. | Use database transactions with explicit row locks (`SELECT ... FOR UPDATE`) or atomic SQL increments. | +| **Rust / CLI** | Failure Semantics | Silent partial failure | Ignoring `Result` via `.unwrap_or_default()` on critical I/O. | Bubble up errors with contextual details via `anyhow` or domain error types; clean up staging files. | +| **NixOS / Homelab** | Authority | Secret leakage | Baking plaintext API keys into world-readable Nix store derivations. | Reference secret paths resolved at runtime via sops-nix or systemd credentials. | diff --git a/skills/code-review/references/finding-schema.md b/skills/code-review/references/finding-schema.md new file mode 100644 index 0000000..5bae8ce --- /dev/null +++ b/skills/code-review/references/finding-schema.md @@ -0,0 +1,76 @@ +# Finding Schema and Review Output + +Reference for `code-review`. Defines the required structure for reporting findings, ensuring every note is actionable, evidence-backed, and auditable. + +Derived and adapted from Matt Pocock's review principles (github.com/mattpocock/skills), combining side-by-side axis reporting with strict defect provenance and disposition contracts. + +## 1. Finding Record Schema + +Every reported finding must populate all seven fields: + +| Field | Description | Allowed Values / Format | +| :--- | :--- | :--- | +| **ID** | Stable identifier within this review. | `CR-01`, `CR-02`, etc. | +| **Axis** | The review axis that uncovered the finding. | `Spec & Scope`, `Standards & Smells`, `Seam & Test Integrity`, `Defensive Invariants`. | +| **Severity** | Potential failure consequence if the defect occurs. Describes impact, not reviewer confidence. | `Critical` (system security breach, data loss, fatal crash), `High` (broken invariant, missing spec requirement), `Medium` (code smell, fragile logic, missing edge test), `Low` (minor style inconsistency, naming). | +| **Evidence** | Exact location, change category, and reproducible behavior. | Distinguishes whether the code is committed, staged, or unstaged: e.g. `src/view.ts:L45 (unstaged)` with excerpt. | +| **Invariant** | The requirement, contract, or system property violated. | Clear statement of expectation (e.g., "Untrusted DOM values must be escaped before interpolation"). | +| **Impact** | Concrete failure consequence if left unaddressed. | What breaks in production, concurrency, or maintenance (e.g., "Stored XSS when name contains `