fix: handle missing trusted base config with clean skip and fallback support #36
Loading…
Reference in a new issue
No description provided.
Delete branch "fix/issue-22-missing-trusted-config"
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?
Problem
When a repository first sets up
forgejo-auto-pr-review, the initial setup PR introduces workflow configuration and.forgejo/ai-review.yml. Because executable review configuration is loaded from the pull request's base commit (pr["base"]["sha"]), that configuration does not yet exist on the base branch (Forgejo returns HTTP 404).Previously,
fetch_config()returned{}on 404, making an absent file indistinguishable from an intentionally empty configuration. The default provider resolution then fell through to Ollama and failed with an unrelated missing model error (provider.model or OLLAMA_MODEL is required).Solution
Distinguish absent from empty configuration or API errors:
fetch_config()now returnsNonestrictly on HTTP 404.{}) parse and return{}.Clean bootstrap skip & actionable guidance:
--preparemode: skips cleanly withshould_review = Falseand explains that the configuration is not yet merged to the base branch.Explicit trusted fallback configuration (
fallback-config):--fallback-configargument /FORGEJO_REVIEW_FALLBACK_CONFIGenv var toreviewer.pyandfallback-configinput toaction.yml.formal_review_eventwill never emitAPPROVED).Documentation & Tests:
fallback-configusage inREADME.md.Closes #22
Automated code review
Reviewed commit:
e669128468adb4d7e95373fa83104b7d7c8d3163Verdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The supplied changes implement the described bootstrap behaviour:
fetch_config()returnsNoneonly on HTTP 404 (other HTTP errors still raise),prepare_review()andmain()skip cleanly with an explanatory feedback message when trusted base configuration is absent, and afallback-configinput /FORGEJO_REVIEW_FALLBACK_CONFIGenv var /--fallback-configflag supplies configuration withrun_checks()suppressed andAPPROVEDsuppressed informal_review_event(). Bothfetch_configcall sites were updated consistently, and the new tests cover absent, empty, malformed YAML/JSON, non-404, fallback file/string, and fallback-mode suppression. Two defects are demonstrable from the supplied code: the published report in bootstrap mode still asserts that deterministic checks passed (it reuses the normal rendering path with an empty check list), andload_fallback_config()resolves a supplied relative path against the pull-request checkout, so PR-provided files can be read as trusted configuration. Remaining items are documentation and test-quality suggestions.Blocking findings
None.
Important findings
Bootstrap reports claim deterministic checks passed when they were skipped (reviewer.py:1353; high confidence)
checks = [] if is_bootstrap else run_checks(config, root)passes an empty check list into the unchangedrender()(reviewer.py:1179), which callsrender_checks()(reviewer.py:1128-1130) and emits '- No configured deterministic checks.', and buildsverdict_reason(reviewer.py:1185-1188) as 'No blocking or important findings were retained, and deterministic checks passed.' with verdict 'Ready to merge'.render()has nois_bootstrapparameter, so the only signal that checks were skipped is the limitation string appended at reviewer.py:1363-1365.Impact: In fallback/bootstrap mode the published report asserts verification that did not happen: it presents 'Ready to merge' plus 'deterministic checks passed' for a run where no check was executed, and the 'Tests and validation' section reads as if the repository simply has no checks configured rather than that checks were unavailable. This weakens the trust boundary the PR is establishing for setup PRs.
Suggested fix: Thread the bootstrap flag into
render()(or pass a distinct sentinel instead of[]) so the 'Tests and validation' section and the verdict reason state explicitly that deterministic checks were skipped because trusted base configuration was unavailable, instead of claiming they passed.Fallback configuration path is resolved against the pull-request checkout, so PR content can be read as trusted configuration (reviewer.py:199; medium confidence)
load_fallback_config()doespath = Path(fallback_source); if path.is_file(): ... parse_config(path.read_text(...)), i.e. a relative path is resolved against the process working directory. Inmain()the reviewer runs withroot, api = Path.cwd(), ...(reviewer.py:1295) after the workflow has checked out the PR head, andload_fallback_config(args.fallback_config)is called at reviewer.py:1317. A non-existing path silently falls through to parsing the path string itself as YAML, which raises 'invalid config line: ' fromparse_config().Impact: A file added by the pull request can shadow the intended trusted fallback file, so PR-authored content would be consumed as trusted configuration (provider selection, review flags,
min_approval_confidence), contradicting the PR/README claim thatfallback-configis 'trusted'. A mistyped path also produces an opaque YAML parse error rather than an actionable message.Suggested fix: Resolve fallback paths against an explicit trusted directory (or require an absolute path outside the checkout), and distinguish 'path-like input that does not exist' from 'inline configuration string' with an explicit error; document that the fallback file must not live in the pull-request tree.
Suggestions
Fallback configuration's own analysis commands are silently discarded (reviewer.py:1353; medium confidence)
checks = [] if is_bootstrap else run_checks(config, root)skips every configured command, includinganalysis.commandsdeclared inside the fallback configuration itself (the fallback config parsed at reviewer.py:1317/441 is used asconfig). README.md only states 'Repository-defined commands from the pull request are never executed (analysis commands are omitted).' The new test fixture at tests/test_reviewer.py encodes this with a command nameduntrusted-checkandrun_checks.assert_not_called().Impact: A user supplying a full trusted fallback configuration that includes checks gets none of them run, with no explanation; the README wording emphasises PR-derived commands, so the broader suppression is ambiguous to users.
Suggested fix: Either run commands declared in the trusted fallback configuration (they are not PR-derived), or state in README.md that fallback mode suppresses all deterministic checks, including any defined in the fallback configuration.
README fallback snippet does not cover the two-step invocation pattern used by the example workflow (README.md:74; medium confidence)
The bootstrap section shows a single
- name: Run advisory reviewinvocation carryingfallback-config, but examples/forgejo-workflow/ai-review.yml runs aprepare: 'true'step followed by a separate 'Run configured review' step.fallback-configis consumed per invocation: action.yml maps it toFORGEJO_REVIEW_FALLBACK_CONFIG, which is read only at reviewer.py:1270/1282/1316.Impact: A consuming repository that copies the example workflow and adds
fallback-configonly to the preparation step would reportshould-review=truefrom preparation and then skip cleanly in the review step, giving a confusing no-review outcome for a setup PR.Suggested fix: Document that
fallback-configmust be supplied to every invocation of the action in a multi-step workflow, or show the two-step example with the input on both steps.Malformed-JSON test asserts only a bare Exception (tests/test_reviewer.py:223; medium confidence)
with self.assertRaises(Exception): reviewer.fetch_config(... '.forgejo/ai-review.json' ...)accepts any exception type, unlike the sibling YAML case which assertsValueError(line 217) and the non-404 case which assertsurllib.error.HTTPErrorand checksexc.exception.code == 500(lines 229-233).Impact: The test would pass on an unrelated failure and would not catch a regression where malformed JSON is swallowed and returned as
{}, which is precisely the absent-vs-empty distinction this PR introduces.Suggested fix: Assert the specific exception type (
json.JSONDecodeError, aValueErrorsubclass) or wrap the parse so the raised type is stable, mirroring the other new tests.Tests and validation
Questions
{}base configuration produce an actionable message? With the supplied code it still falls through to provider resolution and fails with 'provider.model or OLLAMA_MODEL is required' (reviewer.py:747), which is the same unrelated error the PR set out to eliminate for the absent-file case.is_bootstrapbe exposed as an action output? action.yml currently declares only should-review, pull-request, and head-sha, so a consuming workflow cannot distinguish a bootstrap review from a normal skip when deciding whether to run the checkout/review steps.allow_request_changesfrom a fallback configuration can still submit REQUEST_CHANGES (reviewer.py:1166-1169 runs before theis_bootstrapguard at line 1170), while only APPROVED is suppressed?Review limitations
Diff coverage
README.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_reviewer.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
eed1b6488d7ca444e3325887b9e83e6b1721ba97Verdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The bootstrap/fallback wiring is consistent across reviewer.py, action.yml, README.md, and the new tests: fetch_config now returns None only on HTTP 404 (empty and invalid configs are distinguished and covered by new tests), the clean-skip path returns 0 with feedback, checks are suppressed under fallback configuration, the published report and verdict text explain the skipped checks, and APPROVED is suppressed under is_bootstrap. Two concrete inconsistencies remain in the changed code: the documented 'outside the checked-out repository' guard for a fallback-config path is not applied on the prepare/comment-request path, and the model prompt still renders the bootstrap state as 'No configured deterministic checks.' A third, weaker issue is the shape-based path-vs-inline heuristic in load_fallback_config.
Blocking findings
None.
Important findings
prepare_review resolves the fallback with
config = load_fallback_config(fallback_config)(reviewer.py:455) — norootargument — while main's direct path callsload_fallback_config(args.fallback_config, root=root)(reviewer.py:1334). main then reuses the prepared value verbatim:if prepared and "config" in prepared: config = prepared["config"], so the containment check in load_fallback_config ("fallback configuration file must not reside within the checked-out repository", reviewer.py:193-207) never runs forissue_comment/manual requests. action.yml is a single composite step that setsFORGEJO_REVIEW_FALLBACK_CONFIGand runs reviewer.py with the PR head already checked out, soPath.cwd()in that flow is the untrusted checkout.Impact: In the comment/manual-request flow an absolute fallback path inside the checkout is accepted, so a file added by the pull request itself can be treated as trusted fallback configuration, and its
reviewsettings (allow_approval, formal_review, comment_trigger, provider selection) are honoured. The same input behaves differently for push reviews versus comment requests, weakening the trust boundary README.md states forfallback-config.Suggested fix: Apply the same guard on the prepared path: pass the checkout root into load_fallback_config from prepare_review when a checkout exists, or re-validate the resolved fallback path in main before reusing
prepared["config"], so both flows reject paths inside the checkout; alternatively state in README.md that the outside-checkout rule is enforced only in direct execution mode.Suggestions
Model prompt still reports 'No configured deterministic checks' in bootstrap mode (reviewer.py:1045; medium confidence)
review_promptcallscheck_text = render_checks(checks)with nois_bootstrapargument (reviewer.py:1045), while onlyrenderthreads it through (render_checks(checks, is_bootstrap=is_bootstrap), reviewer.py:1214). main setschecks = [] if is_bootstrap else run_checks(config, root)(reviewer.py:1367-1370), so in bootstrap mode render_checks falls through toif not checks: return "- No configured deterministic checks."and the prompt line 'Deterministic checks (factual results; do not duplicate as findings):' tells the model no checks are configured rather than that trusted configuration was unavailable.Impact: The model is given a materially different account of the run than the published report ('Deterministic checks were skipped because trusted base repository configuration was unavailable'), which can lead it to treat the absence of check output as a clean signal or to emit a spurious limitation/question about missing checks; the prompt and report then disagree.
Suggested fix: Thread
is_bootstrapthroughreview_prompt(and the second-pass prompt) intorender_checks, or add an explicit prompt line stating that deterministic checks were skipped because trusted base configuration was unavailable.Path-vs-inline detection in load_fallback_config decides by text shape, not syntax (reviewer.py:201; medium confidence)
is_path_like = "\n" not in source and (source.startswith("/") or source.startswith("./") or source.startswith("../") or source.endswith(".yml") or source.endswith(".yaml") or source.endswith(".json"))classifies by shape before parsing, and the path branch then raisesFileNotFoundError(f"fallback configuration file not found: {source}")when the file does not exist. A single-line inline mapping whose text ends in.yml/.yaml/.json(e.g.model: qwen.json) or begins with/is therefore read as a filesystem path rather than parsed as configuration. The new testtest_load_fallback_config_from_file_and_stringonly exercises multi-line inline values, so this branch is untested.Impact: A valid one-line fallback configuration fails the whole run with a 'file not found' error that does not indicate the input was misread as a path, which is a confusing failure for a documented input form.
Suggested fix: Decide by explicit syntax rather than shape: treat the value as a path only when it resolves to an existing file (or introduce an unambiguous
file:/inline:prefix), and document the chosen rule in README.md.Tests and validation
Questions
REQUEST_CHANGESstill intended to be reachable (theis_bootstrapguard is added only to the APPROVED branch of formal_review_event), and should the model prompt state that deterministic checks were skipped rather than 'No configured deterministic checks.'?Review limitations
fallback-configto both steps is not reflected in the example it points users to, and did not report it as a finding because it concerns unchanged code outside the diff.Diff coverage
README.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_reviewer.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
4f874e78b0a137fa535d0f3bc5643841370edebfVerdict: Requires further work
Resolve the blocking or important findings and investigate failed deterministic checks before merging.
Overall assessment
The supplied changes implement the documented bootstrap behaviour: fetch_config() returns None only on HTTP 404 and both call sites handle it, fallback configuration is loaded through load_fallback_config(), deterministic checks and APPROVED authority are suppressed under fallback, and the report/prompt state that checks were skipped. The findings I kept concern the trust-boundary handling of the fallback path (the guarded load in main() is discarded and the guard never runs in --prepare mode, so the configuration actually consumed is the unguarded one, and the file is read/parsed twice), an inverted exception-substring guard, a verdict heading that is unchanged under bootstrap, and the absence of any bootstrap signal in the prepare-step outputs.
Blocking findings
None.
Important findings
prepare_review() loads the fallback with
config = load_fallback_config(fallback_config)(reviewer.py:463), i.e. root=None, and stores it in the result. In main(), the prepared branch callsload_fallback_config(args.fallback_config, root=root)at line 1340 for its side effect only - the parsed value is thrown away - and then usesconfig = prepared["config"]at line 1341. In --prepare mode main() returns at lines 1309-1314 after writing should-review/pull-request/head-sha, so the 'must not reside within the checked-out repository' guard at lines 214-220 never runs for that step.Impact: The README states the fallback path must be outside the checked-out tree so PR content cannot shadow trusted configuration, but the configuration consumed is the one loaded without that check. A file at the supplied path that is inside the review step's checkout root is accepted by the prepare step (which then prints 'Accepted: review will run against the resolved PR head.' and sets should-review=true) and only rejected afterwards, as an uncaught ValueError, in the review step - so the two steps disagree and the workflow fails after reporting acceptance. The same path is also read and parsed a second time, so a file that changes between the steps is validated in one state and used in another.
Suggested fix: Have load_fallback_config return the parsed config from the guarded call and use that value in main() instead of prepared["config"] (or carry the root-guarded result through prepare_review), and either evaluate the outside-checkout guard in --prepare mode or state explicitly in README/action.yml that the guard is deferred to the review step.
Suggestions
Outside-checkout guard is expressed as inverted control flow that matches an exception message by substring (reviewer.py:217; high confidence)
The guard is
try: path.resolve().relative_to(root.resolve()); raise ValueError("fallback configuration file must not reside within the checked-out repository") except ValueError as exc: if "must not reside" in str(exc): raise. The rejection is raised inside the try and re-raised from the handler; any other ValueError from resolve()/relative_to() is silently swallowed, and acceptance of an in-checkout path depends on the message wording matching.Impact: The behaviour is coupled to CPython's exception message text rather than to an explicit containment test; an unrelated ValueError is silently treated as 'outside the checkout', which would accept an unverified path as trusted configuration.
Suggested fix: Compute containment explicitly, e.g.
try: inside = path.resolve() == root.resolve() or root.resolve() in path.resolve().parents; except ValueError: inside = False, then raise the guard error from a plainif inside:.Bootstrap reports still render the unqualified '## Verdict: Ready to merge' heading when no deterministic checks ran (reviewer.py:1208; medium confidence)
render() computes
verdict = "Requires further work" if needs_work else "Ready to merge"with no is_bootstrap branch; only verdict_reason is specialised (lines 1211-1212). review_needs_work() returns False for the empty checks list that main() builds at line 1379 (checks = [] if is_bootstrap else run_checks(config, root)), so a clean bootstrap review renders '## Verdict: Ready to merge'.Impact: The published setup-PR report leads with an unqualified 'Ready to merge' heading even though the repository's configured checks were never run; the caveat appears only in the following sentence and the limitations section.
Suggested fix: Give bootstrap runs a distinct verdict heading or suffix (for example 'Ready to merge (advisory only: trusted configuration unavailable)'), keeping the existing limitation text.
The prepare step emits no bootstrap indicator, so a review step that omits fallback-config silently skips after being told to review (reviewer.py:1312; medium confidence)
The --prepare output block writes only
should-review,pull-requestandhead-sha(lines 1312-1313), and action.yml declares only those three outputs. is_bootstrap is kept only in the in-process result (result.update(config=config, head=head, is_bootstrap=is_bootstrap), line 472). In the review step, if fallback-config is not passed, main() re-fetches config (line 1343), gets None, and returns 0 with 'Skipped: no trusted review configuration found on the base branch (first-time setup)'.Impact: A two-step workflow that passes fallback-config only to the prepare step gets should-review=true from prepare, then a clean exit-0 skip with no published report - a silently missing review rather than an error.
Suggested fix: Emit an is-bootstrap (or fallback-in-use) output from --prepare and declare it in action.yml outputs so a consuming workflow can assert both steps resolved identically, or compare the prepare and review resolutions and fail on mismatch.
Tests and validation
Questions
not is_bootstrapto the APPROVED condition (reviewer.py:1194), so allow_request_changes remains active under fallback configuration.Review limitations
Diff coverage
README.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_reviewer.py: reviewed — included in a context-limited batchReview metadata
Automated code review
Reviewed commit:
5f2d2b8e28b8554c3b53c4233393bbeabcd85b8dVerdict: Ready to merge
No blocking or important findings were retained, and deterministic checks passed. Suggestions remain advisory.
Overall assessment
The supplied change adds a
None-on-404 contract tofetch_config, aload_fallback_configloader with an absolute-path and outside-checkout guard, and threads anis_bootstrapflag throughprepare_review,main,review_prompt,render_checks,render, andformal_review_event. The primary behaviours are consistent across the diff and the added tests: absent base configuration yields a clean skip (status 0, no model calls, nopublish), an empty{}configuration still parses, non-404 HTTP errors and malformed YAML/JSON now propagate, fallback mode skipsrun_checks(reviewer.py:1381), renders the skipped-checks text (render_checks,reviewer.py:1149), appends the limitation (reviewer.py:1391), and suppressesAPPROVEDvianot is_bootstrapinformal_review_event(reviewer.py:1192). I checked the initial review's claim that the root-guarded reload is skipped when the review step omits--fallback-config: it is not reachable, becausepreparedis only built in-process atreviewer.py:1319from the sameargs.fallback_configthat guards the reload atreviewer.py:1335, andprepare_reviewsetsis_bootstrap = Trueonly insideif fallback_config:(reviewer.py:461-462); a separateprepare: 'true'step returns atreviewer.py:1329and never carriespreparedinto the review step, which then re-fetches and takes the guarded path. That finding was therefore dropped. Two documentation/message gaps in the changed files remain actionable.Blocking findings
None.
Important findings
None.
Suggestions
Undocumented
file:prefix accepted by load_fallback_config (action.yml:12; high confidence)load_fallback_configaccepts afile:prefix to force path interpretation (reviewer.py:201-203:if source.startswith("file:"): source = source[5:].strip(); is_path = True), andtests/test_reviewer.pyexercises it (cfg6 = reviewer.load_fallback_config(f"file:{f.name}"), and the inside-root rejection withf"file:{inside}"). Neither the new README.md bootstrap section (which only states that a file path 'must be an absolute path to a trusted file outside the checked-out repository tree') nor thefallback-configinput description inaction.yml:12('Trusted fallback review configuration (path to a runner-local file or YAML/JSON string) when base revision has no configuration.') nor the--fallback-confighelp text atreviewer.py:1293mention this prefix.Impact: Users reading only README.md or action.yml cannot discover the
file:form, which is the only unambiguous way to force path interpretation for a source that the heuristic atreviewer.py:204-208would otherwise treat as inline configuration (it requires no newline plus an absolute-path or.yml/.yaml/.jsonsuffix with no colon). A user supplying a path that does not match the heuristic silently gets a parse error instead of a file read.Suggested fix: Document the
file:prefix in the README.md bootstrap section and in theaction.ymlfallback-configdescription (and the--fallback-confighelp string), alongside the existing absolute-path requirement.Skip message asserts a 'first-time setup' cause the code cannot establish (reviewer.py:1348; medium confidence)
fetch_configmaps any HTTP 404 from/repos/{repo}/contents/{path}?ref={base_sha}toNone(reviewer.py:181-183), and bothprepare_review(reviewer.py:465-466) andmain(reviewer.py:1348-1349) render the fixed text 'Skipped: no trusted review configuration found on the base branch (first-time setup). Merge {config} to enable reviews.' The code has no signal distinguishing why the contents request returned 404; the previous behaviour surfaced the condition as a raised error rather than a status-0 skip with a causal message.Impact: The skip exits 0 and prints a message that attributes every missing-configuration case to first-time setup, so a repository that already had review configuration removed or renamed on the base branch loses review coverage with an explanation that does not match what happened, which is easy to miss in the Actions log.
Suggested fix: Word the reason neutrally, e.g. 'No review configuration found at {path} on the base revision; reviews are skipped until it is present on the base branch', and mention first-time setup only as a possible cause; keep the README.md wording in sync with the emitted string.
Tests and validation
Questions
file:prefix intended to be user-facing (and thus documented in README.md/action.yml), or only a test-internal disambiguation aid?Review limitations
run_checks,find_guidance, and provider invocation were not re-examined beyond the call sites touched by this change, and no defects are inferred in unchanged code that was not supplied.--fallback-configwas checked againstreviewer.py:1319,1333-1341, and461-470and found unreachable (is_bootstrapis true only whenargs.fallback_configis truthy in the same process;preparedis not carried across workflow steps), so it is not reported.Diff coverage
README.md: reviewed — included in a context-limited batchaction.yml: reviewed — included in a context-limited batchreviewer.py: reviewed — included in a context-limited batchtests/test_reviewer.py: reviewed — included in a context-limited batchReview metadata