feat(code-review): add risk-scaled review workflow

Inspects git diffs, pull requests, and commit ranges across four
independent axes: Spec & Scope, Standards & Smells, Seam & Test
Integrity, and Defensive Invariants.

Adapted from Matt Pocock's skills repository (github.com/mattpocock/skills)
for multi-axis review, the Fowler smell baseline, and TDD interface seams,
integrated with Armonia-derived defensive invariants (trust boundaries,
state authority, conflict reconciliation, failure semantics, resource limits)
and strict evidence-backed finding dispositions.
This commit is contained in:
kiskaadee committed 2026-10-30 00:17:15 -05:00
1 parent 9db036e4ac
commit d866b602b8
7 files changed
+252 -1

No files matched your search

+1
View File
@@ -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/`)
+1 -1
View File
@@ -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
+42
View File
@@ -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 <base>`. Inspect working-tree state (`git status --short`, unstaged `git diff`, staged `git diff --cached`) alongside committed history (`git diff <base>...HEAD` and `git log <base>..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.
+53
View File
@@ -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?<br/>2. Is there unrequested functionality or premature generalization?<br/>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)?<br/>2. Are code smells present that warrant refactoring? (See [smell-heuristics](smell-heuristics.md)).<br/>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?<br/>2. Are assertions non-tautological (do not mirror code logic or pass by construction)?<br/>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)).<br/>2. Does state reconcile against authoritative sources rather than local heuristic drift?<br/>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`.
@@ -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 = '<span>' + user.name + '</span>'` | 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. |
@@ -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 `<script>`"). |
| **Disposition** | Current evidentiary status of the finding. | `Confirmed` (proven defect backed by evidence), `Rejected` (disproven or false positive), `Unresolved` (open disagreement or missing evidence), `Accepted Trade-off` (conscious compromise approved by owner). |
## 2. Disposition and Severity Rules
1. **Blocking status**: Only `Confirmed` findings (Critical, High, or changes-required Medium/Low) trigger a `Needs Rework` verdict.
2. **Unresolved findings**: `Unresolved Critical` or `Unresolved High` findings result in a `Blocked` verdict until resolved with evidence or owner adjudication. `Unresolved Medium` or `Low` findings can remain `Ready` if the owner accepts the trade-off.
3. **Rejected vs. Accepted Trade-off**:
- `Rejected`: The finding was an invalid concern or disproven by facts.
- `Accepted Trade-off`: The finding identifies a genuine compromise where the owner explicitly accepts the local cost for an engineering reason.
Both remain in the ledger for full audit traceability.
4. **Severity vs. confidence**: `Severity` describes potential impact, never reviewer confidence. A suspected high-impact flaw with incomplete evidence must be logged as `High` severity with `Unresolved` disposition, not downgraded to `Low`.
## 3. Review Report Layout
The final review summary presented to the user must follow this structure:
```markdown
# Code Review Summary: <branch or commit range>
## Overview & Scope State
- **Base Commit**: `<base-ref>` (`<base-commit-sha>`) -> `<HEAD>` (`<head-commit-sha>`)
- **Working Tree State**: Clean / Staged Changes / Unstaged Changes (`git status --short`)
- **Assigned Risk Tier**: `Lightweight` | `Standard` | `High-Assurance`
- **Execution Mode**: `Sequential` | `Independent Passes` | `Subagent Reviewers`
## Findings Ledger
### Confirmed Findings (Needs Rework)
| ID | Axis | Severity | State | Location | Invariant Violated | Impact |
| :--- | :--- | :--- | :--- | :--- | :--- | :--- |
| CR-01 | Defensive Invariants | Critical | Committed | `src/view.ts:L45` | Unescaped dynamic HTML sink | DOM XSS via attendee name |
### Unresolved Disagreements / Material Risks (Blocked if Critical/High)
| ID | Axis | Severity | Location | Competing Perspectives / Open Risk | Decision Needed |
| :--- | :--- | :--- | :--- | :--- | :--- |
| CR-02 | Standards & Smells | Medium | `src/api.ts:L110` | Reviewer A flags Primitive Obsession; Author notes single call site. | Accept string or introduce domain type |
### Accepted Trade-offs & Rejected Findings (Audit Traceability)
| ID | Axis | Disposition | Location | Rationale / Decision |
| :--- | :--- | :--- | :--- | :--- |
| CR-03 | Spec & Scope | Rejected | `src/main.ts:L12` | Suspected scope creep confirmed as required wiring for acceptance criterion 2. |
| CR-04 | Standards & Smells | Accepted Trade-off | `scripts/seed.py:L10` | Inlined script logic accepted to keep utility independent of core module. |
## Axis Breakdown
- **Spec & Scope**: Pass/Fail summary. Notes on scope containment and shared entrypoints across working-tree and commits.
- **Standards & Smells**: Adherence to repo conventions and Fowler smell diagnostics.
- **Seam & Test Integrity**: Evaluation of test boundaries, tautological assertions, and vertical slice evidence.
- **Defensive Invariants**: Status of trust boundaries, authority, consistency, failure semantics, and resource limits.
## Recommended Runtime Scenarios for verify-slice
List concrete runtime checks or adversarial test cases that static inspection identified as necessary for runtime verification:
1. Scenario: Verify out-of-band 409 conflict handling with simultaneous check-in attempts.
2. Scenario: Verify input sanitization with payload `<img src=x onerror=alert(1)>`.
## Overall Recommendation
- **Status**: `Ready` | `Needs Rework` | `Blocked`
- **Next Action**: State whether to hand off to `verify-slice` for runtime verification, `diagnose` for root-cause fixes, or present to human owner for adjudication.
```
@@ -0,0 +1,36 @@
# Code Smells and Design Diagnostics
Reference for `code-review`. Treats code smell catalogs as diagnostic heuristics rather than mechanical violation checklists.
Derived and adapted from Martin Fowler's refactoring catalog as curated in Matt Pocock's skills repository (github.com/mattpocock/skills).
## 1. Three-Tier Evaluation Framework
When a reviewer observes a suspicious pattern in the diff, they must classify it into one of three distinct categories:
1. **Confirmed Violation**: Observable evidence proves the pattern actively damages correctness, testability, or maintainability (e.g., duplicate business logic causing divergent bugfixes, or unreadable obfuscated variable names).
2. **Potential Design Smell**: A pattern that warrants architectural inquiry and discussion, but whose harm depends on future evolution (e.g., a function taking six parameters that might benefit from a dedicated parameter struct).
3. **Contextual Trade-Off**: An intentional compromise where the author consciously accepted a local cost for a tangible engineering benefit (e.g., inlining logic in a script to keep it self-contained, or using primitive strings in a one-off parser to avoid premature type layers).
Reviewers must never demand refactoring for a contextual trade-off without demonstrating concrete harm.
## 2. Fowler Smell Diagnostics
| Heuristic | What to Look For | When It Is a Problem | When It Is Acceptable |
| :--- | :--- | :--- | :--- |
| **Primitive Obsession** | Using basic strings, numbers, or dicts for domain concepts (e.g. raw string for currency or unvalidated email). | When parsing, validation, and operations on that concept are duplicated across multiple call sites. | At external system boundaries, simple internal scripts, or when the concept has zero invariant behavior. |
| **Feature Envy** | A method or function that accesses data from another module more than its own. | When business rules belonging to Module B are scattered across callers in Module A. | When implementing intentional adapters, serialization mappers, or presentation formatters. |
| **Speculative Generality** | Interfaces, generics, hook points, or abstract classes added for hypothetical future needs. | When the abstraction adds indirection today for requirements that do not yet exist. | When building published public libraries with strict semver compatibility commitments. |
| **Shotgun Surgery** | A single logical feature change forces scattered micro-edits across many different files. | When related behavior is fragmented across unrelated modules instead of cohesive units. | Cross-cutting infrastructure updates (e.g. updating a dependency signature or logging framework). |
| **Divergent Change** | A single file or module is edited frequently for completely different business reasons. | When unrelated concerns (e.g. UI rendering, database persistence, and auth) live in one file. | Cohesive coordinating modules (such as application entrypoints or top-level routers). |
| **Mysterious Name** | Variables, functions, or types whose names obscure what they do. | When reading the code requires mental translation or leaves ambiguity about side effects. | Conventional short loop indexes (`i`, `j`) or well-understood mathematical terms in algorithmic loops. |
| **Repeated Switches** | Identical `if`/`else` or `match`/`switch` chains repeated across several functions on the same type. | When adding a new type variant requires editing every switch statement manually. | Simple two-branch checks or isolated dispatchers in serialization code. |
## 3. Commit Cohesion and Granularity
Commit size is a **diagnostic signal**, not an absolute rule.
- **The Goal**: Commits should represent cohesive, localizable units of work that can be understood, reviewed, and reverted independently if needed.
- **Diagnostic Threshold**: A commit touching more than 350 lines is a signal to inspect whether multiple concerns were bundled together (for example, combining data model types, UI rendering, and a mutation modal into a single commit).
- **Legitimate Exceptions**: Generated schemas, lockfile updates, broad renaming refactors, or database seed migrations often legitimately exceed 350 lines while remaining completely cohesive.
- **The True Anti-pattern**: Splitting a single atomic change into non-functional fragments, or conversely, combining unrelated feature work and opportunistic refactorings into one commit.