Manual
Almnck.
Price: 50ⓐ

Full-Codebase Critique: JS, Static Generation, Build Layer, Structure

Date: 2026-07-06 (amended 2026-07-13) Status: Proposal — prioritized work list for a future agent, with follow-up review notes Scope: in-page JavaScript (assets/js/, inline scripts, margin-box code), static generation (src/almnck/, templates), Makefile + bin/ + CI posture, the membership API (api/), and overall repository structure. Not reviewed: vendor library internals, llc/, editorial prose, secrets/.

Context

Every layer was read in full and all line numbers below were verified against the working tree at the time of review. Two overall observations frame the list:

  1. None of the March 2026 critique was implemented. All five findings in 2026-03-29-distill-aware-refactor-opportunities.md are still open: the duplicate catch-all routes, the frontmatter-parsing duplication, views.py acting as a service layer, the scattered frontpage rules, and the build-time caching experiments. Several have since produced the predicted drift (see items 14, 20, 21).
  2. The codebase’s systemic disease is the same at every layer: useful logic is trapped inside entry points (a view, a management command, a bin script, an IIFE) and gets re-implemented rather than shared. Each copy then drifts. The JS layer has a second variant of the disease: sediment from the HTMX-to-View-Transitions migration — dead lifecycle machinery, comments describing a navigation model that no longer exists, and one dangling variable that breaks the masthead outright (item 1).

Items are numbered continuously so future work can reference them (“fix item 7”). Within each tier they are ordered by expected value.

Follow-up review (2026-07-13). This amendment re-read the current source, operational documentation, dependency setup, and test entry points. It keeps the original numbering so existing references remain useful; corrections and new evidence are incorporated into the affected items below. In particular, the API’s dedicated pytest suite exists and passes locally, but no documented make test* path runs it; that turns the absence of CI from a general concern into a concrete coverage gap.


Priority 0 — live breakage, security, and data-loss paths

1. assets/js/celestial.js:1121,1643 — undeclared dateAnim throws ReferenceError; the masthead sphere does not render. Commit b936c5b5 (“Drop celestial date-sweep animation”) removed the variable but left two reads. The file is a "use strict" IIFE (line 23), so the read throws; doRender() hits line 1121 unconditionally on first paint, and everything after the initial doRender() call in init() (minute tick, test hooks) never runs. Fix: delete both conditions (the feature is gone), smoke-test the masthead in a browser, and add a browser regression test that asserts the canvas painted.

2. assets/js/identity.js:47-55 — the identity “public key” embeds 29 of the 32 secret bytes; member identities are forgeable. generateKeypair() derives both pubkey ('age1' + hex.slice(0,58) = first 29 bytes) and secretKey (all 32 bytes) from the same random array, and deriveSigningKeypair() (lines 90-99) HKDF-derives the Ed25519 signing seed from those same bytes. Anyone who observes a member’s pubkey — which is sent on every /register, /visit, and /checkout — can brute-force the missing 3 bytes (2²⁴ HKDF+Ed25519 trials, checkable against any observed signature) and reproduce the signing key, then spoof /visit (debits balance) and /checkout. The // simplified MVP comments acknowledge the shortcut, but it is live behind payment-adjacent auth. Fix: generate the signing seed from independent random bytes, derive the public identifier from the secret (or use real age/typage keys), and plan a key-rotation path for existing members (the server keys Member rows by pubkey, so migration needs a signed re-key endpoint or an accepted balance-reset).

2a. api/main.py:121-132 — POST /register lets any unauthenticated caller bind a signing key to an existing member, seizing legacy accounts. When a member row already exists but has no signing_pubkey, register writes whatever signing_pubkey the request supplies (if request.signing_pubkey and not member.signing_pubkey: …). The endpoint requires no signature — knowing a member’s public identifier (pubkey, which travels on every request) is enough to claim their account. Every member created before signing keys were introduced has signing_pubkey = None (models.py:14), so the entire legacy cohort is exposed, and the exposure is worst during exactly the item-2 key migration: an attacker who claims the signing key before the real member re-keys owns the balance thereafter. This is unauthenticated account takeover, the same severity class as item 2 — not the P2 hardening it was first filed under (item 27). Fix: bind signing_pubkey only at row creation; never let register mutate an existing row. Re-keying an existing member must require a proof from the old credential, or an explicit operator-reviewed recovery flow. The membership manual’s claim that a timestamp-only signature proves key ownership is contradicted by this path and must be corrected.

3. src/almnck/units/management/commands/sync_with_repo.py:47-52 — a full scan that finds zero units deletes every Unit in the database. The exclude(source_path__in=units_found).delete() prune runs whenever --path is absent; an empty-but-present editorial/ (bad mount, misdirected ALMANACK_ROOT, partial clone) classifies everything as “no longer on disk”. Because make prod-deploy chains sync → build → rsync --delete, the failure mode is an empty site pushed to production. Fix: refuse to prune when the scan found zero (or suspiciously few) units unless a --prune flag is passed, and log the prune count loudly.

4. Makefile:343-353 and bin/a-test — the production path has no deterministic verification, and failures can be reported as success. There is no CI configuration, the git hooks are stock git-lfs shims, and prod-deploy depends on update-finances sync celestial build — never on any test* target. The orphaned pre-deploy target is not a substitute: it asks an interactive claude -p session to run tests and edit code, so it is neither reproducible nor a safe deploy prerequisite.

The test runner adds two concrete false-green paths. When no container runtime is installed, or when the API image fails to build or start, bin/a-test prints an ok ... # SKIP line and exits zero (28-34, 51-54, 80-83, 204-213). Thus the default make test can pass without testing the API at all. Worse, the runner executes only the seven-request bin/a-api-test smoke script; it never runs api/tests/, including the 21 fast tests of registration, signatures, checkout, and Stripe-webhook crediting. test-all does not run them either. The Makefile also pipes every test command through tapview without pipefail, so an abnormal runner exit can be masked if it does not emit a failing TAP record.

Separately, the deploy foreach loops join per-host rsync/Caddy commands with ;, so a failed rsync to one host still prints “Deploy complete” and pings IndexNow. The same unguarded-loop pattern appears in prod-api-deploy and prod-ipfs-deploy: a failed secret transfer, git pull, or container start can be followed by a misleading success message. prod-deploy also lacks even an index.html guard before an rsync with --delete.

Fix: add one non-interactive verify target and make it the CI and release gate. It should install from uv.lock, run test-doc, the marker-corrected site unit suite, pytest api/tests, a framework check/sync/build smoke test, and a strict container API smoke test in environments that advertise a container runtime. In CI, a missing or failed required runtime must fail, not skip; optional local skips may remain only behind an explicit flag. Create a CI workflow for that target on every change and protect the deployment branch with it. Make deploy depend only on the fast deterministic local gate (not an LLM), require web/index.html, use explicit for loops that stop on the first failed host, and health-check each reloaded service before declaring success. Keep IndexNow non-fatal, but run it only after every deployment step has succeeded.

5. Database overwrites with no backup: bin/a-db-sync:71-77 and Makefile:420-434. The nightly replica sync stops the API and \mvs the transferred snapshot over the live failover members.db with no integrity check (PRAGMA integrity_check), no size sanity, and no copy of the outgoing file — a truncated transfer silently destroys the replica, discovered only at failover time. prod-api-restore overwrites the production DB over ssh with only a y/N prompt and no server-side backup of what it replaces. Both violate the house rule of backup-before-destructive-DB-ops. Fix: stage to a temp path, integrity-check, back up the current file, then swap; on restore, snapshot the live DB server-side first.

6. api/main.py:322-333 — a paid checkout that can’t be credited is acknowledged and forgotten. stripe_webhook returns 200 regardless; _handle_checkout returns silently when the member row or metadata is missing, without recording the event or logging. Stripe considers the event delivered and never retries: the customer paid, no Almanickels were credited, and no trace exists. Fix: log loudly and return a 500 (so Stripe retries) — or record a quarantine row — whenever a checkout.session.completed can’t be applied.

The same treatment is needed for an invoice.paid event whose subscription cannot be matched (354-367) and for malformed metadata (int(amount) at 335). The membership manual currently says that all events are recorded; that is false for each of these paths. Record a durable rejected/quarantined event with the Stripe event ID and a reason, alert an operator, and choose the response deliberately: retryable transient failures should return 5xx, while permanent bad data should be retained for reconciliation without an infinite retry loop.

6a. api/main.py:164-202, 308-386 and api/models.py — webhook conflict handling and daily-visit idempotency are not expressed as complete database contracts. WebhookEvent’s primary key prevents two committed receipts for the same Stripe event, but the handler checks for it before writing it. Two concurrent deliveries can therefore both pass session.get(); one will then hit an unhandled unique-key error at commit instead of returning the intended idempotent 200. The existing test covers only sequential delivery. Transaction.stripe_event_id is not unique as a second audit invariant. Daily visits have a more direct data-integrity gap: two requests can both see an old last_visit, while Visit has no unique (pubkey, visited_on) constraint, so duplicate history rows and ambiguous debit responses are possible.

Fix: claim the Stripe event with insert-on-conflict/no-op (or a receipt state machine), process the balance change only for the successful claim, and return 200 for an already committed receipt. Keep the claim and balance change in one transaction, and make the transaction event ID unique as a second audit invariant. Likewise add the unique visit constraint and treat a conflict as an already-debited visit. Configure SQLite deliberately for the FastAPI thread model (connection settings, WAL/busy timeout, and a documented single-writer limit), then add concurrent webhook and visit tests. This is payment state: a sequential test and a receipt primary key are not sufficient proof of the full concurrency contract.

Priority 1 — user-visible bugs and operational traps

7. assets/js/sidenotes.js:1299-1308 — positionMarginBoxes() leaks a window scroll listener and a 60 s setInterval on every reflow. reposition() calls it on every resize/content-reflow/box-injection invalidation; the handlers are registered raw (not via the tracked on() helper) so nothing removes them. Each leaked handler runs querySelectorAll('[class*="wc-mb-"]') plus per-box getBoundingClientRect() on every scroll frame — jank compounds with session length. Fix: register the sundial scroll handler and interval once in init(); have positionMarginBoxes() just call setSundialProperties().

8. Video-figure lifecycle cluster (assets/js/figures/). (a) video-player.js:30,137-139 — the annotation-mode preference can never persist: the localStorage key derives from a Date.now()-generated container id, different every load. Key on the article path + figure ordinal instead. (b) video-player.js:555-570 — onFullscreenChange checks the global document.fullscreenElement unscoped, so fullscreening one video forces every player on the page into on-screen annotation mode. Early-return unless the fullscreen element is (or contains) this player. (c) video-player.js:429-441 vs 608-614 — the scene-dropdown’s document-level click/keydown listeners are never removed by cleanup(); re-inits accumulate them over detached nodes. (d) runtime.js:61-77 + video-annotations.js:233-242, video-scenes.js:120-124 — wireCapabilities hands out subscribe with no unsubscribe handle, so cleanup leaves stale handlers in topic sets; and video-annotations.js:64-77 adds a new synthetic text track (irremovable by spec) on every re-setup. Fix all four with one AbortController-based teardown owned by the runtime (see item 22).

9. assets/js/figures/vtt.js:20-22 — cues written in the legal MM:SS.mmm form parse to zero. The timing regex demands HH:MM:SS.mmm on both sides; many tools emit two-field times. Annotations and the scene TOC silently vanish for such files. Fix: make the hours group optional, defaulting to 0; add parser tests for two-field times and for payload lines containing -->.

10. Figure-loader inline scripts hardcode the article’s canonical URL (3 articles). editorial/articles/kropotkins-funeral/article.md:46, logiebair/article.md:182, regolith-with-latitude/article.md:58 each bake /{volume}/{month}/{day}/{slug}/assets/figures into const base. A date or slug change silently 404s the manifest and kills every interactive figure. The enclosing #article-swap already carries data-title-path="{{ unit.output_path }}" on both article and index pages — read that instead, and document the pattern in the markdown guide.

11. assets/js/interactive-margin-boxes.js:33 — margin-box code.js is imported with no cache-bust into an immutable cache. /static/* is served max-age=31536000, immutable (assets/system/Caddyfile:6-10); the dynamic import('/static/margin-boxes/'+slug+'/code.js') carries no ?tag=, so returning visitors run stale box code forever after an edit. Fix: emit a per-file content hash onto the box element at build (e.g. data-code-tag) and append it, mirroring figures/runtime.js’s propagateTags.

12. Identity/top-up flow defects (beyond item 2). (a) assets/js/topup.js:63-91 — buttons are disabled only after two awaits; a double-click opens two checkout sessions. Disable synchronously first. (b) topup.js:137-143 and editorial/margin-boxes/identity/assets/code.js:103-108 wait for a noble-crypto-ready event that no code ever dispatches — currently dead because the vendor scripts load synchronously, but a load-order change hangs top-up silently, with no timeout. Dispatch the event from the inline mapping block in base.html, or use a bounded-poll promise. (c) identity.js:159-163 — publicKey is read from the stored profile, not derived from the stored secret; clearing almanack:profile while almanack:identity survives yields pubkey: undefined on signed requests. Derive from the secret. (d) identity.js:21-22 — the secret persists in plaintext localStorage; any XSS is full identity/balance takeover. At minimum document the threat model alongside the fix for item 2.

13. assets/js/pen-marginalia.js:232-233 vs 73-87 — a stroke is rendered and pushed before saveStrokes() can refuse it. Over-budget or throwing localStorage leaves the stroke visible this session but gone on reload — the annotator believes it saved. Fix: persist first, keep the stroke only on success, surface a storage-full notice. Also add the idempotency guard the file lacks (sidenotes has if (window.Sidenotes) return; a second execution here doubles overlays and pointer listeners).

14. Routing: collapse the duplicate catch-alls into one unit_detail (March item 1, now with observable divergence). units/urls.py:135-147 still declares two identical <path:path> routes; article_detail (views.py:515-521) doesn’t constrain unit_type, so page_detail is dead in dev routing — and it contains the subscribe-confirmation branch (views.py:677-679), so /subscribe/?thanks=1 behaves differently under make serve than in the distilled build. Tests call page_detail directly and miss it. Fix: one route resolving by output_path, branch on unit_type where behavior differs, plus a resolver-level (client.get) regression test. Relatedly, models.py:25 — output_path is not unique: collisions 500 in dev (MultipleObjectsReturned) but silently last-writer-wins in the build. Detect duplicates at sync time and fail.

15. bin/a-test:109-113 + src/tests/test_topup_integration.py:19 — the “unit” suite collects the Stripe/Playwright checkout tests. The file is marked only checkout; the unit filter -m "not regression and not browser" doesn’t exclude it, contradicting the documented “no browser, ~0.3 s” and making make test need a browser and Stripe config. Fix: add the browser mark to that file or extend the unit filter. Follow-up confirmation: pytest’s current collection selected all five methods in this file under that exact “unit” expression (135 selected tests total), so this is not merely a theoretical marker mismatch.

16. Deploy entanglement: make prod-deploy runs finances and NASA fetches. bin/a-update-finances:40-59 embeds ledger error messages into doc/02-finances/index.md and exits 0, so a broken ledger invocation ships an error string in a deploy; its update_output_pre also collapses all <pre class="output"> blocks into one combined output. bin/a-celestial:16-17 fetches sdo.gsfc.nasa.gov and svs.gsfc.nasa.gov inside the deploy dependency chain (Makefile:348), so a NASA outage blocks an editorial deploy. Fix: a-update-finances exits nonzero on ledger failure and pairs each block with its own output; celestial imagery moves to its own schedule with non-fatal failure.

17. Failover and ssh-wrapper sharp edges. bin/a-failover:147-157 checks target health only after the DNS cutover — verify /health on the target before flipping. bin/a-failover:41 vs 67-68 picks DNS records with head -1 in one place and tail -1 in another. bin/a-ssh:10 uses unquoted $*, mangling any remote command containing spaces ("$@").

18. assets/js/celestial.js:1204-1218 — trackResize() is a self-perpetuating rAF loop stopped only by transitionend. Under prefers-reduced-motion (or any suppressed transition) the event never fires, so after the first masthead expand the loop runs sizeCanvas() + doRender() every frame, forever. The defined-but-never-called prefersReducedMotion() (line 227) is evidently the missing guard. Fix: stop the loop on a timeout fallback and short-circuit when reduced motion is set.

19. assets/js/celestial.js:372,390 and all of zodiac.js hardcode latitude 40°, ignoring _observerLat. In the ephemeris-fallback path (BCE dates, no embedded ephemeris) sun/moon and the whole zodiac render for 40°N even for a geolocated reader, and armillary bodies (which do use _observerLat) can sit visibly off their own 40°-computed diurnal paths. Thread the observer latitude through the fallback and expose it to zodiac.js.

Priority 2 — consolidations and missing abstractions

20. One shared editorial-parsing module (March item 2, drift now observed). parse_frontmatter/find_content_file exist in at least six places: sync_with_repo.py:182-240, manual/scanner.py:15-29, events/.../a_date.py:167-196, bin/update-index, bin/update-summary, bin/editorial-doctor/editorial-status (variants). They have already diverged: update-index treats index.md as a content file, sync_with_repo._find_content_file does not; contracts differ ({} vs None vs tuple). The almanac-day → volume/path math is triplicated (core/citations.py:33-71 is canonical; sync_with_repo.py:254-284 and build_with_distill.py:192-216 bypass it), and the frontmatter["frontpage"] rules are read at seven call sites with subtly different filters (<= today in find_frontpage_article:142 but not chronology:840 or frontpage_manifest:1005). Build almnck/core/editorial.py exporting parse_frontmatter, find_content_file, output_path_for(almanac_day, slug) (delegating to citations), and frontpage_dates(unit, until=None); migrate all callers; the bin/ scripts already sys.path.insert the src tree.

21. Extract a rendering/service module from units/views.py (March item 3). The 1,037-line module mixes markdown rendering (render_markdown:405), SVG dimension probing, RSS, sitemap, byte-range file serving, and frontpage selection — and sync_with_repo.py:326-329 imports view functions, inverting the layering. Concrete drift this has caused: the margin-box <div> is built in three places (templates/units/article.html:82-90, index.html:30-38, and hand-written HTML in views.py:1029-1035) and the views copy omits data-wash, so a pinned box silently loses its wash tint. Move rendering into almnck/core/rendering.py, render the margin box through one shared partial, and make sync import from core, not views.

22. A small JS lifecycle harness. Four independently-recurring bug families — the sundial leak (7), the scene-dropdown listeners and never-unsubscribed topics (8c,d), the never-dispatched noble-crypto-ready (12b), and the copy-pasted ready-bootstrap (sidenotes.js:2335-2339 ≡ pen-marginalia.js:318-322) — are one missing abstraction. A ~60-line assets/js/almanack-core.js exporting onReady(fn), a per-module AbortController-backed listener registry, a cryptoReady promise, and safeStorage.get/set (the try/catch-localStorage pattern is also duplicated: sidenotes.js:393-410 ≡ pen-marginalia.js:65-87) would structurally prevent all four classes. Also standardize on one module idiom — sidenotes is const/arrow style, pen-marginalia is var/function, index-search is the lone non-IIFE.

23. Decompose sidenotes.js (2,479 lines) and delete its dead lifecycle machinery. cleanup() (1622-1715) is self-documented as “currently uncalled in production”; with it go the LayoutState enum (37-44), runtime/transition() (46-55), and the HTMX-snapshot scaffolding — ~150 lines of inert state every reader must model. The live code splits along clean seams: permalink affordance (1963-2258, fully self-contained), margin-slot geometry (findAvailableSlot/findClosestSlot/placeBox/…, testable as pure functions — note the overlap predicate is copy-pasted three times at 231, 262, 889), sundial/washes (1315-1497), swipe navigation, pinned boxes (390-506), and the trailing lightbox IIFE (2457-2479). Extract in that order; the geometry module finally becomes unit-testable.

24. Share the sphere-projection math between celestial and zodiac. zodiac.js:164-181 is a verbatim copy of celestial.js:594-623 (altAzToXYZ/project, including the 1.8/0.3 perspective constants), self-admitted at zodiac.js:124-125. Any projection change silently de-registers the constellations from the bodies. Publish the helpers on the celestial namespace or extract a tiny shared module.

25. bin/_common.sh for the script bootstrap. a-pass() is defined in both a-activate:49 and a-ssh:6; the ALMANACK_ROOT/venv/pass discovery block is re-derived in a-ssh, a-date, a-failover, a-dns-update. One sourced helper removes the drift and gives the a-ssh quoting fix (17) a single home. While there: quote $ALMANACK_ROOT in a-activate (20,29,30) and gate the make install-dev-binaries call (a-activate:36) behind a tools-present check and [ -t 0 ] so non-interactive activation can’t hang on read.

26. One subscribe-submit routine. The subscribe page inline script (editorial/pages/subscribe/page.md:44-83) and the subscribe margin box (editorial/margin-boxes/subscribe/assets/code.js) POST to the same Listmonk endpoint with different success checks (data.data vs resp.ok), different error UX (alert() vs inline status), and 429-backoff in only one. Share the routine; drop the alert()s.

27. API auth hardening (api/main.py). The Ed25519 message is almanack:timestamp:{ts} only (line 44) — one captured signature authorizes any endpoint for ±5 minutes; include the endpoint and a payload digest in the signed message. /me (line 148) takes pubkey/sig/ts as GET query params, which land in server and proxy logs — make it a POST or move auth to headers. CORS (lines 65-71) is allow_origins=["*"] with allow_credentials=True — an invalid combination browsers reject, and a payments API should pin its origins. Note also visit (line 184) lets balances go negative without bound — if intentional, comment it. Update the membership manual’s claim that a timestamp-only signature proves the caller is the key owner. (The related unauthenticated re-key hole in POST /register is item 2a.)

Priority 3 — documentation repairs

28. Correct the setup, operational, and API documentation. CLAUDE.md line 326 says dependencies use uv_build and Python >=3.10; the project uses hatchling and requires >=3.11. Its prod-deploy description (“sync, build, push”) omits update-finances, celestial (NASA fetches), and indexnow (Makefile:348-354) — deploy touches the finances doc, which is worth knowing before running it. test-all also runs the checkout suite (Makefile:195), while the “~5 s” claim for make test ignores the cold API-container build.

The public setup guide repeats the Python 3.10 error and recommends uv pip install -e ., which does not install the API extra, pytest/browser tools, and omits the dependency-group-only Ruff configuration despite the project’s stated lint policy. Make the documented route make install/uv sync --locked with the required extras and groups, or clearly distinguish an editorial-only install from the test/development profile. State which optional tools (lychee, jq, container runtime, Playwright, Stripe CLI) each test target needs. The membership manual also claims every webhook event is recorded and that a timestamp-only signature proves ownership; both are contradicted by items 6 and 27. Documentation link checks passing is useful, but it cannot validate these semantic contracts.

29. Stale-comment sweep (each one actively misleads). sidenotes.js:16-21 cites a historyRestore handler that doesn’t exist; figures/runtime.js:232-234 attributes _figureCleanup to “HTMX history restore”; celestial.js:17-19,31 still describe the removed HTMX date-sweep (ARC_DURATION is dead); celestial.js:36-38 says the moon-epoch constant is ≈9126.24 when the (correct) constant is 9491.24; pen-marginalia.js:174 promises a “Safari fallback below” that doesn’t exist; video-annotations.js:96 says line = -3 while the code sets -1; build_with_distill.py:111 and views.py:685 reference the obsolete jan/01 path format.

30. Document the data-hide-on-page single-<dd> constraint. The selector [data-hide-on-page~=…] + dd (article.html:63-64, index.html:20-21, and CLAUDE.md) hides only the first adjacent <dd>; a term with two definitions leaves the second orphaned-visible. Either document “one dd per hidden dt” beside the convention or extend the pattern.

31. Merge docs/plans/ into doc/05-process/plans/. Three plan files (night-mode, pen-marginalia) live in a parallel docs/ tree that shadows the canonical doc/ hierarchy — almost certainly a wrong-guess by a past agent. Move them and delete docs/ before it accretes more.

32. Record vendor versions. assets/js/vendor/ carries noble-ed25519, noble-hashes, astronomy-engine, and media-chrome with versions recoverable only from header comments (media-chrome 4.17.2) or not at all. A vendor/VERSIONS.txt (source URL, version, date) makes upgrades and CVE triage tractable. This should be a lock-and-verify change, not just a note: make update-vendor downloads GitHub releases/latest and raw-branch content with silent curl -sL, no pinned revision, checksum, failure flag, or atomic replacement. bin/a-install-tools similarly installs md-age from a moving raw URL. Define a manifest of immutable version/tag or commit URLs and SHA-256s; download with curl --fail --location to a temporary path, verify, then rename. Have CI validate the manifest against the vendored files.

Priority 4 — housekeeping

33. Move the video masters out of git. ~3.6 GB of the repository is kropotkins-funeral/assets/: a 2.7 GB _final_restored.mp4 plus five intermediate encodes and the original mkv. Only the web-served renditions belong in the tree; masters belong in annex/LFS/object storage (the repo has had one history rewrite already — worth doing properly this time, or at least stopping the pattern before the next video article).

34. Dead-code deletions. sidenotes.js cleanup machinery (see 23); celestial.js:227 prefersReducedMotion() (or wire it per item 18); identity.js:57-62 derivePublicKey (ignores its argument, unused); celestial-demo.js (drives the removed __celestialUpdate API; either repoint at __celestialSetHour or delete); bin/a-preview.sh (self-described deprecated pre-Django hack, unwired); the dead "api" entry in bin/a-test’s get_test_suites() (only --list reads it); zodiac.js per-constellation lines arrays (unread; honestly labeled “kept for armillary” — keep only if that lands); redundant import re in views.py:951; dead existing bindings in sync_with_repo.py:378-383.

35. Cache-busting hardening. base.html:10 favicon references /static/favicon.svg un-busted into an immutable cache — use {% cdnstatic %} (the font preload’s exemption on line 9 is deliberate and commented; the favicon’s isn’t). render_markdown’s rewrite (views.py:432-443) only handles double-quoted /static/js/ refs and mangles author-supplied query strings ([^"?]+ → x.js?tag=H?v=1). _file_content_hash (views.py:53-56) emits ?tag=missing for typo’d paths instead of failing the build. celestial.js:122-123 loads the 422 KB astronomy engine un-tagged when no ephemeris hash is present — fall back to a build-time constant. Consider documenting why the noble scripts in base.html:70-76 must not get defer (adding it would break the global mapping that follows them).

36. api/ dependency and placement split-brain. The FastAPI app’s dependencies are listed in both api/requirements.txt and root pyproject.toml (fastapi, sqlmodel, stripe, pynacl are in the Django project’s install set), but the production Dockerfile uses neither: it runs an unpinned pip install fastapi uvicorn sqlmodel pynacl stripe. The committed uv.lock therefore does not constrain the API image. Three independent dependency definitions can silently produce different test and production behavior.

Choose one source of truth. For example, retain an api extra in pyproject.toml, build the image from pyproject.toml plus uv.lock using a locked export/sync, and delete the redundant requirements file; or generate that file from the lock in CI and fail when it is stale. Keep runtime, development, and image-only dependencies explicit. Moving api/ under src/ is optional, but making its resolved dependencies reproducible is not.

37. Small fixes, grouped. frontpage-nav.js:62 year formatting is '0'+y (use padStart); frontpage-nav.js:28 accepts Feb 31 and rolls the Date; backup filenames use date -Ihours and overwrite within the hour (Makefile:417-418, a-list-backup:13); DESTINATIONS includes boat but WEB_SERVERS doesn’t reload it (Makefile:339-341) — fix or comment; a-list-export:17-24 can’t distinguish “last page” from “error” and truncates silently; bin/a-test has no per-suite timeout, so one hung browser test hangs the runner; margin-box getFirstname (identity code.js:33-35) returns the second word (“Fellow Traveler” → “Traveler”); video-annotations.js:184 computes videoId via closest() on a sibling, so timestamped permalinks always fall back; pen-marginalia.js:76 compares UTF-16 code units against a byte budget; index.html:6 hardcodes a literal 0 before {% now "Y" %}; visit’s date.today() (api/main.py:178) uses server-local midnight for streaks — fine, but worth a comment.


Overall structure

What’s healthy. The docs are unusually accurate at the command-name level (every documented make target exists); the TAP-everywhere testing convention and check-activated guard are real discipline; a-failover and a-serve are careful scripts; the distill model (git → SQLite → static HTML) is the right architecture for the project and the domain math (Anno Mundi, BCE year-0, Roman months) is currently consistent across its copies. The API verifies both member signatures and Stripe webhook signatures and keeps an idempotency table. Those strengths should not be overstated: setup prerequisites, API behavior, payment failure paths, and test coverage claims need the repairs in items 4, 6, 6a, 27, and 28.

The three structural facts a future agent should internalize:

  1. The path to production is the soft spot. No CI, no reliable test gate, deploys that swallow per-host failures, a sync that can wipe the DB, race-prone payment state, and two backup-less DB overwrites — items 3-6a cluster there and should be done before anything cosmetic.
  2. Duplication is the disease; entry-point trapping is the cause. The same fix shape recurs at every layer: extract the shared thing (editorial parsing, rendering, JS lifecycle, projection math, shell bootstrap) into one importable home, then delete the copies. Items 20-26 are the same refactor five times.
  3. The HTMX-to-View-Transitions migration was never swept. Dead lifecycle code, comments describing the old navigation model, and one outright breakage (item 1) all date from it. A single “migration sediment” pass (items 1, 23, 29, 34) would remove most of the JS layer’s confusion.

Test coverage note. The riskiest regions found here are exactly the untested ones: figure lifecycle/re-init (all of item 8), resolver-level routing (item 14’s divergence is invisible to direct-call tests), VTT edge cases (item 9), concurrent payment/visit state (item 6a), and everything in bin/. The dedicated API tests are an additional blind spot in practice: they exist, but the standard runner never executes them (item 4). New tests should target these paths before broadening elsewhere.

Follow-up verification (2026-07-13). bin/a-test --suite doc passed its 94 offline link checks. pytest api/tests passed 21 tests, and selected editorial/date/cache-busting tests passed 22 tests. A collection-only run confirmed item 15: the nominal unit selector includes all five checkout integration tests. Ruff could not be run in the existing virtual environment because its executable was absent; that is consistent with the setup-document and dependency-group ambiguity noted in item 28, not evidence that the source is lint-clean.