feat(code-review): upgrade to GitHub PR reviews with build_review.py

- Add stdlib-only executable skills/code-review/scripts/build_review.py with diff-hunk validation (LEFT/RIGHT), unanchored body fallback, monotonic CR-XX numbering across paginated reviews/comments, cr-review-meta stamping, collapsible RV-* blocks, triage summaries, duplicate (head_sha, verdict) skip (exit 2), and 3-rework-cycle cap (exit 1)
- Add tests/fixtures/test_build_review.py unittest suite covering pagination flattening, diff anchoring, unanchored fallback, monotonic rollover, RV-*/triage rendering, duplicate/rework-cap guards, and invalid input handling
- Update skills/code-review/SKILL.md (78 lines) for GitHub PR publishing via build_review.py + gh api, no-PR local fallback notice, split rework routing to implement/verify, and removal of Accepted Trade-off and delegation skip rules
- Update skills/code-review/references/axes.md with code-hygiene checks (docstrings, stale comments, lint/format, affected local markdown) and GitHub/verify terminology
- Update skills/code-review/references/finding-schema.md with the build_review.py input schema, gh api --paginate --slurp publishing workflow, 3 GitHub-native triage exits, and cr-review-meta contract
This commit is contained in:
kiskaadee committed 2026-11-25 14:59:19 -05:00
1 parent bedd01e729
commit 8c5172eeaf
5 files changed
+1050 -158

No files matched your search

+60 -28
View File
@@ -1,46 +1,78 @@
--- ---
name: code-review name: code-review
description: >- description: >-
Inspects git diffs, pull requests, and commit ranges across four independent Inspects git diffs, GitHub pull requests, and commit ranges across four
axes: Spec & Scope, Standards & Smells, Seam & Test Integrity, and Defensive independent axes: Spec & Scope, Standards & Smells, Seam & Test Integrity,
Invariants. Use when reviewing code changes before merge or verifying diff and Defensive Invariants. Use when reviewing code changes before merge or
quality. Not for live runtime QA: use verify-slice. verifying diff quality. Not for live runtime QA: use verify.
--- ---
# Code Review # Code Review
## Use when ## Use when
- Reviewing a branch, pull request, work-in-progress diff, or commit range before merge. - Reviewing a branch, open GitHub PR, work-in-progress diff, or commit range.
- Evaluating code structure, defensive invariants, and test seam integrity. - Evaluating code structure, hygiene, defensive invariants, and test seams.
- Not for live runtime browser or deployment testing: use `verify-slice`. - Not for live runtime QA, CI promotion, or merge: use `verify`.
- Not for debugging an unknown symptom: use `diagnose`. - Not for debugging an unknown symptom: use `diagnose`.
## Steps ## Steps
1. **Pin the fixed point and scope.** Resolve the base ref and record exact base and head commit SHAs (`git rev-parse <base> HEAD`). Inspect working-tree state (`git status --short`, unstaged `git diff`, staged `git diff --cached`, and relevant untracked files) alongside committed history (`git diff <base>...HEAD` and `git log <base>..HEAD --oneline`). Record the covered revisions and working-tree diff state (for example, clean tree or diff fingerprint) so downstream tools can verify whether the reviewed diff remained unchanged, and distinguish findings across committed, staged, and unstaged changes. Keep the codebase strictly read-only: never edit repository files, create
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`; for `High-Assurance`, never run `Sequential` or a single combined subagent: spawn a dedicated isolated Axis 3 (`Seam & Test Integrity`) subagent separate from Axes 1/2/4 and record both subagent IDs in `Execution Mode`. commits, or mutate GitHub Projects v2 board cards.
3. **Inspect the four axes.** Evaluate the diff against each axis independently using [axes](references/axes.md):
- **Spec & Scope**: originating requirements satisfied, aligned with canonical project direction (`ARCHITECTURE.md`, `ROADMAP.md`, ADRs, active milestone) when present, minimal shared-file footprint, zero scope creep. 1. **Pin the fixed point and scope.** Resolve `<base>` and `HEAD` SHAs
- **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). (`git rev-parse <base> HEAD`). Inspect working-tree state (`git status --short`,
- **Seam & Test Integrity**: audit test diffs against [seams-and-mocking](../tdd/references/seams-and-mocking.md) and [test-quality](../tdd/references/test-quality.md) (public seams, injected timing callables, deterministic waits/teardown, non-tautological literals, boundary coverage, single-behavior naming). unstaged `git diff`, staged `git diff --cached`, relevant untracked files)
- **Defensive Invariants**: system properties from [defensive-invariants](references/defensive-invariants.md) (trust boundaries, authority, consistency, failure semantics, resource limits). and committed history (`git diff <base>...HEAD`, `git log <base>..HEAD --oneline`).
4. **Record structured findings.** Record every finding using the schema in [finding-schema](references/finding-schema.md) (`ID`, `Axis`, `Severity`, `Evidence`, `Invariant`, `Impact`, `Disposition`). Never self-assign `Accepted Trade-off` on a review pass: all valid findings start as `Confirmed` (or `Unresolved`); only the human owner may grant `Accepted Trade-off`. A strong pass on one axis never compensates for a failure on another. 2. **Select execution tier.** Before inspecting, read [axes](references/axes.md)
5. **Aggregate without silent resolution.** When multiple reviewers or passes disagree, keep the disagreement visible under `Unresolved` until evidence settles it. and assign `Lightweight`, `Standard`, or `High-Assurance`. For `High-Assurance`,
6. **Emit executable runtime checks.** For stateful or high-risk paths that static inspection cannot prove, emit runnable fenced shell commands for `verify-slice` following the Step 6 contract in [finding-schema](references/finding-schema.md) (stating purpose, `local` vs. `live-infra` scope classification, explicit pass condition, and explicit failure signal). never run `Sequential` or a single combined subagent: spawn a dedicated isolated
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), `Pending Triage` (only untriaged Medium/Low findings remain; never recommend merging until each takes one of the 3 triage exits in [finding-schema](references/finding-schema.md)), or `Ready` (all four axes completed and zero untriaged findings remain). Static review establishes static provenance for that diff only; never authorize release. Axis 3 (`Seam & Test Integrity`) subagent separate from Axes 1/2/4 and record
8. **Auto-publish the PR review block (standalone open PR only).** Keep the codebase strictly read-only (never edit repo files or mutate project boards). When invoked standalone on an open PR, draft `review-body.md` (and `inline-comments.json` when inline findings exist) per section 4 of [finding-schema](references/finding-schema.md), including the compact 4-axis pass block on clean `Ready` reviews, verify `head_sha` and duplicate/pending guards, and automatically publish one `--comment` review pinned with `--commit <reviewed-head-sha>` in the same turn. Skip PR publishing when delegated inside `implement-slice`. both subagent IDs in `Execution Mode`.
3. **Inspect the four axes independently.**
- **Spec & Scope**: issue/spec satisfaction, alignment with canonical docs
(`ARCHITECTURE.md`, `ROADMAP.md`, ADRs), minimal shared-file footprint,
and affected local markdown accuracy.
- **Standards & Smells**: repo rules, [smell-heuristics](references/smell-heuristics.md),
missing docstrings on new/modified public symbols, stale inline comments,
and lint/format regressions.
- **Seam & Test Integrity**: audit test diffs against
[seams-and-mocking](../tdd/references/seams-and-mocking.md) and
[test-quality](../tdd/references/test-quality.md).
- **Defensive Invariants**: [defensive-invariants](references/defensive-invariants.md)
(trust boundaries, authority, consistency, failure semantics, resource limits).
4. **Record findings and executable runtime checks.** Before formatting output
or publishing, read [finding-schema](references/finding-schema.md). Valid
findings start in `Pending Triage` (never self-dismiss). Keep disagreements
under `Unresolved`. Emit runnable `RV-*` checks (`local` vs. `live-infra`,
explicit `FAIL if ...` signals) for stateful or high-risk paths.
5. **Determine verdict and publish on open GitHub PRs.** Apply [axes](references/axes.md)
(`Needs Rework`, `Blocked`, `Pending Triage`, `Ready`). Verify GitHub repo via
`gh repo view --json url` and check for an open PR on `HEAD`. Whenever an open
GitHub PR exists (standalone or delegated), build the payload via
`skills/code-review/scripts/build_review.py --input ... --diff ... --reviews ... --comments ... --head-sha <sha> --verdict <ready|needs_rework>`
and pipe stdout to `gh api repos/{owner}/{repo}/pulls/{n}/reviews --input -`.
Handle exit `2` (duplicate `(head_sha, verdict)` skip) and exit `1`
(`3-rework-cycle cap` escalation). When no open PR exists or in local-only mode,
skip publishing and explicitly state in output that no open PR was found and
findings are reported locally.
## Your call ## Your call
- **Triaging findings (3 exits before merge)**: for each `Confirmed` or `Unresolved` finding, decide whether to (A) fix in-branch now, (B) promote to a live tracker (append/create Gitea issue or `todo.txt` via `tuxedo add`), or (C) grant permanent `Accepted Trade-off` (`record`). - **Triaging findings (3 exits before `Ready`)**: choose Exit A (fix in-branch),
- **Adjudicating unresolved disagreements**: resolve conflicting reviewer perspectives. Exit B (promote to a GitHub Issue), or Exit C (dismiss as invalid/false positive).
- **Authorizing release**: verification and review evidence inform decisions, but the human owner remains the sole release authority. - **Escalations and disagreements**: adjudicate `Unresolved` findings or a
`3-rework-cycle cap` halt.
- **Release authority**: static provenance never authorizes merge or release.
## Done when ## Done when
- All four axes have been inspected across working-tree and committed changes, every finding is recorded with evidence and disposition, executable Step 6 runtime checks are emitted for `verify-slice` if needed, and the human owner has reviewed the findings. - All four axes are inspected, findings and `RV-*` checks are recorded, and the
review is published to the open GitHub PR (or explicitly reported locally when
no open PR exists).
## Hands off to ## Hands off to
- `tdd`: when Axis 3 fails (`Suggested Next Step: /tdd <affected-test-files>`) or production rework needs test-first fixes (`Suggested Next Step: /tdd <module-or-test-path>`). - `implement`: on `Needs Rework` (`<= 2`-file localized fixes take the fast path;
complex rework enters Step 1; `Suggested Next Step: /implement #<issue>`).
- `verify`: on `Ready` (`Suggested Next Step: /verify`).
- `tdd`: when Axis 3 fails (`Suggested Next Step: /tdd <affected-test-files>`).
- `diagnose`: when a finding exposes an unknown root cause (`Suggested Next Step: /diagnose`). - `diagnose`: when a finding exposes an unknown root cause (`Suggested Next Step: /diagnose`).
- `verify-slice`: when `Ready` and runtime/`RV-*` checks are needed (`Suggested Next Step: /verify-slice`). - Emit one outcome-matched `Suggested Next Step:` on standalone turns; suppress
- `git-manager`: when branching, committing review fixes, or rebasing. when delegated per [skeleton](../build-skill/references/skeleton.md).
- `gitea-pr`: when `Ready` on an open PR with clean runtime checks (`Suggested Next Step: /gitea-pr <pr-or-issue>`).
- Emit one outcome-matched `Suggested Next Step` on standalone turns; suppress when delegated (per [skeleton](../build-skill/references/skeleton.md)).
+19 -19
View File
@@ -8,47 +8,47 @@ Derived and adapted from Matt Pocock's skills repository (github.com/mattpocock/
| Axis | Primary Question | Failure Mode Caught | Core Inspection Questions | | Axis | Primary Question | Failure Mode Caught | Core Inspection Questions |
| :--- | :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| **Spec & Scope** | Did we build what was requested, aligned with project direction, and only that? | Scope creep, missing requirements, architectural or roadmap drift, leaky abstractions | 1. Does the diff satisfy the originating issue or specification contract?<br/>2. When canonical direction docs exist (`ARCHITECTURE.md`, `ROADMAP.md`, ADRs, or active milestone scope), does the change align with long-term boundaries and trajectory?<br/>3. Is there unrequested functionality or premature generalization?<br/>4. Are changes to shared entrypoints (e.g., routers, base config) minimal and additive? | | **Spec & Scope** | Did we build what was requested, aligned with project direction, and only that? | Scope creep, missing requirements, architectural or roadmap drift, stale local docs | 1. Does the diff satisfy the originating GitHub issue or specification contract?<br/>2. When canonical direction docs exist (`ARCHITECTURE.md`, `ROADMAP.md`, ADRs, or active milestone scope), does the change align with long-term boundaries and trajectory?<br/>3. Is there unrequested functionality or premature generalization?<br/>4. Are changes to shared entrypoints minimal and additive, and are affected local markdown files updated when behavior or interfaces change? |
| **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? | | **Standards & Smells** | Is the implementation maintainable, hygienic, and consistent? | Structural debt, missing docstrings, stale comments, lint/format regressions | 1. Does the code adhere to repo standards (`CODING_STANDARDS.md`, linter and formatter configs) with zero lint/format regressions?<br/>2. Are new or modified public symbols documented with clear docstrings, and are inline comments accurate (no stale comments contradicting the new code)?<br/>3. Are code smells present that warrant refactoring? (See [smell-heuristics](smell-heuristics.md)).<br/>4. Is naming clear and aligned with domain vocabulary? |
| **Seam & Test Integrity** | Do tests prove actual contracts at public interfaces? | Tautological tests, implementation coupling, boundary gaps, flaky waits | Audit against [seams-and-mocking](../../tdd/references/seams-and-mocking.md) and [test-quality](../../tdd/references/test-quality.md):<br/>1. Public seams only; boundary mocks only; injected timing/clock callables instead of global runtime monkeypatching; deterministic waits and guaranteed teardown.<br/>2. Non-tautological assertions with independent literals (no imported production value constants), exact+neighbor boundary points (`[min-1, min, max, max+1]`), and single-behavior test names (no vague buckets or `_and_` chains). | | **Seam & Test Integrity** | Do tests prove actual contracts at public interfaces? | Tautological tests, implementation coupling, boundary gaps, flaky waits | Audit against [seams-and-mocking](../../tdd/references/seams-and-mocking.md) and [test-quality](../../tdd/references/test-quality.md):<br/>1. Public seams only; boundary mocks only; injected timing/clock callables instead of global runtime monkeypatching; deterministic waits and guaranteed teardown.<br/>2. Non-tautological assertions with independent literals (no imported production value constants), exact+neighbor boundary points (`[min - 1, min, max, max + 1]`), and single-behavior test names (no vague buckets or `_and_` chains). |
| **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? | | **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 ### Non-Compensation Invariant
A strong pass on one axis never excuses a failure on another: 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. - Clean abstractions and zero code smells cannot excuse an unescaped HTML sink or an unhandled conflict.
- 100% test coverage cannot excuse unrequested feature drift, architectural direction drift, or broken domain invariants. - 100% test coverage cannot excuse unrequested feature drift, architectural direction drift, or broken domain invariants.
- Strict spec compliance cannot excuse fragile code structure that breaks repository conventions. - Strict spec compliance cannot excuse fragile code structure, missing public docstrings, or lint regressions that break repository conventions.
## 2. Review Recommendations Matrix ## 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. 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 | | Condition Observed | Final Recommendation | Published `verdict` | Action Required |
| :--- | :--- | :--- | | :--- | :--- | :--- | :--- |
| **Confirmed Critical or High** | `Needs Rework` | Fix confirmed defects on the branch before release review. | | **Confirmed Critical or High** | `Needs Rework` | `needs_rework` | Fix confirmed defects on the branch via `implement` before `verify`. |
| **Confirmed or Unresolved Medium or Low (untriaged)** | `Pending Triage` | Do not recommend merge. Human owner chooses 1 of 3 exits per finding: (A) fix in-branch, (B) promote to live tracker (Gitea issue or `todo.txt`), or (C) grant permanent `Accepted Trade-off`. | | **Confirmed or Unresolved Medium or Low (untriaged)** | `Pending Triage` | `needs_rework` | Do not promote or merge. Human owner chooses 1 of 3 exits per finding: Exit A (fix in-branch), Exit B (promote to a GitHub Issue), or Exit C (dismiss as invalid/false positive). |
| **Unresolved Critical or High** | `Blocked` | Resolve missing evidence or escalate to human owner before proceeding. | | **Unresolved Critical or High** | `Blocked` | `needs_rework` | Resolve missing evidence or escalate to human owner before proceeding. |
| **Scope Inability or Missing Base Ref** | `Blocked` | Establish base commit and diff boundaries before reviewing. | | **Scope Inability or Missing Base Ref** | `Blocked` | (local halt) | Establish base commit and diff boundaries before reviewing. |
| **Zero Untriaged Findings** | `Ready` | All findings resolved, tracked in a live tracker, or explicitly granted `Accepted Trade-off` by the owner. | | **Zero Untriaged Findings** | `Ready` | `ready` | All findings resolved in-branch, promoted to a GitHub Issue (Exit B), or dismissed as invalid/false positive (Exit C). Route to `verify`. |
### `Ready` vs. `Pending Triage` Semantics and Downstream Reuse ### `Ready` vs. `Pending Triage` Semantics and Downstream Reuse
- **No agent self-adjudication**: Reviewer agents must never self-assign `Accepted Trade-off` on a review pass. Every valid observation (including `Low` nits) starts as `Confirmed` (or `Unresolved`), producing `Pending Triage` (or `Needs Rework`) rather than `Ready`. - **No agent self-dismissal**: Every valid finding (including `Low` severity) starts in `Pending Triage` as `Confirmed` (or `Unresolved`), producing `Pending Triage` or `Needs Rework` (`verdict=needs_rework`) rather than `Ready`.
- **`Pending Triage` blocks merge recommendations**: A review in `Pending Triage` qualifies as `Ready` for `gitea-pr` merge readiness only after every finding has taken one of the three explicit exits: (A) fixed in a new commit on the branch, (B) recorded in a live tracker that future agents read (an open Gitea issue or `todo.txt` via `tuxedo add`), or (C) explicitly approved by the human owner as a permanent `Accepted Trade-off` (no future action needed). - **`Pending Triage` blocks `verify` promotion**: A review qualifies as `Ready` (`verdict=ready`) for `verify` only after every finding has taken one of the three explicit exits: Exit A (fixed in a new commit on the branch), Exit B (promoted to a GitHub Issue and recorded as `Promoted to #<N>` in the superseding `Ready` review's triage summary), or Exit C (dismissed as invalid/false positive and recorded as `Dismissed: <reason>` in the superseding `Ready` review's triage summary).
- A `Ready` review establishes static provenance for that exact diff; it does not substitute for runtime verification or authorize release. - A `Ready` review establishes static provenance for that exact `head_sha`; it does not substitute for runtime verification in `verify` or authorize release.
## 3. Risk-Scaled Execution Tiers ## 3. Risk-Scaled Execution Tiers
To keep review overhead proportional to risk, execution mode reuses the tiers established in `verify-slice`: To keep review overhead proportional to risk, execution mode aligns with the risk tiers used in `verify`:
| Review Risk Tier | Typical Change | Review Execution Strategy | | 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. | | **Lightweight** | Small localized diffs, 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. | | **Standard** | Multi-file feature slices, 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. | Assign a dedicated isolated reviewer to **Seam & Test Integrity** (Axis 3, auditing test diffs against `tdd/references/`), separate from `Spec & Scope` + `Defensive Invariants` and `Standards & Smells`, followed by independent aggregation. | | **High-Assurance** | Security, auth, permissions, payments, schema migrations, concurrent state reconciliation, destructive actions, core shared libraries, or >500-line diffs. | Assign a dedicated isolated reviewer to **Seam & Test Integrity** (Axis 3, auditing test diffs against `tdd/references/`), separate from `Spec & Scope` + `Defensive Invariants` and `Standards & Smells`, followed by independent aggregation. |
## 4. Aggregation and Anti-Silence Rules ## 4. Aggregation and Anti-Silence Rules
When multiple passes or subagents inspect a change: 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. 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. 2. **Preserve exact evidence**: Every finding must include exact file paths, line numbers, and code snippets demonstrating the condition.
3. **Emit executable runtime checks**: Where static analysis cannot verify dynamic timing, rendering, or network failure modes, formulate runnable Step 6 checks formatted per [finding-schema](finding-schema.md) and pass them to `verify-slice`. 3. **Emit executable runtime checks**: Where static analysis cannot verify dynamic timing, rendering, or network failure modes, formulate runnable `RV-*` checks formatted per [finding-schema](finding-schema.md) so `verify` can execute them from the published PR review body.
+114 -111
View File
@@ -1,6 +1,6 @@
# Finding Schema and Review Output # Finding Schema and GitHub PR Review Output
Reference for `code-review`. Defines the required structure for reporting findings, ensuring every note is actionable, evidence-backed, and auditable. Reference for `code-review`. Sole owner of the `CR-XX` finding lifecycle, the `build_review.py` payload contract, and GitHub PR review publishing.
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. 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.
@@ -10,45 +10,45 @@ Every reported finding must populate all seven fields:
| Field | Description | Allowed Values / Format | | Field | Description | Allowed Values / Format |
| :--- | :--- | :--- | | :--- | :--- | :--- |
| **ID** | Stable identifier within this review. | `CR-01`, `CR-02`, etc. | | **ID** | Monotonic per-PR identifier across all review passes. | `CR-01`..`CR-99`, `CR-100`, etc. (assigned deterministically by `build_review.py`). |
| **Axis** | The review axis that uncovered the finding. | `Spec & Scope`, `Standards & Smells`, `Seam & Test Integrity`, `Defensive Invariants`. | | **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). | | **Severity** | Potential failure consequence if the defect occurs. Describes impact, not reviewer confidence. | `Critical` (security breach, data loss, fatal crash), `High` (broken invariant, missing spec requirement), `Medium` (code smell, fragile logic, missing edge test), `Low` (minor style, docstring, or naming issue). |
| **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. | | **Evidence** | Exact location, change category, and reproducible behavior. | Distinguishes committed, staged, or unstaged state: e.g. `src/view.ts:L45 (committed)` with excerpt. |
| **Invariant** | The requirement, contract, or system property violated. | Clear statement of expectation (e.g., "Untrusted DOM values must be escaped before interpolation"). | | **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>`"). | | **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). | | **Disposition** | Current evidentiary status of the finding. | `Pending Triage` / `Confirmed` (proven defect backed by evidence), `Unresolved` (open disagreement or missing evidence), `Dismissed` (invalid or false positive, Exit C). |
## 2. Disposition, Severity, and the 3 Triage Exits ## 2. Disposition, Severity, and the 3 Triage Exits
1. **No agent self-assigned `Accepted Trade-off`**: On a review pass, every valid finding (even `Low` severity) must be logged as `Confirmed` (or `Unresolved`). Only the human owner may assign `Accepted Trade-off`. 1. **Every valid finding starts in `Pending Triage`**: On a review pass, every valid finding (even `Low` severity) must be logged as `Confirmed` (or `Unresolved`) in `Pending Triage`. Never silently waive findings or self-dismiss defects.
2. **Verdict gating (`Needs Rework` vs. `Pending Triage` vs. `Ready`)**: 2. **Verdict gating (`Needs Rework` vs. `Blocked` vs. `Pending Triage` vs. `Ready`)**:
- `Confirmed Critical` or `Confirmed High` -> `Needs Rework`. - `Confirmed Critical` or `Confirmed High` -> `Needs Rework` (`verdict=needs_rework`).
- `Unresolved Critical` or `Unresolved High` -> `Blocked`. - `Unresolved Critical` or `Unresolved High` -> `Blocked` (`verdict=needs_rework`).
- Only `Confirmed` or `Unresolved` `Medium`/`Low` findings remain -> `Pending Triage` (never recommend merging while findings are untriaged). - Only `Confirmed` or `Unresolved` `Medium`/`Low` findings remain -> `Pending Triage` (`verdict=needs_rework`; never promote or merge while untriaged findings remain).
- Zero untriaged findings remain -> `Ready`. - Zero unresolved `Pending Triage` findings remain -> `Ready` (`verdict=ready`).
3. **Three Mandatory Exits for `Pending Triage` Findings (No Silent Tech-Debt in Closed PRs)**: 3. **Three Mandatory Exits for `Pending Triage` Findings (No Silent Tech-Debt in Closed PRs)**:
Because future coding agents do not read closed PR comments, an unresolved problem cannot simply be left as a closed PR comment and forgotten. Prompt the human owner to choose one exit per finding before merge: Because future coding agents do not read closed PR comments, an unresolved finding cannot be left behind in a closed PR thread. Prompt the human owner to choose one exit per finding before `Ready`:
- **Exit A (`fix-in-branch`)**: Fix the finding on the PR branch now (`/tdd` or `/git-manager`) and re-verify. - **Exit A (`fix-in-branch`)**: Fix the finding on the PR branch (`implement` fast path for `<= 2`-file localized fixes, `implement` Step 1 for complex rework, or `tdd` + `git-manager`) and re-run `code-review`.
- **Exit B (`live-tracker`)**: Defer the work by recording it in a live tracker that future agents read before starting the next slice: append to an upcoming Gitea issue (`gt issue edit <next>`), create a follow-up Gitea issue (`gt issue create` / `gitea-plan`), or add to `todo.txt` (`tuxedo add "(B) ..."`), and link that tracker ID on the PR. - **Exit B (`github-issue`)**: Promote the finding to a GitHub Issue (`gh issue create` or `projects`), optionally paired with `TODO(#<N>): ...` or a `Why:` comment + ADR link in `docs/decisions/`. Record `Promoted to #<N>` in the superseding `Ready` review body's `triage_closures[]` summary.
- **Exit C (`record` / `Accepted Trade-off`, human-only)**: The human owner explicitly decides no future code change is desired and permanently accepts the trade-off as-is. - **Exit C (`dismiss`)**: Dismiss the finding as invalid or a false positive. Record `Dismissed: <reason>` in the superseding `Ready` review body's `triage_closures[]` summary.
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`. 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 ## 3. Review Report Layout
The final review summary presented to the user must follow this structure: The review summary presented to the user must follow this structure:
```markdown ```markdown
# Code Review Summary: <branch or commit range> # Code Review Summary: <branch or commit range>
## Overview & Scope State ## Overview & Scope State
- **Base Commit**: `<base-ref>` (`<base-commit-sha>`) -> `<HEAD>` (`<head-commit-sha>`) - **Base Commit**: `<base-ref>` (`<base-commit-sha>`) -> `<HEAD>` (`<head-commit-sha>`)
- **Covered Working-Tree State**: `Clean` | Staged, unstaged, and relevant untracked summary plus content fingerprint (covering staged changes, unstaged changes, and relevant untracked file contents so downstream tools can verify zero state drift) - **Covered Working-Tree State**: `Clean` | Staged, unstaged, and relevant untracked summary plus content fingerprint
- **Assigned Risk Tier**: `Lightweight` | `Standard` | `High-Assurance` - **Assigned Risk Tier**: `Lightweight` | `Standard` | `High-Assurance`
- **Execution Mode**: `Sequential` (`Lightweight` only) | `Independent Passes` (`Standard`) | `Subagent Reviewers` (`High-Assurance` mandatory: Axes 1/2/4 subagent `<id>`, Dedicated Axis 3 Tests subagent `<id>`) - **Execution Mode**: `Sequential` (`Lightweight` only) | `Independent Passes` (`Standard`) | `Subagent Reviewers` (`High-Assurance` mandatory: Axes 1/2/4 subagent `<id>`, Dedicated Axis 3 Tests subagent `<id>`)
## Findings Ledger ## Findings Ledger
### Confirmed Findings (Needs Rework) ### Confirmed Findings (Pending Triage / Needs Rework)
| ID | Axis | Severity | State | Location | Invariant Violated | Impact | | 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 | | CR-01 | Defensive Invariants | Critical | Committed | `src/view.ts:L45` | Unescaped dynamic HTML sink | DOM XSS via attendee name |
@@ -56,132 +56,135 @@ The final review summary presented to the user must follow this structure:
### Unresolved Disagreements / Material Risks (Blocked if Critical/High) ### Unresolved Disagreements / Material Risks (Blocked if Critical/High)
| ID | Axis | Severity | Location | Competing Perspectives / Open Risk | Decision Needed | | 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 | | CR-02 | Standards & Smells | Medium | `src/api.ts:L110` | Reviewer A flags Primitive Obsession; Author notes single call site. | Fix in-branch, promote to GitHub Issue, or dismiss |
### Accepted Trade-offs & Rejected Findings (Audit Traceability) ### Triage Closures (Exit B / Exit C Audit Trail)
| ID | Axis | Disposition | Location | Rationale / Decision | | ID | Exit | Resolution |
| :--- | :--- | :--- | :--- | :--- | | :--- | :--- | :--- |
| CR-03 | Spec & Scope | Rejected | `src/main.ts:L12` | Suspected scope creep confirmed as required wiring for acceptance criterion 2. | | CR-03 | Exit B | Promoted to #45 |
| CR-04 | Standards & Smells | Accepted Trade-off | `scripts/seed.py:L10` | Inlined script logic accepted to keep utility independent of core module. | | CR-04 | Exit C | Dismissed: false positive on test fixture |
## Axis Breakdown ## Axis Breakdown
- **Spec & Scope**: Pass/Fail summary. Notes on scope containment and shared entrypoints across working-tree and commits. - **Spec & Scope**: Pass/Fail summary, scope containment, shared entrypoints, and affected local markdown.
- **Standards & Smells**: Adherence to repo conventions and Fowler smell diagnostics. - **Standards & Smells**: Repo conventions, docstrings on new/modified public symbols, inline comment accuracy, lint/format hygiene, and Fowler smell diagnostics.
- **Seam & Test Integrity**: Evaluation of test boundaries, tautological assertions, and vertical slice evidence. - **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. - **Defensive Invariants**: Status of trust boundaries, authority, consistency, failure semantics, and resource limits.
## Executable Runtime Checks for verify-slice ## Executable Runtime Checks for verify
Every candidate runtime check must be directly consumable by `verify-slice` without reinterpreting narrative prose. Commands must assume execution from the repository root and use repository-relative paths (if an external path or environment dependency is genuinely required, declare that dependency and scope explicitly). Each entry requires: Every candidate runtime check must be directly consumable by `verify` from the published PR review body without reinterpreting narrative prose. Commands assume execution from the repository root with repository-relative paths. Each entry requires:
- **Purpose** in the check header (`Check RV-XX: <purpose>`). - **Purpose** in the check header (`Check RV-XX: <purpose>`).
- **Scope**: `local` (safe workstation or isolated fixture execution) or `live-infra` (touches privileged permissions, host state, or external/production infrastructure; executable when the human owner explicitly authorizes the target environment and operation, otherwise recorded by `verify-slice` as `BLOCKED (out-of-bounds)`). - **Scope**: `local` (safe workstation or isolated fixture execution) or `live-infra` (touches privileged permissions, host state, or external/production infrastructure; requires explicit human owner authorization in `verify`, otherwise recorded as `BLOCKED (out-of-bounds)`).
- **Pass Condition**: explicit observable output or state transition. - **Pass Condition**: explicit observable output or state transition.
- **Failure Signal**: explicit contradiction condition. - **Failure Signal**: explicit `FAIL if ...` contradiction condition.
- **Command**: copy-pasteable fenced shell block. - **Command**: copy-pasteable fenced shell block.
### Check RV-01: Out-of-band conflict handling on concurrent submission ### Check RV-01: Out-of-band conflict handling on concurrent submission
- **Scope**: `local` - **Scope**: `local`
- **Pass Condition**: First request returns HTTP `200`; concurrent duplicate returns HTTP `409` with JSON code `conflict` and persisted count increments by `1`. - **Pass Condition**: First request returns HTTP `200`; concurrent duplicate returns HTTP `409` with JSON code `conflict` and persisted count increments by `1`.
- **Failure Signal**: Duplicate returns `200` or `500`, unhandled traceback, or persisted count increments by `2`. - **Failure Signal**: `FAIL if` duplicate returns `200` or `500`, unhandled traceback occurs, or persisted count increments by `2`.
```sh ```sh
./scripts/test-concurrency-check.sh --endpoint /api/check-in ./scripts/test-concurrency-check.sh --endpoint /api/check-in
``` ```
### Check RV-02: Privileged service reload and health verification
- **Scope**: `live-infra`
- **Pass Condition**: Target service reloads cleanly and health endpoint returns `200 OK`.
- **Failure Signal**: Non-zero exit status, permission refusal, or failed unit healthcheck.
```sh
systemctl reload app-daemon.service && systemctl is-active --quiet app-daemon.service
```
## Overall Recommendation ## Overall Recommendation
- **Status**: `Ready` | `Pending Triage` | `Needs Rework` | `Blocked` - **Status**: `Ready` | `Pending Triage` | `Needs Rework` | `Blocked`
- **Next Action**: When `Pending Triage` or `Needs Rework`, do not recommend merging; prompt the human owner to select Exit A (`fix-in-branch`), Exit B (`live-tracker`: Gitea issue or `todo.txt`), or Exit C (permanent `Accepted Trade-off`) for each finding. Static provenance and runtime verification remain distinct inputs; neither authorizes release on its own. - **PR Publishing**: Published review URL (or explicit notice: `No open GitHub PR found; findings reported locally.`)
- **Next Action**: Route `Needs Rework` to `implement` (`<= 2`-file fast path or Step 1), `Pending Triage` to owner triage (Exit A / Exit B / Exit C), or `Ready` to `verify`. Static provenance never authorizes release on its own.
- **Suggested Next Step**: `/<skill> <args>` (emit one concrete command matched to the recommendation on standalone turns; omit when running inside a delegated subagent). - **Suggested Next Step**: `/<skill> <args>` (emit one concrete command matched to the recommendation on standalone turns; omit when running inside a delegated subagent).
``` ```
## 4. PR Review Block (Drafted and Auto-Published Here on Standalone Open PRs) ## 4. GitHub PR Review Publishing via `build_review.py`
`code-review` is strictly read-only regarding the codebase (never modifies repository files, commits, or Gitea project boards), and automatically publishes a comment-only PR review in the same turn when invoked standalone on an open pull request. When running as a delegated subagent inside `implement-slice`, skip PR posting and return the compact report to the orchestrator. `code-review` is strictly read-only regarding the codebase (never modifies repository files, commits, or GitHub Projects v2 boards). Whenever invoked on an open GitHub PR (verified via `gh repo view --json url`), whether standalone or delegated, build the review payload deterministically with `skills/code-review/scripts/build_review.py` and publish one comment-only review pinned to `head_sha`.
### What goes in If no open PR exists for `HEAD` (or when running in local-only mode), skip PR publishing and explicitly state in the report that no open PR was found and findings are reported locally.
- Every finding except `Rejected` ones (those stay in the local ledger only).
- Zero eligible findings on a `Ready` review: still draft and auto-publish `review-body.md` using the compact 4-axis pass template below (and omit `inline-comments.json`) so every reviewed PR head has an immutable, commit-pinned review record on Gitea.
### Per-finding routing (proposed here, decided by the owner before merge) ### Input Schema (`--input <findings.json>`)
| Field | Values | Rule |
| :--- | :--- | :--- |
| **Placement** | `inline` or `body` | `inline` only when the location is a committed line inside a diff hunk at the reviewed head SHA. Unstaged, staged, file-level, or cross-cutting findings go in `body`. |
| **Follow-up** | `fix-in-branch`, `live-tracker`, or `record` | Proposed triage exit: `fix-in-branch` (quick fix on PR branch), `live-tracker` (defer to Gitea issue or `todo.txt` via `tuxedo add` before merge), or `record` (only after owner grants permanent `Accepted Trade-off`). A closed PR comment is never a task tracker. |
### Identity across re-reviews Write temporary scratch files outside the repository tree (for example under `/tmp/cr-review-$$/`):
Finding IDs (`CR-01`) are only unique within one review. The block header names the reviewed head SHA, and any cross-review reference uses `<short-sha>/CR-01`. `gitea-pr` uses the header SHA to avoid posting the same review twice.
### Files
Write both files to an untracked scratch location (never inside the repository tree):
`review-body.md`:
```markdown
**Code review @ `<short-head-sha>`** (`<base-ref>`..`<head-ref>`): `<Ready | Pending Triage | Needs Rework | Blocked>`
Covered state: `<Clean | fingerprint>`. Tier: `<tier>`. Static provenance only; merge authority stays with the owner.
| ID | Axis | Severity | Disposition | Placement | Proposed Exit |
| :--- | :--- | :--- | :--- | :--- | :--- |
| CR-01 | Standards & Smells | Low | Confirmed | inline | fix-in-branch (or live-tracker) |
### Body-placed findings
- **CR-02** (`<location>`): <invariant, impact, and suggested change>.
```
`review-body.md` (clean `Ready` review with zero non-rejected findings; omit `inline-comments.json`):
```markdown
**Code review @ `<short-head-sha>`** (`<base-ref>`..`<head-ref>`): `Ready`
Covered state: `<Clean | fingerprint>`. Tier: `<tier>`. Static provenance only; merge authority stays with the owner.
| Axis | Disposition |
| :--- | :--- |
| Spec & Scope | Pass |
| Standards & Smells | Pass |
| Seam & Test Integrity | Pass |
| Defensive Invariants | Pass |
No non-rejected findings.
```
`inline-comments.json` (the `gt pr review --comments-file` format; `new_position` is the line number in the new version of the file and must fall inside a diff hunk):
```json ```json
[ {
{ "base_ref": "main",
"path": "src/pkg/config.py", "head_ref": "feat/example",
"new_position": 40, "covered_state": "Clean",
"body": "**CR-01** (Low, Accepted Trade-off, record): <invariant and impact>. <Suggested change>." "tier": "Standard",
} "findings": [
] {
"path": "src/pkg/config.py",
"line": 40,
"side": "RIGHT",
"severity": "Medium",
"axis": "Standards & Smells",
"title": "Missing public docstring",
"body": "Invariant, impact, and suggested change."
}
],
"rv_checks": [
{
"id": "RV-01",
"purpose": "Out-of-band conflict handling",
"scope": "local",
"pass_condition": "Duplicate returns HTTP 409",
"fail_signal": "FAIL if duplicate returns 200 or 500",
"command": "./scripts/test-concurrency-check.sh"
}
],
"triage_closures": [
{
"id": "CR-01",
"exit": "B",
"resolution": "Promoted to #45"
}
]
}
``` ```
Every inline entry also appears in the body table, so the record stays complete if inline placement is rejected and the entry moves to the body. - `findings[]` is required (may be `[]` on a clean `Ready` pass). Each finding requires non-empty strings `severity`, `title`, and `body`.
- `path`, `line`, and `side` (`"LEFT"` for deleted lines in the diff, `"RIGHT"` for added, modified, or context lines) are validated against `--diff`. Any finding that is cross-file (`path: null`), targets a missing file, or falls outside a diff hunk is automatically moved into `### Findings (Unanchored / Cross-File)` in the review `body` to prevent GitHub `422 Unprocessable Entity` errors.
- `rv_checks[]` (optional) renders inside a collapsible `<details>` block in the review `body` so `verify` can recover all `RV-*` checks in a fresh session.
- `triage_closures[]` (optional) renders a `### Triage Summary` section recording Exit B (`Promoted to #<N>`) and Exit C (`Dismissed: <reason>`) closures on a superseding `Ready` review.
### Auto-Publishing via `gt pr review` (Standalone Open PR Runs) ### Monotonic `CR-XX`, Guards, and `cr-review-meta`
When invoked standalone on an open PR, verify guards and publish one comment-only review pinned to the reviewed commit in the same turn:
`skills/code-review/scripts/build_review.py` parses paginated prior reviews and inline comments outside LLM context:
1. **Pagination flattening**: Consumes `gh api --paginate --slurp` (`[[...]]`) or flat (`[...]`) JSON arrays for both `--reviews` and `--comments`.
2. **Monotonic `max_id`**: Extracts the maximum integer across every `<!-- cr-review-meta: max_id=NN ... -->` marker and `^### CR-(\d+)` heading in prior reviews and inline comments. New findings start at `max_id + 1` (`CR-01`..`CR-99`, `CR-100`).
3. **Duplicate `(head_sha, verdict)` guard**: If a prior review already has the exact same `(head_sha, verdict)`, `build_review.py` exits `2` with no stdout JSON (skip re-posting). A `verdict=ready` review on the same `head_sha` is allowed to supersede an earlier `verdict=needs_rework` review after Exit B/C triage.
4. **3-rework-cycle cap**: Counts prior `cr-review-meta` entries with `verdict=needs_rework`. If 3 or more already exist and `--verdict needs_rework` is requested, `build_review.py` exits `1` with an escalation message on stderr; halt and escalate to the human owner.
5. **Metadata stamp**: Appends `<!-- cr-review-meta: max_id=NN head_sha=<sha> verdict=ready|needs_rework -->` to the emitted review `body`. `verify` reads this marker to confirm `verdict=ready` matches the current PR `head_sha`.
### Publishing Workflow (`gh api`)
```bash ```bash
# 1. Staleness: the PR head must equal the reviewed head SHA. Mismatch: stop, re-run code-review. # 1. Verify GitHub repository identity and resolve open PR number + head_sha
gt pr view <number> --json head_sha -q .head_sha gh repo view --json url -q .url
pr_num=$(gh pr view --json number -q .number)
head_sha=$(gh pr view "$pr_num" --json headRefOid -q .headRefOid)
repo=$(gh repo view --json nameWithOwner -q .nameWithOwner)
# 2. Duplicates and pending state: stop if any review is PENDING (posting would publish its # 2. Fetch PR diff and paginated review/comment history to scratch files
# inline comments too) or if a review already exists for the reviewed SHA from this block. scratch=$(mktemp -d)
gt pr review list <number> --json id,state,commit,body gh pr diff "$pr_num" > "$scratch/pr.diff"
gh api --paginate --slurp "repos/${repo}/pulls/${pr_num}/reviews" > "$scratch/reviews.json"
gh api --paginate --slurp "repos/${repo}/pulls/${pr_num}/comments" > "$scratch/comments.json"
# 3. Auto-publish one comment-only review, pinned to the reviewed commit. # 3. Build validated GitHub PR review JSON (exits 0=post, 2=duplicate skip, 1=error/3-cycle cap)
gt pr review <number> --comment --commit <reviewed-head-sha> \ if payload=$(python3 skills/code-review/scripts/build_review.py \
-F review-body.md --comments-file inline-comments.json --json id,url --input "$scratch/findings.json" \
--diff "$scratch/pr.diff" \
# Body-only block (no inline entries): omit --comments-file. --reviews "$scratch/reviews.json" \
--comments "$scratch/comments.json" \
--head-sha "$head_sha" \
--verdict "$verdict"); then
printf '%s\n' "$payload" | gh api "repos/${repo}/pulls/${pr_num}/reviews" --input - --jq '{id, html_url}'
else
rc=$?
# rc == 2: duplicate (head_sha, verdict) already published; skip cleanly
# rc == 1: invalid input or 3-rework-cycle cap reached; escalate to human owner
fi
rm -rf "$scratch"
``` ```
- Never pass `--approve` or `--request-changes`: the verdict in the body is informational, and merge authority stays with the owner (Gitea also refuses approval on your own PR). - `build_review.py` always emits `"event": "COMMENT"` pinned to `"commit_id": "<head_sha>"`. Never emit `APPROVE` or `REQUEST_CHANGES`: merge authority stays with the human owner.
- Never pass `--yes`: it exists to publish a pending review, which step 2 already rules out. - Record the returned review `id` and `html_url` in the final review summary.
- If Gitea rejects an inline entry (line outside a diff hunk), confirm with step 2 that no review was created, move that entry into the body, and retry once.
- Record the returned review `id` and `url`. Later fixes use `gt pr review reply` with `Fixed in <sha>` and `gt pr review resolve` via `gitea-pr`.
+470
View File
@@ -0,0 +1,470 @@
#!/usr/bin/env python3
"""
Deterministic GitHub PR review payload builder for the code-review skill.
Parses unified PR diffs and paginated prior GitHub reviews/comments to:
- Enforce duplicate (head_sha, verdict) skipping (exit 2)
- Enforce the 3-rework-cycle cap before human escalation (exit 1)
- Compute monotonic per-PR CR-XX finding IDs outside LLM context
- Anchor valid (path, line, side) findings as inline comments and move
out-of-hunk, missing-file, or cross-file findings into the review body
- Render optional collapsible RV-* runtime checks and triage closure summaries
- Stamp cr-review-meta and emit GitHub POST /pulls/{n}/reviews JSON to stdout
"""
import argparse
import json
import re
import sys
from pathlib import Path
from typing import Any
VALID_VERDICTS = ("ready", "needs_rework")
VALID_SIDES = ("LEFT", "RIGHT")
MAX_REWORK_CYCLES = 3
META_RE = re.compile(
r"<!--\s*cr-review-meta:\s*max_id=(\d+)\s+head_sha=(\S+)\s+verdict=(ready|needs_rework)\s*-->"
)
CR_HEADING_RE = re.compile(r"^###\s+CR-(\d+)\b", re.MULTILINE)
HUNK_RE = re.compile(r"^@@ -(\d+)(?:,(\d+))? \+(\d+)(?:,(\d+))? @@")
def fail(message: str, code: int = 1) -> None:
"""Write error message to stderr and exit with the given code."""
print(f"build_review: {message}", file=sys.stderr)
sys.exit(code)
def load_json_file(path_str: str, label: str) -> Any:
"""Load and parse a UTF-8 JSON file, exiting 1 on I/O or decode failure."""
path = Path(path_str)
try:
raw = path.read_text(encoding="utf-8")
except OSError as exc:
fail(f"cannot read {label} file '{path_str}': {exc}")
try:
return json.loads(raw)
except json.JSONDecodeError as exc:
fail(f"invalid JSON in {label} file '{path_str}': {exc}")
def flatten_paginated(data: Any, label: str) -> list[dict[str, Any]]:
"""Flatten gh api --paginate --slurp ([[...]]) or flat ([...]) JSON lists."""
if not isinstance(data, list):
fail(f"{label} must be a JSON array")
items: list[dict[str, Any]] = []
for entry in data:
if isinstance(entry, list):
for sub in entry:
if not isinstance(sub, dict):
fail(f"{label} nested page contains non-object entry")
items.append(sub)
elif isinstance(entry, dict):
items.append(entry)
else:
fail(f"{label} contains non-object entry")
return items
def _strip_diff_prefix(path_token: str, prefix: str) -> str:
"""Strip git diff a/ or b/ prefix and optional surrounding quotes."""
token = path_token.strip()
if token.startswith('"') and token.endswith('"') and len(token) >= 2:
token = token[1:-1]
if token.startswith(prefix):
return token[len(prefix):]
return token
def parse_diff_hunks(diff_text: str) -> tuple[dict[str, set[int]], dict[str, set[int]]]:
"""
Parse unified diff text into valid inline anchor line sets per file.
Returns (left_lines, right_lines) where:
- left_lines[path] holds deleted line numbers valid for side="LEFT"
- right_lines[path] holds added/modified/context line numbers valid for side="RIGHT"
"""
left_lines: dict[str, set[int]] = {}
right_lines: dict[str, set[int]] = {}
old_path: str | None = None
current_path: str | None = None
in_hunk = False
old_line = 0
new_line = 0
old_remaining = 0
new_remaining = 0
for raw_line in diff_text.splitlines():
if in_hunk and (old_remaining > 0 or new_remaining > 0):
if raw_line.startswith("\\"):
continue
if raw_line.startswith("-"):
if current_path is not None:
left_lines.setdefault(current_path, set()).add(old_line)
old_line += 1
old_remaining = max(0, old_remaining - 1)
continue
if raw_line.startswith("+"):
if current_path is not None:
right_lines.setdefault(current_path, set()).add(new_line)
new_line += 1
new_remaining = max(0, new_remaining - 1)
continue
if raw_line.startswith(" ") or raw_line == "":
if current_path is not None:
right_lines.setdefault(current_path, set()).add(new_line)
old_line += 1
new_line += 1
old_remaining = max(0, old_remaining - 1)
new_remaining = max(0, new_remaining - 1)
continue
# Unexpected non-hunk line ends the current hunk.
in_hunk = False
if raw_line.startswith("diff --git "):
in_hunk = False
old_path = None
current_path = None
continue
if raw_line.startswith("--- "):
in_hunk = False
token = raw_line[4:].split("\t", 1)[0].strip()
old_path = None if token == "/dev/null" else _strip_diff_prefix(token, "a/")
continue
if raw_line.startswith("+++ "):
in_hunk = False
token = raw_line[4:].split("\t", 1)[0].strip()
if token == "/dev/null":
current_path = old_path
else:
current_path = _strip_diff_prefix(token, "b/")
continue
match = HUNK_RE.match(raw_line)
if match:
old_line = int(match.group(1))
old_remaining = int(match.group(2)) if match.group(2) is not None else 1
new_line = int(match.group(3))
new_remaining = int(match.group(4)) if match.group(4) is not None else 1
in_hunk = True
return left_lines, right_lines
def inspect_history(
reviews: list[dict[str, Any]],
comments: list[dict[str, Any]],
) -> tuple[int, set[tuple[str, str]], int]:
"""
Scan prior reviews and inline comments for monotonic max_id,
prior (head_sha, verdict) pairs, and needs_rework cycle count.
"""
max_id = 0
seen_sha_verdicts: set[tuple[str, str]] = set()
needs_rework_count = 0
for review in reviews:
body = review.get("body") or ""
if not isinstance(body, str):
continue
for m in META_RE.finditer(body):
meta_max = int(m.group(1))
meta_sha = m.group(2)
meta_verdict = m.group(3)
if meta_max > max_id:
max_id = meta_max
seen_sha_verdicts.add((meta_sha, meta_verdict))
if meta_verdict == "needs_rework":
needs_rework_count += 1
for m in CR_HEADING_RE.finditer(body):
cid = int(m.group(1))
if cid > max_id:
max_id = cid
for comment in comments:
body = comment.get("body") or ""
if not isinstance(body, str):
continue
for m in META_RE.finditer(body):
meta_max = int(m.group(1))
if meta_max > max_id:
max_id = meta_max
for m in CR_HEADING_RE.finditer(body):
cid = int(m.group(1))
if cid > max_id:
max_id = cid
return max_id, seen_sha_verdicts, needs_rework_count
def validate_input(data: Any) -> tuple[list[dict[str, Any]], list[dict[str, Any]], list[dict[str, Any]], dict[str, str]]:
"""Validate input JSON schema and return (findings, rv_checks, triage_closures, meta_fields)."""
if not isinstance(data, dict):
fail("input JSON root must be an object")
if "findings" not in data or not isinstance(data["findings"], list):
fail("input JSON must include a 'findings' array")
findings: list[dict[str, Any]] = []
for idx, item in enumerate(data["findings"]):
if not isinstance(item, dict):
fail(f"findings[{idx}] must be an object")
for req in ("severity", "title", "body"):
val = item.get(req)
if not isinstance(val, str) or not val.strip():
fail(f"findings[{idx}] missing required non-empty string field '{req}'")
path_val = item.get("path")
if path_val is not None and not isinstance(path_val, str):
fail(f"findings[{idx}].path must be a string or null")
line_val = item.get("line")
if line_val is not None:
if isinstance(line_val, bool) or not isinstance(line_val, int) or line_val <= 0:
fail(f"findings[{idx}].line must be a positive integer or null")
side_val = item.get("side")
if side_val is not None and side_val not in VALID_SIDES:
fail(f"findings[{idx}].side must be 'LEFT', 'RIGHT', or null")
findings.append(item)
rv_checks = data.get("rv_checks", [])
if not isinstance(rv_checks, list):
fail("input JSON 'rv_checks' must be an array when provided")
for idx, chk in enumerate(rv_checks):
if not isinstance(chk, dict):
fail(f"rv_checks[{idx}] must be an object")
triage_closures = data.get("triage_closures", [])
if not isinstance(triage_closures, list):
fail("input JSON 'triage_closures' must be an array when provided")
for idx, cls_item in enumerate(triage_closures):
if not isinstance(cls_item, dict):
fail(f"triage_closures[{idx}] must be an object")
meta_fields: dict[str, str] = {}
for key in ("summary", "base_ref", "head_ref", "covered_state", "tier"):
val = data.get(key)
if isinstance(val, str) and val.strip():
meta_fields[key] = val.strip()
return findings, rv_checks, triage_closures, meta_fields
def format_cr_id(num: int) -> str:
"""Format numeric finding ID as CR-01..CR-99, CR-100, etc."""
return f"CR-{num:02d}"
def format_finding_block(cr_id: str, finding: dict[str, Any], include_location: bool) -> str:
"""Render a finding with a canonical ### CR-NN heading."""
title = finding["title"].strip()
severity = finding["severity"].strip()
axis = finding.get("axis")
meta_parts = [f"**Severity:** {severity}"]
if isinstance(axis, str) and axis.strip():
meta_parts.append(f"**Axis:** {axis.strip()}")
if include_location:
path_val = finding.get("path")
line_val = finding.get("line")
side_val = finding.get("side")
if isinstance(path_val, str) and path_val.strip():
loc = f"`{path_val.strip()}`"
if line_val is not None:
loc += f":L{line_val}"
if side_val:
loc += f" ({side_val})"
meta_parts.append(f"**Location:** {loc}")
else:
meta_parts.append("**Location:** Cross-file / General")
lines = [
f"### {cr_id}: {title}",
"",
" | ".join(meta_parts),
"",
finding["body"].strip(),
]
return "\n".join(lines)
def format_triage_summary(closures: list[dict[str, Any]]) -> str:
"""Render Exit B / Exit C triage closure summary."""
lines = ["### Triage Summary", ""]
for item in closures:
cid = str(item.get("id", "CR-??")).strip()
exit_code = str(item.get("exit", "")).strip()
resolution = str(item.get("resolution", "")).strip()
exit_label = f"Exit {exit_code}" if exit_code and not exit_code.lower().startswith("exit") else exit_code
if exit_label:
lines.append(f"- **{cid}** ({exit_label}): {resolution}")
else:
lines.append(f"- **{cid}**: {resolution}")
return "\n".join(lines)
def format_rv_checks(rv_checks: list[dict[str, Any]]) -> str:
"""Render collapsible RV-* executable runtime checks block."""
lines = [
"<details>",
"<summary>Executable Runtime Checks (RV-*)</summary>",
"",
]
for idx, chk in enumerate(rv_checks, start=1):
chk_id = str(chk.get("id") or f"RV-{idx:02d}").strip()
purpose = str(chk.get("purpose") or "Runtime verification check").strip()
scope = str(chk.get("scope") or "local").strip()
pass_cond = str(chk.get("pass_condition") or "").strip()
fail_sig = str(chk.get("fail_signal") or "").strip()
command = str(chk.get("command") or "").strip()
lines.append(f"#### {chk_id}: {purpose}")
lines.append(f"- **Scope:** `{scope}`")
if pass_cond:
lines.append(f"- **Pass Condition:** {pass_cond}")
if fail_sig:
lines.append(f"- **Failure Signal:** {fail_sig}")
if command:
lines.append("```sh")
lines.append(command)
lines.append("```")
lines.append("")
lines.append("</details>")
return "\n".join(lines)
def build_parser() -> argparse.ArgumentParser:
"""Build CLI argument parser."""
parser = argparse.ArgumentParser(
description="Build a validated GitHub PR review JSON payload with monotonic CR-XX IDs."
)
parser.add_argument("--input", required=True, help="Path to findings JSON input file")
parser.add_argument("--diff", required=True, help="Path to unified PR diff file")
parser.add_argument("--reviews", required=True, help="Path to prior PR reviews JSON file")
parser.add_argument("--comments", required=True, help="Path to prior PR inline comments JSON file")
parser.add_argument("--head-sha", required=True, help="Reviewed PR head commit SHA")
parser.add_argument("--verdict", required=True, help="Review verdict: ready or needs_rework")
return parser
def main(argv: list[str] | None = None) -> int:
parser = build_parser()
args = parser.parse_args(argv)
head_sha = args.head_sha.strip()
if not head_sha:
fail("--head-sha must be a non-empty string")
if args.verdict not in VALID_VERDICTS:
fail(f"invalid --verdict '{args.verdict}'; expected one of: {', '.join(VALID_VERDICTS)}")
input_data = load_json_file(args.input, "input")
reviews_raw = load_json_file(args.reviews, "reviews")
comments_raw = load_json_file(args.comments, "comments")
try:
diff_text = Path(args.diff).read_text(encoding="utf-8")
except OSError as exc:
fail(f"cannot read diff file '{args.diff}': {exc}")
findings, rv_checks, triage_closures, meta_fields = validate_input(input_data)
reviews = flatten_paginated(reviews_raw, "reviews")
comments = flatten_paginated(comments_raw, "comments")
max_id, seen_sha_verdicts, needs_rework_count = inspect_history(reviews, comments)
if (head_sha, args.verdict) in seen_sha_verdicts:
fail(
f"duplicate review skipped: (head_sha={head_sha}, verdict={args.verdict}) already exists",
code=2,
)
if args.verdict == "needs_rework" and needs_rework_count >= MAX_REWORK_CYCLES:
fail(
f"3-rework-cycle cap reached ({needs_rework_count} prior needs_rework reviews); escalate to human owner",
code=1,
)
left_lines, right_lines = parse_diff_hunks(diff_text)
inline_comments: list[dict[str, Any]] = []
unanchored_blocks: list[str] = []
current_id = max_id
for finding in findings:
current_id += 1
cr_id = format_cr_id(current_id)
path_val = finding.get("path")
line_val = finding.get("line")
side_val = finding.get("side") or "RIGHT"
anchored = False
if isinstance(path_val, str) and path_val.strip() and isinstance(line_val, int):
norm_path = path_val.strip()
if side_val == "LEFT" and line_val in left_lines.get(norm_path, set()):
anchored = True
elif side_val == "RIGHT" and line_val in right_lines.get(norm_path, set()):
anchored = True
if anchored:
inline_comments.append(
{
"path": path_val.strip(),
"line": line_val,
"side": side_val,
"body": format_finding_block(cr_id, finding, include_location=False),
}
)
else:
unanchored_blocks.append(format_finding_block(cr_id, finding, include_location=True))
short_sha = head_sha[:7]
body_sections: list[str] = []
header_line = f"**Code review @ `{short_sha}`**: `{args.verdict}`"
if "base_ref" in meta_fields and "head_ref" in meta_fields:
header_line = (
f"**Code review @ `{short_sha}`** "
f"(`{meta_fields['base_ref']}`..`{meta_fields['head_ref']}`): `{args.verdict}`"
)
body_sections.append(header_line)
meta_notes: list[str] = []
if "covered_state" in meta_fields:
meta_notes.append(f"Covered state: `{meta_fields['covered_state']}`.")
if "tier" in meta_fields:
meta_notes.append(f"Tier: `{meta_fields['tier']}`.")
meta_notes.append("Static provenance only; merge authority stays with the owner.")
body_sections.append(" ".join(meta_notes))
if "summary" in meta_fields:
body_sections.append(meta_fields["summary"])
elif not findings:
body_sections.append("No new findings.")
if unanchored_blocks:
body_sections.append("### Findings (Unanchored / Cross-File)\n\n" + "\n\n".join(unanchored_blocks))
if triage_closures:
body_sections.append(format_triage_summary(triage_closures))
if rv_checks:
body_sections.append(format_rv_checks(rv_checks))
body_sections.append(
f"<!-- cr-review-meta: max_id={current_id:02d} head_sha={head_sha} verdict={args.verdict} -->"
)
payload = {
"commit_id": head_sha,
"event": "COMMENT",
"body": "\n\n".join(body_sections),
"comments": inline_comments,
}
print(json.dumps(payload, indent=2))
return 0
if __name__ == "__main__":
sys.exit(main())
+387
View File
@@ -0,0 +1,387 @@
#!/usr/bin/env python3
"""
Unit tests for skills/code-review/scripts/build_review.py.
Covers:
1. --paginate --slurp JSON flattening ([[...]] and [...]) for --reviews and --comments
2. Unified diff hunk parsing and validation (LEFT deleted, RIGHT added/modified/context)
3. Out-of-hunk, missing-file, and cross-file findings routed to review body
4. Monotonic max_id extraction from cr-review-meta and ### CR-NN headings across reviews/comments
5. Collapsible RV-* block from rv_checks[] and Triage Summary from triage_closures[]
6. Duplicate (head_sha, verdict) exits 2; ready superseding needs_rework on same head_sha exits 0
7. 3-rework-cycle cap exits 1 on 4th needs_rework, allows ready
8. Invalid JSON, invalid verdict, and missing required fields exit 1
"""
import json
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent.parent
SCRIPT = REPO_ROOT / "skills" / "code-review" / "scripts" / "build_review.py"
SAMPLE_DIFF = """diff --git a/src/app.py b/src/app.py
index 1111111..2222222 100644
--- a/src/app.py
+++ b/src/app.py
@@ -10,4 +10,5 @@ def process(data):
x = 1
- old_call(data)
+ new_call(data)
+ extra_check(data)
return x
diff --git a/src/removed.py b/src/removed.py
deleted file mode 100644
index 3333333..0000000
--- a/src/removed.py
+++ /dev/null
@@ -1,2 +0,0 @@
-def legacy():
- return 0
"""
class TestBuildReview(unittest.TestCase):
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.tmp = Path(self._tmp.name)
def tearDown(self):
self._tmp.cleanup()
def _write_file(self, name, content):
path = self.tmp / name
if isinstance(content, str):
path.write_text(content, encoding="utf-8")
else:
path.write_text(json.dumps(content), encoding="utf-8")
return path
def _run(self, input_data, diff_text=SAMPLE_DIFF, reviews=None, comments=None,
head_sha="abc1234def5678", verdict="needs_rework"):
input_path = self._write_file("input.json", input_data)
diff_path = self._write_file("pr.diff", diff_text)
reviews_path = self._write_file("reviews.json", [] if reviews is None else reviews)
comments_path = self._write_file("comments.json", [] if comments is None else comments)
return subprocess.run(
[
sys.executable,
str(SCRIPT),
"--input", str(input_path),
"--diff", str(diff_path),
"--reviews", str(reviews_path),
"--comments", str(comments_path),
"--head-sha", head_sha,
"--verdict", verdict,
],
capture_output=True,
text=True,
)
def test_valid_anchored_left_and_right_findings_emit_inline_comments(self):
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "LEFT",
"severity": "High",
"axis": "Defensive Invariants",
"title": "Deleted validation call",
"body": "Removing old_call drops input validation.",
},
{
"path": "src/app.py",
"line": 12,
"side": "RIGHT",
"severity": "Medium",
"title": "Unbounded check",
"body": "extra_check lacks timeout.",
},
{
"path": "src/app.py",
"line": 10,
"side": "RIGHT",
"severity": "Low",
"title": "Context line anchor",
"body": "Context line inside hunk is valid on RIGHT.",
},
{
"path": "src/removed.py",
"line": 1,
"side": "LEFT",
"severity": "Medium",
"title": "Deleted file line anchor",
"body": "Deleted file line 1 is valid on LEFT.",
},
]
}
res = self._run(payload_in, head_sha="deadbeef0011", verdict="needs_rework")
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(out["commit_id"], "deadbeef0011")
self.assertEqual(out["event"], "COMMENT")
self.assertEqual(len(out["comments"]), 4)
self.assertEqual(out["comments"][0]["path"], "src/app.py")
self.assertEqual(out["comments"][0]["line"], 11)
self.assertEqual(out["comments"][0]["side"], "LEFT")
self.assertTrue(out["comments"][0]["body"].startswith("### CR-01:"))
self.assertEqual(out["comments"][1]["side"], "RIGHT")
self.assertTrue(out["comments"][1]["body"].startswith("### CR-02:"))
self.assertTrue(out["comments"][2]["body"].startswith("### CR-03:"))
self.assertEqual(out["comments"][3]["path"], "src/removed.py")
self.assertEqual(out["comments"][3]["side"], "LEFT")
self.assertTrue(out["comments"][3]["body"].startswith("### CR-04:"))
self.assertNotIn("### Findings (Unanchored / Cross-File)", out["body"])
self.assertIn(
"<!-- cr-review-meta: max_id=04 head_sha=deadbeef0011 verdict=needs_rework -->",
out["body"],
)
def test_unanchored_out_of_hunk_missing_file_and_cross_file_move_to_body(self):
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 99,
"side": "RIGHT",
"severity": "Medium",
"title": "Out of hunk line",
"body": "Line 99 is not in diff hunk.",
},
{
"path": "src/app.py",
"line": 10,
"side": "LEFT",
"severity": "Low",
"title": "Context line on LEFT rejected",
"body": "Context line is not a deleted line on LEFT.",
},
{
"path": "src/nonexistent.py",
"line": 5,
"side": "RIGHT",
"severity": "High",
"title": "Missing file",
"body": "File is not in diff.",
},
{
"path": None,
"line": None,
"side": None,
"severity": "High",
"title": "Cross-file architectural drift",
"body": "Multiple modules violate layering.",
},
]
}
res = self._run(payload_in, head_sha="aaaa1111", verdict="needs_rework")
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(out["comments"], [])
self.assertIn("### Findings (Unanchored / Cross-File)", out["body"])
for idx in ("### CR-01:", "### CR-02:", "### CR-03:", "### CR-04:"):
self.assertIn(idx, out["body"])
self.assertIn("<!-- cr-review-meta: max_id=04 head_sha=aaaa1111 verdict=needs_rework -->", out["body"])
def test_slurp_and_flat_pagination_monotonic_max_id_and_three_digit_rollover(self):
# Slurped nested pages for reviews: [[...], [...]]
slurped_reviews = [
[
{
"body": "Prior review\n<!-- cr-review-meta: max_id=05 head_sha=oldsha1 verdict=needs_rework -->"
}
],
[
{
"body": "### Findings (Unanchored / Cross-File)\n### CR-98: Old unanchored\nBody"
}
],
]
# Flat list for comments with CR-99
flat_comments = [
{"body": "### CR-99: Inline finding\nDetails"}
]
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "RIGHT",
"severity": "Medium",
"title": "Hundredth finding",
"body": "Should roll over to CR-100.",
}
]
}
res = self._run(
payload_in,
reviews=slurped_reviews,
comments=flat_comments,
head_sha="newsha99",
verdict="needs_rework",
)
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(len(out["comments"]), 1)
self.assertTrue(out["comments"][0]["body"].startswith("### CR-100:"))
self.assertIn(
"<!-- cr-review-meta: max_id=100 head_sha=newsha99 verdict=needs_rework -->",
out["body"],
)
def test_slurped_comments_also_flattened(self):
slurped_comments = [
[{"body": "### CR-03: First\nDetails"}],
[{"body": "### CR-07: Seventh\nDetails"}],
]
payload_in = {
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "RIGHT",
"severity": "Low",
"title": "Next finding",
"body": "Should be CR-08.",
}
]
}
res = self._run(
payload_in,
reviews=[[]],
comments=slurped_comments,
head_sha="sha0008",
verdict="needs_rework",
)
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertTrue(out["comments"][0]["body"].startswith("### CR-08:"))
def test_rv_checks_collapsible_block_and_triage_closures_summary(self):
payload_in = {
"findings": [],
"rv_checks": [
{
"id": "RV-01",
"purpose": "Concurrent submission returns 409",
"scope": "local",
"pass_condition": "HTTP 409 returned",
"fail_signal": "FAIL if HTTP 200 or 500",
"command": "./scripts/check_conflict.sh",
}
],
"triage_closures": [
{"id": "CR-01", "exit": "B", "resolution": "Promoted to #45"},
{"id": "CR-02", "exit": "C", "resolution": "Dismissed: false positive on fixture"},
],
}
prior_reviews = [
{
"body": "Prior\n<!-- cr-review-meta: max_id=02 head_sha=sha_same verdict=needs_rework -->"
}
]
# ready superseding needs_rework on same head_sha must exit 0
res = self._run(
payload_in,
reviews=prior_reviews,
head_sha="sha_same",
verdict="ready",
)
self.assertEqual(res.returncode, 0, res.stderr)
out = json.loads(res.stdout)
self.assertEqual(out["comments"], [])
self.assertIn("<details>", out["body"])
self.assertIn("RV-01", out["body"])
self.assertIn("./scripts/check_conflict.sh", out["body"])
self.assertIn("FAIL if HTTP 200 or 500", out["body"])
self.assertIn("### Triage Summary", out["body"])
self.assertIn("CR-01", out["body"])
self.assertIn("Promoted to #45", out["body"])
self.assertIn("Dismissed: false positive on fixture", out["body"])
self.assertIn(
"<!-- cr-review-meta: max_id=02 head_sha=sha_same verdict=ready -->",
out["body"],
)
def test_duplicate_head_sha_and_verdict_exits_2_with_empty_stdout(self):
prior_reviews = [
[
{
"body": "Already reviewed\n<!-- cr-review-meta: max_id=01 head_sha=dup1234 verdict=ready -->"
}
]
]
res = self._run({"findings": []}, reviews=prior_reviews, head_sha="dup1234", verdict="ready")
self.assertEqual(res.returncode, 2)
self.assertEqual(res.stdout.strip(), "")
self.assertIn("duplicate", res.stderr.lower())
def test_three_rework_cycle_cap_blocks_fourth_needs_rework_but_allows_ready(self):
prior_reviews = [
{"body": "<!-- cr-review-meta: max_id=01 head_sha=sha1 verdict=needs_rework -->"},
{"body": "<!-- cr-review-meta: max_id=02 head_sha=sha2 verdict=needs_rework -->"},
{"body": "<!-- cr-review-meta: max_id=03 head_sha=sha3 verdict=needs_rework -->"},
]
res_blocked = self._run(
{"findings": []},
reviews=prior_reviews,
head_sha="sha4",
verdict="needs_rework",
)
self.assertEqual(res_blocked.returncode, 1)
self.assertEqual(res_blocked.stdout.strip(), "")
self.assertIn("3-rework-cycle cap", res_blocked.stderr.lower())
res_ready = self._run(
{"findings": []},
reviews=prior_reviews,
head_sha="sha4",
verdict="ready",
)
self.assertEqual(res_ready.returncode, 0, res_ready.stderr)
out = json.loads(res_ready.stdout)
self.assertIn("<!-- cr-review-meta: max_id=03 head_sha=sha4 verdict=ready -->", out["body"])
def test_invalid_inputs_exit_1(self):
# Invalid JSON
res_bad_json = self._run("{not valid json")
self.assertEqual(res_bad_json.returncode, 1)
# Invalid verdict
res_bad_verdict = self._run({"findings": []}, verdict="approved")
self.assertEqual(res_bad_verdict.returncode, 1)
# Missing required findings key
res_no_findings = self._run({"rv_checks": []})
self.assertEqual(res_no_findings.returncode, 1)
# Finding missing required field (title)
res_missing_field = self._run(
{"findings": [{"severity": "High", "body": "Missing title"}]}
)
self.assertEqual(res_missing_field.returncode, 1)
# Invalid side value
res_bad_side = self._run(
{
"findings": [
{
"path": "src/app.py",
"line": 11,
"side": "CENTER",
"severity": "Low",
"title": "Bad side",
"body": "Invalid side enum.",
}
]
}
)
self.assertEqual(res_bad_side.returncode, 1)
if __name__ == "__main__":
unittest.main()