Compare commits

...
3 Commits
Author SHA1 Message Date
Markus Graf 122fc8e91d issue-triage: size issues/MRs against a reviewable-line budget via the Jev decision model 2026-12-01 09:59:22 +01:00
Markus Graf d15cb4d165 code-review: review the fakes' contract assumptions, diff external call sites against proven patterns, treat declared verification gaps as review scope
From the ai-cowork #154 rollout: a dockerode attach without hijack:true shipped
through three review rounds — the fake's stream accepted writes, the tests were
green, and the MR honestly declared the helper spawn as manually-smoke-only.
All three nets had the same hole: the boundary the tests fake.
2026-12-01 09:54:59 +01:00
Markus Graf 5254a480a2 integrations: rename pi-zai-usage to zai-usage 2026-12-01 09:54:59 +01:00
7 changed files with 502 additions and 1 deletions
+20 -1
View File
@@ -19,7 +19,9 @@ thorough, never pad with style opinions.
This skill is designed to run with **fresh context** (e.g. in a subagent). If the
current session authored the changes it is about to review, say so and recommend
a fresh-context review instead: the assumptions made while writing code carry
over into its review.
over into its review. The same applies to the review brief itself: an issue or
prompt highlights what the author considered risky — deliberately review what it
does *not* mention (fakes, declared verification gaps, transport plumbing).
## Workflow
@@ -33,6 +35,11 @@ over into its review.
3. If the diff is large (roughly >600 changed lines): review in passes, one
group of related files at a time, prioritizing source code over tests, docs,
and generated files. State explicitly which files you did not fully review.
4. **Declared verification gaps are review scope.** An MR that says "X is not
covered by automation — manual smoke before merge" has marked a surface as
untested. Either run that smoke yourself or review the surface by other
means (trace the real contract, exercise it in a safe environment).
Accepting the declaration as handled is how honest MRs ship broken features.
### Phase 2 — Context (the diff alone lies)
@@ -44,6 +51,12 @@ over into its review.
3. Trace the change into the codebase: open the full files around the hunks,
grep callers of changed functions, follow the data flow end to end. Do not
judge code you have not seen in context.
4. **Inventory the fakes**: find the test doubles the diff introduces or relies
on for external systems (docker, HTTP clients, DBs, queues, SDKs). Each fake
encodes the author's assumption about that system's contract — verify every
assumption against the real library (docs, source, or the repo's own proven
call site). A green suite against an optimistic fake proves the code matches
the assumption, not the system.
### Phase 3 — Review passes
@@ -54,6 +67,12 @@ Run the passes in this order; spend effort where the real defects live:
conditions, wrong state transitions.
2. **Contract breaks** — changed signatures or behavior vs. callers; API, DB,
or schema mismatches; serialization changes.
2b. **External call sites vs. proven patterns** — for every call the diff adds
into an external SDK, driver, or daemon API, find the repo's existing proven
call site for the same operation and diff the two call shapes (options,
flags, stream modes, attach/hijack variants). Subtle contract differences
(a missing `hijack: true` on a docker attach, a dropped TLS option) never
show up in unit tests with fakes — they only show in production.
3. **Security at trust boundaries** — user input, files, network, env vars,
secrets in logs or history, auth checks, injection, unsafe deserialization.
4. **Tests** — which changed behavior has no test? Do new tests assert
+80
View File
@@ -0,0 +1,80 @@
---
name: issue-triage
description: Judge whether an issue is too large to ship as one reviewable MR — uses the Jev decision model via OpenRouter's Decisions API plus a deterministic MR-size gate, anchored to a 30-minute senior-review budget (200 comfort / 400 ceiling reviewable lines). Use whenever the user asks whether an issue or feature should be split, wants an issue triaged/sized/scoped, wonders if something is "too big", asks for how to break work into reviewable chunks, or wants a branch/MR/PR checked for reviewable size — even when they just say "is this too large?" without naming this skill.
---
# Issue triage
Two gates keep merge requests reviewable:
1. **Triage (before code)** — a decision model judges the *issue* and returns calibrated
answers, not prose. Cheap (~$0.00003/call), input-token billing only.
2. **Size gate (after code, deterministic)** — counts *reviewable* changed lines of a
branch against the review budget. No model, no cost, always honest.
The anchor everywhere is review effort, not implementation effort: an MR a competent
senior developer can review in about 30 minutes. Where the numbers come from:
read `references/rubric.md` once when thresholds or the rubric are questioned.
## Triage an issue
```bash
bash ~/.config/opencode/skill/issue-triage/scripts/issue-triage.sh "issue text ..."
cat issue.txt | bash ~/.config/opencode/skill/issue-triage/scripts/issue-triage.sh
bash .../issue-triage.sh --json "issue text" # machine-readable verdict
```
Interpretation of the answers:
- `size_band` — estimated **reviewable** lines (handwritten logic only; renames,
generated code, lockfiles excluded). This is a prediction; verify with the gate.
- `review_too_big` — probability the MR exceeds the ~30-minute budget. Above ~0.7,
treat the issue as too large even if `action` says ship, and say so.
- `one_idea` — low value means the issue bundles separable ideas (the title would
need an "and"); each idea becomes its own issue/MR.
- `risk` (1–4) — high risk (auth, migrations, concurrency, data loss) lowers the
line budget and suggests expand–migrate–contract.
- `action` — `ship`, `split_before_coding`, or `needs_human`.
The script prints templated, deterministic advice derived from these answers.
**Advice only** — never create issues, sub-issues, or MRs from the verdict unless
the user explicitly asks. Do not invent extra "analysis" beyond the printed output.
## Check MR size
```bash
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh # auto base
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh origin/main
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh --strict # warn fails too
bash ~/.config/opencode/skill/issue-triage/scripts/mr-size-gate.sh --json
```
Exits 1 above the fail threshold, so it can run in CI or pre-push. It excludes
lockfiles, generated files, assets, binaries and pure renames from the count;
add repo-specific noise with `--exclude 'patterns/**'` or `MRGATE_EXCLUDE`.
Suggest adding repeatable exclusions to the repo rather than retyping them.
## Security and credentials
- The OpenRouter key lives in `~/.config/openrouter/scripts.env` (mode 600). The
scripts source it themselves; if it is missing, run `openrouter-env-sync`.
- Never print, echo, or log the key; never pass it as a CLI argument — the scripts
already hand it to curl via config-on-stdin. Do not read OpenCode's database
for keys in scripts.
- Do not copy issue text plus key into chat output; show verdicts, not payloads.
## Configuration
| Variable | Default | Purpose |
| --- | --- | --- |
| `JEV_MODEL` | `~typesafe/jev-latest` | pin a version, e.g. `typesafe/jev-1.13` |
| `MRGATE_WARN` / `MRGATE_FAIL` | 200 / 400 | reviewable-line thresholds |
| `MRGATE_EXCLUDE` | — | extra exclude globs, comma/space separated |
## Limits to keep in mind
- The Decisions endpoint is OpenRouter **alpha**: request shape may change; if the
script reports a 400 with schema complaints, re-check the API reference before
"fixing" the script blindly.
- Triage estimates are predictions about code that does not exist yet. The size
gate is the ground truth; when they disagree, trust the gate and mention the gap.
@@ -0,0 +1,71 @@
# Why these thresholds: the empirical grounding
The anchor is **review effort**, not implementation effort: an MR a competent
senior developer can review in about 30 focused minutes. Everything below traces
that anchor to published evidence, so the numbers are not taste.
## The review-budget research
- **SmartBear/Cisco study** (2,500 reviews, 3.2M lines, 10 months — the largest
public code-review study): defect-detection effectiveness peaks at
**200–400 reviewable lines** per change; a productive review session lasts
**60–90 minutes** at a pace of **300–500 lines/hour**. Past ~400 lines,
reviewers are overwhelmed and defect yield collapses.
- **30 minutes × 300–500 lines/hour ≈ 150–250 lines.** Our 200/400 thresholds
therefore sit in the lower half of the research sweet spot — deliberately
stricter than the classic "400-line ceiling".
- Corroborating data (Koalr analysis of review time vs. size): ≤200 changed
lines ≈ 22 minutes; 201–500 ≈ 48 minutes. 30 minutes lands around
250–300 lines — consistent with a 200 comfort / 400 hard ceiling.
- **Google's eng-practices**: "100 lines is usually a reasonable size for a CL,
and 1000 lines is usually too large."
- **Propel Code 2024**: PRs above 1,000 LOC show ~70% lower defect detection and
3× slower approval than 200–400-line PRs.
## What counts — and what never counts
The unit is **reviewable lines**: handwritten logic a reviewer must actually
understand. Excluded everywhere (triage estimates and size gate alike):
- lockfiles, dependency sums
- generated code (`*.pb.go`, `*_pb2.py`, `*.generated.*`, minified bundles, snapshots)
- binary and asset files
- **pure renames/moves** — reviewed by checking provenance and that tests pass,
never line by line
This is why "8 files" is meaningless as a unit: 8 files of comment tweaks is
close to zero reviewable lines; 8 files of rewrite can be 1,500. The count that
predicts review time is understanding-requiring lines, not files.
**One idea per MR** is the second gate: if the title needs an "and", it is two
MRs. A refactor and a behavior change never share one — "make the change easy
(warning: this may be hard), then make the easy change" (Kent Beck). Mechanical
changes get their own MRs because they are reviewed by a different, cheaper
method. Changes that cannot ship half-done go behind a flag or use
expand–migrate–contract, which is what keeps every slice independently
shippable.
## Why judge at triage time
- In the agent era this problem grows: an October 2026 analysis of 381
agent-written PRs found median PR size grew ~3× with AI assistance, large PRs
(≥400 reviewable lines) were ~4× more likely to contain a later-fixed bug, and
review attention thinned as size grew (comment density fell ~20×). The PRs
that need review most get the least.
- ThoughtWorks (Nov 2026) puts **stacked PRs in the Caution ring**: stacking is
"a workaround for poor upfront decomposition; the better habit is to specify,
split, size and deliver work as small, independent units." Judging the issue
*before* code exists is that better habit; the post-hoc splitters
(split-pr, stacksmith, pr-splitter, pr-shrinker) are the safety net.
- Two gates, one honest system: Jev **predicts** at triage time (cheap,
calibrated, advice-only); the deterministic size gate **verifies** on the
branch (free, exact). Predictions about code that does not exist are
fallible — the gate is the ground truth. When they disagree, trust the gate.
## Status of the numbers
The 200/400 thresholds and the question wording are **literature-anchored
defaults**, not calibrated on this user's history — deliberately, because
current session history does not yet represent the target level of work. If a
calibration pass is ever run (hand-labeled past issues, threshold sweep like
OpenRouter's Jev cookbook), this file is where the results and dates go.
+197
View File
@@ -0,0 +1,197 @@
#!/usr/bin/env bash
# issue-triage — judge whether an issue is too large to ship as one reviewable MR.
#
# Calls a decision model (Jev) through OpenRouter's Decisions API and returns
# typed, calibrated answers: size band, review-too-big probability, one-idea
# test, risk level, and a recommended action. Advice-only: it never creates
# issues or MRs.
#
# Usage:
# issue-triage.sh "issue text ..." # or pipe the issue text on stdin
# issue-triage.sh --json "issue text" # machine-readable verdict only
#
# Environment:
# OPENROUTER_API_KEY inherited; otherwise sourced from
# ~/.config/openrouter/scripts.env (run openrouter-env-sync)
# JEV_MODEL model override (default ~typesafe/jev-latest)
#
# Exit codes: 0 verdict produced, 1 API error, 2 usage error
set -euo pipefail
ENDPOINT="https://openrouter.ai/api/alpha/decisions"
MODEL="${JEV_MODEL:-~typesafe/jev-latest}"
ENV_FILE="${OPENROUTER_ENV_FILE:-$HOME/.config/openrouter/scripts.env}"
ATTEMPTS=5
need() { command -v "$1" >/dev/null 2>&1 || { echo "error: missing dependency '$1'" >&2; exit 2; }; }
need curl
need jq
json=0
if [ "${1:-}" = "--json" ]; then json=1; shift; fi
issue="${*:-}"
[ -n "$issue" ] || issue="$(cat)"
[ -n "$issue" ] || { sed -n '2,14p' "$0" | sed 's/^# \{0,1\}//'; exit 2; }
# --- key handling: never printed, never passed as a command-line argument ---
if [ -z "${OPENROUTER_API_KEY:-}" ] && [ -f "$ENV_FILE" ]; then
# shellcheck disable=SC1090
. "$ENV_FILE"
fi
if [ -z "${OPENROUTER_API_KEY:-}" ]; then
echo "error: no API key — run 'openrouter-env-sync' or set OPENROUTER_API_KEY (env file: $ENV_FILE)" >&2
exit 1
fi
payload=$(jq -n --arg model "$MODEL" --arg issue "$issue" '{
model: $model,
state: { issue: $issue },
questions: {
size_band: {
type: "choice",
instructions: ("Estimate the change set a competent developer would need to write to resolve this issue, counting only reviewable lines: handwritten logic a reviewer must actually understand. Exclude renames, moves, pure formatting, generated code, lockfiles, vendored code and binary assets. Pick the band the estimated reviewable-line total falls into."),
criteria: {
"under_150": "Under about 150 reviewable lines.",
"150_400": "Roughly 150 to 400 reviewable lines.",
"400_1000": "Roughly 400 to 1000 reviewable lines.",
"over_1000": "More than about 1000 reviewable lines."
}
},
review_too_big: {
type: "noul",
instructions: "If this issue were implemented as one merge request, would reviewing that merge request take a competent senior developer more than 30 focused minutes (roughly more than 400 reviewable lines, where renames, generated code and lockfiles do not count)?"
},
one_idea: {
type: "noul",
instructions: "Is this issue one coherent idea that could be titled without an 'and', or does it bundle independently separable ideas — including mixing a refactor with a behavior change?"
},
risk: {
type: "score",
instructions: "How risky is the likely change set for data integrity and security?",
criteria: [
"Low: no authentication, data migration, concurrency, or data-loss surfaces touched.",
"Moderate: one sensitive surface touched, well contained.",
"High: several sensitive surfaces touched (auth, migrations, concurrency, data handling).",
"Critical: touches authentication, data migrations, or anything that can lose or corrupt data."
]
},
action: {
type: "choice",
instructions: "What should happen with this issue before any code is written?",
criteria: {
"ship": "Small enough to implement and review as one merge request as described.",
"split_before_coding": "Should be split into separately reviewable merge requests before implementation starts.",
"needs_human": "Scope or intent is ambiguous; a human should refine the issue first."
}
}
}
}')
# --- request with retry: 429 / 5xx / in-flight-budget 402 are transient ---
attempt=0
body=""
while :; do
attempt=$((attempt + 1))
errf=$(mktemp); hdrs=$(mktemp)
set +e
resp=$(printf 'header = "Authorization: Bearer %s"\n' "$OPENROUTER_API_KEY" \
| curl -sS --max-time 90 -K - -D "$hdrs" -w '\n%{http_code}' \
-H "Content-Type: application/json" -d "$payload" "$ENDPOINT" 2>"$errf")
rc=$?
set -e
if [ $rc -ne 0 ]; then
code="000"; body=""
else
code="${resp##*$'\n'}"; body="${resp%$'\n'*}"
fi
transient=0
if [ "$code" = "429" ] || [ "$code" = "000" ] || [ "${code:0:1}" = "5" ]; then
transient=1
elif [ "$code" = "402" ] && jq -e '.error.metadata.limit_source == "openrouter_in_flight_budget"' <<<"${body:-{}}}" >/dev/null 2>&1; then
transient=1
fi
if [ "$transient" = "1" ] && [ "$attempt" -lt "$ATTEMPTS" ]; then
ra=$(awk -F': *' 'tolower($1) == "retry-after" && $2 + 0 > 0 { print int($2) }' "$hdrs")
delay=${ra:-$(( 1 << (attempt - 1) ))}
[ "$delay" -le 30 ] || delay=30
sleep "$delay"
rm -f "$errf" "$hdrs"
continue
fi
break
done
rm -f "$errf" "$hdrs"
if [ "$code" != "200" ]; then
echo "error: Decisions API HTTP $code: ${body:0:300}" >&2
exit 1
fi
# --- extract answers (defensive on the score field name) ---
verdict=$(jq '{
model: .model,
size_band: { choice: .answers.size_band.choice, confidence: .answers.size_band.confidence },
review_too_big: .answers.review_too_big.noul,
one_idea: .answers.one_idea.noul,
risk: (.answers.risk.score // .answers.risk.value // .answers.risk.level),
action: { choice: .answers.action.choice, confidence: .answers.action.confidence },
usage: { input_tokens: .usage.input_tokens, output_tokens: .usage.output_tokens, cost: .usage.cost }
}' <<<"$body")
[ "$json" = "1" ] && { printf '%s\n' "$verdict"; exit 0; }
band=$(jq -r '.size_band.choice' <<<"$verdict")
too_big=$(jq -r '.review_too_big' <<<"$verdict")
one_idea=$(jq -r '.one_idea' <<<"$verdict")
risk_raw=$(jq -r '.risk // 0' <<<"$verdict")
# score answers are continuous; map to the nearest of the 4 rubric levels (0=Low .. 3=Critical)
risk_idx=$(awk "BEGIN{r=$risk_raw+0; l=int(r+0.5); if(l<0)l=0; if(l>3)l=3; print l}")
risk_name=$(printf '%s\n' "Low" "Moderate" "High" "Critical" | sed -n "$((risk_idx + 1))p")
action=$(jq -r '.action.choice' <<<"$verdict")
action_conf=$(jq -r '.action.confidence // "n/a"' <<<"$verdict")
cost=$(jq -r '.usage.cost' <<<"$verdict")
in_tok=$(jq -r '.usage.input_tokens' <<<"$verdict")
out_tok=$(jq -r '.usage.output_tokens' <<<"$verdict")
case "$band" in
under_150) band_h="under 150 reviewable lines";;
"150_400") band_h="~150-400 reviewable lines";;
"400_1000") band_h="~400-1000 reviewable lines";;
*) band_h=">1000 reviewable lines";;
esac
echo "Issue triage — $MODEL"
echo " estimated size: $band_h"
echo " review_too_big: $too_big (>0.7 means over the ~30-minute review budget)"
echo " one_idea: $one_idea (low = bundles separable ideas)"
echo " risk level: $risk_name (score $risk_raw)"
echo " action: $action (confidence $action_conf)"
echo
advice() {
if [ "$1" = "split_before_coding" ]; then
echo "Advice: split before writing code. Suggested seams, in dependency order:"
awk "BEGIN{exit !($2 < 0.5)}" && echo " - The issue bundles separable ideas: find the 'and' in the scope; one MR per idea."
echo " - Land refactors, renames and mechanical changes in their own MRs first (make the change easy, then make the easy change)."
echo " - Keep tests in the same MR as the code they test; generated code, lockfiles and pure renames go into a separate mechanical MR."
if [ "$4" = "400_1000" ] || [ "$4" = "over_1000" ]; then
echo " - Likely a stack of 2-4 MRs; order them by dependency, each independently buildable and reviewable."
fi
if [ "$3" -ge 2 ]; then
echo " - Risky surfaces (auth/migrations/concurrency/data): use expand-migrate-contract so every MR ships safely; keep the risky MR's diff minimal."
fi
elif [ "$1" = "needs_human" ]; then
echo "Advice: refine scope with the issue author before implementation — the model judged the intent ambiguous."
else
if awk "BEGIN{exit !($5 >= 0.7)}"; then
echo "Advice: model says ship, but its review-too-big probability is high — sanity-check the size estimate before trusting this verdict."
else
echo "Advice: small enough to implement and review as one MR."
fi
fi
}
advice "$action" "$one_idea" "$risk_idx" "$band" "$too_big"
printf 'cost: $%.6f (%s in / %s out tokens)\n' "$cost" "$in_tok" "$out_tok"
+134
View File
@@ -0,0 +1,134 @@
#!/usr/bin/env bash
# mr-size-gate — deterministic reviewable-lines check for a branch/MR vs a base ref.
#
# Counts "reviewable lines" (added + removed) that a human must actually read:
# excludes lockfiles, generated/asset files, binaries, and pure renames, so a
# 40,000-line lockfile bump or a directory rename never hides real changes —
# and never inflates them.
#
# Usage:
# mr-size-gate.sh [options] [base-ref]
# Options:
# --base REF base ref (default: origin/main, origin/master, main, master)
# --head REF head ref (default: HEAD)
# --warn N warn threshold in reviewable lines (default 200, env MRGATE_WARN)
# --fail N fail threshold in reviewable lines (default 400, env MRGATE_FAIL)
# --exclude PAT extra glob pattern to exclude, matches full path (repeatable;
# env MRGATE_EXCLUDE, comma/space separated)
# --strict exit non-zero also in the warn zone
# --json machine-readable output
#
# Exit codes: 0 ok (or warn without --strict), 1 fail (or warn with --strict), 2 error
set -euo pipefail
warn="${MRGATE_WARN:-200}"
fail="${MRGATE_FAIL:-400}"
strict=0 json=0
declare -a pats=()
base="" head="HEAD"
usage() { sed -n '2,22p' "$0" | sed 's/^# \{0,1\}//'; }
while [ $# -gt 0 ]; do
case "$1" in
--base) base="$2"; shift 2;;
--head) head="$2"; shift 2;;
--warn) warn="$2"; shift 2;;
--fail) fail="$2"; shift 2;;
--exclude) pats+=("$2"); shift 2;;
--strict) strict=1; shift;;
--json) json=1; shift;;
-h|--help) usage; exit 0;;
--*) echo "error: unknown option $1" >&2; usage >&2; exit 2;;
*) base="$1"; shift;;
esac
done
if [ -n "${MRGATE_EXCLUDE:-}" ]; then
# shellcheck disable=SC2206
pats+=(${MRGATE_EXCLUDE//,/ })
fi
git rev-parse --git-dir >/dev/null 2>&1 || { echo "error: not inside a git repository" >&2; exit 2; }
if [ -z "$base" ]; then
for cand in origin/main origin/master main master; do
if git rev-parse --verify --quiet "$cand" >/dev/null 2>&1; then base="$cand"; break; fi
done
fi
[ -n "$base" ] || { echo "error: no base ref found (tried origin/main, origin/master, main, master) — pass --base" >&2; exit 2; }
git rev-parse --verify --quiet "$base" >/dev/null 2>&1 || { echo "error: base ref '$base' not found" >&2; exit 2; }
git rev-parse --verify --quiet "$head" >/dev/null 2>&1 || { echo "error: head ref '$head' not found" >&2; exit 2; }
declare -A nfiles=([reviewable]=0 [lockfile]=0 [generated]=0 [asset]=0 [binary]=0 [rename]=0 [user]=0)
declare -A nlines=([reviewable]=0 [lockfile]=0 [generated]=0 [asset]=0 [binary]=0 [rename]=0 [user]=0)
classify() {
local added="$1" removed="$2" path="$3" base_name
base_name="${path##*/}"
if [ "$added" = "-" ]; then nfiles[binary]=$((nfiles[binary]+1)); return; fi
if [ "$added" = "0" ] && [ "$removed" = "0" ] && [[ "$path" == *"=>"* ]]; then
nfiles[rename]=$((nfiles[rename]+1)); return
fi
case "$base_name" in
package-lock.json|yarn.lock|pnpm-lock.yaml|bun.lockb|bun.lock|deno.lock|go.sum|go.work.sum|Cargo.lock|poetry.lock|uv.lock|Gemfile.lock|composer.lock|Pipfile.lock|packages.locked|gradle.lockfile|flake.lock)
nfiles[lockfile]=$((nfiles[lockfile]+1)); return;;
esac
case "$path" in
*.min.js|*.min.mjs|*.min.css|*.js.map|*.css.map|*.snap|*.pb.go|*_pb2.py|*_pb2_grpc.py|*.generated.*|*.asset.php)
nfiles[generated]=$((nfiles[generated]+1)); return;;
esac
case "$base_name" in
*.svg|*.svgz) nfiles[asset]=$((nfiles[asset]+1)); return;;
esac
local pat
for pat in ${pats[@]+"${pats[@]}"}; do
# shellcheck disable=SC2053 # unquoted glob match is intended
[[ "$path" == $pat ]] && { nfiles[user]=$((nfiles[user]+1)); return; }
done
nfiles[reviewable]=$((nfiles[reviewable]+1))
nlines[reviewable]=$((nlines[reviewable] + added + removed))
}
diff="$(git diff --numstat --find-renames "$base...$head")" || {
echo "error: git diff failed (are $base and $head related?)" >&2; exit 2; }
while IFS=$'\t' read -r added removed path; do
[ -n "${path:-}" ] || continue
classify "$added" "$removed" "$path"
done <<<"$diff"
total=${nlines[reviewable]}
if [ "$total" -gt "$fail" ]; then
verdict="FAIL"; rc=1
elif [ "$total" -gt "$warn" ]; then
verdict="WARN"; rc=$(( strict ? 1 : 0 ))
else
verdict="OK"; rc=0
fi
if [ "$json" = "1" ]; then
jq -n \
--arg base "$base" --arg head "$head" \
--argjson reviewable_lines "$total" \
--argjson reviewable_files "${nfiles[reviewable]}" \
--argjson warn "$warn" --argjson fail "$fail" \
--arg verdict "$verdict" \
--argjson excluded "$(jq -n \
--argjson lockfile "${nfiles[lockfile]}" --argjson generated "${nfiles[generated]}" \
--argjson asset "${nfiles[asset]}" --argjson binary "${nfiles[binary]}" \
--argjson rename "${nfiles[rename]}" --argjson user "${nfiles[user]}" \
'{lockfile: $lockfile, generated: $generated, asset: $asset, binary: $binary, pure_renames: $rename, user_patterns: $user}')" \
'{base: $base, head: $head, reviewable_lines: $reviewable_lines,
reviewable_files: $reviewable_files, excluded_files: $excluded,
warn_threshold: $warn, fail_threshold: $fail, verdict: $verdict}'
else
echo "MR size gate: $base ... $head"
echo " reviewable: $total lines across ${nfiles[reviewable]} files"
echo " excluded files: lockfile=${nfiles[lockfile]} generated=${nfiles[generated]} asset=${nfiles[asset]} binary=${nfiles[binary]} pure-renames=${nfiles[rename]} user-patterns=${nfiles[user]}"
echo " limits: warn $warn / fail $fail reviewable lines (≈30-minute senior review budget: 200 comfort, 400 ceiling)"
case "$verdict" in
OK) echo " verdict: OK — comfortably reviewable in one sitting";;
WARN) echo " verdict: WARN — at the edge of a 30-minute review; consider trimming or splitting";;
FAIL) echo " verdict: FAIL — over the review budget; split the MR before requesting review";;
esac
fi
exit "$rc"