Skip to content

fix(xtask): resolve link anchors in markdown-links (#3975) - #3989

Merged
EffortlessSteven merged 2 commits into
mainfrom
claude/ux-polish-doawhf-anchors
Sep 24, 2026
Merged

EffortlessSteven merged 2 commits into
mainfrom
claude/ux-polish-doawhf-anchors

Conversation

@claude

@claude claude Bot commented Sep 23, 2026 •

Copy link
Copy Markdown
Contributor

Requested by Steven · project thread

Summary

Before: cargo xtask markdown-links validated the document half of a link and
ignored the #fragment. A link to a heading that no longer existed was
reported as a pass, so a heading rename silently broke every deep link into it
and nothing in precommit or CI noticed.

After: the check resolves the fragment against the target document's headings
and fails when it names none.

docs/QUICKSTART.md:184 links to `COMMAND_HIERARCHY.md#this-anchor-does-not-exist`, and `docs/COMMAND_HIERARCHY.md` has no heading with that anchor

Same-document #anchor links go through the same pass, and that found one real
break on main: docs/ROADMAP.md:1077 linked to
#current-operating-sequence-090-release-and-evidence-to-repair-routing after
the heading was renamed to Historical Operating Sequence: …. The section now
opens 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_target returns both halves of a link instead of the
document alone, so one parser owns the split. heading_slugs reads a
document's ATX headings outside fences and offers GitHub's anchor for each,
numbering repeats the way GitHub does. missing_anchor_violation makes the
one 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 other
character that is not a letter, digit, _ or -. Dropping rather than
collapsing 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_slug to collapse them makes the gate report
twelve false failures on today's tree, ten of them docs/LIBRARY.md links
into docs/LEARNINGS.md.

Swarm / Source Boundary

  • swarm-only CI, runner, routing, source-of-truth, or agent-operating
    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 in docs/ROADMAP.md that the
    repaired gate rejects.

Scope Classification

  • One production behavior

Production delta:

  • markdown-links fails a link whose #fragment names no heading in the
    target document. Links with no fragment, and links to documents that do not
    exist, behave exactly as before.
  • Same-document #anchor links are now in scope; they were skipped entirely.
  • The command catalog's description says what the check now enforces
    ("Checks Markdown links and their heading anchors.") rather than the wider
    "Checks Markdown links."

Evidence/support delta:

  • Five new tests in xtask/src/tests.rs: the violation the check produces and
    what 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:1077 repaired.

Single acceptance criterion:

  • A Markdown link whose fragment names no heading in its target fails
    markdown-links; every link in the repository that resolves on GitHub today
    still passes.

Non-goals:

  • Fragments on non-Markdown targets (src/lib.rs#L20) are skipped: those
    documents have no headings for this check to read.
  • HTML anchors (<a id="…">) are not read as heading targets. The repository
    has none, so implementing that would add an untested branch.
  • Headings carrying inline links are not unwrapped for the same reason: the
    repository has none.
  • Setext headings (=== / --- underlining) are not read, for the same
    reason 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 YAML
    frontmatter, which is not a heading. The failure direction here is a false
    failure, so a setext heading appearing later breaks precommit loudly rather
    than passing silently.
  • External URLs and their fragments are unchanged; this check does not fetch.

Support-tier Impact

  • changes a README, release, docs, CLI, JSON, editor, CI, or package claim

Claim/proof notes:

  • The catalog description is the claim that changed. No JSON, schema, or
    report-format field changes; violations travel the existing
    finish_policy_report channel.

Policy Impact

  • no-panic

Ledger or exception notes:

  • The four new tests that can report several failures return
    Result<(), String> and accumulate them, so no unwrap/expect was added
    and no allowlist entry was needed.
  • No new Command::new, dependency, or network surface, so
    check-process-policy, check-dependencies and check-network-policy are
    unaffected and pass.

Proof

cargo fmt --check                                  # exit 0
cargo xtask precommit                              # exit 0, on this base
cargo clippy -p xtask --all-targets                # exit 0, no output
cargo run -p xtask -- markdown-links               # pass
cargo test -p xtask --bin xtask -- heading_slug local_markdown_target markdown_link missing_anchor a_fragment_with
                                                   # 12 passed
cargo test -p xtask --bin xtask                    # 2151 passed, 1 failed (below)

Positive corpus. The gate reads 122 anchor links across the tracked
Markdown tree. With docs/ROADMAP.md repaired, all 122 resolve, including the
twelve doubled-dash anchors that a naive slugifier would reject.

Discrimination. Five mutations, each run against the built gate or the
focused suite:

Mutation Result
Break a cross-document fragment (COMMAND_HIERARCHY.md#this-anchor-does-not-exist) fails, naming the link and the target
Add a same-document #no-such-heading-here fails, naming the document itself
heading_slug collapses consecutive separators twelve false failures on today's tree
heading_slugs drops GitHub's repeat numbering exactly one test fails, and no other
missing_anchor_violation never produces a violation exactly one test fails, and no other

Restored after each, the gate passes and the twelve focused tests pass.

Result, failures, or skipped proof:

  • One failure in the full xtask run, disclosed rather than classified:
    reports::eval_sweep_refresh::python_eval_sweep_refresh::unreadable_subtree_marks_corpus_selection_incomplete.
    It chmods a directory to 0o000 and expects the walk to fail; this container
    runs 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 package and cargo publish --dry-run were not run here; they remain for the fixed-candidate step.

Claim Boundary

After this PR, a renamed heading breaks precommit instead of breaking links
silently. 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-links green now means the file and the
anchor 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-links check, its tests, and one line of docs/ROADMAP.md; no
persisted state, schema field, or config key.

Spec-Test-Code Traceability

  • Spec: none (repository automation)
  • Tests: 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 existing
    markdown_link_helpers_skip_fences_and_external_targets
  • Code: xtask/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.rs
  • Golden outputs: none affected
  • Metrics: none
  • ADR/learning: none

Static Language Check

  • Static output avoids killed, survived, untested, proven, and adequate.
  • Unknowns include stop reasons where applicable.

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

  • No new panic, unwrap, expect, todo, or unimplemented in production code.
  • No new panic, unwrap, expect, todo, or unimplemented in tests.
  • New non-Rust programming files are allowlisted with owner, surface, and reason.
  • New generated, dependency, process-spawn, or network surfaces are allowlisted with owner and reason.
  • Errors are reported with actionable context.
  • Public JSON/schema changes are documented.

Gates

Ticked only where the command actually ran for this candidate.

  • cargo fmt --check
  • cargo check --workspace --all-targets
  • cargo test --workspace
  • cargo clippy --workspace --all-targets -- -D warnings (ran -p xtask --all-targets)
  • cargo doc --workspace --no-deps
  • cargo package -p ripr --list
  • cargo publish -p ripr --dry-run
  • cargo xtask check-static-language
  • cargo xtask check-doc-artifacts
  • cargo xtask check-support-tiers
  • cargo xtask check-no-panic-family
  • cargo xtask check-allow-attributes
  • cargo xtask check-local-context
  • cargo xtask check-file-policy
  • cargo xtask check-covered-by
  • cargo xtask check-executable-files
  • cargo xtask check-workflows
  • cargo xtask check-spec-format
  • cargo xtask check-spec-numbering
  • cargo xtask check-fixture-contracts
  • cargo xtask check-doc-index
  • cargo xtask markdown-links
  • cargo xtask check-command-catalog
  • cargo xtask check-generated
  • cargo xtask check-badge-diff-policy
  • cargo xtask check-generated-clean
  • cargo xtask check-dependencies
  • cargo xtask check-process-policy
  • cargo xtask check-network-policy

Extension changes: none.


🤖 Generated with Claude Code

https://claude.ai/code/session_01PTKGFhuph96fcVyfb8vBxK

`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
@coderabbitai

coderabbitai Bot commented Sep 23, 2026 •

Copy link
Copy Markdown

Important

Review skipped

Bot user detected.

To trigger a single review, invoke the @coderabbitai review command.

⚙️ Run configuration

Configuration used: Organization UI

Review profile: ASSERTIVE

Plan: Advanced

Run ID: 69cce4a7-82f8-473d-ae34-ad781244a75a

You can disable this status message by setting the reviews.review_status to false in the CodeRabbit configuration file.

Use the checkbox below for a quick retry:

  • 🔍 Trigger review

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.

❤️ Share

Comment @coderabbitai help to get the list of available commands.

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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
@claude

claude Bot commented Sep 23, 2026

Copy link
Copy Markdown
Contributor Author

Review answered at 657e3dff3. One finding was correct and is repaired; the rest are answered below with source.

Repaired

"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."

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, missing_anchor_violation(file, link, resolved, fragment, slugs), with a_fragment_with_no_heading_names_the_link_and_the_target: a resolving anchor produces nothing, and a missing one names the source line, the link as written, and the target document. Replacing slugs.contains(fragment) so the violation is never produced fails that test and no other (11 passed, 1 failed).

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 contains_key / get pair would have needed an unreachable "just inserted but absent" arm to hand slugs to the new function, and an untestable branch is not worth the tidiness.

Answered, not changed

read_text_lossy(&resolved) returns Err and aborts the whole check rather than reporting the link.

Deliberate, and consistent with what the check already did: the source-file read three lines up is read_text_lossy(path)? on exactly the same terms. A tracked Markdown file that exists and cannot be read is a repository problem, not a link defect, and reporting it as a link violation would put a wrong cause on the line. Aborting names the unreadable file and stops, which is the fail-closed direction this repository asks for. The disappears-between-exists()-and-read race is real but resolves the same way: the run aborts loudly rather than passing.

Setext headings (=== / --- underlining) are not handled and have no test.

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 --- of YAML frontmatter (.agents/skills/*/SKILL.md:4, .github/ISSUE_TEMPLATE/design-plan.md:7, docs/agent-context/CONTEXT_SYSTEM.md:7, docs/templates/HANDOFF_TEMPLATE.md:13). Those are not headings and atx_heading_title correctly offers no anchor for them.

So this is the same call the PR body already records for HTML <a id="…"> anchors and for headings containing inline links: no subject in the corpus, and implementing it would add a branch with nothing to test it against. Parked is the right disposition. Worth keeping for whoever picks it up: the failure direction is a false failure, so a setext heading appearing later breaks precommit loudly rather than passing silently.

Helper placement between existing helpers.

The three new helpers sit immediately after markdown_links, the only caller. The split the review noticed is pre-existing: next_checkpoints_from_capabilities already sat between markdown_links and markdown_links_in_text on main. This diff does not widen that gap; it puts the new code next to what uses it.

"Confirm three helpers co-located under markdown_links is appropriate scope; they are not reused outside this check."

Confirmed, and that is the intent. They are private to main.rs and have one caller. Hoisting them into a shared module would widen the surface for no consumer, and this repository's own guidance is to use the existing semantic owner rather than fork a parallel one.


cargo fmt --check, cargo clippy -p xtask --all-targets, cargo xtask precommit and cargo xtask markdown-links all pass on 657e3dff3.


Generated by Claude Code

@EffortlessSteven EffortlessSteven left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

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 in missing_anchor_violation with 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 Result SUCCESS; mergeStateStatus CLEAN.

Disposition: REVIEW_READY.

@chatgpt-codex-connector

Copy link
Copy Markdown

You have reached your Codex usage limits for code reviews. You can see your limits in the Codex usage dashboard.
To continue using code reviews, add credits to your account and enable them for code reviews in your settings.

@EffortlessSteven
EffortlessSteven merged commit 67995b2 into main Sep 24, 2026
23 checks passed
@EffortlessSteven
EffortlessSteven deleted the claude/ux-polish-doawhf-anchors branch September 24, 2026 02:59

@github-actions github-actions Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

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-1 from the second # Added, but the third heading # Other doesn't reset it; the third ## Added should be added-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_anchor asserts #anchor and # only. It does not assert the local_markdown_target("#") == None decision survives the surrounding path.is_none() && fragment.is_none() branch when document is 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.

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.

2 participants