# Gotchas already paid for

Every one of these cost real time on the example site. They are grouped by where
they bite.

## d3 and SVG

**CSS class font-size beats the SVG attribute.** `.lab { font-size: 12px }` in
style.css overrides `text.attr("font-size", 9)`. On anything carrying a class,
use `.style("font-size", "9px")` — never `.attr(...)`. Symptom: labels you sized
down to avoid a collision are still full size and still colliding.

**Grid axes double-print tick labels.** Put `.tickFormat(() => "")` on the axis
used for gridlines and draw the real labels once, by hand. Otherwise every tick
appears twice, slightly offset, and looks like a rendering bug rather than a
duplicate.

**`svgFor` already translated the `<g>` by the margin.** Adding `m.t` or `m.l`
again inside the chart body double-shifts everything. Symptom: a chart pushed out
of its own frame with no error. (`layerStrip` did this once.)

**A d3 `line` needs `.attr("d", line)`.** Forgetting it renders *nothing* and
throws *nothing*. You get an empty chart and a clean console. (`flopsChart` did
this once.) When a chart is blank and the console is clean, suspect a missing
attribute, not a data problem.

**A step/snake connector must special-case same-column moves**, or it draws a
straight line through the box it was supposed to route around. (`engramFlow` did
this once.)

**Check the shape before you index.** `BigInt(undefined)` is the error you get
when you assume a nested array and the data is flat. The example site's Engram
primes are FLAT, 48 per layer, indexed `k = (order-1)*8 + head`. Print the shape
first; do not infer it from the variable name.

**Two things with the same name are two things.** This model has two different
Sinkhorn iterations: mHC's `comb` balancing (**20** iterations,
`hc_sinkhorn_iters`) and the optimizer's update balancing (**K = 11**, §4.2.2).
Same word, different algorithm, different constant, different section. Never let a
sentence imply they are one thing — and never let a variable name imply it either.

## Editing the files

**`edit`'s `old_string` must match byte-for-byte, and these files are full of
unicode** — `·`, `—`, `₂₀`, `τ`, `√`, `ℓ`, Greek subscripts. When an edit refuses
to match, do not retype the string from memory or from a rendered screenshot.
Derive it from the file:

```python
t = Path("index.html").read_text()
i = t.find("anchor you are sure of")
print(repr(t[i-200:i+400]))     # copy the exact bytes from here
```

`repr()` shows you the real characters; the terminal's rendering of them lies.

**Never locate the end of a matrix by scanning for a generic delimiter.** The
example site corrupted `data.js` by searching for `"],\n"` to find where a matrix
ended — that string also terminates every *row*. Replace the **whole block**,
anchored on the key name before it and the key name after it, or on a
brace-counting parse. Then `node --check` immediately.

**`%g` loses precision silently.** See `fixtures.md`. Fixed decimals only.

**`numpy.int64` breaks `json.dump` mid-write**, leaving a truncated file on disk.
Cast with `int()` / `float()` first. The truncation happens *during* the write, so
the file looks almost fine and fails to parse at the end.

**An evidence block inserted into a plan can eat the ✅ from a header.** After any
bulk insertion into PLAN.md, re-scan for item headers missing their mark:

```python
for m in re.finditer(r"^\*\*\d+\.\d+\*\*(?! ✅)", plan, re.M):
    print(m.start(), repr(m.group(0)[:60]))
```

Beware the false positives: a *second* mention of `**5.2**` inside an evidence
block legitimately has no ✅. Check the offset is the header, not a reference.

## Playwright and verification

**Launch the server with `proc("start", ...)`. Nothing else works.** The trap is
file descriptors, not signals: `subprocess.run(cmd, capture_output=True)` waits
for EOF on the capture pipe, EOF arrives only when every holder of the write end
closes it, and the server you just backgrounded is holding it. Measured —
`bash -c 'sleep 8 & echo hi'` under `subprocess.run(..., capture_output=True,
timeout=3)`: bash exits in milliseconds, `communicate()` raises `TimeoutExpired`
three seconds later, and with no timeout it never returns. `nohup`, `setsid`,
`start_new_session=True` and a script that daemonizes itself are all the same
mistake, because none of them close the descriptor. `proc("start", ...)` points
stdout/stderr at a log file, returns the pid in ~0 ms, and the server survives
the cell, the kernel and a reset; `proc("ps")`, `proc("log", pid=…)` and
`proc("kill", pid=…)` find it afterwards, because the registry lives on disk at
`/tmp/crow-proc/<session>.jsonl`. `proc("run", ...)` is the bounded form for
everything else: it waits on the process, drains for ≤2 s, and hands back
partial output plus a `.note` if something is still holding the pipe.

**`proc("start")` returns before the server is up.** It returned in 0 ms while
`uv` was still resolving the project; reading `/tmp/siteport.txt` on the next
line raised `FileNotFoundError`. Poll for the portfile (~1 s), and delete a stale
one *first* — a leftover port from a dead daemon reads exactly like a live
server, and every script then fails against nothing while looking configured.

**`add_style_tag("html{scroll-behavior:auto!important}")` is mandatory**, in every
script, right after `goto`. The page's CSS sets `scroll-behavior: smooth`; with it
on, `scroll_into_view_if_needed()` returns before the scroll finishes and you
screenshot a half-drawn chart. This is the single most confusing failure mode in
the whole workflow because it is intermittent and looks like a rendering bug.

**Wait ~1400 ms after scrolling before screenshotting.** d3 transitions run 900 ms
with per-element delays.

**Select toggle buttons by class, not by tag.** `.eg-bar button` matches *both* the
`.segbtn` toggles and the `.sltick` preset buttons, so `btns[1]` is not the button
you think. Use `.eg-bar button.segbtn`. Symptom: clicking "decode" scrubs the
slider to k=1 instead.

**`console.assert` failures arrive as console messages of type `"assert"`**, not
`"error"`. A regression script that only listens for `"error"` reports a clean page
full of failed asserts. `scripts/regress.py` keeps three buckets — `ERRORS`
(page errors and uncaught exceptions), `ASSERTS` (a fixture disagreed with the
page), `WARNINGS` (`console.warn`, reported but not fatal) — and exits 1 on
either of the first two. Keep them separate: "the page is broken" and "a number
is wrong" have different fixes, and one merged list hides which one you have.

**Console output is the only channel.** There is no test runner, no exit code from
the page. Anything you want to know, `console.assert` or `console.warn` it, and
read it back through playwright.

**Scroll to the bottom once before an overlap audit**, so every transitioned
figure has actually drawn. `scripts/overlap.py` does this.

**An empty audit result can mean the selector matched nothing.** `BAD: []` from
a host selector that no longer fits the page is indistinguishable from a clean
one, and the page structure is exactly what a late phase changes. Count the
population first — on the example site `figure .chart` matches 27 hosts holding
27 `<svg>`s and 720 `<text>` nodes, none empty. Then prove the gate can fail by
serving a copy of the page with a deliberate break injected (SKILL.md →
"Prove the gate can fail"): the mutant must produce a non-empty `ERRORS`,
`ASSERTS` and `BAD` and exit 1. Both halves were verified on the example site.

**A probe that follows the mouse needs `scroll_into_view_if_needed()` first** —
`ev.clientX` is viewport-relative and the tooltip lands in the wrong place (or the
hover never fires) if the element is off-screen. (`engramGate` did this once.)

**`vision(...)` returns a `VisionResult`, not text.** The image comes back as an
attachment in the conversation; there is no `.text` to print. Ask a specific
question — "is any label cut off, overlapping, or outside its frame?" — and judge
the answer yourself. Do not ask "describe this" and skim.

## Figure design traps

**A toggle that does not change the numbers is decoration.** The example site's
τ-mask toggle was cosmetic — it changed styling but not the computation — until
the walk was split into `runMask` and `runNo`, both computed at load, both
asserted, and the toggle switched between them. Test a toggle by asking: if I
flip this, does any asserted quantity change? If not, either wire it up or take it
out.

**Edge positions need their own wording.** At `k=0` the figure shows the raw
matrix, not "iteration 0 of the walk" — the title had to say so explicitly, or it
implied a normalization had already happened. Check the first and last position of
every slider; that is where the labels are wrong.

**Overlaps are invisible until you measure them.** Two real ones survived
screenshots on the example site and were caught only by the DOM audit: a row
header colliding with its bar (fixed by moving it to the bar's right end) and head
labels overlapping the first bars (fixed by starting them at P4). Run
`scripts/overlap.py` after every figure, not just at the end.

**State the demo's scaling on the page.** A figure that runs 12 positions where
the real system runs 16,384 must say so in the figcaption *and* keep the real
number visible in the same figure. Hiding the scale factor is how an explainer
becomes misleading without a single false sentence.

## The source material

**Check whether the weights are real before you plan around them.** The example
checkout's 48 `.safetensors` files are git-lfs pointers, 134–137 bytes each. There
is not one tensor value on the machine. `model.safetensors.index.json` (7.5 MB)
still gives 96,085 real tensor **names** and a `total_size` — enough to prove
claims about what a layer owns, which is what the page actually needed.

**Cite the config you were given, not the one you found first.** HF repos ship a
flat internal config and a nested HF-style one with the same numbers under
`text_config.*`. Pick one, say which in a comment, and never let a constant appear
in two spellings.

**Some things need a shim.** `build_compressed_token_map` wants an object exposing
`.backend_tokenizer` and `__len__`; HF's `Tokenizer` has no `len()` — use
`get_vocab_size()`.

**Benchmarks are not explanations.** §4.3, §5.3 and Appendix B of the example
report are eval tables. Write the exclusion into the plan at phase 0 so a later
phase does not drift into pasting a leaderboard.

## Git

`git --no-pager …` always — a paged `diff` or `log` hangs waiting for input.
Commit at the end of every phase with `git commit -a -F /tmp/msgN.txt` and your
session id as a trailer. Stage only what belongs to the work: the example repo had
two untracked paths (`topics/ai/game-site/`, `untitled-01.ipynb`) that no session
was ever to touch, so `git commit -a` was safe there but would not be in a repo
with stray build output. Check `git status --short` before you assume.
