Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(crews): public crew directory and invite search, linked from the game
nirholasc9c96d454ef9
diff --git a/api/crews/directory.js b/api/crews/directory.jsindex 2a68e32d7..5a562afe9 100644--- a/api/crews/directory.js+++ b/api/crews/directory.js@@ -1,6 +1,6 @@// GET /api/crews/directory?limit=24// The public crew directory: every crew that has members, biggest first. This-// is what a visitor with no crew sees — somewhere to look before deciding to+// is what a visitor with no crew sees: somewhere to look before deciding to// found one, and the only way a crew is discoverable without knowing its tag.//// Public and cacheable: a roster is public exactly like the agent gallery, anddiff --git a/api/crews/search.js b/api/crews/search.jsindex ce1721235..cd7578e76 100644--- a/api/crews/search.js+++ b/api/crews/search.js@@ -5,7 +5,7 @@// already has an invite out to them. The Crew HQ renders those as a disabled// row with the real reason instead of letting the click 409.//-// Auth required, and the caller must be in a crew — searching people to invite+// Auth required, and the caller must be in a crew. Searching people to invite// when you have no crew to invite them to is a dead path, so it is closed here// rather than rendered and then rejected on submit.diff --git a/docs/crews.md b/docs/crews.mdnew file mode 100644index 000000000..1afc3540a--- /dev/null+++ b/docs/crews.md@@ -0,0 +1,155 @@+# Crews++A **crew** is a group of accounts whose agents fly one short tag. It is the group+half of the social system: [friends](/play) are one-to-one and live in the+in-world drawer, a crew is the name a set of people operate under, and it has a+public headquarters at [`/crews`](https://three.ws/crews).++Every crew has:++- a **tag**: 2 to 6 letters or digits, unique across the whole site, rendered+ over its members' avatars in the 3D world,+- a **name**: up to 32 characters, what people read,+- an **owner**: the founder, who can remove members; ownership passes to the+ longest-standing member if the owner leaves,+- a **roster**: one account belongs to at most one crew at a time.++## The headquarters++`/crews` renders the crew as a room rather than a list. Each member stands in it+as their own agent's 3D avatar, resolved from the account's agent identity, and+is lit when they are online in a realm and unlit when they are not. Presence is+read from the same Redis keys the in-world friends list reads, so "in world"+means the same thing in both places.++Three views share the page:++| URL | Who sees it | What it shows |+| --- | --- | --- |+| `/crews` | signed out | The public crew directory |+| `/crews` | signed in | Your HQ, or the found-a-crew form plus any invites addressed to you |+| `/crews/<TAG>` | anyone | That crew's HQ, read-only, shareable |++A crew's colour is derived from its tag (an FNV-1a hash to a hue), so the same+crew looks the same in the room, the directory, and the share card without+anyone uploading art or storing a palette.++### Rendering budget++Browsers cap live WebGL contexts at roughly 16, and a large crew asking for one+canvas per member would evict the rest of the site's viewers. `LIVE_FIGURE_BUDGET`+in [`src/crews-page.js`](../src/crews-page.js) caps how many members render as a+live `<agent-3d>` (6); everyone past that renders as their avatar's still image,+and live figures mount only when they scroll into the stage.++## API++All endpoints answer `{ data: … }` on success and+`{ error: <code>, error_description: <sentence> }` on failure.++### `GET /api/crews`++The caller's crew, roster and pending invites. Requires a session or bearer+token. Returns empty values rather than an error when the caller is in no crew.++```bash+curl -s https://three.ws/api/crews -H "Authorization: Bearer $THREE_WS_TOKEN"+```++```json+{+ "data": {+ "crew": { "id": "…", "tag": "NOVA", "name": "Nova Collective", "role": "owner", "isOwner": true, "memberCount": 3 },+ "members": [+ {+ "id": "…", "name": "Ada", "username": "ada", "avatarUrl": "https://…/ada.png",+ "role": "owner", "joinedAt": "2026-07-31T09:12:00.000Z",+ "online": true, "realm": "mainland", "server": 2,+ "standee": { "agentId": "…", "agentName": "Ada-1", "modelUrl": "https://…/ada-1.glb", "thumbUrl": "https://…/ada-1.png" }+ }+ ],+ "invites": []+ }+}+```++`standee` is the member's renderable agent. It is `null` when the account has no+agent, and `modelUrl` is `null` when the agent's avatar is private: visibility is+enforced exactly as `api/agents.js` enforces it, so a private model can never+leak through a roster.++### `POST /api/crews`++Every mutation goes through one endpoint, selected by `action`.++| `action` | Body | Effect |+| --- | --- | --- |+| `create` | `{ tag, name }` | Found a crew; the caller becomes owner |+| `invite` | `{ userId }` | Invite an account (any member may invite) |+| `accept` | `{ crewId }` | Accept an invite; clears your other invites |+| `decline` | `{ crewId }` | Decline an invite |+| `leave` | `{}` | Leave; disbands the crew if you were the last member |+| `kick` | `{ userId }` | Owner only: remove a member |++```bash+curl -s https://three.ws/api/crews \+ -H "Authorization: Bearer $THREE_WS_TOKEN" \+ -H 'content-type: application/json' \+ -d '{"action":"create","tag":"NOVA","name":"Nova Collective"}'+```++Error codes you should handle: `bad_tag`, `tag_taken`, `tag_reserved`,+`already_in_crew`, `target_in_crew`, `no_invite`, `not_owner`, `not_member`.++`tag_reserved` covers tags that would collide with a route segment (`SEARCH`,+`INDEX`, `API`, `ADMIN`, `NEW`, `ME`, `ALL`, `NULL`). Both `/crews/:tag` and+`/api/crews/:tag` resolve an exact file before the dynamic segment, so a crew+tagged `SEARCH` would be permanently unreachable at its own URL. The tag is+refused at founding time, which is the only point where that is fixable without+breaking an existing crew's link.++### `GET /api/crews/<TAG>`++The public view of one crew: identity plus roster with presence and standees. No+auth required. `404 not_found` when no crew flies that tag.++### `GET /api/crews/search?q=<term>`++Accounts to invite, for a caller who is already in a crew. Each hit carries what+the inviter needs before clicking:++```json+{ "data": { "results": [+ { "id": "…", "name": "Ada", "username": "ada", "avatarUrl": "…", "crew": null, "invited": false },+ { "id": "…", "name": "Grace", "username": "grace", "avatarUrl": "…", "crew": { "tag": "AXI", "name": "Axiom" }, "invited": false }+] } }+```++`crew` non-null means they already fly someone else's tag and cannot be invited;+`invited` means your crew already has an invite out to them. The UI renders both+as state on the row instead of letting the click fail.++Returns `400 no_crew` when the caller is in no crew: searching people to invite+with no crew to invite them to is a dead path, so it is closed here rather than+rendered and then rejected on submit.++### `GET /api/crews/directory?limit=24`++Every crew with at least one member, biggest first, with up to five member faces+each. Public and cacheable; no auth.++## Where the code lives++| Piece | File |+| --- | --- |+| Page markup | [`pages/crews.html`](../pages/crews.html) |+| Page logic | [`src/crews-page.js`](../src/crews-page.js) |+| Page styles | [`src/crews.css`](../src/crews.css) |+| Data layer | [`api/_lib/crews-store.js`](../api/_lib/crews-store.js) |+| Endpoints | [`api/crews/`](../api/crews) |+| Presence | [`api/_lib/presence-store.js`](../api/_lib/presence-store.js) |+| Schema | `api/_lib/migrations/2026-06-05-crews.sql` |+| Tests | [`tests/crews-shared.test.js`](../tests/crews-shared.test.js), [`tests/crews-wiring.test.js`](../tests/crews-wiring.test.js) |++The in-world friends drawer links to the HQ from its header, which is how a+player who is already social in the world finds the group surface.diff --git a/src/crews-page.js b/src/crews-page.jsindex 28c14c651..02f6decaa 100644--- a/src/crews-page.js+++ b/src/crews-page.js@@ -1,11 +1,12 @@-// Crew HQ (/crews and /crews/<TAG>) — the browser half of the crews system.+// Crew HQ (/crews and /crews/<TAG>): the browser half of the crews system.//// The crews backend (api/crews/*, api/_lib/crews-store.js, the 2026-06-05// migration) has been complete and reachable since the /play world shipped, but// nothing in the product ever rendered it: the only reference anywhere in the-// frontend was a `if (a.openCrew)` branch in the game HUD that nothing supplied,-// so the button never drew. This page is the surface that closes that gap, and-// src/game/hud/index.js now supplies openCrew so the in-world button opens it.+// frontend was a `if (a.openCrew)` branch in src/game/hud/index.js that nothing+// ever supplied. This page is the surface that closes that gap; the in-world+// friends drawer (src/game/coincommunities.js) links here from its header, which+// is how a player already being social in the world finds the group surface.//// What makes it a room rather than a list: every member stands in the HQ as// their own agent's avatar (crews-store.standeesFor resolves each account's@@ -24,16 +25,12 @@// render as their avatar still, which is the same figure, just not animated.import { apiFetch } from './api.js';+import { crestHues, presenceLine, sanitizeTag, tagFromPath, validateTag } from './crews-shared.js';const LIVE_FIGURE_BUDGET = 6;const DEFAULT_RIG = '/avatars/default.glb';const PRESENCE_POLL_MS = 20_000;const SEARCH_DEBOUNCE_MS = 250;-const TAG_RE = /^[A-Z0-9]{2,6}$/;-// Kept in sync with RESERVED_TAGS in api/_lib/crews-store.js. Duplicated rather-// than fetched so the founding form can say "reserved" as you type instead of-// after a round trip; the server remains the authority and rejects it anyway.-const RESERVED_TAGS = new Set(['SEARCH', 'INDEX', 'API', 'ADMIN', 'NEW', 'ME', 'ALL', 'NULL']);const $ = (id) => document.getElementById(id);@@ -43,18 +40,6 @@ const esc = (s) =>);// ── crest ────────────────────────────────────────────────────────────────────-// A crew's colour is derived from its tag, so it is stable everywhere the crew-// appears (room, directory, share card) without anyone picking or storing one.-function crestHues(tag) {- let h = 2166136261;- for (const ch of String(tag || '')) {- h ^= ch.charCodeAt(0);- h = Math.imul(h, 16777619) >>> 0;- }- const hue = h % 360;- return { hue, hue2: (hue + 58) % 360 };-}-function applyCrewHues(el, tag) {const { hue, hue2 } = crestHues(tag);el.style.setProperty('--crew-hue', String(hue));@@ -69,22 +54,6 @@ function crestHtml(tag, small = false) {);}-// ── presence wording ─────────────────────────────────────────────────────────-// Matches src/game/friends-panel.js so the same person reads the same in both.-function realmLabel(realm, server) {- if (!realm) return '';- const r = String(realm)- .replace(/[_-]+/g, ' ')- .replace(/\b\w/g, (c) => c.toUpperCase());- return server ? `${r} · Server ${server}` : r;-}--function presenceLine(m) {- if (!m.online) return 'Offline';- const where = realmLabel(m.realm, m.server);- return where ? `In ${where}` : 'Online';-}-function joinedLabel(iso) {if (!iso) return '';const d = new Date(iso);@@ -342,29 +311,14 @@ function wireFoundForm() {const submit = $('cw-found-submit');const validate = () => {- const tag = tagInput.value.trim().toUpperCase().replace(/[^A-Z0-9]/g, '');- if (tagInput.value !== tag) tagInput.value = tag;- let msg = '';- let tone = '';- let ok = false;- if (!tag) {- msg = '2 to 6 letters or digits. This is the badge worn over your avatar in world.';- } else if (!TAG_RE.test(tag)) {- msg = tag.length < 2 ? 'A tag needs at least 2 characters.' : 'A tag is at most 6 characters.';- tone = 'bad';- } else if (RESERVED_TAGS.has(tag)) {- msg = `${tag} is reserved by the site.`;- tone = 'bad';- } else {- msg = `${tag} looks good.`;- tone = 'good';- ok = true;- }- note.textContent = msg;- note.dataset.tone = tone;- tagInput.setAttribute('aria-invalid', tone === 'bad' ? 'true' : 'false');- submit.disabled = !ok || nameInput.value.trim().length < 2;- return ok;+ const clean = sanitizeTag(tagInput.value);+ if (tagInput.value !== clean) tagInput.value = clean;+ const verdict = validateTag(clean);+ note.textContent = verdict.message;+ note.dataset.tone = verdict.tone;+ tagInput.setAttribute('aria-invalid', verdict.tone === 'bad' ? 'true' : 'false');+ submit.disabled = !verdict.ok || nameInput.value.trim().length < 2;+ return verdict.ok;};tagInput.addEventListener('input', validate);@@ -673,7 +627,7 @@ function startPolling() {renderMine();}} catch {- // A failed poll is not an error state — the last good render stands and+ // A failed poll is not an error state. The last good render stands and// the next tick tries again.}};@@ -684,16 +638,11 @@ function startPolling() {}// ── boot ─────────────────────────────────────────────────────────────────────-function tagFromPath() {- const m = location.pathname.match(/^\/crews\/([A-Za-z0-9]{2,6})\/?$/);- return m ? m[1].toUpperCase() : '';-}-async function boot() {wireFoundForm();wireInviteSearch();- const tag = tagFromPath();+ const tag = tagFromPath(location.pathname);if (tag) {state.mode = 'public';state.publicTag = tag;diff --git a/src/crews-shared.js b/src/crews-shared.jsnew file mode 100644index 000000000..a2675ae3b--- /dev/null+++ b/src/crews-shared.js@@ -0,0 +1,78 @@+// Pure crew helpers shared by the Crew HQ page and its tests.+//+// Split out of crews-page.js because that module boots itself on import (it is+// a page entry point, not a library). Everything here is deterministic and+// DOM-free, so the rules that decide what a visitor reads can be pinned by a+// test instead of by looking at the page.++// Tag grammar, mirroring normalizeTag() in api/_lib/crews-store.js.+export const TAG_RE = /^[A-Z0-9]{2,6}$/;++// Kept in sync with RESERVED_TAGS in api/_lib/crews-store.js. Duplicated rather+// than fetched so the founding form can say "reserved" as you type instead of+// after a round trip; the server remains the authority and rejects it anyway.+// tests/crews-store.test.js asserts the two lists never drift.+export const RESERVED_TAGS = new Set(['SEARCH', 'INDEX', 'API', 'ADMIN', 'NEW', 'ME', 'ALL', 'NULL']);++// What the tag input accepts as you type: uppercase, letters and digits only.+export function sanitizeTag(raw) {+ return String(raw || '')+ .trim()+ .toUpperCase()+ .replace(/[^A-Z0-9]/g, '');+}++// The founding form's verdict on a tag. Returns the sentence the user reads and+// the tone it reads in, so the message and the submit-enabled state can never+// disagree: `ok` is the single source for both.+export function validateTag(raw) {+ const tag = sanitizeTag(raw);+ if (!tag) {+ return {+ tag,+ ok: false,+ tone: '',+ message: '2 to 6 letters or digits. This is the badge worn over your avatar in world.',+ };+ }+ if (tag.length < 2) return { tag, ok: false, tone: 'bad', message: 'A tag needs at least 2 characters.' };+ if (!TAG_RE.test(tag)) return { tag, ok: false, tone: 'bad', message: 'A tag is at most 6 characters.' };+ if (RESERVED_TAGS.has(tag)) return { tag, ok: false, tone: 'bad', message: `${tag} is reserved by the site.` };+ return { tag, ok: true, tone: 'good', message: `${tag} looks good.` };+}++// A crew's colour is derived from its tag (FNV-1a), so it is stable everywhere+// the crew appears (room, directory, share card) without anyone picking or+// storing one. The second hue is a fixed rotation away, which keeps every crest+// gradient legible rather than letting two random hues collide.+export function crestHues(tag) {+ let h = 2166136261;+ for (const ch of String(tag || '')) {+ h ^= ch.charCodeAt(0);+ h = Math.imul(h, 16777619) >>> 0;+ }+ const hue = h % 360;+ return { hue, hue2: (hue + 58) % 360 };+}++// Presence wording, matching src/game/friends-panel.js so the same person reads+// the same in the drawer and in the HQ.+export function realmLabel(realm, server) {+ if (!realm) return '';+ const r = String(realm)+ .replace(/[_-]+/g, ' ')+ .replace(/\b\w/g, (c) => c.toUpperCase());+ return server ? `${r} · Server ${server}` : r;+}++export function presenceLine(member) {+ if (!member?.online) return 'Offline';+ const where = realmLabel(member.realm, member.server);+ return where ? `In ${where}` : 'Online';+}++// The tag in /crews/<TAG>, or '' for the personal HQ at /crews.+export function tagFromPath(pathname) {+ const m = String(pathname || '').match(/^\/crews\/([A-Za-z0-9]{2,6})\/?$/);+ return m ? m[1].toUpperCase() : '';+}diff --git a/src/crews.css b/src/crews.cssindex 5f0f91447..49734ed13 100644--- a/src/crews.css+++ b/src/crews.css@@ -1,4 +1,4 @@-/* Crew HQ (/crews) — the room, the roster, the directory.+/* Crew HQ (/crews): the room, the roster, the directory.** Everything here rides the site tokens in public/style.css. The only local* variables are the two the crest generator drives per crew (--crew-hue anddiff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 2a9572c9c..90c445c5d 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -2050,6 +2050,18 @@ html[data-bg="transparent"] #cc-lobby {font-weight: 800; font-size: 13px; letter-spacing: 0.06em; text-transform: uppercase;color: var(--cc-text);}+/* Crew HQ link. `margin-left: auto` pushes it and the close button to the right+ edge as a pair, so the head keeps its title-left / actions-right rhythm. */+.cc-friends-panel-crew {+ flex: none; margin-left: auto;+ padding: 5px 10px; border-radius: 999px;+ font-size: 11px; font-weight: 700; letter-spacing: 0.04em; text-transform: uppercase;+ color: var(--cc-text); text-decoration: none;+ border: 1px solid var(--cc-edge);+ transition: border-color 0.14s ease, background 0.14s ease;+}+.cc-friends-panel-crew:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.08); }+.cc-friends-panel-crew:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }.cc-friends-panel-close {flex: none; width: 30px; height: 30px;display: inline-flex; align-items: center; justify-content: center;diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 9e61a5de2..75614ba43 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -2126,9 +2126,21 @@ export class CoinCommunities {title.className = 'cc-friends-panel-title';title.textContent = 'Friends';+ // The other half of the social system. Friends are one-to-one and live+ // in this drawer; a crew is the group the same people fly as, and it has+ // its own headquarters. Without this link the two never meet, which is+ // how the crews backend sat shipped and unreachable for so long.+ const crew = document.createElement('a');+ crew.className = 'cc-friends-panel-crew';+ crew.href = '/crews';+ crew.target = '_blank';+ crew.rel = 'noopener';+ crew.textContent = 'Crew HQ';+ crew.title = 'Found a crew, invite these people, and see the roster in 3D';+const head = document.createElement('div');head.className = 'cc-friends-panel-head';- head.append(title, close);+ head.append(title, crew, close);const body = document.createElement('div');body.className = 'cc-friends-panel-body';diff --git a/tests/crews-shared.test.js b/tests/crews-shared.test.jsnew file mode 100644index 000000000..6599cdcd5--- /dev/null+++ b/tests/crews-shared.test.js@@ -0,0 +1,135 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import {+ RESERVED_TAGS,+ TAG_RE,+ crestHues,+ presenceLine,+ realmLabel,+ sanitizeTag,+ tagFromPath,+ validateTag,+} from '../src/crews-shared.js';+import { normalizeTag, isReservedTag } from '../api/_lib/crews-store.js';++describe('crew tags', () => {+ it('accepts 2 to 6 letters or digits and upper-cases them', () => {+ expect(sanitizeTag(' nova ')).toBe('NOVA');+ expect(sanitizeTag('n-o-v-a')).toBe('NOVA');+ expect(sanitizeTag('3ws')).toBe('3WS');+ expect(TAG_RE.test('3WS')).toBe(true);+ });++ it('rejects a tag that is too short, too long, or reserved', () => {+ expect(validateTag('n').ok).toBe(false);+ expect(validateTag('toolongtag').ok).toBe(false);+ expect(validateTag('search').ok).toBe(false);+ expect(validateTag('search').message).toMatch(/reserved/i);+ });++ it('gives an empty input guidance rather than an error', () => {+ const v = validateTag('');+ expect(v.ok).toBe(false);+ expect(v.tone).toBe('');+ expect(v.message).toMatch(/2 to 6/);+ });++ it('agrees with the server on what a tag is', () => {+ for (const raw of ['nova', '3ws', 'a', 'toolongtag', 'n-o-v-a', ' ax ']) {+ const client = validateTag(raw);+ const server = normalizeTag(raw);+ // The client only calls a tag good when the server would also accept it.+ expect(client.ok).toBe(Boolean(server) && !isReservedTag(server));+ if (server) expect(client.tag).toBe(server);+ }+ });++ // The reserved list is duplicated so the founding form can answer without a+ // round trip. If the two ever drift, a tag the form calls good is refused on+ // submit, the exact failure the duplication exists to avoid.+ it('keeps the reserved list identical to the server list', () => {+ const src = readFileSync(new URL('../api/_lib/crews-store.js', import.meta.url), 'utf8');+ const match = src.match(/const RESERVED_TAGS = new Set\(\[([^\]]*)\]\)/);+ expect(match, 'server RESERVED_TAGS literal not found').toBeTruthy();+ const serverTags = [...match[1].matchAll(/'([^']+)'/g)].map((m) => m[1]);+ expect(serverTags.sort()).toEqual([...RESERVED_TAGS].sort());+ for (const tag of serverTags) expect(isReservedTag(tag)).toBe(true);+ });++ it('reserves every tag that would shadow a real /api/crews route file', () => {+ // server/index.mjs resolves an exact file before a [param].js, so any+ // endpoint added under api/crews/ must also be an unusable tag.+ for (const routeFile of ['search', 'index', 'directory']) {+ const asTag = normalizeTag(routeFile);+ if (!asTag) continue; // longer than 6 chars: can never be a tag+ expect(isReservedTag(asTag)).toBe(true);+ }+ });+});++describe('crew crest', () => {+ it('is deterministic and in range', () => {+ const a = crestHues('NOVA');+ expect(crestHues('NOVA')).toEqual(a);+ expect(a.hue).toBeGreaterThanOrEqual(0);+ expect(a.hue).toBeLessThan(360);+ expect(a.hue2).toBeGreaterThanOrEqual(0);+ expect(a.hue2).toBeLessThan(360);+ });++ it('separates the two hues so the gradient never collapses to one colour', () => {+ for (const tag of ['NOVA', '3WS', 'AX', 'ZZZZZZ', '000000']) {+ const { hue, hue2 } = crestHues(tag);+ expect(hue).not.toBe(hue2);+ }+ });++ it('gives different tags different colours', () => {+ const hues = new Set(['NOVA', 'AXIOM', '3WS', 'ORBIT', 'ZED'].map((t) => crestHues(t).hue));+ expect(hues.size).toBeGreaterThan(3);+ });++ it('does not throw on an empty tag', () => {+ expect(() => crestHues('')).not.toThrow();+ });+});++describe('crew presence wording', () => {+ it('says Offline when the member is not in a world', () => {+ expect(presenceLine({ online: false, realm: 'mainland' })).toBe('Offline');+ expect(presenceLine(null)).toBe('Offline');+ });++ it('names the realm and server when there is one', () => {+ expect(presenceLine({ online: true, realm: 'coin_world', server: 2 })).toBe('In Coin World · Server 2');+ expect(presenceLine({ online: true, realm: 'mainland' })).toBe('In Mainland');+ });++ it('falls back to Online when presence carries no realm', () => {+ expect(presenceLine({ online: true, realm: null })).toBe('Online');+ });++ it('formats realms the same way the in-world friends drawer does', () => {+ expect(realmLabel('coin-world', null)).toBe('Coin World');+ expect(realmLabel('', 3)).toBe('');+ });+});++describe('crew routing', () => {+ it('reads the tag out of /crews/<TAG>', () => {+ expect(tagFromPath('/crews/NOVA')).toBe('NOVA');+ expect(tagFromPath('/crews/nova/')).toBe('NOVA');+ expect(tagFromPath('/crews/3ws')).toBe('3WS');+ });++ it('treats the bare page as the personal HQ', () => {+ expect(tagFromPath('/crews')).toBe('');+ expect(tagFromPath('/crews/')).toBe('');+ });++ it('ignores anything that is not a tag-shaped segment', () => {+ expect(tagFromPath('/crews/toolongtag')).toBe('');+ expect(tagFromPath('/crews/NOVA/extra')).toBe('');+ expect(tagFromPath('/other')).toBe('');+ });+});diff --git a/tests/crews-wiring.test.js b/tests/crews-wiring.test.jsnew file mode 100644index 000000000..688389645--- /dev/null+++ b/tests/crews-wiring.test.js@@ -0,0 +1,77 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++// The crews backend shipped complete and stayed invisible for weeks because+// nothing routed to it. These assertions pin every hop a visitor takes from a+// URL to the rendered page, so the same gap cannot reopen quietly.++const root = resolve(import.meta.dirname, '..');+const read = (p) => readFileSync(resolve(root, p), 'utf8');++describe('crews wiring', () => {+ it('routes /crews and /crews/<TAG> to the page', () => {+ const routes = JSON.parse(read('vercel.json')).routes;+ const dests = routes.filter((r) => /^\/crews/.test(r.src || '')).map((r) => r.dest);+ expect(dests).toContain('/crews.html');+ const tagRoute = routes.find((r) => r.src === '/crews/([A-Za-z0-9]{2,6})/?');+ expect(tagRoute?.dest).toBe('/crews.html');+ });++ it('builds the page: it is a vite rollup input', () => {+ expect(read('vite.config.js')).toContain("crews: resolve(__dirname, 'pages/crews.html')");+ });++ it('declares the page so the sitemap, llms.txt and changelog pick it up', () => {+ const pages = JSON.parse(read('data/pages.json'));+ const entry = pages.sections.flatMap((s) => s.pages).find((p) => p.path === '/crews');+ expect(entry).toBeTruthy();+ expect(entry.title).toBeTruthy();+ expect(entry.description.length).toBeGreaterThan(40);+ expect(entry.added).toMatch(/^\d{4}-\d{2}-\d{2}$/);+ });++ it('is reachable from the site navigation', () => {+ expect(read('public/nav-data.js')).toContain("href: '/crews'");+ });++ it('loads its module, styles and the 3D component', () => {+ const html = read('pages/crews.html');+ expect(html).toContain('/src/crews-page.js');+ expect(html).toContain('/src/crews.css');+ expect(html).toContain('agent-3d');+ // Every element the page module reaches for by id must exist somewhere: in+ // the static markup, or in the markup the module itself renders. An id in+ // neither place is a whole state that silently no-ops.+ const js = read('src/crews-page.js');+ const ids = [...js.matchAll(/\$\('([a-z0-9-]+)'\)/g)].map((m) => m[1]);+ expect(ids.length).toBeGreaterThan(10);+ for (const id of new Set(ids)) {+ const inPage = html.includes(`id="${id}"`);+ const rendered = js.includes(`id="${id}"`);+ expect(inPage || rendered, `#${id} is read by crews-page.js but nothing ever creates it`).toBe(true);+ }+ });++ it('links the in-world friends drawer to the HQ', () => {+ expect(read('src/game/coincommunities.js')).toContain("crew.href = '/crews'");+ });++ it('ships every endpoint the page calls', () => {+ const js = read('src/crews-page.js');+ for (const path of ['/api/crews', '/api/crews/directory', '/api/crews/search']) {+ expect(js).toContain(path);+ }+ expect(() => read('api/crews/index.js')).not.toThrow();+ expect(() => read('api/crews/directory.js')).not.toThrow();+ expect(() => read('api/crews/search.js')).not.toThrow();+ expect(() => read('api/crews/[tag].js')).not.toThrow();+ });++ it('never emits a private avatar through a roster', () => {+ const store = read('api/_lib/crews-store.js');+ expect(store).toContain("a.visibility in ('public', 'unlisted')");+ expect(store).toMatch(/readable && r\.storage_key \? publicUrl/);+ expect(store).toMatch(/readable && r\.thumbnail_key \? thumbnailUrl/);+ });+});