Skip to content

feat(rules): add links/broken-anchors for in-page anchor links - #718

Merged
nc9 merged 1 commit into
mainfrom
claude/706-broken-anchors
Oct 12, 2026
Merged

nc9 merged 1 commit into
mainfrom
claude/706-broken-anchors

Conversation

@nc9

@nc9 nc9 commented Oct 12, 2026 •

Copy link
Copy Markdown
Contributor

Summary

Adds the links/broken-anchors rule. A link to #pricing, or to /page#pricing, whose target id no longer exists still loads, and the reader lands at the top of the page. The rule warns when a fragment names no id or <a name> on its target page.

  • Same page: a #frag link is judged against the page's own ids.
  • Another crawled page: a /page#frag link is judged against that page's ids. A target that was not fetched, or answered 4xx/5xx, is left to links/broken-links.
  • One finding per target URL and fragment, listing every page that links to it.
  • Unconfirmed (info): a target that was fetched without rendering and looks like an empty client-side shell. Its ids may be added by JavaScript.
  • Skip links: a broken skip link is labelled (skip link). a11y/skip-link keeps its verdict. Its selector is now exported and shared, with no change to its logic.
  • Not reported: # and #top, purely numeric fragments (#0, #1, template do-nothing links), hash routes and state (#/x, #!x, #k=v), text fragments (#:~:), links to uncrawled or error pages, and targets over the id cap.
  • Cached snapshots: a streaming snapshot cached before the anchor record existed (no page carries it) is reported as skipped with a --refresh hint, never as a pass with zero links judged.

Streaming parity. The streaming engine drops each page's DOM after the page pass, so the ids cannot be read later. Each page's distinct ids, <a name> values, same-page fragments and skip-link fragments are collected page-time into a capped record (collected-signals.ts, links/page-anchors.ts). The v1 engine builds the same record from the DOM through the same extractor. The rendered flag rides on the site-page entries so both engines make the same unconfirmed call. The per-page record is capped at 512 ids and 256 same-page fragments, so memory stays bounded on large crawls.

Changes from the maintainer review (2026-10-12):

  • Rebased onto main after feat(rules): add reliability/broken-resources and the Reliability category #703 #714 (0c733ec). Golden gate: streaming-rules-canonical-golden.test.ts 101737 -> 101738 findings and 302 -> 303 tally rows, with comments; the rule's tally row is pinned (one pass on the synthetic site). healthScore.overall stays 51.
  • Docs quote the message templates ({count} in-page anchor link(s) ...), and list the numeric-fragment exclusion and the cached-snapshot skip.
  • A finding's linking pages are a Set (was Array.includes per link: O(sources^2) for a site-wide nav link).
  • The skip-link text heuristic is exported from a11y/skip-link (hasSkipLinkText) and shared, beside SKIP_LINK_SELECTOR.
  • Comment on the same-page redirect mapping (finalKey to sourceKey).
  • CHANGELOG line under [Unreleased] / ### Added.
  • No network requests: the rule reads only what the crawl fetched, so no egress or credential surface.

Agent skill: yes, the squirrelscan agent skill (squirrelscan/skills) should learn the new rule; the maintainer files that as a private issue. Per-category counts (Links 15 -> 16) are left for the maintainer's batched docs PR.

Closes #706

Verification

bun install --frozen-lockfile
(cd packages/rules && bun test tests/broken-anchors.test.ts tests/skip-link.test.ts)           # 35 pass, 0 fail
(cd packages/audit-engine && bun test tests/broken-anchors-streaming-golden.test.ts)         # 1 pass
(cd packages/audit-engine && bun test tests/streaming-rules-canonical-golden.test.ts)        # 1 pass
(cd packages/audit-engine && bun test tests/streaming-rules-golden.test.ts tests/streaming-pre-rules-golden.test.ts)  # 11 pass
(cd packages/rules && bun run typecheck)          # clean
(cd packages/audit-engine && bun run typecheck)   # clean
bun run scripts/test-suites.ts --check            # every test file covered
(cd docs && bun run check)                        # tangly check --strict: all checks passed

The new rule, extractor and test files are oxfmt-clean and oxlint-clean (the rules package has no format or lint script of its own).

Notes for review:

  • The synthetic site renders no #x same-page links or id attributes, so the same-page DOM path is covered by the rule-level parity test in broken-anchors.test.ts, not by the seeded crawl.
  • The unrendered-shell case is covered by a rendered flag on the fixture, not by a browser-rendered audit.

Acceptance checklist (#706)

  • Fixture: a page with <a href="#pricing"> and no element with id="pricing" produces a warning naming the link, the fragment and the page
  • Fixture: the same page with <section id="pricing">, or with <a name="pricing">, produces no finding
  • Fixture: page A links to /b#install, page B is crawled and has no id="install": one warning naming /b#install and listing page A as a source
  • Fixture: five pages share a nav link to /#pricing and the homepage has no id="pricing": one finding listing the five source pages, not five findings
  • href="#", #top (with no id="top" on the page), #/settings, #!/home, #access_token=abc and #:~:text=hello produce no finding
  • A link to /c#x where /c was not crawled, or answered 404, produces no finding from this rule
  • An id with non-ASCII or percent-encoded characters matches its decoded link (#caf%C3%A9 finds id="café"), and #Pricing does not match id="pricing"
  • Fixture: in an unrendered audit, a link to /app#settings where /app is an empty client-rendered shell (<div id="root"></div> plus a script) is reported as unconfirmed (info), not as a warning
  • A skip link to a missing #main-content is reported once, by this rule, and labelled as a skip link; the a11y/skip-link verdict for that page is unchanged
  • The cross-page check gives the same result in a streaming audit as in a non-streaming one
  • The rule has a docs page under docs/rules/links/

Checklist

  • I added or updated tests for behavioral changes.
  • I did not include secrets, customer data, or incompatible third-party material.
  • Every commit includes a DCO Signed-off-by line (git commit -s).

@claude

claude Bot commented Oct 12, 2026

Copy link
Copy Markdown

Review of links/broken-anchors. I read the diff and checked that isRenderedFetch exists in adapter.ts. I did not run the tests.

(low) packages/rules/src/links/page-anchors.ts: the [id] and a[name] scans and the a[href] scan each walk the whole DOM on every page, in addition to the other page-time extractors. The cost is bounded by the time budget in timed(...). If the budget is hit, anchors becomes null and the page goes unjudged, which fails safe. A single combined pass would be cheaper on large pages.

(low) broken-anchors.ts: when collectedSignals is present, a page with no record (cached before the field existed) is silently skipped. This is documented as unjudged, but the pass check still reports "No broken in-page anchor links detected" with anchorLinks: judged. Consider a skipped or info note when the judged count is 0 but anchor links were seen.

(nit) broken-anchors.ts: for same-page links the target is the source page, so a redirect (finalKey) is mapped to sourceKey. That is correct, but a short comment would help.

(nit) page-anchors.ts: the skip-link text heuristic (skip, jump to content, go to main) duplicates logic in a11y/skip-link beyond the shared selector. Consider exporting that too, to avoid drift.

(nit) Test coverage: the golden test is good for engine parity. I could not confirm unit coverage for percent-encoded fragments, the #top and hash-route exclusions, and the idsTruncated path. I saw only the start of tests/broken-anchors.test.ts, so I'm not sure they are covered.

I found no critical or high issues. The logic looks correct and conservative: it skips 4xx/5xx and unfetched targets, handles truncation, and treats unrendered client shells as unconfirmed. The docs and registration look consistent.

@nc9

nc9 commented Oct 12, 2026

Copy link
Copy Markdown
Contributor Author

Maintainer review (2026-10-12)

Verdict: needs fixes (low). I reviewed head 6c7950b against main 2dca3b9. Main CI is green at that sha, so the red checks here come from this PR.

Acceptance criteria (#706)

All 11 are met. packages/rules/tests/broken-anchors.test.ts covers them, and packages/audit-engine/tests/broken-anchors-streaming-golden.test.ts checks streaming parity.

Fixes

  1. Golden gate. This one test fails "Audit engine golden tests" and the "Audit engine tests" step of "CLI tests". The apps/cli tests step itself passes.
    • File: packages/audit-engine/tests/streaming-rules-canonical-golden.test.ts.
    • expect(v1.findings.length).toBe(101736); (line 154): CI received 101737. links/broken-anchors is site-scoped and adds one whole-crawl check. Raise the number by 1 and add a comment line in the existing style, for example // 101736 -> 101737: links/broken-anchors is site-scoped and adds one whole-crawl check (#706). <its status on the fixture>.
    • expect(v1.perRuleTally.length).toBe(301); (line 176) fails next. Raise it by 1 and extend the tripwire comment.
    • The numbers are relative to the main you rebase on. Other rule PRs edit the same two lines, so rebase and read them again after each merge.
    • Verify with cd packages/audit-engine && bun test tests/streaming-rules-canonical-golden.test.ts. healthScore.overall must stay 51, or the comment must explain why it changed.
  2. Docs templates. docs/rules/links/broken-anchors.mdx quotes filled examples: 2 in-page anchor link(s) point at ... and 1 in-page anchor link(s) target .... Write {count} in both.
  3. Performance. group.sources.includes(...) is O(sources²) for a site-wide nav link. A 5k-page site with 10 nav anchors means about 250M compares inside the site-rule budget. Use a Set per group.
  4. Cached snapshots. When collectedSignals is present but no page has an anchors record, the rule still passes with anchorLinks: 0. That happens with a snapshot cached before this field existed. Report it as not checked or info, not as a pass.
  5. False positives to watch (optional). Template sites often use href="#0" and JS-hook fragments (#menu, #close) with no matching id, and those will warn. Consider skipping purely numeric fragments.
  6. Open nits from the review bot. The skip-link text heuristic (skip, jump to content, go to main) duplicates logic in a11y/skip-link outside the shared selector, so export it too. A short comment on the same-page redirect mapping (finalKey to sourceKey) would help.

PR hygiene

  • CHANGELOG: add one line under ## [Unreleased] / ### Added, ending with squirrelscan/squirrelscan#706.
  • PR description: add a line saying whether the squirrelscan agent skill (squirrelscan/skills) needs a change.
  • Attribution:
    • Remove the Co-Authored-By: and Claude-Session: trailers from the commit, and keep Signed-off-by:.
    • Remove the "Generated with Claude Code" footers and the session URL from the PR body.
    • No attribution lines of any kind in commit or PR text.
  • Docs: quote message templates with placeholders, never filled examples. No em-dashes.
  • Rule counts: leave the per-category counts in the README and docs tables alone (Links 15 to 16). The maintainer updates them in one docs PR after these rule PRs merge.

Merge order

This PR merges second, after #714. #720 conflicts with it in packages/rules/src/collected-signals.ts and will rebase on it.

@github-actions

Copy link
Copy Markdown
Contributor

Auto-review did not complete

The claude-review job failed before posting a review. This PR has not been auto-reviewed. Run a review manually (/review) before merging.

  • Result: success / is_error=true after 1 turns, 0 permission denial(s), $0.00
  • Job log

Partial findings recovered from the session (incomplete, unverified, and NOT a merge signal):

Show partial review

You've hit your session limit · resets 10:10pm (UTC)

A link to #pricing, or to /page#pricing, whose target id is gone still loads,
and the reader lands at the top of the page. links/broken-anchors warns when a
fragment names no id or <a name> on its target page, reports an unrendered
client-side shell as unconfirmed (info), and labels broken skip links.

The cross-page check needs each crawled page's ids. The streaming engine drops
each DOM after the page pass, so the ids are collected page-time into a capped
per-page record (collected-signals.ts). The v1 engine builds the same record from
the DOM through the same extractor (links/page-anchors.ts), so both engines judge
identical records. SiteData pages carry `rendered` so the v1 path can tell an
unrendered shell from a rendered one.

- Each finding's linking pages are a Set, so a nav link repeated across a large
  site costs one insert per link, not a scan of every page so far.
- A streaming snapshot cached before the anchor record existed (no page has the
  field) is skipped with a --refresh hint instead of passing with zero links.
- Purely numeric fragments (#0, #1) are template do-nothing links and are not
  judged.
- The skip-link text heuristic is shared with a11y/skip-link
  (hasSkipLinkText), beside the shared SKIP_LINK_SELECTOR.

No network requests: the rule reads only what the crawl already fetched.

Golden gate: 101737 -> 101738 findings and 302 -> 303 tally rows on main
with #703 (one whole-crawl check, a pass on the synthetic site);
healthScore.overall stays 51.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 force-pushed the claude/706-broken-anchors branch from 7b897c1 to 6408959 Compare October 12, 2026 22:45
@claude

claude Bot commented Oct 12, 2026

Copy link
Copy Markdown

Review of links/broken-anchors. The design is sound. Both engines read one shared record, and the caps, the cached-snapshot skip and the unconfirmed-shell handling are all deliberate. I found nothing that should block the merge. I read the diff but did not run the test suite.

  • (low) packages/rules/src/links/page-anchors.ts (decodeFragment): browsers try the raw fragment against ids first, and percent-decode only if that finds nothing. An id that contains a literal % (e.g. id="50%25") linked as #50%25 would be decoded to 50% and reported broken. This is rare. Matching either the raw or the decoded form would mirror the spec exactly and avoid a false positive.
  • (low) packages/rules/src/links/page-anchors.ts (buildPageAnchorSignal): the client-shell check reads body.textContent and runs querySelectorAll("script, style, noscript, template") for every page in the page-time collector. That is extra per-page work in the streaming path, on large pages and when no rule needs it. It sits inside timed(...) so it is bounded, but the check can be skipped when rendered is true (it already is) or when the page has no # links targeting it. Low priority.
  • (low) packages/rules/src/links/broken-anchors.ts (SELF_FRAGMENTS_CAP = 256): a page with more than 256 distinct same-page fragments silently leaves the extras unjudged. The docs list the id cap but not this one. Consider adding it to the "What squirrel does not report" list, or flagging a partial result the way broken-resources does.
  • (low) Test coverage: no test covers the redirect case, where a page is stored under the requested URL and a link to its finalUrl#frag is treated as same-page. No test covers the selfFragments cap or an idsTruncated same-page target. These are new branches in broken-anchors.ts.
  • (nit) packages/rules/src/links/broken-anchors.ts: group.unconfirmed is set from the first link to a group. This is fine because it depends only on the target record, but a short comment would make that obvious.
  • (nit) packages/rules/src/a11y/skip-link.ts: the refactor to export SKIP_LINK_SELECTOR and hasSkipLinkText keeps the logic identical, and the test asserting the unchanged skip-link verdict is a good guard.

Security: no concerns. The rule does no network I/O and only reads already-parsed DOM, and the per-page record is capped, so memory stays bounded.

@nc9
nc9 merged commit 5952a2c into main Oct 12, 2026
15 checks passed
@nc9
nc9 deleted the claude/706-broken-anchors branch October 12, 2026 23:39
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.

New rule: links to in-page anchors that do not exist

1 participant