Subject Index Deep Links Implementation Plan
For agentic workers: REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (
- [ ]) syntax for tracking.
Goal: Index citations link to the paragraph, sidenote or margin box they refer to; cross-references link to the index entry they name.
Architecture: A pure module, src/almnck/core/anchors.py, normalises element text, hashes word shingles, and matches elements against a per-article _anchors.yaml sidecar to give paragraphs stable ids. make sync writes sidecars; render_markdown callers apply them at build. A second pure module, src/almnck/core/subject_index.py, gives index entries ids, links cross-references, and checks the index. bin/update-index gains a locate tool for the LLM and a --reanchor mode.
Tech Stack: Python 3.10+, Django 5, Python-Markdown, BeautifulSoup4, PyYAML, llm ≥ 0.28 tools, Playwright for browser tests, TAP via bin/a-test.
Spec: doc/05-process/plans/2026-10-31-index-deep-links-design.md
Global Constraints
- Paragraph ids:
p-+ first 5 chars of lowercase base32 SHA-256 of the normalised words joined by single spaces; collisions in an article get-2,-3in document order. - Margin box ids:
mb:<data-slug>if the aside hasdata-slug, elsemb:+ the same 5-char hash. - Footnote ids stay
fn:<name>; headings keeptocids; any element that already has an id keeps it and is not in the sidecar. - Shingles: word 3-grams (single words for elements under three words), each
blake2b(key=b"almnck-anchors", digest_size=4)as 8 hex chars, sorted, unique. - Matching: Jaccard similarity, greedy highest-first, one-to-one, threshold 0.5.
- Sidecar path
editorial/articles/<slug>/_anchors.yaml,version: 1, no plaintext prose, byte-identical output for identical input. make buildnever writes intoeditorial/.- Index entry ids:
idx-<slug(head)>,idx-<parent>--<sub>for sub-entries (rules in spec §12). - All new tests in
src/tests/, unit tests unmarked, browser tests@pytest.mark.browser. - Commit messages: one short subject line, ending with the session attribution line.
Review Focus
- Two identical paragraphs in one article (refrains, repeated speaker lines): ids must differ (
-2suffix) and stay attached to the same paragraph across syncs. Test in Task 1. - Appending the
#affordance to a justified paragraph (justif-init.jslays out body text): the paragraph’s height and line breaks must not change when the#appears. Test in Task 4. - HTML entities inside a cross-reference list (
&contains;): splitting targets must not cut an entity. Test in Task 5. - An encrypted article (md-age): sync and
locatemust read decrypted text, and the sidecar must contain no word of the article. Test in Task 2. - Index search filter active when a cross-reference is clicked: the target entry must become visible and be scrolled to. Test in Task 6.
Task 1: Anchor core module
Files:
- Create: src/almnck/core/anchors.py
- Test: src/tests/test_anchors.py
Interfaces:
- Produces:
- normalize_words(text: str) -> list[str] — NFKC, casefold, smart quotes/dashes/ellipsis to ASCII, punctuation stripped, split on whitespace.
- element_words(el: bs4.Tag) -> list[str] — text of el excluding sup footnote refs, img, script, style, svg, and nested ul/ol (for li).
- shingles(words: list[str]) -> frozenset[str]
- fresh_id(words: list[str], prefix: str = "p-") -> str
- @dataclass(frozen=True) class Anchor: id: str; shingles: frozenset[str]
- anchorable_elements(soup: BeautifulSoup) -> list[bs4.Tag] — in document order: p and text-bearing li (no p child) outside div.footnote and outside aside.margin-box; aside.margin-box themselves; skipping elements with an existing id, with zero words, or containing only images. Asides with data-slug are returned too (they get the fixed mb:<slug>).
- assign_ids(elements: list[bs4.Tag], remembered: list[Anchor]) -> list[Anchor] — one Anchor per element, same order.
- anchor_html(html: str, remembered: list[Anchor]) -> tuple[str, list[Anchor]] — sets ids, returns new HTML and the anchors to remember (slug-fixed asides excluded from the returned list).
- load_sidecar(path: Path) -> list[Anchor] (missing file → []), dump_sidecar(anchors: list[Anchor]) -> str.
- [ ] Step 1: Write failing tests in
src/tests/test_anchors.py: test_normalize_folds_quotes_case_and_punctuation:normalize_words("“Hello,” she said—LOUDLY…")==["hello", "she", "said", "loudly"].test_element_words_ignores_link_urls_and_footnote_refs:<p>See <a href="https://x.example/y">the wheel</a><sup id="fnref:a"><a class="footnote-ref" href="#fn:a">1</a></sup> turn.</p>→["see", "the", "wheel", "turn"].test_fresh_id_shape: matches^p-[a-z2-7]{5}$, and is equal for<p>A b c</p>and<p>a, B — c.</p>.test_typo_keeps_id: anchor a 40-word paragraph; change one word;anchor_htmlagainst the first result gives the same id.test_rewritten_sentence_keeps_id: 3-sentence paragraph, replace one sentence → same id.test_heavy_rewrite_gets_new_id: replace 80% of words → new id.test_inserted_paragraph_does_not_shift_others: insert a new paragraph at the top; all old ids unchanged.test_split_paragraph_larger_half_keeps_id.test_identical_paragraphs_get_distinct_stable_ids(Review Focus 1): two identical paragraphs → idsXandX-2; re-anchoring against the result gives the same ids in the same order.test_footnotes_and_existing_ids_untouched:<div class="footnote"><ol><li id="fn:a"><p>x y z</p></li></ol></div>and<p id="coffin">…</p>keep their ids, inner footnotepgets none.test_margin_box_ids:<aside class="margin-box" data-slug="fqa">→mb:fqa; aside without slug →^mb:[a-z2-7]{5}$; its innerpgets no id.test_sidecar_roundtrip_is_byte_stable:dump_sidecar(load_sidecar(p))== file bytes; dumping twice is identical.-
test_sidecar_contains_no_words: dumped sidecar for “The quick brown fox jumps” contains none of those words. -
[ ] Step 2: Run
bin/a-test --suite unit(orcd src && pytest tests/test_anchors.py). Expected: FAIL, module not found. -
[ ] Step 3: Implement
src/almnck/core/anchors.py. No Django imports. Matching inassign_ids: score all pairs, sort by (score desc, element index asc, remembered index asc), take pairs ≥ 0.5 where neither side is taken; then fresh ids for the rest in document order, suffixing on collision with any id already used. -
[ ] Step 4: Run tests. Expected: PASS.
-
[ ] Step 5: Tune. Replay real edits: for
kropotkins-funeralanddisputation-of-the-hands, take each pair of consecutive revisions fromgit log -p(decrypt via md-age if needed), anchor old then new, and print which paragraph ids changed beside a word-diff. Adjust threshold/shingle size only if typo-level edits change ids; record the result in a comment at the top ofanchors.py. -
[ ] Step 6: Commit
Add paragraph anchor matching core.
Task 2: Sync writes sidecars; views apply them
Files:
- Modify: src/almnck/units/management/commands/sync_with_repo.py (_sync_unit)
- Modify: src/almnck/units/views.py (index, article_detail, draft_detail)
- Test: src/tests/test_sync_anchors.py
Interfaces:
- Consumes: anchor_html, load_sidecar, dump_sidecar (Task 1); render_markdown (views).
- Produces: anchored_article_html(unit: Unit) -> str in views.py = anchor_html(render_markdown(unit.content), load_sidecar(sidecar_path(unit)))[0]; sidecar_path(unit: Unit) -> Path = EDITORIAL_DIR / unit.source_path / "_anchors.yaml".
- [ ] Step 1: Failing tests (
@pytest.mark.django_db,tmp_patheditorial dir viasettings.EDITORIAL_DIR): test_sync_creates_sidecar_for_article.test_sync_is_byte_stable: sync twice, sidecar bytes identical, mtime unchanged on the second run (write only when content differs).test_sync_creates_missing_sidecar_even_if_hash_unchanged: sync, delete sidecar, sync → sidecar exists again.test_pages_get_no_sidecar:editorial/pages/x/page.md→ no_anchors.yaml.test_article_detail_html_has_sidecar_ids: rendered article page containsid="<id from sidecar>".-
test_encrypted_article_sidecar_has_no_plaintext(Review Focus 4): use the existing md-age test helpers if present, otherwise mock_read_contentto return decrypted text and assert sidecar contains no body word. -
[ ] Step 2: Run. Expected: FAIL.
-
[ ] Step 3: Implement. In
_sync_unit, forunit_type == ARTICLE: before the unchanged-hash early return, if the sidecar is missing, continue; after saving, compute anchors from the body and write the sidecar if its text differs. Useanchored_article_htmlin the three views in place of the barerender_markdown(...content)call for articles. -
[ ] Step 4: Run tests and
make sync. Expected: PASS; seven_anchors.yamlfiles appear undereditorial/articles/; a secondmake syncleavesgit statusunchanged. -
[ ] Step 5: Commit sidecar code, tests, and the seven generated sidecars:
Remember paragraph ids in per-article sidecars.
Task 3: Keep sidecars committed
Files:
- Modify: bin/a-verify (after the sync step)
- Modify: Makefile (ed-commit)
- Modify: bin/editorial-doctor (treat _anchors.yaml as expected)
- Test: src/tests/test_verify_gate.py (extend)
-
[ ] Step 1: Failing test
test_verify_fails_on_dirty_sidecar, following the existing pattern intest_verify_gate.py: a dirty_anchors.yamlafter sync makes the check exit non-zero and print the path. -
[ ] Step 2: Run. Expected: FAIL.
-
[ ] Step 3: Implement. In
a-verify, aftersync_with_repo:git status --porcelain -- 'editorial/**/_anchors.yaml'; non-empty → print the paths and “commit the regenerated anchors (make ed-commit)” and exit 1.ed-commitrunssyncbeforegit add editorial/. -
[ ] Step 4: Run test and
make verify-fast. Expected: PASS on a clean tree. -
[ ] Step 5: Commit
Fail verify when paragraph anchors are uncommitted.
Task 4: Paragraph permalink affordance
Files:
- Modify: assets/js/sidenotes.js (setupPermalinkAffordance, setupTouchPermalinkAffordance selectors; inline-aside id assignment ~line 1799 keeps server ids)
- Modify: assets/css/almanack.css (near .permalink-affordance, line ~1015)
- Test: src/tests/test_paragraph_permalinks.py (@pytest.mark.browser)
- [ ] Step 1: Failing browser tests against the dev server on
kropotkins-funeral: test_paragraph_shows_permalink_after_hover: hover a.body-text p[id]for 1s →.permalink-affordance.visibleinside it withhref == "#" + id.test_fragment_scrolls_and_highlights_paragraph: load…/#<p-id>→ that paragraph getsfragment-highlightedand is in the viewport.-
test_permalink_does_not_reflow_justified_paragraph(Review Focus 2): paragraphgetBoundingClientRect().heightandgetClientRects().lengthof its text are unchanged after the#shows. -
[ ] Step 2: Run
bin/a-test --suite browser. Expected: FAIL. -
[ ] Step 3: Implement. Selector becomes
'.sidenote, .margin-box, .figure, figure, .body-text p[id], .body-text li[id]'. The#for paragraphs sits in the right gutter level with the paragraph’s first line, absolutely positioned so it takes no inline space (.body-text p[id] { position: relative }). Check placement with the art-direction skill at desktop and phone widths. -
[ ] Step 4: Run browser tests. Expected: PASS.
-
[ ] Step 5: Commit
Show permalink on paragraphs.
Task 5: Index entry ids and cross-reference links
Files:
- Create: src/almnck/core/subject_index.py
- Modify: src/almnck/units/views.py (page_detail: when output_path == "/index/", pass content through link_index(html))
- Test: src/tests/test_subject_index.py
Interfaces:
- Produces:
- head_term(li: bs4.Tag) -> str — entry text before the first comma outside parentheses, trailing parenthetical dropped.
- link_index(html: str) -> tuple[str, list[str]] — returns HTML with ids on every entry li in .idx and cross-reference targets wrapped in <a href="#idx-…">, plus a list of problems ("unresolved cross-reference 'X' in entry 'Y'").
- [ ] Step 1: Failing tests:
test_entry_ids: “Tcheka (Veh-Tcheka, All-Russian Extraordinary Commission), see also: Hostages” →id="idx-tcheka"; sub-entry “non-involvement policy, …” under “Almanack” →idx-almanack--non-involvement-policy.test_shared_head_terms_extend: entries “Kropotkin, Peter, …” and “Kropotkin, Alexandra, …” →idx-kropotkin-peter,idx-kropotkin-alexandra.test_see_links_to_entry: “Cheka, see: Tcheka” →<a href="#idx-tcheka">Tcheka</a>.test_see_also_list_stops_at_citation: “Anarchism, see also: Goldman, Emma; Kropotkin, Peter, (citation link)” → two links, citation untouched, no trailing comma inside a link.test_target_with_markup: “see also: Umbin” resolves to theidx-umbinentry, link wraps the<em>.test_subentry_target: “Bash, see: Linux, shell scripting” →#idx-linux--shell-scripting.test_entity_in_target_not_split(Review Focus 3): target “Smith & Wesson; Guns” yields two targets, “Smith & Wesson” and “Guns”.-
test_unresolved_target_reported_and_left_plain. -
[ ] Step 2: Run. Expected: FAIL.
-
[ ] Step 3: Implement with BeautifulSoup. Split the target run on
;at the node level (text nodes only), so entities and tags are never cut. -
[ ] Step 4: Run tests. Expected: PASS.
-
[ ] Step 5: Commit
Link index cross-references to their entries.
Task 6: Index page behaviour for cross-reference jumps
Files:
- Modify: assets/js/index-search.js
- Modify: assets/css/almanack.css (.idx li:target highlight matching .fragment-highlighted)
- Test: src/tests/test_index_crossrefs.py (@pytest.mark.browser)
- [ ] Step 1: Failing browser tests on
/index/: test_crossref_click_scrolls_to_entry: click the “Tcheka” link in the “Cheka” entry →location.hash == "#idx-tcheka"and the entry is in the viewport.-
test_crossref_click_clears_filter(Review Focus 5): typecheka, seeinto the filter (matches the “Cheka” entry, hides “Tcheka (…)”), click its “Tcheka” link → filter input empty, all entries visible,#idx-tchekain viewport. -
[ ] Step 2: Run. Expected: FAIL.
-
[ ] Step 3: Implement. Delegated click handler on
a[href^="#idx-"]: if the target is hidden, clear the input and re-runfilterEntries()before letting navigation proceed. -
[ ] Step 4: Run. Expected: PASS.
-
[ ] Step 5: Commit
Clear index filter when following a cross-reference.
Task 7: Cross-reference cleanup and convention
Files:
- Modify: editorial/pages/index/page.md
- Modify: assets/prompts/indexer.md (Cross-References section)
- Test: src/tests/test_subject_index.py (add real-data test)
-
[ ] Step 1: Failing test
test_real_index_crossrefs_all_resolve(@pytest.mark.django_dbnot needed):link_index(render_markdown(index body))problems list is empty. -
[ ] Step 2: Run. Expected: FAIL, listing the unresolved targets (at least “Mutual Aid”, “Gilgamesh”, “Prime Directive, Tripitaka, …”).
-
[ ] Step 3: Fix each reported entry in
page.mdby hand:;between targets, unlinked*Almnck.*citations moved before the cross-reference, target text made equal to the entry it names. Change no glosses. Updateindexer.md: targets separated by;only, a target is the entry’s head term (or “Parent, sub-entry”), plain-text citations never follow a cross-reference. -
[ ] Step 4: Run. Expected: PASS.
-
[ ] Step 5: Commit
Tidy index cross-references to the new convention.
Task 8: locate tool and fragment preservation in update-index
Files:
- Create: src/almnck/core/index_tools.py (logic, importable for tests)
- Modify: bin/update-index (thin CLI; Django setup; uses index_tools)
- Modify: assets/prompts/indexer.md (citations come from locate)
- Modify: src/tests/test_update_index.py (import from index_tools instead of duplicating helpers)
- Test: src/tests/test_index_tools.py
Interfaces:
- Consumes: anchored_article_html (Task 2), normalize_words, element_words (Task 1), format_url (core/citations.py).
- Produces:
- locate(slug: str, quote: str) -> str — "/vol/m/d/slug/#id", or an error string starting "Not found." listing up to 3 closest elements as #id: first 12 words…. Searches anchorable elements, footnote li[id^=fn:], and margin boxes; the smallest element containing the quote’s normalised words as a contiguous run wins.
- article_ids(slug: str) -> set[str] — every id in the rendered article.
- restore_fragments(old_md: str, new_md: str, skip_paths: set[str]) -> str — for each link in new_md to an article path without a fragment, copy the fragment from the same entry (parent heads + own head) and same path in old_md; skip paths being re-indexed.
- [ ] Step 1: Failing tests (
@pytest.mark.django_db, synced fixture article): test_locate_paragraph,test_locate_footnote(returns#fn:<name>),test_locate_ignores_case_and_punctuation,test_locate_not_found_lists_near_misses.test_restore_fragments_keeps_other_articles: old line has(/5921/2/13/kropotkins-funeral/#p-abcde), model output dropped the fragment → restored.-
test_restore_fragments_skips_reindexed_article. -
[ ] Step 2: Run. Expected: FAIL.
-
[ ] Step 3: Implement.
cmd_indexusesmodel.chain(prompt, tools=[locate]).text();--modelflag, defaultllm.get_model(); ifnot model.supports_tools, exit with “model X has no tool support; pass –model”. After merging sections, runrestore_fragments. Prompt: every citation link must be the URLlocatereturned for a quote from the article; the bare article URL only for whole-article subjects. -
[ ] Step 4: Run tests. Expected: PASS.
-
[ ] Step 5: Make the
llmextra reliable and smoke-test.a-verifyrunsuv sync --locked --extra api, which removes thellmextra, so change the Makefileidx-*targets to runuv run --extra llm bin/update-index …. Thenmake idx-status. Expected: status list, no import error. -
[ ] Step 6: Commit
Give the indexer a locate tool for paragraph links.
Task 9: --reanchor, index check, and the migration run
Files:
- Modify: src/almnck/core/index_tools.py, bin/update-index
- Test: src/tests/test_index_tools.py, src/tests/test_subject_index.py
Interfaces:
- Produces:
- entries_citing(index_md: str, path: str) -> list[tuple[int, str]] — (line number, entry text with parent head) for every line linking to path.
- apply_fragments(index_md: str, path: str, fixes: dict[int, str]) -> str — sets the fragment on that line’s link(s) to path; leaves everything else byte-identical.
- check_index(index_md: str) -> list[str] — every fragment exists in article_ids(slug), plus link_index problems.
- [ ] Step 1: Failing tests:
test_apply_fragments_changes_only_the_link.test_reanchor_rejects_invented_ids: a fix whose id is not inarticle_idsis skipped and reported.-
test_check_index_reports_missing_fragment. -
[ ] Step 2: Run. Expected: FAIL.
-
[ ] Step 3: Implement
--reanchor [slug ...](no slugs → all published articles): per article, send the model the numbered entries, the article text, andlocate; ask for one<line>: <url>per entry; validate againstarticle_ids;apply_fragments; save. Add--checkthat printscheck_indexproblems and exits 1 if any. -
[ ] Step 4: Run tests. Expected: PASS.
-
[ ] Step 5: Run the migration:
bin/update-index --reanchor, thenbin/update-index --check. Expected: check clean. Spot-check five links per article in the dev server (make serve, follow index links, confirm the highlighted paragraph mentions the subject). -
[ ] Step 6: Add
test_real_index_has_no_broken_fragments(@pytest.mark.django_db, runscheck_indexon the real index aftersync) to the unit suite. -
[ ] Step 7: Leave the migrated
editorial/pages/index/page.mduncommitted and commit only code and tests:Re-anchor existing index citations. Tell Danny the index diff is ready for review.
Task 10: End-to-end
- [ ]
make sync && make build; thenbin/a-test --suite unit,browser,web-links. Expected: all pass,web/index/index.htmlcontainshref="/5921/2/13/kropotkins-funeral/#p-andhref="#idx-tcheka". - [ ] Open the built index in the browser, follow three citations and three cross-references, and check one on a phone-width viewport.
- [ ] Update
doc/01-editorial/(index section, or the markdown guide) with: paragraph ids are automatic,{: #name}overrides,_anchors.yamlis generated and committed,update-index --reanchor/--check.