# AGENTS.md

## Overview

`demiurge/public/www` is a Next.js 16 monorepo: a markdown document/post platform plus an embedded Three.js isometric 3D engine with Ammo.js physics. It runs on the shared VMAX backend and publishes to VMAX.ai.

## Documentation map: READ the matching doc BEFORE editing a subsystem

The detail lives in per-subsystem docs, not here. Each doc is the **contract** for its area. Do not edit a subsystem without reading its doc first. Sub-`AGENTS.md` files nest; always read the **deepest** one that owns your file.

| Read this | Covers | Before you... |
|---|---|---|
| [`demiurge/public/www/app/AGENTS.md`](demiurge/public/www/app/AGENTS.md) | App Router front door: route map, Next.js conventions, how a post URL becomes a page | touch any route, page, layout, or the SSR pipeline |
| ↳ [`demiurge/public/www/app/-/AGENTS.md`](demiurge/public/www/app/-/AGENTS.md) | the `app/-/` standalone reference and test routes | add or use a test/debug/reference route |
| [`demiurge/public/www/three-isometric-engine/AGENTS.md`](demiurge/public/www/three-isometric-engine/AGENTS.md) | the 3D engine: scene architecture, flat-sea and seafloor placement rules, mount manifest, per-frame loop, shadow scheduling, shaders, physics | touch anything under `three-isometric-engine/` |
| ↳ [`demiurge/public/www/three-isometric-engine/world-entities/AGENTS.md`](demiurge/public/www/three-isometric-engine/world-entities/AGENTS.md) | per-entity contracts (publishes/subscribes, manifest gate, quirks) | edit or add an `Entity` |
| ↳ [`demiurge/public/www/three-isometric-engine/world-meshes/AGENTS.md`](demiurge/public/www/three-isometric-engine/world-meshes/AGENTS.md) | per-factory reference | edit or add a mesh factory |
| ↳ [`demiurge/public/www/three-isometric-engine/agent-simulation/AGENTS.md`](demiurge/public/www/three-isometric-engine/agent-simulation/AGENTS.md) | flag cloth, boat-placement geometry (water-sdf, offshore band), c-space grid | touch flag cloth, boat placement, or wayfinding geometry |
| [`demiurge/public/www/next-vmax/AGENTS.md`](demiurge/public/www/next-vmax/AGENTS.md) | `next-vmax` component invariants not in its skill doc | edit `next-vmax/` |
| ↳ [`demiurge/public/www/next-vmax/islands/AGENTS.md`](demiurge/public/www/next-vmax/islands/AGENTS.md) + [`demiurge/public/www/next-vmax/islands/island-scenes.ts`](demiurge/public/www/next-vmax/islands/island-scenes.ts) | The preset catalog; `IslandStage` instances any row. Browse at `/-/vmax-tools-template/islands/{key}` | build, change, or verify any island / structure / scene |
| [`demiurge/public/www/next-vmax-tools/AGENTS.md`](demiurge/public/www/next-vmax-tools/AGENTS.md) | tools-shell invariants not in its skill doc | edit `next-vmax-tools/` |
| [`demiurge/public/www/campaign-three-library/AGENTS.md`](demiurge/public/www/campaign-three-library/AGENTS.md) | CampaignThreeLibrary, the `/campaigns` Campaign tool built on the `campaigns-v2/` components: its forked controller, campaign-only shell, the selected campaign's application and Self-Play view rows in the history sidebar that never return to the v2 campaign document, the summary inside the Campaign progress card, and the bottom-left campaign menu of campaign actions | edit `campaign-three-library/` or `app/campaigns/` |
| [`demiurge/public/www/campaign-director-library/AGENTS.md`](demiurge/public/www/campaign-director-library/AGENTS.md) | the `/-/campaign-director-components` prototype: the `/campaigns` shell, sidebar, and campaign actions bar with a simulated campaign selected, its director conversation played out to its last step, through task generation, Quality Control, Evals, and Training, as nested tree apps and cards, the same conversation beside a timeline of titled notches tagged by stage, a third campaign whose conversation plays the same steps live beside that timeline, which lists what remains, and waits for the viewer's answers, and the real `CampaignThreeSelfPlay` results beside it | edit `campaign-director-library/` |
| [`demiurge/public/www/campaigns-v2/AGENTS.md`](demiurge/public/www/campaigns-v2/AGENTS.md) | the Campaign 0.2 component copies `/campaigns` imports, and the 0.2 fixture controller behind `/-/vmax-tools-template/campaign-0-2` | edit `campaigns-v2/` |
| [`demiurge/public/www/document-system-common/AGENTS.md`](demiurge/public/www/document-system-common/AGENTS.md) | shared non-React document layer | edit `document-system-common/` |
| [`demiurge/public/www/document-system-components/AGENTS.md`](demiurge/public/www/document-system-components/AGENTS.md) | markdown-post React UI plus the six overlay shaders | edit `document-system-components/` |
| [`demiurge/public/www/next-slate-markdown/AGENTS.md`](demiurge/public/www/next-slate-markdown/AGENTS.md) | post API client, server helpers, the password-post and head-tag components | edit `next-slate-markdown/` |
| [`skills/post-permissions-and-viewing/SKILL.md`](skills/post-permissions-and-viewing/SKILL.md) | Sign-in, draft review, author/admin writes, publication, team URLs, and partner domain onboarding across the website and sibling API | diagnose or change post permissions, add or revoke partner access |
| [`demiurge/public/www/public/SKILL.md`](demiurge/public/www/public/SKILL.md) | VMAX.ai posting API, Slate JSON serialization, common-mistakes checklist | run any posting workflow |
| [`demiurge/public/www/ALGORITHMS.md`](demiurge/public/www/ALGORITHMS.md) | every algorithm with code demos, plus section 24, the standing performance evaluation ledger (cost models, backtests, adopted and rejected alternatives). **Jump to its Table of Contents; do not read end-to-end** (about 600 KB) | implement or modify an algorithm; before proposing a faster one, read its ledger row |
| [`demiurge/public/www/skills/`](demiurge/public/www/skills) `*/SKILL.md` | task workflows (new island/structure/agent, the structure builder and its uuid identity model, shader and TypeScript perf discipline, LaTeX to Vmax, [`use-campaign-api`](demiurge/public/www/skills/use-campaign-api/SKILL.md), the ONE source of truth for the Campaign product and API, [`create-vmax-presentation`](demiurge/public/www/skills/create-vmax-presentation/SKILL.md), the ONE source of truth for the presentation Markdown dialect, deck conventions, and the handoff an agent with a user's API key follows to create a presentation, [`use-slides-api`](demiurge/public/www/skills/use-slides-api/SKILL.md), the ONE source of truth for the Slides application, its compiler, and the internet.dev slides API client, [`write-help-from-seth`](demiurge/public/www/skills/write-help-from-seth/SKILL.md), the voice and grounding standard for every help card, and [`create-wood-block-simulation-illustration`](demiurge/public/www/skills/create-wood-block-simulation-illustration/SKILL.md), which turns a paper's diagram into a SandWoodBlock scene and red brief on `/-/sample`, linked from `.claude/skills/` so it runs as `/create-wood-block-simulation-illustration`) | invoke that workflow; read the one skill fully first |

## Top-level directories

| Directory | Purpose |
|---|---|
| `app/` | App Router pages plus the `app/-/` reference/test routes. See [`demiurge/public/www/app/AGENTS.md`](demiurge/public/www/app/AGENTS.md). |
| `common/` | Repo-wide shared utilities (`derive-world-mode.ts`, `theme-colors.ts`, `attach-theme-observer.ts`, `use-viewport.ts`, `use-mounted.ts`, `use-shader-icon.ts` (the shared-context slot lifecycle of the shader-drawn rail icons, contract in `app/AGENTS.md`), `scene-modal-bridge.ts`, `navigation-links.ts`, `affiliations.ts` (the one organization-to-logo map every byline, `/research`, and the GlyphBench tower read; contract in `document-system-components/AGENTS.md`, "Author byline behavior"), `home-post-descriptions.ts`, `research-copy.ts`, `campaign-copy.ts`, `campaign-prior-art.ts`, `slides-copy.ts`, `page-tracking.ts` (the `/page-tracking` route constants, record type, and pure view helpers; contract in `next-vmax-tools/AGENTS.md`, "FormPageTracking"), `page-return.ts`, `speech-voices.ts`, `browser-baseline.ts` (stand-ins for built-ins newer than the browser floor, "Browser floor" below)). Invariants below. |
| `components/` | Top-level React components: page chrome, the modal system, sign-in, the home marketing stack, the brand mark, `ForestCacheWarmer`, `RootLayoutEffects`, `Providers`. Invariants below; page-level contracts in `app/AGENTS.md`. |
| `next-vmax/` | Application components the site and the tools kit share, including `ModalAuthentication` (the non-dismissable `/sign-in` Google-auth gate), `Tooltip`, the glass buttons, `Icon`, and `islands/` (preset catalog, `IslandStage`, `WorldStage`). Catalogue: [`demiurge/public/www/skills/create-vmax-tools-page/SKILL.md`](demiurge/public/www/skills/create-vmax-tools-page/SKILL.md), "Shared `next-vmax` components"; invariants: [`demiurge/public/www/next-vmax/AGENTS.md`](demiurge/public/www/next-vmax/AGENTS.md). |
| `next-vmax-tools/` | The `/-/vmax-tools-template` tools shell and `Form*` body kit (alias `@nextjs-vmax-tools/*`), a reference app to clone for any internal tool. `AppContainer` wraps every page; `tools-pages.tsx` is the `TOOLS_PAGES` registry both routes read. See [`demiurge/public/www/skills/create-vmax-tools-page/SKILL.md`](demiurge/public/www/skills/create-vmax-tools-page/SKILL.md). |
| `campaign-three-library/` | CampaignThreeLibrary, the third-generation Campaign tool behind `/campaigns`. It imports the Campaign 0.2 copies in `campaigns-v2/` for everything it does not own. See its `AGENTS.md`. |
| `campaign-director-library/` | The campaign director prototype behind `/-/campaign-director-components`; every request is simulated. See its `AGENTS.md`. |
| `campaigns-v2/` | The Campaign 0.2 copies `campaign-three-library/` imports. No route mounts its live controllers; `/-/vmax-tools-template/campaign-0-2` mounts its fixture controller as prior art. See its `AGENTS.md`. |
| `document-system-common/` | Shared non-React document layer, including `shader-context` (shared WebGL2 manager). See its `AGENTS.md`. |
| `document-system-components/` | React UI for markdown posts plus the six overlay shaders. See its `AGENTS.md`. |
| `next-slate-markdown/` | Post API client, server helpers, and the password-post and head-tag components. Posts persist as markdown; the editor is `next-vmax-tools/FormPaperEditor`. See its `AGENTS.md`. |
| `three-isometric-engine/` | Three.js engine with physics, shaders, scenes. See its `AGENTS.md` and [`demiurge/public/www/skills/fast-threejs-shaders-check/SKILL.md`](demiurge/public/www/skills/fast-threejs-shaders-check/SKILL.md). |
| `modules/` | Tiny shared modules and vendored `minisearch.js` + `minisearch.d.ts` (imported as `@modules/minisearch`). |
| `pages/` | Legacy Pages Router; one endpoint (`oauth.tsx`). |
| `scripts/` | Build/utility scripts (`npm run script`). |
| `public/` | Static assets including `SKILL.md`, served at `/skill` (its alias redirects live in `next.config.ts` `redirects()`). |
| `skills/` | Project-local agent skills. |

### Cross-file invariants in `common/` and `components/`

- **All internal navigation is a HARD load: never soft-navigate.** No `next/link`, no `useRouter`/`router.push`/`router.replace`: hrefs render plain `<a>` and programmatic navigation assigns `window.location.href`. Pages stack full-viewport fixed overlays (scene backdrops, the persistent `ModalRenderer`/`SceneModalBridge` in root `Providers`), so a client-side transition would carry the previous page's overlays onto the next page.
  - Same-page URL cleanup that must NOT reload uses `window.history.replaceState`, which is not a navigation.
- **`Providers` seeds `activeConfigs` WITHOUT reading `window.matchMedia` in the `useState` initializer** so server and client agree on the first render; the mount `useEffect` reconciles `prefers-color-scheme`. `useViewportMode` / `useViewportSize` (`common/use-viewport.ts`, `MOBILE_BREAKPOINT`) follow the same rule.
- **No clock is read during render: every counter waits for the browser to mount.** `common/use-mounted.ts` `useMounted()` is `false` on the server and the first client render and `true` after the mount effect; `useMountedAtMilliseconds()` is `0` until then and the mount time after. A `useState(() => Date.now())` initializer or a module-level `Date.now()` runs on the server and hydrates against a different clock, so an elapsed label rendered from it mismatches or shows the server's uptime. Every elapsed counter (`next-vmax-tools/FormCampaignElapsedLine` `useElapsedMilliseconds`) reads `0` until mounted and `FormTemplateCampaign` stamps its refine fixture through `useMountedAtMilliseconds`; the braille loaders start at frame `0` on both sides and advance only in their effects, which is the same rule by construction.
  - `useHydrated()` (same file) is the gate for a value that exists only on the client and may change before a component hydrates: it is `useSyncExternalStore` with a server snapshot of `false`, so it reads `false` on the server and in every hydration pass (including a deferred `<React.Activity>` section hydrating after its provider changed) and `true` from the first render of anything mounted after load. Prefer it to `useMounted` when a late client mount must render the value in its first commit; `useMounted` always costs one commit.
- **`common/derive-world-mode.ts` `sceneNeedsPhysics(props)` is the ONE reader of which scene flags load Ammo**; its body is the roster of physics gates, and every scene it does not name loads no Ammo. `hasPropel` gates physics on every scene, the inline `/campaign` included, because its hwacha shatters trebuchets. `GLComponent` evaluates it once; a new destructible or agent gate is added there and to the literal table in `common/derive-world-mode.test.ts`, never as a second check in an entity (`three-isometric-engine/AGENTS.md`, "Physics").
- `common/scene-frame.ts` owns the engine-to-HUD frame subscription. `GLComponent` publishes after its projections and shader overlays; `useSceneControlPosition` consumes the latest coordinates without a separate animation loop or per-frame React state. The control behavior contract lives in `app/AGENTS.md`.
- `requestSceneModal(key)` (`common/scene-modal-bridge.ts`) fires `SCENE_MODAL_EVENT` on `window`; `SceneModalBridge` (mounted once in `Providers`, deduped) opens the registered modal from `SCENE_MODALS` (`sign-in` → `ModalAuthentication`, `CAMPAIGN_ACCESS_MODAL` → `FormCampaignAccess`) unless that component is already in the stack. It is the only way a Three.js scene element, or a plain function outside React, opens a React modal it cannot reach through hooks.
- **`attachThemeObserver` stores its MutationObserver on `mesh.userData.themeObserver`**: `three-isometric-engine/common/three/scene-teardown.ts` disconnects the observer under that key on the ice, grass, and desert land masses on unmount. Renaming the key leaks observers.
- **`DOCUMENT_NAVIGATION_SECTIONS` (`common/navigation-links.ts`) is the shared site-menu registry** that `NavigationMenuTrigger` renders for every `DocumentHeading` mark (the post pages and the tools top bar), with entries alphabetized within each section so every page presents the same hierarchy. It excludes the agent-discovery and template routes, so site navigation stays focused on the product; `SHARED_SIDEBAR_GROUPS` keeps the template review pages in its `Preview:` groups.
- **`VMAX_SOCIAL_LINKS` (`common/navigation-links.ts`) is Vmax's own social accounts** (LinkedIn and X), the items of the site menu's `social` section and the home page's social icons (`components/Homepage`); a new account is added there once. Their marks are `Icon.X` and `Icon.LinkedIn` (`next-vmax/Icon.tsx`), which `DropdownMenu` draws too. `Icon.LinkedIn`'s viewBox is cropped to its square because `Icon.X` fills its whole box; with the full box the LinkedIn mark drew at five sixths of the X's size beside it.
- **`NavigationMenuItem.themeAction` and `visibility` are serializable tokens.** `NavigationMenuTrigger` calls `resolveNavigationItems` when the menu opens, so the `vmax` cookie is read in the browser and each opening reflects the current session. Campaign links to `CAMPAIGNS_URL` (`/campaigns`) only when signed in; Sign in appears only when signed out. Toggle Theme reads the current body class on activation and uses `Utilities.setTheme`, preserving the independent font classes.
- **`TEAM_MENU_ITEMS` derives from `SOCIAL_LINKS` without reordering it**, because the engine seats the roster in its order. A new member joins the `/world` chessboard island; the GlyphBench island's members are named in `GLYPHBENCH_ISLAND_MEMBERS` (`three-isometric-engine/world-entities/AGENTS.md`, "Chessboard island"). The alphabetized projection carries each person's LinkedIn link and the existing unavatar X avatar source; `TEAM_NAVIGATION_SECTION` supplies both the site menu and the home Team popover so names, portraits, and links cannot drift. Members without a personal X account use Vmax's own X account and its avatar; their names retain their personal LinkedIn destination. A shared X URL is not a unique person key.
- **The signed-in site menu leads with the viewer's profile, `@{username}` linking `/{username}`, above Campaign.** `viewerProfileNavigationItem` (`common/navigation-links.ts`) builds the row; `NavigationMenuTrigger` asks `loadViewerUsername` (`common/viewer-username.ts`) for the username from `DropdownMenuTrigger`'s `onIntent` (pointer enter or focus on the trigger) and `onOpen`, because no session cookie carries it and the menu renders on pages whose server never resolved a viewer (posts, home, marketing). `loadViewerUsername` shares one `HTTP.getViewer` request per session key for the life of the page and forgets an empty answer so a later opening retries; a username that arrives while the menu is open is inserted at the top of the open menu.
- **`CAMPAIGNS_URL` (`common/navigation-links.ts`, `/campaigns`) is the ONE Campaign product destination**: the site menu's Campaign, the tools rail's `CAMPAIGNS_SIDEBAR_GROUP` header, the marketing pages' signed-in try button, and the `/client` hand-offs lead there, and `CAMPAIGN_SHARED_URL` is its `/shared` child. `next.config.ts` `redirects()` sends `/campaigns-v2` and `/campaigns-v3`, with any path and query beneath them, to the same address under `/campaigns`, so every older Campaign link opens the current Campaign.
- **`common/campaign-prior-art.ts` is the roster of retired Campaign applications kept as prior art** (`CAMPAIGN_PRIOR_ART`: Campaign 0.1 and Campaign 0.2, each a label, a `/-/vmax-tools-template/campaign-0-*` href, and a description). The template rail's `Preview: Prior Art` group and each route's `campaignPriorArtMetadata` read it, so a label or address changes in one place. The routes are `next-vmax-tools/AGENTS.md`, "Campaign prior art".
- **`CAMPAIGNS_URL` and `CAMPAIGN_BLUEPRINT_URL` remain in `common/navigation-links.ts`**, because `tools-pages.tsx` imports this module and re-exports them as `CAMPAIGNS_HREF` and `CAMPAIGN_BLUEPRINT_HREF`. A component outside the tools shell imports a URL from `navigation-links`, never from `tools-pages`: the registry statically imports every tools page body (KaTeX through `FormEquation`, the Slate editor and `marked` through `FormClientExperience`, the island stages), so one constant pulls all of it into that page's JavaScript. The site menu carries no template or debug-route links.
- **`common/scene-debug-flags.ts` is the ONE reader of the rendering-debug URL flags** (`isBareScene()` for `?bare=true`, `isPerfScene()` for `?perf=true`, `isFreezeScene()` for `?freeze=true`, and `isDebugScene()` / `isMeshScene()` for the `DEBUG_QUERY_*` and `MESH_QUERY_*` pairs that `Providers` also reads; the last two are engine-only and documented in `three-isometric-engine/AGENTS.md`, "`?perf=true`"). **`isBareScene()` is the ONE reader of the `?bare=true` flag**, read by `GLComponent`, which threads it into the scene manifest; a React surface that floats over a scene and must hide for it calls the same function inside an EFFECT (never during render, same rule as `Providers` and `matchMedia`). The engine's own projected tags are part of the scene under inspection, so the flag hides page chrome over the world and nothing belonging to the world. Contract: [`demiurge/public/www/three-isometric-engine/AGENTS.md`](demiurge/public/www/three-isometric-engine/AGENTS.md).
- **`home-post-descriptions.ts` resolves each blurb from `PUBLISHED_POSTS` by HREF, never by index.** `PUBLISHED_POSTS` is newest-first and `HOME_POST_NUMBERS` (in the same file) names each post's number, which `GLComponent` uses to pick the blurb for each tag. Keys are local post_numbers, not post UUIDs, so copy edits never touch an id.
- **`PUBLISHED_POSTS` (`navigation-links.ts`) is a CURATION list, not a content source.** Only its `href` is authoritative; titles, dates, and abstracts are fetched live through `Server.getResearchPosts()` (see `next-slate-markdown/AGENTS.md`), so a copy edit on VMAX.ai reaches every surface without a deploy. **Curation is not publication:** a curated post appears ONLY when the viewer can read it (`canReadPost`: published to everyone; a team post also to a verified viewer with the `canPreviewTeamPosts` flag, its owner, and public-access staff). An entry is never rendered from its checked-in title and abstract, because that would show an unpublished post on `/research`.
  - `/research` is the one place the feed is enumerated; the home page only links to it (`RESEARCH_URL`, `CAREERS_URL`).
  - When `getPostBySlug` fails, `getResearchPosts` drops the post; nothing renders the checked-in titles as an outage fallback.
  - `getHomePostDescriptions` keeps its `PUBLISHED_POSTS` default because `FormIslandScene` is a client component calling it with no argument.
  - `publishedPostSlug(href)` is the shared href-to-slug reduction. `MODAL_CODER_URL` is curated for the chess-island article sign; its fallback date stays empty until supplied by the live post. Its checked-in description, grounded in the article copy, keeps the scene card present when the public metadata is unavailable.
  - **A curated entry's slug must be the live post's slug.** `getPostBySlug` fails on any other, and the entry silently disappears from `/research`, the home page, and every sidebar. Check `${API}/posts/public/{slug}` before curating.
  - **`/research` renders the whole live abstract; compact surfaces render `postSummary(post)`.** `FormResearch` draws one paragraph per blank-line-separated block (`postDescriptionParagraphs`). The home research list, the home sidebar's post tooltips, and the world's post signs (`getHomePostDescriptions` through `postSummaryForHref`) show the live description when it is one paragraph and the curated description when it is empty or runs to several paragraphs, because a multi-paragraph abstract cannot fit a sign or a tooltip. Shortening the VMAX.ai description to one paragraph makes it the summary everywhere without a deploy.
- **`authorSocialLink(name)` and `authorLinkedInLink(name)` (`navigation-links.ts`) must stay narrow**; both resolve through the same `authorPerson` key lookup. `SOCIAL_LINKS` holds display names while `data.authors` carries publication forms (middle names, initials, extended surnames such as `Matthew Daborn-Sargent`), so `authorSocialKeys` reduces both sides to `first token + last token` (lowercased, periods/apostrophes stripped) and, for a hyphenated surname, also `first token + final hyphen segment`. A miss returns `null` (no glyph) rather than mislinking a real person; widening the match is not a safe cleanup. The lookup reads `SOCIAL_LINKS` first and then `RESEARCH_AUTHOR_LINKS`, the credited authors of published research who are no longer on the team: they keep their byline LinkedIn link and `/research` X marker without joining the Team menu or the `/world` roster. A departing member who is credited on a published paper moves from `SOCIAL_LINKS` to `RESEARCH_AUTHOR_LINKS` instead of being deleted. `campaigns-v2/common/navigation-links.ts` carries the same two lists.
- **`common/grid-block.ts` is the one reader of the grid variables in script.** The CSS owns the sizes (`--theme-grid-block` in `global-block-size-public-post.css` and `global-block-size-app.css`, overridden per component); script reads them through `readGridBlock(element?)` and `readGridBlockApplications(element?)`, whose `GRID_BLOCK_FALLBACK` (the public post's desktop block) and its half are the only numbers script holds, for server render and a missing stylesheet. `--theme-grid-block-applications` is a `calc()` of the grid block, and a custom property's computed value is its unevaluated text, so `parseFloat` of it is NaN; `readCSSLength` resolves it through a hidden probe's computed `width` instead, inside the element so per-component overrides apply. Never read a grid variable with `getPropertyValue` or a local fallback; `OceanSurfaceEntity` (`OCEAN_DEFAULT_GRID_STEP`) and `campaigns-v2/next-vmax/SpokenText` still do.
- **`getCSSVariableColor` (`theme-colors.ts`) resolves through a temporary DOM element and `getComputedStyle(...).color`** so oklch/hsl/rgb values all normalise to `rgb(...)`; `THREE.Color` cannot parse oklch.
- **`theme-*` and `font-*` body classes are independent axes.** `setTheme` swaps only the theme class (a wholesale `body.className` assignment wipes the font class); `toggleFontClassName` keeps `font-*` classes mutually exclusive.
- **`ForestCacheWarmer` must stay mounted in root `app/layout.tsx`** so the forest-template cache is warm on every entry path, including direct navigation to `/[username]/[slug]`, and `createNeutralForest()` skips the bake. The warmup is idempotent. It skips `FOREST_FREE_PATHS`, the pages whose scenes build no forest: navigation is always a full page load, so the in-memory cache it would warm dies before any forest page could read it.
- **Nothing in the root layout or root `not-found.tsx` statically imports Three.js, the engine, or the tools registry.** Both are part of EVERY route's module tree, and Next serializes the root not-found element into every page's payload, so their client imports ship to every page, `/use-campaign` and the home page included. `ForestCacheWarmer` imports `create-neutral-forest` with a dynamic `import()` inside its idle callback (the same module instance the engine uses, so the cache is shared); `PlayerAgentActionBar` loads `DockPreviewCanvas` with `React.lazy` (`app/AGENTS.md`); `app/not-found.tsx` renders only `NotFoundScreen` (`app/AGENTS.md`, route map). With the three in place `/use-campaign` loads 20 script chunks, 1.5 MB raw and 460 KB gzipped, against 36 chunks, 3.8 MB and 1.1 MB with the not-found tree and the two root imports static (`ALGORITHMS.md` 24o). A new root-layout or not-found import that reaches `three`, `@engine/*`, `tools-pages`, or `AppContainer` reopens that cost on every page.
- **`OutsideElementEvent` listens on `document`, not the overlay.** The modal overlay is `pointer-events: none` so a scene behind stays interactive; do not add an overlay `onClick` or re-enable overlay pointer events to "fix" dismissal.

#### Navigation popovers

- **`DropdownMenu` applies `next-vmax/Tooltip.module.css`'s `.tooltip` class directly**, so HelpTip's four gradient hairlines, square corners and theme-specific shadows stay shared. `DropdownMenu.module.css` owns the section hierarchy and the inner scroller, with a pinned menu grid (`--menu-grid`) and desktop base type so body-portalled menus do not inherit the larger public-post scale.
- **`DropdownMenu.module.css` steps each text section down one size at its mobile media query**, which repeats `MOBILE_BREAKPOINT` as a literal because CSS cannot read the constant: primary links, team names in `.secondary`, and team portraits. Primary links use `--tooltip-font-size` and `--tooltip-line-height` so shared tooltip breakpoints cannot resize them again; social SVGs keep an explicit size.
- **`DropdownMenu.module.css` sizes rows from the type, with no row minimum.** Each item pads a quarter grid above and below and half a grid at the sides, so the rows shrink with the mobile type. The scroller inset and each side of a section divider are one `--menu-grid` at every width; social controls keep an explicit square.
- **`DropdownMenu.module.css` uses `.root.root` for `pointer-events: auto`**, giving the interactive menu higher specificity than the shared `.tooltip` rule's `pointer-events: none`. A single-class override depends on CSS chunk order and can make every menu link ignore pointer input.
- **`DropdownMenu` uses `FormHintAvatar.module.css`'s `.avatar` for team portrait frames**, so their gradient hairlines, 1px inset, and theme-specific shadows match Seth. The menu's `.avatar.avatar` pins the portrait square (`--avatar-width`, smaller on mobile) independently of stylesheet order; the inner `.portrait` keeps the image and its fallback inside the frame.
- **`DOCUMENT_NAVIGATION_SECTIONS` and `TEAM_NAVIGATION_SECTION` set `hideHeading` on every section**, so the logo menu and home Team popover show their contents without visible section titles. `DropdownMenu` retains each section's `aria-label` so the groups remain named for assistive technology.
- **`DropdownMenu` items draw no focus state.** `.item:focus-visible` sets `outline: none` and only pointer hover tints the row, so the menu's first entry is never framed when the popup opens.
- **`DropdownMenuTrigger` owns a native button and a labelled, nonmodal dialog**, so Enter/Space activates the trigger, Tab follows native links and buttons, and Escape returns focus without closing an underlying modal. Arrow keys, Home, and End move through menu entries; an outside pointer press or focus leaving the popup dismisses it.
- **`DropdownMenuTrigger` sizes the popup before calling `Position.calculate` with zero scroll offsets**, because its portal uses fixed viewport coordinates. The larger vertical space around the trigger limits the inner scroller within the viewport height, and a viewport margin keeps long team menus reachable on narrow or short screens.
- **`DropdownMenuTrigger` observes the trigger and popup with `ResizeObserver`, and only the body's class attribute with `MutationObserver`**, so image sizing and theme changes reposition the card without observing every moving scene node. Both observers and all listeners are removed on close.
- **`NavigationMenuTrigger` preserves explicit `navigationItems` as a complete replacement**, so a scene reference can supply its own links. `customNavigationItems` append inside the primary site section while the shared team and social sections stay present.

#### Modal system (`ModalContext`, `ModalRenderer`)

- `useModals()` returns `ModalContextType` (`components/ModalContext.tsx`); `close()` with no key closes the top card.
- **`update(key, props)` replaces an open card's props in place and returns `false` when no card holds that key.** A card's props are snapshotted at `open`, so a modal that follows a request (`next-vmax-tools/FormCampaignLaunchModal`) is advanced by the caller through `update` rather than closed and reopened, which would remount it into a new window slot. The presence check reads `modalStackRef` (written by `commit` together with the state, so it holds a change made in the same tick), so a caller learns the viewer already closed the card and can raise the result another way; never reopen a fresh card to show a later phase.
- **A modal that owns a close control closes ITSELF through `useCloseSelf`** (key from `ModalInstanceProvider`, which `ModalRenderer` wraps around every modal): in windowed mode several cards are live at once, so a bare `close()` hits the wrong one.
- Items are keyed `${modal.key}-${viewportMode}` and `positions`, `heights`, and `frontKey` reset on the change, so crossing `MOBILE_BREAKPOINT` remounts every modal into a clean layout instead of stranding windows at stale coordinates.
- **`ModalComponent.placement = 'bottom-left-stack'` anchors the whole stack at the bottom-left on EVERY viewport**, set by `ModalAuthentication`. It applies only when every open modal asks for it; a mixed stack falls back to the layouts below. Each card is `left`/`bottom` at `ANCHORED_MARGIN` (`ANCHORED_MARGIN_MOBILE` below `MOBILE_BREAKPOINT`), capped at `ANCHORED_WIDTH` on desktop and fluid between the two mobile gutters on mobile (`--panel-width: 100%` of that wrapper), with `--panel-max-height` leaving room for every card's `STACK_OFFSET` peek. Cards behind the front one use the stack's offset and blur, only the front card is interactive, and outside clicks dismiss nothing (each card closes through its own control). **The cards share ONE grid cell** (`.anchoredStack`, `display: grid`, every `.anchored` item at `grid-area: 1 / 1`, flex column with its card at `flex: 1`), so the row is as tall as the tallest card and every card stretches to it: equal heights from layout alone, with no measuring. The container carries the position, width, and max height; items carry only the stack offset and blur. A lone card (`/sign-in`) is simply its own height.
- **Mobile is a STACK**: lower cards offset by `STACK_OFFSET` and blurred by `STACK_BLUR` per level; only the top card is interactive (`.interactive` re-enables `pointer-events`), and outside-click dismissal attaches to the top card alone so one click peels one card.
- **Desktop is draggable WINDOWS.** A window sizes to its content (`--panel-max-height: none`, `--panel-overflow: visible`); layouts use heights measured by a `ResizeObserver` keyed on `data-modal-key`, `WINDOW_ASSUMED_HEIGHT` being only the first-paint placeholder. Clamping to a computed cell height makes cards grow their own scrollbars.
- **`ModalComponent.preferredWidth` opts a modal into a wider packed window.** `ModalRenderer` records the preference in the sticky slot roster and includes it when choosing column count and each card's width, capped by the viewport. A roster with an explicit preference uses `packWindows` instead of the hero composition; closed slots retain their width until the stack empties, so closing a card does not rearrange survivors. Ordinary modals keep the `WINDOW_MAX_WIDTH` cap; `CampaignAppInspection` sets a wider `preferredWidth`. The wrapper width, `--panel-width`, and drag clamp all use the same resolved width.
- **A drag writes the DOM, not React state.** `handlePointerMove` clamps through `clampWindowPosition` (`components/modal-window-drag.ts`, the one home of `WINDOW_KEEP_VISIBLE`) into a reused scratch record, writes `left` / `top` on the dragged element's style directly, and keeps the live point on `dragRef`; `setPositions` runs once on `pointerup` / `pointercancel` with that point, and `frontKey` still updates on `pointerdown`. A React commit that lands mid-drag (a `ResizeObserver` height) reads the live point for the dragged key, so it never snaps the card back to its origin. `modal-window-drag.test.ts` pins the clamp against the inline expressions over random viewports and deltas.
- **Outside-click dismissal is OFF in windowed mode**: a click on one window would close another. Windows close only through their own control.
- `composeWindowsAroundFocus` runs first; `packWindows` (shortest-column pack, `WINDOW_MIN_CELL` sets column count) takes over when the stack was never a composition (fewer than two cards ever slotted, e.g. a lone `ModalAuthentication`) or the viewport cannot fit two bands plus the minimum corridor.
- `composeWindowsAroundFocus` lays several windows around a 3D scene whose centre island is the subject; a plain pack reads as a grid over it.
  - Each modal key gets a STICKY slot the first time it is seen (`slotIndexByKey` in `slotIndexRef`, cleared only when the stack empties); slot parity picks the LEFT or RIGHT band. A live-index split renumbers survivors on close and swaps bands; the clear-on-empty stops a reopened stack from continuing the numbering.
  - **Both layout functions read the slot ROSTER (`slotRoster.rosterKeys`), never live `orderedKeys`, and `heights` is never pruned for a closed key.** The closed card's slot, height, and band space stay reserved, so a close moves nothing and survivors' placements are byte-identical until a resize. Composing over live keys re-centres the band (`placeBand` sums `stackHeight`), shifts later cards by `cardHeight + WINDOW_GAP`, drags `inward` (derived from `top`) horizontally, and drops a lone survivor into the pack.
  - The bands hold a clear corridor (`FOCUS_CORRIDOR_RATIO` of width, clamped by `FOCUS_CORRIDOR_MIN`/`FOCUS_CORRIDOR_MAX`) so the scene centre is never covered; they centre on `BAND_ANCHOR_RATIO`, stagger by `BAND_STAGGER`, and each card tucks inward by `FOCUS_ARC_DEPTH` scaled by its distance from `FOCUS_CENTER_RATIO` (falloff `FOCUS_SPAN_RATIO`), which is where the hero island renders under `WorldStage`'s `HOME_CAMERA_Y_OFFSET`.
  - `WINDOW_WIDTH_STEP` narrows each successive card off its sticky slot, floored at `WINDOW_MIN_WIDTH`, so `--panel-width` is per card and a card keeps the width it opened with.
- Drag raises via `frontKey`; `NON_DRAGGABLE` skips drags starting on a control; the clamp keeps `WINDOW_KEEP_VISIBLE` of the card's OWN width (from `dragRef`) on-screen.
- **Placement is written as `--panel-width`/`--panel-max-height` AND as an inline `width` on the `.windowed` wrapper.** The wrapper is `position: absolute` with `left`; without a pinned width a `width: 100%` card (`FormCard`, `FormModal`, `ModalAuthentication`) shrinks to `viewport - left`, height feeds x, x feeds width, width re-wraps copy, and the `ResizeObserver` `setHeights` loop throws `Maximum update depth exceeded`.

#### Home marketing stack and brand mark

Component-level contracts (`PanelShell` and its slots, `VmaxAppIcon`, `VmaxFlag`, `VmaxSpellTile` and the spell-tile bake modules, the shader icons (`VmaxAtlasIcon`, `VmaxPresentationsIcon`), `VmaxCreatePaperIcon`, `SignInScreen`, `RootLayoutEffects`) live in `app/AGENTS.md`. Cross-file rules:

- `PanelShell` closes BY KEY through `useCloseSelf` ("Modal system" above).
- `PanelShell` switches OFF its `GlassButton` children's `backdrop-filter` via `--glass-button-backdrop`: over an opaque card an inner blur samples only the card's own fill (see `next-vmax/AGENTS.md`).
- `VmaxWaitlist` posts `HTTP.joinWaitlist` (`next-slate-markdown/AGENTS.md`, "`http.ts`") and shows a uniform confirmation. Its submit is a primary `FormLiquidButton` (`next-vmax-tools/AGENTS.md`).
- `common/campaign-copy.ts` is the single source of the Campaign description, `CAMPAIGN_GENERATED_PROMPT`, `CAMPAIGN_PROMPT_PLACEHOLDER` (`FormCampaignComposer` and `FormClientExperience`), and `COMPOSER_MINIMUM_PROMPT_LENGTH` + `COMPOSER_SHORT_PROMPT_MESSAGE` (`FormCampaignApplication` and `FormCampaignTemplate`) so live and fixture controllers cannot drift. The floor is the composer's rule, not the API's, and the message says so.
  - **`CAMPAIGN_START_LABEL` names the creation action in `FormCampaignSidebar`.** The tools rail's `CAMPAIGNS_SIDEBAR_GROUP` and the site menu both read `Campaign` and name the product destination, so product navigation and campaign creation keep distinct labels.
- `common/research-copy.ts` holds the research/home intro paragraphs; `firstSentences` derives the `/research` meta description from the first. `HOME_INTRO_PARAGRAPHS` is the home page's intro (`components/Homepage`), and `HOME_RESEARCH_PARAGRAPH` is its research lede, grounded in the published papers.
- **`common/page-return.ts` `onPageReturn(handler)` is the ONE "the viewer is back" signal**: `visibilitychange` to visible, window `focus`, a bfcache `pageshow`, and `online`, coalesced within `RETURN_COALESCE_MS` and silent while `document.visibilityState` is `hidden`; it returns the unsubscribe. A polling surface subscribes it to resync at once instead of waiting out a timer a background tab suspended (`FormCampaignApplication` and `FormSlidesApplication`, `next-vmax-tools/AGENTS.md`; `CampaignThreeApplication`). `RootLayoutEffects`' `pageshow` reload is a different contract (a restored page reloads whole) and stays where it is.

## Cross-cutting rules

### Change discipline

- Treat the files you read in the current run as the evidence base. If the evidence does not identify a requirement, state the assumption or ask before changing behavior.
- Preserve existing contracts before chasing a local fix. When behavior changes, update the canonical source, the verification path, and affected agent-facing docs together.
- Expand through the repo's extension points: registries, manifests, entities, shared predicates, helpers, skills. Do not hard-code one-off branches.
- Keep temporary diagnostics, captures, audit outputs, and source backups in the operating system's temporary directory. Do not leave scratch files or directories in this project. Required assets belong in their canonical source or public asset directories.
- `npm run check:workspace` rejects recognized scratch directories, logs, profiles, compiler caches outside `.next`, before/after source snapshots, and generated output that must never ship (`public/prepared/`, orphaned binary height fields that nothing reads and that the repository's text hooks corrupt), including ignored files. It runs before `npm test` and `npm run build`; it reports paths without deleting anything. Normal dependency/build caches and Finder metadata are excluded.
- An ignore rule does not remove files already tracked. When removing accidental diagnostics, keep their deletions in the change submitted to CI; do not format disposable scripts into permanent source or weaken lint rules to retain them.

### Node and scripts

The Node requirement and the `npm` commands are in [`README.md`](README.md), "Requirements" and "Commands"; `package.json` `engines` and `scripts` are the source. The test runner is vitest.

### Validation before handoff

- Run `npm run check` and the existing tests relevant to the change. A clean TypeScript result does not establish formatting, Python lint, or workspace cleanliness.
- The CI lint contract is [`.pre-commit-config.yaml`](../../.pre-commit-config.yaml). From this directory, run `pre-commit run --config ../../.pre-commit-config.yaml --files <edited-file> ...` on the existing files changed by the task, with each path relative to this directory (`next-vmax-tools/FormSlidesActions.tsx`). `pre-commit` resolves `--files` against the current directory, so a `public/www/`-prefixed path matches nothing and every hook reports `(no files to check)` while the run still exits zero; a real run shows `Passed` for the text hooks. List files explicitly; do not stage, stash, or commit as part of validation. If tooling is missing, install its environment and caches in an operating-system temporary directory.
- Re-run pre-commit after an auto-fixing hook changes files; the final run must exit zero. Text files have no trailing whitespace and end with one newline. Retained Python utilities must satisfy the configured Ruff lint and formatter, including annotations and the diagnostic-print rule. Do not suppress a hook to claim a clean result.

### TypeScript

Pure TypeScript under `tsconfig.json` `compilerOptions`, which owns the flag list; the rules below lean on its `strict` and `noUncheckedIndexedAccess`.

- `tsconfig.json` places incremental compiler state in `.next/cache/tsconfig.tsbuildinfo`, keeping generated cache files out of the project root.
- The only `.js` files are vendored bundles paired with a `.d.ts` stub so `allowJs: false` resolves types while the bundler picks up the runtime: `three-isometric-engine/vendor/ammo.js` and `modules/minisearch.js` (verbatim npm build; vendored code is exempt from the comment and `Map` rules). The other two, `scripts/strip-glb.js` and `scripts/scrub-glb.js`, are GLB tooling like the `.mjs` scripts beside them (`simplify-glb.mjs`, `bake-portrait-glb.mjs`, `quantize-glb.mjs`, `glb-io.mjs`; see `world-meshes/AGENTS.md`).
- **No `any` at boundaries.** Exported functions, constructors, and pub/sub channels have typed parameters; interior logic uses inference.
- **`as const`** on frozen constant objects.
- **`import type`** for type-only imports.
- **Unused parameters** are prefixed `_`; the `_` prefix is reserved for that alone.
- **Private members and module-scoped privates use a `__private` prefix** (`this.__privateHeatField`, `__privateCameraTarget`). See [`demiurge/public/www/skills/fast-typescript-check/SKILL.md`](demiurge/public/www/skills/fast-typescript-check/SKILL.md).
- **No `Map` in hot paths.** Use `Record<string, T>`; `Map` only for object-reference keys.
- **`typeof` checks against globals** are hoisted to module constants (`const HAS_WINDOW = typeof window !== 'undefined'`).
- **Barrel exports** exist at each engine subsystem root; import from the barrel, not deep paths. One recorded exception: `three-isometric-engine/world-entities/index.ts` registers idle entities through `() => import('@engine/world-entities/<Entity>')` deep paths so each entity is its own chunk, and re-exports no entity class; `GLComponent` types its entity fields with `import type` from the same deep paths.
- **Non-null assertions (`!`)** are used in hot-path engine loops where indices are loop-bounded. Do not add runtime null guards there.
- **Root `types.d.ts` globally re-declares Next.js's generated `LayoutProps`** because the Next.js 16 type generator's layout types fail to compile without it. Remove only after confirming an upgrade fixes the generator.
- **Root `types.d.ts` also declares `Array.prototype.at` and `ReadonlyArray.prototype.at`**, the one built-in above `tsconfig.json`'s `lib` that the browser floor may use, because Next's polyfill module (`next/dist/build/polyfills/polyfill-module.js`) installs it; `String.prototype.at` and the typed arrays' `at` stay undeclared, because nothing supplies them ("Browser floor" below).

### File naming convention

File names use **hyphen-case** (`shader-context.ts`), with two PascalCase exceptions: React components (`AffiliationSquare.tsx`) and class-per-file modules whose primary export is a single class (`WorldContext.ts`, `GLComponent.ts`, `*Entity.ts`). camelCase file names are not permitted.

### No comments: knowledge lives in AGENTS.md

**Comments are banned everywhere in this repository.** No `//` line comments, no `/* */` block comments, no `NOTE(@handle)` annotations: in TypeScript, TSX, GLSL, CSS, tests, configs, and scripts alike. Identifier names carry the meaning (see "Identifier naming" below); if code reads unclearly, expand the name or restructure the code; never annotate it. This is permanent policy, not a per-PR preference.

The only permitted exceptions are machine-read directives where technically required: `@ts-expect-error`, `@ts-ignore`, `eslint-disable`, `/// <reference>`. Nothing else survives review.

Knowledge that would once have been a comment (a constraint, a tradeoff, a non-obvious ordering, a workaround, a gotcha) belongs in the deepest `AGENTS.md` that owns the file, as a note that cites the exact function/class/symbol name so a reader can find it from the code (`grep` the symbol, read the doc). If a fact is not worth an AGENTS.md note, it is not worth keeping at all.

`next-vmax/islands/AGENTS.md` and `world-entities/AGENTS.md` are the reference for a good note: every claim traces to live code, names match the source exactly, nothing is restated that a reader could infer.

Documentation prose contains no em-dashes, in AGENTS.md files, SKILL.md files, and prose strings in source alike: use a comma, colon, semicolon, parentheses, or a second sentence. Literal em-dash glyphs that are rendered content (the campaign metric placeholder value) are content, not punctuation, and stay.

### Describe the current state only

- **AGENTS.md notes describe what IS, never what was.** No "previously / used to / now / replaced / the maintainer asked" narrative. Git holds the history.
- **Every note is: symbol name + invariant + why.** A note with no why and no rule is inventory and is deleted.
- **No prop-list or interface restatements.** The TypeScript says what a component takes; the doc says what must stay true and why.
- **One fact per bullet.** No multi-KB paragraphs; split into sub-bullets.

### Terms are defined once, in `common/glossary.ts`

- **`common/glossary.ts` is the one definition of every term the product uses** (`GLOSSARY_TERMS`: slug, term, definition, related; ONE meaning per word, never two entries or two senses for the same word). It is a source file, not a page: the site has no glossary or help route.
- **A new product term is added to `GLOSSARY_TERMS` first, then used.** An AGENTS.md, hint, or UI string may name a term and say how it applies here, but must not restate its definition; link `demiurge/public/www/common/glossary.ts` instead. If a definition changes, it changes there and nowhere else.
- **Skills are the exception: every `SKILL.md` is self-contained.** A skill is handed to an agent on its own, often outside this repository (`/skill/slides` serves `create-vmax-presentation` to any agent), so it explains in its own words, where they are used, each term and surface it relies on, and never sends a reader elsewhere for a meaning. A skill's explanation stays consistent with `GLOSSARY_TERMS` and the hint that covers the same surface.
- **Help tips and product copy carry no automatic glossary links.** `SpokenText` only lights the spoken word. `next-vmax/GlossaryText` (the home page) and the Campaign marketing chrome's `GlossaryText` match `GLOSSARY_TERMS` names through `glossaryLinkSpans` and link only the terms their caller maps to an href (component mechanics: `next-vmax/AGENTS.md`).
- **A surface is EXPLAINED by its hint; AGENTS.md files do not re-explain it.** Every help tip is one `CampaignHint` in `next-vmax-tools/campaign-hints.tsx` (field cards in `campaign-setting-hints.tsx`), shown beside its `?` in the product. AGENTS.md files hold invariants and file contracts; `common/glossary.ts` holds meanings; hints hold explanations; skills carry their own (above).
- **New product vocabulary goes into `GLOSSARY_TERMS` first**, then, if a surface needs explaining, into a `CampaignHint` on that surface, and only then may an AGENTS.md mention it. A skill that relies on the new term explains it where it uses it.
- `common/glossary.test.ts` pins unique slugs, resolvable `related` slugs, unique names and definitions, and the inline matching rules of `glossaryLinkSpans`, so a typo fails at test time, not on a reader's screen.

### Identifier naming: spell names out in full

Spell every local variable and parameter out in full: `context` not `ctx`, `deltaX`/`deltaZ` not `dx`/`dz`, `event` not `e`, `element` not `el`, `callback` not `cb`, `index` not `i` (`innerIndex` or a domain name for nested loops). The reader never decodes an abbreviation.

This governs names you own: locals and parameters. Properties, methods, exported symbols, type fields, JSON manifest keys, pub/sub channel names, React props, THREE `userData` keys, GLSL identifiers (`iTime`, `uColor`, `vUv`), and CSS variables are contracts; renaming one is an API change, not a readability cleanup.

**Deliberate exceptions (do NOT "fix" these to longer names):**
- **Domain-canonical single letters:** `x`/`y`/`z`, `u`/`v`, `r`/`g`/`b`/`a` ONLY as colour channels, generic type parameters (`<T>`).
- **`props` and `params`** stay as canonical React/JS idioms.
- **Not variables at all:** `vi.fn()`, CSS `calc(...)` in style strings, the `src` attribute/prop, string literals, and any identifier inside a GLSL/shader template literal (shaders are excluded wholesale).
- **Type-position contracts:** a function-TYPE signature's parameter name (`decode?: (str: string) => string`) is a declared shape, not a binding you own.

### Never separate metadata with middle dots

Bylines, metadata, counts, dates, statuses, and captions never join their parts with ` · ` (or any dot separator). Put each part on its own line instead: a list row's description is newline-separated (`SidebarItem` draws each line of `description` as its own ellipsised row), a status is two lines, a size sits under its file name. The maintainer has asked for this many times; treat a new ` · ` in user-visible text as a bug. Older Campaign surfaces still carry some and are being removed.

### Brand name casing

Branding writes **Vmax** (capital `V`, lowercase `max`, one word) in prose, UI copy, and PascalCase identifiers and file names (`VmaxAppIcon`, `Icon.VmaxLogo`). Do NOT write `VMax` or `VMAX…` inside a mixed-case identifier.

All-caps **`VMAX`** survives only where the whole token is uppercase or it is a product/wordmark reference: the `VMAX` backend, `VMAX.ai` / `vmax.ai`, the wordmark SVG, `SCREAMING_SNAKE_CASE` constants (`VMAX_SVG_PATHS`), the `{ VMAX: 'vmax' }` key of `render-authors.tsx` `AFFILIATION_TOKENS`. The lowercase `next-vmax*` folders and `@nextjs-vmax*` aliases stay lowercase.

### Code correctness > tests passing

`vitest.config.ts` carries `passWithNoTests`, so a green run with zero matching tests is possible. A "pinned by `X.test.ts`" reference in a doc names an invariant that must hold; if the file is absent it is a re-pinning checklist item, not evidence.

**A green `npm test` is not a signal that a feature works.** It only signals that the asserted contracts hold under the harness. Visual correctness, physics plausibility, emergent behavior, and cross-subsystem interaction are out of scope for vitest.

Before reporting a feature complete:

1. For UI / 3D / shader / physics work: run `npm run dev`, load the scene, **look at the result**. A passing suite with a broken visual is a false green.
2. Assert invariants (mass conservation, bounded spread, byte-identical non-mutation), not that a function was called. "Runs without throwing" is not a test.
3. When you weaken a spec's behavioral assertion to an API-shape assertion, say so explicitly.

**Agents (including Claude) are demonstrably weaker at writing tests than implementation.** Failure modes: asserting intermediate state instead of observable behavior; synthetic inputs that bypass the real bug class; declaring success on "tests pass" without running the feature. Check delegated tests against the spec's intent. A test that passes on the first run without iteration is a yellow flag.

**Do not write tests the type system already proves.** A `strict` compiler with `noUncheckedIndexedAccess` is the first test suite. Delete tests whose only claim is a tautology: default field values of a fresh object, math identities independent of the code under test, shape/length/"returns an array" assertions on a typed return. Keep every test asserting *behavior the types cannot*: invariants, gating and ordering, geometry/placement, regressions. When unsure, keep it: the bar for deletion is "the compiler already fails if this is false."

### Debug visibility rules (apply to every subsystem)

Full contract in [`demiurge/public/www/three-isometric-engine/AGENTS.md`](demiurge/public/www/three-isometric-engine/AGENTS.md) ("Barrier visibility invariant", "One-classification-of-truth invariant").

1. **Every barrier renders red.** Hard barriers (physics bodies, planner stamps, predicate gates) AND soft cost-based barriers (RVO penalties, halos, dominating taxes) MUST draw a red debug primitive. If you cannot draw one, do not stamp it as a barrier. The reserved debug colours are listed in the engine's "Barrier visibility invariant".
2. **Visible matches math.** Every debug overlay derives from the EXACT constants the runtime predicate uses; no visual-only scale factors. Document any clamp / projection in the owning `AGENTS.md`, citing the rendering function.
3. **One classification of truth.** When one physical concept (sailability, walkability, flammability) lives in several structures, every representation MUST agree. Multi-class enums NEVER collapse with `> 0` shortcuts; every consumer lists every class or imports the canonical predicate.

### Browser floor

- **`package.json` `browserslist` is the supported floor** (Chrome 87, Edge 88, Firefox 78, Safari and iOS Safari 15, Samsung Internet 14). SWC lowers syntax and Lightning CSS lowers CSS for it, but neither supplies a missing built-in method, and a built-in a phone's browser lacks throws when it runs, which stops that script.
- **`tsconfig.json` `lib` is that floor** (`es2021`, `es2022.error`, `es2022.object`), so a newer built-in fails `npm run check:types`. Use `common/browser-baseline.ts` in its place: `findLastItem` and `findLastItemIndex` for `findLast` and `findLastIndex`, `createDeferred` for `Promise.withResolvers`, and `timeoutSignal` and `anySignal`, which call `AbortSignal.timeout` and `AbortSignal.any` where they exist and stand in for them where they do not; reverse a fresh array in place rather than calling `toReversed`. `common/browser-baseline.test.ts` pins the signal stand-ins with the native functions removed.
- **The DOM library cannot be narrowed**, so a DOM API newer than the floor (`requestIdleCallback`, `structuredClone`, `OffscreenCanvas`) is feature-tested where it is used, as `ForestCacheWarmer` and `WorldContext` test `requestIdleCallback`.
- **Lightning CSS keeps a `vh` declaration placed before a `dvh` one and resolves `color-mix()` only over literal colours.** A page that must work on older phones writes the `vh` fallback first (`components/Homepage.module.css`, `document-system-components/DocumentLayout.module.css`), and a `color-mix()` over custom properties gets an `@supports not (color: color-mix(in srgb, red, blue))` block of literal colours (`components/HomepageEmberRipple.module.css`, `components/Homepage.module.css`); `vw` and `dvw` are the same width, so a width uses `vw`.
- **Three.js r163 and later render only WebGL2**, which every floor browser ships; a WebGL scene probes each optional extension and runs without it, and a page shows its content without the scene when no WebGL2 context can be made (`app/AGENTS.md`, the home page's scene; `app/-/AGENTS.md`, "Home next").

### Never hand-write a `-webkit-` pair in CSS

Lightning CSS (the Next.js 16 minifier) auto-prefixes from browserslist. Write the standard property alone and it emits `-webkit-backdrop-filter` plus `backdrop-filter`. Write BOTH by hand and it collapses to the `-webkit-` form only, so the effect is missing in Firefox.

- `components/PanelShell.module.css` carries no hand-written prefix and is the reference.
- `next-vmax/GlassButton.module.css` and `next-slate-markdown/components/Button.module.css` still carry hand-written `-webkit-backdrop-filter` lines, so their blur does not render in Firefox. Deleting them is the fix but turns the filter ON for Firefox users: a visual change, not a cleanup.

### Path aliases (`tsconfig.json`)

`tsconfig.json` `compilerOptions.paths` is the alias roster (`@engine/*`, `@nextjs-slate/*`, and the rest); docs name an alias, never a second copy of the map.

### Sub-AGENTS files apply hierarchically

Each top-level sub-file owns its subsystem in full; `three-isometric-engine/` nests further into `world-entities/AGENTS.md` and `world-meshes/AGENTS.md`. **Do not duplicate sub-file content into a parent.** Reference the deepest file that owns the detail.

## Engine data flow

The manifest-driven mount, the entity roster, and the `WorldContext` publish/subscribe pairs are the engine's: [`demiurge/public/www/three-isometric-engine/AGENTS.md`](demiurge/public/www/three-isometric-engine/AGENTS.md), "Mount manifest", with each entity's contract in [`demiurge/public/www/three-isometric-engine/world-entities/AGENTS.md`](demiurge/public/www/three-isometric-engine/world-entities/AGENTS.md). How a post's text selects its scene is in `app/AGENTS.md`, "How a post becomes a page".

### Scene composition is shared

`common/derive-world-mode.ts` also owns `postScenePresetFor`, the ordered post-to-preset selector, and `textTriggersThreeMileIsland`, the exact-sentence test behind its first rule. `Document` reads the returned row from `ISLAND_PRESETS`, so post overrides and reference islands share their scene flags; matching and precedence are documented in `document-system-components/AGENTS.md`.

`common/derive-world-mode.ts` is the single source of truth for scene mode and world type: `document-system-components/Document.tsx` calls `deriveWorldMode` and `deriveWorldType`, and `GLComponent` imports their `WorldMode` and `WorldType` types (and `sceneNeedsPhysics`). The post page (`app/[username]/[slug]/(document)/page.tsx`) renders `Document` and reads neither directly.

- `deriveWorldMode(events)` reads the byline `EVENT` column; new code reads its `mode`, not `isCTF`.
- `deriveWorldType({ imageCount, isDesert })` picks the world type from the content scan.
- **CTF takes precedence over wander (`!isCTF && WANDER_RE.test(...)`)**: an `EVENT` value that names both (`CTF, wander`) must select the agent system. Keep the ordering. The value is one byline field, so it cannot contain `|`, which `Document.tsx` splits the byline on.

## Publishing to VMAX.ai

Before any posting workflow, read [`demiurge/public/www/public/SKILL.md`](demiurge/public/www/public/SKILL.md). The persisted post format and the `source` sent to the API are in `next-slate-markdown/AGENTS.md`, "Overview" and "`http.ts`"; the `::isometric(0)` prepend is in `document-system-components/AGENTS.md`, "Syntax table".

## Agent discovery routes

`/agents` serves this file. The agent-discovery routes (`/skill` and its sub-routes, `/llms.txt`), the sitemap, and robots are in the route map of `app/AGENTS.md`.

<!-- BEGIN:nextjs-agent-rules -->

## This is NOT the Next.js you know

This version has breaking changes — APIs, conventions, and file structure may all differ from your training data. Read the relevant guide in `node_modules/next/dist/docs/` (resolved from this file's directory; in monorepos the `next` package may not be visible from the repo root) before writing any code. Heed deprecation notices.

This block is written and re-added by `next dev` — verify at `node_modules/next/dist/server/lib/generate-agent-files.js`. Removing it from a diff only re-creates the uncommitted change; committing it with your work keeps the tree clean.

<!-- END:nextjs-agent-rules -->

- `campaignDeploymentHeaders` pins same-origin Campaign fetches to the build deployment, preserving upload and campaign schema ownership across alias changes. The experimental Vercel project must enable Skew Protection.
- `uploadCampaignContext` hashes sliced files, uploads through a rolling pool of at most eight chunks concurrently, stops scheduling after a failure, waits for all in-flight writes before cancellation, and requires background verification above 512 MiB. Original ZIPs can occupy up to 5 GiB; certified task context retains its independent 512 MiB limit.
- `uploadCampaignContext` sends bounded Blob slices through `requestBytes` only when the session advertises `chunk_content_type: application/octet-stream`. Other sessions and base64-backed files retain JSON transport, so a new client can use an older API without changing byte identity or retry semantics.
