Repository navigation
ci: add a weekly workflow that turns recurring review comments into build rules - #16225
AnkushinDaniil wants to merge 36 commits into
Conversation
|
Claude finished @AnkushinDaniil's task in 1m 42s —— View job Review of PR #16225 (review rule bot)
The pipeline is well thought out: it counts hits from the compiler output instead of grep, uses a red control for new analyzers, and samples precision with a separate pass. The main problem is the security boundary. The PR body says model jobs can't touch the write token, but they can. Findings
Not mergeable yet: the Critical and High security issues need fixing first. The Medium items need a fix or a stated reason. |
| new_id=() | ||
| [ "$ROUTE" = B ] && new_id=(--new-id "$IDS") | ||
| git add -N . | ||
| python3 scripts/rule-bot/rule_bot.py guard --base HEAD "${new_id[@]}" |
There was a problem hiding this comment.
Critical – the path guard runs code from the patch it is checking, in the job that holds the write token.
git apply "$DATA/fix.patch" runs on line 391, before this line. So scripts/rule-bot/rule_bot.py here is already the patched copy. The patch comes from jobs where Claude had unrestricted Edit/Write, and route-b feeds it untrusted review-comment text. If such a patch changes check_paths (or anything else in rule_bot.py), that code runs with GH_TOKEN set to the app token, and with the app token stored in .git/config by checkout (persist-credentials is on by default here). The modified guard then lets .github/, scripts/ and so on go into the pushed branch.
The same problem appears earlier in the chain:
- In route-b,
route-b.shcalls"$here/rule_bot.py" guard/redfrom the working tree after the model has run. - In the fix job,
analyzer.patchis applied first, and then the guard on line 339 runs from the working tree.
So the stated boundary ("jobs that run Claude never get a token that can write") can be bypassed. Those jobs can't write directly, but they control code that later runs where the token is.
Suggested fix: in open-pr, run the guard from a copy taken before applying the patch, for example git show HEAD:scripts/rule-bot/rule_bot.py > "$RUNNER_TEMP/rule_bot.py" and use that copy. Better still, run the path check over git apply --numstat/--summary output before applying anything. Also set persist-credentials: false on this checkout and push with an explicit token URL.
There was a problem hiding this comment.
Fixed in fbb0e54. Every job now copies scripts/rule-bot to $RUNNER_TEMP before applying any generated patch and runs the guard from that copy. The guard checks the patch text (guard --patch) before git apply, and checks the tree again after it. open-pr checks out with persist-credentials: false and passes the token only on the push URL. Tests: the Guard class (including test_patch_changes) in scripts/rule-bot/tests/test_rule_bot.py.
| jq --arg c "$cluster" '.[$c].new_examples // []' "$data/gates.json" > "$data/route-b-new-examples.json" | ||
| jq -s 'add' "$data/route-b-examples.json" "$data/route-b-new-examples.json" > "$data/route-b-all-examples.json" | ||
| rm -f "$data/analyzer-result.json" | ||
| "$here/llm.sh" "$here/prompts/analyzer.txt" "Read,Glob,Grep,Edit,Write,Bash(dotnet build:*),Bash(dotnet test:*)" \ |
There was a problem hiding this comment.
High – prompt injection can lead to arbitrary code execution while CLAUDE_CODE_OAUTH_TOKEN is in the environment.
EXAMPLES contains review-comment bodies, and anyone who can comment on a PR can write those. findings_from does not restrict comment authors to org members. The prompt says to "treat as data", but that is not a security control. The model has an unrestricted Write/Edit and Bash(dotnet test:*), so any code it writes (tests, a Directory.Build.props, rule_bot.py itself) runs in this job with the OAuth token in the environment.
In addition, test_class from the model's JSON is passed through eval on line 31, which allows command injection outside Claude's tool sandbox.
Suggestions:
- Limit the examples to comments by org members or collaborators (
authorAssociation). - Limit
Write/Editto the analyzer and test directories, e.g.Write(src/Nethermind/Nethermind.Analyzers/**). - Check
test_classagainst^[A-Za-z0-9_]+$before using it, and drop theeval.
There was a problem hiding this comment.
Fixed in fbb0e54. Examples now come only from comments whose authorAssociation is OWNER, MEMBER or COLLABORATOR. Write/Edit are limited to Nethermind.Analyzers/** and Nethermind.Analyzers.Test/**. test_class must match ^[A-Za-z_][A-Za-z0-9_]*$. The test and red runs go through rule_bot.py test/red with an argv list (no eval, no shell) and with CLAUDE_CODE_OAUTH_TOKEN removed from the environment. One risk remains: the model's own dotnet build/dotnet test calls still run while the token is set. Those calls can only build the analyzer projects it may edit, and their inputs now come only from trusted authors.
| bad.append(f"{path}: only one appended row for {new_id or 'the new rule'} is allowed") | ||
| elif path.startswith(GUARDED_PREFIXES) or path.endswith(".md"): | ||
| bad.append(f"{path}: outside the paths the bot may change") | ||
| elif not (path == ".editorconfig" or path.endswith((".cs", ".props", ".globalconfig"))): |
There was a problem hiding this comment.
Medium – .props and arbitrary .cs paths pass the guard, and the PR branch is pushed to this repo, not a fork.
A .props file can contain <Target>/<Exec>. Because the branch lives in NethermindEth/nethermind and the PR is opened with an app token, CI on it runs with internal-branch trust, not fork isolation. Route A only needs .cs edits plus .editorconfig, and route B only needs files under Nethermind.Analyzers{,.Test}/.
Suggestion: drop .props/.globalconfig and limit route B to those two directories.
There was a problem hiding this comment.
Fixed in fbb0e54. The guard now allows only .cs files plus a modified .editorconfig, so .props, .globalconfig and .csproj are rejected. Route A may only modify files listed in fix-hits.txt. Route B may also touch the two analyzer projects and append exactly one row to AnalyzerReleases.Unshipped.md. New files must be mode 100644, and symlinks, mode changes, renames and binary patches fail.
|
|
||
| def gate_cluster(base, new_rows): | ||
| d = cluster_stats(new_rows) | ||
| st = dict(n=base["n"] + d["n"], prs=base["prs"] + d["prs"], commenters=base["authors"] + d["commenters"], |
There was a problem hiding this comment.
Medium – the gate counts the same PRs and commenters twice.
base["authors"] + d["commenters"] and base["prs"] + d["prs"] add two distinct-counts together. A reviewer who commented both before and after baseline.until is counted twice, and so is a PR that has comments in both periods. Two people commenting in both periods already pass the commenters >= 3 gate, and every weekly run inflates the counts further.
Suggested fix: store the sets of logins and PR numbers in baseline.json (or just the logins/PRs) and take the union.
There was a problem hiding this comment.
Fixed in fbb0e54 and b0a0221. baseline.json now stores pr_set/author_set, and the gate takes len(base set ∪ new). The baseline counts are rebuilt with the same clusters.json matcher the weekly run uses (2026-05-19..2026-11-19), so the baseline and new rows are counted the same way. Test test_two_people_in_both_periods_fail_the_commenter_gate covers your example.
| def overlay(ids, exclude_tests=False): | ||
| s = "\n[*.cs]\n" + "".join(f"dotnet_diagnostic.{i}.severity = warning\n" for i in ids) | ||
| if exclude_tests: | ||
| for sec in ("src/Nethermind/{*Test*,*Benchmark*}/**.cs", "tools/*/{*Test*,*Benchmark*}/**.cs"): |
There was a problem hiding this comment.
Low – the test exclusion in .editorconfig doesn't match how scope() decides what counts as a test.
scope() treats a file as a test if any directory under the project matches *Test*/*Benchmark*, for example src/Nethermind/Foo/Tests/x.cs. The .editorconfig section only excludes top-level project directories. A file like that is counted as "test", so it is not fixed, but the rule still applies to it after the PR. CI would then fail on it (if warnings are errors), or the PR would leave hits that aren't mentioned anywhere.
There was a problem hiding this comment.
Fixed in fbb0e54. scope() now marks a file as a test only by its project directory (src/<x>/<Project>/…), which is the same rule as the .editorconfig glob src/Nethermind/{*Test*,*Benchmark*}/**.cs. Test: test_scope_matches_the_editorconfig_exclusion.
Stateless guest costRestored from Only absolute measurements are shown.
|
…row what the bot may change
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 1m 47s —— View job Re-review of PR #16225 (review rule bot), after fbb0e54 and b0a0221
Earlier findings
New findings
The write-token boundary now holds: Not mergeable yet: three new Medium findings, and the C# port question (Medium) still has no answer. |
|
|
||
| attempt() { | ||
| local cluster=$1 why=$2 | ||
| jq --arg c "$cluster" '[.clusters[$c].samples[]?]' "$here/baseline.json" > "$data/route-b-examples.json" |
There was a problem hiding this comment.
Medium – b0a0221 broke this: the analyzer generator no longer gets the baseline examples.
b0a0221 rebuilt baseline.json without the samples key. Each cluster now has only n, valid, human, pr_set, author_set, ex, and ex holds just [url, author], with no body, path or line. So .clusters[$c].samples[]? now returns [], and the prompt's {{EXAMPLES}} gets only this week's new_examples (at most 5, from trusted authors only). That is often zero. With no code shapes to work from, the generator will mostly skip, or guess from why alone. The NETH012 dry run in the PR body used the old baseline, which still had samples.
Fix: put samples back in baseline.json (filtered to OWNER/MEMBER/COLLABORATOR authors, to keep the injection fix), or change this line to read whatever key now holds them. A unit test that checks every route-B cluster has at least one example would catch this next time.
There was a problem hiding this comment.
Fixed in fb90308. baseline.json has a samples list again for every cluster. It holds up to 5 comments per cluster, from people (not bots) whose author_association is OWNER, MEMBER or COLLABORATOR, and whose comment counts as valid, with the body cut at 500 characters. route-b.sh reads .clusters[$c].samples as before. Test: Baseline.test_route_b_clusters_have_trusted_samples checks that every route B cluster in routes.json has at least one sample with a body from a person.
| return bad | ||
|
|
||
|
|
||
| def patch_changes(text): |
There was a problem hiding this comment.
Medium – guard --patch passes patches that don't use diff --git headers.
patch_changes only notices files that have a diff --git a/X b/X header. git apply also accepts traditional unified diffs, and paths that git quotes ("a/…") don't match \S+ either. Reproduced:
--- /dev/null
+++ b/.github/workflows/evil.yml
@@ -0,0 +1 @@
+on: push
guard --patch → guard: PASS (0 files). git apply then creates .github/workflows/evil.yml. A hunk like this placed after a valid header is also credited to the previous file.
In open-pr, the tree guard that runs after git apply still catches this, so the write token stays safe. But in measure (line 166) and fix (line 316), the patch guard is the only check before git apply and dotnet build. There, an analyzer.patch from a compromised route-b job could drop a Directory.Build.targets that runs during the build.
Fix: let git parse the patch instead of a regex. Use git apply --numstat --summary -z <patch> for the paths and modes, and fail closed if the patch has any ---/+++ pair that isn't in that list. Alternatively, apply the patch and then run the tree guard (guard --base HEAD) before any build, as open-pr does.
There was a problem hiding this comment.
Fixed in fb90308. patch_changes now tracks hunk line counts, and any ---/+++ header outside a hunk counts as a change. If that header names a file other than the current diff --git file, it is listed as X and rejected. Your example now gives guard: FAIL .github/workflows/evil.yml (exit 1). Also, measure and fix now run the tree guard (git add -N . + guard --new-id) right after git apply, using the copy of the guard made before the patch. Tests: test_patch_changes_sees_files_without_git_header, test_patch_changes_sees_second_file_inside_git_block.
| cp -r scripts/rule-bot "$RUNNER_TEMP/rule-bot" | ||
| new_id=() | ||
| [ "$ROUTE" = B ] && new_id=(--new-id "$IDS") | ||
| python3 "$RUNNER_TEMP/rule-bot/rule_bot.py" guard --patch "$DATA/fix.patch" --files "$DATA/fix-hits.txt" "${new_id[@]}" |
There was a problem hiding this comment.
Medium – the file allowlist comes from the job it is meant to limit.
open-pr gets fix-hits.txt from the rule-bot-fix artifact, which the fix job uploads. Arbitrary code can run in that job. The model may Edit(src/**/*.cs), and that includes Nethermind.Analyzers/*.cs, which the compiler runs during the model's own dotnet build. In route B, the generated analyzer also runs there. Code like that can rewrite fix-hits.txt so it lists any .cs file in the repo, and guard --files will then allow changes to those files in the pushed PR. The .github/, scripts/ and non-.cs limits still apply, so the impact stays within .cs files. But "Route A may only modify files listed in fix-hits.txt" doesn't hold.
Fix: get fix-hits.txt (and candidates.json/body.md) from rule-bot-result, which propose uploads before any model edits code. Upload only fix.patch from fix.
There was a problem hiding this comment.
Fixed in fb90308. rule-bot-fix now uploads only fix.patch. open-pr downloads rule-bot-result (uploaded by propose, before any generated code runs) to $RUNNER_TEMP/rule-bot-result, and takes fix-hits.txt and body.md from there for both guard calls and gh pr create.
…e the package from before the fix
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 1m 48s —— View job Third review of PR #16225 (review rule bot), after fb90308
Second-round findings
New findings
The write-token boundary still holds. Every artifact Not mergeable yet: one new Medium (route B can change or delete existing analyzers), and the Medium about porting to C# still has no answer. |
| bad.append(f"{path}: may only be modified") | ||
| elif not path.endswith(".cs") or path.startswith(GUARDED_PREFIXES): | ||
| bad.append(f"{path}: outside the paths the bot may change") | ||
| elif not (new_id and path.startswith(ANALYZER_DIRS)) and not (status == "M" and path in fix_files): |
There was a problem hiding this comment.
Medium: in route B, the guard accepts any change to an existing analyzer, including deleting it.
When --new-id is set, any .cs path under ANALYZER_DIRS passes with any status. That includes M and D on existing files. I checked this against HEAD with guard --patch --new-id NETH099:
- deleting
src/Nethermind/Nethermind.Analyzers/ExistingAnalyzer.csgivesguard: PASS (1 files) - modifying the same file also gives
guard: PASS (1 files)
The PR body says route B may change "only new analyzer and test files, plus one appended row in AnalyzerReleases.Unshipped.md". With this check, a route-B patch could weaken or remove EmptyCatchBlockAnalyzer, BannedConcurrentDictionaryKeysValuesAnalyzer and others, along with their tests. The edited analyzer would then run in measure and fix and change the hit counts there, and it would ship in the PR as a small diff that is easy to miss next to the new files. The tree guard in open-pr runs the same check_paths, so it doesn't catch this either.
Suggested fix: under ANALYZER_DIRS, accept only status == "A" (Unshipped.md already has its own branch). Add a test that M/D on an existing analyzer fails with new_id set.
| elif not (new_id and path.startswith(ANALYZER_DIRS)) and not (status == "M" and path in fix_files): | |
| elif not (new_id and status == "A" and path.startswith(ANALYZER_DIRS)) and not (status == "M" and path in fix_files): |
There was a problem hiding this comment.
Fixed in 7802036. With --new-id, a file under ANALYZER_DIRS now passes only if its status is A. Changes to existing analyzers and tests (M or D) fail unless the file is in fix-hits.txt. Test: Guard.test_route_b_cannot_change_existing_analyzers (M and D of EmptyCatchBlockAnalyzer.cs both fail).
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 27s —— View job Fourth review of PR #16225 (review rule bot), after 7802036
Third-round findings
New findingsNone. The 7802036 change does what it says and doesn't loosen any other check. VerdictThe security boundary holds:
Not mergeable yet: only the C# port Medium is left. One sentence in the PR body explaining why this stays in Python and shell would resolve it. The two Lows can be fixed or answered in a reply. |
…ccept only the rule overlay in .editorconfig
|
Claude finished @AnkushinDaniil's task in 1m 10s —— View job Fourteenth review of PR #16225 (review rule bot), after 5d693dc
Findings from round 13
New findingsNone at Critical, High, Medium or Low. 5d693dc does what it says and doesn't loosen any check:
Nit (not blocking): some numbers in the PR body are out of date. The Changes section says "+3,378 lines" and "tool 853 to 1,732 lines". The tool is now about 1,327 lines ( VerdictMergeable. Every Critical, High and Medium finding from the earlier rounds is either fixed in code or addressed in the design, and no new ones came up. The PR still needs a code-owner approval for |
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 53s —— View job Fifteenth review of PR #16225 (review rule bot), after 4c48bec
What changed
Edge cases I checked:
Earlier findingsEvery Critical, High and Medium finding from rounds 1–14 is still resolved, and this commit doesn't touch the guard, the workflow or the token boundary. New findingsNone. Nit (not blocking): the PR body still says 91 tests, which matches. VerdictMergeable. It still needs a code-owner approval for |
Read analyzer-result.json fields by JSON kind, so a mistyped skip or summary no longer discards a passing analyzer. Stop on rows and fields the previous port rejected: missing required keys, a null route B cluster or queue, hits without solutions, examples without url or author, and a validity outside 0 to 1.
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 1m 6s —— View job Sixteenth review of PR #16225 (review rule bot), after 780a054
What changedThe commit makes malformed input files stop the command instead of being accepted silently:
I checked these edge cases:
Earlier findingsEvery Critical, High and Medium finding from rounds 1–15 is still resolved. This commit doesn't touch the workflow, New findingsNone. Nit (not blocking): the null-thread case in VerdictMergeable. It still needs a code-owner approval for |
…PRs that enable the rule Claude Code 2.1.330 ignores Write(path) allow and deny rules for file permission checks; only Edit(path) rules apply and cover Write. Route B could not write analyzer-result.json and the label step could not write labels.json. OpenPrsFor now counts an open PR only when its .editorconfig diff enables the rule, so a PR that only names the id no longer blocks a package.
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 1m 4s —— View job Seventeenth review of PR #16225 (review rule bot), after f1cab35
What changed1. File permissions now use
Claude Code applies The leading 2. A rule is only treated as a duplicate if an open PR actually enables it. It fails closed in two ways:
The test covers five cases: enable, API error, set to Earlier findingsEvery Critical, High and Medium finding from rounds 1–16 is still resolved. This commit doesn't touch New findings
No Critical, High or Medium findings. VerdictMergeable. The PR still needs a code-owner approval for |
…t only precision labels that match it
stdevMac
left a comment
There was a problem hiding this comment.
P2 — Verify that precision labels cover the sampled diagnostics
scripts/rule-bot/rule-bot.helpers.cs:1021–1042 checks the number of labels and positive verdicts, but never checks that the labels correspond to the hits in sample.json. A labeling response with duplicate entries or entries for different hits can pass the precision gate, and propose treats that result as sufficient to select the new analyzer.
Please pass the saved sample into the precision check, require exactly one label for each sampled diagnostic, and cover duplicate and mismatched labels in the gate tests.
🤖 AI agent (Codex / GPT-6.2-Sol) on behalf of @stdevMac
|
@claude review |
|
I'll analyze this and get back to you. |
|
Claude finished @AnkushinDaniil's task in 1m 16s —— View job Eighteenth review of PR #16225 (review rule bot), after 75d3579
What changed1. Each precision label must match a sampled hit (this addresses stdevMac's P2). 2. Only labels that match the stated reason count as true positives. A true positive now needs Earlier findingsEvery Critical, High and Medium finding from rounds 1–17 is still resolved. These commits don't touch the guard, the deny list or the token handling. New findings
Nit: the PR body's Tests section says 97 tests. There are now 99. VerdictMergeable. There are no Critical, High or Medium findings, and stdevMac's P2 is fixed in code and covered by tests. The PR still needs a code-owner approval for |
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 48s —— View job Nineteenth review of PR #16225 (review rule bot), after cf1031a
What changedEach line of the precision sample in the PR body now shows Earlier findingsEvery Critical, High, Medium and Low finding from rounds 1–18 is now resolved. This commit only changes how the body text is formatted. It doesn't touch the guard, the deny list, the precision gate, the workflow or token handling. New findingsNone. Nit (not blocking): the PR body's Tests section says 97 tests. The suite now has 100. VerdictMergeable. The PR still needs a code-owner approval for |
|
|
||
| internal static async Task<List<long>> OpenPrsFor(string ruleId, CancellationToken token) | ||
| { | ||
| var output = await Gh(["pr", "list", "-R", Repo, "--state", "open", "--search", $"{ruleId} in:title,body", "--json", "number", "--limit", "20"], token, check: false); |
There was a problem hiding this comment.
A PR can enable the rule only in .editorconfig, and a failed search also looks like an empty result. Page through open PRs, check their diffs for the rule, and stop on lookup failure before opening a duplicate.
| { | ||
| long prs = rows.Select(r => r.Pr).Distinct().Count(), commenters = rows.Select(r => r.Author).Distinct().Count(), human = rows.Count(r => !r.Bot), valid = rows.Count(CountedValid); | ||
| var validity = rows.Count > 0 ? Round2((double)valid / rows.Count) : 0.0; | ||
| var fails = new (string Name, bool Ok)[] { ("prs", prs >= 10), ("commenters", commenters >= 3), ("human", human >= 5), ("validity", validity >= 0.6) } |
There was a problem hiding this comment.
Rounding first lets 28/47 (59.57%) pass the 60% gate. Use rows.Count > 0 && valid * 5 >= (long)rows.Count * 3 for the gate and round only the displayed value.
marcindsobczak
left a comment
There was a problem hiding this comment.
Checked at cf1031aa01:
test-rule-bot.csthroughrun-script-tests.cs: 100/100. Four mutants ofrule-bot.helpers.cs, all killed: nogit apply --numstatcross-check inGuard(1 test fails), noFixAllowedinCheckPaths(1), noSameHitsinPrecision(3), no prefix check inAppendedEditorConfigLines(1).- The measure path with the bot's own commands (
overlay --exclude-tests,build.sh,hits,package,guard) on the seven Roslyn projects, with 14 of the 15 route-A ids that are not enforced on master (all but CS1591). - All 85 entry points under
scripts/and.github/actions/, built with that overlay the way "Check C# CI scripts" builds them, and again with only the overlayfixwrites for theunusedpackage. catalogwith the--sdkpath the workflow passes and with the SDK folder that holds theanalysislevel_*files;RecentlyTriedwith a merged route-B PR.GuardedPrefixesmatchesci-change-guard.yml, andmeasure-route-bruns only whenroute-breportspassed.
The guard and the token boundary held in everything I ran. The two Medium points concern the bot's output. For today's candidate ids, some hits in the Roslyn projects and in scripts/ are hits the bot cannot fix, and a failed fix comes back every week.
Verdict: changes needed — the bot can get stuck on a package it cannot fix, and its [*.cs] overlay reaches scripts it neither builds nor may change.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| { | ||
| var chosen = Load<CandidatesFile>(Path.Combine(data, "candidates.json")).Chosen ?? throw new BotExit(1, "package: no chosen candidate"); | ||
| var hits = Load<HitsFile>(Path.Combine(data, "hits.json")); | ||
| var mine = hits.Hits.Where(x => chosen.Ids.Contains(x.Id) && x.Scope == "prod").ToList(); |
There was a problem hiding this comment.
[possible issue] Medium — a package with a production hit in an analyzer or generator project can never pass fix, and it is chosen again every week.
Scope() (L590-596) calls Nethermind.Analyzers and the generator projects prod, so this line puts their hits into fix-hits.txt. The fix model is denied those paths (FixDenyTools, rule-bot.yml:441) and CheckPaths rejects them (L847), so the check at rule-bot.yml:456 always fails. No PR is opened, and RejectedIds reads only closed PRs (L509). So next week propose picks the same package first again (L782), ahead of every other route-A package.
At this head, overlay + build.sh + hits on the seven Roslyn projects give IDE0051 at Nethermind.Serialization.SszGenerator/SszType.cs:465 and IDE0059 at Nethermind.Analyzers/SpanToArrayAtCallSiteAnalyzer.cs:119 (the unused package of the dry run). package lists both, and guard fails an edit to either with "not a file with a listed hit", although both files are listed.
Suggest: in propose, count the hits that FixAllowed rejects, and skip or defer such a package with that reason.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| internal static string Overlay(IEnumerable<string> ids, bool excludeTests = false) | ||
| { | ||
| var list = ids.ToList(); | ||
| var output = new StringBuilder("\n[*.cs]\n"); |
There was a problem hiding this comment.
[possible issue] Medium — the [*.cs] overlay also turns the rule on in scripts/ and .github/actions/ (their own .editorconfig files have no root = true). measure never builds those (CiSolutions, L625-632), and the bot may not change them (GuardedPrefixes). The root Directory.Build.props sets TreatWarningsAsErrors=true, and the file-based apps inherit it.
At this head, with the overlay that fix appends for the unused package, run-script-tests.cs -- --check scripts/rpc-bench/test-json-bench-reuse.cs fails with error IDE0051 at scripts/rpc-bench/run-json-bench.cs:461 and :463: that test includes the file with SCRIPT_TEST, which drops the only uses (run-json-bench.cs:49, :71). Without the overlay it passes. Other candidate ids give CA1031/CA1849/CA2000 errors there too (also in gcp-runner); CA2012 gives none. So a bot PR for IDE0051 would fail "Check C# CI scripts" on hits the bot neither counted nor may fix.
Suggest: append a none section for {scripts,.github}/**.cs next to the test sections (and accept it in OverlaySections). Alternatively, build the scripts in measure and drop any package with hits there.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| run: | | ||
| RULE_BOT_DENY=$("$RUNNER_TEMP/rule-bot/rule-bot" deny-tools) | ||
| export RULE_BOT_DENY | ||
| bash "$RUNNER_TEMP/rule-bot/llm.sh" "$RUNNER_TEMP/rule-bot/prompts/fix.txt" "Read,Glob,Grep,Edit(src/**/*.cs),Edit(tools/**/*.cs),Bash(dotnet build:*)" \ |
There was a problem hiding this comment.
[possible issue] Low — the fix prompt's "unfixable" list has nowhere to go. prompts/fix.txt (lines 8, 10, 15) tells the model to leave or suppress a site it cannot fix and to list it in {{RESULT}} ($DATA/fix-result.json). These tools grant no Edit on that file, and no step reads it. Route B and the label step do grant their result files (RouteBTools in rule-bot.helpers.cs:1109, and line 347 here).
A site left in place fails line 456. A #pragma or SuppressMessage passes the 0-hits check and the guard (which checks paths, not content), and the body then says "all fixed in this PR" (rule-bot.helpers.cs:1197).
Suggest: grant Edit(/$DATA/fix-result.json) and put its unfixable list into the body. Alternatively, drop the suppression clause and fail the guard on added #pragma warning disable or SuppressMessage lines.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| { | ||
| var rows = EditorConfigRules(ReadText(Path.Combine(repo, ".editorconfig"))); | ||
| var sdkDefaults = new Dictionary<string, string>(); | ||
| foreach (var file in GlobIn(Path.Combine(sdk, "analyzers/build/config"), "analysislevel_", "_default.globalconfig")) |
There was a problem hiding this comment.
[possible issue] Low — the SDK half of catalog reads a folder that does not exist. The workflow passes --sdk "$DOTNET_ROOT/sdk/$(dotnet --version)" (rule-bot.yml:63), and this line looks in <sdk>/analyzers/build/config. With SDK 11.0.100 that folder is missing: the analysislevel_*_default.globalconfig files are in sdk/11.0.100/Sdks/Microsoft.NET.Sdk/analyzers/build/config. Entries turns the missing folder into an empty list, so sdkDefaults is always empty. test_sdk_default_warning_counts passes only because it injects the dictionary.
Today nothing changes: no route-A id is warning in those files, and catalog writes the same catalog.json with either path. If the folder is read, the last file in directory-enumeration order wins, not the effective analysis level.
Suggest: use the Sdks/Microsoft.NET.Sdk path, read only the file of the effective analysis level, and fail when the folder is missing. Or drop the SDK part.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| internal static HashSet<string> RecentlyTried(IEnumerable<BotPr> botPrs, IEnumerable<string> clusters, DateOnly today) | ||
| { | ||
| var keys = clusters.ToList(); | ||
| return botPrs.Where(pr => DaysSince(today, pr.CreatedAt) < CooldownDays) |
There was a problem hiding this comment.
[possible issue] Low — 56 days after a route-B PR is opened, its cluster comes back even if the PR was merged, and the bot writes a second analyzer for the same pattern. This check ignores the PR state.
Route A has an end state: a merged rule is warning under [*.cs], so catalog marks it enforced. Route B has none. routes.json keeps the cluster with no ids, and the gates keep passing on the comments that predate the analyzer for the rest of the 180-day window.
Probe at this head: a MERGED PR rule-bot/sleep-neth012-… opened on 2026-10-05 gives RecentlyTried = [sleep] on 2026-11-23 and [] on 2026-11-30. The next attempt gets a new NETH id (L558). With 5 or more production hits it opens an overlapping PR; otherwise it spends a generation and the generated-analyzer matrix.
Suggest: keep a cluster out for good once a route-B PR for it is MERGED, or until comments newer than the merge pass the gates again.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| throw new BotExit(1, $"collect: GitHub API failed: {string.Join(' ', args.Take(3))}"); | ||
| } | ||
|
|
||
| internal static bool IsBot(string name) => Bots.Contains(name) || name.EndsWith("[bot]", StringComparison.Ordinal); |
There was a problem hiding this comment.
[question] Low — should comments that agents post from members' accounts count as hand-written? IsBot and Bots (L118) look only at the login, and Slim takes Bot from User.Type. So an agent-written inline comment posted from a member's account counts toward human and commenters, is valid as likely (CountedValid), and can be one of the TrustedExamples sent to the generator.
On this PR, three member reviews are signed "🤖 AI agent (…) on behalf of @…" in the review body only; their inline comments, which are what collect reads, carry no such line. So a footer check in Slim would catch only agents that sign every inline comment.
The PR body describes the input as comments "reviewers keep writing by hand". If they should not count, Slim could mark rows that carry the footer as Bot (signed comments only); if they should, a sentence in the PR body would settle it.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
| mkdir -p "$logs" | ||
| log="$logs/$(printf '%s' "$solution" | sed 's#/#__#g').log" | ||
| echo "build: dotnet build $solution -c Release $*" | ||
| dotnet build "$solution" -c Release -p:TreatWarningsAsErrors=false -p:EnforceCodeStyleInBuild=true \ |
There was a problem hiding this comment.
[suggestion] Low — this build has no stall guard. build-solutions.yml builds the three src/Nethermind solutions under run-with-stall-watchdog and keeps scheduler tracing for EthereumTests, "the solution that has deadlocked". Here a stall runs until timeout-minutes: 90 (rule-bot.yml:93, :215). With fail-fast and the failure/cancelled conditions on route-b and propose (rule-bot.yml:156, :273), one stall ends the whole week's run with no summary. The watchdog alone would not prevent that: on a stall it exits 1 (scripts/ci/stall-watchdog.md:11-12).
Suggest: run the build under the watchdog (or timeout) and retry it once after a stall.
🤖 AI agent (Claude Code / Opus 5.5) acting on behalf of @marcindsobczak.
…ision gate, scope overlay, SDK config path, stall retry
svlachakis
left a comment
There was a problem hiding this comment.
- Low -
rule-bot.yml:526tests the output ofgh pr listbut ignores its exit status. A failed lookup can let the publish step continue. Assign the command output first and fail the step on error before checking whether it is empty.
|
@claude review |
|
Claude finished @AnkushinDaniil's task in 2m 24s —— View job Twentieth review of PR #16225 (review rule bot), after 755043d
Earlier findings
New findingsNo Critical, High or Medium findings. None of these commits loosens the guard, the deny list or the token handling. Nits (not blocking):
VerdictMergeable. Every Critical, High and Medium finding from rounds 1–19 and from the human reviews is fixed in code and covered by tests. The PR still needs a code-owner approval for |
svlachakis
left a comment
There was a problem hiding this comment.
My previous Low is fixed. The open-PR lookup now fails the publish job on a GitHub error and exits before patch application when a bot PR is open. The CI change guard is the only failing check.

Changes
.github/workflows/rule-bot.yml, a weekly workflow (Monday 04:00 UTC, alsoworkflow_dispatch) that finds review comments reviewers keep writing by hand and turns one such pattern per run into a build rule.scripts/rule-bot/: the pipeline as C# file-based apps (rule-bot.cs,rule-bot.helpers.cs), thin shell wrappers for publish, build and generation, prompts, the pattern list, plus tests (test-rule-bot.cs). The bot keeps no state: nothing is committed and nothing is cached between runs. Each run recomputes everything from the GitHub API over a 180-day window (13 files, +3,112 lines). Size against the Python version: tool 853 to 1,353 lines (rule_bot.pyandroute-b.shtorule-bot.csandrule-bot.helpers.cs), tests 556 to 972.Why
Many review comments repeat the same request (remove dead code, use a throw helper, do not drop a
ValueTask, and so on). Across 4,536 PRs updated between 2026-05-19 and 2026-11-19 (18,828 inline review comments), 1,769 matched one of the patterns inscripts/rule-bot/clusters.json. A build rule catches these before review. #16153 and #16161 were built this way by hand. This workflow keeps doing it every week.How it works
plan: reads every inline review comment created in the last 180 days (
GET /repos/{repo}/pulls/comments?since=…, about 300 pages, about 7 minutes) and the review threads of the PRs with a matching comment. Each comment is counted once (by id), so distinct PRs and commenters come from one pass. It counts each pattern against thresholds (≥ 10 PRs, ≥ 3 commenters, ≥ 5 human comments, where a comment with the signed AI-agent footer counts as a bot, ≥ 60% of comments accepted). It then lists the CA/IDE rules that cover the passing patterns and are not enforced on master.route-b: for patterns that no existing rule covers, Claude writes a new
NETHanalyzer with tests. It tries one pattern per run, and the analyzer is kept only if:Initializeis replaced with a no-op;AnalyzerReleases.Unshipped.md).The queue order rotates weekly, so with N patterns in the queue, a pattern that produced no analyzer comes up again after N weeks if the queue does not change (a change in the queue shifts the order), and each run makes at most one analyzer generation. A pattern is not retried for 8 weeks after a
rule-botPR for it was opened (read from the PR list, not from stored state).measure: a full Release build of every CI solution (the
build-solutions.ymlmatrix and thebuild-tools.ymllist) with the candidate rules at warning. Hit counts come from the compiler output, never from grep. The rules are turned on for.csfiles outsidescripts/and.github/, and each build that stalls past 30 minutes is retried once. Existing rules are built first, and their logs are sealed before any generated code runs. Builds with a generated analyzer run only if it passed its checks, and their logs count only that analyzer's own id.propose: counts hits in production code (test and benchmark projects are excluded) and keeps rules with 5–60 production hits. A new analyzer also needs 20 random production hits labelled by a separate Claude pass with ≥ 18/20 true positives for the reason the review comments state (a hit the analyzer flags for another reason does not count). Rules that an open PR sets to
warningorerrorin an.editorconfigare dropped (a PR that only names the rule does not count; the bot pages through every open PR's files, and a failed lookup stops the run). A rule with a production hit in a file the bot may not change (analyzer and generator projects) is skipped. A rule whoserule-botPR was closed without merge in the last 8 weeks is skipped, a merged one stays out, and nothing is proposed while a PR labelledrule-botis open.fix: Claude fixes the production hits (behaviour-preserving changes only). The job then rebuilds the affected solutions, requires 0 hits left, and checks the changed paths.
open-pr: applies the patch on a clean checkout, re-checks the paths and opens a ready PR labelled
rule-bot. Reviewers come from CODEOWNERS. The PR body has the rule, the hit counts, 3 example review comments with links, the precision sample (new analyzers) and how to revert.The jobs that run Claude never get a token that can write to the repository.
plancreates a read-only app token (pull-requests: read) to read the review comments; it runs no model. Onlyopen-prcreates a token that can write, and it runs no model and no git hooks. Claude Code ignoresWrite(...)permission rules, so every file the model may write is granted, and every denied path is blocked, with anEdit(...)rule. The bot may not change.github/,.agents/,scripts/or any*.mdfile. The one exception is the appendedAnalyzerReleases.Unshipped.mdrow, so an analyzer PR also needs a*.mdcode owner. It uses only existing secrets:APP_PRIVATE_KEYwithvars.APP_ID(as inbump-version.yml) andCLAUDE_CODE_OAUTH_TOKEN(as inclaude-review.yml).flaky-test-fix.ymlalready opens PRs the same way.Manual runs default to
dry_run: true. A dry run stops afterproposeand writes the packages and the PR body to the job summary. A run with nothing to build says why in the job summary.Dry run
The workflow ran locally on this branch before the bot was ported to C# (each
run:step executed as written; checkout, artifacts and cache replaced by local equivalents). It used SDK 11.0.100 and all 15 CI solutions, and every build succeeded.Task.Delaywithout theCancellationTokenin scope)For the new analyzer (this run predates the one-pattern-per-run limit and tried two patterns), the generator skipped the first pattern because the comments do not share one code shape. The second pattern produced NETH012: 11 tests pass, and they fail with the no-op
Initialize. It reports nothing in production code, so no PR. These counts match the earlier hand-made PRs: #16153 and #16161 report the same rules with production counts in the same range.Stateless plan stage (2026-11-21)
Also before the port, the
plansteps ran locally against the live API with the 180-day window: 30,184 inline review comments since 2026-05-25, 302 REST pages, 1,154 PRs read in 47 GraphQL queries, 438 s in total. 16 of 20 patterns pass the thresholds. CA1510, CA1513 and CA1507 are skipped (already warnings on master). CA2012 and the #16153 rules (IDE0051, IDE0052, IDE0059) are still in the list to measure; the #16153 rules are dropped later inproposebecause an open PR already sets them. CA1512 (#16161) is no longer measured: its pattern has 3 human comments in this window, below the threshold of 5.Tests
dotnet run --file scripts/ci/run-script-tests.cs -- scripts/rule-bot: 110 tests pass (the 64 tests of the Python version, ported by name, plus 46 new tests for the guard, the workflow, the route B loop, the Claude Code tool rules, the open-PR check and malformed input files).guard --patch, exit codes, stdout and written files match on every input, with two known differences: on invalid UTF-8 in a diff both exit 1 with different error text, and .NET has a newer Unicode table, so code points unassigned in Python's table count as word characters inrenderkeys.guard --patchdiffers from the Python version on purpose in 1,138 of 1,864 guard inputs. The Python version split patch lines on\r,\f, NEL and LS, whilegit applysplits on\nonly, so a crafted line could hide a file from the guard. The C# guard reads lines as git does and cross-checksgit apply --numstat -z. It also accepts an.editorconfigchange only as an append at the end of the file, because a section header inserted higher up would move existing rules out of scope, and it accepts a new file only with the exact mode100644. Each of the 1,138 was classified against git and the Python guard; none is unexplained. Patches are applied with--index, so a new gitignored file such as*.csproj.useralso fails the post-apply guard.rule-bot.helpers.cs1,722 -> 1,326 lines) against the port at 67b7f65: 7,457 inputs, 4,180 identical, 3,277 differ, 0 unexplained. 3,159 of the inputs put a wrongly typed value in one field of a JSON input file: 980 have the same effect, 2,156 now stop with exit 1 where the earlier port continued, 23 differ only in output text, and none continues where the earlier port failed. Guard: 1,864 inputs, 0 verdict differences; one failing patch reports one extra reason. Classes (one input is in two): wrongly typed fields rejected 2,156, JSON formatting 318, null keys omitted 290, sample selection from the new RNG 169, non-ASCII digits in a log position 168, seed outsidelongrejected 49, wrongly typedlabels.jsonfields fail closed 28, the same fields with a passing precision result already inroute_b.jsonfail closed 50, unreadablelabels.jsonclears that earlier result 6, non-integer seed syntax rejected 7, non-ASCII digits in a test count fail closed 5, a wrongly typedokin the route B precision result fails closed 5, wrongly typed fields that change only output text 23, missinghits.jsonclears an earlier precision result 2, extra guard reason 1, Unicode case folding 1.skiporsummaryis formatted differently (3), an empty result file gets the default skip reason (2), a non-UTF-8 test log changes the summary text (2), and a result file with several JSON documents is rejected as no analyzer (3).$RUNNER_TEMPbefore any generated change is applied and runs that binary from outside the checkout. A test confirms that a hostileDirectory.Build.propsin the tree does not affect the guard.actionlint1.7.12 reports no issues onrule-bot.yml.Review
/.githuband/scriptsare code-owned, so this PR needs a code-owner approval. Before the first scheduled run, a maintainer can run it once by hand withdry_runon (the default) and check the summary.