Subject Index Deep Links: Design
Intent
Every citation in the Subject Index (editorial/pages/index/page.md) links
to the top of an article. A reader looking up “Tcheka” lands at the
masthead of a long piece and has to hunt. Citations should land on the
paragraph, sidenote or margin box where the subject appears, the way a
printed index gives a page number. Cross-references (“see: Tcheka”, “see
also: Goldman, Emma”) should be links to the entry they name, within the
index page.
Paragraph links are also useful in their own right: readers get the same
purple # permalink on paragraphs that sidenotes and figures have now.
Goals
- Citation links in the index carry a fragment:
/5921/2/13/kropotkins-funeral/#p-k3f9q. - Paragraph ids survive small edits: fixing a typo or rewording a sentence leaves the id alone.
- Paragraphs show the delayed purple
#permalink on hover (and on long-press on touch), like.sidenote,.margin-boxandfigure. - Top-level index entries have ids; “see:” and “see also:” targets are links to them.
- The indexer LLM never invents anchors. It names a quote; code finds the anchor.
- Stale or broken index anchors are caught by a check, not by readers.
Non-goals
- No visible locator in the citation text (no “¶4”, no “n. umbin”). The citation reads as it does today; only the link target changes.
- No visible
#on index entries. They get ids only. - No paragraph ids on pages other than articles (the index page itself,
/about/, etc.) for now. - No change to how sidenotes or figures get their ids.
Anti-goals
- An index link that silently lands on the wrong paragraph. A link that falls back to the top of the article is acceptable; a wrong target is not. (This is why paragraph ids are not ordinal numbers.)
- Plaintext article prose leaking into the public repo through the new
sidecar file. Articles may be md-age encrypted (
.gitattributesruns every*.mdthrough themd-agefilter); the sidecar is YAML and is not encrypted. - Anchors that only work with JavaScript. Ids are in the static HTML.
make buildwriting intoeditorial/. Build stays a pure function of the repo.
Approaches considered
- Fingerprint of the paragraph’s opening words. Stable when other paragraphs change, but any edit to the opening changes the id. Rejected alone: Danny wants a paragraph changed by a few words to keep its id.
- Ordinal ids (
#p12). Inserting a paragraph shifts every later id and index links point at the wrong paragraph with no error. Rejected (see anti-goals). - Hand-written ids in the markdown (
{: #coffin}). Never break, but need every article’s source edited. Rejected as the main mechanism; kept as an override (an id already present on an element is never replaced). - Simhash ids, no stored state. Similar paragraphs get similar ids; a build step rewrites the index to the nearest id, and JS repairs stale outside links. Rejected: the id still changes on small edits, outside permalinks need JS, and the index churns in git on every article edit.
- Remembered ids in a committed sidecar per article (chosen). Sync
matches each paragraph to the remembered ones by similarity; a mostly
unchanged paragraph keeps its id. Drift through many small edits is
tolerated because each sync compares against the last. Cost: one more
generated file per article, written by
make sync.
Design
1. Anchorable blocks
In the rendered body of an article, these elements get ids:
<p>elements in the article body, including those inside<blockquote>,<li>and.versesections.- Inline
<aside class="margin-box">elements written in the article markdown get anmb:-prefixed id, replacing the unstablemb:<counter>thatsidenotes.jsassigns at runtime. Paragraphs inside a margin box do not get their own ids; the box is the unit.
Not anchored: footnotes (they already have fn:<name>, which survives the
move into the margin), headings (toc already gives them ids), image-only
paragraphs and section-break ornaments, and any element that already has
an id (author overrides via attr_list, e.g. {: #coffin}).
2. Normalised text
Matching and fresh ids both work from a normalised word list, built from the rendered element’s text:
- link text kept, URLs dropped (falls out of using
.get_text()); - footnote reference markers (
†,<sup>) dropped; - images, scripts, and other non-text elements dropped;
- smart quotes, dashes and ellipses folded to ASCII; Unicode NFKC; case folded;
- punctuation stripped; split on whitespace.
3. Fresh ids
A paragraph with no remembered match gets p- plus the first 5
characters of a base32 SHA-256 of its normalised word list joined by
spaces (lowercase, e.g. p-k3f9q). On collision within an article,
append -2, -3 in document order. Margin boxes use mb: with the same
hash.
4. The sidecar: editorial/articles/<slug>/_anchors.yaml
One entry per anchored element, in document order:
# Generated by make sync. Remembers paragraph ids across edits.
version: 1
anchors:
- id: p-k3f9q
shingles: [a91f03c2, 0b77e4d1, ...] # hashed word 3-grams
- id: mb:7cq2m
shingles: [...]
shingles is the set of word 3-grams of the normalised text (single
words for elements under three words), each hashed to 32 bits with a
keyed hash and written as hex. No plaintext is stored. The key is a fixed
constant in the code: the hash is there to keep prose out of a public
file, not to resist a determined attacker.
5. Matching (at sync)
When make sync processes an article whose content hash changed:
- Render the markdown and collect the anchorable elements and their shingle sets.
- Load the existing
_anchors.yaml, if any. - Score every (new element, remembered anchor) pair by Jaccard similarity of shingle sets. Assign greedily, highest score first, one-to-one, with a threshold of 0.5. A matched element keeps its remembered id. (This handles a split paragraph naturally: the larger half scores higher and keeps the id.)
- Unmatched elements get fresh ids (§3), avoiding ids already in use.
- Write the new
_anchors.yaml. Remembered anchors that matched nothing are dropped.
The threshold and the shingle size are tunables; the builder should check them against real edits in git history (see “Left to the builder”).
6. Rendering (at build)
render_markdown gains the anchoring step as a post-processing pass,
alongside _wrap_verse_lines. For article pages, the view loads the
article’s _anchors.yaml and applies its ids in order to elements that
match (same matching as §5, against the sidecar). If the sidecar is
missing or an element is unmatched, the element gets its fresh id. Build
never writes the sidecar.
The matching code lives in one pure module (no Django imports), e.g.
src/almnck/core/anchors.py, used by sync, the renderer, and
bin/update-index.
7. Paragraph permalinks
sidenotes.js setupPermalinkAffordance and
setupTouchPermalinkAffordance add body paragraphs with ids to their
selector. Arrival via #p-… uses the existing handleFragment
scroll-and-highlight, which already works for any id.
8. Index entry ids and cross-reference links
At render time for the index page (not in the markdown source, which the LLM writes and Danny reads):
- Each top-level entry
<li>under.idxgetsid="idx-<slug>", where the slug comes from the entry’s heading: the entry text before the first citation or cross-reference. For “Goldman, Emma, anarchist…”, the heading is matched as the longest prefix that names an entry (see below), so commas inside names don’t split it wrongly. - Text after
see:orsee also:is split on;. Each target is normalised (§2 rules) and matched to the entry whose normalised heading it is, or starts with. The target text becomes<a href="#idx-…">. - Unresolved targets stay plain text and are reported by the check (§10).
- If the index search filter is hiding the target entry, clicking a
cross-reference clears the filter before scrolling.
(
assets/js/index-search.js.) :targetstyling on index entries gives the same brief highlight as.fragment-highlighted.
9. Indexer: the locate tool
bin/update-index gives the model one tool (llm ≥ 0.28 tool support,
via model.chain(..., tools=[locate])):
def locate(slug: str, quote: str) -> str:
"""Return the URL of the paragraph, sidenote or margin box in article
`slug` containing `quote` (a short verbatim phrase). Returns an error
listing near misses if the quote isn't found."""
It normalises quote and the article’s anchorable elements and footnotes
by the §2 rules, finds the element containing the quote, and returns
/vol/m/d/slug/#p-k3f9q (or #fn:name, #mb:…). If nothing contains
it, it returns an error naming the closest elements, and the model tries
again. indexer.md is updated: every citation link must come from
locate, with the article URL alone only for a whole-article subject.
Builder’s call: cmd_index replaces whole letter sections with the
model’s output, so the model could drop fragments on other articles’
citations. After the merge, code re-applies known fragments, matched by
article URL plus entry text. Citations of the article being re-indexed
are located fresh through locate.
Builder’s call: inline margin boxes that already carry a data-slug
keep mb:<slug>. update-index and locate decrypt md-age articles the
same way sync does (MD_AGE_IDENTITY).
Sidecar ids must be current when the indexer runs, so update-index
runs the same matching as sync (§5) before locating, or refuses with a
“run make sync first” message if the sidecar is stale.
10. Re-anchoring and checks
update-index --reanchor [slug ...](no slugs: all). For each article, collect the index entries citing it, give the model the entry text and thelocatetool, and patch the returned fragments into the existing links. Entry wording and structure are left alone. This is both the one-off migration for the existing 376 citations and the repair tool for stale anchors.- A unit test (and an
ed-doctorline) checks that every fragment in the index exists in the current anchors of its article, and that every cross-reference target resolves. Failures name the entry and suggestupdate-index --reanchor <slug>.
11. Keeping the sidecars committed (decided)
make sync runs inside prod-deploy and a-verify, so an article edited
and deployed without committing its regenerated _anchors.yaml would put
ids live that exist nowhere in git. Therefore:
make ed-commitstages_anchors.yamlfiles alongside articles.make verifyand the pre-push hook fail if sync leaves any_anchors.yamldirty, naming the files.- Sync on an unchanged article must rewrite its sidecar byte for byte (deterministic ordering and formatting), so a clean tree stays clean.
- Sync must also create sidecars for articles that have none, even if their content hash hasn’t changed since the last sync.
12. Cross-reference syntax (decided)
The cross-reference convention is tightened, and the existing 47 cross-references are cleaned up once to match:
- Targets are separated by
;only, never commas. - Builder’s call: the existing order stays (cross-reference before the
citations, as
indexer.mdalready shows). Parsing happens on the rendered HTML: the target list runs fromsee:/see also:to the first citation link (<a>), the first nested list, or the end of the entry, with a trailing comma stripped. This parses most of today’s 47 as they stand. - Unlinked in-universe citations (plain-text
*Almnck.*references) must not follow a cross-reference; they move before it. Two entries need this today (Almanack › non-involvement policy; Prime Directive). - Entry ids come from the head term only (
idx-prime-directive, not the gloss), so they stay stable when glosses change. The head term is the text before the first comma outside parentheses, with any trailing parenthetical dropped: “Tcheka (Veh-Tcheka, …)” →idx-tcheka. If two top-level entries share a head term, both ids extend to the second comma segment (idx-kropotkin-peter). Sub-entries getidx-<parent>--<sub>. - A target matches a top-level entry when its normalised text equals the entry’s head term, or its first two comma segments (“Goldman, Emma”). A target “Parent, sub” matches a sub-entry (“Linux, shell scripting”). “Starts with” matching is dropped. Targets that name no entry are fixed in the cleanup (“Mutual Aid”, “Gilgamesh” today).
indexer.md is updated with the convention, and the check in §10 fails
on any cross-reference that doesn’t parse or resolve.
13. Migration (decided)
The builder runs update-index --reanchor over all published articles
and leaves the result uncommitted for Danny to review. The locate loop
uses the configured llm default model if it supports tools, otherwise
the current Claude Sonnet via llm-anthropic. The llm dependency group
is installed into .venv for this.
Constraints
- Static site, no JS required for anchors to work.
- Every
*.mdmay be encrypted in git; the sidecar holds no prose. bin/update-indexcurrently needs the optionalllmdependency group;.venvdoes not have it installed today.- Tests are TAP via
bin/a-test; new unit tests go in the unit suite, the permalink affordance gets a browser test.
Left to the builder
- The exact threshold (0.5) and shingle size (3), tuned against real paragraph edits in git history. Pick an article with revisions, replay them through the matcher, and check that typo fixes and one-sentence rewrites keep their ids.
- Whether
ed-doctoror a unit test is the primary home for the index check (do both if cheap). - Prompt wording in
indexer.mdand the--reanchorprompt. - How
_anchors.yamlis treated byed-status/ed-doctor(it should be expected, not flagged as unknown).