Skip to content

feat(engine): entity map on every audit, stored in the project store, embedded in every report format (#2091) - #333

Merged
nc9 merged 12 commits into
mainfrom
feat/entity-map
Sep 13, 2026
Merged

nc9 merged 12 commits into
mainfrom
feat/entity-map

Conversation

@nc9

@nc9 nc9 commented Sep 12, 2026 •

Copy link
Copy Markdown
Contributor

Sections 1 to 4 of the entity-map epic (squirrelscan/repo#2061), as scoped by squirrelscan/repo#2091. The map stops being a side artifact behind a flag and becomes part of the product.

Report-only throughout. No rule reads the map and it never touches the health score. The engine golden baseline is unchanged: 518 pages, 282 rules, score 49, same finding counts.

What changed since the prototype

The flags are gone. --entity-map, --entity-map-dir and --entity-map-format no longer exist, along with all output-directory logic, and the shell completions lost them. The map is built on every squirrel audit and every squirrel analyze.

Storage

Three tables in the project store, keyed by crawl id, at schema v29 with a migration and a place in the base schema so a fresh install and an upgrade agree.

Table Holds
entities one row per collapsed entity, JSON columns for types, properties and conflicts
entity_edges one row per typed reference, with the dangling flag
entity_occurrences entity by page, uncapped, unlike the document's pages[]

Two behaviours worth knowing. A rewrite replaces the crawl's rows rather than merging, because squirrel analyze re-running over an existing crawl is the normal path and a leftover row would be an entity the site no longer declares. And all three tables retire with the crawl, since the map is recomputable from the pages by definition.

The map in every report format

One data source, packages/report/src/entities.ts, so the six formats cannot disagree.

  • console and text: an Entities block with the counts that name a problem, then the three entities the site declares most.
  • markdown and llm: summary, entities table, conflicting properties, dangling references, entities without an @id.
  • json and xml: the whole document under an entities key, so it still validates against the core-contracts schema.
  • html: the interactive viewer, embedded.

Nodes now carry pageLocal, and the summary gained pageLocalCount, nodesWithoutIdCount and conflictCount so a format leads with the findings without walking the node array.

The viewer

It moved to packages/report/src/entities-viewer.ts, the only place both the HTML report and the engine's standalone document can reach: the engine depends on report, never the reverse. One implementation, so the embedded section and the standalone page cannot drift.

It is injected into a page that already has its own global stylesheet and its own table, canvas and select rules, so every id and class is em--prefixed and the CSS is scoped under #em-root.

Wheel zoom and drag pan about the cursor, a Fit button, node radius scaled by occurrences, labels above a zoom threshold, hover highlighting a node's neighbours and dimming the rest, legend chips filtering by type, a detail panel on click, and a sortable, filterable table. Page-local entities (per-page types and unnamed images) are hidden from the graph by default; on kinsta.com that is 139 of 188 entities, and hiding them is the difference between a hairball and a readable graph. The table always lists everything.

No network requests: no CDN, no external stylesheet, nothing loaded at runtime. Verified in headless Chrome against a real report.

Untrusted input

Every name, @id and property value comes from an audited page. Lookups use Map, countsByType is built through Object.fromEntries, markdown cells escape the backslash before the pipe and clip before escaping, and the viewer reaches the DOM only through textContent with the map arriving as \uXXXX-escaped JSON inside an application/json block.

For the cloud side

buildEntityMap, toJsonLd, renderEntityMapHtml, renderEntityMapMarkdown and slimEntityMapForPublish are all reachable from the single subpath @squirrelscan/audit-engine/entity-map, so the private API never imports the engine root.

One thing to land on the cloud side: the API's publish schema has to accept the optional entityMap field. Every publish now carries it, and a strict schema rejects the whole body on an unknown key.

Not in scope

The squirrel entities command, map diffing and extra export formats are squirrelscan/repo#2092. The four schema/entity-* rules are a later slice of the epic.

Verified

Check Result
entity-map tests (builder, html, markdown, publish projection) 38 pass
report format tests, one per format 11 pass
store round trip, rewrite, retirement 5 pass
full report suite 343 pass
migration-sensitive crawler tests 38 pass
engine golden baseline 6 pass, score unchanged
tsgo --noEmit on contracts, report, crawler, rules, engine, cli clean
oxlint and oxfmt on apps/cli clean

@nc9 nc9 changed the title feat(engine+cli): entity map prototype behind --entity-map (#2061) feat(engine): entity map on every audit, stored in the project store, embedded in every report format (#2091) Sep 13, 2026
nc9 added 12 commits September 13, 2026 11:18
Prototype of the site-wide entity graph: every JSON-LD entity a crawl saw,
collapsed across pages, plus the typed references between them.

- core-contracts gains a zod schema + inferred type for the
  `squirrelscan/entity-map` v1 document (summary, nodes, edges, pages).
- buildEntityMap reads top-level, @graph and nested JSON-LD, resolves @id
  references across pages, collapses an entity with no @id by type + name /
  url / sameAs, records per-property conflicts, and flags an @id reference
  no page declares as a dangling edge.
- Output is deterministic: pages are walked in URL order and every list is
  sorted, so two runs over an unchanged site differ only in generatedAt.
- toJsonLd re-emits the collapsed graph as JSON-LD; renderEntityMapHtml
  writes one offline, self-contained page with a force-directed graph and a
  sortable, filterable table.

Nothing reads the map yet: no new rules, no scoring, no report changes.

Signed-off-by: Nik Cubrilovic <[email protected]>
…2061)

`squirrel audit --entity-map` writes entity-map.json, entity-map.jsonld and
entity-map.html and prints the three paths on stderr. --entity-map-dir picks
the directory; it defaults to the directory of --output, else the cwd.

Off by default and collected in the streamed pre-rules walk alongside the
tech-detect sample, so a normal audit allocates nothing for it. A write
failure is logged, never fatal: the audit already succeeded.

Signed-off-by: Nik Cubrilovic <[email protected]>
…vigable graph (#2061)

Everything the cloud side needs now reaches it through the single
`@squirrelscan/audit-engine/entity-map` subpath, so the private API never has
to import the engine root.

- renderEntityMapMarkdown: the view an agent reads. Summary and type counts,
  the largest entities, then the three findings sections (conflicting
  properties, dangling references, entities declared on several pages with no
  `@id`). Cells are pipe- and newline-escaped, since the names come from
  audited pages.
- slimEntityMapForPublish + ENTITY_MAP_PUBLISH_LIMITS: bound the map for the
  publish body. Nodes kept by occurrence count, edges follow their source, a
  dangling edge is kept regardless (the missing target IS the finding), pages[]
  dropped. summary keeps the true counts so a reader can see it was clipped.
- AuditReport gains an optional `entityMap`, REPORT-ONLY and non-scoring, set
  only when --entity-map ran. NOTE: the API publish schema must accept the field
  before a --entity-map run can publish.
- HTML viewer: wheel zoom and drag pan about the cursor, a Fit button, node
  radius scaled by occurrences, labels above a zoom threshold, hover highlights
  a node's neighbours and dims the rest, legend chips toggle a type, and a
  'hide page-local entities' checkbox (off by default) that drops per-page types
  and unnamed images from the graph only. The table always lists everything.
  Still one self-contained file with no network requests.

Signed-off-by: Nik Cubrilovic <[email protected]>
…2061)

json, jsonld, html, md; comma-separated or repeated; all four by default. An
unknown value is refused by name rather than silently writing nothing, and both
--entity-map-dir and --entity-map-format require --entity-map.

A --entity-map run also attaches the (capped) map to the report, so a published
run hands the cloud the same graph the local files hold. Off by default, so an
ordinary audit's report and publish body are unchanged.

Completions updated for bash, zsh and fish.

Signed-off-by: Nik Cubrilovic <[email protected]>
Both inputs are site-controlled entity names, so both were reachable.

- js/incomplete-sanitization: the markdown cell escaped `|` without escaping
  backslashes first, so a name containing a literal `\|` became `\\|` —
  an escaped backslash followed by a LIVE pipe, and the table row gained a
  column. Escape backslashes first, and clip BEFORE escaping so a clip can
  never cut an escape pair in half and leave a trailing backslash.
- js/polynomial-redos: `slugify` trimmed dashes with `/^-+|-+$/`, which
  backtracks polynomially. The preceding pass already collapses every run of
  non-alphanumerics to one dash, so two anchored single-character trims do the
  same job in linear time. Clipping before the trims also drops a dash the clip
  introduced.

Tests pin both: a `\|` name keeps its column count, a name that clips
mid-escape still ends on a bare separator, a punctuation-only name still yields
a usable generated `@id`, and a 200k-separator name slugifies instantly.

Signed-off-by: Nik Cubrilovic <[email protected]>
… embedded in every report format (#2091)

The map stops being a side artifact behind a flag and becomes part of the
product: built on every audit and every analyze, persisted, and rendered by all
six report formats. Report-only throughout — no rule reads it and the health
score is unchanged (golden baseline: 518 pages, 282 rules, score 49, identical).

- No flags. `--entity-map`, `--entity-map-dir` and `--entity-map-format` are
  gone, along with the output-directory logic; completions updated.
- Store: `entities`, `entity_edges` and `entity_occurrences` in the project
  store, keyed by crawl id, schema v29 with a migration and a place in the base
  schema. A rewrite REPLACES the crawl's rows so re-analyzing cannot leave a
  previous run's entities behind, and the tables retire with the crawl.
  `entity_occurrences` is uncapped, unlike the document's `pages[]`.
- Nodes carry `pageLocal`, and the summary gains `pageLocalCount`,
  `nodesWithoutIdCount` and `conflictCount` so a format can lead with the
  findings without walking the node array.
- Reports: console and text get an Entities block, markdown and llm get the
  summary plus entities, conflicts, dangling and no-id lists, json and xml carry
  the document under `entities`, and html embeds the interactive viewer.
- The viewer moved to `packages/report/src/entities-viewer.ts`, the only place
  both the HTML report and the engine's standalone document can reach (the
  engine depends on report, never the reverse). Ids and classes are `em-`
  prefixed and the CSS is scoped under `#em-root`, since it is injected into a
  page with its own `table`, `canvas` and `select` rules. Wheel zoom, drag pan,
  fit, size by occurrences, labels above a zoom threshold, neighbour highlight,
  legend filtering, page-local entities hidden by default. Still inline, with no
  network requests.

Kept: the zod schema, the JSON-LD export, the `@squirrelscan/audit-engine/entity-map`
subpath, the optional `entityMap` on the publish payload, and the markdown
renderer (now one implementation shared with the report format).

Signed-off-by: Nik Cubrilovic <[email protected]>
No new secret. The Entities section added 39 lines above the existing
html.tsx entry, so its recorded line_number went stale and
`detect-secrets-hook` rewrites the baseline and exits nonzero until the
rewrite is committed. Only that number and the generated_at stamp changed.

Signed-off-by: Nik Cubrilovic <[email protected]>
…2091)

The barrel re-exported the streaming collector, whose `SiteContextPage` type
import pulls `../adapter` — and behind it crawler, rules and threat-intel —
into the type graph of everything importing
`@squirrelscan/audit-engine/entity-map`. That subpath is the ONE import the
private API is allowed, and it compiles with a different lib/types set, so the
API's typecheck reported five errors in packages neither side had touched
(missing `Bun`, a different DOM lib, an unresolvable `.yml` module).

Runtime was always fine — collect.ts has only type imports — so this is purely
about what the barrel drags along. The collector moves to its own subpath,
`@squirrelscan/audit-engine/entity-map/collect`, which the two CLI controllers
now use. The barrel is left reaching nothing outside `src/entity-map/`, and
every cross-package specifier it still touches is a leaf that only reaches
core-contracts.

Reported and root-caused by the #2094 lane.

Signed-off-by: Nik Cubrilovic <[email protected]>
#2091)

At fit scale a plain zoom threshold is all-or-nothing: every visible node drew
its label at once and the dense centre was unreadable. The budget is now a
COUNT — the N entities with the most occurrences get a label — and N grows with
the square of the zoom, because zooming in grows both dimensions of the readable
area. 12 at fit, 27 at 1.5x, 48 at 2x.

Three things that decide whether it actually reads well:

- The budget is anchored to the FIT scale, not to scale 1. Fit is well above 1
  for a small graph and below it for a large one, so measuring against 1 gave 30
  labels on kinsta and would have given far too few on a big site. Anchored, it
  is exactly 12 on first paint for every site.
- Rank is computed among the nodes actually DRAWN, so hiding the page-local
  entities promotes the site's real subjects into the budget instead of leaving
  them queued behind hidden furniture.
- A repeated label yields its turn. An unnamed node labels as its bare @type, so
  squirrelscan.com spent nine of its twelve labels drawing the word "Offer";
  reach still decides the order, duplicates just sort behind every distinct
  label. The twelve are now twelve different things.

The hovered node, everything it references, and the selection are labelled at
any zoom. An earned label is dropped while its node is dimmed, since a bright
label on a faded dot reads as noise.

Also pins the page-local default in a test: the toggle SHOWS them and ships
unchecked, so the opening view is the site's subject matter rather than one
WebPage per page crawled (130 of 363 on squirrelscan.com, 49 of 188 on kinsta).

Signed-off-by: Nik Cubrilovic <[email protected]>
…dependency (#2091)

core-contracts is a TypeBox package and must stay one. A zod schema here could
not be composed by either consumer: the private API is on zod 3 and the CLI and
rules are on zod 4, which install as two separate copies, so the shared schema
was shared in name only and the API had to carry the field as `unknown` and
validate out of band.

`EntityMapSchema` and its parts are now `Type.Object(...)` with the types via
`Static<typeof ...>`; validate with `Value.Check` from
`@sinclair/typebox/value`. zod is gone from the package and the lockfile.

Also records why ENTITY_MAP_VERSION stays 1 and when it must stop: additive
required fields are free while nothing is persisted, but once the cloud writes
published maps to R2 (#2099) they are v1 documents in the wild with no
migration, and the API re-validates stored bytes on every read — so an
invalidating change after that must bump, or every older report's entity
endpoints 404.

Signed-off-by: Nik Cubrilovic <[email protected]>
Each with a test.

- HIGH, memory: the collector held every page's raw JSON-LD until the crawl
  ended — ~100MB on a 10,000-page site, with the page ceiling as the only
  bound. The builder is incremental now: each page is folded into the
  accumulators as it streams and its markup is dropped. Buffering was also what
  bought determinism (the old builder SORTED pages before walking), so each
  canonical value carries the (page, index) it came from and the MINIMUM wins.
  Arrival order cannot change a byte of the output, which the tests pin.
- HIGH, redos: the trailing-slash trim was `/\/+$/` over a site-controlled
  path. Replaced with a backward scan.
- MEDIUM, payload: node and edge caps do not bound BYTES, because every value in
  the document is a site-controlled string. The publish projection now clamps
  each string, samples conflict values and page lists, and drops
  lowest-occurrence nodes until the serialized map is under a byte budget.
- MEDIUM, correctness: JSON-LD blank nodes (`_:b0`) resolved as ordinary
  relative URLs, which merged every page's first blank node into one entity and
  counted it as a stable `@id`. They are document-scoped now: keyed per page,
  never a stable id, and a reference to one resolves only within its own page.
- MEDIUM, identity: the synthetic key used `types[0]`, so
  `["Organization","LocalBusiness"]` and the reverse split into two nodes.
  schema.org puts no meaning on `@type` order — the key is the sorted set.
- MEDIUM, data loss: the publish slimming mutated `report.entityMap`, so the
  LOCAL `-f json` report was truncated to 750 nodes and lost `pages`. The
  report keeps the full document (it is the canonical export) and publish slims
  its own copy.
- MEDIUM, honesty: a clipped map made markdown say "no entity disagrees with
  itself" while its own summary reported conflicts. The headings and clean-state
  sentences come from the summary totals, and a clipped section says how many
  are not included.

The collector also stops importing `SiteContextPage` from `../adapter` and
declares the shape it needs structurally, so nothing downstream inherits the
crawler/rules/threat-intel type graph.

Signed-off-by: Nik Cubrilovic <[email protected]>
…able (#2091)

The section is informational and unscored, so it sat in the wrong place: between
the score cards and the first issue, pushing the things a reader opened the
report for off the screen. It now renders after the findings in html, text,
markdown, llm and xml, with the xml element still inside the root and the llm
block still inside <audit>.

The embedded table printed all 188 rows. It shows the top 25 by occurrences with
a "Show all N" toggle, and it filters with the graph rather than independently:
page-local entities (per-page types and unnamed images) are hidden from both, so
kinsta.com opens on the 49 entities that matter instead of 139 unnamed images.
The standalone squirrel entities command is the full table (#2092).

json keeps the complete document under `entities`, pages included — it is the
canonical export — and only the publish copy is capped.

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9
nc9 merged commit 174f0cf into main Sep 13, 2026
14 checks passed
@nc9
nc9 deleted the feat/entity-map branch September 13, 2026 01:27
nc9 added a commit that referenced this pull request Sep 13, 2026
) (#343)

* feat(mcp): occurrence_threshold on compare_entities (#2095)

The engine's diffEntityMaps has always taken it and the epic specifies
occurrenceDeltas as "above a configurable threshold", but neither server
exposed it, so the cloud lane had added it as a server-specific input. Shared
now, with the default in ENTITY_MCP_LIMITS so neither side hardcodes 1.

It filters occurrenceDeltas only. An entity added, removed, or changing its @id
is a structural change and survives any setting.

Also, from the cloud lane: the shared get_entity_graph description implied all
six formats exist on every server. Theirs implements three and refuses the rest,
so the description now says a refusal is a refusal and not a site with nothing
to draw.

Claude-Session: https://claude.ai/code/session_01T8w822GqnrviVMytnAsKFP
Signed-off-by: Nik Cubrilovic <[email protected]>

* test(mcp): use the regenerated docs snapshot and drop the page reconstruction

The committed "after" snapshot carried `pages: []` beside `pagesTotal: 60`,
exported before the publish projection stopped clipping the report's own copy,
so the test rebuilt the page index by inverting the nodes' page lists. That was
lossy for the three nodes whose lists are capped at 50 with a morePages
remainder, and it was a liberty the CLI never takes.

Regenerated with the post-#333 CLI: 183 nodes and its own complete 60-page
index. The reconstruction is gone.

The "before" snapshot stays pre-v1 on purpose — it exercises the lenient read
path on an artefact that actually shipped.

Claude-Session: https://claude.ai/code/session_01T8w822GqnrviVMytnAsKFP
Signed-off-by: Nik Cubrilovic <[email protected]>

---------

Signed-off-by: Nik Cubrilovic <[email protected]>
@nc9 nc9 mentioned this pull request Sep 16, 2026
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