feat: support explicit comment-triggered re-reviews #34
Loading…
Reference in a new issue
No description provided.
Delete branch "feat-comment-rereviews"
Deleting a branch is permanent. Although the deleted branch may continue to exist for a short time before it actually gets removed, it CANNOT be undone in most cases. Continue?
Humans can request another review without pushing code by posting explanatory feedback followed by exactly
/ai-review. Trusted base-branch configuration controls owner/allowlist authorization; this repository enablesreview.comment_triggerand formal request-changes authority for validated blocking findings. Important findings alone remain COMMENT reviews.Comment/manual requests validate the PR before checkout, reject forks, and resolve its head. Reviews verify checkout and API heads before checks or model work. Per-PR concurrency serializes requests, completion fingerprints deduplicate unchanged heads/discussion, and new or edited human feedback permits another review. Bot replies are excluded; bounded human discussion reaches both model passes. Advisory reports belong to the current publishing account, while formal reviews retain commit-linked history. Superseded queued push events skip safely and push reports preserve comment-request completion stamps.
Configuration validation handles documented empty lists, username lists and boolean flags. All review paths paginate discussion; malformed author shapes cannot authorize requests or claim reports. Documentation covers publishing-token user-read access, account changes, the fail-closed discussion pagination cap, and checkout requirements for comment-event dry runs. The self-review workflow now checks the actual Actions publishing token's
/useraccess before checkout or model work, including while the action on main is the older version.Validation: 113 tests run, 112 passed, one optional OpenCode integration test skipped;
git diff --checkpassed. The inline credential preflight was checked for successful, malformed and HTTP 403 responses without exposing credentials or response bodies. Live CI run #105 oneab2a1cverified the actual Actions publishing token's/useraccess at 2026-10-10 14:19:13 UTC before checkout; no secret changes were needed. Live/ai-reviewevent validation remains after merge because Forgejo loads comment workflows from the default branch and configuration from the trusted base revision.Closes #21.
Automated code review
Reviewed commit:
5aa83a1d8476fc3efbc793eb928fd121c29253a7Verdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Strict validation pass over the initial review. All three of its findings are supported by the supplied diff and the checked-out code: the README's inline
[]list syntax is genuinely mis-parsed by the bundled YAML-subset parser (parse_scalar returns the string "[]"), which the new list-type check in prepare_review turns into a hard failure and which the push path silently degrades into a character tuple; the identity-scopedexistinglookup pluslookup_existing=Falsegenuinely diverges from the push path'sfind_existing_review; andidentity["login"]is unguarded while the surrounding code deliberately reports ignored requests through the newrequest_feedback. No additional defects were found in the changed files: the"".joinchange inhuman_reply_contextis correct because each rendered item already ends in a newline, the head-race guard and the fork/draft/closed checks match the README's stated design, and the new test file covers authorization, dedup, pagination, and checkout-safety paths. Remaining concerns are kept as questions rather than findings because they depend on runtime behaviour not present in the supplied material.Blocking findings
None.
Important findings
rereview_users: []/bot_users: []is not producible by the config parser and now fails every comment-triggered review (README.md:94; high confidence)README.md:94-95 (added by this diff) documents
rereview_users: []andbot_users: []in the configuration reference.parse_config(reviewer.py:113-145) only creates a list when a key has an empty inline value followed by-items, so[]is passed toparse_scalar(reviewer.py:192-201), which is not true/false/null, failsint(), and returns the literal string"[]". The new check inprepare_review(reviewer.py:399-403) then evaluatesnot isinstance(allowed, list)and raisesValueError("review.rereview_users and review.bot_users must be lists of usernames"), so every/ai-reviewrequest from a repository using the documented form exits non-zero. On the non-comment path, reviewer.py:1263tuple(review_config.get("bot_users", []))turns the same value into("[", "]"), sobot_comment(reviewer.py:310-314) silently stops excluding bot accounts with no error.tests/test_rereview.pyonly injects Python lists/strings (test_allowlist_and_authorization), so no supplied test covers the YAML[]form; the repository's own.forgejo/ai-review.ymlcontains no inline empty lists, so the defect is not exercised in-tree.Impact: Consumers who copy the README configuration get a hard failure on every comment-triggered review, and push reviews silently lose
bot_usersexclusion, contradicting the README's own statement that detected bot accounts never trigger a review and are excluded from replies.Suggested fix: Document only forms the parser supports - a block list (
rereview_users:followed by- nameitems) or omitting the key to default to[]- and drop the[]examples from README.md:94-95; alternatively teachparse_scalar/parse_configto accept[]as an empty list. Applying the same list-type validation tobot_userson the non-comment path would also make the misconfiguration visible instead of degrading silently.Suggestions
Comment-triggered runs scope the 'existing' report to the publishing identity and disable the marker fallback, so a prior comment by another account is orphaned (reviewer.py:1259; medium confidence)
For prepared runs,
existingis selected only among comments whoseuser.loginequalsprepared["bot_login"](reviewer.py:1259-1260, derived fromapi_request(f"{api}/user")at reviewer.py:404-405), andpublishis then called withlookup_existing: False(reviewer.py:1301-1302), which disables the author-agnosticfind_existing_reviewfallback at reviewer.py:1198-1199. The push path still callsfind_existing_review(comments)(reviewer.py:1257), which matches any author containing MARKER. If no comment matches the current identity,existingisNoneandpublishPOSTs a new comment (reviewer.py:1202-1203). README.md:158 (added by this diff) states 'Advisory mode updates the existing single automated comment', and README.md:129-131 makes the publishing account a configurable choice.Impact: After the publishing account changes, a comment-triggered review leaves the previous automated comment in place and posts a second one whose stale findings are never updated, so the two code paths disagree about which comment is the 'existing' one. Deduplication itself still works because
reports(reviewer.py:415-420) scans all bot-authored comments for the fingerprint stamp.Suggested fix: Consider falling back to
find_existing_reviewwhen no comment matches the current identity (or matching on MARKER plus 'not human-authored'), and note in README that changing the publishing account leaves a previous comment orphaned.A
/userresponse withoutloginraises a bare KeyError instead of an ignored-request reason (reviewer.py:405; medium confidence)identity = api_request(f"{api}/user", token)(reviewer.py:404) is followed by unguardedidentity["login"]at reviewer.py:405 and reviewer.py:436, andreportsfiltering usesidentity["login"].casefold()(reviewer.py:415-420). Every other rejected comment request returns a reason thatmainsurfaces through the newrequest_feedback(reviewer.py:349-356, called at reviewer.py:1225), so a token that cannot read its own identity - a requirement stated in README.md:129-131 - bypasses that reporting path entirely and aborts the step with no reason in the Actions log or step summary.Impact: Operators enabling
comment_triggerget an unlabelled failure that does not identify the token-scope requirement, making it harder to diagnose than the other ignored-request paths that report an explicit reason.Suggested fix: Validate the identity response and either raise a descriptive error (e.g. 'publishing token cannot read its own /user identity') or return an 'Ignored: ...' reason so
request_feedbackrecords it, consistent with the other guard clauses inprepare_review.Tests and validation
Questions
prepare_reviewsetsbaseline=baseline or {"created_at": ""}(reviewer.py:435-436), which makeshuman_reply_contextinclude the entire prior human discussion rather than none. Is replaying the whole discussion intended in that case, given README.md:137 describes replies 'after the latest automated report'?cancel-in-progress: falsefor the whole job, which also applies tosynchronizepush events (previouslytrue). Should push reviews keep running for superseded intermediate commits within the 40-minute budget?github.event.comment.body == '/ai-review'exactly, whileprepare_reviewacceptsbody.strip() == '/ai-review'(reviewer.py:373 and reviewer.py:408). Is the stricter gate deliberate, i.e. a command comment with trailing whitespace never runs the job and therefore never reports a reason?@13342ac422278ee34434d0316ed8d881e8d0f6a9and now references@mainwhile depending on newprepare/expected-headinputs andshould-review/pull-request/head-shaoutputs declared in this PR'saction.yml. How does Forgejo resolve@mainrelative to the branch the workflow is loaded from, and is that resolution atomic with the workflow file?Review limitations
nix flake checkresult are unverified;tests/test_rereview.pyandflake.nixwere only read.issue_commentpayload shape (issue.pull_request/issue.is_pull), the/userresponse fields, whether Gitea/Forgejo honourslimit=50&page=Non issue-comment and review endpoints (discussion_items, reviewer.py:344-356 - note its early exit assumes exactly 50 items per page), and whether comment bodies preserve the appended fingerprint marker unchanged could not be confirmed.actions/checkout@v4given a raw head SHA forready_for_review/reopenedevents was not observed, which the newgit rev-parse HEADequality check at reviewer.py:1241-1243 depends on.pull_requestevents,prepare_reviewis only reached in the review step when the event payload contains a top-levelcommentkey ("comment" in payload, reviewer.py:1223 / reviewer.py:371); the PR event payload shape was not supplied, so whether preparation can be entered there (and then rejected by theaction != "created"guard at reviewer.py:371) could not be confirmed.Diff coverage
.forgejo/ai-review.yml: reviewed — included in a context-limited batch.forgejo/workflows/ai-review.yml: reviewed — included in a context-limited batchREADME.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchexamples/forgejo-workflow/ai-review.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_rereview.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
2b075ac630046377f6b0bbad1b34856963a83dacVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Strict validation pass over the supplied diff. Both surviving findings are anchored in the changed files. (1) The new
expected-headwiring falls back to the event-payload head SHA forpull_requestevents (the prepare step is skipped for those events), and reviewer.py raises an uncaught ValueError when the API head has moved past that value; combined with the flip ofcancel-in-progressfrom true to false, previously-cancelled push runs now exit non-zero. (2) The completion fingerprint is appended only whenpreparedis set, andprepare_reviewsetsstamponly in thecomment_eventbranch, so push reviews rewrite the shared advisory comment without any fingerprint, erasing the record that the README's deduplication guarantee depends on. Other items from the initial review were dropped: they were questions about unverifiable Forgejo runtime behaviour, config-validation ordering with no demonstrated defect, or restatements of documented behaviour. I found no additional defect in the changed files beyond these two; the newparse_scalarempty-list form matches the README'srereview_users: []/bot_users: []examples and is exercised by tests/test_rereview.py, andallow_request_changes: truein .forgejo/ai-review.yml satisfiesvalidate_formal_review_config(reviewer.py:1116-1121).Blocking findings
None.
Important findings
Line 58 passes
expected-head: ${{ steps.request.outputs.head-sha || github.event.pull_request.head.sha }}, but the prepare step is guarded byif: github.event_name != 'pull_request'(line 37), so for push events the value is the head SHA captured in the event payload. reviewer.py:1260-1265 then computesexpected_head = args.expected_head or ...and raisesValueError("PR head changed or checkout differs from the resolved head; request a new review")whenpr["head"]["sha"]from the API differs; the module entry point (reviewer.py,except Exception as exc: ... raise SystemExit(1)) converts that into a non-zero exit. The same diff also changedcancel-in-progressfromtruetofalse(line 19), so queued push runs in the per-PR group are no longer cancelled and now execute against stale event payloads. The identical text appears in examples/forgejo-workflow/ai-review.yml.Impact: With several pushes in quick succession, the runs for intermediate heads now fail and publish nothing instead of being cancelled or reviewed leniently: the API head has already moved past the event head, so the equality check aborts before any check or model call. This turns previously-cancelled push runs into red Actions runs while README states 'Push-based reviews remain the default' and instructs readers to keep the per-PR group with
cancel-in-progress: false.Suggested fix: Scope the strict equality check to prepared (comment/manual) requests, or handle a drifted API head for push events as a skip: pass
expected-headonly whensteps.request.outputs.head-shais non-empty (e.g. drop the|| github.event.pull_request.head.shafallback), or in reviewer.py callrequest_feedbackandreturn 0for a head mismatch instead of raising, so stale queued push runs report 'ignored' rather than failing.Suggestions
reviewer.py:1318-1319 appends the fingerprint only under
if prepared:(body += "\n" + prepared["stamp"]), andprepare_reviewassignsstamp(reviewer.py:448) only inside itsif comment_event:branch, so push reviews produce no stamp. Deduplication at reviewer.py:449-450 searches for that stamp inside bot-authored MARKER comments. Because publish updates a single comment viaPATCH .../issues/comments/{existing['id']}with the new body (reviewer.py,api_request(f"{api}/repos/{repo}/issues/comments/{existing['id']}", token, "PATCH", {"body": body})) and README states 'both push and comment reviews update the current publishing account's single advisory comment', a push review overwrites and discards any previously recorded stamp.Impact: A
/ai-reviewrequest whose head, PR title/body and human discussion match an earlier completed comment review will re-run both model passes if a push review (e.g. areopenedorready_for_reviewevent, which does not change the head) rewrote the comment in between, contradicting README's 'Repeating/ai-reviewwith the same context skips model work' guarantee and costing an avoidable model round-trip.Suggested fix: Record the fingerprint for push reviews as well when
comment_triggeris enabled and abot_login-scoped report exists (compute the same head/title/body/human fingerprint in main and append it), or store the fingerprint in a separate marker that publish preserves when updating an existing comment, so the deduplication record survives across push and comment runs.Tests and validation
Questions
github.event.issue.pull_request || github.event.issue.is_pullin the job guard andissue.get("pull_request") or issue.get("is_pull")in prepare_review. No supplied fixture contains a real Forgejoissue_commentpayload, so it is unverified which field this Forgejo version emits; if neither is present the feature never fires (tests/test_rereview.py supplies both keys).reportsfromGET /repos/{repo}/pulls/{number}/reviewsand readsuser.login,body,updated_at/submitted_at/created_at, anddiscussion_itemsrequires a paginated list response (?limit=50&page=N). No supplied fixture exercises a real Forgejo response for that endpoint; only the test'sself.reviewsstub is available.issue_commentevents the review step re-runsprepare_reviewafter checkout (main's condition"comment" in payload or os.environ.get("GITHUB_EVENT_NAME") == "issue_comment"), duplicating the /user, PR, config and paginated-comment requests; is the doubled request cost acceptable, given a rejection at that point returns 0 with a checked-out tree and no published review?rereview_users/bot_usersviareview_usernamesbut does not callvalidate_formal_review_configbefore reading the reviews endpoint; should malformedformal_review/allow_approval/allow_request_changesvalues be rejected with the documented configuration message at that point rather than later in main?Review limitations
issue_commentpayload shape,concurrencygroup semantics withcancel-in-progress: false, the/useridentity endpoint, or the PR-reviews endpoint's fields. Both findings depend partly on these and are marked medium confidence..forgejo/ai-review.yml(comment_trigger: true,allow_request_changes: true) is read from the PR base revision, so its effect on this repository's own reviews cannot be observed in the supplied checkout.Diff coverage
.forgejo/ai-review.yml: reviewed — included in a context-limited batch.forgejo/workflows/ai-review.yml: reviewed — included in a context-limited batchREADME.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchexamples/forgejo-workflow/ai-review.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_rereview.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
5e1ed203c6b2e027c5bee5ef15b94010caa2afcaVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Strict validation pass over the supplied diff. All three findings from the initial review are supported by concrete supplied evidence and are retained, with two corrections: the README token-scope line is at README.md:33 (not 32), and the comment_trigger validation gap is narrower than stated because parse_scalar (reviewer.py:190-199) already maps quoted and mixed-case 'true'/'false' to booleans, so only values such as 1, yes, or on parse to a non-boolean. The push-path pagination asymmetry is real and is aggravated by the new account-scoped report lookup, lookup_existing=False, and the stamp-preservation block at reviewer.py:1325-1330, all of which now depend on the single unpaginated response at reviewer.py:1286. No blocking defect was identified in the changed code; the workflow-expression concerns (concurrency group, steps.* outputs on skipped steps, github.event.issue.is_pull, checkout of a raw SHA) could not be verified against any supplied runtime evidence and are reported as questions and limitations, not findings.
Blocking findings
None.
Important findings
README.md:33 still states "A Forgejo token with repository-read and issue-comment write access, stored as a repository secret", and README.md:498 repeats "Create a dedicated token with only repository read and issue-comment write access". The diff adds publishing_identity (reviewer.py:373-386), which GETs {api}/user and raises "publishing token cannot read its own /user identity; check the token's user-read scope", and main() at reviewer.py:1282 calls it on push runs whenever review_config.get("comment_trigger") is True. .forgejo/ai-review.yml in this diff sets comment_trigger: true. Only the new "Requesting another review" section (README.md:130) documents the /user read scope.
Impact: With comment triggers enabled, a token configured per the two authoritative setup sections (repository read + issue-comment write only) now aborts the whole action with a token-scope error instead of publishing, on push reviews as well as comment reviews. The README contradicts itself, so consumers following Requirements/Permissions hit an avoidable hard failure.
Suggested fix: Amend README.md:33 and the "Permissions and advisory failure behaviour" paragraph at README.md:498 to state that when review.comment_trigger is true the publishing token must also read its own /user identity, and cross-reference the "Requesting another review" section.
Suggestions
comment_trigger is not validated as a boolean, unlike the sibling review flags (reviewer.py:420; medium confidence)
prepare_review tests
review_config.get("comment_trigger") is not True(reviewer.py:420) and main() usesreview_config.get("comment_trigger") is True(reviewer.py:1282), so any non-True value takes the disabled path silently. validate_formal_review_config (reviewer.py:1116-1121) raises "review.{key} must be a boolean" for formal_review, allow_approval and allow_request_changes, and review_usernames raises for malformed username lists; no equivalent check exists for comment_trigger. Note parse_scalar (reviewer.py:190-199) already maps quoted/mixed-case "true" and "false" to booleans, so the reachable mis-typed values are ones such ascomment_trigger: 1(returns int 1) oryes/on(returned as strings).Impact: A configuration typo such as
comment_trigger: 1oryessilently disables comment-triggered re-reviews, and also disables the account-scoped report update on push runs (bot_login stays None), with no reported reason; every other option introduced by this change is validated.Suggested fix: Reject non-boolean values explicitly when the key is present, e.g.
if type(review_config.get("comment_trigger", False)) is not bool: raise ValueError("review.comment_trigger must be a boolean"), applied on both the prepare path and the push path alongside validate_formal_review_config/review_usernames.Push/manual path still fetches issue comments without pagination while the new comment path paginates (reviewer.py:1286; medium confidence)
The diff adds discussion_items (reviewer.py:346-357), which requests
?limit=50&page={page}up to 100 pages and fails closed at the cap, and uses it for comment runs (reviewer.py:427). The changed line reviewer.py:1286 keeps the single unpaginated requestapi_request(f"{api}/repos/{args.repo}/issues/{pr_number}/comments", ...)for push/manual runs. Everything downstream of it is new and depends on that list being complete: the account-scoped report lookup at reviewer.py:1288-1290, publish called with lookup_existing=False (reviewer.py:1338 publish_options, which disables the previous re-discovery at reviewer.py:1220), and the stamp-preservation block at reviewer.py:1325-1330 that re-reads the last REQUEST_MARKER fromexisting.get("body").Impact: For a PR whose existing advisory report is not in the first unpaginated response, a push review with comment triggers enabled finds existing=None: publish POSTs a second advisory comment for the same publishing account (breaking the documented "one structured comment per PR" and "update only the current publishing account's advisory report" guarantees) and the preserved comment-request fingerprint is dropped, so a subsequent /ai-review with unchanged context re-runs model work. The author already treats pagination as required for the comment path, so the asymmetry looks unintentional.
Suggested fix: Reuse discussion_items for the push/manual comment fetch (or share one paginated helper for both paths) so the account-scoped lookup, the report update, and the fingerprint preservation operate on the complete comment set.
Tests and validation
Questions
if: github.event_name != 'pull_request'on the "Validate review request" step intended to be permanent, or only a bootstrap guard while this PR is reviewed by the action as published on main? If permanent, push reviews never run prepare_review, so the fork rejection, closed/merged skip, and draft skip in prepare_review are not applied to push events; they rely instead on the job guard and the expected-head checks in main().inputs.pull_requestin theconcurrencygroup forpull_requestandissue_commentevents (where no workflow inputs exist), and doesgithub.event.issue.is_pullexist in its issue_comment payload? No supplied evidence covers either, so the concurrency group and the job guard could not be verified against the runtime.rereview_usersandbot_usersbe listed explicitly in this repository's .forgejo/ai-review.yml? The README states organization repositories must list maintainers individually, and prepare_review authorizes onlyrepo.split("/")[0](reviewer.py:441) plus rereview_users; the diff adds neither key to .forgejo/ai-review.yml.Review limitations
git diff --checkresult are unverified evidence from the pull-request text.inputscontext outside workflow_dispatch,actions/checkout@v4with a raw SHA ref,steps.<skipped-step>.outputs.*semantics, or theconcurrencygroup, so all workflow-expression concerns remain unverified rather than findings.?limit=50&page=in discussion_items and collect_changed_files, not on an observed truncation./ai-reviewbehaviour after merge is untested by the supplied evidence; the PR states the base-revision configuration on main does not yet containcomment_trigger: true.Diff coverage
.forgejo/ai-review.yml: reviewed — included in a context-limited batch.forgejo/workflows/ai-review.yml: reviewed — included in a context-limited batchREADME.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchexamples/forgejo-workflow/ai-review.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_rereview.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
d727b9d56c607320a9463c9e8ba5308c7e0afb78Verdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Strict validation pass over the initial review. All four initial findings were re-checked against the checked-out reviewer.py and the supplied diffs. Findings 1-3 are supported by concrete, verifiable code in the changed files (the two PR-detection guards genuinely disagree on an empty
pull_requestobject; the newitem.get("user", {}).get("login")accesses genuinely crash on a JSON-nulluserwhile the siblingbot_commentat reviewer.py:313 deliberately guards it; the human-reply filter at reviewer.py:330 and its sort key at reviewer.py:331 use different values). Finding 4 was verified against parse_config (the list-item branch at reviewer.py:136 calls parse_scalar without strip_yaml_comment, unlike the key branch at reviewer.py:135) and is retained only as a test-coverage suggestion since the exclude_paths README line and parse_config itself are unchanged. No new defects were found beyond these; the push-head skip, publishing-account scoping, marker re-stamping, and empty-list parsing behave as the README describes in the supplied code.Blocking findings
None.
Important findings
PR detection in prepare_review disagrees with the workflow guard on an empty
pull_requestobject (reviewer.py:395; medium confidence)reviewer.py:395 rejects the event with
if payload.get("action") != "created" or not (issue.get("pull_request") or issue.get("is_pull")), while both workflow files guard the same event with(github.event.issue.pull_request || github.event.issue.is_pull)(.forgejo/workflows/ai-review.yml and examples/forgejo-workflow/ai-review.yml jobif). The two expressions disagree exactly whenpull_requestis present but empty andis_pullis absent: the workflow guard admits it, Python rejects it. tests/test_rereview.py:26 supplies only the both-fields shape ("pull_request": {}, "is_pull": True), so no supplied fixture pins the real payload.Impact: For a GitHub-style payload that marks a PR only with an empty
pull_requestobject, the job runs, prepare_review returns 'Not a review request.',should-reviewis emitted false, and every/ai-reviewcomment silently does nothing; the feature would be dead on arrival rather than failing visibly.Suggested fix: Make the two guards agree on one rule, e.g.
issue.get("pull_request") is not None or issue.get("is_pull")in prepare_review, or drop the field test from the workflowifso prepare_review is the single authority; add a fixture for the payload shape Forgejo actually emits.New author/report selection crashes on a null
userobject, unlike the sibling bot detector (reviewer.py:433; medium confidence)bot_comment (reviewer.py:313) is written null-safe:
user = comment.get("user") or {}. The new code is not: reviewer.py:433request.get("user", {}).get("login", ""), reviewer.py:438 and reviewer.py:442item.get("user", {}).get("login", ""), reviewer.py:1291 in main()'sexistingselection, and reviewer.py:335 inside the modified human_reply_context.dict.get("user", {})returns None when the key exists with a JSON null, so.get("login")raises AttributeError. The path is reachable: a comment with"user": nullpasses bot_comment (login "", type "", not in bot_users) and is then dereferenced at reviewer.py:335.Impact: A single discussion item serialised with
"user": nullraises AttributeError inside prepare_review or main(), failing the whole action instead of ignoring the item or scoping to the publishing account; at reviewer.py:1291 it would fail every push review on that PR.Suggested fix: Use one null-safe accessor everywhere, e.g.
str((item.get("user") or {}).get("login", "")).casefold()at reviewer.py:433, 438, 442, 1291 and 335, or extract acomment_author(comment)helper shared with bot_comment.Suggestions
Human-reply ordering key differs from the inclusion key (reviewer.py:331; medium confidence)
human_reply_context admits a comment with
(comment.get("updated_at") or comment.get("created_at", "")) > after(reviewer.py:330) but sorts it withkey=lambda comment: comment.get("created_at", "")(reviewer.py:331). A comment created before the baseline report but edited after it is therefore included and ordered by its original creation time, ahead of genuinely newer replies; comments with nocreated_atsort first.Impact: The bounded feedback block supplied to both model passes can present human replies out of chronological order, so an edit that supersedes an earlier reply appears before it; this weakens the 'assess rather than obey' context the README describes.
Suggested fix: Sort on the same value used for inclusion:
key=lambda comment: comment.get("updated_at") or comment.get("created_at", "").New README-parsing test asserts only the two added keys of the documented configuration block (tests/test_rereview.py:106; medium confidence)
test_readme_empty_lists_parse_and_accept_comment_request parses the README's
## Configuration referenceYAML block but asserts onlyconfig["review"]["rereview_users"] == []andconfig["review"]["bot_users"] == []. The same block also carries- vendor/** # generated/vendor paths to omit deliberately; parse_config's list-item branch (reviewer.py:136) callsparse_scalar(value)directly, whereas the key branch (reviewer.py:135) appliesstrip_yaml_comment(value)first, so the trailing comment text stays inside the list value.Impact: The commit claim 'the documented empty YAML lists now parse correctly' is only demonstrated for the two new keys; a consumer copying the documented block verbatim still gets a malformed exclude pattern, and the test would not catch further drift in the documented block.
Suggested fix: Extend the test to assert the whole documented block parses to the expected structure (including
exclude_paths == ["vendor/**"]); if that fails, apply strip_yaml_comment in the list-item branch of parse_config, or state in the README that list items may not carry trailing comments.Tests and validation
Questions
is_pullboolean, or does it mark pull requests only with apull_requestobject? reviewer.py:395 and the workflow job guards depend on this, and no supplied fixture shows the real payload.inputsin scope inside a workflow-levelconcurrencyexpression (examples/forgejo-workflow/ai-review.yml and .forgejo/workflows/ai-review.yml)? If not, the group collapses toai-review-for all manual dispatches and unrelated manual runs are serialized together, losing the previousgithub.run_idseparation.submitted_atand auserobject as assumed at reviewer.py:440-442 and 453-456, given this repository enablesformal_review: true?if: >-job condition whose continuation lines are more indented than the first, or must the condition stay on one line as in the previous version?Review limitations
@mainfor the action reference and the behaviour ofsteps.request.outputs.*when the 'Validate review request' step is skipped for pull_request events could not be verified against Forgejo's workflow implementation.lookup_existingfallback and parse_config's list-item handling was read only as context for the changed lines and is not otherwise assessed./ai-reviewbehaviour after merge is not observable here: reviewer.py reads .forgejo/ai-review.yml from the PR's base commit, so this repository's newcomment_trigger: trueandallow_request_changes: truetake effect only after merge.Diff coverage
.forgejo/ai-review.yml: reviewed — included in a context-limited batch.forgejo/workflows/ai-review.yml: reviewed — included in a context-limited batchREADME.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchexamples/forgejo-workflow/ai-review.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_agent_cli.py: reviewed — included in a context-limited batchtests/test_rereview.py: reviewed — included in a context-limited batchtests/test_reviewer.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
2bacfdf3ba3fdd42a60f80a7ff7a1ff0db9e2a69Verdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
Strict validation pass over the supplied change. The comment-trigger path (prepare step, per-PR concurrency, head resolution, fingerprint deduplication), the publishing-account scoping of the advisory report, discussion pagination, and the tightened configuration validation are internally consistent across reviewer.py, action.yml, both workflows, and the new tests; the prepare/review step ordering, the REQUEST_MARKER stamp regex, the superseded-push skip, and the fixture updates for paginated comment URLs all line up. Four items survive validation: one operational coupling introduced by enabling comment_trigger in this repository's own configuration, and three behavioural/documentation edges (an unguarded comment-author shape, an undocumented discussion pagination failure, and a checkout guard that also applies to comment payloads and --dry-run). No finding demonstrates an incorrect result on a normal path.
Blocking findings
None.
Important findings
The diff sets
comment_trigger: truein the repository's own executable configuration. reviewer.py:1289-1290 then resolves the publishing identity on push runs:bot_login = prepared["bot_login"] if prepared else (publishing_identity(api, args.token) if review_config.get("comment_trigger") is True else None), andpublishing_identityraises "publishing token cannot read its own /user identity; check the token's user-read scope" on a 401/403 or an unusable/userresponse. README.md states the requirement: "Whenreview.comment_trigger: true, also grant user-read access to the token's own/useridentity; push and comment reviews both require it." The repository's own workflow (.forgejo/workflows/ai-review.yml) skips the prepare step for pull_request events, so push reviews hit this code path directly.Impact: Once this configuration is merged into the base branch, every push-based self-review of this repository fails (no published report) unless AI_REVIEW_FORGEJO_TOKEN has already been re-scoped for user-read. The failure is a hard error, not a degraded mode, so the existing workflow would stop publishing rather than fall back. The token's granted scopes are not part of the supplied material, so this coupling is unverified here.
Suggested fix: Confirm the publishing token's user-read scope before merging, or land the token re-scope and the
comment_trigger: trueflag as separate steps so push reviews keep working until the scope is verified.Suggestions
bot_comment assumes a dict
userwhile comment_author deliberately tolerates other shapes (reviewer.py:319; medium confidence)comment_authorguards the shape (login = user.get("login") if isinstance(user, dict) else None), butbot_commentdoesuser = comment.get("user") or {}and then callsuser.get("type", "")/user.get("is_bot")with no isinstance check. Any truthy non-dictuservalue raises AttributeError insidebot_comment, which is called fromhuman_reply_context,prepare_review(request check,reports,humancomprehensions), andmain. tests/test_rereview.py::test_null_authors_are_safe_and_cannot_authorize_or_claim_a_report only injectsuser=None, whichor {}happens to handle.Impact: An unexpected
usershape from the API aborts the whole review (exit 1, no report) instead of being treated as an unattributed comment - the failure modecomment_authorwas written to avoid.Suggested fix: Reuse the same guard in bot_comment, e.g.
user = comment.get("user") if isinstance(comment.get("user"), dict) else {}, so both helpers tolerate identical malformed input.The discussion pagination cap is an undocumented hard failure, unlike the comparable changed-files cap (reviewer.py:362; medium confidence)
discussion_itemspaginates to page 100 and thenraise ValueError("Forgejo discussion pagination limit reached"), so bothprepare_review(reviewer.py:435) andmain(reviewer.py:1294comments = prepared["comments"] if prepared else discussion_items(...)) abort the run with no published report. The analogous cap for files is documented in README.md as a soft outcome: "Changed files for the pull request are collected across paginated API requests (up to a safety cap of 100 pages at 50 files per page). If the retrieved list falls short of Forgejo's reported changed_files count, or if pagination terminates at the safety cap, the shortfall is reported under Review limitations." No equivalent statement exists for the discussion cap; the new README section describes only the fail-closed intent in the docstring.Impact: A pull request whose discussion exceeds ~5,000 comments now fails the action silently with respect to documentation, and this applies to push reviews as well once pagination is used, not only comment requests.
Suggested fix: Document the discussion pagination limit alongside the changed-files cap in README.md, or return the partial item list with a limitation appended, keeping the fail-closed behaviour only where an incomplete discussion would otherwise permit a duplicate review (the fingerprint check).
Comment payloads require the working tree to match the resolved PR head, including under --dry-run (reviewer.py:1268; medium confidence)
expected_head = args.expected_head or (prepared["head"] if prepared else None)is always set for comment payloads becausemain()entersprepare_reviewonargs.prepare or "comment" in payload or os.environ.get("GITHUB_EVENT_NAME") == "issue_comment", and the following block then runsgit rev-parse HEAD(check=True) and raises "checkout differs from the resolved head; request a new review". Nothing skips this guard when--dry-runis set. README.md's Local development section shows only a generic event-JSON invocation, and the new section states the head check only as "The review step checks that the checkout and API head still match that resolved SHA before running checks."Impact: A local or containerised dry run of an issue_comment payload fails on the checkout guard (or on CalledProcessError outside a git repository) unless the caller happens to be in a checkout of that PR head, so comment-request behaviour cannot be exercised from the CLI as documented.
Suggested fix: Skip the checkout comparison when
--dry-runis set, or state in the "Requesting another review" and "Local development" sections that comment-triggered runs require a checkout at the resolved head.Tests and validation
Questions
github.event.comment.body == '/ai-review'exactly, while prepare_review accepts any body that.strip()s to '/ai-review'; a comment with trailing whitespace or a newline would be accepted by the reviewer but never dispatched, and would be silently ignored.Review limitations
GET /user,GET /repos/{repo}/pulls/{n}/reviews, commentuser.type/user.is_bot, andissue.pull_request/issue.is_pullmarkers could not be confirmed.vegarunner registration, and the state of the repository secret are not part of the supplied material, so the token-scope coupling is reported as a dependency rather than a confirmed failure.inputs.pull_requestandgithub.event.issue.numberin the concurrency group and job guard for non-workflow_dispatch events; the pre-existing example already usedinputs.pull_request, so this was not treated as a defect.Diff coverage
.forgejo/ai-review.yml: reviewed — included in a context-limited batch.forgejo/workflows/ai-review.yml: reviewed — included in a context-limited batchREADME.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchexamples/forgejo-workflow/ai-review.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_agent_cli.py: reviewed — included in a context-limited batchtests/test_rereview.py: reviewed — included in a context-limited batchtests/test_reviewer.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
eab2a1cdfd704d94a6945d05f4f1d1ec1fd8b86aVerdict: Ready to merge
No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.
Overall assessment
Strict validation pass over the initial review. All three reported findings are supported by the checked-out code: (1) the 'Verify publishing token identity' step at .forgejo/workflows/ai-review.yml:33 has no
if:guard and runs for pull_request, issue_comment, and workflow_dispatch events, while reviewer.py only calls publishing_identity() when review.comment_trigger is True (main()) or in prepare_review's comment branch, and README.md:34-36/511-513 scope user-read tocomment_trigger: true; (2) human_reply_context (reviewer.py:339-349) sorts replies ascending by updated_at/created_at and consumes the max_reply_bytes budget from the earliest entries, and prepare_review now supplies baseline={"created_at": ""} (reviewer.py:466) so every human comment becomes eligible when no prior report exists; (3) bot_comment (reviewer.py:324) treats any login ending in '[bot]' as bot-authored, which is not documented in README's bot_users guidance (README.md:139). I could not raise any of these above suggestion severity: none produces a failure in this repository (its .forgejo/ai-review.yml sets comment_trigger: true), and each is a documentation/behaviour mismatch rather than a demonstrated defect. No additional defect was found in the changed reviewer/action/workflow code: the fork/closed/merged/draft guards, the head-race and superseded-push skip, the pagination cap in discussion_items, the REQUEST_MARKER re-preservation path, and the configuration validators match the README contract and the new tests in tests/test_rereview.py.Blocking findings
None.
Important findings
None.
Suggestions
Example workflow requires user-read token scope unconditionally; README scopes that requirement to comment_trigger: true (.forgejo/workflows/ai-review.yml:33; medium confidence)
The 'Verify publishing token identity' step carries no
if:condition, so it executes for pull_request, issue_comment, and workflow_dispatch events and exits non-zero with 'Publishing token /user check failed (HTTP %s); check user-read scope.' when/useris unreadable. In reviewer.py, publishing_identity() is only reached whenreview_config.get("comment_trigger") is True(main(), line ~1281) or inside prepare_review's comment branch. README.md:34-36 and README.md:511-513 state user-read is needed only 'Whenreview.comment_trigger: true', and README.md:96 documentscomment_trigger: falseas the default. The same unconditional step is present in examples/forgejo-workflow/ai-review.yml.Impact: An adopter following the README permission guidance with comment_trigger left at its documented default would fail every review, including ordinary push reviews, because of the workflow step rather than any reviewer requirement. The workflow is stricter than the documented token contract; this repository itself is unaffected because .forgejo/ai-review.yml sets comment_trigger: true.
Suggested fix: State in README that this workflow variant always requires user-read scope regardless of
comment_trigger(the inline comment already frames the step as transitional), or gate the step on the trusted configuration so the workflow matches the documented permission contract.Reply-context byte budget retains the oldest human comments, dropping the newest feedback (reviewer.py:348; medium confidence)
human_reply_context sorts candidates ascending by
updated_at/created_atand then walks that order, decrementingremainingand breaking atremaining <= 0, so the max_reply_bytes budget is consumed by the earliest replies. prepare_review now passesbaseline=baseline or {"created_at": ""}(reviewer.py:466), which makesafterempty and therefore every human comment in the PR eligible. README.md:141-142 states only that replies are 'bounded by max_reply_bytes', and README.md:145 states that when no previous report exists 'the bounded human discussion is supplied as the initial context'.Impact: On a PR with a long discussion and no prior report (or after a first review), the newly posted feedback that justified the re-review can be entirely cut from both model passes while stale comments are retained, so the second-pass/validation prompt may not contain the explanation a human just supplied.
Suggested fix: Select the newest replies that fit the budget and render them oldest-first, or document explicitly that the byte budget retains the earliest post-baseline comments.
Undocumented '[bot]' username suffix silently classifies comments as bot-authored (reviewer.py:324; medium confidence)
bot_comment returns true for
login.endswith("[bot]")in addition to the API'stype == 'bot'/is_botfields and the configuredbot_usersset. README.md:139 documents only 'List automation accounts that Forgejo represents as ordinary users inreview.bot_users', and README.md:98 describes bot_users as 'other automation accounts to exclude from replies'. tests/test_rereview.py::test_bots_never_trigger_even_if_allowlisted exercises {"login": "ci[bot]"}, confirming the behaviour is intentional but undocumented.Impact: A human commenter whose username ends in '[bot]' is silently excluded from the reply context and from the request fingerprint, and cannot authorize an
/ai-reviewrequest even when listed inrereview_users; this exclusion is not discoverable from the documentation.Suggested fix: Document the '[bot]' suffix heuristic alongside
bot_users, or restrict bot detection to the API'stype/is_botfields plus the explicit allowlist.Tests and validation
Questions
inputscontext inside the workflow-levelconcurrency.groupexpression (ai-review-${{ github.event.pull_request.number || github.event.issue.number || inputs.pull_request }})? If not, manual dispatches collapse to an empty group suffix and no longer serialize per PR, which the previousgithub.run_idform did.github.event.comment.body == '/ai-review'exactly, while prepare_review acceptsbody.strip() == '/ai-review'. Can a comment body carry trailing whitespace or a newline in the event payload, in which case such requests would never reach the reviewer?analysis.commands[0]contents - intended, given that ordinary README prose edits to that block would fail the suite?Review limitations
mainaccepts the newprepare/expected-headinputs) could not be confirmed.inputsat workflow level,github.event.issue.numberfor issue comments, comment-body normalization, skipped-step output access) and API response shapes (/user,/pulls/{n}/reviewsauthor andsubmitted_atfields) are not supplied, so findings depending on them are reported as questions rather than defects.Diff coverage
.forgejo/ai-review.yml: reviewed — included in a context-limited batch.forgejo/workflows/ai-review.yml: reviewed — included in a context-limited batchREADME.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchexamples/forgejo-workflow/ai-review.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_agent_cli.py: reviewed — included in a context-limited batchtests/test_rereview.py: reviewed — included in a context-limited batchtests/test_reviewer.py: reviewed — included in a context-limited batchReview metadata