From ca56098dab67897d17d17e1d19447c9d680b491b Mon Sep 17 00:00:00 2001 From: Elijah Zupancic <490392+dekobon@users.noreply.github.com> Date: Sat, 7 Nov 2026 15:34:08 -0800 Subject: [PATCH] docs(agents): restructure agent instructions for OpenCode V2 and current Claude Code Both tools loaded ~27,000 words at every session start: AGENTS.md plus eight unscoped files under .claude/rules/, the latter via an `instructions` glob in opencode.jsonc. Vendor guidance for both tools is a short always-loaded core (commands, non-derivable conventions, routing), procedures in skills and docs loaded on demand, and deterministic enforcement for zero-exception rules. The always-loaded core is now ~1,700 words. - AGENTS.md rewritten at ~200 lines: commands, the checks outside `make pre-commit` and their triggers, conventions the code cannot say, working rules (worktrees, publication, delegation, shell, tool output, history rewrites, temp files, evidence, issues, tools), a task-to-document routing table, the verbatim bca metric-feedback policy block. - CLAUDE.md and .claude/CLAUDE.md removed. Measured with Claude Code 2.1.317 in fresh `claude -p` sessions: a one-line `@AGENTS.md` shim expands at the repository root but a session started in a subdirectory receives only the shim; with no CLAUDE.md the native AGENTS.md reader loads the full file from either directory. A personal CLAUDE.local.md starting with `@AGENTS.md` loads both from the root; .gitignore and AGENTS.md's opening paragraph say so. - .claude/rules/ removed. Mechanisms condensed into docs/development/{testing,grammar_dispatch,formatting}.md, with headings matching every citation in the tree; the shell, tool-output, history-rewrite and temp-file rules reduced to bullets in AGENTS.md. Incident narratives dropped. - docs/development/agent_isolation.md: the worktree / branch / shared-read-only protocol the fan-out skills follow instead of Claude-specific `.claude/worktrees/` path detection and mandatory `isolation: "worktree"` / Serena / model prescriptions. Child prompts carry the allocation (mode, root, branch, base) and verify against it; orchestrators list worktrees left behind for the user to remove; read-only skills report rather than restore a modified file. - Permission guardrails: `ask` on `git push` / `gh pr create`, `deny` on `git worktree remove|prune`, in opencode.jsonc and .claude/settings.json, documented as guardrails against command spellings rather than enforcement. - Obsolete surface retired: the bca-check.sh compat wrapper and its Makefile lint lines and test, the MultiEdit matcher, the book's OpenCode V1 section and the assertion pinning its GUIDANCE literal. - CONTRIBUTING.md is now the authoritative gate description; the AGENTS.md-only gate material (baseline refresh in both directions, the -merge and rebase --exec recipe, stubtest, bulk-snapshot traps, role-coverage-observe, lint and grammar-pin rules) moved there. - Threshold table removed from AGENTS.md and from DOCS_REPEATING_THE_TABLE; the book copy stays pinned. - ~170 citations of the deleted rule files and the removed AGENTS.md sections retargeted across utils/, Rust comments, baselines, skills, lessons_learned.md, tests/README.md and the book. Reviewed by astra-review at design, mid-point and final checkpoints, then by fable-review, astra-review and sol-review over the whole branch; every finding is incorporated. `make pre-commit` passes. --- .bca-baseline.toml | 4 +- .claude/CLAUDE.md | 9 - .claude/hooks/bca-check.mjs | 2 +- .claude/hooks/bca-check.sh | 9 - .claude/rules/formatting.md | 181 --- .claude/rules/grammar-dispatch.md | 485 ------ .claude/rules/history-rewrite.md | 24 - .claude/rules/macro-comments.md | 84 -- .claude/rules/shell.md | 223 --- .claude/rules/temp-files.md | 147 -- .claude/rules/testing.md | 891 ----------- .claude/rules/tool-output.md | 50 - .claude/settings.json | 6 +- .claude/skills/add-lang/SKILL.md | 42 +- .claude/skills/audit-crate/SKILL.md | 127 +- .claude/skills/audit-file/SKILL.md | 119 +- .claude/skills/audit-naming/SKILL.md | 92 +- .claude/skills/batch-fix/SKILL.md | 124 +- .claude/skills/cleanup-crate/SKILL.md | 73 +- .claude/skills/fix-issue/SKILL.md | 28 +- .claude/skills/improve-crate/SKILL.md | 76 +- .claude/skills/issue-plan/SKILL.md | 4 +- .claude/skills/lessons-learned/SKILL.md | 32 +- .claude/skills/rust-optimize/SKILL.md | 2 +- .claude/skills/scan-project/SKILL.md | 107 +- .claude/skills/simplify-rust/SKILL.md | 2 +- .github/workflows/ci.yml | 2 +- .gitignore | 4 + .pre-commit-config.yaml | 2 +- .role-bypass-baseline.txt | 2 +- .role-census-baseline.txt | 2 +- .role-coverage-baseline.txt | 4 +- .role-coverage-observed.txt | 2 +- .rustfmt-bail-baseline.txt | 4 +- .snapshot-anchor-baseline.txt | 2 +- AGENTS.md | 1302 +++-------------- CHANGELOG.md | 56 +- CLAUDE.md | 161 -- CONTRIBUTING.md | 163 ++- Makefile | 4 +- big-code-analysis-ast/src/c_declarator.rs | 4 +- big-code-analysis-ast/src/cfg_predicate.rs | 2 +- big-code-analysis-ast/src/checker.rs | 18 +- big-code-analysis-ast/src/checker/csharp.rs | 37 +- big-code-analysis-ast/src/checker/objc.rs | 2 +- big-code-analysis-ast/src/count.rs | 4 +- big-code-analysis-ast/src/getter.rs | 30 +- big-code-analysis-ast/src/getter/csharp.rs | 39 +- big-code-analysis-ast/src/getter/kotlin.rs | 9 - .../src/lang_helpers/ruby.rs | 2 +- big-code-analysis-ast/src/lib.rs | 2 +- big-code-analysis-ast/src/macros/kind_sets.rs | 4 +- big-code-analysis-ast/src/node.rs | 2 +- big-code-analysis-ast/src/node/ancestors.rs | 2 +- .../src/roles/control_flow.rs | 2 +- big-code-analysis-ast/src/roles/csharp.rs | 10 - .../src/roles/derived_parity_tests.rs | 16 - big-code-analysis-ast/src/roles/kotlin.rs | 8 +- big-code-analysis-ast/src/roles/mod.rs | 9 +- .../src/roles/space_tree_tests.rs | 108 +- big-code-analysis-ast/src/test_support.rs | 2 +- big-code-analysis-bench/src/verbatim.rs | 2 +- .../src/developers/README.md | 6 +- .../src/developers/new-language.md | 2 +- big-code-analysis-book/src/metrics.md | 97 +- .../src/recipes/agent-feedback.md | 145 +- big-code-analysis-cli/src/commands_tests.rs | 2 +- .../src/default_thresholds_tests.rs | 12 +- .../tests/check/check_thresholds.rs | 88 -- .../tests/cli_ux/corpus_fixture.rs | 2 +- big-code-analysis-cli/tests/common/mod.rs | 4 +- .../tests/discovery/skip_generated.rs | 2 +- .../tests/discovery/warning_flag.rs | 2 +- .../tests/test_metrics_select.py | 2 +- big-code-analysis-py/tests/test_sarif.py | 41 - big-code-analysis-web/src/web/server_tests.rs | 2 +- docs/development/agent_isolation.md | 100 ++ docs/development/benchmarking.md | 2 +- docs/development/formatting.md | 79 + docs/development/grammar_dispatch.md | 186 +++ docs/development/lessons_learned.md | 122 +- docs/development/testing.md | 201 +++ opencode.jsonc | 28 +- src/c_family_space_names_tests.rs | 7 +- src/lib.rs | 4 +- src/metric_set_tests.rs | 2 +- src/metrics/abc.rs | 68 +- src/metrics/abc/csharp.rs | 29 +- src/metrics/abc/elixir.rs | 2 +- src/metrics/abc/go.rs | 2 +- src/metrics/abc/groovy.rs | 2 +- src/metrics/abc/java.rs | 2 +- src/metrics/abc/js_family.rs | 2 +- src/metrics/abc/kotlin.rs | 6 +- src/metrics/abc/lua.rs | 2 +- src/metrics/abc/python.rs | 4 +- src/metrics/abc/ruby.rs | 2 +- src/metrics/abc/rust.rs | 2 +- src/metrics/cognitive.rs | 4 +- src/metrics/container_scope_tests.rs | 4 +- src/metrics/cyclomatic.rs | 2 +- src/metrics/halstead.rs | 4 +- src/metrics/loc.rs | 38 +- src/metrics/loc/bash.rs | 4 +- src/metrics/loc/elixir.rs | 2 +- src/metrics/loc/irules.rs | 2 +- src/metrics/loc/php.rs | 2 +- src/metrics/loc/tcl.rs | 2 +- src/metrics/mod.rs | 2 +- src/metrics/nargs.rs | 495 +------ src/metrics/nexits.rs | 2 +- src/metrics/npa.rs | 34 - src/metrics/npa/kotlin.rs | 109 +- src/metrics/npa/shared.rs | 2 +- src/metrics/npm.rs | 116 +- src/metrics/npm/csharp.rs | 19 - src/metrics/npm/kotlin.rs | 41 - ...otlin_generic_brackets_not_conditions.snap | 4 +- ...ts__kotlin_object_construction_branch.snap | 4 +- ...npm__tests__kotlin_data_class_methods.snap | 12 +- ...tests__kotlin_init_block_not_a_method.snap | 8 +- ...etrics__wmc__tests__kotlin_data_class.snap | 4 +- ...ics__wmc__tests__kotlin_generic_class.snap | 4 +- ...etrics__wmc__tests__kotlin_init_block.snap | 4 +- src/metrics/wmc.rs | 20 +- src/observation_tests.rs | 2 +- src/output/csv.rs | 2 +- src/spaces_tests.rs | 4 +- src/suppression.rs | 2 +- src/test_support.rs | 2 +- src/vcs/cache_tests.rs | 2 +- src/vcs/git/history_coverage_tests.rs | 2 +- tests/README.md | 2 +- tests/api/ast_seam_test.rs | 4 +- tests/api/main.rs | 2 +- tests/corpus/main.rs | 2 +- tests/grammars/alterator_string_flattening.rs | 2 +- tests/grammars/main.rs | 2 +- tests/output_formats/main.rs | 2 +- tests/parity/main.rs | 8 +- tests/parity/ops_metrics_space_parity.rs | 2 +- tests/parity/space_span_containment.rs | 2 +- tests/repositories/big-code-analysis-output | 2 +- utils/bca-claude-hook-test.mjs | 32 +- utils/check-diagnostic-prefix-test.py | 2 +- utils/check-diagnostic-prefix.py | 2 +- utils/check-excluded-manifests-test.py | 2 +- utils/check-excluded-manifests.py | 8 +- utils/check-feature-gates.py | 4 +- utils/check-grammar-build-watch.py | 4 +- utils/check-grammar-marker-sync.py | 6 +- utils/check-manpage-assets.py | 2 +- utils/check-manpage-drift.py | 2 +- utils/check-publish-metadata.py | 2 +- utils/check-role-bypass.py | 2 +- utils/check-role-census.py | 2 +- utils/check-role-coverage.py | 2 +- utils/check-ruff-lockstep-test.py | 2 +- utils/check-ruff-lockstep.py | 4 +- utils/check-rumdl-lockstep-test.py | 2 +- utils/check-rustfmt-bail.py | 18 +- utils/check-safety-doc-pin.py | 6 +- utils/check-snapshot-anchors.py | 6 +- utils/check-test-lang-gates.py | 8 +- utils/coverage-diff.py | 2 +- utils/patch-coverage.py | 4 +- utils/perturb.py | 4 +- utils/worktree-setup-test.py | 4 +- utils/worktree-setup.py | 2 +- 169 files changed, 1622 insertions(+), 5730 deletions(-) delete mode 100644 .claude/CLAUDE.md delete mode 100755 .claude/hooks/bca-check.sh delete mode 100644 .claude/rules/formatting.md delete mode 100644 .claude/rules/grammar-dispatch.md delete mode 100644 .claude/rules/history-rewrite.md delete mode 100644 .claude/rules/macro-comments.md delete mode 100644 .claude/rules/shell.md delete mode 100644 .claude/rules/temp-files.md delete mode 100644 .claude/rules/testing.md delete mode 100644 .claude/rules/tool-output.md delete mode 100644 CLAUDE.md create mode 100644 docs/development/agent_isolation.md create mode 100644 docs/development/formatting.md create mode 100644 docs/development/grammar_dispatch.md create mode 100644 docs/development/testing.md diff --git a/.bca-baseline.toml b/.bca-baseline.toml index 4947a5753..151d5042b 100644 --- a/.bca-baseline.toml +++ b/.bca-baseline.toml @@ -215,7 +215,7 @@ value = 5.0 path = "big-code-analysis-ast/src/checker.rs" qualified = "" metric = "loc.sloc" -value = 1255.0 +value = 1253.0 [[entry]] path = "big-code-analysis-ast/src/checker.rs" @@ -371,7 +371,7 @@ value = 894.0 path = "big-code-analysis-ast/src/roles/mod.rs" qualified = "" metric = "loc.sloc" -value = 2257.0 +value = 2256.0 [[entry]] path = "big-code-analysis-ast/src/tools.rs" diff --git a/.claude/CLAUDE.md b/.claude/CLAUDE.md deleted file mode 100644 index 4916c7579..000000000 --- a/.claude/CLAUDE.md +++ /dev/null @@ -1,9 +0,0 @@ -# .claude/CLAUDE.md - -Claude Code instructions for this repository now live in the top-level -[`../CLAUDE.md`](../CLAUDE.md), which imports shared project conventions -from [`../AGENTS.md`](../AGENTS.md) via the `@AGENTS.md` directive. - -This file is intentionally a stub. See those two files for current -guidance; this one can be removed once you are confident no tooling -references it. diff --git a/.claude/hooks/bca-check.mjs b/.claude/hooks/bca-check.mjs index 8b71d9b0b..8dde819c6 100644 --- a/.claude/hooks/bca-check.mjs +++ b/.claude/hooks/bca-check.mjs @@ -4,7 +4,7 @@ import { fileURLToPath } from "node:url" import { advisory, analyzer, checkout, checkContext, checkArgs, guidance, inside, run, unchanged } from "./bca-common.mjs" const MAX_INPUT = 8 * 1024 * 1024 -const EDIT_TOOLS = new Set(["Edit", "Write", "MultiEdit"]) +const EDIT_TOOLS = new Set(["Edit", "Write"]) // One invocation per successful tool call. No persistent dedup state can outlive a clean edit. export async function checkHook(input, signal) { diff --git a/.claude/hooks/bca-check.sh b/.claude/hooks/bca-check.sh deleted file mode 100755 index 4a3413412..000000000 --- a/.claude/hooks/bca-check.sh +++ /dev/null @@ -1,9 +0,0 @@ -#!/usr/bin/env bash -# Compatibility entrypoint for existing shell-form hook configurations. -set -euo pipefail -if ! command -v node >/dev/null 2>&1; then - printf '%s\n' '[bca-check] Node.js unavailable; advisory check skipped' >&2 - exit 0 -fi -script_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)" -exec node "$script_dir/bca-check.mjs" diff --git a/.claude/rules/formatting.md b/.claude/rules/formatting.md deleted file mode 100644 index 9aec9ce05..000000000 --- a/.claude/rules/formatting.md +++ /dev/null @@ -1,181 +0,0 @@ -# Formatting Rule - -`cargo fmt --check` is not a complete formatting gate. It exits `0` -over code rustfmt declined to format, and rustfmt declines silently. - -## A comment inside a match pattern disables that match - -When a comment sits inside a match *pattern* — between the pattern and -its `=>`, or between `|` alternatives — rustfmt emits the enclosing -match expression verbatim. No warning, no diagnostic, and -`cargo fmt --check` still exits `0`. - -Both spellings trigger it: - -```rust -// Block comment before `=>` -Else /* else-if also */ => { … } - -// Line comments between `|` alternatives -P::IfStatement -| P::UnlessStatement -// Postfix conditional / loop forms (`return 1 if $cond;`) — the -// condition is a real cognitive branch. -| P::IfSimpleStatement -| P::ForSimpleStatement => { … } -``` - -A comment *above* an arm, outside the pattern, is fine and formats -normally. - -**The blast radius is the match, not the file or the item.** Statements -before and after the match in the same function are still formatted. A -misindented line two statements below a bailing match gets fixed, which -makes it easy to conclude — wrongly — that the file is unaffected. - -**`macro_rules!` bodies are not exempt and are not a separate cause.** -rustfmt formats macro bodies by default (`format_macro_bodies`, default -`true`), so a macro body containing a match with an in-pattern comment -bails for exactly the reason above. The `js_cognitive!` body in -`src/metrics/cognitive.rs` was the clearest demonstration of this until -#1136 hoisted its `Else /* else-if also */ =>` comment above the arm, -after which rustfmt reformatted the whole body — the comment was the -only thing holding it back. - -A macro body can also bail for a *second*, unrelated reason: a -metavariable in a position that is not valid Rust, such as the -`LANG::$camel => …` arms of `mk_langs!` (or the pattern repetition -`$ternary $(| $short_circuit)+` that `impl_cyclomatic_c_family!` carried -until #1697 replaced it). No comment is involved there and hoisting one -fixes nothing. The gate cannot tell the two apart, which is why -`.rustfmt-bail-baseline.txt` names the known cause-2 entries. - -## Measuring it - -`make rustfmt-bail` (`utils/check-rustfmt-bail.py`, #1136) is the -measurement. It over-indents **every** match arm in every tracked Rust -file, pipes each through `rustfmt --emit stdout`, and counts the arms -that come back untouched. Per-file counts live in -`.rustfmt-bail-baseline.txt`; increases fail, decreases are silent and -ratchet with `--update`. It is wired into `make lint`, so -`make pre-commit` and `make ci` already run it. - -`./utils/check-rustfmt-bail.py --show ` names each stuck arm with -its line number, which is what you want before editing anything. - -Three things that version gets right and the hand-rolled probe below -did not: - -- **It feeds rustfmt on stdin.** Given a *path*, rustfmt resolves and - recurses into `mod` declarations, so `big-code-analysis-ast/src/getter.rs` and - `src/metrics/cognitive.rs` error out with "file not found for module" - — which reads exactly like a bail if stderr is discarded. On stdin - there is nothing to resolve, so those two probe like any other file. - There is no unprobeable-file class. -- **It ignores `=>` inside string literals and comments.** A bare regex - over the text matches the JS, C# and TypeScript fixtures these test - modules are full of (`const add = (a, b) => a + b`, `public int W => - _w`) and Groovy's spaceship (`a <=> b`). rustfmt never rewrites string - contents, so every one of those reads as a permanent bail: the naive - probe reported 15 in `src/metrics/nom.rs`, 8 in `wmc.rs`, 3 in - `nargs.rs` and 37 in `cyclomatic.rs`, and **all of them were string - literals**. Do not act on a count from a probe that skips this step. -- **It probes every arm, not the first.** The bail is match-scoped, so a - file whose first `match` formats cleanly still hides a later one that - does not (`big-code-analysis-ast/src/getter/c.rs`), and a module whose arms are all - expression-bodied (`… => HalsteadType::Operator,` in - `big-code-analysis-ast/src/getter/go.rs`) has no `=> {` to probe at - all. Over `big-code-analysis-ast/src/getter` the first-arm-only - version gave 11 false verdicts out of 18. - -## Two causes, one measurement - -An entry in the baseline means rustfmt declined to format that region. -It does not tell you why, and there is more than one why: - -1. **A comment inside a match pattern** — this rule. Hoist it above the - arm. -2. **A `macro_rules!` body rustfmt cannot parse** — a metavariable in a - position that is not valid Rust, such as the `LANG::$camel => …` - arms of `mk_langs!`. No comment is involved and hoisting one fixes - nothing. - -Metavariables alone do not cause a bail: `js_cognitive!` interpolates -`$lang` and still formats once its in-pattern comment is hoisted. So -check with `--show` before concluding either way. The baseline file -names the known cause-2 entries. - -## Where it currently bites - -**Do not read a list here — run the gate.** `make rustfmt-bail` prints -the live per-file counts and `./utils/check-rustfmt-bail.py --show -` names the stuck arms; `.rustfmt-bail-baseline.txt` carries the -checked-in counts and, in its header, the cause-2 entries that will -never go away. - -That is a deliberate change from how this section used to read. It -carried a hand-maintained list of files, and that list was wrong twice: -first by naming only `src/metrics/`, which hid the largest cluster -(`big-code-analysis-ast/src/getter/`, 18 of 25 modules) for two revisions of this file, and -then by going stale the moment #1136 hoisted seven comments out of -`src/metrics/cognitive/`. A stale list of bailing files reads exactly -like a clean tree — the failure this whole rule exists to prevent — so -the list is gone. The gate sweeps every tracked Rust file, so no -directory can go unmentioned again. - -## Why it matters - -A bulk or regex-driven edit across sibling modules is exactly the change -that produces misformatted output, and it lands in exactly the files -where the gate cannot see it. During #1086 a regex rewrite of 43 call -sites left hanging-argument calls and over-length lines across several -of these files; `cargo fmt --all` followed by `cargo fmt --all --check` -reported clean, and every one was found by reading the diff instead. - -## How to apply - -- After any bulk, scripted, or regex edit under `big-code-analysis-ast/src/getter/` or - `src/metrics/`, read the resulting diff rather than trusting the fmt - gate. Check indentation and line length by eye. -- Line length is worth a direct check, since it is mechanical: - - ```bash - awk 'length > 100 {print FILENAME":"FNR" ("length")"}' - ``` - - Expect some pre-existing hits in test string literals containing `\n`; - those cannot be wrapped and are not what you are looking for. -- To decide whether a specific region is affected, run - `./utils/check-rustfmt-bail.py --show `; it names each stuck arm - by line. If you perturb by hand instead, three traps, all of which - have already produced a wrong answer here: - - Suppressing stderr. A leaf module formats standalone, but if you - pass rustfmt a *path* to a file with `mod` declarations it cannot - resolve them outside its own tree and errors out — which reads as a - bail if you discard the message. Feeding the text on stdin avoids - the whole class. - - Counting `=>` inside string literals. These modules are full of JS - and C# fixtures; rustfmt never rewrites string contents, so a probe - that does not skip them reports permanent bails in files that have - no bail at all. - - Grepping for the restored indentation instead of checking the - perturbed line. Another untouched line elsewhere in the file matches - the pattern and reports a false "formatted". Likewise, perturbing a - function that does not contain the bailing match proves nothing, - because the bail is match-scoped. -- Do not remove an explanatory comment merely to re-enable formatting. - The per-arm rationale in these modules is load-bearing; hoisting it - above the arm (outside the pattern) is a legitimate fix when the - comment reads just as well there, but manual formatting review is - otherwise the cheaper trade. -- **Do not open a campaign to clear the existing bails.** #1136 decided - they stay: the remaining ones are all section comments inside a long - or-pattern, so hoisting means splitting the arm into identical-bodied - arms that `clippy::match_same_arms` correctly rejects, and every way - of buying the formatting back makes the classifier table harder to - read. `#[rustfmt::skip]` in particular changes nothing the gate - measures — verified by probe — and can only sit on the enclosing - `fn`, so it removes more from `cargo fmt` than the bail does. The - reasoning and the measurements are in the header of - `.rustfmt-bail-baseline.txt`. Hoisting a *single* comment with - nothing to split is still welcome when you are already in the file. diff --git a/.claude/rules/grammar-dispatch.md b/.claude/rules/grammar-dispatch.md deleted file mode 100644 index fdf15aad8..000000000 --- a/.claude/rules/grammar-dispatch.md +++ /dev/null @@ -1,485 +0,0 @@ -# Grammar Dispatch Rule - -Every per-language `Checker` predicate, `Getter` classifier and metric -arm asks a question of a node's kind. Since the role-table series -(#1690, R01–R10, closed by #1701) the *membership* half of that -question — which kinds own a construct, which tokens pay for it — is -declared once per -language in `big-code-analysis-ast/src/roles/.rs` and read -through the predicates `role_table!` emits; the module doc of -`roles/mod.rs` is the contributor reference for the row grammar, what -a table emits, how a consumer reads a row, and **what the mechanism -cannot see**. Read that last section before this file. Where a gate -now catches part of an item, the item says which (§1, §5, §7); the -rest is manual and stays for that reason. - -**A kind list is a coverage claim, not a specification** — whether it -sits on a row or in a surviving `match`. The compiler cannot tell you -it is incomplete, and a metric that scores a valid construct as zero -looks exactly like a construct that legitimately scores zero. Three -gates (`make role-census`, `role-coverage`, `role-bypass`) and the -derived parity suite see a *new, unaccounted-for* kind, a restated -list inside the consumer boundary, and two consumers of one row -disagreeing on a corpus node. None of them judges whether a row's -membership is right, which role should claim a kind, or whether a -consumer reads the right projection. There is no compile error, no -clippy warning, and no test failure for those unless a fixture -exercises the exact shape *and* asserts a value above the base. - -The checklist applies whenever you add a language, bump a grammar pin, -add a kind to a row, or copy a row or a gate from a sibling module. - -## 1. Match every aliased variant - -tree-sitter emits N distinct `kind_id`s for one grammar rule used in N -positions: an unsuffixed `PrimitiveType` plus `PrimitiveType2`, -`PrimitiveType3`, …, all mapping to the same `node.kind()` string. They -are different `u16`s. Matching only the unsuffixed one compiles, runs, -and returns wrong numbers. - -Confirm every numeric-suffix variant of every matched rule is either -listed or excluded with a comment: - -```bash -rg 'Lang::([A-Za-z]+)\b' big-code-analysis-ast/src/getter/ big-code-analysis-ast/src/checker/ big-code-analysis-ast/src/alterator.rs \ - src/spaces.rs src/metrics/ -``` - -The bug class reaches every match on a grammar rule — `alterator.rs`, -`spaces.rs`, and `src/metrics/*` are as susceptible as `getter.rs` and -`checker.rs`. A kind list a role owns belongs on its row in -`big-code-analysis-ast/src/roles/.rs`, and a list several -languages share is a `..name!()` fragment there (`roles/c_family.rs`, -`roles/js_family.rs`, `roles/tcl_family.rs`); what is left in -`big-code-analysis-ast/src/macros/kind_sets.rs` is five alias unions -no row owns — C#'s parenthesised, prefix-unary and variable-declaration -shapes and Go's boolean terminals, read by the ABC and NPA walkers -only. Prefer extending either over open-coding a list. When a rule has -many aliases, prefer one `node.kind()` string comparison over enumerating -seventeen variants — pay the small runtime cost for forward -compatibility. - -**What `make role-coverage` buys here, precisely.** It fails on a kind -id that is claimed by *no* row, excluded by none, and not in -`.role-coverage-baseline.txt` — so a grammar bump that mints a -`PrimitiveType4` is caught the moment the enum is regenerated. It does -**not** catch an alias omitted from the *intended* row: that id is -either still in the baseline as debt, or claimed by some other role, -and the gate passes either way (`utils/check-role-coverage.py`, "What -the ratchet cannot see: … an incomplete row"). So the inventory above -— every numeric-suffix variant listed on the row or excluded with a -reason — stays a manual check, for row declarations exactly as for -the consumers outside the boundary. Do not read "the gate is green" as -"every alias is on its row". - -**After bumping a grammar pin, regenerate the enum first.** Bump both -manifests in lockstep (root `Cargo.toml` and `enums/Cargo.toml` — the -excluded crate cannot inherit the workspace pin), then: - -```bash -cargo run --manifest-path ./enums/Cargo.toml -- \ - -lrust -o ./big-code-analysis-ast/src/languages -``` - -Stable *named*-node ids are not evidence the ids held. Inserting one -anonymous terminal renumbers the whole anonymous block after it, so -`Else` can silently become `)`. Spot-check a known anonymous token with -`bca dump` against the enum. - -## 2. Skip hidden-rule variants, but mark them - -A rule whose name begins with `_` (`_string`, `_multiline_string_literal`) -is hidden: the variant exists in the enum and the parser never emits it. -Check the `Lang::Variant => "name"` arm in -`big-code-analysis-ast/src/languages/language_.rs` before listing a "looks like an alias" -variant. Keep the defensive arm *and* pin its hidden status with a -`!ast_has_kind_id(&parser, Lang::HiddenVariant as u16)` assertion naming -the hidden rule — otherwise a future grammar that promotes the rule -changes behaviour invisibly. - -## 3. Address children by role, never by index - -Use `child_by_field_name("condition")` over `node.child(1)` for any slot -the grammar can precede with an optional preamble. The field name -survives a grammar re-order; the index does not. - -The preambles that have already produced silent miscounts: an -init-statement (`if x := f(); x`), a `constexpr` keyword -(`if constexpr (cond)`), a named-argument label (`m(name: $a)` vs -`m($a)`), and BLANK ALIAS bodies (Lua `repeat … until`). When the -grammar exposes no field for the slot, iterate -`node.named_children(cursor)` and pick by role, with a comment naming -the variant set you verified. - -**Minimum test bar for a new dispatcher arm:** one fixture per optional -preamble the grammar permits, not just the form already in the corpus. - -## 4. Re-derive a sibling's gate against the target grammar - -The semantic role transfers across languages; the node *kind* does not. -A copied child-kind gate compiles, runs, and matches nothing. - -The jump label is the clearest case: it surfaces as -`StatementIdentifier` in the JS family, `Identifier` in Java and Groovy, -`LabelName` in Go, and `Label` in Perl. - -`is_else_if` is the largest, and the one to consult before writing a -new one. Since #1697 every language answers it through its `ElseIf` -row — `Checker::is_else_if` forwards to `roles::::else_if::owns`, -or keeps the trait's `false` where the row is `absent` — and the -strategy is the row's gate. -**Re-derive it rather than trusting the list below** — it moves whenever -a language is added: - -```bash -rg -n 'ElseIf \{' big-code-analysis-ast/src/roles/*.rs # the rows -rg -o 'else_if_(parent_clause|prev_sibling)_gate!\(\s*(\w+)' -r '$1 $2' big-code-analysis-ast/src/roles/ --no-filename | sort -rg -n 'ElseIf \{ absent' big-code-analysis-ast/src/roles/*.rs # the constant-false languages -``` - -| Strategy | Emitter | Languages | -| --- | --- | --- | -| the owner's parent is the else-clause | `else_if_parent_clause_gate!` (`roles/control_flow.rs`) | C, Cpp, Mozcpp, Objc, Rust, Javascript, Mozjs, Typescript, Tsx; PHP's two-word `else if` by its own gate (two clause aliases) | -| the owner's previous sibling is the `else` keyword | `else_if_prev_sibling_gate!` (`roles/control_flow.rs`) | Csharp, Groovy, Java, Kotlin | -| the owner's parent is the outer `if` (no clause node) | hand-written gate on the row | Go | -| the clause node *is* the else-if — a `pays_itself` owner | none needed | Bash, Irules, Lua, Perl, Ruby, Tcl; PHP's one-word `elseif` | -| the owner is the sole statement of the `else:` block (`else_clause → block → if_statement`, #276) | hand-written gate on the row; the Checker is `Branch ∧ ElseIf`, so the `elif_clause` the row also owns stays false | Python | -| `absent` row — the trait default `false` | — | Elixir (`cond` and nested `if/else`, no chain to collapse) | - -A gate that is only the owner's parent kind is not a `fn` at all -since #1794: spell it on the row as `K(under [P, ..])` or -`K(not_under [P, ..])`, which the Python reader and the derived suite -then see. The `ElseIf` family keeps its emitters because their gates -read more than the parent (the clause's previous sibling, the outer -`if`), and because a `fn` stays in cargo-mutants' reach where a row -list does not (`docs/development/mutation_testing.md`). - -Two things that list is worth reading for. The dedicated-clause row -exists because some grammars emit an `elif_clause` / `ElsifClause` / -`Elseif` node with no nested `if` to inspect at all — a shape neither -parent nor sibling can express, and one the `pays []` split row spells -as an owner that pays for itself. And Elixir's `absent` is a declared -answer with its reason on the row, not a stub: the language has no -`else if` chain to recognise. - -**Not every structural fact is a row.** A consumer's projection of an -owner's *child* (the `switch_block` a `Switch` owner nests its arms in) -lives as a named `fn` beside the table with a row test pinning the -relation; the module doc's "Reading a row from a consumer" states the -convention and its two kind-accounting forms (#1701). - -Dump the AST for the construct in the *target* grammar before reusing a -sibling's predicate, and add a fixture that exercises the gated branch — -a suite of only unlabelled inputs proves nothing about a label gate. - -## 5. One kind per operator; parent-guard compound leaves - -A grammar routinely emits an operator as a wrapper node *containing* the -keyword token (`await a()` is an await-expression wrapping an `await` -token). Halstead keys on `kind_id`, so listing both counts every -occurrence twice and inflates `n1` through the two distinct ids. -Classify exactly one kind and verify the stream with `bca ops`. - -The inverse trap: a compound operator (`not in`, `is not`) wraps leaves -that are each valid operators elsewhere. Classify the compound and -return `Unknown` for the inner leaf **only when its parent is the -compound** — a blanket suppression drops every standalone `not x`, -`a in b`, `for x in y`. - -The trap generalises past Halstead: any predicate listing both a -container and a kind it can contain double-counts. Ruby's -`is_closure` matching `Lambda | Block | DoBlock` scored one stabby -lambda as two closures for the same reason. - -On a row the two halves are declared apart and the macro keeps them -apart: a kind in both `owns` and `pays` of one row fails a `const` -assertion at expansion time, so declared owners and declared payers -are disjoint by construction. A consumer that wants the wrapper *and* -the leaf reads two projections — `pays_at_wrapper` and `pays_at_leaf` — so a -deliberate double count is a visible choice at the consumer, never an -accident on the row. The compound-operator case above is still the -consumer's: the row owns `not in` and pays its token, and returning -`Unknown` for the inner `not` *under* the compound is a parent guard -in the classifier, which a row cannot spell: a payer takes -`under [..]`, never `not_under` (#1794). - -## 6. Narrow a dispatch set with a gate, never by deletion - -When a construct over-counts because its node sits in `is_func` / -`is_func_space` while its children are also functions, deleting the -construct's kind regresses its **childless** variant to zero — the form -with no qualifying children relied on that membership to be counted at -all. C# expression-bodied indexers and properties (`this[i] => …;`, -`int W => _w;`) each hit this. - -Gate the arm on child-presence (`!csharp_member_has_accessors(node)`) -and keep `is_func`, `is_func_space`, and `get_space_kind` gated by the -*same* predicate, so the space tree never disagrees with itself. - -The same rule decides which node *keeps* a classification when a -wrapper/leaf pair double-counts: the keeper is the node that exists for -**every** spelling of the construct, verified with `bca dump` rather -than assumed. PHP's `primitive_type` is childless for `callable`, -`iterable`, `mixed`, `void`, `false` and `true`, so keeping the keyword -leaf — the "obvious" innermost choice — would have scored six types -zero (#1293). - -When neither choice can strand a childless node — every wrapper requires -its leaf and the unwrapped spelling carries no wrapper at all — the -hazard is absent and the tiebreak is identity: keep the node whose span -*is* the operand. Ruby's `1r`, `1i` and `1ri` are three constants -distinct from `1`, and only the `rational` / `complex` wrapper's text -says which; billing the leaf files all four under `1` (#1359). Bash's -`$"…"` went the other way for the first reason, not this one — its -`string` child is the node present in argument position, where the -grammar emits no wrapper (#1358). - -**`node-types.json` cannot answer "every spelling" — it describes the -well-formed grammar only.** It says nothing about error recovery, where -a child routinely appears with its documented parent absent, so a keeper -argued from it is argued from half the evidence. #1412 routed Bash's -`heredoc_redirect` and **deleted** the two `heredoc_body` arms on the -grounds that `node-types.json` lists `heredoc_body` as a child of -`heredoc_redirect` and of nothing else. A single-line compound carrying -a heredoc — `f() { cat <.rs` — and -the byte-less pair is each row's kind table, gates aside: it forwards -with no bytes and a *known-empty* chain (`Ancestors::known(&[])`, never -`Ancestors::unknown()`, which would climb). So the two spellings now -disagree wherever a row has a gate that reads the chain, not only where -one reads the bytes. Ruby is the second case: its `block` / `do_block` -open a space only outside a stabby lambda's own body, and -`ruby_byte_less_spellings_stay_the_kind_table` pins that the byte-less -spelling over-approximates there exactly as the pre-row kind list did. -A byte-less call site is therefore wrong on Elixir, Ruby *and* C# today -— C#'s primary constructor is a `parameter_list` gated `under` a type -declaration (#1828), which the known-empty chain cannot see, so the -byte-less pair answers `(false, Unknown)` where the walk promotes it — -and on whichever language next gates an opener. - -Elixir's byte-less pair is also the worked example of a kind list the -bypass gate *exempts* on purpose: `is_func_space` and `get_space_kind` -spell `Source | AnonymousFunction` under `// role-bypass: allow(…)` — -the ungated subset of the `FuncOpener` / `Container` owners, which is -all a spelling with no bytes can answer, and not a forward to -`opens_space`, because the walk's promotion calls the byte-less checker -spelling per node *before* its single keyword read and the forward -would scan each `call`'s target twice more for a known `None`. The -exemption hides a kind later added inside that `matches!`; the derived -suite's `KNOWN_DISAGREEMENTS` names exactly `call` for both, so any -other kind added there fails as an unnamed disagreement, and `call` -itself fails `promotion_reads_each_calls_keyword_once` (#1701). - -This has already landed once. `ops_inner` opened spaces on the byte-less -`is_func || is_func_space`, so `bca ops` returned a bare file-level space -for every Elixir input while `bca metrics` returned a full -module/function tree — no error, no wrong number, just a missing tree -(#1130). `tests/parity/ops_metrics_space_parity.rs` exists to keep the -two walks agreeing. - -## 8. Anchor a default/fallback exclusion to the construct - -A `default` / `else` / `_` arm is +0 only when the construct's *own* -node already paid the nesting or decision increment. The same node kind -routinely serves both a switch-like construct (arm is +0) and a chain -construct (arm is a real +1): Ruby's `Else` is +0 under `case` — which -pays nesting — and +1 under `begin`/`rescue`, which does not. - -Confirm which construct owns the arm before suppressing, and never -blanket-suppress a shared token. Where ABC and cyclomatic must agree, -reuse cyclomatic's existing gate rather than re-deriving the predicate, -and pin `abc.conditions == cyclomatic() - 1` per space (not -`cyclomatic_sum()`, which carries a per-space base of 1). - -## 9. Watch for control flow with no dedicated kind - -In command-dispatched languages (Tcl, iRules, shell-like grammars) a -construct that is semantically control flow may parse as the same -generic `command` node as any other builtin. There is no missing arm to -find — the *kind* the dispatcher would need does not exist. Tcl's -`switch` scored cognitive 0 for exactly this reason. - -Recognise these out-of-band by the command's leading word -(`name` field == `"switch"`) and locate sub-parts by **structural -position** (the sole trailing `braced_word`), not a fixed index, so -optional `-exact` / `-glob` / `--` flags do not break detection. - -## 10. Read the bytes for identity questions - -Structural shape answers "is this an attribute access." It never -answers "whose attribute is it." An `Attribute` whose first child is an -`Identifier` is `self.x`, and equally `db.x` and `logger.x` — Python NPA -counted all three as class attributes until it read the receiver. - -When correctness hinges on *which* object or name, compare the source -bytes with `code.get(start..end)`. Never `to_string_lossy()` (see -`AGENTS.md`). When the language encodes semantics in bare identifier -text (Ruby `private`, Elixir keyword `Call`s), the metric trait needs -`&[u8]` in `compute` — plan the widening with the impl, not as a -follow-up, and standardise on -`<'a>(node: &Node<'a>, code: &'a [u8], stats: &mut Stats)`. - -## 11. Give one input to each independent path - -When two structurally independent paths sum into the same field — a -token arm classifying leaves and a walker arm descending containers — -a fixture covered by *either* reads the right total. The dead path is -invisible from the result. C# ABC's `if`/`while` walker was dead for -every existing test because each fixture's condition contained a -comparison operator that an independent token arm already counted. - -Write at least one fixture only the path under test can classify — a -bare identifier `if (x)` for a walker arm, an empty container for an arm -that descends — and test-via-revert that arm alone per -[`testing.md`](testing.md). - -## When you fix one language, sweep the rest - -Every item above is a per-language failure that almost always exists in -siblings. `big-code-analysis-ast/src/languages/` modules are deliberate clones, so the fix for -one is the audit table for the other twenty. Build that table in the -issue, land the sibling fixes in one commit so the symmetry is visible -to a reviewer, and anchor any known-wrong-but-unfixed case with an -inline `FIXME(#NNN)` so the gap stays in CI rather than in a tracker. -Build it by dumping the construct in each sibling grammar, not by -`rg`-ing for a kind name: a §9 construct has no kind to find, which is -how #1765's PHP `break N` fix recorded "no other grammar has a -numeric-level jump" while Bash's `break n` — a plain `command` — scored -+0 as any other command until the whole-branch review dumped it. - -A `LANG` variant that owns **no file extension** (`mozcpp`) gets no -integration-snapshot coverage at all, because nothing routes to it — -pin it with a parity test against its extension-owning sibling instead. diff --git a/.claude/rules/history-rewrite.md b/.claude/rules/history-rewrite.md deleted file mode 100644 index fc66f7810..000000000 --- a/.claude/rules/history-rewrite.md +++ /dev/null @@ -1,24 +0,0 @@ -# History Rewrite Rule - -`git rebase -i` resolves each todo line's hash as any commit-ish. A -scripted todo edit that names a *superseded* hash — the pre-amend or -pre-fixup copy of a commit, which still exists in the object store — -replays that old commit in place of the current one. Nothing errors: the -rebase completes, later commits apply on top, and the tree silently -loses whatever the old copy lacked. On PR #1609 a reword script naming -the pre-fixup hash of a commit dropped a fix, a fixture and a scaling -probe, and `make pre-commit` then passed on the stale tree. - -## How to apply - -- Before a scripted rewrite, keep the tip: `git branch - backup/-before- HEAD`. -- Build todo edits from hashes in the *current* `git log`, never from a - hash noted earlier in the session. -- After the rewrite, compare trees, not test results. A message-only - rewrite must leave `git diff --stat HEAD` empty. For a content - rewrite, list `git log --format='%T %s'` for both ranges side by side; - every tree should match its old counterpart except where you meant it - to change. -- A gate that passes after a rewrite proves the tree passes, not that it - is the tree you meant. diff --git a/.claude/rules/macro-comments.md b/.claude/rules/macro-comments.md deleted file mode 100644 index 3df536e9a..000000000 --- a/.claude/rules/macro-comments.md +++ /dev/null @@ -1,84 +0,0 @@ -# Macro Comment Hoisting Rule - -When consolidating N near-identical predicates, dispatch arms, or -trait impls behind a `macro_rules!` (`impl_cyclomatic_rows!`, -`impl_exit_from_row!`, `impl_else_if_from_row!`, the various -`c_macro` / `c_langs_macros` helpers), keep the macro body minimal -and hoist *per-call* rationale comments above the macro invocation, -not into the macro definition. - -## Why - -Each pre-consolidation impl typically accumulated language-specific -explanatory comments over months: "why does PHP include `String3`?", -"why does Bash omit `_heredoc_body`?", "why is Groovy's `Assert` -arm distinct?", "what does `OptionalChain` vs `QMARKDOT` cost us in -test fixtures?". Those comments are not redundant — each answers -a question only its language's grammar quirks produced. - -If they collapse into the macro body, the reader at the call site -sees only `impl_simple_is_string!(Php, String, String3, …);` and has -no clue that `String3` is the hidden `_string` supertype, or that the -`String2` alias missing from that list is the `string` *type* keyword -rather than an oversight. The comment is two screens away, attached -to a token-tree the reader has no reason to scroll to. - -## How to apply - -At each macro invocation, place the language-specific rationale -*directly above* the call: - -```rust -// PHP's String2 alias is the `string` *type* keyword, excluded so -// `find string` reports literals (#288 listed it, #1474 withdrew -// it); String3 is the hidden `_string` supertype (lesson #34 — -// defensive arm + drift marker in tests below). -impl_simple_is_string!(Php, String, String3, …); -``` - -The macro body itself should contain only the structural pattern — -not language-specific narrative. The macro's *own* doc comment -(`///`) can describe the shape (`takes a language, a list of -variants, emits a `matches!()` against them`) but not per-call -particulars. - -## Failure mode this guards against - -When the macro is later refactored or extended (a new language is -added, a new slot is introduced, the macro is replaced by something -narrower), the per-call comments survive the change — they are -attached to each invocation, not to the macro shape. If they were -inside the macro definition, refactoring the macro would risk -deleting them or making them irrelevant to the new shape. - -Lesson #34 documents the related case of hidden-rule variants; -this rule is the call-site discipline that makes those defensive -arms self-explanatory at the call site even after another round -of macro consolidation. - -## Row comments in a `role_table!` - -A `role_table!` invocation (`big-code-analysis-ast/src/roles/.rs`) -is the largest macro call site in the tree, and the same rule applies -one row at a time. The module doc of `roles/mod.rs` ("Reading a row -from a consumer") states what a row's comment may and may not say — -the grammar, not the consumer's policy; cite it rather than restating -it. Where each kind of rationale goes: - -| what it explains | where it lives | -| --- | --- | -| the grammar fact a row encodes — what the construct's nodes are, how they nest, why an alias is listed or left off | a `//` comment on the line above the row, inside the invocation | -| why a gate exists and what it reads (`gated_by f`, `text_gated_by f`) | the `///` doc on the gate `fn` beside the table | -| why an owner is gated `under [..]` / `not_under [..]` its parents — a gate with no `fn` to carry it | the `//` comment above the row, as the grammar fact it is | -| why a kind the author considered is not on the row | the `excludes [K "why"]` string itself — it is read by the coverage gate and printed with the residue | -| which consumer reads which projection, and why it counts there | at the consumer, in `big-code-analysis` | -| the shape of the macro — what `owns`, `pays`, `opens` mean | `roles/mod.rs` only, never a row comment | - -Groovy's `Switch` row after #1701 is the model: the `//` comment above -it states the grammar fact, the `excludes` string the rejection, and -the consumer's reading sits in `src/metrics/cognitive/groovy.rs`. - -The failure mode is the same as above: a row comment that explains a -consumer's reading is wrong the day that consumer changes, and the -reader deciding whether the row is right has no way to tell the stale -policy sentence from the grammar fact beside it. diff --git a/.claude/rules/shell.md b/.claude/rules/shell.md deleted file mode 100644 index fffc20170..000000000 --- a/.claude/rules/shell.md +++ /dev/null @@ -1,223 +0,0 @@ -# Shell Rule - -The `Bash` tool runs **zsh**, not bash (`echo $0` → `/usr/bin/zsh`). - -## zsh does not field-split an unquoted parameter expansion - -In POSIX sh and bash, `$var` unquoted is split on `IFS`. **In zsh it is -not.** The value arrives as a single word, however many spaces or -newlines it contains. - -This is the one zsh/bash divergence that reliably produces a *wrong -answer rather than an error*, because the command still runs, still -exits 0, and still prints a plausible result. - -Measured in this repository's shell: - -| expression | zsh | bash | -| --- | --- | --- | -| `FLAGS="-p a -p b"; cmd $FLAGS` | **1 argument** | 4 arguments | -| `FILES=$(cat two-lines); for f in $FILES` | **1 iteration** | 2 iterations | -| `for f in $(cat two-lines)` | 2 iterations | 2 iterations | -| `cmd "${ARR[@]}"` where `ARR=(-p a -p b)` | 4 arguments | 4 arguments | - -Note the third row. **Command substitution *is* split in zsh** — only -*parameter expansion* is not. So `for f in $(rg -l pattern)` behaves as -you expect, and the trap is specifically the intermediate variable: -assign the output first and the loop silently collapses to one -iteration. Do not "fix" the working form while chasing this. - -## What it cost here - -Two measurement loops during the #1090-#1151 batch, both of which -produced confident, uniform, entirely fabricated numbers. - -Re-measuring #1143's threshold offenders: - -```zsh -SCOPE="-p src -p big-code-analysis-cli/src -p big-code-analysis-web/src" -for spec in nargs=7 nargs=6 abc=50 cognitive=15; do - bca check --no-config --exclude-tests $SCOPE --threshold "$spec" … -done -``` - -`$SCOPE` reached `bca` as the single argument -`-p src -p big-code-analysis-cli/src -p big-code-analysis-web/src`, -which matched no path, so every row reported **0 offenders**. Seven -rows of zeros is a coherent-looking result — "the repo is already -compliant everywhere" — and it is the answer that would have shipped -had the number not been implausible enough to re-check. The array form -reported 19, 73 and 127. - -## How to apply - -- **Build argument lists as arrays, expand them quoted:** - - ```zsh - SCOPE=(-p src -p big-code-analysis-cli/src) - bca check "${SCOPE[@]}" --threshold cognitive=15 - ``` - - `"${ARR[@]}"` expands to one word per element in both shells. This is - the only spelling that is correct in zsh *and* bash, so prefer it even - in a script you think only zsh will run. - -- **Iterate lines with `while IFS= read -r`, never through a variable:** - - ```zsh - while IFS= read -r f; do …; done < list.txt - rg -l pattern | while IFS= read -r f; do …; done - ``` - - This also survives paths containing spaces, which the split forms do - not. - -- **When a loop must reuse a captured list, capture into an array:** - `FILES=("${(@f)$(cat list.txt)}")` splits on newlines only, or just - re-run the command inside the `for`. - -- **Sanity-check any measurement loop against a single hand-run case - before believing the table.** One `bca check -p src …` typed out in - full would have caught this immediately. A loop that emits a tidy - column of zeros deserves that check specifically, because zero is - what every one of these failure modes produces. - -## Two siblings worth knowing - -Both bit the same measurement in the same session, and both also yield -a plausible number rather than an error: - -- **`$?` after a pipeline is the *last* stage's status.** - `cmd | head` reports `head`'s success even when `cmd` failed. zsh - spells the per-stage array `$pipestatus` (1-indexed); `PIPESTATUS` - is bash-only and expands to nothing here. -- **`bca check` writes offenders to stderr.** `2>/dev/null` on a check - invocation discards the entire result and leaves an empty stdout that - reads as "no offenders". - -## A `pgrep -f` wait loop matches itself and never exits - -`pgrep -f` matches against the **full command line**. When a wait loop -is passed as text — `zsh -c "until ! pgrep -f 'make pre-commit' …"`, -which is exactly how the `Bash` tool runs every command — that text -*is* the shell's argv. The loop therefore finds itself, the condition -never goes false, and it runs until the machine reboots: - -```zsh -# Never exits: this shell's own argv contains "make pre-commit". -zsh -c "until ! pgrep -f 'make pre-commit' >/dev/null; do sleep 30; done" -``` - -**The `-c` part is the precondition, not incidental.** The identical -loop inside a script file has argv `zsh /path/to/waiter.sh`, does not -match itself, and exits normally — verified by probe. So the bug is -specific to the way commands are issued here, and a reader who fails to -reproduce it from a `.sh` file has not disproved it. - -The failure is silent in the way the rest of this file describes: no -error, no output, nothing in the log. It reads as "the job is still -running", which is indistinguishable from the truth right up until you -notice the job finished half a day ago. - -Ten of these accumulated in one session here — seven waiting on a -`make pre-commit` that had long since written its `BCA_GATE: pass`, -three on a finished `collect.sh`. Each spun a `sleep` every 15-30s, the -oldest for twelve hours. They also **match each other**, so killing one -at a time does not help: six siblings keep the seventh's condition -true. `pgrep -af ` is the diagnosis — if every PID it prints -is a waiter, that is the whole bug. - -### How to apply - -- **Prefer a condition that is not a process at all.** The artifact the - job produces cannot match the watcher — and bound the wait, because - an unbounded loop on a job that dies is the same hang by another - route: - - ```zsh - log=$(mktemp /tmp/bca-pre-commit.XXXXXX.log) - make pre-commit >"$log" 2>&1 & - - for _ in {1..90}; do # ceiling: 90 x 20s = 30 min - grep -qs '^BCA_GATE:' "$log" && break - sleep 20 - done - - grep -s '^BCA_GATE:' "$log" || - { echo "no BCA_GATE line after 30 min — crashed, killed, or still running" >&2; exit 1; } - ``` - - Three details earn their place (and a fourth, the `mktemp` template, - is [`temp-files.md`](temp-files.md)'s). The `for` ceiling is what - makes a dead job a bounded failure instead of a hang. `-s` on both greps - suppresses `No such file or directory` before the log exists — - without it the loop emits one stderr line per tick, forever. And the - trailing `grep ||` makes the no-verdict case exit non-zero, so - "silence" cannot read as success; that is the third state - [`AGENTS.md`](../../AGENTS.md) names under "Reading the verdict". - - Exit 0 here means *a verdict appeared*, not that it said `pass` — - read the line, as that section requires. - - Verified against four cases: verdict already present (breaks early), - verdict arriving mid-wait (picked up), log present with no verdict, - and log never created (both exit 1, no stderr noise). - -- **When it really must be a process, break the self-match** with a - bracket class, the standard `ps | grep` trick — `[m]ake` matches the - string `make` but the pattern itself does not contain it: - - ```zsh - until ! pgrep -f '[m]ake pre-commit' >/dev/null; do sleep 30; done - ``` - - Verified both halves by probe: the bracket watcher does not appear in - its own `pgrep` output (so the loop exits), and the pattern still - matches a real process whose argv contains `make pre-commit`. The - naive form in the same probe matched itself and hung. - - It protects the watcher from *itself* only. Any other process quoting - the plain string still matches — a sibling watcher written the naive - way, a `ps | grep` someone left running, an editor holding the - command in a buffer. That is why the file-artifact form above is the - first recommendation and this one the fallback. - -- **Do not reach for `$$` to exclude yourself. It does not work.** - The obvious repair — - - ```zsh - # BROKEN. Hangs exactly like the naive form. - until ! (pgrep -f 'make pre-commit' | grep -qv "^$$\$"); do sleep 30; done - ``` - - — fails because the watcher is not the only process carrying that - argv. The command substitution and the `(…)` subshell both fork from - it and inherit it, so `pgrep` returns several PIDs where `$$` is only - one: - - ```text - watcher $$ = 1347315 ; pgrep sees: 1347301 1347315 1347316 - ``` - - Filtering one PID can never empty that list, the pipeline stays true, - and the loop never ends — measured, in both quoting styles. (Under - `zsh -c "…"` there is a second, independent defect: a double-quoted - `$$` is expanded by the *parent* before the child ever sees it, so - the watcher excludes someone else's PID.) The bracket class above - avoids the whole class, because it forks no subshell and `pgrep`'s - own argv carries `[m]ake`, not `make`. - -- **Do not poll for harness-tracked work at all.** `Bash` with - `run_in_background` re-invokes on exit, and `Monitor` streams events. - A hand-rolled waiter is only for something neither can see. - -- **Check for leaks before ending a long session**: `pgrep -af 'do - sleep'`. A waiter costs almost nothing, but it outlives the session - and the next one inherits a process list nobody can account for. - -Every snippet in this section was run before it was written down. The -first draft was not: the bracket form was probed and the other two were -reasoned about, and both of the reasoned ones were wrong — one hung, -one claimed a timeout it did not have. In a file about shell that -returns a plausible answer instead of an error, an unrun example is the -defect it documents. diff --git a/.claude/rules/temp-files.md b/.claude/rules/temp-files.md deleted file mode 100644 index 2b7caadab..000000000 --- a/.claude/rules/temp-files.md +++ /dev/null @@ -1,147 +0,0 @@ -# Temp Files and Evidence Rule - -Every file an agent writes outside the tree is in one of three tiers, -and the tier decides the directory. Decide it *before* the first -write: a file parked in the wrong tier is the one that is gone when -you need it, and nothing warns you at the time. - -## The three tiers - -Work down the list; the first match wins. - -### 1. Cannot be regenerated - -A hand-written oracle fixture, a perturbation driver, a comparison -harness, a captured output whose producer no longer exists. If losing -it would leave a claim nobody can re-measure, it does not belong in a -temp directory at all. - -- A **fixture** that pins a behaviour becomes a regression test under - `src/` or `tests/`, where it is run and gated. -- A **driver or harness** that is reusable across issues goes under - `utils/`, where it is linted and self-tested like the gates there. -- Anything that fits neither and is ≤ 25 MB compressed is **attached - to the issue or PR** that cites it, so the claim and its inputs travel - together. -- **Otherwise, stop and ask the user.** That covers a file too large to - attach, one with sensitive or third-party content, one with no issue - to attach it to, and a per-issue driver that is not obviously - worth a permanent home (the #1724 toolchain probes that diffed two - `.pot` outputs stayed out of the tree; the check they motivated is - `utils/check-xgettext-backend.sh`). Keep the only copy where it is - until you have an answer — "do not park it in `/tmp`" never means - delete it. - -### 2. Regenerable, but expensive or needed across sessions - -A base-vs-head corpus dump, a coverage profile, a built binary for a -superseded commit, a benchmark log you will compare against next -week. Everything here can be rebuilt from the tree and a command, so -the risk is cost, not loss — which is what `/var/tmp` is for. - -```zsh -issue_dir=/var/tmp/bca/ -mkdir -p "$issue_dir" -run_dir=$(mktemp -d -p "$issue_dir" '.XXXXXX') -``` - -Three things that shape earns: - -- **`/var/tmp/bca//` is deterministic** so the next session can - find it without being told; `mktemp -d` *inside* it - keeps two concurrent runs — two agents on the same issue, or a - re-run beside its predecessor — from overwriting each other. Name - the run directory after what it holds (`corpus-base.XXXXXX`, - `coverage.XXXXXX`, `bench.XXXXXX`), not after the tool. -- **Check the root before trusting it.** `/var/tmp` is sticky and - world-writable, and `mkdir -p` succeeds on a directory someone else - owns. On a shared host, `[ -O /var/tmp/bca ] && [ ! -L /var/tmp/bca ]` - must hold; if it does not, stop rather than write into it. -- **Every run directory carries a `PROVENANCE.md`** naming the commit, - the command that produced each file, and what to run to regenerate - it. A cache without that is a pile of numbers; with it, the cache is - optional. - -**A claim never cites this directory.** `AGENTS.md`'s "Support for a -claim goes where the claim is" governs what an issue or PR comment -points at — the numbers, the revisions, the exact command, a fixture -in the tree — and a path on one host is a citation to nothing. This -tier is the working cache that lets *you* avoid re-running the command -tomorrow; the `PROVENANCE.md` is what makes the cache disposable once -the comment carries the command. `/var/tmp` survives a reboot but is -not archival: systemd's upstream `tmpfiles.d/tmp.conf` ages it at 30 -days (`q /var/tmp 1777 root root 30d`); Ubuntu ships that line -commented out, and other distributions may not. Check the host's -`tmpfiles.d` when a run needs to outlive that, and ask the user when -nothing on the host can keep it long enough. - -### 3. Easily regenerated, truly temporary - -A pre-commit log, an issue body on its way to `gh --body-file`, a -one-shot `bca` dump, a `git archive` scratch tree. These go in `/tmp` -and are allowed to disappear on the next boot. - -```zsh -log=$(mktemp "${TMPDIR:-/tmp}/bca-pre-commit.XXXXXX.log") -body=$(mktemp "${TMPDIR:-/tmp}/bca-issue-body.XXXXXX.md") -scratch=$(mktemp -d "${TMPDIR:-/tmp}/bca-scan.XXXXXX") -``` - -- **Always `mktemp`, never a fixed name.** `/tmp/pc.log`, - `/tmp/issue-body.md` and `/tmp/scan-metrics.json` are shared by every - checkout, worktree and agent on the host; one agent has already - diagnosed another's `fmt-check` failure from a shared log - (`CONTRIBUTING.md`, "Reading the verdict"). -- **The template names the source.** `bca-.XXXXXX[.ext]` reads - in `ls /tmp` as what it is and who wrote it; GNU `mktemp` accepts the - suffix after the `X`s, so the extension can stay for tools that key - on it. Quote the whole template: `${TMPDIR:-/tmp}` is a parameter - expansion, and unquoted it is subject to word-splitting and globbing - in bash. -- **A harness-preferred scratch directory is still tier 3.** - `/tmp/opencode/`, `$TMPDIR`, and plain `/tmp` are interchangeable - here — honour `TMPDIR` when it is set, and do not keep anything in - any of them that the next session needs. -- **Hand a random path forward explicitly.** A skill that allocates a - directory in step 2 and reads from it in step 8 must print the - resolved absolute path and pass it to every later step and - subagent; a variable does not survive a tool-call boundary. - -## Typical placements - -The tier is a property of the *need*, not the file type: a pre-commit -log you must compare against next week is tier 2, and a review diff -holding edits that exist nowhere else is tier 1. The table is where -each usually lands. - -| Artifact | Usual tier | Where | -| --- | --- | --- | -| `make pre-commit` log | 3 | `mktemp "${TMPDIR:-/tmp}/bca-pre-commit.XXXXXX.log"` | -| `gh` issue / PR body, comment | 3 | `mktemp "${TMPDIR:-/tmp}/bca-issue-body.XXXXXX.md"` | -| `bca` corpus dumps for a base/head diff | 2 | `/var/tmp/bca//corpus-.XXXXXX/` | -| `llvm-cov` JSON, patch-coverage report | 2 | `/var/tmp/bca//coverage.XXXXXX/` | -| base / head `bca` binaries, worktree checkouts | 2 | `/var/tmp/bca//bin.XXXXXX/` | -| bench-scaling logs kept for comparison | 2 | `/var/tmp/bca//bench.XXXXXX/` | -| perturbation driver, comparison harness | 1 | `utils/`, or attached to the issue | -| hand-written oracle fixture | 1 | a regression test; interim copies may sit beside the tier-2 run that used them | -| review-packet diff of *committed* work | 3 | `mktemp "${TMPDIR:-/tmp}/bca-review.XXXXXX.diff"` | - -## What it cost here - -Two fixture files of the #1696 oracle lived only in `/tmp/opencode/` -and were lost to a host restart mid-review. They were rebuilt from the -recorded verbatim exports and dumps — possible only because the -outputs had been kept, and the outputs happened to encode the inputs. -The #1710 workflow harness sat under the earlier `~/bca-evidence/` -convention beside the captures it produced, a check that would never -run again; it is `utils/mutation-workflow-test.py` now, under `make -mutation-workflow-test` — the tier-1 move this rule asks for, made -after the fact. - -`~/bca-evidence//` was the convention before this rule. It was -one directory for every tier at once, which is why 196 GB of -regenerable corpus output sat beside a handful of irreplaceable -drivers with nothing to tell them apart. `AGENTS.md` retired it as a -*citation* target; this rule retires it as a *location*. Its contents -moved to `/var/tmp/bca//` when this rule landed, and the tier-1 -pieces still there are listed as follow-ups on the PR that moved them. diff --git a/.claude/rules/testing.md b/.claude/rules/testing.md deleted file mode 100644 index 1352effa3..000000000 --- a/.claude/rules/testing.md +++ /dev/null @@ -1,891 +0,0 @@ -# Testing Rules - -Project-specific testing practices for big-code-analysis. These -supplement, not replace, the test-quality lessons in -[`docs/development/lessons_learned.md`](../../docs/development/lessons_learned.md) -(particularly #6, #7, #23, #31). - -## Verify defensive refactor tests by reverting the production code - -When you add a regression test for a *defensive* refactor — one that -fixes no current bug but pins an invariant against future drift -(e.g., #306's `apply_suppression` Unit-kind predicate) — the test -must demonstrably fail against the pre-refactor code. A test that -passes under both the old and new implementations protects nothing. - -**Verification procedure:** - -1. Stash or note the production change you just made. -2. `git checkout HEAD~1 -- ` (or manually revert the specific - lines). -3. Run the new test(s). Confirm they fail with the assertion message - you expected. -4. Restore the production change. -5. Re-run the tests. Confirm they pass. - -Two minutes of test-via-revert gives higher confidence than a -passing test alone — it proves the test exercises the changed line, -not an unrelated path. Without this step, defensive refactors often -ship with tests that would pass against the bug they claim to guard. - -**Revert safely — a file-level restore discards your fix too.** When -the file you are perturbing also carries your *uncommitted* production -fix, `git checkout HEAD~1 -- ` (or any `git checkout -- `) -restores the whole file and wipes the fix along with the perturbation. -This destroyed in-progress work twice in one batch (during the #605 -and #615 fix sessions — commits `b8ceb8cf`, `e02ed585`; the incidents -live in the session record, not the issues); in one case the follow-up -build "passed" only because an orphaned-import warning masked the -regression. Step 1 above is therefore load-bearing, -not optional. Concretely, before perturbing a file with uncommitted -work, do one of: - -- commit or `git stash push ` the real change first; -- apply the perturbation as a precise edit and undo it with the exact - inverse edit — never a file-level restore; -- when a partial revert would not build, patch the production line to - a no-op in place instead (the approach used in the #615 fix session). - -**A sweep of several perturbations needs a script, not a shell loop.** -The inverse-edit advice above does not scale past one or two: a loop -that perturbs, tests, and restores is where `git checkout -- ` -gets reached for, and it destroyed an entire uncommitted rewrite a third -time during #1219. Read the file once into a variable, write each -perturbation from that string, and restore from it in a `finally` — the -backup then lives in memory and cannot be defeated by the working tree -changing underneath. Write that same copy to disk before the first -edit, too, for the case below — and when the file carries uncommitted -work, that copy is the only one of it anywhere, so it is tier 1 under -[`temp-files.md`](temp-files.md), not scratch: a reboot while a mutant -is installed would otherwise delete the fix along with the sweep. -`git stash push ` or a WIP commit *before the first perturbation* -is the only acceptable form; if neither suits, stop and ask rather than -start the sweep. `utils/perturb.py` (#1744) is that script: it refuses -a target that is modified, untracked, ignored or absent outright, -keeps the backup in memory and in a `mktemp` directory as bytes, and -rejects an anchor that is absent or equal to its replacement. An -`.orig` in the run directory is a convenience copy for the `cmp` -below, never the backup. Put the driver itself in -a file rather than nesting quotes through zsh into `python3 -c`, -which is how those edits came to be applied inconsistently in the -first place; the driver is tier 1 too, since it cannot be -regenerated, so it goes under `utils/` or onto the issue rather than -beside its own outputs. - -**An interrupted sweep leaves a mutant in the tree, and it looks like -a fix in progress.** A driver killed between a perturbation and its -restore — a server restart, a cancelled agent — never reaches its -`finally`, and production code keeps the mutant. What the next reader -sees is an uncommitted edit that compiles with a warning -(`unused variable: index`, for the dropped `index > 0 &&`) or fails one -test, which is exactly the shape of a half-finished fix, and the -natural response is to finish it. Before trusting partial edits from an -interrupted session, `cmp` each touched file against the on-disk copy -the driver wrote; where the agent that ran the driver can be resumed, -have it do the classification, since it knows which hunks were its own -edits and which its mutant. During #1613 a restart left one mutant in -`doxygen.rs` beside real edits; the resumed agent's `cmp` is what told -them apart. - -**The driver can outlive the session that started it, and then the -mutant comes back.** A harness restart kills the *agent*, not -necessarily the background process it launched: during #1401 a sweep -driver survived a restart and kept perturbing, so the tree `cmp`ed -clean against the `.orig` copy, a test run two minutes later reported -218 passed / 5 failed from a mutant with one arm removed, and a second -`cmp` was dirty again. The order after any restart is `pgrep -af -'[.]py'` **first**, kill what it finds, *then* `cmp` and -restore — a clean `cmp` while the driver is alive is a snapshot of -whichever perturbation it is between, not a verdict. - -**A perturbation whose replacement equals its anchor runs the -unperturbed code and reports zero.** Drivers that build replacements by -`CONST.replace(old, new)` go wrong the moment the anchor stops matching -— a rustfmt re-indent moved four of #1401's arm lists by four columns, -`replace` returned the constant unchanged, and the sweep reported -`0 -> []` for four arms that had each failed a test an hour earlier. -The table looked like four arms had lost their coverage; the driver had -stopped editing. Assert `old != new` beside `count(old) == 1` before -every write, and read a perturbation that newly passes as a harness -question before a coverage question (lesson 94). - -**A broken harness reports a plausible failure count, not an error.** -In that same sweep the restore silently reverted the gate to its `main` -version, so every subsequent perturbation ran the *new* test suite -against the *old* implementation and reported an identical 34 — six -failures and twenty-eight errors, reproducible today by checking out -either side alone. Three perturbations in a row returning the same -number reads as "well covered"; it meant the file under test was no -longer the file being edited. Before believing any perturbation result, -confirm the subject still contains the change: `rg -c ` on -the file, or a `git diff --stat` that shows what you expect. - -**For a compiled subject the rebuild must be inside the measurement -step.** `rg` on the source proves the *source* changed; a sweep that -shells out to `target/release/bca` is measuring the last binary someone -built. During #1412 a corpus sweep reported "0 of 438 files changed" — -a perfectly plausible result — because the restore ran without a -rebuild, so the before and after runs used the same stale binary. Put -`cargo build` in the same step as the run, and assert a known fixture -whose answer differs between the two states immediately after each -build; that guard is what caught it on the rewrite. - -**The result *parser* is the other half of the subject.** During #1238 a -sweep drove three perturbations of one match arm and reported zero Rust -failures for all three, while the Python leg of the same sweep reported -the expected four, five and eight. Nothing was stale — the driver ran -`cargo test -q`, which prints dots rather than per-test lines, so a -parser scanning for `... FAILED` matched nothing and every mutation read -as "no test noticed". A uniform zero across perturbations is the same -tell as a uniform 34: it describes the harness, not the code. Cross-check -any parsed count against the process exit status and treat a -disagreement in *either* direction as a harness bug, not a result. - -**So is the invocation.** `cargo test` stops at the first failing -*target*, so a sweep that names a unit target and an integration target -in one invocation never reaches the second once the first fails — every -perturbation then reports the integration guard as passing, which reads -as a dead guard rather than a harness artifact (#1270). Pass -`--no-fail-fast` in any multi-target perturbation run. - -**So is the target set.** A guard often lives outside the crate that -holds the mutated line, in a dependent crate whose walk reaches the -function without naming it. A sweep over one crate sees only that -crate's guards, so every other guard reads as absent. During #1784 a -sweep over `-p big-code-analysis --lib` reported the new test as the -only failure of a mutant in `big-code-analysis-ast`'s `checker.rs`. -Adding `-p big-code-analysis-ast` showed `rust_outer_attr_scans_agree` -failing too, after the claim had reached the issue and the test's doc -comment. Before writing "only this test catches it", sweep the mutated -crate and every crate that depends on it (`cargo tree --workspace -i - -e normal` lists them), or sweep `--workspace`. A text search -for the function's name is no substitute: the root-crate guard calls -`Ast::metrics` and never names the function, and `rg` found its file -only because a doc comment mentions it. - -**Classify a build failure by `error[` or `could not compile`, never by -`error`.** `cargo test` prints `error: test failed` to stderr on an -ordinary red run, so a driver matching bare `error` reads every -discriminating perturbation as a build break. One sweep returned -BUILD-ERROR for six of seven cases that were in fact all working (#1466) -— a uniform non-answer of exactly the shape the uniform-34 and uniform-0 -tells above describe. - -**A perturbation that *passes* is a finding, not a null result.** It says -the assertion does not depend on the line you neutralised, and the usual -cause is that the test's stated claim is wrong rather than that the test -is weak. Check whether the behaviour is *enforced by the mechanism* or -merely *absent from a list* before strengthening anything: Perl's -statement-modifier walker keys on the grammar's `condition` field, so -adding `ForSimpleStatement` to its arm changes nothing — the `for` -modifier exposes no such field — and a comment claiming the test would -catch a widened arm was false until the sweep proved it (#1464). Correct -the comment; do not invent a fixture to justify it. The inverse error is -equally common: two candidate rankings in #1465 were merely *different -valid orderings* rather than defects, and the honest fix was to trim the -test comment's claim. - -**Re-run the perturbations when two predicates merge.** When two guards -are folded into one shared predicate, re-run the perturbation for every -test that guarded either one. A test can stop discriminating without -failing, because the merged paths can offset each other. During #1539, -once Perl ABC's `and` gate was shared, removing it left one slot row -reading 1: the slot dropped by one and the chain walk gained one. The -row's comment still claimed to guard `perl_condition_scores_itself`, -and only a re-run perturbation showed it no longer did. The comment was -corrected under #1539. - -**Run a perturbation sweep of an imported Python module with -`python3 -B`.** CPython reuses a cached `.pyc` when the source's mtime -(to the second) and size both match. A same-length edit such as `min` → -`max`, restored within the same second, therefore runs stale bytecode on -the next import. In #1562 that produced "isolated test fails, full run -passes" results that described the cache, not the code. For a `unittest` -subject, `utils/perturb.py`'s `"runner": "unittest"` handles this: every -run reads no existing `.pyc` and writes none. By hand, delete the -module's `__pycache__` before the sweep, then run every step with -`python3 -B` (or `PYTHONDONTWRITEBYTECODE=1`). `-B` stops new writes, but -a `.pyc` written before the sweep is still read. - -After restoring, `git status` / `git diff --stat` must show exactly -the edits you intend — nothing extra, nothing missing. - -Applies in particular to: - -- `apply_suppression`-style "make implicit invariant explicit" fixes -- Any `matches!()` predicate tightening -- Any newly-explicit `kind` check that replaces a position-based - index -- Test-quality follow-ups that add `check_func_space` / structural - assertions to previously-vacuous tests (see lesson #31) - -If you cannot test-via-revert because reverting the production -change does not produce a buildable tree (e.g., the change deleted a -helper the new test depends on), construct a synthetic input the -test exercises directly — do not assume the test is correct just -because it passes against the fixed code. - -## When the refactor is compile-time-only, perturb instead of reverting - -A newtype or signature refactor that exists purely to make a -transposition unrepresentable cannot be tested by reverting: undo the -signature and the new test no longer compiles, so there is nothing to -observe failing. Perturb the production line instead — transpose the -two fields the newtype exists to protect — and confirm the new test is -the **only** failure. - -That last clause is the point, not a formality. During #1070, a -transposed `function_depth` / `lambda` inside -`python_comprehension_clause_nesting` left **every cognitive test but -the new one passing** — the whole lib suite reported exactly one -failure — because every consumer folds the three `Nesting` fields into -one sum (`conditional + function_depth + lambda`) and none of the -per-field increments branches on a value. No metric moves under *any* -transposition of those fields. So the issue's framing — that a swap -"would be a straightforwardly wrong metric on every Python -comprehension" — was too strong, and a test asserting a cognitive score -would have proved nothing. Field-level assertions on the map slot were -the only coverage such a refactor can have. - -Two things follow: - -- Run the perturbation against the **whole** suite, not just the new - test. A perturbation that fails hundreds of tests is too coarse to - isolate anything, and one that fails none means the invariant is - currently unobservable — which is worth knowing before you claim the - refactor prevents a bug. -- If the perturbation is unobservable in output, say so in the test's - comment. "Correct-by-construction is the only available defense here" - is a stronger justification for a newtype than an overstated bug - claim, and it stops the next reader from deleting the test as - redundant with the metric assertions. - -Reconstructing a *removed* branch faithfully is often not worth it. -In #1067 the pre-fix rule needed an `is_unit` parameter the fix had -deleted from 23 language modules; restoring it to run one perturbation -would have been a larger edit than the fix. Where that happens, fall -back to establishing the old behaviour by inspection (the removed -arithmetic, plus the issue's own reproducer) and say plainly that the -evidence is inspection rather than a perturbation run. - -See lesson #82 for the related walker case, where the production -bookkeeping and the test's replica of it are two different things and -only a debug assertion in the real walker covers the former. - -## Seed the state you claim to assert on - -An assertion that a function *resets* or *accumulates* something proves -nothing when the fixture starts from the default-constructed value. -`Foo::default()` is usually all zeroes and `None`s, which is exactly the -state a reset produces and exactly the value `+=` and `=` agree on — so -the assertion holds whether or not the line under test exists. - -This is not a hypothetical failure mode. The first two instances below -shipped in the *same* test during #1086, the third in the batch that -fixed #1284; each was measured, not guessed: - -- **A reset asserted from a default fixture** (#1086). The test built - `Stats::default()`, called `increase_nesting`, and asserted - `stats.boolean_seq == BoolSequence::default()`. Deleting - `stats.boolean_seq.reset()` from the production helper failed - **zero** tests across the whole 3,130-test lib suite — the line was - entirely uncovered, and the new test that claimed to cover it did not. - Seeding `boolean_op = Some((1, 0))` first made it the only failure. -- **An accumulation asserted from zero** (#1086). The same test asserted - `stats.structural == 8` from a zeroed `structural`, where - `increment`'s `stats.structural += stats.nesting + 1` is - indistinguishable from a plain `=`. Seeding `structural: 5` and - asserting `13` made the `+=`-to-`=` perturbation fail. -- **A restricted fold asserted on fixtures whose excluded members score - zero** (#1284). Cognitive's and nexits' `average` / `min` / `max` - moved onto the function-space population, and an invariant sweep - over eleven fixtures passed with the numerator perturbed back to the - all-space sum: no unit or container in any fixture carried its own - control flow, so the two sums were equal on every one. The fixtures - now carry module-level flow and the sweep asserts, per metric, that - the two populations differed somewhere. - -The tell is that the expected value equals the default. When you write -`assert_eq!(x.field, 0)` or compare against `Default::default()` after -calling something that is *supposed* to zero it, stop: either seed a -distinguishable value first, or accept that the assertion is decoration. - -**Lesson:** pick fixture values that differ from both the default and -each other, so the assertion can only pass for the intended reason — -and, for a fold over a sub-population, give the *excluded* members a -non-zero contribution, or the restricted and unrestricted folds agree -on every fixture. Then -confirm it by perturbing the exact production line the assertion names — -per the sections above, a test that cannot fail is worse than no test, -because it reads as coverage. - -## Perturb the fixture as well as the production line - -A revert test proves the construct reaches the arm *today*. It says -nothing about whether the fixture still contains the construct tomorrow. -A test that pairs an excluded construct with a genuine condition and -asserts the non-zero total keeps passing after someone trims the -construct out of the fixture, because the surviving comparison supplies -the total on its own — and every #1297 test had exactly that shape, so -each could decay into an assertion about the comparison alone with no -signal. - -Anchor the fixture on a second axis that only the construct contributes, -then verify by deleting the construct from the fixture and watching -exactly that test fail: - -- The three JSX fixtures anchor on `assignments_sum()`: the - `className="x"` attribute `=` is each fixture's only assignment. -- The C# operator overloads are asserted per space rather than through - the file total, which is 3 with the overloads and without them. -- The Perl readlines are three of the sub's four assignments. - -Where the construct contributes to no axis once excluded — a Lua -`` attribute, a TypeScript type argument — there is nothing to -anchor on, and the revert test is the only coverage available. Say so in -a comment, so the missing anchor is not read as an oversight. - -### Retiring a test retires its fixture's shapes too - -A hand-written test is its assertions *and* the inputs they were asked -on. When a derived or shared test replaces it, perturbing the mechanism -and watching the replacement fail proves the mechanism is covered on -the inputs the replacement reads — which need not be the inputs the -retired test read. Before deleting, list the constructs the retired -fixture spelled and confirm the replacement corpus spells each; a -construct only the retired fixture had is a hole the perturbation -cannot show, because the perturbation runs on the replacement corpus. - -#1700 retired `doc_targets_the_space_tree_rejects_by_gate_are_each_named` -after its gated-out shapes were pinned exactly on the derived corpus. -Its fixture had spelled both C# indexer forms — accessor-bodied and -expression-bodied — and the derived corpus's C# fixture only the first, -so between the retired test and its replacement, a `FuncOpener` gate -rejecting *every* indexer was seen by neither (the `nom` and `wmc` -suites pin the expression-bodied form on their own fixtures). The -missing form was added unconditionally to the replacement fixture. - -### Never let the measured value *be* the defect's output - -A fixture whose discriminating quantity is *produced by the bug* stops -measuring anything the moment the bug is fixed. It is the inverse of the -decay above, it bites benchmark probes hardest, and it fails as "the -workload scored zero on its own shape" — which reads like a broken -fixture rather than like the fix working. - -`loc/wide-cfg-test-mod` (`big-code-analysis-bench/src/shapes.rs`) read -`sloc` under `exclude_tests` on a file of nothing but `#[cfg(test)] -mod m {}` repeated. Its only non-zero row was the phantom attribute row -that #1431 then removed, so the probe scored zero and tripped -`probe_workload_is_exercised`. Left unnoticed it would have timed the -walk's fixed overhead and reported an excellent exponent forever. The -repair was to render a retained `fn p() {}` per item, so the reading -survives the fix. - -When a change alters what a shape measures, re-check every probe or -fixture reading *that* metric on *that* shape before comparing a -before/after result. Build the measured quantity out of something the -fix does not touch — for a metric fix, usually retained content -alongside the construct under test. - -### Validate a scaling probe by removing what it prices - -A probe added to pin a memo or cache linear is validated the same way -a regression test is verified by revert: take the memo out, run the -probe, and watch the exponent leave the bound. A probe that stays at -~1.0 either way is timing a path its workload never reaches, and the -timing gate cannot tell that from a working memo — both read "ok". -The failure is placement, not arithmetic: a sibling-scan memo is priced -only by siblings on the side the scan walks, and a workload that puts -them one level up, or on the other side, is linear with or without it. - -`cognitive/elixir-rejected-keyword-list` (#1602, `shapes.rs`) was -written with its comments *inside* the bracketed list, to price the -scan of the siblings *after* that list; the scan never saw them, and -the probe read 1.0 with the memo removed as well as with it. Moving the -comments outside made it fail without the memo (1.68) — and left the -mirror scan, of the siblings *before* the pairs, unmeasured until the -cost audit found that one quadratic on `main` (~2), put comments there -too and removed *that* memo (1.67). Each memo's perturbation is a -separate check; a probe that prices two scans needs both. - -Record the perturbed exponent in the probe's `rationale` beside the -memoised one, as the two `#1602` probes do (1.97 and 1.92 / 1.67 -against ~1.0), so the next reader can see the probe was shown to -discriminate rather than assumed to. - -### Prove a reachability probe can fire - -A temporary assertion run over the suite to show that a branch is -unreachable (lesson 83's probe) reports zero in two cases: when the -branch is unreachable, and when the assertion is dead. It is dead when -it sits where its condition cannot hold, is gated by a `cfg` the run -does not set, or is a `debug_assert!` in a release build. Before reading -zero fires as a finding, drive the branch directly from a throwaway -`#[should_panic(expected = …)]` test and watch it fire. Run any -binary-driven half of the measurement on a dev build for the same -reason. - -#1785's assert in the uncached arm of `Ancestors::previous_sibling` -fired 0 times across 6 890 tests, the self-scan and six `bca` -subcommands. That zero meant something only because a test querying a -200-child root through `Ancestors::known`, with no cache, made it fire -first. When the assertion is kept, keep the control with it: -`previous_sibling_rejects_a_wide_parent_without_its_cache` queries a -root one child wider than `WIDE_PARENT`. - -## Coverage measures execution, not discrimination - -A coverage report answers "did any test run this line?" It never answers -"would any test notice if this line were wrong?" Those come apart -whenever many tests reach a line while all supplying the same value to -the part that matters, and the tool cannot see the difference because -which-inputs-varied is not what it measures. - -`CommaIndex::splits` (`big-code-analysis-ast/src/cfg_predicate.rs`) measured 11 of 11 regions -covered and was entered 150,200 times in one run. Replacing its -`region.start` lower bound with `0` panics on ordinary input — and -before #1105 that perturbation failed **none** of the 3,969 tests then -in the lib targets. - -- Never accept a percentage as evidence a line is guarded. Perturb it. -- Perturb the **sub-expression carrying the invariant** — a bound, an - offset, a comparison direction — not the whole statement, which - usually fails loudly for the wrong reason. -- Treat "the perturbation failed nothing" as a finding to act on. -- When the question is "did this change lose coverage", compare the - **covered count** (`count - missed`) per file and in total, never the - percentage: the denominator moves for reasons unrelated to the change. - This workspace links `big-code-analysis` into five crates, so a file's - report aggregates instantiations that never execute. -- Any scalar summary of a set — coverage percent, test count, snapshot - count — can hold steady while the set changes. Diff the sets when the - comparison is the point. Two `cargo-nextest` listings of the same tree - gave 4,741 and 4,731 purely because one counts `#[ignore]`d entries. -- Before quoting a patch-coverage number, run `cargo llvm-cov clean - --workspace`, then the commands the `coverage` job in `ci.yml` runs, - and read the figure with `utils/patch-coverage.py - `, which applies `codecov.yml`'s `ignore:` list so the - number matches what Codecov's patch status will say. - Profiles left by an earlier build keep mapping functions a refactor - deleted onto the lines their replacements now occupy, so those lines - read as never executed: in CI's own report format, the same library - run of #1526's patch read 47.8% on a stale target and 98.0% on a - clean one. - -## Normalise the expectation, never the observation - -Shared test support earns its terseness by canonicalising — sort the -collection, trim the whitespace, round the float. Applied to the -*expected* value that is fine. Applied to the value returned by the code -under test it silently stops testing a property, for every caller at -once, and no individual test looks wrong. - -`check_ops` sorted `operators_str` / `operands_str` — the observed -values — so eighteen per-language callers could not see that `Ops` -vocabularies came back in `HashMap` order and `bca ops` printed -byte-different output for an unchanged input on consecutive runs -(#1091). The fix sorts in production and drops only the actual-side -sort, turning those same eighteen callers into ordering guards for free. - -Before adding a `sort`, `trim`, `round`, or `to_lowercase` to a returned -value, ask what property you are deleting and whether anything else -asserts it — usually nothing does, because the helper exists so callers -need not restate shared properties. Where a helper already normalises, -remove the normalisation and count the failures: none means the -dimension is untested; many means you just recovered a guard across the -whole caller list. - -## Review the selector as carefully as the assertion - -A test over rendered output must first *select* what to assert on — -filter by indent, find by prefix, search for a substring. The assertion -gets the review attention, but the selector decides whether the claim is -about the subject at all. - -`last_emitted_metric_group_uses_closing_connector` filtered group lines -at three columns while metric groups sit six columns in, so it matched -exactly one line — the `metrics` header — and asserted something true -about it. The test passed with every metric group rendering a dangling -`|-`, the precise defect its name claims to prevent (#1054). - -- Assert the match count: `> 1` where several are required, an exact - number where the shape is fixed. A filter that matches nothing makes - every following assertion vacuously true. -- For indentation-structured output, compare whole lines or whole line - sequences. `contains` cannot discriminate: a deeper rail *ends with* - the shallower one, and labels like `sum` and `value` recur. -- When a test's name states a property, check the selected rows are - capable of violating it. - -## Know what the harness normalises away - -Two chokepoints strip the input class you may be trying to test, and -they sit upstream of nearly every test in the workspace: - -| Path | Normalisation | -| --- | --- | -| a module's `check_metrics` shim → `test_support::check_func_space_with` | `trim_end().trim_matches('\n')`, then `push(b'\n')` | -| integration suites → `read_file_with_eol` → `normalize_line_endings` | unconditional `data.push(b'\n')` | - -Both guarantee a trailing newline, so **"a node ending at EOF" is -unreachable from either harness**. A regression test for that class -written the ordinary way passes against unfixed code. That is why both -issue #1051 (a `usize` underflow on a Rust `DocComment` at EOF) and its -sibling #1067 (`Sloc` keyed on `is_unit` rather than the span's end -column) survived. Use the verbatim helpers in `src/test_support.rs`, which reach -`analyze(Source::new(..))` with no normalisation: `metrics_verbatim` for -a root-aggregate assertion, `space_verbatim` when the claim is about a -*nested* space (#1067's per-function `sloc`). Do not "simplify" either -back to `check_metrics` — their doc comments say why. - -The general form: when a test cannot be made to fail, check for an -intermediate stage that filters, normalises, or short-circuits the input -before it reaches the code under test. Pair any end-to-end test with a -direct unit test on the function whose contract is being verified. - -## Take the expected value from outside the fix - -A metric fixture's expected value, typed by the author of the rule it -tests, certifies that rule. Check it against two oracles the fix did -not write: the construct's spelled-out twin (`case a, b` vs -`if a || b`, a modifier vs its block form, Ruby `elsif` vs Java -`else if`), asserted as a row beside it; and the same input on `main`, -which catches what a twin cannot when the twin shares the gap (`case *p:` -fell to 0 while `if *p` was already 0). Lesson 6 has the four cases. - -## Assertion shapes that are wrong by construction - -- **Never `include_str!` or `fs::read_to_string` the codebase's own - source and string-match it.** The grep is brittle to rustfmt reflow - and satisfied vacuously by adding the identifier in a comment; the - production `matches!()` pattern already *is* the contract. If the - kind_id is grammar-unreachable, document the contract at each call - site instead. The one such test ever written here (#285's - `FunctionDefinition4` regression) was removed as vacuous within - months (#302). -- **Never assert the absence of a structural marker.** A - `!report.contains("### Functions With Many Parameters")` passes - *because* the heading is missing, encoding the bug as the contract — - and inverts into a bug-lock the moment that absence *is* the symptom - (#681). Assert the positive: the heading and its `id` anchor are - present, the suppressed row is absent. -- **Never assert only that a section rendered or a call returned - `Ok`.** Assert the value. `markdown_strip_prefix_accepted` passed - against a no-op implementation. -- **Never build a hash/equality fixture with `Clone`.** A clone is - byte-identical by definition, so the test verifies the derive and not - the constructor — it holds even if the constructor mixes in a counter - or timestamp. Construct both instances through the production - constructor twice. Verified by revert on `PyAnalysisError`: the - clone-based form passed with an `AtomicU64` interleaved into the - field; the two-call form failed. -- **Never compare two structurally-equivalent containers to pin an - ordering contract.** `dict ==` and `HashMap ==` are order-insensitive; - compare against a hand-pinned sequence whose source order is - deliberately non-alphabetical, or compare raw bytes positionally. - -## Gate `#[cfg]` on the `fn`, never on an inner block - -`#[cfg(unix)] { … }` wrapping a test body compiles to an empty body off -target — and an empty `#[test]` is a *passing* test. The harness reports -green on Windows with zero assertions run. The only correct placement is -on the function's attribute stack, alongside `#[test]`, so the test is -hidden rather than vacuous. - -The inverse trap is fabricating a platform-shaped *input* — an -executable name, a path separator, a line ending — in one OS's spelling. -`test_conftest_helpers.py` created `debug/bca` while the locator appends -`.exe` on Windows: green on Linux and macOS, failing only on the Windows -leg. Mirror the production code's platform logic in the fixture -(`bca{EXE}`) rather than hardcoding one OS's form. - -## Gate a feature-gated fixture table on the union of its rows - -A test whose case list is built from `#[cfg(feature = …)]` rows has two -failure modes, and fixing one reintroduces the other. Left ungated, a -feature set that enables none of the rows leaves an empty list, a loop -of zero iterations, and a test that passes having asserted nothing — -which is why `assert_fixtures_present` (`src/test_support.rs`) exists to -make that state loud. But loudness alone turns the same build into a -spurious *failure* that reads as a defect in whatever was being changed. - -Both halves are required: - -- `#[cfg(any(feature = "a", feature = "b", …))]` on the **`fn`**, naming - the union of the features its rows use, so the test is *absent* rather - than failing when none is enabled. -- The non-vacuity assertion (`assert_fixtures_present`, or a `ran > 0` - counter for a hand-rolled loop) inside it, covering the residual case - where a runtime `is_enabled()` check stops agreeing with the feature - it compiled under. - -This bit twice in one batch (#1220, PR #1221). -`the_1184_constructs_open_quiet_function_spaces` had the assertion and -no gate, so `--no-default-features --features rust` failed with "at -least one language feature must be enabled for this test to mean -anything"; its two siblings had been gated in an earlier fix and it was -missed. Then the fix for #1218 -rewrote a Tcl/iRules parity test as a loop, added a `ran > 0` guard, and -reproduced the identical false failure in a second file. - -Verify against a subset that enables **none** of the named features. -`rust,typescript` — the canonical minimal-langs configuration — is not -such a subset for any table containing a TypeScript or TSX row, so a -single non-listed language (`--features go`) is the reproducer. - -Note the union is over *features*, not languages: `LANG::Tsx` rides -`feature = "typescript"`, so a seven-row table can need only six. - -**That verification needs `-p big-code-analysis`.** A workspace-wide -`cargo test --no-default-features --features X` does not isolate features -at all: `big-code-analysis-cli` and `big-code-analysis-web` depend on the -library with default features, and cargo unifies them, so everything is -silently re-enabled. Three different feature sets reported an identical -`4 passed; 3428 filtered out` before this was noticed (#1457) — the -uniform-number tell from the harness sections above. Only `-p` narrowed -it, and then the counts varied (0 / 2 / 3). A feature-gate check run -without `-p` proves nothing, and proves it while looking green; confirm -real isolation by watching the *filtered-out* count differ across sets. - -## Every test that names a language carries that language's gate - -The rule above is about a *fixture table*. The same requirement applies -one level down, to every individual test, and for a blunter reason: -`mk_langs!` generates each `*Parser` alias, `*Code` tag and `LANG` -variant unconditionally, so `check_metrics::(…)` compiles -with `python` off and then panics inside `Tree::new`. Until #1472, -about 2,950 tests named a grammar without gating on it — 2,804 in -`src/`, 104 in `big-code-analysis-ast/src/`, 33 under `tests/`, plus 229 -helpers and fixture tables. Approximate because the figure moves with -the derivation rules themselves: each refinement that stops reading -something as a use lowers it, and this section has already quoted a -higher number taken before the comparison rules landed. A -partial-feature build failed in the thousands. - -`make check-test-lang-gates` derives and enforces it across all three of -those roots: for every item in a test scope it collects the languages -the body reaches — directly, and through same-module helpers that -hardcode a parser — and fails when the item's `cfg` would still admit it -into a build lacking one. A test needs -`all(…)` of what it names; a helper, a `const` fixture table or an -import needs `any(…)` of its users. `--fix` writes the markers and -`--show` prints the derivation. - -Five things the derivation cannot see, so write those by hand and say -why in a comment: - -- **A language chosen from a string.** A helper that maps a path - extension or a filename glob onto a `LANG` hides it — the corpus tests - and `suppression_test.rs`'s `analyze_lang` both did. Prefer passing - the `LANG` explicitly where you can; that is a better call site - anyway. -- **A trait used through its methods.** Nothing names `ParserTrait` in a - body that calls `SomeParser::new`, so its import falls back to the - module's whole union, so it carries no derived gate at all. -- **Anything `pub`.** Its users are in other files, which this - single-file scanner does not see; `src/test_support.rs` is the whole - story. -- **Which grammar a re-export serves.** Same reason, one step further - out — a scoped `#[allow(unused_imports)]` beats a hand-copied union of - seven files' gates. -- **A private item of a parent module that a child file reaches through - `use super::*`.** `roles/doc_tests/doxygen.rs` reads `mod.rs`'s - harness that way; the scanner reads one file at a time, so the - helper's union is derived from `mod.rs`'s callers alone, and `--fix` - *narrows* a correct hand-written union to that. #1699's harness lost - `c`, `cpp`, `mozcpp` and `objc` this way, the four C-family - single-language test builds failed under a green gate, and an - isolated single-language test build is what exposed it. The - `hand-written(c, cpp, mozcpp, objc)` marker on each such item is the - load-bearing one; `utils/check-test-lang-gates-test.py` pins that the - gate keeps it. - -One thing it does see since #1697 that it did not before: a helper -reached only through a **`macro_rules!`-generated test**. A macro body -is a template with no needs of its own, and the gate once read it as an -always-compiled caller, which zeroed the needs of every helper it -invoked — `control_flow_tests.rs`'s shared `check` / `answers!` kept a -two-language gate while a macro-generated Go test called them, and -`--features go` failed with twenty `E0425`s under a green gate. A macro -now inherits the gate of each `mod` that invokes it, so the helpers it -reaches are checked against the union of those `mod`s. The parser named -*inside* the macro is still invisible, which is what the `hand-written` -marker on such a `mod` is for. - -Say so with a marker the gate reads, not prose alone: - -```rust -// test-lang-gates: hand-written(cpp) — the corpus walk picks a -// language per file from its extension, so the glob list decides -// it and nothing in the body names it -#[cfg(feature = "cpp")] -``` - -Because the gate checks the *other* direction too (#1478). A gate wider -than the item needs keeps it out of builds it could have run in, and -that is the failure nothing else can see: too wide panics on the leg -that lacks the grammar, too narrow just drops the test and the leg still -looks green. Sixteen gates in this tree are wider than their bodies -justify, every one for a reason above; the marker is how you say which, -and a gate that grows a feature nobody can account for fails the gate. - -A marker that stops being load-bearing fails too. Narrow the gate and -the feature it named is no longer over-declared, so the marker now -claims a reason that does not apply — and sixteen accepted gates only -read as a census while every one of them is still doing something. The -gate names the stale entry; drop the feature, or the whole marker when -it names nothing else. - -Two things follow for anyone editing a marker by hand: - -- **A comparison is not a use.** `lang == LANG::Go` asks which variant a - value is; the enum is generated unconditionally, so it parses nothing - and needs no grammar. Counting one as a requirement is what conjoined - `feature = "go"` onto `container_scope_tests.rs` and dropped the - positive half of the #1197 contract from every build without Go. This - covers *every* alternative of a `matches!`, not only the leading one: - the call has no arms and drives no table, so `matches!(lang, - LANG::Ccomment | LANG::Preproc)` written to **skip** two languages is - not a requirement for either. Reading the later arms as uses is what - gated two `every_*_in_every_language` parity sweeps down to the one - `c-family-helpers` that leaked out of that exclusion — they ran in - four builds instead of twenty-three, and `--compare` was the only - check that could see it. -- **A sweep still needs the parsers it hardcodes.** `is_enabled` - filtering earns a row set only `any(…)`, because the loop skips what - is missing. A parser named through a *type parameter* - (`check_metrics::`) cannot be skipped by any runtime - filter, so it is required even inside a sweep — otherwise the - exemption is a way round the whole gate. It propagates through - helpers exactly as `needs` does: a sweep whose only fixed-parser call - sits one hop away pins that parser just the same. - - **The pin covers a parser named as a *type*, and nothing else.** A - `LANG::Rust` literal handed to `analyze` inside a sweep is not pinned, - because the gate cannot tell one that sits in the iterated row table — - which the `is_enabled` filter does skip — from one outside the loop, - which it does not. Every sweep in the tree today filters per language, - so nothing is currently wrong; but a sweep that mentions `is_enabled` - anywhere and *also* parses a hard-coded `LANG` outside the loop would - pass this gate and panic (#1480). Write the fixed-parser call as - `check_metrics::` and it is pinned correctly. -- **A sweep over the whole enum needs `any()`**, when it - carries both halves of the rule above — an `is_enabled()` row filter - *and* a non-vacuity assertion. Those two together mean it *fails* - rather than skips with no language enabled, so it has to be absent - then. Do not try to read a narrower set off the body: the fixtures - come from a `LANG`-parameterised helper whose arms are deliberately - not attributed to callers, so the body names almost nothing and - whatever leaks through becomes the whole gate. A full-enum sweep - *without* that guard is a different animal — `Display`, `FromStr` and - slug round-trips walk the same enum over variants that exist without - their grammars, and gating those stops them running on the - `--no-default-features` leg that is exactly where they belong. - -### Why the import lint is off on a partial build - -Both library roots and the five integration-test crate roots carry: - -```rust -#![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] -``` - -Per-language gating makes "is this import live" a function of the -enabled feature set. A `use` that every test in a module needs under -`--all-features` is used by none of them once their grammars are gated -out, and `unused_imports` cannot express that. Nor can a `cfg` on the -import itself: a trait is reached through its methods and so is named -nowhere, a glob binds an unknowable set, and a macro is invoked from -item position. A derived union is wrong in both directions — too wide -and the import is unused, too narrow and it vanishes from under a test -that still compiles. - -The scoping is what keeps it honest. `all-languages` is on by default -and under `--all-features`, so the build CI gates on and the one a -contributor runs both report an unused import exactly as before; only -the single-language legs, where the answer cannot mean anything, go -quiet. - -Dead *items* are relaxed only in the two library roots, which already -carried an `allow(dead_code)` on the same condition before #1472. The -test crates do not, so every helper, `const`, macro and test in -`tests/` still needs its own gate. - -### The direction that needs history - -Both checks above compare a marker against the derivation. When the two -agree and are *both* wrong there is nothing left to compare against — -the marker faithfully mirrors a derivation that is itself too wide, and -no amount of re-reading either one says so. - -`--compare ` is the answer, and it needs no cargo: it scans the -tree at `ref` as well (`git archive` into a scratch directory), computes -which single-language builds compile each test in each, and fails on a -test that still exists but stopped being built somewhere. The probe set -comes from the language table, so a new language extends it for free. -A test's membership includes the `cfg` on the `mod` line that loads its -file, so narrowing a root `mod` gate in a `tests/*/main.rs` is reported -too; before that, #1567's drop of `kotlin` from one went unseen. - -CI runs it per pull request against the base branch head — the PR's -`base.sha`, not `git merge-base`, because the job checks out shallow and -cannot compute one. The difference shows on a PR that is behind: if -`main` widens a gate meanwhile, this reports it against a PR that never -touched it, and the label is then the right answer. It is deliberately -not in `make pre-commit`, which has no base revision to be meaningful -against; by hand it is -`make check-test-lang-gates-compare COMPARE_REF=origin/main`. - -A test that was *deleted* or renamed reads as one name gone and another -arrived, and is not reported — a deliberate removal is not a gate -narrowing under it. - -A *deliberate* narrowing looks identical, though, and does happen: the -gate really was too wide and the test does not need that grammar. Say so -with the `gate-narrowing-intended` label on the pull request, not with -an in-source marker. A marker would be permanently stale the moment the -branch lands — the comparison is relative to a moving base — and would -then sit in the tree as a hole nothing can detect, which is the failure -mode this whole gate exists to prevent. - -The step reads that label **live**, not from the event payload, so -applying it after the failing run — which is when you find out you need -it — takes effect on the next run, and re-running the failed job works -too. Reading it from `github.event.pull_request.labels` did not: that -payload is a snapshot from when the run was queued, and a re-run replays -the same stale copy, so the documented remedy could never take effect at -all (measured on #1479). - -## Assert a whole-run invariant in the run, not in a fixture list - -When a change establishes an invariant that holds at the end of *every* -execution of a hot path — a scratch structure fully drained, a stack -balanced, a counter back at zero — a `debug_assert!` on that path -recruits the entire test corpus as input. A named test covers the -fixtures you thought of; the assertion covers every language, every -corpus file, and every integration suite that happens to run the path, -which is a different order of coverage for one line. - -This matters most when the invariant has more than one owner. #1375's -nesting-slot lifetime is enforced in two places — the walk's -`exclude_tests` prune arm and `propagate_nesting_to_children` — so a -third `continue` added later would leak with nothing to notice. The -targeted test names four seeding paths; the `debug_assert!` covered -3,590 lib tests plus every integration suite on the first run, which is -what actually established the invariant across all twenty languages. - -Both, not either: - -- The **named test** is the regression test `AGENTS.md` requires, it is - what you verify by revert, and it survives into release builds via an - `observation::counter!`. It also documents *which* paths seed state, - which an assertion cannot say. -- The **`debug_assert!`** generalises it for free, and is compiled out - of release, so an O(1) check on a per-walk path costs nothing shipped. - Keep it O(1): a per-node assertion is how the exact ancestor-chain - check went quadratic (`make chain-audit`, #1122). - -The assertion earns its place only if the suite actually exercises the -path under `cfg(debug_assertions)` — which `make pre-commit` does. An -assertion that only a release build reaches is lesson #80. diff --git a/.claude/rules/tool-output.md b/.claude/rules/tool-output.md deleted file mode 100644 index 014184413..000000000 --- a/.claude/rules/tool-output.md +++ /dev/null @@ -1,50 +0,0 @@ -# Tool Output Rule - -A truncated tool result is not the result. When output is too large to -inline, the harness persists it and shows a fragment headed -`Preview (first 2KB)` alongside the path to the full text. That fragment -is shaped exactly like a finished answer: no marker at the cut, no total -row count, nothing at the end saying more was dropped. - -## Why it yields a wrong answer rather than an error - -A preview is a prefix, so what survives is decided by output order, and -output order is rarely importance order. The commands used here most -often put the rows you need past the cut at least as reliably as before -it: - -- `sort | uniq -c` — the counts you are hunting are the largest, and - they sort **last** unless you passed `-rn`. -- `rg` over a tree — hits arrive in path order, so a sweep across - `big-code-analysis-ast/src/languages/` or `big-code-analysis-ast/src/getter/` shows the alphabetically early - languages and hides every one after them. -- `cargo test` / `make pre-commit` — the failure summary is at the end, - behind all the passing output. -- `git log`, `git diff --stat` — the last-listed file is the one cut. - -Reading a prefix of any of these produces a coherent, plausible, partial -answer. Nothing in it looks incomplete, which is the whole problem: the -tell that normally prompts a second look is absent. - -## What it cost here - -During #1127 an agent audited a `sort | uniq -c` tally from the preview -alone, missed two rows, and nearly shipped two tests that could no longer -fail. - -## How to apply - -- Read the persisted file in full before drawing a conclusion from it. A - preview establishes *that* there is output. It never establishes what - the output says. -- Better, do not generate output you will have to re-read. Aggregate in - the command instead: `| wc -l` for a count, `sort -rn | head` to bring - the interesting rows to the front, `rg -c` in place of `rg`, - `--name-only` in place of a full diff. -- Treat every "there are no other X" claim as requiring the full text. - Absence is precisely what a prefix cannot establish, and it is the - conclusion these sweeps are usually run to reach. -- The same discipline covers filters you added yourself. A `| head -20` - written to keep the output small is a truncation you must account for - when reading the result, and unlike the harness preview it leaves no - trace at all. diff --git a/.claude/settings.json b/.claude/settings.json index 0c4e830d7..efe042605 100644 --- a/.claude/settings.json +++ b/.claude/settings.json @@ -1,8 +1,12 @@ { + "permissions": { + "ask": ["Bash(git push *)", "Bash(gh pr create *)"], + "deny": ["Bash(git worktree remove *)", "Bash(git worktree prune *)"] + }, "hooks": { "PostToolUse": [ { - "matcher": "Edit|Write|MultiEdit", + "matcher": "Edit|Write", "hooks": [ { "type": "command", diff --git a/.claude/skills/add-lang/SKILL.md b/.claude/skills/add-lang/SKILL.md index 2f915dd79..a4e2286c2 100644 --- a/.claude/skills/add-lang/SKILL.md +++ b/.claude/skills/add-lang/SKILL.md @@ -72,13 +72,11 @@ continuing. (Step 3a). The three role gates in `make pre-commit` keep removal-only baselines, so a new language cannot add `pending` cells, unclaimed kinds, or bypass sites to them. -- **Worktree safety.** If `git rev-parse --show-toplevel` returns a - path under `.claude/worktrees/`, do not `cd` to the main repo, - remove worktrees, or check out a different branch. Run all work in - the current worktree. -- **Tooling.** Prefer Serena symbol-level editing for `.rs` code, - targeted `Edit` for `.toml`/`.md`. Use `rg`/`fd` (not `grep`/`find`) - for search. +- **Worktree safety.** Run all work in the current worktree; the + worktree rules in `AGENTS.md` apply. +- **Tooling.** Prefer symbol-level editing for `.rs` code when a + code-intelligence tool is available, targeted `Edit` otherwise and + for `.toml`/`.md`. --- @@ -109,9 +107,10 @@ the user's behalf. grammar requires a newer `tree-sitter`, STOP and ask the user — bumping the workspace `tree-sitter` is a separate, larger change. -### 0c: Activate Serena +### 0c: Code intelligence -If a Serena MCP server is available, run `serena:activate_project` so +If a code-intelligence tool such as the Serena MCP server is available, +activate it so symbol-level navigation/editing is the default for all `.rs` edits. --- @@ -553,7 +552,7 @@ Create the file, add `mod ;` to `checker.rs`, and write at the AST shape. Since #1697 the strategy is the `ElseIf` row's gate in `roles/.rs` and the Checker is `impl_else_if_from_row! ()`; lesson 10 in `lessons_learned.md` and - `.claude/rules/grammar-dispatch.md` §4 catalogue the strategies. + `docs/development/grammar_dispatch.md` §4 catalogue the strategies. **Re-derive the membership rather than trusting this table** — it moves with every language: @@ -1133,7 +1132,7 @@ it. (The non-zero smoke checks from Step 4b are an additional defence against the silent-zero failure mode in lesson 1; they are not a substitute for exact-value pinning here.) -**AGENTS.md enforces snapshot anchoring.** Every new +**Snapshot anchoring is gated (`CONTRIBUTING.md` "Snapshot anchors").** Every new `insta::assert_json_snapshot!(metric.X)` call must carry one of: an inline expected block, a positive `assert_eq!` anchor on the headline integer value above it, or a `// expected: ` @@ -1283,7 +1282,7 @@ Sweeps that filter on `LANG::is_enabled()` and assert non-vacuity need `any()`; a helper that picks a language from a string needs a hand-written gate with a `// test-lang-gates: hand-written() — ` marker. The rules -are in `.claude/rules/testing.md`, "Every test that names a language +are in `docs/development/testing.md`, "Every test that names a language carries that language's gate". --- @@ -1329,7 +1328,7 @@ Do not hardcode "now supports N languages" anywhere — counts rot. ## Step 7: Final validation gate -`make pre-commit` is the canonical entry point per AGENTS.md. It +`make pre-commit` is the canonical entry point (`CONTRIBUTING.md`). It runs the cargo trio (fmt-check, clippy with `-D warnings` in both default-features and `--all-features` flavours, full test suite), `cargo +nightly udeps`, the markdown / TOML / shell / Makefile / @@ -1355,8 +1354,8 @@ parallel pass. The ones a language addition touches directly: offender. Two gates are deliberately *not* in `make pre-commit` and a new -language is exactly what they exist for (AGENTS.md, "Benchmarking" and -"The ancestor-chain audit"): `make bench-scaling`, because a new +language is exactly what they exist for (`docs/development/benchmarking.md`, +including its "chain audit" section): `make bench-scaling`, because a new `Checker` / `Getter` / `compute` is where a quadratic walk arrives, and it shows up as *slow* tests rather than red ones; and `make chain-audit`, because the `_with_code` row predicates read the @@ -1412,8 +1411,9 @@ fields, causing further cascading mismatches. work on metric computation, AST traversal, or alterator rules generates `.snap.new` files inside `tests/repositories/big-code-analysis-output/`, which is a separate -git submodule (`dekobon/big-code-analysis-output`). Per AGENTS.md -and lesson 8, a language addition is not done until ALL four hold: +git submodule (`dekobon/big-code-analysis-output`). Per +`CONTRIBUTING.md` "Integration snapshots" and lesson 8, a language +addition is not done until ALL four hold: 1. `cargo test --workspace --all-features` exits clean from a fresh working tree with no `.snap.new` left behind under @@ -1537,7 +1537,7 @@ impl — exactly the failure mode lessons 1, 6, and 19 warn about. ## Worktree Safety Reminder -If `git rev-parse --show-toplevel` returns a path under -`.claude/worktrees/`, all worktree-safety bans apply: do not delete -worktrees, do not `cd` to the main repo, do not check out a different -branch, do not write outside the current worktree. +If this session runs in a worktree, the worktree rules in `AGENTS.md` +apply throughout: never remove or prune worktrees, never `cd` to another +checkout, never check out a different branch, never write outside the +worktree. diff --git a/.claude/skills/audit-crate/SKILL.md b/.claude/skills/audit-crate/SKILL.md index e4f524602..008f45745 100644 --- a/.claude/skills/audit-crate/SKILL.md +++ b/.claude/skills/audit-crate/SKILL.md @@ -31,8 +31,9 @@ below (`audit-state-$ARGUMENTS` etc.). - **NEVER commit code.** No `git commit`, no `git add`, no staging. Zero commits. - **NEVER leave uncommitted files.** No new files, no modified files, no temp files - in the worktree. If you accidentally create or modify a file, revert it - immediately with `git checkout -- .`. + in the worktree. If you accidentally create or modify a file, undo + your own edit with the exact inverse edit; never `git checkout -- .` + in a shared checkout. - **NEVER modify source files.** Not even "harmless" formatting or comment fixes. - **NEVER push branches.** The isolation branch is disposable and local-only. - The ONLY side effects of this skill are: GitHub issues filed, Serena memories @@ -47,100 +48,24 @@ Note any relevant open issues as context, but do NOT let them constrain the audi --- -## Step 0: Launch isolated agent +## Step 0: Isolate -**This step is MANDATORY and must be the very first action.** - -The audit runs in isolation to guarantee the main working tree is never touched. - -### Environment detection - -Determine the isolation mode: - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -``` - -- **Worktree mode**: You are already inside a worktree. Keep all existing - behavior (agent launched with `isolation: "worktree"`). -- **Branch mode**: You are in the main project directory. Agents run without - worktree isolation. Serena LSP works correctly in this mode. - -### Branch mode prerequisites - -In branch mode, verify the working tree is completely clean before proceeding: - -```bash -if [[ "$ISOLATION_MODE" == "branch" ]]; then - DIRTY="$(git status --porcelain)" - if [[ -n "$DIRTY" ]]; then - echo "Error: branch mode requires a clean repository (no uncommitted or untracked files)." >&2 - echo "$DIRTY" >&2 - exit 1 - fi -fi -``` - -### Launch the agent - -If you are the top-level orchestrator (invoked by the user), immediately launch -a single Agent that executes Steps 1-9. Pass the full crate name and any prior -context. Do NOT perform any audit work directly. - -- **Worktree mode**: Launch the Agent with `isolation: "worktree"`. This creates - an isolated worktree automatically. -- **Branch mode**: Launch the Agent WITHOUT `isolation: "worktree"`. The agent - runs in the main project directory (safe because the audit is read-only). - -**CRITICAL**: In worktree mode, the Agent tool call MUST include -`isolation: "worktree"` as a required parameter. Double-check before sending. -In branch mode, do NOT include `isolation: "worktree"`. - -If sub-agents are used (e.g., to audit file groups in parallel), they inherit -the parent context and do NOT need their own `isolation: "worktree"` -- the -audit is read-only, so concurrent reads are safe. - -### Agent verification (MANDATORY) - -Every agent (top-level or sub-agent) must verify its environment before doing -any work: - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT" -``` - -**In worktree mode**: Confirm `PROJECT_ROOT` contains `.claude/worktrees/`. -If not, abort: -"ABORTED: Agent expected worktree isolation but PROJECT_ROOT=\" - -**In branch mode**: Confirm the working tree is clean (`git status --porcelain` -returns empty output). If dirty, abort: -"ABORTED: Branch mode requires a clean working tree." - -In worktree mode, all file operations must be within `PROJECT_ROOT`. - -**Worktree cleanup**: Worktrees are automatically cleaned up by the Claude Code -runtime. NEVER run `git worktree remove` or `git worktree prune`. +This skill writes nothing, so it runs in **shared read-only mode** per +[`docs/development/agent_isolation.md`](../../../docs/development/agent_isolation.md): +verify `git status --porcelain` is empty before starting, run the +audit (and any parallel read-only sub-agents) in the current checkout +without switching branches, cleaning or resetting, and verify the tree +is still clean at the end (Step 9). If the user asked for a separate +checkout, allocate a worktree per that document and start the audit +there instead. Children never remove or prune worktrees. --- ## Step 1: Load audit history -Read the Serena memory `audit-state-$ARGUMENTS` to check for prior audit state. -Invoke the Serena MCP tool `serena:read_memory` directly with -`memory_name: "audit-state-$ARGUMENTS"`. If the Serena MCP server is not active -for this session, call `serena:activate_project` first. +If a persistent-memory tool (such as the Serena MCP server) is +available, read the memory `audit-state-$ARGUMENTS` for prior audit +state. If no persistent-memory tool is available, skip this step and treat every file as unaudited. If the memory exists, it contains a per-file coverage table in this format: @@ -255,7 +180,7 @@ Group every file into one of these categories before auditing: | A — Library core | `src/lib.rs` and the modules it exports (`big-code-analysis-ast/src/languages/`, `src/metrics/`, `src/output/`, `src/spaces.rs`, `big-code-analysis-ast/src/parser.rs`, `big-code-analysis-ast/src/checker.rs`, `big-code-analysis-ast/src/getter.rs`, `big-code-analysis-ast/src/alterator.rs`, `big-code-analysis-ast/src/node.rs`, `big-code-analysis-ast/src/traits.rs`, etc.) | | B — Binaries | `src/bin/` entries plus the workspace crates `big-code-analysis-cli` and `big-code-analysis-web` when those are the audit target | | C — Tests | `tests/` directory | -| D — Supporting files | `README.md`, examples, `Cargo.toml`, `big-code-analysis-book/`, helper scripts, `.claude/rules/` if present | +| D — Supporting files | `README.md`, examples, `Cargo.toml`, `big-code-analysis-book/`, helper scripts, `docs/development/` | **Use the priority table from Step 1** to order files within each group. Audit highest-priority files first. For a focused session, you may skip priority-5 @@ -542,9 +467,9 @@ Also list any findings dropped as duplicates of existing issues. ## Step 8: Save audit state -After completing the audit, persist the coverage state to Serena memory by -invoking the Serena MCP tool `serena:write_memory` directly with -`memory_name: "audit-state-$ARGUMENTS"` and the merged content as `content`. +If a persistent-memory tool is available, write the merged coverage +state to the memory `audit-state-$ARGUMENTS`; otherwise include the +coverage table in the final summary. Build the memory content by **merging** the previous state (from Step 1) with the current session's coverage. Rules for merging: @@ -598,10 +523,10 @@ git status --porcelain If any output is shown, something went wrong — the audit was supposed to be read-only. -- For **modifications to tracked files** (`M ` / ` M` lines), revert with - `git checkout -- ` per file. Do NOT use a blanket `git checkout -- .` - in worktree mode without first verifying every listed path belongs to the - audit (other agents may share the worktree). +- For **modifications to tracked files** (`M ` / ` M` lines), do NOT + restore them: the checkout is shared, and a change made while the audit + ran may be the user's. Report each path and the diff hunk in the final + summary and let the user decide. - For **untracked files** (`??` lines), do NOT delete them automatically. Untracked output means the audit wrote a file it should not have. Surface the path(s) verbatim in the final summary so the user can decide whether @@ -616,11 +541,11 @@ final summary output. All ABSOLUTE CONSTRAINTS (top of this document) apply. Additionally: -- **NEVER delete worktrees.** Only the Claude Code runtime may do that. +- **NEVER delete worktrees.** The orchestrator that created one cleans it up. - Do NOT implement fixes. This is audit-only. - Do NOT file findings without concrete evidence (file + line + reasoning). - Do NOT file duplicate issues. Always check `gh issue list` first. - Use `--body-file` for all `gh issue create` and `gh issue comment` calls. -- In worktree mode, all audit work MUST happen inside the isolated worktree. -- In branch mode, audit work runs in the main directory (read-only, verified clean). +- In shared read-only mode, the checkout is verified clean before and + after; nothing in it is restored or cleaned by this skill. - Sub-agents share the parent context (read-only); they do NOT need separate isolation. diff --git a/.claude/skills/audit-file/SKILL.md b/.claude/skills/audit-file/SKILL.md index 4857a1c52..211256f83 100644 --- a/.claude/skills/audit-file/SKILL.md +++ b/.claude/skills/audit-file/SKILL.md @@ -34,8 +34,9 @@ composing Serena memory keys so the key is a single flat token (e.g., - **NEVER commit code.** No `git commit`, no `git add`, no staging. Zero commits. - **NEVER leave uncommitted files.** No new files, no modified files, no temp files - in the worktree. If you accidentally create or modify a file, revert it - immediately with `git checkout -- .`. + in the worktree. If you accidentally create or modify a file, undo + your own edit with the exact inverse edit; never `git checkout -- .` + in a shared checkout. - **NEVER modify source files.** Not even "harmless" formatting or comment fixes. - **NEVER push branches.** The isolation branch is disposable and local-only. - The ONLY side effects of this skill are: GitHub issues filed, Serena memories @@ -50,95 +51,25 @@ Note any relevant open issues as context, but do NOT let them constrain the audi --- -## Step 0: Launch isolated agent +## Step 0: Isolate -**This step is MANDATORY and must be the very first action.** - -The audit runs in isolation to guarantee the main working tree is never touched. - -### Environment detection - -Determine the isolation mode: - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -``` - -- **Worktree mode**: You are already inside a worktree. Keep all existing - behavior (agent launched with `isolation: "worktree"`). -- **Branch mode**: You are in the main project directory. Agents run without - worktree isolation. Serena LSP works correctly in this mode. - -### Branch mode prerequisites - -In branch mode, verify the working tree is completely clean before proceeding: - -```bash -if [[ "$ISOLATION_MODE" == "branch" ]]; then - DIRTY="$(git status --porcelain)" - if [[ -n "$DIRTY" ]]; then - echo "Error: branch mode requires a clean repository (no uncommitted or untracked files)." >&2 - echo "$DIRTY" >&2 - exit 1 - fi -fi -``` - -### Launch the agent - -If you are the top-level orchestrator (invoked by the user), immediately launch -a single Agent that executes Steps 1-9. Pass the resolved file path and any -prior context. Do NOT perform any audit work directly. - -- **Worktree mode**: Launch the Agent with `isolation: "worktree"`. This creates - an isolated worktree automatically. -- **Branch mode**: Launch the Agent WITHOUT `isolation: "worktree"`. The agent - runs in the main project directory (safe because the audit is read-only). - -**CRITICAL**: In worktree mode, the Agent tool call MUST include -`isolation: "worktree"` as a required parameter. Double-check before sending. -In branch mode, do NOT include `isolation: "worktree"`. - -### Agent verification (MANDATORY) - -Every agent must verify its environment before doing any work: - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT" -``` - -**In worktree mode**: Confirm `PROJECT_ROOT` contains `.claude/worktrees/`. -If not, abort: -"ABORTED: Agent expected worktree isolation but PROJECT_ROOT=\" - -**In branch mode**: Confirm the working tree is clean (`git status --porcelain` -returns empty output). If dirty, abort: -"ABORTED: Branch mode requires a clean working tree." - -In worktree mode, all file operations must be within `PROJECT_ROOT`. - -**Worktree cleanup**: Worktrees are automatically cleaned up by the Claude Code -runtime. NEVER run `git worktree remove` or `git worktree prune`. +This skill writes nothing, so it runs in **shared read-only mode** per +[`docs/development/agent_isolation.md`](../../../docs/development/agent_isolation.md): +verify `git status --porcelain` is empty before starting, run the +audit (and any parallel read-only sub-agents) in the current checkout +without switching branches, cleaning or resetting, and verify the tree +is still clean at the end (Step 9). If the user asked for a separate +checkout, allocate a worktree per that document and start the audit +there instead. Children never remove or prune worktrees. --- ## Step 1: Load audit history -Read the Serena memory keyed on `$FILE_PATH` (with `/` replaced by `-`) to -check for prior audit state. Invoke the Serena MCP tool `serena:read_memory` -directly with `memory_name: "audit-state-"`. If the Serena MCP -server is not active for this session, call `serena:activate_project` first. +If a persistent-memory tool (such as the Serena MCP server) is +available, read the memory `audit-state-` (the +path with `/` replaced by `-`) for prior audit state. If none is +available, skip this step and treat the file as unaudited. If the memory exists, it contains a single-file coverage record in this format: @@ -531,8 +462,8 @@ Also list any findings dropped as duplicates of existing issues. ## Step 8: Save audit state -After completing the audit, persist the coverage state to Serena memory by -invoking the Serena MCP tool `serena:write_memory` directly with +If a persistent-memory tool is available, persist the coverage state by +writing the memory with `memory_name: "audit-state-"` (i.e., `$FILE_PATH` with `/` replaced by `-`) and the merged content as `content`. @@ -581,10 +512,10 @@ git status --porcelain If any output is shown, something went wrong — the audit was supposed to be read-only. -- For **modifications to tracked files** (`M ` / ` M` lines), revert with - `git checkout -- ` per file. Do NOT use a blanket `git checkout -- .` - in worktree mode without first verifying every listed path belongs to the - audit (other agents may share the worktree). +- For **modifications to tracked files** (`M ` / ` M` lines), do NOT + restore them: the checkout is shared, and a change made while the audit + ran may be the user's. Report each path and the diff hunk in the final + summary and let the user decide. - For **untracked files** (`??` lines), do NOT delete them automatically. Untracked output means the audit wrote a file it should not have. Surface the path(s) verbatim in the final summary so the user can decide whether @@ -599,10 +530,10 @@ final summary output. All ABSOLUTE CONSTRAINTS (top of this document) apply. Additionally: -- **NEVER delete worktrees.** Only the Claude Code runtime may do that. +- **NEVER delete worktrees.** The orchestrator that created one cleans it up. - Do NOT implement fixes. This is audit-only. - Do NOT file findings without concrete evidence (file + line + reasoning). - Do NOT file duplicate issues. Always check `gh issue list` first. - Use `--body-file` for all `gh issue create` and `gh issue comment` calls. -- In worktree mode, all audit work MUST happen inside the isolated worktree. -- In branch mode, audit work runs in the main directory (read-only, verified clean). +- In shared read-only mode, the checkout is verified clean before and + after; nothing in it is restored or cleaned by this skill. diff --git a/.claude/skills/audit-naming/SKILL.md b/.claude/skills/audit-naming/SKILL.md index 3e2ac9c4f..9ecdd03e2 100644 --- a/.claude/skills/audit-naming/SKILL.md +++ b/.claude/skills/audit-naming/SKILL.md @@ -32,8 +32,9 @@ memory-key reference below. - **NEVER commit code.** No `git commit`, no `git add`, no staging. - **NEVER leave uncommitted files.** No new files, no modified files, no temp - files in the worktree. If you accidentally create or modify a file, revert - it immediately with `git checkout -- .`. + files in the worktree. If you accidentally create or modify a file, undo + your own edit with the exact inverse edit; never `git checkout -- .` + in a shared checkout. - **NEVER modify source files.** Not even "harmless" formatting or comment fixes. - **NEVER push branches.** - The ONLY side effects of this skill are: GitHub issues filed, Serena @@ -41,77 +42,24 @@ memory-key reference below. --- -## Step 0: Launch isolated agent +## Step 0: Isolate -**This step is MANDATORY and must be the very first action.** - -The audit runs in isolation to guarantee the main working tree is never touched. - -### Environment detection - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -``` - -- **Worktree mode**: You are already inside a worktree. Keep all existing - behavior (agent launched with `isolation: "worktree"`). -- **Branch mode**: You are in the main project directory. Agents run without - worktree isolation. Serena LSP works correctly in this mode. - -### Branch mode prerequisites - -```bash -if [[ "$ISOLATION_MODE" == "branch" ]]; then - DIRTY="$(git status --porcelain)" - if [[ -n "$DIRTY" ]]; then - echo "Error: branch mode requires a clean repository (no uncommitted or untracked files)." >&2 - echo "$DIRTY" >&2 - exit 1 - fi -fi -``` - -### Launch the agent - -If you are the top-level orchestrator, immediately launch a single Agent that -executes Steps 1-8. Do NOT perform any audit work directly. - -- **Worktree mode**: Launch with `isolation: "worktree"`. -- **Branch mode**: Launch WITHOUT `isolation: "worktree"`. - -Sub-agents inherit context (read-only) and do NOT need their own -`isolation: "worktree"`. - -### Agent verification (MANDATORY) - -Every agent must verify its environment before doing any work: - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT" -``` - -In worktree mode: confirm `PROJECT_ROOT` contains `.claude/worktrees/`. -In branch mode: confirm `git status --porcelain` is empty. - -**Worktree cleanup**: NEVER run `git worktree remove` or `git worktree prune`. +This skill writes nothing, so it runs in **shared read-only mode** per +[`docs/development/agent_isolation.md`](../../../docs/development/agent_isolation.md): +verify `git status --porcelain` is empty before starting, run the +audit (and any parallel read-only sub-agents) in the current checkout +without switching branches, cleaning or resetting, and verify the tree +is still clean at the end (Step 8). If the user asked for a separate +checkout, allocate a worktree per that document and start the audit +there instead. Children never remove or prune worktrees. --- ## Step 1: Load audit history -Read the Serena memory `naming-audit-state-$ARGUMENTS` via the Serena MCP tool -`serena:read_memory`. If Serena is not active, call `serena:activate_project` +If a persistent-memory tool (such as the Serena MCP server) is +available, read the memory `naming-audit-state-$ARGUMENTS`; otherwise +treat every file as unaudited. If a memory exists, consult it first. If the memory exists, parse the per-file coverage table: @@ -394,8 +342,9 @@ Skipped: Z findings already caught by clippy ## Step 7: Save audit state -Persist coverage state to Serena memory `naming-audit-state-$ARGUMENTS` via -`serena:write_memory`. +If a persistent-memory tool is available, persist coverage state to the +memory `naming-audit-state-$ARGUMENTS`; otherwise include it in the +final summary. **Merge** the previous state (Step 1) with current session coverage: @@ -427,8 +376,9 @@ git status --porcelain If any output: -- For modifications to tracked files: `git checkout -- ` per file. Do - NOT blanket-revert in worktree mode. +- For modifications to tracked files: do NOT restore them; the checkout + is shared and the change may be the user's. Report each path and diff + in the summary. - For untracked files (`??`): do NOT delete automatically; surface paths in the summary so the user can decide. diff --git a/.claude/skills/batch-fix/SKILL.md b/.claude/skills/batch-fix/SKILL.md index 03300fca0..62bc68ea2 100644 --- a/.claude/skills/batch-fix/SKILL.md +++ b/.claude/skills/batch-fix/SKILL.md @@ -59,21 +59,17 @@ running /batch-fix." ### 0c: Detect isolation mode -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -``` - -- **Worktree mode**: Agents are launched with `isolation: "worktree"` and run - in parallel (existing behavior). -- **Branch mode**: Agents are launched WITHOUT `isolation: "worktree"` and run - sequentially using feature branches. This preserves Serena LSP compatibility. - All agents in a wave MUST be processed one at a time (they share the working - directory). +Choose the mode per +[`docs/development/agent_isolation.md`](../../../docs/development/agent_isolation.md): +**worktree mode** when the runtime can start each child agent in a +worktree you allocate (parallel, at most six in flight), otherwise +**branch mode** (sequential, feature branches off the integration +branch). Record `ISOLATION_MODE` and tell every child which mode it is +in, with the absolute path and branch it must verify. + +- **Worktree mode**: each agent runs in its own worktree, in parallel. +- **Branch mode**: agents run sequentially on feature branches, one at a + time, because they share the working directory. Record `ISOLATION_MODE` for use in Step 4. @@ -323,7 +319,7 @@ Print the wave plan: ``` ## Processing Plan -Isolation: +Isolation: Wave 1 (parallel): #42 (big-code-analysis, quick-win), #57 (big-code-analysis-cli) Wave 2 (parallel): #63 (big-code-analysis), #71 (big-code-analysis-web, quick-win) Wave 3 (sequential): #80 (cross-lang, depends on #42) @@ -347,23 +343,21 @@ Use the issue data (title, body, comments) cached from Step 0a to populate each agent's prompt. Pass each agent the full agent prompt (see below) with ``, -``, ``, and `` substituted. +``, ``, ``, ``, +``, `` and `` substituted (the last +three from the allocation in `docs/development/agent_isolation.md`). #### Worktree mode (`ISOLATION_MODE=worktree`) -**CRITICAL**: Every agent MUST be launched with `isolation: "worktree"`. -This is a required parameter on the Agent tool call, not optional. Agents -launched without worktree isolation will modify the main project directory, -corrupting the integration branch. Double-check that every Agent tool call -includes `isolation: "worktree"` before sending. +Start every child agent in its own worktree, allocated per +`docs/development/agent_isolation.md` (in Claude Code, `isolation: +worktree` on the Agent call creates and enters one). An agent started +in the orchestrator's directory modifies the integration checkout, so +confirm the worktree in every launch before sending. -For a **single-issue wave**: launch one Agent with `isolation: "worktree"` -and `model: "opus"`. - -For a **multi-issue wave**: launch ALL agents in a single message block -(parallel tool calls). Each agent gets `isolation: "worktree"` and -`model: "opus"`. Do NOT use `run_in_background` -- wait for all agents in -the wave to complete before proceeding. +For a **single-issue wave**: launch one agent. For a **multi-issue +wave**: launch all agents of the wave together and wait for every one +to return before proceeding; do not merge while any is running. **Worktree agents fork from the base, not from the integration-branch tip.** Each worktree starts at the commit `INTEGRATION_BRANCH` was created @@ -400,7 +394,7 @@ fi git checkout -b "$BRANCH" "$INTEGRATION_BRANCH" ``` -2. Launch ONE Agent with `model: "opus"` (NO `isolation: "worktree"`). +2. Launch ONE child agent in this directory, on that branch. 3. On **SUCCESS**: @@ -571,8 +565,8 @@ After all waves are processed, if any merges succeeded: git checkout ``` -Then run `make pre-commit` — the canonical gate per "Validation gates" -in `AGENTS.md` (it adds udeps, doc warnings, the lint families, the +Then run `make pre-commit` — the canonical gate per "Local validation gate" +in `CONTRIBUTING.md` (it adds udeps, doc warnings, the lint families, the self-scan gates, and `make snapshot-anchors` on top of the cargo trio). **Capture it to a per-invocation log and read the verdict from the log** @@ -715,6 +709,14 @@ Mode: | # | Issue | Title | Reason | |---|-------|-------|--------| + +### Worktrees left behind +| Path | Branch | State (merged / unmerged / dirty) | +|------|--------|-----------------------------------| +(Each worktree this run allocated; `git worktree remove` is denied to +agents, so the user removes them. Runtime-allocated ones are the +runtime's to sweep.) + ### Statistics - Issues attempted: N - Succeeded: N @@ -746,6 +748,16 @@ review. Merge to main when satisfied, or push to open a PR." You are fixing GitHub issue #: +Your checkout, as allocated by the orchestrator (`runtime` where the +runtime allocated it): + +``` +ISOLATION_MODE: +PROJECT_ROOT: +BRANCH: +BASE_COMMIT: +``` + Issue body: ``` @@ -758,23 +770,24 @@ annotate it. The `Fixes #N` commit trailer will close it on merge. ### Setup — Environment Verification (MANDATORY) -Determine your isolation mode: +Compare the checkout you are in against the block above before touching +anything, per `docs/development/agent_isolation.md`, and abort on any +mismatch: ```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT" +ROOT="$(git rev-parse --show-toplevel)" +BASE="$(git rev-parse HEAD)" +# Orchestrator-allocated: ROOT must equal PROJECT_ROOT exactly. +# Runtime-allocated: ROOT must not be the orchestrator's directory, and +# BASE must equal BASE_COMMIT. +echo "ROOT=$ROOT BASE=$BASE" ``` Verify your branch: ```bash AGENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)" -echo "AGENT_BRANCH=$AGENT_BRANCH" +echo "AGENT_BRANCH=$AGENT_BRANCH" # must equal BRANCH, or match the branch pattern ``` **HARD GATE**: If `AGENT_BRANCH` is `main`, `master`, or `HEAD` (detached), @@ -834,21 +847,17 @@ though `` is checked out elsewhere: git refuses to In branch mode, skip this — your branch was created from the integration branch's current tip in Step 4a and already contains it. -Try to activate Serena: - -``` -serena:activate_project project="big-code-analysis" -``` - -If Serena is unavailable, use text-based tools (Read, Edit, Grep, Glob) and -`rg` / `fd` via Bash. Never use legacy `grep` / `find`. +Use a code-intelligence tool (such as the Serena MCP server) for +symbol-level navigation and editing when one is available; otherwise +use the file tools and `rg` / `fd`. ### Phase 1: Investigate and Fix Follow the `/fix-issue` workflow: -1. Re-read project conventions: top-level `CLAUDE.md`, `AGENTS.md`, and any - rule files under `.claude/rules/` if present. +1. Re-read `AGENTS.md` and the guides its routing table names for this + change (`docs/development/testing.md` always; `grammar_dispatch.md` + for anything touching a language module or metric). 2. If `docs/development/lessons_learned.md` exists, read it and identify any lessons relevant to this issue's domain. 3. Investigate the codebase to understand root cause. For tree-sitter @@ -929,9 +938,10 @@ Follow the `/fix-issue` workflow: - **Integration-snapshot submodule**: a behaviour-changing metric / traversal / alterator fix generates `.snap.new` inside `tests/repositories/big-code-analysis-output/`. Follow the submodule - discipline in `AGENTS.md`: accept the snapshots, push them to the - submodule remote, and record the new submodule SHA in the **same** - commit as the fix (`git add tests/repositories/big-code-analysis-output` + discipline in `CONTRIBUTING.md` "Integration snapshots": accept the snapshots, record the new submodule SHA in the **same** + commit as the fix, and report the submodule commit for the user to + push (pushing is publication and the orchestrator's invocation is + not an instruction to publish) (`git add tests/repositories/big-code-analysis-output` is exempt from the "only files you changed" staging rule). - **Regression check**: `cargo test --workspace --all-features` and `cargo clippy --workspace --all-targets -- -D warnings` must pass. @@ -974,7 +984,7 @@ directly: - Duplicate logic across sibling language modules that should live in a shared helper, trait method, or macro (the project already uses `big-code-analysis-ast/src/c_langs_macros/`, `big-code-analysis-ast/src/macros/`, and `big-code-analysis-ast/src/c_macro.rs` for shared - structure; follow `.claude/rules/macro-comments.md` when consolidating) + structure; follow `docs/development/formatting.md` when consolidating) **Clarity**: @@ -1244,7 +1254,7 @@ git checkout -- . git reset HEAD ``` -Do NOT run `git clean -fd` -- the worktree runtime manages untracked files. +Do NOT run `git clean -fd`; report untracked files and leave them. **END AGENT PROMPT** @@ -1255,7 +1265,7 @@ Do NOT run `git clean -fd` -- the worktree runtime manages untracked files. - Do NOT merge the integration branch into `main` -- leave for the user - Do NOT close GitHub issues -- the `Fixes #N` trailer handles this on merge - Do NOT use `git push --force` or any destructive git operations -- Do NOT delete worktrees -- only the Claude Code runtime may do that +- Do NOT delete worktrees -- the orchestrator that created one cleans it up - Do NOT skip the review phase -- every fix must be reviewed before commit - Do NOT bump tree-sitter grammar pins as part of an issue fix; grammar bumps are a deliberate, separate change driven by `recreate-grammars.sh` diff --git a/.claude/skills/cleanup-crate/SKILL.md b/.claude/skills/cleanup-crate/SKILL.md index 3ab41cf4e..e886a93ec 100644 --- a/.claude/skills/cleanup-crate/SKILL.md +++ b/.claude/skills/cleanup-crate/SKILL.md @@ -117,23 +117,21 @@ continue from where the last run left off (consult Serena memory ### 0d: Detect isolation mode -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -``` +Choose the mode per +[`docs/development/agent_isolation.md`](../../../docs/development/agent_isolation.md): +**worktree mode** when the runtime can start each child agent in a +worktree you allocate (parallel, at most six in flight), otherwise +**branch mode** (sequential, feature branches off the integration +branch). Record `ISOLATION_MODE` and tell every child which mode it is +in, with the absolute path and branch it must verify. -- **Worktree mode**: agents run in parallel with `isolation: "worktree"`. -- **Branch mode**: agents run sequentially using feature branches. --- ## Step 1: Load prior state -Read Serena memories via the Serena MCP tool `serena:read_memory`: +If a persistent-memory tool (such as the Serena MCP server) is +available, read these memories; otherwise start from no prior state: 1. `audit-state-` — prior audit findings 2. `cleanup/` — prior cleanup runs @@ -212,8 +210,9 @@ approval-required). Re-run without --dry-run to apply." #### Worktree mode -**CRITICAL**: Every agent MUST be launched with `isolation: "worktree"`. -Launch removal area agents in parallel, at most six at a time — each one +Start every child agent in its own worktree (allocated per +`docs/development/agent_isolation.md`; in Claude Code, `isolation: +worktree` on the Agent call does this). Launch removal area agents in parallel, at most six at a time — each one clones the workspace, and a crate with a dozen removal areas will fill the disk with scratch clones if they all start at once. Queue the rest and launch each as a slot frees. @@ -233,7 +232,7 @@ fi git checkout -b "$BRANCH" "cleanup/${CRATE_NAME}" ``` -2. Launch ONE Agent (NO `isolation: "worktree"`). +2. Launch ONE child agent in this directory, on that branch. 3. On **SUCCESS**: @@ -264,19 +263,32 @@ You are cleaning up dead code in crate ``. Your removal area: ``` +Your checkout, as allocated by the orchestrator (`runtime` where the +runtime allocated it): + +``` +ISOLATION_MODE: +PROJECT_ROOT: +BRANCH: +BASE_COMMIT: +``` + ### 3a: Setup — Environment Verification (MANDATORY) +Compare the checkout you are in against the block above before touching +anything, per `docs/development/agent_isolation.md`, and abort on any +mismatch: + ```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT" +ROOT="$(git rev-parse --show-toplevel)" +BASE="$(git rev-parse HEAD)" +# Orchestrator-allocated: ROOT must equal PROJECT_ROOT exactly. +# Runtime-allocated: ROOT must not be the orchestrator's directory, and +# BASE must equal BASE_COMMIT. +echo "ROOT=$ROOT BASE=$BASE" AGENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)" -echo "AGENT_BRANCH=$AGENT_BRANCH" +echo "AGENT_BRANCH=$AGENT_BRANCH" # must equal BRANCH, or match the branch pattern ``` **HARD GATE**: If `AGENT_BRANCH` is `master`, `main`, or `HEAD` (detached), @@ -291,8 +303,8 @@ SKIPPED: Agent is on disallowed branch. AGENT_BRANCH= In worktree mode: ALL file operations must be within `PROJECT_ROOT`. -If Serena MCP is available, call `serena:activate_project` first. Otherwise -use Read, Edit, Grep, Glob. +Use a code-intelligence tool for symbol-level navigation when one is +available; otherwise use Read, Edit, Grep, Glob. ### 3b: Verify before removing @@ -395,15 +407,15 @@ git merge --no-edit If a merge conflict: `git merge --abort` and log as conflict. After all merges (or directly, in branch mode), run `make pre-commit` on -the integration branch — the canonical validation gate (see "Validation -gates" in `AGENTS.md`; it adds udeps, doc warnings, the lint families, +the integration branch — the canonical validation gate (see "Local validation +gate" in `CONTRIBUTING.md`; it adds udeps, doc warnings, the lint families, the self-scan gates, and `make snapshot-anchors` on top of the cargo trio run in 3e). If `make` is unavailable, fall back to the raw cargo gates from 3e. --- -## Step 5: Update Serena memories +## Step 5: Update memories (when a persistent-memory tool is available) ### 5a: Update cleanup progress @@ -449,6 +461,13 @@ Branch: cleanup/ ### Approval Required (not applied) | # | Symbol | Reason | +### Worktrees left behind +| Path | Branch | State (merged / unmerged / dirty) | +|------|--------|-----------------------------------| +(Each worktree this run allocated; `git worktree remove` is denied to +agents, so the user removes them. Runtime-allocated ones are the +runtime's to sweep.) + ### Statistics - Removal areas: N - Applied: N diff --git a/.claude/skills/fix-issue/SKILL.md b/.claude/skills/fix-issue/SKILL.md index 6253ebd76..7bbf3fd1b 100644 --- a/.claude/skills/fix-issue/SKILL.md +++ b/.claude/skills/fix-issue/SKILL.md @@ -6,13 +6,12 @@ description: Complete workflow for fixing GitHub issues including investigation, # Fix GitHub Issue Workflow 1. Read the GitHub issue thoroughly (`gh issue view ` plus all comments). -2. If Serena (or another LSP-based code intelligence MCP) is available, read its - instructions manual (`serena:initial_instructions`) so symbol-level navigation - and editing are the default. LSP tools are preferred over text-based search/edit for code; - fall back to `rg`/`fd` and the built-in Grep/Glob tools only when LSP is - unavailable. Never use legacy `grep`/`find`. -3. Re-read any relevant project conventions (e.g., `CLAUDE.md`, `README.md`, and - any rule files under `.claude/rules/` if present). Note any rule that is +2. If a code-intelligence tool (such as the Serena MCP server) is available, + use it for symbol-level navigation and editing; otherwise use the file + tools and `rg` / `fd`. +3. Re-read `AGENTS.md` and the guides its routing table names for this + change (`docs/development/testing.md` always; `grammar_dispatch.md` for + anything touching a language module or metric). Note any rule that is directly relevant so it can be cited in the fix. 4. Investigate the codebase to understand the root cause. For tree-sitter grammar / language-specific behavior, examine the corresponding module under @@ -70,7 +69,7 @@ description: Complete workflow for fixing GitHub issues including investigation, coupling to incidental host/filesystem details. - **Test-via-revert for defensive refactors**: if the fix pins an invariant rather than repairing a live bug, follow - `.claude/rules/testing.md` — prove the new test fails against the + `docs/development/testing.md` — prove the new test fails against the pre-fix code before trusting it, and revert safely (never a file-level restore over uncommitted work). 9. **Review the changes** for: @@ -94,8 +93,8 @@ description: Complete workflow for fixing GitHub issues including investigation, Do NOT commit with known issues and plan to fix them in a follow-up — that is how fix-up chains happen. 11. Run `make pre-commit` as the final gate before committing. It is the - canonical entry point for the full validation gate (see "Validation - gates" in `AGENTS.md` for the current stage list — do not rely on a + canonical entry point for the full validation gate (see "Local + validation gate" in `CONTRIBUTING.md` for the current stage list — do not rely on a from-memory subset). If `make` is unavailable, fall back to running the cargo gates manually (`cargo fmt --all -- --check`, `cargo clippy --workspace --all-targets -- -D warnings`, @@ -116,7 +115,7 @@ description: Complete workflow for fixing GitHub issues including investigation, - `CHANGELOG.md` — add an entry under `## [Unreleased]`. Public-API changes must be cross-referenced against `STABILITY.md`; a source-level break deferred to the next major bump is marked - **(breaking)** (see AGENTS.md "Editing principles"). + **(breaking)** (see AGENTS.md "Conventions the code cannot tell you"). - `README.md` — if user-facing behavior, install steps, or supported languages changed. - `big-code-analysis-book/` — if the change affects documented metrics, @@ -142,8 +141,7 @@ description: Complete workflow for fixing GitHub issues including investigation, ## Worktree Safety Reminder -If this session is running inside a worktree (`git rev-parse --show-toplevel` -returns a path under `.claude/worktrees/`), worktree-safety bans apply -throughout this workflow: never delete worktrees, never `cd` to the main repo, -never check out a different branch, never write to files outside your +If this session runs in a worktree, the worktree rules in `AGENTS.md` +apply throughout: never remove or prune worktrees, never `cd` to another +checkout, never check out a different branch, never write outside the worktree. diff --git a/.claude/skills/improve-crate/SKILL.md b/.claude/skills/improve-crate/SKILL.md index 4b3b71063..f4d710d23 100644 --- a/.claude/skills/improve-crate/SKILL.md +++ b/.claude/skills/improve-crate/SKILL.md @@ -82,20 +82,20 @@ continue. ### 0d: Detect isolation mode -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -``` +Choose the mode per +[`docs/development/agent_isolation.md`](../../../docs/development/agent_isolation.md): +**worktree mode** when the runtime can start each child agent in a +worktree you allocate (parallel, at most six in flight), otherwise +**branch mode** (sequential, feature branches off the integration +branch). Record `ISOLATION_MODE` and tell every child which mode it is +in, with the absolute path and branch it must verify. --- ## Step 1: Load prior state -Read Serena memories via `serena:read_memory`: +If a persistent-memory tool (such as the Serena MCP server) is +available, read these memories; otherwise start from no prior state: 1. `audit-state-` — prior audit findings 2. `code-improvement/` — prior improvement runs @@ -190,7 +190,9 @@ to apply." #### Worktree mode -**CRITICAL**: every agent MUST be launched with `isolation: "worktree"`. +Start every child agent in its own worktree (allocated per +`docs/development/agent_isolation.md`; in Claude Code, `isolation: +worktree` on the Agent call does this). Launch change area agents in parallel, at most six at a time — each one clones the workspace, and a crate with a dozen change areas will fill the disk with scratch clones if they all start at once. Queue the rest @@ -210,7 +212,7 @@ fi git checkout -b "$BRANCH" "improve/${CRATE_NAME}" ``` -2. Launch ONE Agent (NO `isolation: "worktree"`). +2. Launch ONE child agent in this directory, on that branch. 3. On **SUCCESS**: @@ -241,19 +243,32 @@ You are improving code in crate ``. Your change area: ``` +Your checkout, as allocated by the orchestrator (`runtime` where the +runtime allocated it): + +``` +ISOLATION_MODE: +PROJECT_ROOT: +BRANCH: +BASE_COMMIT: +``` + ### 3a: Setup — Environment Verification (MANDATORY) +Compare the checkout you are in against the block above before touching +anything, per `docs/development/agent_isolation.md`, and abort on any +mismatch: + ```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT" +ROOT="$(git rev-parse --show-toplevel)" +BASE="$(git rev-parse HEAD)" +# Orchestrator-allocated: ROOT must equal PROJECT_ROOT exactly. +# Runtime-allocated: ROOT must not be the orchestrator's directory, and +# BASE must equal BASE_COMMIT. +echo "ROOT=$ROOT BASE=$BASE" AGENT_BRANCH="$(git rev-parse --abbrev-ref HEAD)" -echo "AGENT_BRANCH=$AGENT_BRANCH" +echo "AGENT_BRANCH=$AGENT_BRANCH" # must equal BRANCH, or match the branch pattern ``` **HARD GATE**: If `AGENT_BRANCH` is `master`, `main`, or `HEAD` (detached), @@ -267,7 +282,8 @@ SKIPPED: Agent is on disallowed branch. AGENT_BRANCH= In worktree mode: ALL file operations within `PROJECT_ROOT`. -If Serena MCP available, call `serena:activate_project`. Otherwise use +Use a code-intelligence tool for symbol-level navigation when one is +available. Otherwise use Read, Edit, Grep, Glob. ### 3b: Apply improvements @@ -302,7 +318,7 @@ full. Apply fixes directly: - Identical match arms that can be consolidated - Helpers duplicated across `language_*.rs` that could move to `big-code-analysis-ast/src/macros/` / `big-code-analysis-ast/src/c_langs_macros/` / a shared module (follow - `.claude/rules/macro-comments.md` when consolidating into macros) + `docs/development/formatting.md` when consolidating into macros) **Clarity**: @@ -395,8 +411,9 @@ For snapshot test changes: run `cargo insta test --review` and accept or reject each snapshot deliberately. Do NOT blindly accept. If a change shifts snapshots under `tests/repositories/big-code-analysis-output/` (the integration-snapshot submodule), it is behaviour-changing: follow -the submodule discipline in `AGENTS.md` (accepted snapshots pushed to -the submodule remote, new submodule SHA recorded in the same commit) — +the submodule discipline in `CONTRIBUTING.md` "Integration snapshots" (accepted snapshots committed in +the submodule, its new SHA recorded in the same commit, the submodule +commit reported for the user to push) — or treat the change as out of scope for this skill and SKIP, since improvements here must stay behavior-neutral. @@ -442,8 +459,8 @@ git merge --no-edit If conflict: `git merge --abort` and log. After all merges (or directly, in branch mode), run `make pre-commit` on -the integration branch — the canonical validation gate (see "Validation -gates" in `AGENTS.md`; it adds udeps, doc warnings, the lint families, +the integration branch — the canonical validation gate (see "Local validation +gate" in `CONTRIBUTING.md`; it adds udeps, doc warnings, the lint families, the self-scan threshold gates, and `make snapshot-anchors` on top of the cargo trio run in 3e). If `make` is unavailable, fall back to the raw cargo gates from 3e. If it fails, bisect: @@ -454,7 +471,7 @@ git revert -m 1 --- -## Step 5: Update Serena memories +## Step 5: Update memories (when a persistent-memory tool is available) ### 5a: Update improvement progress @@ -495,6 +512,13 @@ Branch: improve/ ### Skipped | # | Change Area | Reason | +### Worktrees left behind +| Path | Branch | State (merged / unmerged / dirty) | +|------|--------|-----------------------------------| +(Each worktree this run allocated; `git worktree remove` is denied to +agents, so the user removes them. Runtime-allocated ones are the +runtime's to sweep.) + ### Statistics - Change areas: N - Applied: N diff --git a/.claude/skills/issue-plan/SKILL.md b/.claude/skills/issue-plan/SKILL.md index 21bd51869..dc7514bc5 100644 --- a/.claude/skills/issue-plan/SKILL.md +++ b/.claude/skills/issue-plan/SKILL.md @@ -41,8 +41,8 @@ Before planning, understand the relevant code: generation), and `enums` (language-enum codegen). Per-language logic lives under `big-code-analysis-ast/src/languages/` (one `language_.rs` per supported language) and metric implementations under `src/metrics/`. -3. Use Serena LSP tools (`find_symbol`, `get_symbols_overview`, - `find_referencing_symbols`) — or Grep / Glob if Serena is unavailable — +3. Use a code-intelligence tool (`find_symbol`, `get_symbols_overview`, + `find_referencing_symbols`) when one is available, or Grep / Glob otherwise, to locate the relevant code paths. 4. Note the scope: how many files, which crate(s), which language modules, whether public API is affected, whether tree-sitter grammar versions diff --git a/.claude/skills/lessons-learned/SKILL.md b/.claude/skills/lessons-learned/SKILL.md index a9ff6c474..7b915dfc8 100644 --- a/.claude/skills/lessons-learned/SKILL.md +++ b/.claude/skills/lessons-learned/SKILL.md @@ -99,7 +99,7 @@ are most likely to contain lesson-worthy material. ### 3d: Documentation changes (skip when hint provided) ```bash -git log --since="$BOUNDARY" --name-only --format="" -- docs/ big-code-analysis-book/ README.md CLAUDE.md +git log --since="$BOUNDARY" --name-only --format="" -- docs/ big-code-analysis-book/ README.md AGENTS.md ``` Look for new or substantially updated documentation that may reflect @@ -113,7 +113,7 @@ For items from Step 3 showing hard-lesson signals: 1. Read full issue threads and linked PRs 2. Examine diffs: `git show ` -3. Use Serena LSP tools or code reading for surrounding context +3. Use a code-intelligence tool or code reading for surrounding context 4. Look for pattern repetition — did the same mistake happen more than once (e.g., across multiple language modules)? @@ -160,10 +160,11 @@ case-by-case reasoning: |--------|-----------------| | One-off debugging trick | Code comment at the relevant site | | Architectural decision | Module-level `//!` doc or design doc | -| Testing pattern | [`.claude/rules/testing.md`](../../rules/testing.md) | -| Per-language dispatch / grammar shape | [`.claude/rules/grammar-dispatch.md`](../../rules/grammar-dispatch.md) | -| Formatting or gate quirk | [`.claude/rules/formatting.md`](../../rules/formatting.md) | -| Project convention or standing policy | `AGENTS.md` | +| Testing pattern | [`docs/development/testing.md`](../../../docs/development/testing.md) | +| Per-language dispatch / grammar shape | [`docs/development/grammar_dispatch.md`](../../../docs/development/grammar_dispatch.md) | +| Formatting or gate quirk | [`docs/development/formatting.md`](../../../docs/development/formatting.md) | +| Standing obligation every session needs | `AGENTS.md`, only if it cannot be derived from the code and applies to most tasks | +| Standing procedure for one kind of task | the guide under `docs/development/` that task routes to, or `CONTRIBUTING.md` for the gate | | Already covered by existing lesson | Merge into existing lesson #N | | Too specific to one issue | Issue comment or PR description | @@ -171,12 +172,14 @@ case-by-case reasoning: obligation.** A lesson is evidence that a bug class is real; a rule is the instruction you follow without re-reading the evidence. If the `**Lesson:**` paragraph you are about to write is an imperative that -applies every time someone touches a given surface — not a warning -about one recurring trap — it belongs in `.claude/rules/` or -`AGENTS.md`, and the lessons entry should shrink to the incident plus a -pointer. Do not restate a policy that already lives in `AGENTS.md`: -duplicated policy drifts, and the copy in the lessons file is the one -nothing enforces. +applies every time someone touches a given surface, it belongs in the +guide that surface routes to, and the lessons entry should shrink to +the incident plus a pointer. `AGENTS.md` loads into every session and +takes only what most tasks need and the code cannot say; a rule for +one kind of task goes in its guide, stated as the mechanism and the +check, not the incident. Do not restate a policy that already has a +home: duplicated policy drifts, and the copy in the lessons file is +the one nothing enforces. Push-back language must be explicit. **"No candidates qualify" is a valid success state.** Do not force entries to justify the workflow. @@ -225,9 +228,8 @@ awk '/^## [0-9]+\./{if(n)print len" "n; n=$0; len=0; next} {if(n)len++} END{if(n)print len" "n}' docs/development/lessons_learned.md | sort -rn | head ``` -The file is reference material read under time pressure, and -`CLAUDE.md`'s length rule applies to it: no filler, no summary that -restates the section above it. +The file is reference material read under time pressure: no filler, +no summary that restates the section above it. ### Cite issues and PRs, never commit hashes diff --git a/.claude/skills/rust-optimize/SKILL.md b/.claude/skills/rust-optimize/SKILL.md index 9051b84ed..a9a0b9703 100644 --- a/.claude/skills/rust-optimize/SKILL.md +++ b/.claude/skills/rust-optimize/SKILL.md @@ -325,7 +325,7 @@ Eliminates custom `Serialize`/`Deserialize` impls on single-field wrappers. If 3+ types share identical method implementations differing only in type name, extract a `macro_rules!` to generate them. (This pattern is already used heavily across `big-code-analysis-ast/src/languages/` — prefer extending the existing macros over inventing new -ones.) When consolidating, follow `.claude/rules/macro-comments.md`: keep the +ones.) When consolidating, follow `docs/development/formatting.md`: keep the macro body minimal and hoist per-call rationale comments above each invocation, never into the macro definition. diff --git a/.claude/skills/scan-project/SKILL.md b/.claude/skills/scan-project/SKILL.md index 338160210..c5107ce2c 100644 --- a/.claude/skills/scan-project/SKILL.md +++ b/.claude/skills/scan-project/SKILL.md @@ -28,8 +28,9 @@ checklist), this skill: - **NEVER commit code.** No `git commit`, no `git add`, no staging. Zero commits. - **NEVER leave uncommitted files.** No new files, no modified files, no temp files - in the worktree. If you accidentally create or modify a file, revert it - immediately with `git checkout -- .`. + in the worktree. If you accidentally create or modify a file, undo + your own edit with the exact inverse edit; never `git checkout -- .` + in a shared checkout. - **NEVER modify source files.** Not even "harmless" formatting or comment fixes. - **NEVER push branches.** - The ONLY side effects of this skill are: GitHub issues filed, Serena memories @@ -45,79 +46,24 @@ the scan. --- -## Step 0: Launch isolated agent +## Step 0: Isolate -**This step is MANDATORY and must be the very first action.** - -### Environment detection - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -``` - -- **Worktree mode**: Already inside a worktree. Keep existing behavior. -- **Branch mode**: Main project directory. Agents run without worktree isolation. - Serena LSP works correctly in this mode. - -### Branch mode prerequisites - -```bash -if [[ "$ISOLATION_MODE" == "branch" ]]; then - DIRTY="$(git status --porcelain)" - if [[ -n "$DIRTY" ]]; then - echo "Error: branch mode requires a clean repository." >&2 - echo "$DIRTY" >&2 - exit 1 - fi -fi -``` - -### Launch the orchestrating agent - -If you are the top-level orchestrator (invoked by the user), immediately launch -a single Agent that executes Steps 1-10. Pass the full workspace root path. - -- **Worktree mode**: Launch the Agent with `isolation: "worktree"`. -- **Branch mode**: Launch the Agent WITHOUT `isolation: "worktree"`. - -Sub-agents launched in Step 3 inherit the parent context (read-only) and do -NOT need their own `isolation: "worktree"`. - -### Agent verification (MANDATORY) - -Every agent must verify its environment before doing any work: - -```bash -PROJECT_ROOT="$(git rev-parse --show-toplevel)" -if [[ "$PROJECT_ROOT" == *".claude/worktrees/"* ]]; then - ISOLATION_MODE="worktree" -else - ISOLATION_MODE="branch" -fi -echo "ISOLATION_MODE=$ISOLATION_MODE PROJECT_ROOT=$PROJECT_ROOT" -``` - -In branch mode, also confirm the working tree is clean: - -```bash -git status --porcelain -``` - -If any output appears, abort: "ABORTED: Branch mode requires a clean working -tree." +This skill writes nothing, so it runs in **shared read-only mode** per +[`docs/development/agent_isolation.md`](../../../docs/development/agent_isolation.md): +verify `git status --porcelain` is empty before starting, run the +audit (and any parallel read-only sub-agents) in the current checkout +without switching branches, cleaning or resetting, and verify the tree +is still clean at the end (Step 10). If the user asked for a separate +checkout, allocate a worktree per that document and start the audit +there instead. Children never remove or prune worktrees. --- ## Step 1: Load scan history -Invoke the Serena MCP tool `serena:read_memory` with -`memory_name: "scan-project-state"`. If the Serena MCP server is not active, -call `serena:activate_project` first. +If a persistent-memory tool (such as the Serena MCP server) is +available, read the memory `scan-project-state`; otherwise treat the +project as unscanned. The memory key is a fixed token (no `$ARGUMENTS` interpolation) because scope is workspace-wide. This sidesteps the slash-sanitization rule @@ -179,7 +125,7 @@ path**: Step 8 reads these files from a different tool call, and a shell variable does not survive that boundary, so the summary needs the literal path. A fixed `/tmp/scan-metrics.json` is shared with every other scan on the host (see -[`.claude/rules/temp-files.md`](../../rules/temp-files.md)). +`AGENTS.md`, "Temporary files"). ```bash SCAN_DIR=$(mktemp -d "${TMPDIR:-/tmp}/bca-scan.XXXXXX") && echo "SCAN_DIR=$SCAN_DIR" @@ -216,12 +162,10 @@ FD=$(command -v fd 2>/dev/null || command -v fdfind 2>/dev/null) ## Step 3: Partition scope and launch sub-agents -Launch all six sub-agents **in parallel**. Use the `Agent` tool with -`subagent_type: "general-purpose"`, one call per partition, all six in a -single message so they run concurrently. Do **not** pass -`isolation: "worktree"` to the sub-agents — Step 0 already arranged -isolation at the orchestrator level, and sub-agents inherit the -parent's read-only context. +Launch all six sub-agents **in parallel**. Launch one general-purpose +sub-agent per partition, all six together so they run concurrently. +They need no worktree of their own: Step 0 already isolated the +orchestrator, and the scan is read-only. Each agent receives: @@ -850,7 +794,8 @@ A degraded run must not be confused with a clean one in ## Step 9: Save scan state -Invoke `serena:write_memory` with `memory_name: "scan-project-state"` and the +If a persistent-memory tool is available, write the memory +`scan-project-state` with the merged content as `content`. Build the memory by **merging** prior state (from Step 1) with the current @@ -895,9 +840,9 @@ git status --porcelain If any output appears: -- For **modified tracked files** (`M` lines): revert with - `git checkout -- `. Do NOT use a blanket `git checkout -- .` in - worktree mode. +- For **modified tracked files** (`M` lines): do NOT restore them; the + checkout is shared and the change may be the user's. Report each path + and diff in the final summary. - For **untracked files** (`??` lines): do NOT delete them. Surface their paths in the final summary for user review. Never run `git clean` from this skill. @@ -910,7 +855,7 @@ summary. All ABSOLUTE CONSTRAINTS (top of this document) apply. Additionally: -- **NEVER delete worktrees.** Only the Claude Code runtime may do that. +- **NEVER delete worktrees.** The orchestrator that created one cleans it up. - Do NOT implement fixes. This is scan-only. - Do NOT file findings without concrete evidence (file + line + reasoning). - Do NOT file duplicate issues. Always check `gh issue list` first. diff --git a/.claude/skills/simplify-rust/SKILL.md b/.claude/skills/simplify-rust/SKILL.md index ef17da7ad..1de313fc2 100644 --- a/.claude/skills/simplify-rust/SKILL.md +++ b/.claude/skills/simplify-rust/SKILL.md @@ -59,7 +59,7 @@ Look for duplicated logic and missing abstractions. - Helper functions that duplicate standard library or crate functionality - Per-language duplicated logic in `big-code-analysis-ast/src/languages/` that could be expressed via a trait method or macro instead of being copied across language modules - (when consolidating into a macro, follow `.claude/rules/macro-comments.md`: + (when consolidating into a macro, follow `docs/development/formatting.md`: hoist per-language rationale comments above each invocation, not into the macro body) diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index d02dd757b..677990e57 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -584,7 +584,7 @@ jobs: # tcl a two-row fixture table whose rows are cfg-gated # collapses to one row (`clippy::single_element_loop`). # - # `go` is the fourth because `.claude/rules/testing.md` names + # `go` is the fourth because `docs/development/testing.md` names # `--features go` as the subset contributors run to verify a # feature-gated fixture table: it is the nearest thing to a # language outside every union, enabling none of the five diff --git a/.gitignore b/.gitignore index 6d2c456e3..2a51bdd0b 100644 --- a/.gitignore +++ b/.gitignore @@ -4,6 +4,10 @@ enums/target .claude/settings.local.json .claude/scheduled_tasks.lock .claude/worktrees/ +# Personal Claude Code overrides. A CLAUDE.local.md (or CLAUDE.md) in the +# tree stops Claude Code reading AGENTS.md natively; put `@AGENTS.md` on +# its first line, or set Project instructions to claude-md-and-agents-md. +CLAUDE.local.md .mcp.json .serena/ *.pending-snap diff --git a/.pre-commit-config.yaml b/.pre-commit-config.yaml index aae257e4e..4561deb7d 100644 --- a/.pre-commit-config.yaml +++ b/.pre-commit-config.yaml @@ -110,7 +110,7 @@ repos: # match verbatim while `cargo fmt --check` still exits 0, so the # `fmt` hook above cannot see any of this. The gate sweeps the # whole workspace rather than a directory list — the site list in - # .claude/rules/formatting.md was scoped to src/metrics/ for two + # docs/development/formatting.md was scoped to src/metrics/ for two # revisions, which is exactly how the largest cluster # (src/getter/) went unnoticed — so the trigger is any Rust file. - id: rustfmt-bail diff --git a/.role-bypass-baseline.txt b/.role-bypass-baseline.txt index e7f83f953..4acee9160 100644 --- a/.role-bypass-baseline.txt +++ b/.role-bypass-baseline.txt @@ -1,6 +1,6 @@ # Role-bypass baseline: role-claimed kinds still restated as # classification inside the consumer boundary (#1692). -# Maintained by check-role-bypass.py; see AGENTS.md "Validation gates". +# Maintained by check-role-bypass.py; see CONTRIBUTING.md "Local validation gate". # # An entry is one site a migration package will replace with a call to # the row. The gate fails on a site not listed here; `--update` only diff --git a/.role-census-baseline.txt b/.role-census-baseline.txt index e785af747..6d8f9272d 100644 --- a/.role-census-baseline.txt +++ b/.role-census-baseline.txt @@ -1,6 +1,6 @@ # Role-census baseline: the (language, role, package) cells still # `pending` in big-code-analysis-ast/src/roles/.rs (#1692). -# Maintained by check-role-census.py; see AGENTS.md "Validation gates". +# Maintained by check-role-census.py; see CONTRIBUTING.md "Local validation gate". # # An entry is one cell a later work package will declare. The gate # fails when a current pending cell is not listed here, so a row cannot diff --git a/.role-coverage-baseline.txt b/.role-coverage-baseline.txt index b23c98075..665f3cd6a 100644 --- a/.role-coverage-baseline.txt +++ b/.role-coverage-baseline.txt @@ -1,5 +1,5 @@ # Role-coverage baseline: runtime kinds no role declares (#1692). -# Maintained by check-role-coverage.py; see AGENTS.md "Validation gates". +# Maintained by check-role-coverage.py; see CONTRIBUTING.md "Local validation gate". # # An entry is one (language, kind id) that no row of any role names in # `owns`, `pays` or `wraps` and no row excludes with a reason. Identity @@ -1140,6 +1140,7 @@ 267 named visible 'accessor_list' 270 named visible 'bracketed_parameter_list' 272 named visible 'explicit_interface_specifier' +273 named visible 'parameter_list' 274 named visible 'parameter' 275 anon hidden '_parameter_array' 276 named visible 'constructor_initializer' @@ -2601,6 +2602,7 @@ 154 named visible 'constructor_delegation_call' 155 named visible 'type_parameters' 156 named visible 'type_parameter' +157 named visible 'primary_constructor' 158 named visible 'class_parameters' 160 named visible 'type_constraints' 161 named visible 'type_constraint' diff --git a/.role-coverage-observed.txt b/.role-coverage-observed.txt index 7c6a090dc..ae21053e8 100644 --- a/.role-coverage-observed.txt +++ b/.role-coverage-observed.txt @@ -6,7 +6,7 @@ observer bca 2.5.2 corpus DeepSpeech aa1d28530d531d0d92289bf5f11a49fe516fdc86 corpus pdf.js 65c4a4b3fe81b20cd262193c55a6f4519362184c corpus serde d6de911855d1cc0ad13f87503a79d40dc4490442 -corpus big-code-analysis-output 5fbe03bf005b9b03a1928273faa477a9c1be5ed7 +corpus big-code-analysis-output d411e605123cd81b7881d819f03b541799dccebe [Javascript tree-sitter-javascript 0.25.0 sampled attempted=388 parsed=388 failed=0] 1 diff --git a/.rustfmt-bail-baseline.txt b/.rustfmt-bail-baseline.txt index d9cc953ec..bb0ccb26a 100644 --- a/.rustfmt-bail-baseline.txt +++ b/.rustfmt-bail-baseline.txt @@ -1,5 +1,5 @@ # Match arms rustfmt declines to format, per file. -# Maintained by check-rustfmt-bail.py; see AGENTS.md "Validation gates". +# Maintained by check-rustfmt-bail.py; see CONTRIBUTING.md "Local validation gate". # Lower-or-equal current counts pass; any increase fails CI. # Regenerate with: ./utils/check-rustfmt-bail.py --update # @@ -10,7 +10,7 @@ # 1. A comment inside a match *pattern* (between the pattern and its # `=>`, or between `|` alternatives). Fix by hoisting the comment # above the arm, outside the pattern — never by deleting it. See -# .claude/rules/formatting.md. +# docs/development/formatting.md. # 2. A `macro_rules!` body rustfmt cannot parse, typically a # metavariable in a non-Rust position such as `mk_langs!`'s # `LANG::$camel => …` arms. No comment is involved; hoisting diff --git a/.snapshot-anchor-baseline.txt b/.snapshot-anchor-baseline.txt index 2dc4db083..9e248ac94 100644 --- a/.snapshot-anchor-baseline.txt +++ b/.snapshot-anchor-baseline.txt @@ -1,5 +1,5 @@ # Bare insta::assert_json_snapshot! call counts per metric file. -# Maintained by check-snapshot-anchors.py; see AGENTS.md. +# Maintained by check-snapshot-anchors.py; see CONTRIBUTING.md "Snapshot anchors". # Lower-or-equal current counts pass; any increase fails CI. # Regenerate with: ./utils/check-snapshot-anchors.py --update # diff --git a/AGENTS.md b/AGENTS.md index 9c2e96b96..3f8a8cd83 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -1,1015 +1,175 @@ # AGENTS.md -Universal project instructions for AI coding assistants. +Shared instructions for coding agents working in this repository. Keep +this file short: it loads into every session. Procedures live in the +documents the routing table names and in `.claude/skills/`. There is +deliberately no `CLAUDE.md`: Claude Code reads this file natively, and +an `@AGENTS.md` shim is not expanded when a session starts in a +subdirectory. A personal `CLAUDE.local.md` suppresses native reading; +start it with `@AGENTS.md` and work from the repository root. -## Project Overview +`big-code-analysis` is a published Rust library (crates.io, `2.x`) with +two binaries, `bca` (CLI) and `bca-web`. It is a Cargo workspace; the +`big-code-analysis-ast` crate is internal plumbing the root pins at +`=X.Y.Z`. Default branch: `main`. Read code before asking about layout. -`big-code-analysis` is a Rust library that extracts maintainability -metrics from source code in many languages. It is a hard fork of -Mozilla's -[rust-code-analysis](https://github.com/mozilla/rust-code-analysis), -maintained in this repository. It is built on -[tree-sitter](https://tree-sitter.github.io/tree-sitter/) and is published on -crates.io as a library plus two binaries. - -The repository is a Cargo workspace: - -| Crate | Path | Purpose | -|-------|------|---------| -| `big-code-analysis` | `./` (root) | Library: the metric walk, output formats, suppression, VCS metrics; the published API surface | -| `big-code-analysis-ast` | `big-code-analysis-ast/` | Parse and classification layer (#1376): generated kind enums, `LANG`, `Node`, `Checker` / `Getter` / `Alterator`, the C preprocessor pass. Internal plumbing the root pins at `=X.Y.Z`; depend on the root, not on it | -| `big-code-analysis-cli` | `big-code-analysis-cli/` | CLI for invoking the library on files / trees | -| `big-code-analysis-py` | `big-code-analysis-py/` (excluded from default-members; needs Python headers + maturin) | PyO3 Python bindings | -| `big-code-analysis-web` | `big-code-analysis-web/` | REST API server wrapping the library | -| `big-code-analysis-bench` | `big-code-analysis-bench/` (excluded from default-members) | Out-of-band benchmark harness for the metric walk: the complexity-class gate (`make bench-scaling`) and criterion measurements (`make bench-walk`); see [`docs/development/benchmarking.md`](docs/development/benchmarking.md) | -| `xtask` | `xtask/` (excluded from default-members) | Build-time helper that renders man pages from the live clap definitions (see `man/`) | -| `enums` | `enums/` (excluded from default workspace) | Code-generation helper for language enums | -| `big-code-analysis-fuzz` | `fuzz/` (excluded from the workspace) | Out-of-band `cargo-fuzz` targets for the parse-and-walk layer (`make fuzz-check` / `fuzz-smoke`); see [`docs/development/fuzzing.md`](docs/development/fuzzing.md) | - -Vendored / path-dependent grammar crates also live in the repo: -`tree-sitter-ccomment`, `tree-sitter-mozcpp`, `tree-sitter-mozjs`, -`tree-sitter-preproc`, `tree-sitter-tcl`. External grammar crates are -pinned with `=X.Y.Z` versions in the root `Cargo.toml`. - -The default branch is **`main`**. - -The CLI binary is **`bca`** (package `big-code-analysis-cli`); the -web-server binary is **`bca-web`** (package `big-code-analysis-web`). -From a checkout, run them via `cargo run -p big-code-analysis-cli --` -and `cargo run -p big-code-analysis-web --`. - -## Project layout - -- `src/lib.rs` — public re-exports; this is the published API surface. - Everything the parse layer defines reaches the metric modules through - one `pub(crate) use big_code_analysis_ast::*` here, so `use crate::*` - in a metric file still names every token enum, tag and classifier. -- `big-code-analysis-ast/src/languages/` — one `language_.rs` per - supported language, generated by `enums/`. These modules deliberately - mirror each other, as do the per-language `checker/`, `getter/` and - `src/metrics//` siblings. A bug in one language module - typically exists in several — fix all affected siblings together. -- `big-code-analysis-ast/src/roles/` — one `role_table!` per language - (`.rs`), declaring for every role which kinds own a construct - and which tokens pay for it, read by the `Checker`, the `Getter` and - the root crate's metric arms instead of restated kind lists (#1690). - `mod.rs` holds the macro and the **module doc that is the - contributor reference**: the role set, the row grammar, what a table - emits, how a consumer reads a row, the gates, and the one list of - what the mechanism cannot see — link to it, do not copy it. - `c_family.rs`, `js_family.rs` and `tcl_family.rs` are the shared - `..fragment!()` kind lists; `control_flow.rs` the shared `ElseIf` - gates; `*_tests.rs`, `doc_tests/` and `derived_parity_tests.rs` the - per-package, documentation and derived parity suites. -- `big-code-analysis-ast/src/` — `langs.rs` (`LANG`, `AnyParser`), - `node.rs`, `parser.rs`, `traits.rs` (`ParserTrait`), `checker.rs`, - `getter.rs`, `alterator.rs`, `lang_helpers/`, `preproc.rs`, - `c_macro.rs`, `comment_rm.rs`, `ast.rs`, `count.rs`, `find.rs`, - `tools.rs`, plus `space_kind.rs` and `token_role.rs` (the two - classifications a `Getter` returns) — everything that turns bytes - into a classified tree and computes no metric. `macros/mod.rs` there - holds `mk_langs!` and the `with_any_parser!` dispatch macro. Nothing - under this crate names a metric: `TokenRole` was `HalsteadType` until - #1376, and the "do the member metrics apply" predicate lives in the - root as `metrics::MemberScopeExt`. -- `src/metrics/` — individual metric implementations: `abc.rs`, - `cognitive.rs`, `cyclomatic.rs`, `nexits.rs`, `halstead.rs`, `loc.rs`, - `mi.rs`, `nargs.rs`, `nom.rs`, `npa.rs`, `npm.rs`, `tokens.rs`, - `wmc.rs`. -- `src/output/` — the text dump trees plus the CSV, SARIF, Checkstyle, - Code Climate and compiler-warning-line writers. The JSON, YAML, TOML - and CBOR serializers live in `big-code-analysis-cli/src/formats.rs`. -- `src/spaces.rs` / `src/spaces/` — `Ast`, `analyze`, `FuncSpace`, and - the metric walk; `src/metric_suite.rs` — the `MetricSuite` supertrait - that keys the 13 per-metric impls on a parser; `src/macros/mod.rs` — - `implement_metric_trait!`. -- `tests/` — integration tests, including `insta` snapshot tests - (`*.snap` / `*.snap.new`). -- `big-code-analysis-book/` — mdBook documentation source. -- `enums/` — separate workspace member (excluded from the root workspace) - that generates language enum tables. -- `utils/` — repo-maintenance helper scripts, including the gates run - by `make pre-commit` / `make ci`: `check-versions.py`, - `check-snapshot-anchors.py`, `check-rustfmt-bail.py`, - `check-manpage-assets.py`, `check-manpage-drift.py`, - `check-diagnostic-prefix.py`, `check-safety-doc-pin.py`, - `check-grammar-build-watch.py`, - `check-grammar-marker-sync.py`, `check-enums-codegen-drift.sh`, - `check-grammar-crate.py`, `check-grammars-crates.sh`, - `check-excluded-manifests.py`, `check-ruff-lockstep.py`, - `check-rumdl-lockstep.py` (the rumdl, actionlint and checkmake pins), - `check-publish-metadata.py`, `check-test-lang-gates.py`, - `check-role-census.py`, `check-role-coverage.py`, - `check-role-bypass.py` (the three role-table gates, all reading - declarations through `role_tables.py`), `verify-name-only-churn.py`, - `mutation-report.py` (the summarize and report halves of the sharded - mutation-testing workflow, with `mutation-workflow-test.py` - executing that workflow's shell steps), and each gate's `*-test.py` - self-tests. - Each gate resolves the repository root from its own location - (`Path(__file__).resolve().parents[1]`) rather than the cwd, so it - runs correctly from anywhere; callers invoke them as `utils/`. - `check-deny-manifests.sh` (#1823) is a gate `make pre-commit` does - not run, because it needs the network: the two `deny` workflow jobs - and `make release-check` (#1826) call it to run cargo-deny once per - tracked `Cargo.lock`, and `make pre-commit` runs only its `*-test.py`, - against a stubbed cargo-deny. - `check-grammar-crate.py`, `check-grammars-crates.sh`, - `patch-coverage.py` and `verify-name-only-churn.py` are not gates: - they take their paths as arguments or run against the cwd. Nor are - the role-series drift drivers (#1697, landed by #1744): - `drift-oracle.py` captures every CLI view — and, given the - `verbatim-oracle` binary from `big-code-analysis-bench`, the - library's verbatim view — per file and language under an options - matrix; `drift-compare.py` compares two captures on keys and bytes - and refuses a view only one side carries; `recovery-oracle.py` is - the lesson-102 truncation sweep; `perturb.py` is the - `.claude/rules/testing.md` perturbation driver, which refuses a - target that is modified, untracked, ignored or absent and restores - from memory, under a `cargo` or a `unittest` runner — the latter runs - `perturb_unittest_recorder.py` in place of `-m unittest`, unittest's - own `main` recording each outcome as data, since a test can print - anything the report prints; `coverage-diff.py` compares two `llvm-cov` reports by - covered count. The extension tables, - grammar-pin reader, byte-level subprocess capture and manifest - shape the three drift drivers share live in `drift_common.py`, - derived from `role_tables.py` so a sweep cannot skip an extension - the enum owns. Each has a `*-test.py` in `make pre-commit` that - stubs the binaries it drives (`coverage-diff-test.py` runs real - `git` on a scratch repository), which is the only thing that lints - them (#1477). `self-scan-bca.py` is what every `make self-scan*` - recipe runs instead of `cargo run`: it picks the `bca` to execute — - an explicit `BCA_SELF_SCAN_BINARY`, a PATH `bca` whose `--version` - reports a `build inputs:` digest equal to the one - `self_scan_digest.py` recomputes over the checkout, or a dev-profile - `cargo run` — and `exec`s it (#1773). The digest module mirrors - `big-code-analysis-cli/src/build_info/digest.rs`; one fixture and one - pinned hex in `self-scan-bca-test.py` and the Rust tests hold the two - together. -- Other helper scripts: `recreate-grammars.sh`, `generate-grammars/`. - (The grammar-bump diff step now uses the native `bca diff`; the former - `split-minimal-tests.py` + external `json-minimal-tests` chain was - retired in #487.) - -## Editing principles - -- This is a published `2.x` library (`big-code-analysis` on crates.io) - with a written stability contract in [`STABILITY.md`](./STABILITY.md). - Treat `lib.rs` re-exports, public traits (`ParserTrait`, - `LanguageInfo`, etc.), and public types (`CodeMetrics`, `FuncSpace`, - language enums) as a stable API surface. Within the current major - line, additive changes belong under a minor bump; breaking shape - changes are reserved for the next major (`3.0`) and must be planned - deliberately — never slip a SemVer break into a patch or minor - release. Public-API changes must be cross-referenced against - `STABILITY.md` and recorded in the `## [Unreleased]` section of - `CHANGELOG.md`; if the change is a source-level break that must - wait for the next major, mark the entry **(breaking)** and note - that it is deferred to the next major bump (the release-prep - commit then moves the entry into the appropriate version section). -- For code files: prefer LSP / symbol-level editing - (`replace_symbol_body`, `insert_before/after_symbol`) over line-based - edits when available. Read the file (or use a symbol overview) before - editing. -- For non-code files (Markdown, TOML, YAML, JSON): use targeted edits with - scoped `old_string` / `new_string` pairs. Avoid `sed` for multi-line - edits. -- The book is translated (Japanese, `big-code-analysis-book/po/ja.po`) - via the gettext workflow in - [`docs/development/translations.md`](docs/development/translations.md). - English doc edits never block on translation — changed paragraphs - fall back to English on the `/ja/` site until someone runs - `make book-po-update` and fills the new/fuzzy entries. Two rules do - apply: pin an explicit `{#anchor}` id on any heading you - fragment-link to, and keep `README.ja.md` in step when you edit - `README.md`. -- Never rewrite an entire test file to add or fix one test. Modify only - the specific tests that need changing. -- Verify previously passing tests still pass before committing - (`cargo test --workspace --all-features`). -- When fixing a bug, add a regression test that would catch the exact bug - if reintroduced. -- Default to writing no comments. Only add one when the *why* is - non-obvious. -- Issue and PR references belong in `//` maintainer comments, never in a - `///` doc comment on a clap type. clap renders `///` into - `bca --help` and `cargo xtask` renders the same text into - `man/`, so an internal note ships to users twice and drifts the - committed man pages. `help_text_carries_no_issue_references` pins - this — a failure is a real leak, not a test to relax. Any edit to a - clap help/about/value doc, even a pure wording fix, must be followed - by `cargo xtask` with the regenerated `man/` pages in the *same* - commit. -- **MANDATORY** before any public API change: enumerate every call site - (`find_referencing_symbols` if an LSP tool is available, otherwise a - workspace-wide search). Cross-crate breakage is silent until CI. -- When a change touches metric computation, AST traversal, or anything - under `big-code-analysis-ast/src/languages/`, exercise **every** language affected — passing - tests in one language do not catch regressions in another. Per-language - modules deliberately mirror each other; a bug in one typically exists in - several. - -## Tool choice - -- **Shell**: assistant tooling runs **zsh**, which does not field-split - an unquoted parameter expansion the way bash does — `cmd $FLAGS` - passes one argument, not several. The failure is silent and yields a - plausible result rather than an error, so it has already produced - fabricated measurement tables here. Build argument lists as arrays and - expand them `"${ARR[@]}"`. See - [`.claude/rules/shell.md`](.claude/rules/shell.md). -- **Tool output**: a truncated result is not a result. Persisted output - shown as a `Preview (first 2KB)` fragment carries no marker at the cut, - and the orderings in routine use here — `sort | uniq -c`, `rg` over a - tree, a test run's trailing summary — put the rows that matter past it. - Read the persisted file, or aggregate in the command. See - [`.claude/rules/tool-output.md`](.claude/rules/tool-output.md). -- **History rewrites**: a scripted rebase that names a superseded hash - replays the old commit without an error. Compare tree hashes against a - backup ref after any rewrite; see - [`.claude/rules/history-rewrite.md`](.claude/rules/history-rewrite.md). -- **Temp files and evidence**: three tiers, decided before the first - write. Irreplaceable → a test, `utils/`, or an issue attachment - (ask when none fits); regenerable but expensive or multi-session → - `/var/tmp/bca//` with a `PROVENANCE.md`; scratch → `/tmp` - via `mktemp "${TMPDIR:-/tmp}/bca-.XXXXXX"`, never a fixed - name. See [`.claude/rules/temp-files.md`](.claude/rules/temp-files.md). -- **Code search**: `rg` (ripgrep). Never `grep` via Bash. -- **File search**: `fd` (or `fdfind` on Debian/Ubuntu). Never `find` via - Bash. -- **Code intelligence**: when an LSP-based tool such as Serena is - available, use it as the default for read / search / edit / refactor - (`get_symbols_overview`, `find_symbol`, `find_referencing_symbols`, - `replace_symbol_body`). -- **External docs**: prefer Context7 / `cargo doc` over web search for - library / crate documentation. -- **Python environment**: `uv` is the canonical, lockfile-driven - bootstrap for `big-code-analysis-py`. `make py-bootstrap` runs - `uv sync --locked --extra dev` from the checked-in `uv.lock`, - producing a reproducible dev environment shared across contributors - who use this path. After editing `pyproject.toml` deps, run - `make py-relock`, which regenerates `uv.lock` **and** the - hash-pinned exports under `big-code-analysis-py/requirements/` - (`dev.txt`, `examples.txt`); bootstrap will fail-loud rather than - silently rewriting the lockfile. Install uv with - `curl -LsSf https://astral.sh/uv/install.sh | sh`, - `brew install uv`, or `pipx install uv`. Alternative provisioning - paths (`mise install` via `mise.toml`, direct `pipx install`, plain - `pip install -e .[dev]`) remain functional but bypass `uv.lock` — - resolved versions can drift from peers and from CI. CI consumes - `uv.lock` through those requirements exports (`pip install - --require-hashes -r …` in the workflows, per OpenSSF Scorecard - Pinned-Dependencies), so a `uv.lock` change and its regenerated - exports must land in the same commit. -- **GitHub Actions linting**: any edit under `.github/workflows/` - must be validated with `make actionlint` before commit. The - Makefile target invokes `actionlint` at the repo root, which - discovers workflows automatically and shells out to `shellcheck` - for embedded `run:` scripts. `make actionlint` is wired into `make - lint`, `make pre-commit`, and `make ci`, and into the `actionlint` - hook in `.pre-commit-config.yaml`. Suppress shellcheck false - positives inside a `run:` block with a scoped `# shellcheck - disable=SCxxxx` directive (and a short why-comment), not by - loosening actionlint configuration. If composite actions are ever - introduced under `.github/actions/*/action.yml`, extend the - Makefile recipe and the pre-commit hook to pass those files to - actionlint explicitly — bare `actionlint` does not discover them. - -## Rust conventions - -- No `unsafe` code anywhere in the workspace, with one narrow, - documented exception: the PyO3 bindings (`big-code-analysis-py`) - erase the lifetime brand on a `Copy`, borrow-free `tree_sitter` FFI - value so a `#[pyclass]` (which cannot carry a lifetime) can hold it, - keeping the owning tree alive through a strong `Py<...>` handle. The - canonical soundness argument lives at - `big-code-analysis-py/src/node.rs` (the `# Safety` module doc and - `detach`), and the node/`Ast` pairing that argument depends on is - enforced by the `owned` module boundary there — private fields, so a - handle can only be built by `wrap` / `rewrap` / `rooted_at` and not by - a struct literal that pairs a node with the wrong tree (#1057). The - version the doc names is gated by `make check-safety-doc-pin`. Any - `unsafe` outside this exact pattern remains banned and - needs a deliberate amendment to this rule. (The PyO3-macro-generated - FFI shims under `#![allow(unsafe_op_in_unsafe_fn)]` in `src/lib.rs` - are source-level `unsafe`-free and not covered by this exception.) -- No `unwrap()` / `expect()` / `panic!()` / `assert!()` in non-test code; - propagate errors with `?`. `expect("reason")` and `assert!()` are - acceptable in tests and may be acceptable in production for - provably-unreachable invariants — document the invariant in the - `expect` message. -- Prefer `pub(crate)` over `pub`; widen visibility only when an item is - re-exported from `lib.rs`. -- Prefer borrowing over cloning. Use `&str` over `String` parameters - unless ownership is required downstream. -- Newtype wrappers for domain identifiers; do not pass two same-typed - primitives where they could be confused. -- Never use `to_string_lossy()` on paths used as identifiers (map keys, - JSON output, error correlation). Use `to_str()` with explicit error - handling. `path.display()` is fine for log output only. -- Stderr diagnostics carry a **lowercase** severity prefix, written in - one place per crate: `warn` / `die` / `note` in - `big-code-analysis-cli/src/diag.rs`, `warn` in `src/diag.rs`. Pass the - bare message and never spell `warning:` / `error:` / `Warning:` in a - literal — including in a `Display` impl, whose renderings are prefixed - by whichever layer presents them (#609, #1199). - `make check-diagnostic-prefix` blocks the capitalised spellings; the - lowercase ones are convention, not gated — so `bca: warning:` and a - hand-rolled `warning:` are on you to catch in review. Informational - `bca: …` lines (`bca: wrote N baseline entries`) are a separate, - severity-free family and stay as they are; a severity word after that - namespace is the redundant double prefix #609 removed. -- Edition is 2024 — `let-else`, let-chains, and other 2024 features are - available. -- The lint posture (`clippy::pedantic` at `warn`, `missing_docs`) lives - in `[workspace.lints]` and reaches members through - `lints.workspace = true`. A **workspace-excluded** crate roots its own - workspace and inherits nothing, so it needs its own copy of those - tables; `enums` carries one, and the five vendored `tree-sitter-*` - crates are exempt by decision, because a regeneration replaces their - generated sources wholesale — with one exception, - `bindings/rust/build.rs`, which carries a hand-maintained - `src/tree_sitter/` header watch (#1773) that no regeneration - restores and that `make check-grammar-build-watch` gates (#1778). - `utils/check-excluded-manifests.py` gates the lint tables — without - it a crate gated at `-D warnings` is measured against the compiler - defaults and still reads as fully linted (#1228). - Additional `allow`s go at file or function level, so the carve-out - stays visible at the affected site. - -## Validation gates - -In a checkout you have not run the gate in before, run -`make worktree-setup` first. It checks out the integration corpora and -the Python-bindings venv; without them `make pre-commit` reports dozens -of test failures and mypy errors that are bootstrap artifacts rather than -regressions. It is idempotent and a ~100 ms no-op afterwards, and it -repairs an interrupted corpus checkout — a state a plain -`git submodule update --init` cannot fix, because the recorded SHA -already matches and the re-run is a silent no-op (#1171). - -Before considering a change done, run `make pre-commit` from the repo -root. It is the canonical entry point for the full validation gate -and runs, in one parallel pass: the cargo trio (`cargo fmt --check` — -over the workspace and, by manifest path, the excluded `enums/` and -`fuzz/` crates that `--all` does not reach, -`cargo clippy --workspace --all-targets -- -D warnings` in both -default-features and `--all-features` flavours, the full test suite -via `make test` + `make test-doc` — `make test` runs `cargo nextest -run --workspace --all-features` when `cargo-nextest` is on PATH and -falls back to `cargo test --workspace --all-features --lib --bins ---tests` otherwise, and `make test-doc` covers the doctests nextest -cannot run), `cargo doc --no-deps --workspace ---all-features` with `RUSTDOCFLAGS="-D warnings"`, -`cargo +nightly udeps`, the markdown / -TOML / shell / Makefile / GitHub Actions lint families, the man-page -drift gate (`cargo xtask` + `utils/check-manpage-drift.py`, mirroring -the `manpage` CI job, which calls the same script — it fails on -modified, deleted, **and** newly added pages, the last of which -`git diff` alone cannot see, #1249), the diagnostic-prefix gate -(`make check-diagnostic-prefix`, which blocks a capitalised -`Warning:` / `Error:` / `Note:` string literal — see "Rust -conventions"), the per-language test gate -(`make check-test-lang-gates`, which fails on a test that would be -compiled into a build lacking a grammar it names — #1472 — and, in the -other direction, on a gate *wider* than the item it guards, which keeps -a test out of builds it could have run in and which nothing else can -see — #1478), -the safety-doc pin gate -(`make check-safety-doc-pin`, which fails when the `tree-sitter` -version cited by the `unsafe` soundness argument in -`big-code-analysis-py/src/node.rs` is not the version -`[workspace.dependencies]` pins, or when the citation is dropped -altogether — #1057), the grammar build-watch gate -(`make check-grammar-build-watch`, which fails when the -`bindings/rust/build.rs` of any `[workspace].exclude` entry naming -`tree-sitter` no longer carries the hand-maintained `src/tree_sitter/` -header watch verbatim, or is missing outright — #1778), the bca -self-scan threshold gate at both -tiers (`make self-scan` mirroring the `Threshold gate` step in -`.github/workflows/pages.yml`, plus `make self-scan-headroom` -which scales every limit by `BCA_HEADROOM` — default `0.95` — so -functions encroaching into the 95-100% band fail before the hard -gate trips; `make self-scan-write-baseline-headroom` refreshes -`.bca-baseline.toml` — prefer the headroom variant over the bare -`make self-scan-write-baseline`, otherwise the soft-tier -`self-scan-headroom` gate re-fires on untouched files), the -ruff-lockstep gate (`make check-ruff-lockstep`, which fails when the -`ruff-pre-commit` `rev:` in `.pre-commit-config.yaml` is not `v` + the -version `big-code-analysis-py/uv.lock` resolves, when the -`requirements/dev.txt` export has fallen behind that lockfile, or when -`pyproject.toml`'s ruff bound was edited without a `make py-relock` — -see "One ruff version" below), the publish-metadata gate -(`make check-publish-metadata`, which asserts every publishable crate -carries the `description` / `readme` / `repository` / `license` fields -crates.io needs, that a crate rooted at the workspace root has a -non-empty `[package].include`, and that the files `cargo package ---list` reports total under 32 MiB — the four top-level -crates pin internal deps at `=` and so cannot be -`cargo publish --dry-run`-ed before the tag, see `RELEASING.md`), and the -Python `ruff` lint / -`ruff format` / `mypy --strict` + `pyright` / `maturin develop` + -`pytest` / `mypy stubtest` stages for `big-code-analysis-py` (each -Python stage is skipped with a clear "X not found" message when the -corresponding tool is absent). `make ci` runs the same checks without -auto-fix, mirroring CI behaviour. - -**One ruff version, four declarations.** -`big-code-analysis-py/uv.lock` is the anchor: it is what `uv sync ---locked` resolves, and everything else follows it. The -`ruff-pre-commit` `rev:` must be `v` + that version, the -`requirements/dev.txt` export (what CI installs with `pip install ---require-hashes`) must pin it, and `pyproject.toml`'s bound must be -the one uv recorded resolving against. Adopting a newer ruff is -therefore two edits in one commit: `uv lock --upgrade-package ruff` -plus the `uv export` pair that `make py-relock` runs, then the `rev:`. -The gate names whichever of the three has fallen behind. Before -`select` landed in #1222 this had already drifted silently — `rev: -v0.15.14` against a lockfile resolving 0.15.22 — which is invisible -until the two versions happen to disagree and then reads as "works -locally, red in CI" (#1230). - -The `make py-fmt` / `py-lint` / `py-fmt-check` recipes resolve -`big-code-analysis-py/.venv/bin/ruff` before PATH, the same way -`py-typecheck` resolves mypy and pyright, so the local gate runs the -locked ruff by construction. Three provisioning paths (`mise.toml`, -the `Dockerfile`, and the `pipx install ruff` CONTRIBUTING documents) -install an *unpinned* ruff onto PATH and stay that way on purpose: -each would otherwise be a fifth exact copy of the version, in a file -no gate reads. Run `make py-bootstrap` and the venv wins. - -**Read the outcome from the `BCA_GATE:` line, nothing else.** Both gates -end with exactly one of `BCA_GATE: pass (gate=pre-commit)` or -`BCA_GATE: fail (gate=pre-commit, exit=2, stage=_pc-fmt)` on stdout, and -no other line of either gate's output starts with that token. Do not -infer an outcome from make's `Error N` lines: the gate is a parallel -DAG, so a stage's `make[2]: *** [… _pc-fmt] Error 2` is printed the -instant it fails and is routinely followed by a hundred lines of other -stages' -*successful* output. Capture each run to its own log path — a fixed -`/tmp/pc.log` is shared with every other checkout and agent on the host -— and grep that log rather than trusting a reported exit status, which -in some tooling is the status of the trailing `echo` rather than of -make: +## Commands ```bash -log=$(mktemp /tmp/bca-pre-commit.XXXXXX.log) -make pre-commit >"$log" 2>&1 -grep '^BCA_GATE:' "$log" -``` - -No `BCA_GATE:` line at all is a third state, not a pass: the run -crashed, was killed, or was interrupted. See -[`CONTRIBUTING.md`](CONTRIBUTING.md), "Reading the verdict". - -A `fail` naming several stages with no code in common is usually the -host, not the change. During #1401 a concurrent cargo build on the -same host slowed one run past the Node harness's 15 s `execFileSync` -limit in `_pc-plugin-test` and made twenty `diff_since` fixtures' `git -commit`s time out. Every one passed clean on the quiet re-run; none -was a finding about the tree. The check: does the failing stage's -output name something the diff touched? - -**`_native.pyi` is stubtest-gated (#673).** The hand-written PyO3 stub -`big-code-analysis-py/python/big_code_analysis/_native.pyi` is no -longer "kept in lockstep by hand" on trust alone: `make py-stubtest` -runs `python -m mypy.stubtest big_code_analysis._native -big_code_analysis.vcs` against the freshly `maturin develop`-built -extension, diffing names, signatures, and **defaults** — catching the -`#[pyo3(signature = …)]`-vs-stub drift that the usage-only `make -py-typecheck` (mypy/pyright over call sites) cannot see (#583 shipped -one such drift). The second module argument extends the same gate to -the `vcs` submodule (`rank` / `trend` / `commit` / `score_diff` / the -`Options` constructor) via its `big_code_analysis.vcs` facade and -`vcs.pyi` stub (#854 — the submodule was previously allowlisted out -wholesale, reopening the #583 gap). It is wired into `make -pre-commit` and `make ci` (chained after `py-test`, sharing its -`maturin develop` build) and skips cleanly when the venv / maturin / -stubtest are absent. When you change a PyO3 signature or default -(`src/lib.rs`, `src/batch.rs`, `src/analysis.rs`, the `vcs` module), -update `_native.pyi` **or** `vcs.pyi` to match and re-run `make -py-stubtest`; the only remaining allowlisted entries are genuinely- -deliberate facade differences (the `_native.vcs` submodule *attribute* -— its signatures are checked via the facade run — and runtime -`__all__`), which live in -`big-code-analysis-py/stubtest-allowlist.txt` — keep that list -minimal so it never masks real drift. Note PyO3 exposes a -`#[new]` constructor as `__new__` (not `__init__`) and renders a -computed default like `commit = "HEAD".to_owned()` as `...` -(Ellipsis) in `__text_signature__`, so the stub must mirror those -runtime shapes for the gate to pass. - -**Baseline-refresh discipline.** Any change that moves a *baselined* -metric past its recorded `.bca-baseline.toml` value must refresh the -baseline in the **same PR**. The baseline filter only suppresses a -violation while the live measurement stays at or below the recorded -value; once a file grows past it (e.g., #445 grew what is now -`big-code-analysis-ast/src/count.rs`'s -`halstead.effort` from ~103k to ~191k), the filter no longer covers -the offender and `make self-scan` goes red on a clean checkout — for -everyone, not just the author (#449). The existing `bca-self-scan` -pre-commit hook and the `Threshold gate` step in -`.github/workflows/pages.yml` already catch this, so the safeguard is -purely procedural: do not bypass pre-commit, and refresh the baseline -with `make self-scan-write-baseline-headroom` in the commit that moved -the metric. A red gate on `main` traces directly to skipping this step. - -**The same duty runs the other way**, and nothing can make it red. A -change that *lowers* a baselined metric leaves the recorded value -describing a tree that no longer exists, and the filter keeps -suppressing the offender all the way up to it — headroom nobody chose, -in which a later regression hides. Since #1465 `bca check --baseline` -warns on stderr when a covered offender has measured past its record -(below it, or above it for the lower-is-worse `mi.*` family), naming -the worst entry and the count. Refresh in the same commit, exactly as -for an increase. The warning covers only offenders still above their -limits: one that stopped breaching altogether produces no violation and -so leaves an entry that only a full regeneration finds. That -regeneration is the quarterly `baseline-freshness.yml` job below, which -closes the other half — but it reports a stale file a quarter late and -under someone else's name, so it is a backstop for this duty, not a -substitute for it. - -The same rule governs **merges**. `.bca-baseline.toml` is marked -`-merge` in `.gitattributes`, so git leaves it wholly conflicted rather -than splicing two branches' entries together. That is deliberate: -neither side's recorded values describe the merged tree, so hand -resolution is always wrong here, not merely tedious. Regenerate with -`make self-scan-write-baseline-headroom` and stage the result. - -The same goes for **a change split into several commits**. The refresh -measures the working tree, not a commit, so a baseline regenerated once -and staged into the first of several commits describes the whole tree, -and that commit fails the self-scan on its own (PR #1609). Regenerate -after each commit instead — `git rebase --exec 'make -self-scan-write-baseline-headroom && (git diff --quiet .bca-baseline.toml -|| git commit -q --amend --no-edit .bca-baseline.toml)' ` — so -each refresh lands in the commit that moved the metric. A later commit -that edits the baseline itself then stops the rebase with a conflict, -because the file is `-merge`: regenerate, stage, and `git rebase ---continue`, as for a merge. - -**What a refresh costs, and why.** The scan itself is ~0.2 s for the -whole tree; what you wait for is the build. The self-scan recipes -build `bca` under the **dev** profile (#1773): ~5 s for a step that -touched something compiled into it — Rust under `src/`, -`big-code-analysis-ast/src/`, `big-code-analysis-cli/src/`, a grammar -crate's sources, a manifest or `Cargo.lock` — and ~0.1 s for one that -did not, because cargo finds every artifact fresh. A commit that -touches nothing compiled is in the second class even though it moves -`HEAD`: the `git:` field of `bca --version` is deliberately *not* -refreshed on a bare commit, because refreshing it would cost the -rebuild on every step of the rebase loop this paragraph is about (it -is exact as of the last build whose inputs changed; the `build -inputs:` digest, the field the resolver decides on, is exact always). -Integration tests under a crate's `tests/`, `.snap` files and grammar -`node-types.json` are not inputs either. They used to build -release, whose `lto = true` / `codegen-units = 1` relink is ~100 s -after *any* such edit — which made the nine-conflict rebase that -motivated #1773 a ten-minute job. `BCA_SELF_SCAN_PROFILE=release` -restores that build when you need CI's exact profile; `make -self-scan-profile-parity` is the per-PR check that the two profiles -write a byte-identical baseline, and the reason the default is safe. -`BCA_SELF_SCAN_BINARY=` skips the build and runs a prebuilt -binary, trusted as given: sound for a batch no commit of which touches -those compiled-in roots or `Cargo.toml` (the manifest, `.bcaignore` -and the baseline are read at run time, so any binary sees the live -copies), and wrong without a warning otherwise. CI sets it to the -release binary it has just installed from HEAD. A `bca` on PATH needs -no such care: `utils/self-scan-bca.py` uses it only when the `build -inputs:` digest its `--version` reports equals the digest of the -checkout's compiled-in sources, recomputed each run — which is to say -only when it was built from these exact bytes — and otherwise builds. -That proof is what an mtime cannot give (a binary installed from a -newer `main` reads as fresh in an older worktree), and it costs ~0.2 s. -It also bounds what the route can save: a tree whose inputs match an -installed binary is one cargo already finds fresh in ~0.1 s, so the -PATH route matters for the forensic trail and for CI's one-build -guarantee more than for the clock. `make self-scan-baseline-fresh` -answers the question the quarterly job asks — does the committed file -still describe the tree — in a few seconds locally. - -**Price a candidate limit at both tiers before calling it free.** -Converging a limit onto a cluster of existing values is never free while -a proportional soft tier is active — the soft tier measures *distance to -the limit*, so a limit chosen to sit exactly on a population's value -maximises soft-tier breach by construction, and none of those functions -can ever clear the band because they *are* the limit. The natural -measurement is the misleading one: `bca check --threshold =` -is applied last and absolutely, never scaled, so it has no soft tier to -report. Use `bca check --explain-threshold =`, which -reports both tiers plus how many offenders each already has in the -baseline, and weigh the *new-entry* count. This repo's `nargs 7 → 6` -was approved on a hard-tier zero and would have bought 74 permanent -baseline entries (#1143, #1169); the same trap applies to a -`[thresholds.lang.]` override (#1141). See -[Tightening a limit onto a cluster](big-code-analysis-book/src/recipes/thresholds.md#converging-onto-a-cluster). - -If GNU Make 4 or any of the optional tools (`taplo`, `rumdl`, -`shellcheck`, `shfmt`, `checkmake`, `actionlint`, `cargo-nextest`, -`ruff`, `mypy`, `pyright`, `maturin`) are unavailable, fall back to the -raw cargo commands: - -```bash -cargo fmt --all -- --check -cargo clippy --workspace --all-targets -- -D warnings +make worktree-setup # once per checkout: corpora submodules + Python venv +make pre-commit # the full validation gate; run before declaring work done cargo test --workspace --all-features -RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace --all-features +cargo nextest run --workspace --all-features -E 'test(name)' # one test +cargo run -p big-code-analysis-cli -- # bca ``` -If `pre-commit` is installed, also run `pre-commit run --all-files`. The -project's `.pre-commit-config.yaml` runs clippy, `cargo +nightly udeps`, -and the test suite. - -**The per-language membership comparison** (`make -check-test-lang-gates-compare COMPARE_REF=origin/main`) is the one gate above -that is not in `make pre-commit`, because it needs a base revision to -mean anything. The gates that are in it compare a `cfg` marker against the -derivation; when the two agree and are both wrong, only the previous -revision says so. This scans the tree at `REF` as well and fails on a -test that still exists but stopped being compiled by some -single-language build — the silent direction, since a gate too narrow -just drops the test and every leg stays green. It runs no cargo, so it -costs a couple of seconds; the `lint` CI job runs it per pull request -against the base branch head — `base.sha` rather than `git merge-base`, -since that job checks out shallow (#1478). - -**The ancestor-chain audit** (`make chain-audit`) re-runs the library -tests with `--cfg chain_audit`, which restores the exact -`chain.last() == node.parent()` assertion in `Ancestors::checked`. The -default build keeps only an `O(1)` approximation of it, because the -exact form is `Node::parent`'s `O(depth)` per node and made every -debug-build walk quadratic (#1122). The approximation misses a chain -that is short by exactly one, so run this around any change to a walk's -truncate/push bookkeeping — `src/spaces/compute.rs`, `src/ops.rs`, -`src/suppression.rs`, and in `big-code-analysis-ast`, `comment_rm.rs`, -`Search::act_on_node` (which `find` and `count` walk through) and the -dump walk's `Export::enter` / `Export::finish` in `ast.rs`. It is -not part of `make pre-commit`; the `chain-audit` CI job runs it per PR. -See [Benchmarking](docs/development/benchmarking.md#chain-audit). - -**Mutation testing** runs out-of-band on a quarterly cron via -`.github/workflows/mutation-test.yml` against `src/metrics/`, -`big-code-analysis-ast/src/checker.rs`, -`big-code-analysis-ast/src/getter.rs`, and the per-language -`big-code-analysis-ast/src/checker/`, `getter/` and `roles/` modules -(the last only for the gate functions written directly in a language -module: cargo-mutants never visits a macro token tree, so neither a -`role_table!`'s membership lists nor a gate emitted by -`else_if_*_gate!` or a family fragment is mutated). It is intentionally not part of -the per-PR gate (a full run is hours, sharded across a matrix). Escapes -auto-file a GitHub issue labelled `mutation-testing`; the script that -summarises each shard and aggregates the report, -`utils/mutation-report.py`, is self-tested per PR by `make -mutation-report-test`, and the workflow's own `run:` bodies by `make -mutation-workflow-test`, which executes them under `bash -e` with -stubs. See -[`docs/development/mutation_testing.md`](docs/development/mutation_testing.md) -for local invocation and triage guidance. - -**Benchmarking** is the second out-of-band quarterly gate -(`.github/workflows/benchmark.yml`, `big-code-analysis-bench`). It is -deliberately not per-PR — shared runners cannot produce stable numbers, -and a timing assertion in the unit suite already produced false -failures in four environments. The consequence is that a reintroduced -quadratic walk makes the unit tests *slow* rather than red, so run -`make bench-scaling` around any change to AST traversal, `Checker`, -`Getter`, or a metric's `compute`. See -[`docs/development/benchmarking.md`](docs/development/benchmarking.md). - -**Fuzzing** is the third out-of-band gate (`.github/workflows/fuzz.yml`, -the workspace-excluded `fuzz/` crate). Out-of-band means out of `make -pre-commit`, not out of CI: a pull request touching `src/`, `fuzz/`, a -manifest or a grammar still builds every target and replays the committed -seeds, and the quarterly cron does the actual fuzzing. cargo-fuzz needs -nightly and builds every grammar under ASan, so it lives in its own -workflow — `ci.yml` sets `RUSTFLAGS: "-D warnings"` workflow-wide and -pairing that with nightly red-Xes CI on unrelated new nightly lints. Run -`make fuzz-check` after editing anything under `fuzz/`, since the crate is -workspace-excluded and therefore invisible to `cargo clippy --workspace` -(the #164 / #1228 blind spot). Bound any run with `-runs=N`, never -`-max_total_time`, or the result cannot be reproduced on another machine. -See [`docs/development/fuzzing.md`](docs/development/fuzzing.md). - -**Baseline freshness** is the fourth -(`.github/workflows/baseline-freshness.yml`, #1473). It regenerates -`.bca-baseline.toml` with `make self-scan-write-baseline-headroom` and -diffs the result against the committed file with `bca diff-baseline`, -filing one `self-scan`-labelled issue when the two disagree — and -commenting on that issue rather than opening a second, because a stale -baseline survives every quarter until someone commits a refresh. It -exists for the one thing no gated run can see: an entry whose offender -stopped breaching its threshold produces no violation, so the -`--baseline` stderr warning above never reaches it. Nothing here needs -running by hand; the refresh duty in "Baseline-refresh discipline" is -what keeps the job quiet. See -[`docs/development/baseline_freshness.md`](docs/development/baseline_freshness.md). - -**Advisories** is the fifth -(`.github/workflows/deny-advisories.yml`, #1815): `cargo-deny check -advisories` every Monday against all eight lockfiles `main` tracks — -the root's and the seven `[workspace].exclude` crates', each a graph of -its own — through `utils/check-deny-manifests.sh` (#1823). The `deny` -job in `ci.yml` runs the same script over the same eight, adding bans, -licences and sources, which do not age, on push, pull request and -dispatch, never on a schedule. So between pushes an advisory is seen by -Dependabot or Scorecard or not at all; a RUSTSEC `unsound` / -`unmaintained` entry has no Dependabot path. A red run is the signal -and no issue is filed. The fix is the same as for a red `deny` job: -move the lockfile past the advisory, or add a documented `ignore` to -`deny.toml`, which is keyed by advisory id and so covers all eight -graphs. The root's graph is rooted at every workspace member -(`--workspace`), not at the `big-code-analysis` package alone. A ninth -tracked lockfile fails the script until its `EXPECTED_LOCKFILES` and -the self-test's `CRATE_DIRS` are raised; an excluded crate that tracks -no lockfile fails `utils/check-excluded-manifests.py` instead, since -the script cannot see a graph with nothing to list. - -For snapshot test changes, run `cargo insta test --review` and accept or -reject each snapshot rather than blindly updating files. - -**Bulk snapshot refresh** (grammar bumps, metric computation changes, -Halstead operator reclassification): these cause hundreds of snapshots -to shift in metric values. Use `cargo insta test --accept` per test -file to accept in batch after verifying the diff pattern is -metric-value-only (no structural changes). Run `cargo insta test ---accept` rather than incremental `mv *.snap.new` — accepting snapshots -one at a time can shift `assertion_line` fields, causing a cascade -where previously-matching snapshots become stale. - -Three traps in that loop: - -- **The corpus runner aborts after its first panics**, so a plain run - reports only part of what moved. #1296 showed 16 of 254 files. - Collect with `INSTA_FORCE_PASS=1 cargo test --no-fail-fast` before - counting or reviewing. -- **A forced pass also hides inline snapshots.** An - `assert_json_snapshot!(…, @"…")` that moved passes and leaves only a - `src/**/.*.pending-snap` file, not a `.snap.new`. Review both kinds - (#1552). -- **`cargo insta test --accept` accepts every pending snapshot it finds - in the workspace**, not only the ones its own run produced. That - includes corpus snapshots left by an earlier forced run (#1486). The - per-test-file advice above holds only when nothing else is pending. - Otherwise review everything that is pending, or accept a filtered set - with `cargo insta accept --snapshot `. - -**Anchor every `insta::assert_json_snapshot!` call.** A bare -`insta::assert_json_snapshot!(metric.X)` records whatever production -emitted at acceptance time — including bugs (see issue #95 and lesson 2 -in `docs/development/lessons_learned.md`; the `InvocationExpression` -aliasing miscount fixed by #94 was masked for the entire C# language- -support PR by exactly this pattern). Every new snapshot assertion must -carry one of: - -- An inline expected block: `insta::assert_json_snapshot!(metric.X, @r###"…"###)`. -- A positive `assert_eq!` on the headline value(s) immediately above - the snapshot call, using integer-valued accessors (`branches()`, - `class_npm_sum()`, `unique_operators()`, …) — float magnitude / volume / - difficulty / effort / `*_average` are bit-brittle and not safe for - exact equality. -- A `// expected: ` comment explaining what the values - should be and why, sufficient for a reviewer to verify without - re-deriving from scratch. - -Bulk `cargo insta accept --workspace` is allowed only when every -accepted snapshot is already anchored — a grammar bump that shifts -metric values for anchored tests is fine; first-time acceptance of -bare snapshots is not. Existing bare snapshots predate this rule and -are tracked under #95; new tests must follow it. - -This policy is enforced automatically. `make snapshot-anchors` (run -as part of `make pre-commit` and `make ci`, the -`.pre-commit-config.yaml` hooks, and the `lint` job in -`.github/workflows/ci.yml`) invokes -`./utils/check-snapshot-anchors.py`, which scans every -`insta::assert_json_snapshot!(metric.…)` call under `src/metrics/` -— **subdirectories included since #1192**; before that the glob was -non-recursive and the 126 files under `abc/`, `cognitive/`, -`cyclomatic/`, `loc/`, `npa/` and `npm/` were invisible to it — and -counts the unanchored ones per file. Outstanding counts are checked -in at `.snapshot-anchor-baseline.txt`; CI fails on any *increase*. -A file with no bare calls is **not** listed, and an unlisted file is -allowed zero, so the baseline reads as a list of debt rather than a -census. Decreases are silent and may be locked in with -`./utils/check-snapshot-anchors.py --update`, which regenerates the -baseline from the working tree. - -The gate lexes Rust literals to decide what is live code, and that -lexer is itself gated: `make snapshot-anchors-test` runs -`utils/check-snapshot-anchors-test.py`, which pins both directions of -the char-literal rule (#1192). A `b'"'` read as an unpaired quote -opens a string span that hides every later snapshot call, and a -lifetime (`'a`, `'outer:`) read as a literal swallows the rest of the -file the other way. Both failure modes make the gate report a clean -file — the outcome it exists to prevent — so neither may be left to -inspection. - -**The role-table gates (#1692).** `big-code-analysis-ast/src/roles/` -holds one `role_table!` per language (#1691), and three gates in `make -pre-commit` / `make ci` keep it honest, each reading the declarations -through `utils/role_tables.py` — the one reader, held to the compiled -constants by `python_reader_agrees_with_the_compiled_tables` in -`roles/mod.rs`. `make role-census`: every (language, role) cell is -declared rows, `absent "why"` or `pending Rnn`; the pending set is a -ratchet in `.role-census-baseline.txt`. `make role-coverage`: every -runtime kind id of every generated enum is claimed by some row, -excluded with a reason, or debt in `.role-coverage-baseline.txt`, keyed -by `(language, id)` under the pinned grammar version — never by -spelling, and with no kind category forgiven. A moved pin fails until -`--migrate-pin ` confirms the baselined ids still spell the same -kinds. `.role-coverage-observed.txt` records which kinds the -integration corpus emits — the three repository submodules whole and -the output submodule under `control_flow/` only (#1700) — with -provenance; refresh it with `make -role-coverage-observe` (builds `bca`, walks the corpora) when the -corpus submodules or a grammar pin move, since `--require-observations` -fails on a stale file. `make role-coverage-claimed` prints every -claimed (language, role, kind) with its corpus label, the -"no occurrence in corpus" rows the derived parity test cannot ask -about; `make role-parity-corpus` runs that test's forward comparison -over the three repository corpora, and `make role-corpus-refresh` runs -it with the observation — the recipe for a moved corpus (#1700). `make role-bypass`: inside the consumer boundary -(the per-language dispatch files, their dispatcher modules and -macros), a kind a row claims must not be restated as classification; -`.role-bypass-baseline.txt` is empty since #1701, so a new finding -fails outright, and a site that is not membership — naming, traversal, -a consumer-chosen subset of a row's owners — takes a `// role-bypass: -allow() — ` exemption on the line above, which must name -a role that claims the kind and covers the whole statement or arm -after it (so a kind of the *same* role later added inside that span -is the derived suite's to catch, not the gate's; a kind only another -role claims is still reported). All three baselines are exact record -sets (the bypass one numbers repeated sites within an item): -`--update` only removes, `--bootstrap` refuses a file that exists or is -tracked at `HEAD`, so a swap cannot hide behind an unchanged count. Each -gate prints what it cannot see with every run: none judges whether a -row's membership is right, which role should claim a kind, or whether -a consumer reads the right projection. The full list, with the manual -check that covers each item, is the "What the mechanism cannot see" -section of `big-code-analysis-ast/src/roles/mod.rs`'s module doc — -the one copy; the rules under `.claude/rules/` link to it. - -**`cargo fmt --check` is not the whole formatting gate.** A comment -inside a match *pattern* makes rustfmt emit the enclosing match -verbatim, silently, with `cargo fmt --check` still exiting `0` — so -everything in that match sits outside the gate. `make rustfmt-bail` -(wired into `make lint`, `make pre-commit` and `make ci`) probes for -this directly: it over-indents every match arm, pipes the file through -rustfmt, and counts the arms that come back untouched. Per-file counts -live in `.rustfmt-bail-baseline.txt`; increases fail, decreases are -silent and ratchet with `./utils/check-rustfmt-bail.py --update`. The -fix is always to *hoist* the comment above the arm, never to delete it. -Read [`.claude/rules/formatting.md`](.claude/rules/formatting.md) before -touching a file this gate names — some entries have a second cause -(an unparseable `macro_rules!` body) that no comment move will fix. - -**Integration snapshots live in the `big-code-analysis-output` -submodule** (`tests/repositories/big-code-analysis-output/`). Any -behaviour-changing fix that touches metric computation, AST traversal, -or alterator rules — cognitive, cyclomatic, Halstead, exit, ABC, -etc. — generates `.snap.new` files **inside the submodule**, not the -parent repo. A fix is not done until **all five** of these have -happened in the same change: - -1. `cargo test --workspace --all-features` exits clean from a fresh - working tree (no `.snap.new` left behind under - `tests/repositories/big-code-analysis-output/`). -2. The accepted snapshots are committed and pushed to the submodule's - remote (`dekobon/big-code-analysis-output`, `main` branch). -3. The parent records the new submodule SHA — `git add - tests/repositories/big-code-analysis-output` — in the **same - parent commit** as the metric/alterator fix, never as a follow-up. -4. After any rebase, force-push, or long-running batch fix, re-run - the integration tests before declaring done. The submodule's - history is force-pushed often enough that prior accepts cannot be - assumed to survive — see lesson 8 in - `docs/development/lessons_learned.md`. -5. `make role-coverage-observe` and commit the regenerated - `.role-coverage-observed.txt` in the same parent commit. The - observation samples this submodule (its `control_flow/` directory, - since #1700) and records its whole SHA as provenance, so every bump - of the gitlink — a snapshot-only one included — leaves the file - stale, and `make role-coverage` (`--require-observations`, in - `make pre-commit` and CI) fails until it is refreshed. The scan - builds a release `bca` and walks ~1,900 files; about a minute. - -A behaviour-changing fix without the matching submodule bump leaves -the next fresh clone with either an unfetchable submodule SHA or -stranded `.snap.new` drift that blocks CI on every subsequent change. - -**Support for a claim goes where the claim is.** A zero-drift or parity -claim on an issue or PR rests on fixtures, base and head revisions, -tool versions, the command that produced the number, and the driver -that compared the two sides. Whoever re-checks it is on another -machine, so a path into anyone's home directory is a citation to -nothing. Put the numbers, the revisions, the versions and the exact -command in the comment that makes the claim; put a fixture worth -keeping in the tree as a test fixture; put a driver worth re-running in -`utils/` as a `*-test.py` wired into `make pre-commit`, which is what -lesson 80 asks of any check that otherwise runs on a rare trigger. -Link to those from the comment rather than pasting them into it. What -is left — the regenerable captures — needs no home at all once the -command that regenerates them is recorded. The `~/bca-evidence/` -convention this paragraph used to prescribe produced ten megabytes of -`--list` captures for one issue (#1726) and comments that cited them -by local path; it is retired. The source comments that cited such -paths (#1299, #1401, #1706, #1724) now point at the issue, where the -content they stood for is recorded. - -**Scratch is scratch, wherever it is.** The #1696 oracle lost two -fixture files to a host restart because they lived only in -`/tmp/opencode/`, and they could be rebuilt only because the outputs -had been recorded. The lesson is the rule above, not a better scratch -directory: no temporary location guarantees retention, and the -clean-up policy of `/var/tmp` varies by host. Work in a private -scratch directory — `/tmp/opencode` is this environment's convention -for throwaway work; `mktemp -d` under whatever survives a reboot on -your platform when a run must — and delete it when the work lands. - -Those two paragraphs decide where the *support for a claim* goes. The -files on disk *while the work is in progress* are a separate question -with its own answer: [`.claude/rules/temp-files.md`](.claude/rules/temp-files.md) -sorts them into three tiers — irreplaceable (a test, `utils/`, the -issue, or ask), a regenerable working cache that must outlive a reboot -(`/var/tmp/bca//`, with a `PROVENANCE.md` so it can be rebuilt -and is never what a claim cites), and scratch (`mktemp`, never a fixed -name) — and says how to allocate each. - -## Metric thresholds - -The limits `bca init` scaffolds are defined once, in -`big-code-analysis-cli/src/default_thresholds.rs`. They are derived -from published thresholds plus a 20-language corpus measurement (#1140), -and each carries its rationale inline. `halstead.effort` was re-measured -in #1569 on a rebuilt corpus recorded in -[`docs/development/threshold_corpus.md`](docs/development/threshold_corpus.md). Change them there, not in a -copy: the scaffolded `bca.toml` renders its `[thresholds]` block from -that table, so there is no second copy of the numbers to drift. - -Two copies of the *summary table* do exist — the one below and the one -in the book's recipe — and `doc_summary_tables_match_the_default_table` -pins both, in each direction. Do not add a third: it would be -unguarded, since that test only knows the paths listed in -`DOCS_REPEATING_THE_TABLE`. - -| Metric | Default | Scope | -|--------|---------|-------| -| `cognitive` | 15 | function | -| `cyclomatic` | 15 | function | -| `abc` | 40 | function | -| `nargs` | 5 | function | -| `nexits` | 5 | function | -| `halstead.effort` | 50000 | function | -| `loc.ploc` | 600 | file | -| `loc.sloc` | 1200 | file | -| `nom` | 30 | container | -| `wmc` | 60 | container | - -Three things to know before quoting a number at anyone: - -- **These are language-agnostic defaults, and no language is - agnostic.** Measured 97.5th-percentile `cognitive` runs from 4 (C#) - to 50 (C). C, Tcl, Bash, Lua, Perl, and Go want roughly double the - `cognitive` default; Java, Ruby, Kotlin, C#, and Elixir sit far - under it. The per-language table lives in - [Choosing thresholds](big-code-analysis-book/src/recipes/thresholds.md). -- **The right limit depends on the job.** A blocking CI gate, an agent - edit loop, a legacy triage pass, and a safety-critical build want - four different tables. That page has one profile for each. -- **This repository's own `bca.toml` deliberately differs from the - shipped defaults.** It is a Rust-specific calibration with - `exclude_tests = true` and a comment-dense house style. `cognitive`, - `nargs`, and `abc` have since converged onto the shipped defaults - (#1143, #1183); `loc.ploc` and `loc.sloc` still differ. Do not "fix" - one file to match the other; they answer different questions. One - `[[thresholds.path]]` entry there gates - `src/metrics/{abc,cognitive,cyclomatic,loc}/*.rs` at `cyclomatic 40` - / `halstead.effort 150000` (#1738): a per-language dispatcher in - those files needs no `suppress` marker, and a reader who finds one at - cyclomatic 19 with no marker is looking at a function gated at 40, - not an oversight — if it trips, the table has outgrown its - population. The entry's comment in `bca.toml` carries the trade-off: - every helper in those files shares the raised limit. +`make pre-commit` ends with exactly one `BCA_GATE: pass …` or +`BCA_GATE: fail …` line on stdout. Capture the run to a `mktemp` log and +read that line; make's `Error N` lines are not the verdict, and no +`BCA_GATE:` line at all means the run did not finish. See +[`CONTRIBUTING.md`](CONTRIBUTING.md) for the stage list, the reading of +the verdict, and the raw cargo fallback when `make` is unavailable. +Report any stage that was skipped or unavailable. + +Checks that are **not** in `make pre-commit` and have their own +triggers: `make bench-scaling` after changing AST traversal, a `Checker` +/ `Getter`, or a metric's `compute`; `make chain-audit` after changing +walk truncate/push bookkeeping; `make fuzz-check` after editing `fuzz/`; +`make check-test-lang-gates-compare COMPARE_REF=origin/main` after +changing a test's `#[cfg(feature)]` gate. Each is described in the +document the routing table names. + +## Conventions the code cannot tell you + +- **Stable API.** `lib.rs` re-exports, public traits and public types + follow [`STABILITY.md`](STABILITY.md). Enumerate every call site + before changing a public signature. Record user-visible changes under + `## [Unreleased]` in `CHANGELOG.md`; mark a source-level break + **(breaking)** and defer it to the next major. +- **No `unsafe`**, except the documented PyO3 lifetime erasure in + `big-code-analysis-py/src/node.rs`. No `unwrap` / `expect` / `panic!` + / `assert!` outside tests; propagate with `?`. `expect("invariant")` + is allowed only for a provably unreachable case, with the invariant + in the message. +- **Per-language modules mirror each other.** A bug in one + `big-code-analysis-ast/src/{languages,checker,getter,roles}/` sibling or + `src/metrics//.rs` usually exists in several. Dump the + construct in each sibling grammar and fix them together; add a test + per affected language. +- **Regression tests for every bug fix**, and prove a test can fail + (see the testing guide). Never rewrite a test file to add one test. +- **Snapshots.** Every new `insta::assert_json_snapshot!` is anchored + with an inline expected block, an `assert_eq!` on an integer headline + value, or an `// expected:` derivation. Review snapshot diffs with + `cargo insta test --review`; accept in bulk only for already-anchored + snapshots after confirming the diff is value-only. +- **Behaviour-changing metric fixes** also move snapshots in the + `tests/repositories/big-code-analysis-output` submodule. The same + change must accept them, record the new gitlink, and refresh + `.role-coverage-observed.txt` (`make role-coverage-observe`). Pushing + the submodule is publication and needs explicit instruction. +- **Baseline refresh runs both ways.** A change that moves a metric + past, or below, its `.bca-baseline.toml` record refreshes it in the + same commit: `make self-scan-write-baseline-headroom`. Never + hand-resolve a baseline conflict; regenerate. +- **Paths as identifiers** (map keys, JSON output, error correlation) + go through `to_str()` with an error, never `to_string_lossy()`; + `display()` is for log output only. Wrap domain identifiers in + newtypes rather than passing two same-typed primitives. Prefer + `pub(crate)`, and borrowing over cloning. +- **Diagnostics** go through the lowercase helpers in `src/diag.rs` + (`warn`) and `big-code-analysis-cli/src/diag.rs` (`warn` / `die` / + `note`); never spell `warning:` / `error:` in a literal. +- **clap help text** carries no issue references; after any help/about + edit run `cargo xtask` and commit the regenerated `man/` pages. +- **Grammar pins.** Grammar crates and the `tree-sitter` runtime are + pinned `=X.Y.Z` in the root manifest and each workspace-excluded + crate's own (`tree-sitter-language`, the trait shim, stays + caret-ranged; members inherit via `workspace = true`). A bump is a + separate, deliberate change. +- **Comments:** none by default; add one only when the *why* is + non-obvious. Never put an issue number in a `///` on a clap type: it + ships in `--help` and `man/` (`help_text_carries_no_issue_references` + pins this). +- **Docs:** prose follows `docs/conventions/documentation.md`; keep + `README.ja.md` in step with `README.md`; pin `{#anchor}` ids on + headings you fragment-link to. + +## Working rules + +- **Worktrees.** Work only in the worktree you were given. Never remove + or prune a worktree you did not create, `cd` into another checkout, + or write outside your worktree except to the scratch locations below. +- **Publication needs explicit instruction**: `git push`, + `gh pr create`, pushing a submodule. Issue-tracker activity + (`gh issue …`) is ordinary work and needs no separate approval. +- **Delegation.** Do the work yourself unless it is independent and + larger than a handful of tool calls; a fresh-context reviewer is + worth spawning, re-checking your own output is not. Child agents do + not see this conversation: restate what they need. Fan-out follows + [`docs/development/agent_isolation.md`](docs/development/agent_isolation.md). +- **Shell.** Build argument lists as arrays and expand them + `"${ARR[@]}"`; an unquoted `$VAR` is not split in every shell. After + a pipeline, `$?` is the last stage's status. `bca check` writes its + offender rows to stderr, so `2>/dev/null` reads as clean. Before + trusting a table + a measurement loop produced, hand-run one case in full and compare; + a tidy column of zeros is the shape every shell mistake makes. Do not + poll for work the harness tracks; a wait loop you must write is + bounded and keys on an artefact, not on `pgrep` of its own command + line. +- **Tool output.** A truncated preview is not the result; read the + persisted file or aggregate in the command (`wc -l`, `rg -c`, + `sort -rn | head`). "There are no other X" needs the full output. +- **History rewrites.** Before a scripted rebase, `git branch + backup/ HEAD`; afterwards compare trees against it, not test + results. Build todo lists from the current `git log` only. +- **Temporary files.** Scratch goes under `$TMPDIR` or `/tmp/opencode` + via `mktemp "${TMPDIR:-/tmp}/bca-.XXXXXX"`, never a fixed + name. Expensive, regenerable artefacts needed across sessions go in a + `mktemp -d` run directory under `/var/tmp/bca//`, each with a + `PROVENANCE.md` naming the commit and the command that rebuilds it; + first check `[ -O /var/tmp/bca ] && [ ! -L /var/tmp/bca ]` and stop + if it fails. Anything irreplaceable becomes a test, a `utils/` + script, or an issue attachment; ask when none fits, and never delete + the only copy meanwhile. +- **Evidence for a claim** (parity, zero drift, a measurement) goes in + the issue or PR comment: revisions, versions, the exact command, the + numbers. A path on one machine is not a citation. +- **Issues and commits** follow Conventional Commits. Write non-trivial + `gh` bodies to a `mktemp` file and pass `--body-file`; put a long + record in a gist and link it (the host proxy has rejected multi-KB + comments), and re-read the issue to confirm a comment landed. Update + the body *and* add a comment; close only when every item is resolved. + Re-verify a deferred issue's premises against the current tree before + building on them. +- **Tools.** `rg` and `fd`, not `grep` and `find`. Context7 or + `cargo doc` before web search for library documentation. Any edit + under `.github/workflows/` runs `make actionlint`; composite actions + under `.github/actions/` are not auto-discovered and must be passed + explicitly. +- **Metric feedback from `bca`** (the post-edit hook, `make self-scan`) + follows the policy below. Markers: `// bca: suppress() -- + `; canonical names only (`nexits`, never `exit`). + +## Before you start, read + +| Task | Read first | +| --- | --- | +| Changing a metric, `Checker`, `Getter`, `Alterator`, a role table, or anything under `big-code-analysis-ast/src/` | [`docs/development/grammar_dispatch.md`](docs/development/grammar_dispatch.md) and the module doc of `big-code-analysis-ast/src/roles/mod.rs` | +| Adding or changing tests, perturbation sweeps, feature gates | [`docs/development/testing.md`](docs/development/testing.md) | +| A file `make rustfmt-bail` names, or consolidating code into a `macro_rules!` | [`docs/development/formatting.md`](docs/development/formatting.md) | +| AST traversal, `Checker` / `Getter`, or a metric's `compute` | [`docs/development/benchmarking.md`](docs/development/benchmarking.md) | +| `fuzz/` | [`docs/development/fuzzing.md`](docs/development/fuzzing.md) | +| Thresholds, `bca.toml`, `.bca-baseline.toml` | `CONTRIBUTING.md` "Metric baseline", [`docs/development/baseline_freshness.md`](docs/development/baseline_freshness.md), the book's `recipes/thresholds.md` | +| Any Rust change | `CONTRIBUTING.md` "Project conventions" | +| Python bindings, `uv.lock`, ruff | `CONTRIBUTING.md` "Python bindings" | +| Fanning work out to child agents | [`docs/development/agent_isolation.md`](docs/development/agent_isolation.md) | +| Adding a language or bumping a grammar | the `add-lang` skill; `big-code-analysis-book/src/developers/` | +| Writing or revising prose docs | the `doc-author` skill; `docs/conventions/documentation.md` | ## Responding to bca metric feedback -This repo dogfoods its own analyzer: a `bca check` threshold violation -may surface mid-edit (via the Claude Code `PostToolUse` hook in -`.claude/hooks/bca-check.mjs`, enabled by `.claude/settings.json`, or -the OpenCode plugin `.opencode/plugins/bca-check.js`, loaded by -discovery) or at the task boundary (`make self-scan`, `make -pre-commit`). The hook runs `$BCA` if set; otherwise the candidate — -`target/debug/bca`, `target/release/bca`, then PATH `bca` — whose -`build inputs:` digest matches the tree, the same test -`utils/self-scan-bca.py` applies, so it agrees with `make self-scan`; -with no match it takes the newest local build, then PATH `bca`, and -names its choice and why in the `[bca-check]` health line (#1776). - -The policy below is the book's "Agent guidance (ship this verbatim)" -block, kept identical by `make plugin-test`; the list after it is -this repository's own addition. - **Responding to `bca` metric feedback.** A threshold violation is a reason to review readability, not proof of a defect. Improve the code where that helps the current task; lowering a score is not itself a goal. @@ -1036,144 +196,12 @@ where that helps the current task; lowering a score is not itself a goal. current change. Findings may concern other functions or the whole file; mention unrelated findings without expanding the edit. -Repository-specific additions: - -- **Marker syntax.** Per-file: `// bca: suppress-file() — `. - Anything after the metric list is free text; no separator is - required. **Name the metrics** if you want to write a reason: a - *bare* verb (`// bca: suppress`, no list) takes no trailing text at - all, because nothing distinguishes a rationale from prose *about* the - marker — put the reason on the line above if the `All` scope is - really what you want. Use canonical metric names — it is `nexits`, - **never** `exit`; an unknown identifier warns and is skipped, while - the recognised names in the same marker still suppress. `tokens` is - not suppressible. See - [Suppression markers](big-code-analysis-book/src/commands/suppression.md) - and the full recipe at - [`recipes/agent-feedback.md`](big-code-analysis-book/src/recipes/agent-feedback.md). -- **Attribute the score before sizing the fix, then size against every - gated metric.** Re-derive the genuine decision count by hand and - compare it to the measurement: part of the headline may be a metric - artifact that adds a CFG edge without adding anything a reader must - reason about. Rust's `?` is the canonical one — it feeds cyclomatic - *and* nexits, and only ~12 of `dump_tree_helper`'s "cyclomatic 32" - was real branching (#401). Large string literals do the same to - halstead, inline tests to file-level `sloc`. Where the gap is an - artifact, say so and justify the refactor on what actually improves. - Then size each new helper against **all** the metrics it could trip — - cyclomatic, nexits, nargs, abc, halstead.effort — because one - construct moves several gauges: #401's proposed split passed - cyclomatic and would have breached nexits. Read the live `bca.toml` - for the limits; an issue's quoted threshold table is routinely wrong. - -The per-edit hook is an early-warning convenience; the task-boundary -gate (`make self-scan` / `make pre-commit`) is the real check before -declaring work done. Thresholds are proxies, not correctness gates — -weigh them, do not drive them to zero at any cost. - -## Tree-sitter grammars - -External grammar crates are version-pinned (`=0.23.5`, `=0.25.1`, -etc.) in the root `Cargo.toml` **and in each workspace-excluded crate's -own manifest** (the five vendored grammars plus `enums`) — -`utils/check-excluded-manifests.py` enforces both (alongside the -`[lints]`-table rule under "Rust conventions"), so neither a root pin -nor a new vendored grammar can reintroduce a caret range (#1151). -Member crates take their grammars through `workspace = true` and carry -no requirement of their own. The gate reads manifests with `tomllib`, -so a literal string (`tree-sitter-cpp = '0.23.4'`) is checked like any -other, and it matches `tree-sitter` anywhere in a dependency name — -`dekobon-tree-sitter-groovy` and any future `bca-tree-sitter-*` are in -scope. A pin means exactly `=X.Y.Z` (whitespace after `=` is fine); a -compound requirement such as `=0.25.0, <0.26` is rejected, because the -`.grammar-marker-baseline.toml` entry that `check-grammar-marker-sync.py` -compares against can name only one version. - -One deliberate exception: `tree-sitter-language`, the ecosystem's shared -`LanguageFn` trait shim, is **not** a grammar and must stay caret-ranged. -`=`-pinning it makes the workspace unresolvable (`tree-sitter-irules -0.2.0` requires `^0.1.7`, and cargo unifies 0.1.x deps) and would break -downstream consumers of the published `bca-tree-sitter-*` crates. The -gate carries it in `PIN_EXEMPT_DEPS`. - -The `tree-sitter` runtime is **not** exempt, though the "not a grammar" -half of that rationale fits it too. The exemption is about unification -pressure and the runtime has none — the lockfile shows 25 crates -depending on `tree-sitter-language` against one external dependent -(`tree-sitter-perl`) for `tree-sitter` — and every manifest here already -pins it at `=0.26.13` with the workspace resolving. Its ABI version is -also what each vendored `parser.c` was generated against, so an -accidental bump is precisely the drift the gate exists to catch. - -A runtime bump also has to carry the `unsafe` soundness argument with -it. `big-code-analysis-py/src/node.rs` reasons about a *named* -tree-sitter release — `Tree(NonNull)`, -`Node<'tree>(ffi::TSNode, PhantomData<&'tree ()>)`, -`Tree::edit(&mut self)`, `Send + Sync` — and `make -check-safety-doc-pin` fails until the literal in that doc matches the -new pin. Re-read the argument against the new release before editing -the line; the forced diff is the prompt, not the fix (#1057). - -Treat the pinned version as fixed: - -- Do not loosen pins to a range without explicit user approval. -- Bumping a grammar version is a deliberate, separate change — usually - driven by `recreate-grammars.sh` or `generate-grammars/`. Snapshot tests - will move; review every diff. -- If a bug is in the grammar (wrong node type, wrong field name) rather - than in our wrapper, document it as upstream-grammar and either - workaround locally or coordinate the upstream fix; do not paper over it - silently. - -## GitHub workflow - -- Issue and commit messages follow Conventional Commits - (`feat(scope): …`, `fix(scope): …`, `refactor(scope): …`). -- For non-trivial `gh issue` / `gh pr` bodies, write to a `mktemp` - file and pass it via `--body-file` to avoid quoting issues. A fixed - `/tmp/issue-body.md` is shared by every agent on the host (see - [`.claude/rules/temp-files.md`](.claude/rules/temp-files.md)): - - ```bash - body=$(mktemp "${TMPDIR:-/tmp}/bca-issue-body.XXXXXX.md") - cat > "$body" <<'EOF' - Content with $variables, `backticks`, and "quotes" - EOF - gh issue create --title "Title" --label "bug" --body-file "$body" - ``` - - **Long bodies.** The host's outbound proxy has rejected some comments - of a few kilobytes that carried tables, with `gh` reporting a failure - and nothing posted (#1399, #1646 — each records the rejected comment - and the gist that took the same bytes). Put a long record in a gist - (`gh gist create`) and link it from a short comment, and re-read the - issue to confirm the comment landed before relying on it. - -- **Re-verify a deferred issue's premises before building on them.** - A deferral records the code as it stood when the issue was filed, - and both halves age: the measurement it rests on may never have - been taken, and a later change may have decided its central design - question the other way. Neither shows up as a contradiction — the - issue and its resolution plan still read as coherent. Check each - cited path, and check whether anything shipped since already - answers the question. #1158 proposed an output-ordering contract - that #1303 had shipped the opposite of, complete with tests, and - its own go/no-go measurement had never been run; when run, it - closed the issue. This is the issue-tracker form of lesson #84. -- Do not push (`git push`, `git push --force`) or open pull - requests (`gh pr create`) without explicit user instruction. - This rule covers **publishing code** only — it does **not** - extend to issue tracker activity. Updating, commenting on, - labelling, creating, and closing issues (`gh issue comment`, - `gh issue close`, `gh issue edit`, `gh issue create`, - `gh issue reopen`) are part of the normal fix-issue workflow - and require no separate authorization beyond the user's - initial request to work on the issue. Treat the issue tracker - as a working surface, not a publish gate. -- Only close an issue when ALL items are resolved. -- When updating issues, update BOTH the body AND add a comment. +Attribute a score before sizing a fix: Rust's `?` feeds cyclomatic and +nexits, string literals feed halstead, inline tests feed file `sloc`. +Size any new helper against every gated metric, reading the live +`bca.toml` for the limits. ## Tone -Criticism is welcome — point out mistakes, suggest better approaches, +Criticism is welcome: point out mistakes, suggest better approaches, cite relevant standards. Be skeptical and concise. diff --git a/CHANGELOG.md b/CHANGELOG.md index 6532a4f82..2a4508b24 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -24,6 +24,16 @@ for historical reference. ## [Unreleased] +### Removed + +- **The `bca-check.sh` compatibility hook wrapper and the book's + "OpenCode V1 (legacy)" recipe.** The agent-feedback recipe now + documents the Node hook for Claude Code and the V2 plugin for + OpenCode only; adopters of the shell wrapper register + `.claude/hooks/bca-check.mjs` directly, as the recipe shows. The + Claude hook matcher covers `Edit|Write`; `MultiEdit` is no longer a + tool in current Claude Code. + ### Changed - **The HTML report's column headers are native sort buttons.** Each @@ -70,52 +80,6 @@ for historical reference. ### Fixed -- **A Kotlin or C# primary constructor opens a function space, so its - parameters count** (#1828). `data class D(val a: Int, …, val f: Int)`, - C# 12's `class C(int a, …, int f) { }` and a positional - `record R(int A, int B);` reported `nargs` 0 on every space, so - `bca check --threshold nargs=5` passed a six-parameter constructor. - Each now opens a `Function` space named after its class and spanning - the parameter list — Kotlin's `primary_constructor` node; C#'s - `parameter_list` where its parent is a class, struct or record - declaration, the one place a list is not a callable's `parameters` - field — and that space owns the parameters: the offender row reads - `D::D: nargs = 6`, in `bca check`, `bca report` and the Python - `to_sarif` binding alike. The constructor also counts as one callable - in `nom`, `npm` and `wmc` (a Kotlin `private` / `internal` / - `protected constructor`, a `sealed` class's and an `enum class`'s are - non-public; a C# primary constructor is public by the language), and - a lambda spelled as a parameter default adds to the constructor's - `closure_args` as a function's spaceless lambdas add to its own. The - superclass call in the header (`: Base(x)`) stays the class's ABC - branch, as #1456 decided — it is a sibling of the list, not inside it. - A written `class G()` is a zero-parameter constructor and counts; - `class N` declares none. A Java or Groovy `record` with no compact - constructor still reads 0 under #1160's decision; the book's - `nargs` zero list now names it, and #1842 holds the question. C#'s byte-less `is_func_space` / - `get_space_kind` keep their pre-#1828 answer for a parameter list — - the parent gate needs the chain — pinned by - `csharp_byte_less_spellings_omit_the_primary_constructor`. - Integration snapshots gain a function space under every Kotlin or C# - type with a primary constructor. Two consequences to know: a - zero-parameter `class G()` is a function row with no code, so its - `mi.*` read the `0.0` sentinel `bca check` and `bca report` already - skip (#1621); and a C# class spelling both a primary and a classic - constructor on one line carries two `H::H` rows at one `start_line`, - which `--baseline` cannot tell apart — the same tie two same-line - overloads already produce. - -- **C# `nargs` counts a `params` array as one parameter** (found under - #1828). tree-sitter-c-sharp spells `params int[] xs` through a hidden - rule whose pieces — the `params` token, the type, the name and any - attribute list — land directly in the `parameter_list`, where an - ordinary parameter is one `parameter` node. The shared negative - filter counted each piece, so `void F(params int[] xs)` read 3 and - `void F([A] params int[] xs)` 4. C# now counts positively: one per - `parameter`, one per `params`. Every C# callable shape moves the same - way — methods, constructors, lambdas, anonymous methods and an - indexer's bracketed list — and two corpus snapshots drop by two. - - **`make release-check` audits all eight lockfiles** (#1826). It ran one `cargo deny check` from the repository root, so the pre-tag gate never read the seven `[workspace].exclude` crates' lockfiles — the diff --git a/CLAUDE.md b/CLAUDE.md deleted file mode 100644 index 793785bc0..000000000 --- a/CLAUDE.md +++ /dev/null @@ -1,161 +0,0 @@ -# CLAUDE.md - -## Shared Project Instructions - -@AGENTS.md - -## Claude Code-Specific Configuration - -### Worktree safety (ABSOLUTE PRIORITY) - -If you are running inside a worktree (check: -`git rev-parse --show-toplevel` returns a path under -`.claude/worktrees/`), the following are hard bans — violating them -destroys other agents' in-progress work: - -- Never run `git worktree remove`, `git worktree prune`, or `rm -rf` - on any worktree directory. -- Never `cd` to the main repository, check out `main` (this repo's - default branch), or write files outside your worktree. -- Never use `/clean_gone` or any command that removes worktrees. -- The only entity that may remove a worktree is the Claude Code - runtime that created it (automatic cleanup on session end). -- If you see stale worktrees, leave them alone — another agent may - be using them, or the user will clean them up manually. - -**Run `make worktree-setup` once per worktree before `make -pre-commit`.** A fresh worktree inherits neither the integration -corpora nor a Python venv, and neither absence names itself: - -- Without the corpora under `tests/repositories/`, the corpus tests - under `tests/corpus/` fail, as do the CLI tests that analyse a real - source file from the `DeepSpeech` corpus. Since #1171 each names the - cause and the remedy; before it they read as bugs in whatever you - were changing. -- Without `big-code-analysis-py/.venv`, `py-typecheck` reports mypy - errors from an untyped `pytest` (its stubs live in the venv) and - `py-test` dies with "Couldn't find a virtualenv". - -Both are bootstrap artifacts, not regressions. The cargo stages -themselves work in a worktree — that was #1145, fixed by the -`[workspace]` tables on the workspace-excluded crates (`enums`, `fuzz` -and the five vendored `tree-sitter-*` grammars). - -`make worktree-setup` is idempotent and a ~100 ms no-op once the tree -is set up, so re-running it is the cheapest way to rule the -environment out. Run it again in particular if a corpus checkout was -interrupted: that leaves the submodule with its files deleted but its -HEAD already at the recorded SHA, so **a plain `git submodule update ---init` is a silent no-op** and only `--force` repairs it. -`worktree-setup` detects that state and escalates on its own; by hand -it is `git submodule update --init --force -- `. It refuses to -force a submodule that also has local modifications — accepted `.snap` -files in `big-code-analysis-output` are exactly what that protects — -and prints the command for you to run once they are safe. - -### Tool choice - -- **Text search**: built-in `Grep`, or `rg` via Bash. Never `grep`. -- **File search**: built-in `Glob`, or `fd` (or `fdfind` on - Debian/Ubuntu) via Bash. Never `find`. -- **Code intelligence**: when an LSP-based tool such as Serena is - available, use it as the default for read / search / edit / - refactor. -- **External docs**: prefer Context7 / `cargo doc` over web search - for library / crate documentation. - -### Editing - -- For code files: prefer Serena symbol-level editing - (`replace_symbol_body`, `insert_before/after_symbol`) over - line-based `Edit` tool calls when available. -- For non-code files: use targeted `Edit` tool calls with scoped - `old_string` / `new_string` pairs. - -### Communication during a task - -- Say in one sentence what you are about to do before the first tool - call. After that, speak up when you find something that changes the - plan or the conclusion — not once per file read. -- Lead the closing message with the outcome: what happened, what - broke, or what you found. Supporting detail goes underneath it, for - the reader who wants it. -- Keep answers short and caveats shorter. When asked to explain a - design decision or a metric, give the high-level answer and expand - only if asked. - -### Length of written deliverables - -Documents produced here — audit and triage reports, GitHub issue -bodies, changelog entries, lessons-learned drafts, book pages — should -be as long as their substance requires and no longer. No filler -sections, no summary that restates the section above it, no -boilerplate heading carrying nothing. A skill's report template is a -maximum shape, not a quota: drop a section with no findings rather -than padding it. `doc-author` and -[`docs/conventions/documentation.md`](docs/conventions/documentation.md) -own the prose rules; this length rule applies to every other written -artifact too. - -### Delegating to subagents - -Skills that fan work out set their own agent counts — follow them. -Outside those, the default is to do the work yourself: - -- Delegate only for work that is genuinely independent and larger than - a handful of tool calls: a wide multi-file investigation, one fix - per crate. Reading three files and editing one is not worth an - agent. -- One agent that can carry the whole task beats three that split it. -- Do not spawn an agent to check work you just did. The independent - reviewers in `simplify-rust`, `review`, and `doc-author` exist - because a fresh context catches what an authoring context cannot; - that is a different thing from re-verifying your own output, which - costs tokens and finds nothing. -- Keep concurrent `isolation: "worktree"` agents to six or fewer. - Each clones the workspace, and this workspace has twelve crate - manifests, so unbounded fan-out has filled the disk with scratch - clones. Queue the remainder and start each as a slot frees. The - fan-out skills encode this same six: `batch-fix` caps wave size, - `improve-crate` and `cleanup-crate` cap concurrent area agents. -- Match the model to the stage. The Agent tool takes `model`, so a - mechanical pass (collecting a diff, running a lint, filling in a - template) can run on a smaller one while analysis keeps the default. - There is no reasoning-effort knob on the Agent tool — only - `Workflow`'s `agent()` accepts one, and no skill here uses - `Workflow`. - -### Skills available under `.claude/skills/` - -| Skill | Use when… | -|-------|-----------| -| `add-lang` | Adding a new tree-sitter language end-to-end (grammar crate, enum, Checker/Getter/Alterator, metrics, tests, docs) | -| `batch-fix` | Fixing several GitHub issues at once on an integration branch (parallel worktrees per crate) | -| `simplify-rust` | Reviewing a diff for reuse / clarity / efficiency, applying fixes inline | -| `rust-optimize` | Reducing verbosity / modernizing Rust syntax with pedantic-clippy triage | -| `review` | Read-only review of a diff, branch, PR, or commit range | -| `audit-tests` | Finding tests that pass for the wrong reason | -| `audit-crate` | Read-only crate-level audit that files GitHub issues for findings | -| `audit-file` | Read-only single-file audit that files GitHub issues for findings | -| `audit-naming` | Read-only crate-level audit of naming quality | -| `scan-project` | Scanning the core library + CLI + web crates for logic errors, security issues, and metrics calculation bugs (6 parallel agents, 50-question checklist) | -| `cleanup-crate` | Removing dead code, unused imports, and unreachable paths from one crate | -| `improve-crate` | Safe code-improvement workflow for one crate (clarity / reuse / efficiency) | -| `issue-plan` | Reading an issue, building a sequential-thinking plan, rating it, applying `low-priority` | -| `issue-triage` | Producing a read-only triage report (quick wins + groupings) over open issues | -| `fix-issue` | End-to-end workflow for fixing a GitHub issue | -| `lessons-learned` | Drafting entries for `docs/development/lessons_learned.md` | -| `doc-author` | Writing / revising / de-slopping a prose doc against `docs/conventions/documentation.md` | - -The `audit-crate`, `audit-file`, `audit-naming`, `scan-project`, `issue-triage`, and -`review` skills are read-only and must not modify the working tree; all -other skills may edit code as part of their workflow. - -### Hooks - -`.claude/settings.json` registers the Node-based `.claude/hooks/bca-check.mjs` -after Edit, Write and MultiEdit. It returns advisory context with exit 0; -analyzer failures stay out of model context and appear in the debug log. -Remove any duplicate local `bca-check.sh` registration when using this default. -See [`recipes/agent-feedback.md`](big-code-analysis-book/src/recipes/agent-feedback.md#claude-code) -for dependencies, configuration discovery and verification. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index 2e5feb537..7f924c8d6 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -2,8 +2,9 @@ Thanks for considering a contribution. This document covers what a contributor needs to set up a checkout, run the validation gate, and -open a pull request. The deeper conventions live in -[`AGENTS.md`](AGENTS.md), [`CLAUDE.md`](CLAUDE.md), and the +open a pull request. The conventions coding agents and contributors +share live in [`AGENTS.md`](AGENTS.md); the per-topic guides it routes +to are under [`docs/development/`](docs/development/) and the [developer guide under `big-code-analysis-book/`](big-code-analysis-book/src/developers/). ## Ground rules @@ -91,9 +92,11 @@ user-level `~/.cargo/config.toml` instead. ## Local validation gate `make pre-commit` is the canonical entry point for the full validation -gate. In one parallel pass it runs, among other stages: +gate. In one parallel pass it runs: -- `cargo fmt --check` ([rustfmt](https://github.com/rust-lang/rustfmt)). +- `cargo fmt --check` ([rustfmt](https://github.com/rust-lang/rustfmt)) + over the workspace and, by manifest path, the excluded `enums/` and + `fuzz/` crates. - `cargo clippy --workspace --all-targets -- -D warnings` ([Clippy](https://doc.rust-lang.org/clippy/)) in both default-features and `--all-features` flavours. @@ -110,18 +113,58 @@ gate. In one parallel pass it runs, among other stages: [`shellcheck`](https://www.shellcheck.net/), [`shfmt`](https://github.com/mvdan/sh), [`checkmake`](https://github.com/checkmake/checkmake), - [`actionlint`](https://github.com/rhysd/actionlint)). -- The man-page drift gate and the `bca` self-scan threshold gates. + [`actionlint`](https://github.com/rhysd/actionlint)). Any edit + under `.github/workflows/` must pass `make actionlint`; suppress a + shellcheck false positive with a scoped `# shellcheck disable=` + directive, not by loosening the configuration. +- The man-page drift gate (`cargo xtask` plus + `utils/check-manpage-drift.py`, which also catches newly added + pages). +- The `bca` self-scan threshold gates at both tiers: `make self-scan` + (the CI limits) and `make self-scan-headroom` (every limit scaled by + `BCA_HEADROOM`, default `0.95`). - `./utils/check-snapshot-anchors.py` (see "Snapshot anchors" below). -- The Python lint / type-check / test stages (see below), skipped - per stage when a tool is absent. - -The authoritative stage list lives in the "Validation gates" section -of [`AGENTS.md`](AGENTS.md). +- `make rustfmt-bail` (see + [`docs/development/formatting.md`](docs/development/formatting.md)). +- The role-table gates `make role-census`, `make role-coverage` and + `make role-bypass`, whose baselines are exact record sets that + `--update` can only shrink; the module doc of + `big-code-analysis-ast/src/roles/mod.rs` describes what each cannot + see. +- `make check-test-lang-gates` (every test carries the `#[cfg(feature)]` + gate of the grammars it names; see + [`docs/development/testing.md`](docs/development/testing.md)). +- The diagnostic-prefix, safety-doc-pin, grammar-build-watch, + excluded-manifests, ruff-lockstep, rumdl-lockstep and + publish-metadata gates, each a `utils/check-*.py` with a `*-test.py` + self-test that runs beside it. +- The Python lint / type-check / test / stubtest stages (see below), + skipped per stage when a tool is absent. `make ci` runs the same checks without auto-fix, mirroring the GitHub Actions behaviour. +Checks that run out of band, each with its own trigger: + +- `make check-test-lang-gates-compare COMPARE_REF=origin/main` after + changing a test's feature gate; it needs a base revision. +- `make chain-audit` after changing a walk's truncate/push + bookkeeping (`src/spaces/compute.rs`, `src/ops.rs`, + `src/suppression.rs`, `comment_rm.rs`, `Search::act_on_node`, the + dump walk in `ast.rs`); see + [Benchmarking](docs/development/benchmarking.md#chain-audit). +- `make bench-scaling` after changing AST traversal, a `Checker`, + `Getter` or a metric's `compute`: a reintroduced quadratic walk makes + the unit tests slow rather than red. See + [Benchmarking](docs/development/benchmarking.md). +- `make fuzz-check` after editing `fuzz/`, which `cargo clippy + --workspace` cannot see. See [Fuzzing](docs/development/fuzzing.md). +- `utils/check-deny-manifests.sh` (cargo-deny over every tracked + lockfile) runs in CI and `make release-check`; it needs the network. +- Mutation testing, benchmarking, fuzzing, baseline freshness and the + advisory audit run on quarterly or weekly schedules; see + [`docs/development/`](docs/development/). + ### Reading the verdict Both gates end with exactly one machine-readable line on stdout: @@ -164,18 +207,20 @@ grep '^BCA_GATE:' "$log" Two habits that idiom encodes: - **Give every run its own log path.** A fixed `/tmp/pc.log` is shared - by every checkout, worktree, and tool on the host. During one batch a - concurrent run's log was read as this one's, and a `fmt-check` failure - was diagnosed against code that had never been touched. The same - rule covers every scratch file; the tiers — and where a file that - must outlive a reboot goes instead — are in - [`.claude/rules/temp-files.md`](.claude/rules/temp-files.md). + by every checkout, worktree, and tool on the host, and a concurrent + run's log has been read as this one's before. - **Read the verdict from the log, not from a reported exit status.** Some tooling reports the status of the last command on the line, so `make pre-commit >log 2>&1; echo "EXIT=$?"` announces `echo`'s success. That is a property of the caller, not of make; the log is the thing that is true either way. +A `fail` naming several stages with no code in common is usually the +host (a concurrent build slowing a fixture past its timeout), not the +change. The check is the same either way: does the failing stage's +output name something the diff touched? Re-run on a quiet host before +reading it as a finding. + If GNU Make 4 or any optional tool is unavailable, fall back to the raw cargo trio: @@ -183,6 +228,7 @@ raw cargo trio: cargo fmt --all -- --check cargo clippy --workspace --all-targets -- -D warnings cargo test --workspace --all-features +RUSTDOCFLAGS="-D warnings" cargo doc --no-deps --workspace --all-features ``` If [`pre-commit`](https://pre-commit.com/) is installed, also run @@ -277,6 +323,15 @@ Linux / macOS / Windows on every supported Python version, gated by a `dorny/paths-filter` job so Rust-only PRs skip it entirely. +The hand-written stubs `python/big_code_analysis/_native.pyi` and +`vcs.pyi` are checked against the built extension by `make py-stubtest` +(`mypy.stubtest`), which diffs names, signatures and defaults. After +changing a PyO3 signature or default, update the stub and re-run it. +PyO3 exposes a `#[new]` constructor as `__new__` and renders a computed +default as `...`, so the stub mirrors those shapes. The allowlist in +`big-code-analysis-py/stubtest-allowlist.txt` holds only deliberate +facade differences; keep it minimal. + To remove Python build artifacts (`.venv`, compiled extension, per-tool caches, `__pycache__` trees), run `make py-clean`. For a full wipe of both cargo `target/` and Python state, run @@ -286,9 +341,23 @@ full wipe of both cargo `target/` and Python state, run - **Rust style**: `cargo fmt`, clippy clean with `--workspace --all-targets -- -D warnings`. No `unsafe` code (one - narrow PyO3 FFI exception; see `AGENTS.md`). Avoid + narrow PyO3 FFI exception, documented in + `big-code-analysis-py/src/node.rs` and gated by + `make check-safety-doc-pin`). Avoid `unwrap` / `expect` / `panic!` / `assert!` in non-test code; propagate errors with `?`. +- **Lints**: `[workspace.lints]` carries `clippy::pedantic` and + `missing_docs`; a workspace-excluded crate needs its own copy + (`utils/check-excluded-manifests.py` gates it), except the five + vendored `tree-sitter-*` grammars, whose generated sources a + regeneration replaces wholesale (`LINTS_EXEMPT_CRATES` in that + gate carries the rationale; their `bindings/rust/build.rs` header + watch is the one hand-maintained part, gated by + `make check-grammar-build-watch`). Put additional `allow`s at file + or function level. +- **Diagnostics**: stderr messages go through the lowercase `warn` / + `die` / `note` helpers in each crate's `diag.rs`; never spell + `warning:` / `error:` in a literal. - **Visibility**: prefer `pub(crate)` over `pub`; widen visibility only when an item is re-exported from `lib.rs`. - **Edition**: 2024; `let-else`, let-chains, and other 2024 features @@ -352,8 +421,6 @@ fails on any *increase* against that baseline. Background reading: -- [`AGENTS.md`](AGENTS.md), section "Validation gates": the full - policy and the bulk-acceptance rules around grammar bumps. - [`docs/development/lessons_learned.md`](docs/development/lessons_learned.md), lesson 2 ("Tree-sitter aliases one rule across many kind_ids") and lesson 6 ("Snapshot tests pin behaviour, not correctness"): the @@ -362,7 +429,44 @@ Background reading: For bulk snapshot refresh after a grammar bump or a deliberate metric-computation change, use `cargo insta test --accept` per test file. Accepting snapshots one at a time via `mv *.snap.new` shifts -`assertion_line` fields and cascades stale-snapshot churn. +`assertion_line` fields and cascades stale-snapshot churn. Three traps +in that loop: + +- The corpus runner aborts after its first panics, so collect with + `INSTA_FORCE_PASS=1 cargo test --no-fail-fast` before counting what + moved. +- A forced pass leaves an inline snapshot that moved as a + `src/**/.*.pending-snap` file, not a `.snap.new`; review both kinds. +- `cargo insta test --accept` accepts every pending snapshot in the + workspace, including ones an earlier run left behind. Review + everything pending, or accept a filtered set with + `cargo insta accept --snapshot `. + +## Metric baseline + +`make self-scan` reads `.bca-baseline.toml`, which suppresses a known +offender only while its measurement stays at or below the record. A +change that moves a baselined metric past its record, or below it (the +`--baseline` run warns on stderr), refreshes the file in the same +commit with `make self-scan-write-baseline-headroom`; the bare +`write-baseline` recipe drops the soft-tier entries. The file is +`-merge` in `.gitattributes`: on a conflict, regenerate rather than +hand-resolve. For a change split into several commits, regenerate at +each step, since the refresh measures the working tree: + +```bash +git rebase --exec 'make self-scan-write-baseline-headroom && (git diff --quiet .bca-baseline.toml || git commit -q --amend --no-edit .bca-baseline.toml)' +``` + +The scan builds `bca` under the dev profile (a few seconds after a +Rust edit, near-instant otherwise); `BCA_SELF_SCAN_PROFILE=release` +restores CI's exact profile and `make self-scan-profile-parity` checks +the two agree. Before tightening a limit, run `bca check +--explain-threshold =`, which reports both tiers and +how many new baseline entries the change would buy; a limit set on a +cluster of existing values maximises soft-tier breach by construction. +See [Baseline freshness](docs/development/baseline_freshness.md) and +the book's [Choosing thresholds](big-code-analysis-book/src/recipes/thresholds.md). ## Integration snapshots and the submodule @@ -381,6 +485,10 @@ the following have happened in the same parent commit: parent commit** as the metric/alterator fix. 4. After any rebase, force-push, or long-running batch fix, re-run the integration tests before declaring done. +5. `make role-coverage-observe` regenerates + `.role-coverage-observed.txt`, which records the submodule SHA as + provenance; commit it in the same parent commit, or + `make role-coverage` fails on the stale file. See lesson 8 in [`docs/development/lessons_learned.md`](docs/development/lessons_learned.md) @@ -395,9 +503,16 @@ guides under `big-code-analysis-book/src/developers/`: - [Updating tree-sitter grammars](big-code-analysis-book/src/developers/update-grammars.md). External grammar crates are version-pinned (`=0.23.5`, `=0.25.1`, and -so on) in the root `Cargo.toml`. Do not loosen those pins without -explicit approval; a grammar bump is a deliberate, separate change and -snapshot tests shift accordingly. +so on) in the root `Cargo.toml` and in each workspace-excluded crate's +own manifest; `utils/check-excluded-manifests.py` enforces both. +`tree-sitter-language`, the shared trait shim, is the one deliberate +exception and stays caret-ranged. Do not loosen a pin without explicit +approval; a grammar bump is a deliberate, separate change that moves +snapshots and, for the `tree-sitter` runtime, the `unsafe` soundness +argument in `big-code-analysis-py/src/node.rs`. If a bug is in the +grammar rather than our wrapper, document it as upstream and work +around it visibly. The per-language checklist is +[`docs/development/grammar_dispatch.md`](docs/development/grammar_dispatch.md). ## Code review diff --git a/Makefile b/Makefile index 17c2e639f..c7711ba0f 100644 --- a/Makefile +++ b/Makefile @@ -535,7 +535,7 @@ mutation-workflow-test: # The role-series drift drivers (#1744): each self-test stubs the # binaries it drives, so these run in seconds and never touch the # corpus. `-B` because a sweep of an imported module must not read a -# stale `.pyc` (`.claude/rules/testing.md`). +# stale `.pyc` (`docs/development/testing.md`). drift-common-test: @echo "Running drift-common self-tests..." @(cd $(BASE_DIR) && python3 -B -m unittest -q utils/drift_common-test.py) @@ -917,8 +917,6 @@ plugin-test: elif [ "$${CI:-}" = "true" ]; then \ echo "Node >= 22.7 required for plugin-test in CI" >&2; exit 1; \ else echo "Node >= 22.7 not found; skipping plugin-test"; fi - @if command -v shellcheck >/dev/null 2>&1; then shellcheck "$(BASE_DIR).claude/hooks/bca-check.sh"; fi - @if command -v shfmt >/dev/null 2>&1; then shfmt -d -i 0 -ci -bn "$(BASE_DIR).claude/hooks/bca-check.sh"; fi # Sync gate for check-grammar-crate.py's EXTENSIONS table. Re-derives # the grammar -> extension mapping from the parse layer's langs.rs diff --git a/big-code-analysis-ast/src/c_declarator.rs b/big-code-analysis-ast/src/c_declarator.rs index e81ebc369..eebd55ab0 100644 --- a/big-code-analysis-ast/src/c_declarator.rs +++ b/big-code-analysis-ast/src/c_declarator.rs @@ -52,7 +52,7 @@ use crate::node::Node; /// nesting can only be a macro (or an `ERROR`, below). The walk stops /// at the outer link there and reports the function's arity (#1213). /// -/// The walk is by field name, per `.claude/rules/grammar-dispatch.md` +/// The walk is by field name, per `docs/development/grammar_dispatch.md` /// §3, which also sidesteps §1: `PointerDeclarator2`, /// `FunctionDeclarator2`/`3` and `ReferenceDeclarator2`/`3`/`4` are /// numeric-suffix aliases that a `kind_id` match would have to @@ -268,7 +268,7 @@ pub fn declarator_name<'tree, T: Checker>(node: &Node<'tree>) -> Option { fn $byteless(node: &Node) -> bool { @@ -121,9 +121,7 @@ macro_rules! impl_byte_gated_row_predicate { // a known-empty chain, which is exact only while neither row reads // either — the build asserts both flags of both rows (#1793). Ruby's // opener is chain-gated by design and keeps a hand-written forward -// pinned at runtime instead (`ruby_byte_less_spellings_stay_the_kind_table`), -// as C#'s is since #1828 -// (`csharp_byte_less_spellings_omit_the_primary_constructor`); +// pinned at runtime instead (`ruby_byte_less_spellings_stay_the_kind_table`); // Elixir overrides both spellings. Per-language rationale — which // rows, why they read nothing — sits above the invocation. macro_rules! impl_byte_less_func_space { @@ -191,7 +189,7 @@ macro_rules! impl_doc_target_from_row { // it: its row also owns the `elif_clause`, and the Checker answers // `Branch ∧ ElseIf` so that clause stays `false` as every caller has had // it. Per-language rationale — which strategy the row spells and why — -// sits above each invocation (`.claude/rules/macro-comments.md`). +// sits above each invocation (`docs/development/formatting.md`). macro_rules! impl_else_if_from_row { ($roles:ident) => { #[inline] @@ -617,7 +615,7 @@ pub trait Checker { /// `parameter_declaration` holding a bare `primitive_type` and no /// declarator is *also* how an unnamed parameter is spelled, and /// `void f(int)` really does take one. Only the bytes tell them - /// apart — `.claude/rules/grammar-dispatch.md` §10. + /// apart — `docs/development/grammar_dispatch.md` §10. #[inline] #[must_use] fn is_empty_param_marker(_param: &Node, _code: &[u8]) -> bool { @@ -671,7 +669,7 @@ pub trait Checker { /// **A call site reaching for the byte-less spelling reads as /// correct against every language without an override, and is wrong /// only on the one that has one** — - /// `.claude/rules/grammar-dispatch.md` §7. There is one call site, + /// `docs/development/grammar_dispatch.md` §7. There is one call site, /// the `"string"` arm of [`ParserTrait::filters`], and it takes this /// spelling; `tcl_script_body_is_a_string_only_to_the_byteless_spelling` /// pins that the two really do disagree, so a future call site that @@ -857,7 +855,7 @@ pub trait Checker { /// Deliberately one method rather than a byte-less / `_with_code` /// pair: the pair forwards by default, so a call site reaching for /// the wrong spelling reads as correct against every language - /// without an override (`.claude/rules/grammar-dispatch.md` §7). + /// without an override (`docs/development/grammar_dispatch.md` §7). /// One spelling has nothing to disagree with. #[inline] #[must_use] @@ -1190,7 +1188,7 @@ fn rust_attribute_run_verdict<'a>( /// fusing this lookahead and the run reading into one pass is /// deliberate. A fused scan would be a third reading of the same run, /// free to drift from the other two — the failure mode -/// `.claude/rules/grammar-dispatch.md` §7 is about. What was quadratic +/// `docs/development/grammar_dispatch.md` §7 is about. What was quadratic /// in #1446 was asking `run` times, which /// [`rust_attribute_run_verdict`]'s reach removes without adding a /// reading. @@ -3597,7 +3595,7 @@ mod tests { /// right. Asserting the disagreement directly is what makes a future /// call site that reaches for the byte-less spelling a wrong answer /// rather than an indistinguishable one - /// (`.claude/rules/grammar-dispatch.md` §7). + /// (`docs/development/grammar_dispatch.md` §7). /// /// Each fixture holds a braced value, a script body reached through /// a *modelled* construct, a script body reached through the diff --git a/big-code-analysis-ast/src/checker/csharp.rs b/big-code-analysis-ast/src/checker/csharp.rs index d15f5c4d7..76344c463 100644 --- a/big-code-analysis-ast/src/checker/csharp.rs +++ b/big-code-analysis-ast/src/checker/csharp.rs @@ -75,29 +75,10 @@ impl Checker for CsharpCode { // `FuncOpener` row (every callable, the closures, and an indexer or // property gated to its accessor-less form — #464, #472) and the // `Container` row are what the walk promotes, and `opens_space` - // labels them. The rows read no bytes (the accessor gate reads the - // node's children), but since #1828 the opener row reads the chain: - // a `parameter_list` opens a space only under a type declaration, - // where it is the primary constructor. So this byte-less spelling - // is hand-written, as Ruby's is, and forwards with a *known-empty* - // chain — the node read as if it were the root, so the parent gate - // sees no type declaration and the list answers `false`, the - // pre-#1828 answer for every parameter list. Not - // `Ancestors::unknown()`, which climbs through `Node::parent` and - // would answer the gated result here. The walk calls the - // `_with_code` one. Where Ruby's gate over-approximates under the - // empty chain, this one under-approximates; - // `csharp_byte_less_spellings_omit_the_primary_constructor` - // (`roles/space_tree_tests.rs`) pins the disagreement by value. - fn is_func_space(node: &Node) -> bool { - const _: () = assert!( - !crate::roles::csharp::func_opener::TEXT_GATED - && !crate::roles::csharp::container::TEXT_GATED - && !crate::roles::csharp::container::CHAIN_GATED, - "a space-opening row reads bytes; the byte-less spelling cannot forward with none" - ); - Self::is_func_space_with_code(node, &[], Ancestors::known(&[])) - } + // labels them. The rows read no bytes and no chain (the accessor + // gate reads the node's children), so the byte-less spelling + // forwards with none and answers the same. + impl_byte_less_func_space!(csharp); fn is_func_space_with_code<'a>( node: &Node<'a>, @@ -127,10 +108,12 @@ impl Checker for CsharpCode { impl_row_predicates!(csharp, call, is_call, is_call_with_code); impl_row_predicates!(csharp, string_lit, is_string, is_string_with_code); - // No `is_non_arg`: `impl NArgs for CsharpCode` counts a parameter - // list positively (`parameter` and `params`), since the grammar - // flattens a `params` array into the list, so the trait's negative - // filter is never consulted and the default `false` stands. + fn is_non_arg(node: &Node) -> bool { + matches!( + node.kind_id().into(), + Csharp::LPAREN | Csharp::COMMA | Csharp::RPAREN + ) + } // The `ElseIf` row of `roles/csharp.rs`: an `if_statement` whose // previous sibling is the bare `else` token (no clause wrapper), read diff --git a/big-code-analysis-ast/src/checker/objc.rs b/big-code-analysis-ast/src/checker/objc.rs index 542deb340..a384ef0af 100644 --- a/big-code-analysis-ast/src/checker/objc.rs +++ b/big-code-analysis-ast/src/checker/objc.rs @@ -60,7 +60,7 @@ impl Checker for ObjcCode { // - `implementation_definition` wraps `function_definition` and // `method_definition` alike, so a parent check alone answers // `true` for every real method and zeroes the class's WMC - // (`.claude/rules/grammar-dispatch.md` §6). + // (`docs/development/grammar_dispatch.md` §6). // - A parent-kind *list* cannot be completed. `@interface` and // `@protocol` take `function_definition` as a direct child with no // wrapper, and both also admit `preproc_if` — so a helper inside diff --git a/big-code-analysis-ast/src/count.rs b/big-code-analysis-ast/src/count.rs index 5a9510c96..3d8c1a6a7 100644 --- a/big-code-analysis-ast/src/count.rs +++ b/big-code-analysis-ast/src/count.rs @@ -183,7 +183,7 @@ mod tests { // cascade into a pool-wide panic. A worker that panics while holding // the shared guard poisons the lock; `CountCollector::add` used to // re-panic on `.lock().unwrap()`. Verified by revert per - // `.claude/rules/testing.md`: reverting the recovery makes this test + // `docs/development/testing.md`: reverting the recovery makes this test // panic instead of applying the tally. #[test] fn add_degrades_on_poisoned_stats_mutex() { @@ -274,7 +274,7 @@ mod tests { // misuse cannot masquerade as a final aggregate. Gated on // `debug_assertions`: `debug_assert!` is a no-op under `--release`, // where the call degrades to the snapshot instead of panicking. - // Verified by revert per `.claude/rules/testing.md`: without the + // Verified by revert per `docs/development/testing.md`: without the // `debug_assert!`, `into_count` returns normally and this test fails // (no panic), proving the assert is what makes the misuse loud. #[test] diff --git a/big-code-analysis-ast/src/getter.rs b/big-code-analysis-ast/src/getter.rs index ba2e29e05..3f14e3214 100644 --- a/big-code-analysis-ast/src/getter.rs +++ b/big-code-analysis-ast/src/getter.rs @@ -75,8 +75,8 @@ macro_rules! get_operator { // `FuncOpener` and `Container` rows (#1696), the Getter half of // `checker.rs`'s `impl_byte_less_func_space!`: forwards with no bytes // and a known-empty chain, which the build asserts neither row reads -// (#1793). Ruby, C# and Elixir keep hand-written spellings for the -// reasons given there. +// (#1793). Ruby and Elixir keep hand-written spellings for the reasons +// given there. macro_rules! impl_byte_less_space_kind { ($roles:ident) => { fn get_space_kind(node: &Node) -> SpaceKind { @@ -1228,17 +1228,14 @@ mod ancestor_tests { /// `get_func_space_name` must name a space the same whether it reads /// the walker's ancestor chain or climbs with `Node::parent`. /// - /// Four grammars consult an ancestor here, for different reasons: + /// Two grammars consult an ancestor here, for different reasons: /// the JS family names an anonymous `function` / arrow from the - /// `pair` or `variable_declarator` holding it, Elixir skips - /// naming a `def` that sits inside a `quote` template, and Kotlin - /// and C# name a primary constructor after the class holding it - /// (#1828). #1088 moved the first two onto the chain. + /// `pair` or `variable_declarator` holding it, and Elixir skips + /// naming a `def` that sits inside a `quote` template. #1088 moved + /// both onto the chain. #[cfg(any( - feature = "csharp", feature = "elixir", feature = "javascript", - feature = "kotlin", feature = "mozjs", feature = "typescript", ))] @@ -1276,10 +1273,8 @@ mod ancestor_tests { } #[cfg(all( - feature = "csharp", feature = "elixir", feature = "javascript", - feature = "kotlin", feature = "mozjs", feature = "typescript", ))] @@ -1315,19 +1310,6 @@ mod ancestor_tests { b"defmodule Foo do\n defmacro multi do\n quote do\n def a, do: 1\n end\n end\nend\n", &["Foo", "multi"], ); - // A primary constructor is named from its parent class; `Inner` - // is nested so the parent is not the root, and `m` keeps the - // field-less default. - assert_name_parity::( - "kotlin", - b"class Outer(val a: Int) {\n class Inner(val b: Int) {\n fun m(x: Int) = x\n }\n}\n", - &["Outer", "Inner", "m"], - ); - assert_name_parity::( - "csharp", - b"class Outer(int a) {\n record Inner(int b) {\n int M(int x) => x;\n }\n}\n", - &["Outer", "Inner", "M"], - ); } } diff --git a/big-code-analysis-ast/src/getter/csharp.rs b/big-code-analysis-ast/src/getter/csharp.rs index 8ff23563f..71e167c51 100644 --- a/big-code-analysis-ast/src/getter/csharp.rs +++ b/big-code-analysis-ast/src/getter/csharp.rs @@ -95,43 +95,8 @@ impl Getter for CsharpCode { // (#1696): an enum opens `Class` for cross-language parity (#429); // a bodied indexer or property defers to its accessors and the // accessor-less form opens `Function` (#464, #472). The rows read no - // bytes; the opener row reads the chain for the primary - // constructor's `parameter_list` (#1828), so this forwards with a - // known-empty chain and labels that list `Unknown`, exactly as the - // Checker half (`checker/csharp.rs`) answers `false` — see the - // rationale there. - fn get_space_kind(node: &Node) -> SpaceKind { - const _: () = assert!( - !crate::roles::csharp::func_opener::TEXT_GATED - && !crate::roles::csharp::container::TEXT_GATED - && !crate::roles::csharp::container::CHAIN_GATED, - "a space-opening row reads bytes; the byte-less spelling cannot forward with none" - ); - Self::get_space_kind_with_code(node, &[], Ancestors::known(&[])) - } - - /// A primary constructor's `parameter_list` carries no name: it - /// takes its type's, as a `constructor_declaration`'s `name` field - /// already spells the type it constructs (#1828). The default would - /// name it ``, which `bca check` reads as a closure. - fn get_func_space_name<'a, 'tree>( - node: &Node<'tree>, - code: &'a [u8], - ancestors: Ancestors<'tree, '_>, - ) -> Option<&'a str> { - // role-bypass: allow(FuncOpener) — a naming rule, not whether the - // node opens a space - // The `Container` row carries no gate, so its kind table is the - // whole answer; a method's list sits under a method, not a - // container, and keeps the default. - if node.kind_id() == Csharp::ParameterList - && let Some(owner) = ancestors.parent(node) - && crate::roles::csharp::container::lists_kind(owner.kind_id()) - { - return crate::getter::default_func_space_name(&owner, code, ancestors); - } - crate::getter::default_func_space_name(node, code, ancestors) - } + // bytes and no chain, so the byte-less spelling forwards with none. + impl_byte_less_space_kind!(csharp); fn get_space_kind_with_code<'a>( node: &Node<'a>, diff --git a/big-code-analysis-ast/src/getter/kotlin.rs b/big-code-analysis-ast/src/getter/kotlin.rs index 23a13a100..e9a5fb995 100644 --- a/big-code-analysis-ast/src/getter/kotlin.rs +++ b/big-code-analysis-ast/src/getter/kotlin.rs @@ -156,12 +156,6 @@ impl Getter for KotlinCode { /// `` / `` are Kotlin's own spelling of the accessor /// keywords; `` is what the JVM calls the constructor an /// `init` block compiles into. - /// - /// A primary constructor carries no name of its own — the grammar - /// gives `primary_constructor` no `name` field — so it takes its - /// class's, as a secondary constructor's `constructor` keyword - /// stands for the class it is in (#1828). The default would name - /// it ``, which `bca check` reads as a closure. fn get_func_space_name<'a, 'tree>( node: &Node<'tree>, code: &'a [u8], @@ -173,9 +167,6 @@ impl Getter for KotlinCode { Kotlin::Getter => Some(""), Kotlin::Setter => Some(""), Kotlin::AnonymousInitializer => Some(""), - Kotlin::PrimaryConstructor => ancestors - .parent(node) - .and_then(|class| crate::getter::default_func_space_name(&class, code, ancestors)), _ => crate::getter::default_func_space_name(node, code, ancestors), } } diff --git a/big-code-analysis-ast/src/lang_helpers/ruby.rs b/big-code-analysis-ast/src/lang_helpers/ruby.rs index 641bce968..9675215b5 100644 --- a/big-code-analysis-ast/src/lang_helpers/ruby.rs +++ b/big-code-analysis-ast/src/lang_helpers/ruby.rs @@ -26,7 +26,7 @@ use crate::node::{Ancestors, FoldLane, Node}; /// One helper the `Closure` and `FuncOpener` rows of `roles/ruby.rs` /// both gate on, so the closure count, the space tree, and the /// cognitive nesting surcharge — each a reader of those rows — cannot -/// drift apart (`.claude/rules/grammar-dispatch.md` §6). +/// drift apart (`docs/development/grammar_dispatch.md` §6). /// /// The parent comes off the caller's chain: all consumers run per node /// from a walk, and `Node::parent` costs `O(depth)` because diff --git a/big-code-analysis-ast/src/lib.rs b/big-code-analysis-ast/src/lib.rs index 6b740bc07..0d0bb5c0b 100644 --- a/big-code-analysis-ast/src/lib.rs +++ b/big-code-analysis-ast/src/lib.rs @@ -84,7 +84,7 @@ // the import itself can express. Partial builds only — `all-languages` // is on by default and under `--all-features`, so the build CI gates on // and the one a contributor runs still police every unused import. See -// `.claude/rules/testing.md`, "Why the import lint is off on a partial +// `docs/development/testing.md`, "Why the import lint is off on a partial // build". #![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] pub mod alterator; diff --git a/big-code-analysis-ast/src/macros/kind_sets.rs b/big-code-analysis-ast/src/macros/kind_sets.rs index 3d6230415..2de8e074e 100644 --- a/big-code-analysis-ast/src/macros/kind_sets.rs +++ b/big-code-analysis-ast/src/macros/kind_sets.rs @@ -8,7 +8,7 @@ // `matches!()` at the call site, where a `use ::*` glob brings // the variants into scope. They carry no logic -- only the variant // membership -- and every per-call grammar rationale comment travels -// with its macro (see `.claude/rules/macro-comments.md`). +// with its macro (see `docs/development/formatting.md`). // // Re-exported below via `pub use` and again from // `macros/mod.rs`, so every existing `crate::macros::` import in @@ -78,7 +78,7 @@ macro_rules! csharp_var_declarator_kinds { // it, while the comparison token beside them scored in both. Each now // has an unconditional arm in its language's ABC `compute` and is // listed in neither place twice — which would score it twice -// (`.claude/rules/grammar-dispatch.md` §5). +// (`docs/development/grammar_dispatch.md` §5). // // The line is the construct's *value*, not its type. A cast, a type // assertion and an `@available` query all yield something the slot diff --git a/big-code-analysis-ast/src/node.rs b/big-code-analysis-ast/src/node.rs index 328608ece..4b59556a4 100644 --- a/big-code-analysis-ast/src/node.rs +++ b/big-code-analysis-ast/src/node.rs @@ -232,7 +232,7 @@ impl<'a> Node<'a> { /// crate already runs passes that parse one buffer and read another /// (`preproc`, `comment_rm`), and `panic!` is banned in non-test code /// whether or not the branch is currently reachable. `data.get(..)` - /// is also what `.claude/rules/grammar-dispatch.md` §10 prescribes + /// is also what `docs/development/grammar_dispatch.md` §10 prescribes /// for reading a node's bytes. #[inline] #[must_use] diff --git a/big-code-analysis-ast/src/node/ancestors.rs b/big-code-analysis-ast/src/node/ancestors.rs index 4f26e18f9..8ffe4c110 100644 --- a/big-code-analysis-ast/src/node/ancestors.rs +++ b/big-code-analysis-ast/src/node/ancestors.rs @@ -530,7 +530,7 @@ impl<'tree, 'chain> Ancestors<'tree, 'chain> { /// Whether `node`'s parent has kind id `kind`. /// - /// The compound-leaf guard of `.claude/rules/grammar-dispatch.md` + /// The compound-leaf guard of `docs/development/grammar_dispatch.md` /// section 5 asks this and nothing else: a delimiter or keyword /// token is suppressed *only* directly under the construct that /// owns it, never under an arbitrary ancestor. Eleven dispatch diff --git a/big-code-analysis-ast/src/roles/control_flow.rs b/big-code-analysis-ast/src/roles/control_flow.rs index 106be8310..d6fa86835 100644 --- a/big-code-analysis-ast/src/roles/control_flow.rs +++ b/big-code-analysis-ast/src/roles/control_flow.rs @@ -5,7 +5,7 @@ //! `Node::prev_sibling`, which resolve the parent by descending from the //! root (#1084, #1584). The per-language rationale — which grammar //! shape makes the gate the right one — stays beside each invocation, -//! per `.claude/rules/macro-comments.md`. +//! per `docs/development/formatting.md`. /// `continues_else_clause`: an `if` whose parent is the grammar's /// `$clause` kind — the `else if` of the C and JS families, whose diff --git a/big-code-analysis-ast/src/roles/csharp.rs b/big-code-analysis-ast/src/roles/csharp.rs index 33fc5dd0d..9c799f412 100644 --- a/big-code-analysis-ast/src/roles/csharp.rs +++ b/big-code-analysis-ast/src/roles/csharp.rs @@ -244,20 +244,10 @@ role_table! { // expression-bodied form (`has_no_accessors`). A lambda and an // anonymous method (`delegate { }`) are closures that open a space // too, as Rust's and Go's do. - // - // A C# 12 primary constructor and a positional record's constructor - // have no node of their own: the grammar hangs their - // `parameter_list` directly under the type declaration, the one - // place a parameter list is not a callable's `parameters` field - // (`node-types.json`: `class_declaration`, `struct_declaration` - // and `record_declaration` carry it as a child; an interface and - // an enum cannot). That list is the constructor (#1828). Its - // superclass call sits in the sibling `base_list`, outside it. FuncOpener { owns [ MethodDeclaration(callable opens Function), ConstructorDeclaration(callable opens Function), - ParameterList(callable opens Function under [ClassDeclaration, StructDeclaration, RecordDeclaration]), DestructorDeclaration(callable opens Function), LocalFunctionStatement(callable opens Function), AccessorDeclaration(callable opens Function), diff --git a/big-code-analysis-ast/src/roles/derived_parity_tests.rs b/big-code-analysis-ast/src/roles/derived_parity_tests.rs index 61a64b21c..27c125e8c 100644 --- a/big-code-analysis-ast/src/roles/derived_parity_tests.rs +++ b/big-code-analysis-ast/src/roles/derived_parity_tests.rs @@ -1081,22 +1081,6 @@ const KNOWN_DISAGREEMENTS: &[(&str, &str, &str, &str)] = &[ "call", "same: no bytes, no `defmodule` arm", ), - // The C# primary constructor is a `parameter_list` under a type - // declaration (#1828): a parent gate the byte-less pair's known-empty - // chain cannot see, so both answer the pre-#1828 `false` / `Unknown` - // (`csharp_byte_less_spellings_omit_the_primary_constructor`). - ( - "Csharp", - "is_func_space", - "parameter_list", - "the `FuncOpener` row gates the list on a type-declaration parent; the known-empty chain has none", - ), - ( - "Csharp", - "get_space_kind", - "parameter_list", - "same: the byte-less spelling forwards with no chain", - ), // The kind-only `is_string` / `is_call` against the gated row: the // Tcl family's braced word is a string only where it is not a // script body or a value slot, which the kind table cannot see diff --git a/big-code-analysis-ast/src/roles/kotlin.rs b/big-code-analysis-ast/src/roles/kotlin.rs index 422464380..179552cf2 100644 --- a/big-code-analysis-ast/src/roles/kotlin.rs +++ b/big-code-analysis-ast/src/roles/kotlin.rs @@ -256,12 +256,7 @@ role_table! { // hard keyword. DeclKeyword { owns [Class, Interface, Fun, Object, Val, Var, Typealias] } Primitive { absent "Kotlin's built-in types are ordinary type names (`Int`, `String`)" } - // A function and either constructor are the callables. The primary - // constructor is the `primary_constructor` child of the class - // declaration — the optional `constructor` keyword and its - // modifiers plus the `class_parameters` list — a sibling of the - // `class_body` and of the `delegation_specifiers` holding the - // superclass call, so the call is outside it (#1828). A + // A function and a secondary constructor are the callables. A // property accessor (`get()` / `set(v)`) and `init { … }` carry // executable code and open a space (#1184) without being callable: // in Kotlin one writes `p.foo`, not `p.getFoo()`, and a callable @@ -274,7 +269,6 @@ role_table! { FuncOpener { owns [ FunctionDeclaration(callable opens Function), - PrimaryConstructor(callable opens Function), SecondaryConstructor(callable opens Function), Getter(opens Function), Setter(opens Function), diff --git a/big-code-analysis-ast/src/roles/mod.rs b/big-code-analysis-ast/src/roles/mod.rs index 76ac25f9b..09735d480 100644 --- a/big-code-analysis-ast/src/roles/mod.rs +++ b/big-code-analysis-ast/src/roles/mod.rs @@ -18,7 +18,7 @@ //! //! This doc is the contributor reference for the tables. Read it before //! adding a language, a row, or a consumer; the rules under -//! `.claude/rules/` and the book's new-language chapter link here rather +//! `docs/development/grammar_dispatch.md` and the book's new-language chapter link here rather //! than restating it. //! //! # The role set @@ -415,8 +415,7 @@ //! `block` under a stabby lambda) answers exactly and only a byte //! gate is dropped. The chain-less pair disagrees with the walk //! wherever a gate reads what it drops — Elixir's text-gated `call` -//! openers, Ruby's `block`, C#'s `parameter_list` under a type -//! declaration (#1828) — and the derived parity suite pins each +//! openers, Ruby's `block` — and the derived parity suite pins each //! such disagreement by name (`KNOWN_DISAGREEMENTS`). Every other //! language's pair asserts `!TEXT_GATED && !CHAIN_GATED` on its //! `FuncOpener` and `Container` rows at build time (#1793). @@ -461,7 +460,7 @@ //! serves), since the reader deciding whether a row is right needs to //! know who reads it; the decision itself stays at the consumer, and //! nothing a row *emits* names a metric (#1690). The row-comment -//! placement rule is `.claude/rules/macro-comments.md`. +//! placement rule is `docs/development/formatting.md`. //! //! # The gates and the derived suite //! @@ -520,7 +519,7 @@ //! those). The check is review of the row against the grammar — `bca //! dump` on a one-line fixture per construct, every `(kind, parent)` //! pair the dump shows given a row or a stated exclusion -//! (`.claude/rules/grammar-dispatch.md` §6) — and a per-language +//! (`docs/development/grammar_dispatch.md` §6) — and a per-language //! spelling test for a kind no corpus file spells. //! //! **An incomplete entry.** A *missing cell* — a language with no row, diff --git a/big-code-analysis-ast/src/roles/space_tree_tests.rs b/big-code-analysis-ast/src/roles/space_tree_tests.rs index ca9054ae7..afa6b9525 100644 --- a/big-code-analysis-ast/src/roles/space_tree_tests.rs +++ b/big-code-analysis-ast/src/roles/space_tree_tests.rs @@ -555,14 +555,12 @@ fn objc_space_tree_rows() { /// C#: the accessor-less indexer and property (`this[int i] => i;`, /// `int W => F;`) open a `Function` space as callables, the bodied ones /// defer to their accessors (#464, #472 — lesson 65), checked by text -/// since one kind spells both; every other kind by the table. A -/// `parameter_list` is likewise two things by its parent (#1828). +/// since one kind spells both; every other kind by the table. #[cfg(feature = "csharp")] #[test] -#[allow(clippy::too_many_lines)] fn csharp_space_tree_rows() { use crate::roles::csharp::{closure, container, func_opener, member}; - let source = b"namespace N {\n interface I { int P { get; set; } void M(); }\n struct S(int g) { public int F; public S(int f) : this(0) { F = f; } }\n record Rec(int X) { public int Y { get; init; } }\n enum E { A, B }\n class P(int a) : I { void M() { } }\n class C : I {\n public int F1, F2 = 2;\n public int P { get; set; }\n public int W => F1;\n public int this[int i] => i;\n public int this[string k] { get { return 1; } }\n public C() { }\n ~C() { }\n public void M() { int L(int z) { return z; } System.Func f = y => y + 1; System.Action a = delegate { }; L(1); }\n public static C operator +(C a, C b) => a;\n public static implicit operator int(C c) => 1;\n }\n}\n"; + let source = b"namespace N {\n interface I { int P { get; set; } void M(); }\n struct S { public int F; public S(int f) { F = f; } }\n record Rec(int X) { public int Y { get; init; } }\n enum E { A, B }\n class C : I {\n public int F1, F2 = 2;\n public int P { get; set; }\n public int W => F1;\n public int this[int i] => i;\n public int this[string k] { get { return 1; } }\n public C() { }\n ~C() { }\n public void M() { int L(int z) { return z; } System.Func f = y => y + 1; System.Action a = delegate { }; L(1); }\n public static C operator +(C a, C b) => a;\n public static implicit operator int(C c) => 1;\n }\n}\n"; let expected: &[(&str, Answers)] = &[ ("compilation_unit", container(SpaceKind::Unit)), ("class_declaration", container(SpaceKind::Class)), @@ -597,43 +595,15 @@ fn csharp_space_tree_rows() { ); seen_kinds.insert(node.kind_id()); // `has_no_accessors` reads the node's own children, so the - // byte-less pair agrees with the `_with_code` one everywhere but - // on the primary constructor's `parameter_list`, whose parent - // gate the empty chain cannot see - // (`csharp_byte_less_spellings_omit_the_primary_constructor`). - if kind != "parameter_list" { - assert_eq!( - ( - CsharpCode::is_func_space(node), - CsharpCode::get_space_kind(node) - ), - (promoted, got.3), - "{kind}: the byte-less spellings are the kind table" - ); - } - // One kind, a constructor under a type declaration and a - // callable's parameters anywhere else (#1828). - if kind == "parameter_list" { - // By id, as the row reads it, so an alias of a type - // declaration minted by a grammar bump is not read as one - // through its shared string (grammar-dispatch §1). - let under_type = chain.last().is_some_and(|p| { - matches!( - p.kind_id().into(), - crate::Csharp::ClassDeclaration - | crate::Csharp::StructDeclaration - | crate::Csharp::RecordDeclaration - ) - }); - let want = if under_type { F } else { NONE }; - assert_eq!( - got, - want, - "{kind} `{}`", - node.utf8_text(source).unwrap_or("?") - ); - return; - } + // byte-less pair agrees with the `_with_code` one everywhere. + assert_eq!( + ( + CsharpCode::is_func_space(node), + CsharpCode::get_space_kind(node) + ), + (promoted, got.3), + "{kind}: the byte-less spellings are the kind table" + ); if matches!(kind, "property_declaration" | "indexer_declaration") { let text = node.utf8_text(source).unwrap_or("?"); let head = text.split_once(['{', '=']).map_or(text, |(h, _)| h).trim(); @@ -734,7 +704,6 @@ fn kotlin_space_tree_rows() { ("companion_object", container(SpaceKind::Class)), ("object_literal", container(SpaceKind::Class)), ("function_declaration", F), - ("primary_constructor", F), ("secondary_constructor", F), ("getter", (false, false, true, SpaceKind::Function, false)), ("setter", (false, false, true, SpaceKind::Function, false)), @@ -1122,58 +1091,3 @@ fn closures_that_open_a_space_are_what_the_book_says() { ); assert_eq!(none, ["bash", "c", "irules", "tcl"]); } - -/// The byte-less `Checker::is_func_space` / `Getter::get_space_kind` -/// forward with a known-empty chain, so the `FuncOpener` row's -/// `under [..]` gate on a `parameter_list` — the primary constructor, -/// #1828 — sees no type declaration and answers `(false, Unknown)`, -/// the pre-#1828 answer for every parameter list, while the -/// `_with_code` spellings the walk reads promote it. The opposite -/// direction from Ruby's block (`ruby_byte_less_spellings_stay_the_kind_table`): -/// a positive parent gate under-approximates where a negative one -/// over-approximates. A method's list answers alike on both. -#[cfg(feature = "csharp")] -#[test] -fn csharp_byte_less_spellings_omit_the_primary_constructor() { - use crate::{Checker, CsharpCode, Getter}; - let source = b"class C(int a) { void M(int b) { } }\nrecord R(int x);\n"; - let mut lists = Vec::new(); - for_each_node_with_chain::(source, |node, chain| { - if node.kind() != "parameter_list" { - return; - } - let ancestors = Ancestors::known(chain); - lists.push(( - node.utf8_text(source).unwrap_or("?").to_owned(), - ( - CsharpCode::is_func_space(node), - CsharpCode::get_space_kind(node), - ), - ( - CsharpCode::is_func_space_with_code(node, source, ancestors), - CsharpCode::get_space_kind_with_code(node, source, ancestors), - CsharpCode::get_func_space_name(node, source, ancestors), - ), - )); - }); - assert_eq!( - lists, - [ - ( - "(int a)".to_owned(), - (false, SpaceKind::Unknown), - (true, SpaceKind::Function, Some("C")) - ), - ( - "(int b)".to_owned(), - (false, SpaceKind::Unknown), - (false, SpaceKind::Unknown, Some("")) - ), - ( - "(int x)".to_owned(), - (false, SpaceKind::Unknown), - (true, SpaceKind::Function, Some("R")) - ), - ] - ); -} diff --git a/big-code-analysis-ast/src/test_support.rs b/big-code-analysis-ast/src/test_support.rs index db2005499..7b9f5be34 100644 --- a/big-code-analysis-ast/src/test_support.rs +++ b/big-code-analysis-ast/src/test_support.rs @@ -110,7 +110,7 @@ fn labelled_prints_the_true_slots_by_name() { /// the walker feeds it the right slice. The walker lives in the other /// crate, so nothing links the two but this sentence — a change to its /// truncate/push discipline must be mirrored here by hand -/// (`.claude/rules/testing.md`, lesson #82). +/// (`docs/development/testing.md`, lesson #82). /// /// # Panics /// diff --git a/big-code-analysis-bench/src/verbatim.rs b/big-code-analysis-bench/src/verbatim.rs index 1f35c7d68..6bc5539e4 100644 --- a/big-code-analysis-bench/src/verbatim.rs +++ b/big-code-analysis-bench/src/verbatim.rs @@ -3,7 +3,7 @@ //! //! Reads each input file verbatim — no newline normalisation, unlike //! the CLI's reader, so this is the one path that reaches a node ending -//! at EOF (`.claude/rules/testing.md`, "Know what the harness normalises +//! at EOF (`docs/development/testing.md`, "Know what the harness normalises //! away") — and emits, per file, the serialised `metrics`, `ops`, the //! `Alterator`-built AST export under both span/comment settings, the //! `find` results for `call` / `string` / `function`, and the `count` diff --git a/big-code-analysis-book/src/developers/README.md b/big-code-analysis-book/src/developers/README.md index 7f6450d2f..d05b12e62 100644 --- a/big-code-analysis-book/src/developers/README.md +++ b/big-code-analysis-book/src/developers/README.md @@ -1,9 +1,9 @@ # Developers Guide How to build, test, lint and run `big-code-analysis` from a checkout. -It is for contributors; the repository-level rules (stability -contract, validation gates, review conventions) live in `AGENTS.md` -and `CONTRIBUTING.md` at the repository root. +It is for contributors; the validation gate and review conventions +live in `CONTRIBUTING.md`, and the rules shared with coding agents in +`AGENTS.md`, both at the repository root. You need a current stable Rust toolchain; diff --git a/big-code-analysis-book/src/developers/new-language.md b/big-code-analysis-book/src/developers/new-language.md index 4183b2ea1..d9b8251ce 100644 --- a/big-code-analysis-book/src/developers/new-language.md +++ b/big-code-analysis-book/src/developers/new-language.md @@ -170,7 +170,7 @@ node.kind_id()` arm that touches an aliasable rule must either list every numbered variant or compare on the string `node.kind()` instead. Missing an alias silently drops nodes from the metric. See the `add-lang` skill for the mechanical audit procedure, and -[`.claude/rules/grammar-dispatch.md`](https://github.com/dekobon/big-code-analysis/blob/main/.claude/rules/grammar-dispatch.md) +[`docs/development/grammar_dispatch.md`](https://github.com/dekobon/big-code-analysis/blob/main/docs/development/grammar_dispatch.md) plus lessons 2, 19 and 34 in [`docs/development/lessons_learned.md`](https://github.com/dekobon/big-code-analysis/blob/main/docs/development/lessons_learned.md) for the failure modes. diff --git a/big-code-analysis-book/src/metrics.md b/big-code-analysis-book/src/metrics.md index 30c0967ce..36112c990 100644 --- a/big-code-analysis-book/src/metrics.md +++ b/big-code-analysis-book/src/metrics.md @@ -194,13 +194,11 @@ class Classic : Base { } ``` -A primary constructor's function space is its parameter list (see -[Primary constructors](#nargs-primary-constructors)) and nothing more. -Its superclass call sits beside that list in the class header (C#'s -`base_list`, Kotlin's `delegation_specifiers`), outside every member, -so no function space encloses it and the branch belongs to the class. -The classic spelling puts the same call inside a constructor -declaration, whose function space does enclose it. +A primary constructor has no body. Its superclass call sits in the class +header (C#'s `base_list`, Kotlin's `delegation_specifiers`), outside +every member, so no function space encloses it and the branch belongs to +the class. The classic spelling puts the same call inside a constructor +declaration, which does open a function space. File-level `abc.branches` is identical either way, so nothing shifts at the aggregate. Per-function figures do: `branches_max`, @@ -208,8 +206,7 @@ the aggregate. Per-function figures do: `branches_max`, the primary-constructor form on a class row and never on a function row. A codebase migrating to primary constructors will therefore see its per-function ABC distribution move without any behaviour change. That is -the intended reading: the constructor's space holds its parameters, and -the call to the base is not among them. +the intended reading: there is no function to attribute the call to. #### Worked example @@ -1699,69 +1696,6 @@ second when none is (`closures_that_open_a_space_are_what_the_book_says` in `big-code-analysis-ast/src/roles/space_tree_tests.rs` pins the two against this paragraph; Bash, C, Tcl and iRules have no closure at all). -### Primary constructors {#nargs-primary-constructors} - -A Kotlin primary constructor and a C# 12 primary constructor — a -positional `record` included — have no body, only a parameter list in -the class header: - -```kotlin -data class D(val a: Int, val b: Int, val c: Int, val d: Int, val e: Int, val f: Int) -``` - -```csharp -public class C(int a, int b, int c, int d, int e, int f) { } -public record R(int A, int B); -``` - -Each opens a function space of its own, named after its class and -spanning the list, so it is gated like any other callable: the row -above reads `D::D: nargs = 6`. -[detekt's `LongParameterList`](https://detekt.dev/docs/rules/complexity/#longparameterlist) -gates constructors the same way, under a threshold of its own and a -data-class opt-out that is on by default; `bca` has neither, so the -`data class` above is reported. Before -[#1828](https://github.com/dekobon/big-code-analysis/issues/1828) the -list belonged to no space and counted nowhere, so a six-parameter data -class passed `--threshold nargs=5`. The space also counts as one -callable in [NOM](#nom), [NPM](#npm) and [WMC](#wmc) — a written -`class G()` declares a zero-parameter constructor and counts too — and -its superclass call stays with the class, as -[Where a constructor call lands](#abc-constructor-attribution) explains. A default spelled -as a lambda (`class L(val f: (Int) -> Int = { it })`) adds that -lambda's parameters to the constructor's `closure_args`, exactly as a -function's spaceless lambdas add to its own, so the row's split shows -them. - -The space is the list and nothing more, so a -[suppression marker](commands/suppression.md) has to sit *inside* it — -a marker on the line above binds to no function, as for any other -callable: - -```kotlin -data class Row( - // bca: suppress(nargs) — a column set, not a signature - val a: Int, val b: Int, val c: Int, val d: Int, val e: Int, val f: Int, -) -``` - -A parameterless `class G()` opens a space with no code in it, so its -`mi.*` read the `0.0` placeholder that -[Maintainability Index](#maintainability-index-mi) describes and -`bca check` and `bca report` skip. - -Two things a reader of the rows will meet. A classic constructor -beside a primary one shares its name — C#'s `H::H` twice, one per -spelling — and `bca check --baseline` tells two same-named rows apart -by line, so a class written on one line leaves them indistinguishable -to the baseline, as two same-line overloads already were. And a Kotlin -*secondary* constructor still reads `` in every listing, -since its node carries no name; only the primary is named after the -class. - -A Java or Groovy `record` with no explicit constructor still reads 0; -see [Languages where it reads 0](#nargs-language-gaps). - ### Averages, minimums and maximums {#nargs-aggregates} NArgs does not follow the @@ -1812,17 +1746,6 @@ A metric that silently reports 0 reads as "no offenders" rather than - **Perl anonymous subs**: a gap, and an upstream one. The grammar parses an anonymous sub's signature inside an error node, so `my $f = sub ($x) {…}` reads 0 even though it has a signature. -- **Java and Groovy records without an explicit constructor**: a - decision, recorded under - [#1160](https://github.com/dekobon/big-code-analysis/issues/1160) - and open for revisiting under - [#1842](https://github.com/dekobon/big-code-analysis/issues/1842). - `record R(int a, int b) {}` declares its components but no - constructor, so there is no space to attribute them to; a compact - constructor `R { … }` opens one and reports the component count. A - C# positional record reads its count either way, because its list - *is* its constructor (see - [Primary constructors](#nargs-primary-constructors)). A `nargs` limit is therefore inert on a Bash codebase and sparse on Perl written before `use v5.36`. Gate it per language rather than @@ -1921,14 +1844,6 @@ metrics exist to report. A Kotlin file of nothing but property accessors therefore reports `nom.functions == 0` while still reporting their complexity (#1184). -A constructor is counted as a function wherever one is written, the -bodiless kind included: a Kotlin primary constructor and a C# 12 -primary constructor or positional record each count one, as the -classic spelling does (see -[Primary constructors](#nargs-primary-constructors)). A compiler- -generated constructor — a class with no parameter list, a Java record -with no compact constructor — is not written and counts nothing. - ### How to read it NOM is the input to several other metrics: WMC sums *cyclomatic* diff --git a/big-code-analysis-book/src/recipes/agent-feedback.md b/big-code-analysis-book/src/recipes/agent-feedback.md index f218d8cd8..e216f41de 100644 --- a/big-code-analysis-book/src/recipes/agent-feedback.md +++ b/big-code-analysis-book/src/recipes/agent-feedback.md @@ -136,7 +136,7 @@ existing settings: "hooks": { "PostToolUse": [ { - "matcher": "Edit|Write|MultiEdit", + "matcher": "Edit|Write", "hooks": [ { "type": "command", @@ -155,12 +155,8 @@ The [exec form](https://code.claude.com/docs/en/hooks#exec-form-and-shell-form) passes the script path as one argument, including spaces and shell metacharacters. The hook requires Node on `PATH`; its JSON handling uses no [npm](https://www.npmjs.com/) packages or -[`jq`](https://jqlang.github.io/jq/). For an existing `bca-check.sh` -registration, replace the old script with the -[current wrapper](https://github.com/dekobon/big-code-analysis/blob/main/.claude/hooks/bca-check.sh) -and copy the `.mjs` files alongside it, or replace that registration -with the Node configuration above. Keep only one registration to avoid -duplicate checks. +[`jq`](https://jqlang.github.io/jq/). Keep only one registration to +avoid duplicate checks. How the hook finds its configuration and analyzer: @@ -208,9 +204,8 @@ offender can reappear on a later edit. It checks the whole file: `[new]` and `[regr]` compare against the configured baseline, not the preceding edit. Use the [standing guidance](#agent-guidance-ship-this-verbatim) to keep any -response within the task's scope. This matcher covers Edit, Write and -MultiEdit; shell commands and external editors need separate -integration. +response within the task's scope. This matcher covers Edit and Write; +shell commands and external editors need separate integration. **Verify model delivery after installation.** Using Claude's Write tool, create a disposable supported source file that breaches a @@ -240,8 +235,9 @@ integration the repository runs on itself, verified with OpenCode Prerequisites: - OpenCode 2.x. The plugin uses the - [V2 server plugin API](https://opencode.ai/v2/docs/build/plugins/server); - for OpenCode 1.x see the [legacy section](#opencode-v1-legacy). + [V2 server plugin API](https://opencode.ai/v2/docs/build/plugins/server). + For a 1.x plugin, port it with the + [migration guide](https://opencode.ai/v2/docs/build/plugins/migrate-v1). - `bca`, and a nonempty `[thresholds]` table in [`bca.toml`](local-gates.md#zero-config-the-bcatoml-manifest), as for Claude Code above. @@ -299,131 +295,6 @@ chosen. Configuration changes under `.opencode/` reload without a restart; if a freshly copied plugin does not load, `opencode service restart` is the fallback. -## OpenCode V1 (legacy) {#opencode-v1-legacy} - -The example in this section uses the V1 plugin API and is an -alternative to the V2 plugin above, not an addition to it: both are -`.opencode/plugins/bca-check.js`. Use the -[migration guide](https://opencode.ai/v2/docs/build/plugins/migrate-v1) -when porting a V1 plugin. - -**Mechanism:** implement a [plugin](https://opencode.ai/docs/plugins/): -a JavaScript or TypeScript module that exports an async function -returning a hooks object. Register **`tool.execute.after`**, which -runs after a tool completes, including the `write` and `edit` tools. - -**Feedback channel:** the after-hook surfaces a problem to the agent by -**throwing**. opencode's public plugins page documents the -throw-to-signal pattern but not an advisory return value for the -after-hook, so this recipe defaults to throwing. A thrown `Error` -carries its message back to the agent as the tool's failure. - -**Mind the argument shape; it differs from the `before` hook.** The -published `@opencode-ai/plugin` types give `tool.execute.after` the -signature `(input, output)` where the tool name is `input.tool` and the -**tool arguments are on `input.args`** (the file path is -`input.args.filePath`). This is the trap: the docs' only worked example -is for `tool.execute.before`, where args live on `output.args` (mutable, -pre-execution). Copy that into an *after* hook and `output.args` is -`undefined`, the guard below always trips, and the plugin silently never -runs: a no-op that looks installed. Read `input.args.filePath` in the -after hook. - -Drop this file in `.opencode/plugins/`. It is project-level and -auto-loaded; no `opencode.json` entry is needed, and in V2 a -single-file entry under `plugins` is skipped with a warning (see -above). The plugin below is plain JavaScript. For a -TypeScript plugin, `import type { Plugin } from "@opencode-ai/plugin"` -and annotate the export, and declare any extra deps in -`.opencode/package.json` (opencode installs it with -[Bun](https://bun.sh/)): - -```javascript -// .opencode/plugins/bca-check.js -// The same text as .claude/hooks/bca-guidance.txt. -const GUIDANCE = ` -[new] and [regr] compare with the configured baseline, not this edit; -without a baseline, every offender is new. rows are file-level -findings, not necessarily a problem in the function you changed. -Review findings relevant to your task: simplify where it genuinely -clarifies, or justify essential complexity with a narrow suppression. -For example, inside a Rust function: // bca: suppress(cognitive) -- reason. -Use the language's comment syntax; use nexits, never exit, and halstead -for halstead.* metrics. tokens is not suppressible. Leave unrelated code -alone and mention relevant remaining findings. Do not move complexity -around just to lower a number. Finish the coherent edit before reacting; -make self-scan and make pre-commit remain this repository's final gates. -`.trim() - -export const BcaCheck = async ({ $ }) => { - return { - // Note: the after-hook's args are on `input.args`, NOT `output.args` - // (output carries the tool's result: title/output/metadata). - "tool.execute.after": async (input, _output) => { - // React only to the file-writing tools. (Patch-style edit tools - // carry no single filePath and are intentionally not covered.) - if (input.tool !== "write" && input.tool !== "edit") return - const filePath = input.args?.filePath - if (!filePath) return - - // `bca check` exits 0 clean, 2 on offenders, 1 on tool error. - // Bun's $ throws on non-zero by default; capture instead so we - // can branch on the exact code. - const res = await $`bca check ${filePath} --no-summary --no-remediation` - .quiet() - .nothrow() - // 0 clean, 1 tool error: not a complexity issue. `< 2` rather than - // `=== 2` so the tiered exit codes (3-5, from `--exit-codes=tiered` - // / `exit_codes = "tiered"`) still report. - if (res.exitCode < 2) return - - // Surface the offenders to the agent by throwing. The rows are on - // stdout; stderr is the fallback for a run whose only output is a - // diagnostic. - const offenders = res.stdout.toString().trim() || res.stderr.toString().trim() - throw new Error(`bca flagged complexity in ${filePath}:\n\n${offenders}\n\n${GUIDANCE}`) - }, - } -} -``` - -`GUIDANCE` is the short runtime reminder from `bca-guidance.txt`, not -the standing policy block below; keep it in step with that file (the -repository's hook tests pin the two equal). Because the channel is a -thrown error, -opencode reports it as a failed post-edit step, which is the intended -"address this before continuing" framing. The edit itself still lands: -`tool.execute.after` runs once the `write` or `edit` tool has already -written the file, so the throw frames the next step without undoing the -change. - -**Restart opencode after adding the plugin.** OpenCode 1.x loads -plugins once at startup and does not hot-reload them, so a freshly -dropped `.opencode/plugins/bca-check.js` does nothing in the running -session. Quit and relaunch opencode, then confirm by editing a file you -know is over threshold and checking that the `edit`/`write` tool -reports the `bca` failure. An installed-but-inert plugin is the most -likely symptom, and a stale session is the most likely cause. - -The [V2 plugin](#opencode-v2) uses a different plugin API and adds -guards worth porting to a V1 setup: - -- **Repo-scope guard.** Resolve the path and skip anything outside the - project root, so the hook never runs `bca` on a file the agent edits - elsewhere on disk. -- **Local-build resolution.** Prefer `$BCA`; then the candidate among - the checkout's `target/debug/bca`, `target/release/bca` and `bca` on - `PATH` whose `build inputs:` digest matches the checkout; then the - newest local build; then `bca` on `PATH`. A project that builds - `bca` itself then gates against a binary built from the tree it is - editing whenever one exists, rather than a stale one or whatever is - installed globally; with no match it falls back to the newest build - it can find. -- **Shared guidance.** Read the guidance text from one file that both - this plugin and the Claude Code hook cite, so the two never drift. - The V1 example above inlines it instead, to stay a single-file - install. - ## Agent guidance (ship this verbatim) {#agent-guidance-ship-this-verbatim} Bare metric feedback can encourage changes that lower scores without diff --git a/big-code-analysis-cli/src/commands_tests.rs b/big-code-analysis-cli/src/commands_tests.rs index f9d6c7524..8ccd98cb8 100644 --- a/big-code-analysis-cli/src/commands_tests.rs +++ b/big-code-analysis-cli/src/commands_tests.rs @@ -1686,7 +1686,7 @@ fn resolve_provenance_maps_each_tier_branch() { // recovered guard still holds every joined worker's file entry, so // `into_preproc_data` degrades to the accumulated data rather than // re-panicking on `.expect("mutex not poisoned")`. Verified by revert -// per `.claude/rules/testing.md`: restoring the `.expect()` chain makes +// per `docs/development/testing.md`: restoring the `.expect()` chain makes // this test panic instead of recovering. #[test] fn into_preproc_data_degrades_on_poisoned_mutex() { diff --git a/big-code-analysis-cli/src/default_thresholds_tests.rs b/big-code-analysis-cli/src/default_thresholds_tests.rs index 53deb6474..9ff8f0727 100644 --- a/big-code-analysis-cli/src/default_thresholds_tests.rs +++ b/big-code-analysis-cli/src/default_thresholds_tests.rs @@ -18,10 +18,7 @@ const MANIFEST_COMMENT_WIDTH: usize = 72; /// of the numbers, and a second copy drifts, so each is pinned by /// `doc_summary_tables_match_the_default_table`. Paths are relative to /// the CLI crate directory. -const DOCS_REPEATING_THE_TABLE: &[&str] = &[ - "/../AGENTS.md", - "/../big-code-analysis-book/src/recipes/thresholds.md", -]; +const DOCS_REPEATING_THE_TABLE: &[&str] = &["/../big-code-analysis-book/src/recipes/thresholds.md"]; #[test] fn every_default_name_is_a_known_metric() { @@ -187,10 +184,9 @@ fn scope_word(name: &str) -> &'static str { /// Metric names appearing as threshold-summary rows in a Markdown doc. /// /// A row is recognized only by its full shape — backticked name, integer -/// limit, then one of the three scope words — because both documents -/// carry unrelated tables whose first cell is also backticked (AGENTS.md -/// lists the workspace crates that way, and the book's per-language table -/// backticks metric names in its header row). +/// limit, then one of the three scope words — because the document +/// carries unrelated tables whose first cell is also backticked (the +/// book's per-language table backticks metric names in its header row). fn documented_threshold_rows(text: &str) -> BTreeSet { text.lines() .filter_map(|line| { diff --git a/big-code-analysis-cli/tests/check/check_thresholds.rs b/big-code-analysis-cli/tests/check/check_thresholds.rs index 9eeadfa94..9d11a446a 100644 --- a/big-code-analysis-cli/tests/check/check_thresholds.rs +++ b/big-code-analysis-cli/tests/check/check_thresholds.rs @@ -2439,94 +2439,6 @@ fn nargs_omits_the_split_for_a_plain_parameter_list() { .stdout(predicate::str::contains("own +").not()); } -/// #1828's reproducers: a Kotlin primary constructor and a C# 12 -/// primary constructor each declare six parameters and were counted -/// nowhere, so this exact invocation exited 0. Each opens a function -/// space named after its class, so the offender row is `D::D` / -/// `C::C`, and the class's methods are not charged — `Sum` declares -/// none. -#[test] -fn nargs_gates_a_primary_constructor_on_its_own_row() { - let dir = TempDir::new().unwrap(); - let kt = write_fixture( - &dir, - "d.kt", - "data class D(val a: Int, val b: Int, val c: Int, val d: Int, val e: Int, val f: Int)\n", - ); - let cs = write_fixture( - &dir, - "c.cs", - "public class C(int a, int b, int c, int d, int e, int f)\n\ - {\n\ - \x20 public int Sum() => a + b + c + d + e + f;\n\ - }\n", - ); - - cli(dir.path()) - .args([ - "check", - "--paths", - &kt, - "--paths", - &cs, - "--threshold", - "nargs=5", - ]) - .assert() - .code(2) - .stdout(predicate::str::contains("D::D: nargs = 6 (limit 5)")) - .stdout(predicate::str::contains("C::C: nargs = 6 (limit 5)")) - .stdout(predicate::str::contains("Sum: nargs =").not()); -} - -/// A primary constructor's space is its parameter list and nothing -/// more, so a function-scope marker binds to it only from a row inside -/// the parentheses — the placement the book's `nargs` section shows. -/// Both spellings are exercised with the marker on its own row, and -/// `--no-suppress` restores the two offenders, so a space that stopped -/// starting at the `(` would be seen here rather than by a reader of -/// the book. -#[test] -fn nargs_suppression_binds_inside_a_primary_constructors_list() { - let dir = TempDir::new().unwrap(); - let kt = write_fixture( - &dir, - "row.kt", - "data class Row(\n\ - \x20 // bca: suppress(nargs) — a column set, not a signature\n\ - \x20 val a: Int, val b: Int, val c: Int, val d: Int, val e: Int, val f: Int,\n\ - )\n", - ); - let cs = write_fixture( - &dir, - "row.cs", - "public record Row(\n\ - \x20 // bca: suppress(nargs) — a column set, not a signature\n\ - \x20 int A, int B, int C, int D, int E, int F);\n", - ); - let paths = ["--paths", &kt, "--paths", &cs, "--threshold", "nargs=5"]; - - cli(dir.path()) - .arg("check") - .args(paths) - .assert() - .code(0) - .stdout(predicate::str::contains("Row::Row").not()); - - cli(dir.path()) - .arg("check") - .args(paths) - .arg("--no-suppress") - .assert() - .code(2) - .stdout(predicate::str::contains( - "row.kt:1-4: Row::Row: nargs = 6 (limit 5)", - )) - .stdout(predicate::str::contains( - "row.cs:1-3: Row::Row: nargs = 6 (limit 5)", - )); -} - /// A space with no code to measure never breaches an `mi.*` floor, in /// the text rows and in the aggregated report alike (#1621). A bodiless /// Ruby block has zero Halstead volume, so its MI is the `0.0` diff --git a/big-code-analysis-cli/tests/cli_ux/corpus_fixture.rs b/big-code-analysis-cli/tests/cli_ux/corpus_fixture.rs index 1d910abaa..4683fd11e 100644 --- a/big-code-analysis-cli/tests/cli_ux/corpus_fixture.rs +++ b/big-code-analysis-cli/tests/cli_ux/corpus_fixture.rs @@ -9,7 +9,7 @@ //! The guard is tested against synthetic trees rather than the real //! corpus: the corpus is present in every tree where this suite runs, //! so a test that waited for its absence would never execute (see -//! `.claude/rules/testing.md`). +//! `docs/development/testing.md`). use std::fs; diff --git a/big-code-analysis-cli/tests/common/mod.rs b/big-code-analysis-cli/tests/common/mod.rs index 5bfcd2e0a..8930d7101 100644 --- a/big-code-analysis-cli/tests/common/mod.rs +++ b/big-code-analysis-cli/tests/common/mod.rs @@ -120,7 +120,7 @@ pub fn corpus_fixture_strip_prefix() -> String { /// Split from [`corpus_fixture_path`] so the diagnostic is testable /// against a synthetic tree. The real corpus is checked out in any tree /// where this suite runs, so a test that waited for its absence would -/// never execute — see `.claude/rules/testing.md`. +/// never execute — see `docs/development/testing.md`. #[allow(dead_code)] pub fn corpus_checkout_hint(workspace_root: &Path, corpus: &str, file: &str) -> Option { let corpus_dir = workspace_root.join(CORPUS_ROOT).join(corpus); @@ -310,7 +310,7 @@ pub fn process_env_lock() -> std::sync::MutexGuard<'static, ()> { /// these drive the cwd into a `.git`-rooted manifest dir and prove the /// hermetic builders ignore it (the assertion then fails if a builder is /// reverted to the un-anchored `bca_command()` — see -/// `.claude/rules/testing.md`). +/// `docs/development/testing.md`). #[allow(dead_code)] pub struct CwdGuard { prior: std::path::PathBuf, diff --git a/big-code-analysis-cli/tests/discovery/skip_generated.rs b/big-code-analysis-cli/tests/discovery/skip_generated.rs index 04de437bc..7e4be1de3 100644 --- a/big-code-analysis-cli/tests/discovery/skip_generated.rs +++ b/big-code-analysis-cli/tests/discovery/skip_generated.rs @@ -118,7 +118,7 @@ fn marker_in_body_is_not_skipped() { /// manifest is never discovered, so `hand.rs` survives. /// - Reverting `cli()` to `bca_command()` (no cwd anchor) inherits this /// leaky cwd, discovers the manifest, and drops `hand.rs` — the test -/// then fails, proving it guards the anchor (see `.claude/rules/testing.md`). +/// then fails, proving it guards the anchor (see `docs/development/testing.md`). /// /// The control arm (raw command explicitly rooted at the leaky dir) /// proves the exclude actually fires, so the hermetic assertion is not diff --git a/big-code-analysis-cli/tests/discovery/warning_flag.rs b/big-code-analysis-cli/tests/discovery/warning_flag.rs index e5ec951f0..f08dab6e0 100644 --- a/big-code-analysis-cli/tests/discovery/warning_flag.rs +++ b/big-code-analysis-cli/tests/discovery/warning_flag.rs @@ -142,7 +142,7 @@ fn warning_flag_names_the_skip_reason_for_a_utf16_file() { /// hermetic builder still reports the default count (the `?` operator /// counts). Reverting `cli()` to `bca_command()` inherits the leaky cwd, /// picks up the manifest, drops the `?` from the count, and fails this -/// test (test-via-revert; see `.claude/rules/testing.md`). +/// test (test-via-revert; see `docs/development/testing.md`). #[test] fn hermetic_cwd_ignores_discoverable_manifest() { let probe = NamedTempFile::with_suffix(".rs").unwrap(); diff --git a/big-code-analysis-py/tests/test_metrics_select.py b/big-code-analysis-py/tests/test_metrics_select.py index 01f9f750a..433165d68 100644 --- a/big-code-analysis-py/tests/test_metrics_select.py +++ b/big-code-analysis-py/tests/test_metrics_select.py @@ -20,7 +20,7 @@ :func:`analyze_batch`. Several tests below are flagged **load-bearing** per -``.claude/rules/testing.md``: reverting the production change they +``docs/development/testing.md``: reverting the production change they guard makes them fail. Treat them as test-via-revert candidates before deleting or weakening their assertions. """ diff --git a/big-code-analysis-py/tests/test_sarif.py b/big-code-analysis-py/tests/test_sarif.py index 28085976c..34ce1a3d7 100644 --- a/big-code-analysis-py/tests/test_sarif.py +++ b/big-code-analysis-py/tests/test_sarif.py @@ -983,47 +983,6 @@ def test_to_sarif_matches_cli_check_for_nargs_own_parameter_list( assert cli_rows == want, f"CLI at nargs={limit}: {cli_rows!r}" -def test_to_sarif_matches_cli_check_for_a_primary_constructor( - bca_binary: str, tmp_path: Path -) -> None: - """A Kotlin or C# primary constructor opens a function space named - after its class (#1828), so the binding — which walks the serialized - tree and reads ``nargs.value`` at every Function space — reports it - exactly where ``bca check`` does. Before #1828 neither front-end - emitted anything for a six-parameter ``data class``. - """ - fixtures = { - "d.kt": ( - "data class D(val a: Int, val b: Int, val c: Int,\n" - " val d: Int, val e: Int, val f: Int)\n", - "D::D", - ), - "c.cs": ( - "public class C(int a, int b, int c, int d, int e, int f)\n" - "{\n" - " public int Sum() => a + b + c + d + e + f;\n" - "}\n", - "C::C", - ), - } - for name, (text, symbol) in fixtures.items(): - src = tmp_path / name - src.write_text(text) - analyzed = bca.analyze(src) - assert analyzed is not None, f"{name} must not be skipped" - ctor = analyzed["spaces"][0]["spaces"][0] - assert (ctor["kind"], ctor["metrics"]["nargs"]["value"]) == ("function", 6), ctor - py_rows = _sarif_rows( - _parse(bca.to_sarif(analyzed, thresholds={"nargs": 5}))["runs"][0]["results"] - ) - cli_rows = _sarif_rows( - _cli_check_sarif(bca_binary, src, threshold="nargs=5")["runs"][0]["results"] - ) - want = [(1, symbol, "nargs 6 exceeds limit 5")] - assert py_rows == want, f"binding on {name}: {py_rows!r}" - assert cli_rows == want, f"CLI on {name}: {cli_rows!r}" - - def _sibling_set_sizes(space: FuncSpaceDict) -> list[int]: """Every sibling-set size in ``space``'s subtree, its own child list first. Lets an ordering test state the shape it needs, so a trimmed diff --git a/big-code-analysis-web/src/web/server_tests.rs b/big-code-analysis-web/src/web/server_tests.rs index b7fbb2adf..abcdc20c2 100644 --- a/big-code-analysis-web/src/web/server_tests.rs +++ b/big-code-analysis-web/src/web/server_tests.rs @@ -3317,7 +3317,7 @@ async fn vcs_error_kind_maps_each_client_variant_to_a_distinct_token() { /// an entry that advertises a token the server never sends. /// /// This reads a published document, not the crate's own source, so it is -/// not the restated-`matches!()` pattern `.claude/rules/testing.md` +/// not the restated-`matches!()` pattern `docs/development/testing.md` /// bans: the drift is between two artifacts, and neither can enumerate /// the other. /// diff --git a/docs/development/agent_isolation.md b/docs/development/agent_isolation.md new file mode 100644 index 000000000..0c521bfbc --- /dev/null +++ b/docs/development/agent_isolation.md @@ -0,0 +1,100 @@ +# Isolating agent work in worktrees + +How a skill that fans work out to child agents keeps each one in its own +checkout, verifies it got there, and cleans up. It is for the +orchestrating skills under `.claude/skills/` (`batch-fix`, +`improve-crate`, `cleanup-crate`, the audits) and for anyone running +them from OpenCode or Claude Code. The shared rules in +[`AGENTS.md`](../../AGENTS.md) ("Worktrees") apply to every agent; this +document is the protocol those skills follow to honour them. + +## Three modes + +- **Worktree mode**: each mutating child gets its own + [git worktree](https://git-scm.com/docs/git-worktree) and branch, so + children can run in parallel. Choose it when the runtime can start a + child in a directory the orchestrator names or allocates. +- **Branch mode**: mutating children share the orchestrator's working + directory and therefore run strictly one at a time, each on a + feature branch. Choose it when a child cannot be started elsewhere. +- **Shared read-only mode**: children that write nothing (the audit and + scan skills) may run in parallel in one checkout. No child switches + branches, cleans or resets while a reader is running, and the + orchestrator verifies `git status --porcelain` is empty before and + after the fan-out. + +The orchestrator decides the mode and tells each child which one it is +in. A child never infers it from its path. + +## Worktree mode protocol + +1. **Allocate.** Either the orchestrator creates the worktree and + branch at the revision the child should start from + (`git worktree add -b `, or OpenCode's + worktree facility) and records the absolute path, branch and base + commit; or the runtime allocates one at launch (in Claude Code, + `isolation: worktree` on the Agent call, or a subagent definition + carrying it). Never both: a preallocated path handed to a launch + that allocates its own produces two worktrees and a child that + cannot match its prompt. +2. **Hand over.** With orchestrator allocation, put the absolute path, + the branch and the base commit in the child's prompt and start the + child there (move its session into the worktree, or require absolute + paths on every file tool). With runtime allocation, the prompt names + the base commit and the branch pattern only; the child reports its + `git rev-parse --show-toplevel`, `--abbrev-ref HEAD` and + `rev-parse HEAD` before writing anything, and proceeds only if the + orchestrator's instructions already cover what it reports (the base + commit matches, the branch is not `main` / `master` / detached, the + root is not the orchestrator's directory). +3. **Verify before writing.** Whichever allocation was used, the child + aborts without editing anything unless its root and branch are the + ones it was told or was told to expect. `main`, `master` and a + detached `HEAD` are always disallowed. +4. **Stay put.** The child does not switch branches, `cd` to another + checkout, or write outside its worktree. Every file-tool call takes + an absolute path under the verified root: a relative path resolves + against the session's directory, which may be the orchestrator's. +5. **Bootstrap once.** A fresh worktree has neither the integration + corpora nor the Python venv; `make worktree-setup` is idempotent and + runs before the first `make pre-commit`. +6. **See earlier work.** A worktree created from the base commit cannot + see what the orchestrator has merged since. When later waves depend + on earlier ones, the child merges the integration branch first + (`git merge --no-edit`); git permits merging + from a branch another worktree has checked out, only not checking it + out. +7. **Clean up by the owner, run by the user.** A child never removes or + prunes worktrees. The orchestrator that created a worktree with + `git worktree add` removes it after merging or discarding its branch; + `git worktree remove` is denied to agents by this repository's + permission rules (a deny, not an ask, so no per-run approval exists), + so the orchestrator lists the worktrees it created, with path, branch + and merged / unmerged / dirty state, in its final summary and the + user removes them. A runtime-allocated worktree is the runtime's to + remove; report any it leaves behind. A worktree the + orchestrator did not create is left alone. + +Keep at most six worktree children in flight: each is a full checkout +with a dozen crate manifests, and unbounded fan-out has filled the disk +before. + +## Branch mode protocol + +1. The orchestrator verifies a clean tree (`git status --porcelain` is + empty) before starting each child, and owns cleanup between children. +2. It creates the child's feature branch from the integration branch's + current tip and names it in the prompt. +3. The child verifies its branch exactly as in worktree mode, and never + runs `git checkout`, `git switch`, `git clean` or `git reset` itself. +4. Mutating children run one at a time. Launching two against one + directory corrupts both. + +## Merging a child's branch + +Merge only after every child in a wave has returned and only into a +clean integration checkout. `git checkout ` refuses +while another worktree holds that branch, which means a child is still +running: wait, do not repair. A successful `git merge` is not evidence +the tree was idle; it refuses only when it would overwrite an +uncommitted change to a file it touches. diff --git a/docs/development/benchmarking.md b/docs/development/benchmarking.md index 84d051ab0..39e45f11d 100644 --- a/docs/development/benchmarking.md +++ b/docs/development/benchmarking.md @@ -954,7 +954,7 @@ Interleave instead. Keep a binary per side. A paired series is usually compared across sessions, and the base binary is slow to rebuild, so the copy goes under `/var/tmp/bca//` rather than `/tmp` (see -[`.claude/rules/temp-files.md`](../../.claude/rules/temp-files.md)): +[`AGENTS.md`](../../AGENTS.md), "Temporary files"): ```bash mkdir -p /var/tmp/bca/ diff --git a/docs/development/formatting.md b/docs/development/formatting.md new file mode 100644 index 000000000..e4ff22ffa --- /dev/null +++ b/docs/development/formatting.md @@ -0,0 +1,79 @@ +# Formatting beyond `cargo fmt` + +Two formatting rules `cargo fmt --check` cannot enforce: match arms +rustfmt silently declines to format, and where explanatory comments go +when code is consolidated behind a `macro_rules!`. It is for anyone +editing a file `make rustfmt-bail` names or writing a macro. + +## Match arms rustfmt declines to format + +A comment inside a match *pattern* (between the pattern and its `=>`, +or between `|` alternatives) makes rustfmt emit the whole enclosing +match verbatim, with no diagnostic and `cargo fmt --check` still +exiting 0. The blast radius is the match, not the file: statements +around it still format, which makes the file look unaffected. Macro +bodies are not exempt. + +`make rustfmt-bail` (`utils/check-rustfmt-bail.py`, in `make lint`, +`make pre-commit` and `make ci`) measures it: it over-indents every +match arm, pipes each file through rustfmt on stdin, and counts the +arms that come back untouched. Per-file counts live in +`.rustfmt-bail-baseline.txt`; increases fail, decreases ratchet with +`--update`. `./utils/check-rustfmt-bail.py --show ` names each +stuck arm, which is what to run before editing. + +An entry has one of three causes, and the gate cannot tell them apart: + +1. A comment inside a match pattern. Hoist it above the arm; never + delete it. The per-arm rationale in the classifier tables is + load-bearing. +2. A `macro_rules!` body rustfmt cannot parse (a metavariable in a + non-Rust position, as in `mk_langs!`). Permanent; the baseline + header lists the known entries. +3. An arm header wider than `max_width`. Wrap it. + +Do not open a campaign to clear the existing bails: the remaining +cause-1 entries are section comments inside long or-patterns, and +every way of buying the formatting back makes the table harder to +read. Hoisting a single comment with nothing to split is welcome when +you are already in the file. + +After any bulk or scripted edit under `big-code-analysis-ast/src/getter/` +or `src/metrics/`, read the diff rather than trusting the gate, and +check line length directly: + +```bash +awk 'length > 100 {print FILENAME":"FNR" ("length")"}' +``` + +## Comments at macro call sites + +When N near-identical predicates or impls are consolidated behind a +`macro_rules!`, keep the macro body structural and put each call's +language-specific rationale directly above the invocation: + +```rust +// PHP's String2 alias is the `string` *type* keyword, excluded so +// `find string` reports literals; String3 is the hidden `_string` +// supertype (defensive arm + drift marker in the tests below). +impl_simple_is_string!(Php, String, String3, …); +``` + +The macro's own `///` doc describes the shape it emits, never per-call +particulars. Call-site comments survive a later refactor of the macro; +comments inside the body do not. + +A `role_table!` invocation is the largest call site in the tree, and +the same rule applies per row. Where each kind of rationale lives: + +| What it explains | Where | +| --- | --- | +| The grammar fact a row encodes: what the nodes are, how they nest, why an alias is listed or left off | `//` comment above the row | +| Why a `gated_by` / `text_gated_by` gate exists and what it reads | the `///` doc on the gate `fn` | +| Why an owner is `under [..]` / `not_under [..]` its parents | `//` comment above the row | +| Why a considered kind is not on the row | the `excludes [K "why"]` string; the coverage gate prints it | +| Which consumer reads which projection, and why it counts there | at the consumer, in `big-code-analysis` | +| What `owns`, `pays`, `opens` mean | `roles/mod.rs` only | + +A row comment that explains a consumer's policy is wrong the day the +consumer changes; keep the grammar fact and the policy apart. diff --git a/docs/development/grammar_dispatch.md b/docs/development/grammar_dispatch.md new file mode 100644 index 000000000..dc820395e --- /dev/null +++ b/docs/development/grammar_dispatch.md @@ -0,0 +1,186 @@ +# Grammar dispatch checklist + +Every per-language `Checker` predicate, `Getter` classifier and metric +arm asks a question of a node's kind. Membership (which kinds own a +construct, which tokens pay for it) is declared once per language in +`big-code-analysis-ast/src/roles/.rs` and read through the +predicates `role_table!` emits. The module doc of `roles/mod.rs` is the +reference for the row grammar, what a table emits, how a consumer reads +a row, and the section "What the mechanism cannot see". Read that +section first; this checklist is the manual half it describes. + +A kind list is a coverage claim, not a specification. The compiler +cannot tell you it is incomplete, and a metric that scores a valid +construct as zero looks exactly like a construct that legitimately +scores zero. The three role gates (`make role-census`, `role-coverage`, +`role-bypass`) and the derived parity suite catch a new unaccounted +kind, a restated list inside the consumer boundary, and two consumers +disagreeing on a corpus node. None judges whether a row's membership is +right. Apply the checklist whenever you add a language, bump a grammar +pin, add a kind to a row, or copy a row or gate from a sibling. + +## 1. Match every aliased variant + +tree-sitter emits one `kind_id` per grammar position, so a rule used in +N positions is `PrimitiveType`, `PrimitiveType2`, … with one `kind()` +string. Matching only the unsuffixed one returns wrong numbers. List or +exclude (with a reason) every numeric-suffix variant: + +```bash +rg 'Lang::([A-Za-z]+)\b' big-code-analysis-ast/src/getter/ big-code-analysis-ast/src/checker/ \ + big-code-analysis-ast/src/alterator.rs src/spaces.rs src/metrics/ +``` + +Put a kind list a role owns on its row; a list several languages share +is a `..name!()` fragment (`roles/c_family.rs`, `js_family.rs`, +`tcl_family.rs`). `make role-coverage` catches an id no row claims; it +does not catch an alias missing from the intended row, so this +inventory stays manual. With many aliases, prefer one `node.kind()` +string comparison over enumerating them. + +After bumping a grammar pin, bump the root `Cargo.toml` and +`enums/Cargo.toml` together and regenerate the enum before anything +else: + +```bash +cargo run --manifest-path ./enums/Cargo.toml -- -lrust -o ./big-code-analysis-ast/src/languages +``` + +Stable named-node ids are no evidence the anonymous ids held; spot-check +a known anonymous token with `bca dump` against the enum. + +## 2. Skip hidden-rule variants, but mark them + +A rule whose name begins with `_` is hidden: the variant exists in the +enum and the parser never emits it. Check the `Lang::Variant => "name"` +arm in `language_.rs` before listing a look-alike. Keep the +defensive arm and pin its hidden status with a +`!ast_has_kind_id(&parser, Lang::HiddenVariant as u16)` assertion, so +a grammar that later promotes the rule changes behaviour visibly. + +## 3. Address children by role, never by index + +Use `child_by_field_name("condition")` over `node.child(1)` for any +slot the grammar can precede with an optional preamble (an +init-statement, `constexpr`, a named-argument label, a BLANK ALIAS +body). When no field exists, iterate `named_children` and pick by role, +naming the variant set you verified in a comment. A new dispatcher arm +needs one fixture per optional preamble the grammar permits. + +## 4. Re-derive a sibling's gate against the target grammar + +The semantic role transfers across languages; the node kind does not. A +copied child-kind gate compiles and matches nothing. `is_else_if` is +the largest example: every language answers through its `ElseIf` row, and +the strategy is the row's gate. Derive the current table rather than +trusting a copy: + +```bash +rg -n 'ElseIf \{' big-code-analysis-ast/src/roles/*.rs +rg -o 'else_if_(parent_clause|prev_sibling)_gate!\(\s*(\w+)' -r '$1 $2' big-code-analysis-ast/src/roles/ --no-filename | sort +rg -n 'ElseIf \{ absent' big-code-analysis-ast/src/roles/*.rs +``` + +| Strategy | Emitter | Languages (re-derive; this moves) | +| --- | --- | --- | +| owner's parent is the else-clause | `else_if_parent_clause_gate!` (`roles/control_flow.rs`) | C, Cpp, Mozcpp, Objc, Rust, Javascript, Mozjs, Typescript, Tsx; PHP's `else if` by its own gate | +| owner's previous sibling is the `else` keyword | `else_if_prev_sibling_gate!` | Csharp, Groovy, Java, Kotlin | +| owner's parent is the outer `if` (no clause node) | hand-written gate on the row | Go | +| the clause node *is* the else-if (`pays_itself`) | none needed | Bash, Irules, Lua, Perl, Ruby, Tcl; PHP's `elseif` | +| owner is the sole statement of the `else:` block | hand-written gate; Checker is `Branch ∧ ElseIf` | Python | +| `absent` row, trait default `false` | — | Elixir | + +The jump label is the same lesson in miniature: `StatementIdentifier` +in the JS family, `Identifier` in Java and Groovy, `LabelName` in Go, +`Label` in Perl. + +A gate that is only the owner's parent kind is spelled on the row as +`K(under [..])` / `K(not_under [..])`, not as a `fn`; the `ElseIf` +emitters stay because they read more than the parent. A consumer's +projection of an owner's child is a named `fn` beside the table with a +row test, not a row. Dump the construct in the target grammar before +reusing a sibling's predicate, and add a fixture that exercises the +gated branch. + +## 5. One kind per operator; parent-guard compound leaves + +A wrapper node containing its keyword token (`await a()`) must be +classified once, or Halstead counts every occurrence twice. Verify the +stream with `bca ops`. The inverse: a compound operator (`not in`) +wraps leaves that are valid operators elsewhere; classify the compound +and return `Unknown` for the inner leaf only when its parent is the +compound. Any predicate listing both a container and a kind it can +contain double-counts (Ruby `Lambda | Block | DoBlock`). On a row, +`owns` and `pays` are disjoint by construction; a consumer that wants +both reads `pays_at_wrapper` and `pays_at_leaf` explicitly. + +## 6. Narrow a dispatch set with a gate, never by deletion + +Deleting a kind from `is_func` / `is_func_space` to stop an over-count +regresses its childless variant to zero. Gate the arm on child presence +and keep `is_func`, `is_func_space` and `get_space_kind` on the same +predicate. When a wrapper/leaf pair double-counts, the keeper is the +node present for every spelling, verified with `bca dump` on valid and +on recovery input: `node-types.json` describes the well-formed grammar +only, and an `ERROR` root routinely holds the leaf with no wrapper. +Where neither choice strands a node, keep the node whose span is the +operand. Skip invented zero-width tokens by `start_byte() == end_byte()`, +not `is_missing()`, with a malformed fixture per grammar. Decide a +grammar-reachable but language-invalid shape on what it buys for valid +input; document the gap instead of pinning numbers for invalid input. +Before writing an arm, list every `(kind, parent)` pair the dump +produced for the construct and give each a gate alternative or a +reason; dump the construct alone, since a packed fixture recovers +differently. + +## 7. Walk the sibling predicates for parity + +`is_string` ↔ `get_op_type` (operands), `is_call` ↔ `get_op_type` +(operators), `is_func_space` ↔ each metric's body walker, and +`is_func_space` ↔ `get_space_kind` all classify the same nodes. The +last pair fails quietly: a space the walker opens but the getter leaves +`Unknown` is not a member scope, so it serialises no `npm` / `npa` +block and nothing diffs. Cross-walk the `_with_code` spellings, which +are what the walk calls: the byte-less defaults forward to them and +agree everywhere except the languages that override (Elixir's +keyword-text containers, Ruby's lambda-body blocks), which is exactly +where the answer matters. `tests/parity/ops_metrics_space_parity.rs` +keeps `bca ops` and `bca metrics` opening the same spaces. + +## 8. Anchor a default/fallback exclusion to the construct + +A `default` / `else` / `_` arm is +0 only when the construct's own node +already paid the increment; the same kind can be +0 under `case` and ++1 under `begin`/`rescue`. Never blanket-suppress a shared token. Where +ABC and cyclomatic must agree, reuse cyclomatic's gate and pin +`abc.conditions == cyclomatic() - 1` per space. + +## 9. Watch for control flow with no dedicated kind + +In command-dispatched grammars (Tcl, iRules, shells) control flow can +parse as a generic `command`. Recognise it by the leading word and +locate sub-parts by structural position, not a fixed index. + +## 10. Read the bytes for identity questions + +Shape says "attribute access"; only bytes say whose. Compare +`code.get(start..end)`, never `to_string_lossy()`. When a language +encodes semantics in identifier text, plan the `&[u8]` widening of +`compute` with the implementation. + +## 11. Give one input to each independent path + +When two independent paths sum into one field, a fixture either path +can classify hides a dead path. Write a fixture only the path under +test can classify (a bare `if (x)` for a walker arm, an empty container +for a descending arm) and perturb that arm alone. + +## When you fix one language, sweep the rest + +Every item above is a per-language failure that usually exists in +siblings. Build the audit table by dumping the construct in each +sibling grammar, not by searching for a kind name (a §9 construct has +no kind to find). Land the sibling fixes in one commit and anchor any +known-wrong case with `FIXME(#NNN)`. A `LANG` variant that owns no file +extension (`mozcpp`) gets no corpus coverage; pin it with a parity test +against its extension-owning sibling. diff --git a/docs/development/lessons_learned.md b/docs/development/lessons_learned.md index 6cb22fb6d..5a9636718 100644 --- a/docs/development/lessons_learned.md +++ b/docs/development/lessons_learned.md @@ -14,13 +14,13 @@ that a bug class is real; a rule is what you follow without re-reading the evidence. Three rule files carry the checklists these lessons produced, and entries below point at them rather than restating them: -- [`.claude/rules/grammar-dispatch.md`](../../.claude/rules/grammar-dispatch.md) +- [`docs/development/grammar_dispatch.md`](grammar_dispatch.md) — per-language `match node.kind_id()` arms, aliased variants, child addressing, cross-predicate parity. -- [`.claude/rules/testing.md`](../../.claude/rules/testing.md) — +- [`docs/development/testing.md`](testing.md) — test-via-revert, perturbation, coverage-vs-protection, harness normalisation, assertion shapes that are wrong by construction. -- [`.claude/rules/formatting.md`](../../.claude/rules/formatting.md) — +- [`docs/development/formatting.md`](formatting.md) — rustfmt's silent bail on in-pattern comments. Project policy lives in [`AGENTS.md`](../../AGENTS.md). Where a lesson's @@ -160,7 +160,6 @@ number and the higher number stays as a redirect. | [114](#114-a-fallback-that-rebuilds-what-you-withheld-answers-as-if-you-had-not) | A fallback that rebuilds what you withheld answers as if you had not | | [115](#115-sharing-the-rule-left-the-list-at-every-caller-sharing-the-list-leaves-the-judgement) | Sharing the rule left the list at every caller; sharing the list leaves the judgement | | [116](#116-a-dead-code-census-describes-the-target-it-was-taken-on) | A dead-code census describes the target it was taken on | -| [117](#117-a-spaces-own-value-is-everything-the-walk-folds-into-it) | A space's own value is everything the walk folds into it | --- @@ -205,7 +204,7 @@ no-ops — they inherit a working trait default; only the named-trait arms ## 2. Tree-sitter aliases one rule across many kind_ids — match every variant **Lesson:** Follow -[`grammar-dispatch.md` §1](../../.claude/rules/grammar-dispatch.md) — +[`grammar-dispatch.md` §1](../../docs/development/grammar_dispatch.md) — after any grammar bump, regenerate the enum *first* (both manifests in lockstep), then confirm every numeric-suffix variant of every matched rule is listed or excluded with a comment. Named-node stability is not @@ -466,7 +465,7 @@ regression. never `is_ok()` or "the section rendered". When fixing a bug, write the test against the function whose contract is wrong, not against a wrapper that may filter the bug-triggering input. -[`testing.md`](../../.claude/rules/testing.md) carries the mechanical +[`testing.md`](../../docs/development/testing.md) carries the mechanical form: the harness-normalisation map, the assertion shapes that are wrong by construction, and the perturbation procedure that proves a test can fail. @@ -575,7 +574,7 @@ not `Unit`, anchored to the parser's full input range. *structure* rather than node kind, examine the grammar's `node-types.json` or parse a representative snippet to confirm how the construct is actually represented. The per-family table is in -[`grammar-dispatch.md` §4](../../.claude/rules/grammar-dispatch.md). +[`grammar-dispatch.md` §4](../../docs/development/grammar_dispatch.md). Treat a stub returning a constant as a to-do, not a finished implementation, and add a test that would fail if it were a no-op — an `else if` chain must score lower than the same chain with independent @@ -597,7 +596,7 @@ increment inflated the penalty for everything nested inside. The fix adopted Kotlin's strategy (`previous_sibling().kind_id() == Else`), and the post-fix audit of the 16 implementations then in the tree produced the first strategy table. That table is now maintained in -[`grammar-dispatch.md` §4](../../.claude/rules/grammar-dispatch.md) with +[`grammar-dispatch.md` §4](../../docs/development/grammar_dispatch.md) with the command to re-derive it — the #115 version went stale within a few language additions, which is lesson 84 in miniature. @@ -1349,7 +1348,7 @@ reverting the `InterfaceDeclaration` arm would pass them vacuously too. **Lesson:** Never string-match the codebase's own source in a test. The rule and its three ranked alternatives are in -[`testing.md`](../../.claude/rules/testing.md) — construct a parseable +[`testing.md`](../../docs/development/testing.md) — construct a parseable input and assert the parse-tree consequence; failing that, document the contract at every production call site; failing that, design a compile-time check (an exhaustive `match`, a `const`-evaluated @@ -1491,7 +1490,7 @@ only aliases unobserved under every context probed. **Lesson:** When refactoring or extending a per-language classification predicate, walk the *other* predicates that classify the same nodes. The minimum cross-walk is in -[`grammar-dispatch.md` §7](../../.claude/rules/grammar-dispatch.md). The +[`grammar-dispatch.md` §7](../../docs/development/grammar_dispatch.md). The reusable diagnostic is a parsed fixture asserting **both** predicates agree: parse a source containing the node, locate every occurrence by kind_id, and assert each predicate's verdict per occurrence. @@ -1656,7 +1655,7 @@ removing the wildcard, which does not compile. **Lesson:** Gate the entire `fn`, never an inner block — the rule and its inverse trap are in -[`testing.md`](../../.claude/rules/testing.md). An inner-block `#[cfg]` +[`testing.md`](../../docs/development/testing.md). An inner-block `#[cfg]` compiles to an empty body off-target, and an empty `#[test]` is a *passing* test: the harness reports green with zero assertions run. The function-level form hides the test instead. @@ -1955,7 +1954,7 @@ capture, so the syntax matches the semantics; or wire it through the body, so the syntax becomes load-bearing and disagreement is a compile error. Pick the easier one. When the macro is hand-rolled because variants need bespoke per-arm logic, drop the capture and lean on -[`macro-comments.md`](../../.claude/rules/macro-comments.md) to preserve +[`formatting.md`](formatting.md) to preserve the per-call narrative at the call site. Decorative is not neutral: a call site reading `(Cpp, tree_sitter_cpp)` @@ -2155,7 +2154,7 @@ languages now classify the `=` from its parent chain. `node.child(idx)` for any slot whose grammar permits an optional preamble. The full rule, including the preamble inventory and the fallback when no field is exposed, is in [`grammar-dispatch.md` -§3](../../.claude/rules/grammar-dispatch.md). The minimum new-test bar +§3](../../docs/development/grammar_dispatch.md). The minimum new-test bar for a dispatcher arm is **one fixture per optional preamble the grammar permits** — not just the form the corpus already has. When migrating a slot from positional to field addressing, dump the AST for *each* @@ -2396,7 +2395,7 @@ percent of the wall, and operator wrapping reusable leaves, classify the compound and parent-guard the leaves to `Unknown` under that compound only — a blanket suppression drops every legitimate standalone use. See -[`grammar-dispatch.md` §5](../../.claude/rules/grammar-dispatch.md). +[`grammar-dispatch.md` §5](../../docs/development/grammar_dispatch.md). This is the mirror image of lesson 50: there two independent paths summing one field *masked* a zero; here one arm listing two aliases of @@ -2523,7 +2522,7 @@ failed on the branch, which is the definition of a regression. another language, dump the AST for the construct in the *target* grammar and confirm the gating kind appears there — the semantic role transfers, the node kind does not. The per-family table is in -[`grammar-dispatch.md` §4](../../.claude/rules/grammar-dispatch.md). Add +[`grammar-dispatch.md` §4](../../docs/development/grammar_dispatch.md). Add a fixture exercising the gated branch (a labeled jump, not a plain one) and test-via-revert that branch alone; a suite of only unlabeled inputs proves nothing. @@ -2615,17 +2614,6 @@ same shape, fixed the same way (#1356) — there the predicate keys on the node's own kind, because a method is always a `method_definition` and no parent-kind list can be completed. -**Opening a space re-parents what is counted inside it** (#1828). A -Kotlin `val` parameter property was counted at its own `class_parameter` -visit and landed on the class because nothing between them opened a -space; the day the primary constructor opened one, the same count landed -on the constructor and left the class's own `npa` short by every -parameter property — 0 for a data class with no body properties. Count -a child's contribution where its owner is on the stack — Kotlin's -class-declaration visit; TypeScript scans a constructor's parameter -properties from the class body for the same reason — not where the -child happens to be visited. - --- ## 64. A default/fallback-arm exclusion is per-construct @@ -2635,7 +2623,7 @@ kind. Confirm the construct's own node pays the nesting/decision increment — so its default really is redundant — before suppressing, and confirm the shared node kind is not also serving a chain construct where the arm is a legitimate +1. See -[`grammar-dispatch.md` §8](../../.claude/rules/grammar-dispatch.md) and +[`grammar-dispatch.md` §8](../../docs/development/grammar_dispatch.md) and lesson 11 for the cross-metric agreement rule. A construct can offer two candidate defaults; exactly one is free. Decide by counting reachable paths, and write the fixture that carries both arms — one that carries @@ -2721,7 +2709,7 @@ the arm fires, and add it in every layout the grammar splits differently — a construct with no node of its own has no fixed shape either, so the same source can reach the recogniser as one command or as several depending on where the newlines fall. See -[`grammar-dispatch.md` §9](../../.claude/rules/grammar-dispatch.md). +[`grammar-dispatch.md` §9](../../docs/development/grammar_dispatch.md). The gap is not a missing enum arm — the *kind* the dispatcher would need does not exist for that construct in that grammar at all. Cousin of @@ -3376,7 +3364,7 @@ over the whole suite a firing probe fails its target and cargo stops at the first one that fails), enumerates which grammars really reach a supposedly-unreachable branch, once a direct test has shown the probe -can fire ([`testing.md`](../../.claude/rules/testing.md), "Prove a +can fire ([`testing.md`](../../docs/development/testing.md), "Prove a reachability probe can fire"). Treat "this per-part value exceeds the whole" as a hard invariant worth asserting outright. @@ -3403,7 +3391,7 @@ tree-sitter-bash reaches the same shape. The input class was unreachable from every in-tree harness, which is why it survived — see the normalisation map in -[`testing.md`](../../.claude/rules/testing.md). The documented rustdoc +[`testing.md`](../../docs/development/testing.md). The documented rustdoc example at `src/spaces.rs` was itself demonstrating the bug in the published docs. @@ -3448,11 +3436,8 @@ gates the build, so anyone budgeting from the comment got it wrong. The rest were a test's exclusion rationale, a changelog's two scope claims and a benchmarking doc's count. Later instances: a Go ABC test citing "the Rust/Java rule" for a number backwards in all three languages -(#1278), three docs-sweep issues each prescribing a fix that was wrong -by the time it ran (#1711, #1712, #1713), and a review finding that a -`sealed` class may write `public constructor` — a fixture pinned that -invalid program until the compiler source said `private` or -`protected` only (#1828). +(#1278), and three docs-sweep issues each prescribing a fix that was +wrong by the time it ran (#1711, #1712, #1713). **A hedge survived two reviews because it admitted uncertainty** (#1417). One of the three sets `Stats::settle_excluded_rows` subtracts @@ -3500,7 +3485,7 @@ no test can see a read that changes no answer. **Lesson:** Never accept a coverage percentage as evidence a line is tested — it is evidence the line is *reached*. The full procedure, and the covered-count-not-percentage rule, are in -[`testing.md`](../../.claude/rules/testing.md). The general shape is that +[`testing.md`](../../docs/development/testing.md). The general shape is that **any scalar summary of a set** — coverage percent, test count, file count, snapshot count — can hold steady or improve while the set underneath it changes; compare the sets themselves whenever the @@ -3574,7 +3559,7 @@ reaches it; the pin moved to the row, asked with the inner node's chain. **Lesson:** In a test helper, normalise the **expectation**, never the **observation** — the rule and the removal check are in -[`testing.md`](../../.claude/rules/testing.md). Where a helper already +[`testing.md`](../../docs/development/testing.md). Where a helper already normalises, remove the normalisation and count the failures: none means the dimension is untested, and a large number means you just recovered a guard across the whole caller list for free. @@ -3611,7 +3596,7 @@ tests under `ops` and `output::dump_ops`. **Lesson:** Review the selector as carefully as the assertion, and treat "how many rows did this match" as part of the test — see -[`testing.md`](../../.claude/rules/testing.md) for the assertion shapes. +[`testing.md`](../../docs/development/testing.md) for the assertion shapes. When a test's name states a property, check that the rows it selected are *capable of violating* that property; if they are not, the test is decoration regardless of how specific its assertion looks. @@ -3663,7 +3648,7 @@ and re-running it is exactly what a careful person does before quoting it. **A `=>` regex over raw Rust counted other languages' lambdas** (#1136). -The probe in `.claude/rules/formatting.md` matched match-arm headers by +The first hand-rolled probe (since replaced by `utils/check-rustfmt-bail.py`) matched match-arm headers by regex, so every JS, C# and TypeScript fixture embedded in a Rust string literal registered as a match arm. `src/metrics/nom.rs` reports **16** arm lines to the raw regex and **0** once string spans are excluded; it @@ -3755,11 +3740,7 @@ invalid source `^(int a,,)` went 1 → 2 and `^({ int x; })` went 0 → 1. Both were kept, because the function channel already reported the same through the same helper; the block arm had been the one caller answering differently. Recording that in the arm's comment is what stops the next -reader filing it as a regression. The same open filter counted C#'s -`params int[] xs` as 3 — the hidden `_parameter_array` lands its pieces -beside the `parameter` nodes — from the day C# joined it until a -positive `parameter | params` count pinned the rule hidden (#1828, -lesson 34). +reader filing it as a regression. **One token, several grammatical roles — a denylist admits the role nobody listed** (#1274, #1280, #1297, #1383). A bare `<` is a @@ -3895,7 +3876,7 @@ with or without the memo** (#1602, #1697 cost audit). The probe's comments sat inside the list; the scan walked the siblings after it; the probe read 1.0 with the memo and 1.0 without. The proof the probe discriminates is the same as this lesson's: remove the memo and watch -the exponent leave the bound (`.claude/rules/testing.md`, "Validate a +the exponent leave the bound (`docs/development/testing.md`, "Validate a scaling probe by removing what it prices"). **Production readers were classified as tests** (#1777). PR #1780 @@ -4075,11 +4056,11 @@ already listed `go` among the helper's needs (#1528). rustfmt re-indent, so the sweep ran the unperturbed code and reported `0 -> []` for arms that had each failed a test an hour earlier. The predicate it answered was "does *this file* fail a test", and the file -was the original; `.claude/rules/testing.md` now asks for `old != new`. +was the original; `docs/development/testing.md` now asks for `old != new`. A dump read for the parent you came looking for answers an equally narrow question: #1706's `catch (var e)` showed its parent only once dumped alone, and #1720's fourth `for` parent, `abstract_type`, only in -the review's one-line dump (`.claude/rules/grammar-dispatch.md` §6). +the review's one-line dump (`docs/development/grammar_dispatch.md` §6). **"No helper was over the raised limit" measured who offends, not who is no longer guarded** (#1747). A path-scoped `cyclomatic = 40` over @@ -4442,7 +4423,7 @@ either way) and, for a seam that reaches the predicate through a derivation, perturb the derivation as well as the walk. The failure hides in the way the forwarding-default trap in -`.claude/rules/grammar-dispatch.md` section 7 does: the predicate reads +`docs/development/grammar_dispatch.md` section 7 does: the predicate reads as memoised at its definition, the walk reads as lending at its construction, and the drop sits in a third place neither reader opens. Until a counter test exists on the seam that reaches the predicate @@ -4601,7 +4582,7 @@ hands each child `[conditional]`; `loc/c-conditional-per-struct-depth` prices the independent-at-depth axis. At the default depths the copy read 1.50 — *on* the `<=` bound, not past it, so the probe as first shipped would not have gone red — and at the next doubling 1.81 against -0.94 fixed, which is where its sizes now sit (`.claude/rules/testing.md`, +0.94 fixed, which is where its sizes now sit (`docs/development/testing.md`, "Validate a scaling probe by removing what it prices"): a probe is validated at the sizes it ships with. It nests structs because nested C++ namespaces are quadratic under `loc` on `main` (#1767, found by @@ -4976,7 +4957,7 @@ Run the suite with CI's explicit artifacts as well as its defaults. After production changes a routed call's path or arguments, repeat the mutation check: the assertion can still pass after the double stops recording the call. See the perturbation procedure in -[`testing.md`](../../.claude/rules/testing.md). +[`testing.md`](../../docs/development/testing.md). An overly broad match can apply a fake's handling to a real artifact. A stale match can let a call bypass the double and its recording logic. @@ -5155,7 +5136,7 @@ from the row. **What stays manual, and where it is written.** The one list is the "What the mechanism cannot see" section of `big-code-analysis-ast/src/roles/mod.rs`'s module doc; AGENTS.md, the -rules under `.claude/rules/` and the book link to it, and so does this +guides under `docs/development/` and the book link to it, and so does this lesson. Each of its items had been a separate gate's "cannot see" header before #1701; consolidating them found two of the bypass lint's items missing from the first draft of the list, which is why @@ -5215,42 +5196,3 @@ silences every partial-feature build — and "no warnings" cannot tell a live lint from a muted one (lesson 80's shape). --- - -## 117. A space's own value is everything the walk folds into it - -**Lesson:** Before a gate, a threshold or a report admits a new space -kind, measure that kind's *own* value on inputs that hold none of the -construct the admission is for. An "own" accessor sums whatever the -walk bills to the innermost open space — `own_args()` is -`function_args() + closure_args()`, so it holds the parameters of every -lambda the language leaves spaceless inside that space — and a -container's own value can therefore be non-zero with no constructor -written. Decide where a new count lands on the measured population, -not on what the number is named. If the construct warrants a space of -its own, the gate, the report and the suppression binding select -Function rows and follow; the metrics that count, attribute or divide -still need auditing one by one. - -The number is plausible either way, which is what hides it. A class -that reads `nargs 6` from three two-parameter comparator fields and no -constructor is not a finding any per-function test asks about — the function tests -read function rows — and a plan that says "a container's own count can -only be its constructor's" reads as reasoning rather than as the -assumption it is. Nothing in the per-space tests contradicts it until -one is written against the kind being admitted. - -**The container route for primary constructors** (#1828). A Kotlin or -C# primary constructor opened no space, so its parameters counted -nowhere. The first design billed them to the class and widened the -`nargs` gate to containers, on the premise above. Measured before -implementation: a Kotlin class with one six-parameter field lambda and -a Java class with three two-parameter comparator fields both read -`nargs.value 6` with no constructor at all, so a gate at `nargs=5` would -have flagged that constructor-free class, and any class whose folded -lambda parameters sum past the limit. The averages were wrong the same -way — `function_args_average` divides by `nom`'s callables, which the -constructor was not. The constructor became a `Function` space: the -gate, the report and the Python binding followed unchanged, while -`nargs`, `npm` and `npa` each needed their own change (lesson 63). - ---- diff --git a/docs/development/testing.md b/docs/development/testing.md new file mode 100644 index 000000000..87bf9d181 --- /dev/null +++ b/docs/development/testing.md @@ -0,0 +1,201 @@ +# Testing guide + +Project-specific testing practice for `big-code-analysis`: how to prove +a test can fail, which fixture shapes are vacuous by construction, what +the harness normalises away, and how feature gates work. It is for +anyone adding or changing tests here. The general lessons it rests on +are in [`lessons_learned.md`](lessons_learned.md). + +## Verify defensive refactor tests by reverting the production code + +A regression test earns its place by failing against the code it +guards. For a defensive refactor (one that pins an invariant rather +than fixing a live bug), demonstrate that before trusting it: + +1. Commit or `git stash push ` the production change first. A + file-level `git checkout -- ` over uncommitted work discards + the fix along with the perturbation. +2. Revert or neutralise the production line with a precise edit, or + patch it to a no-op in place when a partial revert would not build. +3. Run the new test and confirm it fails for the expected reason. +4. Restore with the exact inverse edit, then confirm `git diff --stat` + shows only the edits you intend. + +When reverting is impossible (the refactor deleted a helper the test +needs, or a newtype makes the old shape uncompilable), perturb instead: +transpose the fields the newtype protects, or flip the bound the test +pins, and confirm the test fails. Run the perturbation against the +whole suite. A perturbation that fails nothing means the invariant is +currently unobservable; say so in the test's comment rather than +overstating what the test proves. Claim "only this test catches it" +only after sweeping every crate that depends on the mutated one +(`cargo tree --workspace -i -e normal` lists them). + +### A sweep of several perturbations needs a script + +A sweep of several perturbations is a script, never a shell loop. +`utils/perturb.py` is that script: it refuses a target that is +modified, untracked or absent, keeps the backup in memory and in a +`mktemp` directory, rejects an anchor equal to its replacement, and +restores in a `finally`. Its manifest format and runners (`cargo`, +`unittest`) are in its module docstring. Rules a hand-rolled driver +must also follow: + +- Assert `old != new` and `count(old) == 1` before every write; an + anchor that stopped matching reports zero for the unperturbed code. +- The result parser is the other half of the subject, and so is the + invocation: pass `--no-fail-fast` to any multi-target `cargo test`; + the first failing target otherwise hides every later guard. +- Parse `failures:` lists and exit status together; `cargo test -q` + prints dots, and a parser scanning for `FAILED` reads every mutant as + caught by nothing. Classify a build failure by `error[` or + `could not compile`, never bare `error`. +- Rebuild inside the measurement step for a compiled subject; a stale + binary reports "0 files changed" for any edit. +- Run Python subjects with no bytecode cache (`python3 -B` after + deleting `__pycache__`); a same-length edit restored within the same + second runs the stale `.pyc`. +- After an interrupted sweep, `pgrep -af '[.]py'` and kill it + first, then `cmp` each touched file against the backup. A mutant left + in the tree looks like a half-finished fix. + +A uniform result across perturbations (all zero, all the same count) +describes the harness, not the code. A perturbation that passes is a +finding: check whether the behaviour is enforced by the mechanism or +merely absent from a list before strengthening anything, and re-run the +perturbations whenever two guards merge into one predicate. + +## Fixture shapes that cannot fail + +### Seed the state you claim to assert on + +- **Seed non-default state.** A reset asserted from `Default::default()` + and an accumulation asserted from zero both hold whether or not the + production line exists. Seed values that differ from the default and + from each other; for a fold over a sub-population, give the excluded + members a non-zero contribution. + +### Perturb the fixture as well as the production line + +- **Anchor the construct on its own axis.** A fixture pairing an + excluded construct with a real condition still passes after someone + trims the construct out. Assert something only the construct + contributes (an `assignments_sum()`, a per-space count), and verify by + deleting the construct. Where nothing remains to anchor on, say so in + a comment. +- **Retiring a test retires its fixture's shapes.** Before deleting a + hand-written test in favour of a derived one, list the constructs its + fixture spelled and confirm the replacement corpus spells each. +- **Never let the measured value be the defect's output.** A probe + whose only non-zero reading is produced by the bug scores zero once + the bug is fixed. Build the measured quantity from content the fix + does not touch. +- **Validate a scaling probe by removing what it prices.** A probe that + reads ~1.0 with the memo removed is timing a path its workload never + reaches. Record the perturbed exponent in the probe's `rationale`. +- **Prove a reachability probe can fire** with a throwaway + `#[should_panic]` test before reading zero fires as a finding; a + `debug_assert!` in a release build is dead. + +### Coverage measures execution, not discrimination + +- **Coverage measures execution, not discrimination.** Perturb the + sub-expression carrying the invariant; compare covered counts, never + percentages; diff sets rather than scalar summaries. Before quoting + patch coverage, `cargo llvm-cov clean --workspace`, run the `coverage` + job's commands, and read `utils/patch-coverage.py`. + +### Normalise the expectation, never the observation + +- **Normalise the expectation, never the observation.** A helper that + sorts, trims or rounds the returned value deletes that property from + every caller's assertions at once. + +### Review the selector as carefully as the assertion + +- **Review the selector.** A filter that matches nothing makes every + assertion after it vacuous. Assert the match count; compare whole + lines for indentation-structured output. + +### Take the expected value from outside the fix + +- **Take the expected value from outside the fix:** the construct's + spelled-out twin as a row beside it, and the same input on `main`. + +### Assertion shapes that are wrong by construction + +- **Wrong by construction:** string-matching the repository's own + source; asserting the absence of a structural marker; asserting only + that a call returned `Ok`; building an equality fixture with `Clone`; + comparing order-insensitive containers to pin an ordering. + +### Assert a whole-run invariant in the run + +- **Whole-run invariants** (a drained scratch structure, a balanced + stack) get an O(1) `debug_assert!` on the hot path in addition to the + named test; the suite then checks it on every corpus file. + +## Know what the harness normalises away + +`check_metrics` → `test_support::check_func_space_with` trims and +re-appends a trailing newline; the integration suites' +`read_file_with_eol` appends one unconditionally. A node ending at EOF +is unreachable from either. Use `metrics_verbatim` / `space_verbatim` +in `src/test_support.rs`, which reach `analyze(Source::new(..))` +untouched. When a test cannot be made to fail, look for the stage that +filters or normalises the input before it reaches the code under test, +and pair any end-to-end test with a direct unit test on the function +whose contract is verified. + +## Platform and feature gates + +### Gate `#[cfg]` on the `fn`, never on an inner block + +An empty test is a passing test, so `#[cfg(unix)] { … }` around a +body compiles to green with zero assertions off target. Put the gate on +the function's attribute stack. Mirror the production code's platform +logic in fixtures (`bca{EXE}`), not one OS's spelling. + +### Gate a feature-gated fixture table on the union of its rows + +- A fixture table built from `#[cfg(feature = …)]` rows needs both + `#[cfg(any())]` on the `fn` and a + non-vacuity assertion (`assert_fixtures_present`, or `ran > 0`) + inside it. Verify against a feature set that enables none of the rows (a + single non-listed language such as `--features go`), with + `-p big-code-analysis`: a workspace-wide run unifies features + through the CLI and web crates and isolates nothing. + +### Every test that names a language carries that language's gate + +- `mk_langs!` generates every `*Parser` alias unconditionally, so a test + naming `check_metrics::` compiles with `python` off and + panics. `make check-test-lang-gates` derives the gate each test and + helper needs (`all(…)` of what a test names, `any(…)` of a helper's + users) and fails in both directions: too narrow and too wide. `--fix` + writes markers, `--show` prints the derivation. What it cannot see, + mark by hand with a comment the gate reads: + + ```rust + // test-lang-gates: hand-written(cpp) — the corpus walk picks a + // language per file from its extension + #[cfg(feature = "cpp")] + ``` + + Cases needing the marker: a language chosen from a string, a trait + used only through its methods, anything `pub`, a re-export, and a + parent module's private item reached through `use super::*`. A + comparison (`lang == LANG::Go`, any `matches!` arm) is not a use; a + parser named as a type parameter inside an `is_enabled` sweep is. +- `make check-test-lang-gates-compare COMPARE_REF=origin/main` catches + a gate that narrowed since the base revision, which the per-tree gate + cannot see. CI runs it per PR; a deliberate narrowing is declared + with the `gate-narrowing-intended` label, never an in-source marker. + +### Why the import lint is off on a partial build + +- The library roots and integration crate roots carry + `#![cfg_attr(not(feature = "all-languages"), allow(unused_imports))]` + because import liveness depends on the feature set; dead-item + allowances exist only in the two library roots, so every helper in + `tests/` still needs its own gate. diff --git a/opencode.jsonc b/opencode.jsonc index ff8c574a4..5d4797de4 100644 --- a/opencode.jsonc +++ b/opencode.jsonc @@ -1,15 +1,19 @@ { "$schema": "https://opencode.ai/config.json", - // The metric-feedback plugin is loaded by discovery from - // .opencode/plugins/; do not list it under "plugins", which takes - // packages and plugin directories and skips a single file with a - // warning. See the book's agent-feedback recipe. - // opencode auto-loads AGENTS.md at the repo root, but it does not - // follow the markdown links inside it, and it does not read the - // .claude/rules/ directory on its own (it only falls back to - // .claude/CLAUDE.md when AGENTS.md is absent, and reads - // .claude/skills/). This instructions array is the auto-load path - // for the detailed project rule files Claude Code reads from - // .claude/rules/, so opencode sessions get the same rules. - "instructions": [".claude/rules/*.md"] + // AGENTS.md is discovered automatically. The bca-check plugin loads + // by discovery from .opencode/plugins/; "plugins" takes packages and + // directories, not a single file. + // + // The rules below are guardrails against command spellings, not + // enforcement of the policy in AGENTS.md: `git -C … push` or a + // filesystem removal of a worktree directory are not matched. The + // worktree denials apply to orchestrators too; a skill that created + // worktrees lists them and asks the user to remove them + // (docs/development/agent_isolation.md). + "permissions": [ + { "action": "shell", "resource": "git push *", "effect": "ask" }, + { "action": "shell", "resource": "gh pr create *", "effect": "ask" }, + { "action": "shell", "resource": "git worktree remove *", "effect": "deny" }, + { "action": "shell", "resource": "git worktree prune *", "effect": "deny" } + ] } diff --git a/src/c_family_space_names_tests.rs b/src/c_family_space_names_tests.rs index 2f433ea8d..34a01995e 100644 --- a/src/c_family_space_names_tests.rs +++ b/src/c_family_space_names_tests.rs @@ -152,8 +152,7 @@ fn pad(source: &str) -> String { /// assertion cannot read `root.spaces[0]`; collecting the whole /// subtree also lets each row assert that the fixture opened /// *exactly one* function space, which is `get_space_kind` and -/// `is_func_space` agreeing with the name — `.claude/rules/ -/// grammar-dispatch.md` §6. +/// `is_func_space` agreeing with the name — `docs/development/grammar_dispatch.md` §6. #[cfg(any(feature = "c", feature = "cpp", feature = "mozcpp", feature = "objc"))] fn function_spaces(space: &FuncSpace, found: &mut Vec<(Option, usize, usize)>) { if space.kind == SpaceKind::Function { @@ -234,7 +233,7 @@ fn the_declarator_walk_names_the_function_space() { /// would notice if `function_spaces` selected no space at all — the /// comparison would just find two empty expectations equal, and /// every row would pass vacuously -/// (`.claude/rules/testing.md`, "Review the selector as carefully as +/// (`docs/development/testing.md`, "Review the selector as carefully as /// the assertion"). Feeding it a name that is deliberately wrong is /// the cheapest proof that the selector reaches a real space and the /// comparison discriminates. @@ -290,7 +289,7 @@ fn the_table_reports_a_name_that_does_not_match() { /// mozcpp siding with C rather than with the upstream `tree-sitter-cpp` /// it forked from is the finding worth keeping here: it owns no file /// extension, so nothing routes to it and only a unit test can see -/// it at all (`.claude/rules/grammar-dispatch.md`, "when you fix one +/// it at all (`docs/development/grammar_dispatch.md`, "when you fix one /// language, sweep the rest"). /// /// Recovery trees are outside the walk's contract — see diff --git a/src/lib.rs b/src/lib.rs index fbb3a47f0..e9304c163 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -137,7 +137,7 @@ // the import itself can express. Partial builds only — `all-languages` // is on by default and under `--all-features`, so the build CI gates on // and the one a contributor runs still police every unused import. See -// `.claude/rules/testing.md`, "Why the import lint is off on a partial +// `docs/development/testing.md`, "Why the import lint is off on a partial // build". #![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] #[doc(hidden)] @@ -160,7 +160,7 @@ mod macros; mod test_support; // Gated on the four grammars its tables name, so a build enabling none // of them drops the module rather than tripping its `checked > 0` -// non-vacuity guard (`.claude/rules/testing.md`, #1286). The guard then +// non-vacuity guard (`docs/development/testing.md`, #1286). The guard then // covers only the residual case where `is_enabled` stops agreeing with // the feature it compiled under. #[cfg(test)] diff --git a/src/metric_set_tests.rs b/src/metric_set_tests.rs index 75a3f5e87..646d31dec 100644 --- a/src/metric_set_tests.rs +++ b/src/metric_set_tests.rs @@ -212,7 +212,7 @@ fn _all_variants_exhaustive_guard(m: Metric) { fn from_str_round_trips_every_variant_display_name() { // Reverting any single arm in `impl FromStr for Metric` // makes this fail on exactly that variant — the test is - // load-bearing per `.claude/rules/testing.md`. + // load-bearing per `docs/development/testing.md`. for &m in ALL_VARIANTS { let parsed: Metric = m .to_string() diff --git a/src/metrics/abc.rs b/src/metrics/abc.rs index 14d080ffa..2e632174c 100644 --- a/src/metrics/abc.rs +++ b/src/metrics/abc.rs @@ -2154,7 +2154,7 @@ mod tests { // zero until #1406 — the C# sibling of Kotlin's #1384. // // tree-sitter-c-sharp 0.23.5 spells the `record` and `class` - // families differently, so per `.claude/rules/grammar-dispatch.md` + // families differently, so per `docs/development/grammar_dispatch.md` // §11 they are two independent paths and each needs its own // fixture: the record form nests the arguments under a // `primary_constructor_base_type`, the class form hangs them @@ -2315,19 +2315,10 @@ mod tests { 1, "the class space owns `: Base(x)` and nothing else" ); - // Both constructors are named after the class (#1828), so - // select by position: the primary constructor's parameter - // list precedes the body. The base call is its *sibling*, - // not its child, so it owns no branch. - let rows: Vec<(Option<&str>, u64)> = class - .spaces - .iter() - .map(|s| (s.name.as_deref(), s.metrics.abc.branches())) - .collect(); assert_eq!( - rows, - [(Some("Both"), 0), (Some("Both"), 1)], - "the primary constructor owns nothing; the secondary owns `: this(a)`" + child_space(class, "Both").metrics.abc.branches(), + 1, + "the secondary constructor owns `: this(a)` and nothing else" ); }); } @@ -2382,9 +2373,8 @@ mod tests { // difference — the file totals 3 either way — so a codebase moving // to primary constructors shifts per-function `branches_max` / // `branches_average` and per-space `abc` thresholds without any - // behaviour change. That is deliberate (the constructor's space is - // its parameter list, and the call is not in it — #1828), and C# - // has the identical split, pinned by + // behaviour change. That is deliberate (there is no function to + // attribute the call to), and C# has the identical split, pinned by // `csharp_base_call_and_constructor_initializer_do_not_double_count` // (#1456). // @@ -2525,14 +2515,14 @@ mod tests { // the *same* enum, because that is the only shape that shows the gate // working: a fixture of only `A(1)` scores the same whether the arm is // gated on the argument list or matches every constant - // (`.claude/rules/grammar-dispatch.md` §6). Each also carries a + // (`docs/development/grammar_dispatch.md` §6). Each also carries a // constant whose argument is itself a call, which must score 2 rather // than 1 (§5). // // `branches_sum()` alone cannot notice the bare constant being trimmed // out — it contributes to no axis — so every fixture is anchored on a // node census that fails by name when a spelling is edited away - // (`.claude/rules/testing.md`, "Perturb the fixture as well as the + // (`docs/development/testing.md`, "Perturb the fixture as well as the // production line"). The two are coupled in one helper for the same // reason `assert_kotlin_class_members` couples its pair: a branch // total added without the census reads as coverage and is not. @@ -3769,7 +3759,7 @@ mod tests { /// /// `jmp` differs from `ctl` by exactly one statement, so the /// `goto case` is the only thing that can separate their scores - /// (`.claude/rules/grammar-dispatch.md` §11 — an arm and a + /// (`docs/development/grammar_dispatch.md` §11 — an arm and a /// `goto case` are independent paths into the same counter, and a /// fixture carrying only arms cannot show the gate works). `dfl` is /// the control that was already correct, by accident rather than @@ -4847,7 +4837,7 @@ mod tests { // nothing red. This is that pin. // // `BinaryExpression2` (469) is the pre-alias symbol the arm also - // lists, defensively, per `.claude/rules/grammar-dispatch.md` §1. §2 + // lists, defensively, per `docs/development/grammar_dispatch.md` §1. §2 // asks that such an entry be kept *and* have its unreachability // asserted, so that a pin promoting the symbol changes behaviour // loudly rather than invisibly. @@ -5153,7 +5143,7 @@ mod tests { // Counting both charged a relational arm twice, and twice C#'s own // cyclomatic decision count. // - // Per `.claude/rules/grammar-dispatch.md` §11 the `operator <` + // Per `docs/development/grammar_dispatch.md` §11 the `operator <` // fixture above cannot prove this alone: its `is > 0` sits beside a // `binary_expression` comparison that supplies a plausible total on // its own. Here the pattern operators are the *only* `<` / `>` / @@ -5549,7 +5539,7 @@ mod tests { // codebase with nullable reference types enabled the suffix is // everywhere, so the gap is not an exotic corner. // - // Both walker paths, per `.claude/rules/grammar-dispatch.md` §11: + // Both walker paths, per `docs/development/grammar_dispatch.md` §11: // `p*` go through the `if` predicate slot // (`csharp_count_condition`) and `c*` through the `&&` chain slot // (also `csharp_count_condition`, per chain operand), which reach @@ -5679,7 +5669,7 @@ mod tests { // The statement `switch` reaches the same `when_clause` kind through // a different parent — `switch_section` rather than // `switch_expression_arm` — which makes it an independent path in - // the sense of `.claude/rules/grammar-dispatch.md` §11: the arms + // the sense of `docs/development/grammar_dispatch.md` §11: the arms // themselves are counted by two different owners (a `Case` token // here, the `SwitchExpressionArm` node there), so a guard rule // written against one shape could be dead for the other and every @@ -6818,7 +6808,7 @@ function f(int $a, int $b): int { // The Kotlin binding of the two assertions every #1421 fixture needs, // coupled on purpose. A per-member score table is worth only as much // as the anchor proving the fixture still spells what it claims to - // (`.claude/rules/testing.md`, "Perturb the fixture as well as the + // (`docs/development/testing.md`, "Perturb the fixture as well as the // production line"), and the `when_subject` count is the anchor no // score can stand in for: a `when` that grew a subject scores its // entries the pre-#1421 way with every other row still satisfied. @@ -7604,7 +7594,7 @@ function f(int $a, int $b): int { // taught it therefore have a // second, structurally independent path into the count, and a // fixture covering only the slot leaves it untested - // (`.claude/rules/grammar-dispatch.md` §11). + // (`docs/development/grammar_dispatch.md` §11). // // Each chain is one identifier plus one wrapped comparison, so 2 is // "the walker peeled the wrapper to the comparison, which pays for @@ -7621,7 +7611,7 @@ function f(int $a, int $b): int { // wrapper from its operand: `a && x > 1` scores the same 2 / 3 as // every row here, so trimming the `!!` or the cast out of a // fixture would leave this green with its subject gone - // (`.claude/rules/testing.md`, "Perturb the fixture as well as + // (`docs/development/testing.md`, "Perturb the fixture as well as // the production line"). for (chain, spelling, anchors) in [ ( @@ -16531,7 +16521,7 @@ end // that starts emitting it keeps working, and this pins that it // does not emit it today — otherwise the defensive arm is // indistinguishable from a dead one - // (`.claude/rules/grammar-dispatch.md` §2). + // (`docs/development/grammar_dispatch.md` §2). let parser = RubyParser::new( src.as_bytes().to_vec(), &std::path::PathBuf::from("foo.rb"), @@ -16570,7 +16560,7 @@ end // *without* the slot. Its `when` arm added a flat one on top of // whatever the guard's sub-structure already scored, so `tok` came // back 3 against `call` and `bare`'s 2 — the spelling-dependence the - // batch exists to remove, and a `.claude/rules/grammar-dispatch.md` + // batch exists to remove, and a `docs/development/grammar_dispatch.md` // §5 double count with the `>` token arm. A whole-branch review of // the batch found it; all three rows now read 2, level with the // sibling fixtures above and with their own decision counts. @@ -17068,7 +17058,7 @@ end // written, so the asymmetry was in the mechanism. Each construct // now has an unconditional arm in its language's `compute` and has // left the terminal set; listing it in both would score it twice - // (`.claude/rules/grammar-dispatch.md` §5). + // (`docs/development/grammar_dispatch.md` §5). // // Every fixture below carries the same four shapes, because they // are structurally independent paths and covering one says nothing @@ -17081,7 +17071,7 @@ end // - `outCtl` — the same member spelling `==`. It read 1 before and // after, so it is the anchor that makes `out*`'s 1 a claim about // the construct rather than about the member shape - // (`.claude/rules/testing.md`, "Perturb the fixture as well as + // (`docs/development/testing.md`, "Perturb the fixture as well as // the production line"). // - `in*` / `inAnd` — the predicate slot and the `&&`-chain walker, // the two paths that already owned the count. They must be @@ -17439,7 +17429,7 @@ fn ctrl(x: Option) -> u8 { if x.is_some() { 1 } else { 0 } } // Gated on the union of the features [`ternary_comment_invariance::cases`] // has a row for, so a build enabling none of them — `--no-default-features // --features go` — drops both tests rather than tripping their -// `checked > 0` guards (`.claude/rules/testing.md`, #1286). Both tests +// `checked > 0` guards (`docs/development/testing.md`, #1286). Both tests // read the same table, so one gate on the module is exact for each. #[cfg(test)] #[cfg(any( @@ -17587,7 +17577,7 @@ mod ternary_comment_invariance { // Gated on the union of every row below — the three `pairs` languages // plus Lua, whose test is separate — so a build enabling none of them // drops the module instead of failing its guards -// (`.claude/rules/testing.md`, #1286 / #1411). The three tests do *not* +// (`docs/development/testing.md`, #1286 / #1411). The three tests do *not* // share a row set, so each carries its own narrower gate: a Lua-only // build must not be asked to run the Ruby/Perl baselines. #[cfg(test)] @@ -17736,7 +17726,7 @@ mod keyword_negation_parity { /// gives a failure message naming both spellings. /// `every_operand_scores_its_recorded_values` then pins the absolute /// numbers, so a regression moving *both* sides equally still fails, and -/// carries the cross-metric anchor `.claude/rules/grammar-dispatch.md` §8 +/// carries the cross-metric anchor `docs/development/grammar_dispatch.md` §8 /// asks for. /// /// Two slots per language, because the sets feed two independent walker @@ -17947,7 +17937,7 @@ mod numeric_bool_operands { /// whole module green: /// /// - **`checked > 0`** is the non-vacuity half of the rule in - /// `.claude/rules/testing.md`. The `#[cfg(any(feature = …))]` on + /// `docs/development/testing.md`. The `#[cfg(any(feature = …))]` on /// this module makes the tests *absent* when no truthy-valued /// language is compiled in; this catches the residual case where /// the runtime `is_enabled()` check stops agreeing with the feature @@ -18069,7 +18059,7 @@ mod numeric_bool_operands { /// boolean slot as `==` does, and `groovy_condition_scores_itself` /// lists each so the slot holding one does not pay again; a construct /// takes exactly one of the two routes, never both -/// (`.claude/rules/grammar-dispatch.md` §5). +/// (`docs/development/grammar_dispatch.md` §5). /// - **Perl** `/^#/` (`pattern_matcher`) and `m{^#}` /// (`pattern_matcher_m`), the two spellings of a match against the /// implicit `$_`. They are sibling rules, not aliases, so both are @@ -18120,7 +18110,7 @@ mod numeric_bool_operands { /// decision), so each slot pins its own pair rather than sharing one. // Gated on the union of the three languages with rows, so a build // enabling none of them drops the module instead of failing its -// guards (`.claude/rules/testing.md`, #1286 / #1411). +// guards (`docs/development/testing.md`, #1286 / #1411). #[cfg(test)] #[cfg(any( feature = "groovy", @@ -18538,7 +18528,7 @@ mod own_production_bool_constructs { /// spell-anchored because the modifier is the only thing in them that /// scores a condition: deleting `if $x` from the modifier fixture would /// otherwise turn it into a silent copy of nothing at all -/// (`.claude/rules/testing.md`, "Perturb the fixture as well as the +/// (`docs/development/testing.md`, "Perturb the fixture as well as the /// production line"). #[cfg(test)] #[cfg(feature = "perl")] @@ -18709,12 +18699,12 @@ mod perl_statement_modifier_parity { /// cannot: /// /// - **The `kind_id` each spelling parses to.** This is the whole bug -/// class (`.claude/rules/grammar-dispatch.md` §1): the grammars here +/// class (`docs/development/grammar_dispatch.md` §1): the grammars here /// emit `string` under two ids in JavaScript, Mozjs and Tsx and under /// three in Tsx counting the type keyword, and listing the wrong one /// compiles, runs, and returns the unfixed number. Asserting the id /// turns that measurement into a standing claim rather than a note in -/// an issue. It is also the fixture anchor `.claude/rules/testing.md` +/// an issue. It is also the fixture anchor `docs/development/testing.md` /// asks for — editing `"s"` to `1` in a row now fails by name instead /// of quietly turning that row into a copy of the numeric module. /// - **`cyclomatic` does not move.** Only the operand spelling changes diff --git a/src/metrics/abc/csharp.rs b/src/metrics/abc/csharp.rs index 4562cabf2..29d1d9e95 100644 --- a/src/metrics/abc/csharp.rs +++ b/src/metrics/abc/csharp.rs @@ -357,27 +357,28 @@ fn csharp_count_token_branch<'a>( // they are distinct kind ids, and none of them occurs under a // `base_list`. `BaseList` and `BaseList2` both render to // `"base_list"` and only the second is observed here; both are - // listed per `.claude/rules/grammar-dispatch.md` §1. + // listed per `docs/development/grammar_dispatch.md` §1. // // Where the branch lands is decided by the space tree, not here, // and the two delegation spellings land differently. The // `base_list` is a direct child of the class declaration — outside - // every member, and a *sibling* of the primary constructor's - // `parameter_list` rather than inside it. Since #1828 that list - // opens the constructor's function space, but the space is the - // list and nothing more, so the call is still outside it. So - // `class Sub(int x) : Base(x)` bills its branch to the **class** - // space, while `class C : Base { C(int x) : base(x) {} }` bills - // the same call to the constructor's *function* space. - // File-level `branches_sum` agrees between the two spellings, so - // nothing is wrong at the aggregate, but per-function + // every member, and a sibling of the primary constructor's + // `parameter_list` rather than inside it — and a primary + // constructor has no declaration node of its own for + // `CsharpCode::is_func_space` to promote + // (`big-code-analysis-ast/src/getter/csharp.rs` lists only + // `MethodDeclaration | ConstructorDeclaration | …` as + // `SpaceKind::Function`). So `class Sub(int x) : Base(x)` bills its + // branch to the **class** space, while `class C : Base { C(int x) : + // base(x) {} }` bills the same call to the constructor's *function* + // space. File-level `branches_sum` agrees between the two + // spellings, so nothing is wrong at the aggregate, but per-function // `branches_max` / `branches_average` and a per-space // `bca check --threshold abc=N` see them differently: a codebase // migrating to primary constructors shifts weight off its function // rows and onto its class rows with no behaviour change. That is - // the intended reading — the constructor's space holds its - // parameters, and the call to the base is not among them — and - // it is pinned by + // the intended reading — there is no function to attribute the call + // to — and it is pinned by // `csharp_primary_constructor_base_call_is_a_branch` and // `csharp_base_call_and_constructor_initializer_do_not_double_count` // in `src/metrics/abc.rs`. Kotlin's `ConstructorInvocation` under a @@ -612,7 +613,7 @@ fn csharp_walk_for_conditions<'a>( // cyclomatic decision count, which #1422 fixes upward in // `src/metrics/cyclomatic/csharp.rs`. // - // By role, not index (`.claude/rules/grammar-dispatch.md` §3): + // By role, not index (`docs/development/grammar_dispatch.md` §3): // the two clauses carry their guard as the only *expression* // child but disagree on where it sits, because // `catch_filter_clause` spells its parentheses as anonymous diff --git a/src/metrics/abc/elixir.rs b/src/metrics/abc/elixir.rs index fc62878ea..4a01425e3 100644 --- a/src/metrics/abc/elixir.rs +++ b/src/metrics/abc/elixir.rs @@ -462,7 +462,7 @@ impl Abc for ElixirCode { // (`E::BinaryOperator`, `BinaryOperator2`, // `BinaryOperator3`), and a name comparison stays correct // when a bump adds a fourth - // (`.claude/rules/grammar-dispatch.md` §1, the same call + // (`docs/development/grammar_dispatch.md` §1, the same call // `QUOTED_CONTENT` makes in `src/metrics/loc/elixir.rs`). // The runtime cost that trade buys there is not paid here: // the guard runs only for one of these four tokens, not for diff --git a/src/metrics/abc/go.rs b/src/metrics/abc/go.rs index 707fcac26..f88001148 100644 --- a/src/metrics/abc/go.rs +++ b/src/metrics/abc/go.rs @@ -95,7 +95,7 @@ fn go_count_condition(condition: &Node, parent: &Node, conditions: &mut f64) { // Asking the peel itself which kinds it unwraps, rather than // restating the list here (#1470): a restated list that gained a // kind the peel lacked would read as covering a shape the peel - // then dropped (`.claude/rules/grammar-dispatch.md` §7). + // then dropped (`docs/development/grammar_dispatch.md` §7). go_inspect_container(condition, parent, conditions); } } diff --git a/src/metrics/abc/groovy.rs b/src/metrics/abc/groovy.rs index 7e8544560..4b05503b1 100644 --- a/src/metrics/abc/groovy.rs +++ b/src/metrics/abc/groovy.rs @@ -28,7 +28,7 @@ rows_own_inventory!(comparison, short_circuit, ternary); // that rather than restating the kind list — the divergence #1459 fixed // in Kotlin, where `unary_expression` was routed to the peel while the // peel handled only its `!` spelling, so the slot read as covering a -// shape the peel dropped on the floor (`.claude/rules/grammar-dispatch.md` +// shape the peel dropped on the floor (`docs/development/grammar_dispatch.md` // §7). // // The operand is read by grammar field (§3): `unary_expression` names diff --git a/src/metrics/abc/java.rs b/src/metrics/abc/java.rs index ce9c60bc4..108b4c338 100644 --- a/src/metrics/abc/java.rs +++ b/src/metrics/abc/java.rs @@ -355,7 +355,7 @@ fn java_walk_for_conditions<'a>( // compound guard (`when a > 1 && b < 2`) keeps its // sub-structure rather than collapsing to one. // - // By role, not index (`.claude/rules/grammar-dispatch.md` §3): + // By role, not index (`docs/development/grammar_dispatch.md` §3): // `guard` is `seq('when', expression)` and node-types.json gives // it no field, so the expression is the clause's first operand // that is not an `extra` — `when /*c*/ g` puts a comment before diff --git a/src/metrics/abc/js_family.rs b/src/metrics/abc/js_family.rs index 9ace8c164..588e7eaf9 100644 --- a/src/metrics/abc/js_family.rs +++ b/src/metrics/abc/js_family.rs @@ -340,7 +340,7 @@ macro_rules! js_family_abc_compute { // `type_parameters` — so the allowlist is the inverse of // a five-entry denylist today and, unlike it, needs no // revisiting when the grammar grows a seventh - // (`.claude/rules/grammar-dispatch.md` §1). The shifts + // (`docs/development/grammar_dispatch.md` §1). The shifts // (`<<`, `>>`, `>>>`) are their own tokens. _ if comparison::pays_at_leaf_kind(kind, node, code, ancestors) => { stats.conditions += 1.; diff --git a/src/metrics/abc/kotlin.rs b/src/metrics/abc/kotlin.rs index 46d76a4d7..11e31442d 100644 --- a/src/metrics/abc/kotlin.rs +++ b/src/metrics/abc/kotlin.rs @@ -87,7 +87,7 @@ fn kotlin_eq_initializes_immutable_binding<'a>( // - `as_expression` was not recognised at all, so a cast fell off the // end of the slot's `else if`. // -// By field, not index (`.claude/rules/grammar-dispatch.md` §3): both +// By field, not index (`docs/development/grammar_dispatch.md` §3): both // kinds name their parts (`operator` / `argument`, `left` / `right`), so // one read serves the prefix and postfix spellings alike instead of the // per-spelling index that produced the defect, and it survives a grammar @@ -342,8 +342,8 @@ impl Abc for KotlinCode { // `delegation_specifiers` — outside every member, and a // *sibling* of the `primary_constructor` node rather than its // child — so the innermost enclosing space is the **class**. - // (`PrimaryConstructor` *is* a `SpaceKind::Function` since - // #1828, and this moved nothing, precisely because the + // (Verified by perturbation: labelling `PrimaryConstructor` a + // `SpaceKind::Function` moves nothing, precisely because the // delegation specifier is not inside it.) A // `SecondaryConstructor`, which `KotlinCode::get_space_kind` // does label a function, takes its `: super(x)` with it. diff --git a/src/metrics/abc/lua.rs b/src/metrics/abc/lua.rs index 1d75a0e2a..32d985699 100644 --- a/src/metrics/abc/lua.rs +++ b/src/metrics/abc/lua.rs @@ -134,7 +134,7 @@ impl Abc for LuaCode { // in exactly two productions — `binary_expression` and the // hidden `_attrib`, which surfaces aliased as `attribute` — // so the gate is closed rather than a coverage claim - // (`.claude/rules/grammar-dispatch.md` §1). + // (`docs/development/grammar_dispatch.md` §1). _ if comparison::pays_at_leaf_kind(kind, node, code, ancestors) => { stats.conditions += 1.; } diff --git a/src/metrics/abc/python.rs b/src/metrics/abc/python.rs index c436b6e3b..7f8c90368 100644 --- a/src/metrics/abc/python.rs +++ b/src/metrics/abc/python.rs @@ -113,7 +113,7 @@ fn python_count_condition(condition: &Node, code: &[u8], conditions: &mut f64) { // `seq(expression, 'if', expression, 'else', expression)` carrying no // grammar fields at all, so the slot cannot be named the way Ruby's and // the C family's can. It is located by ROLE rather than by a bare index -// (`.claude/rules/grammar-dispatch.md` item 3): the first child after +// (`docs/development/grammar_dispatch.md` item 3): the first child after // the `if` keyword that is not a comment. // // Both halves of that are load-bearing, and neither is theoretical. @@ -155,7 +155,7 @@ fn python_count_ternary_condition(node: &Node, code: &[u8], conditions: &mut f64 // exactly one, and a compound guard (`case n if a > 1 and b:`) keeps its // sub-structure rather than collapsing to one. // -// By grammar FIELD, not index (`.claude/rules/grammar-dispatch.md` §3): +// By grammar FIELD, not index (`docs/development/grammar_dispatch.md` §3): // `case_clause` names its guard `guard`, which is what keeps a // comprehension's `if_clause` — the same kind, in a wholly different // role — out of this slot. The clause itself carries no field for its diff --git a/src/metrics/abc/ruby.rs b/src/metrics/abc/ruby.rs index 1cb2c5ae3..9d52ad04e 100644 --- a/src/metrics/abc/ruby.rs +++ b/src/metrics/abc/ruby.rs @@ -195,7 +195,7 @@ fn ruby_count_when<'a>( // Java's 4. // // Slots are addressed by grammar field, per -// `.claude/rules/grammar-dispatch.md` item 3. +// `docs/development/grammar_dispatch.md` item 3. // // The condition slot reuses `ruby_count_condition`, so a ternary's // predicate is classified by exactly the code that classifies an diff --git a/src/metrics/abc/rust.rs b/src/metrics/abc/rust.rs index 2857bcb2e..6340e6504 100644 --- a/src/metrics/abc/rust.rs +++ b/src/metrics/abc/rust.rs @@ -126,7 +126,7 @@ fn rust_count_slot(slot: Option, code: &[u8], conditions: &mut f64) { // and a compound guard (`n if a > 1 && b`) keeps its sub-structure // rather than collapsing to one. // -// By grammar FIELD, not index (`.claude/rules/grammar-dispatch.md` §3): +// By grammar FIELD, not index (`docs/development/grammar_dispatch.md` §3): // `match_pattern` names its guard `condition`, so a comment between the // pattern and the `if` cannot shift the read the way it does for the // positional sibling slots. The field is absent on an unguarded arm, diff --git a/src/metrics/cognitive.rs b/src/metrics/cognitive.rs index 45cd38884..40e586a1f 100644 --- a/src/metrics/cognitive.rs +++ b/src/metrics/cognitive.rs @@ -9074,7 +9074,7 @@ end", // (`list.forEach(item -> { if (a) { while (b) {} } })`) also // reports cognitive sum 5.0. // - // Test-via-revert (.claude/rules/testing.md): removing the + // Test-via-revert (docs/development/testing.md): removing the // `Closure => { lambda += 1; }` arm drops this to 3.0 — the // missing +2 lambda surcharge on the nested `if`/`while`. check_metrics::( @@ -12194,7 +12194,7 @@ template bool h(T a) requires (A || B) { return a && a; } /// moving both equally still fails. // Gated on the union of the three languages `cases()` has a row for, so // a build enabling none of them drops the module rather than tripping -// its `checked > 0` guard (`.claude/rules/testing.md`, #1286). +// its `checked > 0` guard (`docs/development/testing.md`, #1286). #[cfg(test)] #[cfg(any(feature = "java", feature = "javascript", feature = "kotlin"))] mod nameless_construct_boundaries { diff --git a/src/metrics/container_scope_tests.rs b/src/metrics/container_scope_tests.rs index 7cc54d38f..b09d4ed2e 100644 --- a/src/metrics/container_scope_tests.rs +++ b/src/metrics/container_scope_tests.rs @@ -402,7 +402,7 @@ int top() { return 0; } }, // Mozcpp owns no file extension, so nothing routes to it and it gets // no integration-snapshot coverage at all — the case - // `.claude/rules/grammar-dispatch.md` says to pin against its + // `docs/development/grammar_dispatch.md` says to pin against its // extension-owning sibling. `cpp_mozcpp_parity` does not cover this: // it compares metric *values* through `metric_sums`, so it would not // notice Mozcpp losing both blocks to a stray `HAS_MEMBERS = false` @@ -680,7 +680,7 @@ fn the_file_root_keeps_its_rollup() { /// keeping one genuine function space — an `AnonymousFunction`, which /// the Elixir fixture happens not to have — would satisfy that guard /// while the rest degraded silently. This sweep filters nothing, so -/// there is no set for a space to fall out of. (`.claude/rules/testing.md`: +/// there is no set for a space to fall out of. (`docs/development/testing.md`: /// "review the selector as carefully as the assertion".) #[test] #[cfg(any( diff --git a/src/metrics/cyclomatic.rs b/src/metrics/cyclomatic.rs index 98f0ed394..e0f9605b7 100644 --- a/src/metrics/cyclomatic.rs +++ b/src/metrics/cyclomatic.rs @@ -2218,7 +2218,7 @@ mod tests { /// pinning the member count, and the whole claim is that `jmp` reads /// the same as `ctl`. The three methods are identical but for one /// statement each, so `jmp`'s `goto case` is the only thing that can - /// separate them (`.claude/rules/grammar-dispatch.md` §11 — an arm + /// separate them (`docs/development/grammar_dispatch.md` §11 — an arm /// and a `goto case` are independent paths into the same counter, and /// a fixture carrying only arms cannot show the gate works). /// diff --git a/src/metrics/halstead.rs b/src/metrics/halstead.rs index ea968ac8f..3391e7ad1 100644 --- a/src/metrics/halstead.rs +++ b/src/metrics/halstead.rs @@ -11423,8 +11423,8 @@ f() { /// The #1318 rows both dialects share. Every independent path /// through the role test gets a row of its own - /// (`.claude/rules/testing.md`, "give one input to each independent - /// path"): the value default, the script-command list, a modelled + /// (`docs/development/grammar_dispatch.md` §11, "Give one input to each + /// independent path"): the value default, the script-command list, a modelled /// construct reached through a `word_list`, the two modelled slots /// that hold values, an unresolvable command name, and both /// nesting directions. diff --git a/src/metrics/loc.rs b/src/metrics/loc.rs index 51958322e..68e19f06e 100644 --- a/src/metrics/loc.rs +++ b/src/metrics/loc.rs @@ -949,7 +949,7 @@ impl Stats { // sets already empty, so `(0, 0)` here is byte-identical over // every corpus input — measured. `a_zero_span_keeps_no_row` // below is therefore a direct `Stats` test rather than a - // fixture, per `.claude/rules/testing.md`: it is the only shape + // fixture, per `docs/development/testing.md`: it is the only shape // that can tell the two spellings apart. // // The corpus measurement is the weaker half of that claim, and @@ -2721,7 +2721,7 @@ line two #[cfg(feature = "python")] #[test] fn python_docstring_is_a_subset_of_cloc() { - // Anchors the subset on a second axis (`.claude/rules/testing.md`): + // Anchors the subset on a second axis (`docs/development/testing.md`): // the comment row is in `cloc` and not in `dloc`, so trimming // either construct out of the fixture fails a different assertion. // expected: 5 rows — `def`, two docstring rows, `# a comment`, @@ -5799,7 +5799,7 @@ line3\";", // The union of the fixture languages below, so a feature subset that // enables none of them makes this test *absent* rather than failing // in a way that reads as a defect in whatever is being changed - // (`.claude/rules/testing.md`). Every call site carries its own + // (`docs/development/testing.md`). Every call site carries its own // narrower gate, so if the test exists at least one row runs and it // cannot go vacuous. #[cfg(any( @@ -5992,7 +5992,7 @@ line3\";", // `read_file_with_eol` path each force a trailing newline, so a // node ending at EOF is unreachable from either and a test written // the ordinary way passes against unfixed code (#1051, #1067 — - // `.claude/rules/testing.md`). These fixtures reach the parser + // `docs/development/testing.md`). These fixtures reach the parser // byte-for-byte through `metrics_verbatim`, with the closing // delimiter as the last byte of the file. // @@ -8071,7 +8071,7 @@ function f() { // lloc=3, cloc=1 (row 3, now a code-comment line, not comment-only), // blank=1 (row 1). Without the fix `blank` collapses to 0 because // row 3 is double-counted. Verified fail-on-revert per - // .claude/rules/testing.md. + // docs/development/testing.md. check_metrics::("echo a\n\necho \"$(\n # c\n)\"\n", "foo.sh", |metric| { assert_eq!(metric.loc.sloc(), 5); assert_eq!(metric.loc.ploc(), 4); @@ -8189,7 +8189,7 @@ function f() { /// The parser emits `variable_assignment` under the id the enum /// spells `VariableAssignment2`; the unsuffixed `VariableAssignment` /// it never emits, so the LLOC arm listing only that scored a bare - /// `a=1` zero (`.claude/rules/grammar-dispatch.md` §1). Adding the + /// `a=1` zero (`docs/development/grammar_dispatch.md` §1). Adding the /// alias ungated then double-counted the two positions where the /// assignment hangs off a node the same arm already counts — a /// `declaration_command` and a `command`'s environment prefix (§5). @@ -8321,7 +8321,7 @@ EOF // // Each fixture isolates one arm of the new match, so a dropped kind // fails here rather than being covered by a sibling - // (`.claude/rules/grammar-dispatch.md` section 11): `raw_string`, + // (`docs/development/grammar_dispatch.md` section 11): `raw_string`, // `ansi_c_string` and `heredoc_body` are childless nodes the old // leaf arm credited only one row of, while `string` emits a // `string_content` child per row that *has* text and so skipped an @@ -8398,7 +8398,7 @@ EOF /// Analyses `source` byte-for-byte as Bash, for the #1412 fixtures /// `check_metrics` cannot carry: that shim trims trailing newlines, /// and a heredoc whose terminator is the last row is exactly the - /// shape it normalises away (`.claude/rules/testing.md`). + /// shape it normalises away (`docs/development/testing.md`). #[cfg(feature = "bash")] fn bash_loc_verbatim(source: &[u8]) -> Stats { metrics_verbatim( @@ -8418,7 +8418,7 @@ EOF /// #1260 routed the body, which fixed only the interior of a body /// that has text — the shape all of its fixtures had. The arm now /// routes the `heredoc_redirect` wrapper, the node present for every - /// spelling (`.claude/rules/grammar-dispatch.md` section 6), which + /// spelling (`docs/development/grammar_dispatch.md` section 6), which /// is what #1396 did for PHP. #[cfg(feature = "bash")] #[test] @@ -8428,7 +8428,7 @@ EOF // rather than a restatement of the fixed behaviour. // // `sloc` is the second axis the fixtures are anchored on - // (`.claude/rules/testing.md`): trimming the heredoc out of any + // (`docs/development/testing.md`): trimming the heredoc out of any // of them leaves a bare `cat` — or, in the last row, a bare // function — which fails the `sloc` assertion before the `blank` // one can go vacuous. @@ -8600,7 +8600,7 @@ EOF /// Asserts each `(source, file rows, blank before the bare-row credit)` /// fixture's file-level `loc_rows` under `lang`, byte-for-byte: /// `check_metrics` would normalise away the CRLF and the missing final - /// newline that some fixtures are about (`.claude/rules/testing.md`). + /// newline that some fixtures are about (`docs/development/testing.md`). /// The credit reached Bash, Tcl and iRules in #1445, the C family, /// Ruby and Elixir in #1801, and Python in #1819. #[cfg(any( @@ -9501,7 +9501,7 @@ EOF // #1819, when the comment credited it itself. CPython // rejects a NUL byte outright, so no tokenizer stream // derives the value: it pins the recovery behaviour only - // (`.claude/rules/grammar-dispatch.md` §6). Measured + // (`docs/development/grammar_dispatch.md` §6). Measured // (3, 2, 1, 0) before and after #1819. (b"x=1\n\\\0# c\ny=2\n", (3, 2, 1, 0), 0), // FIXME(#1825): pins the wrong value. `STRING NEWLINE NAME @@ -11558,7 +11558,7 @@ $y = 10 + match ($x) { 1 => 2, default => 0 };", /// but excluded the heredoc, on the premise that its inner nodes /// already covered every row. /// - /// `sloc` is the fixture anchor (`.claude/rules/testing.md`): + /// `sloc` is the fixture anchor (`docs/development/testing.md`): /// deleting the empty row drops it to 5 and fails this test, rather /// than leaving it quietly asserting `blank 0` about a literal with /// no interior gap left to misclassify. @@ -11610,7 +11610,7 @@ $y = 10 + match ($x) { 1 => 2, default => 0 };", /// wrapper rather than `heredoc_body` / `nowdoc_body`: for a body of /// one empty row the grammar emits **no body node at all**, so an /// arm keyed on the body would still report that row blank - /// (`.claude/rules/grammar-dispatch.md` section 6). The interpolated + /// (`docs/development/grammar_dispatch.md` section 6). The interpolated /// form checks that an interior `{$v}` — whose own nodes cover only /// their row — does not stop the empty row above it being credited. /// The PHP 7.3 indented closing marker is syntax coverage rather @@ -11688,7 +11688,7 @@ $y = 10 + match ($x) { 1 => 2, default => 0 };", /// heredoc whose closing marker is the last byte of the file. /// `check_metrics` trims and re-appends a trailing newline, so that /// shape cannot reach the parser through it at all - /// (`.claude/rules/testing.md`); `metrics_verbatim` hands the bytes + /// (`docs/development/testing.md`); `metrics_verbatim` hands the bytes /// over untouched. /// /// Unlike #1051 and #1067, no *known* defect hides in this class for @@ -14557,7 +14557,7 @@ class A { /// interior insert credits row 1 — `preproc_def` contributes only /// its own start row — so `ploc == 3` fails if that row is ever /// trimmed out of the fixture, per the fixture-decay rule in - /// `.claude/rules/testing.md`. The `blank == 1` half has no such + /// `docs/development/testing.md`. The `blank == 1` half has no such /// anchor available: deleting the dangling backslash also stops /// row 2 being credited, so a revert of the bound is the only /// evidence that half discriminates, and it was run. @@ -15088,7 +15088,7 @@ class A { /// under-subtracting in the ordinary rustfmt layout. /// /// **`shared_row` has no fixture-decay anchor, and none exists.** - /// The rule in `.claude/rules/testing.md` asks for a second axis + /// The rule in `docs/development/testing.md` asks for a second axis /// only the excluded construct contributes to, so that trimming it /// out of the fixture fails this test rather than quietly hollowing /// it. Deleting `#[cfg(test)] mod t {}` from row 0 leaves all four @@ -15208,7 +15208,7 @@ class A { /// well-formed input — measured: replacing all fifteen fixtures /// with well-formed sources of the same row count leaves this test /// green. The phantom node *is* the subject, so it is the axis to - /// anchor on (`.claude/rules/testing.md`, "Perturb the fixture as + /// anchor on (`docs/development/testing.md`, "Perturb the fixture as /// well as the production line"). /// /// Writing that anchor as `has_error()` — the obvious choice — is @@ -15365,7 +15365,7 @@ class A { /// `span == 0` needs a space opened on a genuinely zero-width node /// at column 0, and every `is_func_space` matches compound /// productions — so seeding `Stats` directly is the only shape that - /// can (`.claude/rules/testing.md`, "Pair any end-to-end test with a + /// can (`docs/development/testing.md`, "Pair any end-to-end test with a /// direct unit test on the function whose contract is verified"). #[test] #[cfg(debug_assertions)] diff --git a/src/metrics/loc/bash.rs b/src/metrics/loc/bash.rs index da2d5689a..9655fb2b2 100644 --- a/src/metrics/loc/bash.rs +++ b/src/metrics/loc/bash.rs @@ -57,7 +57,7 @@ impl Loc for BashCode { // // The heredoc is routed through its **wrapper**, // `heredoc_redirect`, rather than through `heredoc_body`, for - // `.claude/rules/grammar-dispatch.md` section 6's keeper rule — + // `docs/development/grammar_dispatch.md` section 6's keeper rule — // the same call #1396 made for PHP. `heredoc_body`'s span // excludes a leading empty body row and collapses to zero width // when the body is empty throughout, so those rows sat inside no @@ -172,7 +172,7 @@ impl Loc for BashCode { // `readonly C=3`) and as a `command`'s environment prefix // (`X=1 cmd`). The unsuffixed `VariableAssignment` below is // never emitted, so listing only it scored `a=1` zero - // logical lines (`.claude/rules/grammar-dispatch.md` §1); + // logical lines (`docs/development/grammar_dispatch.md` §1); // it stays as a defensive arm rather than being swapped. // // The last two positions need the parent gate. Both diff --git a/src/metrics/loc/elixir.rs b/src/metrics/loc/elixir.rs index bce783b39..b2de71b53 100644 --- a/src/metrics/loc/elixir.rs +++ b/src/metrics/loc/elixir.rs @@ -19,7 +19,7 @@ use super::*; /// this one rule to twenty consecutive ids (`Elixir::QuotedContent` /// through `QuotedContent20`), and a name comparison stays correct when a /// grammar bump adds a twenty-first -/// (`.claude/rules/grammar-dispatch.md` section 1). +/// (`docs/development/grammar_dispatch.md` section 1). /// /// The rule calls that a small runtime cost, and it is: against a /// twenty-variant `kind_id` pattern over a 36 000-row Elixir file, the diff --git a/src/metrics/loc/irules.rs b/src/metrics/loc/irules.rs index b34f14dc9..9f1946843 100644 --- a/src/metrics/loc/irules.rs +++ b/src/metrics/loc/irules.rs @@ -92,7 +92,7 @@ impl Loc for IrulesCode { // the arm rather than between the alternatives because a // comment *inside* a match pattern makes rustfmt emit the // whole match verbatim while `cargo fmt --check` still exits - // 0 — see `.claude/rules/formatting.md`. + // 0 — see `docs/development/formatting.md`. Irules::ExprCmd | Irules::Command if ancestors .parent(node) diff --git a/src/metrics/loc/php.rs b/src/metrics/loc/php.rs index bcf5bf297..3fc29297a 100644 --- a/src/metrics/loc/php.rs +++ b/src/metrics/loc/php.rs @@ -48,7 +48,7 @@ impl Loc for PhpCode { // The wrapper is routed rather than `HeredocBody` / `NowdocBody` // because a body of one empty row emits no body node at all — // `heredoc` is the node present for every spelling - // (`.claude/rules/grammar-dispatch.md` section 6). Its span runs + // (`docs/development/grammar_dispatch.md` section 6). Its span runs // from `<<<` to the closing marker, so its interior is the body // rows plus that marker's row, which is code either way. // diff --git a/src/metrics/loc/tcl.rs b/src/metrics/loc/tcl.rs index 88b022fc5..6b6f7559a 100644 --- a/src/metrics/loc/tcl.rs +++ b/src/metrics/loc/tcl.rs @@ -91,7 +91,7 @@ impl Loc for TclCode { // the arm rather than between the alternatives because a // comment *inside* a match pattern makes rustfmt emit the // whole match verbatim while `cargo fmt --check` still exits - // 0 — see `.claude/rules/formatting.md`. + // 0 — see `docs/development/formatting.md`. Tcl::ExprCmd | Tcl::Command if ancestors .parent(node) diff --git a/src/metrics/mod.rs b/src/metrics/mod.rs index de896722f..5094d64a9 100644 --- a/src/metrics/mod.rs +++ b/src/metrics/mod.rs @@ -43,7 +43,7 @@ mod bash_test_connective_tests; // `FIXTURES`, not here: a module gate is an outer `cfg`, so naming only // the `FIXTURES` features would delete that Bash/Lua/C test from a build // enabling exactly the languages it exists to cover -// (`.claude/rules/testing.md`, #1286). +// (`docs/development/testing.md`, #1286). #[cfg(test)] #[cfg(any( feature = "bash", diff --git a/src/metrics/nargs.rs b/src/metrics/nargs.rs index a9c5f909d..292a25789 100644 --- a/src/metrics/nargs.rs +++ b/src/metrics/nargs.rs @@ -29,11 +29,6 @@ use crate::*; /// This metric counts the number of arguments /// of functions/closures. /// -/// A callable is whatever opens a `Function` space and is `is_func`: -/// a Kotlin or C# primary constructor is one, its space being the -/// parameter list in the class header (#1828), so its parameters are -/// its own and never the class's. -/// /// Unlike the per-function fields of cyclomatic, cognitive and nexits /// (#1284), the extrema and the averages here read different /// populations (#1809): @@ -499,19 +494,16 @@ impl NArgs for GoCode { } } -// A function or a secondary constructor lists `parameter`s in a -// `function_value_parameters`; a primary constructor (#1828) lists -// `class_parameter`s — each `[val|var] name: Type [= default]` — in a -// `class_parameters`. One wrapper per parameter in both, so a positive -// count needs no comment or punctuation exclusion. fn compute_kotlin_func_args(node: &Node, nargs: &mut usize) { - let (list, param) = if node.kind_id() == Kotlin::PrimaryConstructor { - (Kotlin::ClassParameters, Kotlin::ClassParameter) - } else { - (Kotlin::FunctionValueParameters, Kotlin::Parameter) - }; - if let Some(params) = node.children().find(|c| c.kind_id() == list) { - *nargs += params.children().filter(|n| n.kind_id() == param).count(); + if let Some(params) = node + .children() + .find(|c| c.kind_id() == Kotlin::FunctionValueParameters) + { + params.act_on_child(&mut |n| { + if n.kind_id() == Kotlin::Parameter { + *nargs += 1; + } + }); } } @@ -776,62 +768,10 @@ implement_metric_trait!( CcommentCode, BashCode, PhpCode, + CsharpCode, RubyCode ); -// tree-sitter-c-sharp wraps an ordinary parameter in a `parameter` -// node but spells a `params` array through the hidden -// `_parameter_array` rule, whose pieces — the attribute lists, the -// `params` token, the type and the name — land directly in the list. -// The shared negative filter counted every one of them, so -// `void F(params int[] xs)` reported 3 and `void F([A] params int[] xs)` -// 4. Count positively instead: one per `parameter`, one per `params` -// token, which is the one child the hidden rule always emits. The same -// shape sits in an indexer's `bracketed_parameter_list`, which the -// `parameters` field also reaches. -// -// A comment in the list is neither, so the #1201 exclusion holds -// without naming it; a bare lambda parameter (`x => x`) is the -// childless `implicit_parameter` the field holds instead of a list -// (#1185), still answered by `is_bare_param`. -fn csharp_count_params(params: &Node) -> usize { - params - .children() - .filter(|c| matches!(c.kind_id().into(), Csharp::Parameter | Csharp::Params)) - .count() -} - -// A primary constructor *is* its `parameter_list` — the `FuncOpener` -// row of `roles/csharp.rs` opens the space on that node (#1828) — so -// the list is the node itself; every other callable holds its list in -// the `parameters` field. -fn csharp_compute_args(node: &Node, nargs: &mut usize) { - if node.kind_id() == Csharp::ParameterList { - *nargs += csharp_count_params(node); - return; - } - if let Some(params) = node.child_by_field_name("parameters") { - if CsharpCode::is_bare_param(¶ms) { - *nargs += 1; - return; - } - *nargs += csharp_count_params(¶ms); - } -} - -impl NArgs for CsharpCode { - fn compute<'a>(node: &Node<'a>, code: &[u8], ancestors: Ancestors<'a, '_>, stats: &mut Stats) { - if Self::is_func_with_code(node, code, ancestors) { - csharp_compute_args(node, &mut stats.fn_nargs); - return; - } - - if Self::is_closure(node, ancestors) { - csharp_compute_args(node, &mut stats.closure_nargs); - } - } -} - // A record's compact constructor (`record R(int a, int b) { R { … } }`, // JLS 8.10.4) declares no formal parameter list of its own: the grammar // gives `compact_constructor_declaration` only `name` and `body` fields, @@ -908,9 +848,7 @@ impl NArgs for GroovyCode { clippy::too_many_lines )] mod tests { - use crate::test_support::{ - check_func_space, check_func_space_only_shim, check_metrics_only_shim, child_space, - }; + use crate::test_support::{check_func_space_only_shim, check_metrics_only_shim}; use super::*; @@ -3255,81 +3193,6 @@ mod tests { ); } - /// A `params` array is one parameter. The grammar's hidden - /// `_parameter_array` rule flattens its pieces into the list, so the - /// shared negative filter read `F(params int[] xs)` as 3 and the - /// attributed form as 4; the positive count reads one each, and the - /// ordinary parameters beside it — attributed, `ref`/`out`/`in`, - /// defaulted — still one each. Every C# callable shape that can - /// carry one is a row, each pinned by its own space, so the file - /// total cannot hide one shape compensating for another. - #[cfg(feature = "csharp")] - #[test] - fn csharp_params_array_is_one_parameter() { - check_spaces::( - "class C { - public C(params int[] xs) { } - void M(params int[] ys) { } - void A([Attr] params int[] zs) { } - void B([Attr] int a, ref int b, out int c, in int d, int e = 1, params int[] f) { } - int this[params int[] i] => 0; - void L() { - var f = (params int[] a) => 0; - var g = x => x; - var h = delegate(int q, params int[] r) { }; - } - }", - "params.cs", - |space| { - let class = &space.spaces[0]; - let rows: Vec<(Option<&str>, u64, u64)> = class - .spaces - .iter() - .map(|s| { - ( - s.name.as_deref(), - s.metrics.nargs.function_args(), - s.metrics.nargs.closure_args(), - ) - }) - .collect(); - assert_eq!( - rows, - vec![ - (Some("C"), 1, 0), - (Some("M"), 1, 0), - (Some("A"), 1, 0), - (Some("B"), 6, 0), - (Some(""), 1, 0), - (Some("L"), 0, 0), - ] - ); - let l = &class.spaces[5]; - let lambdas: Vec = l - .spaces - .iter() - .map(|s| s.metrics.nargs.closure_args()) - .collect(); - assert_eq!(lambdas, vec![1, 1, 2]); - assert_eq!(space.metrics.nargs.function_args_sum(), 10); - assert_eq!(space.metrics.nargs.closure_args_sum(), 4); - }, - ); - // The count rests on `_parameter_array` staying hidden: a grammar - // that promoted it to a named wrapper around its `params` token - // would read 2 per array through `Parameter | Params`. Pinned - // per lesson 34 so the promotion fails here, not in a corpus. - let parser = CsharpParser::new( - b"class C { void M(params int[] ys) { } }".to_vec(), - std::path::Path::new("hidden.cs"), - None, - ); - assert!( - !crate::test_support::ast_has_kind_id(&parser, Csharp::ParameterArray as u16), - "`_parameter_array` is a hidden rule and never emitted" - ); - } - #[cfg(feature = "typescript")] #[test] fn tsx_function_and_arrow() { @@ -3909,336 +3772,6 @@ proc g {x y z} { puts $x }", ); } - /// The `(name, kind, own fn args, own closure args)` rows of a space - /// tree in walk order, for the primary-constructor fixtures below: - /// two constructors share their class's name, so the rows are read - /// positionally rather than by name. - #[cfg(any(feature = "kotlin", feature = "csharp"))] - fn space_rows(space: &FuncSpace) -> Vec<(String, SpaceKind, u64, u64)> { - fn walk(space: &FuncSpace, rows: &mut Vec<(String, SpaceKind, u64, u64)>) { - rows.push(( - space.name.clone().unwrap_or_default(), - space.kind, - space.metrics.nargs.function_args(), - space.metrics.nargs.closure_args(), - )); - for child in &space.spaces { - walk(child, rows); - } - } - let mut rows = Vec::new(); - for child in &space.spaces { - walk(child, &mut rows); - } - rows - } - - /// #1828's reproducer: a six-parameter primary constructor counted - /// nowhere, so `bca check --threshold nargs=5` passed it. It opens a - /// `Function` space named after its class (the `FuncOpener` row of - /// `roles/kotlin.rs`), which owns the six; `nom` counts it as the - /// callable the average divides by. Every row read 0 on `main`. - #[cfg(feature = "kotlin")] - #[test] - fn kotlin_primary_constructor_owns_its_parameters() { - check_spaces::( - "data class D(val a: Int, val b: Int, val c: Int, val d: Int, val e: Int, val f: Int)", - "d.kt", - |space| { - assert_eq!( - space_rows(&space), - [ - ("D".to_owned(), SpaceKind::Class, 0, 0), - ("D".to_owned(), SpaceKind::Function, 6, 0), - ] - ); - let ctor = &space.spaces[0].spaces[0]; - assert_eq!(ctor.metrics.nargs.own_args(), 6); - assert_eq!((ctor.start_line, ctor.end_line), (1, 1)); - assert_eq!(space.metrics.nom.functions_sum(), 1); - assert_eq!(space.metrics.nargs.function_args_sum(), 6); - assert!((space.metrics.nargs.function_args_average() - 6.0).abs() < 1e-9); - }, - ); - } - - /// The two constructor spellings beside each other, with the field - /// lambda that made the container route wrong: the class keeps the - /// lambda's two closure parameters (a Kotlin lambda opens no - /// space), the primary constructor owns exactly its two, the - /// secondary its one. The superclass call `Base(a)` is a sibling of - /// the parameter list, so the class still owns that ABC branch - /// (#1456), and the `val a` property is still the class's own - /// attribute, not the constructor's. - /// The secondary constructor reads `` as it did before - /// #1828 — `secondary_constructor` has no `name` field and no - /// override names it — a gap of its own, not this test's. - #[cfg(feature = "kotlin")] - #[test] - fn kotlin_primary_and_secondary_constructors_each_own_their_parameters() { - check_func_space::( - "class P(val a: Int, b: Int) : Base(a) { - constructor(x: Int) : this(x, x) - val cmp = { p: Int, q: Int -> p } - }", - "p.kt", - |space| { - assert_eq!( - space_rows(&space), - [ - ("P".to_owned(), SpaceKind::Class, 0, 2), - ("P".to_owned(), SpaceKind::Function, 2, 0), - ("".to_owned(), SpaceKind::Function, 1, 0), - ] - ); - let class = &space.spaces[0]; - assert_eq!(class.metrics.abc.branches(), 1, "`Base(a)` is the class's"); - assert_eq!(class.spaces[0].metrics.abc.branches(), 0); - assert_eq!(class.spaces[1].metrics.abc.branches(), 1, "`this(x, x)`"); - // `val a` (a parameter property) and `val cmp` are both - // the class's own attributes; the constructor declares - // none — `kotlin_parameter_properties_stay_the_classs` - // pins the split. - assert_eq!(class.metrics.npa.class_na(), 2); - assert_eq!(class.spaces[0].metrics.npa.class_na(), 0); - assert_eq!(class.metrics.nom.functions_sum(), 2); - assert_eq!(class.metrics.nom.closures_sum(), 1); - }, - ); - } - - /// Every preamble the grammar permits before the list, and the - /// shapes that must not open one: the `constructor` keyword, an - /// annotation and a visibility modifier on it, an `enum class` and - /// an `annotation class`, empty parens (a declared zero-parameter - /// constructor), a comment and a trailing comma in the list, a - /// default, a local class inside a function (billed to the local - /// class's constructor, not to `outer`), and a class with no list - /// at all, which opens nothing. - #[cfg(feature = "kotlin")] - #[test] - fn kotlin_primary_constructor_preambles() { - check_spaces::( - "class E constructor(x: Int) - class F @Inject private constructor(x: Int, y: Int) - enum class G(val v: Int) { A(1) } - annotation class H(val x: Int) - class N - class Z() - class C(val a: Int, /* c */ val b: Int = 2,) - fun outer(p: Int) { class Loc(val q: Int, val r: Int) }", - "preambles.kt", - |space| { - let f = |n: &str, k, a| (n.to_owned(), k, a, 0); - assert_eq!( - space_rows(&space), - [ - f("E", SpaceKind::Class, 0), - f("E", SpaceKind::Function, 1), - f("F", SpaceKind::Class, 0), - f("F", SpaceKind::Function, 2), - f("G", SpaceKind::Class, 0), - f("G", SpaceKind::Function, 1), - f("H", SpaceKind::Class, 0), - f("H", SpaceKind::Function, 1), - f("N", SpaceKind::Class, 0), - f("Z", SpaceKind::Class, 0), - f("Z", SpaceKind::Function, 0), - f("C", SpaceKind::Class, 0), - f("C", SpaceKind::Function, 2), - f("outer", SpaceKind::Function, 1), - f("Loc", SpaceKind::Class, 0), - f("Loc", SpaceKind::Function, 2), - ] - ); - }, - ); - } - - /// A primary constructor's space holds its parameter list and no - /// code, so a parameterless one — `class Z()` — has no Halstead - /// volume and reads the `mi.*` `0.0` sentinel, which `bca check` - /// and `bca report` skip (#1621); a parameterised one's list is its - /// volume. Pinned so the exemption is known to cover the new rows, - /// and so a serialiser reading `0.0` literally knows why one is - /// there. `check_func_space` because `mi` pulls its own inputs. - #[cfg(feature = "kotlin")] - #[test] - fn kotlin_parameterless_primary_constructor_is_mi_empty() { - check_func_space::( - "class Z() -class A(val x: Int)", - "z.kt", - |space| { - let z = &child_space(&space, "Z").spaces[0]; - let a = &child_space(&space, "A").spaces[0]; - assert_eq!((z.kind, a.kind), (SpaceKind::Function, SpaceKind::Function)); - assert!(z.metrics.mi.is_empty(), "no list, no volume"); - assert_eq!(z.metrics.mi.original(), 0.0); - assert!(!a.metrics.mi.is_empty(), "the list is the space's code"); - }, - ); - } - - /// A default spelled as a lambda is part of the signature, so its - /// parameters are the constructor's closure parameters, exactly as - /// a function's spaceless lambdas are its own (#1196): `own_args` - /// reads 1 + 2. Pinned so the row's number is known to carry the - /// default's lambda rather than the written arity alone. - #[cfg(feature = "kotlin")] - #[test] - fn kotlin_primary_constructor_default_lambda_is_its_closure() { - check_spaces::( - "class L(val f: (Int, Int) -> Int = { a, b -> a + b })", - "l.kt", - |space| { - assert_eq!( - space_rows(&space), - [ - ("L".to_owned(), SpaceKind::Class, 0, 0), - ("L".to_owned(), SpaceKind::Function, 1, 2), - ] - ); - assert_eq!(space.spaces[0].spaces[0].metrics.nargs.own_args(), 3); - }, - ); - } - - /// #1828's C# reproducer: a C# 12 primary constructor is the - /// `parameter_list` hanging directly off the type declaration — the - /// `FuncOpener` row of `roles/csharp.rs` gates it on that parent — - /// and it opens a `Function` space named after the type, owning the - /// six. Every row read 0 on `main`. - #[cfg(feature = "csharp")] - #[test] - fn csharp_primary_constructor_owns_its_parameters() { - check_spaces::( - "public class C(int a, int b, int c, int d, int e, int f) - { - public int Sum() => a + b + c + d + e + f; - }", - "c.cs", - |space| { - assert_eq!( - space_rows(&space), - [ - ("C".to_owned(), SpaceKind::Class, 0, 0), - ("C".to_owned(), SpaceKind::Function, 6, 0), - ("Sum".to_owned(), SpaceKind::Function, 0, 0), - ] - ); - let ctor = &space.spaces[0].spaces[0]; - assert_eq!(ctor.metrics.nargs.own_args(), 6); - assert_eq!((ctor.start_line, ctor.end_line), (1, 1)); - assert_eq!(space.metrics.nom.functions_sum(), 2); - assert!((space.metrics.nargs.function_args_average() - 3.0).abs() < 1e-9); - }, - ); - } - - /// Every type that can carry a primary constructor, and the shapes - /// around it: a positional `record`, `record struct` and `record - /// class`, a `struct`, a class delegating to its base (the - /// `base_list` is a sibling of the list, so the class keeps that - /// ABC branch — #1456), a class with no list and one with empty - /// parens, a generic class whose `type_parameter_list` is a - /// different kind, a comment in the list beside an explicit - /// `this(…)` constructor, nesting in a namespace and in a class, - /// and a method's own list, which opens nothing of its own. - #[cfg(feature = "csharp")] - #[test] - fn csharp_primary_constructor_shapes() { - check_func_space::( - "public record R(int A, int B); - public record struct RS(int A); - public record class RC(int A, int B, int C); - public struct S(int x) { } - public class Sub(int x) : Base(x) { } - public class N { } - public class Z() { } - public class G(T x, [Attr] int y = 1, params int[] zs) { } - public class H(int a /* c */, int b) { public H() : this(1, 2) { } } - namespace Ns { public class Nested(int q) { public class Inner(int r, int s) { void M(int t) { } } } }", - "shapes.cs", - |space| { - let f = |n: &str, k, a| (n.to_owned(), k, a, 0); - assert_eq!( - space_rows(&space), - [ - f("R", SpaceKind::Class, 0), - f("R", SpaceKind::Function, 2), - f("RS", SpaceKind::Class, 0), - f("RS", SpaceKind::Function, 1), - f("RC", SpaceKind::Class, 0), - f("RC", SpaceKind::Function, 3), - f("S", SpaceKind::Class, 0), - f("S", SpaceKind::Function, 1), - f("Sub", SpaceKind::Class, 0), - f("Sub", SpaceKind::Function, 1), - f("N", SpaceKind::Class, 0), - f("Z", SpaceKind::Class, 0), - f("Z", SpaceKind::Function, 0), - f("G", SpaceKind::Class, 0), - f("G", SpaceKind::Function, 3), - f("H", SpaceKind::Class, 0), - f("H", SpaceKind::Function, 2), - f("H", SpaceKind::Function, 0), - f("Nested", SpaceKind::Class, 0), - f("Nested", SpaceKind::Function, 1), - f("Inner", SpaceKind::Class, 0), - f("Inner", SpaceKind::Function, 2), - f("M", SpaceKind::Function, 1), - ] - ); - let sub = child_space(&space, "Sub"); - assert_eq!(sub.metrics.abc.branches(), 1, "`: Base(x)` stays the class's"); - assert_eq!(sub.spaces[0].metrics.abc.branches(), 0); - }, - ); - } - - /// The classic and primary spellings of one constructor agree, so a - /// migration to primary constructors moves no `nargs` number — the - /// `params` row included, which is why its miscount was fixed - /// alongside (`csharp_params_array_is_one_parameter`). - #[cfg(feature = "csharp")] - #[test] - fn csharp_primary_and_classic_constructors_agree() { - check_spaces::( - "class Primary(int a, string b, params int[] rest) { } - class Classic { public Classic(int a, string b, params int[] rest) { } }", - "twins.cs", - |space| { - let primary = child_space(&space, "Primary").spaces[0] - .metrics - .nargs - .own_args(); - let classic = child_space(&space, "Classic").spaces[0] - .metrics - .nargs - .own_args(); - assert_eq!((primary, classic), (3, 3)); - }, - ); - } - - /// Error recovery: a list with no closing paren parses to an `ERROR` - /// root holding the `parameter` nodes bare, with no `parameter_list` - /// at all, so no constructor space opens. This cannot see the row's - /// parent gate — with no list node there is nothing for the gate to - /// reject, and an ungated row answers the same here — it records - /// the recovery shape, so a grammar bump that starts recovering the - /// list under `ERROR` changes this row rather than a corpus - /// snapshot. - #[cfg(feature = "csharp")] - #[test] - fn csharp_unclosed_primary_constructor_opens_nothing() { - check_spaces::("class C(int a,", "broken.cs", |space| { - assert_eq!(space_rows(&space), []); - assert_eq!(space.metrics.nargs.total(), 0); - }); - } - #[cfg(feature = "php")] #[test] fn php_no_functions_and_closures() { @@ -5085,7 +4618,7 @@ when HTTP_REQUEST { log local0. \"hit\" } /// through the singular `parameter` field. // Gated on the union of the languages `cases()` has a row for, so a // build enabling none of them drops the module rather than tripping its -// `checked > 0` guard (`.claude/rules/testing.md`, #1286). The +// `checked > 0` guard (`docs/development/testing.md`, #1286). The // closure-channel test below reads a strict subset of that table and so // carries its own narrower gate. #[cfg(test)] @@ -5563,7 +5096,7 @@ mod comments_in_parameter_lists { /// short-circuits before the child walk, so a comment on an /// un-parenthesised lambda parameter is safe only because of where /// the *grammar* puts it. Confirmed rather than reasoned, per - /// `.claude/rules/grammar-dispatch.md`: dumping + /// `docs/development/grammar_dispatch.md`: dumping /// `x /* c */ -> x` shows `block_comment` as a **sibling** of the /// bare `identifier`, and the `parameters` field points at that /// childless identifier. @@ -5773,7 +5306,7 @@ mod c_family_return_type_declarators { // carried — `(0, 0)` is what a walk returning `None` for // *everything* reports, so the row passed with the whole // chain dead while 28 others failed - // (`.claude/rules/testing.md`, "Seed the state you claim to + // (`docs/development/testing.md`, "Seed the state you claim to // assert on"). ("int (*arr(int a, int b))[4] { return 0; }", (0, 2)), ]) diff --git a/src/metrics/nexits.rs b/src/metrics/nexits.rs index cfb8c7c2a..efaf1949b 100644 --- a/src/metrics/nexits.rs +++ b/src/metrics/nexits.rs @@ -129,7 +129,7 @@ where /// The `Exit` row of a language's role table, read as its exit count: /// one owner per explicit exit (#1697). Per-language rationale — which /// kinds are exits and which spellings are deliberately not — sits on -/// the row (`.claude/rules/macro-comments.md`). +/// the row (`docs/development/formatting.md`). macro_rules! impl_exit_from_row { ($code:ty, $roles:path) => { impl Exit for $code { diff --git a/src/metrics/npa.rs b/src/metrics/npa.rs index 0eaee05d6..22b1630d8 100644 --- a/src/metrics/npa.rs +++ b/src/metrics/npa.rs @@ -2344,40 +2344,6 @@ mod tests { ); } - /// A parameter property is the class's attribute, not its primary - /// constructor's — the constructor opens a function space of its own - /// since #1828, inside which each parameter is visited, so the count - /// is read at the class declaration instead. The class's **own** - /// counts carry all three (`a`, `b` public; `c` private) and the - /// constructor's own carry none; the private one keeps `class_npa` - /// independent of `class_na`. Before the move the class's own - /// `class_na` read 0 and the constructor's 3, with only the sums - /// unchanged. - #[cfg(feature = "kotlin")] - #[test] - fn kotlin_parameter_properties_stay_the_classs() { - check_func_space::( - "class C(val a: Int, var b: Int, private val c: Int, d: Int) { - val e: Int = d - }", - "own.kt", - |space| { - let class = child_space(&space, "C"); - let own = |s: &FuncSpace| (s.metrics.npa.class_na(), s.metrics.npa.class_npa()); - assert_eq!(own(class), (4, 3), "a, b, c, e; c is private"); - assert_eq!(own(&class.spaces[0]), (0, 0), "the constructor owns none"); - assert_eq!(class.spaces[0].kind, SpaceKind::Function); - assert_eq!( - ( - class.metrics.npa.class_na_sum(), - class.metrics.npa.class_npa_sum() - ), - (4, 3) - ); - }, - ); - } - #[cfg(feature = "kotlin")] #[test] fn kotlin_primary_constructor_private_param_property() { diff --git a/src/metrics/npa/kotlin.rs b/src/metrics/npa/kotlin.rs index 0a6bafe88..48a7b1ef3 100644 --- a/src/metrics/npa/kotlin.rs +++ b/src/metrics/npa/kotlin.rs @@ -29,27 +29,6 @@ fn kotlin_count_property_attrs(decl: &Node) -> usize { .max(1) } -// The `val` / `var` parameters of `class`'s primary constructor, if it -// has one: `class_declaration → primary_constructor → class_parameters -// → class_parameter`. A parameter without the keyword is a plain -// constructor argument. -fn kotlin_parameter_properties<'a>(class: &Node<'a>) -> impl Iterator> { - use Kotlin::*; - class - .first_child(|id| id == PrimaryConstructor) - .and_then(|ctor| ctor.first_child(|id| id == ClassParameters)) - .into_iter() - .flat_map(|params| params.children()) - // role-bypass: allow(DeclKeyword, DocTarget) — whether the parameter declares a - // property, a question about the parameter, not whether the token is a - // declaration keyword or the parameter a doc target - .filter(|p| { - p.kind_id() == ClassParameter - && p.children() - .any(|c| matches!(c.kind_id().into(), Val | Var)) - }) -} - impl Npa for KotlinCode { fn compute<'a>( node: &Node<'a>, @@ -57,27 +36,25 @@ impl Npa for KotlinCode { ancestors: Ancestors<'a, '_>, stats: &mut Stats, ) { + use crate::roles::kotlin::member; use Kotlin::*; match node.kind_id().into() { // A `ClassParameter` carrying `val` / `var` is a Kotlin - // primary-constructor parameter property — an attribute of - // the class, counted once toward it. Parameters without - // `val`/`var` are plain constructor arguments, not - // attributes. Read at the class declaration rather than at - // each parameter: the primary constructor opens a function - // space of its own (#1828), so a parameter is visited inside - // that space and a count there would make the property the - // constructor's — the same reason TypeScript scans a - // constructor's parameter properties from the class body. - // role-bypass: allow(Container) — which declaration holds the - // constructor, not whether it opens a space - ClassDeclaration => { - for param in kotlin_parameter_properties(node) { - stats.class_na += 1; - if kotlin_is_public(¶m) { - stats.class_npa += 1; - } + // primary-constructor parameter property — counts once toward + // the enclosing class. Parameters without `val`/`var` are plain + // constructor arguments, not attributes. + // role-bypass: allow(DeclKeyword, DocTarget) — whether the parameter declares a + // property, a question about the parameter, not whether the token is a + // declaration keyword or the parameter a doc target + ClassParameter + if node + .children() + .any(|c| matches!(c.kind_id().into(), Val | Var)) => + { + stats.class_na += 1; + if kotlin_is_public(node) { + stats.class_npa += 1; } } // Every `ClassBody` we visit attributes its direct @@ -88,39 +65,31 @@ impl Npa for KotlinCode { // semantics. Nested class / interface bodies start a new // func_space (handled by `spaces.rs`), so they do NOT leak // attributes into their outer space. - ClassBody => kotlin_count_body_properties(node, code, ancestors, stats), - _ => {} - } - } -} - -// The properties declared in a class or interface body. -// tree-sitter-kotlin elides the `class_member_declaration` and -// `declaration` rule layers when those rules are pure forwarding -// choices, so property declarations appear as direct children of -// `class_body`. Each member is asked under its own chain, the body's -// plus the body. -fn kotlin_count_body_properties<'a>( - body: &Node<'a>, - code: &[u8], - ancestors: Ancestors<'a, '_>, - stats: &mut Stats, -) { - use crate::roles::kotlin::member; - let is_interface = kotlin_class_body_is_interface(body, ancestors); - let under = ancestors.of_children(body); - let members = under.get(); - for prop in body.children().filter(|c| member::owns(c, code, members)) { - let attrs = kotlin_count_property_attrs(&prop); - if is_interface { - stats.interface_na += attrs; - // Interface members are always public. - stats.interface_npa += attrs; - } else { - stats.class_na += attrs; - if kotlin_is_public(&prop) { - stats.class_npa += attrs; + ClassBody => { + let is_interface = kotlin_class_body_is_interface(node, ancestors); + // tree-sitter-kotlin elides the `class_member_declaration` + // and `declaration` rule layers when those rules are pure + // forwarding choices, so property declarations appear as + // direct children of `class_body`. + // Each member is asked under its own chain, the body's + // plus the body. + let under = ancestors.of_children(node); + let members = under.get(); + for prop in node.children().filter(|c| member::owns(c, code, members)) { + let attrs = kotlin_count_property_attrs(&prop); + if is_interface { + stats.interface_na += attrs; + // Interface members are always public. + stats.interface_npa += attrs; + } else { + stats.class_na += attrs; + if kotlin_is_public(&prop) { + stats.class_npa += attrs; + } + } + } } + _ => {} } } } diff --git a/src/metrics/npa/shared.rs b/src/metrics/npa/shared.rs index da36b8c5a..2a500f9cd 100644 --- a/src/metrics/npa/shared.rs +++ b/src/metrics/npa/shared.rs @@ -710,7 +710,7 @@ fn cpp_recovered_member_pointers(outer: &Node) -> RecoveredMemberPointers { // `None`. The name is the innermost `qualified_identifier`'s // `type_identifier`; it counts when the grammar invented it // (zero-width, tested by width rather than `is_missing()` — see -// `.claude/rules/grammar-dispatch.md`) or left an `ERROR` beside it. +// `docs/development/grammar_dispatch.md`) or left an `ERROR` beside it. fn cpp_recovered_member_pointer_parameter(parameter: &Node) -> Option { let qualified = parameter .child_by_field_name("type") diff --git a/src/metrics/npm.rs b/src/metrics/npm.rs index bc09ecc9e..2fc2cae03 100644 --- a/src/metrics/npm.rs +++ b/src/metrics/npm.rs @@ -1698,108 +1698,6 @@ mod tests { ); } - /// A C# 12 primary constructor and a positional record's constructor - /// are public methods of their type (#1828): the list hangs off the - /// declaration, not its body, so the body scan never saw one. The - /// primary constructor takes no accessibility modifier — it is - /// public by the language rule — so an internal class's is still - /// counted public here, as the class's `public` members are. Each - /// type is pinned alone, so the sum cannot hide one shape's miss - /// behind another's; `N` is the control with no constructor. - #[cfg(feature = "csharp")] - #[test] - fn csharp_primary_constructor_is_a_public_method() { - check_func_space::( - "public class C(int a) { public void M() { } } - public record R(int A, int B); - public record struct RS(int A); - public struct S(int x) { } - internal class I(int a) { } - public class N { public void M() { } }", - "primary.cs", - |space| { - let rows: Vec<(Option<&str>, u64, u64)> = space - .spaces - .iter() - .map(|s| { - ( - s.name.as_deref(), - s.metrics.npm.class_nm_sum(), - s.metrics.npm.class_npm_sum(), - ) - }) - .collect(); - assert_eq!( - rows, - [ - (Some("C"), 2, 2), - (Some("R"), 1, 1), - (Some("RS"), 1, 1), - (Some("S"), 1, 1), - (Some("I"), 1, 1), - (Some("N"), 1, 1), - ] - ); - }, - ); - } - - /// A Kotlin primary constructor is a method of its class (#1828), - /// public by default like a secondary one, non-public under its own - /// `private` / `internal` / `protected`, and — with nothing written — - /// under two class modifiers that cap it: a `sealed` class's - /// constructors are `protected` by default and may be written only - /// `private` or `protected`, an `enum class`'s are `private`. - /// `data` is a class modifier that changes nothing. Each class is - /// pinned alone. - #[cfg(feature = "kotlin")] - #[test] - fn kotlin_primary_constructor_visibility() { - check_func_space::( - "class A(x: Int) - class B private constructor(x: Int) - class C internal constructor(x: Int) - class D protected constructor(x: Int) - class E public constructor(x: Int) - sealed class F(x: Int) - enum class G(val v: Int) { A(1) } - data class H(val x: Int) - sealed class I protected constructor(x: Int) - sealed class J private constructor(x: Int) - class N", - "ctors.kt", - |space| { - let rows: Vec<(Option<&str>, u64, u64)> = space - .spaces - .iter() - .map(|s| { - ( - s.name.as_deref(), - s.metrics.npm.class_nm_sum(), - s.metrics.npm.class_npm_sum(), - ) - }) - .collect(); - assert_eq!( - rows, - [ - (Some("A"), 1, 1), - (Some("B"), 1, 0), - (Some("C"), 1, 0), - (Some("D"), 1, 0), - (Some("E"), 1, 1), - (Some("F"), 1, 0), - (Some("G"), 1, 0), - (Some("H"), 1, 1), - (Some("I"), 1, 0), - (Some("J"), 1, 0), - (Some("N"), 0, 0), - ] - ); - }, - ); - } - #[cfg(feature = "php")] #[test] fn php_no_class_methods() { @@ -2063,8 +1961,7 @@ mod tests { #[test] fn kotlin_data_class_methods() { // `data class` compiler-generated members are NOT counted — - // only user-written `fun` declarations, and the written primary - // constructor, a public method as a secondary one is (#1828). + // only user-written `fun` declarations. check_metrics::( "data class Point(val x: Int, val y: Int) { fun manhattan(): Int = x + y @@ -2072,8 +1969,8 @@ mod tests { }", "foo.kt", |metric| { - assert_eq!(metric.npm.class_npm_sum(), 2); - assert_eq!(metric.npm.class_nm_sum(), 3); + assert_eq!(metric.npm.class_npm_sum(), 1); + assert_eq!(metric.npm.class_nm_sum(), 2); insta::assert_json_snapshot!(metric.npm); }, ); @@ -2302,8 +2199,7 @@ class C { #[test] fn kotlin_init_block_not_a_method() { // `init` blocks are anonymous initializers — they are not - // function declarations and don't count toward `nm`/`npm`. The - // primary constructor `(val n: Int)` and `get` are the two. + // function declarations and don't count toward `nm`/`npm`. check_metrics::( "class C(val n: Int) { init { require(n >= 0) } @@ -2311,8 +2207,8 @@ class C { }", "foo.kt", |metric| { - assert_eq!(metric.npm.class_npm_sum(), 2); - assert_eq!(metric.npm.class_nm_sum(), 2); + assert_eq!(metric.npm.class_npm_sum(), 1); + assert_eq!(metric.npm.class_nm_sum(), 1); insta::assert_json_snapshot!(metric.npm); }, ); diff --git a/src/metrics/npm/csharp.rs b/src/metrics/npm/csharp.rs index 12b1cc43a..f76f71ff6 100644 --- a/src/metrics/npm/csharp.rs +++ b/src/metrics/npm/csharp.rs @@ -72,27 +72,8 @@ impl Npm for CsharpCode { ancestors: Ancestors<'a, '_>, stats: &mut Stats, ) { - use crate::roles::csharp::func_opener; use Csharp::*; - // A primary constructor is the `parameter_list` child of the - // type declaration itself, not of its `declaration_list` - // (#1828): counted here, where the walk is still on the class - // space — the list's own function space opens one node later. - // Whether a list under this node is one is the `FuncOpener` - // row's question, asked of the list under the node's own chain, - // so the row's parent gate has one copy. Its accessibility is - // the type's (C# 12 §15.8.1, "the primary constructor is - // public"), with no member modifier of its own to read, so - // `csharp_is_explicit_public` does not apply. - // role-bypass: allow(FuncOpener) — a traversal step to the list - // the row then judges, not whether this node opens a space - if let Some(list) = node.first_child(|id| id == ParameterList) - && func_opener::is_callable(&list, code, ancestors.of_children(node).get()) - { - stats.class_nm += 1; - stats.class_npm += 1; - } if !matches!(node.kind_id().into(), DeclarationList) { return; } diff --git a/src/metrics/npm/kotlin.rs b/src/metrics/npm/kotlin.rs index 778e71573..c04400394 100644 --- a/src/metrics/npm/kotlin.rs +++ b/src/metrics/npm/kotlin.rs @@ -11,28 +11,6 @@ use super::*; // Re-uses the visibility helper from the `Npa` impl. Kotlin's default // visibility is `public`, the opposite of Java's -// A primary constructor's visibility is written on the constructor -// itself (`class F private constructor(x: Int)`), read by the shared -// helper off its `modifiers`. Two class modifiers cap it: a `sealed` -// class's constructors are `protected` by default and may be written -// only `private` or `protected` (the compiler rejects any other), and -// an `enum class`'s are always `private`. Neither is a public method, -// whatever is written, so the written visibility is not consulted. -fn kotlin_primary_constructor_is_public(class: &Node, ctor: &Node) -> bool { - let restricted_class = class - .first_child(|id| id == Kotlin::Modifiers) - .is_some_and(|mods| { - mods.children().any(|m| { - m.kind_id() == Kotlin::ClassModifier - // role-bypass: allow(Modifier) — which class modifier, - // not whether the token is one - && m.first_child(|id| matches!(id.into(), Kotlin::Sealed | Kotlin::Enum)) - .is_some() - }) - }); - !restricted_class && super::npa::kotlin_is_public(ctor) -} - // Kotlin's default visibility is `public` (unlike Java, which is // package-private-by-default), so the "no modifier → public" branch is the // common case. @@ -59,25 +37,6 @@ impl Npm for KotlinCode { // not counted here. `data class` synthesizes // `copy` / `equals` / `hashCode` / `toString` at compile time; // those are not user code and are also not counted. - // The primary constructor is a child of the declaration, not of - // the body (#1828): counted here, where the walk is still on the - // class space — its own function space opens one node later. - // The grammar hangs it off `class_declaration` only - // (`object_declaration` has none), and also accepts one under - // the `interface` keyword — `interface I(x: Int)` — which Kotlin - // rejects, so that shape is billed to the class bucket as any - // other and not told apart (grammar-dispatch §6: invalid input, - // no test). - // role-bypass: allow(Container) — which declaration holds the - // constructor, not whether it opens a space - if node.kind_id() == ClassDeclaration - && let Some(ctor) = node.first_child(|id| id == PrimaryConstructor) - { - stats.class_nm += 1; - if kotlin_primary_constructor_is_public(node, &ctor) { - stats.class_npm += 1; - } - } if !matches!(node.kind_id().into(), ClassBody) { return; } diff --git a/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_generic_brackets_not_conditions.snap b/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_generic_brackets_not_conditions.snap index 7499818b5..6051f347e 100644 --- a/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_generic_brackets_not_conditions.snap +++ b/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_generic_brackets_not_conditions.snap @@ -8,8 +8,8 @@ expression: metric.abc "conditions": 0, "magnitude": 1.4142135623730951, "value": 0.0, - "assignments_average": 0.25, - "branches_average": 0.25, + "assignments_average": 0.3333333333333333, + "branches_average": 0.3333333333333333, "conditions_average": 0.0, "assignments_min": 0, "assignments_max": 1, diff --git a/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_object_construction_branch.snap b/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_object_construction_branch.snap index 7499818b5..6051f347e 100644 --- a/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_object_construction_branch.snap +++ b/src/metrics/snapshots/big_code_analysis__metrics__abc__tests__kotlin_object_construction_branch.snap @@ -8,8 +8,8 @@ expression: metric.abc "conditions": 0, "magnitude": 1.4142135623730951, "value": 0.0, - "assignments_average": 0.25, - "branches_average": 0.25, + "assignments_average": 0.3333333333333333, + "branches_average": 0.3333333333333333, "conditions_average": 0.0, "assignments_min": 0, "assignments_max": 1, diff --git a/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_data_class_methods.snap b/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_data_class_methods.snap index bd862aa7b..18abc2dbe 100644 --- a/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_data_class_methods.snap +++ b/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_data_class_methods.snap @@ -3,13 +3,13 @@ source: src/metrics/npm.rs expression: metric.npm --- { - "class_npm_sum": 2, + "class_npm_sum": 1, "interface_npm_sum": 0, - "class_methods": 3, + "class_methods": 2, "interface_methods": 0, - "class_coa": 0.6666666666666666, + "class_coa": 0.5, "interface_coa": 0.0, - "total": 2, - "total_methods": 3, - "coa": 0.6666666666666666 + "total": 1, + "total_methods": 2, + "coa": 0.5 } diff --git a/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_init_block_not_a_method.snap b/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_init_block_not_a_method.snap index 0db3ecd0e..7e178562b 100644 --- a/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_init_block_not_a_method.snap +++ b/src/metrics/snapshots/big_code_analysis__metrics__npm__tests__kotlin_init_block_not_a_method.snap @@ -3,13 +3,13 @@ source: src/metrics/npm.rs expression: metric.npm --- { - "class_npm_sum": 2, + "class_npm_sum": 1, "interface_npm_sum": 0, - "class_methods": 2, + "class_methods": 1, "interface_methods": 0, "class_coa": 1.0, "interface_coa": 0.0, - "total": 2, - "total_methods": 2, + "total": 1, + "total_methods": 1, "coa": 1.0 } diff --git a/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_data_class.snap b/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_data_class.snap index 9c8b477b8..568878a3e 100644 --- a/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_data_class.snap +++ b/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_data_class.snap @@ -3,7 +3,7 @@ source: src/metrics/wmc.rs expression: metric.wmc --- { - "class_wmc_sum": 2, + "class_wmc_sum": 1, "interface_wmc_sum": 0, - "total": 2 + "total": 1 } diff --git a/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_generic_class.snap b/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_generic_class.snap index 14a283ad5..9c8b477b8 100644 --- a/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_generic_class.snap +++ b/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_generic_class.snap @@ -3,7 +3,7 @@ source: src/metrics/wmc.rs expression: metric.wmc --- { - "class_wmc_sum": 3, + "class_wmc_sum": 2, "interface_wmc_sum": 0, - "total": 3 + "total": 2 } diff --git a/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_init_block.snap b/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_init_block.snap index 14a283ad5..9c8b477b8 100644 --- a/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_init_block.snap +++ b/src/metrics/snapshots/big_code_analysis__metrics__wmc__tests__kotlin_init_block.snap @@ -3,7 +3,7 @@ source: src/metrics/wmc.rs expression: metric.wmc --- { - "class_wmc_sum": 3, + "class_wmc_sum": 2, "interface_wmc_sum": 0, - "total": 3 + "total": 2 } diff --git a/src/metrics/wmc.rs b/src/metrics/wmc.rs index eb7059f1a..d49b18b40 100644 --- a/src/metrics/wmc.rs +++ b/src/metrics/wmc.rs @@ -230,8 +230,7 @@ impl Wmc for CsharpCode { // Kotlin's `class_declaration` becomes either `Class` or `Interface` via // `Getter::get_space_kind` (the keyword child disambiguates). `object` // singletons map to `Class`. Function spaces (top-level `fun`, member -// `fun`, primary and secondary constructors, lambdas, anonymous -// functions) contribute +// `fun`, secondary constructors, lambdas, anonymous functions) contribute // their cyclomatic to the enclosing class / interface. `companion_object` // IS a `func_space` and opens its own `Class` scope (#431): `Checker:: // is_func_space` matches `Kotlin::CompanionObject` and `Getter:: @@ -2220,15 +2219,14 @@ mod tests { fn kotlin_data_class() { // `data class` synthesizes copy/equals/hashCode/toString at // compile time, but only user-written methods are counted — - // compiler-generated members are not user code. The primary - // constructor is written, and opens a function space (#1828). + // compiler-generated members are not user code. check_metrics::( - "data class Point(val x: Int, val y: Int) { // +1 (#1828) + "data class Point(val x: Int, val y: Int) { fun manhattan(): Int = kotlin.math.abs(x) + kotlin.math.abs(y) // +1 }", "foo.kt", |metric| { - assert_eq!(metric.wmc.class_wmc_sum(), 2); + assert_eq!(metric.wmc.class_wmc_sum(), 1); assert_eq!(metric.wmc.interface_wmc_sum(), 0); insta::assert_json_snapshot!(metric.wmc); }, @@ -2641,7 +2639,7 @@ mod tests { // which is why this moves even though the block is deliberately // *not* in `is_func` (it is not a callable anyone names). check_metrics::( - "class C(val n: Int) { // +1 since #1828 + "class C(val n: Int) { init { // +1 since #1184 require(n >= 0) { \"n must be non-negative\" } } @@ -2649,7 +2647,7 @@ mod tests { }", "foo.kt", |metric| { - assert_eq!(metric.wmc.class_wmc_sum(), 3); + assert_eq!(metric.wmc.class_wmc_sum(), 2); assert_eq!(metric.wmc.interface_wmc_sum(), 0); insta::assert_json_snapshot!(metric.wmc); }, @@ -2698,15 +2696,15 @@ mod tests { #[cfg(feature = "kotlin")] #[test] fn kotlin_generic_class() { - // Generic class with two methods and a primary constructor. + // Generic class with two methods. check_metrics::( - "class Box(val value: T) { // +1 (#1828) + "class Box(val value: T) { fun get(): T = value // +1 fun mapTo(f: (T) -> T): T = f(value) // +1 }", "foo.kt", |metric| { - assert_eq!(metric.wmc.class_wmc_sum(), 3); + assert_eq!(metric.wmc.class_wmc_sum(), 2); assert_eq!(metric.wmc.interface_wmc_sum(), 0); insta::assert_json_snapshot!(metric.wmc); }, diff --git a/src/observation_tests.rs b/src/observation_tests.rs index 6c771a8c4..187121be9 100644 --- a/src/observation_tests.rs +++ b/src/observation_tests.rs @@ -341,7 +341,7 @@ fn the_exclude_tests_prune_asks_once_per_attributed_item() { // seed, `python` for the instance-attribute scan, `rust` for the // suppression walk. Dropping `c` here would leave `CParser::new` // reaching `Tree::new`'s disabled-language `expect` under -// `--features python,rust` (`.claude/rules/testing.md`). +// `--features python,rust` (`docs/development/testing.md`). #[cfg(all(feature = "c", feature = "python", feature = "rust"))] #[test] fn the_metric_and_suppression_walks_scan_a_tree_on_one_cursor() { diff --git a/src/output/csv.rs b/src/output/csv.rs index 3272f866d..1322daaa2 100644 --- a/src/output/csv.rs +++ b/src/output/csv.rs @@ -663,7 +663,7 @@ d""# /// `#[cfg]` sits on the callers' `fn`, not around a test body: an /// empty `#[test]` body is a *passing* test, so the inner-block form /// reports green on Windows having asserted nothing - /// (`.claude/rules/testing.md`). + /// (`docs/development/testing.md`). #[cfg(unix)] fn non_utf8_path() -> std::path::PathBuf { use std::ffi::OsStr; diff --git a/src/spaces_tests.rs b/src/spaces_tests.rs index 27d5de7be..73c9b6a3e 100644 --- a/src/spaces_tests.rs +++ b/src/spaces_tests.rs @@ -2649,7 +2649,7 @@ int helper(int y) { /// /// These inputs are unreachable through `check_metrics` and the /// integration harnesses, both of which append a trailing newline (see -/// `.claude/rules/testing.md`), so they go through `space_verbatim`. +/// `docs/development/testing.md`), so they go through `space_verbatim`. #[cfg(all(test, feature = "rust"))] mod childless_root_span { use crate::test_support::space_verbatim; @@ -3177,7 +3177,7 @@ fn walk_frees_every_cognitive_nesting_slot() { // The sweep below covers every `LANG` variant, so its row set is every // language feature there is and its non-vacuity guard is only reachable // in a build that compiled none of them. Gated so that build drops the -// test rather than failing it (`.claude/rules/testing.md`, #1286). +// test rather than failing it (`docs/development/testing.md`, #1286). #[cfg(test)] #[cfg(any( feature = "bash", diff --git a/src/suppression.rs b/src/suppression.rs index 8d5d5e413..cda2d35ba 100644 --- a/src/suppression.rs +++ b/src/suppression.rs @@ -1673,7 +1673,7 @@ mod tests { /// A marker carrying a rationale still attaches when the comment is /// the last thing in the file, with no trailing newline. /// - /// Per `.claude/rules/testing.md`, both the `check_metrics` shim and + /// Per `docs/development/testing.md`, both the `check_metrics` shim and /// the integration suites append a newline to every fixture, so "a /// node ending at EOF" is unreachable from them — /// [`crate::test_support::space_verbatim`] analyses the bytes as diff --git a/src/test_support.rs b/src/test_support.rs index 7ed7827e1..70d5c2e5c 100644 --- a/src/test_support.rs +++ b/src/test_support.rs @@ -280,7 +280,7 @@ pub(crate) fn function_space<'a>(func_space: &'a FuncSpace, name: &str) -> &'a F /// #1383, a `goto case`'s `case` token after #1450 — and so has no /// second axis for the metric assertions to rest on. Trimming `> 5` down /// to `5`, or deleting `goto case 2;`, leaves every metric assertion -/// satisfied and the construct gone (`.claude/rules/testing.md`, +/// satisfied and the construct gone (`docs/development/testing.md`, /// "Perturb the fixture as well as the production line"). Editing a /// spelling out of the source now fails here by name instead of silently /// turning the method into a copy of its control. diff --git a/src/vcs/cache_tests.rs b/src/vcs/cache_tests.rs index c32e5c536..624a8d6f6 100644 --- a/src/vcs/cache_tests.rs +++ b/src/vcs/cache_tests.rs @@ -4,7 +4,7 @@ use std::path::PathBuf; /// Stand-in digests, deliberately neither `0` nor equal to each other, so /// an assertion here cannot pass because two default values coincide -/// (`.claude/rules/testing.md`). No real digest is computed in this +/// (`docs/development/testing.md`). No real digest is computed in this /// module — `WalkContext::mailmap_digest`, `diff_config_digest`, /// `diff_attributes_digest` and `shallow_boundary_digest` live in the /// git backend, whose `history_tests` pin that the walk resolves diff --git a/src/vcs/git/history_coverage_tests.rs b/src/vcs/git/history_coverage_tests.rs index 73324e28e..e6a17e847 100644 --- a/src/vcs/git/history_coverage_tests.rs +++ b/src/vcs/git/history_coverage_tests.rs @@ -56,7 +56,7 @@ fn an_unreadable_attributes_file_fails_the_open_as_it_fails_gix() { std::fs::set_permissions(&user_file, std::fs::Permissions::from_mode(0o000)) .expect("chmod user attributes"); // A `return` here would be a passing test with no assertion run - // (`.claude/rules/testing.md`, "an empty test is a passing test"), so + // (`docs/development/testing.md`, "an empty test is a passing test"), so // a privileged runner fails loudly instead of reading as covered. assert!( std::fs::read(&user_file).is_err(), diff --git a/tests/README.md b/tests/README.md index cd8e5346d..89a122145 100644 --- a/tests/README.md +++ b/tests/README.md @@ -247,7 +247,7 @@ mode to watch for: it reads as zero, so a comparison like `tokens_sum() > halstead_total` keeps passing while testing nothing. Every `insta::assert_json_snapshot!` call must be **anchored**; see -`AGENTS.md` "Validation gates". Either inline the expected block, +`CONTRIBUTING.md` "Snapshot anchors". Either inline the expected block, add a positive `assert_eq!` on an integer accessor immediately above, or include a `// expected: …` derivation comment. `make pre-commit` runs `./utils/check-snapshot-anchors.py` against diff --git a/tests/api/ast_seam_test.rs b/tests/api/ast_seam_test.rs index 3cd68aa7e..527b4f969 100644 --- a/tests/api/ast_seam_test.rs +++ b/tests/api/ast_seam_test.rs @@ -760,7 +760,7 @@ fn preprocess_harvest_feeds_the_macro_masking_pass() { /// The quoted word sits **inside** the body deliberately. With it /// outside, deleting the whole `proc` line left the expected list /// unchanged and the fixture could lose its entire subject with no test -/// failing (`.claude/rules/testing.md`, "Perturb the fixture as well as +/// failing (`docs/development/testing.md`, "Perturb the fixture as well as /// the production line"). Inside, the `proc` is load-bearing for the /// expected sequence. #[cfg(feature = "tcl")] @@ -805,7 +805,7 @@ fn strings_found(lang: LANG, code: &str) -> Vec { /// on the exact reported list rather than on the body's absence: an /// absence assertion also passes when the whole filter stops matching, /// which is the over-correction this rule invites -/// (`.claude/rules/testing.md`). +/// (`docs/development/testing.md`). #[cfg(any(feature = "tcl", feature = "irules"))] #[test] fn find_string_reports_tcl_family_literals_and_not_script_bodies() { diff --git a/tests/api/main.rs b/tests/api/main.rs index d9e060eb4..9fe42832e 100644 --- a/tests/api/main.rs +++ b/tests/api/main.rs @@ -20,7 +20,7 @@ // the one a contributor runs still police every unused import. Dead // *items* are not relaxed: unlike the two library roots this test crate // carries no `allow(dead_code)`, so every helper, `const`, macro and -// test here still needs its own gate. See `.claude/rules/testing.md`, +// test here still needs its own gate. See `docs/development/testing.md`, // "Why the import lint is off on a partial build". #![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] mod ast_seam_test; diff --git a/tests/corpus/main.rs b/tests/corpus/main.rs index fa6bcdc71..ad1b74e47 100644 --- a/tests/corpus/main.rs +++ b/tests/corpus/main.rs @@ -13,7 +13,7 @@ // the one a contributor runs still police every unused import. Dead // *items* are not relaxed: unlike the two library roots this test crate // carries no `allow(dead_code)`, so every helper, `const`, macro and -// test here still needs its own gate. See `.claude/rules/testing.md`, +// test here still needs its own gate. See `docs/development/testing.md`, // "Why the import lint is off on a partial build". #![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] #[path = "../common/mod.rs"] diff --git a/tests/grammars/alterator_string_flattening.rs b/tests/grammars/alterator_string_flattening.rs index dfa3b7056..60e4eae5f 100644 --- a/tests/grammars/alterator_string_flattening.rs +++ b/tests/grammars/alterator_string_flattening.rs @@ -81,7 +81,7 @@ fn assert_flattened(lang: LANG, code: &str, file_name: &str, literal: &str) { /// one of them. A row whose grammar is absent must be *absent* too, not /// merely failing: without the gate every row panicked in `dump_root` /// under any feature set short of the full eight, which reads as a -/// defect in whatever was being changed (`.claude/rules/testing.md`, +/// defect in whatever was being changed (`docs/development/testing.md`, /// "Gate a feature-gated fixture table on the union of its rows"). macro_rules! flatten_cases { ($($name:ident: $feat:literal, $lang:expr, $code:expr, $file:expr, $lit:expr;)*) => { diff --git a/tests/grammars/main.rs b/tests/grammars/main.rs index c86c0afe6..75c022da5 100644 --- a/tests/grammars/main.rs +++ b/tests/grammars/main.rs @@ -10,7 +10,7 @@ // the one a contributor runs still police every unused import. Dead // *items* are not relaxed: unlike the two library roots this test crate // carries no `allow(dead_code)`, so every helper, `const`, macro and -// test here still needs its own gate. See `.claude/rules/testing.md`, +// test here still needs its own gate. See `docs/development/testing.md`, // "Why the import lint is off on a partial build". #![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] mod alterator_string_flattening; diff --git a/tests/output_formats/main.rs b/tests/output_formats/main.rs index 6fbb06383..90f7843c0 100644 --- a/tests/output_formats/main.rs +++ b/tests/output_formats/main.rs @@ -18,7 +18,7 @@ // the one a contributor runs still police every unused import. Dead // *items* are not relaxed: unlike the two library roots this test crate // carries no `allow(dead_code)`, so every helper, `const`, macro and -// test here still needs its own gate. See `.claude/rules/testing.md`, +// test here still needs its own gate. See `docs/development/testing.md`, // "Why the import lint is off on a partial build". #![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] #[path = "../common/mod.rs"] diff --git a/tests/parity/main.rs b/tests/parity/main.rs index b36d9076e..d783459ae 100644 --- a/tests/parity/main.rs +++ b/tests/parity/main.rs @@ -10,7 +10,7 @@ // the one a contributor runs still police every unused import. Dead // *items* are not relaxed: unlike the two library roots this test crate // carries no `allow(dead_code)`, so every helper, `const`, macro and -// test here still needs its own gate. See `.claude/rules/testing.md`, +// test here still needs its own gate. See `docs/development/testing.md`, // "Why the import lint is off on a partial build". #![cfg_attr(not(feature = "all-languages"), allow(unused_imports))] @@ -23,7 +23,7 @@ mod support; // Gated on the union of the languages whose fixture rows are `Some`, so // a build enabling only languages with no non-comparison bracket // construct drops the module rather than failing its non-vacuity guard -// (`.claude/rules/testing.md`). TSX rides `feature = "typescript"`. +// (`docs/development/testing.md`). TSX rides `feature = "typescript"`. #[cfg(any( feature = "csharp", feature = "javascript", @@ -76,7 +76,7 @@ mod nargs_cross_language_parity; // configuration — would fail their guards rather than skipping them. // Gated as a group so that build drops them together, which is also // required: the others read `fixture` out of the middle one -// (`.claude/rules/testing.md`, #1286). +// (`docs/development/testing.md`, #1286). #[cfg(any( feature = "bash", feature = "c", @@ -158,7 +158,7 @@ mod space_span_containment; // Gated on the union of the languages whose fixture rows are `Some`, so // a build enabling only self-reference-free languages drops the module -// rather than failing its non-vacuity guard (`.claude/rules/testing.md`). +// rather than failing its non-vacuity guard (`docs/development/testing.md`). #[cfg(any( feature = "cpp", feature = "csharp", diff --git a/tests/parity/ops_metrics_space_parity.rs b/tests/parity/ops_metrics_space_parity.rs index 49cdc53a0..34fe5cb29 100644 --- a/tests/parity/ops_metrics_space_parity.rs +++ b/tests/parity/ops_metrics_space_parity.rs @@ -111,7 +111,7 @@ pub(super) fn fixture(lang: LANG) -> (&'static str, &'static str) { "m", ), // An expression-bodied property alongside an ordinary method: - // per `.claude/rules/grammar-dispatch.md` §6, `is_func`, + // per `docs/development/grammar_dispatch.md` §6, `is_func`, // `is_func_space`, and `get_space_kind` must stay gated by the // same child-presence predicate for these, and a mismatch shows // up here as an ops/metrics divergence. diff --git a/tests/parity/space_span_containment.rs b/tests/parity/space_span_containment.rs index 12f9e3683..c9d762f34 100644 --- a/tests/parity/space_span_containment.rs +++ b/tests/parity/space_span_containment.rs @@ -304,7 +304,7 @@ fn degenerate_sources_still_span_their_lines_in_every_language() { /// /// These reach `analyze(Source::new(..))` directly, so the source is /// analysed byte-for-byte. Do not route them through a helper that -/// regularises the trailing newline (`.claude/rules/testing.md`): the +/// regularises the trailing newline (`docs/development/testing.md`): the /// third fixture *is* the missing-newline case, and appending one turns /// it into the first. #[test] diff --git a/tests/repositories/big-code-analysis-output b/tests/repositories/big-code-analysis-output index 5fbe03bf0..d411e6051 160000 --- a/tests/repositories/big-code-analysis-output +++ b/tests/repositories/big-code-analysis-output @@ -1 +1 @@ -Subproject commit 5fbe03bf005b9b03a1928273faa477a9c1be5ed7 +Subproject commit d411e605123cd81b7881d819f03b541799dccebe diff --git a/utils/bca-claude-hook-test.mjs b/utils/bca-claude-hook-test.mjs index 604913e42..653cd78a4 100644 --- a/utils/bca-claude-hook-test.mjs +++ b/utils/bca-claude-hook-test.mjs @@ -169,7 +169,7 @@ function bcaRegistrations(settings) { test("configured exec hook sends escaped advisory JSON for every file-writing tool", async (t) => { const f = await fixture(t) const settings = JSON.parse(await readFile(join(REPO, ".claude/settings.json"), "utf8")) - assert.deepEqual(Object.keys(settings), ["hooks"]) + assert.deepEqual(Object.keys(settings), ["permissions", "hooks"]) const registrations = bcaRegistrations(settings) assert.equal(registrations.length, 1, "exactly one bca registration; a second one checks every edit twice") const [{ group, handler }] = registrations @@ -183,10 +183,12 @@ test("configured exec hook sends escaped advisory JSON for every file-writing to assert.equal(resolve(script), HOOK) // The recipe's settings example is the one adopters copy; it must be the // registration this repository runs, not a paraphrase of it. + // The example carries the hook registration only; the permission rules + // beside it in this repository's settings are repository policy. const [documented, ...more] = fencedBlocks(await readFile(RECIPE, "utf8"), "json") assert.equal(more.length, 0, "one json block in the recipe: the settings example") - assert.deepEqual(JSON.parse(documented), settings) - for (const tool of ["Edit", "Write", "MultiEdit"]) { + assert.deepEqual(JSON.parse(documented), { hooks: settings.hooks }) + for (const tool of ["Edit", "Write"]) { assert.ok(group.matcher.split("|").includes(tool)) const result = f.run(f.input({ tool_name: tool, agent_id: "child-a" }), {}, script) const text = report(result) @@ -559,18 +561,6 @@ test("oversized hook input is rejected without analyzer execution", async (t) => assert.deepEqual(await f.calls(), []) }) -test("compatibility shell wrapper preserves the Node adapter's JSON and zero exit", { skip: spawnSync("bash", ["--version"]).status !== 0 }, async (t) => { - const f = await fixture(t) - const expected = f.run(f.input()) - const result = spawnSync("bash", [join(REPO, ".claude/hooks/bca-check.sh")], { - input: JSON.stringify(f.input()), encoding: "utf8", - env: { ...f.env, BCA: f.stub, NODE_OPTIONS: `--import=${pathToFileURL(f.preload).href}` }, - cwd: f.temp, timeout: 10_000, - }) - assert.equal(report(result), report(expected)) - assert.equal(result.stdout, expected.stdout) -}) - test("a file modified or removed while analyzing never receives stale findings", async (t) => { const f = await fixture(t) for (const data of [{ replace: true }, { sameSize: true }, { remove: true }]) { @@ -662,10 +652,7 @@ test("sibling-package checks keep the session policy and nested gitfiles require // The recipe's "ship this verbatim" block is the standing policy adopters // paste into their rules file; AGENTS.md is this repository's copy of it. -// The V1 example's GUIDANCE literal is the short runtime reminder, which is -// a different, deliberately smaller text (bca-common.mjs bounds it to -// 1,200 characters inside the 4,000-character advisory). -test("AGENTS.md carries the recipe's policy block and the V1 example carries the runtime reminder", async () => { +test("AGENTS.md carries the recipe's policy block verbatim", async () => { const lf = (text) => text.replaceAll("\r\n", "\n") const recipe = await readFile(RECIPE, "utf8") const [policy, ...morePolicy] = fencedBlocks(recipe, "markdown") @@ -676,11 +663,4 @@ test("AGENTS.md carries the recipe's policy block and the V1 example carries the assert.ok(section, "AGENTS.md has the metric-feedback section") assert.equal(section.split(policy).length - 1, 1, "the policy block appears exactly once, verbatim, in that section") assert.equal(agents.split(policy).length - 1, 1, "and nowhere else") - - const [example, ...moreExamples] = fencedBlocks(recipe, "javascript") - assert.equal(moreExamples.length, 0, "one javascript block in the recipe: the V1 example") - const literal = example.match(/const GUIDANCE = `\n([\s\S]*?)\n`\.trim\(\)/)?.[1] - assert.ok(literal, "the V1 example declares GUIDANCE as a trimmed template literal") - const reminder = lf(await readFile(join(REPO, ".claude/hooks/bca-guidance.txt"), "utf8")).trim() - assert.equal(literal, reminder) }) diff --git a/utils/check-diagnostic-prefix-test.py b/utils/check-diagnostic-prefix-test.py index f9ee8ec2a..3d2451b5a 100644 --- a/utils/check-diagnostic-prefix-test.py +++ b/utils/check-diagnostic-prefix-test.py @@ -17,7 +17,7 @@ The false-clean direction is the one that matters: a gate that reports "OK" over a tree it failed to read is indistinguishable from a tree with nothing to find, which is precisely the outcome the gate exists to -prevent (see `.claude/rules/tool-output.md`). +prevent (see AGENTS.md "Tool output"). Run with: python3 -m unittest -q utils/check-diagnostic-prefix-test.py diff --git a/utils/check-diagnostic-prefix.py b/utils/check-diagnostic-prefix.py index 7e089f860..bc57b8944 100644 --- a/utils/check-diagnostic-prefix.py +++ b/utils/check-diagnostic-prefix.py @@ -53,7 +53,7 @@ ``r``, an unterminated ``r"`` inside a trailing or block comment — was read as one, and every line to the next quote was then skipped (#1219). -See AGENTS.md "Validation gates" for the policy this enforces. +See CONTRIBUTING.md "Local validation gate" for the policy this enforces. """ from __future__ import annotations diff --git a/utils/check-excluded-manifests-test.py b/utils/check-excluded-manifests-test.py index 288490a6d..72fe61683 100644 --- a/utils/check-excluded-manifests-test.py +++ b/utils/check-excluded-manifests-test.py @@ -661,7 +661,7 @@ def test_an_unpinned_grammar_in_an_excluded_crate_is_reported(self) -> None: self.assertIn('should be "=0.23.4"', err) def test_an_unpinned_grammar_in_the_root_manifest_is_reported(self) -> None: - # AGENTS.md claims this gate enforces the root manifest's pins. + # CONTRIBUTING.md claims this gate enforces the root manifest's pins. # Before the root was added to the scan, loosening one there was # invisible. self._repo( diff --git a/utils/check-excluded-manifests.py b/utils/check-excluded-manifests.py index fab454338..1ec0ee9ec 100644 --- a/utils/check-excluded-manifests.py +++ b/utils/check-excluded-manifests.py @@ -52,7 +52,7 @@ a commented-out ``exclude`` entry as a crate, and counted the text ``[workspace]`` inside a multi-line string as a workspace table. -See AGENTS.md "Tree-sitter grammars" for the pinning rule and the +See CONTRIBUTING.md "Adding a new language or bumping a grammar" for the pinning rule and the `#1145` issue for the worktree traversal this guards. """ @@ -126,7 +126,7 @@ # `tree-sitter` dependencies that must NOT carry an `=` pin. # # `tree-sitter-language` is the ecosystem's shared `LanguageFn` trait -# shim, not a grammar, so AGENTS.md's pinning rule does not reach it. +# shim, not a grammar, so the pinning rule in CONTRIBUTING.md does not reach it. # Pinning it breaks resolution in both directions: `tree-sitter-irules # 0.1.1` requires `^0.1.7` and cargo unifies 0.1.x deps, so `=0.1.0` # makes this workspace unresolvable; and these crates are published, so @@ -429,7 +429,7 @@ def _report_unpinned(drifted: list[tuple[str, str, str]]) -> None: ) + "\n\nA caret range lets `cargo update` move a grammar silently and\n" "lets a downstream consumer of the published crate resolve one\n" - "freely (#1151). See AGENTS.md \"Tree-sitter grammars\".", + "freely (#1151). See CONTRIBUTING.md \"Adding a new language or bumping a grammar\".", file=sys.stderr, ) @@ -458,7 +458,7 @@ def main() -> int: # The root manifest is checked alongside the excluded crates: its # `[workspace.dependencies]` block holds ~20 grammar pins, and - # AGENTS.md claims this gate enforces them. + # CONTRIBUTING.md claims this gate enforces them. manifests = [(ROOT_MANIFEST_LABEL, root_text)] + [ ( f"{crate}/Cargo.toml", diff --git a/utils/check-feature-gates.py b/utils/check-feature-gates.py index efa943851..227d75e51 100755 --- a/utils/check-feature-gates.py +++ b/utils/check-feature-gates.py @@ -5,7 +5,7 @@ not merely non-vacuous, under a feature set that enables none of the features its rows name. -``.claude/rules/testing.md`` ("Gate a feature-gated fixture table on the +``docs/development/testing.md`` ("Gate a feature-gated fixture table on the union of its rows") requires two halves on any test whose case list is built from ``#[cfg(feature = …)]`` rows: @@ -718,7 +718,7 @@ def main(argv: list[str] | None = None) -> int: "\nPut `#[cfg(any(feature = \"a\", feature = \"b\", …))]` on the item\n" "itself, naming the union of the features its rows use, so the\n" "subject is *absent* rather than tripping its own non-vacuity\n" - "guard. See `.claude/rules/testing.md`, \"Gate a feature-gated\n" + "guard. See `docs/development/testing.md`, \"Gate a feature-gated\n" "fixture table on the union of its rows\" (#1220, #1472).\n" ) return 1 diff --git a/utils/check-grammar-build-watch.py b/utils/check-grammar-build-watch.py index 003dc30b0..a096d4950 100755 --- a/utils/check-grammar-build-watch.py +++ b/utils/check-grammar-build-watch.py @@ -9,7 +9,7 @@ header-only edit (``parser.h``, ``alloc.h``, ``array.h``) left a stale parser object behind a fresh ``build inputs:`` digest — a binary advertising a tree it did not compile. The block is the one thing in -those files that is *not* generated binding boilerplate: AGENTS.md +those files that is *not* generated binding boilerplate: CONTRIBUTING.md exempts the vendored crates from the workspace lint tables because a regeneration replaces their sources wholesale, and ``recreate-grammars.sh`` / ``generate-grammars/*.sh`` happen to leave ``build.rs`` alone today. @@ -39,7 +39,7 @@ ``--root `` points the gate at another checkout, which is how the self-tests drive it over scratch layouts. -See AGENTS.md "Rust conventions" for the exemption this qualifies. +See CONTRIBUTING.md "Project conventions" for the exemption this qualifies. """ from __future__ import annotations diff --git a/utils/check-grammar-marker-sync.py b/utils/check-grammar-marker-sync.py index f4aee2351..e9844acf8 100755 --- a/utils/check-grammar-marker-sync.py +++ b/utils/check-grammar-marker-sync.py @@ -28,7 +28,7 @@ during a merge conflict), restore it from git history rather than regenerating from --update. -See AGENTS.md "Validation gates" and #400 for context. +See CONTRIBUTING.md "Local validation gate" and #400 for context. """ from __future__ import annotations @@ -624,7 +624,7 @@ def main() -> int: description=( "Block grammar-marker bumps in tree-sitter-{mozjs,mozcpp}/" "Cargo.toml that aren't accompanied by a matching source " - "regen. See AGENTS.md and #400 for context." + "regen. See CONTRIBUTING.md and #400 for context." ), ) parser.add_argument( @@ -709,7 +709,7 @@ def main() -> int: " ./utils/check-grammar-marker-sync.py --update\n" " - The sources were regenerated but the baseline was not\n" " refreshed. Run the --update command above.\n" - "\nSee AGENTS.md and #400 for context.\n" + "\nSee CONTRIBUTING.md and #400 for context.\n" ) return 1 diff --git a/utils/check-manpage-assets.py b/utils/check-manpage-assets.py index 0b0865c32..1c2f3ad17 100755 --- a/utils/check-manpage-assets.py +++ b/utils/check-manpage-assets.py @@ -26,7 +26,7 @@ basename of the asset source path, which is robust against formatting drift and dest-path style differences. -See AGENTS.md "Validation gates" for the policy this enforces. +See CONTRIBUTING.md "Local validation gate" for the policy this enforces. """ from __future__ import annotations diff --git a/utils/check-manpage-drift.py b/utils/check-manpage-drift.py index ddbaf60e1..7eade2ec8 100644 --- a/utils/check-manpage-drift.py +++ b/utils/check-manpage-drift.py @@ -80,7 +80,7 @@ exit status. ``--no-ext-diff`` then keeps the *printed* evidence git's own, so a real failure still shows which lines moved. -See AGENTS.md "Validation gates" for the policy this enforces. +See CONTRIBUTING.md "Local validation gate" for the policy this enforces. """ from __future__ import annotations diff --git a/utils/check-publish-metadata.py b/utils/check-publish-metadata.py index 0c7c57bae..0e9189cae 100644 --- a/utils/check-publish-metadata.py +++ b/utils/check-publish-metadata.py @@ -74,7 +74,7 @@ not emit it, so it is read from the manifest with inheritance resolved by hand. -See `#1224`, ``RELEASING.md``, and AGENTS.md "Validation gates". +See `#1224`, ``RELEASING.md``, and CONTRIBUTING.md "Local validation gate". """ from __future__ import annotations diff --git a/utils/check-role-bypass.py b/utils/check-role-bypass.py index ce28391cb..90dafedec 100755 --- a/utils/check-role-bypass.py +++ b/utils/check-role-bypass.py @@ -123,7 +123,7 @@ HEADER = """\ # Role-bypass baseline: role-claimed kinds still restated as # classification inside the consumer boundary (#1692). -# Maintained by check-role-bypass.py; see AGENTS.md "Validation gates". +# Maintained by check-role-bypass.py; see CONTRIBUTING.md "Local validation gate". # # An entry is one site a migration package will replace with a call to # the row. The gate fails on a site not listed here; `--update` only diff --git a/utils/check-role-census.py b/utils/check-role-census.py index fd2e05b91..2ec02e1c2 100755 --- a/utils/check-role-census.py +++ b/utils/check-role-census.py @@ -52,7 +52,7 @@ HEADER = """\ # Role-census baseline: the (language, role, package) cells still # `pending` in big-code-analysis-ast/src/roles/.rs (#1692). -# Maintained by check-role-census.py; see AGENTS.md "Validation gates". +# Maintained by check-role-census.py; see CONTRIBUTING.md "Local validation gate". # # An entry is one cell a later work package will declare. The gate # fails when a current pending cell is not listed here, so a row cannot diff --git a/utils/check-role-coverage.py b/utils/check-role-coverage.py index aa6fb14c9..d5bbf687c 100755 --- a/utils/check-role-coverage.py +++ b/utils/check-role-coverage.py @@ -112,7 +112,7 @@ def corpus_root(corpus: str, subpath: str | None) -> pathlib.Path: HEADER = """\ # Role-coverage baseline: runtime kinds no role declares (#1692). -# Maintained by check-role-coverage.py; see AGENTS.md "Validation gates". +# Maintained by check-role-coverage.py; see CONTRIBUTING.md "Local validation gate". # # An entry is one (language, kind id) that no row of any role names in # `owns`, `pays` or `wraps` and no row excludes with a reason. Identity diff --git a/utils/check-ruff-lockstep-test.py b/utils/check-ruff-lockstep-test.py index 4212df9b6..60771b16a 100644 --- a/utils/check-ruff-lockstep-test.py +++ b/utils/check-ruff-lockstep-test.py @@ -497,7 +497,7 @@ def test_clean_tree_passes(self) -> None: def test_it_runs_from_an_unrelated_cwd(self) -> None: # `REPO_ROOT` is derived from the script's own location, so the # gate must not depend on being invoked from the repository root - # (AGENTS.md, "Project layout"). + # (every gate under utils/ follows this convention). with tempfile.TemporaryDirectory() as elsewhere: result = subprocess.run( [sys.executable, str(SCRIPT_SRC)], diff --git a/utils/check-ruff-lockstep.py b/utils/check-ruff-lockstep.py index c1652a456..11285201c 100644 --- a/utils/check-ruff-lockstep.py +++ b/utils/check-ruff-lockstep.py @@ -23,7 +23,7 @@ **The ``requirements/dev.txt`` ``ruff==`` pin must equal the locked version.** CI installs its ruff with ``pip install --require-hashes -r requirements/dev.txt`` rather than through uv, so a stale export is a -ruff CI runs that the lockfile never resolved. AGENTS.md requires a +ruff CI runs that the lockfile never resolved. CONTRIBUTING.md requires a ``uv.lock`` change and its regenerated exports to land in the same commit; this is that rule as a check. @@ -47,7 +47,7 @@ default — a version gate that silently passes on malformed input is the bug being fixed, not a lenient version of the fix. -See `#1230` and AGENTS.md "Validation gates". +See `#1230` and CONTRIBUTING.md "Local validation gate". """ from __future__ import annotations diff --git a/utils/check-rumdl-lockstep-test.py b/utils/check-rumdl-lockstep-test.py index 1b6703fb2..7d9115140 100644 --- a/utils/check-rumdl-lockstep-test.py +++ b/utils/check-rumdl-lockstep-test.py @@ -1016,7 +1016,7 @@ def test_clean_tree_passes(self) -> None: def test_it_runs_from_an_unrelated_cwd(self) -> None: # `REPO_ROOT` is derived from the script's own location, so the # gate must not depend on being invoked from the repository root - # (AGENTS.md, "Project layout"). + # (every gate under utils/ follows this convention). with tempfile.TemporaryDirectory() as elsewhere: result = subprocess.run( [sys.executable, str(SCRIPT_SRC)], diff --git a/utils/check-rustfmt-bail.py b/utils/check-rustfmt-bail.py index 2104af03d..91d25b034 100755 --- a/utils/check-rustfmt-bail.py +++ b/utils/check-rustfmt-bail.py @@ -32,9 +32,9 @@ 1. **A comment inside a match pattern** — between the pattern and its ``=>``, or between ``|`` alternatives. This is the one - ``.claude/rules/formatting.md`` is about, and the fix is to hoist the + ``docs/development/formatting.md`` is about, and the fix is to hoist the comment above the arm, outside the pattern. Never delete it: - ``.claude/rules/macro-comments.md`` explains why that per-arm + ``docs/development/formatting.md`` explains why that per-arm rationale is load-bearing where it sits. 2. **A ``macro_rules!`` body rustfmt cannot parse** — a metavariable in a position that is not valid Rust, such as the ``LANG::$camel => …`` @@ -307,8 +307,8 @@ def probe_arms( ``big-code-analysis-ast/src/getter.rs`` or ``src/metrics/cognitive.rs`` standalone errors out with "file not found for module" — an error that reads exactly like a bail if - stderr is discarded, and the reason - ``.claude/rules/formatting.md`` calls those two files unprobeable. + stderr is discarded, which once led a hand-rolled probe to call + those two files unprobeable. On stdin there is nothing to resolve, so they probe like any other. """ lines = source.split("\n") @@ -361,7 +361,7 @@ def discover_targets(root: pathlib.Path) -> list[pathlib.Path]: """Every Rust file in the tree. The sweep is workspace-wide on purpose. The site list in - ``.claude/rules/formatting.md`` was scoped to ``src/metrics/`` for + ``docs/development/formatting.md`` was scoped to ``src/metrics/`` for two revisions, which is exactly why ``big-code-analysis-ast/src/getter/`` — where the bail is close to universal — went unmentioned: a directory nobody swept reads as @@ -438,7 +438,7 @@ def load_baseline(path: pathlib.Path) -> dict[str, int]: BASELINE_HEADER = """\ # Match arms rustfmt declines to format, per file. -# Maintained by check-rustfmt-bail.py; see AGENTS.md "Validation gates". +# Maintained by check-rustfmt-bail.py; see CONTRIBUTING.md "Local validation gate". # Lower-or-equal current counts pass; any increase fails CI. # Regenerate with: ./utils/check-rustfmt-bail.py --update # @@ -449,7 +449,7 @@ def load_baseline(path: pathlib.Path) -> dict[str, int]: # 1. A comment inside a match *pattern* (between the pattern and its # `=>`, or between `|` alternatives). Fix by hoisting the comment # above the arm, outside the pattern — never by deleting it. See -# .claude/rules/formatting.md. +# docs/development/formatting.md. # 2. A `macro_rules!` body rustfmt cannot parse, typically a # metavariable in a non-Rust position such as the pattern # repetition `$ternary $(| $short_circuit)+`. No comment is @@ -537,7 +537,7 @@ def main(argv: list[str] | None = None) -> int: "match pattern (hoist it above the arm) and a macro_rules! body " "rustfmt cannot parse (nothing to fix). This gate cannot tell " "them apart -- run --show and look for the in-pattern comment " - "before editing. See .claude/rules/formatting.md." + "before editing. See docs/development/formatting.md." ), ) parser.add_argument( @@ -636,7 +636,7 @@ def main(argv: list[str] | None = None) -> int: " never delete it;\n" " * neither, inside a `macro_rules!` body -> rustfmt cannot parse\n" " the body and there is nothing to fix.\n" - ".claude/rules/formatting.md has the full rule. If the increase is\n" + "docs/development/formatting.md has the full rule. If the increase is\n" "deliberate and unavoidable, ratchet with:\n" " ./utils/check-rustfmt-bail.py --update\n" ) diff --git a/utils/check-safety-doc-pin.py b/utils/check-safety-doc-pin.py index 92ad67882..3ed63808f 100755 --- a/utils/check-safety-doc-pin.py +++ b/utils/check-safety-doc-pin.py @@ -6,7 +6,7 @@ actually pins in the root ``Cargo.toml``. That module doc is the canonical justification for the workspace's only -sanctioned ``unsafe`` block (AGENTS.md, "Rust conventions"), and part of +sanctioned ``unsafe`` block (CONTRIBUTING.md, "Project conventions"), and part of its argument — that ``Tree``/``Node``/``TreeCursor`` are ``Send + Sync``, that ``Node<'tree>`` is ``(ffi::TSNode, PhantomData<&'tree ()>)``, that ``Tree::edit`` takes ``&mut self`` — is a claim about a *specific* @@ -29,14 +29,14 @@ invisible rather than fixing it. Scope is deliberately one file. Two other places name this pin in -prose — the runtime-exemption rationale in ``AGENTS.md`` and the same +prose — the runtime-exemption rationale in ``CONTRIBUTING.md`` and the same rationale echoed in ``utils/check-excluded-manifests.py`` — but both sit in text that also cites *grammar* pins illustratively (``=0.23.5``, ``=0.26.10``), so a literal-scanning rule there would fail on versions that are supposed to differ. In ``node.rs`` an ``=X.Y.Z`` literal can only mean the tree-sitter pin, which is what makes the rule crisp here. -See AGENTS.md "Validation gates" for the policy this enforces. +See CONTRIBUTING.md "Local validation gate" for the policy this enforces. """ from __future__ import annotations diff --git a/utils/check-snapshot-anchors.py b/utils/check-snapshot-anchors.py index eef1e2132..58a195d8c 100755 --- a/utils/check-snapshot-anchors.py +++ b/utils/check-snapshot-anchors.py @@ -18,7 +18,7 @@ *decreases* are silent (the baseline can be regenerated with ``--update`` after intentional cleanups). -See AGENTS.md "Validation gates" for the policy this enforces. +See CONTRIBUTING.md "Local validation gate" for the policy this enforces. """ from __future__ import annotations @@ -408,7 +408,7 @@ def load_baseline(path: pathlib.Path) -> dict[str, int]: def write_baseline(path: pathlib.Path, counts: dict[str, int]) -> None: body = [ "# Bare insta::assert_json_snapshot! call counts per metric file.", - "# Maintained by check-snapshot-anchors.py; see AGENTS.md.", + "# Maintained by check-snapshot-anchors.py; see CONTRIBUTING.md \"Snapshot anchors\".", "# Lower-or-equal current counts pass; any increase fails CI.", "# Regenerate with: ./utils/check-snapshot-anchors.py --update", "#", @@ -564,7 +564,7 @@ def main() -> int: " - inline expected block: insta::assert_json_snapshot!(metric.X, @r###\"…\"###)\n" " - adjacent assert_eq! on a headline accessor (within 5 non-blank lines)\n" " - // expected: comment (within 5 non-blank lines)\n" - "See AGENTS.md \"Validation gates\". If the increase is intentional\n" + "See CONTRIBUTING.md \"Snapshot anchors\". If the increase is intentional\n" "(e.g. new tests already anchored differently), regenerate the\n" "baseline with: ./utils/check-snapshot-anchors.py --update\n" ) diff --git a/utils/check-test-lang-gates.py b/utils/check-test-lang-gates.py index c1091c7d2..c7c79d9d9 100755 --- a/utils/check-test-lang-gates.py +++ b/utils/check-test-lang-gates.py @@ -1796,7 +1796,7 @@ def reachable(item: Item, generic_too: bool) -> set[str]: # only check that saw it. # # Conditioned on the sweep carrying *both halves* of the - # rule in `.claude/rules/testing.md`: an `is_enabled()` row + # rule in `docs/development/testing.md`: an `is_enabled()` row # filter and a non-vacuity assertion. Together those mean it # *fails* rather than skips when no language is enabled, so # it must be absent then — the #1220 class. A full-enum @@ -2729,7 +2729,7 @@ def main(argv: list[str] | None = None) -> int: "marker: this\ncompares against the merge base, so a marker " "would be stale the moment\nthe branch lands and would sit in " "the tree as a hole nothing detects.\n\n" - "See `.claude/rules/testing.md` (#1478).\n" + "See `docs/development/testing.md` (#1478).\n" ) return 1 print(f"test-lang-gates: OK — no test lost a build since {args.compare}") @@ -2834,7 +2834,7 @@ def main(argv: list[str] | None = None) -> int: "or a path — say so above it:\n\n" " // test-lang-gates: hand-written(cpp) — the corpus walk " "picks the\n // language per file from its extension\n\n" - "See `.claude/rules/testing.md` (#1478).\n" + "See `docs/development/testing.md` (#1478).\n" ) if failures: sys.stderr.write("\n") @@ -2854,7 +2854,7 @@ def main(argv: list[str] | None = None) -> int: "the marker the derivation reports:\n\n" " ./utils/check-test-lang-gates.py --show\n" " ./utils/check-test-lang-gates.py --fix\n\n" - 'See `.claude/rules/testing.md`, "Gate a feature-gated fixture ' + 'See `docs/development/testing.md`, "Gate a feature-gated fixture ' 'table on the\nunion of its rows" (#1472, #1413).\n' ) diff --git a/utils/coverage-diff.py b/utils/coverage-diff.py index 79201fafd..8d790562d 100755 --- a/utils/coverage-diff.py +++ b/utils/coverage-diff.py @@ -8,7 +8,7 @@ `utils/patch-coverage.py` is the quick single-report approximation; this one takes two reports and compares per-file covered counts rather -than percentages (`.claude/rules/testing.md`, "Coverage measures +than percentages (`docs/development/testing.md`, "Coverage measures execution, not discrimination": the denominator moves for reasons unrelated to the change). diff --git a/utils/patch-coverage.py b/utils/patch-coverage.py index 618e1df1e..3b639c4fb 100755 --- a/utils/patch-coverage.py +++ b/utils/patch-coverage.py @@ -20,9 +20,9 @@ Not a gate: it takes its inputs as arguments and is run by hand before quoting a patch-coverage number on a PR (see -`.claude/rules/testing.md`, "Coverage measures execution, not +`docs/development/testing.md`, "Coverage measures execution, not discrimination"). The JSON it reads is a tier-2 artifact under -`.claude/rules/temp-files.md`; this driver is tier 1, which is why it +AGENTS.md "Temporary files"; this driver is irreplaceable, which is why it lives here rather than beside the JSON. """ diff --git a/utils/perturb.py b/utils/perturb.py index 0299e8e61..0ad40e6ac 100755 --- a/utils/perturb.py +++ b/utils/perturb.py @@ -1,5 +1,5 @@ #!/usr/bin/env python3 -"""Perturbation sweep driver (`.claude/rules/testing.md`, "Verify +"""Perturbation sweep driver (`docs/development/testing.md`, "Verify defensive refactor tests by reverting the production code"). Applies one exact substitution to one production file, runs a test @@ -75,7 +75,7 @@ - A `cargo test` argv that can run more than one test target must carry `--no-fail-fast`, or the targets after the first failing one never - run and their guards read as dead (`.claude/rules/testing.md`, "So is + run and their guards read as dead (`docs/development/testing.md`, "So is the invocation"). Anything but exactly one `-p` with exactly one of `--lib`, `--doc`, `--test`, `--bin`, `--example` or `--bench` is refused without it, before anything is read or run; so is a glob diff --git a/utils/worktree-setup-test.py b/utils/worktree-setup-test.py index 1df311b8b..8008c6149 100644 --- a/utils/worktree-setup-test.py +++ b/utils/worktree-setup-test.py @@ -157,7 +157,7 @@ def test_deletion_plus_modification_is_blocked(self) -> None: def test_modification_alone_is_ready(self) -> None: # Accepting a snapshot in the integration-snapshot submodule is - # routine (AGENTS.md); it must not read as damage, or the setup + # routine (CONTRIBUTING.md, "Integration snapshots"); it must not read as damage, or the setup # target would offer to overwrite work in progress. (self.fixture.work / "snapshots" / "s.snap").write_text("locally accepted\n") self.assertIs(self.fixture.classify(), SETUP.State.READY) @@ -181,7 +181,7 @@ class RepairTest(unittest.TestCase): here. A test that assembles its own `git submodule update --force` proves git can repair the tree; it never proves this script asks git to — the production bookkeeping and a test's replica of it are two - different things (`.claude/rules/testing.md`). + different things (`docs/development/testing.md`). """ def setUp(self) -> None: diff --git a/utils/worktree-setup.py b/utils/worktree-setup.py index f45454957..a3e2ee3b3 100755 --- a/utils/worktree-setup.py +++ b/utils/worktree-setup.py @@ -14,7 +14,7 @@ and ``--force`` is destructive: it is ``git checkout --force`` inside the submodule, so it overwrites locally modified tracked files. The integration-snapshot submodule is one contributors legitimately edit -(accepting ``.snap`` files, per AGENTS.md), so the escalation has to be +(accepting ``.snap`` files, per CONTRIBUTING.md), so the escalation has to be conditional on what the submodule actually looks like. That classification is what this script exists for.