# Custom fonts 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:** A person uploads fonts to a library in Slides, picks one for a deck, and every surface shows it behind the font gate, with pictures and the PDF embedding static TrueType faces and falling back otherwise.

**Architecture:** A new package `typeface` in estilo inspects and describes font files. Slides stores a per-person library, records which fonts each deck may serve (as it does for pictures), lists them in the deck's `meta.fontFiles`, loads them through the font gate, and lets the layout and PDF engines use static TrueType faces.

**Tech Stack:** Go (rastrillo, GORM), Rust/wasm CRDT core, Yjs fixtures, esbuild bundles, chromedp browser tests, `github.com/andybalholm/brotli` (for WOFF2), stdlib `compress/zlib` (for WOFF).

**Spec:** `docs/superpowers/specs/2026-11-23-custom-fonts-design.md`.

## Global Constraints

- A font file is at most 10 MiB; a family at most 16 faces; a person at most 32 families.
- Accepted: TTF, OTF, WOFF, WOFF2. Anything else, or anything malformed, is refused before it is stored.
- Pictures and PDF use a face only when it is static, TrueType-outlined, and its `OS/2` fsType allows installable, editable or print-and-preview embedding. Otherwise they fall back to the deck's next font.
- A font is served only through a deck that uses it, and only to someone who can see that deck. A library is visible only to its owner.
- Font files live only in the app's object store, never in a repository, a bundle or an export bundle.
- The gate's rule holds: no flash, and a family late past the deadline commits to its fallback.
- Existing decks render byte for byte as today.
- Every user-facing string is a catalog key and is approved by Paul in copy review before it is written (Task 1).
- Shared machine rules, commit format (subject under 80 characters, body, `Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>`), and `fixtures/*.mjs` under 300 lines, as in the previous slice.

## Review Focus

1. **A font is deleted from the library while decks use it.** Those decks keep showing it. Task 5, `TestDeletingAFontKeepsDecksThatUseIt`.
2. **A deck or link that doesn't use a font asks for it.** It answers 404, including through another person's deck. Task 5, `TestAFontIsServedOnlyThroughADeckThatUsesIt`.
3. **A file that isn't a font, or is truncated, renamed or too big.** It is refused with a clear message and nothing is stored. Task 2 `TestInspectRefuses`, Task 3 `TestUploadRefusesWhatIsNotAFont`.
4. **A family name outside the font-name pattern** (for example `Timeless Sans™` or a non-Latin name). It still works under a safe CSS name. Task 4 vectors, Task 5 `TestAnOddFamilyNameStillLoads`.
5. **A variable font with bold text.** Screens use its weight range; pictures and PDF fall back without error. Task 7, `TestAVariableFontFallsBackInPicturesAndPDF`.

## Calls this plan makes

| # | Call | Why |
|---|---|---|
| F1 | During development Slides points at the estilo worktree with a `replace` directive; Task 8 swaps it for a pushed estilo commit. | estilo has no tags; Slides pins pseudo-versions. |
| F2 | Library uploads go through the app as a form post (multipart), not the signed bucket upload pictures use. | 10 MiB is small enough, and the Fonts page then works with scripts off. |
| F3 | Agents and the API can read `meta.fontFiles` but cannot add a font in this slice. | Fonts belong to a person's library, which the API doesn't expose. |
| F4 | The CSS family name is the font's family name with characters outside `fontPattern` removed, or `Uploaded font N` if nothing is left. | `safeFontStack` must accept it. |
| F5 | A deck refers to a face by its content hash, so deleting a library entry leaves the bytes in place while any deck still refers to them. | Review Focus 1. |

---

### Task 1: Branches and the copy gate

**Files:** none in the repos until the words are approved.

- [ ] **Step 1:** Create the Slides branch `feat/custom-fonts` from `design/custom-fonts`, and an estilo worktree at `~/amadan.net/oficina/estilo-typeface` on branch `feat/typeface` from `origin/main`.
- [ ] **Step 2:** Draft and run the copy review for: the account menu item; the Fonts page title, intro and empty state; the upload form's label, button and hint (the reminder to upload only fonts the person may use on the web); each refusal (not a font, too big, too many faces, too many families, already in the library); the family row's delete action and its confirm page; Deck settings' group label for the person's fonts and its "upload a font" link. Save the approved words as `approved-strings.json` in the plan workspace.

---

### Task 2: The `typeface` package in estilo

**Files:**
- Create: `typeface/typeface.go`, `typeface/woff.go`, `typeface/typeface_test.go`, `typeface/testdata/LiberationSans-Regular.ttf` (copied from Slides `internal/slides/fonts/files/`, SIL OFL)
- Modify: `go.mod`, `go.sum` (add `github.com/andybalholm/brotli`)

**Interfaces (produced):**

```go
package typeface

const MaxBytes = 10 << 20
const MaxFacesPerFamily = 16
const MaxFamilies = 32

type Format string // "ttf", "otf", "woff", "woff2"
type Outline string // "truetype", "cff"

type Face struct {
    Ref       string  // lowercase hex SHA-256 of the file
    Format    Format
    Outline   Outline
    Family    string  // name ID 16, else 1
    Style     string  // name ID 17, else 2
    Weight    int     // OS/2 usWeightClass, 1..1000
    WeightMin int     // = Weight unless variable
    WeightMax int
    Italic    bool    // OS/2 fsSelection bit 0 or head macStyle bit 1
    Variable  bool    // fvar present with a 'wght' axis
    FSType    uint16  // OS/2 fsType
}

var ErrNotAFont, ErrTooBig, ErrMalformed error

func Inspect(data []byte) (Face, error)
func (f Face) Pictures() bool        // static, truetype, embedding allowed
func (f Face) ContentType() string    // font/ttf, font/otf, font/woff, font/woff2
func Headers(w http.ResponseWriter, f Format)
```

`Pictures()`: not `Variable`, `Outline == "truetype"`, format `ttf` or `otf`, and fsType allows embedding (bits 0x0002 restricted-licence alone means no; 0x0200 bitmap-only means no). `Headers` sets the content type, `X-Content-Type-Options: nosniff`, `Cache-Control: public, max-age=31536000, immutable`, and `Content-Security-Policy: default-src 'none'`.

- [ ] **Step 1: Write the failing tests**, building WOFF and WOFF2 copies of the test TTF inside the test (WOFF with zlib; WOFF2 with brotli and null-transformed `glyf`/`loca`), plus synthetic sfnts for CFF (`OTTO` with a stub `CFF ` table), variable (an `fvar` with a `wght` axis 100–900) and restricted fsType:
  `TestInspectReadsTheNamesAndStyle` (family `Liberation Sans`, weight 400, not italic, truetype, ttf);
  `TestInspectReadsWOFFAndWOFF2` (same answers as the TTF);
  `TestInspectReadsCFFAndVariable`;
  `TestPicturesOnlyForStaticTrueTypeThatMayEmbed`;
  `TestInspectRefuses` (empty, a PNG, a truncated table directory, a table past the end, over `MaxBytes`, a WOFF2 whose brotli stream is bad).
- [ ] **Step 2:** `go test ./typeface/ -count=1` — Expected: FAIL, undefined.
- [ ] **Step 3: Implement.** Read only the table directory, `head`, `name`, `OS/2`, `fvar`; bounds-check every offset; never trust a length.
- [ ] **Step 4:** `go test ./typeface/ -count=1` then `make test` in estilo — Expected: PASS.
- [ ] **Step 5: Commit** in estilo: `typeface: inspect TTF, OTF, WOFF and WOFF2 font files`.

---

### Task 3: The library in Slides

**Files:**
- Create: `internal/slides/library.go`, `internal/slides/templates/fonts.html`, `fonts_confirm.html`, `internal/slidestest/library_test.go`
- Modify: `go.mod` (`replace amadan.net/oficina/estilo.git => ../estilo-typeface`, F1), `internal/slides/models.go`, `chrome.go:261`, `app.go` (routes inside the signed-in group), `locales/en.toml`; generate `migrations/0011_*.sql`

**Interfaces (produced):**

```go
type LibraryFont struct { // table library_fonts
    ID        uint
    Owner     string // the person's actor id, indexed
    Family    string
    CSSName   string // F4
    Ref       string // typeface.Face.Ref; unique with Owner
    Format, Outline, Style string
    Weight, WeightMin, WeightMax int
    Italic, Variable, Pictures bool
    Size      int64
    CreatedAt time.Time
}
func fontObjectKey(ref string) string // "fonts/" + ref
func cssFamilyName(family string, n int) string // F4
```

Routes: `GET /fonts` (page), `POST /fonts` (multipart field `file`, one or more files), `GET /fonts/delete?family=<css>` (confirm page), `POST /fonts/delete` (form field `family`). Uploading stores the bytes at `fontObjectKey(ref)` through `a.cfg.Blobs` and writes a row per face. Without a store the page says fonts are unavailable (503 for the POST).

- [ ] **Step 1: Write the failing tests:** `TestUploadAFontAndSeeItListed`, `TestUploadRefusesWhatIsNotAFont` (PNG renamed `.ttf`, 11 MiB, truncated: each a 422 with its approved message and no row or object), `TestTheLibraryLimits` (17th face, 33rd family), `TestALibraryIsOnlyItsOwners`, `TestDeletingAFamilyRemovesItsRows` (and its objects, since no deck refers to them yet), `TestTheFontsPageWorksWithoutScripts`, `TestTheAccountMenuListsFonts`.
- [ ] **Step 2:** Run them — FAIL.
- [ ] **Step 3: Implement;** generate the migration with `go run amadan.net/rastrillo/rastrillo/cmd/rastrillo migration generate` and read it.
- [ ] **Step 4:** `go test ./internal/slidestest -run 'Font|Library|Account' -count=1` — PASS; `make migration-check` — PASS.
- [ ] **Step 5: Commit:** `Fonts: a library of your own fonts`.

---

### Task 4: `meta.fontFiles` in the document

**Files:** `core/src/ops.rs`, `core/src/view.rs`, `core/tests/ops.rs`, `fixtures/ops-parse.mjs`, `ops-apply.mjs`, `view.mjs`, `fixtures/data/canvas.json`, `internal/slides/deck/deck.go`, `docs/api.md`; regenerate vectors and both wasm binaries.

**Interfaces (produced):**
- View key `meta.fontFiles`, omitted when absent: `[{family: string, css: string, faces: [{ref: string, format: string, weight: [min, max], italic: bool, pictures: bool}]}]`.
- `set_meta{fontFiles: [...] | null}`; null removes it. Checks: at most 32 families and 16 faces each; `ref` matches `^[0-9a-f]{64}$`; `css` matches `fontPattern`; weights 1–1000 with min ≤ max; `format` one of ttf, otf, woff, woff2. A wrong-typed value is dropped by the view.
- Go: `deck.Meta.FontFiles []deck.FontFamily`, `deck.FontFamily{Family, CSS string; Faces []deck.FontFace}`, `deck.FontFace{Ref, Format string; Weight [2]int; Italic, Pictures bool}`.

- [ ] **Step 1: Write the failing tests** in Rust and JS: round-trip and clear; each refusal above; a deck without it has no key. Add one `fontFiles` to a new slide's meta in `canvas.json`.
- [ ] **Step 2:** `cd core && cargo test --test ops -- font` — FAIL.
- [ ] **Step 3: Implement,** regenerate vectors (`cd fixtures && node generate.mjs`), rebuild the wasm (`./scripts/build-wasm.sh`, copy) and the PDF wasm if its inputs changed.
- [ ] **Step 4:** `go test ./internal/slides/core ./internal/slides/deck -count=1`, `cd fixtures && node --test` — PASS.
- [ ] **Step 5: Commit, then the gate:** `Document: meta.fontFiles lists a deck's uploaded fonts`.

---

### Task 5: Using a font in a deck, and serving it

**Files:**
- Create: `internal/slides/deckfonts.go`, `internal/slidestest/deckfonts_test.go`, `fixtures/deck-fonts.mjs`
- Modify: `models.go` (`DeckFont{ID, DeckID, Ref}` unique on both; migration `0012_*`), `app.go` (routes), `templates/editor.html:957-975`, `fixtures/inspector.mjs`, `fixtures/inspector-ops.mjs`, `editor.go` (pass the person's families to the template)

**Interfaces (produced):**
- `POST /d/{sqid}/fonts` with `{family}`: the signed-in editor of the deck who owns that family in their library; writes `DeckFont` rows for each face and answers the `deck.FontFamily` JSON. The browser then applies one batch: `set_meta{fontFiles: <existing + this family>, fonts: {heading|body: "'<css>', <current theme stack>"}}`.
- `GET /d/{sqid}/fonts/{ref}`, `/s/{token}/fonts/{ref}`, `/p/{session}/fonts/{ref}`: 404 unless a `DeckFont` row exists for the deck and the ref is in the deck's `meta.fontFiles`; then the bytes with `typeface.Headers`. Parked-slide rules don't apply (fonts are deck-wide).
- Deck settings: each font select gains an optgroup of the person's library families and a link to `/fonts` (new tab). Choosing the theme's font again removes that family from `fontFiles` when neither role uses it.

- [ ] **Step 1: Write the failing tests:** `TestPickingAFontRecordsItForTheDeck`, `TestAFontIsServedOnlyThroughADeckThatUsesIt` (another deck, another person's deck, a share link of a deck without it: 404; viewer, share link and presenter of the deck with it: 200, the right content type, `nosniff`), `TestOnlyTheLibraryOwnerCanAddTheirFont`, `TestDeletingAFontKeepsDecksThatUseIt` (deleting a family keeps any object a `DeckFont` row refers to, and those decks still serve it; this also changes Task 3's delete), `TestAnOddFamilyNameStillLoads`, and a browser test `TestDeckSettingsOffersYourFonts`.
- [ ] **Step 2:** Run — FAIL.
- [ ] **Step 3: Implement;** rebuild the editor bundle and credits.
- [ ] **Step 4:** `go test ./internal/slidestest -run 'Font|DeckFont' -count=1` and the browser test — PASS.
- [ ] **Step 5: Commit, then the gate:** `Slides: use a font from your library in a deck`.

---

### Task 6: The gate loads uploaded fonts

**Files:** `internal/slides/fontgate.go:73-102`, `render/families.go`, `render/render.go` (stacks), `fixtures/font-families.mjs`, `font-session.mjs`, `fonts-gate.mjs`, `fixtures/vectors/font-families.json`, `render/families_test.go`, `fixtures/font-families.test.mjs`, `internal/slidestest/fontgate_test.go`, `fonts_browser_test.go`

**Interfaces:**
- `gateManifest` gains `Uploaded map[string]gateFamily` keyed `"u:" + css`; `gateFace` gains `Format string` and a weight range (`Weight` becomes the CSS `"min max"` string for variable faces). URLs use the surface's base (`/d/{sqid}`, `/s/{token}`, `/p/{session}`) plus `/fonts/{ref}`.
- `FamiliesUsed` and `familiesOfView` return uploaded keys (`"u:<css>"`) beside the catalog keys when a deck stack names an uploaded family; the shared vectors gain cases for an uploaded family in heading, in body, unused, and an odd name.
- `font-session.mjs` uses each face's own `format(...)`.

- [ ] **Step 1: Write the failing tests:** the new vector cases (Go and JS), `TestTheManifestListsTheDecksUploadedFaces`, browser `TestAnUploadedFontIsNotPaintedBeforeItLoads` and `TestALateUploadedFontCommitsToItsFallback`.
- [ ] **Step 2:** Run — FAIL.
- [ ] **Step 3: Implement;** rebuild the gate bundle and credits.
- [ ] **Step 4:** Unit and browser runs (`-run 'Font'`) — PASS; existing font tests unchanged.
- [ ] **Step 5: Commit, then the gate:** `Fonts: the gate waits for a deck's uploaded fonts`.

---

### Task 7: Pictures and PDF

**Files:** `internal/slides/fonts/fonts.go`, `fonts/truetype.go` (read `name`/`OS/2` only if needed), `layout/layout.go:66-110`, `layout/text.go`, `layout/blocks.go`, `svg/svg.go:264`, `export.go:172-176`, `thumbs.go`, their tests

**Interfaces:**
- `fonts.Face` gains an optional uploaded face: `fonts.Face{Family, Bold, Italic, Uploaded *fonts.Uploaded}`, `fonts.Uploaded{CSS string; Weight int; Italic bool; Font *fonts.Font}`; `Advance`, `Metrics` and `Stack()` use it when set.
- `layout.Options{Fonts func(ref string) ([]byte, error)}`; `faceFor` picks an uploaded face when the deck stack's first name is an uploaded family and a face with `Pictures` true exists for the weight/italic needed; otherwise the next name in the stack, as today, with no warning for an uploaded family it skips.
- `Export` adds the uploaded faces' bytes to `faces` for the PDF; the PDF engine already matches by family, weight and style from the SVG.

- [ ] **Step 1: Write the failing tests:** `TestAStaticTrueTypeUploadIsMeasuredAndDrawn` (SVG names the family; a run's width matches the font's advances), `TestTheExportEmbedsAnUploadedFace` (`/FontFile2` and the font's PostScript name in `/BaseFont`), `TestAVariableFontFallsBackInPicturesAndPDF`, `TestARestrictedFontFallsBack`, `TestAWOFF2FallsBack`, and `TestExistingDecksRenderUnchanged` (goldens).
- [ ] **Step 2:** Run — FAIL.
- [ ] **Step 3: Implement.** Load uploaded faces once per render through `Options.Fonts` (blob read by `fontObjectKey`), parse with `fonts.Parse`, and keep them only for that render.
- [ ] **Step 4:** `go test ./internal/slides/... -count=1` — PASS.
- [ ] **Step 5: Commit, then the gate:** `Fonts: pictures and the PDF use uploaded TrueType faces`.

---

### Task 8: Docs, the estilo pin, and the whole check

**Files:** `AGENTS.md` (fonts, the library, the gate), `docs/api.md` (`meta.fontFiles`, F3), `go.mod`, `go.sum`

- [ ] **Step 1:** Update `AGENTS.md` and `docs/api.md`.
- [ ] **Step 2:** With Paul's yes, push estilo `feat/typeface`; in Slides replace the `replace` directive with `go get amadan.net/oficina/estilo.git@<that commit>` (estilo's merge to main follows Paul's separate yes).
- [ ] **Step 3:** `make ci`, the gate, `node --test`, and the full browser suite once; expected failures only the 12 known on main.
- [ ] **Step 4:** Walk it once by hand in a browser against a local app on `127.0.0.1`: upload Liberation Sans as a library font under another name, use it in a deck, open the viewer, a share link and the presenter, export a PDF. Stop the server; remove scratch.
- [ ] **Step 5: Commit:** `Docs: custom fonts`.
