Skip to content

Keep run files in one state folder per PR, with a lock - #13

Merged
catalan-adobe merged 21 commits into
mainfrom
review-state-folder
Nov 28, 2026
Merged

catalan-adobe merged 21 commits into
mainfrom
review-state-folder

Conversation

@catalan-adobe

@catalan-adobe catalan-adobe commented Nov 28, 2026 •

Copy link
Copy Markdown
Owner

PR 3a of review tracking: one state folder per PR, with a lock. Task 1 of docs/superpowers/plans/2026-11-26-review-tracking-pr3-local-worktrees.md. This PR also adds the plan's "Changes after PRs #8, #9 and #10" section, which splits PR 3 into four smaller PRs: 3a, 3b (#14, a read-only reviewer), 3c (local clones and review worktrees) and 3d (gc, docs, a real run).

What changes

  • Run files live in one state folder per PR: ${GH_PR_REVIEW_STATE:-${XDG_STATE_HOME:-~/.local/state}/gh-pr-review}/<host>/<owner>/<repo>/<N>/. Before, they went into pr-review-sessions/ under whatever folder the command ran from. Old folders are left alone.

  • Run folder names:

    • run-<UTC time> while the run works.
    • round-<K> after a post, where K is the .round of the posted record (the number left after the final re-read).
    • preview-<time> for a completed --no-post run.
    • A run that exits 6, fails or isn't confirmed keeps run-…. If round-<K> already exists, it keeps run-… with a warning.
    • The printed session path is the final one.
  • A per-PR lock (lock/ with a pid file) once the loop check decides to run. A second run of the same PR is refused while that PID lives; a dead PID's lock is taken over with a note. --check and rounds don't lock. The lock covers this machine; Record each review round, and stop review loops that don't converge #8's exit-6 check still covers other machines and accounts.

  • loop-check.md in the PR's state folder whenever the loop check stops a run or --check reports a stop.

  • lib/config.sh reads ~/.config/gh-pr-review/config.json (config_get). lib/state.sh adds pr.json get/set. Nothing uses either yet; 3c will.

  • Path safety: pr_state_dir refuses empty, ., .. or /-containing parts, so a crafted URL can't put the folder outside the state root.

  • Also, before review: host, owner and repo are lowercased in the state path, so Owner/Repo and owner/repo share one folder and lock. The lock's pid is written atomically, and a lock folder without a pid yet gets up to 2 s before it counts as stale. The config file must be a JSON object, and an empty-string value gives the default.

Tests

  • New tests/state.sh (43 checks): config, paths, the lock (taken, refused, taken over, released on a failing exit), pr.json, run folder names, loop-check.md.
  • tests/flow.sh now uses a state folder under the stub home. New checks: round-1/, preview-…/, exit 6 keeping run-…, a live lock refusing a second run, a stale lock taken over, --check taking no lock, and loop-check.md on a stop.

All tests pass on macOS (bash 5 and 3.2) and Ubuntu 24.04, and shellcheck and shfmt are clean. Diff: 7 files, +368 −18, plus the plan section (+39).

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approach

What it does: Moves review artifacts from the caller’s working directory into one state folder per PR. A local lock prevents overlapping runs; GitHub still determines which rounds were posted.

Fit with the repo: The state change fits Task 1 of docs/superpowers/plans/2026-11-26-review-tracking-pr3-local-worktrees.md. The concern is the new dependency table: 3c (shared worktrees) needs only 3a (state), not 3b (reviewer guards). The base design explains why those guards matter: a worktree shares “refs, objects, stash and config with my working clone.” This PR still uses a throwaway clone, but its plan permits shipping 3c without the guards.

Strongest case for the approach as built: lib/state.sh owns the folder and lock lifecycle without changing review or round-history logic. The PR says the lock “complements the exit-6 check,” and the code preserves that distinction. Stacked PR #16 already uses the state folder and pr.json.

Alternatives: Keep the split, but make enabling shared worktrees depend on #14. That costs merge ordering, not implementation rework. As written, either PR can land first, leaving a window where the reviewer runs against a user’s clone without the planned guards.

Questions for the author: Can the plan make #14 a prerequisite for enabling shared worktrees? With that gate explicit, I’d call this Sound.

Missing context: None.

Approach: Questionable

Strengths

  • gh-pr-review:1533–1559 finalizes the directory only after the post succeeds or is independently confirmed. An ambiguous post keeps its run-… artifacts rather than presenting them as a posted round.
  • lib/config.sh:18–25 distinguishes an invalid config from a missing setting and preserves meaningful values such as false and 0.
  • tests/flow.sh:304–323 checks the user-visible lock behavior: a refused run makes no model call or post, and --check leaves the live lock alone.

Issues

🚨 Critical (Must Fix Before Merge)

(none found)

⚠️ Important (Should Fix)

  • [lib/state.sh:42] — Two processes can both take over the same stale lock. Both can read the dead PID before either removes the directory. After the first process creates its replacement lock and starts reviewing, the second can delete that live replacement based on its earlier observation. Atomic PID publication does not protect this check-and-delete sequence.

    • Use a locking primitive that releases ownership on process death, or serialize stale-lock recovery and revalidate ownership under that serialization. Add a two-contender test that asserts exactly one process enters the review.
  • [lib/state.sh:97] — Replacing mktemp -d with plain mkdir loses the owner-only permissions on each run. With umask 022 and a traversable state root, another local user can read the private checkout, PR discussion, and unposted --instructions. The old run directory was 0700 regardless of that umask.

    • Create the tool-owned PR and run directories with owner-only permissions from the outset, including when --check is the first command to create state. Test under umask 022.
  • [lib/state.sh:7] — A relative GH_PR_REVIEW_STATE changes meaning during the run. With GH_PR_REVIEW_STATE=./state, the lock and clone are created relative to the launch directory. After cd "$REVIEW_DIR" at gh-pr-review:487, context writes resolve inside the checkout, the later cd "$REVIEW_DIR" normally fails, and the exit trap looks in the wrong place for the lock.

    • Resolve the override against the launch directory once, before deriving any state paths, or reject a relative override before creating anything.

💡 Minor (Nice to Have)

  • [gh-pr-review:1561] — A fetch or context failure after run creation but before the first session: message at line 1119 leaves a run-… directory without reporting its path. Report the final session path on every exit after directory creation, preserving the exit status and lock cleanup.
  • [gh-pr-review:447] — Ctrl-D at the interactive loop-stop prompt makes the preceding read fail under set -e, skipping both loop_check_save and exit 3. Handle EOF as the default “No,” as the nothing-new prompt already does at line 429.
  • [lib/state.sh:80] — The pr.json helpers accept two concatenated JSON objects: pr_json_get can return two values for one key, and pr_json_set rewrites both objects without reporting corruption. Validate exactly one object before reading or updating, as config_get already does.
  • [lib/state.sh:122] — Saving a diagnosis truncates the previous loop-check.md before loop_text succeeds. A failed or interrupted --check can therefore erase the last complete diagnosis. Write to a unique sibling temporary file and rename it only on success; this also keeps concurrent unlocked checks from mixing their output.

Recommendations

Prioritize a contention test with two actual claimants and an end-to-end test using a non-default state root. The existing happy-path tests pass without exercising either failure mode. I ran tests/state.sh and tests/post-decision.sh successfully; tests/flow.sh did not finish within the 240-second review timeout.

Assessment

Ready to merge? No

Reasoning: The normal post and preview lifecycle follows the plan, but stale recovery can admit two reviewers, and the directory change regresses artifact privacy. Those issues and the relative-path failure should be fixed before later PRs rely on this state layer.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for the review. All items are addressed; each fix has a test that failed before it (except the docs change, and two lock tests noted below).

Approach question (make #14 a prerequisite for shared worktrees): yes. cfff879 changes the plan's dependency table: 3c needs 3a and 3b, and a review worktree is not the default until both pi passes run with the read-only git and the tripwire. Merge order: this PR and #14, then #16, which gets main merged in and wires tripwire_snapshot "$CLONE_DIR" "$REVIEW_DIR" around both passes.

Important

  • lib/state.sh:42 (two runs take over the same stale lock): 1a8a69d. A takeover now needs <PR folder>/lock.takeover (atomic mkdir); under it the run reads the lock again and replaces it only if it still holds the same dead PID (or, with no pid file, has stayed unchanged for 2 s). A run that saw the same dead PID then finds the new owner alive and is refused. A lock.takeover older than 5 s is from a run that died mid-takeover and is removed. Tests in tests/state.sh: two contenders with real background processes, exactly one enters (deterministic: the liveness check is slowed so both read the dead PID first; fails on the old code); three contenders, three trials; an abandoned takeover lock; a fresh one waited for. Remaining window: two runs judging the same abandoned lock.takeover stale at the same instant, with a precise interleave, after a crash during a millisecond-long takeover. Closing that fully needs a lock primitive macOS doesn't ship.
  • lib/state.sh:97 (run folders no longer 0700): a770ff6. New pr_state_mkdir creates missing folders under umask 077 and makes the PR folder 0700 even when it existed; run folders use mkdir -m 700. Every function that can create the folder (--check included) goes through it. Tests under umask 022, unit and flow.
  • lib/state.sh:7 (relative GH_PR_REVIEW_STATE): 9867867. state_root_pin makes it absolute against the launch folder once, right after the libraries load. Unit tests plus a flow run with GH_PR_REVIEW_STATE=./state: state in the launch folder, lock released, nothing written in the checkout.

Minor

  • gh-pr-review:1561 (run folder not named on early failures): 0ba1c66. Once the run folder exists, one EXIT handler prints Session: <path> with its final name (stderr after a failure) and releases the lock; the exit status is unchanged. The four messages that printed the path themselves no longer do, so it appears once. Test: a failed discussion fetch names the folder and releases the lock.
  • gh-pr-review:447 (Ctrl-D at the loop-stop prompt): f824b34. End of input is "No": the diagnosis is saved and the exit is 3. Tested through a pseudo-terminal (stdin from /dev/null is not a terminal, so the prompt never shows).
  • lib/state.sh:80 (concatenated objects in pr.json): 5332a06. New pr_json_check, the same rule as config_get; both helpers refuse such a file with the existing error, and pr_json_set leaves it as it is.
  • lib/state.sh:122 (loop-check.md truncated before the new text exists): 01059be. Written to a mktemp file next to it and moved in on success; a failure removes the temp file and warns.

All test files pass on macOS (bash 5) and ubuntu:24.04; tests/state.sh and the new flow tests also pass under /bin/bash 3.2. (The full tests/flow.sh stalls under 3.2 at the 60 KB review case on this branch's base too: that is what #15 fixes.) shellcheck and shfmt are clean.

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 2 · since round 1

6 fixed · 1 still open · 1 new (1 in the new commits) · open blocking: 1 (was 3) · loop: early

Approach

What it does: Keeps review artifacts in one private folder per PR and locks that folder during a review. GitHub remains the source of truth for posted rounds.

Fit with the repo: lib/state.sh owns the folder and lock lifecycle, as Task 1 of docs/superpowers/plans/2026-11-26-review-tracking-pr3-local-worktrees.md specifies. The revised plan resolves the round 1 concern: shared worktrees cannot become the default until both review passes use read-only git and the tripwire. The author confirms the merge order: “this PR and #14, then #16.”

Strongest case for the approach as built: Users can find a PR’s runs regardless of where they launched the command, without changing how either pass reviews code. This PR still uses a throwaway clone.

Alternatives: Keep the split. Combining state, guards, and worktrees would make a larger change without improving safety over the explicit merge order. I’d revisit that choice if #16 enabled shared worktrees before the guards.

Questions for the author: None.
Missing context: None.

Approach: Sound

Strengths

  • lib/state.sh:46 and lib/state.sh:153 restore owner-only access to the PR and run directories. The flow tests cover both a review and a --check that creates the state directory first.
  • gh-pr-review:479–488 centralizes final-path reporting and lock release. tests/flow.sh:241–245 checks the early discussion-fetch failure against the actual directory left on disk, the exit code, and the absence of the lock.

Issues

🚨 Critical (Must Fix Before Merge)

(none found)

⚠️ Important (Should Fix)

  • F1 · [lib/state.sh:78] — A slow, live process can still lose its takeover lock. Suppose run A has rechecked the dead PID and is delayed before the removal at line 85. After five seconds, run B can remove A’s lock.takeover based solely on its age, replace the stale primary lock, and start reviewing. When A resumes, line 85 removes B’s live lock, and A can enter too. Unlike the residual case described in the discussion, this requires neither contender to crash nor an abandoned takeover lock.
    • Don’t revoke takeover ownership based on elapsed time alone. Use a process-owned lock, or refuse the takeover with a recovery message when ownership cannot be established safely. Increasing the timeout only moves the race.

💡 Minor (Nice to Have)

  • [lib/state.sh:181] — If loop-check.md already exists as a directory, mv "$tmp" "$file" succeeds by putting the temporary file inside it. I verified that the save emits no warning and leaves loop-check.md/loop-check.md.<suffix> instead of a readable diagnosis. The previous direct write warned in this case. Reject a directory destination and use the existing warning and cleanup path.
Fixed since the last round (6)
  • F2 — PR and run directories are now 0700, including when --check creates state first.
  • F3 — A relative GH_PR_REVIEW_STATE is pinned to the launch directory before any checkout or state path is derived.
  • F4 — The EXIT handler reports the retained run directory even when the discussion fetch fails before the model runs.
  • F5 — Ctrl-D at the loop-stop prompt now means “No,” saves the diagnosis, and exits 3.
  • F6 — Both pr.json helpers reject concatenated objects, and the setter leaves the invalid file unchanged.
  • F7 — A failed diagnosis render no longer truncates the previous loop-check.md; replacement happens only after rendering succeeds.

Recommendations

Extend the contention test with an explicit synchronization point after stale-PID revalidation. Hold the first claimant there past the takeover timeout and assert that a second claimant cannot enter while the first still owns recovery. tests/state.sh, tests/post-decision.sh, and the selected state and loop-stop cases from tests/flow.sh passed on this checkout.

Assessment

Ready to merge? No

Reasoning: Six of the seven earlier findings are fixed. The remaining race still breaks the PR’s central guarantee: two live runs on this machine can both acquire the same PR’s lock.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for round 2, and for moving the approach to Sound. You were right that the remaining window was wider than I described: a slow but live run could lose its takeover lock to elapsed time. Both items are fixed, each with tests that failed on the code before. This branch also merges main, which now has #15 (5cc1ea5).

Important

  • F1, lib/state.sh:78 (a takeover lock revoked by age): b364f1a. Only a PID establishes who owns a lock, never its age.
    • lock.takeover holds its owner's PID, written to a temp name and moved in, as lock does.
    • Another run's takeover in progress: while its PID is alive, the run waits (about 10 s at most), then refuses. A takeover lock whose PID is gone (checked again that it still holds that PID), or that has no PID after about 2 s, is refused with the reason and the exact rm -rf <path> to run if no review of the PR is going. Nothing removes it automatically.
    • Primary lock: a dead PID is still taken over under lock.takeover, re-checked under it. A lock with no PID after about 2 s is now refused the same way instead of replaced (its run may be alive), and so is a pid file that isn't a number. path_age is gone.
    • Tests in tests/state.sh, following your recommendation: the first claimant is held right after its stale-PID re-check for 6 s (past the old 5 s); the second does not enter and the lock still holds the dead PID; after release exactly one enters. On the old code the second entered while the first was held, and both entered after the release. Plus: a takeover lock with a dead PID and one with no PID are refused with the recovery message and left in place (and once removed by hand, the next run takes over); a live takeover holder makes the run refuse after the wait; a pid-less primary lock is refused and left. The two- and three-contender tests still pass.
    • The README lock/ line says so.

Minor

  • lib/state.sh:181 (loop-check.md as a folder): 69ad063. A loop-check.md that exists and is not a regular file is not replaced: the existing warning, the temp file removed. Test: the warning, nothing written inside the folder, no temp file left.

All test files pass on macOS (bash 5) and ubuntu:24.04, and tests/flow.sh passes with the extension under /bin/bash 3.2 now that #15 is in; tests/state.sh also passes under 3.2. shellcheck and shfmt are clean.

@catalan-adobe catalan-adobe left a comment

Copy link
Copy Markdown
Owner Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Round 3 · since round 2

2 fixed · 3 new (1 in the new commits) · open blocking: 1 (was 1) · loop: converging · full review (the base branch was merged in with conflicts)

Approach

Unchanged since round 2: The lock-recovery and diagnosis fixes stay in lib/state.sh, and shared worktrees still depend on both review passes having read-only Git and the tripwire.

Approach: Sound

Strengths

  • lib/state.sh:96–130 no longer treats elapsed time as proof that a takeover owner died. tests/state.sh:222–253 pauses the first claimant after PID revalidation and checks that a second claimant cannot enter—the interleaving that mattered for F1.
  • lib/state.sh:222–229 preserves the previous diagnosis if rendering or replacement fails. tests/state.sh:338–345 also checks that a directory named loop-check.md is left empty, not merely that the command warns.
  • tests/flow.sh:256–260 checks the final session path, exit status, and lock cleanup together on an early failure, before either model pass runs.

Issues

🚨 Critical (Must Fix Before Merge)

(none found)

⚠️ Important (Should Fix)

  • [lib/state.sh:63] — The printed lock-recovery command does not shell-quote the path. With a state root such as $HOME/Projects Archive/reviews, pasting the suggested command passes $HOME/Projects as a separate operand to rm -rf. It can delete an unrelated directory while leaving the lock intact.
    • Print the path as one shell-escaped argument, for example with printf 'rm -rf -- %q\n' "$1". Test the resulting argument list with a path containing spaces, without running rm.

💡 Minor (Nice to Have)

  • [lib/state.sh:13] — A relative XDG_STATE_HOME still changes meaning after cd. This is distinct from the fixed GH_PR_REVIEW_STATE override: with that override unset and XDG_STATE_HOME=./state, the stubbed flow wrote context/pr-body.md inside the checkout, exited 1 at the second cd, and left the original lock behind.
    • Ignore a non-absolute XDG_STATE_HOME and use the default, as the XDG specification prescribes, or reject it before creating state.
  • [gh-pr-review:1530] — The oversized-review warning points to a round.json path that disappears after a successful post. In the no-room-for-marker flow, stderr reported run-…/round.json, but the file ended up at round-1/round.json. This is the case where the user needs the local record because GitHub does not have it.
    • Refer to round.json in the final Session: directory, or defer printing the absolute record path until after the rename.
Fixed since the last round (2)
  • F1 — A live takeover owner is no longer evicted by age; an unverifiable takeover is refused rather than removed.
  • F8 — A directory at loop-check.md now triggers a warning and temporary-file cleanup without writing inside it.

Recommendations

Keep the contention tests. For the remaining fixes, test the paths users actually consume: the recovery instruction must identify exactly one operand, and a record path advertised for later inspection must still exist after finalization. tests/state.sh, tests/post-decision.sh, and the targeted stubbed flows described above were run on this checkout.

Assessment

Ready to merge? Yes with fixes

Reasoning: Both findings from round 2 are fixed. The remaining merge concern is the copyable recovery command: a valid state path containing a space can turn removal of one lock into deletion of unrelated files.


Review generated by gh pr-review · model: azure-openai-direct/gpt-6.2-astra

@catalan-adobe

Copy link
Copy Markdown
Owner Author

Thanks for round 3. All three items are fixed, each with a test that failed before its fix.

  • Important, lib/state.sh:63 (the printed recovery command was not shell-quoted): 72e5921. lock_refuse prints rm -rf -- <path> with the path as one shell-escaped operand (printf %q, same output in /bin/bash 3.2 and bash 5). Test: a lock under …/Projects Archive/it's $HOME *; the printed command is split with eval "set -- …" in a subshell (rm is never run) and must give exactly -rf, --, <path>/lock; the lock stays. Before the fix the split failed on an unmatched quote.
  • Minor, lib/state.sh:13 (relative XDG_STATE_HOME): e7ef746. As the XDG spec says, a non-absolute XDG_STATE_HOME is ignored and $HOME/.local/state used; the README says so. Unit tests (./state, state, empty) and a flow run with GH_PR_REVIEW_STATE unset and XDG_STATE_HOME=./state: posted, state under $HOME/.local/state/…/round-1, the lock released, nothing written in the launch folder or the checkout. Before the fix the run failed at the second cd, as you described.
  • Minor, gh-pr-review:1530 (the no-room-for-the-marker warning named run-…/round.json): b4ddcfa. The warning now says round.json keeps the full record in the run folder printed at the end (Session: …). Flow test: every absolute path in the warning exists after the run, and <final session>/round.json exists.

All test files pass on macOS (bash 5) and ubuntu:24.04; tests/state.sh and tests/flow.sh also with the extension under /bin/bash 3.2. shellcheck and shfmt are clean.

@catalan-adobe
catalan-adobe merged commit 994e2ac into main Nov 28, 2026
1 check passed
@catalan-adobe
catalan-adobe deleted the review-state-folder branch November 28, 2026 18:34
catalan-adobe added a commit that referenced this pull request Nov 28, 2026
Conflicts:
- README.md: #13's lock description and #14's tripwire/ entry, with this branch's
  review-worktree paragraph, pr.json facts, repo/ (--fresh only) and warnings.txt
  (a reset dirty worktree, or a change in the clone only).
- tests/flow.sh: the stub pi keeps both pi.pwd and #14's pi.evil; run, run_no_y and
  run_tty run $ext_bash (#15) with --fresh; run_local runs $ext_bash too; the
  local-clone cases come before #14's real-git --fresh cases.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant