Repository navigation
fix(xtask): resolve link anchors in markdown-links (#3975) - #3989
Conversation
`markdown-links` reads as the gate that keeps cross-document links working and is in `precommit`, but it validated only the document half of a link and ignored the `#fragment`. A link to a heading that had been renamed passed, so a heading rename silently broke every deep link into it. The check now resolves the fragment against the target document's headings and fails when it names none. Same-document `#anchor` links are covered by the same pass, and that found one real break: `docs/ROADMAP.md` still linked to `#current-operating-sequence-...` after the heading was renamed to `Historical Operating Sequence`. Both the anchor and the link text now name the heading the document actually has. The slug rule is GitHub's, including the part that matters most here: a dropped character leaves the spaces around it behind, so ` — ` and ` / ` produce a doubled dash. Collapsing consecutive separators instead reports twelve false failures on today's tree, measured. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PTKGFhuph96fcVyfb8vBxK
|
Important Review skippedBot user detected. To trigger a single review, invoke the ⚙️ Run configurationConfiguration used: Organization UI Review profile: ASSERTIVE Plan: Advanced Run ID: You can disable this status message by setting the Use the checkbox below for a quick retry:
Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out. Comment |
There was a problem hiding this comment.
Confirmed findings
- read_text_lossy(&resolved) is called inside the cache miss branch and can return Err(String). If the target file disappears between cache miss and read, the whole markdown_links check aborts rather than reporting the link. This is an ownership-of-error contract observation, not a memory-safety blocker.
- markdiff at line 10825 shows a new fn followed by re-aligning an existing
markdown_links_in_line; no functional change but unusual to insert free-standing helpers between existing helpers and a known sibling. Code review of xtask/src/main.rs hygiene only - does not affect behavior. - No active-view region exists in this diff: all changed code is Rust markdown-link parsing with owned String/BTreeSet/BTreeMap values, no slice-against-backing-store, no detach/transfer, no resize. The lane's nominal subject is absent, so the lane has nothing to flag.
Verification questions
- Confirm three helpers (heading_slug / heading_slugs / atx_heading_title) co-located under markdown_links is appropriate scope; they are not reused outside this check and would not be used elsewhere on this diff.
- Confirm setext-style headings (=== / ---) are not covered by atx_heading_title or heading_slugs and have no test; any such heading in tracked Markdown would be silently absent from heading_slugs.
Refuted
- Worker-handoff UB concern could arise from a parallel cache populated across threads.; refuted because: heading_cache is built and read on the same thread within markdown_links; no Send/Sync crossing, no spawn, no rayon par_iter.
- No red/green oracle proves the cross-document fragment failure message names both the link and the target; refuted because: The PR body's discrimination table claims 'fails, naming the link and the target' for a cross-document broken fragment. heading_slugs_read_only_real_headings and the four unit tests cover the slug/heading logic, and the 122-anchor corpus run is the integration check, but no focused test asserts the exact failure-string format for a missing-fragment case in markdown_links itself. This is the only gap of any size.
- Allocation failure in read_text_lossy or heading_cache could be weaponized to skip checks (DoS or info path); refuted because: cargo-allow and miri are skipped and diff raises no allocation-failure objection. Even on alloc failure, the function returns Err which propagates and aborts the check run rather than silently passing. This is a false-premise in scope of the diff.
- heading_cache should be lazy_global rather than per-invocation.; refuted because: The cache is scoped to one markdown_links() call, which is exactly the reuse boundary xtask needs; a process-global would couple unrelated subcommands and survive across runs that may want a fresh tree.
- heading_cache stores a BTreeSet that could be reused as a view onto target_text and become stale if the cache is later mutated or if target_text is re-read into the same buffer; refuted because: Cache key is the resolved PathBuf; entry is set only when contains_key returns false. BTreeSet owns its strings; read_text_lossy returns a fresh String each call. No shared backing storage, no slice aliasing.
Evidence gaps
- Model proof intent was rejected by deterministic validation.
Parked follow-ups
- Setext headings (=== / --- underlining) and ATX with no space after hashes are not handled by atx_heading_title. The repository is reported as using ATX only; if any future doc introduces a setext heading that a link points to, heading_slugs will miss it and the link will fail. Worth noting for parked follow-up, not actionable today.
The review found the one real gap: the PR's discrimination table claimed the cross-document failure names both the link and its target, but that rested on a manual run. Nothing in the test suite asserted it, so a refactor that stopped producing the violation would leave a passing tree and a gate that no longer gates — the exact class this change exists to close. The decision is now its own function, `missing_anchor_violation`, with a test that asserts a resolving anchor produces nothing and a missing one names the source line, the link and the target document. Replacing the `slugs.contains` check so the violation is never produced fails that test and no other. The heading cache moves to the entry API in the same pass, which removes the second lookup and the unreachable "just inserted but absent" arm it would otherwise need. Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01PTKGFhuph96fcVyfb8vBxK
|
Review answered at Repaired"No focused test asserts the exact failure-string format for a missing-fragment case in Correct, and it is the gap that matters most on this particular PR: the whole claim is that a gate's stated contract should equal its enforcement, and the enforcement of the new rule rested on a manual run plus the 122-link corpus. A refactor that stopped producing the violation would have left a passing tree and a gate that no longer gates — the failure class this change exists to close, reintroduced by the change itself. The decision is now its own function, The same pass moves the heading cache to the entry API. That was a side effect of extracting the function, but a welcome one: the previous Answered, not changed
Deliberate, and consistent with what the check already did: the source-file read three lines up is Setext headings ( Measured rather than assumed: the tracked Markdown tree has zero setext headings. A scan for an underline run following a non-blank line returns ten hits, and all ten are the closing So this is the same call the PR body already records for HTML Helper placement between existing helpers. The three new helpers sit immediately after "Confirm three helpers co-located under Confirmed, and that is the intent. They are private to
Generated by Claude Code |
EffortlessSteven
left a comment
There was a problem hiding this comment.
Review (exact head 657e3df)
Surfaces: xtask/src/main.rs (markdown_links + helpers), types.rs (LocalMarkdownTarget), command.rs catalog wording, docs/ROADMAP.md:1077 real-fix link, tests.rs.
- Stimulus/oracle: unit tests pin GitHub's slug rule including the load-bearing no-collapse doubled-dash cases (measured against 12 false failures on today's tree), repeated-heading numbering, fence/
#hashtag/closing-hash/ATX-level rejection, and the violation message naming both link and target. - Owner: one parser (
local_markdown_target) owns the path/fragment split; the gate decision lives inmissing_anchor_violationwith its own test — a refactor that stopped producing the violation leaves a failing test, not a dead gate. - Cross-document vs same-document fragments both resolve; non-Markdown targets with fragments (
src/lib.rs#L20) are correctly out of scope; heading reads cached per resolved path per run. - Bot findings assessed: abort-on-read-error matches the check's existing
read_text_lossy?contract for source files; setext headings parked (repo is ATX-only, not actionable today); helper placement is hygiene-only. - Validation: published-head
Ripr Rust Small ResultSUCCESS;mergeStateStatusCLEAN.
Disposition: REVIEW_READY.
|
You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard. |
There was a problem hiding this comment.
Confirmed findings
- Setext headings are explicitly out of scope; failure mode on a future setext heading is loud (precommit fails) rather than silent pass, which is the correct failure direction. Not actionable today.
- h1 test for repeat-heading numbering does not probe the GitHub rule that interleaving increments the counter (e.g.,
# Added/# Other/## Added=>added,added-1from the second# Added, but the third heading# Otherdoesn't reset it; the third## Addedshould beadded-2). Current rule matches GitHub but is not tested. - Lane subject (worker/async/detach/transfer) is absent; diff is synchronous Rust markdown parsing only.
local_markdown_target_keeps_a_same_document_anchorasserts#anchorand#only. It does not assert thelocal_markdown_target("#") == Nonedecision survives the surroundingpath.is_none() && fragment.is_none()branch whendocumentis empty and fragment is empty — the empty-fragment filter is the new code. Also missing:#foo?bar(fragment with query) and#foo%20bar(URL-encoded space). (xtask/src/tests.rs:22066).- Helper placement: heading_slug/heading_slugs/atx_heading_title/missing_anchor_violation are inserted between markdown_links and markdown_links_in_line. Same scope (markdown-links only) but unusual layout; hygiene only, no behavior impact. Matches github-actions[bot] review note.
- Setext headings (===/---) are explicitly out of scope and the repo has zero; a future setext addition would break precommit loudly (false-failure direction), which is the safer failure mode but still undocumented in the check's error message.
- Catalog wording in
command.rs('Checks Markdown links and their heading anchors.') is the only public-facing claim delta. Behavior matches: missing-fragment now fails the gate. No source-route gap, but worth noting this is the user-visible contract change.
Verification questions
- Confirm h4 test corpus is mostly trivial: '#hashtag' rejected, '####### Seven Hashes' rejected, '# Title' and '## Closing Hashes ##' accepted. It does not probe the closing-hash rule's edge:
## Foo ##(trailing spaces before closing hashes), nor# Foo#(no space, hash is part of word). - Confirm h3 test asserts 6 fixed slug cases including the load-bearing doubled-dash cases. It does not probe Unicode lowercase beyond the literal em-dash case, nor consecutive non-ASCII punctuation, but the rule is character-class based and the case table is small.
Evidence gaps
- artifact-verifier failed (exit 2) with no sensor-status receipt; this lane cannot confirm whether the markdown-links report file or PolicyReportSpec output is among the failed artifacts.
- Model proof intent was rejected by deterministic validation.
- cargo xtask markdown-links full-tree run and cargo test --workspace are not locally witnessed in this diff; PR body defers to hosted CI.
Requested by Steven · project thread
Summary
Before:
cargo xtask markdown-linksvalidated the document half of a link andignored the
#fragment. A link to a heading that no longer existed wasreported as a pass, so a heading rename silently broke every deep link into it
and nothing in
precommitor CI noticed.After: the check resolves the fragment against the target document's headings
and fails when it names none.
Same-document
#anchorlinks go through the same pass, and that found one realbreak on
main:docs/ROADMAP.md:1077linked to#current-operating-sequence-090-release-and-evidence-to-repair-routingafterthe heading was renamed to
Historical Operating Sequence: …. The section nowopens with "Historical context", so both the anchor and the link text are
repaired to name the heading the document actually has, rather than the anchor
alone.
How:
local_markdown_targetreturns both halves of a link instead of thedocument alone, so one parser owns the split.
heading_slugsreads adocument's ATX headings outside fences and offers GitHub's anchor for each,
numbering repeats the way GitHub does.
missing_anchor_violationmakes theone decision the check exists to make. Target documents are read once and
cached for the run.
The slug rule, and why it is not approximate
GitHub lowercases a heading, turns each space into
-, and drops every othercharacter that is not a letter, digit,
_or-. Dropping rather thancollapsing is the load-bearing part: an em-dash or a slash surrounded by spaces
leaves both of those spaces behind, so the anchor carries a doubled dash.
A checker that collapsed consecutive separators would be wrong in the
expensive direction: it reports failures on links that work. Measured, not
assumed: mutating
heading_slugto collapse them makes the gate reporttwelve false failures on today's tree, ten of them
docs/LIBRARY.mdlinksinto
docs/LEARNINGS.md.Swarm / Source Boundary
surface
No publishing, signing, release-asset, or release-secret surface is touched.
Source-of-truth Links
Proposal:
Spec:
ADR:
Plan item:
Active goal: #2379
Issue: #3975
Scope
cargo xtask markdown-links, and the one link indocs/ROADMAP.mdthat therepaired gate rejects.
Scope Classification
Production delta:
markdown-linksfails a link whose#fragmentnames no heading in thetarget document. Links with no fragment, and links to documents that do not
exist, behave exactly as before.
#anchorlinks are now in scope; they were skipped entirely.("Checks Markdown links and their heading anchors.") rather than the wider
"Checks Markdown links."
Evidence/support delta:
xtask/src/tests.rs: the violation the check produces andwhat it names, the slug rule against six real repository headings, GitHub's
repeat numbering, what counts as a heading, and the same-document anchor the
parser used to discard. Three existing tests are updated for the typed link
target.
docs/ROADMAP.md:1077repaired.Single acceptance criterion:
markdown-links; every link in the repository that resolves on GitHub todaystill passes.
Non-goals:
src/lib.rs#L20) are skipped: thosedocuments have no headings for this check to read.
<a id="…">) are not read as heading targets. The repositoryhas none, so implementing that would add an untested branch.
repository has none.
===/---underlining) are not read, for the samereason again. Scanned: the tracked tree has zero. An underline run following
a non-blank line matches ten times and all ten are the closing
---of YAMLfrontmatter, which is not a heading. The failure direction here is a false
failure, so a setext heading appearing later breaks
precommitloudly ratherthan passing silently.
Support-tier Impact
Claim/proof notes:
report-format field changes; violations travel the existing
finish_policy_reportchannel.Policy Impact
Ledger or exception notes:
Result<(), String>and accumulate them, so nounwrap/expectwas addedand no allowlist entry was needed.
Command::new, dependency, or network surface, socheck-process-policy,check-dependenciesandcheck-network-policyareunaffected and pass.
Proof
Positive corpus. The gate reads 122 anchor links across the tracked
Markdown tree. With
docs/ROADMAP.mdrepaired, all 122 resolve, including thetwelve doubled-dash anchors that a naive slugifier would reject.
Discrimination. Five mutations, each run against the built gate or the
focused suite:
COMMAND_HIERARCHY.md#this-anchor-does-not-exist)#no-such-heading-hereheading_slugcollapses consecutive separatorsheading_slugsdrops GitHub's repeat numberingmissing_anchor_violationnever produces a violationRestored after each, the gate passes and the twelve focused tests pass.
Result, failures, or skipped proof:
xtaskrun, disclosed rather than classified:reports::eval_sweep_refresh::python_eval_sweep_refresh::unreadable_subtree_marks_corpus_selection_incomplete.It chmods a directory to
0o000and expects the walk to fail; this containerruns as uid 0, which bypasses the permission bits. It is in a file this diff
does not touch. Hosted CI is the authority.
cargo test --workspace,cargo doc,cargo packageandcargo publish --dry-runwere not run here; they remain for the fixed-candidate step.Claim Boundary
After this PR, a renamed heading breaks
precommitinstead of breaking linkssilently. It may not be claimed that every link in the repository is correct:
this check reads repository-local Markdown only, so an external URL, a
fragment into a non-Markdown file, or a link whose text no longer matches its
target is still unchecked.
markdown-linksgreen now means the file and theanchor resolve; before this PR it meant the file alone, which is why #3974's
fix could not use it as evidence.
Rollback
Revert the commits on this branch. The change is confined to the
markdown-linkscheck, its tests, and one line ofdocs/ROADMAP.md; nopersisted state, schema field, or config key.
Spec-Test-Code Traceability
xtask/src/tests.rs—a_fragment_with_no_heading_names_the_link_and_the_target,heading_slug_drops_punctuation_without_collapsing_the_spaces_around_it,heading_slugs_number_repeated_headings_the_way_github_does,heading_slugs_read_only_real_headings,local_markdown_target_keeps_a_same_document_anchor,local_markdown_target_returns_relative_local_paths, and the existingmarkdown_link_helpers_skip_fences_and_external_targetsxtask/src/main.rs(markdown_links,local_markdown_target,missing_anchor_violation,heading_slug,heading_slugs,atx_heading_title),xtask/src/types.rs(LocalMarkdownTarget),xtask/src/command.rsStatic Language Check
killed,survived,untested,proven, andadequate.CI Economics
One additional read per Markdown document that is the target of an anchor
link, cached per run. No workflow, branch-protection, or artifact change.
Engineering Check
panic,unwrap,expect,todo, orunimplementedin production code.panic,unwrap,expect,todo, orunimplementedin tests.Gates
Ticked only where the command actually ran for this candidate.
cargo fmt --checkcargo check --workspace --all-targetscargo test --workspacecargo clippy --workspace --all-targets -- -D warnings(ran-p xtask --all-targets)cargo doc --workspace --no-depscargo package -p ripr --listcargo publish -p ripr --dry-runcargo xtask check-static-languagecargo xtask check-doc-artifactscargo xtask check-support-tierscargo xtask check-no-panic-familycargo xtask check-allow-attributescargo xtask check-local-contextcargo xtask check-file-policycargo xtask check-covered-bycargo xtask check-executable-filescargo xtask check-workflowscargo xtask check-spec-formatcargo xtask check-spec-numberingcargo xtask check-fixture-contractscargo xtask check-doc-indexcargo xtask markdown-linkscargo xtask check-command-catalogcargo xtask check-generatedcargo xtask check-badge-diff-policycargo xtask check-generated-cleancargo xtask check-dependenciescargo xtask check-process-policycargo xtask check-network-policyExtension changes: none.
🤖 Generated with Claude Code
https://claude.ai/code/session_01PTKGFhuph96fcVyfb8vBxK