Repository navigation
fix(score): resolve path references by basename before calling them broken - #315
Conversation
…roken (closes #293) Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
stackbilt-admin
left a comment
There was a problem hiding this comment.
CHANGES_REQUESTED
The fix targets the right defect and the tree-block case genuinely works. But the unique-basename rule as specified has no path-segment agreement at all, and it already produces a false "resolved" on this very repository — including on one of the three files the PR's own CHANGELOG cites as evidence that genuinely-absent files stay broken. A suffix-agreement variant fixes that at a measured cost of exactly one reference, and passes all four of the PR's new tests unchanged.
-
[BLOCKING]
resolvesByBasenamerequires zero path agreement, and it already marks a documented non-existent file as resolved on this repo.packages/cli/src/commands/score.ts:444-445resolves a reference whenever its basename is unique anywhere in the inventory, regardless of whether any directory segment agrees.packages/cli/src/commands/score.ts:448then removes it frombrokenPaths.Concretely, on this repository right now, with the PR applied:
README.md:128reads:- **No Cloudflare Worker artifacts** — `wrangler.toml`, `schema.sql`, and `src/worker.ts` are never generated. The README's own text asserts those three files do not exist here.- The CHANGELOG entry cites the first two from that sentence as proof the fix does not over-resolve: "while genuinely absent files (
Cargo.toml,wrangler.toml,schema.sql) are still reported". - The third file from the same sentence,
src/worker.ts, is now counted valid — becauseharness/corpus/worker.ts, an unrelated test-corpus fixture, happens to be the onlyworker.tsin the inventory.
That is exactly the score-inflation failure mode: a reference that is genuinely broken is silently marked resolved, and it is demonstrated on the repo the PR uses as its own evidence. Two more reproductions I ran against the branch:
- Doc references
config/database.yml, which exists nowhere; the onlydatabase.ymlistest/fixtures/database.yml. Result:{"total":2,"valid":1,"broken":["deploy/prod/secrets.yml"]}— the bogus reference resolved. - Doc references
src/utils/helper.tsafter the file moved topackages/core/lib/helper.ts. Result:broken: []. Stale-path documentation rot, which is precisely what Grounding exists to catch, is now invisible.
Judgment on the issue's Option 2 as specified: too loose. The issue author proposed basename-only matching, but the reported shapes do not need that much slack. Require the reference's trailing segments to be a suffix of the matched file's segments. Measured on this repo:
variant total valid broken this PR 133 86 47 suffix agreement 133 85 48 The delta is one single reference, and it is
src/worker.ts— i.e. the stricter rule's only "cost" is eliminating the false positive above. It is a gain, not a regression. All four of the PR's new tests and both pre-existing grounding tests pass unchanged under the suffix variant, so the reported case is fully preserved:terminalEvents.ts(bare basename) andsimulation/random.ts(partial prefix) both still resolve.Two implementation details, or this will be written wrong:
- Compare against
reference.candidate, notreference.resolved.resolveReferencedPath(score.ts:1120) prefixes the source file's directory, so.ai/core.adfreferencingrandom.tsyieldsresolved = .ai/random.ts, which is not a suffix ofsrc/random.ts. Suffix-on-resolvedwould silently break every reference made from a non-root doc. (I verified this shape resolves correctly today — basename-on-resolvedworks only becausepath.posix.joinpreserves the last segment.) - Strip
.and..segments from the candidate before comparing.
Sketch of what I measured:
const resolvesByBasename = (reference: ResolvedPathReference): boolean => { const wanted = normalizeRelativePath(reference.candidate) .split('/') .filter((segment) => segment && segment !== '.' && segment !== '..'); if (wanted.length === 0) return false; const matches = basenameIndex.get(wanted[wanted.length - 1]); if (matches?.length !== 1) return false; const actual = matches[0].split('/'); if (wanted.length > actual.length) return false; const offset = actual.length - wanted.length; return wanted.every((segment, index) => segment === actual[offset + index]); };
-
[BLOCKING] Add a regression test pinning the unsound case.
packages/cli/src/__tests__/score.test.ts:287-374has no test where a reference's directory is wrong but its basename is unique — which is the entire precision risk of this change. Add one: create onlytest/fixtures/database.yml, have a doc referenceconfig/database.yml, and assert it stays inbroken. Without it the suffix rule reads as redundant and will be "simplified" back to basename-only later. Consider also assertingsrc/worker.tsstays broken in whatever real-repo check backs the CHANGELOG numbers, since that is the reference the current evidence quietly gets wrong. -
[NIT] The CHANGELOG line and the comment at
packages/cli/src/commands/score.ts:428-431overstate where the index comes from. Both say it is built fromgit ls-files --exclude-standard, so "dependencies and build output cannot resolve a reference".collectRepoFiles(score.ts:744) falls back towalkRepo(score.ts:765) whenever the directory is not a git repo or the git call fails — which is the path every new test fixture takes, sincecreateTempRepo(score.test.ts:488) never runsgit init. The walk honors only the hardcodedWALK_IGNORE_DIRS(score.ts:276:.git,.next,.turbo,.yarn,coverage,dist,build,node_modules), not.gitignore, so a gitignoredout/,target/orvendor/would enter the index there. The big offenders are covered in practice, so this is wording, not behavior — but the claim as written is not what the code does. -
[NIT] Directory-shaped tokens can never benefit from the fallback, and one shape is mildly wrong.
inventory.filesholds files only, so a tree row liketerminal/(real pathsrc/terminal/) stays broken — the fix is incomplete for the directory rows of the very tree blocks it targets, though not wrong. I confirmed the bare unindented rows (src/,terminal/) are not extracted as candidates at all byextractPathCandidates(score.ts:1078), so this only bites for backticked directory references in prose; on my probe those surfaced asbroken: ["terminal/","src/utils/"]. The inverse is the odd one:path.posix.basename('terminal/')isterminal, so a reference to a missing directory can resolve against a unique extensionless file of that name. Narrow, and the suffix rule in (1) does not change it. Flagging, not blocking.
Verified, no action needed (so this is not re-litigated):
- Backslashes are unreachable in
reference.resolved.normalizePathCandidate(score.ts:1113) does.replace(/\\/g, '/'), and every branch ofresolveReferencedPath(score.ts:1120-1140) returns throughnormalizeRelativePath(score.ts:1637), which replaces\again.inventory.filesis normalized identically atscore.ts:750.path.posix.basenameis safe here. - Index is built once.
buildScoreReporthas exactly one caller (score.ts:303); the index atscore.ts:434-443is built before the filter, not per reference. It is aMapover strings already resident ininventory.files; unconditional construction is fine. - No double-correction.
validPaths(score.ts:450) is the only derivation, and every consumer reads it orbrokenPathsdirectly:pathScore(:460-461), summary (:595), recommendation input (:644→:1475-1479), JSON signals (:668-671). Nothing recomputes independently. - Test claims hold exactly as stated. Reverting only
score.ts:448to.filter((reference) => !pathExists(reference.resolved))and re-running gives 2 failed / 4 passed across the sixgrounding checkertests — the two failures being "resolves directory-tree filenames by unique basename" and "matches basenames case-sensitively". The other two new tests pass pre-fix, exactly as the implementer said; they are over-eagerness guards, not bug detectors. That honesty holds. Working tree restored, nothing committed. - The case-sensitivity trap is genuinely avoided. The pre-fix run reports
broken: ['README.md', 'Readme.md'], provingpathExists('README.md')returned false on this case-insensitive/mnt/chost — the short-circuit did not fire. The fixture root contains no readme of any casing (the only one isdocs/README.md), so this holds on every filesystem; the test does not depend onos.tmpdir()being case-sensitive. - Both reported shapes are handled and tested. Bare basename (
terminalEvents.ts) and partial prefix (simulation/random.ts) both resolve, and both are asserted atscore.test.ts:314-316. - Scope is clean. Three files, all on-topic; no unrelated changes. CHANGELOG entry is correctly placed under
### Fixedwith the#293reference, subject to the wording in (3).
🤖 Generated with Claude Code
#293) Basename-only matching resolved a reference against any uniquely-named file, including one in a directory the author never wrote. README.md:128 names wrangler.toml, schema.sql and src/worker.ts as artifacts this repo never generates; the first two stayed broken but src/worker.ts silently resolved against harness/corpus/worker.ts, an unrelated test-corpus fixture. A stale src/utils/helper.ts pointing at a file since moved to packages/core/lib/ likewise resolved, hiding the documentation rot Grounding exists to surface. A match must now also agree on every path segment the author actually wrote. That is checked against reference.candidate, the authored text, not against reference.resolved: resolveReferencedPath prefixes the source file's directory, so a reference to parser.ts from .ai/core.adf resolves to .ai/parser.ts, which is not a suffix of packages/adf/src/parser.ts. Comparing the resolved form would break every reference made from a non-root document. Cost on this repo is one reference: valid 86 -> 85, broken 47 -> 48, and the single delta is the src/worker.ts false positive. Both shapes #293 reports still resolve. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>
Closes #293
The bug
charter scoregrades Grounding partly on how many referenced paths resolve. A fenceddirectory-tree block expresses the path prefix structurally, through indentation, so the
tokens it contains are real filenames with the prefix missing:
Every one of those files exists, but
terminalEvents.ts,random.tsandsimulation/random.tsall fail a literal
fs.existsSynccheck and were counted broken. The perverse incentive: themore thorough a README's structure section, the worse the score.
The fix
When
pathExists(reference.resolved)is false, match the reference against the repo's real filesbefore classifying it as broken. Two conditions must both hold:
arbitrarily —
index.ts, which appears in many directories here, is never resolved.Condition 2 is checked against
reference.candidate, the authored text — notreference.resolved. This is the detail that is easy to get wrong:resolveReferencedPathprefixes the source file's directory, so
parser.tsreferenced from.ai/core.adfresolves to.ai/parser.ts, which is not a suffix ofpackages/adf/src/parser.ts. Comparing the resolvedform would silently break every reference made from a non-root document — the dominant shape in
this repo. A test pins this (see below).
Why condition 2 is not optional
An earlier revision of this PR used basename matching alone. It was unsound, and this PR's own
evidence sentence caught it. README.md:128 reads:
Basename-only kept the first two broken but resolved the third against
harness/corpus/worker.ts, an unrelated test-corpus fixture. Same class: a doc reference tosrc/utils/helper.tsafter the file moved topackages/core/lib/helper.tsreportedbroken: []— stale-path documentation rot made invisible, which is exactly what Groundingexists to catch. With trailing-segment agreement all three of README.md:128's artifacts are
correctly reported broken again.
Measured cost of the stricter rule on this repo: one reference. Valid 86 → 85, broken 47 → 48,
and the single delta is the
src/worker.tsfalse positive. Both shapes #293 reports stillresolve: bare
terminalEvents.tsand partial-prefixsimulation/random.ts.Implementation notes
A single
Map<string, string[]>basename index is built once insidebuildScoreReport— once percharter scoreinvocation, not once per reference, so no O(refs × files) scan.validPathsisderived as
pathReferences.size - brokenPaths.length, so correctingbrokenPathscorrects bothnumbers; the summary line, the recommendation and the JSON signals all read from those same two
values, and no second classification site exists.
Matching is exact-case throughout, mirroring git. On a case-insensitive filesystem
fs.existsSync('Readme.md')already returns true whenREADME.mdis present, so the fallbacknever runs there; on a case-sensitive checkout a wrong-case reference is genuinely broken and
stays reported.
Index provenance (corrected from the first revision).
collectRepoFilesusesgit ls-files --cached --others --exclude-standardin a git repo, and otherwise falls back towalkRepo, which skips the hardcodedWALK_IGNORE_DIRSbut does not read.gitignore. Sonode_modulesand the usual build output stay out of the index either way, but an unusually-namedignored directory could contribute a file on the walk path. The earlier claim that "dependencies
and build output cannot resolve a reference" overstated this; the code comment now says what the
code does. This matters for the test fixtures in particular —
createTempReponever runsgit init, so every test exercises the walk fallback.Directory tokens are unaffected. The prose extractor requires a known file extension, so
src/andterminal/from a tree line are never extracted at all. A backticked`src/`canreach the filter, but the index holds file basenames only, so it finds no match.
Before / after on this repository
Measured with a freshly built
packages/cli/diston the unmodified branch and again after thechange, back to back:
The removed entries are the #293 class — mostly filenames referenced inside
.ai/*.adfmodules,which
resolveReferencedPathprefixes with the source file's directory (.ai/parser.ts) whilethe file really lives at
packages/adf/src/parser.ts. Genuinely absent files are still reported:Cargo.toml,wrangler.toml,schema.sqlandsrc/worker.tsdo not exist anywhere in thisNode/TypeScript repo and all remain in the broken list.
Tests
Six tests in
packages/cli/src/__tests__/score.test.ts, each verified against the source it ismeant to catch rather than asserted by inspection:
resolves directory-tree filenames by unique basenamescore.ts(the #293 bug)matches basenames case-sensitivelyscore.tskeeps a unique basename broken when the referenced directory disagreesexpected [] to include 'config/database.yml'resolves a partial path prefix written from a nested source fileresolved— reproducedexpected ['.ai/src/parser.ts'] to not include '.ai/src/parser.ts'keeps an ambiguous basename broken rather than resolving it arbitrarilystill reports a reference that exists nowhere in the repoThe last two are honest guards against an over-eager implementation, not bug detectors. The middle
two are the ones that make this revision's rule non-redundant: without them, someone would
reasonably "simplify" the suffix check back to basename-only, or write it against
resolvedandbreak every nested reference. I produced both red runs by temporarily reverting the source, not by
reasoning about it.
The case test is deliberately filesystem-independent. The real file is placed at
docs/README.md,never at the repo root, so
pathExists('README.md')is false on a case-sensitive and acase-insensitive filesystem — the fallback always executes and the index lookup is what is under
test. A naive version that puts
README.mdat the root passes on a case-insensitive checkoutwhile the logic is wrong, because
existsSyncshort-circuits before the index is consulted.pnpm test922/922 passed (916 baseline + 6).pnpm run typecheckclean.Remaining limit, stated plainly
The suffix rule can only constrain what the author actually wrote. A bare filename still
resolves to a unique match anywhere in the repo — that is the whole point of #293, but it means
backend.adfin a README tree block resolves againstexamples/context-routing-benchmark/after/.ai/backend.adfbecause this repo has no.ai/backend.adf.No rule keyed on the reference text can distinguish those without the tree's indentation
structure, which the extractor discards. Narrow, and not expanded here.
🤖 Generated with Claude Code