Skip to content

fix(score): resolve path references by basename before calling them broken - #315

Merged
stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-293
Sep 20, 2026
Merged

stackbilt-admin merged 2 commits into
mainfrom
auto/bugfix/issue-293

Conversation

@stackbilt-admin

@stackbilt-admin stackbilt-admin commented Sep 20, 2026 •

Copy link
Copy Markdown
Member

Closes #293

The bug

charter score grades Grounding partly on how many referenced paths resolve. A fenced
directory-tree block expresses the path prefix structurally, through indentation, so the
tokens it contains are real filenames with the prefix missing:

src/
  terminal/    terminalEvents.ts (event protocol)
  simulation/  random.ts (seeded RNG)

Every one of those files exists, but terminalEvents.ts, random.ts and simulation/random.ts
all fail a literal fs.existsSync check and were counted broken. The perverse incentive: the
more 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 files
before classifying it as broken. Two conditions must both hold:

  1. The basename is unique. Zero or several matches stay broken rather than resolving
    arbitrarily — index.ts, which appears in many directories here, is never resolved.
  2. Every segment the author actually wrote agrees with the real file's trailing segments.

Condition 2 is checked against reference.candidate, the authored text — not
reference.resolved.
This is the detail that is easy to get wrong: resolveReferencedPath
prefixes the source file's directory, so parser.ts referenced 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 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:

No Cloudflare Worker artifacts — wrangler.toml, schema.sql, and src/worker.ts are
never generated

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 to
src/utils/helper.ts after the file moved to packages/core/lib/helper.ts reported
broken: [] — stale-path documentation rot made invisible, which is exactly what Grounding
exists 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.ts false positive. Both shapes #293 reports still
resolve: bare terminalEvents.ts and partial-prefix simulation/random.ts.

Implementation notes

A single Map<string, string[]> basename index is built once inside buildScoreReport — once per
charter score invocation, not once per reference, so no O(refs × files) scan. validPaths is
derived as pathReferences.size - brokenPaths.length, so correcting brokenPaths corrects both
numbers; 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 when README.md is present, so the fallback
never runs there; on a case-sensitive checkout a wrong-case reference is genuinely broken and
stays reported.

Index provenance (corrected from the first revision). collectRepoFiles uses
git ls-files --cached --others --exclude-standard in a git repo, and otherwise falls back to
walkRepo, which skips the hardcoded WALK_IGNORE_DIRS but does not read .gitignore. So
node_modules and the usual build output stay out of the index either way, but an unusually-named
ignored 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 — createTempRepo never runs
git init, so every test exercises the walk fallback.

Directory tokens are unaffected. The prose extractor requires a known file extension, so
src/ and terminal/ from a tree line are never extracted at all. A backticked `src/` can
reach 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/dist on the unmodified branch and again after the
change, back to back:

Broken references Paths resolving Grounding Total
Before 79 54/133 13/20 91/100
After 48 85/133 15/20 93/100

The removed entries are the #293 class — mostly filenames referenced inside .ai/*.adf modules,
which resolveReferencedPath prefixes with the source file's directory (.ai/parser.ts) while
the file really lives at packages/adf/src/parser.ts. Genuinely absent files are still reported:
Cargo.toml, wrangler.toml, schema.sql and src/worker.ts do not exist anywhere in this
Node/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 is
meant to catch rather than asserted by inspection:

Test Red against
resolves directory-tree filenames by unique basename original score.ts (the #293 bug)
matches basenames case-sensitively original score.ts
keeps a unique basename broken when the referenced directory disagrees basename-only revision — reproduced expected [] to include 'config/database.yml'
resolves a partial path prefix written from a nested source file suffix-on-resolved — reproduced expected ['.ai/src/parser.ts'] to not include '.ai/src/parser.ts'
keeps an ambiguous basename broken rather than resolving it arbitrarily green on all variants (guard)
still reports a reference that exists nowhere in the repo green on all variants (guard)

The 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 resolved and
break 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 a
case-insensitive filesystem — the fallback always executes and the index lookup is what is under
test. A naive version that puts README.md at the root passes on a case-insensitive checkout
while the logic is wrong, because existsSync short-circuits before the index is consulted.

pnpm test 922/922 passed (916 baseline + 6). pnpm run typecheck clean.

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.adf in a README tree block resolves against
examples/context-routing-benchmark/after/.ai/backend.adf because 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

…roken (closes #293)

Co-Authored-By: Claude Opus 5 (1M context) <[email protected]>

@stackbilt-admin stackbilt-admin left a comment

Copy link
Copy Markdown
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.


  1. [BLOCKING] resolvesByBasename requires zero path agreement, and it already marks a documented non-existent file as resolved on this repo. packages/cli/src/commands/score.ts:444-445 resolves a reference whenever its basename is unique anywhere in the inventory, regardless of whether any directory segment agrees. packages/cli/src/commands/score.ts:448 then removes it from brokenPaths.

    Concretely, on this repository right now, with the PR applied:

    • README.md:128 reads: - **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 — because harness/corpus/worker.ts, an unrelated test-corpus fixture, happens to be the only worker.ts in 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 only database.yml is test/fixtures/database.yml. Result: {"total":2,"valid":1,"broken":["deploy/prod/secrets.yml"]} — the bogus reference resolved.
    • Doc references src/utils/helper.ts after the file moved to packages/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) and simulation/random.ts (partial prefix) both still resolve.

    Two implementation details, or this will be written wrong:

    • Compare against reference.candidate, not reference.resolved. resolveReferencedPath (score.ts:1120) prefixes the source file's directory, so .ai/core.adf referencing random.ts yields resolved = .ai/random.ts, which is not a suffix of src/random.ts. Suffix-on-resolved would silently break every reference made from a non-root doc. (I verified this shape resolves correctly today — basename-on-resolved works only because path.posix.join preserves 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]);
    };
  2. [BLOCKING] Add a regression test pinning the unsound case. packages/cli/src/__tests__/score.test.ts:287-374 has 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 only test/fixtures/database.yml, have a doc reference config/database.yml, and assert it stays in broken. Without it the suffix rule reads as redundant and will be "simplified" back to basename-only later. Consider also asserting src/worker.ts stays broken in whatever real-repo check backs the CHANGELOG numbers, since that is the reference the current evidence quietly gets wrong.

  3. [NIT] The CHANGELOG line and the comment at packages/cli/src/commands/score.ts:428-431 overstate where the index comes from. Both say it is built from git ls-files --exclude-standard, so "dependencies and build output cannot resolve a reference". collectRepoFiles (score.ts:744) falls back to walkRepo (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, since createTempRepo (score.test.ts:488) never runs git init. The walk honors only the hardcoded WALK_IGNORE_DIRS (score.ts:276: .git, .next, .turbo, .yarn, coverage, dist, build, node_modules), not .gitignore, so a gitignored out/, target/ or vendor/ 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.

  4. [NIT] Directory-shaped tokens can never benefit from the fallback, and one shape is mildly wrong. inventory.files holds files only, so a tree row like terminal/ (real path src/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 by extractPathCandidates (score.ts:1078), so this only bites for backticked directory references in prose; on my probe those surfaced as broken: ["terminal/","src/utils/"]. The inverse is the odd one: path.posix.basename('terminal/') is terminal, 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 of resolveReferencedPath (score.ts:1120-1140) returns through normalizeRelativePath (score.ts:1637), which replaces \ again. inventory.files is normalized identically at score.ts:750. path.posix.basename is safe here.
  • Index is built once. buildScoreReport has exactly one caller (score.ts:303); the index at score.ts:434-443 is built before the filter, not per reference. It is a Map over strings already resident in inventory.files; unconditional construction is fine.
  • No double-correction. validPaths (score.ts:450) is the only derivation, and every consumer reads it or brokenPaths directly: 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:448 to .filter((reference) => !pathExists(reference.resolved)) and re-running gives 2 failed / 4 passed across the six grounding checker tests — 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'], proving pathExists('README.md') returned false on this case-insensitive /mnt/c host — the short-circuit did not fire. The fixture root contains no readme of any casing (the only one is docs/README.md), so this holds on every filesystem; the test does not depend on os.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 at score.test.ts:314-316.
  • Scope is clean. Three files, all on-topic; no unrelated changes. CHANGELOG entry is correctly placed under ### Fixed with the #293 reference, 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]>
@stackbilt-admin
stackbilt-admin merged commit 58ec21f into main Sep 20, 2026
5 checks passed
@stackbilt-admin
stackbilt-admin deleted the auto/bugfix/issue-293 branch September 20, 2026 13:53
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

bug(score): directory-tree code blocks in README produce broken-reference false positives

1 participant