# Site media manifest and import

The site's own images, videos and PDFs stay in `core/web/public/{i,v,d}`, tracked in git, and are served at their own paths (`/i/…`, `/v/…`, `/d/…`, the Nuxt public dir). `core/web/content/media.json` is the reviewed metadata for them: one entry per file, with a fixed id, a human name and the owner's title and alt text. The media catalog (SQLite + filesystem locally, DynamoDB + S3 in production) is for new and admin media, not for these files.

This page covers part 1 (PR 5): the metadata policy, the sanitizer, the manifest and the import CLI, and part 2a: [rendering reads the manifest for metadata only](#rendering-metadata-only-part-2a). Part 2b added admin title / alt editing and rename, turned `enforceMetaPolicy` on by default and sends admin uploads through the sanitizer ([media.md](../../packages/media.md#rename), [admin.md](./admin.md#local-media-library-dam)). None of that touches site media: admin edits and renames work on catalog assets, and the site's files are not in the catalog, so their paths, titles and alt text change only in `public/{i,v,d}` and `media.json`.

**Owner decision 2026-10-17.** Site media is not moved into the catalog: no `/m/` URLs for it, no 301s from the public paths, and no site import before a deploy. CD keeps uploading `public/{i,v,d}` through the typed sync for good ([cicd.md](../../cicd.md#no-media-work-in-github-actions)). The labs stay at `/d/htm/…`, and `scripts/enrich-image-meta.mjs` stays in use for content LQIPs and aspect ratios.

## Intentional case-study paths (do not flag)

The tesseract images in two case studies use `/i/portfolio/tesseract/…` paths on purpose (owner decision, #279), although the files live at `core/web/public/i/tesseract/`:

- `core/web/content/case-studies/spatial-experiences.json`: `blue-8-cell-simple.png` and `schlegel-wireframe-8-cell.png`
- `core/web/content/case-studies/innovation-prototyping.json`: the video poster `blue-8-cell-simple.png`

The owner confirmed these paths on 2026-10-14 without a visual check. The Docker test stack (`http://localhost:4300`) serves no static files at all (`/_nuxt/*`, `/i/*` and `/_ipx/*` return 404 or 502; tracked in Phase 9b of `docs/superpowers/plans/2026-10-01-prod-readiness-docker-media.md`), and the deployed test environment predated #279 at the time. (Since 2026-10-19 the `docker:test` `cdn` stand-in serves `public/`, including `/_ipx/*`: [docker/README.md](../../../docker/README.md).)

Other content still points at `/i/tesseract/…` (for example the `spatial-experiences.json` video poster, `gallery.json`, `content/media.json` `legacyPath` and `shared/tesseract.ts`). That mix is intentional as well. Don't "align" the two prefixes in either direction.

Do not move the files, rewrite the paths, restore the file-exists checks that #279 removed from `core/web/tests/portfolio-content.spec.ts` and `core/web/tests/work-card-media.spec.ts`, or report the paths (or the mixed prefixes) as broken or inconsistent. `core/web/tests/tesseract-media-paths.spec.ts` keeps the paths and this note in place.

## Case-study diagrams show whole

Case-study media is framed at the theme's `--media-ratio` with `object-fit: cover` (`core/web/app/pages/work/case-study.scss`). On portrait screens that ratio is 9:16, which is right for photos and video but cut a 16:9 flow diagram to its middle third on a 375px phone. `AppCaseStudyMedia` marks SVG diagrams (`"type": "diagram"`, which must be an SVG, or any SVG `src`) with `data-media-kind="diagram"`; the hero and the Artifacts grid show those at the file's own ratio (`aspect-ratio: auto 16 / 9`, the 16:9 reserved until the file loads) with `object-fit: contain`. Photos and video keep the frame and the crop. Fixed 2026-10-19; `core/web/tests/case-study-diagrams.spec.ts` keeps it (and checks that every SVG in `content/case-studies` is typed `diagram` and every `diagram` is an SVG). Old styles: `theme/core/scss/_archive/2026-10-19-case-study-diagrams/`.

## Manifest

```json
{
  "version": 1,
  "entries": [
    {
      "id": "…uuid…",
      "tenant": "portfolio",
      "kind": "image",
      "name": "profile-pic-1",
      "ext": "jpg",
      "path": "m/pf/i/profile-pic-1.jpg",
      "title": "Tamara Mack portrait",
      "alt": "Portrait of Tamara Mack smiling, …",
      "description": null,
      "credit": "Tamara Mack",
      "sha256": "…of the sanitized bytes…",
      "width": 1024,
      "height": 1024,
      "durationSec": null,
      "lqip": "data:image/webp;base64,…",
      "dominantColor": "#cece9f",
      "variants": [],
      "legacyPath": "/i/profile_pic_1.jpg",
      "reviewNotes": ["check: …"]
    }
  ]
}
```

| Field                                      | Rule                                                                                                                                                                  |
| ------------------------------------------ | --------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `id`                                       | UUIDv5 of `legacyPath` (`siteMediaId`). Stable across reruns and identical in every backend. Never edit it once imported.                                             |
| `name`, `ext`, `path`                      | `normalizeMediaFilename` of the original filename (generator and camera prefixes dropped), `-2`, `-3` on collisions; `path` is `m/pf/{kind code}/{name}.{ext}`.       |
| `title`, `alt`, `description`, `credit`    | Owner-reviewed text, checked by `validateMediaMeta` (title 3–80 characters, alt ≤150 and required for images and SVGs, description ≤300, no filenames or vendor ids). |
| `sha256`, `width`, `height`, `durationSec` | Computed from the **sanitized** bytes. Don't edit by hand.                                                                                                            |
| `lqip`, `dominantColor`                    | Computed for images and SVGs (`ingestImage`). `null` for video and documents.                                                                                         |
| `variants`                                 | Ready catalog variants (`t`, `640`, `1280`, `1920`) for `srcset`. Empty until they are materialized; `--from` exports fill it.                                        |
| `legacyPath`                               | The file's public path, as content references it. Must start with `/`; `.` / `..` segments and backslashes are rejected (the import reads `<source><legacyPath>`).    |
| `reviewNotes`                              | Draft checklist. The import refuses entries that still have notes; notes are never imported.                                                                          |

Types and the validator live in `@tgmc/media` (`SiteMediaEntry`, `validateSiteManifest`, `serializeSiteManifest`). The validator is strict: unknown keys, a `path` that does not match `kind` / `name` / `ext`, an `ext` whose type does not belong to `kind` (`image` + `.pdf`), duplicate ids, names or legacy paths are structural errors; metadata policy issues are reported separately so a draft can still be written.

## Review workflow

```bash
npm run build:libs
npm run media:site-manifest -- --draft --review-out tmp/site-media-review.md
```

`--draft` reads every file under the source (`--source <dir>`, default `data/media-source/` when it exists, else `core/web/public`; folders starting with `.` or `_` are skipped, non-media files such as the HTML labs are listed under `skipped`, and files the overrides exclude under `excluded`). For each file it:

1. Detects the real format from the bytes (a `.png` that is really an animated GIF becomes `.gif`).
2. Pre-fills the title (gallery item title, then the SVG `<title>`, then the filename), alt (the longest content alt that fits) and description (the longest caption that fits, else the SVG `<desc>`), from every content JSON file under `core/web/content/` (except `media.json` itself, and `--out`) and quoted paths in `core/web/{app,shared,server}`.
3. Sanitizes the bytes ([sanitizer](../../packages/image.md#sanitize-media-before-it-is-stored)), then records the sha256, dimensions, duration and LQIP.
4. Adds notes: `check:` (an owner decision: generated title, several content alts, a borrowed gallery title, a changed extension, a renamed collision, a generated-media credit), `unused:` (nothing references the file), `duplicate:` (same sanitized bytes as another file) and `invalid:` (fails the metadata policy).

`--review-out` writes a Markdown table with each entry's legacy and new path, title, alt, description, credit and review notes, so every field the owner signs off on is visible in one place.

The owner edits `media.json` directly: fix titles, alt text, descriptions and credits, delete each note once resolved, then rerun `--draft`. A rerun keeps each existing entry's id, name, editorial fields, variants and the owner's remaining `check:` notes, and recomputes the bytes, dimensions, LQIP and the automatic `unused:` / `duplicate:` / `invalid:` notes. `kind` and `ext` always follow the sniffed bytes: when a source changes format (say the animated GIF named `.png` is replaced by a real PNG), the entry moves to the new extension (and kind code), its `variants` are reset, a name already taken in the new kind gets `-2`, and a `check: format changed: …` note asks for review. Its summary lists `changed` (sha256 differs from the committed manifest) and `dropped` (no longer in the source).

PDFs embed the title, credit (Author) and description (Subject) in the sanitized file, so **editing a PDF's title changes its sha256**: rerun `--draft` before importing.

### Overrides

Decisions a rerun must not undo live in `core/web/site-media.overrides.json` (committed; outside `content/` so it is never scanned as content; `--overrides <file>` points elsewhere):

```json
{
  "exclude": { "/i/portfolio/social-card.png": "why it is not imported" },
  "entries": {
    "/d/Resume2026.pdf": { "name": "Tamara Mack-resume-2026" },
    "/v/portfolio/generated/vimg-tesseract-framework.mp4": { "credit": "Tamara Mack (AI-assisted)" }
  }
}
```

- `exclude` — legacyPath → reason. The file stays on disk but gets no entry (summary `excluded`, not `dropped`), and stops causing `duplicate:` notes.
- `entries.<legacyPath>.name` — wins over the drafted and the previous name; the id stays the UUIDv5 of the legacyPath. Lowercase words joined by `-`; a name another file already uses is an error.
- `entries.<legacyPath>.credit` — replaces the credit and clears the `check: generated media; confirm the credit` note. For PDFs it is also written as the Author.

Unknown keys are errors; overrides for paths that are not in the source are listed under `staleOverrides`. Titles, alt text and descriptions are edited in `media.json` itself (a rerun keeps them).

`npm run media:site-manifest -- --from <endpoint>` exports the manifest back from a catalog (assets tagged `site`), including ready variants. Endpoints are `media:transfer`'s `sqlite:<dir>` or `aws:<table>@<bucket>` with `--region`, `--dynamodb-endpoint`, `--s3-endpoint`, `--path-style`. `postgres:` is refused (the site CLIs have no `--blobs`); to seed a Postgres catalog, import into `sqlite:` and `media:transfer` from there.

## Rendering: metadata only (part 2a)

Content and code keep referencing site media by its public path, exactly as before (`"src": "/i/portfolio/manhattan-2150-keyframe.png"`); `UiImage` and Nuxt Image (IPX, `sizes` → `srcset`) are unchanged. The manifest's `path` (`m/pf/…`) is only the catalog key the optional import writes; the site never requests it. The manifest adds metadata:

- **`useSiteMedia()`** (`app/composables/useSiteMedia.ts`) and `resolveSiteMedia(pathOrId)` (`#shared/site-media`, pure and SSR-safe) return `{ id, kind, url, alt, title, width, height, aspectCss, missing }` for a public path or a manifest id. `url` is always the public path. An unknown path comes back unchanged with `missing: true` (dev builds warn once); an unknown id gets a transparent 1x1 GIF.
- **Client map.** The browser never loads `media.json`. `core/web/shared/site-media-map.json` holds only `id`, `path` (the public path), `kind`, `ext`, `title`, `alt`, `width` and `height` per entry: no review notes, hashes, descriptions, credits or LQIPs (content already carries its LQIPs and aspect ratios from `enrich-image-meta`). `npm run media:site-manifest -- --draft` rewrites it with the manifest; `npm run media:site-map` regenerates it alone. `scripts/site-media-client-map.test.js` (CI) fails when it is out of step with `media.json`, and `core/web/tests/site-media.spec.ts` fails if client code imports `media.json`.
- **Where the metadata shows today.** The manifest alt and title surface only in `og:image:alt` / `twitter:image:alt` of the default social image. On the page, content's own `alt` (and components' computed alt, such as the about portrait) wins; `UiImage` and the gallery components do not read the manifest; `AppCaseStudyMedia` reads only a raster's dimensions, for its width ladder ([Responsive sizes and format](#responsive-sizes-and-format)).
- **Default social image.** Without a page `image`, or when the page image is an SVG or a video (crawlers do not render those; five of the six case studies lead with an SVG diagram), `usePortfolioSeo` uses the `manhattan-2150-keyframe` file (`siteSocialImage(siteUrl, pageImage)`). A raster page image is used as given, absolute on the site URL, without the default's width, height, type or alt. The default: `og:image` / `twitter:image` = site URL + `/i/portfolio/manhattan-2150-keyframe.png` (absolute), with `og:image:width` 1672, `og:image:height` 941, `og:image:type` `image/png` and the manifest alt as `og:image:alt` / `twitter:image:alt`. The file is tracked in `public/`, so every build, the tamaramack.github.io copy included, serves it. (`/i/portfolio/social-card.png`, the old default, has the same bytes and is excluded from the manifest.)

### Content guard

`core/web/tests/site-media-guard.spec.ts` scans `core/web/content` (JSON, Markdown, YAML), `core/web/app` (Vue, TS, SCSS), `core/web/assets` (SCSS), `core/web/shared` and `core/web/server` (TS), the Nuxt layers web extends (`packages/nuxt-layer-base` `app` / `scss` / `src` and `packages/nuxt-layer-ui` `app` / `src`, plus both `nuxt.config.ts`) and `core/web/nuxt.config.ts` (not `media.json` or the client map). Every `/i/…`, `/v/…` or `/d/…` path it finds, after a quote, bracket, `=`, `,`, `:`, `}` (as in `` `${base}/i/x.png` ``) or whitespace, must be a manifest `legacyPath`, so every site file on the page has reviewed metadata. A self-test pins what the pattern catches and that an unknown path is flagged.

Allowlist (permanent):

| Path                                                 | Why                                                                                     |
| ---------------------------------------------------- | --------------------------------------------------------------------------------------- |
| `/i/tesseract/…`, `/i/portfolio/tesseract/…`         | [Intentional case-study paths](#intentional-case-study-paths-do-not-flag) (owner, #279) |
| `/d/htm/adv_wire_tess.html`, `/d/htm/wire_tess.html` | HTML labs (pages, not media), served from `public/d/htm/`                               |

A new site image: add the file under `public/`, rerun `npm run media:site-manifest -- --draft`, review its title and alt in `media.json`, then reference its public path.

## Import

The import is optional tooling: it copies the site's media into a catalog (for example to try admin features against real files). The site never reads site media from the catalog, so no environment needs it, and it is **not** a deploy prerequisite.

```bash
# rehearsal against a scratch catalog (imports entries that still have notes)
npm run media:site-import -- --to sqlite:./data/site-media-rehearsal --allow-unreviewed
# production, after the review
npm run media:site-import -- --to aws:<table>@<bucket> --dry-run
npm run media:site-import -- --to aws:<table>@<bucket>
```

For each entry the import checks that `<source><legacyPath>` exists and is media, then (`importSiteMedia` in `@tgmc/media`):

- **Refuses** entries with `reviewNotes` (unless `--allow-unreviewed`) or metadata policy failures (`refused` in the report).
- **Skips** entries the target already has with the same id, path and manifest `sha256` (and its object), before the file is sanitized, so a rerun after a sharp / svgo / ffmpeg upgrade stays idempotent and needs no ffmpeg when every video is already imported.
- Sanitizes the rest exactly as the draft did (a sanitizer error, such as no ffmpeg for an MP4, fails that entry only).
- **Fails** entries whose sanitized bytes do not hash to the manifest `sha256` (the manifest is stale, or the tool versions changed: rerun `--draft` and review the diff).
- Copies the rest through `transferMedia`, so it inherits the transfer's safety: the name is held on the target, objects are written create-only and re-hashed there, an existing asset with the same id, sha256 and path is **skipped** (reruns are safe), and anything else at that id, name or key is a **conflict**, never overwritten. Rows keep the manifest id, name and path; `meta` carries `tags: ['site']`, `filename`, the editorial fields, dimensions, LQIP and `legacyPath`. Each written asset gets an `asset.site_imported` audit event.

It prints a JSON report (`copied`, `skipped`, `conflicts`, `conflictReasons`, `failed`, `refused`) and exits 1 when anything was refused, conflicted or failed, 2 on bad arguments. A dry run opens a `sqlite:` target read-only and writes nothing.

**The import is create-only, not a sync.** Once an entry is imported, editing its title, alt text, description or credit in `media.json` and re-importing does **not** update the catalog: the entry is skipped (same id, path and sha256), or for a PDF, whose sanitized bytes embed the title and credit, reported as a conflict. Admin's **Details** and **Rename…** can edit the imported copies, but they change only the catalog; the site keeps serving `public/{i,v,d}` with the metadata in `media.json`. `--from` exports the catalog back into `media.json` when the two should be brought in step.

### Production import runbook

Only if a production catalog should hold the site's media; nothing on the site depends on it.

1. Run it on the machine and OS that produced the committed draft (Windows today), with the same ffmpeg (`ffmpeg -version`, or pin `FFMPEG_PATH`) and the same `node_modules` — sanitized bytes, and so every sha256, depend on them.
2. `npm run build:libs`, then `npm run media:site-import -- --to aws:<table>@<bucket> --dry-run`. Expect `failed: []`, `conflicts: []` and `refused: []` (any `refused` entry still has review notes).
3. Only then run the same command without `--dry-run`, and keep the JSON report.

## Tooling notes

- **ffmpeg.** MP4 remuxing runs ffmpeg as a separate process, resolved by `resolveFfmpegPath` (`@tgmc/image/sanitize`): `FFMPEG_PATH`, then `ffmpeg` on `PATH`, then the optional `ffmpeg-static` package (root `optionalDependencies`; `allowScripts` lets its install script download the binary; its own `FFMPEG_BIN` variable overrides the binary it reports). With none of them, sanitizing an MP4 fails with a message saying so; other formats don't need ffmpeg. Licence: the ffmpeg-static binary is GPL-3.0-or-later; it is only executed by local scripts, never linked, bundled into `core/web` / Nitro / Lambda, or redistributed.
- **Determinism.** The sanitized sha256 depends on the sharp / svgo / pdf-lib / ffmpeg versions (and can depend on the platform): for example `vimg-tesseract-framework.mp4` remuxes to different bytes under ffmpeg 6.1 (ffmpeg-static) and 8.1. After upgrading any of them, rerun `--draft`; the import fails loudly rather than storing bytes that differ from the manifest (entries already imported are skipped first).
- **Code.** `scripts/site-media-{cli,client-map,draft,content,review}.js` have no workspace imports and are tested under `node --test` in CI (`scripts/site-media-*.test.js`); `scripts/site-media-{manifest,import,io}.js` wire in `@tgmc/media` and `@tgmc/image` and need `npm run build:libs`.

## Resized images on the CDN

On AWS the Lambda serves no `public/` files (`serveStatic: false`) and so cannot resize them either. A site-root path in the HTML went API Gateway → Lambda, and `server/middleware/cdn.ts` answered with a 302 to CloudFront: about 0.16 s per image before the download, and 1.8–2.6 s for the case-study SVG diagrams. Resized images (`/_ipx/…`) were worse: nothing generated them, so CloudFront returned 403. With a CDN on an `aws_lambda` build (`NUXT_APP_CDN_URL` at build time, which CD sets), site media now goes to the CDN directly:

| Media                                         | URL in the HTML                                  | Comes from                            |
| --------------------------------------------- | ------------------------------------------------ | ------------------------------------- |
| Rasters (`UiImage` → `NuxtImg`)               | `<cdn>/_ipx/w_<ladder width>/<path>`             | `public/_ipx/`, written at build time |
| Rasters asked for as WebP (`format="webp"`)   | `<cdn>/_ipx/w_<ladder width>&f_webp/<path>.webp` | `public/_ipx/`, written at build time |
| SVG diagrams (`UiSvgImg`), videos and posters | `<cdn>/<path>` (`usePublicAssetUrl`)             | `public/` as is                       |

- **Width ladder** (`shared/ipx-variants.ts`). `IPX_VARIANT_WIDTHS` is the one list both sides use. The `cdnIpx` provider (`app/providers/cdn-ipx.ts`) snaps the width `NuxtImg` asks for up to the smallest rung that covers it and drops the height, so the source aspect ratio is kept and `UiImage` crops in CSS (`object-fit: cover`). The URL is the same on server and client; absolute, protocol-relative and `data:` sources pass through.
- **Formats** (`IPX_VARIANT_FORMATS`, today `['webp']`). A `format` modifier in that list links the converted variant, `w_<width>&f_webp/<path>.webp`; any other format (or the source's own) links the same-format one. The `.webp` extension is there because the S3 sync sets each object's `Content-Type` from its extension (`scripts/sam-aws-helpers.mjs`), and it keeps `a.jpg` and `a.png` from sharing a key.
- **Build step** (`config-properties/ipx-variants.ts`, run from the `nitro:build:public-assets` hook in `nuxt.config.ts`). Every raster in `content/media.json` (by `legacyPath`) is written at every rung with sharp into Nitro's `public/_ipx/`, keeping its format and never enlarged, and once more as WebP when it is not WebP already. The usual S3 sync uploads them with `Content-Type: image/webp` for the `.webp` files and the short `Cache-Control` (`public, max-age=3600, must-revalidate`) of every unversioned public file. A source path with no file in `public/` is logged and gets no variant (its URL answers 403/404, as before). Today: 8 rasters × 7 widths = 56 same-format files, plus 5 non-WebP rasters × 7 widths = 35 WebP files (91 files, about 31.5 MB; the WebP set is 2.6 MB). The animated GIF (`/i/tesseract/blue-8-cell-simple.png`, sniffed `ext: gif`) is not a raster to the build step and gets no `_ipx` variant.
- **A raster outside the manifest** gets no variants. Add it to `content/media.json` ([review workflow](#review-workflow)) before using it in `UiImage`.
- **Public files.** `usePublicAssetUrl()` (`@tgmc/nuxt-layer-ui`) prefixes `runtimeConfig.app.cdnURL` to site-root paths. Nuxt itself rewrites only literal template paths, never runtime `:src` values or `NuxtImg` sources ([research note](../../solutions/architecture-patterns/nuxt-public-assets-on-cdn.md)). URLs with a scheme, protocol-relative, `data:` and `blob:` URLs pass through, and so does everything when no CDN is set. No folder is special-cased and the path text never changes.
- **Other builds** (dev, node-server, no CDN) keep the stock ipx provider and its `/_ipx` handler. The CDN middleware still 302s static paths, which catches old cached HTML and any call site that is not converted.
- **docker:test.** The `cdn` service (nginx, `127.0.0.1:4301`) stands in for CloudFront and serves `public/`, `_ipx/` included. Build with `NUXT_APP_CDN_URL=http://localhost:4301` to get the AWS behaviour ([docker/README.md](../../../docker/README.md)).
- **Why not prerender the variants or resize on the Lambda?** Tried and dropped on 2026-10-19: the Lambda's ipx has no source files, a CloudFront failover to it is a circular dependency in `infra/sam/template.yaml` (`cfn-lint` E3004), and Nitro hung on the ipx routes during prerender while the build still exited 0. Details in the research note.

## Responsive sizes and format

`UiImage` has two modes.

- **Default (NuxtImg).** `sizes` is Nuxt Image's syntax (mobile-first: `key:size` applies from the `key` px width up, values in `vw` or `px`, no `calc()`), and NuxtImg builds the `sizes` attribute and its srcset from it: each value × the densities (1×, 2×). `format` (`webp` …) is forwarded. Every existing caller uses this mode, unchanged.
- **`widths`.** With a list of candidate file widths, `UiImage` renders a plain `<img>`: `sizes` is a native `sizes` string, passed through as is, and the srcset is a `w`-descriptor ladder built with the Nuxt Image URL builder (`$img`) in the requested `format`, each candidate cropped to `width` / `height`'s ratio when both are set. A native string can use em media conditions and rem / `calc()` lengths, which NuxtImg's syntax cannot (its media are px, so they drift from the theme's em breakpoints when the reader's default font size is not 16 px). Stop `widths` at the source's width: nothing is upscaled, so a larger descriptor would overstate the file. In development `UiImage` warns when `widths` comes without `sizes` (the browser would assume 100vw).

`$img` comes from @nuxt/image's `image: { inject: true }`, set on both image configs in `core/web/nuxt.config.ts`; the layer does not depend on @nuxt/image. Without it (an app without `inject`, such as `core/admin` today) `widths` is ignored and NuxtImg renders the image with its own srcset; the native `sizes` is then not passed on, since NuxtImg's syntax cannot read it. Loading (`lazy` by default), decoding and the fade-in behave the same in both modes: the plain `<img>` fades in on `load`, and, like NuxtImg, an image that finished before hydration is marked loaded on mount unless the server-side `onerror` marker says it failed.

**The /about portrait** (`app/pages/about.vue`, values in `shared/about-portrait.ts`) is the first `widths` user. Its box is the sidebar's content width (`pages/about.scss` and the theme's split layout): the sidebar column (14 / 16 / 18rem from 48em / 90em / 120em) minus its padding (2 × 1.1rem) and border (2 × 1 px), and below 48em the viewport minus the page pad and the same padding. From 120em the root font is 125%, so those rems count × 1.25. In `sizes`, em and rem are the reader's default font size, as in media queries, so the slot follows their text size like the layout does:

```text
(min-width: 120em) calc(19.75rem - 2px), (min-width: 90em) calc(13.8rem - 2px),
(min-width: 48em) calc(11.8rem - 2px), (min-width: 30em) calc(100vw - 4.7rem - 2px),
calc(100vw - 4.2rem - 2px)
```

`tests/about-page.spec.ts` evaluates the string against boxes measured on a production build at a 16 px and a 20 px default. `widths` is `[320, 480, 640, 960, 1024]` (1024 is the source) and the format is WebP. The portrait stays `lazy` with no `fetchpriority` or preload: the owner's decision is that it is not the page's priority. Measured on `.output/local` (3 cold runs each; the 20 px default set through Chromium's `Page.setFontSizes`):

| Viewport                     | Before (JPEG, px `sizes`)                      | After (WebP, native `sizes`)                   |
| ---------------------------- | ---------------------------------------------- | ---------------------------------------------- |
| 375 × 812, DPR 3             | 960 px JPEG, 93.8 KB; LCP (portrait) 2.0–2.5 s | 960 px WebP, 55.0 KB; LCP (portrait) 1.2–1.5 s |
| 375 × 812, DPR 2             | 960 px JPEG                                    | 640 px WebP, 30.0 KB; LCP (portrait) 1.3 s     |
| 1280 × 800, DPR 1            | 480 px JPEG, 30.5 KB (LCP is the h1)           | 320 px WebP, 10.7 KB (LCP is the h1)           |
| 800 × 900, 20 px default     | 704 px box; a px `sizes` would ask for 187 px  | 960 px WebP, 55.0 KB (not upscaled)            |
| 1280 × 800, 20 px default    | 234 px box                                     | 320 px WebP, 10.7 KB                           |
| 375 × 812, DPR 3, 20 px def. | 289 px box                                     | 960 px WebP, 55.0 KB                           |

**Case studies** (`/work/[slug]`, `app/components/AppCaseStudyMedia.vue`, values in `shared/case-study-media.ts`) are the second `widths` user. The page passes a native `sizes` to `AppCaseStudyMedia`: `CASE_STUDY_HERO_SIZES` for the hero and `caseStudyArtifactSizes(count)` for the Artifacts cells. For a raster in `content/media.json`, `caseStudyRasterLadder(src)` turns that into `widths` (each `IPX_VARIANT_WIDTHS` rung below the source, then the source width, at most the largest rung), the source's own `width` / `height` (so no candidate is cropped to another ratio; the frame already has the file's `aspectCss`) and `format="webp"` unless the source is WebP. SVG diagrams, video, a call without `sizes` and a raster outside the manifest render as before: the manifest is the list the CDN build writes variants for, so an unlisted raster (today the intentional `/i/portfolio/tesseract/…` paths) keeps the default NuxtImg srcset rather than linking variants that do not exist. Loading is unchanged: the hero stays `eager` with no `fetchpriority` or preload, the Artifacts stay `lazy`.

The boxes come from `pages/work/case-study.scss`, `layouts/site.scss` and the theme's prose / split layout. The body column is `--prose-max` (42rem) once there is room; before that it is the viewport minus the site padding (0.5rem below 48em, 0.75rem to 67.5em), the page pad (0.5rem below 30em, 0.75rem to 48em, then `clamp(0.75rem, 0.5rem + 2vw, 1.5rem)`) and, from 48em, the 14rem page nav and its 2rem gap. From 120em the root font is 125%, so 42rem counts as 52.5rem. An Artifacts cell is the section's content box (body − 2 × 1.5rem padding − 2 × 1 px border), halved with the 1 px gap once both columns can be 16rem; a lone artifact spans the grid (`auto-fit` drops the empty column), hence the separate single-cell string:

```text
hero:     (min-width: 120em) 52.5rem, (min-width: 62.5em) 42rem, (min-width: 50em) calc(100vw - 20.5rem),
          (min-width: 48em) calc(96vw - 18.5rem), (min-width: 44.5em) 42rem,
          (min-width: 30em) calc(100vw - 2.5rem), calc(100vw - 2rem)
artifact: (min-width: 120em) calc(24.375rem - 1.5px), (min-width: 62.5em) calc(19.5rem - 1.5px),
          (min-width: 55.75em) calc(50vw - 11.75rem - 1.5px), (min-width: 50em) calc(100vw - 23.5rem - 2px),
          (min-width: 48em) calc(96vw - 21.5rem - 2px), (min-width: 44.5em) calc(19.5rem - 1.5px),
          (min-width: 37.75em) calc(50vw - 2.75rem - 1.5px), (min-width: 30em) calc(100vw - 5.5rem - 2px),
          calc(100vw - 5rem - 2px)
single:   the artifact string without the halving (39rem / 48.75rem - 2px at the wide end)
```

`tests/case-study-media-sizes.spec.ts` evaluates the three strings against boxes measured on a production build at 320–2560 px and a 16 px and a 20 px default, and checks that every candidate of every case-study raster is a variant the CDN build writes (`cdnIpx` snaps the source width up to the next rung, whose file is the source size, never enlarged). `tests/case-study-media-component.spec.ts` covers the rendering (raster, WebP source, unlisted raster, SVG, loading). Measured on `.output/local` (the `innovation-prototyping` hero, `manhattan-2150-keyframe.png`, 1672 × 941; 3 cold runs each):

| Viewport                 | Hero before (1× / 2× PNG)            | Hero after (WebP, native `sizes`) | Artifacts on the page, before → after |
| ------------------------ | ------------------------------------ | --------------------------------- | ------------------------------------- |
| 375 × 812, DPR 3         | 2880 px asked, 1672 px PNG, 3,467 KB | 1280 px WebP, 127 KB (343 px box) | 4,329 KB → 375 KB                     |
| 375 × 812, DPR 2         | 2880 px asked, 1672 px PNG, 3,467 KB | 960 px WebP, 76 KB                | 4,329 KB → 194 KB                     |
| 1280 × 800, DPR 1        | 1440 px PNG, 2,610 KB (672 px box)   | 960 px WebP, 76 KB                | 1,557 KB → 58 KB                      |
| 800 × 900, 20 px default | 1440 px PNG, 2,610 KB (750 px box)   | 960 px WebP, 76 KB                | 1,557 KB → 118 KB                     |

The LCP element of that page is text (the lead paragraph or the h1, 0.38–0.50 s before and after): the hero fades in from `opacity: 0`, which Chromium does not count. On `data-visualization` (one WebP artifact) at a 1280 × 800 viewport the LCP is the artifact; its file went from 109 KB (960 px) to 57 KB (640 px) and the LCP stayed within run-to-run noise (1.3–1.6 s, dominated by the local ipx resizing each cold request). Screenshots at DPR 3 show the hero sharp. Before, the local ipx also cropped every Artifacts candidate to 16:9 (`width="960" height="540"`), including the 1:1 `vimg-crystal-volume.webp`; the ladder now keeps the source ratio, as the CDN variants always did.

WebP needs no JPEG fallback in the browsers the site supports (Safari 14+). AVIF would be about 44% smaller again (960 px: 30.9 KB) but needs a `<picture>` with a fallback, so it is a TODO. The local ipx handler answers `max-age=60` (its default), which only applies to `local` / `development` builds. On AWS the variants are S3 objects with the one-hour revalidated cache (the repo policy for unversioned files). Neither is changed.

## Media slots and placeholders

Pages that had no imagery get **media slots**: named places for a picture or video, listed in `core/web/content/media-slots.json` and read through `#shared/media-slots`. Until the real asset exists, a slot renders a labelled placeholder, so the layout is final before the art is.

```json
{
  "version": 1,
  "slots": {
    "case-study.walkthrough": {
      "kind": "video",
      "src": null,
      "poster": null,
      "alt": "Placeholder: screen-recorded walkthrough of this case study",
      "ratio": "16 / 9",
      "caption": "Walkthrough video coming soon."
    }
  }
}
```

- **Storage and seeding.** Slots live in the data store, next to the posts: `MediaSlotStore` (`core/web/server/db/media-slot-store.ts`, `getMediaSlotStore` / `createMediaSlotStore`, the same `DATA_BACKEND` resolution as the post store) keeps one record per tenant and slot id: `{ tenant, id, kind, ratio, assetId, src, alt, decorative, caption, captions, poster, lqip, dominantColor, updatedAt }`. A record's `assetId` (a media library asset) wins over `src`, then the placeholder. SQLite and Postgres use the `media_slots` table (`migrations/003_media_slots.sql`, primary key `(tenant, id)`); DynamoDB uses items in the Posts table (`id: 'SLOT#pf#<slotId>'`, `entityType: 'mediaSlot'`, see [data stores](../data-stores.md)). `media-slots.json` is the **seed and the defaults**: `seedRecordsFromJson` turns each JSON slot into a `portfolio` record (`assetId: null`, `decorative: false`, missing optional fields `null`), and `listMediaSlots(store)` inserts every seed id the store lacks (`insertIfAbsent`, which never overwrites) before it lists. So the first read seeds an empty store, a slot added to the JSON later appears on the next read, and a slot edited in the store keeps its edit. There is no seed script; every backend seeds lazily. Editing the JSON after a slot is seeded does not change the stored record. The store contract (`core/web/tests/server/db/media-slot-store.spec.ts`) runs on all three backends.
- **Precedence and slot views.** `core/web/server/utils/media-slot-views.ts` turns each record into a `MediaSlotView` (`#shared/media-refs`: the slot's fields plus `id`, `placeholder`, `unavailable`, `decorative`, `srcset`, `width`, `height`, `assetId`). `toSlotView(record, ref)` applies the precedence with fall-through: a resolved `assetId` wins and gives `src`, `srcset`, `width`, `height`, `lqip`, `dominantColor` and `poster`, with the record's `alt` unless it is blank (then the asset's alt); an `assetId` that does not resolve, or resolves to an asset the slot's kind cannot render (an `image` or `svg` slot takes `image` and `svg` assets, a `video` slot only `video`), falls through to the record's `src`; with no `src` either the view is `unavailable` (the labelled fallback), not the "not made yet" placeholder. `placeholder` is `src === null && !unavailable`. An accepted `image` or `svg` asset gives the view its own `kind`, so an svg asset in an image slot (or as a blog cover) renders through `UiSvgImg`, a direct `img`, never NuxtImg / IPX; otherwise `kind` comes from the record. `ratio`, `caption`, `captions` and `decorative` always come from the record. `getMediaSlotViews()` lists the records (`listMediaSlots`) and resolves every slot's asset in one `resolveMediaRefs` call. The record list is cached per process for 60 s (`MEDIA_REF_TTL_MS`; on DynamoDB a list is a full Posts-table scan, too heavy for every render), and `clearMediaSlotCache()` drops it (plan 4's slot writes call it); other instances see a slot edit within 60 s. A store that fails (or cannot be created) falls back to the JSON seed, logs `media.slots_store_unavailable` and caches nothing, so the page still answers 200.
- **The route.** `GET /api/media-slots` answers `{ slots: Record<slotId, MediaSlotView> }` with `Cache-Control: public, max-age=0, must-revalidate`, never `immutable` (library media changes without a deploy). `useMediaSlots()` fetches it once per page: every slot shares `useAsyncData('media-slots')` with `dedupe: 'defer'`, and its handler joins the request already in flight for the app (Nuxt can run the handler once per caller), so a page with several slots makes one request. After hydration it reuses the server's payload, and a client navigation from one slot page to another reuses the loaded views (the shared key). The views are `null` when the route fails or answers anything without `slots`. An `AppMediaSlot` given a `view` (the blog cover) does not call `useMediaSlots()` at all, so a blog post makes no `/api/media-slots` request for its cover (decided at setup).
- **Editing through the API.** The authenticated slot routes (admin principal only; 401 without a token, 403 `admin_only` for a tenant token; every answer `Cache-Control: no-store`; [Web write endpoints](./admin.md#web-write-endpoints)) edit the `portfolio` slots. The code is `core/web/server/utils/media-slot-write.ts` (`saveMediaSlot`, `resetMediaSlot`), with the routes under `core/web/server/api/media-slots/`.
  - `GET /api/media-slots/records` answers `{ slots: Array<{ record, view, needsMedia, seed }> }`: every stored record (seeding the missing ones first, like `listMediaSlots`), its `toSlotView` view (one `resolveMediaRefs` call for the list), `needsMedia` (the view is a placeholder or `unavailable`) and its JSON seed record (`null` when the slot has none). `GET /api/media-slots` (the public views) is unchanged; Nitro serves both.
  - `PUT /api/media-slots/:id` takes `{ assetId, src, alt, decorative, caption, captions }` and answers the saved record. It is a full replace: a field left out is saved as empty (`null`, or `''` / `false`), not kept. `kind` and `ratio` stay as the record (or, for a slot not stored yet, the seed) has them; an id with neither is 404 `Media slot not found`.
  - **Validation** (422 `{ code: 'VALIDATION', fieldErrors: { <field>: [message] } }`, nothing written): `kind`, if sent, must match the slot's; an `assetId` must be an asset of tenant `portfolio` whose kind the slot accepts (`ACCEPTED_ASSET_KINDS`: image or svg for image and svg slots, video for video slots), else `assetId: 'Pick an image from the portfolio library'` (`an SVG`, `a video`), and with no media library a save that names an `assetId` is refused the same way. `src`, `alt` and `captions` follow the `validateMediaSlots` rules: `src` is root-relative or https; `alt` describes the picture, and may be empty only when `decorative`; `captions` are for video slots only, with a root-relative or https `.vtt` `src`, a language tag `srclang` and a `label` (reported as `captions`, `captions.src`, `captions.srclang`, `captions.label`). `caption`, `assetId` and `src` are trimmed, and `''` becomes `null`; `alt` is trimmed. Input hardening, checked before any lookup: an `assetId` outside `[A-Za-z0-9_-]{1,64}` is a 422 on `assetId`, and `src` is at most 2048 characters, `alt`, `caption` and each `captions` field at most 300.
  - **Reset to seed.** `POST /api/media-slots/:id/reset` replaces the stored record with the slot's `seedRecordsFromJson()` entry and answers it; an id with no seed is 404. This is how a `media-slots.json` edit reaches a slot that is already stored.
  - A save or reset writes its usage (`slotUsagePage`: `pending`, the store write, then `live` through `event.waitUntil`; a cleared `assetId` writes `live []`; [Usage list writes](#usage-list-writes)) and then calls `clearMediaSlotCache()`, so this process's next views read the new record. Other processes see it when their cached list expires (`MEDIA_REF_TTL_MS`).
- **JSON fallback.** `resolveMediaSlot(id, fallbackId)` (`#shared/media-slots`) still reads `media-slots.json` and returns the same view shape (no asset). It is the fallback when the route fails, and the only source in the static tamaramack.github.io export, which has no server routes.
- **Fields.** `kind` is `image`, `svg` or `video`; `src` is `null` (placeholder) or a root-relative / `https://` URL; `alt` describes the picture; `ratio` is a CSS `aspect-ratio` (`16 / 9`); optional `caption`, `poster` and `captions` (video), `lqip` and `dominantColor` (raster). `captions` is `{ "src": "/v/<name>.en.vtt", "srclang": "en", "label": "English" }`: a root-relative or https WebVTT file, a language tag and a track name, video slots only. `validateMediaSlots` enforces all of these; `core/web/tests/media-slots.spec.ts` checks the manifest and that every static `slot-id` / `fallback-id` used in a `.vue` file exists, and `core/web/tests/media-slot-component.spec.ts` mounts `AppMediaSlot` once per kind against a stub manifest, plus fetched, given, decorative and unavailable views; `core/web/tests/server/utils/media-slot-views.spec.ts` covers the precedence, the record cache, the store fallback and the route's cache header.
- **Rendering.** `AppMediaSlot` (props `slotId`, `fallbackId`, `view`, `sizes`, `eager`) takes its slot from the `view` prop, else the fetched views (`useMediaSlots()`) by `slotId` then `fallbackId`, else the JSON slot (`resolveMediaSlot`). It renders it through [`AppMediaFile`](#fallbacks-when-media-is-missing) (`kind`, `src`, `srcset`, `unavailable`, `alt`, `ratio`, `width`, `height`, `poster`, `captions`, `lqip`, `dominantColor`, `sizes`, `eager`), inside a `figure.media-slot[data-slot]` with the optional `<figcaption>`. With no `src` the art is not made yet and it shows the `AppPlaceholderMedia` "Placeholder" tag; otherwise it is `UiImage` (raster, with LQIP / dominant colour), `UiSvgImg` (`svg`) or a native `<video controls playsinline>` with a `<track kind="captions" default>` when `captions` is set. If the file then fails to load, or the view is `unavailable`, the same `figure` shows the labelled "unavailable" fallback, named by the slot's `alt`. A `decorative` slot renders its media with `alt=""`. `sizes` is Nuxt Image syntax (default `xs:100vw md:100vw lg:1440px`) for a JSON slot, which goes through NuxtImg. A view with a `srcset` (a library asset) renders a plain `img`, so it gets a native `sizes`: the caller's when it has no Nuxt screen tokens (`xs:`, `md:` …), else `100vw`. Video stays native, like `AppCaseStudyMedia` and `GalleryExhibit`: the repo has no shared video component (`@tgmc/media-player` is a controller class used only by the `/media-player` demo). The old `.media-slot__video` styles moved to `.media-file__video` and are archived in `theme/core/scss/_archive/2026-10-22-media-fallbacks/`.
- **Placeholder rules.** The placeholder is a `div` (it sits inside the slot's `figure`) holding an inline SVG drawn only with theme roles (`--theme-surface-variant-color`, `--theme-border-strong-color`, `--theme-link-color`), so it follows every theme and colour mode. Its visible "Placeholder" label is a `UiTag` (`severity="secondary"`, positioned in the corner) hidden from assistive tech; the placeholder is exposed as `role="img"` with the slot's real `alt` as its accessible name, and reserves the slot's `aspect-ratio`, so swapping in the real asset causes no layout shift. Video slots add a play glyph. Placeholder alt text starts with `Placeholder:` so screen-reader users hear the same thing sighted users see.
- **Swapping in the real asset.** Once a slot is seeded, the live site reads its stored record, so a slot is changed in the store: edit it in **Admin → Slots** ([admin § Slots](./admin.md#slots): choose a library asset, set a static path, alt and captions, or **Reset to seed**), which uses **Editing through the API** above; editing `media-slots.json` then changes only the static github.io export, which reads the JSON, until the slot is reset to its seed (**Reset to seed**). The JSON seeds new slot ids and feeds that export. A JSON `src` (and, for video, `poster`) is a public `/i/…` or `/v/…` file that is an entry in `content/media.json` (the [content guard](#content-guard) fails on any other `/i|v|d/` path; site media gets no `/m/` URLs, owner decision 2026-10-17), or an `https://` URL. Update `alt` to describe the real picture (drop the `Placeholder:` prefix) and keep `ratio` matching the asset. A video with speech needs captions (WCAG 1.2.2): add the `.vtt` next to it and set `captions`; a cross-origin `https` track must be served with CORS headers. No page change is needed.
- **Per-item overrides.** Pages that repeat a slot per item pass a specific id with a generic fallback: `blog.cover.<slug>` falls back to `blog.cover`, `case-study.hero.<slug>` to `case-study.hero`, `case-study.walkthrough.<slug>` to `case-study.walkthrough`. Add `"blog.cover.my-post": {…}` to give one post its own cover; `resolveMediaSlot` throws for an unknown id with no known fallback.
- **Where slots appear.** Under the page hero on Work (`work.hero`), Process (`process.hero`), AI Lab (`ai-lab.hero`), Blog (`blog.hero`) and Product (`product.hero`); under each blog post's header (`blog.cover.<slug>`); on case studies as the hero when the study has no media of its own (`case-study.hero.<slug>`), and in a **Walkthrough** section after Artifacts (`case-study.walkthrough.<slug>`). Code and Docs have no hero imagery (they are working / reading surfaces), and About keeps its real portrait.

## Fallbacks when media is missing

When a file is missing or fails to load in a media slot or on a case study, the page shows a labelled stand-in instead, built by `AppMediaFallback` (`core/web/app/components/AppMediaFallback.vue`; props `kind`, `alt`, `ratio` default `16 / 9`, `poster`). Its root is always its own `[data-media-fallback="<kind>"]` element. Its poster / placeholder box (`.media-fallback__box`) keeps `ratio`, unless a caller frames the root with its own `aspect-ratio`; the box then fills that frame.

- **Coverage.** Media slots (`AppMediaSlot` → `AppMediaFile`) and case-study media (`AppCaseStudyMedia`) get the labelled fallback. Other pages that call `UiImage` / `UiSvgImg` directly (`AppWorkCard`, `AppOrbitStage`, `GalleryExhibit` images, the About portrait) pass no `#fallback` yet: a failed file there is an empty frame named by `alt` (hidden when decorative), never a broken-image icon. The gallery video (`GalleryExhibit`'s raw `<video>`) has no fallback yet. A document or model link is not probed, so it falls back only when its reference is unresolved. Follow-ups are in the [TODO](./interaction-redesign.md#site-media-in-the-library-owner-request-2026-10-21).
- **Copy.** `#shared/media-fallback` holds `MEDIA_UNAVAILABLE_LABEL` (the visible label per kind: `Image unavailable`, `Video unavailable`, `Audio unavailable`, `3D model unavailable`, `Unavailable` for documents; svg reads as an image), `mediaFallbackName(kind, alt)` (the accessible name `<label>: <alt>`, the label alone for a blank alt, `<alt> (unavailable)` for documents) and `mediaRatio(width, height, fallback)` (a CSS `aspect-ratio` from two positive numbers, else the fallback).
- **Per kind.** Image, svg, and video / model without a usable poster render `AppPlaceholderMedia` with the kind's label. Video / model with a `poster` show it (`img alt=""`) in a `role="img"` box named by `mediaFallbackName`, with the label tag; if the poster fails too, or `poster` changes, it falls back to the placeholder or retries. Audio is a plain text row (no player, nothing focusable) and a document is plain text marked unavailable (no link). Long names wrap (`overflow-wrap: anywhere`).
- **Blank alt.** Only a decorative image or svg (blank `alt`) keeps a hidden fallback (`aria-hidden`, no name). Every other kind is named by its label alone. `AppMediaFile` replaces a failed `UiImage` / `UiSvgImg` wholesale with `AppMediaFallback`, which names itself; the `fallbackLabel` prop and `#fallback` slot on the kit components serve other callers, where the failed root carries the name and the fallback is presentational. The roots set `display: block; inline-size: 100%`, so they size themselves inside `UiSvgImg`'s inline failed `span` there.
- **`AppPlaceholderMedia`.** Props are now `alt`, `ratio`, `kind` (any media kind) and `label` (default `Placeholder`, shown in the tag). A blank `alt` makes it decorative.

- **`AppMediaFile`.** One renderer for every kind (`core/web/app/components/AppMediaFile.vue`; props `kind`, `src`, `alt`, `ratio`, `poster`, `captions`, `sizes`, `widths`, `width`, `height`, `format`, `lqip`, `dominantColor`, `eager`, `unavailable`; root `[data-media-kind="<kind>"]`). Image → `UiImage`, svg → `UiSvgImg` (both get the kind's `fallbackLabel`), video → native `video` (`controls`, `playsinline`, the file in a `source`, the captions `track`) in a ratio box, audio → native `audio` (`preload="metadata"`), document → a link with `alt` as its text, or the file name for a blank `alt` (never probed: no request on render), model → its poster through `UiImage` (or a placeholder labelled `3D model`) with an `Open the 3D model: <alt>` link below (`Open the 3D model` for a blank `alt`). `src: null` is the `Placeholder` art (audio / document, with no box to hold, get their fallback row); `unavailable` (the file could not be resolved) or any failed load renders `AppMediaFallback`. A failure is an `error` from `UiImage` / `UiSvgImg` / the `video` or its `source` / the `audio`; a new `src` clears it. A model's poster failing falls to the placeholder and keeps the link. A video's frame is never empty at rest: it uses `preload="none"` only while a working poster covers the frame (a missing video file is then noticed when the reader presses play). A video without a poster uses `preload="metadata"`, so the first frame paints and a missing file errors at rest, which shows the fallback. A video whose poster fails gets the same treatment. A broken `poster` fires no event on the `video`, so a hidden `img` probes it; on failure the `poster` attribute is dropped, `preload` becomes `metadata`, and the fallback is not offered the broken poster. Every kind's box, the image's included, uses one ratio: `ratio`, else `mediaRatio(width, height)`. A failure therefore does not shift the layout.
- **`useMediaFailure(src, element?)`** (`core/web/app/composables/useMediaFailure.ts`) holds that state for one file: `failed` (a ref), `onError` (bind as `@error="onError"`), cleared when the `src` getter changes. Given an `element` getter (the rendered `video` / `audio`, or an `img` such as the poster probe), it also catches a file that failed before hydration. On mount, and only when the component was set up while hydrating, the element counts as failed in two cases. A `video` / `audio` fails when its `error` is set or its `networkState` is `NETWORK_NO_SOURCE` (3). An `img` fails when it carries the `data-error` marker that its server-rendered `onerror` leaves; bind `imgSsrErrorAttrs` from the same module for that. Not after client navigation, where browsers report `NETWORK_NO_SOURCE` briefly on insert; the `error` event covers that case. `useVideoPoster(poster)` in the same module holds a video's poster rule for both components: `posterProbe` (the probe `img` ref), `posterFailed`, `onPosterError`, `posterShown` and `preload` (`none` only while a working poster covers the frame, else `metadata`).

- **Media slots.** `AppMediaSlot` passes the slot's fields to `AppMediaFile`, so a slot with a `src` that fails to load (a raster, svg or video file) shows the fallback for its kind inside the same `figure`, keeping the `figcaption`: `Image unavailable: <alt>` for a raster or svg, and for a video the slot's `poster` (or the placeholder) with no player. This is distinct from a slot whose `src` is `null`: that is the "Placeholder" (art not made yet), keeps the slot's own `alt` as its name and is unchanged. "Unavailable" always means a file that should exist could not be shown.
- **Case-study media.** `AppCaseStudyMedia` (`/work/[slug]` hero and artifacts) keeps its own markup (the `case-study-media` root carrying the page's scope, the WebP `w` ladder, diagrams' `data-media-kind`) and uses `useMediaFailure` for the same rules: a raster (`UiImage`) or SVG / diagram (`UiSvgImg`) that fails, or a video whose `source` fails or that failed before hydration, becomes `AppMediaFallback.case-study-media` (kind `image`, `svg` or `video`; `alt` from the item; ratio `item.aspectCss`, else the WebP ladder's source size, else `mediaRatio(width, height)`: the ratio `UiImage` reserved; while `pages/work/case-study.scss` frames a video's fallback (`[data-media-fallback='video']`, hero and grid) at the `--media-ratio` it gives the player (9:16 on phones), its box filling that frame, so a failure does not shift the layout; the video's `poster`). Its video follows the never-empty-frame rule above: `preload="none"` only while a working poster covers the frame, else `metadata`. The poster probe sits in the `video`'s fallback content, so the component keeps one root; it must stay eager, because a lazy image in non-rendered content may never load in some engines. A new `item.src` retries.

Tests:

- `core/web/tests/media-fallback.spec.ts`: the helpers;
- `core/web/tests/media-fallback-component.spec.ts`: `AppMediaFallback` per kind;
- `core/web/tests/media-file-component.spec.ts`: `AppMediaFile` and `useMediaFailure`;
- `core/web/tests/use-video-poster.spec.ts`: `useVideoPoster`;
- `core/web/tests/media-slot-component.spec.ts`: slots, including the failed-file cases;
- `core/web/tests/case-study-media-component.spec.ts`: case-study media;
- `core/web-e2e/src/e2e/media-fallback.cy.ts` (real browser, files blocked with 404s): the case-study hero SVG and the lazy artifact image fall back with their names and no broken image or page-level overflow at phone, tablet and desktop; a video whose poster 404s ends with `preload="metadata"` and no `poster` (the probe inside `<video>` loads); a failed hero video's fallback keeps the 9:16 player frame on a phone.

## Library media on public pages

A page can reference a library asset by id (never by URL or key). The server resolves the id at render time.

### Resolution and cache

`core/web/server/utils/media-refs.ts` resolves ids for a render: `resolveMediaRefs(ids)` answers a map with every id, `null` when the id does not resolve. `createMediaRefResolver` is the same resolver with its library, storage and clock injected (tests).

- **What an id resolves to.** A `ResolvedMediaRef` (`#shared/media-refs`): kind, mime, `src`, `srcset`, `alt`, `decorative`, `width`, `height`, `lqip`, `dominantColor`, `poster`. Every URL is the public media base (`mediaPublicBaseUrl()`) + key + `?v=<sha8>`.
  - An image's `srcset` lists its ready `640` / `1280` / `1920` variants by width (webp first; never the `t` thumbnail). Its `src` is the largest of them, else the original.
  - An image always has a `srcset`. With no ready variants it is the original: `<src> <width>w` when the meta has a width, else the bare `<src>`. So `UiImage` always takes its plain-`img` branch for library media. It never goes through NuxtImg / IPX, which would rewrite the versioned URL to a `/_ipx/…` path that it refuses (403). An image without variants is served at its original size.
  - Other kinds have no `srcset`; `src` is the original.
  - `alt` is `meta.alt` (else `''`), `decorative` is `meta.decorative === true`. Size, LQIP and dominant colour come from the asset's meta when set.
  - `poster` is the original URL of the image asset named by `meta.posterId` (a video's poster), when that asset resolves.
- **Not resolved: `null`.** An unknown id, a malformed id (not `[A-Za-z0-9_-]{1,64}`, never looked up) and another tenant's asset all resolve to `null`, which renders the kind's fallback. Only `portfolio` assets are public.
- **Cache: 60 s per process.** Each resolution is kept in Nitro's in-memory `media-refs` storage, keyed `portfolio:<id>`, for `MEDIA_REF_TTL_MS` (60 000 ms), a `null` too, so a deleted id doesn't hit the catalog on every render. The memory driver has no TTL of its own, so each entry carries its `expiresAt`.
- **Clearing is per process.** The `@tgmc/media-nuxt` routes that change an asset (delete, rename, meta edit, re-process) emit a change after they succeed. `server/plugins/media-refs-cache.ts` listens and clears that asset's entry, so the instance that handled the change renders it at once (a clear that fails is logged as `media.refs_clear_failed`; the entry then expires within the TTL). A resolve already in flight when the entry is cleared does not cache what it read.
- **Other instances: within 60 s.** Another Lambda instance (or the admin's own process, when it changed the asset) never hears the change; its entry expires within the TTL. So a deleted or renamed asset can show its old URL for up to 60 s on other instances: a renamed asset's old URL is a 404 there, which renders the fallback. A poster's own change likewise reaches its video's cached entry only when the TTL ends.
- **Catalog down.** When the library cannot be read, every id the call had to look up resolves to `null` (placeholders, never a 500), the call logs `media.refs_unavailable` once and nothing is cached, so the next render tries again.

Tests: `core/web/tests/server/utils/media-refs.spec.ts` (a real library on in-memory SQLite) and `packages/media-nuxt/tests/media-asset-events.spec.ts` (the event and the four emitting routes).

### Usage list writes

A post or slot write keeps the library's usage list (which published pages use each asset) up to date, so a delete can't silently take media off a page. The code is `core/web/server/utils/media-usage-sync.ts`. The posts service (`createBlogPostFromBody`, `updateBlogPostFromBody`, `deleteBlogPostById`) runs it when it is given a sync, and without one it writes no usage.

- **Pages.** A post is two usage pages, both labelled with its title and linking `/blog/<slug>`: `post` (the asset ids in the body, `extractAssetRefIds`, which deliberately over-counts) and `post-cover` (`coverAssetId`). A slot is one `slot` page labelled `Media slot <id>`, linking `slotPageUrl(id)`. Only published posts record rows. A slot counts as soon as it is saved. The tenant is `portfolio`.
- **Pending before visible.** A write that makes or keeps a post published first writes `pending` rows: the previous ids and the next ids together. The delete check treats `pending` as in use. A published create picks its post id before the write (`BlogPostStore.create` takes an optional server-only `id`), so its rows name the post before it exists.
- **The 2 s window.** The pending write never fails or slows a publish beyond 2000 ms. On a timeout or error the publish goes ahead and the server logs `media.usage_pending_failed`. Until the rebuild repairs the list, the post's new assets can be deleted without a warning. That gap is the documented window. A pending write that times out keeps running, and the live write waits for it, so a late pending write normally lands before the live rows. That wait is bounded by `PENDING_SETTLE_MS` (10 s): a pending write still unsettled then is logged as `media.usage_write_failed` with `reason: 'pending_stuck'`, and the live rows are written anyway. If the stuck write lands later it can briefly mark the rows `pending` again, which only makes a delete more careful; the rebuild repairs it.
- **Live after, in the background.** After the write, a background task (`event.waitUntil`, else fire-and-forget) writes `live` rows: the post's ids, or `[]` when it is unpublished or deleted. Each page is retried after 1 s and 4 s, then logged as `media.usage_write_failed`. If the store write throws after a pending write, the task puts back the previous rows (their ids, or `[]`). An id with no asset in the tenant (unknown, or another tenant's) gets no row and is logged as `media.usage_missing`.
- **On AWS Lambda the live write is awaited (≤ 5 s).** Nitro 2.13's `aws-lambda` runtime has no platform `waitUntil`: it would return the response and Lambda would freeze the environment with the live write, its retries and the settle wait still pending. `core/web/server/plugins/media-usage-wait.ts` therefore awaits the request's `event.waitUntil` work in `beforeResponse`, only when the Nitro preset is `aws_lambda` (a no-op on `node-server`, where the process keeps running), bounded to 5000 ms in total. A publish on Lambda normally takes a few hundred ms longer; in the worst case about 2 s (pending) plus 5 s (live). When the bound cuts the wait it logs `media.usage_wait_timeout`, and the cut work may never finish: its rows stay `pending`. Keep `MEDIA_USAGE_REBUILD_ENABLED=1` on `test` and `production` ([cicd](../../cicd.md)) as the backstop that settles them.
- **Rebuild input.** `buildUsageRebuildRequest(posts, slots)` lists every published post and every `portfolio` slot with an asset, for `MediaLibrary.rebuildUsage`; a slot of another tenant is left out, since the request names one tenant. `POST /api/media-usage/rebuild` (admin principal only, `no-store`, [Web write endpoints](./admin.md#web-write-endpoints)) runs it through `rebuildMediaUsage` (`core/web/server/utils/media-slot-write.ts`): every post (`listAll`; the builder keeps the published ones) and the stored `portfolio` slots, then `MediaLibrary.rebuildUsage`. It answers `RebuildUsageResult` (`{ added, removed, countersRepaired }`), or 503 `Media library unavailable` when the library cannot open.
- **One sync per write.** A sync holds per-write state (the pages its `beforeWrite` named), so every handler builds a fresh one; it is never shared between requests.
- **Who writes today.** The web's authenticated post routes (`POST /api/blog/posts`, `PUT` and `DELETE /api/blog/posts/:id`, [Web write endpoints](./admin.md#web-write-endpoints)) build a sync on the web's media library, its background work handed to `event.waitUntil`. The admin's blog and slot routes build one on its own library in local media mode; in forward mode (`MEDIA_API_URL`) they forward the write to these web routes, which record the usage ([admin § Forward mode](./admin.md#forward-mode)). The web's slot routes (`PUT /api/media-slots/:id`, `POST /api/media-slots/:id/reset`) build one the same way.

Tests: `core/web/tests/server/utils/media-usage-sync.spec.ts`, `core/web/tests/server/api/posts/posts-service.spec.ts` (usage sync), `core/web/tests/server/api/blog-posts-routes.spec.ts` (the web routes and their auth table), `core/web/tests/server/api/media-slots-admin-routes.spec.ts` and `core/web/tests/server/utils/media-slot-write.spec.ts` (slot writes and the rebuild), `core/admin/tests/admin-blog-usage.spec.ts`, `core/admin/tests/admin-blog-forward.spec.ts` and `core/admin/tests/admin-slots-routes.spec.ts` (forward mode sends the writes to these routes), `core/web/tests/server/plugins/media-usage-wait.spec.ts` (the Lambda wait), and the store contract (`create keeps a given id`).

### Blog covers and embeds

A post's cover and the media in its body come from the library. `GET /api/posts/:slug` resolves them on the server (`core/web/server/utils/blog-post-media.ts`) and answers `{ ...post, html, cover, segments }` with `Cache-Control: public, max-age=0, must-revalidate`. The cover id and the body's block ids resolve in one `resolveMediaRefs` call, next to `getMediaSlotViews()`. Neither throws: with the catalog down the cover falls back and every media segment has `ref: null`, and the post still answers 200. `html` (the whole body as sanitized html) stays for the github.io export and older clients; in it a block reference renders as the unavailable text, like an inline one.

- **Syntax.** `![alt](asset:<id>)` or `::media{asset=<id> alt="…"}`, for any kind (the kind comes from the asset). Ids match `[A-Za-z0-9_-]{1,64}`. A missing alt falls back to the asset's alt.
- **Block only.** A reference renders as media only when it stands alone on its line, outside a code fence (`splitBodyMedia`). An `asset:` image inside running text is rendered as the text `Image unavailable: <alt>` in a `span.blog-media-unavailable`: `renderBlogMarkdown` turns any `img` whose `src` is missing or not http(s) / root-relative into that escaped text, never an `img` without `src`. An inline reference still counts as usage, so a delete can't take it away silently. The same rule turns a relative image src (`![x](images/a.png)`) into `Image unavailable: x` text: a post body uses library references or root-relative / https URLs.
- **Segments.** `renderPostSegments(markdown, refs)` answers the body in order: `{ type: 'html', html }` for each markdown run (through `renderBlogMarkdown`) and `{ type: 'media', assetId, alt, ref }` for each block (`alt` is the written alt, else the asset's; `ref` is `null` when the id does not resolve, for example another tenant's asset).
- **Cover precedence, with fall-through.** `resolvePostCover(post, slots, refs)`: `coverAssetId`, then slot `blog.cover.<slug>`, then slot `blog.cover`, then the placeholder. A source that does not resolve falls through to the next: an unknown or another tenant's asset, an asset of a kind the image cover cannot render (it takes `image` and `svg`, like an image slot), or a slot that is itself a placeholder or unavailable. The cover is `unavailable` (the labelled fallback) only when an asset id was set and nothing after it resolved either; otherwise it is the `blog.cover` placeholder. When the post's asset wins, the view's id is `blog.cover.<slug>` and its `alt` is `coverAlt`, else the asset's alt, else the slot's; it is decorative only when the asset is and the post sets no `coverAlt`. A slot that wins keeps its own alt (it shows a different picture); an unavailable cover is named by `coverAlt`, else the slot's alt.
- **The page.** `app/pages/blog/[slug].vue` renders `AppMediaSlot(:view="post.cover", eager)` and one `article.blog-body` whose children are the segments: each html chunk in a `display: contents` wrapper (`v-html`), each block through `AppMediaFile` with the ref's fields, `unavailable: ref === null` and `kind: ref?.kind ?? 'image'`. Body media get the prose column's native `sizes`, `(min-width: 42em) 42rem, 100vw` (`--prose-max`), so the browser does not pick a 100vw candidate from the `srcset`. The cover sits above the prose column, in the page shell; with a `srcset` it gets `AppMediaSlot`'s native `100vw`, and an svg cover renders through `UiSvgImg` with its direct `/m/…svg?v=` URL. An answer without `cover` / `segments` renders the slot by id and `html`.
- **Writing references.** In the admin blog editor, **Insert media** picks a library asset of any kind and writes its block reference on its own line at the caret, with a blank line before and after (`bodyMediaReference` in `shared/media-refs.ts`, the parser's inverse; its alt drops `[ ] ( ) { } \` so a reference counts exactly one asset); **Choose cover** sets `coverAssetId` from an image or SVG (see [admin § Blog editor](./admin.md#blog-editor)). Inserted mid-line, the block splits that paragraph in two; inserted inside a code fence, it renders as code, not media, but still counts as usage (`extractAssetRefIds` over-counts on purpose).
- **Covers from the portfolio tenant only.** The site renders `portfolio` assets only, so the picker lists that tenant, and a post create or update whose `coverAssetId` names an asset of another tenant is a 422 on `coverAssetId`, "Pick an image from the portfolio library" (`coverTenantChecks` in `server/api/posts/service.ts`; the web routes and the admin's local mode both run it). A cover id with no asset at all still saves: the page shows the fallback and the post is flagged **Needs media**. With the library unavailable, or a lookup that fails for another reason (logged as `media.cover_check_failed`), the write is not checked.
- **Captions gap: warned, not blocked.** A library video or audio embedded in a body renders a native `video` / `audio` with no captions `track` or transcript yet: a `ResolvedMediaRef` has no captions field (slots do). **Insert media** warns "No captions yet: this video will play without captions." (or "this audio") and still inserts (owner, 2026-10-23). Until captions support for library video and audio lands (asset meta or a captions asset), only embed time-based media that has no speech, or link a transcript in the post text (WCAG 1.2.1 / 1.2.2).

Tests: `core/web/tests/server/utils/blog-post-media.spec.ts` (precedence, segments, the route), `core/web/tests/server/utils/render-blog-markdown.spec.ts` (inline images), `core/web/tests/server/utils/media-refs.spec.ts` (the srcset without variants), `core/web/tests/blog-post-page-component.spec.ts` (the page with a cover, segments and a fallback; a library image without variants renders a plain `img` with its direct URL, never `/_ipx/`; an svg cover renders a direct `img`; body and cover `sizes` are native).

Related: [`@tgmc/media`](../../packages/media.md#site-media-manifest-and-import), [`@tgmc/image` sanitizer](../../packages/image.md#sanitize-media-before-it-is-stored), [promote media to production](../../cicd.md#promote-media-to-production).
