Files

198 lines
8.5 KiB
Bash
Raw Permalink Normal View History

#!/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"