Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion .claude/hooks/bca-check.mjs
Original file line number Diff line number Diff line change
Expand Up @@ -39,8 +39,9 @@ export async function checkHook(input, signal) {
const { named, cwd } = context
health.root = context.root
health.cwd = cwd
const bca = await analyzer(context.root)
const { path: bca, reason } = await analyzer(context.root, { signal })
health.analyzer = bca
health.analyzerReason = reason
if (signal?.aborted) {
health.outcome = "cancelled"
return
Expand Down
114 changes: 106 additions & 8 deletions .claude/hooks/bca-common.mjs
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
import { execFile, spawn } from "node:child_process"
import { constants } from "node:fs"
import { access, open, realpath, stat } from "node:fs/promises"
import { dirname, isAbsolute, relative, resolve, sep } from "node:path"
import { delimiter, dirname, isAbsolute, join, relative, resolve, sep } from "node:path"
import { fileURLToPath } from "node:url"

const TIMEOUT = 3_000
const DISCOVERY_BUDGET = 4_000
const MAX_REPORT = 4_000
const BUILD_INPUTS = "build inputs: "
const DIGEST_SCRIPT = fileURLToPath(new URL("../../utils/self_scan_digest.py", import.meta.url))
const FALLBACK = "Review findings relevant to your change; do not move complexity just to lower a score.\n" +
"These are current file findings, not proof of an edit-caused regression. Keep the task-boundary gate."

Expand Down Expand Up @@ -70,16 +74,110 @@ export function inside(root, file) {
return path !== ".." && !path.startsWith(`..${sep}`) && !isAbsolute(path)
}

export async function analyzer(root) {
if (process.env.BCA) return process.env.BCA
const local = resolve(root, "target/release", process.platform === "win32" ? "bca.exe" : "bca")
async function executableFile(path) {
try {
await access(local, constants.X_OK)
if ((await stat(local)).isFile()) return local
await access(path, constants.X_OK)
const info = await stat(path)
return info.isFile() ? { path, mtimeMs: info.mtimeMs, identity: await realpath(path) } : undefined
} catch {
// This checkout has no executable release build; use the installed analyzer.
return undefined
}
}

async function localBuilds(root) {
const name = process.platform === "win32" ? "bca.exe" : "bca"
const builds = await Promise.all(["debug", "release"].map((profile) => executableFile(resolve(root, "target", profile, name))))
return builds.filter(Boolean)
}

// The executable a bare `name` would spawn with `cwd` as the working
// directory: PATH entries are resolved against `cwd` — a relative entry,
// or an empty one, which `spawn` reads as the child's cwd — so the file
// probed here is the file the check later runs.
async function installed(name, cwd) {
const extensions = process.platform === "win32" ? (process.env.PATHEXT ?? ".EXE;.CMD;.BAT;.COM").split(";") : [""]
for (const directory of (process.env.PATH ?? "").split(delimiter)) {
for (const extension of extensions) {
const found = await executableFile(resolve(cwd, directory, name + extension))
if (found) return found
}
}
return undefined
}

async function probe(file, args, cwd, signal) {
const result = await run(file, args, cwd, signal)
if (!result.failed && result.code === 0) return { stdout: result.stdout }
const detail = result.stderr.split(/\r?\n/).map((line) => line.trim()).find(Boolean)?.slice(0, 200)
const status = Number.isInteger(result.code) ? `exited ${result.code}` : result.code ?? "signal"
return { failure: detail ? `${file} ${status}: ${detail}` : `${file} ${status}` }
}

// Every failure of the digest step is a discovery failure, never a thrown
// error, so a check can lose at most the match step — never itself.
async function treeDigest(script, root, signal) {
let present
try { present = (await stat(script)).isFile() } catch (error) { return { failure: `digest script ${error.code ?? "unreadable"}` } }
if (!present) return { failure: "no digest script" }
const { stdout, failure } = await probe("python3", ["-B", script, root], root, signal)
.catch((error) => ({ failure: `python3 ${error.code ?? error.message}` }))
if (failure) return { failure }
const digest = stdout.split(/\r?\n/).map((line) => line.trim()).find((line) => /^[0-9a-f]{64}$/.test(line))
return digest ? { digest } : { failure: "python3 printed no digest" }
}

function reportedInputs(stdout) {
return stdout.split(/\r?\n/).find((line) => line.startsWith(BUILD_INPUTS))?.slice(BUILD_INPUTS.length).trim()
}

// Order: `$BCA` unprobed; else the first of `target/debug/bca`, `target/release/bca`
// and PATH `bca` whose `--version` reports a `build inputs:` digest equal to the
// one `utils/self_scan_digest.py` computes over `root` — the same test
// `utils/self-scan-bca.py` applies, so the hook agrees with `make self-scan`
// (#1776); else the newest local build by mtime; else PATH `bca`.
// Probing executes each candidate, which is the trust level the old order already
// granted `target/release/bca` by running it unconditionally. The script is
// resolved relative to this module, never to `root`: `checkContext` can hand over
// a nested checkout, and that checkout must not supply the Python the parent's
// hook runs. `BCA_DIGEST_SCRIPT` is the tests' seam for that path, like
// `BCA_SELF_SCAN_WORKSPACE` in self-scan-bca.py. PATH `bca` is probed and
// returned as the resolved file, so the binary that answered `--version` is
// the one the check runs and the one the health line names. Discovery shares
// one budget so the check itself keeps room: the digest plus three probes at
// TIMEOUT each could otherwise spend more. The `checkout()` git call before
// this is not under the budget; its 3 s TIMEOUT plus this 4 s plus the
// check's 3 s is 10 s, which is why `.claude/settings.json` registers 15.
export async function analyzer(root, options = {}) {
if (process.env.BCA) return { path: process.env.BCA, reason: "BCA environment variable" }
const budget = new AbortController()
const expire = () => budget.abort()
const timer = setTimeout(expire, DISCOVERY_BUDGET)
options.signal?.addEventListener("abort", expire, { once: true })
if (options.signal?.aborted) expire()
try {
const builds = await localBuilds(root)
const script = process.env.BCA_DIGEST_SCRIPT || DIGEST_SCRIPT
let { digest, failure } = await treeDigest(script, root, budget.signal)
if (digest) {
const candidates = builds.map((build) => build.path)
const onPath = await installed("bca", root)
if (onPath && !builds.some((build) => build.identity === onPath.identity)) candidates.push(onPath.path)
for (const candidate of candidates) {
if (budget.signal.aborted) break
const { stdout } = await probe(candidate, ["--version"], root, budget.signal)
if (stdout !== undefined && reportedInputs(stdout) === digest) {
return { path: candidate, reason: "build inputs match this tree" }
}
}
failure = budget.signal.aborted ? "discovery budget exhausted" : "no candidate reports this tree's build inputs"
}
const [newest] = builds.sort((a, b) => b.mtimeMs - a.mtimeMs)
if (newest) return { path: newest.path, reason: `newest local build (${failure})` }
return { path: "bca", reason: `PATH bca (no local build; ${failure})` }
} finally {
clearTimeout(timer)
options.signal?.removeEventListener("abort", expire)
}
return "bca"
}

export async function checkout(directory) {
Expand Down
2 changes: 1 addition & 1 deletion .claude/settings.json
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@
"type": "command",
"command": "node",
"args": ["${CLAUDE_PROJECT_DIR}/.claude/hooks/bca-check.mjs"],
"timeout": 10
"timeout": 15
}
]
}
Expand Down
10 changes: 10 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -904,6 +904,16 @@ jobs:
run: python3 utils/check-safety-doc-pin.py
- name: check-safety-doc-pin self-tests (explicit)
run: python3 -m unittest -q utils/check-safety-doc-pin-test.py
# Each vendored grammar build.rs carries a hand-maintained block
# that rerun-if-changed-watches src/tree_sitter/ (#1773); a
# regeneration does not restore it, and losing it leaves a stale
# parser object behind a fresh build-inputs digest. Its self-tests
# run as their own step for the usual reason: a source-scanning
# gate that stops matching reports a clean tree (#1778).
- name: check-grammar-build-watch (explicit)
run: python3 -B utils/check-grammar-build-watch.py
- name: check-grammar-build-watch self-tests (explicit)
run: python3 -B -m unittest -q utils/check-grammar-build-watch-test.py
# Defensive twin for the grammar-marker-sync gate (#400): bumping
# the notification-only marker in tree-sitter-{mozjs,mozcpp}/
# Cargo.toml without re-running the matching generate-*.sh
Expand Down
14 changes: 11 additions & 3 deletions .opencode/plugins/bca-check.js
Original file line number Diff line number Diff line change
Expand Up @@ -137,6 +137,13 @@ export default {
const root = await checkout(directory)
audit.root = root

// Per event, not per plugin load: a rebuild between events must be seen.
const analyzers = new Map()
const resolveAnalyzer = (checkoutRoot) => {
let resolved = analyzers.get(checkoutRoot)
if (!resolved) analyzers.set(checkoutRoot, resolved = analyzer(checkoutRoot, { signal: lifetime.signal }))
return resolved
}
const pending = []
const selected = [...paths].slice(0, MAX_FILES)
const omitted = paths.size - selected.length
Expand All @@ -156,14 +163,15 @@ export default {
}
const context = await checkContext(directory, root, lexical, file)
const { named, cwd } = context
const bca = await analyzer(context.root)
const { path: bca, reason } = await resolveAnalyzer(context.root)
audit.analyzer = bca
audit.analyzerReason = reason
audit.cwd = cwd
const binaryKey = JSON.stringify([context.root, bca])
const binaryKey = JSON.stringify([context.root, bca, reason])
if (!binaries.has(binaryKey)) {
if (binaries.size >= 256) binaries.clear()
binaries.add(binaryKey)
console.info(`[bca-check] analyzer=${bca} cwd=${cwd}`)
console.info(`[bca-check] analyzer=${bca} cwd=${cwd} reason=${reason}`)
}
const state = fileState(file, lexical, version)
if (!held.has(state)) state.users++
Expand Down
24 changes: 24 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -587,6 +587,30 @@ repos:
entry: python3 -m unittest -q utils/check-safety-doc-pin-test.py
pass_filenames: false

# The five vendored grammar build scripts carry a hand-maintained
# block that rerun-if-changed-watches src/tree_sitter/ (#1773).
# A regeneration does not restore it, and losing it leaves a
# stale parser object behind a fresh build-inputs digest. Fires
# on the root manifest too, since that is where the crate list
# comes from, and on any crate whose name contains `tree-sitter`,
# which is the gate's own discovery rule (#1778).
- id: check-grammar-build-watch
name: check-grammar-build-watch
language: system
files: '^(Cargo\.toml|[^/]*tree-sitter[^/]*/bindings/rust/build\.rs|utils/check-grammar-build-watch\.py)$'
entry: python3 -B utils/check-grammar-build-watch.py
pass_filenames: false

# Self-tests for the grammar-build-watch gate, for the same reason
# as the pairs above: a source-scanning gate that stops matching
# reports a clean tree.
- id: check-grammar-build-watch-test
name: check-grammar-build-watch-test
language: system
files: '^utils/check-grammar-build-watch(-test)?\.py$'
entry: python3 -B -m unittest -q utils/check-grammar-build-watch-test.py
pass_filenames: false

# The `enums/` crate is workspace-excluded, so the workspace
# clippy/test hooks above never touch it. Add a dedicated check
# so warnings here cannot drift (see #164).
Expand Down
29 changes: 23 additions & 6 deletions AGENTS.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@ and `cargo run -p big-code-analysis-web --`.
`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`,
Expand Down Expand Up @@ -304,10 +305,14 @@ and `cargo run -p big-code-analysis-web --`.
`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 (generated binding boilerplate that a
regeneration replaces wholesale). `utils/check-excluded-manifests.py`
gates this — without it a crate gated at `-D warnings` is measured
against the compiler defaults and still reads as fully linted (#1228).
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.

Expand Down Expand Up @@ -354,7 +359,12 @@ the safety-doc pin gate
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 bca self-scan threshold gate at both
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
Expand Down Expand Up @@ -932,7 +942,14 @@ Three things to know before quoting a number at anyone:
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 at
the task boundary (`make self-scan`, `make pre-commit`). A violation (cognitive, cyclomatic, ABC, …) means
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).
A violation (cognitive, cyclomatic, ABC, …) means
*this function is hard for a human to follow* — the number is a proxy
for that, not the goal. Make the code genuinely simpler, not the number
smaller.
Expand Down
42 changes: 41 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,26 @@ for historical reference.

### Added

- **`bca --version` reads the Mach-O and PE build ids** (#1777). `build
id:` was `unavailable` off Linux because only the ELF reader existed;
two bounded readers now sit beside it — the 16-byte `LC_UUID` of a
thin 64-bit Mach-O, and the `CodeView` `RSDS` GUID plus age of a PE32
or PE32+ image, fetched with a second bounded read since the debug
directory routinely sits past the 64 KiB head. Each is checked
arithmetic, `get`-bounded reads and fail-closed `None`, with synthetic
fixtures for every malformed shape; a universal (FAT) Mach-O and a PE
without a `CodeView` entry read `unavailable`. The ELF reader now also
refuses an `e_phentsize` below 56, which let one `PT_NOTE` be walked
`phnum` times.
- **`make check-grammar-build-watch`** (`utils/check-grammar-build-watch.py`,
#1778): fails when the `bindings/rust/build.rs` of any
`[workspace].exclude` entry naming `tree-sitter` no longer carries,
token for token, the hand-maintained `src/tree_sitter/` header watch
#1773 added, or is missing outright — the block no regeneration
restores, and whose loss leaves a stale parser object behind a fresh
`build inputs:` digest. Wired into `make lint`, `make pre-commit`,
`make ci`, the pre-commit hooks and CI, with its own self-test.

- **`bca --version` records build provenance** (#1773). `-V` is the
unchanged one-line `bca <version>`; `--version` follows it with
`build inputs:` (a SHA-256 content digest of every source compiled
Expand All @@ -36,7 +56,12 @@ for historical reference.
on a bare commit would cost the rebuild #1773 removes),
`built:` (RFC 3339 UTC, honouring `SOURCE_DATE_EPOCH`, with the
profile, `rustc`, target and debug-assertions state) and
`build id:` (the linker's GNU build-id on Linux). Two builds of one
`build id:` (the identifier the linker stamped into the executable,
read back at run time: the GNU build-id note on Linux, the `LC_UUID`
of a thin 64-bit Mach-O on macOS, and the `CodeView` GUID plus age on
Windows — each only when the linker emitted it; lowercase hex of the
raw bytes, `unavailable` for a universal Mach-O or any other shape,
#1777). Two builds of one
tree share a digest whatever their mtimes or branch, and two
binaries that both print `2.4.0` from different commits do not —
which is the question "is this installed `bca` the one this checkout
Expand Down Expand Up @@ -747,6 +772,21 @@ for historical reference.
repository's Rust and the `serde` corpus); the new
`nom/deep-one-attribute-items` scaling probe reads 2.00 before and
1.08 after.
- **The agent hooks run the analyzer whose build inputs match the
tree** (#1776). Since #1773 nothing in the ordinary workflow builds
release, so the `target/release/bca` the Claude Code hook and the
OpenCode plugin preferred was routinely a stale binary and the
per-edit advisory reported offenders a different `bca` computed than
`make self-scan`. `analyzer()` now takes `$BCA` unprobed; else the
first of `target/debug/bca`, `target/release/bca` and PATH `bca` whose
`--version` `build inputs:` equals the digest `utils/self_scan_digest.py`
computes over the checkout — the test the self-scan applies; else the
newest local build; else PATH `bca`. The `[bca-check]` health line
names the choice and why. Discovery shares one 4 s budget under the
hook's signal, the digest script is resolved from the hook module
rather than a nested checkout, and the plugin resolves once per
checkout root per event.

- `utils/check-role-coverage.py`: the "no baseline section" error named
`--report` as the way to list a new language's residue entries, but
`--report` prints only per-language counts; it now names
Expand Down
Loading
Loading