Skip to content

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.

fix(seeders): stop the avatar seeder handing out usernames that already exist

nirholas286f9e737c6e
diff --git a/api/_lib/circulation.js b/api/_lib/circulation.js
index 98159f04c..3def42f94 100644
--- a/api/_lib/circulation.js
+++ b/api/_lib/circulation.js
@@ -33,6 +33,7 @@ import { createSession } from './auth.js';
import { solUsdPrice } from './avatar-wallet.js';
import { CHAIN_BY_ID } from './erc8004-chains.js';
import { publicUrl as r2PublicUrl } from './r2.js';
+import { claimSeedUsername, seedDisplayName } from './seed-username.js';
import { pinToIPFS } from './ipfs-pin.js';
import { confirmSkillPurchase, resolvePayoutAddress } from './purchase-confirm.js';
import { consumeTrialUse, logSkillUsage } from './skill-access.js';
@@ -469,19 +470,6 @@ function slugify(s) {
.slice(0, 40);
}
-// Claim a unique username from a base word (mirrors the forge-seed username claim).
-async function claimUsername(base) {
- const existing = await sql`
- select username from users where username = ${base} or username like ${base + '%'} limit 100
- `;
- const taken = new Set(existing.map((r) => r.username));
- if (!taken.has(base)) return base;
- for (let n = 2; n <= 99; n++) {
- if (!taken.has(`${base}${n}`)) return `${base}${n}`;
- }
- return `${base}_${randomUUID().slice(0, 4)}`;
-}
-
// Clone a random public avatar into `userId`'s ownership so the new agent has a
// real 3D body + thumbnail (reusing the platform's own generated gallery) and so
// the coin launcher can use it as the token image. Returns the new avatar id or
@@ -553,14 +541,12 @@ async function createPoolAgent() {
const agentName = variant === 0 ? persona.name : `${persona.name} #${variant + 1}`;
const ownerWord = `${pick(OWNER_FIRST_NAMES)}${persona.handle}`.replace(/[^a-z0-9]/g, '');
- const username = await claimUsername(slugify(ownerWord) || persona.handle);
+ const username = await claimSeedUsername(slugify(ownerWord) || persona.handle);
+ // Only reachable if a persona ever ships with an empty handle, but a null
+ // username would insert a nameless account rather than skip the tick.
+ if (!username) return { skipped: 'no_username', persona: persona.handle };
const email = `${username}@agents.three.ws`;
- // Drop claimUsername's collision suffixes (`_xxxx` uuid fallback, numbered
- // slot) before titling; stripping digits alone left names like "Fog_".
- const displayName = username
- .replace(/_[0-9a-f]{4}$/, '')
- .replace(/\d+$/, '')
- .replace(/\b\w/g, (c) => c.toUpperCase());
+ const displayName = seedDisplayName(username);
const [user] = await sql`
insert into users (email, display_name, username, plan, email_verified, service_account, created_at, updated_at)
diff --git a/api/_lib/seed-username.js b/api/_lib/seed-username.js
new file mode 100644
index 000000000..7f6b1782f
--- /dev/null
+++ b/api/_lib/seed-username.js
@@ -0,0 +1,74 @@
+// The one username claim used by every seeder that creates a synthetic account.
+//
+// Three seeders (api/cron/avaturn-seed-cron.js, api/cron/forge-seed-cron.js,
+// api/_lib/circulation.js) each carried a private copy of this helper, and all
+// three copies shared the same defect: the "which variants already exist" query
+// ended in `limit 100`, so as soon as a base word had 100 or more variants in
+// the users table the taken-set came back truncated and the helper handed out a
+// name that was already taken. The caller's `on conflict do nothing` insert then
+// returned no row and the tick skipped with "user insert conflict". In
+// production every sampled OG word was past that ceiling (wolf 101, raven 117,
+// fog 336), so the avaturn seeder had stopped producing avatars entirely while
+// still reporting ok:true every minute.
+//
+// Two things make this version correct:
+// 1. It asks for exactly the candidate space it iterates (the bare word plus
+// its numbered slots) and asks for all of it, so the taken-set can never be
+// a partial view of the names about to be handed out.
+// 2. It compares case-insensitively, matching the actual uniqueness rule in
+// Postgres (`users_username_unique` is a unique index on lower(username)),
+// so an existing "Wolf5" now blocks "wolf5" instead of sailing past the
+// check and failing at insert time.
+//
+// A claim is a read, not a reservation: two ticks racing on the same second can
+// still land on the same name. That is what the caller's unique-index conflict
+// handling is for, and it is now the only way a conflict can happen.
+
+import { randomUUID } from 'node:crypto';
+import { sql } from './db.js';
+
+// Numbered slots tried before falling back to a random hex suffix. The old
+// helpers stopped at 99, which is also where the truncated query stopped being
+// able to see the truth; 999 keeps popular words usable for far longer.
+const MAX_NUMBERED_SLOT = 999;
+
+// Escape the Postgres regex metacharacters a slugified base word can contain
+// (circulation feeds slugs, which carry hyphens).
+function escapeRegex(word) {
+ return word.replace(/[.*+?^${}()|[\]\\\-]/g, '\\$&');
+}
+
+// Claim `word` as a username, skipping to the next free numbered slot.
+// Returns the claimed username, or null when `word` is empty.
+export async function claimSeedUsername(word) {
+ const base = String(word || '').trim().toLowerCase();
+ if (!base) return null;
+
+ // Only the bare word and word + up to three digits: a bare prefix match would
+ // drag in unrelated longer usernames and inflate the result set without
+ // telling us anything about the slots we actually iterate.
+ const pattern = `^${escapeRegex(base)}[0-9]{0,3}$`;
+ const existing = await sql`
+ select lower(username) as username from users where lower(username) ~ ${pattern}
+ `;
+ const taken = new Set(existing.map((r) => r.username));
+
+ if (!taken.has(base)) return base;
+ for (let n = 2; n <= MAX_NUMBERED_SLOT; n++) {
+ const candidate = `${base}${n}`;
+ if (!taken.has(candidate)) return candidate;
+ }
+ // Every numbered slot is taken. A random hex suffix keeps the seeder running
+ // instead of stalling on an exhausted word.
+ return `${base}_${randomUUID().slice(0, 4)}`;
+}
+
+// Turn a claimed username back into a display name that reads like a real
+// account. Both collision suffixes have to come off before titling: stripping
+// digits alone turned "fog_1a2b" into the literal display name "Fog_".
+export function seedDisplayName(username) {
+ return String(username)
+ .replace(/_[0-9a-f]{4}$/, '')
+ .replace(/\d+$/, '')
+ .replace(/\b\w/g, (c) => c.toUpperCase());
+}
diff --git a/api/cron/agent-avatar-backfill.js b/api/cron/agent-avatar-backfill.js
index b4310f903..ece34ac24 100644
--- a/api/cron/agent-avatar-backfill.js
+++ b/api/cron/agent-avatar-backfill.js
@@ -18,7 +18,6 @@
// AGENT_AVATAR_BACKFILL_BATCH agents assigned per tick (default 100)
import { json, wrapCron } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
import { logger } from '../_lib/usage.js';
import { backfillAgentAvatars, agentAvatarCoverage } from '../_lib/agent-avatars.js';
import { requireCron } from '../_lib/cron-auth.js';
diff --git a/api/cron/auto-rig-sweep.js b/api/cron/auto-rig-sweep.js
index 04c3fe2c2..cd87bce94 100644
--- a/api/cron/auto-rig-sweep.js
+++ b/api/cron/auto-rig-sweep.js
@@ -18,7 +18,7 @@
// UniRig pipeline) — deterministic precedence means it matches the provider the
// submit path chose. No per-job BYOK key juggling.
-import { error, json, method, wrapCron } from '../_lib/http.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { sql } from '../_lib/db.js';
import { getRegenProviderForMode } from '../_lib/regen-provider.js';
import { finalizeAutoRigStage } from '../_lib/auto-rig.js';
diff --git a/api/cron/avatar-thumbnail-backfill.js b/api/cron/avatar-thumbnail-backfill.js
index 9b14c6a30..e87eab95d 100644
--- a/api/cron/avatar-thumbnail-backfill.js
+++ b/api/cron/avatar-thumbnail-backfill.js
@@ -37,7 +37,6 @@
// the cron exists to keep coverage at 100% once it is there.
import { json, wrapCron } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
import { logger } from '../_lib/usage.js';
import {
ensureBackfillSchema,
diff --git a/api/cron/avatar-thumbnail-render.js b/api/cron/avatar-thumbnail-render.js
index 3a337c0cd..98954a1a3 100644
--- a/api/cron/avatar-thumbnail-render.js
+++ b/api/cron/avatar-thumbnail-render.js
@@ -22,7 +22,6 @@
// THUMBNAIL_RENDER_BG background color or 'transparent' (default #0a0a0a)
import { json, wrapCron } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
import { logger } from '../_lib/usage.js';
import { presignGet, putObject, publicUrl } from '../_lib/r2.js';
import { renderGlbToPng } from '../_lib/render-glb.js';
diff --git a/api/cron/avaturn-seed-cron.js b/api/cron/avaturn-seed-cron.js
index d014b1d79..b337a2ea3 100644
--- a/api/cron/avaturn-seed-cron.js
+++ b/api/cron/avaturn-seed-cron.js
@@ -37,6 +37,7 @@ import { isFlagEnabled } from '../_lib/flags.js';
import { pickDiversityProfile, describeProfile } from '../_lib/avaturn-seed.js';
import { pickBaseBody, pickColorway, pickScale, recolorGlb } from '../_lib/studio-avatar.js';
import { composeStudioAvatar } from '../_lib/avatar-composer/index.js';
+import { claimSeedUsername, seedDisplayName } from '../_lib/seed-username.js';
import { randomUUID } from 'node:crypto';
import { requireCron } from '../_lib/cron-auth.js';
@@ -45,25 +46,12 @@ const CIRCUIT_THRESHOLD = 3;
const CIRCUIT_BASE_MS = 10 * 60_000; // 10 min × consecutive failures
// One recolor at a time across all instances (fast, but keeps the tick serial).
const SLOT_TTL_MS = 280_000;
+// Username claims that may be retried within a tick before it gives up.
+const CLAIM_ATTEMPTS = 3;
// Origin the rigged base bodies are served from (/avatars/*.glb).
const ORIGIN = () => env.APP_ORIGIN || 'https://three.ws';
-// Try to claim `word` as a username, skipping to the next free numbered slot.
-// Returns the claimed username or null. (Mirrors the forge seeder's helper.)
-async function claimUsername(word) {
- const existing = await sql`
- select username from users where username = ${word} or username like ${word + '%'} limit 100
- `;
- const taken = new Set(existing.map((r) => r.username));
- if (!taken.has(word)) return word;
- for (let n = 2; n <= 99; n++) {
- const candidate = `${word}${n}`;
- if (!taken.has(candidate)) return candidate;
- }
- return `${word}_${randomUUID().slice(0, 4)}`;
-}
-
function toSlug(name) {
const base = String(name)
.toLowerCase()
@@ -83,27 +71,27 @@ async function runOnce() {
};
}
- const baseWord = OG_USERNAMES[Math.floor(Math.random() * OG_USERNAMES.length)];
- const username = await claimUsername(baseWord);
- if (!username)
- return { skipped: true, reason: 'could not claim OG username — retry next tick' };
-
- // Drop claimUsername's collision suffixes before titling: the `_xxxx` uuid
- // fallback first, then a numbered slot. Stripping digits alone turned
- // "fog_1a2b" into the literal display name "Fog_".
- const displayName = username
- .replace(/_[0-9a-f]{4}$/, '')
- .replace(/\d+$/, '')
- .replace(/\b\w/g, (c) => c.toUpperCase());
- const email = `${username}@avaturn.three.ws`;
-
- const [user] = await sql`
- insert into users (email, display_name, username, plan, email_verified, service_account, created_at, updated_at)
- values (${email}, ${displayName}, ${username}, 'free', false, true, now(), now())
- on conflict do nothing
- returning id
- `;
- if (!user?.id) return { skipped: true, reason: 'user insert conflict — retry next tick' };
+ // Claiming a name is a read, not a reservation, so two ticks landing in the
+ // same second can still collide on the insert. Redraw and retry inside the
+ // tick rather than throwing the whole minute away on a lost race.
+ let user = null;
+ let username = null;
+ let displayName = null;
+ for (let attempt = 0; attempt < CLAIM_ATTEMPTS && !user; attempt++) {
+ const baseWord = OG_USERNAMES[Math.floor(Math.random() * OG_USERNAMES.length)];
+ username = await claimSeedUsername(baseWord);
+ if (!username) continue;
+ displayName = seedDisplayName(username);
+ const [row] = await sql`
+ insert into users (email, display_name, username, plan, email_verified, service_account, created_at, updated_at)
+ values (${`${username}@avaturn.three.ws`}, ${displayName}, ${username}, 'free', false, true, now(), now())
+ on conflict do nothing
+ returning id
+ `;
+ if (row?.id) user = row;
+ }
+ if (!user?.id)
+ return { skipped: true, reason: `username claim lost ${CLAIM_ATTEMPTS} races, retrying next tick` };
const seed = randomUUID();
// Draw a person from the diversity matrix, then COMPOSE a rigged avatar for
diff --git a/api/cron/coin-intel-observe.js b/api/cron/coin-intel-observe.js
index 5e76f4846..d1b7fe65c 100644
--- a/api/cron/coin-intel-observe.js
+++ b/api/cron/coin-intel-observe.js
@@ -17,8 +17,7 @@
// so overlapping runs converge instead of duplicating.
import WebSocket from 'ws';
-import { error, json, method, wrapCron } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { finalizeObservation } from '../../workers/agent-sniper/intel/finalize.js';
import { pumpPortalWsUrl, handlePumpPortalAck } from '../_lib/pumpportal.js';
import { subscribePumpOnchainTrades } from '../_lib/pump-onchain-trades.js';
diff --git a/api/cron/commit-feed-push.js b/api/cron/commit-feed-push.js
index 8e759649f..034a71af2 100644
--- a/api/cron/commit-feed-push.js
+++ b/api/cron/commit-feed-push.js
@@ -17,7 +17,7 @@
//
// A DB lock (app_settings) keeps overlapping ticks from double-posting.
-import { error, json, method, wrapCron } from '../_lib/http.js';
+import { json, method, wrapCron } from '../_lib/http.js';
import { acquireLock, releaseLock, pushTelegramLane } from '../_lib/commit-feed-push.js';
import { requireCron } from '../_lib/cron-auth.js';
diff --git a/api/cron/copy-fanout.js b/api/cron/copy-fanout.js
index 8caf1feeb..b1792d01c 100644
--- a/api/cron/copy-fanout.js
+++ b/api/cron/copy-fanout.js
@@ -20,7 +20,6 @@
// (subscription_id, leader_oracle_action_id, direction) when leader_oracle_action_id is not null
import { json, method, wrapCron } from '../_lib/http.js';
-import { env } from '../_lib/env.js';
import { sql } from '../_lib/db.js';
import { planCopyOrder } from '../_lib/copy-engine.js';
import { requireCron } from '../_lib/cron-auth.js';
@@ -55,8 +54,10 @@ function buyIntentMessage({ sym, name, plannedSol, leaderName, oracleScore, orac
`Your order: ${plannedSol != null ? `${plannedSol.toFixed(4)} SOL` : 'sized by your rules'}`,
``,
`Act now → https://three.ws${traderUrl}/dashboard/copy`,
- mint ? `pump.fun → https://pump.fun/${mint}` : '',
- ].filter((l) => l !== undefined);
+ ];
+ // Only append the coin link when there is a mint; a blank entry here rendered
+ // as a trailing empty line in the Telegram message.
+ if (mint) lines.push(`pump.fun → https://pump.fun/${mint}`);
return lines.join('\n');
}
@@ -378,7 +379,14 @@ export default wrapCron(async (req, res) => {
if (!requireCron(req, res)) return;
const stats = {};
+ // Every per-run memo is dropped at the top of a tick. Cloud Run keeps a
+ // container warm across ticks, so a Map that is only ever written grows
+ // without bound and, worse, pins a stale answer: an unscored mint cached as
+ // null would keep failing a subscription's min_oracle_score filter long after
+ // the Oracle scored it.
_coinCache.clear();
+ _oracleScoreCache.clear();
+ _agentNameCache.clear();
for (const network of NETWORKS) {
try {
await fanoutBuys(network, stats);
diff --git a/prompts/swarm-100/api-cron-01.md b/prompts/swarm-100/api-cron-01.md
deleted file mode 100644
index 5755f04b5..000000000
--- a/prompts/swarm-100/api-cron-01.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/cron batch 01 (10 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/cron/[name].js
-- api/cron/agent-avatar-backfill.js
-- api/cron/auto-rig-sweep.js
-- api/cron/avatar-thumbnail-backfill.js
-- api/cron/avatar-thumbnail-render.js
-- api/cron/avaturn-seed-cron.js
-- api/cron/changelog-push.js
-- api/cron/coin-intel-observe.js
-- api/cron/commit-feed-push.js
-- api/cron/copy-fanout.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-cron-01.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/seed-username.test.js b/tests/seed-username.test.js
new file mode 100644
index 000000000..7939d15bd
--- /dev/null
+++ b/tests/seed-username.test.js
@@ -0,0 +1,108 @@
+/**
+ * seed-username: the one username claim every synthetic-account seeder uses.
+ *
+ * The regression this pins: the three private copies this module replaced all
+ * capped their "which variants exist" query at 100 rows, so a popular base word
+ * (wolf had 101 variants in production, fog 336) came back with a truncated
+ * taken-set and the helper cheerfully handed out a name that was already in the
+ * table. Every seeder insert then hit `on conflict do nothing`, returned no row,
+ * and the tick skipped. The avaturn seeder was a permanent no-op because of it.
+ *
+ * The query is asserted here as well as the return value: a future edit that
+ * reintroduces a row cap, or drops the case-insensitive comparison that matches
+ * the unique index on lower(username), fails these tests.
+ */
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+let rows = [];
+let queries = [];
+vi.mock('../api/_lib/db.js', () => ({
+ sql: (strings, ...values) => {
+ queries.push({ text: strings.join('?').replace(/\s+/g, ' ').trim(), values });
+ return Promise.resolve(rows);
+ },
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+const { claimSeedUsername, seedDisplayName } = await import('../api/_lib/seed-username.js');
+
+beforeEach(() => {
+ rows = [];
+ queries = [];
+});
+
+describe('claimSeedUsername', () => {
+ it('returns the bare word when nothing is taken', async () => {
+ expect(await claimSeedUsername('wolf')).toBe('wolf');
+ });
+
+ it('skips to the first free numbered slot', async () => {
+ rows = ['wolf', 'wolf2', 'wolf3'].map((username) => ({ username }));
+ expect(await claimSeedUsername('wolf')).toBe('wolf4');
+ });
+
+ it('walks past 99 instead of stopping there', async () => {
+ const taken = ['wolf'];
+ for (let n = 2; n <= 150; n++) taken.push(`wolf${n}`);
+ rows = taken.map((username) => ({ username }));
+ expect(await claimSeedUsername('wolf')).toBe('wolf151');
+ });
+
+ it('never returns a name the query reported as taken', async () => {
+ // The exact shape of the old bug: a large taken-set. Nothing it returns
+ // may collide, no matter how many variants exist.
+ const taken = ['fog'];
+ for (let n = 2; n <= 400; n++) taken.push(`fog${n}`);
+ rows = taken.map((username) => ({ username }));
+ const claimed = await claimSeedUsername('fog');
+ expect(taken).not.toContain(claimed);
+ });
+
+ it('asks for the whole variant space, uncapped and case-insensitively', async () => {
+ await claimSeedUsername('wolf');
+ expect(queries).toHaveLength(1);
+ expect(queries[0].text).not.toMatch(/limit/i);
+ expect(queries[0].text).toContain('lower(username)');
+ expect(queries[0].values[0]).toBe('^wolf[0-9]{0,3}$');
+ });
+
+ it('treats a differently-cased existing name as taken', async () => {
+ rows = [{ username: 'wolf' }];
+ expect(await claimSeedUsername('WOLF')).toBe('wolf2');
+ });
+
+ it('escapes regex metacharacters in a slugified base word', async () => {
+ await claimSeedUsername('ada-lovelace');
+ expect(queries[0].values[0]).toBe('^ada\\-lovelace[0-9]{0,3}$');
+ });
+
+ it('falls back to a hex suffix when every numbered slot is taken', async () => {
+ const taken = ['zed'];
+ for (let n = 2; n <= 999; n++) taken.push(`zed${n}`);
+ rows = taken.map((username) => ({ username }));
+ const claimed = await claimSeedUsername('zed');
+ expect(claimed).toMatch(/^zed_[0-9a-f]{4}$/);
+ });
+
+ it('returns null for an empty word instead of querying', async () => {
+ expect(await claimSeedUsername(' ')).toBeNull();
+ expect(queries).toHaveLength(0);
+ });
+});
+
+describe('seedDisplayName', () => {
+ it('titles the bare word', () => {
+ expect(seedDisplayName('wolf')).toBe('Wolf');
+ });
+
+ it('drops a numbered slot', () => {
+ expect(seedDisplayName('wolf42')).toBe('Wolf');
+ });
+
+ it('drops the hex fallback suffix before titling', () => {
+ // Stripping digits alone left the literal display name "Fog_".
+ expect(seedDisplayName('fog_1a2b')).toBe('Fog');
+ });
+});