diff --git a/README.md b/README.md index a2ff798..936e6a5 100644 --- a/README.md +++ b/README.md @@ -58,11 +58,12 @@ Inside a repo clone, a bare number works: `gh pr-review 42`. | `--no-post` | posting on (with confirm) | Print the review only | | `--instructions ` | none | Extra guidance for both passes, for example `"Focus on db/; skip style nits"`. For a file: `--instructions "$(cat notes.md)"`. The tool does not post them, and the reviewer is told not to quote them, but the review can still reflect them: use `--no-post` to preview a review shaped by sensitive notes | | `--skip-approach` | off | Skip the maintainer's approach pass and run the code review only, for example when the approach is already agreed | -| `--decision ` | from verdict | `comment`, `approve`, `request-changes`. Unset: an approach verdict of Rethink → request-changes. Otherwise the last "Ready to merge?" line decides: No → request-changes, a bare Yes → approve (comment when the round's blocker count is unknown, as for a code review read from its Markdown with no severity section; a valid empty findings block is a known zero, and approves), anything else (Yes with fixes, Yes, with fixes, …) → comment. On your own PR it is always comment. `-y` submits the decision without asking | +| `--decision ` | from verdict | `comment`, `approve`, `request-changes`. Unset: an approach verdict of Rethink → request-changes. Otherwise the last "Ready to merge?" line decides: No → request-changes, a bare Yes → approve only when the round's record shows 0 open blockers (comment when blockers are open, or when the count is unknown, as for a code review read from its Markdown with no severity section; a valid empty findings block is a known zero, and approves), anything else (Yes with fixes, Yes, with fixes, …) → comment. On your own PR it is always comment. `-y` submits the decision without asking | | `-y`, `--yes` | off | Skip the confirmations. A loop-check stop then exits with code 3, and no new commits with code 5, instead of asking | | `--check` | off | Run only the loop check (see below) and exit 0, 3 or 5. No clone, no model call | | `--json` | off | With `--check`: print the decision as JSON on stdout | | `--force-round` | off | Run a round even when the loop check stops it or nothing changed | +| `--full` | off | Review the whole PR again, as in round 1. Earlier findings are still re-checked by ID | | `--doctor` | — | Check prerequisites and exit | Environment variables: `GH_PR_REVIEW_MODEL` (default model), @@ -169,8 +170,12 @@ next round: stop · churning · approach-stuck too-big · Settle the approach be The Markdown is the cross-check for the model's findings block: it is parsed before the block is accepted, and a block that leaves out a blocker the Markdown -shows, or has one where it says none, is rejected. It is also the source when -the block is rejected, and for a review without a usable marker. The reader +shows, or has one where it says none, is rejected. A Later item that can't be +Later (it is in what changed) is kept as a finding: the Markdown showing it in +its Later list instead of its severity section is no contradiction. The +Markdown is also the source when the block is rejected, and for a review +without a usable marker; when the rejected block had such an item, the +Markdown can't count it, so the round's blocker count is unknown. The reader follows the format the tool asks the model for (the `### Issues` section with severity headings, findings as list items, the folded Fixed and Later lists, each `
` tag on its own line), and is best effort for other Markdown: @@ -193,6 +198,56 @@ its Markdown has no severity section to rebuild one from (never read as 0, so never `ready`). `--json` prints the records and the decision; `-u ` picks the gh account, as for a review. +## Round 2 and later + +From the second round, the reviewer builds on the last code review instead of +starting over: + +1. **Earlier findings are re-checked by ID.** Each one comes back `fixed`, + `open` (a fix attempt that did not work stays open) or `declined` (only with + a reason from the PR discussion, quoted; without one it stays open). The + findings that round fixed are listed too: one that comes back keeps its ID + and is `regressed`. One the reviewer forgets is kept `open` and marked as + not re-checked: nothing disappears silently. +2. **What changed since that round is reviewed in full**, at every severity: + `git diff ..`, or `git range-diff` when the author + rebased. +3. **Outside what changed, only Critical findings are raised.** Important and + Minor issues there go to a folded **Later** list. Later items don't block + the PR, and can become follow-up issues. A Critical finding, or one in + what changed, is never Later. + +The owner pass starts from its previous verdict, and keeps it in one line +unless the changes or the discussion change it. After a Rethink it judges +afresh. + +The posted review opens with a progress line counted from the round record, +not from the model's text: + +``` +### Round 3 · since round 2 +4 fixed · 2 still open · 3 new (1 in the new commits) · open blocking: 5 (was 6) · loop: converging +``` + +Fixed findings and the Later list follow the open ones, folded. "Ready to +merge? Yes" with blocking findings still open posts as a comment: the record +wins. + +A later round read back from its Markdown (no marker, or one without the full +counts) takes its open blocking count from the progress line: its Markdown +leaves out the findings it carried without re-checking them. The IDs in its +Fixed list are never open, and every ID it shows, and every Later item, keeps +its number reserved. + +When the comparison is not safe, the round is a full review, and it says why: +the previous head is gone (a force-push), the base branch was merged in with +conflicts, the PR's base changed (a retarget), the last round's base is unknown +(a review read back from its Markdown), git cannot list the changed files, or +the last round's record lost its findings to GitHub's size cap or could not be +built. A later round whose record could not be built still posts a minimal +marker that says so: read back, its blocker count is unknown, never 0. `--full` asks for one, for example after a +rewrite. + ## Loop check Before a round, the tool reads the PR's earlier rounds and decides whether @@ -202,9 +257,18 @@ Important) of each round: - **Converging:** the count drops (to 1 or less, or by 30% over two rounds). The round runs. - **Nit loop** (3 or fewer, no Critical) or **Churning** (anything else) after - the first 3 rounds: a warning. The round runs, and the posted review starts - with a line such as - `**Loop:** Churning · blocking 9, 12, 8 · Split the PR: each part converges on its own`. + the first 3 rounds: a warning. The round runs. Its posted review opens with + the progress line (see above), which carries the loop label, and a + suggested move under it: + + ``` + ### Round 4 · since round 3 + 2 fixed · 6 still open · 4 new · open blocking: 10 (was 8) · loop: churning + **Next:** Split the PR: each part converges on its own + ``` + + Without a round record to count from, the review opens with the older + one-line form instead: `**Loop:** Churning · blocking 9, 12, 8 · …`. - **Two such rounds in a row:** the round stops before any clone or model call. In a terminal it asks first; with `-y` (scripts and agents) it exits with code 3. The suggested move comes from the history: settle the approach, diff --git a/docs/superpowers/specs/2026-11-26-review-tracking-results.md b/docs/superpowers/specs/2026-11-26-review-tracking-results.md index e10409c..ae3318f 100644 --- a/docs/superpowers/specs/2026-11-26-review-tracking-results.md +++ b/docs/superpowers/specs/2026-11-26-review-tracking-results.md @@ -58,3 +58,52 @@ Nothing was posted. The whole suite passes on macOS (BSD userland, jq 1.8.2) and in an Ubuntu 24.04 container (mawk, jq 1.7, no `column`). The first Linux run caught one bug: `column` turned the `–` placeholder into byte escapes outside a UTF-8 locale. `rounds` now pads its table in jq. + +## PR 2: incremental rounds + +Date: 2026-11-26. Branch `review-tracking`. No round was posted. + +### Preview round 3 on adobe/skills#823 + +`gh pr-review https://github.com/adobe/skills/pull/823 --no-post`, model `github-copilot/gpt-5.6-sol`. Rounds 1 and +2 predate the records, so round 3 builds on the backfilled round 2: 8 findings with IDs F11 to F18. + +| Check | Result | +| --- | --- | +| Mode | `incremental`: the author merged `main` into the PR since round 2, so the delta starts from round 2's head merged onto the new base | +| Files the delta touched | 11, all in the PR (a plain diff from round 2's head listed 32: 21 came from `main`) | +| Earlier IDs accounted for | 8 of 8: 5 fixed, 2 open, 1 declined (with the author's reason quoted), 0 not re-checked | +| New findings | 2 (F19, F20), both in the new commits. Later list: empty | +| Open blocking | 3 (was 7): 1 Critical, 2 Important. Label `converging` (series 9, 7, 3) | +| Progress line | `5 fixed · 2 still open · 2 new (2 in the new commits) · 1 declined · open blocking: 3 (was 7) · loop: converging`, the same numbers as `round.json` | +| Owner pass | Got its round 2 verdict (Questionable) and the delta. It changed the verdict to Sound and wrote the full section | +| Findings block | Present (10 entries), cut from the body. No loop line next to the progress line | + +The model set `in_delta: true` on the earlier findings too. It only matters for new findings (the progress line +counts those), so the record keeps it as given. + +### Bugs this check found, fixed before the run above + +- **Backfill carried every earlier finding.** With statuses, a backfilled round carried the round before it as + "open, not re-checked", so the backfilled blocking series grew (adobe/skills#813: 9, 21, 29, …). An old review says + nothing about what was fixed, so backfill now uses the previous record for ID numbers only. The 12 calibration PRs + match the spec's table again. +- **A merge of the base branch counted as the author's change.** A plain `git diff ..` included + everything `main` brought in. The delta now compares with the previous head merged onto the new base + (`git merge-tree --write-tree`), and falls back to a range-diff when that merge conflicts. + +### Posted round 3 on adobe/skills#823 + +With approval, the previewed review above was posted as a comment (my own PR) through the tool's posting functions: +the same body, the round marker, `gh pr review --comment`. The head was unchanged since the preview. + +- On GitHub the review opens with the progress line. Body 11,208 characters, marker 3,264. +- `gh pr-review rounds` reads round 3 from its marker: `source: model`, 1 Critical, 2 Important and 1 Minor open, + label `converging`, 4 commits since round 2. +- `gh pr-review --check` then says "no new commits since round 3" (exit 5). + +### Not checked yet + +- A rebase between two rounds on a real PR: none at hand. The rebase, force-push and shallow cases are covered by + `tests/delta.sh` with real git. +- A full posted run through the interactive prompt (the agent's shell has no terminal). diff --git a/gh-pr-review b/gh-pr-review index 4fbb6db..5d0366c 100755 --- a/gh-pr-review +++ b/gh-pr-review @@ -18,6 +18,7 @@ # --json With --check, print the decision as JSON # --force-round Run a round even when the loop check stops it or nothing changed # (in a terminal, without -y, both ask "Run round K anyway?" instead) +# --full Review the whole PR again (round 2 and later still re-check the earlier findings) # --doctor Check all prerequisites and exit # -h, --help Show this help # @@ -78,6 +79,7 @@ GH_USER="${GH_PR_REVIEW_USER:-}" CHECK_ONLY=false CHECK_JSON=false FORCE_ROUND=false +FULL_ROUND=false # ── arg parsing ────────────────────────────────────────────────────────────── while [[ $# -gt 0 ]]; do @@ -122,6 +124,10 @@ while [[ $# -gt 0 ]]; do FORCE_ROUND=true shift ;; + --full) + FULL_ROUND=true + shift + ;; --no-post) POST_TO_PR=false shift @@ -162,7 +168,7 @@ while [[ $# -gt 0 ]]; do done if [[ "$DOCTOR" == "false" && -z "$TARGET" ]]; then - echo "Usage: gh pr-review [--model ] [--no-post] [--skip-approach] [-y] [--check [--json]] [--force-round] [--doctor]" >&2 + echo "Usage: gh pr-review [--model ] [--no-post] [--skip-approach] [-y] [--check [--json]] [--force-round] [--full] [--doctor]" >&2 exit 1 fi if [[ "$CHECK_JSON" == "true" && "$CHECK_ONLY" == "false" ]]; then @@ -252,10 +258,10 @@ instructions_section() { printf 'on the PR.\n\n%s\n\n' "$INSTRUCTIONS" } -# The posted body: the loop line, the approach section, then the code review, then one footer. Empty in, empty out. -# The code review starts with an invisible boundary line (code_review_boundary in lib/records.jq): the reader reads -# the code review from there, as the writer reads it. -assemble_review() { # +# The posted body: the head (the loop line, or a later round's progress lines: assemble_body), the approach section, +# then the code review, then one footer. Empty in, empty out. The code review starts with an invisible boundary line +# (code_review_boundary in lib/records.jq): the reader reads the code review from there, as the writer reads it. +assemble_review() { # local parts=() part for part in "$1" "$2"; do [[ -n "$part" ]] && parts+=("$part"); done [[ -n "$3" ]] && parts+=($'\n'"$3") @@ -478,11 +484,18 @@ git "${GIT_AUTH[@]}" fetch origin "${BASE_BRANCH}:refs/remotes/origin/${BASE_BRA git checkout pr-branch --quiet HEAD_SHA=$(git rev-parse HEAD) -BASE_SHA=$(git merge-base HEAD "origin/${BASE_BRANCH}") || { - echo "Error: no merge-base between PR head and origin/${BASE_BRANCH} within the" >&2 - echo "shallow clone (depth 50). Refusing to review a partial diff." >&2 - exit 1 -} +# A PR branched off more than 50 commits back has no merge-base in the shallow clone: deepen both histories once. +# One fetch per ref: in a single fetch, git can leave one of them as shallow as it was. +if ! BASE_SHA=$(git merge-base HEAD "origin/${BASE_BRANCH}" 2>/dev/null); then + git "${GIT_AUTH[@]}" fetch --quiet --no-tags --deepen 200 origin "pull/${PR_NUM}/head" || true + git "${GIT_AUTH[@]}" fetch --quiet --no-tags --deepen 200 origin \ + "${BASE_BRANCH}:refs/remotes/origin/${BASE_BRANCH}" || true + BASE_SHA=$(git merge-base HEAD "origin/${BASE_BRANCH}") || { + echo "Error: no merge-base between PR head and origin/${BASE_BRANCH} within the" >&2 + echo "shallow clone (depth 50, deepened by 200). Refusing to review a partial diff." >&2 + exit 1 + } +fi echo " base: ${BASE_SHA:0:8} head: ${HEAD_SHA:0:8}" echo "" @@ -490,7 +503,128 @@ echo "" CONTEXT_DIR="${SESSION_DIR}/context" write_pr_context "$CONTEXT_DIR" +# ── previous round ───────────────────────────────────────────────────────────────── +# Round 2 and later build on the last round with a code review (a Rethink round has none): its open findings are +# re-checked by ID, and what changed since its head is reviewed in full. Anything unusable makes a full round, a +# record without its findings list included: the open findings it had cannot be re-checked, so nothing may be +# skipped. PREVIOUS_OPEN and PREVIOUS_FIXED count only a list that is there: the open findings to re-check, and the +# ones that round fixed, to catch a regression. +FINDINGS_BASE=$(jq -c '[.[] | select(.code_review != false)] | last // null' <<<"$RECORDS") +BASE_ROUND=$(jq -r '.round // empty' <<<"$FINDINGS_BASE") +FINDINGS_KNOWN=$(jq -L "$LIB_DIR" 'include "records"; has_findings_list' <<<"$FINDINGS_BASE") +previous_count() { # + jq -L "$LIB_DIR" "include \"records\"; if has_findings_list then [.findings[] | objects | select($1)] | length + else 0 end" <<<"$FINDINGS_BASE" +} +PREVIOUS_OPEN=$(previous_count '.status == "open" or .status == "new" or .status == "regressed"') +PREVIOUS_FIXED=$(previous_count '.status == "fixed"') +if [[ "$FINDINGS_BASE" == null ]]; then + if [[ "$PREVIOUS_RECORD" == null ]]; then DELTA_REASON="no previous round"; else DELTA_REASON="no earlier code review"; fi + DELTA=$(jq -cn --arg reason "$DELTA_REASON" '{mode: "full", reason: $reason, commands: []}') +elif [[ "$FINDINGS_KNOWN" != true ]]; then + # A later round read back from its Markdown (no marker) shows only what it re-checked: no list either. + DELTA=$(jq -c '{mode: "full", commands: [], reason: (if .source == "backfill" then "the last round has no record of its findings" + else "the last record lost its findings to the size cap" end)}' <<<"$FINDINGS_BASE") +elif [[ "$FULL_ROUND" == "true" ]]; then + DELTA='{"mode":"full","reason":"--full","commands":[]}' +else + DELTA=$(pick_delta "$REVIEW_DIR" "$(jq -r '.head_sha // ""' <<<"$FINDINGS_BASE")" \ + "$(jq -r '.base_sha // ""' <<<"$FINDINGS_BASE")" "$HEAD_SHA" "$BASE_SHA") || + DELTA='{"mode":"full","reason":"could not compare with the last round","commands":[]}' +fi +# delta-files.txt: the files the changes touched, for rule 3. A list git could not give is no proof that the other +# files are untouched: the round is full instead. +if DELTA_FILES=$(changed_files "$REVIEW_DIR" "$DELTA" 2>/dev/null); then + [[ "$(jq -r '.mode' <<<"$DELTA")" == full ]] || printf '%s\n' "$DELTA_FILES" | sed '/^$/d' >"$CONTEXT_DIR/delta-files.txt" +else + DELTA=$(jq -c '.mode = "full" | .reason = "could not list the files the changes touched" | .commands = [] + | del(.from)' <<<"$DELTA") +fi +ROUND_MODE=$(jq -r '.mode' <<<"$DELTA") +if [[ "$ROUND" -gt 1 ]]; then + if [[ "$ROUND_MODE" == full ]]; then + echo " mode: full ($(jq -r '.reason' <<<"$DELTA"))" + else + echo " mode: ${ROUND_MODE} since round ${BASE_ROUND} · ${PREVIOUS_OPEN} earlier findings to re-check," \ + "${PREVIOUS_FIXED} fixed to watch" + fi + echo "" +fi + +# The n-th gh-pr-review review on the PR, without its marker lines. +round_body() { # + # The same tests as fetch_round_records (the header on the first line, a trusted author: trusted_review), so the + # n-th body is round n. An outsider's generated review is no round, and never the previous review. + jq -r -L "$LIB_DIR" --argjson n "$1" --arg me "${ROUNDS_ME:-}" 'include "records"; + [.reviews[] | select(.state != "PENDING" and (.body | is_generated_review) + and ({author_association: .authorAssociation, user: {login: .author.login?}} | trusted_review($me)))] + | sort_by(.submittedAt) | .[$n - 1].body // ""' "$CONTEXT_DIR/discussion.json" | grep -v '^\n%s%s' "$MARKER" "$REVIEW") diff --git a/lib/delta.sh b/lib/delta.sh new file mode 100644 index 0000000..9dff6a4 --- /dev/null +++ b/lib/delta.sh @@ -0,0 +1,207 @@ +#!/usr/bin/env bash +# What changed since the last round: how to show it (pick_delta) and which files it touched (changed_files). +# Functions only. Git runs quietly in the review checkout: stdout carries the JSON or the paths, nothing else. + +# Prints `{mode, reason, commands, prev_head, prev_base, head, base}` as one compact JSON line. Modes: +# incremental the previous head is an ancestor of the head: `git diff --stat` and `git diff` from it. When the +# author merged the base branch in since, the diff starts from the previous head merged onto the new +# base (a tree, in the extra field `from`), so what the base brought is left out. +# rebased the previous head is not an ancestor (rebase or force-push): a `git range-diff` of the two ranges. +# full anything else, with a short human reason: a base merge with conflicts, a base that is not a +# descendant of the previous base (the PR was retargeted), or a previous base that is unknown (a round +# read back from its Markdown has none): what the last round reviewed can't be established, so a +# retarget can't be ruled out. The round then reviews the whole PR. +# The previous head and base come from a marker on the PR, which anyone can edit: they count only as full object IDs +# (40 or 64 hex digits), checked before git sees them. A name (HEAD, main), a short SHA or an option is `full`. +# The four SHA fields are full SHAs when the checkout has the commit, else as given ("" when unknown); changed_files +# reads them. Never fails: every git error ends in `full`. +pick_delta() { # + local repo=$1 prev_head=$2 prev_base=$3 head=$4 base=$5 sha old new reason tree + if [[ -z "$prev_head" ]]; then + delta_json full "no previous round" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + if ! delta_object_id "$prev_head"; then + delta_json full "previous head is not a full commit ID" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + if [[ -z "$prev_base" ]]; then + delta_json full "the previous round's base is unknown" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + if ! delta_object_id "$prev_base"; then + delta_json full "previous base is not a full commit ID" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + if sha=$(delta_resolve "$repo" "$head"); then head=$sha; else + delta_json full "head ${head:0:12} not in the checkout" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + if sha=$(delta_find "$repo" "$prev_head"); then prev_head=$sha; else + delta_json full "previous head ${prev_head:0:12} not found after fetch" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + delta_connect "$repo" "$prev_head" "$head" + + # The PR's base moved backward or sideways (it was retargeted, say from a parent branch to main): commits that were + # base last round are in the PR now, and no diff of the PR's own commits shows them. Only the whole PR does. + if sha=$(delta_find "$repo" "$prev_base"); then prev_base=$sha; else + delta_json full "previous base ${prev_base:0:12} not found after fetch" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + if sha=$(delta_resolve "$repo" "$base"); then base=$sha; else + delta_json full "base ${base:0:12} not in the checkout" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + delta_connect "$repo" "$prev_base" "$base" + if ! git -C "$repo" merge-base --is-ancestor "$prev_base" "$base" >/dev/null 2>&1; then + delta_json full "the PR's base changed" "$prev_head" "$prev_base" "$head" "$base" + return 0 + fi + + if git -C "$repo" merge-base --is-ancestor "$prev_head" "$head" >/dev/null 2>&1; then + # The author merged the base branch in since: a plain diff would show everything the base brought. Compare with + # the previous head merged onto the new base instead, which leaves the author's own changes. + if sha=$(delta_resolve "$repo" "$base") && + ! git -C "$repo" merge-base --is-ancestor "$sha" "$prev_head" >/dev/null 2>&1; then + if tree=$(git -C "$repo" -c core.hooksPath=/dev/null merge-tree --write-tree "$prev_head" "$sha" 2>/dev/null); then + tree=${tree%%$'\n'*} + delta_json incremental "the base branch was merged in: compared with the previous head merged onto the new base" \ + "$prev_head" "$prev_base" "$head" "$sha" "git diff --stat ${tree} ${head}" "git diff ${tree} ${head}" | + jq -c --arg from "$tree" '. + {from: $from}' + return 0 + fi + # A merge with conflicts: the author's resolution lives in the merge commit, which range-diff skips. Only + # the whole PR shows it. + delta_json full "the base branch was merged in with conflicts" "$prev_head" "$prev_base" "$head" "$sha" + return 0 + else + reason="previous head is an ancestor of the head" + [[ "$prev_head" != "$head" ]] || reason="no new commits since the previous round" + delta_json incremental "$reason" "$prev_head" "$prev_base" "$head" "$base" \ + "git diff --stat ${prev_head}..${head}" "git diff ${prev_head}..${head}" + return 0 + fi + fi + + # Rebase or force-push: a plain diff would mix in what the base branch did, so compare the two ranges instead. + old="${prev_base}..${prev_head}" + new="${base}..${head}" + # Try it before handing it to the reviewer: a range it cannot walk (shallow history, odd ranges) fails here. + if git -C "$repo" range-diff --no-color "$old" "$new" >/dev/null 2>&1; then + delta_json rebased "previous head is not an ancestor of the head (rebase or force-push)" \ + "$prev_head" "$prev_base" "$head" "$base" "git range-diff $old $new" + else + reason="range-diff failed on ${prev_base:0:12}..${prev_head:0:12} ${base:0:12}..${head:0:12}" + delta_json full "$reason" "$prev_head" "$prev_base" "$head" "$base" + fi + return 0 +} + +# Prints the paths the delta touched, one per line, sorted and unique: the code that counts as "touched". +# incremental the files changed between the previous head (or `from`) and the head. +# rebased the files whose change in the PR differs between the old and the new version, plus the files the +# PR newly touches or no longer touches. A file the base did not change compares its old and new +# content. A file the base changed between the previous base and the new one is always listed: the +# PR's edit can move inside it in ways no comparison of the two patches can tell from the base's own +# changes, so it counts as touched. +# full nothing. +# Fails when git cannot list or compare the files: an unknown scope is not an empty one. +changed_files() { # + local repo=$1 mode prev_head prev_base head base from path old new names + { + IFS= read -r mode + IFS= read -r prev_head + IFS= read -r prev_base + IFS= read -r head + IFS= read -r base + IFS= read -r from + } < <(jq -r '.mode, .prev_head // "", .prev_base // "", .head // "", .base // "", .from // ""' <<<"$2") + case "$mode" in + incremental) + # from: the previous head merged onto the new base, when the author merged the base in. + names=$(delta_names "$repo" "${from:-$prev_head}" "$head") || return 1 + [[ -z "$names" ]] || LC_ALL=C sort -u <<<"$names" + ;; + rebased) + names=$(delta_names "$repo" "$base" "$head") || return 1 + old=$(delta_names "$repo" "$prev_base" "$prev_head") || return 1 + names=$(printf '%s\n%s\n' "$names" "$old" | LC_ALL=C sort -u) + while IFS= read -r path; do + [[ -n "$path" ]] || continue + old=$(delta_blob "$repo" "$prev_base" "$path") || return 1 + new=$(delta_blob "$repo" "$base" "$path") || return 1 + if [[ "$old" == "$new" ]]; then + # The base did not touch the file: the two versions of the PR's file say it all, where a moved hunk counts. + old=$(delta_blob "$repo" "$prev_head" "$path") || return 1 + new=$(delta_blob "$repo" "$head" "$path") || return 1 + fi + [[ "$old" == "$new" ]] || printf '%s\n' "$path" + done <<<"$names" + ;; + full) ;; + *) return 1 ;; + esac +} + +# ── helpers ────────────────────────────────────────────────────────────────── + +delta_json() { # [command...] + jq -cn --arg mode "$1" --arg reason "$2" --arg prev_head "$3" --arg prev_base "$4" --arg head "$5" \ + --arg base "$6" '{mode: $mode, reason: $reason, commands: $ARGS.positional, + prev_head: $prev_head, prev_base: $prev_base, head: $head, base: $base}' --args "${@:7}" +} + +# A full hexadecimal object ID: 40 digits (SHA-1) or 64 (SHA-256). +delta_object_id() { # + [[ "$1" =~ ^[0-9a-f]{40}$ || "$1" =~ ^[0-9a-f]{64}$ ]] +} + +# Prints the full SHA of a commit the checkout has. Fails when it is missing (or the SHA is empty). +delta_resolve() { # + [[ -n "$2" ]] || return 1 + git -C "$1" rev-parse --verify --quiet --end-of-options "${2}^{commit}" 2>/dev/null +} + +# Like delta_resolve, but a missing commit gets one fetch by SHA first. GitHub serves commits that are still in the +# repository (refs/pull/* keeps many alive), so a commit older than the clone's depth usually comes back. +delta_find() { # + delta_resolve "$1" "$2" && return 0 + local depth=() + # --depth only in a shallow clone: in a full one it would cut the history short. + if delta_shallow "$1"; then depth=(--depth 50); fi + # Same credentials as the clone (GIT_AUTH, when the script set it), no hooks, quiet; errors only mean "missing". + git -C "$1" ${GIT_AUTH[@]+"${GIT_AUTH[@]}"} -c core.hooksPath=/dev/null \ + fetch --quiet --no-tags ${depth[@]+"${depth[@]}"} --end-of-options origin "$2" >/dev/null 2>&1 || true + delta_resolve "$1" "$2" +} + +# In a shallow clone the previous head can be an ancestor of the head yet sit below the head's shallow boundary: +# the histories then share no commit and --is-ancestor says no. Deepen the head's history once, so the check can +# see the link. Connected histories, or a full clone, need nothing. +delta_connect() { # + delta_shallow "$1" || return 0 + git -C "$1" merge-base "$2" "$3" >/dev/null 2>&1 && return 0 + git -C "$1" ${GIT_AUTH[@]+"${GIT_AUTH[@]}"} -c core.hooksPath=/dev/null \ + fetch --quiet --no-tags --deepen 50 --end-of-options origin "$3" >/dev/null 2>&1 || true +} + +# The paths changed between two commits, one per line. Fails when git does. +delta_names() { # + ( + set -o pipefail + git -C "$1" diff --name-only --no-renames -z "$2" "$3" | tr '\0' '\n' + ) +} + +delta_shallow() { # + [[ "$(git -C "$1" rev-parse --is-shallow-repository 2>/dev/null)" == true ]] +} + +# A file's mode, type and blob ID in a commit, or nothing when the commit does not have it. Fails when git does. +delta_blob() { # + ( + set -o pipefail + git --literal-pathspecs -C "$1" ls-tree -z --full-tree "$2" -- "$3" | tr '\0' '\n' | awk -F '\t' 'NR == 1 { print $1 }' + ) +} diff --git a/lib/records.jq b/lib/records.jq index 2861217..a7c594b 100644 --- a/lib/records.jq +++ b/lib/records.jq @@ -52,6 +52,30 @@ def _finding($severity): def _none_line: sub("^\\s*([-*+]|\\d+\\.)\\s+"; "") | ascii_downcase | gsub("[*_()`.\\s]"; "") | . == "none" or . == "nonefound"; +# A later-round item that names an earlier finding: "**F1 · [a.ts:1]** — …" (the ID inside the bold) or +# "**F1** · `a.ts:1` — …". Out: {id, line: the item without its ID, for _finding, after: the text after the bold}, +# or null. +def _id_item: + sub("^([-*+]|\\d+\\.)\\s+"; "") as $rest + | ([$rest | capture("^\\*\\*(?F\\d+)\\s*·\\s*(?.*)$")] | .[0]) as $in + | ([$rest | capture("^\\*\\*(?F\\d+)\\*\\*[\\s·:]*(?.*)$")] | .[0]) as $out + | if $in != null then {id: $in.id, line: ("- **" + $in.r), after: ($in.r | sub("^.*?\\*\\*"; ""))} + elif $out != null then {id: $out.id, line: ("- " + $out.r), after: $out.r} + else null end; + +# An item of the folded "Fixed since the last round" section: {id, status: "fixed"}, or {id, status: "declined", +# reason} for "**F5** — declined: "the quoted reason"" (reason null when nothing follows). Null without an ID. +def _fixed_item: + _id_item as $i + | if $i == null then null + else ([$i.after | capture("^[\\s·:—–-]*declined\\b[\\s:—–-]*(?.*)$"; "i")] | .[0]) as $d + | if $d == null then {id: $i.id, status: "fixed"} + else {id: $i.id, status: "declined", reason: ($d.r | _trim | if . == "" then null else . end)} end + end; + +# The folded section a "
" or "" line opens: fixed, later, or other. +def _folded: ascii_downcase | if test("fixed") then "fixed" elif test("later") then "later" else "other" end; + # The line the writer posts right before the code review (assemble_review): an invisible boundary between the approach # and the code review. A body without a code review (a Rethink) has none. def code_review_boundary: ""; @@ -82,17 +106,25 @@ def code_review_part: # titled "Issues" to the next heading of the same or a higher level; a body without one is read whole. Lines from a # line starting with
), under the same Issues rule; null for every other line. def _lines: def fence: test("^\\s*(```|~~~)"); def opens: test("^ {0,3}\\s*$"; "i")); - reduce (split("\n")[] | sub("\r$"; "")) as $l ({fence: false, details: 0, s: null, i: null, issues: null, has: false, out: []}; + reduce (split("\n")[] | sub("\r$"; "")) as $l ({fence: false, details: 0, fold: null, s: null, i: null, issues: null, + has: false, out: []}; if .fence or ($l | fence) then (if ($l | fence) then .fence |= not else . end) | .out += [if .details > 0 then {l: $l, s: null, i: null} else {l: $l, s, i, code: true} end] elif .details > 0 or ($l | opens) then - .details = ([.details + (if $l | opens then 1 else 0 end) - (if $l | closes then 1 else 0 end), 0] | max) - | .out += [{l: $l, s: null, i: null}] + (if .details == 1 and ($l | opens | not) then + (if $l | test("^\\s*#+)\\s+(?.*)$")) as $h | ($l | _severity) as $sev @@ -102,14 +134,26 @@ def _lines: | .s = $sev | .i = (if .issues != null then $sev else null end) | .out += [{l: $l, s, i, h: true}] else .out += [{l: $l, s, i}] end) - | .has as $has | .out | map({l, s: (if $has then .i else .s end), h: (.h == true), code: (.code == true)}); + | .has as $has + | .out + | map({l, s: (if $has then .i else .s end), h: (.h == true), code: (.code == true), + f: (if $has and (.in | not) then null else .f end)}); # Markdown in, findings out: the top-level "- ", "* ", "+ " and "<n>. " items, bold or plain, in each severity section # (_lines; "- None." is not one). Fenced code is skipped. A location given as a range keeps its last line in line_end -# (the record itself keeps line only: normalize_findings drops it). +# (the record itself keeps line only: normalize_findings drops it). Round 2 and later: an item that starts with an +# earlier ID ("**F1 · …") keeps it, as open; the folded <details> sections are in no severity section: the Fixed one +# is read here, line by line (f), and gives its IDs as fixed (or declined, with the quoted reason); the Later one is +# left out (its items carry no severity). def parse_findings: - [_lines[] | select(.s != null and (.h or .code | not)) | .s as $s | .l - | select(test("^([-*+]|\\d+\\.)\\s+\\S") and (_none_line | not)) | _finding($s)]; + def item: test("^([-*+]|\\d+\\.)\\s+\\S") and (_none_line | not); + [_lines[] + | if .f == "fixed" then .l | select(item) | _fixed_item | select(. != null) + elif .s != null and (.h or .code | not) then + .s as $s | .l | select(item) + | _id_item as $i + | if $i != null then ($i.line | _finding($s)) + {id: $i.id, status: "open"} else _finding($s) end + else empty end]; # The severity sections of a review's Markdown (_lines), in order: {severity, lines (the non-blank lines up to the # next heading), closed (another heading follows)}. Fenced code belongs to the section it is in. @@ -138,9 +182,11 @@ def normalize_findings: | select(.severity == "critical" or .severity == "important" or .severity == "minor")) else [] end; -# The checks below judge the model's findings block (stored_findings) before a record is written from it: -# block_respects_empty and block_covers_markdown. A record posted on GitHub is never judged by its list: it is read -# as it is when its marker is complete (complete_marker), and from its review's Markdown otherwise. +# The checks below judge the model's findings block before a record is written from it: stored_findings($base; +# $later_files), which decides each entry's status with entry_outcome, block_covers_markdown, block_respects_empty and +# findings_block_ok. They are defined below, after the record builder's helpers they need. A record posted on GitHub +# is never judged by its list: it is read as it is when its marker is complete (complete_marker), and from its +# review's Markdown otherwise. # True for an entry that is still open: not fixed or declined. def _open: .status | . != "fixed" and . != "declined"; @@ -148,7 +194,7 @@ def _open: .status | . != "fixed" and . != "declined"; # False when the list ({severity, status, file, line}) has an open entry of a severity the Markdown says it has none of # ($empty: empty_severities): what the reader sees wins. def _respects_empty($empty): - all(.[] | select(_open); .severity as $s | all($empty[]; . != $s)); + all(.[] | select(_open); (.severity | strings | ascii_downcase) as $s | all($empty[]; . != $s)); # True when the list ({severity, status, file, line}) reports at least the blockers the review's Markdown shows # ($parsed: parse_findings of the posted body): as many open Critical entries, and as many open Critical and Important @@ -172,7 +218,7 @@ def _covers_markdown($parsed): | if $i == null then .ok = false else .free |= del(.[$i]) end else . end) | .ok); - def open($sev): [.[] | select(.severity == $sev)] | length; + def open($sev): [.[] | select((.severity | strings | ascii_downcase) == $sev)] | length; def shown($sev): [($parsed // [])[]? | objects | select(.severity == $sev)] | length; [.[] | select(_open)] | [.[] | select(blocking) | location] as $have @@ -181,40 +227,6 @@ def _covers_markdown($parsed): and open("critical") + open("important") >= shown("critical") + shown("important") and ($seen | matched($have)); -# ── Writing: the model's findings block ── - -# The status a findings entry from the model is stored with. This version has no statuses across rounds: every entry -# is stored as a new, open finding, so an entry marked fixed, declined or later is new too. The one place that -# decides it. -def stored_status: "new"; - -# The model's findings as the record will store them: normalized, each entry with its stored_status. The record -# builder stores these, and the block checks (block_respects_empty, block_covers_markdown) judge these, so they never -# disagree about which entries are open. -def stored_findings: - if type == "array" then [.[] | objects | stored_status as $status | ([.] | normalize_findings)[] + {status: $status}] - else [] end; - -# False when the model's block has an open entry, as stored (stored_findings), of a severity the Markdown says it has -# none of ($empty: empty_severities): the round is parsed instead. -def block_respects_empty($empty): stored_findings | _respects_empty($empty); - -# True when the model's findings block can be used as it is: an array whose every entry is an object with a known -# severity, a string title, a file string or null and a line number or null. One bad entry and the whole round falls -# back to the Markdown, so normalize_findings never drops a finding the reader can see. -def findings_block_ok: - type == "array" - and all(.[]; type == "object" - and (.severity | type == "string" and (ascii_downcase | . == "critical" or . == "important" or . == "minor")) - and (.title | type == "string") - and (.file | . == null or type == "string") - and (.line | . == null or type == "number")); - -# True when the model's findings block, as stored (stored_findings: in this version all of it is open), shows every -# blocker the review's Markdown does ($parsed: parse_findings of the posted body; _covers_markdown). Otherwise the -# round is parsed instead. -def block_covers_markdown($parsed): stored_findings | _covers_markdown($parsed); - # ── Reading: a record posted on GitHub ── # True for a marker read as it is: a Rethink, or a code-review marker with the counts marker_line writes at every @@ -227,13 +239,193 @@ def complete_marker: and .open_blocking == .critical + .important); # The highest "<prefix><n>" ID in a record's findings, its later list and its last_ids, or 0. last_ids keeps the -# highest numbers even when the lists are empty (a Rethink) or cut from the marker, so an ID is never given twice. +# highest numbers even when the lists are empty (a Rethink), cut from the marker, or not carried (fixed, declined, +# Later), so an ID is never given twice. def _last_number($prefix): [((.findings // [])[]?, (.later // [])[]?) | objects | .id | strings | capture("^" + $prefix + "(?<n>\\d+)$").n | tonumber] + [(.last_ids // {})[$prefix]? | numbers] | max // 0; +def _severity_ok: . == "critical" or . == "important" or . == "minor"; + +# One entry of the model's array, typed: id and status as given (strings or null), the rest as normalize_findings. +def _entry: + {id: (.id | _str | if . then _trim else null end), status: (.status | if type == "string" then ascii_downcase | _trim + else null end), severity: (.severity | if type == "string" then ascii_downcase | _trim else null end), + file: (.file | _str), line: (.line | _num), title: (.title | _str | _title100), in_delta: (.in_delta == true), + later: (.later == true), reason: (.reason | _str)}; + +# True when a record still has its findings list. A marker cut to fit GitHub's size cap can keep the counts but drop +# the list (findings_dropped): an empty list is a round with no findings, a missing one is unknown. +def has_findings_list: type == "object" and (.findings | type) == "array" and .findings_dropped != true; + +# The finding IDs a record knows, for findings_block_ok: none without its findings list (or without a record). +def known_ids: if has_findings_list then [.findings[] | objects | .id | strings] else [] end; + +# ── Writing: the model's findings block ── + +# The files Later may apply outside of: in an incremental or rebased round ($mode), the files the delta touched +# ($delta_files), when that list is known (an array). Else null: Later does not apply. +def later_files($mode; $delta_files): + if ($mode == "incremental" or $mode == "rebased") and ($delta_files | type) == "array" then $delta_files + else null end; + +# A record's findings by ID, the first one for each; none without its findings list (has_findings_list). +def _known_findings($record): + if $record | has_findings_list then + reduce ($record.findings[] | objects | select(.id | type == "string")) as $f ({}; + if has($f.id) then . else .[$f.id] = $f end) + else {} end; + +# The model's array as typed entries (_entry), the first one for each ID only: the record builder ignores the rest. +def _block_entries: + reduce ((if type == "array" then .[] else empty end) | objects | _entry) as $e ({seen: {}, out: []}; + if $e.id == null then .out += [$e] + elif .seen[$e.id] then . + else .seen[$e.id] = true | .out += [$e] end) + | .out; + +# What a block entry (_entry) is stored as: the one place that decides it, for the record builder (_track) and the +# block checks (stored_findings). $known: _known_findings of the last code review. $later_files: later_files of the +# round. Out: {status, severity, file, line, title} (and unverified: true), or null for a new entry without a known +# severity. An entry with a known ID keeps the model's status when it is fixed, or declined with a reason; open or +# regressed is regressed on an ID last marked fixed (or regressed and still said regressed), else open; anything else +# (declined without a reason, no status, another status) is open and unverified, with the previous severity: it +# cannot downgrade a blocker. What it leaves out comes from the previous finding. Any other entry is new, or later: +# an Important or Minor finding marked later, not in the delta, with a file outside $later_files. A Critical one, one +# marked in the delta, one in a touched file, one without a file, and any when Later does not apply stay new. +def entry_outcome($known; $later_files): + if .id != null and $known[.id] != null then + $known[.id] as $p + | (if .status == "fixed" or .status == "declined" and .reason != null then {status: .status} + elif .status == "open" or .status == "regressed" then + {status: (if $p.status == "fixed" or $p.status == "regressed" and .status == "regressed" + then "regressed" else "open" end)} + else {status: "open", unverified: true} end) as $s + | {status: $s.status, + severity: (if (.severity | _severity_ok) and ($s.unverified | not) then .severity else $p.severity end), + file: (.file // $p.file), line: (.line // $p.line), title: (.title // $p.title)} + + (if $s.unverified then {unverified: true} else {} end) + elif (.severity | _severity_ok) | not then null + elif .later and (.severity == "important" or .severity == "minor") and (.in_delta | not) + and ($later_files | type) == "array" and (.file | type) == "string" + and (.file as $file | $later_files | index([$file | ltrimstr("./")]) == null) then + {status: "later", severity, file, line, title} + else {status: "new", severity, file, line, title} end; + +# stored_findings, each entry the model marked Later but entry_outcome stores as a finding (a Later that does not +# apply: a file the delta touched, a Critical, no file, a full round) with promoted: true. +def _stored($base; $later_files): + _known_findings($base) as $known + | [_block_entries[] | .later as $later | entry_outcome($known; $later_files) + | select(. != null and .status != "later") + | if $later and .status == "new" then . + {promoted: true} else . end]; + +# A model's findings block as the record stores it (entry_outcome), for the block checks (block_covers_markdown, +# block_respects_empty), so they never disagree with the record about which entries are open: its findings, without +# the Later ones (the record keeps those apart). $base: the last code review (null in round 1: every entry is new). +# The findings a round carries (left out of the block, unverified) are not part of it. +def stored_findings($base; $later_files): _stored($base; $later_files) | map(del(.promoted)); + +# True when the model's block ($base, $later_files: as for stored_findings) has an entry it marked Later that the +# record stores as a finding (promoted, _stored). When such a block is rejected, the Markdown, which shows that +# finding in its Later list, gives no blocker count: the round's count is unknown. +def block_promotes($base; $later_files): any(_stored($base; $later_files)[]; .promoted == true); + +# The items of a review's folded Later list (_lines), as the reader sees them: {file, line, line_end}. +def later_items: + [_lines[] | select(.f == "later") | .l | select(test("^([-*+]|\\d+\\.)\\s+\\S") and (_none_line | not)) + | _finding(null) | {file, line, line_end}]; + +# True for a promoted entry the Markdown shows in its Later list ($items: later_items): an item in the same file, at +# the same line (or a range holding it) when both have one. +def _shown_later($items): + .file as $f | .line as $l + | ($f | type) == "string" + and any($items[]; .file == $f and (.line == null or $l == null or .line == $l + or (.line_end != null and $l >= .line and $l <= .line_end))); + +# False when the model's block ($base, $later_files: as for stored_findings) has an open entry, as stored, of a +# severity the Markdown says it has none of ($empty: empty_severities): the round is parsed instead. A promoted entry +# the Markdown shows in its Later list ($later: later_items) is no contradiction: the record keeps it as a finding. +def block_respects_empty($empty; $later; $base; $later_files): + _stored($base; $later_files) | map(select((.promoted == true and _shown_later($later)) | not)) + | _respects_empty($empty); + +# True when the model's block ($base, $later_files: as for stored_findings), as stored, shows every blocker the +# review's Markdown does ($parsed: parse_findings of the posted body; _covers_markdown). Otherwise the round is parsed +# instead. +def block_covers_markdown($parsed; $base; $later_files): stored_findings($base; $later_files) | _covers_markdown($parsed); + +# True when the model's findings block can be used as it is: an array whose every entry is an object with a known +# severity, a string title, a file string or null and a line number or null. One bad entry and the whole round falls +# back to the Markdown, so normalize_findings never drops a finding the reader can see. $ids: the IDs of the last +# code review (known_ids; [] in round 1). Only an entry with one of them may give just its status, the rest coming +# from that record: any other ID is a new finding to the record builder, and needs a severity and a title. +def findings_block_ok($ids): + def severity_ok: type == "string" and (ascii_downcase | . == "critical" or . == "important" or . == "minor"); + type == "array" + and all(.[]; type == "object" + and ((.id | type == "string" and (_trim as $id | $ids | index([$id]) != null)) as $known + | (.severity | severity_ok or ($known and . == null)) + and (.title | type == "string" or ($known and . == null))) + and (.file | . == null or type == "string") + and (.line | . == null or type == "number")); + +# The findings of a code-review round, from the model's array and the previous record's findings. +# Out: {findings, later, last_ids}. Each entry is stored as entry_outcome decides, the first entry for an ID only: +# known IDs keep their ID and first round; new entries get F<n>, or L<n> when Later applies (later_files of $mode +# and $delta_files, the files the delta touched). Previous open, new or regressed findings the reply leaves out are +# carried, unverified. A previous record without its findings list (has_findings_list) knows no ID and carries +# nothing. New IDs start after $floor ({F, L}: the highest numbers in the whole history) and the previous record's. +def _track($findings; $prev; $round; $mode; $floor; $delta_files): + (if $prev | has_findings_list then $prev.findings | map(objects | select(.id | type == "string")) else [] end) + as $old + | _known_findings($prev) as $known + | later_files($mode; $delta_files) as $later_files + | ($findings | _block_entries) as $entries + | (reduce $entries[] as $e ({}; if $e.id != null then .[$e.id] = true else . end)) as $seen + | reduce $entries[] as $e ( + {findings: [], later: [], + f: ([($prev // {}) | _last_number("F"), (($floor // {}).F | numbers)] | max), + l: ([($prev // {}) | _last_number("L"), (($floor // {}).L | numbers)] | max)}; + ($e | entry_outcome($known; $later_files)) as $o + | if $o == null then . + elif $o.status == "later" then + .l += 1 + | .later += [{id: "L\(.l)", severity: $o.severity, file: $o.file, line: $o.line, title: $o.title}] + elif $o.status == "new" then + .f += 1 + | .findings += [{id: "F\(.f)", severity: $o.severity, status: "new", first_round: $round, + in_delta: $e.in_delta, file: $o.file, line: $o.line, title: $o.title}] + else + .findings += [{id: $e.id, severity: $o.severity, status: $o.status, + first_round: ($known[$e.id].first_round // $round), in_delta: $e.in_delta, + file: $o.file, line: $o.line, title: $o.title} + (if $o.unverified then {unverified: true} else {} end)] + end) + | {findings: (.findings + [$old[] | select(.status == "open" or .status == "new" or .status == "regressed") + | select($seen[.id] | not) + | {id, severity, status: "open", first_round, in_delta: false, file, line, title, unverified: true}] + | reduce .[] as $f ({ids: {}, out: []}; if .ids[$f.id] then . else .ids[$f.id] = true | .out += [$f] end) + | .out), + later: .later, last_ids: {F: .f, L: .l}}; + +# A record whose findings miss a file, line or title (a marker leaves out what its review does not show, such as a +# finding the model left out and the round carried) gets them back from the newest record in $history (an array of +# records, oldest first) that has the same ID with that detail. +def recover_details($history): + ([($history // [])[] | objects | (.findings // [])[]? | objects | select(.id | type == "string")] | reverse) + as $earlier + | if (.findings | type) == "array" then + .findings |= map(if type == "object" and (.id | type == "string") then + .id as $id | [$earlier[] | select(.id == $id)] as $same + | .file = (.file // first($same[] | .file | strings) // null) + | .line = (.line // first($same[] | .line | numbers) // null) + | .title = (.title // first($same[] | .title | strings) // null) + else . end) + else . end; + # The ID floor of a history (an array of records): the highest F and L numbers any round used. Older markers have # no last_ids: their findings and later IDs seed it. def id_floor: map(objects) | {F: (map(_last_number("F")) | max // 0), L: (map(_last_number("L")) | max // 0)}; @@ -263,25 +455,38 @@ def reconcile_record($earlier; $position): | .last_ids = {F: ([_last_number("F"), $floor.F] | max), L: ([_last_number("L"), $floor.L] | max)} else . end; -# round.json from the run's facts, the findings (block or parser) and the previous record (or null). New findings -# are numbered after $meta.id_floor ({F, L}, from id_floor over the whole history) and the previous record. A code -# review read from a Markdown with no severity section ($meta.no_sections: true) does not say how many blockers it -# has: its counts are null, so its blocking is unknown, never 0. +# round.json from the run's facts, the findings (block or parser) and the previous record (or null). Round 1 +# findings carry no id or status: all are new. From round 2, see _track. New findings are numbered after +# $meta.id_floor ({F, L}, from id_floor over the whole history) and the previous record. $meta.delta_files: the paths +# the delta touched (changed_files), for Later. A code review whose blocker count is unknown ($meta.unknown_counts: +# true; one read from a Markdown with no severity section, say) gets null counts, so its blocking is unknown, never 0. def build_record($meta; $findings; $prev): ($meta.code_review != false) as $code_review | ([($meta.id_floor // {}).F | numbers] + [($prev // {}) | _last_number("F")] | max) as $last | ([($meta.id_floor // {}).L | numbers] + [($prev // {}) | _last_number("L")] | max) as $last_later | ($meta.round | _num) as $round - | (if $code_review then $findings | stored_findings else [] end) as $found - | ($found | to_entries | map({id: "F\(.key + $last + 1)", severity: .value.severity, status: .value.status, - first_round: $round, in_delta: false, file: .value.file, line: .value.line, title: .value.title})) as $items - | def count($s): $items | map(select(.severity == $s)) | length; - { + | (if $code_review then _track($findings; $prev; $round; $meta.mode; {F: $last, L: $last_later}; $meta.delta_files) + else {findings: [], later: [], last_ids: {F: $last, L: $last_later}} end) as $t + | $t.findings as $items + | def open: select(.status == "open" or .status == "new" or .status == "regressed"); + def count($s): [$items[] | open | select(.severity == $s)] | length; + def status($s): [$items[] | select(.status == $s)] | length; + (if $code_review and $meta.unknown_counts != true then + {open_blocking: (count("critical") + count("important")), critical: count("critical"), + important: count("important"), minor: count("minor"), new: status("new"), fixed: status("fixed"), + declined: status("declined"), regressed: status("regressed"), later: ($t.later | length), + unverified: ([$items[] | select(.unverified == true)] | length)} + else + {open_blocking: null, critical: null, important: null, minor: null, new: null, + fixed: null, declined: null, regressed: null, later: null, unverified: null} + end) as $counts + | { schema: 1, source: $meta.source, pr: ($meta.pr | if type == "object" then {host, owner, repo, number: (.number | _num)} else null end), round: $round, mode: $meta.mode, + mode_reason: ($meta.mode_reason | _str), reviewer: $meta.reviewer, model: $meta.model, posted_at: $meta.posted_at, @@ -290,27 +495,72 @@ def build_record($meta; $findings; $prev): previous_head_sha: ($meta.previous_head_sha // ($prev // {}).head_sha), approach: $meta.approach, ready: $meta.ready, + ready_overridden: ($code_review and ($meta.ready == "yes" or $meta.ready == "yes-with-fixes") + and $counts.open_blocking > 0), decision: $meta.decision, preview: ($meta.preview == true), code_review: $code_review, findings: $items, - later: [], - last_ids: {F: ($last + ($items | length)), L: $last_later}, - counts: (if $code_review and $meta.no_sections != true then - {open_blocking: (count("critical") + count("important")), critical: count("critical"), - important: count("important"), minor: count("minor"), new: ($items | length), - fixed: 0, declined: 0, regressed: 0} - else - {open_blocking: null, critical: null, important: null, minor: null, new: null, - fixed: null, declined: null, regressed: null} - end) + later: $t.later, + last_ids: $t.last_ids, + counts: $counts }; +# The progress line that opens a round 2 or later body, for a person. $prev: the previous code-review record, or +# null (no line). $decision: loop_decide over the history with this record, so its label is this round's. +# ### Round 3 · since round 2 +# 4 fixed · 2 still open · 3 new (1 in the new commits) · open blocking: 5 (was 6) · loop: converging +def progress_line($prev; $decision): + . as $r + | if $prev == null then empty + else "### Round \($r.round) · since round \($prev.round)", + if $r.code_review == false then "code review skipped: the approach needs a rethink" + else ($r.findings // []) as $f + | def n($s): [$f[] | select(.status == $s and (.unverified != true))] | length; + def part($n; $text): if $n > 0 then ["\($n) \($text)"] else [] end; + ([$f[] | select(.status == "new" and .in_delta == true)] | length) as $delta + | ([$f[] | select(.unverified == true)] | length) as $unverified + | (part(n("fixed"); "fixed") + part(n("open"); "still open") + part(n("regressed"); "regressed") + + (if n("new") > 0 then ["\(n("new")) new" + (if $delta > 0 then " (\($delta) in the new commits)" + else "" end)] else [] end) + + part(n("declined"); "declined") + part(($r.later // []) | length; "for later") + + part($unverified; "not re-checked") + # "was" only when the previous findings were there to re-check: else the two counts measure different things. + # An unknown count (no severity section: null) says so, never 0, so the reader never reads it as 0. + + ["open blocking: " + ($r.counts.open_blocking | if type == "number" then tostring else "unknown" end) + + (if ($prev.counts.open_blocking? | type) == "number" and ($prev | has_findings_list) + then " (was \($prev.counts.open_blocking))" else "" end)] + + (if ($decision.label? | type) == "string" + then ["loop: " + (if $decision.label == "nit-loop" then "nit loop" else $decision.label end)] + else [] end) + + (if $r.mode == "full" then ["full review" + (if ($r.mode_reason | type) == "string" + then " (\($r.mode_reason))" else "" end)] else [] end)) + | join(" · ") + end + end; + +# True when a review body is a round 2 or later review: a progress line ("### Round 3 · since round 2") near the top, +# or a folded Fixed since / Later section. Its Markdown leaves out what it did not re-check, so it is no findings list. +def later_round_body: + (split("\n") | map(sub("\r$"; ""))) as $lines + | ($lines[0:8] | any(test("^###\\s+Round\\s+\\d+\\s+·\\s+since\\s+round\\s+\\d+\\s*$"; "i"))) + or ($lines | any(test("<summary>\\s*(fixed since|later\\b)"; "i"))); + +# The open blocking count of a round 2 or later body's progress line ("· open blocking: 3 (was 4) ·"), or null. It +# counts every open blocker, also the carried ones its Markdown leaves out. +def progress_blocking: + if later_round_body then [split("\n")[0:8][] | capture("open blocking: (?<n>\\d+)").n | tonumber] | first // null + else null end; + # A record rebuilt from an old review (GitHub REST review object). The caller reads the verdict lines. Its findings # and sections come from the code-review part (code_review_part), the text the writer read: a code review whose part -# has no severity section (_sections) gets null counts (build_record). +# has no severity section (_sections) gets null counts (build_record). A later-round body that lost its marker +# (later_round_body, read on the whole body: its progress line comes before the code review) gives no findings list +# (findings_dropped, so the next round is full), the open blocking count of its progress line, and last_ids that +# cover the IDs it shows and reserve one L ID per item of its folded Later list. def backfill_record($review; $prev; $round; $pr; $approach; $ready; $code_review): ($review.body // "") as $body + | ($code_review and ($body | later_round_body)) as $later_round | build_record({ source: "backfill", pr: $pr, @@ -325,8 +575,27 @@ def backfill_record($review; $prev; $round; $pr; $approach; $ready; $code_review | .[$review.state | strings] // null), posted_at: $review.submitted_at, code_review: $code_review, - no_sections: ($body | code_review_part | _sections | length == 0) - }; (if $code_review then $body | code_review_part | parse_findings else [] end); $prev); + unknown_counts: ($body | code_review_part | _sections | length == 0) + }; (if $code_review then $body | code_review_part | parse_findings else [] end); + # An old review says nothing about which earlier findings were fixed: the previous record only numbers the IDs, + # so a backfilled round counts what it found, never carries the round before. + (if $prev == null then null + else {round: $prev.round, head_sha: $prev.head_sha, + last_ids: {F: ($prev | _last_number("F")), L: ($prev | _last_number("L"))}} end)) + | if $later_round | not then . + else ([$body | code_review_part | parse_findings[] | .id | strings | capture("^F(?<n>\\d+)$").n | tonumber] | max // 0) + as $shown + | ($body | progress_blocking) as $blocking + # Each item of its folded Later list reserves an L ID, as each finding it shows takes an F ID. + | ([$body | code_review_part | _lines[] | select(.f == "later") | .l + | select(test("^([-*+]|\\d+\\.)\\s+\\S") and (_none_line | not))] | length) as $later + | del(.findings, .later) | .findings_dropped = true + | .last_ids.F = ([.last_ids.F, $shown] | max) + | .last_ids.L += $later + | if $blocking == null then . + else .counts.open_blocking = $blocking + | .ready_overridden = ((.ready == "yes" or .ready == "yes-with-fixes") and $blocking > 0) end + end; # The first line of every body gh-pr-review posts. def generated_header: "<!-- gh-pr-review generated -->"; @@ -338,6 +607,11 @@ def _visible: gsub("[*`]"; "") | gsub("\\s+"; " ") | _trim; # A string as a regex that matches it literally. def _re_literal: gsub("(?<c>[\\\\^$.|?*+()\\[\\]{}/-])"; "\\\(.c)"); +# True for a marker that says its round's blocker count is unknown: counts holds open_blocking, and it is null. The +# reader honours it: the round read back has null counts, whatever its Markdown shows (fetch_round_records). A round +# whose record could not be built posts such a marker (minimal: no findings list either). +def marker_counts_unknown: (.counts | type) == "object" and (.counts | has("open_blocking")) and .counts.open_blocking == null; + # The marker line for a record, posted right below the generated header and above $body, the exact review text. # One HTML comment: every "--" in the JSON is written "-\u002d". The marker never publishes text the review does not # show. A file stays only when $body shows that exact path, as a whole path: the whole content of a code span, less @@ -348,7 +622,8 @@ def _re_literal: gsub("(?<c>[\\\\^$.|?*+()\\[\\]{}/-])"; "\\\(.c)"); # The whole body (header, newline, marker, newline, review) must fit in 60,000 characters, under GitHub's 65,536: it # drops titles, then file, line, first_round and in_delta, then later, then findings (findings_dropped: true; counts # and last_ids stay). When even that does not fit: a minimal marker, {schema, round, findings_dropped: true} and -# last_ids if it fits, so a later round knows the baseline is missing. Nothing when even that does not fit. +# last_ids if it fits, so a later round knows the baseline is missing, with {counts: {open_blocking: null}} for a code +# review whose blocker count is unknown (marker_counts_unknown). Nothing when even that does not fit. def marker_line($body): ($body | _visible) as $seen | ($body | [scan("`([^`\n]+)`") | .[0] | sub(":\\d+.*$"; "") | _trim]) as $spans @@ -373,7 +648,8 @@ def marker_line($body): .later[]?.file, .later[]?.line, .later[]?.first_round, .later[]?.in_delta) end | if fits then . else del(.later) end | if fits then . else del(.findings) | .findings_dropped = true end - | if fits then . else {schema: 1, round, findings_dropped: true} + (if .last_ids then {last_ids} else {} end) end + | if fits then . else {schema: 1, round, findings_dropped: true} + (if .last_ids then {last_ids} else {} end) + + (if marker_counts_unknown and .code_review != false then {counts: {open_blocking: null}} else {} end) end | if fits then . else del(.last_ids) end | if fits then line else empty end; diff --git a/lib/records.sh b/lib/records.sh index d721459..999fdf7 100644 --- a/lib/records.sh +++ b/lib/records.sh @@ -50,12 +50,20 @@ normalize_ready() { # <text> esac } -# round.json from the run's facts (meta JSON), the findings JSON and the previous record JSON (or null). +# round.json from the run's facts (meta JSON), the findings JSON and the previous record JSON (or null). The +# previous record is the last one with a code review. From round 2 the findings carry IDs and statuses. build_record() { # <meta-json> <findings-json> <previous-record-json-or-null> jq -L "${LIB_DIR:?}" -n --argjson meta "$1" --argjson findings "${2:-[]}" --argjson prev "${3:-null}" \ 'include "records"; build_record($meta; $findings; $prev)' } +# The two-line progress line that opens a round 2 or later body. Nothing without a previous record. The decision +# is loop_decide_json over the history including this record. +progress_line() { # <record-json> <previous-record-json-or-null> <decision-json> + jq -r -L "${LIB_DIR:?}" -n --argjson record "$1" --argjson prev "${2:-null}" --argjson decision "${3:-null}" \ + 'include "records"; $record | progress_line($prev; $decision)' +} + # The hidden marker line for a record file, for the review posted below it: a file, or the text itself. Prints # nothing when even the minimal marker would push the body past the size cap (see marker_line in records.jq). marker_line() { # <record-file> <review-file | review-text> diff --git a/lib/rounds.sh b/lib/rounds.sh index ae65b81..561510f 100644 --- a/lib/rounds.sh +++ b/lib/rounds.sh @@ -54,7 +54,10 @@ fetch_round_records() { # <host> <owner> <repo> <N> [<me>] [<ignored-out>] # (findings_dropped), and the IDs the marker held kept as the ID floor. A marker with last_ids that # claims its own position wrote that floor itself: it is the round's (never below the history's), and # counts.new is the marker's. Otherwise every finding the Markdown shows takes a new ID - # (backfill_record), and reconcile_record numbers a round two runs claimed after the floor. + # (backfill_record), and reconcile_record numbers a round two runs claimed after the floor. The L floor + # is the marker's and the backfill's, which reserves an L ID per item of a later round's Later list. + # A marker that says its blocker count is unknown (marker_counts_unknown) gets null counts: its + # Markdown may show fewer blockers than the round had. record=$(printf '%s\n%s\n%s\n' "$records" "$record" "$marker" | jq -cs -L "${LIB_DIR:?}" --argjson round "$round" 'include "records"; .[0] as $earlier | .[2] as $m @@ -63,7 +66,9 @@ fetch_round_records() { # <host> <owner> <repo> <N> [<me>] [<ignored-out>] | {F: ($from | map(_last_number("F")) | max), L: (.[1:] | map(_last_number("L")) | max)} as $ids | .[1] + ($m | del(.source, .findings, .later, .counts)) + {findings_dropped: true, last_ids: $ids} | del(.findings) - | if $own then .counts.new = (($m.counts.new? | numbers) // null) else . end') || return 1 + | if $own then .counts.new = (($m.counts.new? | numbers) // null) else . end + | if $m | marker_counts_unknown then .counts |= map_values(null) | .ready_overridden = false + else . end') || return 1 fi fi facts=$(jq -c '({posted_at: .submitted_at, head_sha: .commit_id, reviewer: .user.login} diff --git a/tests/delta.sh b/tests/delta.sh new file mode 100644 index 0000000..5df888e --- /dev/null +++ b/tests/delta.sh @@ -0,0 +1,460 @@ +#!/usr/bin/env bash +# Picks how to show what changed since the last round (pick_delta, changed_files), with real git on local repos. +# A bare repo plays GitHub: `https://h/o/r.git` points at it through GIT_CONFIG_COUNT, so nothing uses the network. +# HOME, XDG_CONFIG_HOME, the global and the system git config are isolated from the user's. +# Conditions are single-quoted on purpose: expect() evals them after each case sets out (and files). +# SC2034: GIT_AUTH is read by the sourced pick_delta. SC2329: has and patch_text run inside expect's eval. +# SC2030/SC2031: the cases that break the remote URL do it in a subshell on purpose. +# shellcheck disable=SC2016,SC2030,SC2031,SC2034,SC2329 +set -euo pipefail +root=$(cd "$(dirname "$0")/.." && pwd) +tmp=$(mktemp -d) +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap 'rm -rf "$tmp"; [[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT +fail=0 + +unset GIT_DIR GIT_WORK_TREE GIT_INDEX_FILE GIT_OBJECT_DIRECTORY GIT_ALTERNATE_OBJECT_DIRECTORIES GIT_CONFIG \ + GIT_CONFIG_PARAMETERS GIT_CEILING_DIRECTORIES GIT_AUTH +mkdir -p "$tmp/home" +export HOME="$tmp/home" XDG_CONFIG_HOME="$tmp/home/.config" GIT_CONFIG_NOSYSTEM=1 GIT_CONFIG_GLOBAL="$tmp/home/.gitconfig" +export GIT_AUTHOR_NAME=Test GIT_AUTHOR_EMAIL=test@example.com GIT_COMMITTER_NAME=Test GIT_COMMITTER_EMAIL=test@example.com +export GIT_TERMINAL_PROMPT=0 +remote="$tmp/remote.git" +export GIT_CONFIG_COUNT=1 GIT_CONFIG_KEY_0="url.file://$remote.insteadOf" GIT_CONFIG_VALUE_0="https://h/o/r.git" +# Points every https://h/ URL at a folder that does not exist: a fetch through it fails, locally. +broken_key="url.file://$tmp/nowhere/.insteadOf" broken_value="https://h/" + +# shellcheck source=lib/delta.sh +source "$root/lib/delta.sh" + +expect() { # name condition + if eval "$2"; then echo "ok $1"; else + echo "FAIL $1 ($2)" + printf '%s\n' "$out" | sed 's/^/ | /' + fail=1 + fi +} + +world() { # a fresh "GitHub" remote and the author's repo, on main + rm -rf "$remote" "$tmp/src" + git init --quiet --bare -b main "$remote" + # GitHub serves a commit by SHA as long as it still has the object, even after a force-push. + git -C "$remote" config uploadpack.allowAnySHA1InWant true + git init --quiet -b main "$tmp/src" + git -C "$tmp/src" remote add origin "$remote" +} + +src() { git -C "$tmp/src" "$@"; } + +commit() { # <message> <file=content>...: writes the files and commits them + local message=$1 pair + shift + for pair in "$@"; do printf '%s\n' "${pair#*=}" >"$tmp/src/${pair%%=*}"; done + src add -A + src commit --quiet -m "$message" +} + +publish() { # pushes main and the PR branch, as GitHub keeps refs/pull/1/head + src push --quiet --force origin main feature feature:refs/pull/1/head +} + +checkout() { # <depth>: the review checkout, as gh-pr-review clones it. Prints its path. + local dir + dir=$(mktemp -d "$tmp/checkout-XXXXX")/repo + git clone --depth "$1" --quiet https://h/o/r.git "$dir" + git -C "$dir" fetch origin pull/1/head:pr-branch --depth "$1" --quiet + git -C "$dir" fetch origin main:refs/remotes/origin/main --depth "$1" --quiet + printf '%s\n' "$dir" +} + +has() { git -C "$1" cat-file -e "${2}^{commit}" 2>/dev/null; } # <repo> <sha> +# One file's patch between two commits, without its index line and its hunk line numbers. +patch_text() { git -C "$1" diff --no-color "$2" "$3" -- "$4" | sed -e '/^index /d' -e 's/^@@ -[0-9,]* +[0-9,]* @@/@@ @@/'; } # <repo> <from> <to> <path> + +ten=$(printf 'line %s\n' 1 2 3 4 5 6 7 8 9 10) +ten_changed=${ten/line 8/LINE 8} + +# ── sourcing ───────────────────────────────────────────────────────────────── +out=$(bash -c 'before=$(set -o; shopt); source "$1"; [[ $(set -o; shopt) == "$before" ]] && echo same' _ \ + "$root/lib/delta.sh") +expect "source: defines functions only (no output, no options)" '[[ $out == same ]]' + +# ── incremental: a plain new commit ────────────────────────────────────────── +world +commit m1 "a.txt=$ten" +src checkout --quiet -b feature +commit f1 b.txt=one +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +commit f2 b.txt=two e.txt=new +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "incremental: stdout is one JSON line" '[[ $(wc -l <<<"$out") -eq 1 ]] && jq -e . <<<"$out" >/dev/null' +expect "incremental: mode" '[[ $(jq -r .mode <<<"$out") == incremental ]]' +expect "incremental: reason" '[[ $(jq -r .reason <<<"$out") == "previous head is an ancestor of the head" ]]' +expect "incremental: diff --stat and diff, full SHAs" \ + '[[ $(jq -c .commands <<<"$out") == "[\"git diff --stat $prev_head..$head\",\"git diff $prev_head..$head\"]" ]]' +expect "incremental: SHA fields" \ + '[[ $(jq -r "[.prev_head, .prev_base, .head, .base] | join(\" \")" <<<"$out") == "$prev_head $prev_base $head $base" ]]' +files=$(changed_files "$repo" "$out") +expect "incremental: changed_files" '[[ $files == "b.txt"$'"'\n'"'"e.txt" ]]' +out=$(pick_delta "$repo" "$head" "$base" "$head" "$base") +expect "incremental: same head says so" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "incremental,no new commits since the previous round" ]]' + +# ── incremental: the author merged the base branch in ──────────────────────── +world +commit m1 "a.txt=$ten" +src checkout --quiet -b feature +commit f1 b.txt=one +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +src checkout --quiet main +commit m2 c.txt=from-main "a.txt=$ten_changed" +src checkout --quiet feature +src merge --quiet --no-edit main +commit f2 b.txt=two +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +from=$(jq -r '.from // ""' <<<"$out") +expect "base merged in: incremental, from the previous head merged onto the new base" \ + '[[ $(jq -r .mode <<<"$out") == incremental && -n $from && $(jq -r .reason <<<"$out") == "the base branch was merged in"* ]]' +expect "base merged in: the diff starts from that tree" \ + '[[ $(jq -c .commands <<<"$out") == "[\"git diff --stat $from $head\",\"git diff $from $head\"]" ]]' +expect "base merged in: the diff holds the author's change only" \ + '[[ $(git -C "$repo" diff --name-only "$from" "$head") == b.txt ]]' +files=$(changed_files "$repo" "$out") +expect "base merged in: changed_files leaves out what the base brought" '[[ $files == b.txt ]]' + +world +commit m1 "a.txt=$ten" +src checkout --quiet -b feature +commit f1 "a.txt=$ten_changed" +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +src checkout --quiet main +commit m2 "a.txt=${ten/line 8/main 8}" +src checkout --quiet feature +src merge --quiet --no-edit main >/dev/null 2>&1 || true +commit f2 "a.txt=${ten/line 8/both 8}" +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "base merged in with conflicts: full, and it says why" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,the base branch was merged in with conflicts" && $(jq -c .commands <<<"$out") == "[]" ]]' +# What the reviewer gets: the whole PR (git diff base..head), where the resolution is. A range-diff of the two +# versions skips the merge commit, and would have shown only f1, unchanged. +expect "base merged in with conflicts: the whole PR shows the resolution" \ + 'git -C "$repo" diff "$base" "$head" | grep -qx "+both 8"' +expect "base merged in with conflicts: a range-diff would not" \ + '! git -C "$repo" range-diff "$prev_base..$prev_head" "$base..$head" | grep -q "both 8"' +files=$(changed_files "$repo" "$out") +expect "base merged in with conflicts: no delta files" '[[ -z $files ]]' + +# ── full: a stacked PR retargeted from its parent branch to main ───────────── +# Last round the PR targeted parent: its base was parent's tip. Retargeted to main, parent's commit is in the PR now, +# though the previous head is still an ancestor of the head: an incremental diff would show child.txt only. +world +commit m1 "a.txt=$ten" +src checkout --quiet -b parent +commit p1 parent.txt=from-parent +src checkout --quiet -b feature +commit c1 child.txt=one +src push --quiet origin parent +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse parent) +commit c2 child.txt=two +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +expect "retargeted: setup, the PR now holds parent.txt too" \ + '[[ $(git -C "$repo" diff --name-only "$base" "$head" | paste -sd, -) == "child.txt,parent.txt" ]]' +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "retargeted: full, and it says why" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,the PR'"'"'s base changed" && $(jq -c .commands <<<"$out") == "[]" ]]' +# Retargeted back to parent: the base moved forward from main's m1 to parent's p1, which is fine. +out=$(pick_delta "$repo" "$prev_head" "$base" "$head" "$prev_base") +expect "retargeted: a base that moved forward stays incremental" '[[ $(jq -r .mode <<<"$out") == incremental ]]' +# The same retarget after a round with no known base (a review read back from its Markdown): nothing shows what +# that round reviewed, so the whole PR is in scope, parent.txt included, not an incremental diff of child.txt. +out=$(pick_delta "$repo" "$prev_head" "" "$head" "$base") +expect "previous base unknown: full, and it says why" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,the previous round'"'"'s base is unknown" && $(jq -c .commands <<<"$out") == "[]" ]]' +files=$(changed_files "$repo" "$out") +expect "previous base unknown: no delta files, the whole PR is reviewed" '[[ -z $files ]]' + +# ── rebased: onto a moved base, with a changed patch ───────────────────────── +world +commit m1 "a.txt=$ten" c.txt=c1 +src checkout --quiet -b feature +commit f1 "a.txt=$ten_changed" +commit f2 b.txt=old g.txt=dropped-later +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +# The base moves: lines above the PR's change in a.txt (new hunk line numbers, same patch), and c.txt. c.txt is not +# the PR's; a.txt is listed all the same: a file the base changed too counts as touched. +src checkout --quiet main +commit m2 "a.txt=top"$'\n'"$ten" c.txt=c2 +# The author redoes the PR on the new base: same a.txt change, b.txt changed, d.txt new, g.txt gone. +src checkout --quiet -B feature main +commit f1 "a.txt=top"$'\n'"$ten_changed" +commit f2 b.txt=new d.txt=added +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +expect "rebased: setup, the old head is not in the checkout" '! has "$repo" "$prev_head"' +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "rebased: stdout is one JSON line" '[[ $(wc -l <<<"$out") -eq 1 ]] && jq -e . <<<"$out" >/dev/null' +expect "rebased: mode" '[[ $(jq -r .mode <<<"$out") == rebased ]]' +expect "rebased: range-diff of the two ranges" \ + '[[ $(jq -c .commands <<<"$out") == "[\"git range-diff $prev_base..$prev_head $base..$head\"]" ]]' +expect "rebased: the old head was fetched" 'has "$repo" "$prev_head"' +files=$(changed_files "$repo" "$out") +expect "rebased: changed_files, the changed, new and dropped files, and a.txt, which the base changed too" \ + '[[ $files == "a.txt"$'"'\n'"'"b.txt"$'"'\n'"'"d.txt"$'"'\n'"'"g.txt" ]]' +out=$(pick_delta "$repo" "$prev_head" "" "$head" "$base") +expect "rebased: no previous base is full" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,the previous round'"'"'s base is unknown" ]]' +# A git that fails on range-diff only: the round falls back to full and says why. +real_git=$(command -v git) +mkdir -p "$tmp/bin" +cat >"$tmp/bin/git" <<S +#!/usr/bin/env bash +for a in "\$@"; do [[ "\$a" == range-diff ]] && exit 1; done +exec "$real_git" "\$@" +S +chmod +x "$tmp/bin/git" +out=$( + PATH="$tmp/bin:$PATH" + pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base" +) +expect "rebased: range-diff failing falls back to full" \ + '[[ $(jq -r .mode <<<"$out") == full && $(jq -r .reason <<<"$out") == "range-diff failed on "* ]]' +files=$(changed_files "$repo" "$out") +expect "full: changed_files is empty" '[[ -z $files ]]' + +# ── rebased: a binary file ─────────────────────────────────────────────────── +# git prints "Binary files … differ" whatever the content: the blob IDs tell a changed binary from the same one. +bin() { printf 'GIF89a\0%s\0' "$2" >"$tmp/src/$1"; } # <file> <content>: a file git sees as binary +world +commit m1 "a.txt=$ten" +src checkout --quiet -b feature +bin logo.gif v1 +bin icon.gif same +commit f1 "b.txt=one" +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +src checkout --quiet main +commit m2 c.txt=from-main +src checkout --quiet -B feature main +bin logo.gif v2 +bin icon.gif same +commit f1 "b.txt=one" +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "binary: setup, rebased and git sees binary files" \ + '[[ $(jq -r .mode <<<"$out") == rebased ]] && git -C "$repo" diff "$base" "$head" -- logo.gif | grep -q "^Binary files "' +files=$(changed_files "$repo" "$out") +expect "binary: changed_files lists the changed binary, not the same one" '[[ $files == logo.gif ]]' + +# ── rebased: an edit moved between two identical blocks ────────────────────── +# Without line numbers the two patches are the same text, though the change moved. The base never touched the file, +# so the old and new versions of the file decide. +block=$(printf ' x = 1\n y = 2\n z = 3\n w = 4\n v = 5') +blocks() { # <block with the edit: 2 or 3>: four copies of the block, z = 3 changed in one of them + local i + for i in 1 2 3 4; do + if [[ $i == "$1" ]]; then printf '%s\n' "${block/z = 3/z = 4}"; else printf '%s\n' "$block"; fi + done +} +world +commit m1 "x.txt=$(blocks 0)" +src checkout --quiet -b feature +commit f1 "x.txt=$(blocks 2)" +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +src checkout --quiet main +commit m2 c.txt=from-main +src checkout --quiet -B feature main +commit f1 "x.txt=$(blocks 3)" +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "moved edit: setup, rebased, and the patches differ only in their line numbers" \ + '[[ $(jq -r .mode <<<"$out") == rebased && "$(patch_text "$repo" "$prev_base" "$prev_head" x.txt)" == "$(patch_text "$repo" "$base" "$head" x.txt)" ]]' +files=$(changed_files "$repo" "$out") +expect "moved edit: changed_files lists the file" '[[ $files == x.txt ]]' + +# The same moved edit, with an unrelated line the base added at the end of x.txt: the base changed the file, so it is +# listed whatever its two patches look like. +world +commit m1 "x.txt=$(blocks 0)" +src checkout --quiet -b feature +commit f1 "x.txt=$(blocks 2)" +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +src checkout --quiet main +commit m2 "x.txt=$(blocks 0)"$'\n'"upstream line" +src checkout --quiet -B feature main +commit f1 "x.txt=$(blocks 3)"$'\n'"upstream line" +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "moved edit, the base changed the file: setup, rebased, the patches differ only in their line numbers" \ + '[[ $(jq -r .mode <<<"$out") == rebased && "$(patch_text "$repo" "$prev_base" "$prev_head" x.txt)" == "$(patch_text "$repo" "$base" "$head" x.txt)" ]]' +files=$(changed_files "$repo" "$out") +expect "moved edit, the base changed the file: changed_files lists the file" '[[ $files == x.txt ]]' + +# ── changed_files: git failing is an error, not an empty list ──────────────── +cat >"$tmp/bin/git" <<S +#!/usr/bin/env bash +for a in "\$@"; do [[ "\$a" == diff ]] && exit 1; done +exec "$real_git" "\$@" +S +for case_ in "rebased:$out" "incremental:$(pick_delta "$repo" "$head" "$base" "$head" "$base")"; do + mode=${case_%%:*} + rc=0 + # Without pipefail, as a caller may run it: the error must not depend on the caller's options. + files=$( + set +o pipefail + PATH="$tmp/bin:$PATH" + changed_files "$repo" "${case_#*:}" + ) || rc=$? + expect "$mode: a failing git diff fails changed_files" '[[ $rc != 0 && -z $files ]]' +done +rc=0 +changed_files "$repo" '{"mode":"strange"}' >/dev/null || rc=$? +expect "changed_files: an unknown mode fails" '[[ $rc != 0 ]]' + +# ── full: force-push to unrelated history, the old head gone from the remote ─ +world +commit m1 "a.txt=$ten" +src checkout --quiet -b feature +commit f1 b.txt=old +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +src checkout --quiet -B feature main +commit g1 z.txt=other +publish +git -C "$remote" reflog expire --expire=now --all +git -C "$remote" gc --quiet --prune=now +out='' +expect "force-push: setup, the remote lost the old head" '! has "$remote" "$prev_head"' +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "force-push: full, with the reason" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,previous head ${prev_head:0:12} not found after fetch" ]]' +expect "force-push: no commands" '[[ $(jq -c .commands <<<"$out") == "[]" ]]' +files=$(changed_files "$repo" "$out") +expect "force-push: changed_files is empty" '[[ -z $files ]]' + +# ── full: no previous round ────────────────────────────────────────────────── +out=$(pick_delta "$repo" "" "" "$head" "$base") +expect "no previous round: full" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,no previous round" ]]' +expect "no previous round: no commands" '[[ $(jq -c .commands <<<"$out") == "[]" ]]' + +# ── previous head and base from a marker: full commit IDs only ───────────── +# Anyone can edit a marker: a name would resolve against this checkout, an option would reach git fetch. git logs +# every call here, so the checks below also prove no git command saw the value. +world +commit m1 "a.txt=$ten" +src checkout --quiet -b feature +commit f1 b.txt=one +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +commit f2 b.txt=two +publish +repo=$(checkout 50) +head=$(git -C "$repo" rev-parse pr-branch) +base=$(git -C "$repo" merge-base pr-branch origin/main) +mkdir -p "$tmp/logbin" +cat >"$tmp/logbin/git" <<S +#!/usr/bin/env bash +printf '%s\n' "\$*" >>"$tmp/git.log" +exec "$real_git" "\$@" +S +chmod +x "$tmp/logbin/git" +for bad in HEAD main --upload-pack=x "${prev_head:0:7}" "${prev_head}x" "$(tr a-f A-F <<<"$prev_head")"; do + : >"$tmp/git.log" + out=$( + PATH="$tmp/logbin:$PATH" + pick_delta "$repo" "$bad" "$prev_base" "$head" "$base" + ) + expect "marker head '$bad': full, before any git call" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,previous head is not a full commit ID" && ! -s $tmp/git.log ]]' + : >"$tmp/git.log" + out=$( + PATH="$tmp/logbin:$PATH" + pick_delta "$repo" "$prev_head" "$bad" "$head" "$base" + ) + expect "marker base '$bad': full, before any git call" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,previous base is not a full commit ID" && ! -s $tmp/git.log ]]' +done +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "marker: full commit IDs are accepted" '[[ $(jq -r .mode <<<"$out") == incremental ]]' +sha256=$(printf 'ab%.0s' {1..32}) +out=$(pick_delta "$repo" "$sha256" "$prev_base" "$head" "$base") +expect "marker: a 64-digit ID passes the check (then is not found)" \ + '[[ $(jq -r .reason <<<"$out") == "previous head ${sha256:0:12} not found after fetch" ]]' + +# ── shallow: the previous head is older than the depth but still on the remote ─ +world +commit m1 "a.txt=$ten" +src checkout --quiet -b feature +commit f1 s1.txt=1 +commit f2 s2.txt=2 +publish +prev_head=$(src rev-parse HEAD) prev_base=$(src rev-parse main) +for i in 3 4 5 6 7 8; do commit "f$i" "s$i.txt=$i"; done +publish +head=$(src rev-parse feature) +# The merge-base sits below the shallow boundary too, so the base is given, as an earlier run would have found it. +base=$prev_base +repo=$(checkout 3) +out='' +expect "shallow: setup, the previous head is not in the checkout" '! has "$repo" "$prev_head"' +out=$(pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base") +expect "shallow: incremental after the fetch (GIT_AUTH unset)" \ + '[[ $(jq -r .mode <<<"$out") == incremental && $(jq -r ".commands[1]" <<<"$out") == "git diff $prev_head..$head" ]]' +files=$(changed_files "$repo" "$out") +expect "shallow: changed_files" '[[ $(paste -sd, - <<<"$files") == "s3.txt,s4.txt,s5.txt,s6.txt,s7.txt,s8.txt" ]]' +# Only GIT_AUTH knows where the remote is: the fetch works only if pick_delta passes it to git. +repo=$(checkout 3) +out=$( + export GIT_CONFIG_KEY_0="$broken_key" GIT_CONFIG_VALUE_0="$broken_value" + GIT_AUTH=(-c credential.helper= -c "url.file://$remote.insteadOf=https://h/o/r.git") + pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base" +) +expect "shallow: incremental with GIT_AUTH set (it reaches git)" '[[ $(jq -r .mode <<<"$out") == incremental ]]' +# Same, without GIT_AUTH: the fetch fails, and the round is full. +repo=$(checkout 3) +out=$( + export GIT_CONFIG_KEY_0="$broken_key" GIT_CONFIG_VALUE_0="$broken_value" + pick_delta "$repo" "$prev_head" "$prev_base" "$head" "$base" +) +expect "shallow: the fetch failing is full, quietly" \ + '[[ $(jq -r .mode,.reason <<<"$out" | paste -sd, -) == "full,previous head ${prev_head:0:12} not found after fetch" ]]' + +finished=true +exit "$fail" diff --git a/tests/fixtures/reviews/later-round.md b/tests/fixtures/reviews/later-round.md new file mode 100644 index 0000000..51e13b4 --- /dev/null +++ b/tests/fixtures/reviews/later-round.md @@ -0,0 +1,49 @@ +### Round 3 · since round 2 +1 fixed · 2 still open · 1 regressed · 1 new · 1 declined · 1 for later · open blocking: 4 (was 3) + +### Strengths + +- **`src/api.ts:120`** — The handler now rejects unsigned payloads early. + +### Issues + +The findings that are open now: earlier findings still open or regressed, then new ones, by severity. + +#### 🚨 Critical (Must Fix Before Merge) + +- **F1 · `a.ts:1`** — Still trusts the payload when the header is empty. + - The fix checks the header's presence, not its value. + +#### ⚠️ Important (Should Fix) + +- **F5 · [e.ts:5]** — Retries are still unbounded on timeouts. +- **F2** · `b.ts:2` — The pool leak is back in the error path. +- **[d.ts:2]** — The new retry loop has no upper bound. + +#### 💡 Minor (Nice to Have) + +*(none found)* + +<details><summary>Fixed since the last round (2)</summary> + +- **F4** — The helper now closes the pool. +- **F3** — declined: "Kept on purpose until the v2 API ships" (@bob) + +</details> + +<details> +<summary>Later (1)</summary> + +- **[f.ts:6]** — The old helper is slow; it can wait for the cache rework. + +</details> + +### Recommendations + +- Share one retry helper. + +### Assessment + +**Ready to merge?** No + +**Reasoning:** Two blockers remain. diff --git a/tests/flow.sh b/tests/flow.sh index 2217a7f..440c450 100644 --- a/tests/flow.sh +++ b/tests/flow.sh @@ -5,6 +5,9 @@ # shellcheck disable=SC2016,SC2034,SC2329 # SC2329: helpers such as no_session run inside expect's eval set -euo pipefail root=$(cd "$(dirname "$0")/.." && pwd) +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap '[[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 setup() { # approach-output code-review-output [discussion-exit-code] [failing-pass: owner|code] @@ -17,6 +20,7 @@ setup() { # approach-output code-review-output [discussion-exit-code] [failing-p echo '{"comments":[],"reviews":[]}' >"$stub/discussion.json" echo '[]' >"$stub/rest-reviews.json" echo '[]' >"$stub/rest-comments.json" + rm -f "$stub/git.base" "$stub/git.missing" "$stub/git.rebased" "$stub/git.retargeted" "$stub/git.diff-fails" "$stub/git.far-base" "$stub/git.deepened" # The PR head the Nth "pr view" returns: line N of heads, or its last line. The clone checks out line 1. echo head1 >"$stub/heads" cat >"$stub/bin/gh" <<S @@ -59,10 +63,38 @@ case "\$*" in echo '{"title":"T","body":"B","headRefName":"h","baseRefName":"main","author":{"login":"bob"},"additions":1,"deletions":0,"changedFiles":1,"headRefOid":"'"\$head"'"}' ;; esac S - cat >"$stub/bin/git" <<S + # git: HEAD is the first line of heads (the PR head the clone checks out) and the merge-base bbbb (or the SHA in + # git.base). Any other SHA resolves to itself, unless listed in git.missing. The previous head is an ancestor of the head unless git.rebased exists, and the previous base one of the base unless + # git.retargeted exists. git.diff-fails makes `git diff` fail. + # git.far-base: no merge-base until a `fetch --deepen` (logged in git.deepened); "never": not even then. + cat >"$stub/bin/git" <<'S' #!/usr/bin/env bash -for a in "\$@"; do [[ "\$a" == clone ]] && mkdir -p "\${@: -1}"; done -case "\$*" in *rev-parse*) head -1 "$stub/heads" ;; *merge-base*) echo bbbb ;; esac +s=$(cd "$(dirname "$0")/.." && pwd) +H=$(head -1 "$s/heads" 2>/dev/null || echo aaaa) B=$(cat "$s/git.base" 2>/dev/null || echo bbbb) +for a in "$@"; do [[ "$a" == clone ]] && mkdir -p "${@: -1}"; done +case "$*" in +*"rev-parse --is-shallow-repository"*) echo false ;; +*"rev-parse --verify"*) + sha=${*: -1} + sha=${sha%^\{commit\}} + if grep -qx -- "$sha" "$s/git.missing" 2>/dev/null; then exit 1; fi + [[ $sha == HEAD ]] && sha=$H + echo "$sha" + ;; +*rev-parse*) echo "$H" ;; +*"fetch "*--deepen*) printf '%s\n' "$*" >>"$s/git.deepened" ;; +*"merge-base --is-ancestor"*" $H") [[ ! -f "$s/git.rebased" ]] ;; +*"merge-base --is-ancestor"*" $B") [[ ! -f "$s/git.retargeted" ]] ;; +*"merge-base --is-ancestor"*) true ;; +*merge-base*) + if [[ -f "$s/git.far-base" ]] && { [[ ! -f "$s/git.deepened" ]] || grep -qx never "$s/git.far-base"; }; then exit 1; fi + echo "$B" + ;; +*"diff --name-only"*) + [[ ! -f "$s/git.diff-fails" ]] || exit 1 + printf 'd.js\0' + ;; +esac S cat >"$stub/bin/pi" <<S #!/usr/bin/env bash @@ -238,6 +270,16 @@ setup 'unused' 'unused' run --instructions ' ' expect "blank instructions: fails before any model call" '[[ $rc != 0 && $calls == 0 ]]' +setup $'**Approach:** Sound' $'**Ready to merge?** Yes' +touch "$stub/git.far-base" +run +expect "merge-base past the depth: deepens the PR and the base once, then reviews" '[[ $rc == 0 && $calls == 2 && $(grep -c -- "--deepen 200" "$stub/git.deepened") == 2 ]] && grep -q "pull/1/head" "$stub/git.deepened" && grep -q "main:refs/remotes/origin/main" "$stub/git.deepened"' +expect "merge-base past the depth: the deepen uses the credential helper" '[[ $(grep -c "credential.helper=!gh auth git-credential" "$stub/git.deepened") == 2 ]]' +setup $'**Approach:** Sound' $'**Ready to merge?** Yes' +echo never >"$stub/git.far-base" +run +expect "merge-base still missing after the deepen: refuses, no review" '[[ $rc == 1 && $calls == 0 && -z $flag ]] && grep -q "Refusing to review a partial diff" "$stub/out.log"' + # ── round records block=$'```json findings\n[{"severity":"important","file":"a.js","line":3,"title":"thing breaks"}]\n```' setup $'**Approach:** Sound' $'### Issues\n#### ⚠️ Important (Should Fix)\n- **`a.js:3` — thing breaks.**\n\n**Ready to merge?** Yes with fixes\n\n'"$block" @@ -287,6 +329,11 @@ run expect "records: an unusable block entry falls back to parsing the whole round" \ '[[ $rc == 0 && $(jq -r ".source, .counts.critical, .findings[0].file" <<<"$record" | paste -sd, -) == "parsed,1,b.js" ]]' +setup $'**Approach:** Sound' $'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n- **`n.go:4` — Nil dereference.**\n\n**Ready to merge?** No\n\n```json findings\n[{"id":"F999","status":"open","title":"Nil dereference"}]\n```' +run +expect "records: an invented ID without a severity falls back to the Markdown" \ + '[[ $rc == 0 && $(jq -r ".source, .counts.critical, .findings[0].id, .findings[0].file" <<<"$record" | paste -sd, -) == "parsed,1,F1,n.go" ]]' + setup $'**Approach:** Sound' $'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n- **`b.js:9` — data loss.**\n\n**Ready to merge?** Yes with fixes\n\n```json findings\n[]\n```' run expect "records: an empty block next to a Critical bullet falls back to the Markdown" \ @@ -420,7 +467,7 @@ run_no_y expect "loop stop: no terminal, no prompt, exit 3" '[[ $rc == 3 && $calls == 0 ]] && ! grep -q "anyway? \[y/N\]" "$stub/out.log"' run --force-round expect "loop stop: --force-round runs the round" '[[ $rc == 0 && $calls == 2 && $(jq -r ".forced, .round, .loop.decision" <<<"$record" | paste -sd, -) == "true,5,stop" ]]' -expect "loop stop: a forced round shows the loop line" '[[ $body == *"**Loop:** Churning"* ]]' +expect "loop stop: a forced round shows the progress line, not the loop line" '[[ $body == *"### Round 5 · since round 4"*"loop: ready"* && $body != *"**Loop:**"* && $body != *"**Next:**"* ]]' comment_by dave User >"$stub/rest-comments.json" run expect "loop stop: a comment by another person lifts it" '[[ $rc == 0 && $calls == 2 && $(jq -r ".loop.decision" <<<"$record") == warn ]]' @@ -452,7 +499,7 @@ setup $'**Approach:** Sound' "$clean" rounds_with 9 12 8 >"$stub/rest-reviews.json" run expect "loop warn: the round runs" '[[ $rc == 0 && $calls == 2 ]]' -expect "loop warn: the loop line comes right after the markers" '[[ $(sed -n 3p <<<"$body") == "**Loop:** Churning · blocking 9, 12, 8 · "* ]]' +expect "loop warn: the progress line comes right after the markers" '[[ $(sed -n 3p <<<"$body") == "### Round 4 · since round 3" && $body != *"**Loop:**"* ]]' expect "loop warn: the decision still comes from Ready to merge" '[[ $flag == --approve ]]' run --check expect "--check: warn exits 0, no model call" '[[ $rc == 0 && $calls == 0 ]]' @@ -600,6 +647,230 @@ run --check expect "--check: no rounds yet exits 0" '[[ $rc == 0 ]]' run --json expect "--json without --check: fails" '[[ $rc == 1 && $calls == 0 ]]' + +# ── round 2 and later +# Markers carry full commit IDs: anything else makes a full round. +H1=$(printf 'c1%.0s' {1..20}) H2=$(printf 'c2%.0s' {1..20}) B1=$(printf 'b1%.0s' {1..20}) +add_round() { # <record-json> <markdown> -> one more posted round, in the REST reviews and in the discussion + local n + n=$(($(jq length "$stub/rest-reviews.json") + 1)) + jq -c --arg rec "$1" --arg md "$2" --argjson n "$n" '. + [{user: {login: "me", type: "User"}, state: "COMMENTED", + commit_id: ($rec | fromjson | .head_sha), submitted_at: "2026-01-0\($n)T00:00:00Z", + body: ("<!-- gh-pr-review generated -->\n<!-- gh-pr-review:round " + $rec + " -->\n" + $md)}]' \ + "$stub/rest-reviews.json" >"$stub/r.tmp" && mv "$stub/r.tmp" "$stub/rest-reviews.json" + jq -c --arg rec "$1" --arg md "$2" --argjson n "$n" '.reviews += [{author: {login: "me"}, state: "COMMENTED", + submittedAt: "2026-01-0\($n)T00:00:00Z", + body: ("<!-- gh-pr-review generated -->\n<!-- gh-pr-review:round " + $rec + " -->\n" + $md)}]' \ + "$stub/discussion.json" >"$stub/d.tmp" && mv "$stub/d.tmp" "$stub/discussion.json" +} +session_file() { cat "$stub"/work/pr-review-sessions/pr-review-*/context/"$1" 2>/dev/null; } +two_rounds() { # round 1 (F1, F2) and round 2 (F1 open, F2 fixed, F3 new), both Sound + add_round '{"schema":1,"source":"model","round":1,"head_sha":"'"$H1"'","base_sha":"'"$B1"'","approach":"sound","ready":"no","code_review":true,"findings":[{"id":"F1","severity":"important","status":"new","first_round":1,"file":"a.js","line":3,"title":"thing breaks"},{"id":"F2","severity":"minor","status":"new","first_round":1,"file":"b.js","line":1,"title":"nit"}],"counts":{"open_blocking":1,"critical":0,"important":1,"minor":1}}' \ + $'### Approach\n\n**Approach:** Sound\n\n### Issues\n- round one' + add_round '{"schema":1,"source":"model","round":2,"head_sha":"'"$H2"'","base_sha":"'"$B1"'","approach":"sound","ready":"no","code_review":true,"findings":[{"id":"F1","severity":"important","status":"open","first_round":1,"file":"a.js","line":3,"title":"thing breaks"},{"id":"F2","severity":"minor","status":"fixed","first_round":1,"file":"b.js","line":1,"title":"nit"},{"id":"F3","severity":"critical","status":"new","first_round":2,"file":"c.js","line":9,"title":"data loss"}],"counts":{"open_blocking":2,"critical":1,"important":1,"minor":0}}' \ + $'### Approach\n\n**What it does:** x\n\n**Approach:** Sound\n\n### Issues\n- **F3 · `c.js:9`** — data loss' +} +round3=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n- **F3 · `c.js:9`** — still loses data.\n' +round3+=$'#### ⚠️ Important (Should Fix)\n- **`d.js:2`** — retry loop has no bound.\n\n**Ready to merge?** No\n\n' +round3+=$'```json findings\n[{"id":"F1","status":"fixed","severity":"important","file":"a.js","line":3,"title":"thing breaks","in_delta":false,"later":false},\n' +round3+=$' {"id":"F3","status":"open","severity":"critical","file":"c.js","line":9,"title":"data loss","in_delta":false,"later":false},\n' +round3+=$' {"id":null,"status":"new","severity":"important","file":"d.js","line":2,"title":"retry loop has no bound","in_delta":true,"later":false},\n' +round3+=$' {"id":null,"status":"new","severity":"minor","file":"e.js","line":5,"title":"old helper is slow","in_delta":false,"later":true}]\n```' + +setup $'**Approach:** Sound' $'**Ready to merge?** Yes' +run +expect "round 1: no Previous round section" '[[ $rc == 0 ]] && ! grep -q "## Previous round" "$stub/code-prompt.txt"' +expect "round 1: no previous verdict for the owner" '! grep -q "Your previous verdict" "$stub/owner-prompt.txt"' +expect "round 1: a full round, no progress line" '[[ $(jq -r ".mode, .mode_reason" <<<"$record" | paste -sd, -) == "full,no previous round" && $body != *"### Round "* ]]' + +setup $'### Approach\n\n**Approach:** Sound' "$round3" +two_rounds +run +expect "round 3: incremental since round 2" '[[ $rc == 0 && $(jq -r ".round, .mode, .previous_head_sha" <<<"$record" | paste -sd, -) == "3,incremental,$H2" ]] && grep -q "mode: incremental since round 2" "$stub/out.log"' +expect "round 3: open IDs are mandatory, fixed ones only if back" 'grep -q "Every open ID listed is mandatory" "$stub/code-prompt.txt" && grep -q "Those are not mandatory: report one only if the problem is back" "$stub/code-prompt.txt"' +expect "round 3: the code prompt has the three rules" 'grep -q "## Previous round" "$stub/code-prompt.txt" && grep -q "Check every earlier finding" "$stub/code-prompt.txt" && grep -q "Review what changed since round 2 in full" "$stub/code-prompt.txt" && grep -q "Outside what changed, raise only Critical" "$stub/code-prompt.txt"' +expect "round 3: the diff since the previous head" 'grep -qF "git diff --stat $H2..head1" "$stub/code-prompt.txt" && grep -qF "git diff $H2..head1" "$stub/code-prompt.txt"' +expect "round 3: the later-round output format" 'grep -q "Fixed since the last round" "$stub/code-prompt.txt" && grep -q "\"id\": \"F3\" or null" "$stub/code-prompt.txt"' +expect "round 3: the findings block asks for a decline's reason" 'grep -qF "\"reason\": \"<the quoted reason>\" or null" "$stub/code-prompt.txt" && grep -qF "Quote it, in \`\"reason\"\`" "$stub/code-prompt.txt"' +expect "round 3: previous-findings.md lists the open findings first" '[[ $(session_file previous-findings.md | sed -n 1,2p) == "F1 · important · a.js:3 · thing breaks"$'"'"'\n'"'"'"F3 · critical · c.js:9 · data loss" ]]' +expect "round 3: then the fixed ones, to catch a regression" '[[ $(session_file previous-findings.md | sed -n 4,5p) == "Fixed in round 2 (report one only if the problem is back, as open):"$'"'"'\n'"'"'"F2 · minor · b.js:1 · nit" ]]' +expect "round 3: previous-review.md is round 2 without markers" '[[ $(session_file previous-review.md) == *"F3 · \`c.js:9\`"* && $(session_file previous-review.md) != *"<!--"* ]]' +expect "round 3: delta-files.txt" '[[ $(session_file delta-files.txt) == d.js ]]' +expect "round 3: statuses and IDs" '[[ $(jq -r "([.findings[] | .id + \":\" + .status] | join(\" \")), (.later | map(.id) | join(\" \")), .counts.open_blocking" <<<"$record" | paste -sd, -) == "F1:fixed F3:open F4:new,L1,2" ]]' +expect "round 3: a churning loop adds the next move" '[[ $body == *"loop: churning"*"**Next:** "* ]]' +expect "round 3: the progress line opens the body" '[[ $(sed -n 3p <<<"$body") == "### Round 3 · since round 2" && $(sed -n 4p <<<"$body") == "1 fixed · 1 still open · 1 new (1 in the new commits) · 1 for later · open blocking: 2 (was 2)"* ]]' +expect "round 3: the owner starts from its previous verdict" 'grep -q "## Your previous verdict (round 2)" "$stub/owner-prompt.txt" && grep -q "Unchanged since round 2" "$stub/owner-prompt.txt" && grep -qF "git diff --stat $H2..head1" "$stub/owner-prompt.txt"' +expect "round 3: previous-approach.md is the Approach section" '[[ $(session_file previous-approach.md) == "### Approach"*"**Approach:** Sound" ]]' +expect "round 3: the record keeps the label of this round" '[[ $(jq -r ".loop.label" <<<"$record") == churning ]]' + +# Later only outside the files the delta touched: d.js is in delta-files.txt, whatever in_delta says. +setup $'### Approach\n\n**Approach:** Sound' "${round3//\"e.js\"/\"d.js\"}" +two_rounds +run +expect "round 3: a Later entry in a touched file stays a finding" \ + '[[ $(session_file delta-files.txt) == d.js && $(jq -r "(.later | length), ([.findings[] | select(.file == \"d.js\") | .severity] | join(\" \"))" <<<"$record" | paste -sd, -) == "0,important minor" ]]' + +# Round 3 with no Critical in the Markdown: the block is judged as the record stores it (entry_outcome), so an entry +# the record keeps open is open for the checks, and one it stores as fixed, declined or Later is not. F3 is the open +# Critical of round 2; a finding the block leaves out is carried, unverified, and takes no part in the checks. +no_critical() { # <findings block entry, or nothing> -> round 3 with "*(none found)*" under Critical, F1 still open + local md=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n\n*(none found)*\n\n' + md+=$'#### ⚠️ Important (Should Fix)\n- **F1 · `a.js:3`** — thing breaks.\n\n**Ready to merge?** No\n\n' + md+=$'```json findings\n[{"id":"F1","status":"open"}'"${1:+,$1}"$']\n```' + setup $'### Approach\n\n**Approach:** Sound' "$md" + two_rounds + run +} +no_critical '{"id":"F3","status":"declined","reason":"by design"}' +expect "no Critical shown: F3 declined with a reason is not open: the block is used" \ + '[[ $rc == 0 && $(jq -c "[.source, (.findings[] | select(.id == \"F3\") | .status), .counts.critical]" <<<"$record") == "[\"model\",\"declined\",0]" ]]' +no_critical '{"id":"F3","status":"declined"}' +expect "no Critical shown: F3 declined without a reason is stored open: the record is parsed" \ + '[[ $rc == 0 && $(jq -r ".source" <<<"$record") == parsed ]] && grep -q "does not match the review" "$stub/out.log"' +no_critical '{"id":null,"status":"new","severity":"critical","file":"z.js","line":1,"title":"x","in_delta":false,"later":true}' +expect "no Critical shown: a Later Critical is not honoured, so open: the record is parsed" \ + '[[ $rc == 0 && $(jq -r ".source" <<<"$record") == parsed ]]' +no_critical '{"id":"F3","status":"fixed"}' +expect "no Critical shown: F3 fixed: the block is used" \ + '[[ $rc == 0 && $(jq -c "[.source, (.findings[] | select(.id == \"F3\") | .status), .counts.critical]" <<<"$record") == "[\"model\",\"fixed\",0]" ]]' +no_critical +expect "no Critical shown: F3 left out is carried, unverified, and not checked: the block is used" \ + '[[ $rc == 0 && $(jq -c "[.source, (.findings[] | select(.id == \"F3\") | [.status, .unverified])]" <<<"$record") == "[\"model\",[\"open\",true]]" ]]' + +setup $'### Approach\n\nUnchanged since round 2: it still fits.\n\n**Approach:** Sound' "$round3" +two_rounds +run +expect "owner short form: posted as is, and its verdict parses" '[[ $rc == 0 && $body == *"Unchanged since round 2: it still fits."* && $(jq -r ".approach" <<<"$record") == sound && $calls == 2 ]]' + +setup $'### Approach\n\nUnchanged since round 2.\n\n**Approach:** Rethink' "$round3" +two_rounds +run +expect "owner: a changed verdict line wins over Unchanged" '[[ $(jq -r ".approach, .code_review" <<<"$record" | paste -sd, -) == "rethink,false" && $calls == 1 ]]' + +# No findings block in round 3: the Markdown fallback reads the later-round format. +md3=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n- **F3 · `c.js:9`** — still loses data.\n' +md3+=$'#### ⚠️ Important (Should Fix)\n- **[d.js:2]** — retry loop has no bound.\n#### 💡 Minor (Nice to Have)\n*(none found)*\n\n' +md3+=$'<details><summary>Fixed since the last round (1)</summary>\n\n- **F1** — the check is in.\n\n</details>\n\n' +md3+=$'<details><summary>Later (1)</summary>\n\n- **[e.js:5]** — old helper is slow.\n\n</details>\n\n**Ready to merge?** No' +setup $'**Approach:** Sound' "$md3" +two_rounds +run +expect "round 3 without a block: IDs from the Markdown, nothing counted twice" '[[ $(jq -r ".source, ([.findings[] | .id + \":\" + .status] | join(\" \")), .counts.open_blocking, .counts.unverified, .counts.minor" <<<"$record" | paste -sd, -) == "parsed,F3:open F4:new F1:fixed,2,0,0" ]]' + +setup $'**Approach:** Sound' "$round3" +two_rounds +touch "$stub/git.rebased" +run +expect "rebased: a range-diff of the two versions" '[[ $(jq -r ".mode" <<<"$record") == rebased ]] && grep -qF "git range-diff $B1..$H2 bbbb..head1" "$stub/code-prompt.txt" && grep -q "The author rebased" "$stub/code-prompt.txt"' + +setup $'**Approach:** Sound' "$round3" +two_rounds +touch "$stub/git.retargeted" +run +expect "retargeted: a full round that says why" '[[ $(jq -r ".mode, .mode_reason" <<<"$record" | paste -sd, -) == "full,the PR'"'"'s base changed" ]] && ! grep -q "Outside what changed" "$stub/code-prompt.txt"' + +setup $'**Approach:** Sound' "$round3" +two_rounds +echo "$H2" >"$stub/git.missing" +run +expect "previous head gone: a full round that says why" '[[ $(jq -r ".mode" <<<"$record") == full ]] && grep -q "mode: full (previous head ${H2:0:12} not found after fetch)" "$stub/out.log"' +expect "previous head gone: rule 1 only" 'grep -q "Check every earlier finding" "$stub/code-prompt.txt" && ! grep -q "Outside what changed" "$stub/code-prompt.txt" && grep -q "This round is a full review" "$stub/code-prompt.txt"' +expect "previous head gone: the progress line says full review" '[[ $(sed -n 4p <<<"$body") == *"full review (previous head ${H2:0:12} not found after fetch)" ]]' + +setup $'**Approach:** Sound' "$round3" +two_rounds +touch "$stub/git.diff-fails" +run +expect "file list fails: a full round that says why" '[[ $(jq -r ".mode, .mode_reason" <<<"$record" | paste -sd, -) == "full,could not list the files the changes touched" ]] && grep -q "mode: full (could not list the files" "$stub/out.log"' +expect "file list fails: no delta-files.txt, rule 1 only" '[[ -z $(session_file delta-files.txt) ]] && grep -q "Check every earlier finding" "$stub/code-prompt.txt" && ! grep -q "Outside what changed" "$stub/code-prompt.txt" && ! grep -q "delta-files.txt" "$stub/code-prompt.txt"' + +setup $'**Approach:** Sound' "$round3" +two_rounds +run --full +expect "--full: a full round with rule 1 only" '[[ $(jq -r ".mode, .mode_reason" <<<"$record" | paste -sd, -) == "full,--full" ]] && grep -q "Check every earlier finding" "$stub/code-prompt.txt" && ! grep -q "Outside what changed" "$stub/code-prompt.txt"' + +setup $'**Approach:** Sound' $'**Ready to merge?** Yes\n\n```json findings\n[{"id":"F3","status":"open","severity":"critical","file":"c.js","line":9,"title":"data loss","in_delta":false,"later":false},{"id":"F1","status":"fixed","severity":"important","file":"a.js","line":3,"title":"thing breaks","in_delta":false,"later":false}]\n```' +two_rounds +run +expect "ready override: Yes with a blocking finding open posts as comment" '[[ $flag == --comment && $(jq -r ".ready, .ready_overridden" <<<"$record" | paste -sd, -) == "yes,true" ]] && grep -q "blocking findings are still open" "$stub/out.log"' + +setup $'**Approach:** Sound' $'**Ready to merge?** Yes\n\n```json findings\n[{"id":"F3","status":"declined","severity":"critical","in_delta":false,"later":false},{"id":"F1","status":"fixed","in_delta":false,"later":false},{"id":null,"status":"new","severity":"critical","file":"x.js","line":1,"title":"leaks a token","in_delta":false,"later":true}]\n```' +two_rounds +run +expect "model output cannot drop a blocker: no reason, no decline; a Critical is never Later" '[[ $flag == --comment && $(jq -r "([.findings[] | .id + \":\" + .status + (if .unverified then \"?\" else \"\" end)] | join(\" \")), (.later | length), .counts.open_blocking" <<<"$record" | paste -sd, -) == "F3:open? F1:fixed F4:new,0,2" ]]' + +setup $'**Approach:** Sound' $'**Ready to merge?** Yes\n\n```json findings\n[]\n```' +two_rounds +run +expect "unverified: a forgotten finding is carried as open, not re-checked" '[[ $(jq -r "[.findings[] | select(.unverified) | .id] | join(\" \")" <<<"$record") == "F1 F3" && $body == *"2 not re-checked"* && $flag == --comment ]]' + +# Round 2 fixed the last open finding: round 3 still watches it, and a comeback keeps its ID. +fixed_only() { + add_round '{"schema":1,"source":"model","round":1,"head_sha":"'"$H1"'","base_sha":"'"$B1"'","approach":"sound","ready":"no","code_review":true,"findings":[{"id":"F1","severity":"important","status":"new","first_round":1,"file":"a.js","line":3,"title":"thing breaks"}],"counts":{"open_blocking":1,"critical":0,"important":1,"minor":0}}' $'### Issues\n- round one' + add_round '{"schema":1,"source":"model","round":2,"head_sha":"'"$H2"'","base_sha":"'"$B1"'","approach":"sound","ready":"yes","code_review":true,"findings":[{"id":"F1","severity":"important","status":"fixed","first_round":1,"file":"a.js","line":3,"title":"thing breaks"}],"counts":{"open_blocking":0,"critical":0,"important":0,"minor":0}}' $'### Issues\n- round two, all fixed' +} +setup $'**Approach:** Sound' $'**Ready to merge?** No\n\n```json findings\n[{"id":"F1","status":"open","severity":"important","file":"a.js","line":3,"title":"thing breaks again","in_delta":true,"later":false}]\n```' +fixed_only +run +expect "only fixed before: previous-findings.md lists them" '[[ $(session_file previous-findings.md) == "Fixed in round 2 (report one only if the problem is back, as open):"$'"'"'\n'"'"'"F1 · important · a.js:3 · thing breaks" ]] && [[ $(session_file previous-review.md) == *"round two, all fixed"* ]]' +expect "only fixed before: rule 1 asks whether one came back, nothing mandatory" 'grep -q "Check whether an earlier finding came back" "$stub/code-prompt.txt" && ! grep -q -e "Check every earlier finding" -e "is mandatory" "$stub/code-prompt.txt" && grep -q "Fixed since the last round" "$stub/code-prompt.txt"' +expect "only fixed before: the comeback keeps its ID, regressed and blocking" '[[ $(jq -r "(.findings | map(.id + \":\" + .status) | join(\" \")), .counts.open_blocking" <<<"$record" | paste -sd, -) == "F1:regressed,1" && $body == *"1 regressed"* ]]' +run --full +expect "only fixed before, --full: still watches them" '[[ $(jq -r .mode <<<"$record") == full ]] && grep -q "Check whether an earlier finding came back" "$stub/code-prompt.txt"' + +# Round 3 shows an Important for d.js in its Later list only, and its block marks it Later; d.js is in the delta, so +# the record keeps it as a finding. The empty Important section does not reject the block: the Later list shows it. +# The record has 1 blocker, and the Yes posts as comment. A Later item that does not show the entry (another file or +# line) rejects the block: the Markdown leaves the Later list out of its count, so the count is unknown: comment too. +later_promoted() { # <the Later item's location> + local md=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n*(none found)*\n#### ⚠️ Important (Should Fix)\n*(none found)*\n' + md+=$'#### 💡 Minor (Nice to Have)\n*(none found)*\n\n<details><summary>Later (1)</summary>\n\n' + md+="- **\`$1\`** — retry loop has no bound."$'\n\n</details>\n\n**Ready to merge?** Yes\n\n```json findings\n' + md+=$'[{"id":null,"status":"new","severity":"important","file":"d.js","line":2,"title":"retry loop has no bound","in_delta":false,"later":true}]\n```' + setup $'**Approach:** Sound' "$md" + fixed_only + run +} +later_promoted d.js:2 +expect "a Later entry in a touched file, shown in the Later list only: the block is used, 1 blocker, comment" \ + '[[ $rc == 0 && $flag == --comment && $(session_file delta-files.txt) == d.js && + $(jq -c "[.source, .counts.open_blocking, .counts.important, (.later | length), (.findings[] | select(.file == \"d.js\") | .status)]" <<<"$record") == "[\"model\",1,1,0,\"new\"]" ]]' +for elsewhere in e.js:2 d.js:40; do + later_promoted "$elsewhere" + expect "a Later entry in a touched file, the Later list shows $elsewhere: parsed, unknown count, comment" \ + '[[ $rc == 0 && $flag == --comment && $(jq -c "[.source, .counts.open_blocking]" <<<"$record") == "[\"parsed\",null]" ]] && + grep -q "blockers are unknown: posting as comment" "$stub/out.log"' +done + +# A marker cut to fit the size cap: the counts survive, the findings do not. Nothing can be re-checked by ID, so the +# round reviews the whole PR, as a first code review. +for capped in '"findings_dropped":true' '"findings_dropped":false'; do + setup $'**Approach:** Sound' $'**Ready to merge?** Yes\n\n```json findings\n[]\n```' + add_round '{"schema":1,"source":"model","round":1,"head_sha":"'"$H1"'","base_sha":"'"$B1"'","approach":"sound","ready":"no","code_review":true,"findings":[{"id":"F1","severity":"important","status":"new","first_round":1,"file":"a.js","line":3,"title":"thing breaks"}],"counts":{"open_blocking":1,"critical":0,"important":1,"minor":0}}' $'### Issues\n- round one' + add_round '{"schema":1,"source":"model","round":2,"head_sha":"'"$H2"'","base_sha":"'"$B1"'","approach":"sound","ready":"no","code_review":true,'"$capped"',"last_ids":{"F":3,"L":0},"counts":{"open_blocking":3,"critical":1,"important":2,"minor":0}}' $'### Issues\n- round two' + run + expect "capped marker ($capped): a full round that says why" '[[ $rc == 0 && $(jq -r ".round, .mode, .mode_reason" <<<"$record" | paste -sd, -) == "3,full,the last record lost its findings to the size cap" ]] && grep -q "mode: full (the last record lost its findings" "$stub/out.log"' + expect "capped marker ($capped): no rule 1, no rule 3, the first-round format" '! grep -q -e "## Previous round" -e "Check every earlier finding" -e "Outside what changed" -e "Fixed since the last round" "$stub/code-prompt.txt" && [[ -z $(session_file previous-findings.md) ]]' + expect "capped marker ($capped): an empty reply does not claim progress over the lost findings" '[[ $(sed -n 4p <<<"$body") == "open blocking: 0 · "* && $body != *"(was 3)"* && $(sed -n 4p <<<"$body") == *"full review (the last record lost its findings to the size cap)" ]]' +done + +# A later round posted without its marker (no room for it): its Markdown shows only what it re-checked, so reading +# it back gives no findings list, and the next round is full. +setup $'**Approach:** Sound' $'**Ready to merge?** Yes\n\n```json findings\n[]\n```' +add_round '{"schema":1,"source":"model","round":1,"head_sha":"'"$H1"'","base_sha":"'"$B1"'","approach":"sound","ready":"no","code_review":true,"findings":[{"id":"F1","severity":"important","status":"new","first_round":1,"file":"a.js","line":3,"title":"thing breaks"}],"counts":{"open_blocking":1,"critical":0,"important":1,"minor":0}}' $'### Issues\n- round one' +jq -c --arg h "$H2" '. + [{user: {login: "me", type: "User"}, state: "APPROVED", commit_id: $h, + submitted_at: "2026-01-02T00:00:00Z", body: "<!-- gh-pr-review generated -->\n### Round 2 · since round 1\n1 not re-checked · open blocking: 1 (was 1)\n\n### Issues\n\n*(none found)*\n\n**Ready to merge?** Yes"}]' \ + "$stub/rest-reviews.json" >"$stub/r.tmp" && mv "$stub/r.tmp" "$stub/rest-reviews.json" +run +expect "markerless later round: the next round is full and says why" \ + '[[ $rc == 0 && $(jq -r ".round, .mode, .mode_reason" <<<"$record" | paste -sd, -) == "3,full,the last round has no record of its findings" ]] && grep -q "mode: full (the last round has no record of its findings)" "$stub/out.log"' +expect "markerless later round: no claim of progress over it" '[[ $(sed -n 4p <<<"$body") == "open blocking: 0 · "* && $body != *"(was "* ]]' + +setup $'### Approach\n\n**Approach:** Sound' "$round3" +add_round '{"schema":1,"source":"model","round":1,"head_sha":"'"$H1"'","base_sha":"'"$B1"'","approach":"rethink","ready":"unknown","code_review":false,"findings":[],"counts":{"open_blocking":null}}' $'### Approach\n\n**Approach:** Rethink' +run +expect "after a Rethink-only round: judged afresh, and a full first code review" '! grep -q "Your previous verdict" "$stub/owner-prompt.txt" && ! grep -q "## Previous round" "$stub/code-prompt.txt" && [[ $(jq -r ".round, .mode, .mode_reason" <<<"$record" | paste -sd, -) == "2,full,no earlier code review" ]]' + # ── producer to consumer: a posted round, returned as GitHub returns it, read back by rounds --json and --check block=$'```json findings\n[{"severity":"important","file":"a.js","line":3,"title":"thing breaks"}]\n```' setup $'**Approach:** Sound' $'### Issues\n#### ⚠️ Important (Should Fix)\n- **`a.js:3` — thing breaks.**\n\n**Ready to merge?** Yes with fixes\n\n'"$block" @@ -868,6 +1139,37 @@ expect "only the pre-post blocker-count check fails: event, marker and round.jso $(jq -c "[.decision, .preview]" <<<"$record") == "[\"comment\",false]" ]] && grep -q "blockers are unknown: posting as comment" "$stub/out.log"' rm "$stub/bin/jq" +# An automatic approve needs a successful check that the count is 0, not only a number. Round 3 says Yes with F3, a +# Critical, still open (1 blocker, ready_overridden). The lookup of ready_overridden fails: the count check still +# comments. When the first count check wrongly passes too, the final one, on the posted record, does. An approve +# chosen stays. +yes_open=$'**Ready to merge?** Yes\n\n```json findings\n[{"id":"F3","status":"open","severity":"critical","file":"c.js","line":9,"title":"data loss","in_delta":false,"later":false},{"id":"F1","status":"fixed","in_delta":false,"later":false}]\n```' +setup $'**Approach:** Sound' "$yes_open" +two_rounds +cat >"$stub/bin/jq" <<S +#!/usr/bin/env bash +for a in "\$@"; do [[ "\$a" == '.ready_overridden == true' ]] && exit 5; done +exec "$(command -v jq)" "\$@" +S +chmod +x "$stub/bin/jq" +run +expect "the ready_overridden lookup fails, 1 blocker open: comments, not approve" \ + '[[ $rc == 0 && $flag == --comment && $(jq -c "[.source, .counts.open_blocking, .decision]" <<<"$record") == "[\"model\",1,\"comment\"]" ]] && + grep -q "But 1 blocking findings are still open: posting as comment" "$stub/out.log"' +cat >"$stub/bin/jq" <<S +#!/usr/bin/env bash +for a in "\$@"; do [[ "\$a" == '.ready_overridden == true' ]] && exit 5; done +if [[ "\$*" == *'.counts.open_blocking == 0'* && "\${*: -1}" == *round.json ]]; then exit 0; fi +exec "$(command -v jq)" "\$@" +S +run +expect "only the pre-post check sees the 1 open blocker: event, marker and round.json all say comment" \ + '[[ $rc == 0 && $flag == --comment && + $(sed -n 2p <<<"$body" | sed "s/^<!-- gh-pr-review:round //; s/ -->$//" | jq -c "[.decision, .counts.open_blocking]") == "[\"comment\",1]" && + $(jq -c "[.decision, .preview]" <<<"$record") == "[\"comment\",false]" ]]' +rm "$stub/bin/jq" +run --decision approve +expect "1 open blocker, approve chosen: stays an approval" '[[ $rc == 0 && $flag == --approve ]]' # ── the review is bound to the commit it read setup $'**Approach:** Sound' "$clean" @@ -890,15 +1192,17 @@ echo head2 >"$stub/heads" run --check expect "head moved during the review: --check on the new head runs" '[[ $rc == 0 ]] && grep -q "Loop check for round 2: run" "$stub/out.log"' -# A loop warning and a head that moved: the loop line stays the review's first line, the note comes right after it. +# A loop warning and a head that moved: the review's head (here the progress lines, which replace the loop line) stays +# first, the note comes right after it. setup $'**Approach:** Sound' "$clean" rounds_with 9 12 8 >"$stub/rest-reviews.json" printf 'head1\nhead2\n' >"$stub/heads" run -expect "loop line and moved head: the loop line first, then the note" \ - '[[ $rc == 0 && $flag == --comment && $(sed -n 3p <<<"$body") == "**Loop:** Churning"* && -z $(sed -n 4p <<<"$body") && - $(sed -n 5p <<<"$body") == "**Note:** The PR moved to head2 during the review; this review covers head1." && - -z $(sed -n 6p <<<"$body") && $(sed -n 7p <<<"$body") == "**Approach:** Sound" ]]' +expect "progress lines and moved head: the progress lines first, then the note" \ + '[[ $rc == 0 && $flag == --comment && $(sed -n 3p <<<"$body") == "### Round 4 · since round 3" && + $(sed -n 4p <<<"$body") == "open blocking: 0 (was 8)"* && -z $(sed -n 5p <<<"$body") && + $(sed -n 6p <<<"$body") == "**Note:** The PR moved to head2 during the review; this review covers head1." && + -z $(sed -n 7p <<<"$body") && $(sed -n 8p <<<"$body") == "**Approach:** Sound" ]]' setup $'**Approach:** Sound' "$clean" touch "$stub/post.fail" @@ -943,4 +1247,161 @@ lost_as "map(if .id == 1 then . + {state: \$state, commit_id: \$p[0].commit_id, rounds_with 2 >"$stub/rest-reviews.json" run expect "the matching review was already a round before the post: unconfirmed" 'unconfirmed' + +# ── producer to consumer, three code-review rounds: each round reads the last one back as GitHub returns it +H3=$(printf 'c3%.0s' {1..20}) +post_back() { # <commit> <date>: the body just posted, as a submitted review in the REST reviews and the discussion + jq -c --arg body "$body" --arg c "$1" --arg d "$2" '. + [{id: (length + 1), user: {login: "me", type: "User"}, + state: "COMMENTED", commit_id: $c, submitted_at: $d, body: $body}]' "$stub/rest-reviews.json" >"$stub/r.tmp" && + mv "$stub/r.tmp" "$stub/rest-reviews.json" + jq -c --arg body "$body" --arg d "$2" '.reviews += [{author: {login: "me"}, state: "COMMENTED", submittedAt: $d, + body: $body}]' "$stub/discussion.json" >"$stub/d.tmp" && mv "$stub/d.tmp" "$stub/discussion.json" +} +r1=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n- **`c.js:9` — data loss.**\n' +r1+=$'#### ⚠️ Important (Should Fix)\n- **`a.js:3` — thing breaks.**\n\n**Ready to merge?** No\n\n' +r1+=$'```json findings\n[{"severity":"important","file":"a.js","line":3,"title":"thing breaks"},' +r1+=$'{"severity":"critical","file":"c.js","line":9,"title":"data loss"}]\n```' +setup $'**Approach:** Sound' "$r1" +echo "$H1" >"$stub/heads" +echo "$B1" >"$stub/git.base" +run +expect "three rounds: round 1 posted" '[[ $rc == 0 && $(jq -r "[.findings[] | .id + \":\" + .file] | join(\" \")" <<<"$record") == "F1:a.js F2:c.js" ]]' +post_back "$H1" 2026-06-01T10:00:00Z +# Round 2 leaves F1 out of both the block and the Markdown: carried, not re-checked, and its file and title appear +# nowhere in the body, so the marker drops them. F2's title is not shown word for word either. +r2=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n- **F2 · `c.js:9`** — still loses data.\n' +r2+=$'#### ⚠️ Important (Should Fix)\n*(none found)*\n#### 💡 Minor (Nice to Have)\n- **`d.js:4`** — typo in a comment.\n\n' +r2+=$'**Ready to merge?** No\n\n```json findings\n[{"id":"F2","status":"open","severity":"critical","file":"c.js","line":9,' +r2+=$'"title":"data loss","in_delta":false,"later":false},{"id":null,"status":"new","severity":"minor","file":"d.js",' +r2+=$'"line":4,"title":"typo in a comment","in_delta":true,"later":false}]\n```' +printf '%s' "$r2" >"$stub/review.out" +echo "$H2" >"$stub/heads" +run +expect "three rounds: round 2 incremental from round 1's head" \ + '[[ $rc == 0 && $(jq -r ".round, .mode, .previous_head_sha" <<<"$record" | paste -sd, -) == "2,incremental,$H1" ]] && grep -qF "git diff --stat $H1..$H2" "$stub/code-prompt.txt"' +expect "three rounds: round 2 carries F1, and its marker drops what the body does not show" \ + '[[ $(jq -r "[.findings[] | .id + \":\" + .status + (if .unverified then \"?\" else \"\" end)] | join(\" \")" <<<"$record") == "F2:open F3:new F1:open?" ]] && + [[ $(sed -n 2p <<<"$body" | sed "s/^<!-- gh-pr-review:round //; s/ -->$//" | jq -c "[.findings[] | select(.id != \"F3\") | [.id, .file, .title]]") == "[[\"F2\",\"c.js\",null],[\"F1\",null,null]]" ]]' +post_back "$H2" 2026-06-02T10:00:00Z +# An outsider's generated review between rounds 1 and 2: no round, so it must not shift round 2 out of place as the +# previous review. +outsider=$'<!-- gh-pr-review generated -->\n### Issues\n- outsider text' +jq -c --arg body "$outsider" '. + [{id: (length + 1), user: {login: "eve", type: "User"}, author_association: "NONE", + state: "COMMENTED", commit_id: "'"$H1"'", submitted_at: "2026-06-01T12:00:00Z", body: $body}]' \ + "$stub/rest-reviews.json" >"$stub/r.tmp" && mv "$stub/r.tmp" "$stub/rest-reviews.json" +jq -c --arg body "$outsider" '.reviews += [{author: {login: "eve"}, authorAssociation: "NONE", state: "COMMENTED", + submittedAt: "2026-06-01T12:00:00Z", body: $body}]' "$stub/discussion.json" >"$stub/d.tmp" && + mv "$stub/d.tmp" "$stub/discussion.json" +printf '%s' $'**Ready to merge?** No\n\n```json findings\n[]\n```' >"$stub/review.out" +echo "$H3" >"$stub/heads" +run +expect "three rounds: an outsider's generated review is not the previous review" \ + '[[ $(session_file previous-review.md) == *"still loses data"* && $(session_file previous-review.md) != *"outsider text"* ]]' +expect "three rounds: round 3 compares with round 2's head" \ + '[[ $rc == 0 && $(jq -r ".round, .mode, .previous_head_sha" <<<"$record" | paste -sd, -) == "3,incremental,$H2" ]] && + grep -qF "git diff --stat $H2..$H3" "$stub/code-prompt.txt" && grep -qF "git diff $H2..$H3" "$stub/code-prompt.txt"' +expect "three rounds: every carried finding is identifiable, details recovered from round 1" \ + '[[ $(session_file previous-findings.md) == "F2 · critical · c.js:9 · data loss"$'"'"'\n'"'"'"F3 · minor · d.js:4 · typo in a comment"$'"'"'\n'"'"'"F1 · important · a.js:3 · thing breaks" ]]' +expect "three rounds: both blockers still count" '[[ $(jq -r ".counts.open_blocking, .counts.unverified" <<<"$record" | paste -sd, -) == "2,3" ]]' + +# ── producer to reader, a later round: round 2 with fixed, declined, carried, new and Later findings, posted with the +# boundary line, read back by rounds with its full marker and with the minimal ones +read_rounds() { # [--json]: rounds over the stub's REST reviews -> $stub/rounds.out + (cd "$stub/work" && HOME="$stub/home" PATH="$stub/bin:$PATH" GH_PR_REVIEW_USER='' \ + bash "$root/gh-pr-review" rounds https://github.com/o/r/pull/1 "$@" >"$stub/rounds.out" 2>"$stub/out.log") && + rc=0 || rc=$? +} +p1=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n- **`a.js:1` — one.**\n#### ⚠️ Important (Should Fix)\n' +p1+=$'- **`b.js:2` — two.**\n- **`c.js:3` — three.**\n#### 💡 Minor (Nice to Have)\n- **`m.js:4` — four.**\n\n' +p1+=$'**Ready to merge?** No\n\n```json findings\n[{"severity":"critical","file":"a.js","line":1,"title":"one"},' +p1+=$'{"severity":"important","file":"b.js","line":2,"title":"two"},{"severity":"important","file":"c.js","line":3,' +p1+=$'"title":"three"},{"severity":"minor","file":"m.js","line":4,"title":"four"}]\n```' +setup $'**Approach:** Sound' "$p1" +echo "$H1" >"$stub/heads" +echo "$B1" >"$stub/git.base" +run +expect "later round read back: round 1 posted, F1–F4" \ + '[[ $rc == 0 && $(jq -c "[.last_ids.F, .counts.open_blocking]" <<<"$record") == "[4,3]" ]]' +post_back "$H1" 2026-07-01T10:00:00Z +# Round 2: F1 fixed, F2 declined with a quote, F3 left out (carried, not re-checked), F4 still open, a new Important +# in d.js (the delta), and an Important outside it filed under Later. +p2=$'### Issues\n#### 🚨 Critical (Must Fix Before Merge)\n*(none found)*\n#### ⚠️ Important (Should Fix)\n' +p2+=$'- **`d.js:5` — new bug.**\n#### 💡 Minor (Nice to Have)\n- **F4 · `m.js:4`** — still four.\n\n' +p2+=$'<details><summary>Fixed since the last round (2)</summary>\n\n- **F1** — fixed.\n' +p2+=$'- **F2** — declined: "by design" (@bob)\n\n</details>\n\n<details><summary>Later (1)</summary>\n\n' +p2+=$'- **`z.js:9`** — can wait.\n\n</details>\n\n**Ready to merge?** No\n\n```json findings\n' +p2+=$'[{"id":"F1","status":"fixed","in_delta":false,"later":false},' +p2+=$'{"id":"F2","status":"declined","reason":"\\"by design\\" (@bob)","in_delta":false,"later":false},' +p2+=$'{"id":"F4","status":"open","severity":"minor","file":"m.js","line":4,"title":"four","in_delta":false,"later":false},' +p2+=$'{"id":null,"status":"new","severity":"important","file":"d.js","line":5,"title":"new bug","in_delta":true,"later":false},' +p2+=$'{"id":null,"status":"new","severity":"important","file":"z.js","line":9,"title":"can wait","in_delta":false,"later":true}]\n```' +printf '%s' "$p2" >"$stub/review.out" +echo "$H2" >"$stub/heads" +run +expect "later round read back: round 2 written from the block, every status" \ + '[[ $rc == 0 && $(jq -c "[.source, ([.findings[] | .id + \":\" + .status + (if .unverified then \"?\" else \"\" end)] | join(\" \")), (.later | map(.id)), .last_ids, (.counts | [.open_blocking, .critical, .important, .minor, .fixed, .declined])]" <<<"$record") == "[\"model\",\"F1:fixed F2:declined F4:open F5:new F3:open?\",[\"L1\"],{\"F\":5,\"L\":1},[2,0,2,1,1,1]]" ]]' +expect "later round read back: the progress lines, then the approach, then the boundary before the code review" \ + '[[ $(sed -n 3p <<<"$body") == "### Round 2 · since round 1" && $(sed -n 4p <<<"$body") == *"open blocking: 2 (was 3)"* && + $(sed -n 6p <<<"$body") == "**Approach:** Sound" && $(sed -n 8p <<<"$body") == "<!-- gh-pr-review:code-review -->" && + $(sed -n 9p <<<"$body") == "### Issues" ]]' +post_back "$H2" 2026-07-02T10:00:00Z +full_body="$body" +read_rounds --json +full_rounds=$(cat "$stub/rounds.out") +r2_view() { jq -c '[.records[1] | .source, .counts.open_blocking, .counts.critical, .last_ids.F, .last_ids.L] + [.decision.labels[1], .decision.label]' "$stub/rounds.out"; } +expect "later round read back, full marker: as written, 2 blockers, last_ids F5 and L1" \ + '[[ $rc == 0 && $(r2_view) == "[\"model\",2,0,5,1,\"early\",\"early\"]" ]]' +read_rounds +full_table=$(grep '^2 ' "$stub/rounds.out") +# The same posted body with the minimal marker in place of the full one, with last_ids and without: read from the +# Markdown after the boundary, with the progress line's 2 blockers (the carried F3 is not in the Markdown), and the +# same label. With last_ids the floor is the writer's, F5 and L1; without, every finding the Markdown shows takes a +# new ID after round 1's F4 (F5, F6: never below the writer's), and the Later item reserves L1. +for m in '{"schema":1,"round":2,"findings_dropped":true,"last_ids":{"F":5,"L":1}}~5,1' \ + '{"schema":1,"round":2,"findings_dropped":true}~6,1'; do + min_body=$(sed "2s/.*/<!-- gh-pr-review:round ${m%%~*} -->/" <<<"$full_body") + jq -c --arg b "$min_body" '.[1].body = $b' "$stub/rest-reviews.json" >"$stub/r.tmp" && mv "$stub/r.tmp" "$stub/rest-reviews.json" + read_rounds --json + expect "later round read back, minimal marker ${m%%~*}: 2 blockers, the same label, last_ids F,L ${m##*~}" \ + '[[ $rc == 0 && $(r2_view) == "[\"backfill\",2,0,${m##*~},\"early\",\"early\"]" && + $(jq -c ".records[1] | [.findings_dropped, has(\"findings\")]" "$stub/rounds.out") == "[true,false]" && + $(jq -c "[.records[] | .counts.open_blocking]" "$stub/rounds.out") == "$(jq -c "[.records[] | .counts.open_blocking]" <<<"$full_rounds")" ]]' + read_rounds + expect "later round read back, minimal marker ${m%%~*}: the table row differs only in IMP and the source" \ + '[[ $rc == 0 && $(grep "^2 " "$stub/rounds.out" | sed "s/ */ /g") == "$(sed "s/ */ /g; s/ 2 1 early model/ 1 1 early backfill/" <<<"$full_table")" ]]' +done + +# Rounds 1–2 leave two blockers open (F1, F3). Round 3's record can't be built: it posts as comment, its Markdown +# shows neither blocker, and its minimal marker says it is a later round with an unknown count and no findings list. +# Read back that way, round 4 does not build on it as an empty baseline: it is a full review of the whole PR, as a +# first code review (no previous-round rules, no previous-findings.md), and round 3 counts as unknown, not as 0 +# blockers. A full review re-reads the whole PR, so its clean verdict stands: it approves. +setup $'**Approach:** Sound' "$clean" +two_rounds +echo "$H3" >"$stub/heads" +echo "$B1" >"$stub/git.base" +break_record fail +run +expect "record fails in round 3: posted as comment, with a minimal marker of unknown count" \ + '[[ $rc == 0 && $flag == --comment && -z $record && + $(sed -n 2p <<<"$body" | sed "s/^<!-- gh-pr-review:round //; s/ -->$//" | jq -c .) == "{\"schema\":1,\"round\":3,\"findings_dropped\":true,\"last_ids\":{\"F\":3,\"L\":0},\"counts\":{\"open_blocking\":null,\"critical\":null,\"important\":null,\"minor\":null}}" ]]' +rm "$stub/bin/jq" +post_back "$H3" 2026-01-03T00:00:00Z +read_rounds --json +expect "record fails in round 3: read back with unknown counts and no findings list" \ + '[[ $rc == 0 && $(jq -c ".records[2] | [.round, .counts.open_blocking, .counts.critical, .findings_dropped, has(\"findings\"), .last_ids.F]" "$stub/rounds.out") == "[3,null,null,true,false,3]" && + $(jq -c ".decision.series" "$stub/rounds.out") == "[1,2,null]" ]]' +H4=$(printf 'c4%.0s' {1..20}) +echo "$H4" >"$stub/heads" +run +expect "record failed in round 3: round 4 is a full review, not an increment on an empty baseline" \ + '[[ $rc == 0 && $(jq -r ".round, .mode, .mode_reason" <<<"$record" | paste -sd, -) == "4,full,the last round has no record of its findings" ]] && + grep -q "mode: full (the last round has no record of its findings)" "$stub/out.log"' +expect "record failed in round 3: round 4 has no previous-round rules and no previous-findings.md" \ + '! grep -q -e "## Previous round" -e "Check every earlier finding" -e "Outside what changed" "$stub/code-prompt.txt" && + [[ -z $(session_file previous-findings.md) ]]' +expect "record failed in round 3: round 4, a clean full review, approves" \ + '[[ $flag == --approve && $(jq -c "[.counts.open_blocking, .decision]" <<<"$record") == "[0,\"approve\"]" ]]' + +finished=true exit "$fail" diff --git a/tests/loop.sh b/tests/loop.sh index 6fe91b0..8897608 100644 --- a/tests/loop.sh +++ b/tests/loop.sh @@ -6,6 +6,9 @@ root=$(cd "$(dirname "$0")/.." && pwd) LIB_DIR="$root/lib" # shellcheck source=lib/loop.sh source "$root/lib/loop.sh" +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap '[[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 eq() { # name got want @@ -220,4 +223,5 @@ eq "loop_text empty" "$(loop_text "$(loop_decide_json '[]' '{}' new false)")" "L label none (no earlier rounds) blocking none flags none" +finished=true exit "$fail" diff --git a/tests/passes.sh b/tests/passes.sh index 273ece3..04ed9b4 100644 --- a/tests/passes.sh +++ b/tests/passes.sh @@ -5,6 +5,9 @@ root=$(cd "$(dirname "$0")/.." && pwd) stub=$(mktemp -d) sed -n '/^# ── passes/,/^# ── end passes/p' "$root/gh-pr-review" >"$stub/lib.sh" footer='*Review generated by gh pr-review · model: m*' +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap '[[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 eq() { # name got want @@ -40,4 +43,5 @@ eq "skip-approach: boundary, review and footer" "$(in_lib "assemble_review '' '' "$boundary"$'\nREVIEW\n\n---\n'"$footer" eq "rethink: approach and footer, no boundary" "$(in_lib "assemble_review '' 'APPROACH' ''")" $'APPROACH\n\n---\n'"$footer" eq "nothing to post stays empty" "$(in_lib "assemble_review '' '' ''")" "" +finished=true exit "$fail" diff --git a/tests/post-decision.sh b/tests/post-decision.sh index d132600..a9c940b 100755 --- a/tests/post-decision.sh +++ b/tests/post-decision.sh @@ -9,6 +9,9 @@ stub=$(mktemp -d) cat "$root"/lib/*.sh sed -n '/^# ── post/,$p' "$root/gh-pr-review" } >"$stub/post.sh" +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap '[[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 check() { # name review author me decision approach-verdict expected-flag [code-review, default: review] [record: none] @@ -70,4 +73,5 @@ else fi check "empty record before posting: an explicit approve stays" 'x' bob me approve '' --approve x empty check "no dash reason" '**Ready to merge?** No — see Critical' bob me '' '' --request-changes +finished=true exit "$fail" diff --git a/tests/pr-context.sh b/tests/pr-context.sh index cb5de1a..ebe9f3d 100644 --- a/tests/pr-context.sh +++ b/tests/pr-context.sh @@ -5,6 +5,9 @@ root=$(cd "$(dirname "$0")/.." && pwd) stub=$(mktemp -d) sed -n '/^# ── pr context/,/^}/p' "$root/gh-pr-review" >"$stub/lib.sh" no_threads='{"data":{"repository":{"pullRequest":{"reviewThreads":{"nodes":[]}}}}}' +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap '[[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 run() { # pr-json [threads-json] [graphql-exit-code] -> writes into $stub/ctx, sets out and rc @@ -93,4 +96,5 @@ if [[ $rc != 0 && "$out" == *"Error: could not fetch"* ]]; then echo "ok gh fa echo "FAIL gh failure is reported: rc=$rc out=$out" fail=1 fi +finished=true exit "$fail" diff --git a/tests/records.sh b/tests/records.sh index 0fa3f10..ba68b00 100644 --- a/tests/records.sh +++ b/tests/records.sh @@ -10,7 +10,9 @@ source "$root/lib/verdicts.sh" source "$root/lib/records.sh" fixtures="$root/tests/fixtures/reviews" tmp=$(mktemp -d) -trap 'rm -rf "$tmp"' EXIT +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap 'rm -rf "$tmp"; [[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 check() { # name got want @@ -100,10 +102,15 @@ meta='{"source":"model","pr":{"host":"github.com","owner":"o","repo":"r","number "reviewer":"me","model":"m","head_sha":"bbb","approach":"sound","ready":"yes-with-fixes","code_review":true}' prev=$(jq -n '{head_sha: "aaa", findings: [range(1; 8) | {id: "F\(.)"}]}') rec=$(build_record "$meta" "$(parse_findings "$fixtures/bullets.md")" "$prev") +rec_bullets=$rec check "ids continue after F7" "$(jq -r '[.findings[].id] | join(" ")' <<<"$rec")" "F8 F9 F10 F11 F12 F13" check "open_blocking" "$(jq '.counts.open_blocking' <<<"$rec")" 4 check "counts" "$(jq -c '.counts' <<<"$rec")" \ - '{"open_blocking":4,"critical":1,"important":3,"minor":2,"new":6,"fixed":0,"declined":0,"regressed":0}' + '{"open_blocking":4,"critical":1,"important":3,"minor":2,"new":6,"fixed":0,"declined":0,"regressed":0,"later":0,"unverified":0}' +check "round 1: no unverified key" "$(jq '[.findings[] | has("unverified")] | any' <<<"$rec")" false +check "round 1: last ids" "$(jq -c '.last_ids' <<<"$rec")" '{"F":13,"L":0}' +check "round 1: ready kept, not overridden" "$(jq -c '[.ready, .ready_overridden]' <<<"$rec")" '["yes-with-fixes",true]' +check "mode kept, no reason" "$(jq -c '[.mode, .mode_reason]' <<<"$rec")" '["full",null]' check "finding fields" "$(jq -c '.findings[0] | [.status, .first_round, .in_delta]' <<<"$rec")" '["new",2,false]' check "schema, later, preview" "$(jq -c '[.schema, .later, .preview]' <<<"$rec")" '[1,[],false]' check "missing meta keys are null" "$(jq -c '[.base_sha, .posted_at, .decision]' <<<"$rec")" '[null,null,null]' @@ -117,9 +124,199 @@ rethink=$(build_record "$(jq -c '.code_review = false | .approach = "rethink"' < '[{"severity":"critical","title":"t"}]' null) check "rethink: no findings" "$(jq -c '.findings' <<<"$rethink")" "[]" check "rethink: null counts" "$(jq -c '[.counts[]] | unique' <<<"$rethink")" "[null]" +check "rethink: count keys" "$(jq -c '.counts | keys' <<<"$rethink")" \ + '["critical","declined","fixed","important","later","minor","new","open_blocking","regressed","unverified"]' +check "rethink: not overridden, no later" "$(jq -c '[.ready_overridden, .later]' <<<"$rethink")" '[false,[]]' + +# ── build_record with statuses (round 2 and later) ────────────────────────── +# Round 2: F1 open, F2 fixed, F3 declined, F4 new, F5 regressed, L6 later. F and L number apart, each from its +# highest. +meta2=$(jq -c '.round = 3 | .mode = "incremental" | .mode_reason = null | .ready = "no" | .delta_files = ["t.ts"]' <<<"$meta") +prev2=$(jq -nc '{round: 2, head_sha: "aaa", counts: {open_blocking: 3}, findings: [ + {id: "F1", severity: "critical", status: "open", first_round: 1, in_delta: false, file: "a.ts", line: 1, title: "one"}, + {id: "F2", severity: "important", status: "fixed", first_round: 1, in_delta: false, file: "b.ts", line: 2, title: "two"}, + {id: "F3", severity: "important", status: "declined", first_round: 1, in_delta: false, file: "c.ts", line: 3, title: "three"}, + {id: "F4", severity: "minor", status: "new", first_round: 2, in_delta: true, file: "d.ts", line: 4, title: "four"}, + {id: "F5", severity: "important", status: "regressed", first_round: 1, in_delta: false, file: "e.ts", line: 5, + title: "five"}], + later: [{id: "L6", severity: "minor", file: "f.ts", line: 6, title: "six"}]}') +r3() { build_record "$meta2" "$1" "$prev2"; } +one() { jq -c --arg id "$2" '(.findings + .later)[] | select(.id == $id) + | [.status, .first_round, .severity, .file, .line, .title, (.unverified // false)]' <<<"$1"; } + +rec=$(r3 '[{"id":"F1","status":"fixed"}]') +check "known id keeps its status" "$(one "$rec" F1)" '["fixed",1,"critical","a.ts",1,"one",false]' +rec=$(r3 '[{"id":"F1","status":"open","severity":"minor","file":"z.ts","line":9,"title":"new title"}]') +check "known id: model fields win" "$(one "$rec" F1)" '["open",1,"minor","z.ts",9,"new title",false]' +rec=$(r3 '[{"id":"F2","status":"open"}]') +check "fixed then open: regressed" "$(one "$rec" F2)" '["regressed",1,"important","b.ts",2,"two",false]' +check "regressed counts as blocking" "$(jq -c '.counts | [.regressed, .open_blocking]' <<<"$rec")" '[1,3]' +rec=$(r3 '[{"id":"F5","status":"open"}]') +check "regressed then open: open" "$(one "$rec" F5)" '["open",1,"important","e.ts",5,"five",false]' +rec=$(r3 '[{"severity":"minor","title":"n1"},{"severity":"important","file":"l.ts","title":"l1","later":true}, + {"severity":"critical","title":"n2","in_delta":true}]') +check "new ids continue after F5 and L6" "$(jq -c '[.findings[] | select(.status == "new") | .id], [.later[].id]' \ + <<<"$rec" | tr -d '\n')" '["F6","F7"]["L7"]' +check "new finding fields" "$(jq -c '.findings[] | select(.id == "F7") | [.status, .first_round, .in_delta]' \ + <<<"$rec")" '["new",3,true]' +check "later item fields" "$(jq -c '.later[0]' <<<"$rec")" \ + '{"id":"L7","severity":"important","file":"l.ts","line":null,"title":"l1"}' +check "last ids" "$(jq -c '.last_ids' <<<"$rec")" '{"F":7,"L":7}' +check "later items not blocking" "$(jq -c '.counts | [.later, .important]' <<<"$rec")" '[1,1]' +check "previous later not carried" "$(jq -c '[.later[].id] | index("L6")' <<<"$rec")" null +rec=$(r3 '[]') +check "missing ids carried as unverified open" \ + "$(jq -c '[.findings[] | [.id, .status, .unverified]]' <<<"$rec")" \ + '[["F1","open",true],["F4","open",true],["F5","open",true]]' +check "carried keep first round" "$(one "$rec" F4)" '["open",2,"minor","d.ts",4,"four",true]' +check "fixed and declined not carried" "$(jq -c '[.findings[].id | select(. == "F2" or . == "F3")]' <<<"$rec")" "[]" +check "carried: counts" "$(jq -c '.counts' <<<"$rec")" \ + '{"open_blocking":2,"critical":1,"important":1,"minor":1,"new":0,"fixed":0,"declined":0,"regressed":0,"later":0,"unverified":3}' +check "numbering survives an empty round" "$(build_record "$meta2" '[{"severity":"minor","title":"x"}]' "$rec" | + jq -r '.findings[] | select(.status == "new") | .id')" F6 +rec=$(r3 '[{"id":"F1","status":"fixed"},{"id":"F1","status":"open"}]') +check "duplicate keeps the first" "$(jq -c '[.findings[] | select(.id == "F1") | .status]' <<<"$rec")" '["fixed"]' +rec=$(r3 '[{"id":"F99","status":"open","severity":"important","title":"ghost"}]') +check "unknown id becomes new" "$(jq -c '.findings[0] | [.id, .status, .first_round, .title]' <<<"$rec")" \ + '["F6","new",3,"ghost"]' +rec=$(r3 '[{"id":"F1","status":"maybe"}]') +check "bad status: open, unverified" "$(one "$rec" F1)" '["open",1,"critical","a.ts",1,"one",true]' +check "bad status: not carried twice" "$(jq '[.findings[] | select(.id == "F1")] | length' <<<"$rec")" 1 +check "in_delta kept as a boolean" "$(r3 '[{"severity":"minor","title":"t","in_delta":"yes"}]' | + jq -c '.findings[0].in_delta')" false + +rec=$(build_record "$(jq -c '.ready = "yes"' <<<"$meta2")" '[{"id":"F1","status":"open"}]' "$prev2") +check "ready yes with open blocking: overridden" "$(jq -c '[.ready, .ready_overridden]' <<<"$rec")" '["yes",true]' +rec=$(build_record "$(jq -c '.ready = "yes"' <<<"$meta2")" \ + '[{"id":"F1","status":"fixed"},{"id":"F4","status":"open"},{"id":"F5","status":"declined","reason":"out of scope"}]' "$prev2") +check "ready yes, nothing blocking: not overridden" "$(jq -c '[.ready_overridden, .counts.open_blocking]' \ + <<<"$rec")" '[false,0]' +check "ready no: not overridden" "$(r3 '[]' | jq .ready_overridden)" false +rec=$(build_record "$(jq -c '.mode = "full" | .mode_reason = "the previous head is gone"' <<<"$meta2")" '[]' "$prev2") +check "mode and mode_reason kept" "$(jq -c '[.mode, .mode_reason]' <<<"$rec")" '["full","the previous head is gone"]' +rec=$(build_record "$(jq -c '.code_review = false | .approach = "rethink"' <<<"$meta2")" \ + '[{"id":"F1","status":"fixed"}]' "$prev2") +check "rethink after round 2: no findings, null counts" "$(jq -c '[.findings, .later, ([.counts[]] | unique)]' \ + <<<"$rec")" '[[],[],[null]]' + +# Model output that would drop a blocker: a decline needs a reason, Later needs an eligible finding. +rec=$(r3 '[{"id":"F1","status":"declined"},{"id":"F5","status":"declined","reason":" "}]') +check "declined without a reason: open, unverified" "$(one "$rec" F1),$(one "$rec" F5)" \ + '["open",1,"critical","a.ts",1,"one",true],["open",1,"important","e.ts",5,"five",true]' +check "declined without a reason: still blocking" "$(jq -c '.counts | [.open_blocking, .declined]' <<<"$rec")" '[2,0]' +rec=$(r3 '[{"id":"F1","status":"declined","severity":"minor"}]') +check "declined without a reason: no severity downgrade" "$(one "$rec" F1)" '["open",1,"critical","a.ts",1,"one",true]' +check "declined without a reason: the Critical still blocks" \ + "$(jq -c '[.counts.open_blocking, .counts.critical, .counts.minor]' <<<"$rec")" '[2,1,1]' +rec=$(r3 '[{"id":"F1","status":"declined","reason":"\"not in this PR\" (alice)"}]') +check "declined with a reason: declined" "$(one "$rec" F1)" '["declined",1,"critical","a.ts",1,"one",false]' +later_of() { # <meta> <entry> -> where it went: later or the findings, with its status + build_record "$1" "[$2]" "$prev2" | jq -r 'if (.later | length) > 0 then "later" + else .findings[] | select(.status == "new") | "finding:" + .severity end' +} +check "later: an Important outside the delta, incremental" \ + "$(later_of "$meta2" '{"severity":"important","file":"x.ts","title":"x","later":true}')" later +check "later: a Minor outside the delta, rebased" \ + "$(later_of "$(jq -c '.mode = "rebased"' <<<"$meta2")" '{"severity":"minor","file":"x.ts","title":"x","later":true}')" later +check "later: a Critical stays a finding" \ + "$(later_of "$meta2" '{"severity":"critical","title":"x","later":true}')" finding:critical +check "later: one in the delta stays a finding" \ + "$(later_of "$meta2" '{"severity":"important","file":"x.ts","title":"x","later":true,"in_delta":true}')" finding:important +check "later: a full round has no Later" \ + "$(later_of "$(jq -c '.mode = "full"' <<<"$meta2")" '{"severity":"important","file":"x.ts","title":"x","later":true}')" \ + finding:important +check "later: no mode, no Later" \ + "$(later_of "$(jq -c 'del(.mode)' <<<"$meta2")" '{"severity":"minor","file":"x.ts","title":"x","later":true}')" finding:minor +# The delta's file list decides, not in_delta: a touched file, a missing file or an unknown list keeps the finding. +check "later: one in a file the delta touched stays a finding" \ + "$(later_of "$meta2" '{"severity":"important","file":"t.ts","title":"x","later":true,"in_delta":false}')" finding:important +check "later: a ./ path in a touched file stays a finding" \ + "$(later_of "$meta2" '{"severity":"minor","file":"./t.ts","title":"x","later":true}')" finding:minor +check "later: one without a file stays a finding" \ + "$(later_of "$meta2" '{"severity":"important","title":"x","later":true}')" finding:important +check "later: no file list, no Later" \ + "$(later_of "$(jq -c 'del(.delta_files)' <<<"$meta2")" '{"severity":"minor","file":"x.ts","title":"x","later":true}')" \ + finding:minor +rec=$(build_record "$(jq -c '.mode = "full" | .ready = "yes"' <<<"$meta2")" \ + '[{"id":"F1","status":"fixed"},{"id":"F4","status":"fixed"},{"id":"F5","status":"fixed"}, + {"severity":"critical","title":"x","later":true}]' "$prev2") +check "later: a Critical marked later in a full round blocks the approval" \ + "$(jq -c '[.counts.open_blocking, .ready_overridden, (.later | length)]' <<<"$rec")" '[1,true,0]' + +# A full round 3 on the round 2 record: every status moves. +reply='[ + {"id":"F2","status":"open","in_delta":true}, + {"id":"F5","status":"fixed"}, + {"id":"F4","status":"declined","title":"four, declined","reason":"\"Kept on purpose\" (bob)"}, + {"id":"F2","status":"fixed"}, + {"id":"F3","status":"open"}, + {"id":"F77","status":"fixed","severity":"minor","file":"g.ts","line":7,"title":"unknown"}, + {"severity":"critical","file":"h.ts","line":8,"title":"in delta","in_delta":true}, + {"severity":"important","file":"i.ts","line":9,"title":"later one","later":true}, + {"severity":"nit","title":"dropped"} +]' +rec=$(r3 "$reply") +check "round 3: findings" "$(jq -c '[.findings[] | [.id, .status, .first_round, (.unverified // false)]]' <<<"$rec")" \ + '[["F2","regressed",1,false],["F5","fixed",1,false],["F4","declined",2,false],["F3","open",1,false],["F6","new",3,false],["F7","new",3,false],["F1","open",1,true]]' +check "round 3: later" "$(jq -c '[.later[] | [.id, .title]]' <<<"$rec")" '[["L7","later one"]]' +check "round 3: counts" "$(jq -c '.counts' <<<"$rec")" \ + '{"open_blocking":4,"critical":2,"important":2,"minor":1,"new":2,"fixed":1,"declined":1,"regressed":1,"later":1,"unverified":1}' +check "round 3: kept the round 2 head" "$(jq -r .previous_head_sha <<<"$rec")" aaa + +# A marker cut to fit the size cap: counts and last_ids kept, findings list gone. Nothing to carry, no ID to know. +capped2=$(jq -c '.last_ids = {F: 5, L: 6}' <<<"$prev2") +for capped in "$(jq -c 'del(.findings) | .findings_dropped = true' <<<"$capped2")" \ + "$(jq -c 'del(.findings)' <<<"$capped2")" "$(jq -c '.findings_dropped = true' <<<"$capped2")"; do + what=$(jq -r 'if has("findings") then "findings_dropped with a list" elif .findings_dropped then "findings_dropped" + else "no findings key" end' <<<"$capped") + rec=$(build_record "$meta2" '[]' "$capped") + check "capped previous ($what): nothing carried" "$(jq -c '[.findings, .counts.open_blocking, .counts.unverified]' \ + <<<"$rec")" '[[],0,0]' + check "capped previous ($what): no 'was' in the progress line" \ + "$(progress_line "$rec" "$capped" '{"label":null}' | tail -n 1)" "open blocking: 0" + rec=$(build_record "$meta2" '[{"id":"F1","status":"fixed"},{"id":"F2","status":"open","severity":"important","title":"t"}]' \ + "$capped") + check "capped previous ($what): an ID it cannot know is new" "$(jq -c '[.findings[] | [.id, .status]]' <<<"$rec")" \ + '[["F6","new"]]' +done +empty=$(jq -c '.findings = [] | .counts.open_blocking = 0' <<<"$prev2") +rec=$(build_record "$meta2" '[]' "$empty") +check "empty previous list: a known zero, kept in the progress line" \ + "$(progress_line "$rec" "$empty" '{"label":null}' | tail -n 1)" "open blocking: 0 (was 0)" + +# The Markdown fallback on a later-round body (no findings block): IDs kept, folded sections not open findings. +f=$(parse_findings "$fixtures/later-round.md") +check "later round: open items keep their ID, both bullet forms" \ + "$(jq -c '[.[] | select(.status == "open") | [.id, .severity, .file, .line]]' <<<"$f")" \ + '[["F1","critical","a.ts",1],["F5","important","e.ts",5],["F2","important","b.ts",2]]' +check "later round: the ID is not in the title" "$(item "$f" 0)" \ + "critical | a.ts | 1 | Still trusts the payload when the header is empty." +check "later round: a new item has no ID" "$(jq -c '[.[] | select(.id == null) | [.severity, .file, .title]]' <<<"$f")" \ + '[["important","d.ts","The new retry loop has no upper bound."]]' +check "later round: Fixed gives fixed and declined, with the quoted reason" \ + "$(jq -c '[.[] | select(.status == "fixed" or .status == "declined") | [.id, .status, .reason, .severity]]' <<<"$f")" \ + '[["F4","fixed",null,null],["F3","declined","\"Kept on purpose until the v2 API ships\" (@bob)",null]]' +check "later round: the Later item and the Strengths are left out" "$(jq -c '[.[] | .file] | index("f.ts"), index("src/api.ts")' \ + <<<"$f" | paste -sd, -)" "null,null" +rec=$(r3 "$f") +check "later round fallback: every ID once, nothing carried twice" \ + "$(jq -c '[.findings[] | [.id, .status, (.unverified // false)]]' <<<"$rec")" \ + '[["F1","open",false],["F5","open",false],["F2","regressed",false],["F6","new",false],["F4","fixed",false],["F3","declined",false]]' +check "later round fallback: counts" "$(jq -c '.counts | [.open_blocking, .unverified, .later, .minor]' <<<"$rec")" \ + '[4,0,0,0]' +printf '#### ⚠️ Important\n\n- **F1 · `a.ts:1`** — open.\n\n<details><summary>Fixed (1)</summary>\n\n- **F4** — declined:\n- **F5** — declined: \n\n#### 💡 Minor\n\n- **[m.ts:1]** — after an unclosed details.\n' \ + >"$tmp/unclosed.md" +f=$(parse_findings "$tmp/unclosed.md") +check "later round: a decline without a reason has none" "$(jq -c '[.[] | select(.status == "declined") | .reason]' <<<"$f")" \ + '[null,null]' +# A fold runs to its </details> (_lines): a heading inside an unclosed one starts no section. +check "later round: a heading inside an unclosed <details> starts no section" \ + "$(jq -c '[.[] | select(.severity == "minor") | .file]' <<<"$f")" '[]' +check "later round: an unreasoned decline stays open" "$(r3 "$f" | jq -c '[.findings[] | select(.id == "F4" or .id == "F5") + | [.id, .status, .unverified]]')" '[["F4","open",true],["F5","open",true]]' # ── finding IDs never restart ─────────────────────────────────────────────── -check "last_ids: the highest IDs of the round" "$(jq -c '.last_ids' <<<"$rec")" '{"F":13,"L":0}' +check "last_ids: the highest IDs of the round" "$(jq -c '.last_ids' <<<"$rec_bullets")" '{"F":13,"L":0}' one='[{"severity":"minor","title":"t"}]' r1=$(build_record "$meta" "$one" null) r2=$(build_record "$(jq -c '.code_review = false | .approach = "rethink"' <<<"$meta")" "$one" "$r1") @@ -138,17 +335,53 @@ check "id_floor: the next ID comes after the floor, not the previous record" \ "$(build_record "$(jq -c '.id_floor = {F: 9, L: 4}' <<<"$meta")" "$one" "$r1" | jq -c '[.findings[0].id, .last_ids]')" '["F10",{"F":10,"L":4}]' -ok_block() { jq -c -L "$LIB_DIR" 'include "records"; map(findings_block_ok)' <<<"$1"; } +# ── recover_details ───────────────────────────────────────────────────────── +# Round 3's marker left out F1's file and title and F2's title; earlier rounds had them. The newest one wins. +history=$(jq -nc '[{findings: [{id: "F1", file: "old.ts", line: 1, title: "first title"}, {id: "F2", title: "two"}]}, + {findings: [{id: "F1", file: "a.ts", line: 3, title: "thing breaks"}]}, + {findings_dropped: true}, + {findings: [{id: "F1", severity: "important", line: 7}, {id: "F2", file: "c.ts", line: 9}, {id: "F9"}]}]') +check "recover_details: missing details from the newest earlier round with the ID" \ + "$(jq -c -L "$LIB_DIR" 'include "records"; .[-1] | recover_details($h) | [.findings[] | [.id, .file, .line, .title]]' \ + --argjson h "$history" <<<"$history")" \ + '[["F1","a.ts",7,"thing breaks"],["F2","c.ts",9,"two"],["F9",null,null,null]]' +check "recover_details: no history, no change" \ + "$(jq -c -L "$LIB_DIR" 'include "records"; recover_details(null) | .findings' <<<'{"findings":[{"id":"F1"}]}')" '[{"id":"F1","file":null,"line":null,"title":null}]' + +ok_block() { # <blocks> [known ids] + jq -c -L "$LIB_DIR" --argjson ids "${2:-[]}" 'include "records"; map(findings_block_ok($ids))' <<<"$1" +} check "findings_block_ok: good blocks" "$(ok_block '[[], [{"severity":"Critical","title":"t","file":null,"line":null}], [{"severity":"minor","title":"t","file":"a.js","line":3}, {"severity":"important","title":"u"}]]')" \ "[true,true,true]" +check "findings_block_ok: an earlier ID may give only its status" \ + "$(ok_block '[[{"id":"F3","status":"fixed"}], [{"id":"F3","status":"open","severity":"critical"}], [{"id":null,"status":"new","title":"t"}], [{"status":"new","severity":"minor"}], [{"id":" F3 ","status":"fixed"}]]' '["F1","F3"]')" \ + "[true,true,false,false,true]" +# An ID the last code review does not have is a new finding: without a severity and a title, the Markdown decides. +check "findings_block_ok: an unknown ID must be a whole new finding" \ + "$(ok_block '[[{"id":"F999","status":"open","title":"Nil dereference"}], [{"id":"F2","status":"fixed"}], + [{"id":"F999","status":"open","severity":"critical","title":"Nil dereference"}]]' '["F1"]')" "[false,false,true]" +check "findings_block_ok: round 1 knows no ID" "$(ok_block '[[{"id":"F1","status":"fixed"}]]')" "[false]" +check "known_ids: the last code review's IDs, none without its list" \ + "$(jq -c -L "$LIB_DIR" 'include "records"; map(known_ids)' <<<"[null, $prev2, $(jq -c '.findings_dropped = true' <<<"$prev2")]")" \ + '[[],["F1","F2","F3","F4","F5"],[]]' +# Round 1 with an invented ID and no severity: the block is not usable, so the Markdown's Critical is the record's. +printf '#### 🚨 Critical\n\n- **`n.go:4` — Nil dereference.**\n' >"$tmp/invented.md" +if jq -e -L "$LIB_DIR" 'include "records"; findings_block_ok(null | known_ids)' \ + <<<'[{"id":"F999","status":"open","title":"Nil dereference"}]' >/dev/null; then + f='[{"id":"F999","status":"open","title":"Nil dereference"}]' +else f=$(parse_findings "$tmp/invented.md"); fi +check "invented ID: the record has the Critical from the Markdown" \ + "$(build_record "$meta" "$f" null | jq -c '[.counts.critical, .findings[0].id, .findings[0].file]')" '[1,"F1","n.go"]' + check "findings_block_ok: one bad entry spoils the block" "$(ok_block '[{}, [{"level":"critical","title":"t"}], [{"severity":"nit","title":"t"}], [{"severity":"minor"}], [{"severity":"minor","title":"t","line":"3"}], [{"severity":"minor","title":"t","file":3}], [{"severity":"minor","title":"t"}, "F2"]]')" \ "[false,false,false,false,false,false,false]" +# A round 1 block, judged as round 1 stores it (stored_findings without a last code review: every entry is new). covers() { # block parsed -> block_covers_markdown - jq -c -n -L "$LIB_DIR" --argjson b "$1" --argjson p "$2" 'include "records"; $b | block_covers_markdown($p)' + jq -c -n -L "$LIB_DIR" --argjson b "$1" --argjson p "$2" 'include "records"; $b | block_covers_markdown($p; null; null)' } crit='[{"severity":"critical","title":"t"}]' check "block_covers_markdown: [] next to a Critical bullet does not cover it" "$(covers '[]' "$crit")" false @@ -159,8 +392,8 @@ check "block_covers_markdown: a Critical covers an Important" \ "$(covers '[{"severity":"critical","title":"x"}]' '[{"severity":"important","title":"t"}]')" true check "block_covers_markdown: a downgrade to minor does not cover an Important" \ "$(covers '[{"severity":"minor","title":"x"}]' '[{"severity":"important","title":"t"}]')" false -# This version stores every entry as new (stored_status): a block's fixed, declined or later entry is open. -check "block_covers_markdown: fixed, declined and later entries are judged as stored: open" \ +# Round 1 stores every entry as new (entry_outcome): a block's fixed, declined or later entry is open. +check "block_covers_markdown: round 1 fixed, declined and later entries are judged as stored: open" \ "$(covers '[{"severity":"critical","status":"fixed"}]' "$crit"),$(covers '[{"severity":"critical","status":"declined"}]' "$crit"),$(covers '[{"severity":"critical","later":true}]' "$crit")" true,true,true check "block_covers_markdown: open, regressed and status-less entries are" \ "$(covers '[{"severity":"critical","status":"open"},{"severity":"important","status":"regressed"},{"severity":"important"}]' \ @@ -179,7 +412,7 @@ check "block_covers_markdown: two bullets at one location need two entries there check "block_covers_markdown: entries and bullets without a location take no part" \ "$(covers '[{"severity":"critical","title":"x"},{"severity":"critical","file":"z.go"}]' \ '[{"severity":"critical","file":"a.go","line":null},{"severity":"critical","file":null,"line":null}]')" true -check "block_covers_markdown: a fixed entry at the location is stored as new: it covers it" \ +check "block_covers_markdown: a round 1 fixed entry at the location is stored as new: it covers it" \ "$(covers '[{"severity":"critical","file":"a.go","line":10,"status":"fixed"}]' \ '[{"severity":"critical","file":"a.go","line":10}]')" true @@ -224,7 +457,10 @@ check "parse_findings: the same lines are no findings" \ "$(printf '#### 🚨 Critical\n- None.\n#### ⚠️ Important\n- *(none found)*\n1. None.\n' | jq -c -Rs -L "$LIB_DIR" 'include "records"; parse_findings')" '[]' # Severity headings count only in the Issues section, and a folded <details> list is no section's. f=$(parse_findings "$fixtures/approach-context.md") -check "parse_findings: bullets under an approach heading named Important context are no findings" "$f" '[]' +check "parse_findings: bullets under an approach heading named Important context are no findings" \ + "$(jq -c 'map(select(.severity))' <<<"$f")" '[]' +check "parse_findings: the folded Fixed list of that review gives its IDs as fixed" \ + "$(jq -c 'map(.id + " " + .status)' <<<"$f")" '["F1 fixed","F2 fixed"]' check "empty_severities: so every severity of that review is empty" \ "$(jq -c -Rs -L "$LIB_DIR" 'include "records"; empty_severities' "$fixtures/approach-context.md")" '["critical","important","minor"]' check "parse_findings: the same heading in a body without an Issues heading still counts" \ @@ -243,29 +479,93 @@ check "empty_severities: a Minor section holding only a <details> list is empty" check "parse_findings: a fenced <details> example in a fold does not keep the fold open past its </details>" \ "$(printf '### Issues\n#### Minor\n<details><summary>Fixed (1)</summary>\n\n- x\n ```html\n <details>\n ```\n</details>\n#### Critical\n- boom\n' | jq -c -Rs -L "$LIB_DIR" 'include "records"; parse_findings | map(.severity + " " + .title)')" '["critical boom"]' -check "parse_findings: a fixed item quoting </details> in code does not close the fold" \ +check "parse_findings: a fixed item quoting </details> in code does not close the fold: F1 and F2 stay fixed" \ "$(printf '### Issues\n#### Critical\n<details><summary>Fixed (2)</summary>\n\n- **F1** — closes with `</details>`.\n- **F2** — other.\n</details>\n- c\n' | - jq -c -Rs -L "$LIB_DIR" 'include "records"; parse_findings | map(.title)')" '["c"]' + jq -c -Rs -L "$LIB_DIR" 'include "records"; parse_findings | map(.title // "\(.id) \(.status)")')" '["F1 fixed","F2 fixed","c"]' # A heading may start with up to 3 spaces (CommonMark), for the Issues section and its end alike. check "parse_findings: an indented Issues heading and an indented closing heading bound the section" \ "$(printf '#### Important context\n- ctx\n ### Issues\n #### Important\n- a\n ### Notes\n#### Minor\n- b\n' | jq -c -Rs -L "$LIB_DIR" 'include "records"; parse_findings | map(.title)')" '["a"]' check "parse_findings: 4 spaces are no heading" \ "$(printf '### Issues\n#### Minor\n- a\n ### Notes\n- b\n' | jq -c -Rs -L "$LIB_DIR" 'include "records"; parse_findings | map(.title)')" '["a","b"]' -respects() { jq -c -n -L "$LIB_DIR" --argjson b "$1" 'include "records"; $b | block_respects_empty(["critical"])'; } +respects() { # round 1 block -> block_respects_empty, judged as stored + jq -c -n -L "$LIB_DIR" --argjson b "$1" 'include "records"; $b | block_respects_empty(["critical"]; []; null; null)' +} check "block_respects_empty: an open Critical where the Markdown has none" "$(respects '[{"severity":"Critical","title":"x"}]')" false -check "block_respects_empty: fixed, declined and later Criticals are stored as new: open" \ +check "block_respects_empty: round 1 fixed, declined and later Criticals are stored as new: open" \ "$(respects '[{"severity":"critical","status":"fixed"}]'),$(respects '[{"severity":"critical","status":"declined"}]'),$(respects '[{"severity":"critical","later":true}]')" \ false,false,false check "block_respects_empty: other severities are fine" "$(respects '[{"severity":"important"},{"severity":"minor"}]')" true -# Writing from the model's block stores every entry as new (block_*), so fixed and declined entries are judged open. +# Writing from the model's block in round 1 stores every entry as new (block_*: entry_outcome), so fixed and declined +# entries are judged open. fixed_crit='[{"severity":"critical","status":"fixed","file":"a.go","line":10},{"severity":"critical","status":"declined"}]' check "block_*: fixed and declined entries from the model's block are judged open" \ - "$(jq -c -n -L "$LIB_DIR" --argjson b "$fixed_crit" 'include "records"; $b | [block_respects_empty(["critical"]), block_covers_markdown([{severity: "critical", file: "a.go", line: 10}])]')" \ + "$(jq -c -n -L "$LIB_DIR" --argjson b "$fixed_crit" 'include "records"; $b | [block_respects_empty(["critical"]; []; null; null), block_covers_markdown([{severity: "critical", file: "a.go", line: 10}]; null; null)]')" \ '[false,true]' stored=$(build_record '{"round":1,"code_review":true}' '[{"severity":"critical","status":"fixed","later":true,"title":"x"}]' null) check "build_record: stores a fixed, later entry as the checks judge it: new and open" \ "$(jq -c '[.findings[0].status, .counts.open_blocking, .later]' <<<"$stored")" '["new",1,[]]' +# From round 2 the block is judged as entry_outcome stores it: an earlier Critical marked fixed, or declined with a +# reason, is not open. +for st in '"status":"fixed"' '"status":"declined","reason":"by design"'; do + check "block checks: round 3, F1 {$st} is not open" \ + "$(jq -c -n -L "$LIB_DIR" --argjson base "$prev2" --argjson b "[{\"id\":\"F1\",$st}]" 'include "records"; + $b | [block_covers_markdown([{severity: "critical"}]; $base; null), block_respects_empty(["critical"]; []; $base; null)]')" \ + '[false,true]' +done + +# Round 3 on prev2, delta t.ts: an Important marked Later in t.ts is promoted to a finding. Under an empty Important +# section, the Later list showing it (same file, the same line or a range holding it, or no line on either side) is +# no contradiction; one that shows another file or line is. +promoted='[{"severity":"important","title":"x","file":"t.ts","line":7,"later":true}]' +later_md() { printf '### Issues\n#### Important\n*(none found)*\n\n<details><summary>Later (1)</summary>\n\n- **`%s`** — x.\n\n</details>\n' "$1"; } +respects_later() { # <Later item> -> block_respects_empty for the promoted entry + later_md "$1" | jq -c -Rs -L "$LIB_DIR" --argjson b "$promoted" --argjson base "$prev2" --argjson meta "$meta2" 'include "records"; + . as $md | $b | block_respects_empty($md | empty_severities; $md | later_items; $base; later_files($meta.mode; $meta.delta_files))' +} +check "later_items: the Later list's items, with a range's end" \ + "$(later_md 't.ts:5–9' | jq -c -Rs -L "$LIB_DIR" 'include "records"; later_items')" '[{"file":"t.ts","line":5,"line_end":9}]' +check "block_respects_empty: a promoted entry the Later list shows (t.ts:7, t.ts:5–9, t.ts) is no contradiction" \ + "$(respects_later t.ts:7),$(respects_later 't.ts:5–9'),$(respects_later t.ts)" true,true,true +check "block_respects_empty: a promoted entry the Later list does not show (t.ts:8, u.ts:7) is one" \ + "$(respects_later t.ts:8),$(respects_later u.ts:7)" false,false +check "block_promotes: a Later entry in a touched file, not one outside it, nor a status-only earlier ID" \ + "$(jq -c -n -L "$LIB_DIR" --argjson base "$prev2" --argjson meta "$meta2" 'include "records"; + later_files($meta.mode; $meta.delta_files) as $l + | [([{severity: "important", title: "x", file: "t.ts", later: true}] | block_promotes($base; $l)), + ([{severity: "important", title: "x", file: "z.ts", later: true}] | block_promotes($base; $l)), + ([{id: "F1", status: "open", later: true}] | block_promotes($base; $l))]')" '[true,false,false]' + +# ── entry_outcome: one decision for the record builder and the block checks ──────────────────────────────── +# Round 3 on prev2 (F1 Critical open, a.ts:1), incremental, delta t.ts: stored_findings says what build_record stores. +judged() { # <block> -> [status, severity] per stored entry, then the record's [status, severity] per block entry + jq -c -n -L "$LIB_DIR" --argjson b "$1" --argjson base "$prev2" --argjson meta "$meta2" 'include "records"; + [$b | stored_findings($base; later_files($meta.mode; $meta.delta_files))[] | [.status, .severity]], + # The record: the findings from the block (new, or an ID the block gives), not the carried ones. + (build_record($meta; $b; $base) | [(.findings[] | select(.status == "new" or (.id as $id | [$b[].id] | index([$id]))) + | [.status, .severity]), (.later[] | ["later", .severity])])' | + paste -sd' ' - +} +check "entry_outcome: declined with a reason is declined, for both" \ + "$(judged '[{"id":"F1","status":"declined","reason":"by design"}]')" '[["declined","critical"]] [["declined","critical"]]' +check "entry_outcome: declined without a reason is open and keeps its severity, for both" \ + "$(judged '[{"id":"F1","status":"declined","severity":"minor"}]')" '[["open","critical"]] [["open","critical"]]' +check "entry_outcome: a Later Critical is new, for both" \ + "$(judged '[{"severity":"critical","title":"x","file":"z.ts","later":true}]')" '[["new","critical"]] [["new","critical"]]' +check "entry_outcome: a Later Minor outside the delta is Later, left out of the stored findings" \ + "$(judged '[{"severity":"minor","title":"x","file":"z.ts","later":true}]')" '[] [["later","minor"]]' +check "entry_outcome: no Later in a full round" \ + "$(jq -c -n -L "$LIB_DIR" --argjson base "$prev2" 'include "records"; + [{severity: "minor", title: "x", file: "z.ts", later: true}] | stored_findings($base; later_files("full"; ["t.ts"])) + | map(.status)')" '["new"]' +check "entry_outcome: a status-only entry takes the base's severity and location" \ + "$(jq -c -n -L "$LIB_DIR" --argjson base "$prev2" 'include "records"; + [{id: "F1", status: "open"}] | stored_findings($base; null) | map([.status, .severity, .file, .line])')" \ + '[["open","critical","a.ts",1]]' +check "entry_outcome: the first entry for an ID is the one stored" \ + "$(jq -c -n -L "$LIB_DIR" --argjson base "$prev2" 'include "records"; + [{id: "F1", status: "fixed"}, {id: "F1", status: "open"}] | stored_findings($base; null) | map(.status)')" \ + '["fixed"]' # ── normalize_ready ───────────────────────────────────────────────────────── for pair in "Yes=yes" "yes.=yes" "Yes with fixes=yes-with-fixes" "Yes, with fixes=yes-with-fixes" \ @@ -414,6 +714,17 @@ check "marker cap: no room even for the minimal marker, no marker" "$(marker_lin check "marker cap: round.json keeps everything" "$(jq -c '[(.findings | length), (.later | length)]' "$tmp/big.json")" \ "[4,1]" +# A record with an unknown blocker count (null counts, as a round whose record could not be built posts) keeps that +# signal in its minimal marker; one with a known count, or a Rethink, does not. +jq -c '.counts.open_blocking = null' "$tmp/big.json" >"$tmp/unknown.json" +pad_to 59780 +check "marker cap: an unknown count stays in the minimal marker" \ + "$(marker_record "$(generated "$(marker_line "$tmp/unknown.json" "$tmp/body.md")")")" \ + '{"schema":1,"round":2,"findings_dropped":true,"last_ids":{"F":4,"L":0},"counts":{"open_blocking":null}}' +check "marker_counts_unknown: an explicit null count only" \ + "$(jq -c -L "$LIB_DIR" 'include "records"; map(marker_counts_unknown)' <<<'[{"counts": {"open_blocking": null}}, + {"counts": {"open_blocking": 0}}, {"counts": {}}, {}, {"counts": null}]')" '[true,false,false,false,false]' + # A marker is read as it is only with the full counts every marker_line step but the minimal one writes. check "complete_marker: a Rethink and full counts; not partial, inconsistent or minimal ones" \ "$(jq -c -L "$LIB_DIR" 'include "records"; map(complete_marker)' <<<'[{"code_review": false}, @@ -422,6 +733,52 @@ check "complete_marker: a Rethink and full counts; not partial, inconsistent or {"counts": {"open_blocking": 2, "critical": 0, "important": 1, "minor": 0}}, {"schema": 1, "round": 2, "findings_dropped": true}]')" \ '[true,true,false,false,false,false]' +build_record "$meta2" "$reply" "$prev2" >"$tmp/round3.json" +# The posted review shows every title and file, so the marker keeps them all. +body3=$(jq -r '[.findings[], .later[] | (.file // empty), (.title // empty)] | join("\n")' "$tmp/round3.json") +line=$(marker_line "$tmp/round3.json" "$body3") +check "marker: statuses and later round trip" "$(marker_record "$(generated "$line")" | jq -S .)" \ + "$(jq -S . "$tmp/round3.json")" +check "marker: no -- with statuses" "$(grep -c -- '--' <<<"${line:4:${#line}-8}" || true)" 0 +line=$(marker_line "$tmp/round3.json" "$body3$(head -c 59000 /dev/zero | tr '\0' x)") +check "marker: near the cap, last ids and counts stay" \ + "$(marker_record "$(generated "$line")" | jq -c '[.last_ids, .counts.unverified, has("later")]')" '[{"F":7,"L":7},1,false]' + +# ── progress_line ─────────────────────────────────────────────────────────── +dec='{"label":"converging"}' +check "progress: all counts" "$(progress_line "$(cat "$tmp/round3.json")" "$prev2" "$dec")" \ + "### Round 3 · since round 2 +1 fixed · 1 still open · 1 regressed · 2 new (1 in the new commits) · 1 declined · 1 for later · 1 not re-checked \ +· open blocking: 4 (was 3) · loop: converging" +rec=$(r3 '[{"id":"F1","status":"fixed"},{"id":"F4","status":"open"},{"id":"F5","status":"open"}, + {"severity":"minor","title":"n"}]') +check "progress: zero counts dropped" "$(progress_line "$rec" "$(jq -c 'del(.counts)' <<<"$prev2")" \ + '{"label":"nit-loop"}' | tail -n 1)" "1 fixed · 2 still open · 1 new · open blocking: 1 · loop: nit loop" +check "progress: unverified, no label" "$(progress_line "$(r3 '[]')" "$prev2" '{"label":null}' | tail -n 1)" \ + "3 not re-checked · open blocking: 2 (was 3)" +check "progress: still open excludes unverified" "$(progress_line "$(r3 '[{"id":"F1","status":"open"}]')" "$prev2" \ + "$dec" | tail -n 1)" "1 still open · 2 not re-checked · open blocking: 2 (was 3) · loop: converging" +rec=$(build_record "$(jq -c '.mode = "full" | .mode_reason = "the previous head is gone"' <<<"$meta2")" \ + '[{"id":"F1","status":"fixed"},{"id":"F4","status":"fixed"},{"id":"F5","status":"fixed"}]' "$prev2") +check "progress: full with a reason" "$(progress_line "$rec" "$prev2" '{"label":"ready"}' | tail -n 1)" \ + "3 fixed · open blocking: 0 (was 3) · loop: ready · full review (the previous head is gone)" +check "progress: full without a reason" "$(progress_line "$(jq -c '.mode_reason = null' <<<"$rec")" "$prev2" \ + '{"label":"ready"}' | tail -n 1)" "3 fixed · open blocking: 0 (was 3) · loop: ready · full review" +check "progress: no previous record, nothing" "$(progress_line "$rec" null "$dec")" "" +# A later round parsed from a Markdown with no severity section: its counts are null, so the line says unknown, and +# the reader takes no blocker count from it. +rec=$(build_record "$(jq -c '.unknown_counts = true' <<<"$meta2")" '[]' "$prev2") +unknown_line=$(progress_line "$rec" "$prev2" '{"label":"unknown"}') +check "progress: no severity section, open blocking unknown, never 0" \ + "$(tail -n 1 <<<"$unknown_line")" "3 not re-checked · open blocking: unknown (was 3) · loop: unknown" +check "progress: an unknown count reads back as none" \ + "$(printf '%s\n\nLooks fine.\n' "$unknown_line" | jq -c -Rs -L "$LIB_DIR" 'include "records"; [later_round_body, progress_blocking]')" \ + '[true,null]' +rec=$(build_record "$(jq -c '.code_review = false | .approach = "rethink"' <<<"$meta2")" '[]' "$prev2") +check "progress: rethink" "$(progress_line "$rec" "$prev2" "$dec")" \ + "### Round 3 · since round 2 +code review skipped: the approach needs a rethink" + # ── backfill_record ───────────────────────────────────────────────────────── pr='{"host":"github.com","owner":"o","repo":"r","number":7}' review() { # fixture [state] -> GitHub REST review JSON @@ -488,6 +845,60 @@ check "empty_severities: a last section with only none found stays empty: the fo <<<"$boundary"$'\n### Issues\n#### 🚨 Critical\n*(none found)*\n\n'"$tool_footer")" '["critical"]' rec=$(backfill_record "$(review bullets.md)" null 1 "$pr") +rec2=$(backfill_record "$(review numbered.md)" "$rec" 2 "$pr") +check "backfill after backfill: counts its own findings only, nothing carried" \ + "$(jq -c '[.counts.open_blocking, .counts.unverified, ([.findings[] | select(.unverified)] | length)]' <<<"$rec2")" "[4,0,0]" +check "backfill after backfill: IDs continue, previous head kept" \ + "$(jq -r '[.findings[0].id == "F\($n + 1)", .previous_head_sha == $h] | all' --argjson n "$(jq '[.findings[].id[1:] | tonumber] | max' <<<"$rec")" \ + --arg h "$(jq -r .head_sha <<<"$rec")" <<<"$rec2")" true check "backfill bullets: ready" "$(jq -r .ready <<<"$rec")" yes-with-fixes - +has_list() { jq -L "$LIB_DIR" 'include "records"; has_findings_list' <<<"$1"; } +check "backfill: a standalone review keeps its findings list" "$(has_list "$rec")" true + +# A later round posted without its marker: its record carried an Important finding the body does not show (omitted +# by the model, so not re-checked). Read back from the Markdown alone, it must not look like a verified empty list. +prev1=$(jq -nc '{round: 1, head_sha: "aaa", counts: {open_blocking: 1}, findings: [{id: "F1", severity: "important", + status: "new", first_round: 1, file: "a.ts", line: 1, title: "one"}]}') +r2=$(build_record "$(jq -c '.round = 2 | .mode = "incremental" | .ready = "yes"' <<<"$meta")" \ + '[{"severity":"minor","file":"m.ts","line":2,"title":"Tiny nit"}]' "$prev1") +check "later round without marker: setup, the record carries F1" \ + "$(jq -c '[.counts.open_blocking, .counts.unverified, .last_ids.F]' <<<"$r2")" '[1,1,2]' +later_body() { # <filler length>: the round 2 body as posted, with a filler paragraph before the Assessment + echo '<!-- gh-pr-review generated -->' + progress_line "$r2" "$prev1" '{"label":"early"}' + printf '\n### Issues\n\n#### 🚨 Critical (Must Fix Before Merge)\n\n*(none found)*\n\n' + printf '#### ⚠️ Important (Should Fix)\n\n*(none found)*\n\n#### 💡 Minor (Nice to Have)\n\n' + printf -- '- **F2 · `m.ts:2`** — Tiny nit.\n\n' + head -c "$1" /dev/zero | tr '\0' x + printf '\n\n### Assessment\n\n**Ready to merge?** Yes\n' +} +printf '%s\n' "$r2" >"$tmp/r2.json" +# The review's case, 59,776 characters: only the minimal marker fits, and it says the findings list is gone. +later_body $((59776 - $(later_body 1 | jq -Rs length) + 1)) >"$tmp/later-padded.md" +check "later round, 59,776 characters: setup" "$(jq -Rs length "$tmp/later-padded.md")" 59776 +tail -n +2 "$tmp/later-padded.md" >"$tmp/r2-review.md" +line=$(marker_line "$tmp/r2.json" "$tmp/r2-review.md") +check "later round, 59,776 characters: the minimal marker, findings dropped" \ + "$(marker_record "$(generated "$line")" | jq -c '[.round, .findings_dropped, has("findings")]')" '[2,true,false]' +# Bigger still, no marker fits at all: the round is read back from its Markdown. +later_body $((59960 - $(later_body 1 | jq -Rs length) + 1)) >"$tmp/later-padded.md" +check "later round without marker: setup, a 59,960-character body" "$(jq -Rs length "$tmp/later-padded.md")" 59960 +tail -n +2 "$tmp/later-padded.md" >"$tmp/r2-review.md" +line=$(marker_line "$tmp/r2.json" "$(head -c 300 "$tmp/r2-review.md")") +check "later round without marker: setup, the marker fits a short review" "${line:0:24}" "<!-- gh-pr-review:round " +check "later round without marker: setup, no room for any marker" "$(marker_line "$tmp/r2.json" "$tmp/r2-review.md")" "" +rec=$(backfill_record "$(jq -n --rawfile body "$tmp/later-padded.md" '{body: $body, commit_id: "bbb", + submitted_at: "2026-01-03T00:00:00Z", user: {login: "rev"}, state: "APPROVED"}')" "$prev1" 2 "$pr") +check "later round without marker: no findings list" "$(has_list "$rec")" false +check "later round without marker: the blocking count of the progress line, IDs covered" \ + "$(jq -c '[.findings_dropped, .counts.open_blocking, .ready_overridden, .last_ids.F, has("findings")]' <<<"$rec")" \ + '[true,1,true,2,false]' +check "later round without marker: the next round carries nothing it cannot know" \ + "$(build_record "$meta2" '[]' "$rec" | jq -c '[.findings, .counts.open_blocking]')" '[[],0]' +printf '### Issues\n\n- **`a.ts:1`** — x\n\n<details><summary>Later (1)</summary>\n\n- **[e.ts:5]** — slow.\n\n</details>\n' \ + >"$tmp/folded.md" +rec=$(backfill_record "$(jq -n --rawfile body "$tmp/folded.md" '{body: $body}')" null 2 "$pr") +check "later round without marker: a folded Later section is enough" "$(has_list "$rec")" false + +finished=true exit "$fail" diff --git a/tests/rounds.sh b/tests/rounds.sh index 3b3c366..fa2a70b 100644 --- a/tests/rounds.sh +++ b/tests/rounds.sh @@ -5,6 +5,9 @@ set -euo pipefail root=$(cd "$(dirname "$0")/.." && pwd) stub=$(mktemp -d) +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap '[[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 nl=$'\n' @@ -209,6 +212,15 @@ out=$(rounds https://h/o/r/pull/1 --json) && rc=0 || rc=$? expect "approach bullets under Important context, no marker: 0 blockers" \ '[[ $rc == 0 && $(jq -c "[.records[0].source, .records[0].counts.open_blocking, .decision.label]" <<<"$out") == "[\"backfill\",0,\"ready\"]" ]]' minimal='{"schema":1,"round":1,"findings_dropped":true,"last_ids":{"F":0,"L":0}}' +# A later round's Markdown leaves out the findings it carried: with a minimal marker, its blocking count is the +# progress line's (backfill_record), not the Markdown's. +later_md="### Round 2 · since round 1${nl}1 still open · 1 not re-checked · open blocking: 2 (was 2)${nl}${nl}#### 🚨 Critical${nl}*(none found)*${nl}" +later_md+="#### ⚠️ Important${nl}- **F1 · \`a.js:1\`** — boom.${nl}${nl}**Ready to merge?** No" +jq -n --arg b "<!-- gh-pr-review generated -->${nl}<!-- gh-pr-review:round ${minimal/\"round\":1/\"round\":2} -->${nl}${later_md}" \ + '[{body: $b, commit_id: "c2", submitted_at: "2026-03-01T00:00:00Z", user: {login: "me"}}]' >"$stub/reviews.json" +out=$(rounds https://h/o/r/pull/1 --json) && rc=0 || rc=$? +expect "a minimal marker on a later round: blocking from its progress line, not the Markdown" \ + '[[ $rc == 0 && $(jq -c ".records[0] | [.counts.open_blocking, .findings_dropped]" <<<"$out") == "[2,true]" ]]' jq -n --arg b "<!-- gh-pr-review generated -->${nl}<!-- gh-pr-review:round ${minimal} -->${nl}### Approach${nl}**Approach:** Rethink" \ '[{body: $b, commit_id: "c1", submitted_at: "2026-03-01T00:00:00Z", user: {login: "me"}}]' >"$stub/reviews.json" out=$(rounds https://h/o/r/pull/1 --json) && rc=0 || rc=$? @@ -259,6 +271,61 @@ del(.counts.minor)~[3,0,"","nit-loop",30] del(.last_ids) | .counts = {critical: 0, important: 5}~[3,0,"","nit-loop",32] del(.last_ids, .counts) | .findings |= map(if .id == "F28" then .status = "fixed" else . end)~[3,0,"","nit-loop",32] T + +# A later round's marker (#9). Round 2 stored F1 (Critical) as fixed and F2 as declined with a reason: not open. F3 +# (Important) and F4 (Critical) are carried, open and unverified: the Markdown leaves them out (its Critical section +# says none), yet they still count. +r1_marker='{"schema":1,"round":1,"code_review":true,"approach":"sound","ready":"no","last_ids":{"F":4,"L":0}, + "counts":{"open_blocking":4,"critical":2,"important":2,"minor":0,"new":4,"fixed":0,"declined":0,"regressed":0}}' +r2_marker='{"schema":1,"round":2,"mode":"incremental","code_review":true,"approach":"sound","ready":"no","findings":[ + {"id":"F1","severity":"critical","status":"fixed","first_round":1,"in_delta":false,"file":"a.go","line":1}, + {"id":"F2","severity":"important","status":"declined","first_round":1,"in_delta":false,"file":"b.go","line":2}, + {"id":"F3","severity":"important","status":"open","first_round":1,"in_delta":false,"file":"c.go","line":3,"unverified":true}, + {"id":"F4","severity":"critical","status":"open","first_round":1,"in_delta":false,"file":"d.go","line":4,"unverified":true}, + {"id":"F5","severity":"important","status":"new","first_round":2,"in_delta":true,"file":"e.go","line":5}], + "later":[{"id":"L1","severity":"minor","file":"z.go","line":9}],"last_ids":{"F":5,"L":1}, + "counts":{"open_blocking":3,"critical":1,"important":2,"minor":0,"new":1,"fixed":1,"declined":1,"regressed":0,"later":1,"unverified":2}}' +r2_md="### Round 2 · since round 1${nl}1 fixed · 1 new · 1 declined · 1 for later · 2 not re-checked · open blocking: 3 (was 4)" +r2_md+=" · loop: converging${nl}${nl}### Issues${nl}${nl}#### 🚨 Critical (Must Fix Before Merge)${nl}*(none found)*${nl}${nl}" +r2_md+="#### ⚠️ Important (Should Fix)${nl}${nl}- **\`e.go:5\`** — five.${nl}${nl}#### 💡 Minor (Nice to Have)${nl}" +r2_md+="*(none found)*${nl}${nl}<details><summary>Fixed since the last round (2)</summary>${nl}${nl}- **F1** — fixed.${nl}" +r2_md+="- **F2** — declined: \"by design\"${nl}${nl}</details>${nl}${nl}<details><summary>Later (1)</summary>${nl}${nl}" +r2_md+="- **\`z.go:9\`** — later.${nl}${nl}</details>${nl}${nl}**Ready to merge?** No" +later2() { # jq filter on round 2's marker -> reviews.json: round 1 (4 blockers), then round 2 + jq -n --argjson m1 "$r1_marker" --argjson m2 "$(jq -c "$1" <<<"$r2_marker")" --arg md "$r2_md" ' + def review($m; $md; $c; $t): {commit_id: $c, submitted_at: $t, user: {login: "me"}, + body: ("<!-- gh-pr-review generated -->\n<!-- gh-pr-review:round " + ($m | tojson) + " -->\n" + $md)}; + [review($m1; "x"; "c1"; "2026-03-01T00:00:00Z"), review($m2; $md; "c2"; "2026-03-02T00:00:00Z")]' \ + >"$stub/reviews.json" +} +round2() { # [open_blocking, critical, important, fixed, declined, findings_dropped, statuses F1–F5, last_ids.L, floor] + jq -c -L "$root/lib" 'include "records"; [.records[1] | .counts.open_blocking, .counts.critical, .counts.important, + .counts.fixed, .counts.declined, (.findings_dropped // false), ([.findings[]?.status] | join(" ")), .last_ids.L] + + [(.records | id_floor | [.F, .L])]' <<<"$out" +} +# The full marker is read as it is. Any partial marker (complete_marker) is read from the Markdown: 1 Important (F5, +# new), and the progress line's open blocking count, 3, so the carried F3 and F4 still count; F1 and F2 are not open, +# and a partial marker's fixed and declined history is not kept. The list is dropped, and its F and L IDs stay (in +# last_ids, from the later list, or, with neither, the Later item shown in the Markdown reserves L1). Each line: the +# marker filter, "~", then round2's output. +while IFS='~' read -r filter want; do + later2 "$filter" + out=$(rounds https://h/o/r/pull/1 --json) && rc=0 || rc=$? + expect "later round 2, $filter: $want" '[[ $rc == 0 && $(round2) == "$want" ]]' +done <<'T' +.~[3,1,2,1,1,false,"fixed declined open open new",1,[5,1]] +del(.counts)~[3,0,1,0,0,true,"",1,[5,1]] +del(.counts.open_blocking)~[3,0,1,0,0,true,"",1,[5,1]] +.counts = {critical: 0, important: 1}~[3,0,1,0,0,true,"",1,[5,1]] +.counts.open_blocking = 1~[3,0,1,0,0,true,"",1,[5,1]] +del(.counts, .last_ids)~[3,0,1,0,0,true,"",1,[5,1]] +del(.counts) | .findings |= map(select(.unverified | not))~[3,0,1,0,0,true,"",1,[5,1]] +del(.counts, .last_ids) | .findings |= map(select(.unverified | not))~[3,0,1,0,0,true,"",1,[5,1]] +del(.counts, .later) | .findings |= map(select(.unverified | not))~[3,0,1,0,0,true,"",1,[5,1]] +.counts = {critical: 0, important: 1} | .findings = []~[3,0,1,0,0,true,"",1,[5,1]] +{schema: 1, round, findings_dropped: true, last_ids}~[3,0,1,0,0,true,"",1,[5,1]] +{schema: 1, round, findings_dropped: true}~[3,0,1,0,0,true,"",1,[5,1]] +T # The same round under every marker shape marker_line emits, each the largest that fits as the review grows: full, # without titles, without locations, without the Later list, without findings, minimal. Each reads back with the full # marker's counts, ID floor (F30) and next decision, and the next round's first new finding is F31; the minimal @@ -411,4 +478,5 @@ echo '[]' >"$stub/comments.json" out=$(rounds) && rc=0 || rc=$? expect "rounds: a PR is required" '[[ $rc != 0 && $out == *Usage* ]]' +finished=true exit "$fail" diff --git a/tests/verdict.sh b/tests/verdict.sh index 810d524..a407f6a 100644 --- a/tests/verdict.sh +++ b/tests/verdict.sh @@ -4,6 +4,9 @@ set -euo pipefail root=$(cd "$(dirname "$0")/.." && pwd) # shellcheck source=lib/verdicts.sh source "$root/lib/verdicts.sh" +# The script must reach its end: Bash 3.2 can stop on an error inside an EXIT trap with status 0. +finished=false +trap '[[ $finished == true ]] || { echo "FAIL stopped before the end"; exit 1; }' EXIT fail=0 check() { # name label text expected @@ -30,4 +33,5 @@ check "approach notes prose ignored" 'Approach' $'**Approach:** Rethink\n\nAppro check "approach rationale prose ignored" 'Approach' $'**Approach:** Sound\n\n**Approach rationale:** Rethink is unnecessary' 'sound' check "merge criteria prose ignored" 'ready to merge' $'**Ready to merge?** No\nReady to merge criteria: yes' 'no' check "plain label without bold" 'Approach' 'Approach: Questionable' 'questionable' +finished=true exit "$fail"